Skip to content

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

chore(pam): remove old PAM feature code superseded by revamp schema

x032205a16de53398b1
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index d2d95a27b9..9675201718 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -33,19 +33,7 @@ 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 { TPamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-service";
-import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";
-import { TPamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";
-import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
-import { 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";
-import { TPamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";
-import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
-import { TPamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";
import { TPkiAcmeServiceFactory } from "@app/ee/services/pki-acme/pki-acme-types";
@@ -393,7 +381,6 @@ declare module "fastify" {
microsoftTeams: TMicrosoftTeamsServiceFactory;
assumePrivileges: TAssumePrivilegeServiceFactory;
insights: TInsightsServiceFactory;
- pamInsights: TPamInsightsServiceFactory;
relay: TRelayServiceFactory;
gatewayV2: TGatewayV2ServiceFactory;
gatewayPool: TGatewayPoolServiceFactory;
@@ -415,17 +402,6 @@ declare module "fastify" {
announcement: TAnnouncementServiceFactory;
offlineUsageReport: TOfflineUsageReportServiceFactory;
orgProductStats: TOrgProductStatsServiceFactory;
- pamFolder: TPamFolderServiceFactory;
- pamResource: TPamResourceServiceFactory;
- pamDomain: TPamDomainServiceFactory;
- pamResourceRotationRules: TPamResourceRotationRulesServiceFactory;
- pamAccount: TPamAccountServiceFactory;
- pamAccountPolicy: TPamAccountPolicyServiceFactory;
- pamSession: TPamSessionServiceFactory;
- pamSessionChunk: TPamSessionChunkServiceFactory;
- pamProjectRecordingConfig: TPamProjectRecordingConfigServiceFactory;
- pamWebAccess: TPamWebAccessServiceFactory;
- pamDiscoverySource: TPamDiscoverySourceServiceFactory;
mfaSession: TMfaSessionServiceFactory;
membershipUser: TMembershipUserServiceFactory;
membershipIdentity: TMembershipIdentityServiceFactory;
diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.ts
index 83f051393e..0e2eb09572 100644
--- a/backend/src/db/migrations/20260603030053_pam-revamp.ts
+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts
@@ -237,19 +237,19 @@ export async function up(knex: Knex): Promise<void> {
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
- });
+ if (templateId) {
+ 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)
@@ -266,18 +266,18 @@ export async function up(knex: Knex): Promise<void> {
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
- });
+ if (templateId) {
+ 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
+ });
+ }
}
}
diff --git a/backend/src/ee/routes/v1/gateway-pool-router.ts b/backend/src/ee/routes/v1/gateway-pool-router.ts
index 93502537da..aa9b30d93f 100644
--- a/backend/src/ee/routes/v1/gateway-pool-router.ts
+++ b/backend/src/ee/routes/v1/gateway-pool-router.ts
@@ -307,32 +307,6 @@ export const registerGatewayPoolRouter = async (server: FastifyZodProvider) => {
projectName: z.string().nullable()
})
),
- pamDomains: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- projectId: z.string(),
- projectName: z.string().nullable()
- })
- ),
- pamResources: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- projectId: z.string(),
- resourceType: z.string(),
- projectName: z.string().nullable()
- })
- ),
- pamDiscoverySources: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- projectId: z.string(),
- discoveryType: z.string(),
- projectName: z.string().nullable()
- })
- ),
appConnections: z.array(
z.object({
id: z.string(),
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index bc11127229..3e0e6c6a15 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -1,6 +1,5 @@
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";
@@ -33,24 +32,6 @@ import { registerLdapRouter } from "./ldap-router";
import { registerLicenseRouter } from "./license-router";
import { registerOidcRouter } from "./oidc-router";
import { registerOrgRoleRouter } from "./org-role-router";
-import { registerPamAccountPolicyRouter } from "./pam-account-policy-router";
-import { PAM_ACCOUNT_REGISTER_ROUTER_MAP } from "./pam-account-routers";
-import { registerPamAccountRouter } from "./pam-account-routers/pam-account-router";
-import { PAM_DISCOVERY_REGISTER_ROUTER_MAP } from "./pam-discovery-routers";
-import { registerPamDiscoveryRouter } from "./pam-discovery-routers/pam-discovery-router";
-import {
- PAM_DOMAIN_ACCOUNT_REGISTER_ROUTER_MAP,
- PAM_DOMAIN_REGISTER_ROUTER_MAP,
- registerPamDomainRouter
-} from "./pam-domain-routers";
-import { registerPamFolderRouter } from "./pam-folder-router";
-import { registerPamInsightsRouter } from "./pam-insights-router";
-import { registerPamRecordingConfigRouter } from "./pam-recording-config-router";
-import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";
-import { registerPamResourceRotationRulesRouter } from "./pam-resource-routers/pam-resource-rotation-rules-router";
-import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";
-import { registerPamSessionChunkRouter } from "./pam-session-chunk-router";
-import { registerPamSessionRouter } from "./pam-session-router";
import { registerPITRouter } from "./pit-router";
import { registerPkiAcmeRouter } from "./pki-acme-router";
import { registerPkiDiscoveryRouter } from "./pki-discovery-router";
@@ -128,7 +109,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await server.register(registerHoneyTokenRouter, { prefix: "/honey-tokens" });
await server.register(registerInsightsRouter, { prefix: "/insights" });
- await server.register(registerPamInsightsRouter, { prefix: "/insights/pam" });
await server.register(
async (pkiRouter) => {
@@ -215,85 +195,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
{ prefix: "/kmip" }
);
- await server.register(
- async (pamRouter) => {
- await pamRouter.register(injectPamProjectId);
- await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });
- await pamRouter.register(
- async (sessionRouter) => {
- await sessionRouter.register(registerPamSessionRouter);
- await sessionRouter.register(registerPamSessionChunkRouter);
- },
- { prefix: "/sessions" }
- );
- await pamRouter.register(registerPamRecordingConfigRouter);
- await pamRouter.register(registerPamAccountPolicyRouter, { prefix: "/account-policies" });
- await pamRouter.register(
- async (pamDomainRouter) => {
- await pamDomainRouter.register(registerPamDomainRouter);
-
- // Domain-type-specific endpoints
- await Promise.all(
- Object.entries(PAM_DOMAIN_REGISTER_ROUTER_MAP).map(([provider, router]) =>
- pamDomainRouter.register(router, { prefix: `/${provider}` })
- )
- );
- },
- { prefix: "/domains" }
- );
- await pamRouter.register(
- async (pamDiscoveryRouter) => {
- await pamDiscoveryRouter.register(registerPamDiscoveryRouter);
-
- // Discovery-type-specific endpoints
- await Promise.all(
- Object.entries(PAM_DISCOVERY_REGISTER_ROUTER_MAP).map(([provider, router]) =>
- pamDiscoveryRouter.register(router, { prefix: `/${provider}` })
- )
- );
- },
- { prefix: "/discovery-sources" }
- );
-
- await pamRouter.register(
- async (pamAccountRouter) => {
- await pamAccountRouter.register(registerPamAccountRouter);
-
- // Resource-type-specific account endpoints
- await Promise.all(
- Object.entries(PAM_ACCOUNT_REGISTER_ROUTER_MAP).map(([provider, router]) =>
- pamAccountRouter.register(router, { prefix: `/${provider}` })
- )
- );
-
- // Domain-type-specific account endpoints
- await Promise.all(
- Object.entries(PAM_DOMAIN_ACCOUNT_REGISTER_ROUTER_MAP).map(([provider, router]) =>
- pamAccountRouter.register(router, { prefix: `/${provider}` })
- )
- );
- },
- { prefix: "/accounts" }
- );
-
- await pamRouter.register(
- async (pamResourceRouter) => {
- await pamResourceRouter.register(registerPamResourceRouter);
- await pamResourceRouter.register(registerPamResourceRotationRulesRouter);
-
- // Provider-specific endpoints
- await Promise.all(
- Object.entries(PAM_RESOURCE_REGISTER_ROUTER_MAP).map(([provider, router]) =>
- pamResourceRouter.register(router, { prefix: `/${provider}` })
- )
- );
- },
- { prefix: "/resources" }
- );
- },
- { prefix: "/pam" }
- );
-
await server.register(
async (aiRouter) => {
await aiRouter.register(registerAiMcpServerRouter, { prefix: "/mcp/servers" });
diff --git a/backend/src/ee/routes/v1/pam-account-policy-router.ts b/backend/src/ee/routes/v1/pam-account-policy-router.ts
deleted file mode 100644
index 0ac6369ac2..0000000000
--- a/backend/src/ee/routes/v1/pam-account-policy-router.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PolicyRulesInputSchema, SanitizedPamAccountPolicySchema } from "@app/ee/services/pam-account-policy";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-type TSanitizedPolicy = z.infer<typeof SanitizedPamAccountPolicySchema>;
-
-export const registerPamAccountPolicyRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM account policies",
- querystring: z.object({
- projectId: z.string().uuid(),
- search: z.string().trim().optional()
- }),
- response: {
- 200: z.object({
- policies: z.array(SanitizedPamAccountPolicySchema)
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const policies = await server.services.pamAccountPolicy.list(req.query, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.query.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_POLICY_LIST,
- metadata: {
- projectId: req.query.projectId
- }
- }
- });
-
- return { policies: policies as TSanitizedPolicy[] };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:policyId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get a PAM account policy by ID",
- params: z.object({
- policyId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- policy: SanitizedPamAccountPolicySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const policy = await server.services.pamAccountPolicy.getById(req.params, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: policy.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_POLICY_GET,
- metadata: {
- policyId: policy.id,
- projectId: policy.projectId
- }
- }
- });
-
- return { policy: policy as TSanitizedPolicy };
- }
- });
-
- server.route({
- method: "POST",
- url: "/",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Create a PAM account policy",
- body: z.object({
- projectId: z.string().uuid(),
- name: z.string().trim().min(1).max(255),
- description: z.string().trim().max(1000).optional(),
- rules: PolicyRulesInputSchema
- }),
- response: {
- 200: z.object({
- policy: SanitizedPamAccountPolicySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const policy = await server.services.pamAccountPolicy.create(req.body, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_POLICY_CREATE,
- metadata: {
- projectId: req.body.projectId,
- name: req.body.name,
- description: req.body.description
- }
- }
- });
-
- return { policy: policy as TSanitizedPolicy };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:policyId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Update a PAM account policy",
- params: z.object({
- policyId: z.string().uuid()
- }),
- body: z.object({
- name: z.string().trim().min(1).max(255).optional(),
- description: z.string().trim().max(1000).nullable().optional(),
- rules: PolicyRulesInputSchema.optional(),
- isActive: z.boolean().optional()
- }),
- response: {
- 200: z.object({
- policy: SanitizedPamAccountPolicySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const policy = await server.services.pamAccountPolicy.updateById(
- { policyId: req.params.policyId, ...req.body },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: policy.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_POLICY_UPDATE,
- metadata: {
- policyId: policy.id,
- projectId: policy.projectId,
- name: req.body.name,
- isActive: req.body.isActive
- }
- }
- });
-
- return { policy: policy as TSanitizedPolicy };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:policyId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Delete a PAM account policy",
- params: z.object({
- policyId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- policy: SanitizedPamAccountPolicySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const policy = await server.services.pamAccountPolicy.deleteById(req.params, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: policy.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_POLICY_DELETE,
- metadata: {
- policyId: policy.id,
- projectId: policy.projectId,
- name: policy.name
- }
- }
- });
-
- return { policy: policy as TSanitizedPolicy };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-account-routers/index.ts b/backend/src/ee/routes/v1/pam-account-routers/index.ts
deleted file mode 100644
index c5c184ea7e..0000000000
--- a/backend/src/ee/routes/v1/pam-account-routers/index.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import {
- CreateAwsIamAccountSchema,
- SanitizedAwsIamAccountWithResourceSchema,
- UpdateAwsIamAccountSchema
-} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
-import {
- CreateKubernetesAccountSchema,
- SanitizedKubernetesAccountWithResourceSchema,
- UpdateKubernetesAccountSchema
-} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import {
- CreateMongoDBAccountSchema,
- SanitizedMongoDBAccountWithResourceSchema,
- UpdateMongoDBAccountSchema
-} from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";
-import {
- CreateMsSQLAccountSchema,
- SanitizedMsSQLAccountWithResourceSchema,
- UpdateMsSQLAccountSchema
-} from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import {
- CreateMySQLAccountSchema,
- SanitizedMySQLAccountWithResourceSchema,
- UpdateMySQLAccountSchema
-} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
-import {
- CreateOracleAccountSchema,
- SanitizedOracleAccountWithResourceSchema,
- UpdateOracleAccountSchema
-} from "@app/ee/services/pam-resource/oracle/oracle-resource-schemas";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import {
- CreatePostgresAccountSchema,
- SanitizedPostgresAccountWithResourceSchema,
- UpdatePostgresAccountSchema
-} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import {
- CreateRedisAccountSchema,
- SanitizedRedisAccountWithResourceSchema,
- UpdateRedisAccountSchema
-} from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import {
- CreateSSHAccountSchema,
- SanitizedSSHAccountWithResourceSchema,
- UpdateSSHAccountSchema
-} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import {
- CreateWindowsAccountSchema,
- SanitizedWindowsAccountWithResourceSchema,
- UpdateWindowsAccountSchema
-} from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-
-import { registerPamAccountEndpoints } from "./pam-account-endpoints";
-
-export const PAM_ACCOUNT_REGISTER_ROUTER_MAP: Record<PamResource, (server: FastifyZodProvider) => Promise<void>> = {
- [PamResource.Postgres]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.Postgres,
- accountResponseSchema: SanitizedPostgresAccountWithResourceSchema,
- createAccountSchema: CreatePostgresAccountSchema,
- updateAccountSchema: UpdatePostgresAccountSchema
- });
- },
- [PamResource.MySQL]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.MySQL,
- accountResponseSchema: SanitizedMySQLAccountWithResourceSchema,
- createAccountSchema: CreateMySQLAccountSchema,
- updateAccountSchema: UpdateMySQLAccountSchema
- });
- },
- [PamResource.MsSQL]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.MsSQL,
- accountResponseSchema: SanitizedMsSQLAccountWithResourceSchema,
- createAccountSchema: CreateMsSQLAccountSchema,
- updateAccountSchema: UpdateMsSQLAccountSchema
- });
- },
- [PamResource.Redis]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.Redis,
- accountResponseSchema: SanitizedRedisAccountWithResourceSchema,
- createAccountSchema: CreateRedisAccountSchema,
- updateAccountSchema: UpdateRedisAccountSchema
- });
- },
- [PamResource.MongoDB]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.MongoDB,
- accountResponseSchema: SanitizedMongoDBAccountWithResourceSchema,
- createAccountSchema: CreateMongoDBAccountSchema,
- updateAccountSchema: UpdateMongoDBAccountSchema
- });
- },
- [PamResource.SSH]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.SSH,
- accountResponseSchema: SanitizedSSHAccountWithResourceSchema,
- createAccountSchema: CreateSSHAccountSchema,
- updateAccountSchema: UpdateSSHAccountSchema
- });
- },
- [PamResource.Kubernetes]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.Kubernetes,
- accountResponseSchema: SanitizedKubernetesAccountWithResourceSchema,
- createAccountSchema: CreateKubernetesAccountSchema,
- updateAccountSchema: UpdateKubernetesAccountSchema
- });
- },
- [PamResource.AwsIam]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.AwsIam,
- accountResponseSchema: SanitizedAwsIamAccountWithResourceSchema,
- createAccountSchema: CreateAwsIamAccountSchema,
- updateAccountSchema: UpdateAwsIamAccountSchema
- });
- },
- [PamResource.Windows]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.Windows,
- accountResponseSchema: SanitizedWindowsAccountWithResourceSchema,
- createAccountSchema: CreateWindowsAccountSchema,
- updateAccountSchema: UpdateWindowsAccountSchema
- });
- },
- [PamResource.OracleDB]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamResource.OracleDB,
- accountResponseSchema: SanitizedOracleAccountWithResourceSchema,
- createAccountSchema: CreateOracleAccountSchema,
- updateAccountSchema: UpdateOracleAccountSchema
- });
- }
-};
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts
deleted file mode 100644
index 2b444685f4..0000000000
--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-endpoints.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamParentType } from "@app/ee/services/pam-account/pam-account-enums";
-import { TPamAccount } from "@app/ee/services/pam-resource/pam-resource-types";
-import { 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 { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-
-export const registerPamAccountEndpoints = <C extends TPamAccount>({
- server,
- parentType,
- createAccountSchema,
- updateAccountSchema,
- accountResponseSchema
-}: {
- server: FastifyZodProvider;
- parentType: PamParentType;
- createAccountSchema: z.ZodType<{
- credentials: C["credentials"];
- resourceId?: C["resourceId"];
- domainId?: C["domainId"];
- folderId?: C["folderId"];
- name: C["name"];
- description?: C["description"];
- requireMfa?: C["requireMfa"];
- internalMetadata?: Record<string, unknown>;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- policyId?: string | null;
- }>;
- updateAccountSchema: z.ZodType<{
- credentials?: C["credentials"];
- name?: C["name"];
- description?: C["description"];
- requireMfa?: C["requireMfa"];
- internalMetadata?: Record<string, unknown>;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- policyId?: string | null;
- }>;
- accountResponseSchema: z.ZodTypeAny;
-}) => {
- // Convert parent type enum value to PascalCase for operation IDs
- // e.g., "postgres" -> "Postgres", "aws-iam" -> "AwsIam"
- const parentTypeId = parentType
- .split("-")
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
- .join("");
-
- server.route({
- method: "POST",
- url: "/",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `create${parentTypeId}PamAccount`,
- description: "Create PAM account",
- body: createAccountSchema,
- response: {
- 200: z.object({
- account: accountResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const account = await server.services.pamAccount.create(
- {
- ...req.body,
- resourceId: req.body.resourceId ?? undefined,
- domainId: req.body.domainId ?? undefined
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: account.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_CREATE,
- metadata: {
- resourceId: req.body.resourceId,
- domainId: req.body.domainId,
- parentType,
- folderId: req.body.folderId,
- name: req.body.name,
- description: req.body.description,
- requireMfa: req.body.requireMfa
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamAccountCreated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- parentType,
- projectId: account.projectId
- }
- })
- .catch(() => {});
-
- return { account };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:accountId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `update${parentTypeId}PamAccount`,
- description: "Update PAM account",
- params: z.object({
- accountId: z.string().uuid()
- }),
- body: updateAccountSchema,
- response: {
- 200: z.object({
- account: accountResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const account = await server.services.pamAccount.updateById(
- {
- ...req.body,
- accountId: req.params.accountId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: account.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_UPDATE,
- metadata: {
- accountId: req.params.accountId,
- resourceId: account.resourceId,
- domainId: account.domainId,
- parentType,
- name: req.body.name,
- description: req.body.description,
- requireMfa: req.body.requireMfa
- }
- }
- });
-
- return { account };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:accountId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `delete${parentTypeId}PamAccount`,
- description: "Delete PAM account",
- params: z.object({
- accountId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- account: accountResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const account = await server.services.pamAccount.deleteById(req.params.accountId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: account.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_DELETE,
- metadata: {
- accountId: req.params.accountId,
- accountName: account.name,
- resourceId: account.resourceId,
- domainId: account.domainId,
- parentType
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamAccountDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- parentType,
- projectId: account.projectId
- }
- })
- .catch(() => {});
-
- return { account };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
deleted file mode 100644
index 581f3e1e8f..0000000000
--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
+++ /dev/null
@@ -1,875 +0,0 @@
-import type WebSocket from "ws";
-import { z } from "zod";
-
-import { PamAccountDependenciesSchema, PamDomainsSchema, PamResourcesSchema } from "@app/db/schemas";
-import { AuditLogInfo, EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamAccountOrderBy, PamAccountView, PamParentType } from "@app/ee/services/pam-account/pam-account-enums";
-import {
- ActiveDirectoryAccountCredentialsSchema,
- SanitizedActiveDirectoryAccountWithDomainSchema
-} from "@app/ee/services/pam-domain/active-directory/active-directory-domain-schemas";
-import { PamDomainType } from "@app/ee/services/pam-domain/pam-domain-enums";
-import {
- AwsIamAccountCredentialsSchema,
- SanitizedAwsIamAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
-import {
- KubernetesAccountCredentialsSchema,
- SanitizedKubernetesAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import {
- MongoDBAccountCredentialsSchema,
- SanitizedMongoDBAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";
-import {
- MsSQLAccountCredentialsSchema,
- SanitizedMsSQLAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import {
- MySQLAccountCredentialsSchema,
- SanitizedMySQLAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
-import {
- OracleAccountCredentialsSchema,
- SanitizedOracleAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/oracle/oracle-resource-schemas";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { GatewayAccessResponseSchema } from "@app/ee/services/pam-resource/pam-resource-schemas";
-import {
- PostgresAccountCredentialsSchema,
- SanitizedPostgresAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import {
- RedisAccountCredentialsSchema,
- SanitizedRedisAccountWithResourceSchema
-} from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import {
- SanitizedSSHAccountWithResourceSchema,
- SSHAccountCredentialsSchema
-} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import {
- SanitizedWindowsAccountWithResourceSchema,
- WindowsAccountCredentialsSchema
-} from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-import { ms } from "@app/lib/ms";
-import { OrderByDirection } from "@app/lib/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 { ActorType, AuthMode } from "@app/services/auth/auth-type";
-import { TokenType } from "@app/services/auth-token/auth-token-types";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-
-const SanitizedAccountSchema = z
- .discriminatedUnion("parentType", [
- SanitizedKubernetesAccountWithResourceSchema,
- SanitizedSSHAccountWithResourceSchema,
- SanitizedPostgresAccountWithResourceSchema,
- SanitizedMySQLAccountWithResourceSchema,
- SanitizedMsSQLAccountWithResourceSchema,
- SanitizedMongoDBAccountWithResourceSchema,
- SanitizedRedisAccountWithResourceSchema,
- SanitizedAwsIamAccountWithResourceSchema,
- SanitizedWindowsAccountWithResourceSchema,
- SanitizedOracleAccountWithResourceSchema,
- SanitizedActiveDirectoryAccountWithDomainSchema
- ])
- .and(
- z.object({
- credentialsConfigured: z.boolean(),
- dependencyCount: z.number().default(0)
- })
- );
-
-const ListPamAccountsResponseSchema = z.object({
- accounts: SanitizedAccountSchema.array(),
- totalCount: z.number().default(0)
-});
-
-const AccountCredentialsBaseSchema = z.object({
- accountId: z.string().uuid(),
- accountName: z.string(),
- projectId: z.string().uuid(),
- resource: PamResourcesSchema.pick({ id: true, name: true, resourceType: true }).nullable().optional(),
- domain: PamDomainsSchema.pick({ id: true, name: true, domainType: true }).nullable().optional()
-});
-
-const AccountCredentialsResponseSchema = z.discriminatedUnion("parentType", [
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.Postgres),
- credentials: PostgresAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.MySQL),
- credentials: MySQLAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.MsSQL),
- credentials: MsSQLAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.MongoDB),
- credentials: MongoDBAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.Redis),
- credentials: RedisAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.SSH),
- credentials: SSHAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.Kubernetes),
- credentials: KubernetesAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.AwsIam),
- credentials: AwsIamAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.Windows),
- credentials: WindowsAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamResource.OracleDB),
- credentials: OracleAccountCredentialsSchema
- }),
- AccountCredentialsBaseSchema.extend({
- parentType: z.literal(PamDomainType.ActiveDirectory),
- credentials: ActiveDirectoryAccountCredentialsSchema
- })
-]);
-
-export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:accountId/dependencies",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get PAM account dependencies",
- params: z.object({
- accountId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- dependencies: PamAccountDependenciesSchema.extend({
- resourceName: z.string().nullable().optional(),
- lastSyncMessage: z.string().nullable().optional()
- }).array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const dependencies = await server.services.pamDiscoverySource.getAccountDependencies({
- accountId: req.params.accountId,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- return { dependencies };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:accountId/dependencies/:dependencyId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Update a PAM account dependency",
- params: z.object({
- accountId: z.string().uuid(),
- dependencyId: z.string().uuid()
- }),
- body: z.object({
- isRotationSyncEnabled: z.boolean()
- }),
- response: {
- 200: z.object({
- dependency: PamAccountDependenciesSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const dependency = await server.services.pamDiscoverySource.updateAccountDependency({
- accountId: req.params.accountId,
- dependencyId: req.params.dependencyId,
- isRotationSyncEnabled: req.body.isRotationSyncEnabled,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- return { dependency };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:accountId/dependencies/:dependencyId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Delete a PAM account dependency",
- params: z.object({
- accountId: z.string().uuid(),
- dependencyId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- dependency: z.object({
- id: z.string().uuid()
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const dependency = await server.services.pamDiscoverySource.deleteAccountDependency({
- accountId: req.params.accountId,
- dependencyId: req.params.dependencyId,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- return { dependency };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:accountId/rotate",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "triggerPamAccountRotation",
- description: "Manually trigger credential rotation for a PAM account",
- params: z.object({
- accountId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- account: SanitizedAccountSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const account = await server.services.pamAccount.triggerManualRotation(req.params.accountId, req.permission);
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamAccountRotated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- parentType: account.parentType as PamParentType,
- projectId: account.projectId
- }
- })
- .catch(() => {});
-
- return { account: account as z.infer<typeof SanitizedAccountSchema> };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:accountId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get PAM account by ID",
- params: z.object({
- accountId: z.string().uuid()
- }),
- response: {
- 200: SanitizedAccountSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { accountId } = req.params;
-
- const account = await server.services.pamAccount.getById({
- accountId,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: account.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_GET,
- metadata: {
- accountId: account.id,
- accountName: account.name
- }
- }
- });
-
- return account as z.infer<typeof SanitizedAccountSchema>;
- }
- });
-
- server.route({
- method: "POST",
- url: "/:accountId/credentials",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "View full (unsanitized) PAM account credentials",
- params: z.object({
- accountId: z.string().uuid()
- }),
- body: z.object({
- mfaSessionId: z.string().optional()
- }),
- response: {
- 200: AccountCredentialsResponseSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const result = await server.services.pamAccount.viewCredentials({
- accountId: req.params.accountId,
- mfaSessionId: req.body.mfaSessionId,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: result.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_READ_CREDENTIALS,
- metadata: {
- accountId: result.accountId,
- accountName: result.accountName,
- resourceId: result.resource?.id,
- resourceType: result.resource?.resourceType,
- domainId: result.domain?.id,
- domainType: result.domain?.domainType
- }
- }
- });
-
- return result as z.infer<typeof AccountCredentialsResponseSchema>;
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM accounts",
- querystring: z.object({
- projectId: z.string().uuid(),
- accountView: z.nativeEnum(PamAccountView).default(PamAccountView.Flat),
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(100),
- orderBy: z.nativeEnum(PamAccountOrderBy).default(PamAccountOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- search: z.string().trim().optional(),
- filterResourceIds: z
- .string()
- .transform((val) =>
- val
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean)
- )
- .optional()
- }),
- response: {
- 200: ListPamAccountsResponseSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId, accountView, limit, offset, search, orderBy, orderDirection, filterResourceIds } = req.query;
-
- const { accounts, totalCount } = await server.services.pamAccount.list({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId,
- accountView,
- limit,
- offset,
- search,
- orderBy,
- orderDirection,
- filterResourceIds
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_ACCOUNT_LIST,
- metadata: {
- accountCount: accounts.length
- }
- }
- });
-
- return { accounts, totalCount } as z.infer<typeof ListPamAccountsResponseSchema>;
- }
- });
-
- server.route({
- method: "POST",
- url: "/search",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Search PAM accounts",
- body: z.object({
- projectId: z.string().uuid(),
- accountView: z.nativeEnum(PamAccountView).default(PamAccountView.Flat),
- offset: z.number().min(0).default(0),
- limit: z.number().min(1).max(100).default(100),
- orderBy: z.nativeEnum(PamAccountOrderBy).default(PamAccountOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- search: z.string().trim().optional(),
- filterResourceIds: z.array(z.string().uuid()).optional(),
- filterDomainIds: z.array(z.string().uuid()).optional(),
- metadata: z
- .array(
- z.object({
- key: z.string().trim().min(1).max(255),
- value: z.string().trim().max(1020).optional()
- })
- )
- .optional()
- }),
- response: {
- 200: ListPamAccountsResponseSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const {
- projectId,
- accountView,
- limit,
- offset,
- search,
- orderBy,
- orderDirection,
- filterResourceIds,
- filterDomainIds,
- metadata
- } = req.body;
-
- const { accounts, totalCount } = await server.services.pamAccount.list({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId,
- accountView,
- limit,
- offset,
- search,
- orderBy,
- orderDirection,
- filterResourceIds,
- filterDomainIds,
- metadataFilter: metadata
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_ACCOUNT_LIST,
- metadata: {
- accountCount: accounts.length
- }
- }
- });
-
- return { accounts, totalCount } as z.infer<typeof ListPamAccountsResponseSchema>;
- }
- });
-
- server.route({
- method: "POST",
- url: "/access",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Access PAM account",
- body: z.object({
- resourceName: z.string().trim(),
- accountName: z.string().trim(),
- projectId: z.string().uuid(),
- mfaSessionId: z.string().optional(),
- reason: z.string().trim().max(1000).optional(),
- duration: z
- .string()
- .min(1)
- .transform((val, ctx) => {
- const parsedMs = ms(val);
-
- if (typeof parsedMs !== "number" || parsedMs <= 0) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Invalid duration format. Must be a positive duration (e.g., '1h', '30m', '2d')."
- });
- return z.NEVER;
- }
- return parsedMs;
- })
- }),
- response: {
- 200: z.discriminatedUnion("resourceType", [
- // Gateway-based resources (Postgres, MySQL, MsSQL, Redis, SSH, Windows/RDP)
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Postgres) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.MySQL) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.MsSQL) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.MongoDB) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Redis) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.SSH) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Kubernetes) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.OracleDB) }),
- GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Windows) }),
- // AWS IAM (no gateway, returns short-lived STS credentials usable by both CLI and console)
- z.object({
- sessionId: z.string(),
- resourceType: z.literal(PamResource.AwsIam),
- accessKeyId: z.string(),
- secretAccessKey: z.string(),
- sessionToken: z.string(),
- expiresAt: z.string(),
- metadata: z.record(z.string(), z.string().optional()).optional()
- })
- ])
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- // To prevent type errors when accessing req.auth
- if (req.auth.authMode !== AuthMode.JWT) {
- throw new BadRequestError({ message: "You can only access PAM accounts using JWT auth tokens." });
- }
-
- const response = await server.services.pamAccount.access(
- {
- actorEmail: req.auth.user.email ?? "",
- actorIp: req.realIp,
- actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),
- actorUserAgent: req.auditLogInfo.userAgent ?? "",
- resourceName: req.body.resourceName,
- accountName: req.body.accountName,
- projectId: req.body.projectId,
- duration: req.body.duration,
- mfaSessionId: req.body.mfaSessionId,
- reason: req.body.reason
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_ACCESS,
- metadata: {
- accountId: response.account.id,
- resourceName: req.body.resourceName,
- accountName: response.account.name,
- duration: req.body.duration ? new Date(req.body.duration).toISOString() : undefined,
- reason: req.body.reason
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamAccountAccessed,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType: response.resourceType,
- projectId: req.body.projectId,
- duration: req.body.duration
- }
- })
- .catch(() => {});
-
- return response;
- }
- });
-
- // Mint an AWS Console federated sign-in URL from an existing AWS IAM session
- server.route({
- method: "POST",
- url: "/sessions/:sessionId/aws-console-url",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Generate an AWS console sign-in URL for an existing PAM session",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- body: z.object({
- projectId: z.string().uuid(),
- accessKeyId: z.string().min(1),
- secretAccessKey: z.string().min(1),
- sessionToken: z.string().min(1)
- }),
- response: {
- 200: z.object({
- consoleUrl: z.string().url()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- if (req.auth.authMode !== AuthMode.JWT) {
- throw new BadRequestError({ message: "You can only access PAM accounts using JWT auth tokens." });
- }
-
- const result = await server.services.pamAccount.getAwsIamConsoleUrl(
- {
- sessionId: req.params.sessionId,
- projectId: req.body.projectId,
- accessKeyId: req.body.accessKeyId,
- secretAccessKey: req.body.secretAccessKey,
- sessionToken: req.body.sessionToken
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_ACCOUNT_AWS_CONSOLE_URL_GENERATED,
- metadata: {
- sessionId: req.params.sessionId,
- accountId: result.accountId ?? "",
- resourceName: result.resourceName,
- accountName: result.accountName
- }
- }
- });
-
- return { consoleUrl: result.consoleUrl };
- }
- });
-
- // Web access ticket endpoint
- server.route({
- method: "POST",
- url: "/:accountId/web-access-ticket",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Issue a one-time ticket for WebSocket web access",
- params: z.object({
- accountId: z.string().uuid()
- }),
- body: z.object({
- projectId: z.string().uuid(),
- mfaSessionId: z.string().optional(),
- reason: z.string().trim().max(1000).optional(),
- resourceId: z.string().uuid().optional()
- }),
- response: {
- 200: z.object({ ticket: z.string() })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- // Narrows TypeScript type so req.auth.user is available below (verifyAuth hook already enforces JWT)
- if (req.auth.authMode !== AuthMode.JWT) {
- throw new BadRequestError({ message: "Web access requires JWT authentication" });
- }
-
- const { ticket } = await server.services.pamWebAccess.issueWebSocketTicket({
- accountId: req.params.accountId,
- projectId: req.body.projectId,
- orgId: req.permission.orgId,
- actor: req.permission,
- actorEmail: req.auth.user.email ?? "",
- actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),
- auditLogInfo: req.auditLogInfo,
- mfaSessionId: req.body.mfaSessionId,
- reason: req.body.reason,
- resourceId: req.body.resourceId
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamWebAccessStarted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- projectId: req.body.projectId
- }
- })
- .catch(() => {});
-
- return { ticket };
- }
- });
-
- // WebSocket endpoint for web access (ticket-based auth)
- server.route({
- method: "GET",
- url: "/:accountId/web-access",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "WebSocket endpoint for browser-based web access to PAM accounts",
- params: z.object({
- accountId: z.string().uuid()
- }),
- querystring: z.object({
- ticket: z.string()
- }),
- response: {
- 200: z.object({ message: z.string() })
- }
- },
- wsHandler: async (connection: WebSocket, req) => {
- // WASM sends frames before ticket validation finishes; buffer them
- const preAuthMessages: { data: Buffer; isBinary: boolean }[] = [];
- const preAuthHandler = (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
- let buf: Buffer;
- if (Buffer.isBuffer(raw)) {
- buf = raw;
- } else if (Array.isArray(raw)) {
- buf = Buffer.concat(raw);
- } else {
- buf = Buffer.from(raw);
- }
- preAuthMessages.push({ data: buf, isBinary });
- };
- connection.on("message", preAuthHandler);
-
- try {
- const ticketValue = req.query.ticket;
- const separatorIndex = ticketValue.indexOf(":");
- if (separatorIndex === -1) {
- connection.off("message", preAuthHandler);
- connection.close(4001, "Invalid or expired ticket");
- return;
- }
-
- const userId = ticketValue.slice(0, separatorIndex);
- const tokenCode = ticketValue.slice(separatorIndex + 1);
-
- const tokenRecord = await server.services.authToken.validateTokenForUser({
- type: TokenType.TOKEN_PAM_WS_TICKET,
- userId,
- code: tokenCode
- });
-
- if (!tokenRecord?.payload) {
- connection.off("message", preAuthHandler);
- connection.close(4001, "Invalid or expired ticket");
- return;
- }
-
- const payload = z
- .object({
- accountId: z.string(),
- projectId: z.string(),
- orgId: z.string(),
- resourceId: z.string(),
- resourceName: z.string(),
- accountName: z.string(),
- actorEmail: z.string(),
- actorName: z.string(),
- reason: z.string().nullable().optional(),
- grantExpiresAt: z.string().nullable().optional(),
- auditLogInfo: z.object({
- ipAddress: z.string().optional(),
- userAgent: z.string().optional(),
- userAgentType: z.nativeEnum(UserAgentType).optional(),
- actor: z.object({
- type: z.nativeEnum(ActorType),
- metadata: z.record(z.unknown())
- })
- })
- })
- .parse(JSON.parse(tokenRecord.payload));
-
- if (payload.accountId !== req.params.accountId) {
- connection.off("message", preAuthHandler);
- connection.close(4001, "Invalid or expired ticket");
- return;
- }
-
- await server.services.pamWebAccess.handleWebSocketConnection({
- socket: connection,
- accountId: payload.accountId,
- projectId: payload.projectId,
- orgId: payload.orgId,
- resourceId: payload.resourceId,
- resourceName: payload.resourceName,
- accountName: payload.accountName,
- actorEmail: payload.actorEmail,
- actorName: payload.actorName,
- auditLogInfo: payload.auditLogInfo as AuditLogInfo,
- userId,
- actorIp: req.realIp ?? "",
- actorUserAgent: req.headers["user-agent"] ?? "",
- reason: payload.reason,
- grantExpiresAt: payload.grantExpiresAt ?? null,
- preAuthMessages,
- preAuthHandler
- });
- } catch (err) {
- connection.off("message", preAuthHandler);
- logger.error(err, "WebSocket ticket validation failed");
- connection.close(4001, "Invalid or expired ticket");
- }
- },
- handler: async () => {
- return { message: "WebSocket upgrade required" };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/index.ts b/backend/src/ee/routes/v1/pam-discovery-routers/index.ts
deleted file mode 100644
index fe1a4a773f..0000000000
--- a/backend/src/ee/routes/v1/pam-discovery-routers/index.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import {
- ActiveDirectoryDiscoverySourceRunSchema,
- CreateActiveDirectoryDiscoverySourceSchema,
- SanitizedActiveDirectoryDiscoverySourceSchema,
- UpdateActiveDirectoryDiscoverySourceSchema
-} from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas";
-import { PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
-
-import { registerPamDiscoveryEndpoints } from "./pam-discovery-endpoints";
-
-export const PAM_DISCOVERY_REGISTER_ROUTER_MAP: Record<
- PamDiscoveryType,
- (server: FastifyZodProvider) => Promise<void>
-> = {
- [PamDiscoveryType.ActiveDirectory]: async (server: FastifyZodProvider) => {
- registerPamDiscoveryEndpoints({
- server,
- discoveryType: PamDiscoveryType.ActiveDirectory,
- createDiscoverySourceSchema: CreateActiveDirectoryDiscoverySourceSchema,
- updateDiscoverySourceSchema: UpdateActiveDirectoryDiscoverySourceSchema,
- discoveryResponseSchema: SanitizedActiveDirectoryDiscoverySourceSchema,
- discoveryRunResponseSchema: ActiveDirectoryDiscoverySourceRunSchema
- });
- }
-};
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts
deleted file mode 100644
index 363ca23788..0000000000
--- a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts
+++ /dev/null
@@ -1,507 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PAM_DISCOVERY_TYPE_PASCAL_MAP, PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
-import {
- DiscoveredAccountSchema,
- DiscoveredResourceSchema
-} from "@app/ee/services/pam-discovery/pam-discovery-schemas";
-import { TPamDiscoverySource } from "@app/ee/services/pam-discovery/pam-discovery-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";
-
-export const registerPamDiscoveryEndpoints = <T extends TPamDiscoverySource>({
- server,
- discoveryType,
- createDiscoverySourceSchema,
- updateDiscoverySourceSchema,
- discoveryResponseSchema,
- discoveryRunResponseSchema
-}: {
- server: FastifyZodProvider;
- discoveryType: PamDiscoveryType;
- createDiscoverySourceSchema: z.ZodType<{
- name: T["name"];
- projectId: T["projectId"];
- discoveryConfiguration: T["discoveryConfiguration"];
- discoveryCredentials: T["discoveryCredentials"];
- schedule: T["schedule"];
- gatewayId?: string;
- gatewayPoolId?: string;
- }>;
- updateDiscoverySourceSchema: z.ZodType<{
- name?: T["name"];
- discoveryConfiguration?: T["discoveryConfiguration"];
- discoveryCredentials?: T["discoveryCredentials"];
- schedule?: T["schedule"];
- gatewayId?: string;
- gatewayPoolId?: string;
- }>;
- discoveryResponseSchema: z.ZodTypeAny;
- discoveryRunResponseSchema: z.ZodTypeAny;
-}) => {
- const discoveryTypeId = PAM_DISCOVERY_TYPE_PASCAL_MAP[discoveryType];
-
- server.route({
- method: "GET",
- url: "/:discoverySourceId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${discoveryTypeId}PamDiscoverySource`,
- description: "Get PAM Discovery Source",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- source: discoveryResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const source = await server.services.pamDiscoverySource.getById(
- req.params.discoverySourceId,
- discoveryType,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: source.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_GET,
- metadata: {
- sourceId: source.id,
- sourceName: source.name,
- discoveryType: source.discoveryType,
- name: source.name
- }
- }
- });
-
- return { source };
- }
- });
-
- server.route({
- method: "POST",
- url: "/",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `create${discoveryTypeId}PamDiscoverySource`,
- description: "Create PAM Discovery Source",
- body: createDiscoverySourceSchema,
- response: {
- 200: z.object({
- source: discoveryResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const source = await server.services.pamDiscoverySource.create(
- {
- ...req.body,
- discoveryType
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_CREATE,
- metadata: {
- discoveryType,
- sourceName: req.body.name,
- gatewayId: req.body.gatewayId,
- name: req.body.name
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamDiscoverySourceCreated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- discoveryType,
- projectId: req.body.projectId
- }
- })
- .catch(() => {});
-
- return { source };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:discoverySourceId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `update${discoveryTypeId}PamDiscoverySource`,
- description: "Update PAM Discovery Source",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- body: updateDiscoverySourceSchema,
- response: {
- 200: z.object({
- source: discoveryResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const source = await server.services.pamDiscoverySource.updateById(
- {
- ...req.body,
- discoverySourceId: req.params.discoverySourceId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: source.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_UPDATE,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: source.name,
- discoveryType,
- ...(req.body.gatewayId && { gatewayId: req.body.gatewayId }),
- ...(req.body.name && { newSourceName: req.body.name })
- }
- }
- });
-
- return { source };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:discoverySourceId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `delete${discoveryTypeId}PamDiscoverySource`,
- description: "Delete PAM Discovery Source",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- source: discoveryResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const source = await server.services.pamDiscoverySource.deleteById(req.params.discoverySourceId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: source.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_DELETE,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: source.name,
- discoveryType
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamDiscoverySourceDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- discoveryType,
- projectId: source.projectId
- }
- })
- .catch(() => {});
-
- return { source };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:discoverySourceId/scan",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `trigger${discoveryTypeId}PamDiscoverySourceScan`,
- description: "Trigger PAM Discovery Source scan",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- message: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { message, discoverySource } = await server.services.pamDiscoverySource.triggerScanById(
- req.params.discoverySourceId,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: discoverySource.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SCAN,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: discoverySource.name,
- discoveryType
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamDiscoveryScanTriggered,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- discoveryType,
- projectId: discoverySource.projectId
- }
- })
- .catch(() => {});
-
- return { message };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:discoverySourceId/runs",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${discoveryTypeId}PamDiscoverySourceRuns`,
- description: "Get PAM Discovery Source runs",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- querystring: z.object({
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(25)
- }),
- response: {
- 200: z.object({
- runs: discoveryRunResponseSchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { runs, totalCount, discoverySource } = await server.services.pamDiscoverySource.getDiscoveryRuns(
- {
- ...req.query,
- discoverySourceId: req.params.discoverySourceId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: discoverySource.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_RUN_LIST,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: discoverySource.name,
- discoveryType,
- count: totalCount
- }
- }
- });
-
- return { runs, totalCount };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:discoverySourceId/runs/:runId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${discoveryTypeId}PamDiscoverySourceRun`,
- description: "Get PAM Discovery Source run",
- params: z.object({
- discoverySourceId: z.string().uuid(),
- runId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- run: discoveryRunResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { run, discoverySource } = await server.services.pamDiscoverySource.getDiscoveryRunById(
- req.params,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: discoverySource.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_RUN_GET,
- metadata: {
- sourceId: discoverySource.id,
- sourceName: discoverySource.name,
- discoveryType,
- runId: run.id
- }
- }
- });
-
- return { run };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:discoverySourceId/resources",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${discoveryTypeId}PamDiscoverySourceResources`,
- description: "Get PAM Discovery Source resources",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- querystring: z.object({
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(25)
- }),
- response: {
- 200: z.object({
- resources: DiscoveredResourceSchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resources, totalCount, discoverySource } =
- await server.services.pamDiscoverySource.getDiscoveredResources(
- {
- ...req.query,
- discoverySourceId: req.params.discoverySourceId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: discoverySource.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_RESOURCE_LIST,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: discoverySource.name,
- discoveryType,
- count: totalCount
- }
- }
- });
-
- return { resources, totalCount };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:discoverySourceId/accounts",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${discoveryTypeId}PamDiscoverySourceAccounts`,
- description: "Get PAM Discovery Source accounts",
- params: z.object({
- discoverySourceId: z.string().uuid()
- }),
- querystring: z.object({
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(25)
- }),
- response: {
- 200: z.object({
- accounts: DiscoveredAccountSchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { accounts, totalCount, discoverySource } = await server.services.pamDiscoverySource.getDiscoveredAccounts(
- {
- ...req.query,
- discoverySourceId: req.params.discoverySourceId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: discoverySource.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_ACCOUNT_LIST,
- metadata: {
- sourceId: req.params.discoverySourceId,
- sourceName: discoverySource.name,
- discoveryType,
- count: totalCount
- }
- }
- });
-
- return { accounts, totalCount };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts
deleted file mode 100644
index 60ac48ce15..0000000000
--- a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import {
- ActiveDirectoryDiscoveryListItemSchema,
- SanitizedActiveDirectoryDiscoverySourceSchema
-} from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas";
-import { PamDiscoveryOrderBy } from "@app/ee/services/pam-discovery/pam-discovery-enums";
-import { OrderByDirection } from "@app/lib/types";
-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 SanitizedDiscoverySourcesSchema = z.discriminatedUnion("discoveryType", [
- SanitizedActiveDirectoryDiscoverySourceSchema
-]);
-
-const DiscoveryOptionsSchema = z.discriminatedUnion("discoveryType", [ActiveDirectoryDiscoveryListItemSchema]);
-
-export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/options",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM discovery types",
- response: {
- 200: z.object({
- discoveryOptions: DiscoveryOptionsSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: () => {
- const discoveryOptions = server.services.pamDiscoverySource.listDiscoverySourceOptions();
- return { discoveryOptions };
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM discovery sources",
- querystring: z.object({
- projectId: z.string().uuid(),
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(100),
- orderBy: z.nativeEnum(PamDiscoveryOrderBy).default(PamDiscoveryOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- search: z.string().trim().optional(),
- filterDiscoveryTypes: z
- .string()
- .transform((val) =>
- val
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean)
- )
- .optional()
- }),
- response: {
- 200: z.object({
- sources: SanitizedDiscoverySourcesSchema.and(
- z.object({
- totalResources: z.number(),
- totalAccounts: z.number(),
- totalDependencies: z.number()
- })
- ).array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { sources, totalCount } = await server.services.pamDiscoverySource.list({
- ...req.query,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.query.projectId,
- event: {
- type: EventType.PAM_DISCOVERY_SOURCE_LIST,
- metadata: {
- count: totalCount
- }
- }
- });
-
- return { sources, totalCount };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-domain-routers/index.ts b/backend/src/ee/routes/v1/pam-domain-routers/index.ts
deleted file mode 100644
index ab5f2eb432..0000000000
--- a/backend/src/ee/routes/v1/pam-domain-routers/index.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { registerPamAccountEndpoints } from "@app/ee/routes/v1/pam-account-routers/pam-account-endpoints";
-import {
- CreateActiveDirectoryAccountSchema,
- SanitizedActiveDirectoryAccountWithDomainSchema,
- UpdateActiveDirectoryAccountSchema
-} from "@app/ee/services/pam-domain/active-directory/active-directory-domain-schemas";
-import { PamDomainType } from "@app/ee/services/pam-domain/pam-domain-enums";
-import {
- CreateActiveDirectoryDomainSchema,
- SanitizedActiveDirectoryDomainSchema,
- UpdateActiveDirectoryDomainSchema
-} from "@app/ee/services/pam-domain/pam-domain-schemas";
-
-import { registerActiveDirectoryRelatedResourcesEndpoint, registerPamDomainEndpoints } from "./pam-domain-endpoints";
-
-export { registerPamDomainRouter } from "./pam-domain-router";
-
-export const PAM_DOMAIN_REGISTER_ROUTER_MAP: Record<PamDomainType, (server: FastifyZodProvider) => Promise<void>> = {
- [PamDomainType.ActiveDirectory]: async (server: FastifyZodProvider) => {
- registerPamDomainEndpoints({
- server,
- domainType: PamDomainType.ActiveDirectory,
- domainResponseSchema: SanitizedActiveDirectoryDomainSchema,
- createDomainSchema: CreateActiveDirectoryDomainSchema,
- updateDomainSchema: UpdateActiveDirectoryDomainSchema
- });
- registerActiveDirectoryRelatedResourcesEndpoint(server);
- }
-};
-
-export const PAM_DOMAIN_ACCOUNT_REGISTER_ROUTER_MAP: Record<
- PamDomainType,
- (server: FastifyZodProvider) => Promise<void>
-> = {
- [PamDomainType.ActiveDirectory]: async (server: FastifyZodProvider) => {
- registerPamAccountEndpoints({
- server,
- parentType: PamDomainType.ActiveDirectory,
- accountResponseSchema: SanitizedActiveDirectoryAccountWithDomainSchema,
- createAccountSchema: CreateActiveDirectoryAccountSchema,
- updateAccountSchema: UpdateActiveDirectoryAccountSchema
- });
- }
-};
diff --git a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts b/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts
deleted file mode 100644
index f2f2681b18..0000000000
--- a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamDomainType } from "@app/ee/services/pam-domain/pam-domain-enums";
-import { TPamDomain } from "@app/ee/services/pam-domain/pam-domain-types";
-import { SanitizedWindowsResourceSchema } from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-export const registerPamDomainEndpoints = <T extends TPamDomain>({
- server,
- domainType,
- createDomainSchema,
- updateDomainSchema,
- domainResponseSchema
-}: {
- server: FastifyZodProvider;
- domainType: PamDomainType;
- createDomainSchema: z.ZodType<{
- projectId: T["projectId"];
- connectionDetails: T["connectionDetails"];
- gatewayId?: string;
- gatewayPoolId?: string;
- name: T["name"];
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- }>;
- updateDomainSchema: z.ZodType<{
- connectionDetails?: T["connectionDetails"];
- gatewayId?: string;
- gatewayPoolId?: string;
- name?: T["name"];
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- }>;
- domainResponseSchema: z.ZodTypeAny;
-}) => {
- const domainTypeId = domainType
- .split("-")
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
- .join("");
-
- server.route({
- method: "GET",
- url: "/:domainId",
- config: { rateLimit: readLimit },
- schema: {
- operationId: `get${domainTypeId}PamDomain`,
- description: `Get ${domainTypeId} PAM domain`,
- params: z.object({ domainId: z.string().uuid() }),
- response: {
- 200: z.object({
- domain: domainResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const domain = await server.services.pamDomain.getById(req.params.domainId, domainType, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: domain.projectId,
- event: {
- type: EventType.PAM_DOMAIN_GET,
- metadata: {
- domainId: domain.id,
- domainType: domain.domainType,
- name: domain.name
- }
- }
- });
-
- return { domain };
- }
- });
-
- server.route({
- method: "POST",
- url: "/",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: `create${domainTypeId}PamDomain`,
- description: `Create ${domainTypeId} PAM domain`,
- body: createDomainSchema,
- response: {
- 200: z.object({
- domain: domainResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const domain = await server.services.pamDomain.create(
- {
- ...req.body,
- domainType
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_DOMAIN_CREATE,
- metadata: {
- domainType,
- ...(req.body.gatewayId && { gatewayId: req.body.gatewayId }),
- name: req.body.name
- }
- }
- });
-
- return { domain };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:domainId",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: `update${domainTypeId}PamDomain`,
- description: `Update ${domainTypeId} PAM domain`,
- params: z.object({ domainId: z.string().uuid() }),
- body: updateDomainSchema,
- response: {
- 200: z.object({
- domain: domainResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const domain = await server.services.pamDomain.updateById(
- {
- ...req.body,
- domainId: req.params.domainId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: domain.projectId,
- event: {
- type: EventType.PAM_DOMAIN_UPDATE,
- metadata: {
- domainId: req.params.domainId,
- domainType,
- ...(req.body.gatewayId && { gatewayId: req.body.gatewayId }),
- ...(req.body.name && { name: req.body.name })
- }
- }
- });
-
- return { domain };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:domainId",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: `delete${domainTypeId}PamDomain`,
- description: `Delete ${domainTypeId} PAM domain`,
- params: z.object({ domainId: z.string().uuid() }),
- response: {
- 200: z.object({
- domain: domainResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const domain = await server.services.pamDomain.deleteById(req.params.domainId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: domain.projectId,
- event: {
- type: EventType.PAM_DOMAIN_DELETE,
- metadata: {
- domainId: req.params.domainId,
- domainType
- }
- }
- });
-
- return { domain };
- }
- });
-};
-
-export const registerActiveDirectoryRelatedResourcesEndpoint = (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:domainId/related-resources",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "listActiveDirectoryDomainRelatedResources",
- description: "List resources related to an Active Directory domain",
- params: z.object({ domainId: z.string().uuid() }),
- response: {
- 200: z.object({
- resources: SanitizedWindowsResourceSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const resources = await server.services.pamDomain.listRelatedResources(req.params.domainId, req.permission);
- return { resources };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-router.ts b/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-router.ts
deleted file mode 100644
index f88eb9fc09..0000000000
--- a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-router.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamDomainOrderBy } from "@app/ee/services/pam-domain/pam-domain-enums";
-import {
- ActiveDirectoryDomainListItemSchema,
- SanitizedDomainSchema
-} from "@app/ee/services/pam-domain/pam-domain-schemas";
-import { OrderByDirection } from "@app/lib/types";
-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 DomainOptionsSchema = z.discriminatedUnion("domain", [ActiveDirectoryDomainListItemSchema]);
-
-export const registerPamDomainRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/options",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "listPamDomainOptions",
- description: "List available PAM domain types",
- response: {
- 200: z.object({
- options: DomainOptionsSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: () => {
- const options = server.services.pamDomain.listDomainOptions();
- return { options };
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "listPamDomains",
- description: "List PAM domains",
- querystring: z.object({
- projectId: z.string().uuid(),
- search: z.string().optional(),
- limit: z.coerce.number().int().min(1).max(100).optional(),
- offset: z.coerce.number().int().min(0).optional(),
- orderBy: z.nativeEnum(PamDomainOrderBy).default(PamDomainOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- filterDomainTypes: z
- .string()
- .transform((val) =>
- val
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean)
- )
- .optional(),
- discoveryFingerprint: z.string().optional()
- }),
- response: {
- 200: z.object({
- domains: SanitizedDomainSchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { projectId, search, limit, offset, orderBy, orderDirection, filterDomainTypes, discoveryFingerprint } =
- req.query;
-
- const { domains, totalCount } = await server.services.pamDomain.list({
- projectId,
- search,
- limit,
- offset,
- orderBy,
- orderDirection,
- filterDomainTypes,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- discoveryFingerprint
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_DOMAIN_LIST,
- metadata: {
- count: domains.length
- }
- }
- });
-
- return { domains, totalCount };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-folder-router.ts b/backend/src/ee/routes/v1/pam-folder-router.ts
deleted file mode 100644
index cd2506aba2..0000000000
--- a/backend/src/ee/routes/v1/pam-folder-router.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { z } from "zod";
-
-import { PamFoldersSchema } from "@app/db/schemas";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { isValidFolderName } from "@app/lib/validator";
-import { writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-export const registerPamFolderRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "POST",
- url: "/",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Create PAM folder",
- body: z.object({
- projectId: z.string().uuid(),
- parentId: z.string().uuid().nullable().optional(),
- name: z
- .string()
- .trim()
- .refine((name) => isValidFolderName(name), {
- message: "Folder name can only contain alphanumeric characters, dashes, and underscores."
- }),
- description: z.string().trim().max(512).nullable().optional()
- }),
- response: {
- 200: z.object({
- folder: PamFoldersSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const folder = await server.services.pamFolder.createFolder(req.body, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_FOLDER_CREATE,
- metadata: {
- name: req.body.name,
- description: req.body.description,
- parentId: req.body.parentId
- }
- }
- });
-
- return { folder };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Update PAM folder",
- params: z.object({
- folderId: z.string().uuid()
- }),
- body: z.object({
- name: z
- .string()
- .trim()
- .optional()
- .refine((name) => (name ? isValidFolderName(name) : true), {
- message: "Folder name can only contain alphanumeric characters, dashes, and underscores."
- }),
- description: z.string().trim().max(512).nullable().optional()
- }),
- response: {
- 200: z.object({
- folder: PamFoldersSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const folder = await server.services.pamFolder.updateFolder(
- {
- ...req.body,
- id: req.params.folderId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: folder.projectId,
- event: {
- type: EventType.PAM_FOLDER_UPDATE,
- metadata: {
- folderId: req.params.folderId,
- name: req.body.name,
- description: req.body.description
- }
- }
- });
-
- return { folder };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Delete PAM folder",
- params: z.object({
- folderId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- folder: PamFoldersSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const folder = await server.services.pamFolder.deleteFolder(req.params.folderId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: folder.projectId,
- event: {
- type: EventType.PAM_FOLDER_DELETE,
- metadata: {
- folderName: folder.name,
- folderId: req.params.folderId
- }
- }
- });
-
- return { folder };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-insights-router.ts b/backend/src/ee/routes/v1/pam-insights-router.ts
deleted file mode 100644
index bf211d4b40..0000000000
--- a/backend/src/ee/routes/v1/pam-insights-router.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { readLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-export const registerPamInsightsRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/summary",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getPamInsightsSummary",
- description: "Get PAM project totals: resources, accounts, and active sessions",
- security: [{ bearerAuth: [] }],
- querystring: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- totalResources: z.number(),
- resourcesWithRotation: z.number(),
- totalAccounts: z.number(),
- failedRotations: z.number(),
- failedRotationAccounts: z.array(
- z.object({
- accountId: z.string(),
- accountName: z.string(),
- resourceId: z.string(),
- resourceName: z.string(),
- resourceType: z.string(),
- lastRotatedAt: z.date().nullable()
- })
- ),
- activeSessions: z.number(),
- resourceTypeCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId } = req.query;
- const result = await server.services.pamInsights.getSummary(projectId, req.permission);
- await server.services.auditLog.createAuditLog({
- projectId,
- event: { type: EventType.VIEW_INSIGHTS_PAM_SUMMARY, metadata: { projectId } },
- ...req.auditLogInfo
- });
- return result;
- }
- });
-
- server.route({
- method: "GET",
- url: "/session-activity",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getPamInsightsSessionActivity",
- description: "Get session counts grouped by day for the last 30 days",
- security: [{ bearerAuth: [] }],
- querystring: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- days: z.array(z.object({ date: z.string(), count: z.number() })),
- avgPerDay: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId } = req.query;
- const result = await server.services.pamInsights.getSessionActivity(projectId, req.permission);
- await server.services.auditLog.createAuditLog({
- projectId,
- event: { type: EventType.VIEW_INSIGHTS_PAM_SESSION_ACTIVITY, metadata: { projectId } },
- ...req.auditLogInfo
- });
- return result;
- }
- });
-
- server.route({
- method: "GET",
- url: "/top-actors",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getPamInsightsTopActors",
- description: "Get top actors initiating PAM sessions in the last 30 days",
- security: [{ bearerAuth: [] }],
- querystring: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- actors: z.array(
- z.object({
- actorName: z.string(),
- actorEmail: z.string(),
- sessionCount: z.number(),
- isService: z.boolean()
- })
- )
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId } = req.query;
- const result = await server.services.pamInsights.getTopActors(projectId, req.permission);
- await server.services.auditLog.createAuditLog({
- projectId,
- event: { type: EventType.VIEW_INSIGHTS_PAM_TOP_ACTORS, metadata: { projectId } },
- ...req.auditLogInfo
- });
- return result;
- }
- });
-
- server.route({
- method: "GET",
- url: "/resource-breakdown",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getPamInsightsResourceBreakdown",
- description: "Get count of resources and accounts grouped by resource type",
- security: [{ bearerAuth: [] }],
- querystring: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- breakdown: z.array(
- z.object({
- resourceType: z.string(),
- resourceCount: z.number()
- })
- )
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId } = req.query;
- const result = await server.services.pamInsights.getResourceBreakdown(projectId, req.permission);
- await server.services.auditLog.createAuditLog({
- projectId,
- event: { type: EventType.VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN, metadata: { projectId } },
- ...req.auditLogInfo
- });
- return result;
- }
- });
-
- server.route({
- method: "GET",
- url: "/rotation-calendar",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getPamInsightsRotationCalendar",
- description: "Get rotation events for a calendar month, expanded across the visible grid",
- security: [{ bearerAuth: [] }],
- querystring: z.object({
- projectId: z.string().trim(),
- month: z.coerce.number().int().min(1).max(12),
- year: z.coerce.number().int().min(1970).max(9999)
- }),
- response: {
- 200: z.object({
- rotations: z.array(
- z.object({
- id: z.string(),
- accountId: z.string(),
- accountName: z.string(),
- resourceId: z.string(),
- resourceName: z.string(),
- resourceType: z.string(),
- intervalSeconds: z.number(),
- nextRotationAt: z.date()
- })
- )
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId, month, year } = req.query;
- const result = await server.services.pamInsights.getRotationCalendar(projectId, month, year, req.permission);
- await server.services.auditLog.createAuditLog({
- projectId,
- event: {
- type: EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR,
- metadata: { projectId, month, year }
- },
- ...req.auditLogInfo
- });
- return result;
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-recording-config-router.ts b/backend/src/ee/routes/v1/pam-recording-config-router.ts
deleted file mode 100644
index 21924e8ea9..0000000000
--- a/backend/src/ee/routes/v1/pam-recording-config-router.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import RE2 from "re2";
-import { z } from "zod";
-
-import { PamProjectRecordingConfigsSchema } from "@app/db/schemas";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";
-import { TPamRecordingResolvedConfig } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-types";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-const StorageBackendEnum = z.nativeEnum(PamRecordingStorageBackend);
-
-const SanitizedConfigSchema = PamProjectRecordingConfigsSchema.pick({
- id: true,
- projectId: true,
- storageBackend: true,
- connectionId: true,
- bucket: true,
- region: true,
- keyPrefix: true,
- createdAt: true,
- updatedAt: true
-});
-
-const UpsertBodySchema = z.object({
- storageBackend: StorageBackendEnum,
- connectionId: z.string().uuid(),
- bucket: z.string().trim().min(1).max(255),
- region: z.nativeEnum(AWSRegion),
- keyPrefix: z
- .string()
- .trim()
- .max(255)
- .regex(
- new RE2(/^[a-zA-Z0-9\-_/]+$/),
- "Key prefix may only contain letters, numbers, hyphens, underscores, and slashes"
- )
- .nullable()
- .optional()
-});
-
-export const registerPamRecordingConfigRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/projects/:projectId/recording-config",
- config: { rateLimit: readLimit },
- schema: {
- params: z.object({ projectId: z.string().uuid() }),
- response: {
- 200: z.object({
- config: SanitizedConfigSchema.nullable()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { config } = await server.services.pamProjectRecordingConfig.getConfig(
- { projectId: req.params.projectId },
- req.permission
- );
- return { config };
- }
- });
-
- server.route({
- method: "POST",
- url: "/projects/:projectId/recording-config",
- config: { rateLimit: writeLimit },
- schema: {
- params: z.object({ projectId: z.string().uuid() }),
- body: UpsertBodySchema,
- response: {
- 200: z.object({ config: SanitizedConfigSchema, corsProbeUrl: z.string().nullable() })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const upsertInput = { projectId: req.params.projectId, ...req.body };
-
- let resolvedConfig: TPamRecordingResolvedConfig | undefined;
- try {
- ({ resolvedConfig } = await server.services.pamProjectRecordingConfig.testConfig(upsertInput, req.permission));
- } catch (err) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.projectId,
- event: {
- type: EventType.PAM_RECORDING_BUCKET_CONNECTION_TEST_FAILED,
- metadata: {
- projectId: req.params.projectId,
- storageBackend: req.body.storageBackend,
- bucket: req.body.bucket,
- region: req.body.region,
- reason: (err as Error)?.message ?? "unknown"
- }
- }
- });
- throw err;
- }
-
- const { config, corsProbeUrl } = await server.services.pamProjectRecordingConfig.upsertConfig(
- upsertInput,
- req.permission,
- resolvedConfig
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.projectId,
- event: {
- type: EventType.PAM_RECORDING_CONFIG_UPDATE,
- metadata: {
- projectId: req.params.projectId,
- storageBackend: req.body.storageBackend,
- bucket: req.body.bucket,
- region: req.body.region
- }
- }
- });
-
- return { config, corsProbeUrl };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/projects/:projectId/recording-config",
- config: { rateLimit: writeLimit },
- schema: {
- params: z.object({ projectId: z.string().uuid() }),
- response: { 200: z.object({ ok: z.literal(true) }) }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const result = await server.services.pamProjectRecordingConfig.deleteConfig(
- { projectId: req.params.projectId },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.projectId,
- event: {
- type: EventType.PAM_RECORDING_CONFIG_DELETE,
- metadata: { projectId: req.params.projectId }
- }
- });
-
- return result;
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-resource-routers/index.ts b/backend/src/ee/routes/v1/pam-resource-routers/index.ts
deleted file mode 100644
index 045197dc49..0000000000
--- a/backend/src/ee/routes/v1/pam-resource-routers/index.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import {
- CreateAwsIamResourceSchema,
- SanitizedAwsIamResourceSchema,
- UpdateAwsIamResourceSchema
-} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
-import {
- CreateKubernetesResourceSchema,
- SanitizedKubernetesResourceSchema,
- UpdateKubernetesResourceSchema
-} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import {
- CreateMongoDBResourceSchema,
- SanitizedMongoDBResourceSchema,
- UpdateMongoDBResourceSchema
-} from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";
-import {
- CreateMsSQLResourceSchema,
- MsSQLResourceSchema,
- UpdateMsSQLResourceSchema
-} from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import {
- CreateMySQLResourceSchema,
- MySQLResourceSchema,
- UpdateMySQLResourceSchema
-} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
-import {
- CreateOracleResourceSchema,
- OracleResourceSchema,
- UpdateOracleResourceSchema
-} from "@app/ee/services/pam-resource/oracle/oracle-resource-schemas";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import {
- CreatePostgresResourceSchema,
- SanitizedPostgresResourceSchema,
- UpdatePostgresResourceSchema
-} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import {
- CreateRedisResourceSchema,
- SanitizedRedisResourceSchema,
- UpdateRedisResourceSchema
-} from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import {
- CreateSSHResourceSchema,
- SanitizedSSHResourceSchema,
- UpdateSSHResourceSchema
-} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import {
- CreateWindowsResourceSchema,
- SanitizedWindowsResourceSchema,
- UpdateWindowsResourceSchema
-} from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-
-import {
- registerPamResourceEndpoints,
- registerSshCaPublicKeyEndpoint,
- registerSshCaSetupEndpoint
-} from "./pam-resource-endpoints";
-
-export const PAM_RESOURCE_REGISTER_ROUTER_MAP: Record<PamResource, (server: FastifyZodProvider) => Promise<void>> = {
- [PamResource.Postgres]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.Postgres,
- resourceResponseSchema: SanitizedPostgresResourceSchema,
- createResourceSchema: CreatePostgresResourceSchema,
- updateResourceSchema: UpdatePostgresResourceSchema
- });
- },
- [PamResource.MySQL]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.MySQL,
- resourceResponseSchema: MySQLResourceSchema,
- createResourceSchema: CreateMySQLResourceSchema,
- updateResourceSchema: UpdateMySQLResourceSchema
- });
- },
- [PamResource.MsSQL]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.MsSQL,
- resourceResponseSchema: MsSQLResourceSchema,
- createResourceSchema: CreateMsSQLResourceSchema,
- updateResourceSchema: UpdateMsSQLResourceSchema
- });
- },
- [PamResource.SSH]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.SSH,
- resourceResponseSchema: SanitizedSSHResourceSchema,
- createResourceSchema: CreateSSHResourceSchema,
- updateResourceSchema: UpdateSSHResourceSchema
- });
- registerSshCaPublicKeyEndpoint(server);
- registerSshCaSetupEndpoint(server);
- },
- [PamResource.Kubernetes]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.Kubernetes,
- resourceResponseSchema: SanitizedKubernetesResourceSchema,
- createResourceSchema: CreateKubernetesResourceSchema,
- updateResourceSchema: UpdateKubernetesResourceSchema
- });
- },
- [PamResource.AwsIam]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.AwsIam,
- resourceResponseSchema: SanitizedAwsIamResourceSchema,
- createResourceSchema: CreateAwsIamResourceSchema,
- updateResourceSchema: UpdateAwsIamResourceSchema
- });
- },
- [PamResource.Redis]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.Redis,
- resourceResponseSchema: SanitizedRedisResourceSchema,
- createResourceSchema: CreateRedisResourceSchema,
- updateResourceSchema: UpdateRedisResourceSchema
- });
- },
- [PamResource.MongoDB]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.MongoDB,
- resourceResponseSchema: SanitizedMongoDBResourceSchema,
- createResourceSchema: CreateMongoDBResourceSchema,
- updateResourceSchema: UpdateMongoDBResourceSchema
- });
- },
- [PamResource.Windows]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.Windows,
- resourceResponseSchema: SanitizedWindowsResourceSchema,
- createResourceSchema: CreateWindowsResourceSchema,
- updateResourceSchema: UpdateWindowsResourceSchema
- });
- },
- [PamResource.OracleDB]: async (server: FastifyZodProvider) => {
- registerPamResourceEndpoints({
- server,
- resourceType: PamResource.OracleDB,
- resourceResponseSchema: OracleResourceSchema,
- createResourceSchema: CreateOracleResourceSchema,
- updateResourceSchema: UpdateOracleResourceSchema
- });
- }
-};
diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts
deleted file mode 100644
index 5cf77cae9f..0000000000
--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts
+++ /dev/null
@@ -1,363 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { TPamResource } from "@app/ee/services/pam-resource/pam-resource-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 { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-
-export const registerPamResourceEndpoints = <T extends TPamResource>({
- server,
- resourceType,
- createResourceSchema,
- updateResourceSchema,
- resourceResponseSchema
-}: {
- server: FastifyZodProvider;
- resourceType: PamResource;
- createResourceSchema: z.ZodType<{
- projectId: T["projectId"];
- connectionDetails: T["connectionDetails"];
- gatewayId?: T["gatewayId"];
- gatewayPoolId?: string;
- name: T["name"];
- rotationAccountCredentials?: T["rotationAccountCredentials"];
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- }>;
- updateResourceSchema: z.ZodType<{
- connectionDetails?: T["connectionDetails"];
- gatewayId?: T["gatewayId"];
- gatewayPoolId?: string;
- name?: T["name"];
- rotationAccountCredentials?: T["rotationAccountCredentials"];
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- }>;
- resourceResponseSchema: z.ZodTypeAny;
-}) => {
- // Convert resource type enum value to PascalCase for operation IDs
- // e.g., "postgres" -> "Postgres", "aws-iam" -> "AwsIam"
- const resourceTypeId = resourceType
- .split("-")
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
- .join("");
- server.route({
- method: "GET",
- url: "/:resourceId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: `get${resourceTypeId}PamResource`,
- description: "Get PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- resource: resourceResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const resource = await server.services.pamResource.getById(req.params.resourceId, resourceType, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_GET,
- metadata: {
- resourceId: resource.id,
- resourceType: resource.resourceType,
- name: resource.name
- }
- }
- });
-
- return { resource };
- }
- });
-
- server.route({
- method: "POST",
- url: "/",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `create${resourceTypeId}PamResource`,
- description: "Create PAM resource",
- body: createResourceSchema,
- response: {
- 200: z.object({
- resource: resourceResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const resource = await server.services.pamResource.create(
- {
- ...req.body,
- resourceType
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.body.projectId,
- event: {
- type: EventType.PAM_RESOURCE_CREATE,
- metadata: {
- resourceType,
- ...(req.body.gatewayId && { gatewayId: req.body.gatewayId }),
- name: req.body.name
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamResourceCreated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType,
- projectId: req.body.projectId
- }
- })
- .catch(() => {});
-
- return { resource };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:resourceId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `update${resourceTypeId}PamResource`,
- description: "Update PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- body: updateResourceSchema,
- response: {
- 200: z.object({
- resource: resourceResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const resource = await server.services.pamResource.updateById(
- {
- ...req.body,
- resourceId: req.params.resourceId
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_UPDATE,
- metadata: {
- resourceId: req.params.resourceId,
- resourceType,
- ...(req.body.gatewayId && { gatewayId: req.body.gatewayId }),
- ...(req.body.name && { name: req.body.name })
- }
- }
- });
-
- return { resource };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:resourceId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: `delete${resourceTypeId}PamResource`,
- description: "Delete PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- resource: resourceResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const resource = await server.services.pamResource.deleteById(req.params.resourceId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_DELETE,
- metadata: {
- resourceId: req.params.resourceId,
- resourceType
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamResourceDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType,
- projectId: resource.projectId
- }
- })
- .catch(() => {});
-
- return { resource };
- }
- });
-};
-
-export const registerSshCaPublicKeyEndpoint = (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:resourceId/ssh-ca-public-key",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "getSshPamResourceCaPublicKey",
- description: "Get the SSH CA public key for the PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.string()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req, reply) => {
- const { caPublicKey } = await server.services.pamResource.getOrCreateSshCa(req.params.resourceId, req.permission);
-
- void reply.header("Content-Type", "text/plain; charset=utf-8");
- return caPublicKey;
- }
- });
-};
-
-export const registerSshCaSetupEndpoint = (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:resourceId/ssh-ca-setup",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "getSshPamResourceCaSetup",
- description: "Get PAM resource SSH CA setup script for configuring the target server to trust the CA",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.string()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req, reply) => {
- const { caPublicKey } = await server.services.pamResource.getOrCreateSshCa(req.params.resourceId, req.permission);
-
- const setupScript = `#!/bin/bash
-set -e
-
-CA_PUBLIC_KEY="${caPublicKey}"
-CA_FILE="/etc/ssh/infisical_ca.pub"
-SSHD_CONFIG="/etc/ssh/sshd_config"
-
-echo "==> Infisical SSH CA Setup"
-echo ""
-
-if [ "$(id -u)" -ne 0 ]; then
- echo "Error: This script must be run as root (use sudo)"
- exit 1
-fi
-
-echo "==> Writing CA public key to \${CA_FILE}..."
-echo "\${CA_PUBLIC_KEY}" > "\${CA_FILE}"
-chmod 644 "\${CA_FILE}"
-echo " Done."
-
-if grep -q "^TrustedUserCAKeys" "\${SSHD_CONFIG}"; then
- EXISTING_CA_FILE=$(grep "^TrustedUserCAKeys" "\${SSHD_CONFIG}" | awk '{print $2}')
- if [ "\${EXISTING_CA_FILE}" = "\${CA_FILE}" ]; then
- echo "==> TrustedUserCAKeys already configured for \${CA_FILE}"
- else
- echo "Warning: TrustedUserCAKeys is already set to \${EXISTING_CA_FILE}"
- echo " You may need to manually update sshd_config to use \${CA_FILE}"
- echo " or combine multiple CA keys into a single file."
- fi
-else
- echo "==> Adding TrustedUserCAKeys to \${SSHD_CONFIG}..."
- echo "" >> "\${SSHD_CONFIG}"
- echo "# Infisical SSH CA - Added by setup script" >> "\${SSHD_CONFIG}"
- echo "TrustedUserCAKeys \${CA_FILE}" >> "\${SSHD_CONFIG}"
- echo " Done."
-fi
-
-echo "==> Validating SSH configuration..."
-if sshd -t; then
- echo " Configuration is valid."
-else
- echo "Error: SSH configuration is invalid. Please check \${SSHD_CONFIG}"
- exit 1
-fi
-
-echo "==> Restarting SSH service..."
-if command -v systemctl &> /dev/null; then
- if systemctl cat sshd.service &>/dev/null; then
- systemctl restart sshd
- elif systemctl cat ssh.service &>/dev/null; then
- systemctl restart ssh
- else
- echo "Warning: Could not find SSH service. Please restart it manually."
- fi
-elif command -v service &> /dev/null; then
- service sshd restart 2>/dev/null || service ssh restart
-else
- echo "Warning: Could not detect init system. Please restart sshd manually."
-fi
-echo " Done."
-
-echo ""
-echo "==> Setup complete!"
-echo ""
-echo "Your SSH server is now configured to trust certificates signed by the Infisical CA."
-echo ""
-`;
-
- void reply.header("Content-Type", "text/plain; charset=utf-8");
- return setupScript;
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.ts
deleted file mode 100644
index 6e2f1bf9f5..0000000000
--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-rotation-rules-router.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import { z } from "zod";
-
-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 RotationRuleResponseSchema = z.object({
- id: z.string().uuid(),
- resourceId: z.string().uuid(),
- name: z.string().nullable().optional(),
- namePattern: z.string(),
- enabled: z.boolean(),
- intervalSeconds: z.number().nullable().optional(),
- priority: z.number(),
- createdAt: z.date(),
- updatedAt: z.date()
-});
-
-export const registerPamResourceRotationRulesRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:resourceId/rotation-rules",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "listPamRotationRules",
- description: "List rotation rules for a PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- rules: RotationRuleResponseSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resourceId } = req.params;
-
- const { rules, resource } = await server.services.pamResourceRotationRules.listByResourceId(
- resourceId,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_LIST,
- metadata: {
- resourceId,
- resourceName: resource.name,
- count: rules.length
- }
- }
- });
-
- return { rules };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:resourceId/rotation-rules",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "createPamRotationRule",
- description: "Create a rotation rule for a PAM resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- body: z.object({
- name: z.string().max(255).optional(),
- namePattern: z.string().min(1).max(255),
- enabled: z.boolean().default(true),
- intervalSeconds: z.number().min(3600).nullable().optional()
- }),
- response: {
- 200: z.object({
- rule: RotationRuleResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resourceId } = req.params;
-
- const { rule, resource } = await server.services.pamResourceRotationRules.create(
- {
- resourceId,
- ...req.body
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_CREATE,
- metadata: {
- resourceId,
- resourceName: resource.name,
- ruleId: rule.id,
- ruleName: rule.name ?? undefined,
- namePattern: rule.namePattern,
- enabled: rule.enabled,
- intervalSeconds: rule.intervalSeconds
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamRotationRuleCreated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType: resource.resourceType,
- projectId: resource.projectId,
- enabled: rule.enabled,
- hasSchedule: Boolean(rule.intervalSeconds)
- }
- })
- .catch(() => {});
-
- return { rule };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:resourceId/rotation-rules/:ruleId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "updatePamRotationRule",
- description: "Update a rotation rule",
- params: z.object({
- resourceId: z.string().uuid(),
- ruleId: z.string().uuid()
- }),
- body: z.object({
- name: z.string().max(255).nullable().optional(),
- namePattern: z.string().min(1).max(255).optional(),
- enabled: z.boolean().optional(),
- intervalSeconds: z.number().min(3600).nullable().optional()
- }),
- response: {
- 200: z.object({
- rule: RotationRuleResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resourceId, ruleId } = req.params;
-
- const { rule, resource } = await server.services.pamResourceRotationRules.updateById(
- resourceId,
- ruleId,
- req.body,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_UPDATE,
- metadata: {
- resourceId,
- resourceName: resource.name,
- ruleId,
- ruleName: req.body.name,
- namePattern: req.body.namePattern,
- enabled: req.body.enabled,
- intervalSeconds: req.body.intervalSeconds
- }
- }
- });
-
- return { rule };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:resourceId/rotation-rules/:ruleId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "deletePamRotationRule",
- description: "Delete a rotation rule",
- params: z.object({
- resourceId: z.string().uuid(),
- ruleId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- rule: RotationRuleResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resourceId, ruleId } = req.params;
-
- const { rule, resource } = await server.services.pamResourceRotationRules.deleteById(
- resourceId,
- ruleId,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_DELETE,
- metadata: {
- resourceId,
- resourceName: resource.name,
- ruleId,
- ruleName: rule.name,
- namePattern: rule.namePattern
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamRotationRuleDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType: resource.resourceType,
- projectId: resource.projectId
- }
- })
- .catch(() => {});
-
- return { rule };
- }
- });
-
- server.route({
- method: "PUT",
- url: "/:resourceId/rotation-rules/reorder",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- operationId: "reorderPamRotationRules",
- description: "Reorder rotation rules for a resource",
- params: z.object({
- resourceId: z.string().uuid()
- }),
- body: z.object({
- ruleIds: z.array(z.string().uuid())
- }),
- response: {
- 200: z.object({
- rules: RotationRuleResponseSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { resourceId } = req.params;
- const { ruleIds } = req.body;
-
- const { rules, resource } = await server.services.pamResourceRotationRules.reorderRules(
- resourceId,
- ruleIds,
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: resource.projectId,
- event: {
- type: EventType.PAM_RESOURCE_ROTATION_RULE_REORDER,
- metadata: {
- resourceId,
- resourceName: resource.name,
- ruleIds
- }
- }
- });
-
- return { rules };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts
deleted file mode 100644
index b345458a24..0000000000
--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-import { z } from "zod";
-
-import { PamAccountDependenciesSchema } from "@app/db/schemas";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import {
- AwsIamResourceListItemSchema,
- SanitizedAwsIamResourceSchema
-} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
-import {
- KubernetesResourceListItemSchema,
- SanitizedKubernetesResourceSchema
-} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import {
- MongoDBResourceListItemSchema,
- SanitizedMongoDBResourceSchema
-} from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";
-import {
- MsSQLResourceListItemSchema,
- SanitizedMsSQLResourceSchema
-} from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import {
- MySQLResourceListItemSchema,
- SanitizedMySQLResourceSchema
-} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
-import {
- OracleResourceListItemSchema,
- SanitizedOracleResourceSchema
-} from "@app/ee/services/pam-resource/oracle/oracle-resource-schemas";
-import { PamResource, PamResourceOrderBy } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { PAM_AI_INSIGHT_MODELS } from "@app/ee/services/pam-resource/pam-resource-schemas";
-import {
- PostgresResourceListItemSchema,
- SanitizedPostgresResourceSchema
-} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import {
- RedisResourceListItemSchema,
- SanitizedRedisResourceSchema
-} from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import {
- SanitizedSSHResourceSchema,
- SSHResourceListItemSchema
-} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import {
- SanitizedWindowsResourceSchema,
- WindowsResourceListItemSchema
-} from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-import { OrderByDirection } from "@app/lib/types";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-const SanitizedResourceSchema = z.discriminatedUnion("resourceType", [
- SanitizedPostgresResourceSchema,
- SanitizedMySQLResourceSchema,
- SanitizedMsSQLResourceSchema,
- SanitizedSSHResourceSchema,
- SanitizedKubernetesResourceSchema,
- SanitizedAwsIamResourceSchema,
- SanitizedMongoDBResourceSchema,
- SanitizedRedisResourceSchema,
- SanitizedWindowsResourceSchema,
- SanitizedOracleResourceSchema
-]);
-
-const SanitizedResourceWithFavoriteSchema = z.intersection(
- SanitizedResourceSchema,
- z.object({ isFavorite: z.boolean().default(false) })
-);
-
-const ResourceOptionsSchema = z.discriminatedUnion("resource", [
- PostgresResourceListItemSchema,
- MySQLResourceListItemSchema,
- MsSQLResourceListItemSchema,
- SSHResourceListItemSchema,
- KubernetesResourceListItemSchema,
- AwsIamResourceListItemSchema,
- MongoDBResourceListItemSchema,
- RedisResourceListItemSchema,
- WindowsResourceListItemSchema,
- OracleResourceListItemSchema
-]);
-
-export const registerPamResourceRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/ai-insights/models",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List available AI models for PAM session insights, grouped by app connection type",
- response: {
- 200: z.object({
- models: z
- .object({
- connectionApp: z.string(),
- id: z.string(),
- label: z.string()
- })
- .array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: () => {
- return { models: PAM_AI_INSIGHT_MODELS };
- }
- });
-
- server.route({
- method: "GET",
- url: "/options",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM resource types",
- response: {
- 200: z.object({
- resourceOptions: ResourceOptionsSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: () => {
- const resourceOptions = server.services.pamResource.listResourceOptions();
-
- return { resourceOptions };
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM resources",
- querystring: z.object({
- projectId: z.string().uuid(),
- offset: z.coerce.number().min(0).default(0),
- limit: z.coerce.number().min(1).max(100).default(100),
- orderBy: z.nativeEnum(PamResourceOrderBy).default(PamResourceOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- search: z.string().trim().optional(),
- filterResourceTypes: z
- .string()
- .transform((val) =>
- val
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean)
- )
- .optional()
- }),
- response: {
- 200: z.object({
- resources: SanitizedResourceWithFavoriteSchema.array(),
- totalCount: z.number().default(0)
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId, limit, offset, search, orderBy, orderDirection, filterResourceTypes } = req.query;
-
- const { resources, totalCount } = await server.services.pamResource.list({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId,
- limit,
- offset,
- search,
- orderBy,
- orderDirection,
- filterResourceTypes
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.query.projectId,
- event: {
- type: EventType.PAM_RESOURCE_LIST,
- metadata: {
- count: resources.length
- }
- }
- });
-
- return { resources, totalCount };
- }
- });
-
- server.route({
- method: "POST",
- url: "/search",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Search PAM resources",
- body: z.object({
- projectId: z.string().uuid(),
- offset: z.number().min(0).default(0),
- limit: z.number().min(1).max(100).default(100),
- orderBy: z.nativeEnum(PamResourceOrderBy).default(PamResourceOrderBy.Name),
- orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
- search: z.string().trim().optional(),
- filterResourceTypes: z.array(z.string()).optional(),
- metadata: z
- .array(
- z.object({
- key: z.string().trim().min(1).max(255),
- value: z.string().trim().max(1020).optional()
- })
- )
- .optional()
- }),
- response: {
- 200: z.object({
- resources: SanitizedResourceWithFavoriteSchema.array(),
- totalCount: z.number().default(0)
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId, limit, offset, search, orderBy, orderDirection, filterResourceTypes, metadata } = req.body;
-
- const { resources, totalCount } = await server.services.pamResource.list({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId,
- limit,
- offset,
- search,
- orderBy,
- orderDirection,
- filterResourceTypes,
- metadataFilter: metadata
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_RESOURCE_LIST,
- metadata: {
- count: resources.length
- }
- }
- });
-
- return { resources, totalCount };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:resourceType/:resourceId/dependencies",
- config: {
- rateLimit: readLimit
- },
- schema: {
- operationId: "getPamResourceDependencies",
- description: "List dependencies that run on this resource",
- params: z.object({
- resourceType: z.nativeEnum(PamResource),
- resourceId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- dependencies: PamAccountDependenciesSchema.extend({
- accountName: z.string().nullable(),
- lastSyncMessage: z.string().nullable().optional()
- }).array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const dependencies = await server.services.pamDiscoverySource.getResourceDependencies({
- resourceId: req.params.resourceId,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- return { dependencies };
- }
- });
-
- server.route({
- method: "PUT",
- url: "/favorites",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Set a PAM resource favorite status",
- body: z.object({
- projectId: z.string().uuid(),
- resourceId: z.string().uuid(),
- isFavorite: z.boolean()
- }),
- response: {
- 200: z.object({
- message: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId, resourceId, isFavorite } = req.body;
-
- await server.services.pamResource.setUserResourceFavorite({
- projectId,
- resourceId,
- isFavorite,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
-
- return { message: isFavorite ? "Resource added to favorites" : "Resource removed from favorites" };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-session-chunk-router.ts b/backend/src/ee/routes/v1/pam-session-chunk-router.ts
deleted file mode 100644
index 527eb5d744..0000000000
--- a/backend/src/ee/routes/v1/pam-session-chunk-router.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums";
-import { BadRequestError } from "@app/lib/errors";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-const GATEWAY_TOKEN_HEADER = "x-gateway-upload-token";
-
-const ChunkPlaybackSchema = z.object({
- chunkIndex: z.number().int().nonnegative().max(999999),
- startElapsedMs: z.number(),
- endElapsedMs: z.number(),
- storageBackend: z.nativeEnum(PamRecordingStorageBackend),
- externalChunkObjectKey: z.string().nullable(),
- ciphertextSha256: z.string(),
- ciphertextBytes: z.number(),
- iv: z.string(),
- presignedGetUrl: z.string().nullable()
-});
-
-export const registerPamSessionChunkRouter = async (server: FastifyZodProvider) => {
- // Mint a presigned PUT URL for a single chunk. Gateway-authenticated
- server.route({
- method: "POST",
- url: "/:sessionId/chunks/presigned-put",
- config: { rateLimit: writeLimit },
- schema: {
- description: "Mint a presigned PUT URL for a session recording chunk (gateway only)",
- params: z.object({ sessionId: z.string().uuid() }),
- body: z.object({
- chunkIndex: z.number().int().nonnegative().max(999999),
- ciphertextBytes: z.number().int().positive(),
- isKeyframe: z.boolean().optional()
- }),
- response: {
- 200: z.object({
- url: z.string(),
- objectKey: z.string(),
- method: z.literal("PUT"),
- expiresInSeconds: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];
- if (typeof uploadToken !== "string" || !uploadToken) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
- metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }
- }
- });
- throw new BadRequestError({
- message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`
- });
- }
-
- try {
- return await server.services.pamSessionChunk.requestPresignedPut(
- {
- sessionId: req.params.sessionId,
- chunkIndex: req.body.chunkIndex,
- ciphertextBytes: req.body.ciphertextBytes,
- isKeyframe: req.body.isKeyframe,
- uploadToken
- },
- req.permission
- );
- } catch (err) {
- const msg = (err as Error)?.message ?? "";
- if (msg.includes("Invalid upload token")) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
- metadata: { sessionId: req.params.sessionId, chunkIndex: req.body.chunkIndex }
- }
- });
- }
- throw err;
- }
- }
- });
-
- // Submit chunk metadata after the gateway has uploaded ciphertext to S3,
- // OR (for Postgres backend) submit ciphertext + metadata in one call
- server.route({
- method: "POST",
- url: "/:sessionId/chunks",
- config: { rateLimit: writeLimit },
- schema: {
- description: "Record chunk metadata after upload, or upload ciphertext for Postgres backend",
- params: z.object({ sessionId: z.string().uuid() }),
- body: z.object({
- chunkIndex: z.number().int().nonnegative().max(999999),
- startElapsedMs: z.number(),
- endElapsedMs: z.number(),
- ciphertextSha256: z.string(),
- ciphertextBytes: z.number().int().positive(),
- iv: z.string(),
- keyframeObjectKey: z.string().nullable().optional(),
- keyframeSizeBytes: z.number().int().nonnegative().nullable().optional(),
-
- // Base64 inline ciphertext for Postgres backend
- ciphertext: z.string().optional()
- }),
- response: {
- 200: z.object({
- ok: z.literal(true),
- storageBackend: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const uploadToken = req.headers[GATEWAY_TOKEN_HEADER];
- if (typeof uploadToken !== "string" || !uploadToken) {
- throw new BadRequestError({
- message: `Missing ${GATEWAY_TOKEN_HEADER} header: required for chunk upload`
- });
- }
-
- let ciphertextBuf: Buffer | undefined;
- if (req.body.ciphertext) {
- const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
- if (!BASE64_RE.test(req.body.ciphertext)) {
- throw new BadRequestError({ message: "ciphertext must be valid base64" });
- }
- ciphertextBuf = Buffer.from(req.body.ciphertext, "base64");
- }
-
- const result = await server.services.pamSessionChunk.recordChunk(
- {
- sessionId: req.params.sessionId,
- chunkIndex: req.body.chunkIndex,
- startElapsedMs: req.body.startElapsedMs,
- endElapsedMs: req.body.endElapsedMs,
- ciphertextSha256Base64: req.body.ciphertextSha256,
- ciphertextBytes: req.body.ciphertextBytes,
- ivBase64: req.body.iv,
- keyframeObjectKey: req.body.keyframeObjectKey ?? undefined,
- keyframeSizeBytes: req.body.keyframeSizeBytes ?? undefined,
- ciphertext: ciphertextBuf,
- uploadToken
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: result.projectId,
- event: {
- type: EventType.PAM_SESSION_CHUNK_UPLOAD,
- metadata: {
- sessionId: req.params.sessionId,
- chunkIndex: req.body.chunkIndex,
- storageBackend: result.storageBackend,
- ciphertextBytes: req.body.ciphertextBytes
- }
- }
- });
-
- return { ok: true as const, storageBackend: result.storageBackend };
- }
- });
-
- // User-facing playback endpoint: returns the unwrapped session key, chunk metadata, and presigned GET URLs
- // For Postgres-backed chunks, the frontend instead calls /:sessionId/chunks/:chunkIndex/ciphertext to fetch bytes
- server.route({
- method: "GET",
- url: "/:sessionId/playback",
- config: { rateLimit: readLimit },
- schema: {
- description: "Get playback bundle: session key + chunk metadata + presigned GET URLs",
- params: z.object({ sessionId: z.string().uuid() }),
- response: {
- 200: z.object({
- legacy: z.boolean(),
- sessionComplete: z.boolean(),
- sessionKey: z.string().nullable(),
- projectId: z.string().optional(),
- storageBackend: z.string().optional(),
- chunks: z.array(ChunkPlaybackSchema)
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const result = await server.services.pamSessionChunk.getPlaybackBundle(req.params.sessionId, req.permission);
- if (result.legacy) {
- return { legacy: true, sessionComplete: result.sessionComplete, sessionKey: null, chunks: [] };
- }
- return {
- legacy: false,
- sessionComplete: result.sessionComplete,
- sessionKey: result.sessionKey,
- projectId: result.projectId,
- storageBackend: result.storageBackend,
- chunks: result.chunks
- };
- }
- });
-
- // Postgres-backed chunk ciphertext fetch (since there's no presigned GET URL for inline blobs)
- // Returns raw ciphertext bytes for the browser to verify + decrypt
- server.route({
- method: "GET",
- url: "/:sessionId/chunks/:chunkIndex/ciphertext",
- config: { rateLimit: readLimit },
- schema: {
- params: z.object({
- sessionId: z.string().uuid(),
- chunkIndex: z.coerce.number().int().nonnegative().max(999999)
- })
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req, reply) => {
- const { ciphertext } = await server.services.pamSessionChunk.getChunkCiphertext(
- req.params.sessionId,
- req.params.chunkIndex,
- req.permission
- );
- void reply.header("Content-Type", "application/octet-stream");
- void reply.header("Cache-Control", "no-store");
- return reply.send(ciphertext);
- }
- });
-
- // Storage backend constants exposed to the gateway for sanity checks (read-only)
- server.route({
- method: "GET",
- url: "/recording-storage-backends",
- config: { rateLimit: readLimit },
- schema: {
- response: {
- 200: z.object({
- backends: z.array(z.string())
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async () => ({
- backends: Object.values(PamRecordingStorageBackend)
- })
- });
-};
diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts
deleted file mode 100644
index 98de9caafb..0000000000
--- a/backend/src/ee/routes/v1/pam-session-router.ts
+++ /dev/null
@@ -1,456 +0,0 @@
-import { z } from "zod";
-
-import { PamSessionsSchema } from "@app/db/schemas";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PolicyRulesResponseSchema } from "@app/ee/services/pam-account-policy";
-import { KubernetesSessionCredentialsSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import { MongoDBSessionCredentialsSchema } from "@app/ee/services/pam-resource/mongodb/mongodb-resource-schemas";
-import { MsSQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import { MySQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
-import { OracleSessionCredentialsSchema } from "@app/ee/services/pam-resource/oracle/oracle-resource-schemas";
-import { PostgresSessionCredentialsSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import { RedisSessionCredentialsSchema } from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import { SSHSessionCredentialsSchema } from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import { WindowsSessionCredentialsSchema } from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
-import {
- HttpEventSchema,
- PamSessionCommandLogSchema,
- SanitizedSessionListItemSchema,
- SanitizedSessionSchema,
- SessionEventSchema,
- SessionLogsPageSchema
-} from "@app/ee/services/pam-session/pam-session-schemas";
-import { BadRequestError } from "@app/lib/errors";
-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";
-
-// Schemas with distinguishing fields must precede simpler ones — Zod strips unrecognized keys on first match.
-const SessionCredentialsSchema = z.union([
- MsSQLSessionCredentialsSchema,
- SSHSessionCredentialsSchema,
- WindowsSessionCredentialsSchema,
- KubernetesSessionCredentialsSchema,
- MongoDBSessionCredentialsSchema,
- PostgresSessionCredentialsSchema,
- MySQLSessionCredentialsSchema,
- OracleSessionCredentialsSchema,
- RedisSessionCredentialsSchema
-]);
-
-export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
- server.addContentTypeParser("application/octet-stream", { parseAs: "buffer" }, (_req, body, done) => {
- done(null, body);
- });
-
- // Meant to be hit solely by gateway identities
- server.route({
- method: "GET",
- url: "/:sessionId/credentials",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get PAM session credentials and start session",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- credentials: SessionCredentialsSchema,
- policyRules: PolicyRulesResponseSchema,
- recording: z
- .object({
- sessionKey: z.string(),
- uploadToken: z.string(),
- storageBackend: z.string(),
- projectId: z.string(),
- sessionId: z.string()
- })
- .nullable()
- .optional()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { credentials, policyRules, projectId, account, sessionStarted, recording } =
- await server.services.pamAccount.getSessionCredentials(req.params.sessionId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_CREDENTIALS_GET,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: account.name
- }
- }
- });
-
- if (sessionStarted) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_START,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: account.name
- }
- }
- });
-
- await server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamSessionStarted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- projectId
- }
- })
- .catch(() => {});
- }
-
- return {
- credentials: credentials as z.infer<typeof SessionCredentialsSchema>,
- policyRules,
- recording: recording
- ? {
- sessionKey: recording.sessionKeyBase64,
- uploadToken: recording.uploadTokenBase64,
- storageBackend: recording.storageBackend,
- projectId,
- sessionId: req.params.sessionId
- }
- : null
- };
- }
- });
-
- // Meant to be hit solely by gateway identities
- server.route({
- method: "POST",
- url: "/:sessionId/logs",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Update PAM session logs",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- body: z.object({
- logs: z.array(z.union([PamSessionCommandLogSchema, SessionEventSchema, HttpEventSchema]))
- }),
- response: {
- 200: z.object({
- session: PamSessionsSchema.omit({
- encryptedLogsBlob: true
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { session, projectId } = await server.services.pamSession.updateLogsById(
- {
- sessionId: req.params.sessionId,
- logs: req.body.logs
- },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_LOGS_UPDATE,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: session.accountName
- }
- }
- });
-
- return { session };
- }
- });
-
- // Meant to be hit solely by gateway identities
- server.route({
- method: "POST",
- url: "/:sessionId/end",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "End PAM session",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- session: PamSessionsSchema.omit({
- encryptedLogsBlob: true
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { session, projectId, alreadyEnded } = await server.services.pamSession.endSessionById(
- req.params.sessionId,
- req.permission
- );
-
- if (!alreadyEnded) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_END,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: session.accountName
- }
- }
- });
- }
-
- return { session };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:sessionId/terminate",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Terminate an active PAM session",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- session: PamSessionsSchema.omit({
- encryptedLogsBlob: true
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { session, projectId, alreadyEnded } = await server.services.pamSession.terminateSessionById(
- req.params.sessionId,
- req.permission
- );
-
- if (!alreadyEnded) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_TERMINATE,
- metadata: {
- sessionId: req.params.sessionId,
- accountName: session.accountName
- }
- }
- });
-
- const durationMs =
- session.startedAt && session.endedAt
- ? new Date(session.endedAt).getTime() - new Date(session.startedAt).getTime()
- : undefined;
- void server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.PamSessionEnded,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- resourceType: session.resourceType,
- projectId,
- durationMs
- }
- })
- .catch(() => {});
- }
-
- return { session };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:sessionId/logs",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get paginated PAM session logs",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- querystring: z.object({
- offset: z.coerce.number().int().nonnegative().default(0),
- limit: z.coerce.number().int().min(1).max(100).default(20)
- }),
- response: {
- 200: SessionLogsPageSchema
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- return server.services.pamSession.getSessionLogs(
- req.params.sessionId,
- req.query.offset,
- req.query.limit,
- req.permission
- );
- }
- });
-
- server.route({
- method: "GET",
- url: "/:sessionId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Get PAM session",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- session: SanitizedSessionSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const response = await server.services.pamSession.getById(req.params.sessionId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: response.session.projectId,
- event: {
- type: EventType.PAM_SESSION_GET,
- metadata: {
- sessionId: req.params.sessionId
- }
- }
- });
-
- return response;
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "List PAM sessions",
- querystring: z.object({
- projectId: z.string().uuid()
- }),
- response: {
- 200: z.object({
- sessions: SanitizedSessionListItemSchema.array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const response = await server.services.pamSession.list(req.query.projectId, req.permission);
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.query.projectId,
- event: {
- type: EventType.PAM_SESSION_LIST,
- metadata: {
- count: response.sessions.length
- }
- }
- });
-
- return response;
- }
- });
-
- // Meant to be hit solely by gateway identities
- server.route({
- method: "POST",
- url: "/:sessionId/event-batches",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- description: "Upload a PAM session event batch",
- params: z.object({
- sessionId: z.string().uuid()
- }),
- querystring: z.object({
- startOffset: z.coerce.number().int().nonnegative()
- }),
- body: z.instanceof(Buffer),
- response: {
- 200: z.object({ ok: z.literal(true) })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),
- handler: async (req) => {
- const EventBatchSchema = z.array(z.union([PamSessionCommandLogSchema, SessionEventSchema, HttpEventSchema]));
- try {
- EventBatchSchema.parse(JSON.parse(req.body.toString()));
- } catch (e) {
- if (e instanceof SyntaxError) throw new BadRequestError({ message: "Invalid JSON in request body" });
- throw e;
- }
-
- const { projectId, wasInserted } = await server.services.pamSession.uploadEventBatch(
- {
- sessionId: req.params.sessionId,
- startOffset: req.query.startOffset,
- events: req.body
- },
- req.permission
- );
-
- if (wasInserted) {
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_EVENT_BATCH_UPLOAD,
- metadata: {
- sessionId: req.params.sessionId,
- startOffset: req.query.startOffset
- }
- }
- });
- }
-
- return { ok: true as const };
- }
- });
-};
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 3afa024d62..65e95647d1 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -216,24 +216,6 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
environmentSlug: z.string()
})
),
- pamResources: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- projectId: z.string(),
- projectName: z.string(),
- resourceType: z.string()
- })
- ),
- pamDiscoverySources: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- projectId: z.string(),
- projectName: z.string(),
- discoveryType: z.string()
- })
- ),
kubernetesAuths: z.array(
z.object({
id: z.string(),
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
index 072f643cc5..a78e6df260 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
@@ -13,9 +13,6 @@ import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";
import { TLicenseServiceFactory } from "../license/license-service";
-import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";
-import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
import { OrgPermissionGatewayPoolActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";
@@ -41,9 +38,6 @@ type TGatewayPoolServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
- pamDomainDAL: Pick<TPamDomainDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
- pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;
};
@@ -59,9 +53,6 @@ export const gatewayPoolServiceFactory = ({
licenseService,
identityKubernetesAuthDAL,
pkiDiscoveryConfigDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamDiscoverySourceDAL,
appConnectionDAL,
dynamicSecretDAL
}: TGatewayPoolServiceFactoryDep) => {
@@ -118,15 +109,7 @@ export const gatewayPoolServiceFactory = ({
if (pools.length === 0) return [];
// Add more DAL counts here as pool support expands to other consumers
- const [
- k8sAuthCounts,
- pkiDiscoveryCounts,
- pamDomainCounts,
- pamResourceCounts,
- pamDiscoverySourceCounts,
- appConnectionCounts,
- dynamicSecretCounts
- ] = await Promise.all([
+ const [k8sAuthCounts, pkiDiscoveryCounts, appConnectionCounts, dynamicSecretCounts] = await Promise.all([
Promise.all(
pools.map((pool) =>
identityKubernetesAuthDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))
@@ -137,17 +120,6 @@ export const gatewayPoolServiceFactory = ({
pkiDiscoveryConfigDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))
)
),
- Promise.all(
- pools.map((pool) => pamDomainDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))
- ),
- Promise.all(
- pools.map((pool) => pamResourceDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))
- ),
- Promise.all(
- pools.map((pool) =>
- pamDiscoverySourceDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))
- )
- ),
Promise.all(
pools.map((pool) => appConnectionDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))
),
@@ -160,9 +132,6 @@ export const gatewayPoolServiceFactory = ({
for (const { id, count } of [
...k8sAuthCounts,
...pkiDiscoveryCounts,
- ...pamDomainCounts,
- ...pamResourceCounts,
- ...pamDiscoverySourceCounts,
...appConnectionCounts,
...dynamicSecretCounts
]) {
@@ -379,20 +348,9 @@ export const gatewayPoolServiceFactory = ({
}
// Add more DAL calls here as pool support expands to other consumers
- const [
- kubernetesAuths,
- pkiDiscoveryConfigs,
- pamDomains,
- pamResources,
- pamDiscoverySources,
- appConnections,
- dynamicSecrets
- ] = await Promise.all([
+ const [kubernetesAuths, pkiDiscoveryConfigs, appConnections, dynamicSecrets] = await Promise.all([
identityKubernetesAuthDAL.findByGatewayPoolId(poolId),
pkiDiscoveryConfigDAL.findByGatewayPoolId(poolId),
- pamDomainDAL.findByGatewayPoolId(poolId),
- pamResourceDAL.findByGatewayPoolId(poolId),
- pamDiscoverySourceDAL.findByGatewayPoolId(poolId),
appConnectionDAL.findByGatewayPoolId(poolId),
dynamicSecretDAL.findByGatewayPoolId(poolId)
]);
@@ -400,9 +358,6 @@ export const gatewayPoolServiceFactory = ({
return {
kubernetesAuths,
pkiDiscoveryConfigs,
- pamDomains,
- pamResources,
- pamDiscoverySources,
appConnections,
dynamicSecrets
};
@@ -410,32 +365,13 @@ export const gatewayPoolServiceFactory = ({
const getConnectedResourcesCount = async (poolId: string): Promise<number> => {
// Add more DAL counts here as pool support expands to other consumers
- const [
- k8sAuthCount,
- pkiDiscoveryCount,
- pamDomainCount,
- pamResourceCount,
- pamDiscoverySourceCount,
- appConnectionCount,
- dynamicSecretCount
- ] = await Promise.all([
+ const [k8sAuthCount, pkiDiscoveryCount, appConnectionCount, dynamicSecretCount] = await Promise.all([
identityKubernetesAuthDAL.countByGatewayPoolId(poolId),
pkiDiscoveryConfigDAL.countByGatewayPoolId(poolId),
- pamDomainDAL.countByGatewayPoolId(poolId),
- pamResourceDAL.countByGatewayPoolId(poolId),
- pamDiscoverySourceDAL.countByGatewayPoolId(poolId),
appConnectionDAL.countByGatewayPoolId(poolId),
dynamicSecretDAL.countByGatewayPoolId(poolId)
]);
- return (
- k8sAuthCount +
- pkiDiscoveryCount +
- pamDomainCount +
- pamResourceCount +
- pamDiscoverySourceCount +
- appConnectionCount +
- dynamicSecretCount
- );
+ return k8sAuthCount + pkiDiscoveryCount + appConnectionCount + dynamicSecretCount;
};
return {
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 02c847f520..ae4f1c7bf8 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -31,8 +31,6 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";
import { TAiMcpServerDALFactory } from "../ai-mcp-server/ai-mcp-server-dal";
import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";
-import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
import { PamResource } from "../pam-resource/pam-resource-enums";
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
@@ -66,8 +64,6 @@ type TGatewayV2ServiceFactoryDep = {
smtpService: Pick<TSmtpService, "sendMail">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findByGatewayId" | "countByGatewayId">;
dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findByGatewayId" | "countByGatewayId">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findByGatewayId" | "countByGatewayId">;
- pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findByGatewayId" | "countByGatewayId">;
identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "findByGatewayId" | "countByGatewayId">;
aiMcpServerDAL: Pick<TAiMcpServerDALFactory, "findByGatewayId" | "countByGatewayId">;
pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "findByGatewayId" | "countByGatewayId">;
@@ -90,8 +86,6 @@ export const gatewayV2ServiceFactory = ({
notificationService,
appConnectionDAL,
dynamicSecretDAL,
- pamResourceDAL,
- pamDiscoverySourceDAL,
identityKubernetesAuthDAL,
aiMcpServerDAL,
pkiDiscoveryConfigDAL,
@@ -311,16 +305,12 @@ export const gatewayV2ServiceFactory = ({
const [
appConnectionsCounts,
dynamicSecretsCounts,
- pamResourcesCounts,
- pamDiscoverySourcesCounts,
kubernetesAuthsCounts,
mcpServersCounts,
pkiDiscoveryConfigsCounts
] = await Promise.all([
Promise.all(gatewayIds.map((id) => appConnectionDAL.countByGatewayId(id).then((count) => ({ id, count })))),
Promise.all(gatewayIds.map((id) => dynamicSecretDAL.countByGatewayId(id).then((count) => ({ id, count })))),
- Promise.all(gatewayIds.map((id) => pamResourceDAL.countByGatewayId(id).then((count) => ({ id, count })))),
- Promise.all(gatewayIds.map((id) => pamDiscoverySourceDAL.countByGatewayId(id).then((count) => ({ id, count })))),
Promise.all(
gatewayIds.map((id) => identityKubernetesAuthDAL.countByGatewayId(id).then((count) => ({ id, count })))
),
@@ -336,12 +326,6 @@ export const gatewayV2ServiceFactory = ({
for (const { id, count } of dynamicSecretsCounts) {
countMap.set(id, (countMap.get(id) ?? 0) + count);
}
- for (const { id, count } of pamResourcesCounts) {
- countMap.set(id, (countMap.get(id) ?? 0) + count);
- }
- for (const { id, count } of pamDiscoverySourcesCounts) {
- countMap.set(id, (countMap.get(id) ?? 0) + count);
- }
for (const { id, count } of kubernetesAuthsCounts) {
countMap.set(id, (countMap.get(id) ?? 0) + count);
}
@@ -1166,19 +1150,9 @@ export const gatewayV2ServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- const [
- appConnections,
- dynamicSecrets,
- pamResources,
- pamDiscoverySources,
- kubernetesAuths,
- mcpServers,
- pkiDiscoveryConfigs
- ] = await Promise.all([
+ const [appConnections, dynamicSecrets, kubernetesAuths, mcpServers, pkiDiscoveryConfigs] = await Promise.all([
appConnectionDAL.findByGatewayId(gatewayId),
dynamicSecretDAL.findByGatewayId(gatewayId),
- pamResourceDAL.findByGatewayId(gatewayId),
- pamDiscoverySourceDAL.findByGatewayId(gatewayId),
identityKubernetesAuthDAL.findByGatewayId(gatewayId),
aiMcpServerDAL.findByGatewayId(gatewayId),
pkiDiscoveryConfigDAL.findByGatewayId(gatewayId)
@@ -1187,8 +1161,6 @@ export const gatewayV2ServiceFactory = ({
return {
appConnections,
dynamicSecrets,
- pamResources,
- pamDiscoverySources,
kubernetesAuths,
mcpServers,
pkiDiscoveryConfigs
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
index 68adcfd4d1..af8ff4da09 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
@@ -29,21 +29,6 @@ export type TGatewayConnectedDynamicSecret = {
environmentSlug?: string;
};
-export type TGatewayConnectedPamResource = {
- id: string;
- name: string;
- projectId: string;
- projectName?: string;
- resourceType: string;
-};
-
-export type TGatewayConnectedPamDiscoverySource = {
- id: string;
- name: string;
- projectId: string;
- projectName?: string;
-};
-
export type TGatewayConnectedKubernetesAuth = {
id: string;
identityId: string;
@@ -67,8 +52,6 @@ export type TGatewayConnectedPkiDiscoveryConfig = {
export type TGatewayConnectedResources = {
appConnections: TGatewayConnectedAppConnection[];
dynamicSecrets: TGatewayConnectedDynamicSecret[];
- pamResources: TGatewayConnectedPamResource[];
- pamDiscoverySources: TGatewayConnectedPamDiscoverySource[];
kubernetesAuths: TGatewayConnectedKubernetesAuth[];
mcpServers: TGatewayConnectedMcpServer[];
pkiDiscoveryConfigs: TGatewayConnectedPkiDiscoveryConfig[];
diff --git a/backend/src/ee/services/pam-account-policy/index.ts b/backend/src/ee/services/pam-account-policy/index.ts
deleted file mode 100644
index 86b36857b4..0000000000
--- a/backend/src/ee/services/pam-account-policy/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export {
- PAM_ACCOUNT_POLICY_RULE_METADATA,
- PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES
-} from "./pam-account-policy-constants";
-export { pamAccountPolicyDALFactory, type TPamAccountPolicyDALFactory } from "./pam-account-policy-dal";
-export { PamAccountPolicyRuleType } from "./pam-account-policy-enums";
-export {
- PolicyRulesBaseSchema,
- PolicyRulesInputSchema,
- PolicyRulesResponseSchema,
- SanitizedPamAccountPolicySchema
-} from "./pam-account-policy-schemas";
-export { pamAccountPolicyServiceFactory, type TPamAccountPolicyServiceFactory } from "./pam-account-policy-service";
-export type * from "./pam-account-policy-types";
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts
deleted file mode 100644
index c6f9069a83..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-
-import { PamAccountPolicyRuleType } from "./pam-account-policy-enums";
-
-export const PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES: Record<PamAccountPolicyRuleType, PamResource[] | "all"> = {
- [PamAccountPolicyRuleType.CommandBlocking]: [PamResource.SSH],
- [PamAccountPolicyRuleType.SessionLogMasking]: "all",
- [PamAccountPolicyRuleType.RequireReason]: "all"
-};
-
-export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<PamAccountPolicyRuleType, { name: string; description: string }> =
- {
- [PamAccountPolicyRuleType.CommandBlocking]: {
- name: "Command Blocking",
- description: "Block commands matching specified patterns"
- },
- [PamAccountPolicyRuleType.SessionLogMasking]: {
- name: "Session Log Masking",
- description: "Mask sensitive data in session logs matching specified patterns"
- },
- [PamAccountPolicyRuleType.RequireReason]: {
- name: "Require Access Reason",
- description: "Require users to provide a reason before they can start a session"
- }
- };
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.ts
deleted file mode 100644
index 7118126028..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-dal.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TPamAccountPolicyDALFactory = ReturnType<typeof pamAccountPolicyDALFactory>;
-
-export const pamAccountPolicyDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamAccountPolicy);
-
- const findByProjectId = async (projectId: string, search?: string) => {
- const query = db.replicaNode()(TableName.PamAccountPolicy).where({ projectId }).orderBy("createdAt", "desc");
-
- if (search) {
- void query.whereILike("name", `%${search}%`);
- }
-
- return query;
- };
-
- return {
- ...orm,
- findByProjectId
- };
-};
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts
deleted file mode 100644
index e62f5a97be..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export enum PamAccountPolicyRuleType {
- CommandBlocking = "command-blocking",
- SessionLogMasking = "session-log-masking",
- RequireReason = "require-reason"
-}
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts
deleted file mode 100644
index 2814a37cea..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import RE2 from "re2";
-import { z } from "zod";
-
-import { PamAccountPoliciesSchema } from "@app/db/schemas";
-
-import { PamAccountPolicyRuleType } from "./pam-account-policy-enums";
-
-const re2PatternSchema = z
- .string()
- .min(1)
- .max(500, "Pattern must be at most 500 characters")
- .refine(
- (pattern) => {
- try {
- // eslint-disable-next-line no-new
- new RE2(pattern);
- return true;
- } catch {
- return false;
- }
- },
- { message: "Invalid regular expression" }
- );
-
-const RuleConfigSchema = z.object({
- patterns: z.array(re2PatternSchema).min(1).max(20, "A rule can have at most 20 patterns")
-});
-
-const RequireReasonConfigSchema = z.object({});
-
-export const PolicyRulesBaseSchema = z.object({
- [PamAccountPolicyRuleType.CommandBlocking]: RuleConfigSchema.optional(),
- [PamAccountPolicyRuleType.SessionLogMasking]: RuleConfigSchema.optional(),
- [PamAccountPolicyRuleType.RequireReason]: RequireReasonConfigSchema.optional()
-});
-
-export const PolicyRulesInputSchema = PolicyRulesBaseSchema.refine(
- (rules) => Object.values(rules).some((v) => v !== undefined),
- "At least one rule must be configured"
-);
-
-export const PolicyRulesResponseSchema = PolicyRulesBaseSchema;
-
-export const SanitizedPamAccountPolicySchema = PamAccountPoliciesSchema.extend({
- rules: PolicyRulesBaseSchema
-});
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-service.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-service.ts
deleted file mode 100644
index 5e9e891723..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-service.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionPamAccountPolicyActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-
-import { TPamAccountPolicyDALFactory } from "./pam-account-policy-dal";
-import {
- TCreatePamAccountPolicyDTO,
- TDeletePamAccountPolicyDTO,
- TGetPamAccountPolicyByIdDTO,
- TListPamAccountPoliciesDTO,
- TUpdatePamAccountPolicyDTO
-} from "./pam-account-policy-types";
-
-type TPamAccountPolicyServiceFactoryDep = {
- pamAccountPolicyDAL: TPamAccountPolicyDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
-};
-
-export type TPamAccountPolicyServiceFactory = ReturnType<typeof pamAccountPolicyServiceFactory>;
-
-export const pamAccountPolicyServiceFactory = ({
- pamAccountPolicyDAL,
- permissionService
-}: TPamAccountPolicyServiceFactoryDep) => {
- const create = async (
- { projectId, name, description, rules }: TCreatePamAccountPolicyDTO,
- actor: OrgServiceActor
- ) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountPolicyActions.Create,
- ProjectPermissionSub.PamAccountPolicies
- );
-
- const existing = await pamAccountPolicyDAL.findOne({ projectId, name });
- if (existing) {
- throw new BadRequestError({ message: `A policy with name '${name}' already exists in this project` });
- }
-
- const policy = await pamAccountPolicyDAL.create({
- projectId,
- name,
- description,
- rules
- });
-
- return policy;
- };
-
- const updateById = async (
- { policyId, name, description, rules, isActive }: TUpdatePamAccountPolicyDTO,
- actor: OrgServiceActor
- ) => {
- const existingPolicy = await pamAccountPolicyDAL.findById(policyId);
- if (!existingPolicy) throw new NotFoundError({ message: "Policy not found" });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: existingPolicy.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountPolicyActions.Edit,
- ProjectPermissionSub.PamAccountPolicies
- );
-
- if (name && name !== existingPolicy.name) {
- const duplicate = await pamAccountPolicyDAL.findOne({ projectId: existingPolicy.projectId, name });
- if (duplicate) {
- throw new BadRequestError({ message: `A policy with name '${name}' already exists in this project` });
- }
- }
-
- const policy = await pamAccountPolicyDAL.updateById(policyId, {
- name,
- description,
- rules,
- isActive
- });
-
- return policy;
- };
-
- const deleteById = async ({ policyId }: TDeletePamAccountPolicyDTO, actor: OrgServiceActor) => {
- const existingPolicy = await pamAccountPolicyDAL.findById(policyId);
- if (!existingPolicy) throw new NotFoundError({ message: "Policy not found" });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: existingPolicy.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountPolicyActions.Delete,
- ProjectPermissionSub.PamAccountPolicies
- );
-
- const policy = await pamAccountPolicyDAL.deleteById(policyId);
-
- return policy;
- };
-
- const list = async ({ projectId, search }: TListPamAccountPoliciesDTO, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountPolicyActions.Read,
- ProjectPermissionSub.PamAccountPolicies
- );
-
- const policies = await pamAccountPolicyDAL.findByProjectId(projectId, search);
-
- return policies;
- };
-
- const getById = async ({ policyId }: TGetPamAccountPolicyByIdDTO, actor: OrgServiceActor) => {
- const policy = await pamAccountPolicyDAL.findById(policyId);
- if (!policy) throw new NotFoundError({ message: "Policy not found" });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: policy.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountPolicyActions.Read,
- ProjectPermissionSub.PamAccountPolicies
- );
-
- return policy;
- };
-
- return {
- create,
- updateById,
- deleteById,
- list,
- getById
- };
-};
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-types.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-types.ts
deleted file mode 100644
index 1c12a3dbd9..0000000000
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-types.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { z } from "zod";
-
-import { PolicyRulesBaseSchema } from "./pam-account-policy-schemas";
-
-export type TPolicyRules = z.infer<typeof PolicyRulesBaseSchema>;
-
-export type TCreatePamAccountPolicyDTO = {
- projectId: string;
- name: string;
- description?: string;
- rules: TPolicyRules;
-};
-
-export type TUpdatePamAccountPolicyDTO = {
- policyId: string;
- name?: string;
- description?: string | null;
- rules?: TPolicyRules;
- isActive?: boolean;
-};
-
-export type TDeletePamAccountPolicyDTO = {
- policyId: string;
-};
-
-export type TListPamAccountPoliciesDTO = {
- projectId: string;
- search?: string;
-};
-
-export type TGetPamAccountPolicyByIdDTO = {
- policyId: string;
-};
diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts
deleted file mode 100644
index 6bf7281f9c..0000000000
--- a/backend/src/ee/services/pam-account/pam-account-dal.ts
+++ /dev/null
@@ -1,395 +0,0 @@
-import { Knex } from "knex";
-import RE2 from "re2";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { OrderByDirection } from "@app/lib/types";
-import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
-
-import { PamAccountOrderBy, PamAccountView } from "./pam-account-enums";
-
-export type TPamAccountDALFactory = ReturnType<typeof pamAccountDALFactory>;
-
-export const pamAccountDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamAccount);
-
- const findByProjectIdWithParentDetails = async (
- {
- projectId,
- folderId,
- accountView = PamAccountView.Nested,
- search,
- limit,
- offset = 0,
- orderBy = PamAccountOrderBy.Name,
- orderDirection = OrderByDirection.ASC,
- filterResourceIds,
- filterDomainIds,
- metadataFilter
- }: {
- projectId: string;
- folderId?: string | null;
- accountView?: PamAccountView;
- search?: string;
- limit?: number;
- offset?: number;
- orderBy?: PamAccountOrderBy;
- orderDirection?: OrderByDirection;
- filterResourceIds?: string[];
- filterDomainIds?: string[];
- metadataFilter?: Array<{ key: string; value?: string }>;
- },
- tx?: Knex
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamAccount)
- .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
- .leftJoin(TableName.PamDomain, `${TableName.PamAccount}.domainId`, `${TableName.PamDomain}.id`)
- .leftJoin(TableName.PamAccountPolicy, `${TableName.PamAccount}.policyId`, `${TableName.PamAccountPolicy}.id`)
- .where(`${TableName.PamAccount}.projectId`, projectId);
-
- if (accountView === PamAccountView.Nested) {
- if (folderId) {
- void query.where(`${TableName.PamAccount}.folderId`, folderId);
- } else {
- void query.whereNull(`${TableName.PamAccount}.folderId`);
- }
- }
-
- if (search) {
- // escape special characters (`%`, `_`) and the escape character itself (`\`)
- const escapedSearch = search
- .replace(new RE2(/\\/g), "\\\\")
- .replace(new RE2(/%/g), "\\%")
- .replace(new RE2(/_/g), "\\_");
- const pattern = `%${escapedSearch}%`;
- void query.where((q) => {
- void q
- .whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamAccount, "name", pattern])
- .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamResource, "name", pattern])
- .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDomain, "name", pattern])
- .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamAccount, "description", pattern]);
- });
- }
-
- const hasResourceFilter = filterResourceIds && filterResourceIds.length > 0;
- const hasDomainFilter = filterDomainIds && filterDomainIds.length > 0;
-
- if (hasResourceFilter && hasDomainFilter) {
- void query.where((qb) => {
- void qb
- .whereIn(`${TableName.PamAccount}.resourceId`, filterResourceIds)
- .orWhereIn(`${TableName.PamAccount}.domainId`, filterDomainIds);
- });
- } else if (hasResourceFilter) {
- void query.whereIn(`${TableName.PamAccount}.resourceId`, filterResourceIds);
- } else if (hasDomainFilter) {
- void query.whereIn(`${TableName.PamAccount}.domainId`, filterDomainIds);
- }
-
- if (metadataFilter && metadataFilter.length > 0) {
- void applyMetadataFilter(query, metadataFilter, "pamAccountId", TableName.PamAccount);
- }
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamAccount)).select(
- // resource (may be null for domain accounts)
- db.ref("name").withSchema(TableName.PamResource).as("resourceName"),
- db.ref("resourceType").withSchema(TableName.PamResource),
- db
- .ref("encryptedRotationAccountCredentials")
- .withSchema(TableName.PamResource)
- .as("resourceEncryptedRotationAccountCredentials"),
- // domain (may be null for resource accounts)
- db.ref("name").withSchema(TableName.PamDomain).as("domainName"),
- db.ref("domainType").withSchema(TableName.PamDomain),
- // policy
- db.ref("name").withSchema(TableName.PamAccountPolicy).as("policyName")
- );
-
- const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";
-
- void query.orderByRaw(`${TableName.PamAccount}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]);
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [results, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- const accounts = results.map((row) => {
- const r = row as Record<string, unknown>;
- const rId = row.resourceId as string | null;
- const dId = row.domainId as string | null;
-
- return {
- ...row,
- resourceId: rId,
- domainId: dId,
- policyName: (r.policyName as string) || null,
- resource: rId
- ? {
- id: rId,
- name: r.resourceName as string,
- resourceType: r.resourceType as string,
- encryptedRotationAccountCredentials: r.resourceEncryptedRotationAccountCredentials as Buffer | null
- }
- : null,
- domain: dId
- ? {
- id: dId,
- name: r.domainName as string,
- domainType: r.domainType as string
- }
- : null
- };
- });
-
- return { accounts, totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM accounts with parent details" });
- }
- };
-
- const findByIdWithParentDetails = async (accountId: string, tx?: Knex) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const result = await dbInstance(TableName.PamAccount)
- .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
- .leftJoin(TableName.PamDomain, `${TableName.PamAccount}.domainId`, `${TableName.PamDomain}.id`)
- .leftJoin(TableName.PamAccountPolicy, `${TableName.PamAccount}.policyId`, `${TableName.PamAccountPolicy}.id`)
- .where(`${TableName.PamAccount}.id`, accountId)
- .select(selectAllTableCols(TableName.PamAccount))
- .select(
- // resource (may be null for domain accounts)
- db.ref("name").withSchema(TableName.PamResource).as("resourceName"),
- db.ref("resourceType").withSchema(TableName.PamResource),
- db
- .ref("encryptedRotationAccountCredentials")
- .withSchema(TableName.PamResource)
- .as("resourceEncryptedRotationAccountCredentials"),
- // domain (may be null for resource accounts)
- db.ref("name").withSchema(TableName.PamDomain).as("domainName"),
- db.ref("domainType").withSchema(TableName.PamDomain),
- db.ref("name").withSchema(TableName.PamAccountPolicy).as("policyName")
- )
- .first();
-
- if (!result) return null;
-
- const {
- resourceId,
- domainId,
- resourceName,
- resourceType,
- resourceEncryptedRotationAccountCredentials,
- domainName,
- domainType,
- policyName,
- ...account
- } = result as {
- resourceId: string | null;
- domainId: string | null;
- resourceName: string | null;
- resourceType: string | null;
- resourceEncryptedRotationAccountCredentials: Buffer | null;
- domainName: string | null;
- domainType: string | null;
- policyName: string | null;
- } & typeof result;
-
- return {
- ...account,
- resourceId,
- domainId,
- policyName: policyName || null,
- resource: resourceId
- ? {
- id: resourceId,
- name: resourceName,
- resourceType,
- encryptedRotationAccountCredentials: resourceEncryptedRotationAccountCredentials
- }
- : null,
- domain: domainId
- ? {
- id: domainId,
- name: domainName,
- domainType
- }
- : null
- };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM account by ID with parent details" });
- }
- };
-
- const findMetadataByAccountIds = async (accountIds: string[], tx?: Knex) => {
- if (!accountIds.length) return {};
- const rows = await (tx || db.replicaNode())(TableName.ResourceMetadata)
- .select("id", "key", "value", "pamAccountId")
- .whereIn("pamAccountId", accountIds);
- const byAccountId: Record<string, Array<{ id: string; key: string; value: string }>> = {};
- for (const row of rows) {
- if (row.pamAccountId) {
- if (!byAccountId[row.pamAccountId]) byAccountId[row.pamAccountId] = [];
- byAccountId[row.pamAccountId].push({ id: row.id, key: row.key, value: row.value || "" });
- }
- }
- return byAccountId;
- };
-
- const findRotationCandidates = async (
- {
- resourceIds,
- domainIds,
- minIntervalSeconds
- }: {
- resourceIds?: string[];
- domainIds?: string[];
- minIntervalSeconds: number;
- },
- tx?: Knex
- ) => {
- const hasResourceIds = resourceIds && resourceIds.length > 0;
- const hasDomainIds = domainIds && domainIds.length > 0;
- if (!hasResourceIds && !hasDomainIds) return [];
-
- try {
- const cutoff = new Date(Date.now() - minIntervalSeconds * 1000);
-
- return await (tx || db.replicaNode())(TableName.PamAccount)
- .where((qb) => {
- if (hasResourceIds) {
- void qb.whereIn("resourceId", resourceIds);
- }
- if (hasDomainIds) {
- void qb.orWhereIn("domainId", domainIds);
- }
- })
- .where((qb) => {
- void qb.whereNot("rotationStatus", "rotating").orWhereNull("rotationStatus");
- })
- .where((qb) => {
- void qb.where("lastRotatedAt", "<", cutoff).orWhere((inner) => {
- void inner.whereNull("lastRotatedAt").andWhere("createdAt", "<", cutoff);
- });
- })
- .select(selectAllTableCols(TableName.PamAccount));
- } catch (error) {
- throw new DatabaseError({ error, name: "Find rotation candidates" });
- }
- };
-
- const countByProject = async (projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamAccount)
- .where("projectId", projectId)
- .count("id as count")
- .first();
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const countFailedRotationsByProject = async (projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamAccount)
- .where("projectId", projectId)
- .where("rotationStatus", "failed")
- .count("id as count")
- .first();
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const findFailedRotationsByProject = async (
- projectId: string,
- limit: number,
- tx?: Knex
- ): Promise<
- {
- id: string;
- name: string;
- resourceId: string;
- resourceName: string;
- resourceType: string;
- lastRotatedAt: Date | null;
- }[]
- > => {
- const rows = await (tx || db.replicaNode())(TableName.PamAccount)
- .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
- .select(
- `${TableName.PamAccount}.id as id`,
- `${TableName.PamAccount}.name as name`,
- `${TableName.PamAccount}.resourceId as resourceId`,
- `${TableName.PamAccount}.lastRotatedAt as lastRotatedAt`,
- `${TableName.PamResource}.name as resourceName`,
- `${TableName.PamResource}.resourceType as resourceType`
- )
- .where(`${TableName.PamAccount}.projectId`, projectId)
- .where(`${TableName.PamAccount}.rotationStatus`, "failed")
- .orderBy(`${TableName.PamAccount}.lastRotatedAt`, "desc")
- .limit(limit);
-
- return rows as {
- id: string;
- name: string;
- resourceId: string;
- resourceName: string;
- resourceType: string;
- lastRotatedAt: Date | null;
- }[];
- };
-
- const findRotationCandidatesByProject = async (
- projectId: string,
- tx?: Knex
- ): Promise<
- {
- id: string;
- name: string;
- resourceId: string;
- resourceName: string;
- resourceType: string;
- lastRotatedAt: Date | null;
- createdAt: Date;
- }[]
- > => {
- const rows = await (tx || db.replicaNode())(TableName.PamAccount)
- .innerJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
- .select(
- `${TableName.PamAccount}.id as id`,
- `${TableName.PamAccount}.name as name`,
- `${TableName.PamAccount}.resourceId as resourceId`,
- `${TableName.PamAccount}.lastRotatedAt as lastRotatedAt`,
- `${TableName.PamAccount}.createdAt as createdAt`,
- `${TableName.PamResource}.name as resourceName`,
- `${TableName.PamResource}.resourceType as resourceType`
- )
- .where(`${TableName.PamAccount}.projectId`, projectId)
- .whereNotNull(`${TableName.PamResource}.encryptedRotationAccountCredentials`);
-
- return rows as {
- id: string;
- name: string;
- resourceId: string;
- resourceName: string;
- resourceType: string;
- lastRotatedAt: Date | null;
- createdAt: Date;
- }[];
- };
-
- return {
- ...orm,
- findByProjectIdWithParentDetails,
- findByIdWithParentDetails,
- findMetadataByAccountIds,
- findRotationCandidates,
- findRotationCandidatesByProject,
- countByProject,
- countFailedRotationsByProject,
- findFailedRotationsByProject
- };
-};
diff --git a/backend/src/ee/services/pam-account/pam-account-fns.ts b/backend/src/ee/services/pam-account/pam-account-fns.ts
deleted file mode 100644
index 493b501436..0000000000
--- a/backend/src/ee/services/pam-account/pam-account-fns.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { KubernetesAuthMethod } from "../pam-resource/kubernetes/kubernetes-resource-enums";
-import { PamResource } from "../pam-resource/pam-resource-enums";
-import { TPamAccountCredentials, TPamResourceInternalMetadata } from "../pam-resource/pam-resource-types";
-import { SSHAuthMethod } from "../pam-resource/ssh/ssh-resource-enums";
-
-type TAccountParentResource = {
- id: string;
- name: string;
- resourceType: string;
- encryptedRotationAccountCredentials?: Buffer | null;
-};
-
-type TAccountParentDomain = {
- id: string;
- name: string;
- domainType: string;
-};
-
-export const formatAccountParent = ({
- resource,
- domain
-}: {
- resource?: TAccountParentResource | null;
- domain?: TAccountParentDomain | null;
-}) => ({
- parentType: resource?.resourceType ?? domain?.domainType ?? "",
- resource: resource
- ? {
- id: resource.id,
- name: resource.name,
- resourceType: resource.resourceType,
- rotationCredentialsConfigured: Boolean(resource.encryptedRotationAccountCredentials)
- }
- : null,
- domain: domain
- ? {
- id: domain.id,
- name: domain.name,
- domainType: domain.domainType
- }
- : null
-});
-
-export const encryptAccountCredentials = async ({
- projectId,
- credentials,
- kmsService
-}: {
- projectId: string;
- credentials: TPamAccountCredentials;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob: encryptedCredentialsBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(credentials))
- });
-
- return encryptedCredentialsBlob;
-};
-
-export const decryptAccountCredentials = async ({
- projectId,
- encryptedCredentials,
- kmsService
-}: {
- projectId: string;
- encryptedCredentials: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedCredentials
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as TPamAccountCredentials;
-};
-
-export const decryptAccountMessage = async ({
- projectId,
- encryptedMessage,
- kmsService
-}: {
- projectId: string;
- encryptedMessage: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedMessage
- });
-
- return decryptedPlainTextBlob.toString();
-};
-
-// Returns false for account types where all credential fields are already visible in the sanitized view
-export const hasSensitiveCredentials = (parentType: string, credentials: TPamAccountCredentials): boolean => {
- if (parentType === PamResource.AwsIam) return false;
- if (
- parentType === PamResource.Kubernetes &&
- "authMethod" in credentials &&
- credentials.authMethod === KubernetesAuthMethod.GatewayKubernetesAuth
- )
- return false;
- if (
- parentType === PamResource.SSH &&
- "authMethod" in credentials &&
- credentials.authMethod === SSHAuthMethod.Certificate
- )
- return false;
- return true;
-};
-
-const hasConfiguredCredentials = (credentials: TPamAccountCredentials): boolean => {
- if ("password" in credentials && credentials.password) return true;
- if ("privateKey" in credentials && credentials.privateKey) return true;
- if ("serviceAccountToken" in credentials && credentials.serviceAccountToken) return true;
- if ("targetRoleArn" in credentials && credentials.targetRoleArn) return true;
- if ("authMethod" in credentials && credentials.authMethod === SSHAuthMethod.Certificate) return true;
- if ("authMethod" in credentials && credentials.authMethod === KubernetesAuthMethod.GatewayKubernetesAuth) return true;
- return false;
-};
-
-export const decryptAccount = async <
- T extends { encryptedCredentials: Buffer; encryptedLastRotationMessage?: Buffer | null; internalMetadata?: unknown }
->(
- account: T,
- projectId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
-): Promise<
- Omit<T, "encryptedCredentials" | "encryptedLastRotationMessage" | "internalMetadata"> & {
- credentials: TPamAccountCredentials;
- credentialsConfigured: boolean;
- lastRotationMessage: string | null;
- internalMetadata?: TPamResourceInternalMetadata;
- }
-> => {
- const { encryptedCredentials, encryptedLastRotationMessage, internalMetadata, ...rest } = account;
-
- const credentials = await decryptAccountCredentials({
- encryptedCredentials,
- projectId,
- kmsService
- });
-
- return {
- ...rest,
- credentials,
- internalMetadata: internalMetadata as TPamResourceInternalMetadata | undefined,
- credentialsConfigured: hasConfiguredCredentials(credentials),
- lastRotationMessage: encryptedLastRotationMessage
- ? await decryptAccountMessage({
- encryptedMessage: encryptedLastRotationMessage,
- projectId,
- kmsService
- })
- : null
- };
-};
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
deleted file mode 100644
index 8034cce1a9..0000000000
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ /dev/null
@@ -1,2022 +0,0 @@
-import { ForbiddenError, subject } from "@casl/ability";
-import picomatch from "picomatch";
-
-import { ActionProjectType, OrganizationActionScope, TableName, TPamAccounts, TPamResources } from "@app/db/schemas";
-import { decryptDomainConnectionDetails } from "@app/ee/services/pam-domain/pam-domain-fns";
-import {
- AWS_STS_MIN_DURATION_SECONDS,
- exchangeCredentialsForConsoleUrl,
- extractAwsAccountIdFromArn,
- generateAwsIamSessionCredentials,
- TAwsIamAccountCredentials
-} from "@app/ee/services/pam-resource/aws-iam";
-import { parseMongoConnectionString } from "@app/ee/services/pam-resource/mongodb/mongodb-resource-factory";
-import { PAM_RESOURCE_FACTORY_MAP } from "@app/ee/services/pam-resource/pam-resource-factory";
-import {
- decryptResource,
- decryptResourceConnectionDetails,
- decryptResourceMetadata
-} from "@app/ee/services/pam-resource/pam-resource-fns";
-import { SSHAuthMethod } from "@app/ee/services/pam-resource/ssh/ssh-resource-enums";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionPamAccountActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { createSshCert, createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";
-import { SshCertType } from "@app/ee/services/ssh/ssh-certificate-authority-types";
-import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";
-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
-import { DatabaseErrorCode } from "@app/lib/error-codes";
-import {
- BadRequestError,
- DatabaseError,
- ForbiddenRequestError,
- NotFoundError,
- PolicyViolationError
-} from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
-import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { OrgServiceActor } from "@app/lib/types";
-import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
-import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";
-import { TApprovalRequestGrantsDALFactory } from "@app/services/approval-policy/approval-request-dal";
-import { TPamAccessPolicy } from "@app/services/approval-policy/pam-access/pam-access-policy-types";
-import { ActorType, MfaMethod } from "@app/services/auth/auth-type";
-import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
-import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
-import { TOrgDALFactory } from "@app/services/org/org-dal";
-import { TPamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
-import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
-import { TSmtpService } from "@app/services/smtp/smtp-service";
-import { TUserDALFactory } from "@app/services/user/user-dal";
-
-import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";
-import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES } from "../pam-account-policy/pam-account-policy-constants";
-import { TPamAccountPolicyDALFactory } from "../pam-account-policy/pam-account-policy-dal";
-import { PamAccountPolicyRuleType } from "../pam-account-policy/pam-account-policy-enums";
-import { TPolicyRules } from "../pam-account-policy/pam-account-policy-types";
-import { TPamAccountDependenciesDALFactory } from "../pam-discovery/pam-account-dependencies-dal";
-import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
-import { PamDomainType } from "../pam-domain/pam-domain-enums";
-import { PAM_DOMAIN_FACTORY_MAP } from "../pam-domain/pam-domain-factory";
-import { TPamProjectRecordingConfigDALFactory } from "../pam-project-recording-config/pam-project-recording-config-dal";
-import { TPamProjectRecordingConfigServiceFactory } from "../pam-project-recording-config/pam-project-recording-config-service";
-import { MsSqlAuthMethod } from "../pam-resource/mssql/mssql-resource-enums";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
-import { PamResource } from "../pam-resource/pam-resource-enums";
-import { TPamResourceRotationRulesDALFactory } from "../pam-resource/pam-resource-rotation-rules-dal";
-import { TPamAccountCredentials } from "../pam-resource/pam-resource-types";
-import { TRedisAccountCredentials } from "../pam-resource/redis/redis-resource-types";
-import { TSqlAccountCredentials, TSqlResourceConnectionDetails } from "../pam-resource/shared/sql/sql-resource-types";
-import { TSSHAccountCredentials, TSSHResourceInternalMetadata } from "../pam-resource/ssh/ssh-resource-types";
-import { TWindowsAccountCredentials } from "../pam-resource/windows-server/windows-server-resource-types";
-import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
-import { PamSessionStatus } from "../pam-session/pam-session-enums";
-import { decryptSessionKey, generateSessionRecordingSecrets } from "../pam-session/pam-session-recording-secrets";
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
-import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
-import { TPamAccountDALFactory } from "./pam-account-dal";
-import { PamAccountRotationStatus } from "./pam-account-enums";
-import {
- decryptAccount,
- decryptAccountCredentials,
- encryptAccountCredentials,
- formatAccountParent,
- hasSensitiveCredentials
-} from "./pam-account-fns";
-import {
- TAccessAccountDTO,
- TCreateAccountDTO,
- TGetAccountByIdDTO,
- TListAccountsDTO,
- TUpdateAccountDTO,
- TViewAccountCredentialsDTO
-} from "./pam-account-types";
-
-type TPamAccountServiceFactoryDep = {
- pamResourceDAL: TPamResourceDALFactory;
- pamDomainDAL: TPamDomainDALFactory;
- pamSessionDAL: TPamSessionDALFactory;
- pamAccountDAL: TPamAccountDALFactory;
- pamAccountPolicyDAL: Pick<TPamAccountPolicyDALFactory, "findById">;
- pamResourceRotationRulesDAL: Pick<TPamResourceRotationRulesDALFactory, "findByResourceIds">;
- mfaSessionService: TMfaSessionServiceFactory;
- projectDAL: TProjectDALFactory;
- orgDAL: TOrgDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2Service: Pick<
- TGatewayV2ServiceFactory,
- "getPAMConnectionDetails" | "getPlatformConnectionDetailsByGatewayId"
- >;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
- userDAL: TUserDALFactory;
- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
- tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser" | "validateTokenForUser">;
- smtpService: Pick<TSmtpService, "sendMail">;
- approvalPolicyDAL: TApprovalPolicyDALFactory;
- approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
- pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;
- resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
- pamAccountDependenciesDAL: Pick<
- TPamAccountDependenciesDALFactory,
- "findByAccountId" | "updateById" | "countByAccountIds"
- >;
- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem">;
- pamProjectRecordingConfigDAL: Pick<TPamProjectRecordingConfigDALFactory, "findByProjectId">;
- pamProjectRecordingConfigService: Pick<TPamProjectRecordingConfigServiceFactory, "resolveConfigForProject">;
-};
-
-export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;
-
-const ROTATION_CONCURRENCY_LIMIT = 10;
-
-export const pamAccountServiceFactory = ({
- pamResourceDAL,
- pamDomainDAL,
- pamSessionDAL,
- pamAccountDAL,
- pamAccountPolicyDAL,
- pamResourceRotationRulesDAL,
- mfaSessionService,
- projectDAL,
- orgDAL,
- userDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- auditLogService,
- approvalPolicyDAL,
- approvalRequestGrantsDAL,
- pamSessionExpirationService,
- resourceMetadataDAL,
- pamAccountDependenciesDAL,
- keyStore,
- pamProjectRecordingConfigDAL,
- pamProjectRecordingConfigService
-}: TPamAccountServiceFactoryDep) => {
- // Helper to resolve account parent (resource or domain)
- const resolveAccountParent = async ({
- resourceId,
- domainId
- }: {
- resourceId?: string | null;
- domainId?: string | null;
- }) => {
- if (resourceId) {
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
- return {
- projectId: resource.projectId,
- name: resource.name,
- resourceType: resource.resourceType,
- domainType: null as string | null,
- gatewayId: resource.gatewayId,
- gatewayPoolId: resource.gatewayPoolId ?? null,
- encryptedConnectionDetails: resource.encryptedConnectionDetails,
- encryptedResourceMetadata: resource.encryptedResourceMetadata,
- encryptedRotationAccountCredentials: resource.encryptedRotationAccountCredentials,
- isResource: true as const,
- raw: resource
- };
- }
- if (!domainId) throw new BadRequestError({ message: "Either resourceId or domainId must be provided" });
- const domain = await pamDomainDAL.findById(domainId);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${domainId}' not found` });
- return {
- projectId: domain.projectId,
- name: domain.name,
- resourceType: null as string | null,
- domainType: domain.domainType,
- gatewayId: domain.gatewayId,
- gatewayPoolId: domain.gatewayPoolId ?? null,
- encryptedConnectionDetails: domain.encryptedConnectionDetails,
- encryptedResourceMetadata: null as Buffer | null,
- encryptedRotationAccountCredentials: null as Buffer | null,
- isResource: false as const,
- raw: domain
- };
- };
-
- // Resolve whether the given policy enforces RequireReason at access time.
- // Surfaced on account responses so the UI can gate access without needing
- // pam-account-policy:read permission.
- const resolveRequireReason = async (policyId?: string | null) => {
- if (!policyId) return false;
- const policy = await pamAccountPolicyDAL.findById(policyId);
- const policyRules = (policy?.rules ?? {}) as TPolicyRules;
- return Boolean(policy?.isActive && policyRules[PamAccountPolicyRuleType.RequireReason]);
- };
-
- const create = async (
- {
- credentials,
- resourceId,
- domainId,
- name,
- description,
- folderId,
- requireMfa,
- internalMetadata,
- metadata,
- policyId
- }: TCreateAccountDTO,
- actor: OrgServiceActor
- ) => {
- const parent = await resolveAccountParent({ resourceId, domainId });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: parent.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Create,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: name,
- ...(parent.isResource && { resourceName: parent.name, resourceType: parent.resourceType }),
- ...(!parent.isResource && { domainName: parent.name, domainType: parent.domainType }),
- metadata: (metadata || []).map(({ key, value }) => ({ key, value: value ?? "" }))
- })
- );
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(parent);
- let factory;
- if (parent.isResource) {
- const connectionDetails = await decryptResourceConnectionDetails({
- projectId: parent.projectId,
- encryptedConnectionDetails: parent.encryptedConnectionDetails,
- kmsService
- });
- const resourceInternalMetadata = parent.encryptedResourceMetadata
- ? await decryptResourceMetadata({
- encryptedMetadata: parent.encryptedResourceMetadata,
- projectId: parent.projectId,
- kmsService
- })
- : undefined;
- factory = PAM_RESOURCE_FACTORY_MAP[parent.resourceType as PamResource](
- parent.resourceType as PamResource,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- parent.projectId,
- resourceInternalMetadata
- );
- } else {
- const connectionDetails = await decryptDomainConnectionDetails({
- projectId: parent.projectId,
- encryptedConnectionDetails: parent.encryptedConnectionDetails,
- kmsService
- });
- factory = PAM_DOMAIN_FACTORY_MAP[parent.domainType as PamDomainType](
- parent.domainType as PamDomainType,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- parent.projectId
- );
- }
- const validatedCredentials = await factory.validateAccountCredentials(credentials);
-
- const encryptedCredentials = await encryptAccountCredentials({
- credentials: validatedCredentials,
- projectId: parent.projectId,
- kmsService
- });
-
- if (policyId) {
- const policy = await pamAccountPolicyDAL.findById(policyId);
- if (!policy || policy.projectId !== parent.projectId) {
- throw new NotFoundError({ message: "Policy not found" });
- }
- }
-
- try {
- const { account, insertedMetadata } = await pamAccountDAL.transaction(async (tx) => {
- const newAccount = await pamAccountDAL.create(
- {
- projectId: parent.projectId,
- resourceId: resourceId || null,
- domainId: domainId || null,
- encryptedCredentials,
- name,
- description,
- folderId,
- requireMfa,
- internalMetadata: internalMetadata ?? null,
- policyId: policyId ?? null
- },
- tx
- );
-
- let metadataRows: Awaited<ReturnType<typeof resourceMetadataDAL.insertMany>> | undefined;
- if (metadata && metadata.length > 0) {
- metadataRows = await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamAccountId: newAccount.id,
- orgId: actor.orgId
- })),
- tx
- );
- }
-
- return { account: newAccount, insertedMetadata: metadataRows };
- });
-
- return {
- ...(await decryptAccount(account, parent.projectId, kmsService)),
- ...formatAccountParent({
- resource: parent.isResource ? parent.raw : null,
- domain: parent.isResource ? null : parent.raw
- }),
- metadata: insertedMetadata?.map(({ id, key, value }) => ({ id, key, value: value ?? "" })) ?? [],
- requireReason: await resolveRequireReason(account.policyId)
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Account with name '${name}' already exists`
- });
- }
-
- throw err;
- }
- };
-
- const updateById = async (
- { accountId, credentials, description, name, requireMfa, internalMetadata, metadata, policyId }: TUpdateAccountDTO,
- actor: OrgServiceActor
- ) => {
- const account = await pamAccountDAL.findById(accountId);
- if (!account) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
-
- const parent = await resolveAccountParent(account);
- const resource = parent.isResource ? (parent.raw as TPamResources) : null;
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: account.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const existingAccountMeta = await pamAccountDAL.findMetadataByAccountIds([accountId]);
- const currentMetadata = existingAccountMeta[accountId] || [];
-
- // Check against current state
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Edit,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: account.name,
- ...(parent.isResource && { resourceName: parent.name, resourceType: parent.resourceType }),
- ...(!parent.isResource && { domainName: parent.name, domainType: parent.domainType }),
- metadata: currentMetadata
- })
- );
-
- // If any conditionable field is changing, also check permission against proposed state
- if (metadata || name) {
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Edit,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: name ?? account.name,
- ...(parent.isResource && { resourceName: parent.name, resourceType: parent.resourceType }),
- ...(!parent.isResource && { domainName: parent.name, domainType: parent.domainType }),
- metadata: metadata ? metadata.map(({ key, value }) => ({ key, value: value ?? "" })) : currentMetadata
- })
- );
- }
-
- const updateDoc: Partial<TPamAccounts> = {};
-
- if (name !== undefined) {
- updateDoc.name = name;
- }
-
- if (requireMfa !== undefined) {
- updateDoc.requireMfa = requireMfa;
- }
-
- if (description !== undefined) {
- updateDoc.description = description;
- }
-
- if (internalMetadata !== undefined) {
- updateDoc.internalMetadata = internalMetadata;
- }
-
- if (policyId !== undefined) {
- if (policyId) {
- const policy = await pamAccountPolicyDAL.findById(policyId);
- if (!policy || policy.projectId !== account.projectId) {
- throw new NotFoundError({ message: "Policy not found" });
- }
- }
- updateDoc.policyId = policyId;
- }
-
- if (credentials !== undefined) {
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(parent);
- let factory;
- if (parent.isResource) {
- const connectionDetails = await decryptResourceConnectionDetails({
- projectId: account.projectId,
- encryptedConnectionDetails: parent.encryptedConnectionDetails,
- kmsService
- });
- const resourceInternalMetadata = parent.encryptedResourceMetadata
- ? await decryptResourceMetadata({
- encryptedMetadata: parent.encryptedResourceMetadata,
- projectId: account.projectId,
- kmsService
- })
- : undefined;
- factory = PAM_RESOURCE_FACTORY_MAP[parent.resourceType as PamResource](
- parent.resourceType as PamResource,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- account.projectId,
- resourceInternalMetadata
- );
- } else {
- const connectionDetails = await decryptDomainConnectionDetails({
- projectId: account.projectId,
- encryptedConnectionDetails: parent.encryptedConnectionDetails,
- kmsService
- });
- factory = PAM_DOMAIN_FACTORY_MAP[parent.domainType as PamDomainType](
- parent.domainType as PamDomainType,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- account.projectId
- );
- }
-
- const decryptedCredentials = await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- projectId: account.projectId,
- kmsService
- });
-
- // Logic to prevent overwriting unedited censored values
- const finalCredentials = await factory.handleOverwritePreventionForCensoredValues(
- credentials,
- decryptedCredentials
- );
-
- const validatedCredentials = await factory.validateAccountCredentials(finalCredentials);
- const encryptedCredentials = await encryptAccountCredentials({
- credentials: validatedCredentials,
- projectId: account.projectId,
- kmsService
- });
- updateDoc.encryptedCredentials = encryptedCredentials;
- }
-
- // If nothing was updated, return the fetched account
- if (Object.keys(updateDoc).length === 0 && metadata === undefined) {
- const existingMeta = await pamAccountDAL.findMetadataByAccountIds([accountId]);
- return {
- ...(await decryptAccount(account, account.projectId, kmsService)),
- ...formatAccountParent({
- resource,
- domain: parent.isResource ? null : parent.raw
- }),
- metadata: existingMeta[accountId] || [],
- requireReason: await resolveRequireReason(account.policyId)
- };
- }
-
- try {
- const updatedAccount = await pamAccountDAL.transaction(async (tx) => {
- if (metadata) {
- await resourceMetadataDAL.delete({ pamAccountId: accountId }, tx);
- if (metadata.length > 0) {
- await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamAccountId: accountId,
- orgId: actor.orgId
- })),
- tx
- );
- }
- }
- if (Object.keys(updateDoc).length > 0) {
- return pamAccountDAL.updateById(accountId, updateDoc, tx);
- }
- return account;
- });
-
- const freshMeta = await pamAccountDAL.findMetadataByAccountIds([accountId]);
-
- return {
- ...(await decryptAccount(updatedAccount, account.projectId, kmsService)),
- ...formatAccountParent({
- resource,
- domain: parent.isResource ? null : parent.raw
- }),
- metadata: freshMeta[accountId] || [],
- requireReason: await resolveRequireReason(updatedAccount.policyId)
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Account with name '${name}' already exists for this resource`
- });
- }
-
- throw err;
- }
- };
-
- const deleteById = async (id: string, actor: OrgServiceActor) => {
- const account = await pamAccountDAL.findById(id);
- if (!account) throw new NotFoundError({ message: `Account with ID '${id}' not found` });
-
- const parent = await resolveAccountParent(account);
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: account.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const accountMeta = await pamAccountDAL.findMetadataByAccountIds([id]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Delete,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: account.name,
- ...(parent.isResource && { resourceName: parent.name, resourceType: parent.resourceType }),
- ...(!parent.isResource && { domainName: parent.name, domainType: parent.domainType }),
- metadata: accountMeta[id] || []
- })
- );
-
- const deletedAccount = await pamAccountDAL.deleteById(id);
-
- return {
- ...(await decryptAccount(deletedAccount, account.projectId, kmsService)),
- ...formatAccountParent({
- resource: parent.isResource ? parent.raw : null,
- domain: parent.isResource ? null : parent.raw
- })
- };
- };
-
- const list = async ({
- projectId,
- accountView,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- ...params
- }: TListAccountsDTO) => {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const limit = params.limit || 20;
- const offset = params.offset || 0;
-
- const { accounts: accountsWithParentDetails, totalCount } = await pamAccountDAL.findByProjectIdWithParentDetails({
- projectId,
- accountView,
- offset,
- limit,
- search: params.search,
- orderBy: params.orderBy,
- orderDirection: params.orderDirection,
- filterResourceIds: params.filterResourceIds,
- filterDomainIds: params.filterDomainIds,
- metadataFilter: params.metadataFilter
- });
-
- const decryptedAndPermittedAccounts: Array<
- Omit<TPamAccounts, "encryptedCredentials" | "encryptedLastRotationMessage"> & {
- resource:
- | (Pick<TPamResources, "id" | "name" | "resourceType"> & { rotationCredentialsConfigured: boolean })
- | null;
- domain: { id: string; name: string; domainType: string } | null;
- credentials: TPamAccountCredentials;
- lastRotationMessage: string | null;
- }
- > = [];
-
- // Fetch metadata for all accounts before permission loop
- const allAccountIds = accountsWithParentDetails.map((a) => a.id);
- const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds(allAccountIds);
-
- for await (const account of accountsWithParentDetails) {
- if (
- permission.can(
- ProjectPermissionPamAccountActions.Read,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: account.name,
- ...(account.resource && {
- resourceName: account.resource.name,
- resourceType: account.resource.resourceType
- }),
- ...(account.domain && { domainName: account.domain.name, domainType: account.domain.domainType }),
- metadata: metadataByAccountId[account.id] || []
- })
- )
- ) {
- // Decrypt the account only if the user has permission to read it
- const decryptedAccount = await decryptAccount(
- account as Parameters<typeof decryptAccount>[0],
- account.projectId,
- kmsService
- );
-
- decryptedAndPermittedAccounts.push({
- ...decryptedAccount,
- ...formatAccountParent({
- resource: account.resource,
- domain: account.domain
- })
- } as unknown as (typeof decryptedAndPermittedAccounts)[0]);
- }
- }
-
- // Fetch dependency counts for all permitted accounts
- const permittedAccountIds = decryptedAndPermittedAccounts.map((a) => a.id);
- const dependencyCountMap =
- permittedAccountIds.length > 0 ? await pamAccountDependenciesDAL.countByAccountIds(permittedAccountIds) : {};
-
- return {
- accounts: decryptedAndPermittedAccounts.map((a) => ({
- ...a,
- metadata: metadataByAccountId[a.id] || [],
- dependencyCount: dependencyCountMap[a.id] || 0
- })),
- totalCount
- };
- };
-
- const getById = async ({ accountId, actor, actorId, actorAuthMethod, actorOrgId }: TGetAccountByIdDTO) => {
- const accountWithParent = await pamAccountDAL.findByIdWithParentDetails(accountId);
- if (!accountWithParent) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: accountWithParent.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds([accountWithParent.id]);
- const accountMetadata = metadataByAccountId[accountWithParent.id] || [];
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Read,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: accountWithParent.name,
- ...(accountWithParent.resource && {
- resourceName: accountWithParent.resource.name,
- resourceType: accountWithParent.resource.resourceType
- }),
- ...(accountWithParent.domain && {
- domainName: accountWithParent.domain.name,
- domainType: accountWithParent.domain.domainType
- }),
- metadata: accountMetadata
- })
- );
-
- const decryptedAccount = await decryptAccount(accountWithParent, accountWithParent.projectId, kmsService);
-
- return {
- ...decryptedAccount,
- ...formatAccountParent({
- resource: accountWithParent.resource,
- domain: accountWithParent.domain
- }),
- metadata: accountMetadata,
- requireReason: await resolveRequireReason(accountWithParent.policyId)
- };
- };
-
- const access = async (
- {
- resourceName: inputResourceName,
- accountName: inputAccountName,
- projectId,
- actorEmail,
- actorIp,
- actorName,
- actorUserAgent,
- duration,
- mfaSessionId,
- reason
- }: TAccessAccountDTO,
- actor: OrgServiceActor
- ) => {
- // Find resource by name
- const resource = await pamResourceDAL.findOne({ projectId, name: inputResourceName });
- if (!resource) {
- throw new NotFoundError({ message: `Resource with name '${inputResourceName}' not found` });
- }
-
- // Wire format for AD-domain accounts is `<fqdn>:<slug>` (e.g.
- // 'corp.example.com:administrator'). PAM slugs can't contain ':' so the
- // separator is unambiguous. Plain `<slug>` routes to the local bucket.
- const colonIdx = inputAccountName.indexOf(":");
- const isDomainAccount = colonIdx !== -1;
- const accountSlug = isDomainAccount ? inputAccountName.slice(colonIdx + 1) : inputAccountName;
- const fqdnHint = isDomainAccount ? inputAccountName.slice(0, colonIdx) : null;
-
- if (isDomainAccount && resource.resourceType !== PamResource.Windows) {
- throw new BadRequestError({
- message: `Domain account access is only supported for Windows resources`
- });
- }
-
- // accountIdentity is fed to the approval layer; the FQDN prefix on domain
- // accounts prevents a like-named local-account grant from matching.
- const lookupAccount = async () => {
- if (!isDomainAccount) {
- const localAccount = await pamAccountDAL.findOne({
- projectId,
- resourceId: resource.id,
- name: accountSlug
- });
- if (!localAccount) return null;
- return { account: localAccount, accountIdentity: localAccount.name };
- }
- if (!resource.domainId) {
- throw new BadRequestError({
- message: `Resource '${inputResourceName}' is not joined to a domain`
- });
- }
- const domain = await pamDomainDAL.findById(resource.domainId);
- if (!domain) {
- throw new NotFoundError({ message: `Domain with ID '${resource.domainId}' not found` });
- }
- const domainConn = await decryptDomainConnectionDetails({
- projectId,
- encryptedConnectionDetails: domain.encryptedConnectionDetails,
- kmsService
- });
- if (domainConn.domain.toLowerCase() !== fqdnHint?.toLowerCase()) {
- throw new BadRequestError({
- message: `Resource '${inputResourceName}' is not joined to '${fqdnHint}'`
- });
- }
- const domainAccount = await pamAccountDAL.findOne({
- projectId,
- domainId: resource.domainId,
- name: accountSlug
- });
- if (!domainAccount) return null;
- return { account: domainAccount, accountIdentity: `${domainConn.domain}:${domainAccount.name}` };
- };
- const lookup = await lookupAccount();
-
- if (!lookup) {
- throw new NotFoundError({
- message: `Account with name '${inputAccountName}' not found for resource '${inputResourceName}'`
- });
- }
- const { account, accountIdentity } = lookup;
-
- const trimmedReason = reason?.trim() || null;
-
- const fac = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.PamAccess](ApprovalPolicyType.PamAccess);
-
- const inputs = {
- resourceId: resource.id,
- resourceName: resource.name,
- accountName: accountIdentity
- };
-
- const activeGrant = await fac.canAccess(approvalRequestGrantsDAL, resource.projectId, actor.id, inputs);
-
- // Grant does not exist, check policy and fallback to permission check
- if (!activeGrant) {
- const policy = await fac.matchPolicy(approvalPolicyDAL, resource.projectId, inputs);
-
- if (policy) {
- throw new PolicyViolationError({
- message: "A policy is in place for this resource",
- details: {
- policyId: policy.id,
- policyName: policy.name,
- policyType: policy.type,
- constraints: {
- accessDuration: {
- max: (policy as TPamAccessPolicy).constraints.constraints.accessDuration.max
- }
- }
- }
- });
- }
-
- // If there isn't a policy in place, continue with checking permission
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: account.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const accountMeta = await pamAccountDAL.findMetadataByAccountIds([account.id]);
-
- // On Access, resourceName/resourceType match the connect-target (the
- // Windows host the credentials are used against), and for domain
- // accounts domainName/domainType additionally scope to the parent.
- // Other actions (create/read/update/delete) keep resourceName as the
- // account's parent, which is undefined for domain accounts.
- const domain = isDomainAccount && account.domainId ? await pamDomainDAL.findById(account.domainId) : null;
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Access,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: account.name,
- resourceName: resource.name,
- resourceType: resource.resourceType,
- ...(isDomainAccount && domain && { domainName: domain.name, domainType: domain.domainType }),
- metadata: accountMeta[account.id] || []
- })
- );
- }
-
- // Cap the requested duration to the grant's remaining lifetime
- let effectiveDuration = duration;
- if (activeGrant?.expiresAt) {
- const grantRemainingMs = activeGrant.expiresAt.getTime() - Date.now();
- if (grantRemainingMs <= 0) {
- throw new ForbiddenRequestError({ message: "Approval grant has expired" });
- }
- effectiveDuration = Math.min(duration, grantRemainingMs);
- }
-
- // Reason check is intentionally placed after the approval/permission gates so
- // its distinct error code does not leak policy configuration to unauthorized actors.
- if (account.policyId) {
- const policy = await pamAccountPolicyDAL.findById(account.policyId);
- const policyRules = (policy?.rules ?? {}) as TPolicyRules;
- if (policy?.isActive && policyRules[PamAccountPolicyRuleType.RequireReason] && !trimmedReason) {
- throw new BadRequestError({
- message: "A reason is required to access this account",
- name: "PAM_REASON_REQUIRED"
- });
- }
- }
-
- const actorUser = await requestMemoize(requestMemoKeys.userFindById(actor.id), () => userDAL.findById(actor.id));
- if (!actorUser) throw new NotFoundError({ message: `User with ID '${actor.id}' not found` });
-
- // If no mfaSessionId is provided, create a new MFA session
- if (!mfaSessionId && account.requireMfa) {
- const project = await requestMemoize(requestMemoKeys.projectFindById(account.projectId), () =>
- projectDAL.findById(account.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${account.projectId}' not found` });
- const org = await requestMemoize(requestMemoKeys.orgFindOrgById(project.orgId), () =>
- orgDAL.findOrgById(project.orgId)
- );
- if (!org) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });
-
- // Determine which MFA method to use
- // Priority: org-enforced > user-selected > email as fallback
- const orgMfaMethod = org.enforceMfa ? (org.selectedMfaMethod as MfaMethod | null) : undefined;
- const userMfaMethod = actorUser.isMfaEnabled ? (actorUser.selectedMfaMethod as MfaMethod | null) : undefined;
- const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
-
- // Create MFA session
- const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, account.id, mfaMethod);
-
- // If MFA method is email, send the code immediately
- if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
- await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
- }
-
- // Throw an error with the mfaSessionId to signal that MFA is required
- throw new BadRequestError({
- message: "MFA verification required to access PAM account",
- name: "SESSION_MFA_REQUIRED",
- details: {
- mfaSessionId: newMfaSessionId,
- mfaMethod
- }
- });
- }
-
- if (mfaSessionId && account.requireMfa) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (!mfaSession) {
- throw new BadRequestError({
- message: "MFA session not found or expired"
- });
- }
-
- // Verify the session belongs to the current user
- if (mfaSession.userId !== actor.id) {
- throw new BadRequestError({
- message: "MFA session does not belong to current user"
- });
- }
-
- // Verify the session is for the same account
- if (mfaSession.resourceId !== account.id) {
- throw new BadRequestError({
- message: "MFA session is for a different account"
- });
- }
-
- // Check if MFA session is active
- if (mfaSession.status !== MfaSessionStatus.ACTIVE) {
- throw new BadRequestError({
- message: "MFA session is not active. Please complete MFA verification first."
- });
- }
-
- // MFA verified successfully, delete the session and proceed with access
- await mfaSessionService.deleteMfaSession(mfaSessionId);
- }
-
- const decryptedResource = await decryptResource(resource, account.projectId, kmsService);
- const { connectionDetails, resourceType } = decryptedResource;
- const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: decryptedResource.gatewayId,
- gatewayPoolId: decryptedResource.gatewayPoolId
- });
-
- if (resourceType === PamResource.Windows) {
- const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(account.projectId);
- if (!recordingConfig || recordingConfig.storageBackend === PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message:
- "Windows resources require an external (S3) session recording configuration. Postgres storage is not supported for RDP sessions. Configure an S3 bucket in project settings before accessing Windows accounts."
- });
- }
- }
-
- const user = await requestMemoize(requestMemoKeys.userFindById(actor.id), () => userDAL.findById(actor.id));
- if (!user) throw new NotFoundError({ message: `User with ID '${actor.id}' not found` });
-
- if (resourceType === PamResource.AwsIam) {
- const awsCredentials = (await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- kmsService,
- projectId: account.projectId
- })) as TAwsIamAccountCredentials;
-
- let sessionDuration = awsCredentials.defaultSessionDuration;
- if (activeGrant?.expiresAt) {
- const grantRemainingSeconds = Math.floor((activeGrant.expiresAt.getTime() - Date.now()) / 1000);
- // STS rejects DurationSeconds below the floor, so a grant shorter than that can't be honored
- if (grantRemainingSeconds < AWS_STS_MIN_DURATION_SECONDS) {
- throw new ForbiddenRequestError({
- message: "Approval grant has insufficient remaining time for an AWS IAM session"
- });
- }
- sessionDuration = Math.min(sessionDuration, grantRemainingSeconds);
- }
-
- const credentials = await generateAwsIamSessionCredentials({
- connectionDetails,
- targetRoleArn: awsCredentials.targetRoleArn,
- roleSessionName: actorEmail,
- projectId: account.projectId, // Use project ID as External ID for security
- sessionDuration
- });
-
- const session = await pamSessionDAL.create({
- accountName: account.name,
- actorEmail,
- actorIp,
- actorName,
- actorUserAgent,
- projectId: account.projectId,
- resourceName: resource.name,
- resourceType: resource.resourceType,
- status: PamSessionStatus.Active, // AWS IAM sessions are immediately active
- accountId: account.id,
- resourceId: resource.id,
- userId: actor.id,
- expiresAt: credentials.expiresAt,
- startedAt: new Date(),
- reason: trimmedReason
- });
-
- // Cache the AccessKeyId so /aws-console-url can verify the caller is
- // submitting credentials that actually belong to this session
- const ttlSeconds = Math.max(1, Math.floor((credentials.expiresAt.getTime() - Date.now()) / 1000));
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.PamAwsIamAccessKeyId(session.id),
- ttlSeconds,
- credentials.accessKeyId
- );
-
- // Schedule session expiration job to run at expiresAt
- await pamSessionExpirationService.scheduleSessionExpiration(session.id, credentials.expiresAt);
-
- return {
- sessionId: session.id,
- resourceType,
- account,
- accessKeyId: credentials.accessKeyId,
- secretAccessKey: credentials.secretAccessKey,
- sessionToken: credentials.sessionToken,
- expiresAt: credentials.expiresAt.toISOString(),
- metadata: {
- awsAccountId: extractAwsAccountIdFromArn(connectionDetails.roleArn),
- targetRoleArn: awsCredentials.targetRoleArn,
- federatedUsername: actorEmail
- }
- };
- }
-
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required for this resource type" });
- }
-
- const session = await pamSessionDAL.create({
- accountName: account.name,
- actorEmail,
- actorIp,
- actorName,
- actorUserAgent,
- projectId,
- resourceName: resource.name,
- resourceType: resource.resourceType,
- status: PamSessionStatus.Starting,
- accountId: account.id,
- resourceId: isDomainAccount ? null : resource.id,
- selectedResourceId: isDomainAccount ? resource.id : null,
- userId: actor.id,
- gatewayId,
- expiresAt: new Date(Date.now() + effectiveDuration),
- reason: trimmedReason
- });
-
- const { host, port } = (() => {
- if (resourceType === PamResource.Kubernetes) {
- const url = new URL(connectionDetails.url);
- let portNumber: number | undefined;
- if (url.port) {
- portNumber = Number(url.port);
- } else {
- portNumber = url.protocol === "https:" ? 443 : 80;
- }
- return { host: url.hostname, port: portNumber };
- }
-
- if (resourceType === PamResource.MongoDB) {
- const parsed = parseMongoConnectionString(connectionDetails.connectionString);
- return { host: parsed.hostname, port: parsed.port };
- }
-
- return connectionDetails as { host: string; port: number };
- })();
-
- const gatewayConnectionDetails = await gatewayV2Service.getPAMConnectionDetails({
- gatewayId,
- duration: effectiveDuration,
- sessionId: session.id,
- resourceType: resource.resourceType as PamResource,
- host,
- port,
- actorMetadata: {
- id: actor.id,
- type: actor.type,
- name: user.email ?? ""
- }
- });
-
- if (!gatewayConnectionDetails) {
- throw new NotFoundError({ message: `Gateway connection details for gateway '${gatewayId}' not found.` });
- }
-
- let metadata;
-
- switch (resourceType) {
- case PamResource.Postgres:
- case PamResource.MySQL:
- case PamResource.MsSQL:
- case PamResource.OracleDB:
- case PamResource.MongoDB:
- {
- const connectionCredentials = (await decryptResourceConnectionDetails({
- encryptedConnectionDetails: resource.encryptedConnectionDetails,
- kmsService,
- projectId
- })) as TSqlResourceConnectionDetails;
-
- const credentials = (await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- kmsService,
- projectId
- })) as TSqlAccountCredentials;
-
- metadata = {
- username: credentials.username,
- database: connectionCredentials.database,
- accountName: account.name,
- resourceName: resource.name
- };
- }
- break;
- case PamResource.Redis:
- {
- const credentials = (await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- kmsService,
- projectId
- })) as TRedisAccountCredentials;
-
- metadata = {
- username: credentials.username,
- accountName: account.name,
- resourceName: resource.name
- };
- }
- break;
- case PamResource.SSH:
- {
- const credentials = (await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- kmsService,
- projectId
- })) as TSSHAccountCredentials;
-
- metadata = {
- username: credentials.username
- };
- }
- break;
- case PamResource.Windows:
- {
- const credentials = (await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- kmsService,
- projectId
- })) as TWindowsAccountCredentials;
-
- metadata = {
- username: credentials.username
- };
- }
- break;
- case PamResource.Kubernetes:
- metadata = {
- resourceName: resource.name,
- accountName: account.name
- };
- break;
- default:
- break;
- }
-
- return {
- sessionId: session.id,
- resourceType,
- relayClientCertificate: gatewayConnectionDetails.relay.clientCertificate,
- relayClientPrivateKey: gatewayConnectionDetails.relay.clientPrivateKey,
- relayServerCertificateChain: gatewayConnectionDetails.relay.serverCertificateChain,
- gatewayClientCertificate: gatewayConnectionDetails.gateway.clientCertificate,
- gatewayClientPrivateKey: gatewayConnectionDetails.gateway.clientPrivateKey,
- gatewayServerCertificateChain: gatewayConnectionDetails.gateway.serverCertificateChain,
- relayHost: gatewayConnectionDetails.relayHost,
- projectId,
- account,
- metadata
- };
- };
-
- const getAwsIamConsoleUrl = async (
- {
- sessionId,
- projectId,
- accessKeyId,
- secretAccessKey,
- sessionToken
- }: {
- sessionId: string;
- projectId: string;
- accessKeyId: string;
- secretAccessKey: string;
- sessionToken: string;
- },
- actor: OrgServiceActor
- ) => {
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- if (session.projectId !== projectId) {
- throw new ForbiddenRequestError({ message: "Session does not belong to the specified project" });
- }
-
- if (session.userId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Session does not belong to the current user" });
- }
-
- if (session.resourceType !== PamResource.AwsIam) {
- throw new BadRequestError({ message: "Session is not an AWS IAM session" });
- }
-
- if (session.endedAt || (session.expiresAt && session.expiresAt < new Date())) {
- throw new BadRequestError({ message: "Session has ended or expired" });
- }
-
- // Confirm the submitted creds actually belong to this session by comparing
- // against the AccessKeyId we stashed at /access time
- const expectedAccessKeyId = await keyStore.getItem(KeyStorePrefixes.PamAwsIamAccessKeyId(sessionId));
- if (!expectedAccessKeyId) {
- throw new BadRequestError({
- message: "Session credentials are no longer available. Please re-access the account."
- });
- }
- if (expectedAccessKeyId !== accessKeyId) {
- throw new ForbiddenRequestError({
- message: "Submitted credentials do not match the session"
- });
- }
-
- const consoleUrl = await exchangeCredentialsForConsoleUrl({
- accessKeyId,
- secretAccessKey,
- sessionToken
- });
-
- return {
- consoleUrl,
- accountId: session.accountId,
- accountName: session.accountName,
- resourceName: session.resourceName
- };
- };
-
- const getSessionCredentials = async (sessionId: string, actor: OrgServiceActor) => {
- // To be hit by gateways only (identity-based or enrollment-flow)
- if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {
- throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
- }
-
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const project = await requestMemoize(requestMemoKeys.projectFindById(session.projectId), () =>
- projectDAL.findById(session.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });
-
- if (actor.type === ActorType.IDENTITY) {
- const { permission } = await permissionService.getOrgPermission({
- actor: actor.type,
- actorId: actor.id,
- orgId: project.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- scope: OrganizationActionScope.Any
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.CreateGateways,
- OrgPermissionSubjects.Gateway
- );
- } else if (actor.type === ActorType.GATEWAY) {
- if (project.orgId !== actor.orgId) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to this session" });
- }
- }
-
- if (!session.accountId) throw new NotFoundError({ message: "Session is missing accountId column" });
-
- // Verify that the session has not ended
- if (session.endedAt || (session.expiresAt && session.expiresAt < new Date())) {
- throw new BadRequestError({ message: "Session has ended or expired" });
- }
-
- const account = await pamAccountDAL.findById(session.accountId);
- if (!account) throw new NotFoundError({ message: `Account with ID '${session.accountId}' not found` });
-
- const resourceId = session.selectedResourceId ?? account.resourceId;
- if (!resourceId) {
- throw new NotFoundError({ message: `Session '${sessionId}' has no associated resource` });
- }
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- if (!session.gatewayId) {
- throw new BadRequestError({ message: "Session has no associated gateway" });
- }
- const authorized =
- actor.type === ActorType.GATEWAY ? session.gatewayId === actor.id : session.gatewayIdentityId === actor.id;
- if (!authorized) {
- throw new ForbiddenRequestError({
- message: "Gateway does not have access to fetch the PAM session credentials"
- });
- }
-
- const decryptedAccount = await decryptAccount(account, session.projectId, kmsService);
-
- const decryptedResource = await decryptResource(resource, session.projectId, kmsService);
-
- // Resolve policy rules for gateway
- const policyRules: TPolicyRules = {};
- if (account.policyId) {
- const policy = await pamAccountPolicyDAL.findById(account.policyId);
- if (policy && policy.isActive) {
- const rules = (policy.rules ?? {}) as TPolicyRules;
-
- const gatewayRuleTypes = [
- PamAccountPolicyRuleType.CommandBlocking,
- PamAccountPolicyRuleType.SessionLogMasking
- ] as const;
- for (const ruleType of gatewayRuleTypes) {
- const ruleConfig = rules[ruleType];
- const supported = PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES[ruleType];
- const isSupported = supported === "all" || supported.includes(resource.resourceType as PamResource);
- if (ruleConfig && isSupported) {
- policyRules[ruleType] = ruleConfig;
- }
- }
- }
- }
-
- let sessionStarted = false;
-
- // Recording secrets are lazily generated on the first /credentials call (status=Starting)
- // The upload token is returned exactly once; the gateway persists it to disk
- // On subsequent calls (status=Active), the session key and storage backend are re-derived so the gateway can resume chunk creation after a restart
- let sessionRecordingSecrets: {
- sessionKeyBase64: string;
- uploadTokenBase64: string;
- storageBackend: PamRecordingStorageBackend;
- } | null = null;
- if (session.status === PamSessionStatus.Starting) {
- const projectRecordingConfig = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId);
- const storageBackend = projectRecordingConfig?.backend ?? PamRecordingStorageBackend.Postgres;
-
- if (resource.resourceType === PamResource.Windows && storageBackend === PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message:
- "Windows (RDP) sessions require an external (S3) recording backend. Postgres storage is not supported for RDP recordings."
- });
- }
-
- const { sessionKey, uploadToken, encryptedSessionKey, uploadTokenHash } = await generateSessionRecordingSecrets({
- projectId: session.projectId,
- sessionId,
- kmsService
- });
-
- const started = await pamSessionDAL.startSession(sessionId, {
- encryptedSessionKey,
- gatewayUploadTokenHash: uploadTokenHash
- });
-
- if (started) {
- sessionStarted = true;
- sessionRecordingSecrets = {
- sessionKeyBase64: sessionKey.toString("base64"),
- uploadTokenBase64: uploadToken.toString("base64"),
- storageBackend
- };
- }
- } else if (session.status === PamSessionStatus.Active && session.encryptedSessionKey) {
- const projectRecordingConfig = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId);
- const storageBackend = projectRecordingConfig?.backend ?? PamRecordingStorageBackend.Postgres;
-
- if (resource.resourceType === PamResource.Windows && storageBackend === PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message:
- "Windows (RDP) sessions require an external (S3) recording backend. Postgres storage is not supported for RDP recordings."
- });
- }
-
- const sessionKey = await decryptSessionKey({
- projectId: session.projectId,
- sessionId,
- encryptedSessionKey: session.encryptedSessionKey,
- kmsService
- });
- sessionRecordingSecrets = {
- sessionKeyBase64: sessionKey.toString("base64"),
- uploadTokenBase64: "",
- storageBackend
- };
- }
-
- // Handle SSH certificate-based authentication
- if (decryptedResource.resourceType === PamResource.SSH) {
- const accountCredentials = decryptedAccount.credentials as TSSHAccountCredentials;
-
- if (accountCredentials.authMethod === SSHAuthMethod.Certificate) {
- if (!resource.encryptedResourceMetadata) {
- throw new BadRequestError({
- message: "SSH resource does not have a CA configured for certificate-based authentication"
- });
- }
-
- const metadata = await decryptResourceMetadata<TSSHResourceInternalMetadata>({
- encryptedMetadata: resource.encryptedResourceMetadata,
- projectId: session.projectId,
- kmsService
- });
-
- const { caPrivateKey, caKeyAlgorithm } = metadata;
-
- // Generate a new key pair for the user
- const keyAlgorithm = (caKeyAlgorithm as SshCertKeyAlgorithm) || SshCertKeyAlgorithm.ED25519;
- const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);
-
- // Calculate TTL from session expiry
- const ttlSeconds = Math.max(Math.floor((session.expiresAt.getTime() - Date.now()) / 1000), 60);
-
- // Sign the public key with the CA to create a certificate
- const { signedPublicKey } = await createSshCert({
- caPrivateKey,
- clientPublicKey: publicKey,
- keyId: `pam-session-${session.id}`,
- principals: [accountCredentials.username],
- requestedTtl: `${ttlSeconds}s`,
- certType: SshCertType.USER
- });
-
- return {
- credentials: {
- ...decryptedResource.connectionDetails,
- authMethod: SSHAuthMethod.Certificate,
- username: accountCredentials.username,
- privateKey,
- certificate: signedPublicKey
- },
- policyRules,
- projectId: project.id,
- account,
- sessionStarted,
- recording: sessionRecordingSecrets
- };
- }
- }
-
- if (decryptedResource.resourceType === PamResource.Windows) {
- const { hostname, ...rest } = decryptedResource.connectionDetails;
-
- // The bridge forwards `domain` to IronRDP for NTLM CredSSP against AD.
- let domainName: string | undefined;
- if (account.domainId) {
- const domain = await pamDomainDAL.findById(account.domainId);
- if (!domain) {
- throw new NotFoundError({ message: `Domain with ID '${account.domainId}' not found` });
- }
- const domainConnectionDetails = await decryptDomainConnectionDetails({
- projectId: session.projectId,
- encryptedConnectionDetails: domain.encryptedConnectionDetails,
- kmsService
- });
- domainName = domainConnectionDetails.domain;
- }
-
- return {
- credentials: {
- ...rest,
- host: hostname,
- ...decryptedAccount.credentials,
- ...(domainName ? { domain: domainName } : {})
- },
- policyRules,
- projectId: project.id,
- account,
- sessionStarted,
- recording: sessionRecordingSecrets
- };
- }
-
- const credentials: Record<string, unknown> = {
- ...decryptedResource.connectionDetails,
- ...decryptedAccount.credentials
- };
-
- // Old MSSQL accounts pre-date the authMethod field — default to sql-login
- if (decryptedResource.resourceType === PamResource.MsSQL && !("authMethod" in credentials)) {
- credentials.authMethod = MsSqlAuthMethod.SqlLogin;
- }
-
- return {
- credentials,
- policyRules,
- projectId: project.id,
- account,
- sessionStarted,
- recording: sessionRecordingSecrets
- };
- };
-
- // Find accounts due for rotation using rule-based matching
- const findAccountsDueForRotation = async () => {
- // Get only resources with rotation credentials configured
- const resourcesWithRotationCreds = await pamResourceDAL.find({
- $notNull: ["encryptedRotationAccountCredentials"]
- });
- if (!resourcesWithRotationCreds.length) return [];
-
- const resourceIds = resourcesWithRotationCreds.map((r) => r.id);
-
- const allRules = await pamResourceRotationRulesDAL.findByResourceIds(resourceIds);
- if (!allRules.length) return [];
-
- // Group rules by resource, compute minimum interval for DB pre-filter
- const rulesByResource: Record<string, typeof allRules> = {};
- let minIntervalSeconds = Infinity;
- for (const rule of allRules) {
- if (!rulesByResource[rule.resourceId]) rulesByResource[rule.resourceId] = [];
- rulesByResource[rule.resourceId].push(rule);
- if (rule.enabled && rule.intervalSeconds) {
- minIntervalSeconds = Math.min(minIntervalSeconds, rule.intervalSeconds);
- }
- }
-
- if (minIntervalSeconds === Infinity) return [];
-
- const resourceIdsWithRules = Object.keys(rulesByResource);
- const accounts = await pamAccountDAL.findRotationCandidates({
- resourceIds: resourceIdsWithRules,
- minIntervalSeconds
- });
-
- const now = Date.now();
- const dueAccounts: TPamAccounts[] = [];
-
- for (const account of accounts) {
- const rules = rulesByResource[account.resourceId!];
- // eslint-disable-next-line no-continue
- if (!rules) continue;
-
- // Find first matching rule by priority (already sorted by DAL)
- const matchedRule = rules.find((rule) => picomatch.isMatch(account.name, rule.namePattern));
-
- // eslint-disable-next-line no-continue
- if (!matchedRule || !matchedRule.enabled || !matchedRule.intervalSeconds) continue;
-
- // Check if interval has elapsed
- const lastRotated = account.lastRotatedAt
- ? new Date(account.lastRotatedAt).getTime()
- : account.createdAt.getTime();
-
- const nextRotationAt = lastRotated + matchedRule.intervalSeconds * 1000;
-
- // eslint-disable-next-line no-continue
- if (nextRotationAt > now) continue;
-
- dueAccounts.push(account);
- }
-
- return dueAccounts;
- };
-
- const rotateAccount = async (account: TPamAccounts) => {
- let logResourceType = "unknown";
- try {
- // Atomically claim rotation lock, only proceeds if not already rotating
- const claimed = await pamAccountDAL.transaction(async (tx) => {
- const updated = await tx(TableName.PamAccount)
- .where({ id: account.id })
- .where((qb) => {
- void qb.whereNull("rotationStatus").orWhereNot("rotationStatus", PamAccountRotationStatus.Rotating);
- })
- .update({ rotationStatus: PamAccountRotationStatus.Rotating })
- .returning("*");
- return updated[0];
- });
- if (!claimed) return;
-
- // Read resource
- const resource = await pamResourceDAL.findById(account.resourceId!);
- if (!resource || !resource.encryptedRotationAccountCredentials) {
- logger.warn(
- `[Rotation] Resource or rotation credentials missing for account [accountId=${account.id}], releasing lock`
- );
- await pamAccountDAL.updateById(account.id, { rotationStatus: PamAccountRotationStatus.Failed });
- return;
- }
- logResourceType = resource.resourceType;
-
- const decrypted = await decryptResource(resource, account.projectId, kmsService);
- const {
- connectionDetails,
- rotationAccountCredentials,
- gatewayId,
- gatewayPoolId: rotationGatewayPoolId,
- resourceType
- } = decrypted;
- if (!rotationAccountCredentials) {
- logger.warn(
- `[Rotation] Decrypted rotation credentials missing for account [accountId=${account.id}], releasing lock`
- );
- await pamAccountDAL.updateById(account.id, { rotationStatus: PamAccountRotationStatus.Failed });
- return;
- }
-
- // Perform rotation
- const accountCredentials = await decryptAccountCredentials({
- encryptedCredentials: account.encryptedCredentials,
- projectId: account.projectId,
- kmsService
- });
-
- // Prevent the rotation account from rotating its own password
- const rotationUsername = (rotationAccountCredentials as { username?: string })?.username;
- const accountUsername = (accountCredentials as { username?: string })?.username;
- if (rotationUsername && accountUsername && rotationUsername.toLowerCase() === accountUsername.toLowerCase()) {
- logger.warn(
- `[Rotation] Skipping rotation for account [accountId=${account.id}] — account is the rotation account itself`
- );
- const errorMsg = "This account cannot be rotated because it is used as the rotation credentials";
- try {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: account.projectId
- });
- const { cipherTextBlob: encryptedMessage } = encryptor({ plainText: Buffer.from(errorMsg) });
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.Failed,
- encryptedLastRotationMessage: encryptedMessage
- });
- } catch {
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.Failed
- });
- }
- return;
- }
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId,
- gatewayPoolId: rotationGatewayPoolId
- });
- const factory = PAM_RESOURCE_FACTORY_MAP[resourceType as PamResource](
- resourceType as PamResource,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- account.projectId
- );
- const newCredentials = await factory.rotateAccountCredentials(rotationAccountCredentials, accountCredentials);
-
- // Save result
- const encryptedCredentials = await encryptAccountCredentials({
- credentials: newCredentials,
- projectId: account.projectId,
- kmsService
- });
-
- await pamAccountDAL.updateById(account.id, {
- encryptedCredentials,
- lastRotatedAt: new Date(),
- rotationStatus: PamAccountRotationStatus.Success,
- encryptedLastRotationMessage: null
- });
-
- await auditLogService.createAuditLog({
- projectId: account.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION,
- metadata: {
- accountId: account.id,
- accountName: account.name,
- resourceId: resource.id,
- resourceType: logResourceType
- }
- }
- });
-
- // Run post-rotate hook (e.g. dependency sync)
- if (factory.postRotate) {
- try {
- await factory.postRotate(
- account.id,
- newCredentials,
- account.projectId,
- { pamAccountDependenciesDAL, pamResourceDAL, kmsService },
- rotationAccountCredentials
- );
- } catch (postRotateError) {
- // Password was rotated but dependency sync failed, mark as partial success
- const postRotateMsg = `Password rotated successfully, but dependency sync failed: ${postRotateError instanceof Error ? postRotateError.message : String(postRotateError)}`;
- logger.error(postRotateError, `Post-rotation hook failed for account [accountId=${account.id}]`);
- try {
- const { encryptor: postRotateEncryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: account.projectId
- });
- const { cipherTextBlob: encryptedPostRotateMsg } = postRotateEncryptor({
- plainText: Buffer.from(postRotateMsg)
- });
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.PartialSuccess,
- encryptedLastRotationMessage: encryptedPostRotateMsg
- });
- } catch (encryptErr) {
- logger.error(encryptErr, `Failed to store post-rotation warning for account [accountId=${account.id}]`);
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.PartialSuccess
- });
- }
- }
- }
- } catch (error) {
- logger.error(error, `Failed to rotate credentials for account [accountId=${account.id}]`);
-
- const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";
-
- try {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: account.projectId
- });
-
- const { cipherTextBlob: encryptedMessage } = encryptor({
- plainText: Buffer.from(errorMessage)
- });
-
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.Failed,
- encryptedLastRotationMessage: encryptedMessage
- });
- } catch (encryptErr) {
- logger.error(encryptErr, `Failed to encrypt rotation error for account [accountId=${account.id}]`);
- await pamAccountDAL.updateById(account.id, {
- rotationStatus: PamAccountRotationStatus.Failed
- });
- }
-
- try {
- await auditLogService.createAuditLog({
- projectId: account.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED,
- metadata: {
- accountId: account.id,
- accountName: account.name,
- resourceId: account.resourceId!,
- resourceType: logResourceType,
- errorMessage
- }
- }
- });
- } catch (auditErr) {
- logger.error(auditErr, `Failed to create audit log for rotation failure [accountId=${account.id}]`);
- }
- }
- };
-
- const rotateAllDueAccounts = async () => {
- const accounts = await findAccountsDueForRotation();
-
- for (let i = 0; i < accounts.length; i += ROTATION_CONCURRENCY_LIMIT) {
- const batch = accounts.slice(i, i + ROTATION_CONCURRENCY_LIMIT);
- // eslint-disable-next-line no-await-in-loop
- await Promise.all(batch.map(rotateAccount));
- }
- };
-
- const triggerManualRotation = async (accountId: string, actor: OrgServiceActor) => {
- const accountWithParent = await pamAccountDAL.findByIdWithParentDetails(accountId);
- if (!accountWithParent) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
- if (!accountWithParent.resource)
- throw new NotFoundError({ message: `Resource not found for account '${accountId}'` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: accountWithParent.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.TriggerRotation,
- subject(ProjectPermissionSub.PamAccounts, {
- resourceName: accountWithParent.resource.name,
- accountName: accountWithParent.name,
- resourceType: accountWithParent.resource.resourceType
- })
- );
-
- if (!accountWithParent.resource.encryptedRotationAccountCredentials) {
- throw new BadRequestError({ message: "Rotation credentials are not configured on this resource" });
- }
-
- // Immediate check. There's an actual atomic lock in rotateAccount
- if (accountWithParent.rotationStatus === PamAccountRotationStatus.Rotating) {
- throw new BadRequestError({ message: "Account is already being rotated" });
- }
-
- await rotateAccount(accountWithParent);
-
- const updatedAccountWithParent = await pamAccountDAL.findByIdWithParentDetails(accountId);
- if (!updatedAccountWithParent) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
- if (!updatedAccountWithParent.resource)
- throw new NotFoundError({ message: `Resource not found for account '${accountId}'` });
-
- const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds([updatedAccountWithParent.id]);
- const accountMetadata = metadataByAccountId[updatedAccountWithParent.id] || [];
-
- const decryptedAccount = await decryptAccount(
- updatedAccountWithParent,
- updatedAccountWithParent.projectId,
- kmsService
- );
-
- return {
- ...decryptedAccount,
- metadata: accountMetadata,
- ...formatAccountParent({
- resource: updatedAccountWithParent.resource,
- domain: null
- })
- };
- };
-
- const viewCredentials = async ({
- accountId,
- mfaSessionId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TViewAccountCredentialsDTO) => {
- const accountWithParent = await pamAccountDAL.findByIdWithParentDetails(accountId);
- if (!accountWithParent) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
- if (!accountWithParent.resource && !accountWithParent.domain)
- throw new NotFoundError({ message: `Parent not found for account '${accountId}'` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: accountWithParent.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds([accountWithParent.id]);
- const accountMetadata = metadataByAccountId[accountWithParent.id] || [];
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.ReadCredentials,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: accountWithParent.name,
- ...(accountWithParent.resource && {
- resourceName: accountWithParent.resource.name,
- resourceType: accountWithParent.resource.resourceType
- }),
- ...(accountWithParent.domain && {
- domainName: accountWithParent.domain.name,
- domainType: accountWithParent.domain.domainType
- }),
- metadata: accountMetadata
- })
- );
-
- const parentType = accountWithParent.resource?.resourceType || accountWithParent.domain?.domainType || "";
-
- const credentials = await decryptAccountCredentials({
- encryptedCredentials: accountWithParent.encryptedCredentials,
- kmsService,
- projectId: accountWithParent.projectId
- });
-
- if (!hasSensitiveCredentials(parentType, credentials)) {
- throw new BadRequestError({ message: "This account has no sensitive credentials to view" });
- }
-
- if (!mfaSessionId && accountWithParent.requireMfa) {
- // actorOrgId equals project.orgId: getProjectPermission above guarantees project existence
- // and org membership, so no separate project lookup is needed to resolve the org ID.
- const actorUser = await requestMemoize(requestMemoKeys.userFindById(actorId), () => userDAL.findById(actorId));
- if (!actorUser) throw new NotFoundError({ message: `User with ID '${actorId}' not found` });
-
- const org = await requestMemoize(requestMemoKeys.orgFindOrgById(actorOrgId), () =>
- orgDAL.findOrgById(actorOrgId)
- );
- if (!org) throw new NotFoundError({ message: `Organization with ID '${actorOrgId}' not found` });
-
- const orgMfaMethod = org.enforceMfa ? (org.selectedMfaMethod as MfaMethod | null) : undefined;
- const userMfaMethod = actorUser.isMfaEnabled ? (actorUser.selectedMfaMethod as MfaMethod | null) : undefined;
- const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
-
- const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, accountWithParent.id, mfaMethod);
-
- if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
- await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
- }
-
- throw new BadRequestError({
- message: "MFA verification required to view PAM account credentials",
- name: "SESSION_MFA_REQUIRED",
- details: {
- mfaSessionId: newMfaSessionId,
- mfaMethod
- }
- });
- }
-
- if (mfaSessionId && accountWithParent.requireMfa) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (!mfaSession) {
- throw new BadRequestError({ message: "MFA session not found or expired" });
- }
-
- if (mfaSession.userId !== actorId) {
- throw new BadRequestError({ message: "MFA session does not belong to current user" });
- }
-
- if (mfaSession.resourceId !== accountWithParent.id) {
- throw new BadRequestError({ message: "MFA session is for a different account" });
- }
-
- if (mfaSession.status !== MfaSessionStatus.ACTIVE) {
- throw new BadRequestError({ message: "MFA session is not active. Please complete MFA verification first." });
- }
-
- await mfaSessionService.deleteMfaSession(mfaSessionId);
- }
-
- return {
- credentials,
- parentType,
- accountId: accountWithParent.id,
- accountName: accountWithParent.name,
- projectId: accountWithParent.projectId,
- resource: accountWithParent.resource
- ? {
- id: accountWithParent.resource.id,
- name: accountWithParent.resource.name,
- resourceType: accountWithParent.resource.resourceType
- }
- : null,
- domain: accountWithParent.domain
- ? {
- id: accountWithParent.domain.id,
- name: accountWithParent.domain.name,
- domainType: accountWithParent.domain.domainType
- }
- : null
- };
- };
-
- return {
- create,
- updateById,
- deleteById,
- list,
- getById,
- access,
- getAwsIamConsoleUrl,
- viewCredentials,
- getSessionCredentials,
- rotateAllDueAccounts,
- triggerManualRotation
- };
-};
diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts
deleted file mode 100644
index b61e83f908..0000000000
--- a/backend/src/ee/services/pam-account/pam-account-types.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { z } from "zod";
-
-import { OrderByDirection, TProjectPermission } from "@app/lib/types";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-import { TPamAccount } from "../pam-resource/pam-resource-types";
-import { PamAccountOrderBy, PamAccountView } from "./pam-account-enums";
-
-// DTOs
-export type TCreateAccountDTO = Pick<
- TPamAccount,
- "name" | "description" | "credentials" | "folderId" | "requireMfa"
-> & {
- resourceId?: string;
- domainId?: string;
- internalMetadata?: Record<string, unknown>;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
- policyId?: string | null;
-};
-
-export type TUpdateAccountDTO = Partial<Omit<TCreateAccountDTO, "folderId" | "resourceId">> & {
- accountId: string;
-};
-
-export type TAccessAccountDTO = {
- resourceName: string;
- accountName: string;
- projectId: string;
- actorEmail: string;
- actorIp: string;
- actorName: string;
- actorUserAgent: string;
- duration: number;
- mfaSessionId?: string;
- reason?: string;
-};
-
-export type TListAccountsDTO = {
- accountView: PamAccountView;
- search?: string;
- orderBy?: PamAccountOrderBy;
- orderDirection?: OrderByDirection;
- limit?: number;
- offset?: number;
- filterResourceIds?: string[];
- filterDomainIds?: string[];
- metadataFilter?: Array<{ key: string; value?: string }>;
-} & TProjectPermission;
-
-export type TGetAccountByIdDTO = {
- accountId: string;
-} & Omit<TProjectPermission, "projectId">;
-
-export type TViewAccountCredentialsDTO = {
- accountId: string;
- mfaSessionId?: string;
-} & Omit<TProjectPermission, "projectId">;
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
deleted file mode 100644
index 1c10fb4725..0000000000
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ /dev/null
@@ -1,1388 +0,0 @@
-import net from "node:net";
-
-import ldapjs from "@infisical/ldapjs";
-import { Knex } from "knex";
-import RE2 from "re2";
-import { runPowershell } from "winrm-client";
-
-import { TPamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";
-import { TPamDiscoveryScanDeps } from "@app/ee/services/pam-discovery/pam-discovery-factory";
-import { TPamDiscoverySourceDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dependencies-dal";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { TPamAccountDALFactory } from "../../pam-account/pam-account-dal";
-import { encryptAccountCredentials } from "../../pam-account/pam-account-fns";
-import {
- TActiveDirectoryAccountCredentials,
- TActiveDirectoryAccountInternalMetadata
-} from "../../pam-domain/active-directory/active-directory-domain-types";
-import { TPamDomainDALFactory } from "../../pam-domain/pam-domain-dal";
-import { PamDomainType } from "../../pam-domain/pam-domain-enums";
-import { encryptDomainConnectionDetails } from "../../pam-domain/pam-domain-fns";
-import { TPamResourceDALFactory } from "../../pam-resource/pam-resource-dal";
-import { PamResource } from "../../pam-resource/pam-resource-enums";
-import { encryptResourceConnectionDetails, encryptResourceInternalMetadata } from "../../pam-resource/pam-resource-fns";
-import { resolveDnsTcp } from "../../pam-resource/shared/dns-over-dc";
-import { WindowsAccountType, WindowsProtocol } from "../../pam-resource/windows-server/windows-server-resource-enums";
-import {
- TWindowsAccountCredentials,
- TWindowsAccountMetadata,
- TWindowsResourceConnectionDetails,
- TWindowsResourceInternalMetadata
-} from "../../pam-resource/windows-server/windows-server-resource-types";
-import {
- PamAccountDependencySource,
- PamAccountDependencyType,
- PamDiscoverySourceRunStatus,
- PamDiscoverySourceRunTrigger,
- PamDiscoveryStepStatus
-} from "../pam-discovery-enums";
-import { TPamDiscoveryFactory } from "../pam-discovery-types";
-import { DEPENDENCY_ENUMERATION_SCRIPT } from "./active-directory-discovery-scripts";
-import {
- TActiveDirectoryDiscoverySourceConfiguration as TAdDiscoveryConfiguration,
- TActiveDirectoryDiscoverySourceCredentials as TAdDiscoveryCredentials,
- TActiveDirectoryDiscoverySourceRunProgress
-} from "./active-directory-discovery-types";
-
-const LDAP_TIMEOUT = 30 * 1000;
-const LDAP_PAGE_SIZE = 500;
-const SERVICE_ACCOUNT_PATTERNS = [new RE2(/^svc[_-]/i), new RE2(/[_-]service$/i), new RE2(/[_-]svc$/i)];
-const BUILTIN_SERVICE_ACCOUNTS = new Set([
- "localsystem",
- "nt authority\\localservice",
- "nt authority\\networkservice",
- "nt authority\\system"
-]);
-
-type TWinRmLocalUser = {
- Name: string;
- Enabled: boolean;
- LastLogon: string | null;
- PasswordLastSet: string | null;
- Description: string;
- SID: { Value: string };
-};
-
-type TWinRmService = {
- Name: string;
- DisplayName: string;
- State: string;
- StartMode: string;
- StartName: string;
- ProcessId: number | null;
- PathName: string | null;
- Description: string | null;
-};
-
-type TWinRmScheduledTask = {
- TaskName: string;
- TaskPath: string;
- State: string;
- UserId: string;
- LogonType: string;
- RunLevel: string;
- LastRunTime: string | null;
- NextRunTime: string | null;
- LastTaskResult: number | null;
- Triggers: TWinRmTaskTrigger[] | null;
- Actions: TWinRmTaskAction[] | null;
-};
-
-type TWinRmTaskTrigger = {
- Type: string;
- StartBoundary: string | null;
- Interval: number | null;
-};
-
-type TWinRmTaskAction = {
- Type: string;
- Execute: string | null;
- Arguments: string | null;
-};
-
-type TWinRmIisAppPool = {
- Name: string;
- State: string;
- IdentityType: string;
- Username: string;
- ManagedRuntimeVersion: string | null;
- ManagedPipelineMode: string | null;
- AutoStart: boolean | null;
-};
-
-type TWinRmDependencies = {
- services: TWinRmService[];
- scheduledTasks: TWinRmScheduledTask[];
- iisAppPools: TWinRmIisAppPool[];
-};
-
-type TLdapComputer = {
- cn: string;
- dNSHostName: string;
- operatingSystem: string;
- operatingSystemVersion: string;
- objectGUID: string;
- whenChanged: string;
- resolvedIp?: string;
-};
-
-type TLdapUser = {
- sAMAccountName: string;
- userPrincipalName: string;
- objectGUID: string;
- displayName: string;
- servicePrincipalName: string | string[];
- memberOf: string | string[];
- pwdLastSet: string;
- userAccountControl: string;
- lastLogonTimestamp: string;
- whenChanged: string;
-};
-
-const isServiceAccount = (user: TLdapUser): boolean => {
- const spn = user.servicePrincipalName;
- if (spn && (typeof spn === "string" ? spn.length > 0 : spn.length > 0)) {
- return true;
- }
- const name = user.sAMAccountName || "";
- if (SERVICE_ACCOUNT_PATTERNS.some((pattern) => pattern.test(name))) {
- return true;
- }
- return false;
-};
-
-const toSlugName = (name: string): string =>
- name
- .toLowerCase()
- .replace(new RE2(/[^a-z0-9-]/g), "-")
- .replace(new RE2(/-+/g), "-")
- .replace(new RE2(/^-|-$/g), "");
-
-// Parses .NET JSON date format `/Date(ms)/` to ISO 8601 string
-const parseDotNetDate = (value: string | null): string | undefined => {
- if (!value) return undefined;
- const match = new RE2(/^\/Date\((\d+)\)\/$/).exec(value);
- if (!match) return undefined;
- return new Date(Number(match[1])).toISOString();
-};
-
-// Converts a Windows FILETIME string (100-ns intervals since 1601-01-01) to ISO 8601 string
-const fileTimeToIso = (filetime: string | undefined): string | undefined => {
- if (!filetime) return undefined;
- try {
- const value = BigInt(filetime);
- if (value === 0n) return undefined;
- const epochDiffMs = 11644473600000n;
- const ms = value / 10000n - epochDiffMs;
- return new Date(Number(ms)).toISOString();
- } catch {
- return undefined;
- }
-};
-
-const buildDomainDN = (domainFQDN: string): string => {
- return domainFQDN
- .split(".")
- .map((part) => `DC=${part}`)
- .join(",");
-};
-
-const parseObjectGUID = (buf: Buffer | undefined): string => {
- if (buf && buf.length === 16) {
- const hex = buf.toString("hex");
- return [
- hex.substring(6, 8) + hex.substring(4, 6) + hex.substring(2, 4) + hex.substring(0, 2),
- hex.substring(10, 12) + hex.substring(8, 10),
- hex.substring(14, 16) + hex.substring(12, 14),
- hex.substring(16, 20),
- hex.substring(20, 32)
- ].join("-");
- }
- return "";
-};
-
-const ldapSearch = async (
- client: ldapjs.Client,
- baseDN: string,
- filter: string,
- attributes: string[]
-): Promise<ldapjs.SearchEntry[]> => {
- return new Promise((resolve, reject) => {
- const results: ldapjs.SearchEntry[] = [];
-
- client.search(
- baseDN,
- {
- filter,
- scope: "sub",
- attributes,
- paged: { pageSize: LDAP_PAGE_SIZE },
- timeLimit: LDAP_TIMEOUT / 1000
- },
- (err, searchRes) => {
- if (err) {
- reject(err);
- return;
- }
-
- searchRes.on("searchEntry", (entry) => {
- results.push(entry);
- });
-
- searchRes.on("error", (searchErr) => {
- reject(searchErr);
- });
-
- searchRes.on("end", (result) => {
- if (result?.status !== 0) {
- reject(new Error(`LDAP search failed with status ${result?.status}`));
- } else {
- resolve(results);
- }
- });
- }
- );
- });
-};
-
-const executeWithGateway = async <T>(
- config: {
- dcAddress: string;
- port: number;
- gatewayId: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (proxyPort: number) => Promise<T>
-): Promise<T> => {
- const { dcAddress, port, gatewayId } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: dcAddress,
- isGateway: true,
- isDynamicSecret: false
- });
-
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- return operation(proxyPort);
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-// Resolve AD hostnames to IP addresses by querying DNS over TCP through the DC
-const resolveHostnamesViaDc = async (
- computers: TLdapComputer[],
- configuration: TAdDiscoveryConfiguration,
- gatewayId: string,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
-): Promise<void> => {
- await executeWithGateway(
- { dcAddress: configuration.dcAddress, port: 53, gatewayId },
- gatewayV2Service,
- async (proxyPort) => {
- // Resolve each hostname sequentially to avoid overwhelming the proxy
- // eslint-disable-next-line no-await-in-loop
- for (const computer of computers) {
- const hostname = computer.dNSHostName || computer.cn;
- if (!hostname) {
- // skip computers without a hostname
- } else if (net.isIP(hostname)) {
- computer.resolvedIp = hostname;
- } else {
- try {
- // eslint-disable-next-line no-await-in-loop
- const ip = await resolveDnsTcp(hostname, proxyPort);
- if (ip) {
- computer.resolvedIp = ip;
- } else {
- logger.warn(`DNS resolution returned no A records [hostname=${hostname}]`);
- }
- } catch (err) {
- logger.warn(err, `Failed to resolve hostname via DC DNS [hostname=${hostname}]`);
- }
- }
- }
- }
- );
-};
-
-type TLdapAttribute = { type: string; values: string[]; buffers: Buffer[] };
-
-const getAttr = (entry: ldapjs.SearchEntry, attrName: string): string => {
- const attr = (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
- (a) => a.type.toLowerCase() === attrName.toLowerCase()
- );
- return attr?.values?.[0] ?? "";
-};
-
-const getAttrBuffer = (entry: ldapjs.SearchEntry, attrName: string): Buffer | undefined => {
- const attr = (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
- (a) => a.type.toLowerCase() === attrName.toLowerCase()
- );
- return attr?.buffers?.[0];
-};
-
-const getAttrAll = (entry: ldapjs.SearchEntry, attrName: string): string[] => {
- const attr = (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
- (a) => a.type.toLowerCase() === attrName.toLowerCase()
- );
- return attr?.values ?? [];
-};
-
-const executeLdapEnumeration = async (
- configuration: TAdDiscoveryConfiguration,
- credentials: TAdDiscoveryCredentials,
- gatewayId: string,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
-): Promise<{ computers: TLdapComputer[]; users: TLdapUser[] }> => {
- const ldapProtocol = configuration.useLdaps ? "ldaps" : "ldap";
-
- return executeWithGateway(
- { dcAddress: configuration.dcAddress, port: configuration.ldapPort, gatewayId },
- gatewayV2Service,
- async (proxyPort) => {
- const client = ldapjs.createClient({
- url: `${ldapProtocol}://localhost:${proxyPort}`,
- connectTimeout: LDAP_TIMEOUT,
- timeout: LDAP_TIMEOUT,
- ...(configuration.useLdaps && {
- tlsOptions: {
- rejectUnauthorized: configuration.ldapRejectUnauthorized,
- ...(configuration.ldapCaCert && {
- ca: [configuration.ldapCaCert],
- servername: configuration.ldapTlsServerName || configuration.dcAddress
- })
- }
- })
- });
-
- // Capture TLS/connection errors that fire before or during bind
- // Without this handler, unhandled 'error' events (e.g. TLS cert mismatch) crash the Node.js process
- let clientError: Error | null = null;
- client.on("error", (err: Error) => {
- clientError = err;
- });
-
- try {
- const bindDn = `${credentials.username}@${configuration.domainFQDN}`;
- await new Promise<void>((resolve, reject) => {
- client.bind(bindDn, credentials.password, (err) => {
- if (clientError) reject(clientError);
- else if (err) reject(new Error(`LDAP bind failed: ${err.message}`));
- else resolve();
- });
- });
-
- const baseDN = buildDomainDN(configuration.domainFQDN);
-
- const computerEntries = await ldapSearch(
- client,
- baseDN,
- "(&(objectClass=computer)(operatingSystem=*Server*))",
- ["cn", "dNSHostName", "operatingSystem", "operatingSystemVersion", "objectGUID", "whenChanged"]
- );
-
- const computers: TLdapComputer[] = computerEntries.map((entry) => ({
- cn: getAttr(entry, "cn"),
- dNSHostName: getAttr(entry, "dNSHostName"),
- operatingSystem: getAttr(entry, "operatingSystem"),
- operatingSystemVersion: getAttr(entry, "operatingSystemVersion"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID")),
- whenChanged: getAttr(entry, "whenChanged")
- }));
-
- const userEntries = await ldapSearch(client, baseDN, "(&(objectClass=user)(objectCategory=person))", [
- "sAMAccountName",
- "userPrincipalName",
- "objectGUID",
- "displayName",
- "servicePrincipalName",
- "memberOf",
- "pwdLastSet",
- "userAccountControl",
- "lastLogonTimestamp",
- "whenChanged"
- ]);
-
- const users: TLdapUser[] = userEntries.map((entry) => ({
- sAMAccountName: getAttr(entry, "sAMAccountName"),
- userPrincipalName: getAttr(entry, "userPrincipalName"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID")),
- displayName: getAttr(entry, "displayName"),
- servicePrincipalName: getAttrAll(entry, "servicePrincipalName"),
- memberOf: getAttrAll(entry, "memberOf"),
- pwdLastSet: getAttr(entry, "pwdLastSet"),
- userAccountControl: getAttr(entry, "userAccountControl"),
- lastLogonTimestamp: getAttr(entry, "lastLogonTimestamp"),
- whenChanged: getAttr(entry, "whenChanged")
- }));
-
- logger.info(
- `PAM AD discovery LDAP enumeration completed [computerCount=${computers.length}] [userCount=${users.length}]`
- );
-
- return { computers, users };
- } finally {
- try {
- client.unbind();
- } catch {
- // client may already be destroyed from a TLS/connection error
- }
- }
- }
- );
-};
-
-const upsertDomain = async (
- projectId: string,
- configuration: TAdDiscoveryConfiguration,
- gatewayId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- pamDomainDAL: Pick<TPamDomainDALFactory, "create" | "find">,
- tx: Knex,
- gatewayPoolId?: string | null
-) => {
- const fingerprint = configuration.domainFQDN.toLowerCase();
-
- const existing = await pamDomainDAL.find(
- {
- projectId,
- domainType: PamDomainType.ActiveDirectory,
- discoveryFingerprint: fingerprint
- },
- { tx }
- );
-
- if (existing.length > 0) {
- return { domain: existing[0], isNew: false };
- }
-
- const domainResourceName = toSlugName(configuration.domainFQDN);
-
- const encryptedConnectionDetails = await encryptDomainConnectionDetails({
- projectId,
- connectionDetails: {
- domain: configuration.domainFQDN,
- dcAddress: configuration.dcAddress,
- port: configuration.ldapPort,
- useLdaps: configuration.useLdaps,
- ldapRejectUnauthorized: configuration.ldapRejectUnauthorized,
- ldapCaCert: configuration.ldapCaCert,
- ldapTlsServerName: configuration.ldapTlsServerName
- },
- kmsService
- });
-
- const domain = await pamDomainDAL.create(
- {
- projectId,
- name: domainResourceName,
- domainType: PamDomainType.ActiveDirectory,
- gatewayId: gatewayPoolId ? null : gatewayId,
- gatewayPoolId: gatewayPoolId ?? null,
- encryptedConnectionDetails,
- discoveryFingerprint: fingerprint
- },
- tx
- );
-
- return { domain, isNew: true };
-};
-
-const upsertWindowsServerResource = async (
- projectId: string,
- computer: TLdapComputer,
- domainId: string,
- domainFQDN: string,
- gatewayId: string,
- gatewayPoolId: string | null | undefined,
- winrmConfig: {
- winrmPort: number;
- useWinrmHttps: boolean;
- winrmRejectUnauthorized: boolean;
- winrmCaCert?: string;
- },
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- pamResourceDAL: Pick<TPamResourceDALFactory, "create" | "find" | "updateById">,
- tx: Knex
-) => {
- const fingerprint = `${domainFQDN.toLowerCase()}:${computer.objectGUID}`;
-
- const existing = await pamResourceDAL.find(
- {
- projectId,
- resourceType: PamResource.Windows,
- discoveryFingerprint: fingerprint
- },
- { tx }
- );
-
- if (existing.length > 0) {
- const found = existing[0];
-
- // Reconnect if the resource was orphaned (e.g. the domain was previously deleted)
- if (!found.domainId) {
- const reconnected = await pamResourceDAL.updateById(found.id, { domainId }, tx);
- return { resource: reconnected, isNew: false };
- }
- return { resource: found, isNew: false };
- }
-
- const hostname = computer.dNSHostName || computer.cn;
- const resourceName = toSlugName(hostname);
-
- const [encryptedConnectionDetails, encryptedResourceMetadata] = await Promise.all([
- encryptResourceConnectionDetails({
- projectId,
- connectionDetails: {
- protocol: WindowsProtocol.RDP,
- hostname: computer.resolvedIp || hostname,
- port: 3389,
- ...winrmConfig
- } as TWindowsResourceConnectionDetails,
- kmsService
- }),
- encryptResourceInternalMetadata({
- projectId,
- internalMetadata: {
- osVersion: computer.operatingSystem || undefined,
- osVersionDetail: computer.operatingSystemVersion || undefined
- } as TWindowsResourceInternalMetadata,
- kmsService
- })
- ]);
-
- const resource = await pamResourceDAL.create(
- {
- projectId,
- name: resourceName,
- resourceType: PamResource.Windows,
- gatewayId: gatewayPoolId ? null : gatewayId,
- gatewayPoolId: gatewayPoolId ?? null,
- encryptedConnectionDetails,
- encryptedResourceMetadata,
- domainId,
- discoveryFingerprint: fingerprint
- },
- tx
- );
-
- return { resource, isNew: true };
-};
-
-const upsertDomainAccount = async (
- projectId: string,
- user: TLdapUser,
- domainId: string,
- domainFQDN: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find">,
- tx: Knex
-) => {
- const fingerprint = `${domainFQDN.toLowerCase()}:${user.objectGUID}`;
-
- const existing = await pamAccountDAL.find(
- {
- projectId,
- domainId,
- discoveryFingerprint: fingerprint
- },
- { tx }
- );
-
- if (existing.length > 0) {
- return { account: existing[0], isNew: false };
- }
-
- const accountName = toSlugName(user.sAMAccountName);
- const accountType = isServiceAccount(user) ? "service" : "user";
-
- const encryptedCredentials = await encryptAccountCredentials({
- projectId,
- credentials: {
- username: user.sAMAccountName,
- password: ""
- } as TActiveDirectoryAccountCredentials,
- kmsService
- });
-
- let servicePrincipalName: string[] | undefined;
- if (Array.isArray(user.servicePrincipalName)) {
- servicePrincipalName = user.servicePrincipalName;
- } else if (user.servicePrincipalName) {
- servicePrincipalName = [user.servicePrincipalName];
- }
-
- const internalMetadata = {
- accountType,
- adGuid: user.objectGUID,
- displayName: user.displayName || undefined,
- userPrincipalName: user.userPrincipalName || undefined,
- servicePrincipalName,
- userAccountControl: user.userAccountControl ? parseInt(user.userAccountControl, 10) : undefined,
- passwordLastSet: fileTimeToIso(user.pwdLastSet),
- lastLogon: fileTimeToIso(user.lastLogonTimestamp)
- } as TActiveDirectoryAccountInternalMetadata;
-
- const account = await pamAccountDAL.create(
- {
- projectId,
- domainId,
- name: accountName,
- encryptedCredentials,
- internalMetadata,
- discoveryFingerprint: fingerprint
- },
- tx
- );
-
- return { account, isNew: true };
-};
-
-const executeWinRmLocalAccountEnumeration = async (
- computer: TLdapComputer,
- domainFQDN: string,
- credentials: TAdDiscoveryCredentials,
- winrmPort: number,
- useWinrmHttps: boolean,
- winrmRejectUnauthorized: boolean,
- winrmCaCert: string | undefined,
- gatewayId: string,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
-): Promise<TWinRmLocalUser[]> => {
- const hostname = computer.dNSHostName || computer.cn;
- const targetAddress = computer.resolvedIp || hostname;
-
- return executeWithGateway(
- { dcAddress: targetAddress, port: winrmPort, gatewayId },
- gatewayV2Service,
- async (proxyPort) => {
- const netbiosDomain = domainFQDN.split(".")[0].toUpperCase();
- const winrmUsername = `${netbiosDomain}\\${credentials.username}`;
- const script = `Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, Description, SID | ConvertTo-Json`;
- // Use machine's DNS hostname as TLS servername for cert verification
- const stdout = await runPowershell(
- script,
- "localhost",
- winrmUsername,
- credentials.password,
- proxyPort,
- useWinrmHttps,
- winrmRejectUnauthorized,
- winrmCaCert,
- hostname
- );
-
- if (!stdout.trim()) {
- return [];
- }
-
- const parsed = JSON.parse(stdout) as TWinRmLocalUser | TWinRmLocalUser[];
- return Array.isArray(parsed) ? parsed : [parsed];
- }
- );
-};
-
-const executeWinRmDependencyEnumeration = async (
- computer: TLdapComputer,
- domainFQDN: string,
- credentials: TAdDiscoveryCredentials,
- winrmPort: number,
- useWinrmHttps: boolean,
- winrmRejectUnauthorized: boolean,
- winrmCaCert: string | undefined,
- gatewayId: string,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
-): Promise<TWinRmDependencies> => {
- const hostname = computer.dNSHostName || computer.cn;
- const targetAddress = computer.resolvedIp || hostname;
-
- return executeWithGateway(
- { dcAddress: targetAddress, port: winrmPort, gatewayId },
- gatewayV2Service,
- async (proxyPort) => {
- const netbiosDomain = domainFQDN.split(".")[0].toUpperCase();
- const winrmUsername = `${netbiosDomain}\\${credentials.username}`;
- // Use machine's DNS hostname as TLS servername for cert verification
- const stdout = await runPowershell(
- DEPENDENCY_ENUMERATION_SCRIPT,
- "localhost",
- winrmUsername,
- credentials.password,
- proxyPort,
- useWinrmHttps,
- winrmRejectUnauthorized,
- winrmCaCert,
- hostname
- );
-
- if (!stdout.trim()) {
- return { services: [], scheduledTasks: [], iisAppPools: [] };
- }
-
- const parsed = JSON.parse(stdout) as Partial<TWinRmDependencies>;
- const result = {
- services: Array.isArray(parsed.services) ? parsed.services : [],
- scheduledTasks: Array.isArray(parsed.scheduledTasks) ? parsed.scheduledTasks : [],
- iisAppPools: Array.isArray(parsed.iisAppPools) ? parsed.iisAppPools : []
- };
-
- return result;
- }
- );
-};
-
-// Resolve a dependency's "run as" username to a discovered account ID
-// Handles formats: DOMAIN\user, [email protected], .\localuser, plain localuser
-const resolveAccountForDependency = (
- runAsUser: string,
- domainFQDN: string,
- domainAccountMap: Map<string, string>,
- localAccountMap: Map<string, string>
-): string | null => {
- if (!runAsUser) return null;
-
- const normalized = runAsUser.trim();
- const netbiosDomain = domainFQDN.split(".")[0].toUpperCase();
-
- // DOMAIN\user format
- if (normalized.includes("\\")) {
- const [domain, user] = normalized.split("\\", 2);
- if (domain === ".") {
- // .\user is explicitly local
- return localAccountMap.get(user.toLowerCase()) ?? null;
- }
- if (domain.toUpperCase() === netbiosDomain) {
- // NETBIOS\user — domain takes priority
- return domainAccountMap.get(user.toLowerCase()) ?? localAccountMap.get(user.toLowerCase()) ?? null;
- }
- // Domain account
- return domainAccountMap.get(user.toLowerCase()) ?? null;
- }
-
- // user@domain format
- if (normalized.includes("@")) {
- const [user] = normalized.split("@", 2);
- return domainAccountMap.get(user.toLowerCase()) ?? null;
- }
-
- // Plain username — check local first, then domain
- return localAccountMap.get(normalized.toLowerCase()) ?? domainAccountMap.get(normalized.toLowerCase()) ?? null;
-};
-
-const upsertLocalAccount = async (
- projectId: string,
- localUser: TWinRmLocalUser,
- computerObjectGUID: string,
- domainFQDN: string,
- windowsServerResourceId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find">,
- tx: Knex
-) => {
- const fingerprint = `${domainFQDN.toLowerCase()}:${computerObjectGUID}:${localUser.Name.toLowerCase()}`;
-
- const existing = await pamAccountDAL.find(
- {
- resourceId: windowsServerResourceId,
- discoveryFingerprint: fingerprint
- },
- { tx }
- );
-
- if (existing.length > 0) {
- return { account: existing[0], isNew: false };
- }
-
- const accountName = toSlugName(localUser.Name);
-
- const encryptedCredentials = await encryptAccountCredentials({
- projectId,
- credentials: {
- username: localUser.Name,
- password: ""
- } as TWindowsAccountCredentials,
- kmsService
- });
-
- const internalMetadata = {
- accountType: WindowsAccountType.User,
- lastLogon: parseDotNetDate(localUser.LastLogon),
- passwordLastSet: parseDotNetDate(localUser.PasswordLastSet),
- sid: localUser.SID?.Value || undefined,
- enabled: localUser.Enabled
- } as TWindowsAccountMetadata;
-
- const account = await pamAccountDAL.create(
- {
- projectId,
- resourceId: windowsServerResourceId,
- name: accountName,
- encryptedCredentials,
- internalMetadata,
- discoveryFingerprint: fingerprint
- },
- tx
- );
-
- return { account, isNew: true };
-};
-
-const upsertDiscoveredDependency = async (
- dependencyType: PamAccountDependencyType,
- name: string,
- displayName: string | null,
- state: string | null,
- data: Record<string, unknown>,
- accountId: string,
- resourceId: string,
- discoverySourceId: string,
- runId: string,
- pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "upsertDependency">,
- pamDiscoverySourceDependenciesDAL: Pick<TPamDiscoverySourceDependenciesDALFactory, "upsertJunction">
-) => {
- const dependency = await pamAccountDependenciesDAL.upsertDependency({
- accountId,
- resourceId,
- dependencyType,
- name,
- displayName,
- state,
- data,
- source: PamAccountDependencySource.Discovery
- });
-
- await pamDiscoverySourceDependenciesDAL.upsertJunction({
- discoverySourceId,
- dependencyId: dependency.id,
- lastSeenRunId: runId
- });
-
- return dependency;
-};
-
-export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory<
- TAdDiscoveryConfiguration,
- TAdDiscoveryCredentials
-> = (_discoveryType, configuration, credentials, gatewayId, projectId, gatewayV2Service, gatewayPoolId) => {
- const validateConnection = async () => {
- try {
- const ldapProtocol = configuration.useLdaps ? "ldaps" : "ldap";
- await executeWithGateway(
- { dcAddress: configuration.dcAddress, port: configuration.ldapPort, gatewayId },
- gatewayV2Service,
- async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const client = ldapjs.createClient({
- url: `${ldapProtocol}://localhost:${proxyPort}`,
- connectTimeout: LDAP_TIMEOUT,
- timeout: LDAP_TIMEOUT,
- ...(configuration.useLdaps && {
- tlsOptions: {
- rejectUnauthorized: configuration.ldapRejectUnauthorized,
- ...(configuration.ldapCaCert && {
- ca: [configuration.ldapCaCert],
- servername: configuration.ldapTlsServerName || configuration.dcAddress
- })
- }
- })
- });
-
- client.on("error", (err: Error) => {
- client.unbind();
- reject(err);
- });
-
- const bindDn = `${credentials.username}@${configuration.domainFQDN}`;
- client.bind(bindDn, credentials.password, (err) => {
- if (err) {
- client.unbind();
- logger.warn(err, "PAM AD discovery LDAP bind failed during connection validation");
- reject(new Error(`LDAP bind failed: ${err.message}`));
- } else {
- client.unbind();
- resolve();
- }
- });
- });
- }
- );
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to Active Directory: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const scan = async (
- discoverySourceId: string,
- triggeredBy: PamDiscoverySourceRunTrigger,
- deps: TPamDiscoveryScanDeps
- ) => {
- const {
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamAccountDAL,
- kmsService
- } = deps;
-
- // Create discovery run
- const run = await pamDiscoveryRunDAL.create({
- discoverySourceId,
- status: PamDiscoverySourceRunStatus.Running,
- triggeredBy,
- startedAt: new Date(),
- progress: {
- adEnumeration: { status: PamDiscoveryStepStatus.Running }
- } as TActiveDirectoryDiscoverySourceRunProgress
- });
-
- let adEnumerationSucceeded = false;
- let resourcesDiscoveredCount = 0;
- let accountsDiscoveredCount = 0;
- let dependenciesDiscoveredCount = 0;
- let newResourcesCount = 0;
- let newAccountsCount = 0;
- let newDependenciesCount = 0;
-
- try {
- const { computers, users } = await executeLdapEnumeration(
- configuration,
- credentials,
- gatewayId,
- gatewayV2Service
- );
-
- adEnumerationSucceeded = true;
-
- // Resolve computer hostnames to IPs via DC DNS so the gateway can reach them
- try {
- await resolveHostnamesViaDc(computers, configuration, gatewayId, gatewayV2Service);
- } catch (err) {
- logger.warn(err, "Failed to resolve hostnames via DC DNS, will use hostnames directly");
- }
-
- await pamDiscoveryRunDAL.updateById(run.id, {
- progress: {
- adEnumeration: { status: PamDiscoveryStepStatus.Completed, completedAt: new Date().toISOString() },
- machineEnumeration: {
- status: PamDiscoveryStepStatus.Running,
- totalMachines: computers.length,
- scannedMachines: 0,
- failedMachines: 0
- }
- } as TActiveDirectoryDiscoverySourceRunProgress
- });
-
- // Auto-import AD domain
- const { domain } = await pamDomainDAL.transaction(async (tx) => {
- const result = await upsertDomain(
- projectId,
- configuration,
- gatewayId,
- kmsService,
- pamDomainDAL,
- tx,
- gatewayPoolId
- );
- return result;
- });
-
- // Auto-import Windows Server resources and build mapping for local account discovery
- const computerResourceMap = new Map<string, string>(); // objectGUID -> resourceId
-
- for await (const computer of computers) {
- try {
- const { resource: windowsResource, isNew } = await pamResourceDAL.transaction(async (tx) => {
- const result = await upsertWindowsServerResource(
- projectId,
- computer,
- domain.id,
- configuration.domainFQDN,
- gatewayId,
- gatewayPoolId,
- {
- winrmPort: configuration.winrmPort,
- useWinrmHttps: configuration.useWinrmHttps,
- winrmRejectUnauthorized: configuration.winrmRejectUnauthorized,
- winrmCaCert: configuration.winrmCaCert
- },
- kmsService,
- pamResourceDAL,
- tx
- );
-
- await pamDiscoverySourceResourcesDAL.upsertJunction(
- {
- discoverySourceId,
- resourceId: result.resource.id,
- lastDiscoveredRunId: run.id
- },
- tx
- );
-
- return result;
- });
-
- computerResourceMap.set(computer.objectGUID, windowsResource.id);
- resourcesDiscoveredCount += 1;
- if (isNew) newResourcesCount += 1;
- } catch (err) {
- logger.warn(err, `Failed to import Windows Server resource [computer=${computer.dNSHostName}]`);
- }
- }
-
- // Persist resource counts before processing accounts
- await pamDiscoveryRunDAL.updateById(run.id, {
- resourcesDiscoveredCount
- });
-
- // Auto-import domain accounts and build lookup map for dependency resolution
- const domainAccountMap = new Map<string, string>(); // sAMAccountName (lowercase) -> accountId
-
- for await (const user of users) {
- try {
- const { account, isNew } = await pamAccountDAL.transaction(async (tx) => {
- const result = await upsertDomainAccount(
- projectId,
- user,
- domain.id,
- configuration.domainFQDN,
- kmsService,
- pamAccountDAL,
- tx
- );
-
- await pamDiscoverySourceAccountsDAL.upsertJunction(
- {
- discoverySourceId,
- accountId: result.account.id,
- lastDiscoveredRunId: run.id
- },
- tx
- );
-
- return result;
- });
-
- domainAccountMap.set(user.sAMAccountName.toLowerCase(), account.id);
- accountsDiscoveredCount += 1;
- if (isNew) newAccountsCount += 1;
- } catch (err) {
- logger.warn(err, `Failed to import domain account [username=${user.sAMAccountName}]`);
- }
- }
-
- // WinRM local account discovery
- let scannedMachines = 0;
- let failedMachines = 0;
- const machineErrors: Record<string, string> = {};
-
- // eslint-disable-next-line no-await-in-loop
- for (const computer of computers) {
- const windowsResourceId = computerResourceMap.get(computer.objectGUID);
- if (!windowsResourceId) {
- failedMachines += 1;
- } else {
- const hostname = computer.dNSHostName || computer.cn;
-
- try {
- // eslint-disable-next-line no-await-in-loop
- const localUsers = await executeWinRmLocalAccountEnumeration(
- computer,
- configuration.domainFQDN,
- credentials,
- configuration.winrmPort,
- configuration.useWinrmHttps,
- configuration.winrmRejectUnauthorized,
- configuration.winrmCaCert,
- gatewayId,
- gatewayV2Service
- );
-
- const localAccountMap = new Map<string, string>(); // Name (lowercase) -> accountId
-
- for (const localUser of localUsers) {
- try {
- // eslint-disable-next-line no-await-in-loop
- const { account, isNew } = await pamAccountDAL.transaction(async (tx) => {
- const result = await upsertLocalAccount(
- projectId,
- localUser,
- computer.objectGUID,
- configuration.domainFQDN,
- windowsResourceId,
- kmsService,
- pamAccountDAL,
- tx
- );
-
- await pamDiscoverySourceAccountsDAL.upsertJunction(
- {
- discoverySourceId,
- accountId: result.account.id,
- lastDiscoveredRunId: run.id
- },
- tx
- );
-
- return result;
- });
-
- localAccountMap.set(localUser.Name.toLowerCase(), account.id);
- accountsDiscoveredCount += 1;
- if (isNew) newAccountsCount += 1;
- } catch (err) {
- logger.warn(err, `Failed to import local account [username=${localUser.Name}] [computer=${hostname}]`);
- }
- }
-
- // Dependency discovery (services, scheduled tasks, IIS app pools)
- if (configuration.discoverDependencies)
- try {
- // eslint-disable-next-line no-await-in-loop
- const dependencies = await executeWinRmDependencyEnumeration(
- computer,
- configuration.domainFQDN,
- credentials,
- configuration.winrmPort,
- configuration.useWinrmHttps,
- configuration.winrmRejectUnauthorized,
- configuration.winrmCaCert,
- gatewayId,
- gatewayV2Service
- );
-
- const depItems: {
- type: PamAccountDependencyType;
- name: string;
- displayName: string | null;
- state: string | null;
- runAsUser: string;
- data: Record<string, unknown>;
- }[] = [];
-
- for (const svc of dependencies.services) {
- const startName = (svc.StartName || "").toLowerCase();
- if (!startName || BUILTIN_SERVICE_ACCOUNTS.has(startName) || startName.startsWith("nt service\\")) {
- // eslint-disable-next-line no-continue
- continue;
- }
- depItems.push({
- type: PamAccountDependencyType.WindowsService,
- name: svc.Name,
- displayName: svc.DisplayName,
- state: svc.State,
- runAsUser: svc.StartName,
- data: {
- startMode: svc.StartMode,
- processId: svc.ProcessId,
- pathName: svc.PathName,
- description: svc.Description,
- runAsAccount: svc.StartName
- }
- });
- }
-
- for (const task of dependencies.scheduledTasks) {
- depItems.push({
- type: PamAccountDependencyType.ScheduledTask,
- name: task.TaskName,
- displayName: null,
- state: task.State,
- runAsUser: task.UserId,
- data: {
- taskPath: task.TaskPath,
- logonType: task.LogonType,
- runLevel: task.RunLevel,
- lastRunTime: task.LastRunTime,
- nextRunTime: task.NextRunTime,
- lastTaskResult: task.LastTaskResult,
- runAsAccount: task.UserId,
- triggers: task.Triggers ?? [],
- actions: task.Actions ?? []
- }
- });
- }
-
- for (const pool of dependencies.iisAppPools) {
- depItems.push({
- type: PamAccountDependencyType.IisAppPool,
- name: pool.Name,
- displayName: null,
- state: pool.State,
- runAsUser: pool.Username,
- data: {
- identityType: pool.IdentityType,
- managedRuntimeVersion: pool.ManagedRuntimeVersion,
- managedPipelineMode: pool.ManagedPipelineMode,
- autoStart: pool.AutoStart,
- runAsAccount: pool.Username
- }
- });
- }
-
- for (const dep of depItems) {
- const accountId = resolveAccountForDependency(
- dep.runAsUser,
- configuration.domainFQDN,
- domainAccountMap,
- localAccountMap
- );
-
- if (accountId) {
- try {
- // eslint-disable-next-line no-await-in-loop
- const dependency = await upsertDiscoveredDependency(
- dep.type,
- dep.name,
- dep.displayName,
- dep.state,
- dep.data,
- accountId,
- windowsResourceId,
- discoverySourceId,
- run.id,
- pamAccountDependenciesDAL,
- pamDiscoverySourceDependenciesDAL
- );
-
- dependenciesDiscoveredCount += 1;
-
- if (dependency.isNew) {
- newDependenciesCount += 1;
- }
- } catch (err) {
- logger.warn(err, `Failed to import dependency [dependency=${dep.name}] [computer=${hostname}]`);
- }
- }
- }
- } catch (err) {
- logger.warn(err, `WinRM dependency enumeration failed for machine [computer=${hostname}]`);
- }
-
- scannedMachines += 1;
- } catch (err) {
- failedMachines += 1;
- machineErrors[hostname] = (err as Error).message;
- logger.warn(err, `WinRM local account enumeration failed for machine [computer=${hostname}]`);
- }
- }
-
- // Update progress periodically
- // eslint-disable-next-line no-await-in-loop
- await pamDiscoveryRunDAL.updateById(run.id, {
- accountsDiscoveredCount,
- dependenciesDiscoveredCount,
- progress: {
- adEnumeration: { status: PamDiscoveryStepStatus.Completed, completedAt: new Date().toISOString() },
- machineEnumeration: {
- status: PamDiscoveryStepStatus.Running,
- totalMachines: computers.length,
- scannedMachines,
- failedMachines
- },
- machineErrors: Object.keys(machineErrors).length > 0 ? machineErrors : undefined
- } as TActiveDirectoryDiscoverySourceRunProgress
- });
- }
-
- if (adEnumerationSucceeded) {
- const staleResourcesCount =
- (await pamDiscoverySourceResourcesDAL.markStaleForRun(discoverySourceId, run.id)) || 0;
- const staleAccountsCount =
- (await pamDiscoverySourceAccountsDAL.markStaleForRun(discoverySourceId, run.id)) || 0;
- const staleDependenciesCount =
- (await pamDiscoverySourceDependenciesDAL.markStaleForRun(discoverySourceId, run.id)) || 0;
-
- const machineEnumerationStatus =
- failedMachines === computers.length && computers.length > 0
- ? PamDiscoveryStepStatus.Failed
- : PamDiscoveryStepStatus.Completed;
-
- await pamDiscoveryRunDAL.updateById(run.id, {
- status: PamDiscoverySourceRunStatus.Completed,
- resourcesDiscoveredCount,
- accountsDiscoveredCount,
- dependenciesDiscoveredCount,
- newResourcesCount,
- staleResourcesCount,
- newAccountsCount,
- staleAccountsCount,
- newDependenciesCount,
- staleDependenciesCount,
- completedAt: new Date(),
- progress: {
- adEnumeration: { status: PamDiscoveryStepStatus.Completed, completedAt: new Date().toISOString() },
- machineEnumeration: {
- status: machineEnumerationStatus,
- totalMachines: computers.length,
- scannedMachines,
- failedMachines,
- statusMessage:
- failedMachines > 0
- ? `${failedMachines} of ${computers.length} machines failed local account enumeration`
- : undefined
- },
- machineErrors: Object.keys(machineErrors).length > 0 ? machineErrors : undefined
- } as TActiveDirectoryDiscoverySourceRunProgress
- });
- }
- } catch (error) {
- logger.error(error, `PAM AD discovery scan failed [discoverySourceId=${discoverySourceId}] [runId=${run.id}]`);
-
- const progress: TActiveDirectoryDiscoverySourceRunProgress = adEnumerationSucceeded
- ? {
- adEnumeration: { status: PamDiscoveryStepStatus.Completed },
- machineEnumeration: { status: PamDiscoveryStepStatus.Failed, statusMessage: (error as Error).message }
- }
- : {
- adEnumeration: { status: PamDiscoveryStepStatus.Failed, error: (error as Error).message }
- };
-
- await pamDiscoveryRunDAL.updateById(run.id, {
- status: PamDiscoverySourceRunStatus.Failed,
- progress,
- errorMessage: (error as Error).message,
- completedAt: new Date()
- });
- } finally {
- await pamDiscoverySourceDAL.updateById(discoverySourceId, {
- lastRunAt: new Date()
- });
- }
- };
-
- return {
- validateConnection,
- scan
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts
deleted file mode 100644
index 64facb5bdc..0000000000
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { ActiveDirectoryDiscoveryListItemSchema } from "./active-directory-discovery-schemas";
-
-export const getActiveDirectorySourceListItem = () => {
- return {
- name: ActiveDirectoryDiscoveryListItemSchema.shape.name.value,
- discoveryType: ActiveDirectoryDiscoveryListItemSchema.shape.discoveryType.value
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
deleted file mode 100644
index 7bf4dc3893..0000000000
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { z } from "zod";
-
-import { PamDiscoveryStepStatus, PamDiscoveryType } from "../pam-discovery-enums";
-import {
- BaseCreatePamDiscoverySourceSchema,
- BasePamDiscoverySourceRunSchema,
- BasePamDiscoverySourceSchema,
- BaseUpdatePamDiscoverySourceSchema
-} from "../pam-discovery-schemas";
-
-// Discovery Source
-const BaseActiveDirectoryDiscoverySourceSchema = BasePamDiscoverySourceSchema.extend({
- discoveryType: z.literal(PamDiscoveryType.ActiveDirectory)
-});
-
-export const ActiveDirectoryDiscoveryListItemSchema = z.object({
- name: z.literal("Active Directory"),
- discoveryType: z.literal(PamDiscoveryType.ActiveDirectory)
-});
-
-export const ActiveDirectoryDiscoveryConfigurationSchema = z.object({
- domainFQDN: z.string().trim().min(1).max(255),
- dcAddress: z.string().trim().min(1).max(255),
- // LDAP
- ldapPort: z.coerce.number().int().min(1).max(65535),
- useLdaps: z.boolean(),
- ldapRejectUnauthorized: z.boolean(),
- ldapCaCert: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional(),
- ldapTlsServerName: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional(),
- // WinRM
- winrmPort: z.coerce.number().int().min(1).max(65535),
- useWinrmHttps: z.boolean(),
- winrmRejectUnauthorized: z.boolean(),
- winrmCaCert: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional(),
- // Dependencies
- discoverDependencies: z.boolean()
-});
-
-export const ActiveDirectoryDiscoveryCredentialsSchema = z.object({
- username: z.string().trim().min(1).max(255),
- password: z.string().trim().min(1).max(255)
-});
-
-export const ActiveDirectoryDiscoverySourceSchema = BaseActiveDirectoryDiscoverySourceSchema.extend({
- discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
- discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema
-});
-
-export const SanitizedActiveDirectoryDiscoverySourceSchema = BaseActiveDirectoryDiscoverySourceSchema.extend({
- discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
- discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema.pick({
- username: true
- })
-});
-
-export const CreateActiveDirectoryDiscoverySourceSchema = BaseCreatePamDiscoverySourceSchema.extend({
- discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
- discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema
-});
-
-export const UpdateActiveDirectoryDiscoverySourceSchema = BaseUpdatePamDiscoverySourceSchema.extend({
- discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema.optional(),
- discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema.optional()
-});
-
-// Discovery Run
-export const ActiveDirectoryDiscoverySourceRunProgressSchema = z.object({
- adEnumeration: z
- .object({
- status: z.nativeEnum(PamDiscoveryStepStatus),
- completedAt: z.string().optional(),
- error: z.string().optional()
- })
- .optional(),
- machineEnumeration: z
- .object({
- status: z.nativeEnum(PamDiscoveryStepStatus),
- totalMachines: z.number().optional(),
- scannedMachines: z.number().optional(),
- failedMachines: z.number().optional(),
- statusMessage: z.string().optional()
- })
- .optional(),
- machineErrors: z.record(z.string(), z.string()).optional()
-});
-
-export const ActiveDirectoryDiscoverySourceRunSchema = BasePamDiscoverySourceRunSchema.extend({
- progress: ActiveDirectoryDiscoverySourceRunProgressSchema
-});
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-scripts.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-scripts.ts
deleted file mode 100644
index ca8057a4a4..0000000000
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-scripts.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Enumerates Windows Services (non-built-in), Scheduled Tasks (non-system),
- * and IIS Application Pools (SpecificUser identity) on a remote machine.
- */
-export const DEPENDENCY_ENUMERATION_SCRIPT = [
- "$result = @{};",
- "$result.services = @(Get-WmiObject Win32_Service | Where-Object { $_.StartName -and $_.StartName -notmatch 'LocalSystem|NT AUTHORITY|NT SERVICE|LocalService|NetworkService' } | Select-Object Name, DisplayName, StartName, State, StartMode, ProcessId, PathName, Description);",
- "$result.scheduledTasks = @(Get-ScheduledTask | ForEach-Object {",
- " $t = $_;",
- " $info = $null; try { $info = $t | Get-ScheduledTaskInfo -ErrorAction Stop } catch {};",
- " $lrt = $null; $nrt = $null; $ltr = $null;",
- " if ($info) {",
- " try { $lrt = $info.LastRunTime.ToString('o') } catch {};",
- " try { $nrt = $info.NextRunTime.ToString('o') } catch {};",
- " $ltr = $info.LastTaskResult",
- " };",
- " $trig = @();",
- " if ($t.Triggers) {",
- " $trig = @($t.Triggers | Where-Object { $_ -ne $null } | ForEach-Object {",
- " $rep = $null;",
- " if ($_.Repetition -and $_.Repetition.Interval) { $rep = $_.Repetition.Interval };",
- " [PSCustomObject]@{ Type = $_.GetType().Name; StartBoundary = $_.StartBoundary; Interval = $rep }",
- " })",
- " };",
- " $acts = @();",
- " if ($t.Actions) {",
- " $acts = @($t.Actions | Where-Object { $_ -ne $null } | ForEach-Object {",
- " [PSCustomObject]@{ Type = [string]$_.GetType().Name; Execute = $_.Execute; Arguments = $_.Arguments }",
- " })",
- " };",
- " [PSCustomObject]@{",
- " TaskName = $t.TaskName; TaskPath = $t.TaskPath; State = [string]$t.State;",
- " UserId = $t.Principal.UserId; LogonType = [string]$t.Principal.LogonType; RunLevel = [string]$t.Principal.RunLevel;",
- " LastRunTime = $lrt; NextRunTime = $nrt; LastTaskResult = $ltr;",
- " Triggers = $trig; Actions = $acts",
- " }",
- "} | Where-Object { $_.UserId -and $_.UserId -notmatch 'SYSTEM|LOCAL SERVICE|NETWORK SERVICE' });",
- "try {",
- " Import-Module WebAdministration -ErrorAction Stop;",
- " $result.iisAppPools = @(Get-ChildItem IIS:\\AppPools | ForEach-Object {",
- " [PSCustomObject]@{",
- " Name = $_.Name; State = [string]$_.State;",
- " IdentityType = [string]$_.processModel.identityType; Username = $_.processModel.userName;",
- " ManagedRuntimeVersion = [string]$_.managedRuntimeVersion;",
- " ManagedPipelineMode = [string]$_.managedPipelineMode;",
- " AutoStart = [bool]$_.autoStart",
- " }",
- " } | Where-Object { $_.IdentityType -eq 'SpecificUser' })",
- "} catch { $result.iisAppPools = @() };",
- "$result | ConvertTo-Json -Depth 4"
-].join(" ");
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts
deleted file mode 100644
index 61fb908bc1..0000000000
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { z } from "zod";
-
-import {
- ActiveDirectoryDiscoveryConfigurationSchema,
- ActiveDirectoryDiscoveryCredentialsSchema,
- ActiveDirectoryDiscoverySourceRunProgressSchema,
- ActiveDirectoryDiscoverySourceSchema
-} from "./active-directory-discovery-schemas";
-
-export type TActiveDirectoryDiscoverySource = z.infer<typeof ActiveDirectoryDiscoverySourceSchema>;
-export type TActiveDirectoryDiscoverySourceCredentials = z.infer<typeof ActiveDirectoryDiscoveryCredentialsSchema>;
-export type TActiveDirectoryDiscoverySourceConfiguration = z.infer<typeof ActiveDirectoryDiscoveryConfigurationSchema>;
-export type TActiveDirectoryDiscoverySourceRunProgress = z.infer<
- typeof ActiveDirectoryDiscoverySourceRunProgressSchema
->;
diff --git a/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts b/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts
deleted file mode 100644
index d2edad18b6..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName, TPamAccountDependencies } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify } from "@app/lib/knex";
-
-export type TPamAccountDependenciesDALFactory = ReturnType<typeof pamAccountDependenciesDALFactory>;
-
-export const pamAccountDependenciesDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamAccountDependency);
-
- const findByAccountId = async (accountId: string, tx?: Knex) => {
- try {
- const docs = await (tx || db.replicaNode())(TableName.PamAccountDependency)
- .where(`${TableName.PamAccountDependency}.accountId`, accountId)
- .leftJoin(TableName.PamResource, `${TableName.PamAccountDependency}.resourceId`, `${TableName.PamResource}.id`)
- .select(`${TableName.PamAccountDependency}.*`, `${TableName.PamResource}.name as resourceName`)
- .orderBy(`${TableName.PamAccountDependency}.name`, "asc");
-
- return docs as (TPamAccountDependencies & { resourceName: string | null })[];
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM account dependencies by account ID" });
- }
- };
-
- const findByResourceId = async (resourceId: string, tx?: Knex) => {
- try {
- const docs = await (tx || db.replicaNode())(TableName.PamAccountDependency)
- .where(`${TableName.PamAccountDependency}.resourceId`, resourceId)
- .leftJoin(TableName.PamAccount, `${TableName.PamAccountDependency}.accountId`, `${TableName.PamAccount}.id`)
- .select(`${TableName.PamAccountDependency}.*`, `${TableName.PamAccount}.name as accountName`)
- .orderBy(`${TableName.PamAccountDependency}.name`, "asc");
-
- return docs as (TPamAccountDependencies & { accountName: string | null })[];
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM account dependencies by resource ID" });
- }
- };
-
- const countByAccountIds = async (accountIds: string[], tx?: Knex) => {
- try {
- const rows = await (tx || db.replicaNode())(TableName.PamAccountDependency)
- .whereIn("accountId", accountIds)
- .groupBy("accountId")
- .select("accountId")
- .count("*", { as: "count" });
-
- return Object.fromEntries(rows.map((r) => [r.accountId, Number(r.count)])) as Record<string, number>;
- } catch (error) {
- throw new DatabaseError({ error, name: "Count PAM account dependencies by account IDs" });
- }
- };
-
- const countByResourceIds = async (resourceIds: string[], tx?: Knex) => {
- try {
- const rows = await (tx || db.replicaNode())(TableName.PamAccountDependency)
- .whereIn("resourceId", resourceIds)
- .groupBy("resourceId")
- .select("resourceId")
- .count("*", { as: "count" });
-
- return Object.fromEntries(rows.map((r) => [r.resourceId, Number(r.count)])) as Record<string, number>;
- } catch (error) {
- throw new DatabaseError({ error, name: "Count PAM account dependencies by resource IDs" });
- }
- };
-
- const upsertDependency = async (
- data: {
- accountId: string;
- resourceId: string;
- dependencyType: string;
- name: string;
- displayName?: string | null;
- state?: string | null;
- data: Record<string, unknown>;
- source: string;
- },
- tx?: Knex
- ) => {
- try {
- const knex = tx || db;
-
- const [doc] = await knex(TableName.PamAccountDependency)
- .insert({
- ...data,
- isRotationSyncEnabled: true
- })
- .onConflict(["accountId", "resourceId", "dependencyType", "name"])
- .merge({
- displayName: data.displayName,
- state: data.state,
- data: data.data
- // Note: isRotationSyncEnabled is NOT merged - preserves admin's explicit enable/disable
- })
- .returning(["*", knex.raw('(xmax = 0) as "isNew"')]);
-
- return doc as TPamAccountDependencies & { isNew: boolean };
- } catch (error) {
- throw new DatabaseError({ error, name: "Upsert PAM account dependency" });
- }
- };
-
- return {
- ...orm,
- findByAccountId,
- findByResourceId,
- countByAccountIds,
- countByResourceIds,
- upsertDependency
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts b/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts
deleted file mode 100644
index 1c39e3136e..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
-import { activeDirectoryDiscoveryFactory } from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-factory";
-import { TPamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";
-import { PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
-import { TPamDiscoverySourceAccountsDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-accounts-dal";
-import { TPamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";
-import { TPamDiscoverySourceDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dependencies-dal";
-import { TPamDiscoverySourceResourcesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-resources-dal";
-import { TPamDiscoverySourceRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-run-dal";
-import {
- TPamDiscoveryConfiguration,
- TPamDiscoveryCredentials,
- TPamDiscoveryFactory
-} from "@app/ee/services/pam-discovery/pam-discovery-types";
-import { TPamDomainDALFactory } from "@app/ee/services/pam-domain/pam-domain-dal";
-import { TPamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-
-export type TPamDiscoveryScanDeps = {
- pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findById" | "updateById">;
- pamDiscoveryRunDAL: Pick<TPamDiscoverySourceRunDALFactory, "create" | "updateById">;
- pamDiscoverySourceResourcesDAL: Pick<TPamDiscoverySourceResourcesDALFactory, "upsertJunction" | "markStaleForRun">;
- pamDiscoverySourceAccountsDAL: Pick<TPamDiscoverySourceAccountsDALFactory, "upsertJunction" | "markStaleForRun">;
- pamDiscoverySourceDependenciesDAL: Pick<
- TPamDiscoverySourceDependenciesDALFactory,
- "upsertJunction" | "markStaleForRun"
- >;
- pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "upsertDependency">;
- pamDomainDAL: Pick<TPamDomainDALFactory, "create" | "find" | "transaction">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "create" | "find" | "findById" | "updateById" | "transaction">;
- pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find" | "updateById" | "transaction">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
-};
-
-type TPamDiscoveryFactoryImplementation = TPamDiscoveryFactory<TPamDiscoveryConfiguration, TPamDiscoveryCredentials>;
-
-export const PAM_DISCOVERY_FACTORY_MAP: Record<PamDiscoveryType, TPamDiscoveryFactoryImplementation> = {
- [PamDiscoveryType.ActiveDirectory]: activeDirectoryDiscoveryFactory as TPamDiscoveryFactoryImplementation
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
deleted file mode 100644
index e4b979fa48..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { TPamDiscoverySources } from "@app/db/schemas";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { getActiveDirectorySourceListItem } from "./active-directory/active-directory-discovery-fns";
-import { TPamDiscoveryConfiguration, TPamDiscoveryCredentials, TPamDiscoverySource } from "./pam-discovery-types";
-
-export const listDiscoverySourceOptions = () => {
- return [getActiveDirectorySourceListItem()].sort((a, b) => a.name.localeCompare(b.name));
-};
-
-export const encryptDiscoveryCredentials = async ({
- projectId,
- credentials,
- kmsService
-}: {
- projectId: string;
- credentials: TPamDiscoveryCredentials;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(credentials))
- });
-
- return cipherTextBlob;
-};
-
-export const decryptDiscoveryCredentials = async ({
- projectId,
- encryptedCredentials,
- kmsService
-}: {
- projectId: string;
- encryptedCredentials: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedCredentials
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as TPamDiscoveryCredentials;
-};
-
-export const decryptDiscoverySource = async (
- source: TPamDiscoverySources,
- projectId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
-) => {
- return {
- ...source,
- discoveryConfiguration: source.discoveryConfiguration as TPamDiscoveryConfiguration,
- discoveryCredentials: source.encryptedDiscoveryCredentials
- ? await decryptDiscoveryCredentials({
- encryptedCredentials: source.encryptedDiscoveryCredentials,
- projectId,
- kmsService
- })
- : null
- } as TPamDiscoverySource;
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
deleted file mode 100644
index 7ac566bd22..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
-import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
-import { logger } from "@app/lib/logger";
-import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-
-import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
-import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
-import { TPamAccountDependenciesDALFactory } from "./pam-account-dependencies-dal";
-import { PamDiscoverySourceRunTrigger, PamDiscoveryType } from "./pam-discovery-enums";
-import { PAM_DISCOVERY_FACTORY_MAP } from "./pam-discovery-factory";
-import { decryptDiscoveryCredentials } from "./pam-discovery-fns";
-import { TPamDiscoverySourceAccountsDALFactory } from "./pam-discovery-source-accounts-dal";
-import { TPamDiscoverySourceDALFactory } from "./pam-discovery-source-dal";
-import { TPamDiscoverySourceDependenciesDALFactory } from "./pam-discovery-source-dependencies-dal";
-import { TPamDiscoverySourceResourcesDALFactory } from "./pam-discovery-source-resources-dal";
-import { TPamDiscoverySourceRunDALFactory } from "./pam-discovery-source-run-dal";
-import { TPamDiscoveryConfiguration } from "./pam-discovery-types";
-
-type TPamDiscoveryQueueFactoryDep = {
- pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findById" | "updateById" | "findDueForScan">;
- pamDiscoveryRunDAL: Pick<TPamDiscoverySourceRunDALFactory, "create" | "updateById">;
- pamDiscoverySourceResourcesDAL: Pick<TPamDiscoverySourceResourcesDALFactory, "upsertJunction" | "markStaleForRun">;
- pamDiscoverySourceAccountsDAL: Pick<TPamDiscoverySourceAccountsDALFactory, "upsertJunction" | "markStaleForRun">;
- pamDiscoverySourceDependenciesDAL: Pick<
- TPamDiscoverySourceDependenciesDALFactory,
- "upsertJunction" | "markStaleForRun"
- >;
- pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "upsertDependency">;
- pamDomainDAL: Pick<TPamDomainDALFactory, "create" | "find" | "transaction">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "create" | "find" | "findById" | "updateById" | "transaction">;
- pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find" | "updateById" | "transaction">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- queueService: TQueueServiceFactory;
- cronJob: TCronJobFactory;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
-};
-
-export type TPamDiscoveryQueueFactory = ReturnType<typeof pamDiscoveryQueueFactory>;
-
-export const pamDiscoveryQueueFactory = ({
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamAccountDAL,
- kmsService,
- queueService,
- cronJob,
- gatewayV2Service,
- gatewayV2DAL,
- gatewayPoolService
-}: TPamDiscoveryQueueFactoryDep) => {
- const startPamDiscoveryQueue = () => {
- queueService.start(QueueName.PamDiscoveryScan, async (job) => {
- try {
- if (job.name === QueueJobs.PamDiscoverySourceRunScan) {
- const { discoverySourceId, triggeredBy } = job.data as {
- discoverySourceId: string;
- triggeredBy: PamDiscoverySourceRunTrigger;
- };
-
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- logger.error({ discoverySourceId, triggeredBy }, "PAM Discovery Source not found, skipping scan");
- return;
- }
-
- const discoveryType = discoverySource.discoveryType as PamDiscoveryType;
-
- const credentials = await decryptDiscoveryCredentials({
- projectId: discoverySource.projectId,
- encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
- kmsService
- });
-
- const configuration = discoverySource.discoveryConfiguration as TPamDiscoveryConfiguration;
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: discoverySource.gatewayId,
- gatewayPoolId: discoverySource.gatewayPoolId
- });
- if (!effectiveGatewayId) {
- logger.error(
- { discoverySourceId, triggeredBy },
- "PAM Discovery Source has no gateway or gateway pool, skipping scan"
- );
- return;
- }
-
- const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](
- discoveryType,
- configuration,
- credentials,
- effectiveGatewayId,
- discoverySource.projectId,
- gatewayV2Service,
- discoverySource.gatewayPoolId
- );
-
- const scanDeps = {
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamAccountDAL,
- kmsService,
- gatewayV2Service,
- gatewayV2DAL
- };
-
- await factory.scan(discoverySourceId, triggeredBy, scanDeps);
- } else if (job.name === QueueJobs.PamDiscoveryScheduledScan) {
- const dueSources = await pamDiscoverySourceDAL.findDueForScan();
-
- for await (const src of dueSources) {
- await queueService.queue(
- QueueName.PamDiscoveryScan,
- QueueJobs.PamDiscoverySourceRunScan,
- { discoverySourceId: src.id, triggeredBy: PamDiscoverySourceRunTrigger.Schedule },
- { jobId: `pam-discovery-scan-${src.id}` }
- );
- }
- }
- } catch (error) {
- logger.error({ error, jobName: job.name, jobId: job.id }, "PAM Discovery queue job failed");
- throw error;
- }
- });
-
- // runs every day at 3:00 AM
- cronJob.register({
- name: CronJobName.PamDiscoveryScheduledScan,
- pattern: "0 3 * * *",
- runHashTtlS: 3 * 24 * 60 * 60,
- handler: async () => {
- await queueService.queue(QueueName.PamDiscoveryScan, QueueJobs.PamDiscoveryScheduledScan, undefined as never, {
- jobId: CronJobName.PamDiscoveryScheduledScan
- });
- }
- });
- };
-
- const queuePamDiscoveryScan = async (discoverySourceId: string) => {
- await queueService.queue(
- QueueName.PamDiscoveryScan,
- QueueJobs.PamDiscoverySourceRunScan,
- { discoverySourceId, triggeredBy: PamDiscoverySourceRunTrigger.Manual },
- {
- jobId: `pam-discovery-scan-${discoverySourceId}`,
- attempts: 1,
- removeOnComplete: true,
- removeOnFail: true
- }
- );
- };
-
- return {
- startPamDiscoveryQueue,
- queuePamDiscoveryScan
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts
deleted file mode 100644
index dc4aa5fe7c..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { z } from "zod";
-
-import {
- PamDiscoverySourceAccountsSchema,
- PamDiscoverySourceResourcesSchema,
- PamDiscoverySourceRunsSchema,
- PamDiscoverySourcesSchema
-} from "@app/db/schemas";
-import { slugSchema } from "@app/server/lib/schemas";
-
-import { ActiveDirectoryAccountMetadataSchema } from "../pam-domain/active-directory/active-directory-domain-schemas";
-import { PamDomainType } from "../pam-domain/pam-domain-enums";
-import { PamResource } from "../pam-resource/pam-resource-enums";
-import { SanitizedSSHResourceInternalMetadataSchema } from "../pam-resource/ssh/ssh-resource-schemas";
-import {
- SanitizedWindowsResourceInternalMetadataSchema,
- WindowsAccountMetadataSchema
-} from "../pam-resource/windows-server/windows-server-resource-schemas";
-import {
- PamDiscoverySchedule,
- PamDiscoverySourceRunStatus,
- PamDiscoverySourceRunTrigger,
- PamDiscoverySourceStatus
-} from "./pam-discovery-enums";
-
-// Discovery Sources
-export const BasePamDiscoverySourceSchema = PamDiscoverySourcesSchema.omit({
- discoveryType: true,
- discoveryConfiguration: true,
- encryptedDiscoveryCredentials: true
-}).extend({
- schedule: z.nativeEnum(PamDiscoverySchedule),
- status: z.nativeEnum(PamDiscoverySourceStatus)
-});
-
-// No .superRefine — would turn into ZodEffects and break .extend() in per-type schemas.
-export const BaseCreatePamDiscoverySourceSchema = z.object({
- projectId: z.string().uuid(),
- name: slugSchema({ field: "name" }),
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional(),
- schedule: z.nativeEnum(PamDiscoverySchedule)
-});
-
-export const BaseUpdatePamDiscoverySourceSchema = z.object({
- name: slugSchema({ field: "name" }).optional(),
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional(),
- schedule: z.nativeEnum(PamDiscoverySchedule).optional()
-});
-
-// Discovery Runs
-export const BasePamDiscoverySourceRunSchema = PamDiscoverySourceRunsSchema.omit({
- progress: true
-}).extend({
- status: z.nativeEnum(PamDiscoverySourceRunStatus),
- triggeredBy: z.nativeEnum(PamDiscoverySourceRunTrigger)
-});
-
-export const DiscoveredResourceSchema = PamDiscoverySourceResourcesSchema.extend({
- resourceName: z.string(),
- resourceType: z.nativeEnum(PamResource),
- resourceInternalMetadata: z
- .union([SanitizedSSHResourceInternalMetadataSchema, SanitizedWindowsResourceInternalMetadataSchema])
- .optional(),
- dependencyCount: z.number().default(0)
-});
-
-export const DiscoveredAccountSchema = PamDiscoverySourceAccountsSchema.extend({
- resourceType: z.nativeEnum(PamResource).nullable().optional(),
- resourceName: z.string().nullable().optional(),
- resourceId: z.string().uuid().nullable().optional(),
- domainType: z.nativeEnum(PamDomainType).nullable().optional(),
- domainName: z.string().nullable().optional(),
- domainId: z.string().uuid().nullable().optional(),
- accountName: z.string(),
- internalMetadata: z.union([ActiveDirectoryAccountMetadataSchema, WindowsAccountMetadataSchema]),
- dependencyCount: z.number().default(0)
-});
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts
deleted file mode 100644
index 8160e25833..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { Knex } from "knex";
-import { z } from "zod";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-
-import { DiscoveredAccountSchema } from "./pam-discovery-schemas";
-
-export type TPamDiscoverySourceAccountsDALFactory = ReturnType<typeof pamDiscoverySourceAccountsDALFactory>;
-
-export const pamDiscoverySourceAccountsDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDiscoverySourceAccount);
-
- const findByDiscoverySourceIdWithAccounts = async (
- discoverySourceId: string,
- { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamDiscoverySourceAccount)
- .join(TableName.PamAccount, `${TableName.PamDiscoverySourceAccount}.accountId`, `${TableName.PamAccount}.id`)
- .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
- .leftJoin(TableName.PamDomain, `${TableName.PamAccount}.domainId`, `${TableName.PamDomain}.id`)
- .where(`${TableName.PamDiscoverySourceAccount}.discoverySourceId`, discoverySourceId);
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(
- selectAllTableCols(TableName.PamDiscoverySourceAccount),
- db.ref("name").withSchema(TableName.PamAccount).as("accountName"),
- db.ref("resourceId").withSchema(TableName.PamAccount).as("resourceId"),
- db.ref("domainId").withSchema(TableName.PamAccount).as("domainId"),
- db.ref("resourceType").withSchema(TableName.PamResource).as("resourceType"),
- db.ref("domainType").withSchema(TableName.PamDomain).as("domainType"),
- db.ref("internalMetadata").withSchema(TableName.PamAccount).as("internalMetadata"),
- db.ref("name").withSchema(TableName.PamResource).as("resourceName"),
- db.ref("name").withSchema(TableName.PamDomain).as("domainName")
- );
-
- void query.orderBy(`${TableName.PamAccount}.name`, "asc");
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [accounts, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return {
- accounts: accounts as unknown as z.infer<typeof DiscoveredAccountSchema>[],
- totalCount
- };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find discovered accounts by source ID" });
- }
- };
-
- const upsertJunction = async (
- {
- discoverySourceId,
- accountId,
- lastDiscoveredRunId
- }: {
- discoverySourceId: string;
- accountId: string;
- lastDiscoveredRunId: string;
- },
- tx?: Knex
- ) => {
- try {
- const now = new Date();
- const knex = tx || db;
-
- await knex(TableName.PamDiscoverySourceAccount)
- .insert({
- discoverySourceId,
- accountId,
- lastDiscoveredAt: now,
- lastDiscoveredRunId,
- isStale: false
- })
- .onConflict(["discoverySourceId", "accountId"])
- .merge({
- lastDiscoveredAt: now,
- lastDiscoveredRunId,
- isStale: false
- });
- } catch (error) {
- throw new DatabaseError({ error, name: "Upsert PAM discovery source account junction" });
- }
- };
-
- const countByDiscoverySourceIds = async (discoverySourceIds: string[], tx?: Knex) => {
- try {
- const rows = await (tx || db.replicaNode())(TableName.PamDiscoverySourceAccount)
- .whereIn("discoverySourceId", discoverySourceIds)
- .groupBy("discoverySourceId")
- .select("discoverySourceId")
- .count("*", { as: "count" });
-
- return Object.fromEntries(rows.map((r) => [r.discoverySourceId, Number(r.count)]));
- } catch (error) {
- throw new DatabaseError({ error, name: "Count PAM discovery source accounts by source IDs" });
- }
- };
-
- const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
- try {
- const knex = tx || db;
-
- const result = await knex(TableName.PamDiscoverySourceAccount)
- .where({ discoverySourceId })
- .andWhere((qb) => {
- void qb.whereNull("lastDiscoveredRunId").orWhereNot("lastDiscoveredRunId", runId);
- })
- .andWhere("isStale", false)
- .update({ isStale: true });
-
- return result;
- } catch (error) {
- throw new DatabaseError({ error, name: "Mark stale PAM discovery source accounts" });
- }
- };
-
- return {
- ...orm,
- findByDiscoverySourceIdWithAccounts,
- countByDiscoverySourceIds,
- upsertJunction,
- markStaleForRun
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts
deleted file mode 100644
index 32c3990b09..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { Knex } from "knex";
-import RE2 from "re2";
-
-import { TDbClient } from "@app/db";
-import { TableName, TPamDiscoverySources } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { OrderByDirection } from "@app/lib/types";
-
-import { PamDiscoveryOrderBy, PamDiscoverySourceRunStatus } from "./pam-discovery-enums";
-
-export type TPamDiscoverySourceDALFactory = ReturnType<typeof pamDiscoverySourceDALFactory>;
-
-export const pamDiscoverySourceDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDiscoverySource);
-
- const findByProjectId = async (
- projectId: string,
- {
- offset = 0,
- limit = 25,
- search,
- orderBy = PamDiscoveryOrderBy.Name,
- orderDirection = OrderByDirection.ASC,
- filterDiscoveryTypes,
- tx
- }: {
- offset?: number;
- limit?: number;
- search?: string;
- orderBy?: PamDiscoveryOrderBy;
- orderDirection?: OrderByDirection;
- filterDiscoveryTypes?: string[];
- tx?: Knex;
- } = {}
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamDiscoverySource).where(
- `${TableName.PamDiscoverySource}.projectId`,
- projectId
- );
-
- if (search) {
- // escape special characters (`%`, `_`) and the escape character itself (`\`)
- const escapedSearch = search
- .replace(new RE2(/\\/g), "\\\\")
- .replace(new RE2(/%/g), "\\%")
- .replace(new RE2(/_/g), "\\_");
- const pattern = `%${escapedSearch}%`;
- void query.where((q) => {
- void q
- .whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDiscoverySource, "name", pattern])
- .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDiscoverySource, "discoveryType", pattern]);
- });
- }
-
- if (filterDiscoveryTypes && filterDiscoveryTypes.length) {
- void query.whereIn(`${TableName.PamDiscoverySource}.discoveryType`, filterDiscoveryTypes);
- }
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamDiscoverySource));
-
- void query.orderBy(`${TableName.PamDiscoverySource}.${orderBy}`, orderDirection);
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [sources, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return { sources, totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM Discovery Sources by project ID" });
- }
- };
-
- const findDueForScan = async (tx?: Knex) => {
- try {
- const now = new Date();
- const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
- const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
-
- const docs = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
- .where({ status: "active" })
- .andWhere((qb) => {
- void qb.where({ schedule: "daily" }).orWhere({ schedule: "weekly" });
- })
- .andWhere((qb) => {
- void qb
- .whereNull("lastRunAt")
- .orWhere((sub) => {
- void sub.where({ schedule: "daily" }).andWhere("lastRunAt", "<=", oneDayAgo);
- })
- .orWhere((sub) => {
- void sub.where({ schedule: "weekly" }).andWhere("lastRunAt", "<=", sevenDaysAgo);
- });
- })
- // Exclude sources that have a running scan
- .whereNotExists(
- (tx || db.replicaNode())(TableName.PamDiscoverySourceRun)
- .select(db.raw("1"))
- .whereRaw(`"discoverySourceId" = ${TableName.PamDiscoverySource}."id"`)
- .where("status", PamDiscoverySourceRunStatus.Running)
- );
-
- return docs as TPamDiscoverySources[];
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM Discovery Sources due for scan" });
- }
- };
-
- const findByGatewayId = async (gatewayId: string, tx?: Knex) => {
- const docs = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
- .leftJoin(TableName.Project, `${TableName.PamDiscoverySource}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.PamDiscoverySource}.gatewayId`, gatewayId)
- .select(
- db.ref("id").withSchema(TableName.PamDiscoverySource),
- db.ref("name").withSchema(TableName.PamDiscoverySource),
- db.ref("projectId").withSchema(TableName.PamDiscoverySource),
- db.ref("discoveryType").withSchema(TableName.PamDiscoverySource),
- db.ref("name").withSchema(TableName.Project).as("projectName")
- );
-
- return docs;
- };
-
- const countByGatewayId = async (gatewayId: string, tx?: Knex) => {
- const result = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
- .where(`${TableName.PamDiscoverySource}.gatewayId`, gatewayId)
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- };
-
- const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const docs = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
- .leftJoin(TableName.Project, `${TableName.PamDiscoverySource}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.PamDiscoverySource}.gatewayPoolId`, gatewayPoolId)
- .select(
- db.ref("id").withSchema(TableName.PamDiscoverySource),
- db.ref("name").withSchema(TableName.PamDiscoverySource),
- db.ref("projectId").withSchema(TableName.PamDiscoverySource),
- db.ref("discoveryType").withSchema(TableName.PamDiscoverySource),
- db.ref("name").withSchema(TableName.Project).as("projectName")
- );
-
- return docs;
- };
-
- const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const result = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
- .where(`${TableName.PamDiscoverySource}.gatewayPoolId`, gatewayPoolId)
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- };
-
- return {
- ...orm,
- findByProjectId,
- findDueForScan,
- findByGatewayId,
- countByGatewayId,
- findByGatewayPoolId,
- countByGatewayPoolId
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts
deleted file mode 100644
index b17340866a..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify } from "@app/lib/knex";
-
-export type TPamDiscoverySourceDependenciesDALFactory = ReturnType<typeof pamDiscoverySourceDependenciesDALFactory>;
-
-export const pamDiscoverySourceDependenciesDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDiscoverySourceDependency);
-
- const countByDiscoverySourceId = async (discoverySourceId: string, tx?: Knex) => {
- try {
- const result = await (tx || db.replicaNode())(TableName.PamDiscoverySourceDependency)
- .where({ discoverySourceId })
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- } catch (error) {
- throw new DatabaseError({ error, name: "Count discovered dependencies by source ID" });
- }
- };
-
- const countByDiscoverySourceIds = async (discoverySourceIds: string[], tx?: Knex) => {
- try {
- const rows = await (tx || db.replicaNode())(TableName.PamDiscoverySourceDependency)
- .whereIn("discoverySourceId", discoverySourceIds)
- .groupBy("discoverySourceId")
- .select("discoverySourceId")
- .count("*", { as: "count" });
-
- return Object.fromEntries(rows.map((r) => [r.discoverySourceId, Number(r.count)]));
- } catch (error) {
- throw new DatabaseError({ error, name: "Count PAM discovery source dependencies by source IDs" });
- }
- };
-
- const upsertJunction = async (
- {
- discoverySourceId,
- dependencyId,
- lastSeenRunId
- }: {
- discoverySourceId: string;
- dependencyId: string;
- lastSeenRunId: string;
- },
- tx?: Knex
- ) => {
- try {
- const now = new Date();
- const knex = tx || db;
-
- await knex(TableName.PamDiscoverySourceDependency)
- .insert({
- discoverySourceId,
- dependencyId,
- lastSeenAt: now,
- lastSeenRunId,
- isStale: false
- })
- .onConflict(["discoverySourceId", "dependencyId"])
- .merge({
- lastSeenAt: now,
- lastSeenRunId,
- isStale: false
- });
- } catch (error) {
- throw new DatabaseError({ error, name: "Upsert PAM discovery source dependency junction" });
- }
- };
-
- const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
- try {
- const knex = tx || db;
-
- const result = await knex(TableName.PamDiscoverySourceDependency)
- .where({ discoverySourceId })
- .andWhere((qb) => {
- void qb.whereNull("lastSeenRunId").orWhereNot("lastSeenRunId", runId);
- })
- .andWhere("isStale", false)
- .update({ isStale: true });
-
- return result;
- } catch (error) {
- throw new DatabaseError({ error, name: "Mark stale PAM discovery source dependencies" });
- }
- };
-
- return {
- ...orm,
- countByDiscoverySourceId,
- countByDiscoverySourceIds,
- upsertJunction,
- markStaleForRun
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts
deleted file mode 100644
index ed70fdee76..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import { Knex } from "knex";
-import { z } from "zod";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-
-import { DiscoveredResourceSchema } from "./pam-discovery-schemas";
-
-export type TPamDiscoverySourceResourcesDALFactory = ReturnType<typeof pamDiscoverySourceResourcesDALFactory>;
-
-export const pamDiscoverySourceResourcesDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDiscoverySourceResource);
-
- const findByDiscoverySourceIdWithResources = async (
- discoverySourceId: string,
- { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamDiscoverySourceResource)
- .join(
- TableName.PamResource,
- `${TableName.PamDiscoverySourceResource}.resourceId`,
- `${TableName.PamResource}.id`
- )
- .where(`${TableName.PamDiscoverySourceResource}.discoverySourceId`, discoverySourceId);
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(
- selectAllTableCols(TableName.PamDiscoverySourceResource),
- db.ref("name").withSchema(TableName.PamResource).as("resourceName"),
- db.ref("resourceType").withSchema(TableName.PamResource).as("resourceType"),
- db.ref("encryptedResourceMetadata").withSchema(TableName.PamResource).as("encryptedResourceMetadata")
- );
-
- void query.orderBy(`${TableName.PamResource}.name`, "asc");
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [resources, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return {
- resources: resources as unknown as z.infer<typeof DiscoveredResourceSchema>[],
- totalCount
- };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find discovered resources by source ID" });
- }
- };
-
- const upsertJunction = async (
- {
- discoverySourceId,
- resourceId,
- lastDiscoveredRunId
- }: {
- discoverySourceId: string;
- resourceId: string;
- lastDiscoveredRunId: string;
- },
- tx?: Knex
- ) => {
- try {
- const now = new Date();
- const knex = tx || db;
-
- await knex(TableName.PamDiscoverySourceResource)
- .insert({
- discoverySourceId,
- resourceId,
- lastDiscoveredAt: now,
- lastDiscoveredRunId,
- isStale: false
- })
- .onConflict(["discoverySourceId", "resourceId"])
- .merge({
- lastDiscoveredAt: now,
- lastDiscoveredRunId,
- isStale: false
- });
- } catch (error) {
- throw new DatabaseError({ error, name: "Upsert PAM discovery source resource junction" });
- }
- };
-
- const countByDiscoverySourceIds = async (discoverySourceIds: string[], tx?: Knex) => {
- try {
- const rows = await (tx || db.replicaNode())(TableName.PamDiscoverySourceResource)
- .whereIn("discoverySourceId", discoverySourceIds)
- .groupBy("discoverySourceId")
- .select("discoverySourceId")
- .count("*", { as: "count" });
-
- return Object.fromEntries(rows.map((r) => [r.discoverySourceId, Number(r.count)]));
- } catch (error) {
- throw new DatabaseError({ error, name: "Count PAM discovery source resources by source IDs" });
- }
- };
-
- const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
- try {
- const knex = tx || db;
-
- const result = await knex(TableName.PamDiscoverySourceResource)
- .where({ discoverySourceId })
- .andWhere((qb) => {
- void qb.whereNull("lastDiscoveredRunId").orWhereNot("lastDiscoveredRunId", runId);
- })
- .andWhere("isStale", false)
- .update({ isStale: true });
-
- return result;
- } catch (error) {
- throw new DatabaseError({ error, name: "Mark stale PAM discovery source resources" });
- }
- };
-
- return {
- ...orm,
- findByDiscoverySourceIdWithResources,
- countByDiscoverySourceIds,
- upsertJunction,
- markStaleForRun
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.ts
deleted file mode 100644
index eb87e3ad1b..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName, TPamDiscoverySourceRuns } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-
-export type TPamDiscoverySourceRunDALFactory = ReturnType<typeof pamDiscoveryRunDALFactory>;
-
-export const pamDiscoveryRunDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDiscoverySourceRun);
-
- const findByDiscoverySourceId = async (
- discoverySourceId: string,
- { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamDiscoverySourceRun).where({ discoverySourceId });
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamDiscoverySourceRun)).orderBy("createdAt", "desc");
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [runs, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return { runs, totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM discovery runs by source ID" });
- }
- };
-
- const findLatestBySourceId = async (discoverySourceId: string, tx?: Knex) => {
- try {
- const doc = await (tx || db.replicaNode())(TableName.PamDiscoverySourceRun)
- .where({ discoverySourceId })
- .orderBy("createdAt", "desc")
- .first();
-
- return (doc as TPamDiscoverySourceRuns) || null;
- } catch (error) {
- throw new DatabaseError({ error, name: "Find latest PAM discovery run by source ID" });
- }
- };
-
- return {
- ...orm,
- findByDiscoverySourceId,
- findLatestBySourceId
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
deleted file mode 100644
index 5d30f98002..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
+++ /dev/null
@@ -1,881 +0,0 @@
-import { ForbiddenError, subject } from "@casl/ability";
-
-import { ActionProjectType, OrganizationActionScope, TPamDiscoverySources } from "@app/db/schemas";
-import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
-import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionActions,
- ProjectPermissionPamAccountActions,
- ProjectPermissionPamDiscoveryActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-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 { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
-import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
-import { decryptResourceMetadata } from "../pam-resource/pam-resource-fns";
-import { TPamAccountDependenciesDALFactory } from "./pam-account-dependencies-dal";
-import { PamDiscoverySourceRunStatus, PamDiscoverySourceStatus, PamDiscoveryType } from "./pam-discovery-enums";
-import { PAM_DISCOVERY_FACTORY_MAP } from "./pam-discovery-factory";
-import {
- decryptDiscoveryCredentials,
- decryptDiscoverySource,
- encryptDiscoveryCredentials,
- listDiscoverySourceOptions
-} from "./pam-discovery-fns";
-import { TPamDiscoveryQueueFactory } from "./pam-discovery-queue";
-import { TPamDiscoverySourceAccountsDALFactory } from "./pam-discovery-source-accounts-dal";
-import { TPamDiscoverySourceDALFactory } from "./pam-discovery-source-dal";
-import { TPamDiscoverySourceDependenciesDALFactory } from "./pam-discovery-source-dependencies-dal";
-import { TPamDiscoverySourceResourcesDALFactory } from "./pam-discovery-source-resources-dal";
-import { TPamDiscoverySourceRunDALFactory } from "./pam-discovery-source-run-dal";
-import {
- TCreatePamDiscoverySourceDTO,
- TGetDiscoveredAccountsDTO,
- TGetDiscoveredResourcesDTO,
- TGetPamDiscoverySourceRunDTO,
- TGetPamDiscoverySourceRunsDTO,
- TListPamDiscoverySourcesDTO,
- TPamDiscoveryConfiguration,
- TPamDiscoveryCredentials,
- TUpdatePamDiscoverySourceDTO
-} from "./pam-discovery-types";
-
-type TPamDiscoverySourceServiceFactoryDep = {
- pamDiscoverySourceDAL: Pick<
- TPamDiscoverySourceDALFactory,
- "create" | "findById" | "updateById" | "deleteById" | "findByProjectId"
- >;
- pamDiscoveryRunDAL: Pick<
- TPamDiscoverySourceRunDALFactory,
- "findByDiscoverySourceId" | "findLatestBySourceId" | "findById" | "find"
- >;
- pamDiscoverySourceResourcesDAL: Pick<
- TPamDiscoverySourceResourcesDALFactory,
- "findByDiscoverySourceIdWithResources" | "countByDiscoverySourceIds"
- >;
- pamDiscoverySourceAccountsDAL: Pick<
- TPamDiscoverySourceAccountsDALFactory,
- "findByDiscoverySourceIdWithAccounts" | "countByDiscoverySourceIds"
- >;
- pamDiscoverySourceDependenciesDAL: Pick<TPamDiscoverySourceDependenciesDALFactory, "countByDiscoverySourceIds">;
- pamAccountDependenciesDAL: Pick<
- TPamAccountDependenciesDALFactory,
- | "countByAccountIds"
- | "countByResourceIds"
- | "findByAccountId"
- | "findByResourceId"
- | "findById"
- | "updateById"
- | "deleteById"
- >;
- pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithParentDetails" | "findMetadataByAccountIds">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- gatewayPoolService: Pick<
- TGatewayPoolServiceFactory,
- "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"
- >;
- pamDiscoveryQueue: Pick<TPamDiscoveryQueueFactory, "queuePamDiscoveryScan">;
-};
-
-export type TPamDiscoverySourceServiceFactory = ReturnType<typeof pamDiscoverySourceServiceFactory>;
-
-export const pamDiscoverySourceServiceFactory = ({
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamAccountDAL,
- pamResourceDAL,
- permissionService,
- kmsService,
- gatewayV2DAL,
- gatewayV2Service,
- gatewayPoolService,
- pamDiscoveryQueue
-}: TPamDiscoverySourceServiceFactoryDep) => {
- const create = async (
- {
- projectId,
- name,
- discoveryType,
- gatewayId,
- gatewayPoolId,
- discoveryCredentials,
- discoveryConfiguration,
- schedule
- }: TCreatePamDiscoverySourceDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
- if (!gatewayId && !gatewayPoolId) {
- throw new BadRequestError({ message: "A gateway or gateway pool is required" });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Create,
- ProjectPermissionSub.PamDiscovery
- );
-
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor: actor.type,
- actorId: actor.id,
- orgId: actor.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId
- });
-
- if (gatewayId) {
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayActions.AttachGateways,
- OrgPermissionSubjects.Gateway
- );
-
- const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });
- if (!gateway) {
- throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });
- }
- } else if (gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
- }
-
- const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });
- if (!validationGatewayId) throw new BadRequestError({ message: "A gateway or gateway pool is required" });
-
- const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](
- discoveryType,
- discoveryConfiguration,
- discoveryCredentials,
- validationGatewayId,
- projectId,
- gatewayV2Service
- );
- await factory.validateConnection();
-
- const encryptedDiscoveryCredentials = await encryptDiscoveryCredentials({
- projectId,
- credentials: discoveryCredentials,
- kmsService
- });
-
- try {
- const discoverySource = await pamDiscoverySourceDAL.create({
- projectId,
- name,
- discoveryType,
- gatewayId: gatewayPoolId ? null : gatewayId,
- gatewayPoolId: gatewayPoolId ?? null,
- encryptedDiscoveryCredentials,
- discoveryConfiguration,
- schedule,
- status: PamDiscoverySourceStatus.Active
- });
-
- return await decryptDiscoverySource(discoverySource, projectId, kmsService);
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Discovery Source with name '${name}' already exists for this project`
- });
- }
- throw err;
- }
- };
-
- const updateById = async (
- {
- discoverySourceId,
- name,
- gatewayId,
- gatewayPoolId,
- discoveryCredentials,
- discoveryConfiguration,
- schedule
- }: TUpdatePamDiscoverySourceDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
-
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Edit,
- ProjectPermissionSub.PamDiscovery
- );
-
- const updateDoc: Partial<TPamDiscoverySources> = {};
-
- if (gatewayId && gatewayId !== discoverySource.gatewayId) {
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor: actor.type,
- actorId: actor.id,
- orgId: actor.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId
- });
-
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayActions.AttachGateways,
- OrgPermissionSubjects.Gateway
- );
-
- const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });
- if (!gateway) {
- throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });
- }
- updateDoc.gatewayId = gatewayId;
- updateDoc.gatewayPoolId = null;
- } else if (gatewayPoolId && gatewayPoolId !== discoverySource.gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
-
- updateDoc.gatewayPoolId = gatewayPoolId;
- updateDoc.gatewayId = null;
- }
-
- if (name !== undefined) updateDoc.name = name;
- if (discoveryConfiguration !== undefined) updateDoc.discoveryConfiguration = discoveryConfiguration;
- if (schedule !== undefined) updateDoc.schedule = schedule;
-
- let finalCredentials: TPamDiscoveryCredentials | undefined;
- if (discoveryCredentials) {
- finalCredentials = { ...discoveryCredentials };
-
- // Handle unchanged password sentinel
- if (discoverySource.encryptedDiscoveryCredentials) {
- const currentCredentials = await decryptDiscoveryCredentials({
- projectId: discoverySource.projectId,
- encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
- kmsService
- });
-
- if (
- "password" in finalCredentials &&
- (finalCredentials as { password?: string }).password === "__INFISICAL_UNCHANGED__" &&
- "password" in currentCredentials
- ) {
- finalCredentials = {
- ...finalCredentials,
- password: (currentCredentials as { password: string }).password
- };
- }
- }
-
- updateDoc.encryptedDiscoveryCredentials = await encryptDiscoveryCredentials({
- projectId: discoverySource.projectId,
- credentials: finalCredentials,
- kmsService
- });
- }
-
- if (gatewayId || gatewayPoolId || discoveryConfiguration || discoveryCredentials) {
- const effectiveAttachedGatewayId =
- updateDoc.gatewayId !== undefined ? updateDoc.gatewayId : discoverySource.gatewayId;
- const effectiveAttachedPoolId =
- updateDoc.gatewayPoolId !== undefined ? updateDoc.gatewayPoolId : discoverySource.gatewayPoolId;
- const effectiveConfiguration = (discoveryConfiguration ??
- discoverySource.discoveryConfiguration) as TPamDiscoveryConfiguration;
-
- let effectiveCredentials = finalCredentials;
- if (!effectiveCredentials && discoverySource.encryptedDiscoveryCredentials) {
- effectiveCredentials = await decryptDiscoveryCredentials({
- projectId: discoverySource.projectId,
- encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
- kmsService
- });
- }
-
- const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: effectiveAttachedGatewayId,
- gatewayPoolId: effectiveAttachedPoolId
- });
-
- if (validationGatewayId && effectiveCredentials) {
- const factory = PAM_DISCOVERY_FACTORY_MAP[discoverySource.discoveryType as PamDiscoveryType](
- discoverySource.discoveryType as PamDiscoveryType,
- effectiveConfiguration,
- effectiveCredentials,
- validationGatewayId,
- discoverySource.projectId,
- gatewayV2Service
- );
- await factory.validateConnection();
- }
- }
-
- // If nothing was updated, return the fetched resource
- if (Object.keys(updateDoc).length === 0) {
- return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
- }
-
- try {
- const updatedResource = await pamDiscoverySourceDAL.updateById(discoverySourceId, updateDoc);
- return await decryptDiscoverySource(updatedResource, discoverySource.projectId, kmsService);
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Discovery Source with name '${name}' already exists for this project`
- });
- }
- throw err;
- }
- };
-
- const deleteById = async (id: string, actor: OrgServiceActor) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(id);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${id}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Delete,
- ProjectPermissionSub.PamDiscovery
- );
-
- await pamDiscoverySourceDAL.deleteById(id);
-
- return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
- };
-
- const getById = async (id: string, discoveryType: PamDiscoveryType, actor: OrgServiceActor) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(id);
- if (!discoverySource) throw new NotFoundError({ message: `Discovery source with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- if (discoverySource.discoveryType !== discoveryType) {
- throw new BadRequestError({
- message: `Discovery source with ID '${id}' is not of type '${discoveryType}'`
- });
- }
-
- return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
- };
-
- const list = async ({
- projectId,
- offset,
- limit,
- search,
- orderBy,
- orderDirection,
- filterDiscoveryTypes,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TListPamDiscoverySourcesDTO) => {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- const { sources, totalCount } = await pamDiscoverySourceDAL.findByProjectId(projectId, {
- offset,
- limit,
- search,
- orderBy,
- orderDirection,
- filterDiscoveryTypes
- });
-
- const sourceIds = sources.map((s) => s.id);
-
- const [resourceCounts, accountCounts, dependencyCounts]: { [k: string]: number }[] = await Promise.all([
- sourceIds.length ? pamDiscoverySourceResourcesDAL.countByDiscoverySourceIds(sourceIds) : {},
- sourceIds.length ? pamDiscoverySourceAccountsDAL.countByDiscoverySourceIds(sourceIds) : {},
- sourceIds.length ? pamDiscoverySourceDependenciesDAL.countByDiscoverySourceIds(sourceIds) : {}
- ]);
-
- return {
- sources: await Promise.all(
- sources.map(async (src) => ({
- ...(await decryptDiscoverySource(src, projectId, kmsService)),
- totalResources: resourceCounts[src.id] ?? 0,
- totalAccounts: accountCounts[src.id] ?? 0,
- totalDependencies: dependencyCounts[src.id] ?? 0
- }))
- ),
- totalCount
- };
- };
-
- const triggerScanById = async (id: string, actor: OrgServiceActor) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(id);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${id}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.RunScan,
- ProjectPermissionSub.PamDiscovery
- );
-
- if (discoverySource.status !== PamDiscoverySourceStatus.Active) {
- throw new BadRequestError({ message: "Cannot trigger scan on a non-active Discovery Source" });
- }
-
- // Check if a scan is already running
- const latestRun = await pamDiscoveryRunDAL.findLatestBySourceId(id);
- if (latestRun && latestRun.status === PamDiscoverySourceRunStatus.Running) {
- throw new BadRequestError({ message: "A scan is already in progress for this Discovery Source" });
- }
-
- await pamDiscoveryQueue.queuePamDiscoveryScan(id);
-
- return { message: "Scan queued successfully", discoverySource };
- };
-
- const getDiscoveryRuns = async (
- { discoverySourceId, offset, limit }: TGetPamDiscoverySourceRunsDTO,
- actor: OrgServiceActor
- ) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- const result = await pamDiscoveryRunDAL.findByDiscoverySourceId(discoverySourceId, { offset, limit });
- return { ...result, discoverySource };
- };
-
- const getDiscoveryRunById = async (
- { discoverySourceId, runId }: TGetPamDiscoverySourceRunDTO,
- actor: OrgServiceActor
- ) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- const run = await pamDiscoveryRunDAL.findById(runId);
- if (!run || run.discoverySourceId !== discoverySourceId) {
- throw new NotFoundError({ message: `Discovery Run with ID '${runId}' not found` });
- }
-
- return { run, discoverySource };
- };
-
- const getDiscoveredResources = async (
- { discoverySourceId, offset, limit }: TGetDiscoveredResourcesDTO,
- actor: OrgServiceActor
- ) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- const { resources, totalCount } = await pamDiscoverySourceResourcesDAL.findByDiscoverySourceIdWithResources(
- discoverySourceId,
- { offset, limit }
- );
-
- const decryptedResources = await Promise.all(
- resources.map(async (resource) => {
- const { encryptedResourceMetadata, ...rest } = resource as typeof resource & {
- encryptedResourceMetadata?: Buffer | null;
- };
- if (!encryptedResourceMetadata) return rest;
- try {
- const resourceInternalMetadata = await decryptResourceMetadata({
- projectId: discoverySource.projectId,
- encryptedMetadata: encryptedResourceMetadata,
- kmsService
- });
- return { ...rest, resourceInternalMetadata };
- } catch {
- return rest;
- }
- })
- );
-
- // Add dependency counts per resource
- const resourceIds = decryptedResources.map((r) => r.resourceId).filter(Boolean);
- const depCountsByResource = resourceIds.length
- ? await pamAccountDependenciesDAL.countByResourceIds(resourceIds)
- : {};
-
- const resourcesWithDeps = decryptedResources.map((r) => ({
- ...r,
- dependencyCount: (r.resourceId ? depCountsByResource[r.resourceId] : 0) ?? 0
- }));
-
- return { resources: resourcesWithDeps, totalCount, discoverySource };
- };
-
- const getDiscoveredAccounts = async (
- { discoverySourceId, offset, limit }: TGetDiscoveredAccountsDTO,
- actor: OrgServiceActor
- ) => {
- const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
- if (!discoverySource) {
- throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: discoverySource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamDiscoveryActions.Read,
- ProjectPermissionSub.PamDiscovery
- );
-
- const result = await pamDiscoverySourceAccountsDAL.findByDiscoverySourceIdWithAccounts(discoverySourceId, {
- offset,
- limit
- });
-
- // Add dependency counts per account
- const accountIds = result.accounts.map((a) => a.accountId).filter(Boolean);
- const depCountsByAccount = accountIds.length ? await pamAccountDependenciesDAL.countByAccountIds(accountIds) : {};
-
- const accountsWithDeps = result.accounts.map((a) => ({
- ...a,
- dependencyCount: (a.accountId ? depCountsByAccount[a.accountId] : 0) ?? 0
- }));
-
- return { accounts: accountsWithDeps, totalCount: result.totalCount, discoverySource };
- };
-
- const verifyAccountPermission = async (
- accountId: string,
- action: ProjectPermissionPamAccountActions,
- actor: ActorType,
- actorId: string,
- actorAuthMethod: ActorAuthMethod,
- actorOrgId: string
- ) => {
- const accountWithParent = await pamAccountDAL.findByIdWithParentDetails(accountId);
- if (!accountWithParent) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: accountWithParent.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds([accountWithParent.id]);
- const accountMetadata = metadataByAccountId[accountWithParent.id] || [];
-
- ForbiddenError.from(permission).throwUnlessCan(
- action,
- subject(ProjectPermissionSub.PamAccounts, {
- accountName: accountWithParent.name,
- ...(accountWithParent.resource && {
- resourceName: accountWithParent.resource.name,
- resourceType: accountWithParent.resource.resourceType
- }),
- ...(accountWithParent.domain && {
- domainName: accountWithParent.domain.name,
- domainType: accountWithParent.domain.domainType
- }),
- metadata: accountMetadata
- })
- );
-
- return accountWithParent;
- };
-
- const decryptDependencySyncMessages = async <T extends { encryptedLastSyncMessage?: Buffer | null }>(
- deps: T[],
- projectId: string
- ): Promise<(T & { lastSyncMessage: string | null })[]> => {
- if (!deps.length) return deps.map((d) => ({ ...d, lastSyncMessage: null as string | null }));
-
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- return deps.map((dep) => {
- let lastSyncMessage: string | null = null;
- if (dep.encryptedLastSyncMessage) {
- try {
- lastSyncMessage = decryptor({ cipherTextBlob: dep.encryptedLastSyncMessage }).toString();
- } catch {
- lastSyncMessage = "Failed to decrypt error message";
- }
- }
- return { ...dep, lastSyncMessage };
- });
- };
-
- const getAccountDependencies = async ({
- accountId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: {
- accountId: string;
- actor: ActorType;
- actorId: string;
- actorAuthMethod: ActorAuthMethod;
- actorOrgId: string;
- }) => {
- const accountWithParent = await verifyAccountPermission(
- accountId,
- ProjectPermissionPamAccountActions.Read,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- );
- const deps = await pamAccountDependenciesDAL.findByAccountId(accountId);
- return decryptDependencySyncMessages(deps, accountWithParent.projectId);
- };
-
- const getResourceDependencies = async ({
- resourceId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: {
- resourceId: string;
- actor: ActorType;
- actorId: string;
- actorAuthMethod: ActorAuthMethod;
- actorOrgId: string;
- }) => {
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: resource.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, { name: resource.name, resourceType: resource.resourceType })
- );
-
- const deps = await pamAccountDependenciesDAL.findByResourceId(resourceId);
- return decryptDependencySyncMessages(deps, resource.projectId);
- };
-
- const updateAccountDependency = async ({
- accountId,
- dependencyId,
- isRotationSyncEnabled,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: {
- accountId: string;
- dependencyId: string;
- isRotationSyncEnabled: boolean;
- actor: ActorType;
- actorId: string;
- actorAuthMethod: ActorAuthMethod;
- actorOrgId: string;
- }) => {
- await verifyAccountPermission(
- accountId,
- ProjectPermissionPamAccountActions.Edit,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- );
-
- const dep = await pamAccountDependenciesDAL.findById(dependencyId);
- if (!dep || dep.accountId !== accountId) {
- throw new NotFoundError({ message: "Dependency not found" });
- }
- return pamAccountDependenciesDAL.updateById(dependencyId, { isRotationSyncEnabled });
- };
-
- const deleteAccountDependency = async ({
- accountId,
- dependencyId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: {
- accountId: string;
- dependencyId: string;
- actor: ActorType;
- actorId: string;
- actorAuthMethod: ActorAuthMethod;
- actorOrgId: string;
- }) => {
- await verifyAccountPermission(
- accountId,
- ProjectPermissionPamAccountActions.Edit,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- );
-
- const dep = await pamAccountDependenciesDAL.findById(dependencyId);
- if (!dep || dep.accountId !== accountId) {
- throw new NotFoundError({ message: "Dependency not found" });
- }
- return pamAccountDependenciesDAL.deleteById(dependencyId);
- };
-
- return {
- create,
- updateById,
- deleteById,
- getById,
- list,
- triggerScanById,
- getDiscoveryRuns,
- getDiscoveryRunById,
- getDiscoveredResources,
- getDiscoveredAccounts,
- getAccountDependencies,
- getResourceDependencies,
- updateAccountDependency,
- deleteAccountDependency,
- listDiscoverySourceOptions
- };
-};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
deleted file mode 100644
index 0e81bccc9a..0000000000
--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { OrderByDirection, TProjectPermission } from "@app/lib/types";
-
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import {
- TActiveDirectoryDiscoverySource,
- TActiveDirectoryDiscoverySourceConfiguration,
- TActiveDirectoryDiscoverySourceCredentials
-} from "./active-directory/active-directory-discovery-types";
-import { PamDiscoveryOrderBy, PamDiscoverySourceRunTrigger, PamDiscoveryType } from "./pam-discovery-enums";
-import { TPamDiscoveryScanDeps } from "./pam-discovery-factory";
-
-export type TPamDiscoverySource = TActiveDirectoryDiscoverySource;
-export type TPamDiscoveryCredentials = TActiveDirectoryDiscoverySourceCredentials;
-export type TPamDiscoveryConfiguration = TActiveDirectoryDiscoverySourceConfiguration;
-
-// Discovery Source DTOs
-export type TCreatePamDiscoverySourceDTO = Pick<
- TPamDiscoverySource,
- "name" | "projectId" | "discoveryType" | "discoveryConfiguration" | "schedule"
-> & {
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- discoveryCredentials: TPamDiscoveryCredentials;
-};
-
-export type TUpdatePamDiscoverySourceDTO = Partial<
- Omit<TCreatePamDiscoverySourceDTO, "projectId" | "discoveryType">
-> & {
- discoverySourceId: string;
-};
-
-export type TListPamDiscoverySourcesDTO = {
- projectId: string;
- offset?: number;
- limit?: number;
- search?: string;
- orderBy?: PamDiscoveryOrderBy;
- orderDirection?: OrderByDirection;
- filterDiscoveryTypes?: string[];
-} & Omit<TProjectPermission, "projectId">;
-
-// Discovery Run DTOs
-export type TGetPamDiscoverySourceRunsDTO = {
- discoverySourceId: string;
- offset?: number;
- limit?: number;
-};
-
-export type TGetPamDiscoverySourceRunDTO = {
- discoverySourceId: string;
- runId: string;
-};
-
-// Discovered items DTOs
-export type TGetDiscoveredResourcesDTO = {
- discoverySourceId: string;
- offset?: number;
- limit?: number;
-};
-
-export type TGetDiscoveredAccountsDTO = {
- discoverySourceId: string;
- offset?: number;
- limit?: number;
-};
-
-// Factory
-export type TPamDiscoveryFactory<T extends TPamDiscoveryConfiguration, C extends TPamDiscoveryCredentials> = (
- discoveryType: PamDiscoveryType,
- configuration: T,
- credentials: C,
- gatewayId: string,
- projectId: string,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- gatewayPoolId?: string | null
-) => {
- validateConnection: () => Promise<void>;
- scan: (
- discoverySourceId: string,
- triggeredBy: PamDiscoverySourceRunTrigger,
- deps: TPamDiscoveryScanDeps
- ) => Promise<void>;
-};
diff --git a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-enums.ts b/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-enums.ts
deleted file mode 100644
index 3e1783a57e..0000000000
--- a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-enums.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export enum ActiveDirectoryAccountType {
- User = "user",
- Service = "service"
-}
diff --git a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-factory.ts b/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-factory.ts
deleted file mode 100644
index 2f3f8caff6..0000000000
--- a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-factory.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-import ldapjs from "@infisical/ldapjs";
-
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { PamResource } from "../../pam-resource/pam-resource-enums";
-import {
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPostRotateContext
-} from "../../pam-resource/pam-resource-types";
-import { syncDependenciesAfterRotation } from "../../pam-resource/shared/dependency-sync-fns";
-import { resolveDnsTcp } from "../../pam-resource/shared/dns-over-dc";
-import { generatePassword } from "../../secret-rotation-v2/shared/utils";
-import { TPamDomainFactory } from "../pam-domain-types";
-import { TActiveDirectoryAccountCredentials, TActiveDirectoryConnectionDetails } from "./active-directory-domain-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-const executeWithGateway = async <T>(
- config: {
- connectionDetails: TActiveDirectoryConnectionDetails;
- resourceType: PamResource;
- gatewayId: string;
- targetPortOverride?: number;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (proxyPort: number) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId, targetPortOverride } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.dcAddress,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: targetPortOverride ?? connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- return operation(proxyPort);
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const activeDirectoryDomainFactory: TPamDomainFactory<
- TActiveDirectoryConnectionDetails,
- TActiveDirectoryAccountCredentials
-> = (domainType, connectionDetails, gatewayId, gatewayV2Service) => {
- const resourceType = domainType as unknown as PamResource;
- const ldapProtocol = connectionDetails.useLdaps ? "ldaps" : "ldap";
-
- const buildLdapTlsOptions = () => {
- if (!connectionDetails.useLdaps) return {};
- return {
- tlsOptions: {
- rejectUnauthorized: connectionDetails.ldapRejectUnauthorized,
- ...(connectionDetails.ldapCaCert && {
- ca: [connectionDetails.ldapCaCert],
- servername: connectionDetails.ldapTlsServerName || connectionDetails.dcAddress
- })
- }
- };
- };
-
- const validateConnection = async () => {
- if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for connection validation" });
-
- try {
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const client = ldapjs.createClient({
- url: `${ldapProtocol}://localhost:${proxyPort}`,
- connectTimeout: EXTERNAL_REQUEST_TIMEOUT,
- timeout: EXTERNAL_REQUEST_TIMEOUT,
- ...buildLdapTlsOptions()
- });
-
- let clientError: Error | null = null;
- client.on("error", (err: Error) => {
- clientError = err;
- try {
- client.unbind();
- } catch {
- // do nothing
- }
- reject(err);
- });
-
- // Anonymous bind to verify this is a reachable LDAP server
- client.bind("", "", (err) => {
- if (clientError) return;
-
- if (err) {
- // Connection-level errors mean the server is unreachable
- // Any other LDAP error (e.g. InvalidCredentialsError) means the server responded with a protocol-level rejection
- if (err.name === "ConnectionError" || err.name === "TimeoutError") {
- client.unbind();
- reject(err);
- } else if ("lde_message" in err) {
- logger.info("[Active Directory Domain Factory] LDAP connection validated (server responded)");
- client.unbind();
- resolve();
- } else {
- client.unbind();
- reject(err);
- }
- } else {
- logger.info("[Active Directory Resource Factory] LDAP anonymous bind successful");
- client.unbind();
- resolve();
- }
- });
- });
- });
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
-
- return connectionDetails;
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<
- TActiveDirectoryAccountCredentials
- > = async (credentials) => {
- if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for credential validation" });
-
- try {
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const bindDn = `${credentials.username}@${connectionDetails.domain}`;
-
- const client = ldapjs.createClient({
- url: `${ldapProtocol}://localhost:${proxyPort}`,
- connectTimeout: EXTERNAL_REQUEST_TIMEOUT,
- timeout: EXTERNAL_REQUEST_TIMEOUT,
- ...buildLdapTlsOptions()
- });
-
- let clientError: Error | null = null;
- client.on("error", (err: Error) => {
- clientError = err;
- try {
- client.unbind();
- } catch {
- // do nothing
- }
- reject(err);
- });
-
- client.bind(bindDn, credentials.password, (err) => {
- if (clientError) return;
-
- if (err) {
- client.unbind();
- logger.warn(err, "[Active Directory Resource Factory] LDAP bind failed during credential validation");
- reject(new Error(`LDAP bind failed: ${err.message}`));
- } else {
- logger.info("[Active Directory Resource Factory] LDAP credential validation successful");
- client.unbind();
- resolve();
- }
- });
- });
- });
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
-
- return credentials;
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<
- TActiveDirectoryAccountCredentials
- > = async (rotationAccountCredentials, currentCredentials) => {
- if (!gatewayId) throw new BadRequestError({ message: "Gateway is required for AD credential rotation" });
-
- const newPassword = generatePassword();
-
- if (!connectionDetails.useLdaps) {
- throw new BadRequestError({
- message: "LDAPS must be enabled on this Active Directory resource to perform password rotation"
- });
- }
-
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const client = ldapjs.createClient({
- url: `ldaps://localhost:${proxyPort}`,
- connectTimeout: EXTERNAL_REQUEST_TIMEOUT,
- timeout: EXTERNAL_REQUEST_TIMEOUT,
- ...buildLdapTlsOptions()
- });
-
- let clientError: Error | null = null;
- client.on("error", (err: Error) => {
- clientError = err;
- try {
- client.unbind();
- } catch {
- // do nothing
- }
- reject(err);
- });
-
- // Bind as rotation account (admin)
- const bindDn = `${rotationAccountCredentials.username}@${connectionDetails.domain}`;
- client.bind(bindDn, rotationAccountCredentials.password, (bindErr) => {
- if (clientError) return;
- if (bindErr) {
- client.unbind();
- reject(new Error(`Rotation account bind failed: ${bindErr.message}`));
- return;
- }
-
- // Search for target user's DN by sAMAccountName
- const searchBase = connectionDetails.domain
- .split(".")
- .map((dc: string) => `DC=${dc}`)
- .join(",");
-
- client.search(
- searchBase,
- {
- filter: new ldapjs.EqualityFilter({ attribute: "sAMAccountName", value: currentCredentials.username }),
- scope: "sub",
- attributes: ["dn"]
- },
- (searchErr, searchRes) => {
- if (searchErr) {
- client.unbind();
- reject(new Error(`LDAP search failed: ${searchErr.message}`));
- return;
- }
-
- let userDn: string | null = null;
-
- searchRes.on("searchEntry", (entry) => {
- userDn = entry.objectName;
- });
-
- searchRes.on("error", (err) => {
- client.unbind();
- reject(new Error(`LDAP search error: ${err.message}`));
- });
-
- searchRes.on("end", () => {
- if (!userDn) {
- client.unbind();
- reject(new Error(`User '${currentCredentials.username}' not found in AD`));
- return;
- }
-
- // Admin reset: use "replace" operation on unicodePwd
- const encodedPassword = Buffer.from(`"${newPassword}"`, "utf16le");
- const change = new ldapjs.Change({
- operation: "replace",
- modification: { type: "unicodePwd", values: [encodedPassword] }
- });
-
- client.modify(userDn, change, (modifyErr) => {
- client.unbind();
- if (modifyErr) {
- reject(new Error(`AD password reset failed: ${modifyErr.message}`));
- } else {
- logger.info(
- `[AD Rotation] Password rotated for domain account [username=${currentCredentials.username}] on [domain=${connectionDetails.domain}]`
- );
- resolve();
- }
- });
- });
- }
- );
- });
- });
- });
-
- return { username: currentCredentials.username, password: newPassword };
- };
-
- const postRotate = async (
- accountId: string,
- newCredentials: TActiveDirectoryAccountCredentials,
- projectId: string,
- ctx: TPostRotateContext,
- rotationAccountCredentials: TActiveDirectoryAccountCredentials
- ) => {
- if (!gatewayId) return;
-
- await syncDependenciesAfterRotation({
- accountId,
- newCredentials,
- projectId,
- ctx,
- gatewayV2Service,
- rotationCredentials: rotationAccountCredentials,
- gatewayId,
- resolveHostname: async (hostname) => {
- // Resolve via DC's DNS through the gateway
- return executeWithGateway(
- { connectionDetails, gatewayId, resourceType, targetPortOverride: 53 },
- gatewayV2Service,
- async (proxyPort) => {
- const ip = await resolveDnsTcp(hostname, proxyPort);
- if (ip) {
- logger.info(`[AD DependencySync] Resolved ${hostname} -> ${ip}`);
- return ip;
- }
- logger.warn(`[AD DependencySync] DNS resolution failed for ${hostname}, using original`);
- return hostname;
- }
- );
- },
- formatWinrmUsername: (rotationUsername) => {
- const netbiosDomain = connectionDetails.domain.split(".")[0].toUpperCase();
- return `${netbiosDomain}\\${rotationUsername}`;
- }
- });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TActiveDirectoryAccountCredentials,
- currentCredentials: TActiveDirectoryAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- postRotate,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-schemas.ts b/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-schemas.ts
deleted file mode 100644
index 14629f16cd..0000000000
--- a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-schemas.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { z } from "zod";
-
-import {
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BaseUpdatePamAccountSchema
-} from "../../pam-resource/pam-resource-schemas";
-import { PamDomainType } from "../pam-domain-enums";
-import { ActiveDirectoryAccountType } from "./active-directory-domain-enums";
-
-export const ActiveDirectoryConnectionDetailsSchema = z.object({
- domain: z.string().trim().min(1).max(255),
- dcAddress: z.string().trim().min(1).max(255),
- port: z.coerce.number().int().min(1).max(65535),
- useLdaps: z.boolean(),
- ldapRejectUnauthorized: z.boolean(),
- ldapCaCert: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional(),
- ldapTlsServerName: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional()
-});
-
-export const ActiveDirectoryAccountCredentialsSchema = z.object({
- username: z.string().trim().min(1).max(255),
- password: z.string().trim().min(1).max(255)
-});
-
-export const ActiveDirectoryAccountMetadataSchema = z.object({
- accountType: z.nativeEnum(ActiveDirectoryAccountType),
- adGuid: z.string().optional(),
- displayName: z.string().optional(),
- userPrincipalName: z.string().optional(),
- servicePrincipalName: z.string().array().optional(),
- userAccountControl: z.number().optional(),
- passwordLastSet: z.string().optional(),
- lastLogon: z.string().optional()
-});
-
-export const ActiveDirectoryAccountSchema = BasePamAccountSchema.extend({
- credentials: ActiveDirectoryAccountCredentialsSchema,
- internalMetadata: ActiveDirectoryAccountMetadataSchema
-});
-
-export const CreateActiveDirectoryAccountSchema = BaseCreatePamAccountSchema.omit({ resourceId: true }).extend({
- domainId: z.string().uuid(),
- credentials: ActiveDirectoryAccountCredentialsSchema,
- internalMetadata: ActiveDirectoryAccountMetadataSchema
-});
-
-export const UpdateActiveDirectoryAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: ActiveDirectoryAccountCredentialsSchema.optional(),
- internalMetadata: ActiveDirectoryAccountMetadataSchema.optional()
-});
-
-export const SanitizedActiveDirectoryAccountWithDomainSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamDomainType.ActiveDirectory),
- credentials: z.object({
- username: z.string()
- }),
- internalMetadata: ActiveDirectoryAccountMetadataSchema
-});
-
-export const ActiveDirectorySessionCredentialsSchema = ActiveDirectoryConnectionDetailsSchema.and(
- ActiveDirectoryAccountCredentialsSchema
-);
diff --git a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-types.ts b/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-types.ts
deleted file mode 100644
index 113bc4e95a..0000000000
--- a/backend/src/ee/services/pam-domain/active-directory/active-directory-domain-types.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { z } from "zod";
-
-import {
- ActiveDirectoryAccountCredentialsSchema,
- ActiveDirectoryAccountMetadataSchema,
- ActiveDirectoryConnectionDetailsSchema
-} from "./active-directory-domain-schemas";
-
-export type TActiveDirectoryConnectionDetails = z.infer<typeof ActiveDirectoryConnectionDetailsSchema>;
-
-export type TActiveDirectoryAccountCredentials = z.infer<typeof ActiveDirectoryAccountCredentialsSchema>;
-export type TActiveDirectoryAccountInternalMetadata = z.infer<typeof ActiveDirectoryAccountMetadataSchema>;
diff --git a/backend/src/ee/services/pam-domain/pam-domain-dal.ts b/backend/src/ee/services/pam-domain/pam-domain-dal.ts
deleted file mode 100644
index e65042c87f..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-dal.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { Knex } from "knex";
-import RE2 from "re2";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { OrderByDirection } from "@app/lib/types";
-
-import { PamDomainOrderBy } from "./pam-domain-enums";
-
-export type TPamDomainDALFactory = ReturnType<typeof pamDomainDALFactory>;
-
-export const pamDomainDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamDomain);
-
- const findById = async (id: string, tx?: Knex) => {
- try {
- const result = await (tx || db.replicaNode())(TableName.PamDomain)
- .leftJoin(TableName.GatewayV2, `${TableName.PamDomain}.gatewayId`, `${TableName.GatewayV2}.id`)
- .where(`${TableName.PamDomain}.id`, id)
- .select(selectAllTableCols(TableName.PamDomain))
- .select(
- db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"),
- db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId")
- )
- .first();
-
- return result || null;
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM domain by ID" });
- }
- };
-
- const findByProjectId = async (
- {
- projectId,
- search,
- limit,
- offset = 0,
- orderBy = PamDomainOrderBy.Name,
- orderDirection = OrderByDirection.ASC,
- filterDomainTypes,
- discoveryFingerprint
- }: {
- projectId: string;
- search?: string;
- limit?: number;
- offset?: number;
- orderBy?: PamDomainOrderBy;
- orderDirection?: OrderByDirection;
- filterDomainTypes?: string[];
- discoveryFingerprint?: string;
- },
- tx?: Knex
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamDomain).where(`${TableName.PamDomain}.projectId`, projectId);
-
- if (search) {
- const escapedSearch = search
- .replace(new RE2(/\\/g), "\\\\")
- .replace(new RE2(/%/g), "\\%")
- .replace(new RE2(/_/g), "\\_");
- const pattern = `%${escapedSearch}%`;
- void query.whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDomain, "name", pattern]);
- }
-
- if (filterDomainTypes && filterDomainTypes.length) {
- void query.whereIn(`${TableName.PamDomain}.domainType`, filterDomainTypes);
- }
-
- if (discoveryFingerprint) {
- void query.where(`${TableName.PamDomain}.discoveryFingerprint`, discoveryFingerprint);
- }
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamDomain));
-
- const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";
- void query.orderByRaw(`${TableName.PamDomain}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]);
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [results, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return { domains: results, totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM domains by project" });
- }
- };
-
- const findMetadataByDomainIds = async (domainIds: string[], tx?: Knex) => {
- if (!domainIds.length) return {};
- const rows = await (tx || db.replicaNode())(TableName.ResourceMetadata)
- .select("id", "key", "value", "pamDomainId")
- .whereIn("pamDomainId", domainIds);
- const byDomainId: Record<string, Array<{ id: string; key: string; value: string }>> = {};
- for (const row of rows) {
- if (row.pamDomainId) {
- if (!byDomainId[row.pamDomainId]) byDomainId[row.pamDomainId] = [];
- byDomainId[row.pamDomainId].push({ id: row.id, key: row.key, value: row.value || "" });
- }
- }
- return byDomainId;
- };
-
- const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const docs = await (tx || db.replicaNode())(TableName.PamDomain)
- .leftJoin(TableName.Project, `${TableName.PamDomain}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.PamDomain}.gatewayPoolId`, gatewayPoolId)
- .select(
- db.ref("id").withSchema(TableName.PamDomain),
- db.ref("name").withSchema(TableName.PamDomain),
- db.ref("projectId").withSchema(TableName.PamDomain),
- db.ref("name").withSchema(TableName.Project).as("projectName")
- );
-
- return docs;
- };
-
- const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const result = await (tx || db.replicaNode())(TableName.PamDomain)
- .where(`${TableName.PamDomain}.gatewayPoolId`, gatewayPoolId)
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- };
-
- return {
- ...orm,
- findById,
- findByProjectId,
- findMetadataByDomainIds,
- findByGatewayPoolId,
- countByGatewayPoolId
- };
-};
diff --git a/backend/src/ee/services/pam-domain/pam-domain-factory.ts b/backend/src/ee/services/pam-domain/pam-domain-factory.ts
deleted file mode 100644
index 1ab6a8a2e3..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-factory.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { TPamAccountCredentials } from "../pam-resource/pam-resource-types";
-import { activeDirectoryDomainFactory } from "./active-directory/active-directory-domain-factory";
-import { PamDomainType } from "./pam-domain-enums";
-import { TPamDomainConnectionDetails, TPamDomainFactory } from "./pam-domain-types";
-
-type TPamDomainFactoryImplementation = TPamDomainFactory<TPamDomainConnectionDetails, TPamAccountCredentials>;
-
-export const PAM_DOMAIN_FACTORY_MAP: Record<PamDomainType, TPamDomainFactoryImplementation> = {
- [PamDomainType.ActiveDirectory]: activeDirectoryDomainFactory as TPamDomainFactoryImplementation
-};
diff --git a/backend/src/ee/services/pam-domain/pam-domain-fns.ts b/backend/src/ee/services/pam-domain/pam-domain-fns.ts
deleted file mode 100644
index bd2d4b4032..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-fns.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { TPamDomainConnectionDetails } from "./pam-domain-types";
-
-export const encryptDomainConnectionDetails = async ({
- projectId,
- connectionDetails,
- kmsService
-}: {
- projectId: string;
- connectionDetails: TPamDomainConnectionDetails;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(connectionDetails))
- });
-
- return cipherTextBlob;
-};
-
-export const decryptDomainConnectionDetails = async ({
- projectId,
- encryptedConnectionDetails,
- kmsService
-}: {
- projectId: string;
- encryptedConnectionDetails: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedConnectionDetails
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as TPamDomainConnectionDetails;
-};
diff --git a/backend/src/ee/services/pam-domain/pam-domain-schemas.ts b/backend/src/ee/services/pam-domain/pam-domain-schemas.ts
deleted file mode 100644
index 8b1580822e..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-schemas.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { z } from "zod";
-
-import { PamDomainsSchema, ResourceMetadataSchema } from "@app/db/schemas";
-import { slugSchema } from "@app/server/lib/schemas";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-import { ActiveDirectoryConnectionDetailsSchema } from "./active-directory/active-directory-domain-schemas";
-import { PamDomainType } from "./pam-domain-enums";
-
-export const BasePamDomainSchema = PamDomainsSchema.omit({
- encryptedConnectionDetails: true,
- domainType: true
-}).extend({
- metadata: ResourceMetadataSchema.pick({ id: true, key: true, value: true }).array().optional()
-});
-
-export const ActiveDirectoryDomainListItemSchema = z.object({
- name: z.literal("Active Directory"),
- domain: z.literal(PamDomainType.ActiveDirectory)
-});
-
-const BaseActiveDirectoryDomainSchema = BasePamDomainSchema.extend({
- domainType: z.literal(PamDomainType.ActiveDirectory)
-});
-
-export const ActiveDirectoryDomainSchema = BaseActiveDirectoryDomainSchema.extend({
- connectionDetails: ActiveDirectoryConnectionDetailsSchema
-});
-
-export const SanitizedActiveDirectoryDomainSchema = BaseActiveDirectoryDomainSchema.extend({
- connectionDetails: ActiveDirectoryConnectionDetailsSchema
-});
-
-const CoreCreatePamDomainSchema = z.object({
- projectId: z.string().uuid(),
- name: slugSchema({ field: "name" }),
- metadata: ResourceMetadataNonEncryptionSchema.optional()
-});
-
-export const CreateActiveDirectoryDomainSchema = CoreCreatePamDomainSchema.extend({
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional(),
- connectionDetails: ActiveDirectoryConnectionDetailsSchema
-}).superRefine((data, ctx) => {
- if (data.gatewayId && data.gatewayPoolId) {
- ctx.addIssue({
- path: ["gatewayPoolId"],
- code: z.ZodIssueCode.custom,
- message: "Cannot specify both a gateway and a gateway pool"
- });
- }
- if (!data.gatewayId && !data.gatewayPoolId) {
- ctx.addIssue({
- path: ["gatewayId"],
- code: z.ZodIssueCode.custom,
- message: "A gateway or gateway pool is required"
- });
- }
-});
-
-const CoreUpdatePamDomainSchema = z.object({
- name: slugSchema({ field: "name" }).optional(),
- metadata: ResourceMetadataNonEncryptionSchema.optional()
-});
-
-export const UpdateActiveDirectoryDomainSchema = CoreUpdatePamDomainSchema.extend({
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional(),
- connectionDetails: ActiveDirectoryConnectionDetailsSchema.optional()
-}).superRefine((data, ctx) => {
- if (data.gatewayId && data.gatewayPoolId) {
- ctx.addIssue({
- path: ["gatewayPoolId"],
- code: z.ZodIssueCode.custom,
- message: "Cannot specify both a gateway and a gateway pool"
- });
- }
-});
-
-export const SanitizedDomainSchema = z.discriminatedUnion("domainType", [SanitizedActiveDirectoryDomainSchema]);
diff --git a/backend/src/ee/services/pam-domain/pam-domain-service.ts b/backend/src/ee/services/pam-domain/pam-domain-service.ts
deleted file mode 100644
index 4e2ca88913..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-service.ts
+++ /dev/null
@@ -1,467 +0,0 @@
-import { ForbiddenError, subject } from "@casl/ability";
-
-import { ActionProjectType, TPamDomains } from "@app/db/schemas";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-
-import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
-import { decryptResourceConnectionDetails } from "../pam-resource/pam-resource-fns";
-import { TWindowsResource } from "../pam-resource/windows-server/windows-server-resource-types";
-import { PamDomainType } from "./pam-domain-enums";
-import { PAM_DOMAIN_FACTORY_MAP } from "./pam-domain-factory";
-import { decryptDomainConnectionDetails, encryptDomainConnectionDetails } from "./pam-domain-fns";
-import {
- TCreateDomainDTO,
- TListDomainsDTO,
- TPamDomain,
- TPamDomainServiceFactoryDep,
- TUpdateDomainDTO
-} from "./pam-domain-types";
-
-export type TPamDomainServiceFactory = ReturnType<typeof pamDomainServiceFactory>;
-
-const decryptDomain = async (
- domain: TPamDomains,
- projectId: string,
- kmsService: TPamDomainServiceFactoryDep["kmsService"]
-): Promise<TPamDomain> => {
- const connectionDetails = await decryptDomainConnectionDetails({
- encryptedConnectionDetails: domain.encryptedConnectionDetails,
- projectId,
- kmsService
- });
-
- return {
- ...domain,
- domainType: domain.domainType as PamDomainType,
- connectionDetails
- } as TPamDomain;
-};
-
-export const pamDomainServiceFactory = ({
- pamDomainDAL,
- pamResourceDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- resourceMetadataDAL
-}: TPamDomainServiceFactoryDep) => {
- const getById = async (id: string, domainType: PamDomainType, actor: OrgServiceActor) => {
- const domain = await pamDomainDAL.findById(id);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: domain.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByDomainId = await pamDomainDAL.findMetadataByDomainIds([domain.id]);
- const domainMetadata = metadataByDomainId[domain.id] || [];
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamDomains, {
- name: domain.name,
- domainType: domain.domainType,
- metadata: domainMetadata
- })
- );
-
- if (domain.domainType !== domainType) {
- throw new BadRequestError({
- message: `Domain with ID '${id}' is not of type '${domainType}'`
- });
- }
-
- return {
- ...(await decryptDomain(domain, domain.projectId, kmsService)),
- metadata: domainMetadata
- };
- };
-
- const create = async (
- { domainType, connectionDetails, gatewayId, gatewayPoolId, name, projectId, metadata }: TCreateDomainDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
- if (!gatewayId && !gatewayPoolId) {
- throw new BadRequestError({ message: "A gateway or gateway pool is required" });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Create,
- subject(ProjectPermissionSub.PamDomains, {
- name,
- domainType,
- metadata: (metadata || []).map(({ key, value }) => ({ key, value: value ?? "" }))
- })
- );
-
- if (gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
- }
-
- const existingDomain = await pamDomainDAL.findOne({ name, projectId });
- if (existingDomain) {
- throw new BadRequestError({
- message: `Domain with name '${name}' already exists in this project`
- });
- }
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });
-
- const factory = PAM_DOMAIN_FACTORY_MAP[domainType](
- domainType,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- projectId
- );
-
- const validatedConnectionDetails = await factory.validateConnection();
- const encryptedConnectionDetails = await encryptDomainConnectionDetails({
- connectionDetails: validatedConnectionDetails,
- projectId,
- kmsService
- });
-
- try {
- const { domain: newDomain, insertedMetadata } = await pamDomainDAL.transaction(async (tx) => {
- const created = await pamDomainDAL.create(
- {
- domainType,
- encryptedConnectionDetails,
- gatewayId: gatewayPoolId ? null : gatewayId,
- gatewayPoolId: gatewayPoolId ?? null,
- name,
- projectId
- },
- tx
- );
- let metadataRows: Awaited<ReturnType<typeof resourceMetadataDAL.insertMany>> | undefined;
- if (metadata && metadata.length > 0) {
- metadataRows = await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamDomainId: created.id,
- orgId: actor.orgId
- })),
- tx
- );
- }
- return { domain: created, insertedMetadata: metadataRows };
- });
-
- return {
- ...(await decryptDomain(newDomain, projectId, kmsService)),
- metadata: insertedMetadata?.map(({ id, key, value }) => ({ id, key, value: value ?? "" })) ?? []
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Domain with name '${name}' already exists in this project`
- });
- }
- throw err;
- }
- };
-
- const updateById = async (
- { domainId, connectionDetails, name, gatewayId, gatewayPoolId, metadata }: TUpdateDomainDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
-
- const domain = await pamDomainDAL.findById(domainId);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${domainId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: domain.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const existingMetadata = await pamDomainDAL.findMetadataByDomainIds([domainId]);
- const currentMetadata = existingMetadata[domainId] || [];
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamDomains, {
- name: domain.name,
- domainType: domain.domainType,
- metadata: currentMetadata
- })
- );
-
- if (metadata || name) {
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamDomains, {
- name: name ?? domain.name,
- domainType: domain.domainType,
- metadata: metadata ? metadata.map(({ key, value }) => ({ key, value: value ?? "" })) : currentMetadata
- })
- );
- }
-
- if (gatewayPoolId && gatewayPoolId !== domain.gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
- }
-
- const updateDoc: Partial<TPamDomains> = {};
- // Mutual exclusion: setting one clears the other.
- let effectiveGatewayId: string | null | undefined = domain.gatewayId;
- let effectiveGatewayPoolId: string | null | undefined = domain.gatewayPoolId;
- if (gatewayId !== undefined && gatewayPoolId !== undefined) {
- effectiveGatewayId = gatewayId;
- effectiveGatewayPoolId = gatewayPoolId;
- } else if (gatewayId !== undefined) {
- effectiveGatewayId = gatewayId;
- effectiveGatewayPoolId = gatewayId !== null ? null : undefined;
- } else if (gatewayPoolId !== undefined) {
- effectiveGatewayPoolId = gatewayPoolId;
- effectiveGatewayId = gatewayPoolId !== null ? null : undefined;
- }
-
- if (gatewayId !== undefined || gatewayPoolId !== undefined) {
- updateDoc.gatewayId = effectiveGatewayId;
- updateDoc.gatewayPoolId = effectiveGatewayPoolId;
- }
-
- if (name !== undefined) {
- updateDoc.name = name;
- }
-
- if (connectionDetails !== undefined) {
- const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: effectiveGatewayId,
- gatewayPoolId: effectiveGatewayPoolId
- });
- const factory = PAM_DOMAIN_FACTORY_MAP[domain.domainType as PamDomainType](
- domain.domainType as PamDomainType,
- connectionDetails,
- validationGatewayId,
- gatewayV2Service,
- domain.projectId
- );
- const validatedConnectionDetails = await factory.validateConnection();
- const encryptedConnectionDetails = await encryptDomainConnectionDetails({
- connectionDetails: validatedConnectionDetails,
- projectId: domain.projectId,
- kmsService
- });
- updateDoc.encryptedConnectionDetails = encryptedConnectionDetails;
- }
-
- if (Object.keys(updateDoc).length === 0 && metadata === undefined) {
- const existingMeta = await pamDomainDAL.findMetadataByDomainIds([domainId]);
- return {
- ...(await decryptDomain(domain, domain.projectId, kmsService)),
- metadata: existingMeta[domainId] || []
- };
- }
-
- try {
- const updatedDomain = await pamDomainDAL.transaction(async (tx) => {
- if (metadata) {
- await resourceMetadataDAL.delete({ pamDomainId: domainId }, tx);
- if (metadata.length > 0) {
- await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamDomainId: domainId,
- orgId: actor.orgId
- })),
- tx
- );
- }
- }
- if (Object.keys(updateDoc).length > 0) {
- return pamDomainDAL.updateById(domainId, updateDoc, tx);
- }
- return domain;
- });
-
- const freshMeta = await pamDomainDAL.findMetadataByDomainIds([domainId]);
-
- return {
- ...(await decryptDomain(updatedDomain, domain.projectId, kmsService)),
- metadata: freshMeta[domainId] || []
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Domain with name '${name}' already exists in this project`
- });
- }
- throw err;
- }
- };
-
- const deleteById = async (id: string, actor: OrgServiceActor) => {
- const domain = await pamDomainDAL.findById(id);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: domain.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByDomainId = await pamDomainDAL.findMetadataByDomainIds([id]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Delete,
- subject(ProjectPermissionSub.PamDomains, {
- name: domain.name,
- domainType: domain.domainType,
- metadata: metadataByDomainId[id] || []
- })
- );
-
- try {
- const deletedDomain = await pamDomainDAL.deleteById(id);
- return await decryptDomain(deletedDomain, domain.projectId, kmsService);
- } catch (err) {
- if (
- err instanceof DatabaseError &&
- (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation
- ) {
- throw new BadRequestError({
- message: "Failed to delete domain because it is attached to active PAM accounts or resources"
- });
- }
- throw err;
- }
- };
-
- const list = async ({ projectId, actor, actorId, actorAuthMethod, actorOrgId, ...params }: TListDomainsDTO) => {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PamDomains);
-
- const { domains, totalCount } = await pamDomainDAL.findByProjectId({
- projectId,
- ...params
- });
-
- const domainIds = domains.map((d) => d.id);
- const metadataByDomainId = await pamDomainDAL.findMetadataByDomainIds(domainIds);
-
- return {
- domains: await Promise.all(
- domains.map(async (d) => ({
- ...(await decryptDomain(d, projectId, kmsService)),
- metadata: metadataByDomainId[d.id] || []
- }))
- ),
- totalCount
- };
- };
-
- const listRelatedResources = async (domainId: string, actor: OrgServiceActor) => {
- const domain = await pamDomainDAL.findById(domainId);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${domainId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: domain.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByDomainId = await pamDomainDAL.findMetadataByDomainIds([domainId]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamDomains, {
- name: domain.name,
- domainType: domain.domainType,
- metadata: metadataByDomainId[domainId] || []
- })
- );
-
- const relatedResources = await pamResourceDAL.find({ domainId });
-
- return Promise.all(
- relatedResources.map(async (r) => {
- const { encryptedConnectionDetails, encryptedRotationAccountCredentials, encryptedResourceMetadata, ...rest } =
- r;
- const rConnectionDetails = await decryptResourceConnectionDetails({
- encryptedConnectionDetails,
- projectId: domain.projectId,
- kmsService
- });
- const rotationAccountCredentials = encryptedRotationAccountCredentials
- ? await decryptAccountCredentials({
- encryptedCredentials: encryptedRotationAccountCredentials,
- projectId: domain.projectId,
- kmsService
- })
- : null;
- return { ...rest, connectionDetails: rConnectionDetails, rotationAccountCredentials } as TWindowsResource;
- })
- );
- };
-
- const listDomainOptions = () => {
- return [{ name: "Active Directory" as const, domain: PamDomainType.ActiveDirectory }].sort((a, b) =>
- a.name.localeCompare(b.name)
- );
- };
-
- return {
- getById,
- create,
- updateById,
- deleteById,
- list,
- listRelatedResources,
- listDomainOptions
- };
-};
diff --git a/backend/src/ee/services/pam-domain/pam-domain-types.ts b/backend/src/ee/services/pam-domain/pam-domain-types.ts
deleted file mode 100644
index e320bc5978..0000000000
--- a/backend/src/ee/services/pam-domain/pam-domain-types.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { z } from "zod";
-
-import { OrderByDirection, TProjectPermission } from "@app/lib/types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
-import { TPostRotateContext } from "../pam-resource/pam-resource-types";
-import { TPermissionServiceFactory } from "../permission/permission-service-types";
-import { TActiveDirectoryConnectionDetails } from "./active-directory/active-directory-domain-types";
-import { TPamDomainDALFactory } from "./pam-domain-dal";
-import { PamDomainOrderBy, PamDomainType } from "./pam-domain-enums";
-
-export type TPamDomainConnectionDetails = TActiveDirectoryConnectionDetails;
-
-export type TPamDomain = {
- id: string;
- projectId: string;
- name: string;
- domainType: PamDomainType;
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- discoveryFingerprint?: string | null;
- createdAt: Date;
- updatedAt: Date;
- connectionDetails: TPamDomainConnectionDetails;
- metadata?: Array<{ id: string; key: string; value: string }>;
-};
-
-export type TCreateDomainDTO = {
- projectId: string;
- name: string;
- domainType: PamDomainType;
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- connectionDetails: TPamDomainConnectionDetails;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
-};
-
-export type TUpdateDomainDTO = {
- domainId: string;
- name?: string;
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- connectionDetails?: TPamDomainConnectionDetails;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
-};
-
-export type TListDomainsDTO = {
- search?: string;
- orderBy?: PamDomainOrderBy;
- orderDirection?: OrderByDirection;
- limit?: number;
- offset?: number;
- discoveryFingerprint?: string;
- filterDomainTypes?: string[];
-} & TProjectPermission;
-
-export type TDeleteDomainDTO = {
- domainId: string;
-};
-
-export type TPamDomainServiceFactoryDep = {
- pamDomainDAL: TPamDomainDALFactory;
- pamResourceDAL: Pick<TPamResourceDALFactory, "find" | "findById">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- gatewayPoolService: Pick<
- TGatewayPoolServiceFactory,
- "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"
- >;
- resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
-};
-
-export type TPamDomainFactory<T, C> = (
- domainType: PamDomainType,
- connectionDetails: T,
- gatewayId: string | null | undefined,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- projectId: string | null | undefined
-) => {
- validateConnection: () => Promise<T>;
- validateAccountCredentials: (credentials: C) => Promise<C>;
- rotateAccountCredentials: (rotationAccountCredentials: C, currentCredentials: C) => Promise<C>;
- postRotate?: (
- accountId: string,
- newCredentials: C,
- projectId: string,
- ctx: TPostRotateContext,
- rotationAccountCredentials: C
- ) => Promise<void>;
- handleOverwritePreventionForCensoredValues: (updatedAccountCredentials: C, currentCredentials: C) => Promise<C>;
-};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-dal.ts b/backend/src/ee/services/pam-folder/pam-folder-dal.ts
deleted file mode 100644
index 2fbeb7cc4c..0000000000
--- a/backend/src/ee/services/pam-folder/pam-folder-dal.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Knex } from "knex";
-import RE2 from "re2";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { OrderByDirection } from "@app/lib/types";
-
-import { PamAccountOrderBy } from "../pam-account/pam-account-enums";
-
-export type TPamFolderDALFactory = ReturnType<typeof pamFolderDALFactory>;
-export const pamFolderDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamFolder);
-
- const findByProjectId = async (
- {
- projectId,
- parentId,
- search,
- limit,
- offset = 0,
- orderBy = PamAccountOrderBy.Name,
- orderDirection = OrderByDirection.ASC
- }: {
- projectId: string;
- parentId?: string | null;
- search?: string;
- limit?: number;
- offset?: number;
- orderBy?: PamAccountOrderBy;
- orderDirection?: OrderByDirection;
- },
- tx?: Knex
- ) => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamFolder).where(`${TableName.PamFolder}.projectId`, projectId);
-
- if (parentId) {
- void query.where(`${TableName.PamFolder}.parentId`, parentId);
- } else {
- void query.whereNull(`${TableName.PamFolder}.parentId`);
- }
-
- if (search) {
- // escape special characters (`%`, `_`) and the escape character itself (`\`)
- const escapedSearch = search
- .replace(new RE2(/\\/g), "\\\\")
- .replace(new RE2(/%/g), "\\%")
- .replace(new RE2(/_/g), "\\_");
- void query.whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamFolder, "name", `%${escapedSearch}%`]);
- }
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamFolder));
- const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";
-
- void query.orderByRaw(`${TableName.PamFolder}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]);
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [folders, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return { folders, totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM folders" });
- }
- };
-
- const findByPath = async (projectId: string, path: string, tx?: Knex) => {
- try {
- const dbInstance = tx || db.replicaNode();
-
- const folders = await dbInstance(TableName.PamFolder)
- .where(`${TableName.PamFolder}.projectId`, projectId)
- .select(selectAllTableCols(TableName.PamFolder));
-
- const pathSegments = path.split("/").filter(Boolean);
- if (pathSegments.length === 0) {
- return undefined;
- }
-
- const foldersByParentId = new Map<string | null, typeof folders>();
- for (const folder of folders) {
- const children = foldersByParentId.get(folder.parentId ?? null) ?? [];
- children.push(folder);
- foldersByParentId.set(folder.parentId ?? null, children);
- }
-
- let parentId: string | null = null;
- let currentFolder: (typeof folders)[0] | undefined;
-
- for (const segment of pathSegments) {
- const childFolders: typeof folders = foldersByParentId.get(parentId) || [];
- currentFolder = childFolders.find((folder) => folder.name === segment);
-
- if (!currentFolder) {
- return undefined;
- }
-
- parentId = currentFolder.id;
- }
-
- return currentFolder;
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM folder by path" });
- }
- };
-
- return { ...orm, findByProjectId, findByPath };
-};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-fns.ts b/backend/src/ee/services/pam-folder/pam-folder-fns.ts
deleted file mode 100644
index bcba0ab3b3..0000000000
--- a/backend/src/ee/services/pam-folder/pam-folder-fns.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { TPamFolderDALFactory } from "./pam-folder-dal";
-
-type GetFullFolderPath = {
- pamFolderDAL: Pick<TPamFolderDALFactory, "find">;
- folderId?: string | null;
- projectId: string;
-};
-
-export const getFullPamFolderPath = async ({
- pamFolderDAL,
- folderId,
- projectId
-}: GetFullFolderPath): Promise<string> => {
- if (!folderId) return "/";
-
- const folders = await pamFolderDAL.find({ projectId });
- const folderMap = new Map(folders.map((folder) => [folder.id, folder]));
-
- if (!folderMap.has(folderId)) return "";
-
- const path: string[] = [];
- let currentFolderId: string | null | undefined = folderId;
-
- while (currentFolderId) {
- const folder = folderMap.get(currentFolderId);
- if (!folder) break;
-
- path.unshift(folder.name);
- currentFolderId = folder.parentId;
- }
-
- return `/${path.join("/")}`;
-};
diff --git a/backend/src/ee/services/pam-folder/pam-folder-service.ts b/backend/src/ee/services/pam-folder/pam-folder-service.ts
deleted file mode 100644
index 2f6b81bc48..0000000000
--- a/backend/src/ee/services/pam-folder/pam-folder-service.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { ActionProjectType, TPamFolders } from "@app/db/schemas";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-
-import { TPamFolderDALFactory } from "./pam-folder-dal";
-import { TCreateFolderDTO, TUpdateFolderDTO } from "./pam-folder-types";
-
-type TPamFolderServiceFactoryDep = {
- pamFolderDAL: TPamFolderDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
-};
-
-export type TPamFolderServiceFactory = ReturnType<typeof pamFolderServiceFactory>;
-
-export const pamFolderServiceFactory = ({ pamFolderDAL, permissionService }: TPamFolderServiceFactoryDep) => {
- const createFolder = async ({ name, description, parentId, projectId }: TCreateFolderDTO, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PamFolders);
-
- if (parentId) {
- if (!(await pamFolderDAL.findOne({ id: parentId, projectId }))) {
- throw new NotFoundError({
- message: `Parent folder '${parentId}' not found for project '${projectId}'`
- });
- }
- }
-
- try {
- const folder = await pamFolderDAL.create({
- name,
- description: description ?? null,
- parentId: parentId || null,
- projectId
- });
-
- return folder;
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Folder with name '${name}' already exists for this path`
- });
- }
-
- throw err;
- }
- };
-
- const updateFolder = async ({ id, name, description }: TUpdateFolderDTO, actor: OrgServiceActor) => {
- const folder = await pamFolderDAL.findById(id);
- if (!folder) throw new NotFoundError({ message: `Folder with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: folder.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PamFolders);
-
- const updateDoc: Partial<TPamFolders> = {};
-
- if (name !== undefined) {
- updateDoc.name = name;
- }
-
- if (description !== undefined) {
- updateDoc.description = description;
- }
-
- if (Object.keys(updateDoc).length === 0) {
- return folder;
- }
-
- try {
- const updatedFolder = await pamFolderDAL.updateById(id, updateDoc);
-
- return updatedFolder;
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Folder with name '${name}' already exists for this path`
- });
- }
-
- throw err;
- }
- };
-
- const deleteFolder = async (id: string, actor: OrgServiceActor) => {
- const folder = await pamFolderDAL.findById(id);
- if (!folder) throw new NotFoundError({ message: `Folder with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: folder.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.PamFolders);
-
- const deletedFolder = await pamFolderDAL.deleteById(id);
-
- return deletedFolder;
- };
-
- return { createFolder, updateFolder, 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
deleted file mode 100644
index c8a4356370..0000000000
--- a/backend/src/ee/services/pam-folder/pam-folder-types.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// DTOs
-export interface TCreateFolderDTO {
- projectId: string;
- parentId?: string | null;
- name: string;
- description?: string | null;
-}
-
-export interface TUpdateFolderDTO {
- id: string;
- name?: string;
- description?: string | null;
-}
diff --git a/backend/src/ee/services/pam-insights/pam-insights-service.ts b/backend/src/ee/services/pam-insights/pam-insights-service.ts
deleted file mode 100644
index 648496fa54..0000000000
--- a/backend/src/ee/services/pam-insights/pam-insights-service.ts
+++ /dev/null
@@ -1,310 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-import picomatch from "picomatch";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
-import { TPamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
-import { TPamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";
-import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionPamInsightsActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
-import { withCache } from "@app/lib/cache/with-cache";
-import { OrgServiceActor } from "@app/lib/types";
-
-const SESSION_ACTIVITY_DAYS = 30;
-const TOP_ACTORS_DAYS = 30;
-const TOP_ACTORS_LIMIT = 10;
-const FAILED_ROTATIONS_LIMIT = 25;
-
-type TPamInsightsServiceFactoryDep = {
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- pamSessionDAL: Pick<
- TPamSessionDALFactory,
- "countActiveByProjectId" | "countDailyByProjectId" | "findTopActorsByProjectId"
- >;
- pamResourceDAL: Pick<
- TPamResourceDALFactory,
- "countByProject" | "countWithRotationByProject" | "countByProjectGroupedByType"
- >;
- pamAccountDAL: Pick<
- TPamAccountDALFactory,
- | "countByProject"
- | "countFailedRotationsByProject"
- | "findFailedRotationsByProject"
- | "findRotationCandidatesByProject"
- >;
- pamResourceRotationRulesDAL: Pick<TPamResourceRotationRulesDALFactory, "findByResourceIds">;
- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem">;
-};
-
-export type TPamInsightsServiceFactory = ReturnType<typeof pamInsightsServiceFactory>;
-
-const checkPamInsightsPermission = async (
- permissionService: TPamInsightsServiceFactoryDep["permissionService"],
- projectId: string,
- actor: OrgServiceActor
-) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- projectId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamInsightsActions.Read,
- ProjectPermissionSub.PamInsights
- );
-};
-
-const getStartOfDayUtc = (offsetDays: number): Date => {
- const now = new Date();
- const utcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
- return new Date(utcMidnight - offsetDays * 24 * 60 * 60 * 1000);
-};
-
-export const pamInsightsServiceFactory = ({
- permissionService,
- pamSessionDAL,
- pamResourceDAL,
- pamAccountDAL,
- pamResourceRotationRulesDAL,
- keyStore
-}: TPamInsightsServiceFactoryDep) => {
- const getSummary = async (projectId: string, actor: OrgServiceActor) => {
- await checkPamInsightsPermission(permissionService, projectId, actor);
-
- return withCache({
- keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, "pam:summary"),
- ttlSeconds: 15,
- fetcher: async () => {
- const [
- totalResources,
- resourcesWithRotation,
- totalAccounts,
- failedRotations,
- failedRotationAccounts,
- activeSessions,
- resourceTypeCount
- ] = await Promise.all([
- pamResourceDAL.countByProject(projectId),
- pamResourceDAL.countWithRotationByProject(projectId),
- pamAccountDAL.countByProject(projectId),
- pamAccountDAL.countFailedRotationsByProject(projectId),
- pamAccountDAL.findFailedRotationsByProject(projectId, FAILED_ROTATIONS_LIMIT),
- pamSessionDAL.countActiveByProjectId(projectId),
- pamResourceDAL.countByProjectGroupedByType(projectId)
- ]);
-
- return {
- totalResources,
- resourcesWithRotation,
- totalAccounts,
- failedRotations,
- failedRotationAccounts: failedRotationAccounts.map((a) => ({
- accountId: a.id,
- accountName: a.name,
- resourceId: a.resourceId,
- resourceName: a.resourceName,
- resourceType: a.resourceType,
- lastRotatedAt: a.lastRotatedAt
- })),
- activeSessions,
- resourceTypeCount: resourceTypeCount.length
- };
- }
- });
- };
-
- const getSessionActivity = async (projectId: string, actor: OrgServiceActor) => {
- await checkPamInsightsPermission(permissionService, projectId, actor);
-
- return withCache({
- keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, "pam:session-activity"),
- ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
- fetcher: async () => {
- const startDate = getStartOfDayUtc(SESSION_ACTIVITY_DAYS - 1);
- const rows = await pamSessionDAL.countDailyByProjectId(projectId, startDate);
-
- const dayCounts = new Map<string, number>();
- for (let i = SESSION_ACTIVITY_DAYS - 1; i >= 0; i -= 1) {
- const d = getStartOfDayUtc(i);
- dayCounts.set(d.toISOString().slice(0, 10), 0);
- }
- rows.forEach((row) => {
- if (dayCounts.has(row.date)) dayCounts.set(row.date, row.count);
- });
-
- const days = Array.from(dayCounts.entries()).map(([date, count]) => ({ date, count }));
- const total = days.reduce((sum, d) => sum + d.count, 0);
- const avgPerDay = days.length > 0 ? Math.round(total / days.length) : 0;
-
- return { days, avgPerDay };
- }
- });
- };
-
- const getTopActors = async (projectId: string, actor: OrgServiceActor) => {
- await checkPamInsightsPermission(permissionService, projectId, actor);
-
- return withCache({
- keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, "pam:top-actors"),
- ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
- fetcher: async () => {
- const startDate = getStartOfDayUtc(TOP_ACTORS_DAYS - 1);
- const rows = await pamSessionDAL.findTopActorsByProjectId(projectId, startDate, TOP_ACTORS_LIMIT);
-
- return {
- actors: rows.map((row) => ({
- actorName: row.actorName,
- actorEmail: row.actorEmail,
- sessionCount: row.sessionCount,
- isService: row.userId === null
- }))
- };
- }
- });
- };
-
- const getResourceBreakdown = async (projectId: string, actor: OrgServiceActor) => {
- await checkPamInsightsPermission(permissionService, projectId, actor);
-
- return withCache({
- keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, "pam:resource-breakdown"),
- ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
- fetcher: async () => {
- const resourceCounts = await pamResourceDAL.countByProjectGroupedByType(projectId);
-
- const breakdown = resourceCounts.map((row) => ({
- resourceType: row.resourceType,
- resourceCount: row.count
- }));
-
- breakdown.sort((a, b) => b.resourceCount - a.resourceCount);
-
- return { breakdown };
- }
- });
- };
-
- const getRotationCalendar = async (projectId: string, month: number, year: number, actor: OrgServiceActor) => {
- await checkPamInsightsPermission(permissionService, projectId, actor);
-
- return withCache({
- keyStore,
- key: KeyStorePrefixes.InsightsCache(projectId, `pam:rotation-calendar:${year}-${month}`),
- ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
- fetcher: async () => {
- // Build the visible calendar grid range: from the Monday on/before the 1st through
- // the Sunday on/after the last day of the month, mirroring how the frontend renders.
- const monthStart = new Date(Date.UTC(year, month - 1, 1));
- const monthEnd = new Date(Date.UTC(year, month, 0, 23, 59, 59, 999));
- // weekday: 0=Sun..6=Sat. For Monday-start weeks, offset = (day + 6) % 7
- const startOffset = (monthStart.getUTCDay() + 6) % 7;
- const endOffset = 6 - ((monthEnd.getUTCDay() + 6) % 7);
- const rangeStart = new Date(monthStart.getTime() - startOffset * 24 * 60 * 60 * 1000);
- const rangeEnd = new Date(monthEnd.getTime() + endOffset * 24 * 60 * 60 * 1000);
-
- const candidates = await pamAccountDAL.findRotationCandidatesByProject(projectId);
- if (!candidates.length) return { rotations: [] };
-
- const resourceIds = [...new Set(candidates.map((c) => c.resourceId))];
- const allRules = await pamResourceRotationRulesDAL.findByResourceIds(resourceIds);
- if (!allRules.length) return { rotations: [] };
-
- const rulesByResource: Record<string, typeof allRules> = {};
- for (const rule of allRules) {
- if (!rulesByResource[rule.resourceId]) rulesByResource[rule.resourceId] = [];
- rulesByResource[rule.resourceId].push(rule);
- }
-
- type TCalendarRotationEvent = {
- id: string;
- accountId: string;
- accountName: string;
- resourceId: string;
- resourceName: string;
- resourceType: string;
- intervalSeconds: number;
- nextRotationAt: Date;
- };
-
- const events: TCalendarRotationEvent[] = [];
- const rangeStartMs = rangeStart.getTime();
- const rangeEndMs = rangeEnd.getTime();
- const MAX_EVENTS_PER_ACCOUNT = 100;
-
- for (const candidate of candidates) {
- const rules = rulesByResource[candidate.resourceId];
- // eslint-disable-next-line no-continue
- if (!rules) continue;
-
- const matchedRule = rules.find((rule) => picomatch.isMatch(candidate.name, rule.namePattern));
- // eslint-disable-next-line no-continue
- if (!matchedRule || !matchedRule.enabled || !matchedRule.intervalSeconds) continue;
-
- const baseMs = candidate.lastRotatedAt
- ? new Date(candidate.lastRotatedAt).getTime()
- : candidate.createdAt.getTime();
- const intervalMs = matchedRule.intervalSeconds * 1000;
- if (intervalMs <= 0) {
- // eslint-disable-next-line no-continue
- continue;
- }
-
- // Fast-forward to the first occurrence within the visible range.
- let occurrenceMs = baseMs;
- if (occurrenceMs < rangeStartMs) {
- const skips = Math.ceil((rangeStartMs - occurrenceMs) / intervalMs);
- occurrenceMs = baseMs + skips * intervalMs;
- }
-
- let count = 0;
- while (occurrenceMs <= rangeEndMs && count < MAX_EVENTS_PER_ACCOUNT) {
- events.push({
- id: `${candidate.id}-${occurrenceMs}`,
- accountId: candidate.id,
- accountName: candidate.name,
- resourceId: candidate.resourceId,
- resourceName: candidate.resourceName,
- resourceType: candidate.resourceType,
- intervalSeconds: matchedRule.intervalSeconds,
- nextRotationAt: new Date(occurrenceMs)
- });
- occurrenceMs += intervalMs;
- count += 1;
- }
- }
-
- events.sort((a, b) => a.nextRotationAt.getTime() - b.nextRotationAt.getTime());
-
- return { rotations: events };
- },
- reviver: (parsed) => {
- parsed.rotations.forEach((r) => {
- // eslint-disable-next-line no-param-reassign
- r.nextRotationAt = new Date(r.nextRotationAt);
- });
- return parsed;
- }
- });
- };
-
- return {
- getSummary,
- getSessionActivity,
- getTopActors,
- getResourceBreakdown,
- getRotationCalendar
- };
-};
diff --git a/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts b/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts
index 78628be48e..a2362fd2c3 100644
--- a/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts
+++ b/backend/src/ee/services/pam-instance/pam-project-bootstrap.ts
@@ -7,9 +7,8 @@ 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 { PamAccountType, PamRecordingStorageBackend } 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">;
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts
deleted file mode 100644
index 185b9f0f87..0000000000
--- a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-dal.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TPamProjectRecordingConfigDALFactory = ReturnType<typeof pamProjectRecordingConfigDALFactory>;
-
-export const pamProjectRecordingConfigDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamProjectRecordingConfig);
-
- const findByProjectId = async (projectId: string) => {
- return db.replicaNode()(TableName.PamProjectRecordingConfig).where({ projectId }).first();
- };
-
- return { ...orm, findByProjectId };
-};
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts
deleted file mode 100644
index c4a647d73c..0000000000
--- a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-service.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
-import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";
-import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
-import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
-import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";
-import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-
-import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
-import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-storage/pam-session-recording-storage-factory";
-import {
- normalizeKeyPrefix,
- TPamRecordingResolvedConfig
-} from "../pam-session-recording-storage/pam-session-recording-storage-types";
-import { TPamProjectRecordingConfigDALFactory } from "./pam-project-recording-config-dal";
-import {
- TDeletePamRecordingConfigDTO,
- TGetPamRecordingConfigDTO,
- TUpsertPamRecordingConfigDTO
-} from "./pam-project-recording-config-types";
-
-type TPamProjectRecordingConfigServiceFactoryDep = {
- pamProjectRecordingConfigDAL: TPamProjectRecordingConfigDALFactory;
- pamSessionDAL: Pick<TPamSessionDALFactory, "countActiveByProjectId">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "findAppConnectionById">;
- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-};
-
-export type TPamProjectRecordingConfigServiceFactory = ReturnType<typeof pamProjectRecordingConfigServiceFactory>;
-
-export const pamProjectRecordingConfigServiceFactory = ({
- pamProjectRecordingConfigDAL,
- pamSessionDAL,
- permissionService,
- appConnectionService,
- appConnectionDAL,
- kmsService
-}: TPamProjectRecordingConfigServiceFactoryDep) => {
- // Callers are responsible for their own authorization
- const resolveConfigForProject = async (projectId: string): Promise<TPamRecordingResolvedConfig | null> => {
- const row = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
- if (!row) return null;
-
- if (row.storageBackend === PamRecordingStorageBackend.AwsS3) {
- const raw = await appConnectionDAL.findById(row.connectionId);
- if (!raw) throw new NotFoundError({ message: `AWS app connection ${row.connectionId} not found` });
- const appConnection = await decryptAppConnection(raw, kmsService);
-
- const awsConfig = await getAwsConnectionConfig(
- appConnection as unknown as TAwsConnectionConfig,
- row.region as never
- );
-
- return {
- backend: PamRecordingStorageBackend.AwsS3,
- bucket: row.bucket,
- region: row.region as AWSRegion,
- keyPrefix: row.keyPrefix ?? null,
- awsCredentials: awsConfig.credentials
- };
- }
-
- return {
- backend: PamRecordingStorageBackend.Postgres,
- keyPrefix: row.keyPrefix ?? null
- };
- };
-
- const getConfig = async ({ projectId }: TGetPamRecordingConfigDTO, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);
-
- const row = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
- return { config: row ?? null };
- };
-
- const testConfig = async (input: TUpsertPamRecordingConfigDTO, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: input.projectId,
- actionProjectType: ActionProjectType.PAM
- });
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
-
- if (input.storageBackend !== PamRecordingStorageBackend.AwsS3) {
- throw new BadRequestError({ message: `Unsupported storage backend: ${input.storageBackend}` });
- }
-
- const appConnection = await appConnectionService.findAppConnectionById(
- AppConnection.AWS,
- input.connectionId,
- actor
- );
- if (!appConnection) throw new NotFoundError({ message: `AWS app connection ${input.connectionId} not found` });
-
- const awsConfig = await getAwsConnectionConfig(
- appConnection as unknown as TAwsConnectionConfig,
- input.region as never
- );
-
- const resolvedConfig: TPamRecordingResolvedConfig = {
- backend: PamRecordingStorageBackend.AwsS3,
- bucket: input.bucket,
- region: input.region,
- keyPrefix: input.keyPrefix ?? null,
- awsCredentials: awsConfig.credentials
- };
-
- const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[input.storageBackend]();
- await provider.validateConfig({ config: resolvedConfig });
-
- return { ok: true as const, resolvedConfig };
- };
-
- const upsertConfig = async (
- input: TUpsertPamRecordingConfigDTO,
- actor: OrgServiceActor,
- preValidatedConfig?: TPamRecordingResolvedConfig
- ) => {
- const resolvedConfig = preValidatedConfig ?? (await testConfig(input, actor)).resolvedConfig;
-
- const existing = await pamProjectRecordingConfigDAL.findByProjectId(input.projectId);
-
- const bucketChanging =
- existing &&
- (existing.bucket !== input.bucket ||
- existing.region !== input.region ||
- existing.keyPrefix !== (input.keyPrefix ?? null));
-
- if (bucketChanging) {
- const activeCount = await pamSessionDAL.countActiveByProjectId(input.projectId);
- if (activeCount > 0) {
- throw new BadRequestError({
- message: `Cannot change bucket configuration while ${activeCount} session${activeCount > 1 ? "s are" : " is"} in progress. End all active sessions first.`
- });
- }
- }
-
- let config;
- if (existing) {
- config = await pamProjectRecordingConfigDAL.updateById(existing.id, {
- storageBackend: input.storageBackend,
- connectionId: input.connectionId,
- bucket: input.bucket,
- region: input.region,
- keyPrefix: input.keyPrefix ?? null
- });
- } else {
- config = await pamProjectRecordingConfigDAL.create({
- projectId: input.projectId,
- storageBackend: input.storageBackend,
- connectionId: input.connectionId,
- bucket: input.bucket,
- region: input.region,
- keyPrefix: input.keyPrefix ?? null
- });
- }
-
- let corsProbeUrl: string | null = null;
- if (resolvedConfig) {
- try {
- const probeKey = `${normalizeKeyPrefix(resolvedConfig.keyPrefix)}.cors-probe`;
- const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[input.storageBackend]();
- const { url } = await provider.mintPresignedGet({ config: resolvedConfig, objectKey: probeKey });
- corsProbeUrl = url;
- } catch {
- // Non-fatal -- the config is already saved
- }
- }
-
- return { config, corsProbeUrl };
- };
-
- const deleteConfig = async ({ projectId }: TDeletePamRecordingConfigDTO, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
-
- const existing = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
- if (!existing) return { ok: true as const };
-
- const activeCount = await pamSessionDAL.countActiveByProjectId(projectId);
- if (activeCount > 0) {
- throw new BadRequestError({
- message: `Cannot disable recording configuration while ${activeCount} session${activeCount > 1 ? "s are" : " is"} in progress. End all active sessions first.`
- });
- }
-
- await pamProjectRecordingConfigDAL.deleteById(existing.id);
- return { ok: true as const };
- };
-
- return {
- getConfig,
- testConfig,
- upsertConfig,
- deleteConfig,
- resolveConfigForProject
- };
-};
diff --git a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts b/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts
deleted file mode 100644
index 5bb26165aa..0000000000
--- a/backend/src/ee/services/pam-project-recording-config/pam-project-recording-config-types.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
-
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
-
-export type TUpsertPamRecordingConfigDTO = {
- projectId: string;
- storageBackend: PamRecordingStorageBackend;
- connectionId: string;
- bucket: string;
- region: AWSRegion;
- keyPrefix?: string | null;
-};
-
-export type TGetPamRecordingConfigDTO = {
- projectId: string;
-};
-
-export type TDeletePamRecordingConfigDTO = {
- projectId: string;
-};
diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts
deleted file mode 100644
index af78a8f753..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import { AssumeRoleCommand, Credentials, STSClient, STSClientConfig } from "@aws-sdk/client-sts";
-
-import { CustomAWSHasher } from "@app/lib/aws/hashing";
-import { getConfig } from "@app/lib/config/env";
-import { request } from "@app/lib/config/request";
-import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, InternalServerError } from "@app/lib/errors";
-
-import { TAwsIamResourceConnectionDetails } from "./aws-iam-resource-types";
-
-export const AWS_STS_MIN_DURATION_SECONDS = 900;
-
-// We hardcode us-east-1 because:
-// 1. IAM is global - roles can be assumed from any STS regional endpoint
-// 2. The temporary credentials returned work globally across all AWS regions
-// 3. The target account's resources can be in any region - it doesn't affect STS calls
-const AWS_STS_DEFAULT_REGION = "us-east-1";
-
-const createStsClient = (credentials?: Credentials): STSClient => {
- const appCfg = getConfig();
-
- const config: STSClientConfig = {
- region: AWS_STS_DEFAULT_REGION,
- useFipsEndpoint: crypto.isFipsModeEnabled(),
- sha256: CustomAWSHasher
- };
-
- if (credentials) {
- // Use provided credentials (for role chaining)
- config.credentials = {
- accessKeyId: credentials.AccessKeyId!,
- secretAccessKey: credentials.SecretAccessKey!,
- sessionToken: credentials.SessionToken
- };
- } else if (appCfg.PAM_AWS_ACCESS_KEY_ID && appCfg.PAM_AWS_SECRET_ACCESS_KEY) {
- // Use configured static credentials
- config.credentials = {
- accessKeyId: appCfg.PAM_AWS_ACCESS_KEY_ID,
- secretAccessKey: appCfg.PAM_AWS_SECRET_ACCESS_KEY
- };
- }
- // Otherwise uses instance profile if hosting on AWS
-
- return new STSClient(config);
-};
-
-/**
- * Assumes the PAM role and returns the credentials.
- * Returns null if assumption fails (for validation) or throws if throwOnError is true.
- */
-const assumePamRole = async ({
- connectionDetails,
- projectId,
- sessionDuration = AWS_STS_MIN_DURATION_SECONDS,
- sessionNameSuffix = "validation",
- throwOnError = false
-}: {
- connectionDetails: TAwsIamResourceConnectionDetails;
- projectId: string;
- sessionDuration?: number;
- sessionNameSuffix?: string;
- throwOnError?: boolean;
-}): Promise<Credentials | null> => {
- const stsClient = createStsClient();
-
- try {
- const result = await stsClient.send(
- new AssumeRoleCommand({
- RoleArn: connectionDetails.roleArn,
- RoleSessionName: `infisical-pam-${sessionNameSuffix}-${Date.now()}`,
- DurationSeconds: sessionDuration,
- ExternalId: projectId
- })
- );
-
- if (!result.Credentials) {
- if (throwOnError) {
- throw new InternalServerError({
- message: "Failed to assume PAM role - AWS STS did not return credentials"
- });
- }
- return null;
- }
-
- return result.Credentials;
- } catch (error) {
- if (throwOnError) {
- throw new InternalServerError({
- message: `Failed to assume PAM role - AWS STS did not return credentials: ${error instanceof Error ? error.message : "Unknown error"}`
- });
- }
- return null;
- }
-};
-
-/**
- * Assumes a target role using PAM role credentials (role chaining).
- * Returns null if assumption fails (for validation) or throws if throwOnError is true.
- */
-const assumeTargetRole = async ({
- pamCredentials,
- targetRoleArn,
- projectId,
- roleSessionName,
- sessionDuration = AWS_STS_MIN_DURATION_SECONDS,
- throwOnError = false
-}: {
- pamCredentials: Credentials;
- targetRoleArn: string;
- projectId: string;
- roleSessionName: string;
- sessionDuration?: number;
- throwOnError?: boolean;
-}): Promise<Credentials | null> => {
- const chainedStsClient = createStsClient(pamCredentials);
-
- try {
- const result = await chainedStsClient.send(
- new AssumeRoleCommand({
- RoleArn: targetRoleArn,
- RoleSessionName: roleSessionName,
- DurationSeconds: sessionDuration,
- ExternalId: projectId
- })
- );
-
- if (!result.Credentials) {
- if (throwOnError) {
- throw new BadRequestError({
- message: "Failed to assume target role - verify the target role trust policy allows the PAM role to assume it"
- });
- }
- return null;
- }
-
- return result.Credentials;
- } catch (error) {
- if (throwOnError) {
- throw new InternalServerError({
- message: `Failed to assume target role - AWS STS did not return credentials: ${error instanceof Error ? error.message : "Unknown error"}`
- });
- }
- return null;
- }
-};
-
-export const validatePamRoleConnection = async (
- connectionDetails: TAwsIamResourceConnectionDetails,
- projectId: string
-): Promise<boolean> => {
- try {
- const credentials = await assumePamRole({ connectionDetails, projectId });
- return credentials !== null;
- } catch {
- return false;
- }
-};
-
-export const validateTargetRoleAssumption = async ({
- connectionDetails,
- targetRoleArn,
- projectId
-}: {
- connectionDetails: TAwsIamResourceConnectionDetails;
- targetRoleArn: string;
- projectId: string;
-}): Promise<boolean> => {
- try {
- const pamCredentials = await assumePamRole({ connectionDetails, projectId });
- if (!pamCredentials) return false;
-
- const targetCredentials = await assumeTargetRole({
- pamCredentials,
- targetRoleArn,
- projectId,
- roleSessionName: `infisical-pam-target-validation-${Date.now()}`
- });
- return targetCredentials !== null;
- } catch {
- return false;
- }
-};
-
-export type TAwsIamSessionCredentials = {
- accessKeyId: string;
- secretAccessKey: string;
- sessionToken: string;
- expiresAt: Date;
-};
-
-/**
- * Runs the STS role-chaining sequence and returns the temporary credentials
- * that the caller can either consume directly (CLI) or exchange for a
- * federated console sign-in URL via {@link exchangeCredentialsForConsoleUrl}.
- */
-export const generateAwsIamSessionCredentials = async ({
- connectionDetails,
- targetRoleArn,
- roleSessionName,
- projectId,
- sessionDuration
-}: {
- connectionDetails: TAwsIamResourceConnectionDetails;
- targetRoleArn: string;
- roleSessionName: string;
- projectId: string;
- sessionDuration: number;
-}): Promise<TAwsIamSessionCredentials> => {
- const pamCredentials = await assumePamRole({
- connectionDetails,
- projectId,
- sessionDuration,
- sessionNameSuffix: "session",
- throwOnError: true
- });
-
- const targetCredentials = await assumeTargetRole({
- pamCredentials: pamCredentials!,
- targetRoleArn,
- projectId,
- roleSessionName,
- sessionDuration,
- throwOnError: true
- });
-
- const { AccessKeyId, SecretAccessKey, SessionToken, Expiration } = targetCredentials!;
-
- if (!AccessKeyId || !SecretAccessKey || !SessionToken) {
- throw new InternalServerError({
- message: "AWS STS returned credentials missing required fields"
- });
- }
-
- return {
- accessKeyId: AccessKeyId,
- secretAccessKey: SecretAccessKey,
- sessionToken: SessionToken,
- expiresAt: Expiration ?? new Date(Date.now() + sessionDuration * 1000)
- };
-};
-
-// Exchanges existing STS credentials for a one-shot AWS console sign-in URL
-export const exchangeCredentialsForConsoleUrl = async (
- credentials: Pick<TAwsIamSessionCredentials, "accessKeyId" | "secretAccessKey" | "sessionToken">
-): Promise<string> => {
- const sessionJson = JSON.stringify({
- sessionId: credentials.accessKeyId,
- sessionKey: credentials.secretAccessKey,
- sessionToken: credentials.sessionToken
- });
-
- const federationEndpoint = "https://signin.aws.amazon.com/federation";
- const signinTokenUrl = `${federationEndpoint}?Action=getSigninToken&Session=${encodeURIComponent(sessionJson)}`;
-
- const tokenResponse = await request.get<{ SigninToken?: string }>(signinTokenUrl);
-
- if (!tokenResponse.data.SigninToken) {
- throw new InternalServerError({
- message: `AWS federation endpoint did not return a SigninToken: ${JSON.stringify(tokenResponse.data).substring(0, 200)}`
- });
- }
-
- const consoleDestination = `https://console.aws.amazon.com/`;
- return `${federationEndpoint}?Action=login&SigninToken=${encodeURIComponent(tokenResponse.data.SigninToken)}&Destination=${encodeURIComponent(consoleDestination)}`;
-};
diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-factory.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-factory.ts
deleted file mode 100644
index a3b149ca18..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-factory.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../pam-resource-types";
-import { validatePamRoleConnection, validateTargetRoleAssumption } from "./aws-iam-federation";
-import { TAwsIamAccountCredentials, TAwsIamResourceConnectionDetails } from "./aws-iam-resource-types";
-
-export const awsIamResourceFactory: TPamResourceFactory<
- TAwsIamResourceConnectionDetails,
- TAwsIamAccountCredentials,
- TPamResourceInternalMetadata
-> = (
- resourceType: PamResource,
- connectionDetails: TAwsIamResourceConnectionDetails,
- // AWS IAM doesn't use gateway
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _gatewayId,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _gatewayV2Service,
- projectId
-) => {
- const validateConnection = async () => {
- try {
- const isValid = await validatePamRoleConnection(connectionDetails, projectId ?? "");
-
- if (!isValid) {
- throw new BadRequestError({
- message:
- "Unable to assume the PAM role. Verify the role ARN and ensure the trust policy allows Infisical to assume the role."
- });
- }
-
- logger.info(
- { roleArn: connectionDetails.roleArn },
- "[AWS IAM Resource Factory] PAM role connection validated successfully"
- );
-
- return connectionDetails;
- } catch (error) {
- if (error instanceof BadRequestError) {
- throw error;
- }
-
- logger.error(error, "[AWS IAM Resource Factory] Failed to validate PAM role connection");
-
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TAwsIamAccountCredentials> = async (
- credentials
- ) => {
- try {
- const isValid = await validateTargetRoleAssumption({
- connectionDetails,
- targetRoleArn: credentials.targetRoleArn,
- projectId: projectId ?? ""
- });
-
- if (!isValid) {
- throw new BadRequestError({
- message: `Unable to assume the target role. Verify the target role ARN and ensure the PAM role (ARN: ${connectionDetails.roleArn}) has permission to assume it.`
- });
- }
-
- logger.info(
- { targetRoleArn: credentials.targetRoleArn },
- "[AWS IAM Resource Factory] Target role credentials validated successfully"
- );
-
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError) {
- throw error;
- }
-
- logger.error(error, "[AWS IAM Resource Factory] Failed to validate target role credentials");
-
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TAwsIamAccountCredentials> = async (
- _rotationAccountCredentials,
- currentCredentials
- ) => {
- return currentCredentials;
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TAwsIamAccountCredentials,
- // AWS IAM has no censored credential values - role ARNs are not secrets
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- _currentCredentials: TAwsIamAccountCredentials
- ) => {
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-fns.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-fns.ts
deleted file mode 100644
index d04018d492..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-fns.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import RE2 from "re2";
-
-import { BadRequestError } from "@app/lib/errors";
-
-import { AwsIamResourceListItemSchema } from "./aws-iam-resource-schemas";
-
-export const getAwsIamResourceListItem = () => {
- return {
- name: AwsIamResourceListItemSchema.shape.name.value,
- resource: AwsIamResourceListItemSchema.shape.resource.value
- };
-};
-
-/**
- * Extract the AWS Account ID from an IAM Role ARN
- * ARN format: arn:aws:iam::123456789012:role/RoleName
- */
-export const extractAwsAccountIdFromArn = (roleArn: string): string => {
- const match = roleArn.match(new RE2("^arn:aws:iam::(\\d{12}):role/"));
- if (!match) {
- throw new BadRequestError({ message: "Invalid IAM Role ARN format" });
- }
- return match[1];
-};
diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts
deleted file mode 100644
index 8b6f8cfc66..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreatePamAccountSchema,
- BaseCreatePamResourceSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdatePamAccountSchema,
- BaseUpdatePamResourceSchema
-} from "../pam-resource-schemas";
-
-// AWS STS session duration limits (in seconds)
-// Role chaining (Infisical → PAM role → target role) limits max session to 1 hour
-// @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
-const AWS_STS_MIN_SESSION_DURATION = 900; // 15 minutes
-const AWS_STS_MAX_SESSION_DURATION_ROLE_CHAINING = 3600; // 1 hour
-
-export const AwsIamResourceConnectionDetailsSchema = z.object({
- roleArn: z.string().trim().min(1)
-});
-
-export const AwsIamAccountCredentialsSchema = z.object({
- targetRoleArn: z.string().trim().min(1).max(2048),
- defaultSessionDuration: z.coerce
- .number()
- .min(AWS_STS_MIN_SESSION_DURATION)
- .max(AWS_STS_MAX_SESSION_DURATION_ROLE_CHAINING)
-});
-
-const BaseAwsIamResourceSchema = BasePamResourceSchema.extend({
- resourceType: z.literal(PamResource.AwsIam),
- gatewayId: z.string().uuid().nullable().optional()
-});
-
-export const AwsIamResourceSchema = BaseAwsIamResourceSchema.extend({
- connectionDetails: AwsIamResourceConnectionDetailsSchema,
- rotationAccountCredentials: AwsIamAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedAwsIamResourceSchema = BaseAwsIamResourceSchema.extend({
- connectionDetails: AwsIamResourceConnectionDetailsSchema,
- rotationAccountCredentials: AwsIamAccountCredentialsSchema.nullable().optional()
-});
-
-export const AwsIamResourceListItemSchema = z.object({
- name: z.literal("AWS IAM"),
- resource: z.literal(PamResource.AwsIam)
-});
-
-export const CreateAwsIamResourceSchema = BaseCreatePamResourceSchema.extend({
- connectionDetails: AwsIamResourceConnectionDetailsSchema,
- rotationAccountCredentials: AwsIamAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateAwsIamResourceSchema = BaseUpdatePamResourceSchema.extend({
- connectionDetails: AwsIamResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: AwsIamAccountCredentialsSchema.nullable().optional()
-});
-
-export const AwsIamAccountSchema = BasePamAccountSchema.extend({
- credentials: AwsIamAccountCredentialsSchema
-});
-
-export const CreateAwsIamAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: AwsIamAccountCredentialsSchema
-});
-
-export const UpdateAwsIamAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: AwsIamAccountCredentialsSchema.optional()
-});
-
-export const SanitizedAwsIamAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.AwsIam),
- credentials: AwsIamAccountCredentialsSchema.pick({
- targetRoleArn: true,
- defaultSessionDuration: true
- })
-});
diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-types.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-types.ts
deleted file mode 100644
index 732355371a..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- AwsIamAccountCredentialsSchema,
- AwsIamAccountSchema,
- AwsIamResourceConnectionDetailsSchema,
- AwsIamResourceSchema
-} from "./aws-iam-resource-schemas";
-
-// Resources
-export type TAwsIamResource = z.infer<typeof AwsIamResourceSchema>;
-export type TAwsIamResourceConnectionDetails = z.infer<typeof AwsIamResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TAwsIamAccount = z.infer<typeof AwsIamAccountSchema>;
-export type TAwsIamAccountCredentials = z.infer<typeof AwsIamAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/aws-iam/index.ts b/backend/src/ee/services/pam-resource/aws-iam/index.ts
deleted file mode 100644
index 8e41fa48a7..0000000000
--- a/backend/src/ee/services/pam-resource/aws-iam/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export * from "./aws-iam-federation";
-export * from "./aws-iam-resource-factory";
-export * from "./aws-iam-resource-fns";
-export * from "./aws-iam-resource-schemas";
-export * from "./aws-iam-resource-types";
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts
deleted file mode 100644
index a846debbe4..0000000000
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export enum KubernetesAuthMethod {
- ServiceAccountToken = "service-account-token",
- GatewayKubernetesAuth = "gateway-kubernetes-auth"
-}
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts
deleted file mode 100644
index d58e6e19f0..0000000000
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-import { AxiosError } from "axios";
-import https from "https";
-
-import { request } from "@app/lib/config/request";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway/types";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { PamResource } from "../pam-resource-enums";
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../pam-resource-types";
-import { KubernetesAuthMethod } from "./kubernetes-resource-enums";
-import { TKubernetesAccountCredentials, TKubernetesResourceConnectionDetails } from "./kubernetes-resource-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-export const executeWithGateway = async <T>(
- config: {
- connectionDetails: TKubernetesResourceConnectionDetails;
- resourceType: PamResource;
- gatewayId: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (baseUrl: string, httpsAgent: https.Agent) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
- const url = new URL(connectionDetails.url);
- const [targetHost] = await verifyHostInputValidity({ host: url.hostname, isGateway: true, isDynamicSecret: false });
-
- let targetPort: number;
- if (url.port) {
- targetPort = Number(url.port);
- } else if (url.protocol === "https:") {
- targetPort = 443;
- } else {
- targetPort = 80;
- }
-
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort
- });
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
- const httpsAgent = new https.Agent({
- ca: connectionDetails.sslCertificate,
- rejectUnauthorized: connectionDetails.sslRejectUnauthorized,
- servername: targetHost
- });
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const protocol = url.protocol === "https:" ? "https" : "http";
- const baseUrl = `${protocol}://localhost:${proxyPort}`;
- return operation(baseUrl, httpsAgent);
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay,
- httpsAgent
- }
- );
-};
-
-const validateWithGatewayHttp = async <T>(
- config: {
- gatewayId: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (baseUrl: string) => Promise<T>
-): Promise<T> => {
- // For gateway-auth validation, the gateway auto-discovers the K8s API from env vars,
- // so we use a placeholder host/port. The actual target is resolved by the gateway's
- // use-k8s-sa handler via KUBERNETES_SERVICE_HOST env var.
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId: config.gatewayId,
- targetHost: "kubernetes.default.svc.cluster.local",
- targetPort: 443
- });
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const baseUrl = `http://localhost:${proxyPort}`;
- return operation(baseUrl);
- },
- {
- protocol: GatewayProxyProtocol.Http,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const kubernetesResourceFactory: TPamResourceFactory<
- TKubernetesResourceConnectionDetails,
- TKubernetesAccountCredentials,
- TPamResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
- try {
- await executeWithGateway(
- { connectionDetails, gatewayId, resourceType },
- gatewayV2Service,
- async (baseUrl, httpsAgent) => {
- // Validate connection by checking API server version
- try {
- await request.get(`${baseUrl}/version`, {
- ...(httpsAgent ? { httpsAgent } : {}),
- signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
- timeout: EXTERNAL_REQUEST_TIMEOUT
- });
- } catch (error) {
- if (error instanceof AxiosError) {
- // If we get a 401/403, it means we reached the API server but need auth - that's fine for connection validation
- if (error.response?.status === 401 || error.response?.status === 403) {
- logger.info(
- { status: error.response.status },
- "[Kubernetes Resource Factory] Kubernetes connection validation succeeded (auth required)"
- );
- return connectionDetails;
- }
- throw new BadRequestError({
- message: `Unable to connect to Kubernetes API server: ${error.response?.statusText || error.message}`
- });
- }
- throw error;
- }
-
- logger.info("[Kubernetes Resource Factory] Kubernetes connection validation succeeded");
- return connectionDetails;
- }
- );
- return connectionDetails;
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<
- TKubernetesAccountCredentials
- > = async (credentials) => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- const { authMethod } = credentials;
-
- if (authMethod === KubernetesAuthMethod.ServiceAccountToken) {
- try {
- await executeWithGateway(
- { connectionDetails, gatewayId, resourceType },
- gatewayV2Service,
- async (baseUrl, httpsAgent) => {
- // Validate service account token using SelfSubjectReview API (whoami)
- // This endpoint doesn't require any special permissions from the service account
- try {
- await request.post(
- `${baseUrl}/apis/authentication.k8s.io/v1/selfsubjectreviews`,
- {
- apiVersion: "authentication.k8s.io/v1",
- kind: "SelfSubjectReview"
- },
- {
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${credentials.serviceAccountToken}`
- },
- ...(httpsAgent ? { httpsAgent } : {}),
- signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
- timeout: EXTERNAL_REQUEST_TIMEOUT
- }
- );
-
- logger.info("[Kubernetes Resource Factory] Kubernetes service account token authentication successful");
- } catch (error) {
- if (error instanceof AxiosError) {
- if (error.response?.status === 401 || error.response?.status === 403) {
- throw new BadRequestError({
- message:
- "Account credentials invalid. Service account token is not valid or does not have required permissions."
- });
- }
- throw new BadRequestError({
- message: `Unable to validate account credentials: ${error.response?.statusText || error.message}`
- });
- }
- throw error;
- }
- }
- );
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError) {
- throw error;
- }
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- }
-
- if (authMethod === KubernetesAuthMethod.GatewayKubernetesAuth) {
- // Validate gateway auth by performing an impersonated SelfSubjectReview through the gateway.
- // The gateway's use-k8s-sa handler injects its own pod token and discovers the K8s API.
- // We add Impersonate-User header which passes through untouched.
- // This validates that the gateway has RBAC permission to impersonate the specified SA.
- // NOTE: It does NOT verify the SA exists — K8s impersonation is a pure permission check.
- // A non-existent SA passes validation here but fails at session time with 403.
- try {
- await validateWithGatewayHttp({ gatewayId }, gatewayV2Service, async (baseUrl) => {
- const impersonateUser = `system:serviceaccount:${credentials.namespace}:${credentials.serviceAccountName}`;
- try {
- await request.post(
- `${baseUrl}/apis/authentication.k8s.io/v1/selfsubjectreviews`,
- {
- apiVersion: "authentication.k8s.io/v1",
- kind: "SelfSubjectReview"
- },
- {
- headers: {
- "Content-Type": "application/json",
- "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount,
- "Impersonate-User": impersonateUser
- },
- signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
- timeout: EXTERNAL_REQUEST_TIMEOUT
- }
- );
-
- logger.info(
- `[Kubernetes Resource Factory] Gateway K8s auth validation successful [namespace=${credentials.namespace}] [sa=${credentials.serviceAccountName}]`
- );
- } catch (error) {
- if (error instanceof AxiosError) {
- const errorMessage =
- (error.response?.data as { message?: string })?.message || error.response?.statusText || error.message;
-
- if (errorMessage?.includes("failed to read k8s sa auth token")) {
- throw new BadRequestError({
- message:
- "Gateway is not running inside a Kubernetes cluster. Gateway auth requires the gateway to be deployed as a pod."
- });
- }
- if (error.response?.status === 403) {
- if (errorMessage?.includes("impersonate")) {
- throw new BadRequestError({
- message: `Gateway service account lacks impersonation permissions for service account "${credentials.serviceAccountName}" in namespace "${credentials.namespace}". Ensure the gateway's ClusterRole includes the impersonate verb for this service account.`
- });
- }
- throw new BadRequestError({
- message: `Unable to impersonate service account "${credentials.serviceAccountName}" in namespace "${credentials.namespace}": ${errorMessage}`
- });
- }
- if (error.code === "ECONNABORTED" || error.code === "ERR_CANCELED") {
- throw new BadRequestError({
- message: "Unable to reach the Kubernetes API server through the gateway."
- });
- }
- throw new BadRequestError({
- message: `Unable to validate gateway auth credentials: ${errorMessage}`
- });
- }
- throw error;
- }
- });
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError) {
- throw error;
- }
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- }
-
- throw new BadRequestError({
- message: `Unsupported Kubernetes auth method: ${authMethod as string}`
- });
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<
- TKubernetesAccountCredentials
- > = async () => {
- throw new BadRequestError({
- message: `Unable to rotate account credentials for ${resourceType}: not implemented`
- });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TKubernetesAccountCredentials,
- currentCredentials: TKubernetesAccountCredentials
- ) => {
- if (updatedAccountCredentials.authMethod !== currentCredentials.authMethod) {
- return updatedAccountCredentials;
- }
-
- if (
- updatedAccountCredentials.authMethod === KubernetesAuthMethod.ServiceAccountToken &&
- currentCredentials.authMethod === KubernetesAuthMethod.ServiceAccountToken
- ) {
- if (updatedAccountCredentials.serviceAccountToken === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- serviceAccountToken: currentCredentials.serviceAccountToken
- };
- }
- }
-
- // Gateway auth has no sensitive fields (namespace and serviceAccountName are identifiers, not secrets),
- // so no sentinel handling is needed — fall through to return as-is.
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-fns.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-fns.ts
deleted file mode 100644
index b7d3546c5c..0000000000
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { KubernetesResourceListItemSchema } from "./kubernetes-resource-schemas";
-
-export const getKubernetesResourceListItem = () => {
- return {
- name: KubernetesResourceListItemSchema.shape.name.value,
- resource: KubernetesResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts
deleted file mode 100644
index 4e2b836257..0000000000
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import { KubernetesAuthMethod } from "./kubernetes-resource-enums";
-
-export const BaseKubernetesResourceSchema = BasePamResourceSchema.extend({
- resourceType: z.literal(PamResource.Kubernetes)
-});
-
-export const KubernetesResourceListItemSchema = z.object({
- name: z.literal("Kubernetes"),
- resource: z.literal(PamResource.Kubernetes)
-});
-
-export const KubernetesResourceConnectionDetailsSchema = z.object({
- url: z.string().url().trim().max(500),
- sslRejectUnauthorized: z.boolean(),
- sslCertificate: z
- .string()
- .trim()
- .transform((value) => value || undefined)
- .optional()
-});
-
-export const KubernetesServiceAccountTokenCredentialsSchema = z.object({
- authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken),
- serviceAccountToken: z.string().trim().max(10000)
-});
-
-export const KubernetesGatewayAuthCredentialsSchema = z.object({
- authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
- namespace: z.string().trim().min(1).max(63),
- serviceAccountName: z.string().trim().min(1).max(253)
-});
-
-export const KubernetesAccountCredentialsSchema = z.discriminatedUnion("authMethod", [
- KubernetesServiceAccountTokenCredentialsSchema,
- KubernetesGatewayAuthCredentialsSchema
-]);
-
-export const KubernetesResourceSchema = BaseKubernetesResourceSchema.extend({
- connectionDetails: KubernetesResourceConnectionDetailsSchema,
- rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedKubernetesResourceSchema = BaseKubernetesResourceSchema.extend({
- connectionDetails: KubernetesResourceConnectionDetailsSchema,
- rotationAccountCredentials: z
- .discriminatedUnion("authMethod", [
- z.object({
- authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
- }),
- z.object({
- authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
- namespace: z.string(),
- serviceAccountName: z.string()
- })
- ])
- .nullable()
- .optional()
-});
-
-export const CreateKubernetesResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: KubernetesResourceConnectionDetailsSchema,
- rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateKubernetesResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: KubernetesResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const KubernetesAccountSchema = BasePamAccountSchema.extend({
- credentials: KubernetesAccountCredentialsSchema
-});
-
-export const CreateKubernetesAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: KubernetesAccountCredentialsSchema
-});
-
-export const UpdateKubernetesAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: KubernetesAccountCredentialsSchema.optional()
-});
-
-export const SanitizedKubernetesAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.Kubernetes),
- credentials: z.discriminatedUnion("authMethod", [
- z.object({
- authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
- }),
- z.object({
- authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
- namespace: z.string(),
- serviceAccountName: z.string()
- })
- ])
-});
-
-// Sessions
-export const KubernetesSessionCredentialsSchema = KubernetesResourceConnectionDetailsSchema.and(
- KubernetesAccountCredentialsSchema
-);
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-types.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-types.ts
deleted file mode 100644
index d23163d267..0000000000
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- KubernetesAccountCredentialsSchema,
- KubernetesAccountSchema,
- KubernetesResourceConnectionDetailsSchema,
- KubernetesResourceSchema
-} from "./kubernetes-resource-schemas";
-
-// Resources
-export type TKubernetesResource = z.infer<typeof KubernetesResourceSchema>;
-export type TKubernetesResourceConnectionDetails = z.infer<typeof KubernetesResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TKubernetesAccount = z.infer<typeof KubernetesAccountSchema>;
-export type TKubernetesAccountCredentials = z.infer<typeof KubernetesAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-factory.ts b/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-factory.ts
deleted file mode 100644
index da274558f9..0000000000
--- a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-factory.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-import dns from "dns";
-import { MongoClient, MongoServerError } from "mongodb";
-import ConnectionString from "mongodb-connection-string-url";
-import tls, { PeerCertificate } from "tls";
-import { promisify } from "util";
-
-import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../pam-resource-types";
-import { TMongoDBAccountCredentials, TMongoDBResourceConnectionDetails } from "./mongodb-resource-types";
-
-const resolveSrv = promisify(dns.resolveSrv);
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-// MongoDB error code 18 = AuthenticationFailed
-const MONGO_AUTH_FAILED_CODE = 18;
-
-interface MongoDBResourceConnection {
- validate: (connectOnly: boolean) => Promise<void>;
- rotateCredentials: (currentCredentials: TMongoDBAccountCredentials, newPassword: string) => Promise<never>;
- close: () => Promise<void>;
-}
-
-/**
- * Parse a MongoDB connection string into its components for relay routing and connection building.
- * Expects a validated URI (mongodb:// or mongodb+srv://) — schema validation ensures this.
- */
-export const parseMongoConnectionString = (connectionString: string) => {
- const cs = new ConnectionString(connectionString);
- const { isSRV } = cs;
- const authSource = cs.searchParams.get("authSource") || "admin";
-
- const [firstHost] = cs.hosts;
- let hostname: string;
- let port: number | undefined;
-
- if (isSRV) {
- // SRV hosts have no port
- hostname = firstHost;
- } else {
- const colonIdx = firstHost.lastIndexOf(":");
- if (colonIdx !== -1) {
- hostname = firstHost.slice(0, colonIdx);
- port = parseInt(firstHost.slice(colonIdx + 1), 10);
- } else {
- hostname = firstHost;
- port = 27017;
- }
- }
-
- return { hostname, port, isSRV, authSource };
-};
-
-/**
- * For MongoDB SRV connections, resolve the SRV record to discover the actual host and port.
- * Used for relay routing — the relay needs a concrete host:port for the TCP tunnel.
- */
-const resolveMongoSrvHost = async (host: string): Promise<{ host: string; port: number }> => {
- const records = await resolveSrv(`_mongodb._tcp.${host}`);
- if (records.length > 0) {
- // Randomize record selection so retries can hit a different node if one is down
- const record = records[Math.floor(Math.random() * records.length)];
- return { host: record.name, port: record.port };
- }
- throw new BadRequestError({
- message: `Unable to resolve SRV record for MongoDB host "${host}". Ensure the host is a valid SRV domain.`
- });
-};
-
-/**
- * Build a MongoDB client connection through a local gateway proxy.
- * Receives pre-parsed connection info — no URI parsing happens here.
- */
-const makeMongoDBConnection = (
- proxyPort: number,
- config: {
- hostname: string;
- authSource: string;
- database: string;
- sslEnabled: boolean;
- sslRejectUnauthorized: boolean;
- sslCertificate?: string;
- username?: string;
- password?: string;
- }
-): MongoDBResourceConnection => {
- const { hostname, authSource, database, sslEnabled, sslRejectUnauthorized, sslCertificate, username, password } =
- config;
-
- const authPart = username && password ? `${encodeURIComponent(username)}:${encodeURIComponent(password)}@` : "";
-
- const encodedDatabase = encodeURIComponent(database);
- const uri = `mongodb://${authPart}localhost:${proxyPort}/${encodedDatabase}?authSource=${encodeURIComponent(authSource)}&directConnection=true&serverSelectionTimeoutMS=${EXTERNAL_REQUEST_TIMEOUT}&connectTimeoutMS=${EXTERNAL_REQUEST_TIMEOUT}`;
-
- const mongoClient = new MongoClient(uri, {
- ...(sslEnabled && {
- tls: true,
- tlsAllowInvalidCertificates: !sslRejectUnauthorized,
- servername: hostname,
- checkServerIdentity: (_hostnameParam: string, cert: PeerCertificate) => {
- return tls.checkServerIdentity(hostname, cert);
- }
- }),
- ...(sslEnabled && sslCertificate && { ca: sslCertificate })
- });
-
- return {
- validate: async (connectOnly) => {
- try {
- await mongoClient.connect();
- await mongoClient.db(database).command({ ping: 1 });
- } catch (error) {
- if (connectOnly && error instanceof MongoServerError && error.code === MONGO_AUTH_FAILED_CODE) {
- return;
- }
- throw new BadRequestError({
- message: `Unable to validate connection to MongoDB: ${(error as Error).message || String(error)}`
- });
- }
- },
- rotateCredentials: async () => {
- throw new BadRequestError({
- message: "Credential rotation is not yet supported for MongoDB resources"
- });
- },
- close: async () => {
- await mongoClient.close();
- }
- };
-};
-
-const executeWithGateway = async <T>(
- config: {
- connectionDetails: TMongoDBResourceConnectionDetails;
- gatewayId: string;
- username?: string;
- password?: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (connection: MongoDBResourceConnection) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
-
- // Parse the connection string once — extract hostname, port, SRV flag, and authSource
- const parsed = parseMongoConnectionString(connectionDetails.connectionString);
-
- let resolvedHost = parsed.hostname;
- let resolvedPort: number = parsed.port ?? 0;
-
- // For SRV hosts, resolve to a concrete host:port for the relay tunnel
- if (parsed.isSRV) {
- const resolved = await resolveMongoSrvHost(parsed.hostname);
- resolvedHost = resolved.host;
- resolvedPort = resolved.port;
- }
-
- const [targetHost] = await verifyHostInputValidity({
- host: resolvedHost,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: resolvedPort
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- // For SRV, use the resolved shard hostname for TLS servername.
- // TLS certificates are issued for individual shard hostnames, not the SRV domain,
- // so the servername must match the actual server we're connecting to.
- const effectiveHostname = parsed.isSRV ? resolvedHost : parsed.hostname;
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const connection = makeMongoDBConnection(proxyPort, {
- hostname: effectiveHostname,
- authSource: parsed.authSource,
- database: connectionDetails.database,
- sslEnabled: connectionDetails.sslEnabled,
- sslRejectUnauthorized: connectionDetails.sslRejectUnauthorized,
- sslCertificate: connectionDetails.sslCertificate,
- username: config.username,
- password: config.password
- });
- try {
- return await operation(connection);
- } finally {
- await connection.close();
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const mongodbResourceFactory: TPamResourceFactory<
- TMongoDBResourceConnectionDetails,
- TMongoDBAccountCredentials,
- TPamResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway({ connectionDetails, gatewayId }, gatewayV2Service, async (client) => {
- await client.validate(true);
- });
- return connectionDetails;
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TMongoDBAccountCredentials> = async (
- credentials
- ) => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway(
- {
- connectionDetails,
- gatewayId,
- username: credentials.username,
- password: credentials.password
- },
- gatewayV2Service,
- async (client) => {
- await client.validate(false);
- }
- );
- return credentials;
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<
- TMongoDBAccountCredentials
- > = async () => {
- throw new BadRequestError({
- message: "Credential rotation is not yet supported for MongoDB resources"
- });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TMongoDBAccountCredentials,
- currentCredentials: TMongoDBAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-fns.ts b/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-fns.ts
deleted file mode 100644
index 408f3992cd..0000000000
--- a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { MongoDBResourceListItemSchema } from "./mongodb-resource-schemas";
-
-export const getMongoDBResourceListItem = () => {
- return {
- name: MongoDBResourceListItemSchema.shape.name.value,
- resource: MongoDBResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-schemas.ts b/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-schemas.ts
deleted file mode 100644
index dc4f3be59c..0000000000
--- a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-schemas.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import ConnectionString from "mongodb-connection-string-url";
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-
-// Resources
-// MongoDB uses a connection string (mongodb:// or mongodb+srv:// URI) instead of
-// separate host + port fields. The URI is validated and sanitized on input.
-export const MongoDBResourceConnectionDetailsSchema = z.object({
- connectionString: z
- .string()
- .trim()
- .min(1)
- .max(1024)
- .transform((val, ctx) => {
- let cs: ConnectionString;
- try {
- cs = new ConnectionString(val);
- } catch {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Invalid MongoDB connection string. Must start with mongodb:// or mongodb+srv://"
- });
- return z.NEVER;
- }
-
- if (cs.username || cs.password) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message:
- "Credentials should not be included in the connection string — they are managed separately per account"
- });
- return z.NEVER;
- }
-
- if (cs.pathname && cs.pathname !== "/") {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Database should not be included in the connection string — use the Database field instead"
- });
- return z.NEVER;
- }
-
- return cs.toString();
- }),
- database: z
- .string()
- .trim()
- .min(1)
- .max(64)
- .regex(/^[a-zA-Z0-9_-]+$/, "Database name can only contain letters, numbers, underscores, and hyphens"),
- sslEnabled: z.boolean(),
- sslRejectUnauthorized: z.boolean(),
- sslCertificate: z
- .string()
- .trim()
- .transform((value) => value || undefined)
- .optional()
-});
-
-export const MongoDBAccountCredentialsSchema = z.object({
- username: z.string().trim().min(1).max(256, "Username must be 256 characters or less"),
- password: z.string().trim().min(1).max(256, "Password must be 256 characters or less")
-});
-
-const BaseMongoDBResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.MongoDB) });
-
-export const MongoDBResourceSchema = BaseMongoDBResourceSchema.extend({
- connectionDetails: MongoDBResourceConnectionDetailsSchema,
- rotationAccountCredentials: MongoDBAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedMongoDBResourceSchema = BaseMongoDBResourceSchema.extend({
- connectionDetails: MongoDBResourceConnectionDetailsSchema,
- rotationAccountCredentials: MongoDBAccountCredentialsSchema.pick({
- username: true
- })
- .nullable()
- .optional()
-});
-
-export const MongoDBResourceListItemSchema = z.object({
- name: z.literal("MongoDB"),
- resource: z.literal(PamResource.MongoDB)
-});
-
-export const CreateMongoDBResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: MongoDBResourceConnectionDetailsSchema,
- rotationAccountCredentials: MongoDBAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateMongoDBResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: MongoDBResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: MongoDBAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const MongoDBAccountSchema = BasePamAccountSchema.extend({
- credentials: MongoDBAccountCredentialsSchema
-});
-
-export const CreateMongoDBAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: MongoDBAccountCredentialsSchema
-});
-
-export const UpdateMongoDBAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: MongoDBAccountCredentialsSchema.optional()
-});
-
-export const SanitizedMongoDBAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.MongoDB),
- credentials: MongoDBAccountCredentialsSchema.pick({
- username: true
- })
-});
-
-// Sessions
-export const MongoDBSessionCredentialsSchema = MongoDBResourceConnectionDetailsSchema.and(
- MongoDBAccountCredentialsSchema
-);
diff --git a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-types.ts b/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-types.ts
deleted file mode 100644
index 0d0d18ad25..0000000000
--- a/backend/src/ee/services/pam-resource/mongodb/mongodb-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- MongoDBAccountCredentialsSchema,
- MongoDBAccountSchema,
- MongoDBResourceConnectionDetailsSchema,
- MongoDBResourceSchema
-} from "./mongodb-resource-schemas";
-
-// Resources
-export type TMongoDBResource = z.infer<typeof MongoDBResourceSchema>;
-export type TMongoDBResourceConnectionDetails = z.infer<typeof MongoDBResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TMongoDBAccount = z.infer<typeof MongoDBAccountSchema>;
-export type TMongoDBAccountCredentials = z.infer<typeof MongoDBAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/mssql/mssql-resource-enums.ts b/backend/src/ee/services/pam-resource/mssql/mssql-resource-enums.ts
deleted file mode 100644
index 502d70b747..0000000000
--- a/backend/src/ee/services/pam-resource/mssql/mssql-resource-enums.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export enum MsSqlAuthMethod {
- SqlLogin = "sql-login",
- Ntlm = "ntlm",
- Kerberos = "kerberos"
-}
diff --git a/backend/src/ee/services/pam-resource/mssql/mssql-resource-fns.ts b/backend/src/ee/services/pam-resource/mssql/mssql-resource-fns.ts
deleted file mode 100644
index 5613460f77..0000000000
--- a/backend/src/ee/services/pam-resource/mssql/mssql-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { MsSQLResourceListItemSchema } from "./mssql-resource-schemas";
-
-export const getMsSQLResourceListItem = () => {
- return {
- name: MsSQLResourceListItemSchema.shape.name.value,
- resource: MsSQLResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/mssql/mssql-resource-schemas.ts b/backend/src/ee/services/pam-resource/mssql/mssql-resource-schemas.ts
deleted file mode 100644
index e879a1dd0d..0000000000
--- a/backend/src/ee/services/pam-resource/mssql/mssql-resource-schemas.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import { BaseSqlResourceConnectionDetailsSchema } from "../shared/sql/sql-resource-schemas";
-import { MsSqlAuthMethod } from "./mssql-resource-enums";
-
-export { MsSqlAuthMethod };
-
-// Resources
-export const MsSQLResourceConnectionDetailsSchema = BaseSqlResourceConnectionDetailsSchema;
-
-const MsSQLSqlLoginCredentialsSchema = z.object({
- authMethod: z.literal(MsSqlAuthMethod.SqlLogin).default(MsSqlAuthMethod.SqlLogin),
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256)
-});
-
-const MsSQLNtlmCredentialsSchema = z.object({
- authMethod: z.literal(MsSqlAuthMethod.Ntlm),
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256),
- domain: z.string().trim().min(1, "Domain is required for NTLM authentication").max(255)
-});
-
-const MsSQLKerberosCredentialsSchema = z.object({
- authMethod: z.literal(MsSqlAuthMethod.Kerberos),
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256),
- realm: z
- .string()
- .trim()
- .min(1, "Realm is required for Kerberos")
- .max(255)
- .regex(/^[A-Za-z0-9._-]+$/, "Realm must contain only letters, numbers, dots, hyphens")
- .transform((v) => v.toUpperCase()),
- kdcAddress: z
- .string()
- .trim()
- .max(255)
- .regex(/^[A-Za-z0-9._:-]*$/, "KDC address must be a hostname or IP with optional port")
- .transform((v) => v || undefined)
- .optional(),
- spn: z
- .string()
- .trim()
- .min(1, "SPN is required for Kerberos")
- .max(500)
- .regex(/^[A-Za-z0-9._:/-]+$/, "SPN must contain only letters, numbers, dots, colons, slashes, hyphens")
-});
-
-// z.union so old accounts without authMethod fall through to the sql-login .default()
-export const MsSQLAccountCredentialsSchema = z.union([
- MsSQLKerberosCredentialsSchema,
- MsSQLNtlmCredentialsSchema,
- MsSQLSqlLoginCredentialsSchema
-]);
-
-const BaseMsSQLResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.MsSQL) });
-
-export const MsSQLResourceSchema = BaseMsSQLResourceSchema.extend({
- connectionDetails: MsSQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: MsSQLAccountCredentialsSchema.nullable().optional()
-});
-
-const SanitizedMsSQLCredentialsSchema = z.union([
- z.object({
- authMethod: z.literal(MsSqlAuthMethod.Kerberos),
- username: z.string(),
- realm: z.string(),
- kdcAddress: z.string().optional(),
- spn: z.string()
- }),
- z.object({ authMethod: z.literal(MsSqlAuthMethod.Ntlm), username: z.string(), domain: z.string() }),
- z.object({ authMethod: z.literal(MsSqlAuthMethod.SqlLogin).default(MsSqlAuthMethod.SqlLogin), username: z.string() })
-]);
-
-export const SanitizedMsSQLResourceSchema = BaseMsSQLResourceSchema.extend({
- connectionDetails: MsSQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: SanitizedMsSQLCredentialsSchema.nullable().optional()
-});
-
-export const MsSQLResourceListItemSchema = z.object({
- name: z.literal("Microsoft SQL Server"),
- resource: z.literal(PamResource.MsSQL)
-});
-
-export const CreateMsSQLResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: MsSQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: MsSQLAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateMsSQLResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: MsSQLResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: MsSQLAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const MsSQLAccountSchema = BasePamAccountSchema.extend({
- credentials: MsSQLAccountCredentialsSchema
-});
-
-export const CreateMsSQLAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: MsSQLAccountCredentialsSchema
-});
-
-export const UpdateMsSQLAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: MsSQLAccountCredentialsSchema.optional()
-});
-
-export const SanitizedMsSQLAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.MsSQL),
- credentials: SanitizedMsSQLCredentialsSchema
-});
-
-// Strict variants (no .default()/.transform()) — prevents cross-resource false matches in SessionCredentialsSchema
-const MsSQLStrictSqlLoginCredentialsSchema = z.object({
- authMethod: z.literal(MsSqlAuthMethod.SqlLogin),
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256)
-});
-
-const MsSQLStrictKerberosCredentialsSchema = z.object({
- authMethod: z.literal(MsSqlAuthMethod.Kerberos),
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256),
- realm: z.string().trim().min(1).max(255),
- kdcAddress: z.string().trim().max(255).optional(),
- spn: z.string().trim().min(1).max(500)
-});
-
-export const MsSQLSessionCredentialsSchema = z.union([
- MsSQLResourceConnectionDetailsSchema.and(MsSQLStrictKerberosCredentialsSchema),
- MsSQLResourceConnectionDetailsSchema.and(MsSQLNtlmCredentialsSchema),
- MsSQLResourceConnectionDetailsSchema.and(MsSQLStrictSqlLoginCredentialsSchema)
-]);
diff --git a/backend/src/ee/services/pam-resource/mssql/mssql-resource-types.ts b/backend/src/ee/services/pam-resource/mssql/mssql-resource-types.ts
deleted file mode 100644
index eb3e49b8b1..0000000000
--- a/backend/src/ee/services/pam-resource/mssql/mssql-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- MsSQLAccountCredentialsSchema,
- MsSQLAccountSchema,
- MsSQLResourceConnectionDetailsSchema,
- MsSQLResourceSchema
-} from "./mssql-resource-schemas";
-
-// Resources
-export type TMsSQLResource = z.infer<typeof MsSQLResourceSchema>;
-export type TMsSQLResourceConnectionDetails = z.infer<typeof MsSQLResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TMsSQLAccount = z.infer<typeof MsSQLAccountSchema>;
-export type TMsSQLAccountCredentials = z.infer<typeof MsSQLAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts
deleted file mode 100644
index 4010d208b5..0000000000
--- a/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { MySQLResourceListItemSchema } from "./mysql-resource-schemas";
-
-export const getMySQLResourceListItem = () => {
- return {
- name: MySQLResourceListItemSchema.shape.name.value,
- resource: MySQLResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts
deleted file mode 100644
index 9f6604c2cc..0000000000
--- a/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import {
- BaseSqlAccountCredentialsSchema,
- BaseSqlResourceConnectionDetailsSchema
-} from "../shared/sql/sql-resource-schemas";
-
-// Resources
-export const MySQLResourceConnectionDetailsSchema = BaseSqlResourceConnectionDetailsSchema.extend({
- // MySQL db in many cases the db will not be provided when making connection
- database: z.string().trim()
-});
-export const MySQLAccountCredentialsSchema = BaseSqlAccountCredentialsSchema;
-
-const BaseMySQLResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.MySQL) });
-
-export const MySQLResourceSchema = BaseMySQLResourceSchema.extend({
- connectionDetails: MySQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedMySQLResourceSchema = BaseMySQLResourceSchema.extend({
- connectionDetails: MySQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: MySQLAccountCredentialsSchema.pick({
- username: true
- })
- .nullable()
- .optional()
-});
-
-export const MySQLResourceListItemSchema = z.object({
- name: z.literal("MySQL"),
- resource: z.literal(PamResource.MySQL)
-});
-
-export const CreateMySQLResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: MySQLResourceConnectionDetailsSchema,
- rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateMySQLResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: MySQLResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const MySQLAccountSchema = BasePamAccountSchema.extend({
- credentials: MySQLAccountCredentialsSchema
-});
-
-export const CreateMySQLAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: MySQLAccountCredentialsSchema
-});
-
-export const UpdateMySQLAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: MySQLAccountCredentialsSchema.optional()
-});
-
-export const SanitizedMySQLAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.MySQL),
- credentials: MySQLAccountCredentialsSchema.pick({
- username: true
- })
-});
-
-// Sessions
-export const MySQLSessionCredentialsSchema = MySQLResourceConnectionDetailsSchema.and(MySQLAccountCredentialsSchema);
diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts
deleted file mode 100644
index 43c2eea517..0000000000
--- a/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- MySQLAccountCredentialsSchema,
- MySQLAccountSchema,
- MySQLResourceConnectionDetailsSchema,
- MySQLResourceSchema
-} from "./mysql-resource-schemas";
-
-// Resources
-export type TMySQLResource = z.infer<typeof MySQLResourceSchema>;
-export type TMySQLResourceConnectionDetails = z.infer<typeof MySQLResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TMySQLAccount = z.infer<typeof MySQLAccountSchema>;
-export type TMySQLAccountCredentials = z.infer<typeof MySQLAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/oracle/oracle-resource-constants.ts b/backend/src/ee/services/pam-resource/oracle/oracle-resource-constants.ts
deleted file mode 100644
index 91ea924901..0000000000
--- a/backend/src/ee/services/pam-resource/oracle/oracle-resource-constants.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const ORACLE_TLS_PROBE_TIMEOUT_MS = 10 * 1000;
diff --git a/backend/src/ee/services/pam-resource/oracle/oracle-resource-factory.ts b/backend/src/ee/services/pam-resource/oracle/oracle-resource-factory.ts
deleted file mode 100644
index 51d16dce29..0000000000
--- a/backend/src/ee/services/pam-resource/oracle/oracle-resource-factory.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import oracledb from "oracledb";
-
-import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../pam-resource-types";
-import { probeOracleTls } from "./oracle-resource-fns";
-import { TOracleAccountCredentials, TOracleResourceConnectionDetails } from "./oracle-resource-types";
-
-const ORACLE_CONNECT_TIMEOUT_SECONDS = 30;
-const TEST_CONNECTION_USERNAME = "infisical-gateway-connection-test";
-const TEST_CONNECTION_PASSWORD = "infisical-gateway-connection-test-password";
-
-interface OracleResourceConnection {
- validate: (connectOnly: boolean) => Promise<void>;
- rotateCredentials: () => Promise<never>;
- close: () => Promise<void>;
-}
-
-const makeOracleConnection = (
- proxyPort: number,
- config: {
- connectionDetails: TOracleResourceConnectionDetails;
- username?: string;
- password?: string;
- }
-): OracleResourceConnection => {
- const { connectionDetails } = config;
- const { host, sslEnabled, sslRejectUnauthorized, sslCertificate } = connectionDetails;
- const actualUsername = config.username ?? TEST_CONNECTION_USERNAME;
- const actualPassword = config.password ?? TEST_CONNECTION_PASSWORD;
-
- const connectString = sslEnabled
- ? `tcps://localhost:${proxyPort}/${connectionDetails.database}?ssl_server_dn_match=false`
- : `localhost:${proxyPort}/${connectionDetails.database}`;
-
- const openConnection = () =>
- oracledb.getConnection({
- user: actualUsername,
- password: actualPassword,
- connectString,
- connectTimeout: ORACLE_CONNECT_TIMEOUT_SECONDS,
- transportConnectTimeout: ORACLE_CONNECT_TIMEOUT_SECONDS
- });
-
- return {
- validate: async (connectOnly) => {
- // Probe TLS first to validate hostname + cert chain. The tcps:// connect
- // string uses ssl_server_dn_match=false (required because we connect via
- // localhost proxy), so this probe is the hostname validation layer.
- if (sslEnabled) {
- try {
- await probeOracleTls({
- tcpHost: "localhost",
- port: proxyPort,
- servername: host,
- caPem: sslCertificate,
- rejectUnauthorized: sslRejectUnauthorized
- });
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to Oracle: ${(error as Error).message || String(error)}`
- });
- }
- }
-
- let conn: oracledb.Connection | null = null;
- try {
- conn = await openConnection();
- await conn.execute("SELECT 1 FROM DUAL");
- } catch (error) {
- if (error instanceof Error) {
- const msg = error.message || "";
- if (connectOnly && msg.includes("ORA-")) {
- return;
- }
- }
- // Probe passed so the cert is valid — tcps:// failure is likely because
- // the custom CA isn't in the system trust store. Save anyway; creds
- // will be checked on first PAM session.
- if (sslEnabled && sslCertificate) {
- return;
- }
- throw new BadRequestError({
- message: `Unable to validate connection to Oracle: ${(error as Error).message || String(error)}`
- });
- } finally {
- if (conn) {
- await conn.close().catch(() => undefined);
- }
- }
- },
- rotateCredentials: async () => {
- throw new BadRequestError({ message: "Credential rotation is not yet supported for Oracle resources" });
- },
- close: async () => {}
- };
-};
-
-const executeWithGateway = async <T>(
- config: {
- connectionDetails: TOracleResourceConnectionDetails;
- gatewayId: string;
- username?: string;
- password?: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (connection: OracleResourceConnection) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.host,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const connection = makeOracleConnection(proxyPort, config);
- try {
- return await operation(connection);
- } finally {
- await connection.close();
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const oracleResourceFactory: TPamResourceFactory<
- TOracleResourceConnectionDetails,
- TOracleAccountCredentials,
- TPamResourceInternalMetadata
-> = (_resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway({ connectionDetails, gatewayId }, gatewayV2Service, async (client) => {
- await client.validate(true);
- });
- return connectionDetails;
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TOracleAccountCredentials> = async (
- credentials
- ) => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- try {
- await executeWithGateway(
- {
- connectionDetails,
- gatewayId,
- username: credentials.username,
- password: credentials.password
- },
- gatewayV2Service,
- async (client) => {
- await client.validate(false);
- }
- );
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError && error.message.includes("ORA-01017")) {
- throw new BadRequestError({
- message: "Account credentials invalid: Username or password incorrect"
- });
- }
- throw error;
- }
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TOracleAccountCredentials> = async () => {
- throw new BadRequestError({ message: "Credential rotation is not yet supported for Oracle resources" });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TOracleAccountCredentials,
- currentCredentials: TOracleAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/oracle/oracle-resource-fns.ts b/backend/src/ee/services/pam-resource/oracle/oracle-resource-fns.ts
deleted file mode 100644
index 79d3da4d7c..0000000000
--- a/backend/src/ee/services/pam-resource/oracle/oracle-resource-fns.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import net from "net";
-import tls from "tls";
-
-import { ORACLE_TLS_PROBE_TIMEOUT_MS } from "./oracle-resource-constants";
-import { OracleResourceListItemSchema } from "./oracle-resource-schemas";
-import { TProbeOracleTlsArgs } from "./oracle-resource-types";
-
-export const getOracleResourceListItem = () => {
- return {
- name: OracleResourceListItemSchema.shape.name.value,
- resource: OracleResourceListItemSchema.shape.resource.value
- };
-};
-
-// TLS reachability + cert chain check. node-oracledb thin can't accept an inline CA.
-export const probeOracleTls = ({
- tcpHost,
- port,
- servername,
- caPem,
- rejectUnauthorized,
- timeoutMs = ORACLE_TLS_PROBE_TIMEOUT_MS
-}: TProbeOracleTlsArgs): Promise<void> =>
- new Promise((resolve, reject) => {
- const socket = net.connect({ host: tcpHost, port });
- socket.setTimeout(timeoutMs);
- socket.once("error", (err) => {
- socket.destroy();
- reject(err);
- });
- socket.once("timeout", () => {
- socket.destroy();
- reject(new Error("timeout connecting to Oracle listener"));
- });
- socket.once("connect", () => {
- const tlsSocket = tls.connect({
- socket,
- servername,
- ca: caPem || undefined,
- rejectUnauthorized
- });
- tlsSocket.once("secureConnect", () => {
- tlsSocket.end();
- resolve();
- });
- tlsSocket.once("error", (err) => {
- tlsSocket.destroy();
- reject(err);
- });
- });
- });
diff --git a/backend/src/ee/services/pam-resource/oracle/oracle-resource-schemas.ts b/backend/src/ee/services/pam-resource/oracle/oracle-resource-schemas.ts
deleted file mode 100644
index 6721ebc15c..0000000000
--- a/backend/src/ee/services/pam-resource/oracle/oracle-resource-schemas.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import {
- BaseSqlAccountCredentialsSchema,
- BaseSqlResourceConnectionDetailsSchema
-} from "../shared/sql/sql-resource-schemas";
-
-// Resources
-export const OracleResourceConnectionDetailsSchema = BaseSqlResourceConnectionDetailsSchema.extend({
- database: z
- .string()
- .trim()
- .min(1)
- .max(128)
- .regex(
- /^[a-zA-Z][a-zA-Z0-9_.#$]*$/,
- "Invalid Oracle service name: must start with a letter and contain only letters, digits, underscores, dots, # or $"
- )
-});
-export const OracleAccountCredentialsSchema = BaseSqlAccountCredentialsSchema;
-
-const BaseOracleResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.OracleDB) });
-
-export const OracleResourceSchema = BaseOracleResourceSchema.extend({
- connectionDetails: OracleResourceConnectionDetailsSchema,
- rotationAccountCredentials: OracleAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedOracleResourceSchema = BaseOracleResourceSchema.extend({
- connectionDetails: OracleResourceConnectionDetailsSchema,
- rotationAccountCredentials: OracleAccountCredentialsSchema.pick({
- username: true
- })
- .nullable()
- .optional()
-});
-
-export const OracleResourceListItemSchema = z.object({
- name: z.literal("Oracle Database"),
- resource: z.literal(PamResource.OracleDB)
-});
-
-export const CreateOracleResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: OracleResourceConnectionDetailsSchema,
- rotationAccountCredentials: OracleAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateOracleResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: OracleResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: OracleAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const OracleAccountSchema = BasePamAccountSchema.extend({
- credentials: OracleAccountCredentialsSchema
-});
-
-export const CreateOracleAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: OracleAccountCredentialsSchema
-});
-
-export const UpdateOracleAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: OracleAccountCredentialsSchema.optional()
-});
-
-export const SanitizedOracleAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.OracleDB),
- credentials: OracleAccountCredentialsSchema.pick({
- username: true
- })
-});
-
-// Sessions
-export const OracleSessionCredentialsSchema = OracleResourceConnectionDetailsSchema.and(OracleAccountCredentialsSchema);
diff --git a/backend/src/ee/services/pam-resource/oracle/oracle-resource-types.ts b/backend/src/ee/services/pam-resource/oracle/oracle-resource-types.ts
deleted file mode 100644
index 92cffb9d25..0000000000
--- a/backend/src/ee/services/pam-resource/oracle/oracle-resource-types.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { z } from "zod";
-
-import {
- OracleAccountCredentialsSchema,
- OracleAccountSchema,
- OracleResourceConnectionDetailsSchema,
- OracleResourceSchema
-} from "./oracle-resource-schemas";
-
-export type TOracleResource = z.infer<typeof OracleResourceSchema>;
-export type TOracleResourceConnectionDetails = z.infer<typeof OracleResourceConnectionDetailsSchema>;
-export type TOracleAccount = z.infer<typeof OracleAccountSchema>;
-export type TOracleAccountCredentials = z.infer<typeof OracleAccountCredentialsSchema>;
-
-export type TProbeOracleTlsArgs = {
- tcpHost: string;
- port: number;
- servername: string;
- caPem: string | undefined;
- rejectUnauthorized: boolean;
- timeoutMs?: number;
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-dal.ts
deleted file mode 100644
index c9709b5835..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-dal.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-import { Knex } from "knex";
-import RE2 from "re2";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { TPamResourceWithFavorite } from "@app/ee/services/pam-resource/pam-resource-types";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { OrderByDirection } from "@app/lib/types";
-import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
-
-import { PamResourceOrderBy } from "./pam-resource-enums";
-
-export type TPamResourceDALFactory = ReturnType<typeof pamResourceDALFactory>;
-export const pamResourceDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamResource);
-
- const findById = async (id: string, tx?: Knex) => {
- const doc = await (tx || db.replicaNode())(TableName.PamResource)
- .leftJoin(TableName.GatewayV2, `${TableName.PamResource}.gatewayId`, `${TableName.GatewayV2}.id`)
- .select(selectAllTableCols(TableName.PamResource))
- .select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))
- .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))
- .where(`${TableName.PamResource}.id`, id)
- .first();
-
- return doc;
- };
-
- const findByProjectId = async (
- {
- projectId,
- search,
- limit,
- offset = 0,
- orderBy = PamResourceOrderBy.Name,
- orderDirection = OrderByDirection.ASC,
- filterResourceTypes,
- metadataFilter,
- userId
- }: {
- projectId: string;
- search?: string;
- limit?: number;
- offset?: number;
- orderBy?: PamResourceOrderBy;
- orderDirection?: OrderByDirection;
- filterResourceTypes?: string[];
- metadataFilter?: Array<{ key: string; value?: string }>;
- userId?: string;
- },
- tx?: Knex
- ): Promise<{ resources: TPamResourceWithFavorite[]; totalCount: number }> => {
- try {
- const dbInstance = tx || db.replicaNode();
- const query = dbInstance(TableName.PamResource).where(`${TableName.PamResource}.projectId`, projectId);
-
- if (userId) {
- void query.leftJoin(TableName.PamResourceFavorite, function joinFavorites() {
- this.on(`${TableName.PamResourceFavorite}.pamResourceId`, `${TableName.PamResource}.id`).andOn(
- `${TableName.PamResourceFavorite}.userId`,
- db.raw("?", [userId])
- );
- });
- }
-
- if (search) {
- // escape special characters (`%`, `_`) and the escape character itself (`\`)
- const escapedSearch = search
- .replace(new RE2(/\\/g), "\\\\")
- .replace(new RE2(/%/g), "\\%")
- .replace(new RE2(/_/g), "\\_");
- const pattern = `%${escapedSearch}%`;
- void query.where((q) => {
- void q
- .whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamResource, "name", pattern])
- .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamResource, "resourceType", pattern]);
- });
- }
-
- if (filterResourceTypes && filterResourceTypes.length) {
- void query.whereIn(`${TableName.PamResource}.resourceType`, filterResourceTypes);
- }
-
- if (metadataFilter && metadataFilter.length > 0) {
- void applyMetadataFilter(query, metadataFilter, "pamResourceId", TableName.PamResource);
- }
-
- const countQuery = query.clone().count("*", { as: "count" }).first();
-
- void query.select(selectAllTableCols(TableName.PamResource));
-
- if (userId) {
- void query.select(
- db.raw(
- `CASE WHEN "${TableName.PamResourceFavorite}"."id" IS NOT NULL THEN true ELSE false END as "isFavorite"`
- )
- );
- } else {
- void query.select(db.raw(`false as "isFavorite"`));
- }
-
- const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";
-
- if (userId) {
- void query.orderByRaw(`"isFavorite" DESC`);
- }
- void query.orderByRaw(`${TableName.PamResource}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]);
-
- if (typeof limit === "number") {
- void query.limit(limit).offset(offset);
- }
-
- const [resources, countResult] = await Promise.all([query, countQuery]);
- const totalCount = Number(countResult?.count || 0);
-
- return { resources: resources as TPamResourceWithFavorite[], totalCount };
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM resources" });
- }
- };
-
- const findMetadataByResourceIds = async (resourceIds: string[], tx?: Knex) => {
- if (!resourceIds.length) return {};
- const rows = await (tx || db.replicaNode())(TableName.ResourceMetadata)
- .select("id", "key", "value", "pamResourceId")
- .whereIn("pamResourceId", resourceIds);
- const byResourceId: Record<string, Array<{ id: string; key: string; value: string }>> = {};
- for (const row of rows) {
- if (row.pamResourceId) {
- if (!byResourceId[row.pamResourceId]) byResourceId[row.pamResourceId] = [];
- byResourceId[row.pamResourceId].push({ id: row.id, key: row.key, value: row.value || "" });
- }
- }
- return byResourceId;
- };
-
- const findByDomainId = async (domainId: string, tx?: Knex) => {
- try {
- const resources = await (tx || db.replicaNode())(TableName.PamResource)
- .select(selectAllTableCols(TableName.PamResource))
- .where(`${TableName.PamResource}.domainId`, domainId)
- .orderBy(`${TableName.PamResource}.name`, "asc");
-
- return resources;
- } catch (error) {
- throw new DatabaseError({ error, name: "Find PAM resources by domain ID" });
- }
- };
-
- const findByGatewayId = async (gatewayId: string, tx?: Knex) => {
- const docs = await (tx || db.replicaNode())(TableName.PamResource)
- .leftJoin(TableName.Project, `${TableName.PamResource}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.PamResource}.gatewayId`, gatewayId)
- .select(
- db.ref("id").withSchema(TableName.PamResource),
- db.ref("name").withSchema(TableName.PamResource),
- db.ref("projectId").withSchema(TableName.PamResource),
- db.ref("resourceType").withSchema(TableName.PamResource),
- db.ref("name").withSchema(TableName.Project).as("projectName")
- );
-
- return docs;
- };
-
- const countByGatewayId = async (gatewayId: string, tx?: Knex) => {
- const result = await (tx || db.replicaNode())(TableName.PamResource)
- .where(`${TableName.PamResource}.gatewayId`, gatewayId)
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- };
-
- const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const docs = await (tx || db.replicaNode())(TableName.PamResource)
- .leftJoin(TableName.Project, `${TableName.PamResource}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.PamResource}.gatewayPoolId`, gatewayPoolId)
- .select(
- db.ref("id").withSchema(TableName.PamResource),
- db.ref("name").withSchema(TableName.PamResource),
- db.ref("projectId").withSchema(TableName.PamResource),
- db.ref("resourceType").withSchema(TableName.PamResource),
- db.ref("name").withSchema(TableName.Project).as("projectName")
- );
-
- return docs;
- };
-
- const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {
- const result = await (tx || db.replicaNode())(TableName.PamResource)
- .where(`${TableName.PamResource}.gatewayPoolId`, gatewayPoolId)
- .count("id")
- .first();
-
- return parseInt(String(result?.count || "0"), 10);
- };
-
- const countByProject = async (projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamResource)
- .where("projectId", projectId)
- .count("id as count")
- .first();
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const countWithRotationByProject = async (projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamResource)
- .where("projectId", projectId)
- .whereNotNull("encryptedRotationAccountCredentials")
- .count("id as count")
- .first();
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const countByProjectGroupedByType = async (
- projectId: string,
- tx?: Knex
- ): Promise<{ resourceType: string; count: number }[]> => {
- const rows = (await (tx || db.replicaNode())(TableName.PamResource)
- .select("resourceType")
- .count("id as count")
- .where("projectId", projectId)
- .groupBy("resourceType")) as unknown as { resourceType: string; count: string | number }[];
-
- return rows.map((row) => ({ resourceType: row.resourceType, count: Number(row.count) }));
- };
-
- return {
- ...orm,
- findById,
- findByProjectId,
- findMetadataByResourceIds,
- findByDomainId,
- findByGatewayId,
- countByGatewayId,
- findByGatewayPoolId,
- countByGatewayPoolId,
- countByProject,
- countWithRotationByProject,
- countByProjectGroupedByType
- };
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-factory.ts b/backend/src/ee/services/pam-resource/pam-resource-factory.ts
deleted file mode 100644
index 4cc0348ee3..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-factory.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { awsIamResourceFactory } from "./aws-iam/aws-iam-resource-factory";
-import { kubernetesResourceFactory } from "./kubernetes/kubernetes-resource-factory";
-import { mongodbResourceFactory } from "./mongodb/mongodb-resource-factory";
-import { oracleResourceFactory } from "./oracle/oracle-resource-factory";
-import { PamResource } from "./pam-resource-enums";
-import {
- TPamAccountCredentials,
- TPamResourceConnectionDetails,
- TPamResourceFactory,
- TPamResourceInternalMetadata
-} from "./pam-resource-types";
-import { redisResourceFactory } from "./redis/redis-resource-factory";
-import { sqlResourceFactory } from "./shared/sql/sql-resource-factory";
-import { sshResourceFactory } from "./ssh/ssh-resource-factory";
-import { windowsResourceFactory } from "./windows-server/windows-server-resource-factory";
-
-type TPamResourceFactoryImplementation = TPamResourceFactory<
- TPamResourceConnectionDetails,
- TPamAccountCredentials,
- TPamResourceInternalMetadata
->;
-
-export const PAM_RESOURCE_FACTORY_MAP: Record<PamResource, TPamResourceFactoryImplementation> = {
- [PamResource.Postgres]: sqlResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.MySQL]: sqlResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.MsSQL]: sqlResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.SSH]: sshResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.Kubernetes]: kubernetesResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.AwsIam]: awsIamResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.Redis]: redisResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.MongoDB]: mongodbResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.Windows]: windowsResourceFactory as TPamResourceFactoryImplementation,
- [PamResource.OracleDB]: oracleResourceFactory as TPamResourceFactoryImplementation
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-favorite-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-favorite-dal.ts
deleted file mode 100644
index 4eee185547..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-favorite-dal.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TPamResourceFavoriteDALFactory = ReturnType<typeof pamResourceFavoriteDALFactory>;
-
-export const pamResourceFavoriteDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamResourceFavorite);
-
- return { ...orm };
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-fns.ts b/backend/src/ee/services/pam-resource/pam-resource-fns.ts
deleted file mode 100644
index c9241322d8..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-fns.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { TPamResources } from "@app/db/schemas";
-import { logger } from "@app/lib/logger";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
-import { getAwsIamResourceListItem } from "./aws-iam/aws-iam-resource-fns";
-import { getKubernetesResourceListItem } from "./kubernetes/kubernetes-resource-fns";
-import { getMongoDBResourceListItem } from "./mongodb/mongodb-resource-fns";
-import { getMsSQLResourceListItem } from "./mssql/mssql-resource-fns";
-import { getMySQLResourceListItem } from "./mysql/mysql-resource-fns";
-import { getOracleResourceListItem } from "./oracle/oracle-resource-fns";
-import { TPamResource, TPamResourceConnectionDetails, TPamResourceInternalMetadata } from "./pam-resource-types";
-import { getPostgresResourceListItem } from "./postgres/postgres-resource-fns";
-import { getRedisResourceListItem } from "./redis/redis-resource-fns";
-import { getSshResourceListItem } from "./ssh/ssh-resource-fns";
-import { getWindowsResourceListItem } from "./windows-server/windows-server-resource-fns";
-
-export const listResourceOptions = () => {
- return [
- getPostgresResourceListItem(),
- getMySQLResourceListItem(),
- getMsSQLResourceListItem(),
- getOracleResourceListItem(),
- getAwsIamResourceListItem(),
- getKubernetesResourceListItem(),
- getRedisResourceListItem(),
- getMongoDBResourceListItem(),
- getWindowsResourceListItem(),
- getSshResourceListItem()
- ].sort((a, b) => a.name.localeCompare(b.name));
-};
-
-// Resource
-export const encryptResourceConnectionDetails = async ({
- projectId,
- connectionDetails,
- kmsService
-}: {
- projectId: string;
- connectionDetails: TPamResourceConnectionDetails;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob: encryptedConnectionDetailsBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(connectionDetails))
- });
-
- return encryptedConnectionDetailsBlob;
-};
-
-export const decryptResourceConnectionDetails = async ({
- projectId,
- encryptedConnectionDetails,
- kmsService
-}: {
- projectId: string;
- encryptedConnectionDetails: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedConnectionDetails
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as TPamResourceConnectionDetails;
-};
-
-// Resource Metadata
-export const encryptResourceInternalMetadata = async ({
- projectId,
- internalMetadata,
- kmsService
-}: {
- projectId: string;
- internalMetadata: TPamResourceInternalMetadata;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(internalMetadata))
- });
-
- return cipherTextBlob;
-};
-
-export const decryptResourceMetadata = async <T extends TPamResourceInternalMetadata>({
- projectId,
- encryptedMetadata,
- kmsService
-}: {
- projectId: string;
- encryptedMetadata: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedMetadata
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as T;
-};
-
-export const decryptResource = async (
- resource: TPamResources,
- projectId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
-) => {
- const {
- encryptedConnectionDetails,
- encryptedRotationAccountCredentials,
- encryptedResourceMetadata,
- encryptedSessionSummaryConfig,
- ...rest
- } = resource;
-
- let sessionSummaryConfig: { aiInsightsEnabled: boolean; connectionId: string; model: string } | null = null;
-
- if (encryptedSessionSummaryConfig) {
- try {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- sessionSummaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedSessionSummaryConfig }).toString()) as {
- aiInsightsEnabled: boolean;
- connectionId: string;
- model: string;
- };
- } catch (err) {
- logger.warn(
- { err, resourceId: resource.id },
- "decryptResource: failed to decrypt sessionSummaryConfig, falling back to null"
- );
- }
- }
-
- return {
- ...rest,
- connectionDetails: await decryptResourceConnectionDetails({
- encryptedConnectionDetails,
- projectId,
- kmsService
- }),
- rotationAccountCredentials: encryptedRotationAccountCredentials
- ? await decryptAccountCredentials({
- encryptedCredentials: encryptedRotationAccountCredentials,
- projectId,
- kmsService
- })
- : null,
- sessionSummaryConfig
- } as TPamResource;
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.ts
deleted file mode 100644
index 5296bb6818..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-dal.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { ormify } from "@app/lib/knex";
-
-export type TPamResourceRotationRulesDALFactory = ReturnType<typeof pamResourceRotationRulesDALFactory>;
-
-export const pamResourceRotationRulesDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamResourceRotationRule);
-
- const findByResourceId = async (resourceId: string, tx?: Knex) => {
- try {
- return await (tx || db.replicaNode())(TableName.PamResourceRotationRule)
- .where({ resourceId })
- .orderBy("priority", "asc")
- .select("*");
- } catch (error) {
- throw new DatabaseError({ error, name: "Find rotation rules by resource ID" });
- }
- };
-
- const findByResourceIds = async (resourceIds: string[], tx?: Knex) => {
- try {
- if (!resourceIds.length) return [];
-
- return await (tx || db.replicaNode())(TableName.PamResourceRotationRule)
- .whereIn("resourceId", resourceIds)
- .orderBy("priority", "asc")
- .select("*");
- } catch (error) {
- throw new DatabaseError({ error, name: "Find rotation rules by resource IDs" });
- }
- };
-
- const getMaxPriority = async (resourceId: string, tx?: Knex) => {
- try {
- const result = await (tx || db.replicaNode())(TableName.PamResourceRotationRule)
- .where({ resourceId })
- .max("priority as maxPriority")
- .first();
-
- return Number((result as { maxPriority?: number | null })?.maxPriority) || 0;
- } catch (error) {
- throw new DatabaseError({ error, name: "Get max rotation rule priority" });
- }
- };
-
- return {
- ...orm,
- findByResourceId,
- findByResourceIds,
- getMaxPriority
- };
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.ts b/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.ts
deleted file mode 100644
index 6991dffd78..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-rotation-rules-service.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-import { ForbiddenError, subject } from "@casl/ability";
-import picomatch from "picomatch";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor } from "@app/lib/types";
-
-import { TPermissionServiceFactory } from "../permission/permission-service-types";
-import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
-import { TPamResourceDALFactory } from "./pam-resource-dal";
-import { TPamResourceRotationRulesDALFactory } from "./pam-resource-rotation-rules-dal";
-
-type TPamResourceRotationRulesServiceFactoryDep = {
- pamResourceRotationRulesDAL: TPamResourceRotationRulesDALFactory;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
-};
-
-export type TPamResourceRotationRulesServiceFactory = ReturnType<typeof pamResourceRotationRulesServiceFactory>;
-
-export const pamResourceRotationRulesServiceFactory = ({
- pamResourceRotationRulesDAL,
- pamResourceDAL,
- permissionService
-}: TPamResourceRotationRulesServiceFactoryDep) => {
- const ensureEditPermission = async (resourceId: string, actor: OrgServiceActor) => {
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamResources, { name: resource.name, resourceType: resource.resourceType })
- );
-
- return resource;
- };
-
- const listByResourceId = async (resourceId: string, actor: OrgServiceActor) => {
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, { name: resource.name, resourceType: resource.resourceType })
- );
-
- const rules = await pamResourceRotationRulesDAL.findByResourceId(resourceId);
- return { rules, resource };
- };
-
- const create = async (
- {
- resourceId,
- name,
- namePattern,
- enabled,
- intervalSeconds
- }: {
- resourceId: string;
- name?: string;
- namePattern: string;
- enabled: boolean;
- intervalSeconds?: number | null;
- },
- actor: OrgServiceActor
- ) => {
- const resource = await ensureEditPermission(resourceId, actor);
-
- if (enabled && (intervalSeconds === undefined || intervalSeconds === null)) {
- throw new BadRequestError({ message: "Interval is required when the rule is enabled" });
- }
-
- // Validate glob pattern
- try {
- picomatch.parse(namePattern);
- } catch {
- throw new BadRequestError({ message: `Invalid glob pattern: ${namePattern}` });
- }
-
- const rule = await pamResourceRotationRulesDAL.transaction(async (tx) => {
- const maxPriority = await pamResourceRotationRulesDAL.getMaxPriority(resourceId, tx);
-
- return pamResourceRotationRulesDAL.create(
- {
- resourceId,
- name: name ?? null,
- namePattern,
- enabled,
- intervalSeconds: intervalSeconds ?? null,
- priority: maxPriority + 1
- },
- tx
- );
- });
-
- return { rule, resource };
- };
-
- const updateById = async (
- resourceId: string,
- ruleId: string,
- updates: {
- name?: string | null;
- namePattern?: string;
- enabled?: boolean;
- intervalSeconds?: number | null;
- },
- actor: OrgServiceActor
- ) => {
- const existingRule = await pamResourceRotationRulesDAL.findById(ruleId);
- if (!existingRule) throw new NotFoundError({ message: `Rotation rule with ID '${ruleId}' not found` });
-
- if (existingRule.resourceId !== resourceId) {
- throw new BadRequestError({ message: `Rule '${ruleId}' does not belong to resource '${resourceId}'` });
- }
-
- const resource = await ensureEditPermission(existingRule.resourceId, actor);
-
- const finalEnabled = updates.enabled ?? existingRule.enabled;
- const finalInterval =
- updates.intervalSeconds !== undefined ? updates.intervalSeconds : existingRule.intervalSeconds;
-
- if (finalEnabled && (finalInterval === undefined || finalInterval === null)) {
- throw new BadRequestError({ message: "Interval is required when the rule is enabled" });
- }
-
- if (updates.namePattern) {
- try {
- picomatch.parse(updates.namePattern);
- } catch {
- throw new BadRequestError({ message: `Invalid glob pattern: ${updates.namePattern}` });
- }
- }
-
- const rule = await pamResourceRotationRulesDAL.updateById(ruleId, updates);
- return { rule, resource };
- };
-
- const deleteById = async (resourceId: string, ruleId: string, actor: OrgServiceActor) => {
- const existingRule = await pamResourceRotationRulesDAL.findById(ruleId);
- if (!existingRule) throw new NotFoundError({ message: `Rotation rule with ID '${ruleId}' not found` });
-
- if (existingRule.resourceId !== resourceId) {
- throw new BadRequestError({ message: `Rule '${ruleId}' does not belong to resource '${resourceId}'` });
- }
-
- const resource = await ensureEditPermission(existingRule.resourceId, actor);
-
- const rule = await pamResourceRotationRulesDAL.deleteById(ruleId);
- return { rule, resource };
- };
-
- const reorderRules = async (resourceId: string, orderedRuleIds: string[], actor: OrgServiceActor) => {
- const resource = await ensureEditPermission(resourceId, actor);
-
- const existingRules = await pamResourceRotationRulesDAL.findByResourceId(resourceId);
- const existingIds = new Set(existingRules.map((r) => r.id));
- const uniqueRuleIds = new Set(orderedRuleIds);
-
- if (uniqueRuleIds.size !== orderedRuleIds.length) {
- throw new BadRequestError({ message: "Duplicate rule IDs are not allowed" });
- }
-
- for (const id of orderedRuleIds) {
- if (!existingIds.has(id)) {
- throw new BadRequestError({ message: `Rule ID '${id}' does not belong to resource '${resourceId}'` });
- }
- }
-
- if (orderedRuleIds.length !== existingRules.length) {
- throw new BadRequestError({ message: "All rules must be included in the reorder request" });
- }
-
- await pamResourceRotationRulesDAL.transaction(async (tx) => {
- // Set all priorities to negative (temp) to avoid unique constraint violations during reorder
- for (let i = 0; i < orderedRuleIds.length; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- await pamResourceRotationRulesDAL.updateById(orderedRuleIds[i], { priority: -(i + 1) }, tx);
- }
- // Now set final priorities
- for (let i = 0; i < orderedRuleIds.length; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- await pamResourceRotationRulesDAL.updateById(orderedRuleIds[i], { priority: i + 1 }, tx);
- }
- });
-
- const rules = await pamResourceRotationRulesDAL.findByResourceId(resourceId);
- return { rules, resource };
- };
-
- return {
- listByResourceId,
- create,
- updateById,
- deleteById,
- reorderRules
- };
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts
deleted file mode 100644
index 63a1b9ee9c..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { z } from "zod";
-
-import { PamAccountsSchema, PamDomainsSchema, PamResourcesSchema, ResourceMetadataSchema } from "@app/db/schemas";
-import { PamDomainType } from "@app/ee/services/pam-domain/pam-domain-enums";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { slugSchema } from "@app/server/lib/schemas";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-export const GatewayAccessResponseSchema = z.object({
- sessionId: z.string(),
- relayClientCertificate: z.string(),
- relayClientPrivateKey: z.string(),
- relayServerCertificateChain: z.string(),
- gatewayClientCertificate: z.string(),
- gatewayClientPrivateKey: z.string(),
- gatewayServerCertificateChain: z.string(),
- relayHost: z.string(),
- metadata: z.record(z.string(), z.string().optional()).optional()
-});
-
-// AI Insights model list — single source of truth for what models are available per provider
-export const PAM_AI_INSIGHT_MODELS: { connectionApp: string; id: string; label: string }[] = [
- { connectionApp: "anthropic", id: "claude-opus-4-6", label: "Claude Opus 4.6" },
- { connectionApp: "anthropic", id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" },
- { connectionApp: "anthropic", id: "claude-haiku-4-5", label: "Claude Haiku 4.5" }
-];
-
-// Resources
-export const SessionSummaryConfigSchema = z
- .object({
- aiInsightsEnabled: z.boolean(),
- connectionId: z.string().uuid(),
- model: z.enum(["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"])
- })
- .nullable()
- .optional();
-
-export const BasePamResourceSchema = PamResourcesSchema.omit({
- encryptedConnectionDetails: true,
- encryptedRotationAccountCredentials: true,
- encryptedResourceMetadata: true,
- encryptedSessionSummaryConfig: true,
- resourceType: true
-}).extend({
- metadata: ResourceMetadataSchema.pick({ id: true, key: true, value: true }).array().optional(),
- sessionSummaryConfig: SessionSummaryConfigSchema
-});
-
-const CoreCreatePamResourceSchema = z.object({
- projectId: z.string().uuid(),
- name: slugSchema({ field: "name" }),
- metadata: ResourceMetadataNonEncryptionSchema.optional()
-});
-
-// No .superRefine — would turn into ZodEffects and break .extend() in per-type schemas.
-export const BaseCreateGatewayPamResourceSchema = CoreCreatePamResourceSchema.extend({
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional()
-});
-
-export const BaseCreatePamResourceSchema = CoreCreatePamResourceSchema;
-
-const CoreUpdatePamResourceSchema = z.object({
- name: slugSchema({ field: "name" }).optional(),
- metadata: ResourceMetadataNonEncryptionSchema.optional(),
- sessionSummaryConfig: SessionSummaryConfigSchema
-});
-
-export const BaseUpdateGatewayPamResourceSchema = CoreUpdatePamResourceSchema.extend({
- gatewayId: z.string().uuid().optional(),
- gatewayPoolId: z.string().uuid().optional()
-});
-
-export const BaseUpdatePamResourceSchema = CoreUpdatePamResourceSchema;
-
-// Accounts
-export const BasePamAccountSchema = PamAccountsSchema.omit({
- encryptedCredentials: true
-}).extend({
- metadata: ResourceMetadataSchema.pick({ id: true, key: true, value: true }).array().optional()
-});
-
-export const BasePamAccountSchemaWithResource = BasePamAccountSchema.extend({
- parentType: z.union([z.nativeEnum(PamResource), z.nativeEnum(PamDomainType)]),
- resource: PamResourcesSchema.pick({
- id: true,
- name: true,
- resourceType: true
- })
- .extend({
- rotationCredentialsConfigured: z.boolean()
- })
- .nullable()
- .optional(),
- domain: PamDomainsSchema.pick({ id: true, name: true, domainType: true }).nullable().optional(),
- policyName: z.string().nullable().optional(),
- lastRotationMessage: z.string().nullable().optional(),
- rotationStatus: z.string().nullable().optional(),
- requireReason: z.boolean().default(false)
-});
-
-export const BaseCreatePamAccountSchema = z.object({
- resourceId: z.string().uuid(),
- folderId: z.string().uuid().optional(),
- name: slugSchema({ field: "name" }),
- description: z.string().max(512).nullable().optional(),
- requireMfa: z.boolean().optional().default(false),
- metadata: ResourceMetadataNonEncryptionSchema.optional(),
- policyId: z.string().uuid().nullable().optional()
-});
-
-export const BaseUpdatePamAccountSchema = z.object({
- name: slugSchema({ field: "name" }).optional(),
- description: z.string().max(512).nullable().optional(),
- requireMfa: z.boolean().optional(),
- metadata: ResourceMetadataNonEncryptionSchema.optional(),
- policyId: z.string().uuid().nullable().optional()
-});
diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.ts
deleted file mode 100644
index a101cd9f8d..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ /dev/null
@@ -1,922 +0,0 @@
-import { ForbiddenError, subject } from "@casl/ability";
-
-import { ActionProjectType, OrganizationActionScope, TPamResources } from "@app/db/schemas";
-import { OrgPermissionAppConnectionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionActions,
- ProjectPermissionAppConnectionActions,
- ProjectPermissionPamAccountActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";
-import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";
-import { PgSqlLock } from "@app/keystore/keystore";
-import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
-import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
-import { AppConnection } from "@app/services/app-connection/app-connection-enums";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
-
-import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
-import { PamAccountView } from "../pam-account/pam-account-enums";
-import { decryptAccountCredentials, encryptAccountCredentials } from "../pam-account/pam-account-fns";
-import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
-import { TPamResourceDALFactory } from "./pam-resource-dal";
-import { PamResource } from "./pam-resource-enums";
-import { PAM_RESOURCE_FACTORY_MAP } from "./pam-resource-factory";
-import { TPamResourceFavoriteDALFactory } from "./pam-resource-favorite-dal";
-import {
- decryptResource,
- decryptResourceConnectionDetails,
- decryptResourceMetadata,
- encryptResourceConnectionDetails,
- encryptResourceInternalMetadata,
- listResourceOptions
-} from "./pam-resource-fns";
-import { TCreateResourceDTO, TListResourcesDTO, TUpdateResourceDTO } from "./pam-resource-types";
-import { TSSHResourceInternalMetadata } from "./ssh/ssh-resource-types";
-
-// Extend this set as more LLM providers are added (e.g. AppConnection.OpenAI)
-const LLM_APP_CONNECTIONS = new Set<AppConnection>([AppConnection.Anthropic]);
-
-// Resource types that have AI session summary prompts defined in pam-session-summary-fns.ts
-const AI_SUMMARY_SUPPORTED_RESOURCE_TYPES = new Set<PamResource>([PamResource.Postgres, PamResource.SSH]);
-
-type TPamResourceServiceFactoryDep = {
- pamResourceDAL: TPamResourceDALFactory;
- pamResourceFavoriteDAL: TPamResourceFavoriteDALFactory;
- pamDomainDAL: Pick<TPamDomainDALFactory, "findById">;
- pamAccountDAL: Pick<TPamAccountDALFactory, "findByProjectIdWithParentDetails" | "findMetadataByAccountIds">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2Service: Pick<
- TGatewayV2ServiceFactory,
- "getPAMConnectionDetails" | "getPlatformConnectionDetailsByGatewayId"
- >;
- gatewayPoolService: Pick<
- TGatewayPoolServiceFactory,
- "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"
- >;
- resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- pamProjectRecordingConfigDAL: {
- findByProjectId: (projectId: string) => Promise<unknown>;
- };
-};
-
-export type TPamResourceServiceFactory = ReturnType<typeof pamResourceServiceFactory>;
-
-export const pamResourceServiceFactory = ({
- pamResourceDAL,
- pamResourceFavoriteDAL,
- pamDomainDAL,
- pamAccountDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- resourceMetadataDAL,
- appConnectionDAL,
- pamProjectRecordingConfigDAL
-}: TPamResourceServiceFactoryDep) => {
- const assertDomainInProject = async (domainId: string, projectId: string) => {
- const domain = await pamDomainDAL.findById(domainId);
- if (!domain) throw new NotFoundError({ message: `Domain with ID '${domainId}' not found` });
- if (domain.projectId !== projectId) {
- throw new BadRequestError({ message: "Domain must belong to the same project as the resource" });
- }
- };
-
- const getById = async (id: string, resourceType: PamResource, actor: OrgServiceActor) => {
- const resource = await pamResourceDAL.findById(id);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- // Fetch metadata for permission check
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds([resource.id]);
- const resourceMetadata = metadataByResourceId[resource.id] || [];
-
- const canReadResources = permission.can(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: resourceMetadata
- })
- );
-
- if (!canReadResources) {
- // Check if user can read at least one account in this resource
- const { accounts } = await pamAccountDAL.findByProjectIdWithParentDetails({
- projectId: resource.projectId,
- accountView: PamAccountView.Flat,
- filterResourceIds: [id]
- });
-
- const accountIds = accounts.map((a) => a.id);
- const accountMetadata = await pamAccountDAL.findMetadataByAccountIds(accountIds);
-
- const hasAccountAccess = accounts.some((account) => {
- return permission.can(
- ProjectPermissionPamAccountActions.Read,
- subject(ProjectPermissionSub.PamAccounts, {
- resourceName: resource.name,
- accountName: account.name,
- resourceType: resource.resourceType,
- metadata: accountMetadata[account.id] || []
- })
- );
- });
-
- if (!hasAccountAccess) {
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: resourceMetadata
- })
- );
- }
- }
-
- if (resource.resourceType !== resourceType) {
- throw new BadRequestError({
- message: `Resource with ID '${id}' is not of type '${resourceType}'`
- });
- }
-
- return {
- ...(await decryptResource(resource, resource.projectId, kmsService)),
- metadata: resourceMetadata
- };
- };
-
- const create = async (
- {
- resourceType,
- connectionDetails,
- gatewayId,
- gatewayPoolId,
- name,
- projectId,
- rotationAccountCredentials,
- domainId,
- metadata
- }: TCreateResourceDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
- if (resourceType !== PamResource.AwsIam && !gatewayId && !gatewayPoolId) {
- throw new BadRequestError({ message: "A gateway or gateway pool is required for this resource type" });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Create,
- subject(ProjectPermissionSub.PamResources, {
- name,
- resourceType,
- metadata: (metadata || []).map(({ key, value }) => ({ key, value: value ?? "" }))
- })
- );
-
- if (gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
- }
-
- if (domainId) {
- await assertDomainInProject(domainId, projectId);
- }
-
- // Windows (RDP) recordings are too large for Postgres-backed storage; require an external bucket
- if (resourceType === PamResource.Windows) {
- const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
- if (!recordingConfig) {
- throw new BadRequestError({
- message:
- "Windows resources require an external session recording configuration. Configure session recording in project settings before creating a Windows resource."
- });
- }
- }
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });
-
- const factory = PAM_RESOURCE_FACTORY_MAP[resourceType](
- resourceType,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- projectId
- );
-
- const validatedConnectionDetails = await factory.validateConnection();
- const encryptedConnectionDetails = await encryptResourceConnectionDetails({
- connectionDetails: validatedConnectionDetails,
- projectId,
- kmsService
- });
-
- let encryptedRotationAccountCredentials: Buffer | null = null;
-
- if (rotationAccountCredentials) {
- const validatedRotationAccountCredentials = await factory.validateAccountCredentials(rotationAccountCredentials);
-
- encryptedRotationAccountCredentials = await encryptAccountCredentials({
- credentials: validatedRotationAccountCredentials,
- projectId,
- kmsService
- });
- }
-
- try {
- const { resource, insertedMetadata } = await pamResourceDAL.transaction(async (tx) => {
- const newResource = await pamResourceDAL.create(
- {
- resourceType,
- encryptedConnectionDetails,
- gatewayId: gatewayPoolId ? null : gatewayId,
- gatewayPoolId: gatewayPoolId ?? null,
- name,
- projectId,
- encryptedRotationAccountCredentials,
- domainId: domainId ?? null
- },
- tx
- );
- let metadataRows: Awaited<ReturnType<typeof resourceMetadataDAL.insertMany>> | undefined;
- if (metadata && metadata.length > 0) {
- metadataRows = await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamResourceId: newResource.id,
- orgId: actor.orgId
- })),
- tx
- );
- }
- return { resource: newResource, insertedMetadata: metadataRows };
- });
-
- return {
- ...(await decryptResource(resource, projectId, kmsService)),
- metadata: insertedMetadata?.map(({ id, key, value }) => ({ id, key, value: value ?? "" })) ?? []
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Resource with name '${name}' already exists for this project`
- });
- }
- throw err;
- }
- };
-
- const updateById = async (
- {
- connectionDetails,
- resourceId,
- name,
- rotationAccountCredentials,
- gatewayId,
- gatewayPoolId,
- domainId,
- metadata,
- sessionSummaryConfig
- }: TUpdateResourceDTO,
- actor: OrgServiceActor
- ) => {
- if (gatewayId && gatewayPoolId) {
- throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });
- }
-
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- // Fetch current metadata for permission check
- const existingMetadata = await pamResourceDAL.findMetadataByResourceIds([resourceId]);
- const currentMetadata = existingMetadata[resourceId] || [];
-
- // Check permission against current state
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: currentMetadata
- })
- );
-
- // If any conditionable field is changing, also check permission against proposed state
- if (metadata || name) {
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamResources, {
- name: name ?? resource.name,
- resourceType: resource.resourceType,
- metadata: metadata ? metadata.map(({ key, value }) => ({ key, value: value ?? "" })) : currentMetadata
- })
- );
- }
-
- if (gatewayPoolId && gatewayPoolId !== resource.gatewayPoolId) {
- await gatewayPoolService.resolveAttachableGatewayFromPool({
- poolId: gatewayPoolId,
- orgId: actor.orgId,
- actor
- });
- }
-
- const updateDoc: Partial<TPamResources> = {};
-
- // Mutual exclusion: setting one clears the other.
- let effectiveGatewayIdAttr: string | null | undefined = resource.gatewayId;
- let effectiveGatewayPoolIdAttr: string | null | undefined = resource.gatewayPoolId ?? null;
- if (gatewayId !== undefined && gatewayPoolId !== undefined) {
- effectiveGatewayIdAttr = gatewayId;
- effectiveGatewayPoolIdAttr = gatewayPoolId;
- } else if (gatewayId !== undefined) {
- effectiveGatewayIdAttr = gatewayId;
- effectiveGatewayPoolIdAttr = gatewayId !== null ? null : undefined;
- } else if (gatewayPoolId !== undefined) {
- effectiveGatewayPoolIdAttr = gatewayPoolId;
- effectiveGatewayIdAttr = gatewayPoolId !== null ? null : undefined;
- }
-
- if (gatewayId !== undefined || gatewayPoolId !== undefined) {
- updateDoc.gatewayId = effectiveGatewayIdAttr;
- updateDoc.gatewayPoolId = effectiveGatewayPoolIdAttr;
- }
-
- if (name !== undefined) {
- updateDoc.name = name;
- }
-
- if (domainId !== undefined) {
- if (domainId) {
- await assertDomainInProject(domainId, resource.projectId);
- }
- updateDoc.domainId = domainId;
- }
-
- let effectiveGatewayId: string | null | undefined;
- if (connectionDetails !== undefined || rotationAccountCredentials !== undefined) {
- effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: effectiveGatewayIdAttr,
- gatewayPoolId: effectiveGatewayPoolIdAttr
- });
- }
-
- if (connectionDetails !== undefined) {
- const factory = PAM_RESOURCE_FACTORY_MAP[resource.resourceType as PamResource](
- resource.resourceType as PamResource,
- connectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- resource.projectId
- );
- const validatedConnectionDetails = await factory.validateConnection();
- const encryptedConnectionDetails = await encryptResourceConnectionDetails({
- connectionDetails: validatedConnectionDetails,
- projectId: resource.projectId,
- kmsService
- });
- updateDoc.encryptedConnectionDetails = encryptedConnectionDetails;
- }
-
- if (rotationAccountCredentials !== undefined) {
- updateDoc.encryptedRotationAccountCredentials = null;
-
- if (rotationAccountCredentials) {
- const decryptedConnectionDetails =
- connectionDetails ??
- (await decryptResourceConnectionDetails({
- encryptedConnectionDetails: resource.encryptedConnectionDetails,
- projectId: resource.projectId,
- kmsService
- }));
-
- const factory = PAM_RESOURCE_FACTORY_MAP[resource.resourceType as PamResource](
- resource.resourceType as PamResource,
- decryptedConnectionDetails,
- effectiveGatewayId,
- gatewayV2Service,
- resource.projectId
- );
-
- let finalCredentials = { ...rotationAccountCredentials };
- if (resource.encryptedRotationAccountCredentials) {
- const decryptedCredentials = await decryptAccountCredentials({
- encryptedCredentials: resource.encryptedRotationAccountCredentials,
- projectId: resource.projectId,
- kmsService
- });
-
- finalCredentials = await factory.handleOverwritePreventionForCensoredValues(
- rotationAccountCredentials,
- decryptedCredentials
- );
- }
-
- try {
- const validatedRotationAccountCredentials = await factory.validateAccountCredentials(finalCredentials);
-
- updateDoc.encryptedRotationAccountCredentials = await encryptAccountCredentials({
- credentials: validatedRotationAccountCredentials,
- projectId: resource.projectId,
- kmsService
- });
- } catch (err) {
- if (err instanceof BadRequestError) {
- throw new BadRequestError({
- message: `Rotation Account Error: ${err.message}`
- });
- }
-
- throw err;
- }
- }
- }
-
- if (sessionSummaryConfig !== undefined) {
- if (sessionSummaryConfig === null) {
- updateDoc.encryptedSessionSummaryConfig = null;
- } else {
- if (!AI_SUMMARY_SUPPORTED_RESOURCE_TYPES.has(resource.resourceType as PamResource)) {
- throw new BadRequestError({
- message: `AI session summaries are not supported for resource type '${resource.resourceType}'`
- });
- }
-
- const appConnection = await appConnectionDAL.findById(sessionSummaryConfig.connectionId);
- if (!appConnection) {
- throw new NotFoundError({
- message: `App connection with ID '${sessionSummaryConfig.connectionId}' not found`
- });
- }
- if (appConnection.orgId !== actor.orgId) {
- throw new BadRequestError({
- message: "App connection does not belong to the same organization as the resource"
- });
- }
- if (!LLM_APP_CONNECTIONS.has(appConnection.app as AppConnection)) {
- throw new BadRequestError({
- message: `App connection must be an AI provider connection, got '${appConnection.app}'`
- });
- }
-
- // Check actor has Connect permission on the app connection
- if (appConnection.projectId) {
- const { permission: appConnectionPermission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- projectId: appConnection.projectId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.Any
- });
- ForbiddenError.from(appConnectionPermission).throwUnlessCan(
- ProjectPermissionAppConnectionActions.Connect,
- subject(ProjectPermissionSub.AppConnections, { connectionId: sessionSummaryConfig.connectionId })
- );
- } else {
- const { permission: appConnectionPermission } = await permissionService.getOrgPermission({
- actorId: actor.id,
- actor: actor.type,
- orgId: appConnection.orgId,
- actorOrgId: actor.orgId,
- actorAuthMethod: actor.authMethod,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(appConnectionPermission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Connect,
- subject(OrgPermissionSubjects.AppConnections, { connectionId: sessionSummaryConfig.connectionId })
- );
- }
-
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: resource.projectId
- });
- const { cipherTextBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(sessionSummaryConfig))
- });
- updateDoc.encryptedSessionSummaryConfig = cipherTextBlob;
- }
- }
-
- // If nothing was updated, return the fetched resource
- if (Object.keys(updateDoc).length === 0 && metadata === undefined && sessionSummaryConfig === undefined) {
- const existingMeta = await pamResourceDAL.findMetadataByResourceIds([resourceId]);
- return {
- ...(await decryptResource(resource, resource.projectId, kmsService)),
- metadata: existingMeta[resourceId] || []
- };
- }
-
- try {
- const updatedResource = await pamResourceDAL.transaction(async (tx) => {
- if (metadata) {
- await resourceMetadataDAL.delete({ pamResourceId: resourceId }, tx);
- if (metadata.length > 0) {
- await resourceMetadataDAL.insertMany(
- metadata.map(({ key, value }) => ({
- key,
- value: value ?? "",
- pamResourceId: resourceId,
- orgId: actor.orgId
- })),
- tx
- );
- }
- }
- if (Object.keys(updateDoc).length > 0) {
- return pamResourceDAL.updateById(resourceId, updateDoc, tx);
- }
- return resource;
- });
-
- const freshMeta = await pamResourceDAL.findMetadataByResourceIds([resourceId]);
-
- return {
- ...(await decryptResource(updatedResource, resource.projectId, kmsService)),
- metadata: freshMeta[resourceId] || []
- };
- } catch (err) {
- if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
- throw new BadRequestError({
- message: `Resource with name '${name}' already exists for this project`
- });
- }
- throw err;
- }
- };
-
- const deleteById = async (id: string, actor: OrgServiceActor) => {
- const resource = await pamResourceDAL.findById(id);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${id}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds([id]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Delete,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: metadataByResourceId[id] || []
- })
- );
-
- try {
- const deletedResource = await pamResourceDAL.deleteById(id);
- return await decryptResource(deletedResource, resource.projectId, kmsService);
- } catch (err) {
- if (
- err instanceof DatabaseError &&
- (err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation
- ) {
- throw new BadRequestError({
- message: "Failed to delete resource because it is attached to active PAM accounts"
- });
- }
- throw err;
- }
- };
-
- const list = async ({ projectId, actor, actorId, actorAuthMethod, actorOrgId, ...params }: TListResourcesDTO) => {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- // Check what kind of PamResources read rules the user has
- const canReadResources = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
-
- if (canReadResources) {
- // Check if rules have conditions
- const resourceRules = permission.rulesFor(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
- const hasConditions = resourceRules.some((rule) => rule.conditions || rule.inverted);
-
- if (!hasConditions) {
- // TIER 1: Unconditional access — fast path with DB pagination (existing behavior)
- const { resources, totalCount } = await pamResourceDAL.findByProjectId({
- projectId,
- userId: actorId,
- ...params
- });
- const resourceIds = resources.map((r) => r.id);
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds(resourceIds);
- return {
- resources: await Promise.all(
- resources.map(async (resource) => ({
- ...(await decryptResource(resource, projectId, kmsService)),
- metadata: metadataByResourceId[resource.id] || [],
- isFavorite: resource.isFavorite
- }))
- ),
- totalCount
- };
- }
- }
-
- // Fetch all resources once for both Tier 2 and Tier 3
- const { resources: allResources } = await pamResourceDAL.findByProjectId({
- projectId,
- userId: actorId,
- search: params.search,
- orderBy: params.orderBy,
- orderDirection: params.orderDirection,
- filterResourceTypes: params.filterResourceTypes,
- metadataFilter: params.metadataFilter
- });
-
- if (allResources.length === 0) {
- return { resources: [], totalCount: 0 };
- }
-
- // TIER 2: Conditional access — filter per-resource
- if (canReadResources) {
- const allResourceIds = allResources.map((r) => r.id);
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds(allResourceIds);
-
- const permittedResources = allResources.filter((resource) =>
- permission.can(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: metadataByResourceId[resource.id] || []
- })
- )
- );
-
- if (permittedResources.length > 0) {
- const totalCount = permittedResources.length;
- const offset = params.offset || 0;
- const limit = params.limit || 100;
- const paginatedResources = permittedResources.slice(offset, offset + limit);
-
- return {
- resources: await Promise.all(
- paginatedResources.map(async (resource) => ({
- ...(await decryptResource(resource, projectId, kmsService)),
- metadata: metadataByResourceId[resource.id] || [],
- isFavorite: resource.isFavorite
- }))
- ),
- totalCount
- };
- }
- }
-
- // Fetch all accounts for the project (flat view, no pagination) for permission checking
- const { accounts: allAccounts } = await pamAccountDAL.findByProjectIdWithParentDetails({
- projectId,
- accountView: PamAccountView.Flat
- });
-
- if (allAccounts.length === 0) {
- return { resources: [], totalCount: 0 };
- }
-
- // Fetch account metadata for permission checks
- const allAccountIds = allAccounts.map((a) => a.id);
- const accountMetadata = await pamAccountDAL.findMetadataByAccountIds(allAccountIds);
-
- // Group accounts by resource ID
- const accountsByResourceId = new Map<
- string,
- Array<{ accountName: string; metadata: Array<{ id: string; key: string; value: string }> }>
- >();
- for (const account of allAccounts) {
- if (account.resourceId) {
- // Skip domain accounts for resource-level permission check
- const existing = accountsByResourceId.get(account.resourceId) || [];
- existing.push({ accountName: account.name, metadata: accountMetadata[account.id] || [] });
- accountsByResourceId.set(account.resourceId, existing);
- }
- }
-
- // Filter to only resources where the user can read at least one account
- const permittedResources = allResources.filter((resource) => {
- const accounts = accountsByResourceId.get(resource.id) || [];
- return accounts.some((account) =>
- permission.can(
- ProjectPermissionPamAccountActions.Read,
- subject(ProjectPermissionSub.PamAccounts, {
- resourceName: resource.name,
- accountName: account.accountName,
- resourceType: resource.resourceType,
- metadata: account.metadata
- })
- )
- );
- });
-
- const totalCount = permittedResources.length;
- const offset = params.offset || 0;
- const limit = params.limit || 100;
- const paginatedResources = permittedResources.slice(offset, offset + limit);
-
- const paginatedResourceIds = paginatedResources.map((r) => r.id);
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds(paginatedResourceIds);
-
- return {
- resources: await Promise.all(
- paginatedResources.map(async (resource) => ({
- ...(await decryptResource(resource, projectId, kmsService)),
- metadata: metadataByResourceId[resource.id] || [],
- isFavorite: resource.isFavorite
- }))
- ),
- totalCount
- };
- };
-
- const getOrCreateSshCa = async (resourceId: string, actor: OrgServiceActor) => {
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
-
- if (resource.resourceType !== PamResource.SSH) {
- throw new BadRequestError({ message: "This operation is only available for SSH resources" });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: resource.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds([resourceId]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Edit,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: metadataByResourceId[resourceId] || []
- })
- );
-
- // Check if metadata already exists with CA
- if (resource.encryptedResourceMetadata) {
- const metadata = await decryptResourceMetadata<TSSHResourceInternalMetadata>({
- encryptedMetadata: resource.encryptedResourceMetadata,
- projectId: resource.projectId,
- kmsService
- });
- return { caPublicKey: metadata.caPublicKey };
- }
-
- // Transaction with advisory lock to prevent race conditions
- const caPublicKey = await pamResourceDAL.transaction(async (tx) => {
- await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.PamResourceSshCaInit(resourceId)]);
-
- // Re-check after acquiring lock in case another transaction created it
- const currentResource = await pamResourceDAL.findById(resourceId, tx);
- if (currentResource?.encryptedResourceMetadata) {
- const metadata = await decryptResourceMetadata<TSSHResourceInternalMetadata>({
- encryptedMetadata: currentResource.encryptedResourceMetadata,
- projectId: currentResource.projectId,
- kmsService
- });
- return metadata.caPublicKey;
- }
-
- // Generate new CA key pair
- const keyAlgorithm = SshCertKeyAlgorithm.ED25519;
- const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);
-
- const internalMetadata: TSSHResourceInternalMetadata = {
- caPrivateKey: privateKey,
- caPublicKey: publicKey.trim(),
- caKeyAlgorithm: keyAlgorithm
- };
-
- const encryptedResourceMetadata = await encryptResourceInternalMetadata({
- internalMetadata,
- projectId: resource.projectId,
- kmsService
- });
-
- await pamResourceDAL.updateById(resourceId, { encryptedResourceMetadata }, tx);
-
- return internalMetadata.caPublicKey;
- });
-
- return { caPublicKey };
- };
-
- const setUserResourceFavorite = async ({
- projectId,
- resourceId,
- isFavorite,
- actorId,
- actor,
- actorAuthMethod,
- actorOrgId
- }: TProjectPermission & {
- resourceId: string;
- isFavorite: boolean;
- }) => {
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorAuthMethod,
- actorId,
- actorOrgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const userId = actorId;
-
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource || resource.projectId !== projectId) {
- throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });
- }
-
- const metadataByResourceId = await pamResourceDAL.findMetadataByResourceIds([resourceId]);
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Read,
- subject(ProjectPermissionSub.PamResources, {
- name: resource.name,
- resourceType: resource.resourceType,
- metadata: metadataByResourceId[resource.id] || []
- })
- );
-
- if (isFavorite) {
- await pamResourceFavoriteDAL.upsert(
- [{ userId, pamResourceId: resourceId, projectId }],
- ["userId", "pamResourceId"]
- );
- } else {
- await pamResourceFavoriteDAL.delete({ userId, pamResourceId: resourceId });
- }
- };
-
- return {
- getById,
- create,
- updateById,
- deleteById,
- list,
- listResourceOptions,
- getOrCreateSshCa,
- setUserResourceFavorite
- };
-};
diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.ts
deleted file mode 100644
index 9e29643ac7..0000000000
--- a/backend/src/ee/services/pam-resource/pam-resource-types.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-/* eslint-disable @typescript-eslint/no-duplicate-type-constituents */
-import { z } from "zod";
-
-import { TPamResources } from "@app/db/schemas";
-import { OrderByDirection, TProjectPermission } from "@app/lib/types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
-
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { TPamAccountDependenciesDALFactory } from "../pam-discovery/pam-account-dependencies-dal";
-import {
- TAwsIamAccount,
- TAwsIamAccountCredentials,
- TAwsIamResource,
- TAwsIamResourceConnectionDetails
-} from "./aws-iam/aws-iam-resource-types";
-import {
- TKubernetesAccount,
- TKubernetesAccountCredentials,
- TKubernetesResource,
- TKubernetesResourceConnectionDetails
-} from "./kubernetes/kubernetes-resource-types";
-import {
- TMongoDBAccount,
- TMongoDBAccountCredentials,
- TMongoDBResource,
- TMongoDBResourceConnectionDetails
-} from "./mongodb/mongodb-resource-types";
-import {
- TMsSQLAccount,
- TMsSQLAccountCredentials,
- TMsSQLResource,
- TMsSQLResourceConnectionDetails
-} from "./mssql/mssql-resource-types";
-import {
- TMySQLAccount,
- TMySQLAccountCredentials,
- TMySQLResource,
- TMySQLResourceConnectionDetails
-} from "./mysql/mysql-resource-types";
-import {
- TOracleAccount,
- TOracleAccountCredentials,
- TOracleResource,
- TOracleResourceConnectionDetails
-} from "./oracle/oracle-resource-types";
-import { TPamResourceDALFactory } from "./pam-resource-dal";
-import { PamResource, PamResourceOrderBy } from "./pam-resource-enums";
-import {
- TPostgresAccount,
- TPostgresAccountCredentials,
- TPostgresResource,
- TPostgresResourceConnectionDetails
-} from "./postgres/postgres-resource-types";
-import {
- TRedisAccount,
- TRedisAccountCredentials,
- TRedisResource,
- TRedisResourceConnectionDetails
-} from "./redis/redis-resource-types";
-import {
- TSSHAccount,
- TSSHAccountCredentials,
- TSSHResource,
- TSSHResourceConnectionDetails,
- TSSHResourceInternalMetadata
-} from "./ssh/ssh-resource-types";
-import {
- TWindowsAccount,
- TWindowsAccountCredentials,
- TWindowsResource,
- TWindowsResourceConnectionDetails,
- TWindowsResourceInternalMetadata
-} from "./windows-server/windows-server-resource-types";
-
-// Resource types
-export type TPamResource =
- | TPostgresResource
- | TMySQLResource
- | TMsSQLResource
- | TSSHResource
- | TAwsIamResource
- | TKubernetesResource
- | TRedisResource
- | TMongoDBResource
- | TWindowsResource
- | TOracleResource;
-export type TPamResourceWithFavorite = TPamResources & { isFavorite: boolean };
-export type TPamResourceConnectionDetails =
- | TPostgresResourceConnectionDetails
- | TMySQLResourceConnectionDetails
- | TMsSQLResourceConnectionDetails
- | TSSHResourceConnectionDetails
- | TKubernetesResourceConnectionDetails
- | TAwsIamResourceConnectionDetails
- | TRedisResourceConnectionDetails
- | TMongoDBResourceConnectionDetails
- | TWindowsResourceConnectionDetails
- | TOracleResourceConnectionDetails;
-export type TPamResourceInternalMetadata = TSSHResourceInternalMetadata | TWindowsResourceInternalMetadata;
-
-// Account types
-export type TPamAccount =
- | TPostgresAccount
- | TMySQLAccount
- | TMsSQLAccount
- | TSSHAccount
- | TAwsIamAccount
- | TKubernetesAccount
- | TRedisAccount
- | TMongoDBAccount
- | TWindowsAccount
- | TOracleAccount;
-
-export type TPamAccountCredentials =
- | TPostgresAccountCredentials
- | TMySQLAccountCredentials
- | TMsSQLAccountCredentials
- | TSSHAccountCredentials
- | TKubernetesAccountCredentials
- | TAwsIamAccountCredentials
- | TRedisAccountCredentials
- | TMongoDBAccountCredentials
- | TWindowsAccountCredentials
- | TOracleAccountCredentials;
-
-// Resource DTOs
-export type TCreateResourceDTO = Pick<TPamResource, "name" | "connectionDetails" | "resourceType" | "projectId"> & {
- gatewayId?: string | null;
- gatewayPoolId?: string | null;
- rotationAccountCredentials?: TPamAccountCredentials | null;
- domainId?: string | null;
- metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;
-};
-
-export type TSessionSummaryConfigDTO = {
- aiInsightsEnabled: boolean;
- connectionId: string;
- model: string;
-} | null;
-
-export type TUpdateResourceDTO = Partial<Omit<TCreateResourceDTO, "resourceType" | "projectId">> & {
- resourceId: string;
- sessionSummaryConfig?: TSessionSummaryConfigDTO;
-};
-
-export type TListResourcesDTO = {
- search?: string;
- orderBy?: PamResourceOrderBy;
- orderDirection?: OrderByDirection;
- limit?: number;
- offset?: number;
- filterResourceTypes?: string[];
- metadataFilter?: Array<{ key: string; value?: string }>;
-} & TProjectPermission;
-
-// Resource factory
-export type TPamResourceFactoryValidateConnection<T extends TPamResourceConnectionDetails> = () => Promise<T>;
-export type TPamResourceFactoryValidateAccountCredentials<C extends TPamAccountCredentials> = (
- credentials: C
-) => Promise<C>;
-export type TPamResourceFactoryRotateAccountCredentials<C extends TPamAccountCredentials> = (
- rotationAccountCredentials: C,
- currentCredentials: C
-) => Promise<C>;
-
-export type TPostRotateContext = {
- pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "findByAccountId" | "updateById">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findById" | "find">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-};
-
-export type TPamResourceFactory<
- T extends TPamResourceConnectionDetails,
- C extends TPamAccountCredentials,
- M extends TPamResourceInternalMetadata
-> = (
- resourceType: PamResource,
- connectionDetails: T,
- gatewayId: string | null | undefined,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- projectId: string | null | undefined,
- resourceInternalMetadata?: M
-) => {
- validateConnection: TPamResourceFactoryValidateConnection<T>;
- validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<C>;
- rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<C>;
- postRotate?: (
- accountId: string,
- newCredentials: C,
- projectId: string,
- ctx: TPostRotateContext,
- rotationAccountCredentials: C
- ) => Promise<void>;
- handleOverwritePreventionForCensoredValues: (updatedAccountCredentials: C, currentCredentials: C) => Promise<C>;
-};
diff --git a/backend/src/ee/services/pam-resource/postgres/postgres-resource-fns.ts b/backend/src/ee/services/pam-resource/postgres/postgres-resource-fns.ts
deleted file mode 100644
index a3329a9fb1..0000000000
--- a/backend/src/ee/services/pam-resource/postgres/postgres-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { PostgresResourceListItemSchema } from "./postgres-resource-schemas";
-
-export const getPostgresResourceListItem = () => {
- return {
- name: PostgresResourceListItemSchema.shape.name.value,
- resource: PostgresResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/postgres/postgres-resource-schemas.ts b/backend/src/ee/services/pam-resource/postgres/postgres-resource-schemas.ts
deleted file mode 100644
index 4d6e3c945c..0000000000
--- a/backend/src/ee/services/pam-resource/postgres/postgres-resource-schemas.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import {
- BaseSqlAccountCredentialsSchema,
- BaseSqlResourceConnectionDetailsSchema
-} from "../shared/sql/sql-resource-schemas";
-
-export const PostgresResourceConnectionDetailsSchema = BaseSqlResourceConnectionDetailsSchema;
-export const PostgresAccountCredentialsSchema = BaseSqlAccountCredentialsSchema;
-
-// Resources
-const BasePostgresResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.Postgres) });
-
-export const PostgresResourceSchema = BasePostgresResourceSchema.extend({
- connectionDetails: PostgresResourceConnectionDetailsSchema,
- rotationAccountCredentials: PostgresAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedPostgresResourceSchema = BasePostgresResourceSchema.extend({
- connectionDetails: PostgresResourceConnectionDetailsSchema,
- rotationAccountCredentials: PostgresAccountCredentialsSchema.pick({
- username: true
- })
- .nullable()
- .optional()
-});
-
-export const PostgresResourceListItemSchema = z.object({
- name: z.literal("PostgreSQL"),
- resource: z.literal(PamResource.Postgres)
-});
-
-export const CreatePostgresResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: PostgresResourceConnectionDetailsSchema,
- rotationAccountCredentials: PostgresAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdatePostgresResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: PostgresResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: PostgresAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const PostgresAccountSchema = BasePamAccountSchema.extend({
- credentials: PostgresAccountCredentialsSchema
-});
-
-export const CreatePostgresAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: PostgresAccountCredentialsSchema
-});
-
-export const UpdatePostgresAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: PostgresAccountCredentialsSchema.optional()
-});
-
-export const SanitizedPostgresAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.Postgres),
- credentials: PostgresAccountCredentialsSchema.pick({
- username: true
- })
-});
-
-// Sessions
-export const PostgresSessionCredentialsSchema = PostgresResourceConnectionDetailsSchema.and(
- PostgresAccountCredentialsSchema
-);
diff --git a/backend/src/ee/services/pam-resource/postgres/postgres-resource-types.ts b/backend/src/ee/services/pam-resource/postgres/postgres-resource-types.ts
deleted file mode 100644
index 223ba67904..0000000000
--- a/backend/src/ee/services/pam-resource/postgres/postgres-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- PostgresAccountCredentialsSchema,
- PostgresAccountSchema,
- PostgresResourceConnectionDetailsSchema,
- PostgresResourceSchema
-} from "./postgres-resource-schemas";
-
-// Resources
-export type TPostgresResource = z.infer<typeof PostgresResourceSchema>;
-export type TPostgresResourceConnectionDetails = z.infer<typeof PostgresResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TPostgresAccount = z.infer<typeof PostgresAccountSchema>;
-export type TPostgresAccountCredentials = z.infer<typeof PostgresAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/redis/redis-resource-factory.ts b/backend/src/ee/services/pam-resource/redis/redis-resource-factory.ts
deleted file mode 100644
index b4a3b06cf4..0000000000
--- a/backend/src/ee/services/pam-resource/redis/redis-resource-factory.ts
+++ /dev/null
@@ -1,305 +0,0 @@
-import { Redis } from "ioredis";
-import tls, { PeerCertificate } from "tls";
-
-import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../pam-resource-types";
-import { TRedisAccountCredentials, TRedisResourceConnectionDetails } from "./redis-resource-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-export interface RedisResourceConnection {
- /**
- * Validate the connection and optionally authenticate with credentials.
- * If credentials are provided, authenticates with them. Otherwise, just validates the connection.
- *
- * @param credentials optional username and password to authenticate with
- * @returns Promise to be resolved when the connection is good (and authenticated if credentials provided), otherwise an error will be errbacked
- */
- validate: (credentials?: TRedisAccountCredentials) => Promise<void>;
-
- /**
- * Close the connection.
- *
- * @returns Promise for closing the connection
- */
- close: () => Promise<void>;
-}
-
-const makeRedisConnection = (
- proxyPort: number,
- config: {
- connectionDetails: TRedisResourceConnectionDetails;
- }
-): RedisResourceConnection => {
- const { connectionDetails } = config;
- const { sslEnabled, sslRejectUnauthorized, sslCertificate } = connectionDetails;
-
- let client: Redis | null = null;
-
- const createClient = () => {
- // TODO: this ioredis client is too complex for our use case here.
- // ideally we should use a simpler client. but that's what we are using already so..
- const redis = new Redis({
- host: "localhost",
- port: proxyPort,
- connectTimeout: EXTERNAL_REQUEST_TIMEOUT,
- commandTimeout: EXTERNAL_REQUEST_TIMEOUT,
- ...(sslEnabled && {
- tls: {
- rejectUnauthorized: sslRejectUnauthorized,
- ca: sslCertificate,
- // When using proxy, we need to bypass hostname validation since we connect to localhost
- // but validate the certificate against the actual hostname
- checkServerIdentity: (hostname: string, cert: PeerCertificate) => {
- return tls.checkServerIdentity(connectionDetails.host, cert);
- }
- }
- }),
- maxRetriesPerRequest: 0,
- enableReadyCheck: false,
- reconnectOnError: () => false,
- retryStrategy: () => {
- return null;
- }
- });
- return new Promise<Redis>((resolve, reject) => {
- redis.once("connect", () => {
- redis.removeAllListeners("error");
- resolve(redis);
- });
- redis.once("error", (error) => {
- redis.removeAllListeners("connect");
- reject(error);
- });
- });
- };
-
- return {
- validate: async (credentials?) => {
- const isConnectOnly = !credentials || !credentials.username || !credentials.password;
-
- try {
- client = await createClient();
-
- if (credentials && credentials.username && credentials.password) {
- // Authenticate with provided credentials
- const result = await client.auth(credentials.username, credentials.password);
- if (result !== "OK") {
- throw new BadRequestError({
- message: `Authentication failed: Redis returned ${result as string} status`
- });
- }
- } else {
- // Just validate connection with ping
- await client.ping();
- }
- } catch (error) {
- if (isConnectOnly) {
- // If we're only checking connection, authentication failures are acceptable
- if (
- error instanceof Error &&
- (error.message.includes("NOAUTH") ||
- error.message.includes("WRONGPASS") ||
- error.message.includes("invalid password"))
- ) {
- return;
- }
- }
-
- if (error instanceof BadRequestError) {
- throw error;
- }
-
- const errorMessage = isConnectOnly
- ? `Unable to validate Redis connection: ${(error as Error).message || String(error)}`
- : `Unable to authenticate Redis connection: ${(error as Error).message || String(error)}`;
-
- throw new BadRequestError({
- message: errorMessage
- });
- } finally {
- if (client) {
- await client.quit();
- client = null;
- }
- }
- },
- close: async () => {
- if (client) {
- await client.quit();
- client = null;
- }
- }
- };
-};
-
-export const executeWithGateway = async <T>(
- config: {
- connectionDetails: TRedisResourceConnectionDetails;
- gatewayId: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (connection: RedisResourceConnection) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.host,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const connection = makeRedisConnection(proxyPort, config);
- try {
- return await operation(connection);
- } finally {
- await connection.close();
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const redisResourceFactory: TPamResourceFactory<
- TRedisResourceConnectionDetails,
- TRedisAccountCredentials,
- TPamResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- try {
- await executeWithGateway({ connectionDetails, gatewayId }, gatewayV2Service, async (client) => {
- await client.validate();
- });
- return connectionDetails;
- } catch (error) {
- if (error instanceof BadRequestError && error.message === "Connection terminated unexpectedly") {
- throw new BadRequestError({
- message: "Connection terminated unexpectedly. Verify that host and port are correct"
- });
- }
-
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TRedisAccountCredentials> = async (
- credentials
- ) => {
- // Skip validation if credentials are not provided
- if (!credentials.username && !credentials.password) {
- return credentials;
- }
-
- // If either username or password is provided, both are required for validation
- if (!credentials.username || !credentials.password) {
- throw new BadRequestError({
- message: "Both username and password are required for credential validation"
- });
- }
-
- // TypeScript narrowing: at this point both username and password are defined
- const validatedCredentials = {
- username: credentials.username,
- password: credentials.password
- };
-
- try {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway(
- {
- connectionDetails,
- gatewayId
- },
- gatewayV2Service,
- async (client) => {
- await client.validate(validatedCredentials);
- }
- );
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError) {
- if (
- error.message.includes("NOAUTH") ||
- error.message.includes("WRONGPASS") ||
- error.message.includes("invalid password")
- ) {
- throw new BadRequestError({
- message: "Account credentials invalid: Username or password incorrect"
- });
- }
-
- if (error.message === "Connection terminated unexpectedly") {
- throw new BadRequestError({
- message: "Connection terminated unexpectedly. Verify that host and port are correct"
- });
- }
- }
-
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TRedisAccountCredentials> = async () => {
- // TODO: Redis password rotation is not supported yet
- throw new BadRequestError({
- message: "Unsupported operation"
- });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TRedisAccountCredentials,
- currentCredentials: TRedisAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/redis/redis-resource-fns.ts b/backend/src/ee/services/pam-resource/redis/redis-resource-fns.ts
deleted file mode 100644
index cb7239b190..0000000000
--- a/backend/src/ee/services/pam-resource/redis/redis-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { RedisResourceListItemSchema } from "./redis-resource-schemas";
-
-export const getRedisResourceListItem = () => {
- return {
- name: RedisResourceListItemSchema.shape.name.value,
- resource: RedisResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/redis/redis-resource-schemas.ts b/backend/src/ee/services/pam-resource/redis/redis-resource-schemas.ts
deleted file mode 100644
index 2070498612..0000000000
--- a/backend/src/ee/services/pam-resource/redis/redis-resource-schemas.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-
-// Resources
-export const RedisResourceConnectionDetailsSchema = z.object({
- host: z.string().trim().min(1).max(255),
- port: z.coerce.number(),
- sslEnabled: z.boolean(),
- sslRejectUnauthorized: z.boolean(),
- sslCertificate: z
- .string()
- .trim()
- .transform((value) => value || undefined)
- .optional()
-});
-
-export const RedisAccountCredentialsSchema = z.object({
- username: z
- .string()
- .trim()
- .max(256, "Username must be 256 characters or less")
- .transform((value) => (value === "" ? undefined : value))
- .optional(),
- password: z
- .string()
- .max(256, "Password must be 256 characters or less")
- .transform((value) => (value === "" ? undefined : value))
- .optional()
-});
-
-const BaseRedisResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.Redis) });
-
-export const RedisResourceSchema = BaseRedisResourceSchema.extend({
- connectionDetails: RedisResourceConnectionDetailsSchema,
- rotationAccountCredentials: RedisAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedRedisResourceSchema = BaseRedisResourceSchema.extend({
- connectionDetails: RedisResourceConnectionDetailsSchema,
- rotationAccountCredentials: RedisAccountCredentialsSchema.pick({
- username: true
- })
- .nullable()
- .optional()
-});
-
-export const RedisResourceListItemSchema = z.object({
- name: z.literal("Redis"),
- resource: z.literal(PamResource.Redis)
-});
-
-export const CreateRedisResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: RedisResourceConnectionDetailsSchema,
- rotationAccountCredentials: RedisAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateRedisResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: RedisResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: RedisAccountCredentialsSchema.nullable().optional()
-});
-
-// Accounts
-export const RedisAccountSchema = BasePamAccountSchema.extend({
- credentials: RedisAccountCredentialsSchema
-});
-
-export const CreateRedisAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: RedisAccountCredentialsSchema
-});
-
-export const UpdateRedisAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: RedisAccountCredentialsSchema.optional()
-});
-
-export const SanitizedRedisAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.Redis),
- credentials: RedisAccountCredentialsSchema.pick({
- username: true
- })
-});
-
-// Sessions
-export const RedisSessionCredentialsSchema = RedisResourceConnectionDetailsSchema.and(RedisAccountCredentialsSchema);
diff --git a/backend/src/ee/services/pam-resource/redis/redis-resource-types.ts b/backend/src/ee/services/pam-resource/redis/redis-resource-types.ts
deleted file mode 100644
index c199b03c27..0000000000
--- a/backend/src/ee/services/pam-resource/redis/redis-resource-types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod";
-
-import {
- RedisAccountCredentialsSchema,
- RedisAccountSchema,
- RedisResourceConnectionDetailsSchema,
- RedisResourceSchema
-} from "./redis-resource-schemas";
-
-// Resources
-export type TRedisResource = z.infer<typeof RedisResourceSchema>;
-export type TRedisResourceConnectionDetails = z.infer<typeof RedisResourceConnectionDetailsSchema>;
-
-// Accounts
-export type TRedisAccount = z.infer<typeof RedisAccountSchema>;
-export type TRedisAccountCredentials = z.infer<typeof RedisAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts b/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts
deleted file mode 100644
index af3780b91b..0000000000
--- a/backend/src/ee/services/pam-resource/shared/dependency-sync-fns.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-import pLimit from "p-limit";
-import RE2 from "re2";
-import { runPowershell } from "winrm-client";
-
-import { TPamAccountDependencies } from "@app/db/schemas";
-import { groupBy } from "@app/lib/fn";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { PamAccountDependencyType, PamDependencySyncStatus } from "../../pam-discovery/pam-discovery-enums";
-import { decryptResource } from "../pam-resource-fns";
-import { TPostRotateContext } from "../pam-resource-types";
-import { TWindowsResourceConnectionDetails } from "../windows-server/windows-server-resource-types";
-
-const DEPENDENCY_SYNC_RESOURCE_CONCURRENCY = 5;
-
-// Sanitize a string for safe use inside PowerShell single-quoted strings:
-// - doubles single quotes (PowerShell escape)
-// - strips newlines/carriage returns
-const SINGLE_QUOTE_RE = new RE2("'", "g");
-const NEWLINE_RE = new RE2("[\\r\\n]", "g");
-export const escapePowershellSingleQuote = (value: string) =>
- NEWLINE_RE.replace(SINGLE_QUOTE_RE.replace(value, "''"), "");
-
-// Reject control characters (U+0000–U+001F) that could survive escaping
-const CONTROL_CHAR_RE = new RE2("[\\x00-\\x1f]");
-const validateNoControlChars = (value: string, label: string) => {
- if (CONTROL_CHAR_RE.test(value)) {
- throw new Error(`${label} contains control characters`);
- }
-};
-
-// Allow alphanumerics, spaces, hyphen, underscore, dot
-const SAFE_WINDOWS_NAME_RE = new RE2("^[a-zA-Z0-9 _\\-.]+$");
-const validateWindowsName = (value: string, label: string) => {
- if (!SAFE_WINDOWS_NAME_RE.test(value)) {
- throw new Error(`${label} contains invalid characters: ${value}`);
- }
-};
-
-// Allow alphanumerics, spaces, hyphen, underscore, dot, backslash, forward slash (but reject ".." path traversal)
-const SAFE_WINDOWS_PATH_RE = new RE2("^[a-zA-Z0-9 _\\-.\\\\/]+$");
-const PATH_TRAVERSAL_RE = new RE2("\\.\\.");
-const validateWindowsPath = (value: string, label: string) => {
- if (!SAFE_WINDOWS_PATH_RE.test(value) || PATH_TRAVERSAL_RE.test(value)) {
- throw new Error(`${label} contains invalid characters or path traversal: ${value}`);
- }
-};
-
-export const buildDependencySyncScript = (
- dep: TPamAccountDependencies,
- accountUsername: string,
- newPassword: string
-): string => {
- const escapedPassword = escapePowershellSingleQuote(newPassword);
- const escapedName = escapePowershellSingleQuote(dep.name);
- const escapedUsername = escapePowershellSingleQuote(accountUsername);
-
- // Validate all escaped values before interpolation into PowerShell commands
- validateWindowsName(escapedName, "Dependency name");
- validateNoControlChars(escapedUsername, "Account username");
- validateNoControlChars(escapedPassword, "Password");
-
- switch (dep.dependencyType) {
- case PamAccountDependencyType.WindowsService:
- return [
- `sc.exe config '${escapedName}' obj= '${escapedUsername}' password= '${escapedPassword}'`,
- `Restart-Service -Name '${escapedName}' -Force -ErrorAction SilentlyContinue`
- ].join("; ");
-
- case PamAccountDependencyType.ScheduledTask: {
- const taskData = dep.data as { TaskPath?: string } | null;
- const taskPath = taskData?.TaskPath ?? "\\";
- validateWindowsPath(taskPath, "Task path");
- const escapedPath = escapePowershellSingleQuote(taskPath);
- return `schtasks.exe /Change /TN '${escapedPath}${escapedName}' /RU '${escapedUsername}' /RP '${escapedPassword}'`;
- }
-
- case PamAccountDependencyType.IisAppPool:
- return [
- `Import-Module WebAdministration`,
- `Set-ItemProperty 'IIS:\\AppPools\\${escapedName}' processModel.userName '${escapedUsername}'`,
- `Set-ItemProperty 'IIS:\\AppPools\\${escapedName}' processModel.password '${escapedPassword}'`,
- `Restart-WebAppPool '${escapedName}'`
- ].join("; ");
-
- default:
- throw new Error(`Unknown dependency type: ${dep.dependencyType}`);
- }
-};
-
-type TSyncDependenciesParams = {
- accountId: string;
- newCredentials: { username: string; password: string };
- projectId: string;
- ctx: TPostRotateContext;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- rotationCredentials: { username: string; password: string };
- gatewayId: string;
- resolveHostname?: (hostname: string) => Promise<string>;
- formatWinrmUsername?: (rotationUsername: string, hostname: string, resourceType: string) => string;
-};
-
-type TWinrmConfig = {
- winrmPort: number;
- useWinrmHttps: boolean;
- winrmRejectUnauthorized: boolean;
- winrmCaCert?: string;
- winrmTlsServerName?: string;
-};
-
-export type TDependencySyncResult = {
- total: number;
- succeeded: number;
- failed: number;
-};
-
-export const syncDependenciesAfterRotation = async ({
- accountId,
- newCredentials,
- projectId,
- ctx,
- gatewayV2Service,
- rotationCredentials,
- gatewayId,
- resolveHostname,
- formatWinrmUsername
-}: TSyncDependenciesParams): Promise<TDependencySyncResult> => {
- const allDeps = await ctx.pamAccountDependenciesDAL.findByAccountId(accountId);
- const enabledDeps = allDeps.filter((d) => d.isRotationSyncEnabled);
- if (!enabledDeps.length) return { total: 0, succeeded: 0, failed: 0 };
-
- const grouped = groupBy(enabledDeps, (d) => d.resourceId);
-
- // Batch-fetch all target resources to get their hostnames
- const resourceIds = Object.keys(grouped);
- const resources = await ctx.pamResourceDAL.find({ $in: { id: resourceIds } });
- const resourceMap = new Map(resources.map((r) => [r.id, r]));
-
- // Create encryptor lazily (only on first error)
- let encryptor: ((params: { plainText: Buffer }) => { cipherTextBlob: Buffer }) | null = null;
- const getEncryptor = async () => {
- if (!encryptor) {
- const cipherPair = await ctx.kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- encryptor = cipherPair.encryptor;
- }
- return encryptor;
- };
-
- // Track success/failure counts
- let succeededCount = 0;
- let failedCount = 0;
-
- const failAllDeps = async (deps: typeof enabledDeps, msg: string) => {
- let encryptedMsg: Buffer | null = null;
- try {
- const enc = await getEncryptor();
- encryptedMsg = enc({ plainText: Buffer.from(msg) }).cipherTextBlob;
- } catch (err) {
- logger.error(err, `[DependencySync] Failed to encrypt error message`);
- }
- await Promise.all(
- deps.map((dep) =>
- ctx.pamAccountDependenciesDAL.updateById(dep.id, {
- syncStatus: PamDependencySyncStatus.Failed,
- encryptedLastSyncMessage: encryptedMsg
- })
- )
- );
- failedCount += deps.length;
- };
-
- const limit = pLimit(DEPENDENCY_SYNC_RESOURCE_CONCURRENCY);
-
- await Promise.all(
- Object.entries(grouped).map(([resourceId, deps]) =>
- limit(async () => {
- const resource = resourceMap.get(resourceId);
- if (!resource) {
- const msg = `Resource ${resourceId} not found`;
- logger.warn(`[DependencySync] ${msg}, skipping`);
- await failAllDeps(deps, msg);
- return;
- }
-
- // Get hostname and WinRM config from the target resource's connection details
- let hostname: string | null = null;
- let winrmConfig: TWinrmConfig = {
- winrmPort: 5986,
- useWinrmHttps: true,
- winrmRejectUnauthorized: true
- };
-
- try {
- const decrypted = await decryptResource(resource, projectId, ctx.kmsService);
- const connDetails = decrypted.connectionDetails as TWindowsResourceConnectionDetails;
- hostname = connDetails.hostname;
- winrmConfig = {
- winrmPort: connDetails.winrmPort,
- useWinrmHttps: connDetails.useWinrmHttps,
- winrmRejectUnauthorized: connDetails.winrmRejectUnauthorized,
- winrmCaCert: connDetails.winrmCaCert,
- winrmTlsServerName: connDetails.winrmTlsServerName
- };
- } catch (err) {
- logger.error(err, `[DependencySync] Failed to decrypt resource ${resourceId}`);
- await failAllDeps(deps, `Failed to decrypt resource connection details`);
- return;
- }
-
- if (!hostname) {
- const msg = `No hostname found for resource ${resourceId}`;
- logger.warn(`[DependencySync] ${msg}, skipping`);
- await failAllDeps(deps, msg);
- return;
- }
-
- const winrmUsername = formatWinrmUsername
- ? formatWinrmUsername(rotationCredentials.username, hostname, resource.resourceType)
- : rotationCredentials.username;
-
- // Resolve hostname — use custom resolver (e.g. DC DNS) if provided, otherwise use as-is
- let resolvedHost = hostname;
- if (resolveHostname) {
- try {
- resolvedHost = await resolveHostname(hostname);
- } catch (err) {
- logger.warn(err, `[DependencySync] Failed to resolve hostname ${hostname}, using original`);
- }
- }
-
- const [targetHost] = await verifyHostInputValidity({
- host: resolvedHost,
- isGateway: true,
- isDynamicSecret: false
- });
-
- // Get gateway connection once for all dependencies on this resource
- const connectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: winrmConfig.winrmPort
- });
-
- if (!connectionDetails) {
- const msg = "Unable to establish gateway connection for dependency sync";
- logger.warn(`[DependencySync] ${msg} [resourceId=${resourceId}]`);
- await failAllDeps(deps, msg);
- return;
- }
-
- // Process dependencies sequentially for this resource (same WinRM connection target)
- // eslint-disable-next-line no-restricted-syntax
- for (const dep of deps) {
- try {
- // eslint-disable-next-line no-await-in-loop
- await ctx.pamAccountDependenciesDAL.updateById(dep.id, { syncStatus: PamDependencySyncStatus.Pending });
-
- const script = buildDependencySyncScript(dep, newCredentials.username, newCredentials.password);
-
- // eslint-disable-next-line no-await-in-loop
- await withGatewayV2Proxy(
- async (proxyPort) => {
- await runPowershell(
- script,
- "localhost",
- winrmUsername,
- rotationCredentials.password,
- proxyPort,
- winrmConfig.useWinrmHttps,
- winrmConfig.winrmRejectUnauthorized,
- winrmConfig.winrmCaCert,
- winrmConfig.winrmTlsServerName
- );
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: connectionDetails.relayHost,
- gateway: connectionDetails.gateway,
- relay: connectionDetails.relay
- }
- );
-
- // eslint-disable-next-line no-await-in-loop
- await ctx.pamAccountDependenciesDAL.updateById(dep.id, {
- syncStatus: PamDependencySyncStatus.Success,
- lastSyncedAt: new Date(),
- encryptedLastSyncMessage: null
- });
-
- succeededCount += 1;
- logger.info(`[DependencySync] Synced ${dep.dependencyType} '${dep.name}' on resource ${resourceId}`);
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- logger.error(
- error,
- `[DependencySync] Failed to sync ${dep.dependencyType} '${dep.name}' on resource ${resourceId}`
- );
-
- let encryptedLastSyncMessage: Buffer | null = null;
- try {
- // eslint-disable-next-line no-await-in-loop
- const enc = await getEncryptor();
- const { cipherTextBlob } = enc({
- plainText: Buffer.from(errorMessage)
- });
- encryptedLastSyncMessage = cipherTextBlob;
- } catch (err) {
- logger.error(err, `[DependencySync] Failed to encrypt error message for [depId=${dep.id}]`);
- }
-
- // eslint-disable-next-line no-await-in-loop
- await ctx.pamAccountDependenciesDAL.updateById(dep.id, {
- syncStatus: PamDependencySyncStatus.Failed,
- encryptedLastSyncMessage
- });
-
- failedCount += 1;
- }
- }
- })
- )
- );
-
- return {
- total: enabledDeps.length,
- succeeded: succeededCount,
- failed: failedCount
- };
-};
diff --git a/backend/src/ee/services/pam-resource/shared/dns-over-dc.ts b/backend/src/ee/services/pam-resource/shared/dns-over-dc.ts
deleted file mode 100644
index 8e10e35b9a..0000000000
--- a/backend/src/ee/services/pam-resource/shared/dns-over-dc.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import net from "node:net";
-
-import * as dnsPacket from "dns-packet";
-
-// Resolve a hostname to an IP via DNS-over-TCP through a local proxy port
-export const resolveDnsTcp = (hostname: string, proxyPort: number): Promise<string | null> => {
- return new Promise((resolve) => {
- const query = dnsPacket.streamEncode({
- type: "query",
- flags: dnsPacket.RECURSION_DESIRED,
- questions: [{ type: "A", name: hostname }]
- });
-
- const socket = net.connect({ host: "127.0.0.1", port: proxyPort }, () => {
- socket.write(query);
- });
-
- const MAX_DNS_TCP_SIZE = 2 + 65535;
- let responseData = Buffer.alloc(0);
-
- socket.on("data", (chunk: Buffer) => {
- responseData = Buffer.concat([responseData, chunk]);
-
- if (responseData.length > MAX_DNS_TCP_SIZE) {
- socket.destroy();
- resolve(null);
- return;
- }
-
- if (responseData.length >= 2) {
- const msgLen = responseData.readUInt16BE(0);
- if (responseData.length >= 2 + msgLen) {
- try {
- const response = dnsPacket.streamDecode(responseData);
- const aRecord = response.answers?.find((a) => a.type === "A");
- socket.destroy();
- resolve(aRecord && "data" in aRecord ? (aRecord.data as string) : null);
- } catch {
- socket.destroy();
- resolve(null);
- }
- }
- }
- });
-
- socket.on("error", () => {
- resolve(null);
- });
-
- socket.setTimeout(5000, () => {
- socket.destroy();
- resolve(null);
- });
- });
-};
diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts
deleted file mode 100644
index 8fd9737003..0000000000
--- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts
+++ /dev/null
@@ -1,468 +0,0 @@
-import knex from "knex";
-import mysql, { Connection } from "mysql2/promise";
-import tls, { PeerCertificate } from "tls";
-
-import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { alphaNumericNanoId } from "@app/lib/nanoid";
-
-import { PamResource } from "../../pam-resource-enums";
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPamResourceInternalMetadata
-} from "../../pam-resource-types";
-import { TSqlAccountCredentials, TSqlResourceConnectionDetails } from "./sql-resource-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-const TEST_CONNECTION_USERNAME = "infisical-gateway-connection-test";
-const TEST_CONNECTION_PASSWORD = "infisical-gateway-connection-test-password";
-const SIMPLE_QUERY = "select 1";
-
-export interface SqlResourceConnection {
- /**
- * Check and see if the connection is good or not.
- *
- * @param connectOnly when true, if we only want to know that making the connection is possible or not,
- * we don't care about authentication failures
- * @returns Promise to be resolved when the connection is good, otherwise an error will be errbacked
- */
- validate: (connectOnly: boolean) => Promise<void>;
-
- /**
- * Rotate password and return the new credentials.
- *
- * @param currentCredentials the current credentials to rotate
- *
- * @returns Promise to be resolved with the new credentials
- */
- rotateCredentials: (
- currentCredentials: TSqlAccountCredentials,
- newPassword: string
- ) => Promise<TSqlAccountCredentials>;
-
- /**
- * Close the connection.
- *
- * @returns Promise for closing the connection
- */
- close: () => Promise<void>;
-}
-
-const makeSqlConnection = (
- proxyPort: number,
- config: {
- connectionDetails: TSqlResourceConnectionDetails;
- resourceType: PamResource;
- username?: string;
- password?: string;
- authMethod?: string; // MSSQL-only: "ntlm" triggers Windows auth via Tedious
- domain?: string; // MSSQL-only: AD domain for NTLM authentication
- }
-): SqlResourceConnection => {
- const { connectionDetails, resourceType, username, password } = config;
- const { host, sslEnabled, sslRejectUnauthorized, sslCertificate } = connectionDetails;
- const actualUsername = username ?? TEST_CONNECTION_USERNAME; // Use provided username or fallback
- const actualPassword = password ?? TEST_CONNECTION_PASSWORD; // Use provided password or fallback
- switch (config.resourceType) {
- case PamResource.Postgres: {
- const client = knex({
- client: "pg",
- connection: {
- host: "localhost",
- port: proxyPort,
- user: actualUsername,
- password: actualPassword,
- database: connectionDetails.database,
- connectionTimeoutMillis: EXTERNAL_REQUEST_TIMEOUT,
- ssl: sslEnabled
- ? {
- rejectUnauthorized: sslRejectUnauthorized,
- ca: sslCertificate,
- servername: host,
- // When using proxy, we need to bypass hostname validation since we connect to localhost
- // but validate the certificate against the actual hostname
- checkServerIdentity: (hostname: string, cert: PeerCertificate) => {
- return tls.checkServerIdentity(host, cert);
- }
- }
- : false
- }
- });
- return {
- validate: async (connectOnly) => {
- try {
- await client.raw(SIMPLE_QUERY);
- } catch (error) {
- if (error instanceof Error) {
- // Hacky way to know if we successfully hit the database.
- // TODO: potentially two approaches to solve the problem.
- // 1. change the work flow, add account first then resource
- // 2. modify relay to add a new endpoint for returning if the target host is healthy or not
- // (like being able to do an auth handshake regardless pass or not)
- if (
- connectOnly &&
- (error.message === `password authentication failed for user "${TEST_CONNECTION_USERNAME}"` ||
- error.message === `role "${TEST_CONNECTION_USERNAME}" does not exist`)
- ) {
- return;
- }
- }
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- },
- rotateCredentials: async (currentCredentials, newPassword) => {
- // Note: The generated random password is not really going to make SQL Injection possible.
- // The reason we are not using parameters binding is that the "ALTER USER" syntax is DDL,
- // parameters binding is not supported. But just in case if the this code got copied
- // around and repurposed, let's just do some naive escaping regardless
- await client.raw(`ALTER USER :username: WITH PASSWORD '${newPassword.replace(/'/g, "''")}'`, {
- username: currentCredentials.username
- });
- return { username: currentCredentials.username, password: newPassword };
- },
- close: () => client.destroy()
- };
- }
- case PamResource.MySQL: {
- return {
- validate: async (connectOnly) => {
- let client: Connection | null = null;
- try {
- // Notice: the reason we are not using Knex for mysql2 is because we don't need any fancy feature from Knex.
- // mysql2 doesn't provide custom ssl verification function pass in.
- // ref: https://github.com/sidorares/node-mysql2/blob/2543272a2ada8d8a07f74582549d7dd3fe948e2d/lib/base/connection.js#L358-L362
- // and then even I tried to workaround it with Knex's pool afterCreate hook, but then encounter a bug:
- // ref: https://github.com/knex/knex/issues/5352
- // It appears that using Knex causing more troubles than not, we are just checking the connections,
- // so it's much easier to create raw connection with the driver lib directly
- client = await mysql.createConnection({
- host: "localhost",
- port: proxyPort,
- user: actualUsername, // Use provided username or fallback
- password: actualPassword, // Use provided password or fallback
- database: connectionDetails.database,
- ssl: sslEnabled
- ? {
- rejectUnauthorized: sslRejectUnauthorized,
- ca: sslCertificate
- }
- : undefined
- });
- await client.query(SIMPLE_QUERY);
- } catch (error) {
- if (connectOnly) {
- // Hacky way to know if we successfully hit the database.
- if (
- error instanceof Error &&
- error.message.startsWith(`Access denied for user '${TEST_CONNECTION_USERNAME}'@`)
- ) {
- return;
- }
- }
- // TODO: handle other errors, and throw standardlized errors providing user-friendly msg
- throw error;
- } finally {
- await client?.end();
- }
- },
- rotateCredentials: async () => {
- // TODO: the pwd rotation for MySQL is not supported yet
- throw new BadRequestError({
- message: "Unsupported operation"
- });
- },
- close: async () => {}
- };
- }
- case PamResource.MsSQL: {
- // For MSSQL through a gateway proxy:
- // - TCP connects to localhost:proxyPort, gateway forwards to real server
- // - TLS certificate is issued for the real hostname, not localhost
- // - The tedious driver doesn't support custom checkServerIdentity
- // - We must use serverName option to tell tedious to validate against the real host
- const mssqlOptions = sslEnabled
- ? {
- encrypt: true,
- trustServerCertificate: !sslRejectUnauthorized,
- cryptoCredentialsDetails: sslCertificate ? { ca: sslCertificate } : {},
- serverName: host
- }
- : { encrypt: false };
-
- const isNtlm = config.authMethod === "ntlm";
-
- if (isNtlm && !config.domain) {
- throw new BadRequestError({ message: "Domain is required for NTLM authentication" });
- }
-
- const client = knex({
- client: "mssql",
- connection: {
- server: "localhost",
- port: proxyPort,
- database: connectionDetails.database,
- requestTimeout: EXTERNAL_REQUEST_TIMEOUT,
- // Knex MSSQL dialect maps these flat fields into Tedious's authentication object
- ...(isNtlm
- ? {
- type: "ntlm",
- userName: actualUsername,
- password: actualPassword,
- domain: config.domain
- }
- : {
- user: actualUsername,
- password: actualPassword
- }),
- // ref: https://github.com/knex/knex/blob/b6507a7129d2b9fafebf5f831494431e64c6a8a0/lib/dialects/mssql/index.js#L66
- options: mssqlOptions
- }
- });
- return {
- validate: async (connectOnly) => {
- try {
- await client.raw(SIMPLE_QUERY);
- } catch (error) {
- if (error instanceof Error) {
- // Check for authentication failure - MSSQL returns error code 18456 for login failures
- if (
- connectOnly &&
- (error.message.includes("Login failed for user") || error.message.includes("ELOGIN"))
- ) {
- return;
- }
- }
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- },
- rotateCredentials: async () => {
- // Password rotation for MSSQL is not supported yet
- throw new BadRequestError({
- message: "Unsupported operation"
- });
- },
- close: () => client.destroy()
- };
- }
- default:
- throw new BadRequestError({
- message: `Unhandled SQL Resource Connection Config: ${resourceType as PamResource}`
- });
- }
-};
-
-export const executeWithGateway = async <T>(
- config: {
- connectionDetails: TSqlResourceConnectionDetails;
- resourceType: PamResource;
- gatewayId: string;
- username?: string;
- password?: string;
- authMethod?: string; // MSSQL-only: "ntlm" triggers Windows auth via Tedious
- domain?: string; // MSSQL-only: AD domain for NTLM authentication
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (connection: SqlResourceConnection) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.host,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const connection = makeSqlConnection(proxyPort, config);
- try {
- return await operation(connection);
- } finally {
- await connection.close();
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const sqlResourceFactory: TPamResourceFactory<
- TSqlResourceConnectionDetails,
- TSqlAccountCredentials,
- TPamResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- try {
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (client) => {
- await client.validate(true);
- });
- return connectionDetails;
- } catch (error) {
- if (error instanceof BadRequestError && error.message === "Connection terminated unexpectedly") {
- throw new BadRequestError({
- message: "Connection terminated unexpectedly. Verify that host and port are correct"
- });
- }
-
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TSqlAccountCredentials> = async (
- credentials
- ) => {
- try {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- if ("authMethod" in credentials && credentials.authMethod === "kerberos") {
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (client) => {
- await client.validate(true);
- });
- return credentials;
- }
-
- await executeWithGateway(
- {
- connectionDetails,
- gatewayId,
- resourceType,
- username: credentials.username,
- password: credentials.password,
- authMethod: "authMethod" in credentials ? credentials.authMethod : undefined,
- domain: "domain" in credentials ? credentials.domain : undefined
- },
- gatewayV2Service,
- async (client) => {
- await client.validate(false);
- }
- );
- return credentials;
- } catch (error) {
- // TODO: extract these logic into each SQL connection
- if (error instanceof BadRequestError) {
- if (
- error.message === `password authentication failed for user "${credentials.username}"` ||
- error.message === `role "${credentials.username}" does not exist`
- ) {
- throw new BadRequestError({
- message: "Account credentials invalid: Username or password incorrect"
- });
- }
-
- if (error.message === "Connection terminated unexpectedly") {
- throw new BadRequestError({
- message: "Connection terminated unexpectedly. Verify that host and port are correct"
- });
- }
- }
-
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TSqlAccountCredentials> = async (
- rotationAccountCredentials,
- currentCredentials
- ) => {
- const newPassword = alphaNumericNanoId(32);
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- try {
- return await executeWithGateway(
- {
- connectionDetails,
- gatewayId,
- resourceType,
- username: rotationAccountCredentials.username,
- password: rotationAccountCredentials.password
- },
- gatewayV2Service,
- (client) => client.rotateCredentials(currentCredentials, newPassword)
- );
- } catch (error) {
- if (error instanceof BadRequestError) {
- if (
- error.message === `password authentication failed for user "${rotationAccountCredentials.username}"` ||
- error.message === `role "${rotationAccountCredentials.username}" does not exist`
- ) {
- throw new BadRequestError({
- message: "Management credentials invalid: Username or password incorrect"
- });
- }
-
- if (error.message.includes("permission denied")) {
- throw new BadRequestError({
- message: `Management credentials lack permission to rotate password for user "${currentCredentials.username}"`
- });
- }
-
- if (error.message === "Connection terminated unexpectedly") {
- throw new BadRequestError({
- message: "Connection terminated unexpectedly. Verify that host and port are correct"
- });
- }
- }
-
- const sanitizedErrorMessage = ((error as Error).message || String(error)).replaceAll(newPassword, "REDACTED");
-
- throw new BadRequestError({
- message: `Unable to rotate account credentials for ${resourceType}: ${sanitizedErrorMessage}`
- });
- }
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TSqlAccountCredentials,
- currentCredentials: TSqlAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-schemas.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-schemas.ts
deleted file mode 100644
index 96b6a6a24d..0000000000
--- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-schemas.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { z } from "zod";
-
-// Resources
-export const BaseSqlResourceConnectionDetailsSchema = 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((value) => value || undefined)
- .optional()
-});
-
-// Accounts
-export const BaseSqlAccountCredentialsSchema = z.object({
- username: z.string().trim().min(1).max(63),
- password: z.string().trim().min(1).max(256)
-});
diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-types.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-types.ts
deleted file mode 100644
index 4506db5941..0000000000
--- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-types.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/* eslint-disable @typescript-eslint/no-duplicate-type-constituents */
-import { TMsSQLAccountCredentials, TMsSQLResourceConnectionDetails } from "../../mssql/mssql-resource-types";
-import { TMySQLAccountCredentials, TMySQLResourceConnectionDetails } from "../../mysql/mysql-resource-types";
-import {
- TPostgresAccountCredentials,
- TPostgresResourceConnectionDetails
-} from "../../postgres/postgres-resource-types";
-
-export type TSqlResourceConnectionDetails =
- | TPostgresResourceConnectionDetails
- | TMySQLResourceConnectionDetails
- | TMsSQLResourceConnectionDetails;
-
-export type TSqlAccountCredentials = TPostgresAccountCredentials | TMySQLAccountCredentials | TMsSQLAccountCredentials;
diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts
deleted file mode 100644
index 9b6ed1f157..0000000000
--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export enum SSHAuthMethod {
- Password = "password",
- PublicKey = "public-key",
- Certificate = "certificate"
-}
diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts
deleted file mode 100644
index 8c9efa4da5..0000000000
--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-import { Client } from "ssh2";
-
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { PamResource } from "../pam-resource-enums";
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials
-} from "../pam-resource-types";
-import { SSHAuthMethod } from "./ssh-resource-enums";
-import {
- TSSHAccountCredentials,
- TSSHResourceConnectionDetails,
- TSSHResourceInternalMetadata
-} from "./ssh-resource-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-export const executeWithGateway = async <T>(
- config: {
- connectionDetails: TSSHResourceConnectionDetails;
- resourceType: PamResource;
- gatewayId: string;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (proxyPort: number) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.host,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- return operation(proxyPort);
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const sshResourceFactory: TPamResourceFactory<
- TSSHResourceConnectionDetails,
- TSSHAccountCredentials,
- TSSHResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service, _projectId, resourceInternalMetadata) => {
- const validateConnection = async () => {
- try {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const client = new Client();
- let handshakeComplete = false;
-
- client.on("error", (err) => {
- logger.info(
- { error: err.message, handshakeComplete },
- "[SSH Resource Factory] SSH client error event received"
- );
- // If we got an authentication error, it means we successfully reached the SSH server
- // and completed the SSH handshake - that's good enough for connection validation
- if (handshakeComplete || err.message.includes("authentication") || err.message.includes("publickey")) {
- logger.info(
- { handshakeComplete, errorMessage: err.message },
- "[SSH Resource Factory] SSH connection validation succeeded (auth error after handshake)"
- );
- client.end();
- resolve();
- } else {
- logger.error(
- { error: err.message, handshakeComplete },
- "[SSH Resource Factory] SSH connection validation failed"
- );
- reject(err);
- }
- });
-
- client.on("handshake", () => {
- // SSH handshake completed - the server is reachable and responding
- logger.info("[SSH Resource Factory] SSH handshake event received - setting handshakeComplete to true");
- handshakeComplete = true;
- client.end();
- resolve();
- });
-
- client.on("timeout", () => {
- logger.error("[SSH Resource Factory] SSH connection timeout");
- reject(new Error("Connection timeout"));
- });
-
- // Attempt connection with a dummy username (we don't care about auth success)
- // The goal is just to verify SSH server is reachable and responding
- client.connect({
- host: "localhost",
- port: proxyPort,
- username: "infisical-connection-test",
- password: "infisical-connection-test-password",
- readyTimeout: EXTERNAL_REQUEST_TIMEOUT,
- tryKeyboard: false,
- // We want to fail fast on auth, we're just testing reachability
- authHandler: () => {
- // If authHandler is called, SSH handshake succeeded
- handshakeComplete = true;
- return false; // Don't continue with auth
- }
- });
- });
- });
- return connectionDetails;
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TSSHAccountCredentials> = async (
- credentials
- ) => {
- try {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const client = new Client();
-
- client.on("ready", () => {
- logger.info(
- { username: credentials.username, authMethod: credentials.authMethod },
- "[SSH Resource Factory] SSH authentication successful"
- );
- client.end();
- resolve();
- });
-
- client.on("error", (err) => {
- logger.error(
- { error: err.message, username: credentials.username, authMethod: credentials.authMethod },
- "[SSH Resource Factory] SSH authentication failed"
- );
- reject(err);
- });
-
- client.on("timeout", () => {
- logger.error(
- { username: credentials.username, authMethod: credentials.authMethod },
- "[SSH Resource Factory] SSH authentication timeout"
- );
- reject(new Error("Connection timeout"));
- });
-
- // Build connection config based on auth method
- const baseConfig = {
- host: "localhost",
- port: proxyPort,
- username: credentials.username,
- readyTimeout: EXTERNAL_REQUEST_TIMEOUT
- };
-
- switch (credentials.authMethod) {
- case SSHAuthMethod.Password:
- client.connect({
- ...baseConfig,
- password: credentials.password,
- tryKeyboard: false
- });
- break;
- case SSHAuthMethod.PublicKey:
- client.connect({
- ...baseConfig,
- privateKey: credentials.privateKey,
- tryKeyboard: false
- });
- break;
- case SSHAuthMethod.Certificate:
- // We cant fully validate the connection since ssh2 doesn't support cert auth
- if (!resourceInternalMetadata) {
- reject(
- new BadRequestError({
- message:
- "SSH CA is not configured for this resource. Please set up the CA first using the SSH CA setup script."
- })
- );
- return;
- }
-
- logger.info(
- { username: credentials.username },
- "[SSH Resource Factory] Certificate auth - CA is configured, skipping connection validation"
- );
- resolve();
- break;
- default:
- reject(new Error(`Unsupported SSH auth method: ${(credentials as TSSHAccountCredentials).authMethod}`));
- }
- });
- });
- return credentials;
- } catch (error) {
- if (error instanceof Error) {
- // Check for common authentication failure messages
- if (
- error.message.includes("authentication") ||
- error.message.includes("All configured authentication methods failed") ||
- error.message.includes("publickey")
- ) {
- throw new BadRequestError({
- message: "Account credentials invalid."
- });
- }
-
- if (error.message === "Connection timeout") {
- throw new BadRequestError({
- message: "Connection timeout. Verify that the SSH server is reachable"
- });
- }
- }
-
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
- }
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TSSHAccountCredentials> = async (
- rotationAccountCredentials
- ) => {
- return rotationAccountCredentials;
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TSSHAccountCredentials,
- currentCredentials: TSSHAccountCredentials
- ) => {
- if (updatedAccountCredentials.authMethod !== currentCredentials.authMethod) {
- return updatedAccountCredentials;
- }
-
- if (
- updatedAccountCredentials.authMethod === SSHAuthMethod.Password &&
- currentCredentials.authMethod === SSHAuthMethod.Password
- ) {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
- }
-
- if (
- updatedAccountCredentials.authMethod === SSHAuthMethod.PublicKey &&
- currentCredentials.authMethod === SSHAuthMethod.PublicKey
- ) {
- if (updatedAccountCredentials.privateKey === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- privateKey: currentCredentials.privateKey
- };
- }
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-fns.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-fns.ts
deleted file mode 100644
index 761ec078a9..0000000000
--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { SSHResourceListItemSchema } from "./ssh-resource-schemas";
-
-export const getSshResourceListItem = () => {
- return {
- name: SSHResourceListItemSchema.shape.name.value,
- resource: SSHResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts
deleted file mode 100644
index 61866cfbb6..0000000000
--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import { SSHAuthMethod } from "./ssh-resource-enums";
-
-export const BaseSSHResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.SSH) });
-
-export const SSHResourceListItemSchema = z.object({
- name: z.literal("SSH"),
- resource: z.literal(PamResource.SSH)
-});
-
-export const SSHResourceConnectionDetailsSchema = z.object({
- host: z.string().trim().max(255),
- port: z.number()
-});
-
-export const SSHPasswordCredentialsSchema = z.object({
- authMethod: z.literal(SSHAuthMethod.Password),
- username: z.string().trim().max(255),
- password: z.string().trim().max(255)
-});
-
-export const SSHPublicKeyCredentialsSchema = z.object({
- authMethod: z.literal(SSHAuthMethod.PublicKey),
- username: z.string().trim().max(255),
- privateKey: z.string().trim().max(5000)
-});
-
-export const SSHCertificateCredentialsSchema = z.object({
- authMethod: z.literal(SSHAuthMethod.Certificate),
- username: z.string().trim().max(255)
-});
-
-export const SSHAccountCredentialsSchema = z.discriminatedUnion("authMethod", [
- SSHPasswordCredentialsSchema,
- SSHPublicKeyCredentialsSchema,
- SSHCertificateCredentialsSchema
-]);
-
-// Schema for session credentials - includes certificate with keys
-export const SSHSessionAccountCredentialsSchema = z.discriminatedUnion("authMethod", [
- SSHPasswordCredentialsSchema,
- SSHPublicKeyCredentialsSchema,
- SSHCertificateCredentialsSchema.extend({
- privateKey: z.string().trim().max(5000),
- certificate: z.string().trim().max(5000)
- })
-]);
-
-export const SSHResourceSchema = BaseSSHResourceSchema.extend({
- connectionDetails: SSHResourceConnectionDetailsSchema,
- rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedSSHResourceSchema = BaseSSHResourceSchema.extend({
- connectionDetails: SSHResourceConnectionDetailsSchema,
- rotationAccountCredentials: z
- .discriminatedUnion("authMethod", [
- z.object({
- authMethod: z.literal(SSHAuthMethod.Password),
- username: z.string()
- }),
- z.object({
- authMethod: z.literal(SSHAuthMethod.PublicKey),
- username: z.string()
- }),
- z.object({
- authMethod: z.literal(SSHAuthMethod.Certificate),
- username: z.string()
- })
- ])
- .nullable()
- .optional()
-});
-
-export const CreateSSHResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: SSHResourceConnectionDetailsSchema,
- rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional()
-});
-
-export const UpdateSSHResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: SSHResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional()
-});
-
-// Resource Metadata
-export const SSHResourceInternalMetadataSchema = z.object({
- caPrivateKey: z.string(),
- caPublicKey: z.string(),
- caKeyAlgorithm: z.string()
-});
-
-export const SanitizedSSHResourceInternalMetadataSchema = SSHResourceInternalMetadataSchema.pick({
- caPublicKey: true,
- caKeyAlgorithm: true
-});
-
-// Accounts
-export const SSHAccountSchema = BasePamAccountSchema.extend({
- credentials: SSHAccountCredentialsSchema
-});
-
-export const CreateSSHAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: SSHAccountCredentialsSchema
-});
-
-export const UpdateSSHAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: SSHAccountCredentialsSchema.optional()
-});
-
-export const SanitizedSSHAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.SSH),
- credentials: z.discriminatedUnion("authMethod", [
- z.object({
- authMethod: z.literal(SSHAuthMethod.Password),
- username: z.string()
- }),
- z.object({
- authMethod: z.literal(SSHAuthMethod.PublicKey),
- username: z.string()
- }),
- z.object({
- authMethod: z.literal(SSHAuthMethod.Certificate),
- username: z.string()
- })
- ])
-});
-
-// Sessions
-export const SSHSessionCredentialsSchema = SSHResourceConnectionDetailsSchema.and(SSHSessionAccountCredentialsSchema);
diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts
deleted file mode 100644
index 8498a0aab0..0000000000
--- a/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { z } from "zod";
-
-import {
- SSHAccountCredentialsSchema,
- SSHAccountSchema,
- SSHResourceConnectionDetailsSchema,
- SSHResourceInternalMetadataSchema,
- SSHResourceSchema
-} from "./ssh-resource-schemas";
-
-// Resources
-export type TSSHResource = z.infer<typeof SSHResourceSchema>;
-export type TSSHResourceConnectionDetails = z.infer<typeof SSHResourceConnectionDetailsSchema>;
-export type TSSHResourceInternalMetadata = z.infer<typeof SSHResourceInternalMetadataSchema>;
-
-// Accounts
-export type TSSHAccount = z.infer<typeof SSHAccountSchema>;
-export type TSSHAccountCredentials = z.infer<typeof SSHAccountCredentialsSchema>;
diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-enums.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-enums.ts
deleted file mode 100644
index d7999084c7..0000000000
--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-enums.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export enum WindowsProtocol {
- RDP = "rdp"
-}
-
-export enum WindowsAccountType {
- User = "user",
- Service = "service"
-}
diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts
deleted file mode 100644
index 4622860fda..0000000000
--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-factory.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import net from "node:net";
-
-import { runPowershell } from "winrm-client";
-
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-
-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
-import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
-import { generatePassword } from "../../secret-rotation-v2/shared/utils";
-import { PamResource } from "../pam-resource-enums";
-import {
- TPamResourceFactory,
- TPamResourceFactoryRotateAccountCredentials,
- TPamResourceFactoryValidateAccountCredentials,
- TPostRotateContext
-} from "../pam-resource-types";
-import { escapePowershellSingleQuote, syncDependenciesAfterRotation } from "../shared/dependency-sync-fns";
-import {
- TWindowsAccountCredentials,
- TWindowsResourceConnectionDetails,
- TWindowsResourceInternalMetadata
-} from "./windows-server-resource-types";
-
-const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
-
-const executeWithGateway = async <T>(
- config: {
- connectionDetails: TWindowsResourceConnectionDetails;
- resourceType: PamResource;
- gatewayId: string;
- targetPortOverride?: number;
- },
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
- operation: (proxyPort: number) => Promise<T>
-): Promise<T> => {
- const { connectionDetails, gatewayId, targetPortOverride } = config;
- const [targetHost] = await verifyHostInputValidity({
- host: connectionDetails.hostname,
- isGateway: true,
- isDynamicSecret: false
- });
- const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost,
- targetPort: targetPortOverride ?? connectionDetails.port
- });
-
- if (!platformConnectionDetails) {
- throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
- }
-
- return withGatewayV2Proxy(
- async (proxyPort) => {
- return operation(proxyPort);
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- relayHost: platformConnectionDetails.relayHost,
- gateway: platformConnectionDetails.gateway,
- relay: platformConnectionDetails.relay
- }
- );
-};
-
-export const windowsResourceFactory: TPamResourceFactory<
- TWindowsResourceConnectionDetails,
- TWindowsAccountCredentials,
- TWindowsResourceInternalMetadata
-> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
- const validateConnection = async () => {
- if (!gatewayId) {
- throw new BadRequestError({ message: "Gateway ID is required" });
- }
-
- try {
- await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (proxyPort) => {
- return new Promise<void>((resolve, reject) => {
- const socket = new net.Socket();
- let settled = false;
-
- const finish = (error?: Error) => {
- if (settled) return;
- settled = true;
- socket.destroy();
- if (error) reject(error);
- else resolve();
- };
-
- socket.setTimeout(EXTERNAL_REQUEST_TIMEOUT);
- socket.on("timeout", () => finish(new Error("Connection timeout")));
- socket.on("error", (err) => finish(err));
- socket.on("close", () => finish(new Error("Connection closed before RDP handshake completed")));
-
- socket.on("connect", () => {
- // Send a minimal RDP X.224 Connection Request to verify the server speaks RDP.
- // TPKT header (4 bytes) + X.224 CR (7 bytes) + RDP Negotiation Request (8 bytes) = 19 bytes
- // prettier-ignore
- socket.write(Buffer.from([
- 0x03, 0x00, 0x00, 0x13, // TPKT: version 3, length 19
- 0x0e, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, // X.224 Connection Request
- 0x01, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00 // RDP Neg Request: TLS
- ]));
- });
-
- socket.on("data", (data: Buffer) => {
- // An RDP server responds with X.224 Connection Confirm:
- // byte 0 = 0x03 (TPKT version), byte 5 = 0xD0 (CC code)
- if (data.length >= 7 && data[0] === 0x03 && data[5] === 0xd0) {
- logger.info("[Windows Server Resource Factory] RDP handshake successful");
- finish();
- } else {
- finish(new Error("Server is not an RDP server"));
- }
- });
-
- socket.connect(proxyPort, "localhost");
- });
- });
- } catch (error) {
- throw new BadRequestError({
- message: `Unable to validate connection to windows: ${(error as Error).message || String(error)}`
- });
- }
-
- return connectionDetails;
- };
-
- const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<TWindowsAccountCredentials> = async (
- credentials
- ) => {
- // Temporarily allow all credentials. Later on we'll implement a check with RDP
- return credentials;
- };
-
- const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<TWindowsAccountCredentials> = async (
- rotationAccountCredentials,
- currentCredentials
- ) => {
- if (!gatewayId) throw new BadRequestError({ message: "Gateway ID is required for Windows credential rotation" });
-
- const newPassword = generatePassword();
-
- const escapedNewPassword = escapePowershellSingleQuote(newPassword);
- const escapedUsername = escapePowershellSingleQuote(currentCredentials.username);
-
- const { winrmPort } = connectionDetails;
- const { useWinrmHttps } = connectionDetails;
-
- await executeWithGateway(
- { connectionDetails, gatewayId, resourceType, targetPortOverride: winrmPort },
- gatewayV2Service,
- async (proxyPort) => {
- const script = [
- `$securePassword = ConvertTo-SecureString '${escapedNewPassword}' -AsPlainText -Force`,
- `Set-LocalUser -Name '${escapedUsername}' -Password $securePassword`
- ].join("; ");
-
- await runPowershell(
- script,
- "localhost",
- rotationAccountCredentials.username,
- rotationAccountCredentials.password,
- proxyPort,
- useWinrmHttps,
- useWinrmHttps ? connectionDetails.winrmRejectUnauthorized : undefined,
- connectionDetails.winrmCaCert,
- connectionDetails.winrmTlsServerName
- );
-
- logger.info(
- `[Windows Rotation] Password rotated for local account [username=${currentCredentials.username}] on [hostname=${connectionDetails.hostname}]`
- );
- }
- );
-
- return { username: currentCredentials.username, password: newPassword };
- };
-
- const postRotate = async (
- accountId: string,
- newCredentials: TWindowsAccountCredentials,
- projectId: string,
- ctx: TPostRotateContext,
- rotationAccountCredentials: TWindowsAccountCredentials
- ) => {
- if (!gatewayId) return;
-
- await syncDependenciesAfterRotation({
- accountId,
- newCredentials,
- projectId,
- ctx,
- gatewayV2Service,
- rotationCredentials: rotationAccountCredentials,
- gatewayId
- });
- };
-
- const handleOverwritePreventionForCensoredValues = async (
- updatedAccountCredentials: TWindowsAccountCredentials,
- currentCredentials: TWindowsAccountCredentials
- ) => {
- if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") {
- return {
- ...updatedAccountCredentials,
- password: currentCredentials.password
- };
- }
-
- return updatedAccountCredentials;
- };
-
- return {
- validateConnection,
- validateAccountCredentials,
- rotateAccountCredentials,
- postRotate,
- handleOverwritePreventionForCensoredValues
- };
-};
diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-fns.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-fns.ts
deleted file mode 100644
index 9394ec18f5..0000000000
--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-fns.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { WindowsResourceListItemSchema } from "./windows-server-resource-schemas";
-
-export const getWindowsResourceListItem = () => {
- return {
- name: WindowsResourceListItemSchema.shape.name.value,
- resource: WindowsResourceListItemSchema.shape.resource.value
- };
-};
diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-schemas.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-schemas.ts
deleted file mode 100644
index f3dd310733..0000000000
--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-schemas.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource-enums";
-import {
- BaseCreateGatewayPamResourceSchema,
- BaseCreatePamAccountSchema,
- BasePamAccountSchema,
- BasePamAccountSchemaWithResource,
- BasePamResourceSchema,
- BaseUpdateGatewayPamResourceSchema,
- BaseUpdatePamAccountSchema
-} from "../pam-resource-schemas";
-import { WindowsAccountType, WindowsProtocol } from "./windows-server-resource-enums";
-
-// Resources
-const BaseWindowsResourceSchema = BasePamResourceSchema.extend({
- resourceType: z.literal(PamResource.Windows)
-});
-
-export const WindowsResourceListItemSchema = z.object({
- name: z.literal("Windows Server"),
- resource: z.literal(PamResource.Windows)
-});
-
-export const WindowsResourceConnectionDetailsSchema = z.object({
- protocol: z.literal(WindowsProtocol.RDP),
- hostname: z.string().trim().min(1).max(255),
- port: z.coerce.number().int().min(1).max(65535),
-
- // WinRM config — used for rotation only, configured in the rotation policy modal
- winrmPort: z.coerce.number().int().min(1).max(65535),
- useWinrmHttps: z.boolean(),
- winrmRejectUnauthorized: z.boolean(),
- winrmCaCert: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional(),
- winrmTlsServerName: z
- .string()
- .trim()
- .transform((val) => val || undefined)
- .optional()
-});
-
-// Credentials (username + password for RDP)
-export const WindowsAccountCredentialsSchema = z.object({
- username: z.string().trim().min(1).max(255),
- password: z.string().trim().min(1).max(255)
-});
-
-// Account metadata
-export const WindowsAccountMetadataSchema = z.object({
- accountType: z.nativeEnum(WindowsAccountType),
- lastLogon: z.string().optional(),
- passwordLastSet: z.string().optional(),
- sid: z.string().optional(),
- enabled: z.boolean().optional()
-});
-
-// Resource Metadata
-export const WindowsResourceInternalMetadataSchema = z.object({
- osVersion: z.string().optional(),
- osVersionDetail: z.string().optional()
-});
-
-export const SanitizedWindowsResourceInternalMetadataSchema = WindowsResourceInternalMetadataSchema.pick({
- osVersion: true,
- osVersionDetail: true
-});
-
-export const WindowsResourceSchema = BaseWindowsResourceSchema.extend({
- connectionDetails: WindowsResourceConnectionDetailsSchema,
- rotationAccountCredentials: WindowsAccountCredentialsSchema.nullable().optional()
-});
-
-export const SanitizedWindowsResourceSchema = BaseWindowsResourceSchema.extend({
- connectionDetails: WindowsResourceConnectionDetailsSchema,
- rotationAccountCredentials: z
- .object({
- username: z.string()
- })
- .nullable()
- .optional()
-});
-
-export const CreateWindowsResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
- connectionDetails: WindowsResourceConnectionDetailsSchema,
- rotationAccountCredentials: WindowsAccountCredentialsSchema.nullable().optional(),
- domainId: z.string().uuid().nullable().optional()
-});
-
-export const UpdateWindowsResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
- connectionDetails: WindowsResourceConnectionDetailsSchema.optional(),
- rotationAccountCredentials: WindowsAccountCredentialsSchema.nullable().optional(),
- domainId: z.string().uuid().nullable().optional()
-});
-
-// Accounts
-export const WindowsAccountSchema = BasePamAccountSchema.extend({
- credentials: WindowsAccountCredentialsSchema,
- internalMetadata: WindowsAccountMetadataSchema
-});
-
-export const CreateWindowsAccountSchema = BaseCreatePamAccountSchema.extend({
- credentials: WindowsAccountCredentialsSchema,
- internalMetadata: WindowsAccountMetadataSchema
-});
-
-export const UpdateWindowsAccountSchema = BaseUpdatePamAccountSchema.extend({
- credentials: WindowsAccountCredentialsSchema.optional(),
- internalMetadata: WindowsAccountMetadataSchema.optional()
-});
-
-export const SanitizedWindowsAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
- parentType: z.literal(PamResource.Windows),
- credentials: z.object({
- username: z.string()
- }),
- internalMetadata: WindowsAccountMetadataSchema
-});
-
-// Sessions
-// Renames `hostname` to `host` so the gateway can dispatch all resource types
-// uniformly on a `host` field. `domain` is set on AD-account sessions for NTLM.
-export const WindowsSessionCredentialsSchema = WindowsResourceConnectionDetailsSchema.omit({ hostname: true })
- .extend({ host: z.string().trim().min(1).max(255), domain: z.string().optional() })
- .and(WindowsAccountCredentialsSchema);
diff --git a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-types.ts b/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-types.ts
deleted file mode 100644
index f2b269011a..0000000000
--- a/backend/src/ee/services/pam-resource/windows-server/windows-server-resource-types.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { z } from "zod";
-
-import {
- WindowsAccountCredentialsSchema,
- WindowsAccountMetadataSchema,
- WindowsAccountSchema,
- WindowsResourceConnectionDetailsSchema,
- WindowsResourceInternalMetadataSchema,
- WindowsResourceSchema
-} from "./windows-server-resource-schemas";
-
-// Resources
-export type TWindowsResource = z.infer<typeof WindowsResourceSchema>;
-export type TWindowsResourceConnectionDetails = z.infer<typeof WindowsResourceConnectionDetailsSchema>;
-export type TWindowsResourceInternalMetadata = z.infer<typeof WindowsResourceInternalMetadataSchema>;
-
-// Accounts
-export type TWindowsAccount = z.infer<typeof WindowsAccountSchema>;
-export type TWindowsAccountCredentials = z.infer<typeof WindowsAccountCredentialsSchema>;
-export type TWindowsAccountMetadata = z.infer<typeof WindowsAccountMetadataSchema>;
diff --git a/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts
deleted file mode 100644
index 023c031db8..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/aws-s3/aws-s3-provider-factory.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import {
- DeleteObjectsCommand,
- GetObjectCommand,
- HeadBucketCommand,
- ListObjectsV2Command,
- PutObjectCommand,
- S3Client
-} from "@aws-sdk/client-s3";
-import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
-
-import { CustomAWSHasher } from "@app/lib/aws/hashing";
-import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-
-import {
- PAM_RECORDING_MAX_CHUNK_BYTES,
- PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS
-} from "../pam-session-recording-storage-constants";
-import {
- buildExternalChunkObjectKey,
- normalizeKeyPrefix,
- TPamRecordingResolvedConfig,
- TPamRecordingStorageProvider
-} from "../pam-session-recording-storage-types";
-
-const buildClient = (config: TPamRecordingResolvedConfig) => {
- if (!config.region || !config.awsCredentials) {
- throw new BadRequestError({ message: "AWS S3 storage backend requires region and credentials" });
- }
- return new S3Client({
- region: config.region,
- useFipsEndpoint: crypto.isFipsModeEnabled(),
- sha256: CustomAWSHasher,
- credentials: config.awsCredentials
- });
-};
-
-export const AwsS3RecordingStorageProvider: TPamRecordingStorageProvider = () => ({
- validateConfig: async ({ config }) => {
- if (!config.bucket) {
- throw new BadRequestError({ message: "Bucket is required for AWS S3 backend" });
- }
- const client = buildClient(config);
- try {
- await client.send(new HeadBucketCommand({ Bucket: config.bucket }));
- } catch (err) {
- logger.warn({ err, bucket: config.bucket }, `S3 HeadBucket failed [bucket=${config.bucket}]`);
- throw new BadRequestError({
- message: `Unable to access bucket. Verify region, credentials, and bucket policy [bucket=${config.bucket}]`
- });
- }
-
- const testKey = `${normalizeKeyPrefix(config.keyPrefix)}.test/${crypto.nativeCrypto.randomUUID()}`;
-
- try {
- await client.send(
- new PutObjectCommand({
- Bucket: config.bucket,
- Key: testKey,
- Body: Buffer.from("infisical-pam-recording-config-test"),
- ContentType: "application/octet-stream"
- })
- );
- } catch (err) {
- logger.warn({ err, bucket: config.bucket, testKey }, `S3 round-trip PutObject failed [bucket=${config.bucket}]`);
- throw new BadRequestError({
- message: "Bucket reachable but PutObject failed. Grant s3:PutObject on the configured key prefix"
- });
- }
-
- try {
- await client.send(
- new DeleteObjectsCommand({
- Bucket: config.bucket,
- Delete: { Objects: [{ Key: testKey }], Quiet: true }
- })
- );
- } catch (err) {
- // Best-effort delete; the test object lives under .test/ and is harmless if it lingers
- logger.warn({ err, bucket: config.bucket, testKey }, `S3 test object cleanup failed [testKey=${testKey}]`);
- }
- },
-
- mintPresignedPut: async ({ config, projectId, sessionId, chunkIndex, ciphertextBytes, isKeyframe }) => {
- if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
- throw new BadRequestError({
- message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
- });
- }
- if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
-
- const client = buildClient(config);
- const objectKey = buildExternalChunkObjectKey(
- config.keyPrefix,
- projectId,
- sessionId,
- chunkIndex,
- Boolean(isKeyframe)
- );
-
- const command = new PutObjectCommand({
- Bucket: config.bucket,
- Key: objectKey,
- ContentLength: ciphertextBytes,
- ContentType: "application/octet-stream"
- });
-
- // unhoistableHeaders forces Content-Length into the signature so the gateway can't pad
- const url = await getSignedUrl(client, command, {
- expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS,
- unhoistableHeaders: new Set(["content-length"])
- });
-
- return {
- url,
- objectKey,
- method: "PUT",
- expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS
- };
- },
-
- mintPresignedGet: async ({ config, objectKey }) => {
- if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
- const client = buildClient(config);
- const command = new GetObjectCommand({ Bucket: config.bucket, Key: objectKey });
- const url = await getSignedUrl(client, command, { expiresIn: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS });
- return { url, expiresInSeconds: PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS };
- },
-
- deleteSession: async ({ config, projectId, sessionId }) => {
- if (!config.bucket) throw new BadRequestError({ message: "Bucket is required" });
- const client = buildClient(config);
-
- const prefix = `${normalizeKeyPrefix(config.keyPrefix)}${projectId}/${sessionId}/`;
-
- let continuationToken: string | undefined;
- do {
- // eslint-disable-next-line no-await-in-loop
- const listed = await client.send(
- new ListObjectsV2Command({
- Bucket: config.bucket,
- Prefix: prefix,
- ContinuationToken: continuationToken
- })
- );
- const keys = (listed.Contents ?? []).map((o) => o.Key).filter((k): k is string => Boolean(k));
- if (keys.length > 0) {
- // eslint-disable-next-line no-await-in-loop
- await client.send(
- new DeleteObjectsCommand({
- Bucket: config.bucket,
- Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true }
- })
- );
- }
- continuationToken = listed.IsTruncated ? listed.NextContinuationToken : undefined;
- } while (continuationToken);
- }
-});
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts
deleted file mode 100644
index 2f3582a796..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-constants.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-// Versioning suffix on AAD lets us swap binding scheme later without migrating ciphertext
-export const PAM_RECORDING_AAD_VERSION = "v1";
-
-// 5-minute presigned URL expiry for both PUT and GET URLs
-export const PAM_RECORDING_PRESIGNED_URL_EXPIRY_SECONDS = 300;
-
-// Hard ceiling on a single chunk's ciphertext size -- 256 MB
-// RDP can produce large keyframes; this protects backend, S3, and browser
-export const PAM_RECORDING_MAX_CHUNK_BYTES = 256 * 1024 * 1024;
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts
deleted file mode 100644
index 8c3051434b..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-enums.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export enum PamRecordingStorageBackend {
- Postgres = "postgres",
- AwsS3 = "aws-s3"
-}
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts
deleted file mode 100644
index cbc416293b..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-factory.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { AwsS3RecordingStorageProvider } from "./aws-s3/aws-s3-provider-factory";
-import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";
-import { TPamRecordingStorageProvider } from "./pam-session-recording-storage-types";
-import { PostgresRecordingStorageProvider } from "./postgres/postgres-provider-factory";
-
-export const PAM_RECORDING_STORAGE_FACTORY_MAP: Record<PamRecordingStorageBackend, TPamRecordingStorageProvider> = {
- [PamRecordingStorageBackend.Postgres]: PostgresRecordingStorageProvider,
- [PamRecordingStorageBackend.AwsS3]: AwsS3RecordingStorageProvider
-};
diff --git a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts b/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts
deleted file mode 100644
index f67986f0e7..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/pam-session-recording-storage-types.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
-
-import { PamRecordingStorageBackend } from "./pam-session-recording-storage-enums";
-
-export type TPamRecordingChunkRef = {
- storageBackend: PamRecordingStorageBackend;
- externalChunkObjectKey?: string | null;
- encryptedEventsBlob?: Buffer | null;
-};
-
-export type TPamRecordingResolvedConfig = {
- backend: PamRecordingStorageBackend;
- bucket?: string;
- region?: AWSRegion;
- keyPrefix?: string | null;
-
- // Pre-resolved AWS credentials when backend === AwsS3, otherwise undefined
- awsCredentials?: {
- accessKeyId: string;
- secretAccessKey: string;
- sessionToken?: string;
- };
-};
-
-export type TPamRecordingValidateConfig = (input: { config: TPamRecordingResolvedConfig }) => Promise<void>;
-
-export type TPamRecordingMintPresignedPut = (input: {
- config: TPamRecordingResolvedConfig;
- projectId: string;
- sessionId: string;
- chunkIndex: number;
- ciphertextBytes: number;
- isKeyframe?: boolean;
-}) => Promise<{ url: string; objectKey: string; expiresInSeconds: number; method: "PUT" }>;
-
-export type TPamRecordingMintPresignedGet = (input: {
- config: TPamRecordingResolvedConfig;
- objectKey: string;
-}) => Promise<{ url: string; expiresInSeconds: number }>;
-
-export type TPamRecordingDeleteSession = (input: {
- config: TPamRecordingResolvedConfig;
- projectId: string;
- sessionId: string;
-}) => Promise<void>;
-
-export type TPamRecordingStorageProvider = () => {
- validateConfig: TPamRecordingValidateConfig;
- mintPresignedPut: TPamRecordingMintPresignedPut;
- mintPresignedGet: TPamRecordingMintPresignedGet;
- deleteSession: TPamRecordingDeleteSession;
-};
-
-export const normalizeKeyPrefix = (keyPrefix: string | null | undefined): string =>
- keyPrefix ? `${keyPrefix.replace(/^\/+|\/+$/g, "")}/` : "";
-
-export const buildExternalChunkObjectKey = (
- keyPrefix: string | null | undefined,
- projectId: string,
- sessionId: string,
- chunkIndex: number,
- isKeyframe: boolean
-): string => {
- const prefix = normalizeKeyPrefix(keyPrefix);
- const suffix = isKeyframe ? "keyframe.png.enc" : "json.enc";
- const padded = chunkIndex.toString().padStart(6, "0");
- return `${prefix}${projectId}/${sessionId}/chunk-${padded}.${suffix}`;
-};
diff --git a/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts b/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts
deleted file mode 100644
index dbcdfe9923..0000000000
--- a/backend/src/ee/services/pam-session-recording-storage/postgres/postgres-provider-factory.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { TPamRecordingStorageProvider } from "../pam-session-recording-storage-types";
-
-// Postgres backend: chunks are stored inline in the chunks table
-// All upload/playback flows go through the backend (gateway POSTs ciphertext, browser GETs ciphertext)
-export const PostgresRecordingStorageProvider: TPamRecordingStorageProvider = () => ({
- validateConfig: async () => {
- // Postgres is always available; nothing to validate
- },
- mintPresignedPut: async () => {
- throw new Error(
- "Postgres recording backend does not support presigned PUT URLs; gateway must POST ciphertext directly to backend"
- );
- },
- mintPresignedGet: async () => {
- throw new Error("Postgres recording backend does not support presigned GET URLs; backend serves ciphertext inline");
- },
- deleteSession: async () => {
- // Chunks cascade-delete with the session row
- }
-});
diff --git a/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts b/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts
deleted file mode 100644
index 2bc442e7ec..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-ai-summary-queue.ts
+++ /dev/null
@@ -1,396 +0,0 @@
-import { TPamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { getConfig } from "@app/lib/config/env";
-import { logger } from "@app/lib/logger";
-import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
-import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { TPamSessionDALFactory } from "./pam-session-dal";
-import { TPamSessionEventBatchDALFactory } from "./pam-session-event-batch-dal";
-import { decryptSessionCommandLogs } from "./pam-session-fns";
-import {
- buildSummaryPrompt,
- formatLogsForSummary,
- generateSessionSummary,
- MAX_LOG_CHARS
-} from "./pam-session-summary-fns";
-import { TPamSessionCommandLog, TSessionEvent } from "./pam-session-types";
-
-type TSessionSummaryConfig = {
- aiInsightsEnabled: boolean;
- connectionId: string;
- model: string;
-};
-
-type TPamSessionAiSummaryServiceFactoryDep = {
- queueService: TQueueServiceFactory;
- pamSessionDAL: Pick<TPamSessionDALFactory, "findById" | "updateById">;
- pamSessionEventBatchDAL: Pick<TPamSessionEventBatchDALFactory, "findBySessionIdPaginated">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-};
-
-export type TPamSessionAiSummaryServiceFactory = ReturnType<typeof pamSessionAiSummaryServiceFactory>;
-
-export const pamSessionAiSummaryServiceFactory = ({
- queueService,
- pamSessionDAL,
- pamSessionEventBatchDAL,
- pamResourceDAL,
- appConnectionDAL,
- kmsService
-}: TPamSessionAiSummaryServiceFactoryDep) => {
- const queueAiSummary = async (sessionId: string, projectId: string) => {
- // Check if AI insights is enabled for this session's resource before touching the DB or queue
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) return;
-
- const resourceId = session.selectedResourceId ?? session.resourceId;
- if (!resourceId) return;
-
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) return;
-
- const { encryptedSessionSummaryConfig: encryptedConfig } = resource;
- if (!encryptedConfig) return;
-
- let summaryConfig: TSessionSummaryConfig;
- try {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- summaryConfig = JSON.parse(decryptor({ cipherTextBlob: encryptedConfig }).toString()) as TSessionSummaryConfig;
- } catch (err) {
- logger.warn(
- { sessionId, err },
- `queueAiSummary: failed to decrypt sessionSummaryConfig, skipping [sessionId=${sessionId}]`
- );
- return;
- }
-
- if (!summaryConfig.aiInsightsEnabled) return;
-
- // AI is enabled — enqueue first, then mark pending only on successful enqueue
- await queueService.queue(
- QueueName.PamSessionAiSummary,
- QueueJobs.PamSessionAiSummary,
- { sessionId, projectId },
- {
- jobId: `pam-session-ai-summary-${sessionId}`,
- removeOnComplete: { count: 20 },
- removeOnFail: { count: 20 }
- }
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: "pending" });
- };
-
- const appCfg = getConfig();
-
- const init = () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.PamSessionAiSummary, async (job) => {
- const { sessionId, projectId } = job.data;
-
- logger.info({ sessionId }, `${QueueName.PamSessionAiSummary}: starting AI summary [sessionId=${sessionId}]`);
-
- try {
- // 1. Fetch session
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) {
- logger.warn(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: session not found, skipping [sessionId=${sessionId}]`
- );
- return;
- }
-
- const resourceId = session.selectedResourceId ?? session.resourceId;
- if (!resourceId) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: no resourceId on session (resource deleted?), skipping [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- // 3. Fetch resource and decrypt sessionSummaryConfig
- const resource = await pamResourceDAL.findById(resourceId);
- if (!resource) {
- logger.info(
- { sessionId, resourceId },
- `${QueueName.PamSessionAiSummary}: resource not found, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- const { encryptedSessionSummaryConfig: encryptedConfig } = resource;
-
- if (!encryptedConfig) {
- logger.info(
- { sessionId, resourceId },
- `${QueueName.PamSessionAiSummary}: no sessionSummaryConfig on resource, skipping [sessionId=${sessionId}] [resourceId=${resourceId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- let summaryConfig: TSessionSummaryConfig;
- try {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- summaryConfig = JSON.parse(
- decryptor({ cipherTextBlob: encryptedConfig }).toString()
- ) as TSessionSummaryConfig;
- } catch (err) {
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionAiSummary}: failed to decrypt sessionSummaryConfig [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- if (!summaryConfig.aiInsightsEnabled) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: AI insights disabled for resource, skipping [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- // 4. Fetch app connection and decrypt credentials
- const appConnection = await appConnectionDAL.findById(summaryConfig.connectionId);
- if (!appConnection) {
- await pamSessionDAL.updateById(sessionId, {
- aiInsightsStatus: "failed",
- aiInsightsError: "Configured AI app connection not found"
- });
- return;
- }
-
- let apiKey: string;
- try {
- const credentials = await decryptAppConnectionCredentials({
- orgId: appConnection.orgId,
- encryptedCredentials: appConnection.encryptedCredentials,
- kmsService,
- projectId: appConnection.projectId
- });
- apiKey = (credentials as { apiKey: string }).apiKey;
- } catch (err) {
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionAiSummary}: failed to decrypt connection credentials [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, {
- aiInsightsStatus: "failed",
- aiInsightsError: "Failed to decrypt AI connection credentials"
- });
- return;
- }
-
- // 5. Decrypt session logs — batch table first (new), fall back to legacy blob.
- // Stop decrypting once accumulated content exceeds MAX_LOG_CHARS — there is no point
- // loading more data than formatLogsForSummary will use, and this bounds memory usage
- // to the content budget rather than an arbitrary batch count.
- let logs;
- try {
- const PAGE_SIZE = 20;
- let offset = 0;
- let contentChars = 0;
- const accumulatedLogs: (TPamSessionCommandLog | TSessionEvent)[] = [];
- let hasMoreBatches = true;
-
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- while (hasMoreBatches && contentChars < MAX_LOG_CHARS) {
- // eslint-disable-next-line no-await-in-loop
- const page = await pamSessionEventBatchDAL.findBySessionIdPaginated(sessionId, {
- offset,
- limit: PAGE_SIZE
- });
- if (page.length === 0) break;
- for (const batch of page) {
- const plain = decryptor({ cipherTextBlob: batch.encryptedEventsBlob });
- const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TSessionEvent)[];
- // For SSH, only input events are used by formatLogsForSummary — count only those bytes
- // to avoid premature truncation from output/resize/error events that are discarded.
- // For Postgres, every event is a command log so count all of them.
- const isSsh = resource.resourceType === PamResource.SSH;
- for (const event of batchEvents) {
- if (isSsh) {
- const termEvent = event as TSessionEvent;
- if (termEvent.eventType === "input")
- contentChars += termEvent.data ? Buffer.from(termEvent.data, "base64").length : 0;
- } else {
- const cmdLog = event as TPamSessionCommandLog;
- contentChars += (cmdLog.input?.length ?? 0) + (cmdLog.output?.length ?? 0);
- }
- }
- accumulatedLogs.push(...batchEvents);
- if (contentChars >= MAX_LOG_CHARS) break;
- }
- if (page.length < PAGE_SIZE) hasMoreBatches = false;
- offset += PAGE_SIZE;
- }
-
- if (contentChars >= MAX_LOG_CHARS) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: session logs exceed size limit, skipping AI summary [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- if (accumulatedLogs.length > 0) {
- logs = accumulatedLogs;
- } else if (session.encryptedLogsBlob) {
- const legacyLogs = await decryptSessionCommandLogs({
- projectId,
- encryptedLogs: session.encryptedLogsBlob,
- kmsService
- });
- const isSshLegacy = resource.resourceType === PamResource.SSH;
- const legacyChars = legacyLogs.reduce((sum, e) => {
- if (isSshLegacy) {
- const termEvent = e as TSessionEvent;
- if (termEvent.eventType !== "input") return sum;
- return sum + (termEvent.data ? Buffer.from(termEvent.data, "base64").length : 0);
- }
- const cmd = e as TPamSessionCommandLog;
- return sum + (cmd.input?.length ?? 0) + (cmd.output?.length ?? 0);
- }, 0);
- if (legacyChars >= MAX_LOG_CHARS) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: legacy session logs exceed size limit, skipping AI summary [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
- logs = legacyLogs;
- } else {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: no session logs, skipping [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- if (logs.length === 0) {
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
- } catch (err) {
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionAiSummary}: failed to decrypt session logs [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, {
- aiInsightsStatus: "failed",
- aiInsightsError: "Failed to decrypt session logs"
- });
- return;
- }
-
- // 6. Format logs, build prompt, and generate summary
- try {
- const resourceType = resource.resourceType as PamResource;
- const durationSeconds = session.endedAt
- ? (new Date(session.endedAt).getTime() - new Date(session.createdAt).getTime()) / 1000
- : 0;
-
- const formattedLogs = formatLogsForSummary(logs, resourceType);
-
- if (!formattedLogs) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: no usable log content after formatting, skipping [sessionId=${sessionId}]`
- );
- await pamSessionDAL.updateById(sessionId, { aiInsightsStatus: null });
- return;
- }
-
- const { system, user } = buildSummaryPrompt({
- resourceType,
- resourceName: resource.name,
- actorName: session.actorName,
- actorEmail: session.actorEmail,
- durationSeconds,
- formattedLogs
- });
-
- const { summary, warnings } = await generateSessionSummary(apiKey, summaryConfig.model, system, user);
-
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const { cipherTextBlob: encryptedAiInsights } = encryptor({
- plainText: Buffer.from(JSON.stringify({ summary, warnings }))
- });
-
- await pamSessionDAL.updateById(sessionId, {
- encryptedAiInsights,
- aiInsightsStatus: "completed",
- aiInsightsError: null
- });
-
- logger.info(
- { sessionId },
- `${QueueName.PamSessionAiSummary}: AI summary completed successfully [sessionId=${sessionId}]`
- );
- } catch (err) {
- const message =
- err instanceof Error && err.message.length < 500
- ? err.message
- : "AI summarization failed. The session logs may be too large for the selected model.";
-
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionAiSummary}: AI summarization failed [sessionId=${sessionId}]`
- );
-
- await pamSessionDAL.updateById(sessionId, {
- aiInsightsStatus: "failed",
- aiInsightsError: message
- });
- }
- } catch (err) {
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionAiSummary}: unexpected worker error [sessionId=${sessionId}]`
- );
- try {
- await pamSessionDAL.updateById(sessionId, {
- aiInsightsStatus: "failed",
- aiInsightsError: "Unexpected error during AI summarization"
- });
- } catch {
- // best-effort status reset
- }
- }
- });
- };
-
- return { queueAiSummary, init };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts b/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
deleted file mode 100644
index de04997ed0..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-chunk-service.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-import { OrgServiceActor } from "@app/lib/types";
-import { ActorType } from "@app/services/auth/auth-type";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-
-import { TPamProjectRecordingConfigServiceFactory } from "../pam-project-recording-config/pam-project-recording-config-service";
-import { PAM_RECORDING_MAX_CHUNK_BYTES } from "../pam-session-recording-storage/pam-session-recording-storage-constants";
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
-import { PAM_RECORDING_STORAGE_FACTORY_MAP } from "../pam-session-recording-storage/pam-session-recording-storage-factory";
-import { buildExternalChunkObjectKey } from "../pam-session-recording-storage/pam-session-recording-storage-types";
-import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";
-import { TPamSessionDALFactory } from "./pam-session-dal";
-import { PamSessionStatus } from "./pam-session-enums";
-import { TPamSessionEventChunkDALFactory } from "./pam-session-event-chunk-dal";
-import { decryptSessionKey, verifyGatewayUploadToken } from "./pam-session-recording-secrets";
-
-type TPamSessionChunkServiceFactoryDep = {
- pamSessionDAL: TPamSessionDALFactory;
- pamSessionEventChunkDAL: TPamSessionEventChunkDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- pamProjectRecordingConfigService: Pick<TPamProjectRecordingConfigServiceFactory, "resolveConfigForProject">;
-};
-
-export type TPamSessionChunkServiceFactory = ReturnType<typeof pamSessionChunkServiceFactory>;
-
-function assertGatewayActor(actor: OrgServiceActor) {
- if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {
- throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
- }
-}
-
-export const pamSessionChunkServiceFactory = ({
- pamSessionDAL,
- pamSessionEventChunkDAL,
- permissionService,
- kmsService,
- pamProjectRecordingConfigService
-}: TPamSessionChunkServiceFactoryDep) => {
- const requestPresignedPut = async (
- {
- sessionId,
- chunkIndex,
- ciphertextBytes,
- isKeyframe,
- uploadToken
- }: {
- sessionId: string;
- chunkIndex: number;
- ciphertextBytes: number;
- isKeyframe?: boolean;
- uploadToken: string;
- },
- actor: OrgServiceActor
- ) => {
- assertGatewayActor(actor);
-
- if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
- throw new BadRequestError({
- message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
- });
- }
-
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
-
- if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });
- }
- if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });
- }
-
- verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);
-
- const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId);
- if (!config || config.backend === PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message:
- "Project is not configured for object-storage recordings. Gateway should POST ciphertext to /chunks instead."
- });
- }
-
- const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();
- const presigned = await provider.mintPresignedPut({
- config,
- projectId: session.projectId,
- sessionId,
- chunkIndex,
- ciphertextBytes,
- isKeyframe
- });
-
- return presigned;
- };
-
- const recordChunk = async (
- {
- sessionId,
- chunkIndex,
- startElapsedMs,
- endElapsedMs,
- ciphertextSha256Base64,
- ciphertextBytes,
- ivBase64,
- keyframeObjectKey,
- keyframeSizeBytes,
- ciphertext,
- uploadToken
- }: {
- sessionId: string;
- chunkIndex: number;
- startElapsedMs: number;
- endElapsedMs: number;
- ciphertextSha256Base64: string;
- ciphertextBytes: number;
- ivBase64: string;
- keyframeObjectKey?: string;
- keyframeSizeBytes?: number;
-
- // For Postgres backend, the gateway POSTs the ciphertext bytes inline
- ciphertext?: Buffer;
- uploadToken: string;
- },
- actor: OrgServiceActor
- ) => {
- assertGatewayActor(actor);
-
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
-
- if (actor.type === ActorType.GATEWAY && session.gatewayId && session.gatewayId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Gateway not authorized for this session" });
- }
- if (actor.type === ActorType.IDENTITY && session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Identity not authorized for this session" });
- }
-
- verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);
-
- if (ciphertextBytes <= 0 || ciphertextBytes > PAM_RECORDING_MAX_CHUNK_BYTES) {
- throw new BadRequestError({
- message: `Chunk size out of range [bytes=${ciphertextBytes}, max=${PAM_RECORDING_MAX_CHUNK_BYTES}]`
- });
- }
-
- const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
- if (!BASE64_RE.test(ciphertextSha256Base64) || !BASE64_RE.test(ivBase64)) {
- throw new BadRequestError({ message: "Invalid base64 in chunk metadata" });
- }
- const ciphertextSha256 = Buffer.from(ciphertextSha256Base64, "base64");
- const iv = Buffer.from(ivBase64, "base64");
- if (ciphertextSha256.length !== 32) {
- throw new BadRequestError({ message: "ciphertextSha256 must be 32 bytes (sha256 digest)" });
- }
- if (iv.length !== 12) {
- throw new BadRequestError({ message: "iv must be 12 bytes (AES-GCM standard)" });
- }
-
- const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId);
- const backend = config?.backend ?? PamRecordingStorageBackend.Postgres;
-
- if (backend === PamRecordingStorageBackend.Postgres) {
- if (!ciphertext) {
- throw new BadRequestError({
- message: "Postgres backend requires the ciphertext bytes to be POSTed inline"
- });
- }
- if (ciphertext.length !== ciphertextBytes) {
- throw new BadRequestError({
- message: `Declared ciphertextBytes does not match body length [declared=${ciphertextBytes}, actual=${ciphertext.length}]`
- });
- }
- }
-
- const externalChunkObjectKey =
- backend === PamRecordingStorageBackend.AwsS3
- ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, false)
- : null;
-
- const externalKeyframeObjectKey =
- backend === PamRecordingStorageBackend.AwsS3 && keyframeObjectKey
- ? buildExternalChunkObjectKey(config?.keyPrefix, session.projectId, sessionId, chunkIndex, true)
- : null;
-
- try {
- await pamSessionEventChunkDAL.insertIgnoreDuplicate({
- sessionId,
- chunkIndex,
- startElapsedMs,
- endElapsedMs,
- storageBackend: backend,
- encryptedEventsBlob: backend === PamRecordingStorageBackend.Postgres ? (ciphertext ?? null) : null,
- externalChunkObjectKey,
- chunkSizeBytes: backend === PamRecordingStorageBackend.AwsS3 ? ciphertextBytes : null,
- externalKeyframeObjectKey,
- keyframeSizeBytes: keyframeSizeBytes ?? null,
- ciphertextSha256,
- ciphertextBytes,
- iv
- });
- } catch (err) {
- logger.error(
- { sessionId, chunkIndex, err },
- `Chunk insert failed [sessionId=${sessionId}] [chunkIndex=${chunkIndex}]`
- );
- throw err;
- }
-
- return { ok: true as const, projectId: session.projectId, storageBackend: backend };
- };
-
- const getPlaybackBundle = async (sessionId: string, actor: OrgServiceActor) => {
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: session.projectId,
- actionProjectType: ActionProjectType.PAM
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Read,
- ProjectPermissionSub.PamSessions
- );
-
- const sessionComplete = session.status !== PamSessionStatus.Active && session.status !== PamSessionStatus.Starting;
-
- if (!session.encryptedSessionKey) {
- // Legacy session fall through to legacy decrypt path
- return { sessionKey: null, chunks: [], legacy: true as const, sessionComplete };
- }
-
- const sessionKey = await decryptSessionKey({
- projectId: session.projectId,
- sessionId,
- encryptedSessionKey: session.encryptedSessionKey,
- kmsService
- });
-
- const chunks = await pamSessionEventChunkDAL.findAllBySessionId(sessionId);
-
- let presignedGetByObjectKey: Record<string, { url: string }> = {};
- const config = await pamProjectRecordingConfigService.resolveConfigForProject(session.projectId);
- if (config?.backend === PamRecordingStorageBackend.AwsS3) {
- const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();
- const minted = await Promise.all(
- chunks
- .filter((c) => c.storageBackend === PamRecordingStorageBackend.AwsS3 && c.externalChunkObjectKey)
- .map(async (c) => {
- const presigned = await provider.mintPresignedGet({
- config,
- objectKey: c.externalChunkObjectKey as string
- });
- return [c.externalChunkObjectKey as string, { url: presigned.url }] as const;
- })
- );
- presignedGetByObjectKey = Object.fromEntries(minted);
- }
-
- return {
- sessionKey: sessionKey.toString("base64"),
- legacy: false as const,
- sessionComplete,
- projectId: session.projectId,
- storageBackend: config?.backend ?? PamRecordingStorageBackend.Postgres,
- chunks: chunks.map((c) => ({
- chunkIndex: c.chunkIndex,
- startElapsedMs: Number(c.startElapsedMs),
- endElapsedMs: Number(c.endElapsedMs),
- storageBackend: c.storageBackend as PamRecordingStorageBackend,
- externalChunkObjectKey: c.externalChunkObjectKey ?? null,
- ciphertextSha256: c.ciphertextSha256.toString("base64"),
- ciphertextBytes: Number(c.ciphertextBytes),
- iv: c.iv.toString("base64"),
- presignedGetUrl: c.externalChunkObjectKey
- ? (presignedGetByObjectKey[c.externalChunkObjectKey]?.url ?? null)
- : null
- }))
- };
- };
-
- const getChunkCiphertext = async (sessionId: string, chunkIndex: number, actor: OrgServiceActor) => {
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session ${sessionId} not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: session.projectId,
- actionProjectType: ActionProjectType.PAM
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Read,
- ProjectPermissionSub.PamSessions
- );
-
- const chunk = await pamSessionEventChunkDAL.findByChunkIndex(sessionId, chunkIndex);
- if (!chunk) throw new NotFoundError({ message: `Chunk ${chunkIndex} not found` });
- if (chunk.storageBackend !== PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message: "Chunk is stored externally; use the presigned GET URL from the playback endpoint"
- });
- }
- if (!chunk.encryptedEventsBlob) {
- throw new BadRequestError({ message: "Chunk has no inline ciphertext" });
- }
- return { ciphertext: chunk.encryptedEventsBlob };
- };
-
- return { requestPresignedPut, recordChunk, getPlaybackBundle, getChunkCiphertext };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.ts
deleted file mode 100644
index eab7676d02..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify, selectAllTableCols } from "@app/lib/knex";
-
-import { PamSessionStatus } from "./pam-session-enums";
-
-export type TPamSessionDALFactory = ReturnType<typeof pamSessionDALFactory>;
-export const pamSessionDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamSession);
-
- // COALESCE(session.selectedResourceId, account.resourceId) for domain + local sessions.
- const sessionResourceOn = db.raw(`COALESCE(??.??, ??.??) = ??.??`, [
- TableName.PamSession,
- "selectedResourceId",
- TableName.PamAccount,
- "resourceId",
- TableName.PamResource,
- "id"
- ]);
-
- const findById = async (id: string, tx?: Knex) => {
- const session = await (tx || db.replicaNode())(TableName.PamSession)
- .leftJoin(TableName.PamAccount, `${TableName.PamSession}.accountId`, `${TableName.PamAccount}.id`)
- .leftJoin(TableName.PamResource, function joinResource() {
- this.on(sessionResourceOn);
- })
- .leftJoin(TableName.GatewayV2, function joinSessionGateway() {
- this.on(
- `${TableName.GatewayV2}.id`,
- "=",
- db.raw("COALESCE(??, ??)", [`${TableName.PamSession}.gatewayId`, `${TableName.PamResource}.gatewayId`])
- );
- })
- .select(selectAllTableCols(TableName.PamSession))
- .select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName"))
- .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))
- .select(db.ref("id").withSchema(TableName.GatewayV2).as("gatewayId"))
- .where(`${TableName.PamSession}.id`, id)
- .first();
-
- return session;
- };
-
- const countActiveWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamSession)
- .where("userId", userId)
- .where("projectId", projectId)
- .where("accessMethod", "web")
- .whereIn("status", [PamSessionStatus.Starting, PamSessionStatus.Active])
- .count("id as count")
- .first();
-
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const countActiveByProjectId = async (projectId: string, tx?: Knex): Promise<number> => {
- const result = await (tx || db.replicaNode())(TableName.PamSession)
- .where("projectId", projectId)
- .whereIn("status", [PamSessionStatus.Starting, PamSessionStatus.Active])
- .count("id as count")
- .first();
-
- return Number((result as { count?: string | number })?.count ?? 0);
- };
-
- const expireSessionById = async (sessionId: string, tx?: Knex) => {
- const now = new Date();
-
- const updatedCount = await (tx || db)(TableName.PamSession)
- .where("id", sessionId)
- .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
- .update({
- status: PamSessionStatus.Ended,
- endedAt: now
- });
-
- return updatedCount;
- };
-
- const endExpiredWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {
- const now = new Date();
- const updatedCount = await (tx || db)(TableName.PamSession)
- .where("userId", userId)
- .where("projectId", projectId)
- .where("accessMethod", "web")
- .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
- .where("expiresAt", "<", now)
- .update({ status: PamSessionStatus.Ended, endedAt: now });
- return updatedCount;
- };
-
- const findByProjectId = async (projectId: string, tx?: Knex) => {
- const sessions = await (tx || db.replicaNode())(TableName.PamSession)
- .leftJoin(TableName.PamAccount, `${TableName.PamSession}.accountId`, `${TableName.PamAccount}.id`)
- .leftJoin(TableName.PamResource, function joinResource() {
- this.on(sessionResourceOn);
- })
- .leftJoin(TableName.GatewayV2, function joinSessionGateway() {
- this.on(
- `${TableName.GatewayV2}.id`,
- "=",
- db.raw("COALESCE(??, ??)", [`${TableName.PamSession}.gatewayId`, `${TableName.PamResource}.gatewayId`])
- );
- })
- .select(selectAllTableCols(TableName.PamSession))
- .select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))
- .select(db.ref("id").withSchema(TableName.GatewayV2).as("gatewayId"))
- .where(`${TableName.PamSession}.projectId`, projectId);
-
- return sessions;
- };
-
- const endSessionById = async (sessionId: string, tx?: Knex) => {
- const [updated] = await (tx || db)(TableName.PamSession)
- .where("id", sessionId)
- .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
- .update({ status: PamSessionStatus.Ended, endedAt: new Date() })
- .returning("*");
- return updated;
- };
-
- const terminateSessionById = async (sessionId: string, tx?: Knex) => {
- const [updated] = await (tx || db)(TableName.PamSession)
- .where("id", sessionId)
- .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
- .update({ status: PamSessionStatus.Terminated, endedAt: new Date() })
- .returning("*");
- return updated;
- };
-
- const activateSession = async (sessionId: string, tx?: Knex) => {
- const [updated] = await (tx || db)(TableName.PamSession)
- .where("id", sessionId)
- .where("status", PamSessionStatus.Starting)
- .update({ status: PamSessionStatus.Active, startedAt: new Date() })
- .returning("*");
- return updated;
- };
-
- const startSession = async (
- sessionId: string,
- patch: {
- encryptedSessionKey: Buffer;
- gatewayUploadTokenHash: Buffer;
- },
- tx?: Knex
- ) => {
- const [updated] = await (tx || db)(TableName.PamSession)
- .where("id", sessionId)
- .where("status", PamSessionStatus.Starting)
- .update({
- status: PamSessionStatus.Active,
- startedAt: new Date(),
- ...patch
- })
- .returning("*");
- return updated;
- };
-
- const countDailyByProjectId = async (
- projectId: string,
- startDate: Date,
- tx?: Knex
- ): Promise<{ date: string; count: number }[]> => {
- const rows = (await (tx || db.replicaNode())(TableName.PamSession)
- .select(db.raw(`to_char(("createdAt" AT TIME ZONE 'UTC')::date, 'YYYY-MM-DD') as date`))
- .count("id as count")
- .where("projectId", projectId)
- .where("createdAt", ">=", startDate)
- .groupByRaw(`("createdAt" AT TIME ZONE 'UTC')::date`)
- .orderByRaw(`("createdAt" AT TIME ZONE 'UTC')::date asc`)) as unknown as {
- date: string;
- count: string | number;
- }[];
-
- return rows.map((row) => ({ date: String(row.date), count: Number(row.count) }));
- };
-
- const findTopActorsByProjectId = async (
- projectId: string,
- startDate: Date,
- limit: number,
- tx?: Knex
- ): Promise<
- {
- actorName: string;
- actorEmail: string;
- userId: string | null;
- sessionCount: number;
- }[]
- > => {
- const rows = (await (tx || db.replicaNode())(TableName.PamSession)
- .select("actorName", "actorEmail", "userId")
- .count("id as count")
- .where("projectId", projectId)
- .where("createdAt", ">=", startDate)
- .groupBy("actorName", "actorEmail", "userId")
- .orderBy("count", "desc")
- .limit(limit)) as unknown as {
- actorName: string;
- actorEmail: string;
- userId: string | null;
- count: string | number;
- }[];
-
- return rows.map((row) => ({
- actorName: row.actorName,
- actorEmail: row.actorEmail,
- userId: row.userId,
- sessionCount: Number(row.count)
- }));
- };
-
- return {
- ...orm,
- findById,
- findByProjectId,
- expireSessionById,
- endExpiredWebSessions,
- countActiveWebSessions,
- countActiveByProjectId,
- countDailyByProjectId,
- findTopActorsByProjectId,
- endSessionById,
- terminateSessionById,
- activateSession,
- startSession
- };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-enums.ts b/backend/src/ee/services/pam-session/pam-session-enums.ts
deleted file mode 100644
index 790a7ac768..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-enums.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-export enum PamSessionStatus {
- Starting = "starting", // Starting, user connecting to resource
- Active = "active", // Active, user is connected to resource
- Ended = "ended", // Ended by user or automatically expired after expiresAt timestamp
- Terminated = "terminated" // Terminated by an admin
-}
-
-export enum SessionChannelType {
- Terminal = "terminal", // Interactive SSH terminal session
- Exec = "exec", // SSH exec command
- Sftp = "sftp", // SFTP file transfer session
- Rdp = "rdp" // RDP frame/input tap; data carries an RDP-specific JSON envelope
-}
diff --git a/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts b/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts
deleted file mode 100644
index bf54470cbd..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-event-batch-dal.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TPamSessionEventBatchDALFactory = ReturnType<typeof pamSessionEventBatchDALFactory>;
-
-export const pamSessionEventBatchDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamSessionEventBatch);
-
- const findBySessionIdPaginated = async (
- sessionId: string,
- { offset, limit }: { offset: number; limit: number },
- tx?: Knex
- ) => {
- return (tx || db.replicaNode())(TableName.PamSessionEventBatch)
- .where("sessionId", sessionId)
- .orderBy("startOffset", "asc")
- .limit(limit)
- .offset(offset)
- .select("*");
- };
-
- const upsertBatch = async (sessionId: string, startOffset: number, encryptedEventsBlob: Buffer, tx?: Knex) => {
- const result = await (tx || db)(TableName.PamSessionEventBatch)
- .insert({ sessionId, startOffset, encryptedEventsBlob })
- .onConflict(["sessionId", "startOffset"])
- .merge(["encryptedEventsBlob"]) // on re-upload of the same offset, overwrite the blob instead of erroring or skipping
- .returning(db.raw("(xmax = 0) as inserted"));
- return { wasInserted: (result[0] as unknown as { inserted: boolean })?.inserted === true };
- };
-
- return { ...orm, findBySessionIdPaginated, upsertBatch };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts b/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts
deleted file mode 100644
index 58e323a3bc..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-event-chunk-dal.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Knex } from "knex";
-
-import { TDbClient } from "@app/db";
-import { TableName, TPamSessionEventChunksInsert } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TPamSessionEventChunkDALFactory = ReturnType<typeof pamSessionEventChunkDALFactory>;
-
-export const pamSessionEventChunkDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.PamSessionEventChunk);
-
- const findAllBySessionId = async (sessionId: string, tx?: Knex) => {
- return (tx || db.replicaNode())(TableName.PamSessionEventChunk)
- .where("sessionId", sessionId)
- .orderBy("chunkIndex", "asc")
- .select("*");
- };
-
- const findByChunkIndex = async (sessionId: string, chunkIndex: number, tx?: Knex) => {
- return (tx || db.replicaNode())(TableName.PamSessionEventChunk).where({ sessionId, chunkIndex }).first();
- };
-
- const insertIgnoreDuplicate = async (data: TPamSessionEventChunksInsert, tx?: Knex) => {
- await (tx || db)(TableName.PamSessionEventChunk).insert(data).onConflict(["sessionId", "chunkIndex"]).ignore();
- };
-
- return { ...orm, findAllBySessionId, findByChunkIndex, insertIgnoreDuplicate };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
deleted file mode 100644
index 36b491874e..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { TPamSessionEventBatches, TPamSessions } from "@app/db/schemas";
-import { logger } from "@app/lib/logger";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { TPamSanitizedSession, TPamSessionCommandLog, TSessionEvent } from "./pam-session-types";
-
-export const decryptSessionCommandLogs = async ({
- projectId,
- encryptedLogs,
- kmsService
-}: {
- projectId: string;
- encryptedLogs: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decryptedPlainTextBlob = decryptor({
- cipherTextBlob: encryptedLogs
- });
-
- return JSON.parse(decryptedPlainTextBlob.toString()) as (TPamSessionCommandLog | TSessionEvent)[];
-};
-
-export const decryptBatches = async (
- batches: TPamSessionEventBatches[],
- projectId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
-) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const events: (TPamSessionCommandLog | TSessionEvent)[] = [];
- for (const batch of batches) {
- const plain = decryptor({ cipherTextBlob: batch.encryptedEventsBlob });
- const batchEvents = JSON.parse(plain.toString()) as (TPamSessionCommandLog | TSessionEvent)[];
- events.push(...batchEvents);
- }
- return events;
-};
-
-export const decryptSession = async (
- session: TPamSessions,
- projectId: string,
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
-) => {
- const { encryptedAiInsights } = session;
-
- let aiInsights: { summary: string; warnings: { text: string; logIndex?: number }[] } | null = null;
- if (encryptedAiInsights) {
- try {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
- aiInsights = JSON.parse(decryptor({ cipherTextBlob: encryptedAiInsights }).toString()) as {
- summary: string;
- warnings: { text: string; logIndex?: number }[];
- };
- } catch (err) {
- logger.warn({ err }, "decryptSession: failed to decrypt aiInsights, falling back to null");
- }
- }
-
- return {
- ...session,
- logs: session.encryptedLogsBlob
- ? await decryptSessionCommandLogs({
- projectId,
- encryptedLogs: session.encryptedLogsBlob,
- kmsService
- })
- : [],
- aiInsights
- } as TPamSanitizedSession;
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts b/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts
deleted file mode 100644
index f633f98d1d..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-recording-secrets.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, InternalServerError } from "@app/lib/errors";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { PAM_RECORDING_AAD_VERSION } from "../pam-session-recording-storage/pam-session-recording-storage-constants";
-
-const SESSION_KEY_LENGTH = 32; // AES-256
-const UPLOAD_TOKEN_LENGTH = 32; // 256 random bits
-
-const buildWrapAad = (projectId: string, sessionId: string) =>
- crypto.nativeCrypto.createHash("sha256").update(`${projectId}|${sessionId}|${PAM_RECORDING_AAD_VERSION}`).digest();
-
-export const generateSessionRecordingSecrets = async ({
- projectId,
- sessionId,
- kmsService
-}: {
- projectId: string;
- sessionId: string;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const sessionKey = crypto.randomBytes(SESSION_KEY_LENGTH);
- const uploadToken = crypto.randomBytes(UPLOAD_TOKEN_LENGTH);
-
- const wrapAad = buildWrapAad(projectId, sessionId);
-
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- // KMS createCipherPairWithDataKey doesn't expose a native AAD parameter, so we prepend the AAD bytes to the plaintext before wrapping
- // Unwrap then verifies the prefix matches the expected AAD with a constant-time compare
- const encryptionPayload = Buffer.concat([wrapAad, sessionKey]);
- const { cipherTextBlob: encryptedSessionKey } = encryptor({ plainText: encryptionPayload });
-
- const uploadTokenHash = crypto.nativeCrypto.createHash("sha256").update(uploadToken).digest();
-
- return {
- sessionKey,
- uploadToken,
- encryptedSessionKey,
- uploadTokenHash
- };
-};
-
-export const decryptSessionKey = async ({
- projectId,
- sessionId,
- encryptedSessionKey,
- kmsService
-}: {
- projectId: string;
- sessionId: string;
- encryptedSessionKey: Buffer;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
-}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId
- });
-
- const decrypted = decryptor({ cipherTextBlob: encryptedSessionKey });
- if (decrypted.length !== 32 + SESSION_KEY_LENGTH) {
- throw new InternalServerError({ message: "Encrypted session key has unexpected size" });
- }
- const recoveredAad = decrypted.subarray(0, 32);
- const expectedAad = buildWrapAad(projectId, sessionId);
- if (!crypto.nativeCrypto.timingSafeEqual(recoveredAad, expectedAad)) {
- throw new InternalServerError({ message: "Session key AAD mismatch — refusing to unwrap" });
- }
- return decrypted.subarray(32, 32 + SESSION_KEY_LENGTH);
-};
-
-export const verifyGatewayUploadToken = (
- presentedTokenBase64: string | undefined | null,
- storedTokenHash: Buffer | null | undefined
-) => {
- if (!presentedTokenBase64 || !storedTokenHash) {
- throw new BadRequestError({
- message: "Gateway upload token missing or session not configured for chunked uploads"
- });
- }
- let presentedBuf: Buffer;
- try {
- presentedBuf = Buffer.from(presentedTokenBase64, "base64");
- } catch {
- throw new BadRequestError({ message: "Invalid upload token" });
- }
- if (presentedBuf.length !== UPLOAD_TOKEN_LENGTH) {
- throw new BadRequestError({ message: "Invalid upload token" });
- }
- const presentedHash = crypto.nativeCrypto.createHash("sha256").update(presentedBuf).digest();
- if (presentedHash.length !== storedTokenHash.length) {
- throw new BadRequestError({ message: "Invalid upload token" });
- }
- if (!crypto.nativeCrypto.timingSafeEqual(presentedHash, storedTokenHash)) {
- throw new BadRequestError({ message: "Invalid upload token" });
- }
-};
-
-export const SESSION_KEY_BYTES = SESSION_KEY_LENGTH;
-export const UPLOAD_TOKEN_BYTES = UPLOAD_TOKEN_LENGTH;
diff --git a/backend/src/ee/services/pam-session/pam-session-schemas.ts b/backend/src/ee/services/pam-session/pam-session-schemas.ts
deleted file mode 100644
index 163dc9a95a..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-schemas.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { z } from "zod";
-
-import { PamSessionsSchema } from "@app/db/schemas";
-
-import { SessionChannelType } from "./pam-session-enums";
-
-export const PamSessionCommandLogSchema = z.object({
- input: z.string(),
- output: z.string(),
- timestamp: z.coerce.date()
-});
-
-// "rdp" events carry a JSON envelope in `data` (target_frame / keyboard / unicode / mouse).
-export const SessionEventTypeSchema = z.enum(["input", "output", "resize", "error", "rdp"]);
-
-export const SessionChannelTypeSchema = z.nativeEnum(SessionChannelType);
-
-export const HttpEventTypeSchema = z.enum(["request", "response"]);
-
-export const SessionEventSchema = z.object({
- timestamp: z.coerce.date(),
- eventType: SessionEventTypeSchema,
- channelType: SessionChannelTypeSchema.optional(), // Optional for backwards compatibility with existing logs
- data: z.string(), // Base64 encoded binary data
- elapsedTime: z.number() // Seconds since session start (for replay)
-});
-
-export const HttpBaseEventSchema = z.object({
- timestamp: z.coerce.date(),
- requestId: z.string(),
- eventType: SessionEventTypeSchema,
- headers: z.record(z.string(), z.array(z.string())),
- body: z.string().optional()
-});
-
-export const HttpRequestEventSchema = HttpBaseEventSchema.extend({
- eventType: z.literal(HttpEventTypeSchema.Values.request),
- method: z.string(),
- url: z.string()
-});
-
-export const HttpResponseEventSchema = HttpBaseEventSchema.extend({
- eventType: z.literal(HttpEventTypeSchema.Values.response),
- status: z.string()
-});
-
-export const HttpEventSchema = z.discriminatedUnion("eventType", [HttpRequestEventSchema, HttpResponseEventSchema]);
-
-export const AiInsightsSchema = z
- .object({
- summary: z.string(),
- warnings: z.array(z.object({ text: z.string(), logIndex: z.number().int().optional() }))
- })
- .nullable()
- .optional();
-
-const SessionInternalFieldsOmit = {
- encryptedLogsBlob: true,
- encryptedAiInsights: true,
- encryptedSessionKey: true,
- gatewayUploadTokenHash: true
-} as const;
-
-export const SanitizedSessionSchema = PamSessionsSchema.omit(SessionInternalFieldsOmit).extend({
- logs: z.array(z.union([PamSessionCommandLogSchema, HttpEventSchema, SessionEventSchema])),
- gatewayIdentityId: z.string().nullable().optional(),
- gatewayId: z.string().nullable().optional(),
- aiInsights: AiInsightsSchema
-});
-
-export const SanitizedSessionListItemSchema = PamSessionsSchema.omit(SessionInternalFieldsOmit).extend({
- gatewayIdentityId: z.string().nullable().optional(),
- gatewayId: z.string().nullable().optional()
-});
-
-export const SessionLogsPageSchema = z.object({
- logs: z.array(z.union([PamSessionCommandLogSchema, SessionEventSchema, HttpEventSchema])),
- hasMore: z.boolean(),
- batchCount: z.number()
-});
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
deleted file mode 100644
index cf6f87f9cd..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ /dev/null
@@ -1,455 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-import net from "net";
-
-import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
-import { createGatewayConnection, createRelayConnection } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
-import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { OrgServiceActor } from "@app/lib/types";
-import { ActorType } from "@app/services/auth/auth-type";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { TUserDALFactory } from "@app/services/user/user-dal";
-
-import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
-import { PamResource } from "../pam-resource/pam-resource-enums";
-import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
-import { ProjectPermissionPamSessionActions, ProjectPermissionSub } from "../permission/project-permission";
-import { TPamSessionAiSummaryServiceFactory } from "./pam-session-ai-summary-queue";
-import { TPamSessionDALFactory } from "./pam-session-dal";
-import { PamSessionStatus } from "./pam-session-enums";
-import { TPamSessionEventBatchDALFactory } from "./pam-session-event-batch-dal";
-import { decryptBatches, decryptSession, decryptSessionCommandLogs } from "./pam-session-fns";
-import { TUpdateSessionLogsDTO, TUploadEventBatchDTO } from "./pam-session-types";
-
-type TPamSessionServiceFactoryDep = {
- pamSessionDAL: TPamSessionDALFactory;
- pamSessionEventBatchDAL: TPamSessionEventBatchDALFactory;
- projectDAL: TProjectDALFactory;
- userDAL: Pick<TUserDALFactory, "findById">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
- pamSessionAiSummaryService: Pick<TPamSessionAiSummaryServiceFactory, "queueAiSummary">;
-};
-
-export type TPamSessionServiceFactory = ReturnType<typeof pamSessionServiceFactory>;
-
-export const pamSessionServiceFactory = ({
- pamSessionDAL,
- pamSessionEventBatchDAL,
- projectDAL,
- userDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- pamSessionAiSummaryService
-}: TPamSessionServiceFactoryDep) => {
- // Helper to check and update expired sessions when viewing session details (redundancy for scheduled job)
- // Only applies to non-gateway sessions (e.g., AWS IAM) - gateway sessions are managed by the gateway
- // This is intentionally only called in getById (session details view), not in list
- const checkAndExpireSessionIfNeeded = async <
- T extends {
- id: string;
- status: string;
- expiresAt: Date | null;
- gatewayIdentityId?: string | null;
- gatewayId?: string | null;
- projectId?: string | null;
- }
- >(
- session: T
- ): Promise<T> => {
- // Skip gateway-based sessions - they have their own lifecycle managed by the gateway
- if (session.gatewayIdentityId || session.gatewayId) {
- return session;
- }
-
- const isActive = session.status === PamSessionStatus.Active || session.status === PamSessionStatus.Starting;
- const isExpired = session.expiresAt && new Date(session.expiresAt) <= new Date();
-
- if (isActive && isExpired) {
- const updated = await pamSessionDAL.expireSessionById(session.id);
- if (updated > 0) {
- const { projectId } = session;
- if (projectId) {
- void (async () => {
- try {
- await pamSessionAiSummaryService.queueAiSummary(session.id, projectId);
- } catch (err) {
- logger.error(
- { sessionId: session.id, err },
- `Failed to queue AI summary for inline-expired session [sessionId=${session.id}]`
- );
- }
- })();
- }
- return { ...session, status: PamSessionStatus.Ended, endedAt: new Date() } as T;
- }
- return session;
- }
-
- return session;
- };
-
- const getById = async (sessionId: string, actor: OrgServiceActor) => {
- const sessionFromDb = await pamSessionDAL.findById(sessionId);
- if (!sessionFromDb) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const session = await checkAndExpireSessionIfNeeded(sessionFromDb);
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: session.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Read,
- ProjectPermissionSub.PamSessions
- );
-
- return {
- session: await decryptSession(session, session.projectId, kmsService)
- };
- };
-
- const list = async (projectId: string, actor: OrgServiceActor) => {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Read,
- ProjectPermissionSub.PamSessions
- );
-
- const sessions = await pamSessionDAL.findByProjectId(projectId);
-
- return { sessions };
- };
-
- const updateLogsById = async ({ sessionId, logs }: TUpdateSessionLogsDTO, actor: OrgServiceActor) => {
- // To be hit by gateways only (identity-based or enrollment-flow)
- if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {
- throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
- }
-
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- if (session.encryptedLogsBlob) {
- throw new BadRequestError({ message: "Cannot update logs for sessions with existing logs" });
- }
-
- const project = await requestMemoize(requestMemoKeys.projectFindById(session.projectId), () =>
- projectDAL.findById(session.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });
-
- if (actor.type === ActorType.IDENTITY) {
- const { permission } = await permissionService.getOrgPermission({
- actor: actor.type,
- actorId: actor.id,
- orgId: project.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- scope: OrganizationActionScope.Any
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.CreateGateways,
- OrgPermissionSubjects.Gateway
- );
- } else if (actor.type === ActorType.GATEWAY) {
- if (project.orgId !== actor.orgId) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to this session" });
- }
- }
-
- const authorized =
- actor.type === ActorType.GATEWAY
- ? !session.gatewayId || session.gatewayId === actor.id
- : !session.gatewayIdentityId || session.gatewayIdentityId === actor.id;
- if (!authorized) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to update logs for this session" });
- }
-
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: session.projectId
- });
-
- const { cipherTextBlob } = encryptor({
- plainText: Buffer.from(JSON.stringify(logs))
- });
-
- const updatedSession = await pamSessionDAL.updateById(sessionId, {
- encryptedLogsBlob: cipherTextBlob
- });
-
- return { session: updatedSession, projectId: session.projectId };
- };
-
- const endSessionById = async (sessionId: string, actor: OrgServiceActor) => {
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const project = await requestMemoize(requestMemoKeys.projectFindById(session.projectId), () =>
- projectDAL.findById(session.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });
-
- if (actor.type === ActorType.IDENTITY) {
- const { permission } = await permissionService.getOrgPermission({
- actor: actor.type,
- actorId: actor.id,
- orgId: project.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- scope: OrganizationActionScope.Any
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.CreateGateways,
- OrgPermissionSubjects.Gateway
- );
-
- if (session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Identity does not have access to end this session" });
- }
- } else if (actor.type === ActorType.GATEWAY) {
- if (project.orgId !== actor.orgId) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to this session" });
- }
- if (session.gatewayId && session.gatewayId !== actor.id) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to end this session" });
- }
- } else if (actor.type === ActorType.USER) {
- if (session.userId !== actor.id) {
- throw new ForbiddenRequestError({ message: "You are not authorized to end this session" });
- }
- } else {
- throw new ForbiddenRequestError({ message: "Only gateways and users can perform this action" });
- }
-
- const updatedSession = await pamSessionDAL.endSessionById(sessionId);
-
- if (
- !updatedSession &&
- session.status !== PamSessionStatus.Ended &&
- session.status !== PamSessionStatus.Terminated
- ) {
- throw new BadRequestError({ message: "Cannot end sessions that are not active or starting" });
- }
-
- // Always queue — the gateway calling end means logs are uploaded.
- void (async () => {
- try {
- await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
- } catch (err) {
- logger.error({ sessionId, err }, `Failed to queue AI summary for ended session [sessionId=${sessionId}]`);
- }
- })();
-
- return { session: updatedSession ?? session, projectId: session.projectId, alreadyEnded: !updatedSession };
- };
-
- const terminateSessionById = async (sessionId: string, actor: OrgServiceActor) => {
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: session.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Terminate,
- ProjectPermissionSub.PamSessions
- );
-
- // No project lookup needed: getProjectPermission above throws NotFoundError if the
- // project doesn't exist, and session.projectId === project.id by definition.
- // Atomic update: only transitions active/starting → terminated
- const updatedSession = await pamSessionDAL.terminateSessionById(sessionId);
- if (!updatedSession) {
- return { session, projectId: session.projectId, alreadyEnded: true };
- }
-
- // Fire-and-forget AI summarization
- void (async () => {
- try {
- await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
- } catch (err) {
- logger.error({ sessionId, err }, `Failed to queue AI summary for terminated session [sessionId=${sessionId}]`);
- }
- })();
-
- // Fire-and-forget ALPN cancellation for gateway sessions
- if (session.gatewayId) {
- void (async () => {
- let relayConn: net.Socket | null = null;
- try {
- const user = await requestMemoize(requestMemoKeys.userFindById(actor.id), () => userDAL.findById(actor.id));
- const certs = await gatewayV2Service.getPAMConnectionDetails({
- gatewayId: session.gatewayId,
- sessionId,
- resourceType: session.resourceType as PamResource,
- // host/port are embedded in cert extensions for routing but not used for cancellation —
- // real values are encrypted in PamResource.encryptedConnectionDetails and not worth decrypting here
- host: "0.0.0.0",
- port: 0,
- actorMetadata: { id: actor.id, type: actor.type, name: user?.email ?? "" }
- });
- if (!certs) {
- logger.error(
- { sessionId, gatewayId: session.gatewayId },
- `Failed to get gateway [gatewayId=${session.gatewayId}] connection details for PAM session [sessionId=${sessionId}] termination`
- );
- return;
- }
- relayConn = await createRelayConnection({
- relayHost: certs.relayHost,
- clientCertificate: certs.relay.clientCertificate,
- clientPrivateKey: certs.relay.clientPrivateKey,
- serverCertificateChain: certs.relay.serverCertificateChain
- });
- const cancelConn = await createGatewayConnection(
- relayConn,
- certs.gateway,
- GatewayProxyProtocol.PamSessionCancellation
- );
- cancelConn.end();
- } catch (err) {
- logger.error(
- { sessionId, err },
- `Session [sessionId=${sessionId}] termination ALPN signal failed (best-effort)`
- );
- } finally {
- relayConn?.destroy();
- }
- })();
- }
-
- return { session: updatedSession, projectId: session.projectId, alreadyEnded: false };
- };
-
- const getSessionLogs = async (sessionId: string, offset: number, limit: number, actor: OrgServiceActor) => {
- const sessionFromDb = await pamSessionDAL.findById(sessionId);
- if (!sessionFromDb) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: sessionFromDb.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamSessionActions.Read,
- ProjectPermissionSub.PamSessions
- );
-
- // Fetch one extra to determine whether another page exists
- const batches = await pamSessionEventBatchDAL.findBySessionIdPaginated(sessionId, {
- offset,
- limit: limit + 1
- });
-
- if (batches.length > 0 || offset > 0) {
- // Batch-based session
- const hasMore = batches.length > limit;
- const pageBatches = hasMore ? batches.slice(0, limit) : batches;
- const logs = pageBatches.length > 0 ? await decryptBatches(pageBatches, sessionFromDb.projectId, kmsService) : [];
- return { logs, hasMore, batchCount: pageBatches.length };
- }
-
- // Legacy blob-based session — bounded by Fastify body limit on upload
- if (sessionFromDb.encryptedLogsBlob) {
- const logs = await decryptSessionCommandLogs({
- projectId: sessionFromDb.projectId,
- encryptedLogs: sessionFromDb.encryptedLogsBlob,
- kmsService
- });
- return { logs, hasMore: false, batchCount: 0 };
- }
-
- return { logs: [], hasMore: false, batchCount: 0 };
- };
-
- const uploadEventBatch = async ({ sessionId, startOffset, events }: TUploadEventBatchDTO, actor: OrgServiceActor) => {
- // To be hit by gateways only (identity-based or enrollment-flow)
- if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {
- throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });
- }
-
- const session = await pamSessionDAL.findById(sessionId);
- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
-
- const project = await requestMemoize(requestMemoKeys.projectFindById(session.projectId), () =>
- projectDAL.findById(session.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });
-
- if (actor.type === ActorType.IDENTITY) {
- const { permission } = await permissionService.getOrgPermission({
- actor: actor.type,
- actorId: actor.id,
- orgId: project.orgId,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- scope: OrganizationActionScope.Any
- });
-
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.CreateGateways,
- OrgPermissionSubjects.Gateway
- );
- } else if (actor.type === ActorType.GATEWAY) {
- if (project.orgId !== actor.orgId) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to this session" });
- }
- }
-
- const authorized =
- actor.type === ActorType.GATEWAY
- ? !session.gatewayId || session.gatewayId === actor.id
- : !session.gatewayIdentityId || session.gatewayIdentityId === actor.id;
- if (!authorized) {
- throw new ForbiddenRequestError({ message: "Gateway does not have access to upload events for this session" });
- }
-
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.SecretManager,
- projectId: session.projectId
- });
-
- const { cipherTextBlob } = encryptor({ plainText: events });
-
- const { wasInserted } = await pamSessionEventBatchDAL.upsertBatch(sessionId, startOffset, cipherTextBlob);
-
- return { projectId: session.projectId, wasInserted };
- };
-
- return { getById, list, getSessionLogs, updateLogsById, endSessionById, terminateSessionById, uploadEventBatch };
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-summary-fns.ts b/backend/src/ee/services/pam-session/pam-session-summary-fns.ts
deleted file mode 100644
index 30ce6aad36..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-summary-fns.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { createAnthropic } from "@ai-sdk/anthropic";
-import { generateObject } from "ai";
-import { z } from "zod";
-
-import { PamResource } from "../pam-resource/pam-resource-enums";
-import { TPamSessionCommandLog, TSessionEvent } from "./pam-session-types";
-
-export const MAX_LOG_CHARS = 200_000; // rough guard before sending to LLM
-
-export const formatLogsForSummary = (
- logs: (TPamSessionCommandLog | TSessionEvent)[],
- resourceType: PamResource
-): string => {
- if (resourceType === PamResource.Postgres) {
- const sqlLogs = logs as TPamSessionCommandLog[];
- const lines = sqlLogs.map((log, i) => {
- const ts = new Date(log.timestamp).toISOString();
- return `[${i + 1}] [${ts}]\nQuery: ${log.input.trim()}\nResult: ${log.output.trim()}`;
- });
- return lines.join("\n\n");
- }
-
- // SSH: extract input events and decode Base64 → printable text
- const terminalLogs = logs as TSessionEvent[];
- const inputLines: string[] = [];
- for (const event of terminalLogs.filter((e) => e.eventType === "input")) {
- try {
- const decoded = Buffer.from(event.data, "base64").toString("utf8");
- // Strip ANSI escape codes first, then apply backspace/DEL line-editing semantics
- // so that characters the user erased are not sent to the AI
- // eslint-disable-next-line no-control-regex
- const noAnsi = decoded.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
- let edited = "";
- for (const ch of noAnsi) {
- if (ch === "\x08" || ch === "\x7f") {
- edited = edited.slice(0, -1);
- } else {
- edited += ch;
- }
- }
- // eslint-disable-next-line no-control-regex
- const cleaned = edited.replace(/[^\x20-\x7e\t\n\r]/g, "");
- if (cleaned.trim()) inputLines.push(cleaned);
- } catch {
- // skip malformed base64
- }
- }
- return inputLines.join("");
-};
-
-const SYSTEM_PROMPTS: Partial<Record<PamResource, string>> = {
- [PamResource.Postgres]: `You are a security analyst reviewing a privileged access session on a PostgreSQL database.
-The session was initiated through a data explorer tool that automatically runs queries to enumerate tables and inspect schema metadata on startup — these auto-generated queries are normal and expected. Do not flag them.
-
-Write a concise summary of what the user actually did. Focus on meaningful actions: DML writes (INSERT/UPDATE/DELETE), DDL changes (CREATE/DROP/ALTER), stored procedure or function modifications, and privilege changes (GRANT/REVOKE).
-
-Only add a warning for actions that are clearly destructive or suspicious — for example: bulk or unconditional DELETE/UPDATE, DROP TABLE/DATABASE, TRUNCATE, privilege escalation, or writes to sensitive system tables. Do NOT warn about SELECT queries, schema inspection, pg_catalog or information_schema reads, or any other read-only operations regardless of their scope.
-
-Populate "summary" with a high-level overview (2-4 sentences) of the user's intent and the overall nature of their activity — not a chronological list of events. Write it as if explaining to a security team what the user was trying to accomplish, grouping related actions together. Populate "warnings" with objects containing "text" (≤ 20 words describing the concern) and "logIndex" (the 1-based index number shown in brackets at the start of the relevant log entry) for clearly destructive or suspicious write/modification actions only; leave it empty if none.`,
-
- [PamResource.SSH]: `You are a security analyst reviewing a privileged access session on an SSH server.
-Only add a warning for actions that are clearly destructive or suspicious — for example: deleting files or directories (rm -rf), killing processes (kill/pkill), privilege escalation (sudo su, passwd), exfiltrating data (curl/wget to external hosts, nc), modifying system files (chmod/chown on sensitive paths), or installing/removing software. Do NOT warn about routine read-only commands (ls, cat, grep, ps, top, df, etc.) or typical developer/admin operations unless they target clearly sensitive paths.
-
-Populate "summary" with a high-level overview (2-4 sentences) of the user's intent and the overall nature of their activity — not a chronological list of events. Write it as if explaining to a security team what the user was trying to accomplish, grouping related actions together. Populate "warnings" with objects containing "text" (≤ 20 words describing the concern) for clearly destructive or suspicious actions only; omit "logIndex" for all warnings; leave warnings empty if none.`
-};
-
-export const buildSummaryPrompt = ({
- resourceType,
- resourceName,
- actorName,
- actorEmail,
- durationSeconds,
- formattedLogs
-}: {
- resourceType: PamResource;
- resourceName: string;
- actorName: string;
- actorEmail: string;
- durationSeconds: number;
- formattedLogs: string;
-}): { system: string; user: string } => {
- const system = SYSTEM_PROMPTS[resourceType];
- if (!system) throw new Error(`No AI summary prompt defined for resource type: ${resourceType}`);
-
- const user = `Session metadata:
-- Resource: ${resourceName} (${resourceType})
-- Actor: ${actorName} <${actorEmail}>
-- Duration: ${Math.round(durationSeconds)}s
-
-Session logs:
-<formattedLogs>
-${formattedLogs}
-</formattedLogs>`;
-
- return { system, user };
-};
-
-const SessionSummarySchema = z.object({
- summary: z.string(),
- warnings: z.array(
- z.object({
- text: z.string(),
- logIndex: z.number().int().optional()
- })
- )
-});
-
-export const generateSessionSummary = async (
- apiKey: string,
- model: string,
- system: string,
- user: string
-): Promise<{ summary: string; warnings: { text: string; logIndex?: number }[] }> => {
- const anthropic = createAnthropic({ apiKey });
-
- const { object } = await generateObject({
- model: anthropic(model),
- schema: SessionSummarySchema,
- system,
- messages: [{ role: "user", content: user }],
- maxOutputTokens: 1024
- });
-
- return object;
-};
diff --git a/backend/src/ee/services/pam-session/pam-session-types.ts b/backend/src/ee/services/pam-session/pam-session-types.ts
deleted file mode 100644
index 99fe54b746..0000000000
--- a/backend/src/ee/services/pam-session/pam-session-types.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { z } from "zod";
-
-import {
- HttpEventSchema,
- PamSessionCommandLogSchema,
- SanitizedSessionSchema,
- SessionEventSchema
-} from "./pam-session-schemas";
-
-export type TPamSessionCommandLog = z.infer<typeof PamSessionCommandLogSchema>;
-export type TSessionEvent = z.infer<typeof SessionEventSchema>;
-export type THttpEvent = z.infer<typeof HttpEventSchema>;
-export type TPamSanitizedSession = z.infer<typeof SanitizedSessionSchema>;
-
-// DTOs
-export type TUpdateSessionLogsDTO = {
- sessionId: string;
- logs: (TPamSessionCommandLog | TSessionEvent | THttpEvent)[];
-};
-
-export type TUploadEventBatchDTO = {
- sessionId: string;
- startOffset: number;
- events: Buffer;
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts b/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts
deleted file mode 100644
index 88f3ce9c34..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-import { parse as parseSql } from "libpg-query";
-import pg from "pg";
-import Cursor from "pg-cursor";
-
-import { logger } from "@app/lib/logger";
-
-import { getTableDetailQuery } from "./pam-postgres-data-explorer-metadata";
-import {
- PostgresClientMessageType,
- PostgresServerMessageType,
- type TPostgresClientMessage,
- type TPostgresCorrelatedServerMessage
-} from "./pam-postgres-ws-types";
-
-type ControllerParams = {
- relayPort: number;
- username: string;
- database: string;
- sessionId: string;
- connectionId: string;
- sendResponse: (msg: TPostgresCorrelatedServerMessage) => void;
- onUnexpectedTermination: (reason: string) => void;
-};
-
-// Tab-scoped messages the controller handles. Metadata (get-schemas, get-tables)
-// and lifecycle messages are handled at the multiplexer layer.
-type TTabScopedMessage = Extract<
- TPostgresClientMessage,
- {
- type: PostgresClientMessageType.GetTableDetail | PostgresClientMessageType.Query | PostgresClientMessageType.Cancel;
- }
->;
-
-export type TPostgresConnectionController = {
- connectionId: string;
- backendPid: number | null;
- handleMessage: (msg: TTabScopedMessage) => void;
- dispose: () => void;
- isDisposing: () => boolean;
-};
-
-// Type parser shared between the pg.Client and pg-cursor instances so all
-// results — whether fetched via the simple query path or cursor — apply the
-// same normalisation rules.
-const pgTypes = {
- getTypeParser: (oid: number) => {
- // Boolean (OID 16): Postgres wire protocol sends 't'/'f' — expand to 'true'/'false'
- // so the Data Explorer UI displays human-readable literals.
- if (oid === 16)
- return (val: string | Buffer) => {
- const raw = typeof val === "string" ? val : val.toString("utf8");
- return raw === "t" ? "true" : "false";
- };
- return (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"));
- }
-};
-
-export const createPostgresConnectionController = async (
- params: ControllerParams
-): Promise<TPostgresConnectionController> => {
- const { relayPort, username, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;
-
- const pgClient = new pg.Client({
- host: "localhost",
- port: relayPort,
- user: username,
- database,
- password: "",
- ssl: false,
- connectionTimeoutMillis: 30_000,
- statement_timeout: 30_000,
- types: pgTypes
- });
-
- await pgClient.connect();
-
- const { rows: pidRows } = await pgClient.query<{ pid: number }>("SELECT pg_backend_pid() AS pid");
- const backendPid = pidRows[0]?.pid ?? null;
-
- // Server-side transaction state — updated after every query so the client
- // always receives the authoritative value, including for multi-statement SQL.
- let isInTransaction = false;
- let disposing = false;
-
- const sendQueryError = async (id: string, err: unknown) => {
- const pgErr = err as { message?: string; detail?: string; hint?: string };
-
- // If the failed query was inside a transaction, roll back so the
- // connection is not stuck in an aborted transaction state.
- try {
- await pgClient.query("ROLLBACK");
- } catch {
- // ROLLBACK fails if there was no active transaction — safe to ignore.
- }
-
- isInTransaction = false;
-
- sendResponse({
- type: PostgresServerMessageType.Error,
- id,
- connectionId,
- transactionOpen: false,
- error: pgErr.message ?? "Query execution failed",
- detail: pgErr.detail,
- hint: pgErr.hint
- });
- };
-
- // Cancel the currently running query via pg_cancel_backend.
- // Runs on a separate connection so it is not blocked by the sequential queue.
- const cancelRunningQuery = async () => {
- if (!backendPid) return;
- const cancelClient = new pg.Client({
- host: "localhost",
- port: relayPort,
- user: username,
- database,
- password: "",
- ssl: false,
- connectionTimeoutMillis: 5_000
- });
- // pg.Client is an EventEmitter; an unhandled 'error' would throw and
- // crash the Node process. Attach a no-op listener.
- cancelClient.on("error", (err) => {
- logger.debug(err, `Cancel client error [sessionId=${sessionId}] [connectionId=${connectionId}]`);
- });
- try {
- await cancelClient.connect();
- await cancelClient.query("SELECT pg_cancel_backend($1)", [backendPid]);
- } catch (err) {
- logger.debug(err, `Failed to cancel backend query [sessionId=${sessionId}] [connectionId=${connectionId}]`);
- } finally {
- await cancelClient.end().catch(() => {});
- }
- };
-
- // Sequential message processing to prevent concurrent query issues on the
- // same pg.Client. Each controller has its own queue.
- let processingPromise: Promise<void> = Promise.resolve();
-
- const handleMessage = (message: TTabScopedMessage) => {
- // Cancel is handled immediately outside the sequential queue so it can
- // interrupt a running query rather than waiting behind it.
- if (message.type === PostgresClientMessageType.Cancel) {
- if (disposing) return;
- void cancelRunningQuery();
- return;
- }
-
- processingPromise = processingPromise
- .then(async () => {
- if (disposing) return;
-
- switch (message.type) {
- case PostgresClientMessageType.GetTableDetail: {
- try {
- const query = getTableDetailQuery(message.schema, message.table);
- const result = await pgClient.query<{ result: string }>(query.text, query.values);
- const rawDetail = result.rows[0]?.result;
- if (!rawDetail) {
- sendResponse({
- type: PostgresServerMessageType.Error,
- id: message.id,
- connectionId,
- transactionOpen: isInTransaction,
- error: "Table not found or no metadata available"
- });
- break;
- }
- const detail =
- typeof rawDetail === "string"
- ? (JSON.parse(rawDetail) as Record<string, unknown>)
- : (rawDetail as unknown as Record<string, unknown>);
- sendResponse({
- type: PostgresServerMessageType.TableDetail,
- id: message.id,
- connectionId,
- transactionOpen: isInTransaction,
- data: detail as {
- columns: {
- name: string;
- type: string;
- nullable: boolean;
- identityGeneration: string | null;
- }[];
- primaryKeys: string[];
- foreignKeys: {
- constraintName: string;
- columns: string[];
- targetSchema: string;
- targetTable: string;
- targetColumns: string[];
- }[];
- }
- });
- } catch (err) {
- await sendQueryError(message.id, err);
- }
- break;
- }
-
- case PostgresClientMessageType.Query: {
- try {
- const startTime = performance.now();
- const MAX_ROWS = 1000;
-
- // Split the SQL into individual statements using the real PostgreSQL C parser
- // (via libpg-query WASM). Each statement is then run through a pg-cursor with
- // an explicit row cap — the server sends at most MAX_ROWS+1 rows at the wire
- // level regardless of result set size, so memory usage is bounded.
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- const parsed = await parseSql(message.sql);
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- const stmtTexts = (parsed.stmts as Array<{ stmt_location?: number; stmt_len?: number }>).map((s) => {
- const location = s.stmt_location ?? 0;
- return s.stmt_len !== undefined
- ? message.sql.slice(location, location + s.stmt_len)
- : message.sql.slice(location).trim();
- });
-
- let lastRows: Record<string, unknown>[] = [];
- let lastFields: { name: string }[] = [];
- let lastRowCount: number | null = null;
- let lastCommand = "";
- let lastIsTruncated = false;
-
- for (const stmtSql of stmtTexts) {
- const cursor = pgClient.query(new Cursor(stmtSql.trim(), null, { types: pgTypes }));
- // eslint-disable-next-line no-await-in-loop
- const stmtRows = await cursor.read(MAX_ROWS + 1);
- const stmtIsTruncated = stmtRows.length > MAX_ROWS;
- if (stmtIsTruncated) stmtRows.splice(MAX_ROWS);
- // eslint-disable-next-line no-await-in-loop
- await cursor.close();
-
- // eslint-disable-next-line no-underscore-dangle
- const cursorResult = cursor._result;
- const cmd = (cursorResult.command ?? "").toUpperCase();
- if (cmd === "BEGIN" || cmd === "START") isInTransaction = true;
- if (cmd === "COMMIT" || cmd === "ROLLBACK") isInTransaction = false;
-
- lastRows = stmtRows;
- lastFields = (cursorResult.fields ?? []).map((f) => ({ name: f.name }));
- lastRowCount = cursorResult.rowCount;
- lastCommand = cursorResult.command ?? "";
- lastIsTruncated = stmtIsTruncated;
- }
-
- const executionTimeMs = Math.round(performance.now() - startTime);
- sendResponse({
- type: PostgresServerMessageType.QueryResult,
- id: message.id,
- connectionId,
- rows: lastRows,
- fields: lastFields,
- rowCount: lastRowCount,
- isTruncated: lastIsTruncated,
- transactionOpen: isInTransaction,
- command: lastCommand,
- executionTimeMs
- });
- } catch (err) {
- await sendQueryError(message.id, err);
- }
- break;
- }
-
- default:
- break;
- }
- })
- .catch((err) => {
- logger.error(err, `Error processing Postgres message [sessionId=${sessionId}] [connectionId=${connectionId}]`);
- });
- };
-
- // Server-initiated termination — pg.Client errors outside clean dispose.
- pgClient.on("error", (err) => {
- if (disposing) return;
- logger.error(err, `Tab connection error [sessionId=${sessionId}] [connectionId=${connectionId}]`);
- disposing = true;
- onUnexpectedTermination(err.message || "Database connection error");
- });
-
- pgClient.on("end", () => {
- if (disposing) return;
- disposing = true;
- onUnexpectedTermination("Database connection ended");
- });
-
- const dispose = () => {
- if (disposing) return;
- disposing = true;
- // Fire-and-forget: Postgres auto-rollbacks uncommitted txns on socket close
- // and cleans up backend PIDs when it next tries to write. No explicit
- // ROLLBACK needed — keeps dispose synchronous from the caller's view.
- void pgClient.end().catch((err) => {
- logger.debug(err, `Error closing pg client [sessionId=${sessionId}] [connectionId=${connectionId}]`);
- });
- };
-
- return {
- connectionId,
- backendPid,
- handleMessage,
- dispose,
- isDisposing: () => disposing
- };
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.ts
deleted file mode 100644
index 3a133db804..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, expect, test } from "vitest";
-
-import { getSchemasQuery, getTableDetailQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";
-
-describe("getSchemasQuery", () => {
- test("returns SQL with no parameters", () => {
- const query = getSchemasQuery();
- expect(query.text).toContain("pg_namespace");
- expect(query.text).toContain("pg_catalog");
- expect(query.text).toContain("information_schema");
- expect(query.values).toEqual([]);
- });
-
- test("excludes system schemas", () => {
- const query = getSchemasQuery();
- expect(query.text).toContain("pg_toast");
- expect(query.text).toContain("pg_temp_");
- });
-});
-
-describe("getTablesQuery", () => {
- test("returns parameterized query for schema", () => {
- const query = getTablesQuery("public");
- expect(query.values).toEqual(["public"]);
- expect(query.text).toContain("$1");
- expect(query.text).toContain("pg_class");
- expect(query.text).toContain("relkind");
- });
-
- test("includes table type mapping", () => {
- const query = getTablesQuery("myschema");
- expect(query.text).toContain("'table'");
- expect(query.text).toContain("'view'");
- expect(query.text).toContain("'materialized_view'");
- });
-});
-
-describe("getTableDetailQuery", () => {
- test("returns parameterized query for schema and table", () => {
- const query = getTableDetailQuery("public", "users");
- expect(query.values).toEqual(["public", "users"]);
- expect(query.text).toContain("$1");
- expect(query.text).toContain("$2");
- });
-
- test("queries columns from pg_attribute", () => {
- const query = getTableDetailQuery("public", "users");
- expect(query.text).toContain("pg_attribute");
- expect(query.text).toContain("pg_type");
- });
-
- test("queries primary keys from pg_constraint", () => {
- const query = getTableDetailQuery("public", "users");
- expect(query.text).toContain("contype = 'p'");
- });
-
- test("queries foreign keys from pg_constraint", () => {
- const query = getTableDetailQuery("public", "users");
- expect(query.text).toContain("contype = 'f'");
- });
-
- test("returns JSON result", () => {
- const query = getTableDetailQuery("public", "users");
- expect(query.text).toContain("json_build_object");
- expect(query.text).toContain("'columns'");
- expect(query.text).toContain("'primaryKeys'");
- expect(query.text).toContain("'foreignKeys'");
- });
-});
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts
deleted file mode 100644
index 0945dc9dfc..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-data-explorer-metadata.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-// System catalog SQL queries for the Postgres Data Explorer.
-// All queries use parameterized inputs ($1, $2) — no string interpolation.
-
-export const getSchemasQuery = () => ({
- text: `
- SELECT nspname AS name
- FROM pg_namespace
- WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
- AND nspname NOT LIKE 'pg_temp_%'
- AND nspname NOT LIKE 'pg_toast_temp_%'
- ORDER BY nspname
- `,
- values: [] as string[]
-});
-
-export const getTablesQuery = (schema: string) => ({
- text: `
- SELECT
- c.relname AS name,
- CASE c.relkind
- WHEN 'r' THEN 'table'
- WHEN 'v' THEN 'view'
- WHEN 'm' THEN 'materialized_view'
- WHEN 'f' THEN 'foreign_table'
- WHEN 'p' THEN 'partitioned_table'
- ELSE 'other'
- END AS "tableType"
- FROM pg_class c
- JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE n.nspname = $1
- AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
- ORDER BY c.relname
- `,
- values: [schema]
-});
-
-export const getTableDetailQuery = (schema: string, table: string) => ({
- // Returns a JSON object with columns and primaryKeys
- text: `
- WITH target AS (
- SELECT c.oid AS table_oid
- FROM pg_class c
- JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE n.nspname = $1 AND c.relname = $2
- ),
- cols AS (
- SELECT json_agg(
- json_build_object(
- 'name', a.attname,
- 'type', CASE WHEN a.attndims > 0 OR t.typelem != 0 AND t.typlen = -1
- THEN (SELECT bt.typname FROM pg_type bt WHERE bt.oid = t.typelem) || '[]'
- ELSE t.typname END,
- -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values
- -- 'typeOid', a.atttypid,
- 'nullable', NOT a.attnotnull,
- -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values
- -- 'defaultValue', pg_get_expr(d.adbin, d.adrelid),
- -- 'isIdentity', a.attidentity != '',
- 'identityGeneration', CASE a.attidentity
- WHEN 'a' THEN 'ALWAYS'
- WHEN 'd' THEN 'BY DEFAULT'
- ELSE null END
- -- Left commented out so the query doesn't have to be modified if the UI ever needs these standard catalog values
- -- 'isArray', a.attndims > 0 OR (t.typelem != 0 AND t.typlen = -1),
- -- 'maxLength', CASE WHEN a.atttypmod > 0 THEN a.atttypmod - 4 ELSE null END
- ) ORDER BY a.attnum
- ) AS data
- FROM pg_attribute a
- JOIN target ON a.attrelid = target.table_oid
- JOIN pg_type t ON t.oid = a.atttypid
- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
- WHERE a.attnum > 0 AND NOT a.attisdropped
- ),
- pks AS (
- SELECT json_agg(a.attname ORDER BY arr.pos) AS data
- FROM pg_constraint con
- JOIN target ON con.conrelid = target.table_oid
- CROSS JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)
- JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum
- WHERE con.contype = 'p'
- ),
- fks AS (
- SELECT json_agg(
- json_build_object(
- 'constraintName', con.conname,
- 'columns', (
- SELECT json_agg(a.attname ORDER BY arr.pos)
- FROM unnest(con.conkey) WITH ORDINALITY AS arr(attnum, pos)
- JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = arr.attnum
- ),
- 'targetSchema', tn.nspname,
- 'targetTable', tc.relname,
- 'targetColumns', (
- SELECT json_agg(a.attname ORDER BY arr.pos)
- FROM unnest(con.confkey) WITH ORDINALITY AS arr(attnum, pos)
- JOIN pg_attribute a ON a.attrelid = con.confrelid AND a.attnum = arr.attnum
- )
- )
- ) AS data
- FROM pg_constraint con
- JOIN target ON con.conrelid = target.table_oid
- JOIN pg_class tc ON tc.oid = con.confrelid
- JOIN pg_namespace tn ON tn.oid = tc.relnamespace
- WHERE con.contype = 'f'
- )
- -- enum_vals AS (
- -- SELECT json_object_agg(
- -- t.typname,
- -- (SELECT json_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid = t.oid)
- -- ) AS data
- -- FROM pg_attribute a
- -- JOIN target ON a.attrelid = target.table_oid
- -- JOIN pg_type t ON t.oid = a.atttypid
- -- WHERE a.attnum > 0
- -- AND NOT a.attisdropped
- -- AND t.typtype = 'e'
- -- )
- SELECT json_build_object(
- 'columns', COALESCE(cols.data, '[]'::json),
- 'primaryKeys', COALESCE(pks.data, '[]'::json),
- 'foreignKeys', COALESCE(fks.data, '[]'::json)
- -- TODO: re-enable when UI needs these
- -- 'enums', COALESCE(enum_vals.data, '{}'::json)
- ) AS result
- FROM cols, pks, fks
- `,
- values: [schema, table]
-});
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts
deleted file mode 100644
index 90ac171b82..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import pg from "pg";
-
-import { logger } from "@app/lib/logger";
-
-import { getSchemasQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";
-
-// Shared connection options for one-shot metadata queries. Each call opens a
-// fresh pg.Client, runs one query, then disposes — no persistent BE state.
-type OneShotOptions = {
- relayPort: number;
- username: string;
- database: string;
-};
-
-const buildClient = ({ relayPort, username, database }: OneShotOptions): pg.Client => {
- const client = new pg.Client({
- host: "localhost",
- port: relayPort,
- user: username,
- database,
- password: "",
- ssl: false,
- connectionTimeoutMillis: 10_000,
- statement_timeout: 30_000
- });
- // pg.Client is an EventEmitter; an unhandled 'error' (e.g. mid-query socket
- // reset) would throw and crash the Node process. Attach a no-op listener.
- client.on("error", (err) => {
- logger.debug(err, "one-shot pg client error");
- });
- return client;
-};
-
-const withClient = async <T>(opts: OneShotOptions, fn: (client: pg.Client) => Promise<T>): Promise<T> => {
- const client = buildClient(opts);
- await client.connect();
- try {
- return await fn(client);
- } finally {
- await client.end().catch(() => {});
- }
-};
-
-export const fetchSchemasOneShot = (opts: OneShotOptions): Promise<{ name: string }[]> =>
- withClient(opts, async (client) => {
- const query = getSchemasQuery();
- const result = await client.query<{ name: string }>(query.text, query.values);
- return result.rows;
- });
-
-export const fetchTablesOneShot = (
- opts: OneShotOptions,
- schema: string
-): Promise<{ name: string; tableType: string }[]> =>
- withClient(opts, async (client) => {
- const query = getTablesQuery(schema);
- const result = await client.query<{ name: string; tableType: string }>(query.text, query.values);
- return result.rows;
- });
-
-// Called once at WS setup to fail fast if credentials or tunnel are broken —
-// preserves the early "Connection error" UX we used to get from pgClient.connect().
-export const verifyReachabilityOneShot = (opts: OneShotOptions): Promise<void> =>
- withClient(opts, async (client) => {
- await client.query("SELECT 1");
- });
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts
deleted file mode 100644
index ceb3125a61..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts
+++ /dev/null
@@ -1,477 +0,0 @@
-/* eslint-disable @typescript-eslint/no-unsafe-member-access */
-/* eslint-disable @typescript-eslint/no-unsafe-assignment */
-/* eslint-disable @typescript-eslint/no-unsafe-call */
-/* eslint-disable @typescript-eslint/no-unsafe-argument */
-/* eslint-disable @typescript-eslint/unbound-method */
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import type WebSocket from "ws";
-
-import { PostgresClientMessageType, PostgresServerMessageType } from "./pam-postgres-ws-types";
-import { TerminalServerMessageType, type TSessionContext, type TWebSocketServerMessage } from "./pam-web-access-types";
-
-vi.mock("@app/lib/logger", () => ({
- logger: {
- info: vi.fn(),
- error: vi.fn(),
- debug: vi.fn(),
- warn: vi.fn()
- }
-}));
-
-// Per-client script lets individual tests stub behaviour for the Nth pg.Client
-// that gets constructed. Useful for simulating mid-life failures, differing
-// backend PIDs across tab controllers, etc.
-type ClientScript = {
- connect?: () => Promise<void>;
- query?: (text: string, values?: unknown[]) => Promise<any>;
- end?: () => Promise<void>;
-};
-
-const clientScripts: ClientScript[] = [];
-const createdClients: MockPgClient[] = [];
-
-type MockPgClient = {
- query: ReturnType<typeof vi.fn>;
- connect: ReturnType<typeof vi.fn>;
- end: ReturnType<typeof vi.fn>;
- on: ReturnType<typeof vi.fn>;
- emit: (event: string, ...args: unknown[]) => void;
- _listeners: Record<string, Array<(...args: unknown[]) => void>>;
-};
-
-vi.mock("pg", () => {
- const makeClient = (): MockPgClient => {
- const script = clientScripts.shift() ?? {};
- const defaultQuery = vi.fn(async (text: string) => {
- if (text.includes("pg_backend_pid")) return { rows: [{ pid: 1000 + createdClients.length }] };
- return { rows: [] };
- });
- const listeners: Record<string, Array<(...args: unknown[]) => void>> = {};
- const client: MockPgClient = {
- query: vi.fn(script.query ?? defaultQuery),
- connect: vi.fn(script.connect ?? (async () => {})),
- end: vi.fn(script.end ?? (async () => {})),
- on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
- listeners[event] = listeners[event] || [];
- listeners[event].push(cb);
- }),
- emit: (event: string, ...args: unknown[]) => {
- (listeners[event] || []).forEach((cb) => cb(...args));
- },
- _listeners: listeners
- };
- createdClients.push(client);
- return client;
- };
-
- return {
- default: {
- Client: vi.fn(() => makeClient())
- }
- };
-});
-
-// eslint-disable-next-line import/first
-import pg from "pg";
-
-// eslint-disable-next-line import/first
-import { handlePostgresSession } from "./pam-postgres-session-handler";
-
-function resetMockState() {
- clientScripts.length = 0;
- createdClients.length = 0;
- (pg.Client as unknown as { mockClear: () => void }).mockClear();
-}
-
-function createMockContext(): TSessionContext & { sentMessages: TWebSocketServerMessage[] } {
- const sentMessages: TWebSocketServerMessage[] = [];
- return {
- socket: {
- on: vi.fn(),
- close: vi.fn(),
- readyState: 1,
- OPEN: 1,
- send: vi.fn()
- } as unknown as WebSocket,
- relayPort: 5432,
- resourceName: "test-db",
- sessionId: "test-session",
- sendMessage: vi.fn((msg: TWebSocketServerMessage) => {
- sentMessages.push(msg);
- }),
- sendSessionEnd: vi.fn(),
- isNearSessionExpiry: vi.fn().mockReturnValue(false),
- onCleanup: vi.fn(),
- earlyMessages: [],
- releaseEarlyBuffer: vi.fn(),
- sentMessages
- };
-}
-
-const mockParams = {
- connectionDetails: { database: "testdb", host: "localhost", port: 5432 },
- credentials: { username: "testuser" }
-} as Parameters<typeof handlePostgresSession>[1];
-
-function getMessageHandler(ctx: TSessionContext): (data: Buffer) => void {
- const messageCall = (ctx.socket.on as ReturnType<typeof vi.fn>).mock.calls.find(
- ([event]: string[]) => event === "message"
- );
- return messageCall![1] as (data: Buffer) => void;
-}
-
-function getSentResponses(ctx: TSessionContext): any[] {
- const send = ctx.socket.send as unknown as ReturnType<typeof vi.fn>;
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
- return send.mock.calls.map(([raw]) => JSON.parse(raw as string));
-}
-
-async function openConnection(ctx: TSessionContext, id = "11111111-1111-1111-1111-111111111111"): Promise<string> {
- const onMessage = getMessageHandler(ctx);
- onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id })));
- // Let microtasks settle for the async open flow.
- await new Promise<void>((resolve) => {
- setTimeout(resolve, 10);
- });
- const resp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.ConnectionOpened && r.id === id);
- if (!resp) throw new Error("open-connection did not ack");
- return resp.connectionId as string;
-}
-
-describe("handlePostgresSession", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetMockState();
- });
-
- test("sends ready after reachability check succeeds", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- expect(ctx.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ type: TerminalServerMessageType.Ready }));
- // Reachability check — one short-lived client.
- expect(pg.Client).toHaveBeenCalledTimes(1);
- });
-
- test("throws when reachability check fails so the service catch block handles cleanup", async () => {
- clientScripts.push({
- connect: async () => {
- throw new Error("connection refused");
- }
- });
- const ctx = createMockContext();
-
- await expect(handlePostgresSession(ctx, mockParams)).rejects.toThrow("connection refused");
- expect(ctx.sendMessage).not.toHaveBeenCalledWith(
- expect.objectContaining({ type: TerminalServerMessageType.Ready })
- );
- });
-
- test("open-connection creates a controller and returns connectionId + backendPid", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const connectionId = await openConnection(ctx);
- expect(connectionId).toMatch(/[0-9a-f-]{36}/i);
- const resp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.ConnectionOpened);
- expect(resp.backendPid).toBeTypeOf("number");
- });
-
- test("get-schemas uses a short-lived client and works with no tab controllers", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- // Script a schemas query response on the next client created.
- clientScripts.push({
- query: vi.fn(async (text: string) => {
- if (text.includes("pg_namespace")) return { rows: [{ name: "public" }] };
- return { rows: [] };
- })
- });
-
- const onMessage = getMessageHandler(ctx);
- const reqId = "22222222-2222-2222-2222-222222222222";
- onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.GetSchemas, id: reqId })));
-
- await new Promise<void>((r) => {
- setTimeout(r, 20);
- });
-
- const responses = getSentResponses(ctx);
- const schemasResp = responses.find((r) => r.type === PostgresServerMessageType.Schemas && r.id === reqId);
- expect(schemasResp).toBeTruthy();
- expect(schemasResp.data).toEqual([{ name: "public" }]);
- });
-
- test("get-tables works while a tab controller is open", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
- await openConnection(ctx);
-
- clientScripts.push({
- query: vi.fn(async (text: string) => {
- if (text.includes("pg_class")) return { rows: [{ name: "users", tableType: "table" }] };
- return { rows: [] };
- })
- });
-
- const onMessage = getMessageHandler(ctx);
- const reqId = "33333333-3333-3333-3333-333333333333";
- onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.GetTables, id: reqId, schema: "public" })));
-
- await new Promise<void>((r) => {
- setTimeout(r, 20);
- });
- const tablesResp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Tables && r.id === reqId);
- expect(tablesResp).toBeTruthy();
- expect(tablesResp.data).toEqual([{ name: "users", tableType: "table" }]);
- });
-
- test("unknown connectionId on tab-scoped message returns 'Connection not found'", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const onMessage = getMessageHandler(ctx);
- const reqId = "44444444-4444-4444-4444-444444444444";
- onMessage(
- Buffer.from(
- JSON.stringify({
- type: PostgresClientMessageType.Query,
- id: reqId,
- connectionId: "99999999-9999-9999-9999-999999999999",
- sql: "SELECT 1"
- })
- )
- );
-
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- const err = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Error && r.id === reqId);
- expect(err).toBeTruthy();
- expect(err.error).toContain("Connection not found");
- });
-
- test("close-connection on unknown id is a silent no-op", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const onMessage = getMessageHandler(ctx);
- onMessage(
- Buffer.from(
- JSON.stringify({
- type: PostgresClientMessageType.CloseConnection,
- connectionId: "99999999-9999-9999-9999-999999999999"
- })
- )
- );
-
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- const responses = getSentResponses(ctx);
- // No response ever sent for close-connection.
- expect(responses.filter((r) => r.type === PostgresServerMessageType.ConnectionClosed)).toEqual([]);
- expect(responses.filter((r) => r.type === PostgresServerMessageType.Error)).toEqual([]);
- });
-
- test("cancel on unknown connectionId is a silent no-op", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const onMessage = getMessageHandler(ctx);
- onMessage(
- Buffer.from(
- JSON.stringify({
- type: PostgresClientMessageType.Cancel,
- connectionId: "99999999-9999-9999-9999-999999999999"
- })
- )
- );
-
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- expect(getSentResponses(ctx)).toEqual([]);
- });
-
- test("activity keepalive is accepted and emits no response", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const onMessage = getMessageHandler(ctx);
- onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.Activity })));
-
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- expect(getSentResponses(ctx)).toEqual([]);
- expect(ctx.sendSessionEnd).not.toHaveBeenCalled();
- });
-
- test("server-initiated controller death removes entry and emits connection-closed", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
- const connectionId = await openConnection(ctx);
-
- // Grab the tab controller's pg.Client (created after reachability client).
- const tabClient = createdClients[1];
- tabClient.emit("error", new Error("peer reset"));
-
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- const closedEvt = getSentResponses(ctx).find(
- (r) => r.type === PostgresServerMessageType.ConnectionClosed && r.connectionId === connectionId
- );
- expect(closedEvt).toBeTruthy();
- expect(closedEvt.reason).toBe("peer reset");
-
- // Subsequent tab-scoped message for the same id should now miss.
- const onMessage = getMessageHandler(ctx);
- const reqId = "55555555-5555-5555-5555-555555555555";
- onMessage(
- Buffer.from(
- JSON.stringify({
- type: PostgresClientMessageType.Query,
- id: reqId,
- connectionId,
- sql: "SELECT 1"
- })
- )
- );
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- const err = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Error && r.id === reqId);
- expect(err.error).toContain("Connection not found");
- });
-
- test("exceeding MAX_CONNECTIONS_PER_WS returns connection-open-failed", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- for (let i = 0; i < 20; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- await openConnection(ctx, `aaaaaaaa-aaaa-aaaa-aaaa-${String(i).padStart(12, "0")}`);
- }
-
- const onMessage = getMessageHandler(ctx);
- const overflowId = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
- onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id: overflowId })));
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
- const failed = getSentResponses(ctx).find(
- (r) => r.type === PostgresServerMessageType.ConnectionOpenFailed && r.id === overflowId
- );
- expect(failed).toBeTruthy();
- expect(failed.error).toContain("Maximum");
- });
-
- test("concurrent open-connection requests cannot bypass the cap", async () => {
- // Simulates a client firing 25 opens at once. Without null-slot
- // reservation, each check against controllers.size would see 0 before
- // any controller finished connecting, and all 25 would succeed.
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- const onMessage = getMessageHandler(ctx);
- const ATTEMPTS = 25;
- for (let i = 0; i < ATTEMPTS; i += 1) {
- onMessage(
- Buffer.from(
- JSON.stringify({
- type: PostgresClientMessageType.OpenConnection,
- id: `eeeeeeee-eeee-eeee-eeee-${String(i).padStart(12, "0")}`
- })
- )
- );
- }
-
- await new Promise<void>((r) => {
- setTimeout(r, 50);
- });
-
- const opened = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);
- const failed = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpenFailed);
- expect(opened.length).toBe(20);
- expect(failed.length).toBe(ATTEMPTS - 20);
- });
-
- test("cleanup disposes every controller", async () => {
- const ctx = createMockContext();
- const result = await handlePostgresSession(ctx, mockParams);
- await openConnection(ctx, "cccccccc-cccc-cccc-cccc-cccccccccccc");
- await openConnection(ctx, "dddddddd-dddd-dddd-dddd-dddddddddddd");
-
- const tabClients = createdClients.slice(1, 3);
-
- await result.cleanup();
-
- tabClients.forEach((c) => {
- expect(c.end).toHaveBeenCalled();
- });
- });
-
- test("in-flight opens self-dispose when cleanup runs before they resolve", async () => {
- const ctx = createMockContext();
- const result = await handlePostgresSession(ctx, mockParams);
-
- // Delay the pg.Client connect for the NEXT client created so the open is
- // still in flight when cleanup runs. Pushed AFTER handlePostgresSession so
- // the reachability client consumes a normal (instant) script.
- let resolveConnect!: () => void;
- clientScripts.push({
- connect: () =>
- new Promise<void>((resolve) => {
- resolveConnect = resolve;
- })
- });
-
- // Kick off an open — it will be stuck at pgClient.connect().
- const onMessage = getMessageHandler(ctx);
- onMessage(
- Buffer.from(
- JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id: "11111111-1111-1111-1111-111111111111" })
- )
- );
-
- // Let the synchronous part of openTabConnection run (reserves the null
- // slot), but the await hasn't resolved yet.
- await new Promise<void>((r) => {
- setTimeout(r, 10);
- });
-
- // Session tears down while the open is in flight.
- await result.cleanup();
-
- // Now let the connect resolve — the open should self-dispose.
- resolveConnect();
- await new Promise<void>((r) => {
- setTimeout(r, 50);
- });
-
- // The controller's pg.Client should have been disposed (end called).
- // The delayed client is the second one created (first is the reachability check).
- const delayedClient = createdClients[1];
- expect(delayedClient.end).toHaveBeenCalled();
-
- // No connection-opened should have been sent.
- const opened = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);
- expect(opened).toHaveLength(0);
- });
-
- test("two tab controllers have independent backendPids", async () => {
- const ctx = createMockContext();
- await handlePostgresSession(ctx, mockParams);
-
- await openConnection(ctx, "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee");
- await openConnection(ctx, "ffffffff-ffff-ffff-ffff-ffffffffffff");
-
- const opens = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);
- expect(opens).toHaveLength(2);
- expect(opens[0].backendPid).not.toBe(opens[1].backendPid);
- });
-});
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
deleted file mode 100644
index ec131509c4..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-import crypto from "crypto";
-
-import {
- TPostgresAccountCredentials,
- TPostgresResourceConnectionDetails
-} from "@app/ee/services/pam-resource/postgres/postgres-resource-types";
-import { logger } from "@app/lib/logger";
-
-import {
- createPostgresConnectionController,
- type TPostgresConnectionController
-} from "./pam-postgres-connection-controller";
-import { fetchSchemasOneShot, fetchTablesOneShot, verifyReachabilityOneShot } from "./pam-postgres-metadata";
-import {
- PostgresClientMessageSchema,
- PostgresClientMessageType,
- PostgresServerMessageType,
- type TPostgresCorrelatedServerMessage
-} from "./pam-postgres-ws-types";
-import { parseClientMessage } from "./pam-web-access-fns";
-import {
- SessionEndReason,
- TerminalServerMessageType,
- TSessionContext,
- TSessionHandlerResult
-} from "./pam-web-access-types";
-
-type TPostgresSessionParams = {
- connectionDetails: TPostgresResourceConnectionDetails;
- credentials: TPostgresAccountCredentials;
-};
-
-// Fan-out bound inside a single already-authenticated WS session.
-const MAX_CONNECTIONS_PER_WS = 20;
-
-// Unwrap a pg driver error into the shape our WS error responses expect.
-const toPgErrorFields = (err: unknown) => {
- const pgErr = err as { message?: string; detail?: string; hint?: string };
- return { message: pgErr.message, detail: pgErr.detail, hint: pgErr.hint };
-};
-
-export const handlePostgresSession = async (
- ctx: TSessionContext,
- params: TPostgresSessionParams
-): Promise<TSessionHandlerResult> => {
- const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, onCleanup } = ctx;
- const { connectionDetails, credentials } = params;
-
- const oneShotOpts = {
- relayPort,
- username: credentials.username,
- database: connectionDetails.database
- };
-
- await verifyReachabilityOneShot(oneShotOpts);
-
- sendMessage({
- type: TerminalServerMessageType.Ready,
- data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`
- });
-
- logger.info(`Postgres web access session established [sessionId=${sessionId}]`);
-
- const sendResponse = (msg: TPostgresCorrelatedServerMessage) => {
- try {
- if (socket.readyState === socket.OPEN) {
- socket.send(JSON.stringify(msg));
- }
- } catch (err) {
- logger.error(err, `Failed to send WebSocket message [sessionId=${sessionId}]`);
- }
- };
-
- // Null = slot reserved for an in-flight open; cleanup clears the map so
- // the open's post-await .has() check fails and it self-disposes.
- const controllers = new Map<string, TPostgresConnectionController | null>();
-
- // Metadata requests (get-schemas / get-tables) are processed outside any
- // controller queue so sidebar refreshes don't block tab work.
- let metadataPromise: Promise<void> = Promise.resolve();
-
- // --- Per-message handlers ---
-
- const openTabConnection = async (requestId: string) => {
- if (controllers.size >= MAX_CONNECTIONS_PER_WS) {
- sendResponse({
- type: PostgresServerMessageType.ConnectionOpenFailed,
- id: requestId,
- error: `Maximum ${MAX_CONNECTIONS_PER_WS} connections per session reached`
- });
- return;
- }
-
- const connectionId = crypto.randomUUID();
- controllers.set(connectionId, null);
- try {
- const controller = await createPostgresConnectionController({
- relayPort,
- username: credentials.username,
- database: connectionDetails.database,
- sessionId,
- connectionId,
- sendResponse,
- onUnexpectedTermination: (reason) => {
- if (!controllers.has(connectionId)) return;
- controllers.delete(connectionId);
- sendResponse({
- type: PostgresServerMessageType.ConnectionClosed,
- connectionId,
- reason
- });
- }
- });
- if (!controllers.has(connectionId)) {
- controller.dispose();
- return;
- }
- controllers.set(connectionId, controller);
- sendResponse({
- type: PostgresServerMessageType.ConnectionOpened,
- id: requestId,
- connectionId,
- backendPid: controller.backendPid
- });
- } catch (err) {
- controllers.delete(connectionId);
- const msg = err instanceof Error ? err.message : "Failed to open connection";
- logger.error(err, `Failed to open tab connection [sessionId=${sessionId}]`);
- sendResponse({
- type: PostgresServerMessageType.ConnectionOpenFailed,
- id: requestId,
- error: msg
- });
- }
- };
-
- // Queue a metadata fetch (schemas / tables) behind any in-flight metadata
- // call so one-shot pg.Clients don't pile up. Errors are normalised into
- // PostgresServerMessageType.Error responses tied to the request id.
- const queueMetadata = <T>(
- requestId: string,
- fetcher: () => Promise<T>,
- onSuccess: (rows: T) => TPostgresCorrelatedServerMessage,
- fallbackError: string
- ) => {
- metadataPromise = metadataPromise
- .then(async () => {
- try {
- const rows = await fetcher();
- sendResponse(onSuccess(rows));
- } catch (err) {
- const { message: errMsg, detail, hint } = toPgErrorFields(err);
- sendResponse({
- type: PostgresServerMessageType.Error,
- id: requestId,
- error: errMsg ?? fallbackError,
- detail,
- hint
- });
- }
- })
- .catch(() => {});
- };
-
- socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
- const message = parseClientMessage(rawData, PostgresClientMessageSchema);
- if (!message) return;
-
- switch (message.type) {
- case PostgresClientMessageType.Control: {
- if (message.data === "quit") {
- sendSessionEnd(SessionEndReason.UserQuit);
- onCleanup();
- socket.close();
- }
- break;
- }
-
- case PostgresClientMessageType.OpenConnection: {
- void openTabConnection(message.id);
- break;
- }
-
- case PostgresClientMessageType.CloseConnection: {
- const controller = controllers.get(message.connectionId);
- if (!controller) return;
- controllers.delete(message.connectionId);
- controller.dispose();
- break;
- }
-
- case PostgresClientMessageType.Cancel: {
- const controller = controllers.get(message.connectionId);
- if (!controller || controller.isDisposing()) {
- logger.debug(
- `Cancel on missing/disposing connection [sessionId=${sessionId}] [connectionId=${message.connectionId}]`
- );
- return;
- }
- controller.handleMessage(message);
- break;
- }
-
- case PostgresClientMessageType.GetSchemas: {
- queueMetadata(
- message.id,
- () => fetchSchemasOneShot(oneShotOpts),
- (rows) => ({ type: PostgresServerMessageType.Schemas, id: message.id, data: rows }),
- "Failed to fetch schemas"
- );
- break;
- }
-
- case PostgresClientMessageType.GetTables: {
- queueMetadata(
- message.id,
- () => fetchTablesOneShot(oneShotOpts, message.schema),
- (rows) => ({ type: PostgresServerMessageType.Tables, id: message.id, data: rows }),
- "Failed to fetch tables"
- );
- break;
- }
-
- case PostgresClientMessageType.GetTableDetail:
- case PostgresClientMessageType.Query: {
- const controller = controllers.get(message.connectionId);
- if (!controller || controller.isDisposing()) {
- sendResponse({
- type: PostgresServerMessageType.Error,
- id: message.id,
- connectionId: message.connectionId,
- error: "Connection not found"
- });
- return;
- }
- controller.handleMessage(message);
- break;
- }
-
- case PostgresClientMessageType.Activity: {
- // No-op. The idle timer is reset by the sibling socket.on("message")
- // listener in pam-web-access-service.ts — this branch just keeps the
- // discriminated-union exhaustive so the `default` arm stays unreachable.
- break;
- }
-
- default:
- break;
- }
- });
-
- return {
- cleanup: async () => {
- const snapshot = Array.from(controllers.values());
- controllers.clear();
- for (const controller of snapshot) {
- if (controller) {
- try {
- controller.dispose();
- } catch (err) {
- logger.debug(err, `Error disposing controller [sessionId=${sessionId}]`);
- }
- }
- }
- }
- };
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts
deleted file mode 100644
index 3877d8bbc1..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import { z } from "zod";
-
-export enum PostgresClientMessageType {
- Control = "control",
- GetSchemas = "get-schemas",
- GetTables = "get-tables",
- GetTableDetail = "get-table-detail",
- Query = "query",
- Cancel = "cancel",
- OpenConnection = "open-connection",
- CloseConnection = "close-connection",
- Activity = "activity"
-}
-
-export enum PostgresServerMessageType {
- Schemas = "schemas",
- Tables = "tables",
- TableDetail = "table-detail",
- QueryResult = "query-result",
- Error = "error",
- ConnectionOpened = "connection-opened",
- ConnectionOpenFailed = "connection-open-failed",
- ConnectionClosed = "connection-closed"
-}
-
-// --- Shared bases ---
-
-const CorrelatedBaseSchema = z.object({ id: z.string().uuid() });
-const TabScopedBaseSchema = CorrelatedBaseSchema.extend({ connectionId: z.string().uuid() });
-
-// =====================================================================
-// Client messages (client → server) — single flat discriminated union
-// =====================================================================
-
-const ControlSchema = z.object({ type: z.literal(PostgresClientMessageType.Control), data: z.string() });
-
-// Metadata messages — not connectionId-scoped; served by one-shot pg.Clients.
-const GetSchemasRequestSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresClientMessageType.GetSchemas)
-});
-
-const GetTablesRequestSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresClientMessageType.GetTables),
- schema: z.string()
-});
-
-// Tab-scoped messages — carry connectionId; routed to a specific controller.
-const GetTableDetailRequestSchema = TabScopedBaseSchema.extend({
- type: z.literal(PostgresClientMessageType.GetTableDetail),
- schema: z.string(),
- table: z.string()
-});
-
-const QueryRequestSchema = TabScopedBaseSchema.extend({
- type: z.literal(PostgresClientMessageType.Query),
- sql: z.string().max(50 * 1024)
-});
-
-// Cancel stays fire-and-forget; gains connectionId for routing but not id.
-const CancelSchema = z.object({
- type: z.literal(PostgresClientMessageType.Cancel),
- connectionId: z.string().uuid()
-});
-
-// Lifecycle — open/close tab controllers.
-const OpenConnectionSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresClientMessageType.OpenConnection)
-});
-
-const CloseConnectionSchema = z.object({
- type: z.literal(PostgresClientMessageType.CloseConnection),
- connectionId: z.string().uuid()
-});
-
-// Fire-and-forget heartbeat sent by the FE while the browser tab is visible, so
-// the server-side idle timer only fires on truly inactive tabs — not on active
-// read-only sessions that don't happen to send queries.
-const ActivitySchema = z.object({
- type: z.literal(PostgresClientMessageType.Activity)
-});
-
-export const PostgresClientMessageSchema = z.discriminatedUnion("type", [
- ControlSchema,
- GetSchemasRequestSchema,
- GetTablesRequestSchema,
- GetTableDetailRequestSchema,
- QueryRequestSchema,
- CancelSchema,
- OpenConnectionSchema,
- CloseConnectionSchema,
- ActivitySchema
-]);
-
-export type TPostgresClientMessage = z.infer<typeof PostgresClientMessageSchema>;
-
-// =====================================================================
-// Server messages (server → client) — correlated request/response schemas.
-// Lifecycle messages (ready / session_end) travel on the shared
-// TerminalServerMessageType channel defined in pam-web-access-types.ts.
-// =====================================================================
-
-const SchemasResponseSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.Schemas),
- data: z.array(z.object({ name: z.string() }))
-});
-
-const TablesResponseSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.Tables),
- data: z.array(z.object({ name: z.string(), tableType: z.string() }))
-});
-
-const TableDetailResponseSchema = TabScopedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.TableDetail),
- transactionOpen: z.boolean(),
- data: z.object({
- columns: z.array(
- z.object({
- name: z.string(),
- type: z.string(),
- // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values
- // typeOid: z.number(),
- nullable: z.boolean(),
- // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values
- // defaultValue: z.string().nullable(),
- // isIdentity: z.boolean(),
- identityGeneration: z.string().nullable()
- // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values
- // isArray: z.boolean(),
- // maxLength: z.number().nullable()
- })
- ),
- primaryKeys: z.array(z.string()),
- foreignKeys: z.array(
- z.object({
- constraintName: z.string(),
- columns: z.array(z.string()),
- targetSchema: z.string(),
- targetTable: z.string(),
- targetColumns: z.array(z.string())
- })
- )
- // Left commented out so the schema doesn't have to be modified if the UI ever needs these standard catalog values
- // enums: z.record(z.string(), z.array(z.string()))
- })
-});
-
-const QueryResultResponseSchema = TabScopedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.QueryResult),
- rows: z.array(z.record(z.string(), z.unknown())),
- fields: z.array(
- z.object({
- name: z.string()
- // Left commented out so the schema doesn't have to be modified if the UI ever needs this standard catalog value
- // dataTypeID: z.number()
- })
- ),
- rowCount: z.number().nullable(),
- isTruncated: z.boolean(),
- transactionOpen: z.boolean(),
- command: z.string(),
- executionTimeMs: z.number()
-});
-
-// Error responses carry transactionOpen for tab-scoped errors so the FE banner
-// stays in sync after auto-rollback. connectionId is optional because errors
-// can come from metadata requests (no connectionId) or unknown-connectionId
-// cases tied to a request id.
-const ErrorResponseSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.Error),
- connectionId: z.string().uuid().optional(),
- transactionOpen: z.boolean().optional(),
- error: z.string(),
- detail: z.string().optional(),
- hint: z.string().optional()
-});
-
-// Lifecycle responses.
-const ConnectionOpenedResponseSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.ConnectionOpened),
- connectionId: z.string().uuid(),
- backendPid: z.number().nullable()
-});
-
-const ConnectionOpenFailedResponseSchema = CorrelatedBaseSchema.extend({
- type: z.literal(PostgresServerMessageType.ConnectionOpenFailed),
- error: z.string()
-});
-
-// Informational — BE pushes this when a controller dies outside clean dispose.
-const ConnectionClosedResponseSchema = z.object({
- type: z.literal(PostgresServerMessageType.ConnectionClosed),
- connectionId: z.string().uuid(),
- reason: z.string()
-});
-
-export type TPostgresCorrelatedServerMessage = z.infer<
- | typeof SchemasResponseSchema
- | typeof TablesResponseSchema
- | typeof TableDetailResponseSchema
- | typeof QueryResultResponseSchema
- | typeof ErrorResponseSchema
- | typeof ConnectionOpenedResponseSchema
- | typeof ConnectionOpenFailedResponseSchema
- | typeof ConnectionClosedResponseSchema
->;
diff --git a/backend/src/ee/services/pam-web-access/pam-rdp-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-rdp-session-handler.ts
deleted file mode 100644
index 7f7dbb2426..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-rdp-session-handler.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import net from "node:net";
-
-import { logger } from "@app/lib/logger";
-
-import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";
-
-const RDP_TCP_CONNECT_TIMEOUT_MS = 30_000;
-const WS_HIGH_WATER_MARK = 1024 * 1024;
-
-const wsRawToBuffer = (raw: Buffer | ArrayBuffer | Buffer[]): Buffer => {
- if (Buffer.isBuffer(raw)) return raw;
- if (Array.isArray(raw)) return Buffer.concat(raw);
- return Buffer.from(raw);
-};
-
-export const handleRdpSession = async (ctx: TSessionContext): Promise<TSessionHandlerResult> => {
- const { socket, relayPort, sessionId, onCleanup, earlyMessages, releaseEarlyBuffer } = ctx;
-
- const tcpSocket = new net.Socket();
- let cleanedUp = false;
-
- const teardown = () => {
- if (cleanedUp) return;
- cleanedUp = true;
- try {
- tcpSocket.destroy();
- } catch (err) {
- logger.debug(err, "rdp session: error destroying tcp socket");
- }
- };
-
- return new Promise<TSessionHandlerResult>((resolve, reject) => {
- const connectTimeout = setTimeout(() => {
- logger.error({ sessionId }, "rdp session: relay connect timed out");
- teardown();
- reject(new Error("RDP relay connection timed out"));
- }, RDP_TCP_CONNECT_TIMEOUT_MS);
-
- tcpSocket.once("connect", () => {
- clearTimeout(connectTimeout);
- tcpSocket.removeAllListeners("error");
-
- releaseEarlyBuffer();
- for (const msg of earlyMessages) {
- if (msg.isBinary && tcpSocket.writable) {
- tcpSocket.write(msg.data);
- }
- }
-
- socket.on("message", (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
- if (cleanedUp || tcpSocket.destroyed || !tcpSocket.writable) return;
- if (!isBinary) return;
- const buf = wsRawToBuffer(raw);
- if (buf.length === 0) return;
- try {
- tcpSocket.write(buf);
- } catch {
- if (!cleanedUp) onCleanup();
- teardown();
- }
- });
-
- tcpSocket.on("data", (chunk: Buffer) => {
- if (cleanedUp || socket.readyState !== socket.OPEN) return;
- if (socket.bufferedAmount > WS_HIGH_WATER_MARK) {
- tcpSocket.pause();
- }
- socket.send(chunk, { binary: true }, (err) => {
- if (err) {
- logger.error(err, "rdp session: ws send failed");
- if (!cleanedUp) onCleanup();
- teardown();
- return;
- }
- if (tcpSocket.isPaused() && socket.bufferedAmount <= WS_HIGH_WATER_MARK) {
- tcpSocket.resume();
- }
- });
- });
-
- tcpSocket.on("close", () => {
- logger.info({ sessionId }, "rdp session: tcp socket closed");
- onCleanup();
- try {
- socket.close();
- } catch (err) {
- logger.debug(err, "rdp session: error closing ws after tcp close");
- }
- });
-
- tcpSocket.on("error", (err) => {
- logger.error(err, "rdp session: tcp socket error");
- if (!cleanedUp) {
- onCleanup();
- }
- teardown();
- });
-
- resolve({
- cleanup: async () => {
- teardown();
- }
- });
- });
-
- tcpSocket.once("error", (err) => {
- clearTimeout(connectTimeout);
- logger.error(err, "rdp session: failed to connect to relay");
- teardown();
- reject(err);
- });
-
- tcpSocket.connect(relayPort, "127.0.0.1");
- });
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.ts b/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.ts
deleted file mode 100644
index 6c04ef02ec..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";
-
-describe("tokenizeRedisInput", () => {
- it("splits simple command", () => {
- expect(tokenizeRedisInput("SET key value")).toEqual(["SET", "key", "value"]);
- });
-
- it("handles double-quoted strings", () => {
- expect(tokenizeRedisInput('SET key "hello world"')).toEqual(["SET", "key", "hello world"]);
- });
-
- it("handles single-quoted strings", () => {
- expect(tokenizeRedisInput("SET key 'hello world'")).toEqual(["SET", "key", "hello world"]);
- });
-
- it("handles multiple quoted arguments", () => {
- expect(tokenizeRedisInput('MSET "key one" "value one" "key two" "value two"')).toEqual([
- "MSET",
- "key one",
- "value one",
- "key two",
- "value two"
- ]);
- });
-
- it("handles single word command", () => {
- expect(tokenizeRedisInput("PING")).toEqual(["PING"]);
- });
-
- it("handles extra whitespace", () => {
- expect(tokenizeRedisInput(" SET key value ")).toEqual(["SET", "key", "value"]);
- });
-
- it("handles tabs", () => {
- expect(tokenizeRedisInput("SET\tkey\tvalue")).toEqual(["SET", "key", "value"]);
- });
-
- it("returns empty array for empty input", () => {
- expect(tokenizeRedisInput("")).toEqual([]);
- expect(tokenizeRedisInput(" ")).toEqual([]);
- });
-
- it("handles empty quoted string", () => {
- expect(tokenizeRedisInput('SET key ""')).toEqual(["SET", "key", ""]);
- });
-
- it("handles mixed quoted and unquoted", () => {
- expect(tokenizeRedisInput('MSET key1 "value 1" key2 value2')).toEqual([
- "MSET",
- "key1",
- "value 1",
- "key2",
- "value2"
- ]);
- });
-});
-
-describe("formatRedisReply", () => {
- it("formats null as (nil)", () => {
- expect(formatRedisReply(null)).toBe("(nil)");
- });
-
- it("formats undefined as (nil)", () => {
- expect(formatRedisReply(undefined)).toBe("(nil)");
- });
-
- it("formats integer", () => {
- expect(formatRedisReply(42)).toBe("(integer) 42");
- });
-
- it("formats zero", () => {
- expect(formatRedisReply(0)).toBe("(integer) 0");
- });
-
- it("formats negative integer", () => {
- expect(formatRedisReply(-1)).toBe("(integer) -1");
- });
-
- it("formats string with quotes", () => {
- expect(formatRedisReply("hello world")).toBe('"hello world"');
- });
-
- it("formats OK with quotes", () => {
- expect(formatRedisReply("OK")).toBe('"OK"');
- });
-
- it("escapes embedded double quotes", () => {
- expect(formatRedisReply('He said "hello"')).toBe('"He said \\"hello\\""');
- });
-
- it("escapes embedded backslashes", () => {
- expect(formatRedisReply("path\\to\\file")).toBe('"path\\\\to\\\\file"');
- });
-
- it("formats empty array", () => {
- expect(formatRedisReply([])).toBe("(empty array)");
- });
-
- it("formats simple array", () => {
- const result = formatRedisReply(["foo", "bar", "baz"]);
- expect(result).toBe('1) "foo"\n2) "bar"\n3) "baz"');
- });
-
- it("formats array with mixed types", () => {
- const result = formatRedisReply(["key", 42, null]);
- expect(result).toBe('1) "key"\n2) (integer) 42\n3) (nil)');
- });
-
- it("formats nested arrays", () => {
- const result = formatRedisReply([["a", "b"], ["c"]]);
- expect(result).toContain('1) 1) "a"');
- expect(result).toContain(' 2) "b"');
- expect(result).toContain('2) 1) "c"');
- });
-
- it("formats Buffer as quoted string", () => {
- const result = formatRedisReply(Buffer.from("hello"));
- expect(result).toBe('"hello"');
- });
-
- it("formats bigint", () => {
- expect(formatRedisReply(BigInt(999))).toBe("(integer) 999");
- });
-});
diff --git a/backend/src/ee/services/pam-web-access/pam-redis-formatter.ts b/backend/src/ee/services/pam-web-access/pam-redis-formatter.ts
deleted file mode 100644
index c709b83871..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-redis-formatter.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import RE2 from "re2";
-
-const escapeBackslash = new RE2(/\\/, "g");
-const escapeQuote = new RE2(/"/, "g");
-
-const escapeRedisString = (str: string): string => str.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"');
-
-export const tokenizeRedisInput = (input: string): string[] => {
- const tokens: string[] = [];
- let current = "";
- let inQuote: "'" | '"' | null = null;
-
- for (let i = 0; i < input.length; i += 1) {
- const ch = input[i];
-
- if (inQuote) {
- if (ch === inQuote) {
- tokens.push(current);
- current = "";
- inQuote = null;
- } else {
- current += ch;
- }
- } else if (ch === '"' || ch === "'") {
- inQuote = ch;
- } else if (ch === " " || ch === "\t") {
- if (current.length > 0) {
- tokens.push(current);
- current = "";
- }
- } else {
- current += ch;
- }
- }
-
- if (current.length > 0) {
- tokens.push(current);
- }
-
- return tokens;
-};
-
-export const formatRedisReply = (reply: unknown, indent: number = 0): string => {
- const prefix = " ".repeat(indent);
-
- if (reply === null || reply === undefined) {
- return `${prefix}(nil)`;
- }
-
- if (typeof reply === "number" || typeof reply === "bigint") {
- return `${prefix}(integer) ${reply}`;
- }
-
- if (typeof reply === "string") {
- return `${prefix}"${escapeRedisString(reply)}"`;
- }
-
- if (Buffer.isBuffer(reply)) {
- return `${prefix}"${escapeRedisString(reply.toString())}"`;
- }
-
- if (Array.isArray(reply)) {
- if (reply.length === 0) {
- return `${prefix}(empty array)`;
- }
- return reply.map((item, i) => `${prefix}${i + 1}) ${formatRedisReply(item, indent + 3).trimStart()}`).join("\n");
- }
-
- return `${prefix}"${String(reply)}"`;
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts
deleted file mode 100644
index 5b9e43fb85..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { Redis } from "ioredis";
-
-import {
- TRedisAccountCredentials,
- TRedisResourceConnectionDetails
-} from "@app/ee/services/pam-resource/redis/redis-resource-types";
-import { logger } from "@app/lib/logger";
-
-import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";
-import { RedisClientMessageSchema, RedisClientMessageType } from "./pam-redis-ws-types";
-import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";
-import {
- SessionEndReason,
- TerminalServerMessageType,
- TSessionContext,
- TSessionHandlerResult
-} from "./pam-web-access-types";
-
-type TRedisSessionParams = {
- connectionDetails: TRedisResourceConnectionDetails;
- credentials: TRedisAccountCredentials;
-};
-
-const executeCommand = async (redisClient: Redis, input: string): Promise<{ output: string; shouldClose: boolean }> => {
- const trimmed = input.trim();
-
- if (trimmed.length === 0) {
- return { output: "", shouldClose: false };
- }
-
- const lower = trimmed.toLowerCase();
- if (lower === "quit" || lower === "exit") {
- return { output: "Goodbye!\n", shouldClose: true };
- }
-
- const tokens = tokenizeRedisInput(trimmed);
- if (tokens.length === 0) {
- return { output: "", shouldClose: false };
- }
-
- const [command, ...args] = tokens;
-
- try {
- const result = await redisClient.call(command, ...args);
- return { output: `${formatRedisReply(result)}\n`, shouldClose: false };
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- return { output: `(error) ${message}\n`, shouldClose: false };
- }
-};
-
-export const handleRedisSession = async (
- ctx: TSessionContext,
- params: TRedisSessionParams
-): Promise<TSessionHandlerResult> => {
- const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =
- ctx;
- const { connectionDetails, credentials } = params;
-
- const redisClient = new Redis({
- host: "localhost",
- port: relayPort,
- maxRetriesPerRequest: 0,
- reconnectOnError: () => false,
- retryStrategy: () => null
- });
-
- try {
- await new Promise<void>((resolve, reject) => {
- redisClient.once("ready", resolve);
- redisClient.once("error", reject);
- redisClient.once("close", () => reject(new Error("Redis connection closed before ready")));
- });
- } catch (err) {
- try {
- redisClient.disconnect();
- } catch {
- /* ignore */
- }
- throw err;
- }
-
- const prompt = `${connectionDetails.host}:${connectionDetails.port}> `;
-
- sendMessage({
- type: TerminalServerMessageType.Ready,
- data: `Connected to ${resourceName} (${connectionDetails.host}:${connectionDetails.port}) as ${credentials.username || "default"}\n\n`,
- prompt
- });
-
- logger.info({ sessionId }, "Redis web access session established");
-
- // Sequential message processing to prevent concurrent command issues
- let processingPromise = Promise.resolve();
-
- socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
- processingPromise = processingPromise
- .then(async () => {
- const message = parseClientMessage(rawData, RedisClientMessageSchema);
- if (!message) {
- sendMessage({
- type: TerminalServerMessageType.Output,
- data: "Invalid message format\n",
- prompt
- });
- return;
- }
-
- if (message.type === RedisClientMessageType.Control) {
- if (message.data === "quit") {
- sendSessionEnd(SessionEndReason.UserQuit);
- onCleanup();
- socket.close();
- return;
- }
- if (message.data === "clear-buffer") {
- return;
- }
- return;
- }
-
- if (message.type === RedisClientMessageType.Input) {
- const result = await executeCommand(redisClient, message.data);
-
- if (result.shouldClose) {
- sendSessionEnd(SessionEndReason.UserQuit);
- onCleanup();
- socket.close();
- return;
- }
-
- sendMessage({
- type: TerminalServerMessageType.Output,
- data: result.output,
- prompt
- });
- }
- })
- .catch((err) => {
- logger.error(err, "Error processing Redis message");
- sendMessage({
- type: TerminalServerMessageType.Output,
- data: "Internal error\n",
- prompt
- });
- });
- });
-
- // Tunnel drop detection
- redisClient.on("error", (err) => {
- logger.error(err, "Redis connection error");
- sendSessionEnd(resolveEndReason(isNearSessionExpiry));
- onCleanup();
- socket.close();
- });
-
- redisClient.on("close", () => {
- sendSessionEnd(resolveEndReason(isNearSessionExpiry));
- onCleanup();
- socket.close();
- });
-
- return {
- cleanup: async () => {
- try {
- await redisClient.quit();
- } catch (err) {
- logger.debug(err, "Error closing Redis client");
- }
- }
- };
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-redis-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-redis-ws-types.ts
deleted file mode 100644
index 40c3abcd6e..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-redis-ws-types.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { z } from "zod";
-
-export enum RedisClientMessageType {
- Input = "input",
- Control = "control"
-}
-
-const InputSchema = z.object({ type: z.literal(RedisClientMessageType.Input), data: z.string() });
-const ControlSchema = z.object({ type: z.literal(RedisClientMessageType.Control), data: z.string() });
-
-export const RedisClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema]);
diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts
deleted file mode 100644
index 04bda1c6da..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { Client, type ClientChannel, type ConnectConfig } from "ssh2";
-
-import {
- TSSHAccountCredentials,
- TSSHResourceConnectionDetails
-} from "@app/ee/services/pam-resource/ssh/ssh-resource-types";
-import { logger } from "@app/lib/logger";
-
-import { SshClientMessageSchema, SshClientMessageType } from "./pam-ssh-ws-types";
-import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";
-import {
- SessionEndReason,
- TerminalServerMessageType,
- TSessionContext,
- TSessionHandlerResult
-} from "./pam-web-access-types";
-
-type TSSHSessionParams = {
- connectionDetails: TSSHResourceConnectionDetails;
- credentials: TSSHAccountCredentials;
-};
-
-export const handleSSHSession = async (
- ctx: TSessionContext,
- params: TSSHSessionParams
-): Promise<TSessionHandlerResult> => {
- const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =
- ctx;
- const { credentials } = params;
-
- const client = new Client();
- let stream: ClientChannel | null = null;
-
- const connectConfig: ConnectConfig = {
- host: "localhost",
- port: relayPort,
- username: credentials.username,
- readyTimeout: 30_000,
- authHandler: ["none"]
- };
-
- return new Promise((resolve, reject) => {
- client.on("ready", () => {
- client.shell({ term: "xterm-256color", rows: 24, cols: 80 }, (err, shellStream) => {
- if (err) {
- logger.error(err, "Failed to open SSH shell");
- sendSessionEnd(SessionEndReason.SetupFailed);
- client.end();
- reject(err);
- return;
- }
-
- stream = shellStream;
-
- // Send Ready message
- sendMessage({
- type: TerminalServerMessageType.Ready,
- data: `Connected to ${resourceName} as ${credentials.username}\r\n`
- });
-
- logger.info({ sessionId }, "SSH web access session shell opened");
-
- // SSH -> WS: forward output from remote shell to WebSocket
- shellStream.on("data", (data: Buffer) => {
- sendMessage({
- type: TerminalServerMessageType.Output,
- data: data.toString("utf-8")
- });
- });
-
- shellStream.stderr.on("data", (data: Buffer) => {
- sendMessage({
- type: TerminalServerMessageType.Output,
- data: data.toString("utf-8")
- });
- });
-
- // WS -> SSH: forward input from WebSocket to remote shell
- socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
- const message = parseClientMessage(rawData, SshClientMessageSchema);
- if (!message) return;
-
- if (message.type === SshClientMessageType.Input) {
- // Raw keystroke forwarding — no buffering, no local echo
- shellStream.write(message.data);
- } else if (message.type === SshClientMessageType.Resize) {
- try {
- const { rows, cols } = JSON.parse(message.data) as { rows: number; cols: number };
- shellStream.setWindow(rows, cols, 0, 0);
- } catch {
- logger.debug("Invalid resize data received");
- }
- } else if (message.type === SshClientMessageType.Control) {
- if (message.data === "quit") {
- shellStream.close();
- client.end();
- }
- }
- });
-
- // Shell stream close
- shellStream.on("close", () => {
- sendSessionEnd(resolveEndReason(isNearSessionExpiry));
- onCleanup();
- socket.close();
- });
-
- resolve({
- cleanup: async () => {
- try {
- stream?.close();
- } catch (streamErr) {
- logger.debug(streamErr, "Error closing SSH stream");
- }
- try {
- client.end();
- } catch (clientErr) {
- logger.debug(clientErr, "Error closing SSH client");
- }
- }
- });
- });
- });
-
- client.on("error", (err) => {
- logger.error(err, "SSH client connection error");
- if (stream) {
- // Session was established, then errored
- sendSessionEnd(resolveEndReason(isNearSessionExpiry));
- onCleanup();
- socket.close();
- } else {
- // Connection never established
- reject(err);
- }
- });
-
- client.on("end", () => {
- logger.debug({ sessionId }, "SSH client connection ended");
- });
-
- client.connect(connectConfig);
- });
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts
deleted file mode 100644
index 4015375f38..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-ssh-ws-types.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { z } from "zod";
-
-export enum SshClientMessageType {
- Input = "input",
- Control = "control",
- Resize = "resize"
-}
-
-const InputSchema = z.object({ type: z.literal(SshClientMessageType.Input), data: z.string() });
-const ControlSchema = z.object({ type: z.literal(SshClientMessageType.Control), data: z.string() });
-const ResizeSchema = z.object({ type: z.literal(SshClientMessageType.Resize), data: z.string() });
-
-export const SshClientMessageSchema = z.discriminatedUnion("type", [InputSchema, ControlSchema, ResizeSchema]);
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts b/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts
deleted file mode 100644
index d6a842671d..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-web-access-fns.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { SessionEndReason } from "./pam-web-access-types";
-
-export const rawBufferToString = (rawData: Buffer | ArrayBuffer | Buffer[]): string => {
- if (Buffer.isBuffer(rawData)) return rawData.toString();
- if (Array.isArray(rawData)) return Buffer.concat(rawData).toString();
- return Buffer.from(rawData).toString();
-};
-
-export const resolveEndReason = (isNearSessionExpiry: () => boolean): SessionEndReason =>
- isNearSessionExpiry() ? SessionEndReason.SessionCompleted : SessionEndReason.ConnectionLost;
-
-export const parseClientMessage = <T>(
- rawData: Buffer | ArrayBuffer | Buffer[],
- schema: { safeParse: (data: unknown) => { success: true; data: T } | { success: false } }
-): T | null => {
- const str = rawBufferToString(rawData);
- let parsed: unknown;
- try {
- parsed = JSON.parse(str);
- } catch {
- return null;
- }
- const result = schema.safeParse(parsed);
- return result.success ? result.data : null;
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
deleted file mode 100644
index a05846b59f..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ /dev/null
@@ -1,836 +0,0 @@
-import net from "node:net";
-
-import { ForbiddenError, subject } from "@casl/ability";
-import type WebSocket from "ws";
-
-import { ActionProjectType } from "@app/db/schemas";
-import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
-import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
-import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionPamAccountActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
-import { BadRequestError, NotFoundError, PolicyViolationError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
-import { createGatewayConnection, createRelayConnection, setupRelayServer } from "@app/lib/gateway-v2/gateway-v2";
-import { logger } from "@app/lib/logger";
-import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
-import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
-import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";
-import { TApprovalRequestGrantsDALFactory } from "@app/services/approval-policy/approval-request-dal";
-import { TPamAccessPolicy } from "@app/services/approval-policy/pam-access/pam-access-policy-types";
-import { ActorType, MfaMethod } from "@app/services/auth/auth-type";
-import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
-import { TokenType } from "@app/services/auth-token/auth-token-types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
-import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
-import { TOrgDALFactory } from "@app/services/org/org-dal";
-import { TPamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
-import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { TUserDALFactory } from "@app/services/user/user-dal";
-
-import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
-import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
-import { TPamAccountPolicyDALFactory } from "../pam-account-policy/pam-account-policy-dal";
-import { PamAccountPolicyRuleType } from "../pam-account-policy/pam-account-policy-enums";
-import { TPolicyRules } from "../pam-account-policy/pam-account-policy-types";
-import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";
-import { decryptDomainConnectionDetails } from "../pam-domain/pam-domain-fns";
-import { TPamProjectRecordingConfigDALFactory } from "../pam-project-recording-config/pam-project-recording-config-dal";
-import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
-import { decryptResourceConnectionDetails } from "../pam-resource/pam-resource-fns";
-import {
- TPostgresAccountCredentials,
- TPostgresResourceConnectionDetails
-} from "../pam-resource/postgres/postgres-resource-types";
-import { TRedisAccountCredentials, TRedisResourceConnectionDetails } from "../pam-resource/redis/redis-resource-types";
-import { TSSHAccountCredentials, TSSHResourceConnectionDetails } from "../pam-resource/ssh/ssh-resource-types";
-import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
-import { PamSessionStatus } from "../pam-session/pam-session-enums";
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
-import { handlePostgresSession } from "./pam-postgres-session-handler";
-import { handleRdpSession } from "./pam-rdp-session-handler";
-import { handleRedisSession } from "./pam-redis-session-handler";
-import { handleSSHSession } from "./pam-ssh-session-handler";
-import {
- DEFAULT_WEB_SESSION_DURATION_MS,
- MAX_WEB_SESSIONS_PER_USER,
- SessionEndReason,
- TEarlyBufferedMsg,
- TerminalServerMessageType,
- TIssueWebSocketTicketDTO,
- TSessionContext,
- TSessionHandlerResult,
- TWebSocketServerMessage,
- WebSocketServerMessageSchema,
- WS_IDLE_TIMEOUT_MS,
- WS_PING_INTERVAL_MS
-} from "./pam-web-access-types";
-
-const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH, PamResource.Redis, PamResource.Windows];
-
-type TPamWebAccessServiceFactoryDep = {
- pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findMetadataByAccountIds">;
- pamDomainDAL: Pick<TPamDomainDALFactory, "findById">;
- pamAccountPolicyDAL: Pick<TPamAccountPolicyDALFactory, "findById">;
- pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
- pamProjectRecordingConfigDAL: Pick<TPamProjectRecordingConfigDALFactory, "findByProjectId">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
- tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
- pamSessionDAL: Pick<
- TPamSessionDALFactory,
- "create" | "updateById" | "countActiveWebSessions" | "endSessionById" | "activateSession" | "endExpiredWebSessions"
- >;
- pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- userDAL: Pick<TUserDALFactory, "findById">;
- mfaSessionService: Pick<
- TMfaSessionServiceFactory,
- "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
- >;
- approvalPolicyDAL: TApprovalPolicyDALFactory;
- approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
- orgDAL: Pick<TOrgDALFactory, "findOrgById">;
- projectDAL: Pick<TProjectDALFactory, "findById">;
-};
-
-export type TPamWebAccessServiceFactory = ReturnType<typeof pamWebAccessServiceFactory>;
-
-type THandleWebSocketConnectionDTO = {
- socket: WebSocket;
- accountId: string;
- projectId: string;
- orgId: string;
- resourceId: string;
- resourceName: string;
- accountName: string;
- auditLogInfo: AuditLogInfo;
- userId: string;
- actorEmail: string;
- actorName: string;
- actorIp: string;
- actorUserAgent: string;
- reason?: string | null;
- grantExpiresAt?: string | null;
- preAuthMessages: TEarlyBufferedMsg[];
- preAuthHandler: (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => void;
-};
-export const pamWebAccessServiceFactory = ({
- pamAccountDAL,
- pamDomainDAL,
- pamAccountPolicyDAL,
- pamResourceDAL,
- pamProjectRecordingConfigDAL,
- permissionService,
- auditLogService,
- tokenService,
- pamSessionDAL,
- pamSessionExpirationService,
- gatewayV2Service,
- gatewayPoolService,
- kmsService,
- userDAL,
- mfaSessionService,
- approvalPolicyDAL,
- approvalRequestGrantsDAL,
- orgDAL,
- projectDAL
-}: TPamWebAccessServiceFactoryDep) => {
- const sendMessage = (socket: WebSocket, message: TWebSocketServerMessage): void => {
- try {
- if (socket.readyState === socket.OPEN) {
- const parsed = WebSocketServerMessageSchema.parse(message);
- socket.send(JSON.stringify(parsed));
- }
- } catch (err) {
- logger.error(err, "Failed to send WebSocket message");
- }
- };
-
- const sendSessionEnd = (socket: WebSocket, reason: SessionEndReason): void => {
- sendMessage(socket, { type: TerminalServerMessageType.SessionEnd, reason });
- };
-
- // Flushes the session_end frame before sending the WS close frame
- const sendSessionEndAndClose = (socket: WebSocket, reason: SessionEndReason): void => {
- try {
- if (socket.readyState === socket.OPEN) {
- const parsed = WebSocketServerMessageSchema.parse({ type: TerminalServerMessageType.SessionEnd, reason });
- socket.send(JSON.stringify(parsed), () => {
- socket.close();
- });
- return;
- }
- } catch (err) {
- logger.error(err, "Failed to send session end message");
- }
- // Fallback: close immediately if send failed or socket wasn't open
- socket.close();
- };
-
- const issueWebSocketTicket = async ({
- accountId,
- projectId,
- orgId,
- actor,
- actorEmail,
- actorName,
- auditLogInfo,
- mfaSessionId,
- reason,
- resourceId: requestResourceId
- }: TIssueWebSocketTicketDTO) => {
- const account = await pamAccountDAL.findById(accountId);
-
- if (!account) {
- throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
- }
-
- if (account.projectId !== projectId) {
- throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
- }
-
- const trimmedReason = reason?.trim() || null;
-
- const effectiveResourceId = account.resourceId ?? requestResourceId;
- if (!effectiveResourceId) {
- throw new BadRequestError({ message: "A resourceId is required for web access" });
- }
-
- const resource = await pamResourceDAL.findById(effectiveResourceId);
-
- if (!resource) {
- throw new NotFoundError({ message: `Resource with ID '${effectiveResourceId}' not found` });
- }
-
- if (resource.projectId !== projectId) {
- throw new NotFoundError({ message: `Resource with ID '${effectiveResourceId}' not found` });
- }
-
- if (!SUPPORTED_WEB_ACCESS_RESOURCES.includes(resource.resourceType as PamResource)) {
- throw new BadRequestError({
- message: "Web access is not supported for this resource type"
- });
- }
-
- const isDomainAccount = !account.resourceId;
- const domain = isDomainAccount && account.domainId ? await pamDomainDAL.findById(account.domainId) : null;
- let accountIdentity = account.name;
-
- if (isDomainAccount) {
- if (resource.resourceType !== PamResource.Windows) {
- throw new BadRequestError({ message: "Domain account web access is only supported for Windows resources" });
- }
-
- if (!account.domainId || resource.domainId !== account.domainId) {
- throw new BadRequestError({ message: "Resource is not joined to this domain account's domain" });
- }
-
- if (!domain) {
- throw new NotFoundError({ message: `Domain with ID '${account.domainId}' not found` });
- }
-
- const domainConnectionDetails = await decryptDomainConnectionDetails({
- projectId,
- encryptedConnectionDetails: domain.encryptedConnectionDetails,
- kmsService
- });
- accountIdentity = `${domainConnectionDetails.domain}:${account.name}`;
- }
-
- // Sessions that outlived their expiresAt may still show as active — end them so that they don't count against the session limit.
- await pamSessionDAL.endExpiredWebSessions(actor.id, projectId);
-
- const activeWebSessionCount = await pamSessionDAL.countActiveWebSessions(actor.id, projectId);
- if (activeWebSessionCount >= MAX_WEB_SESSIONS_PER_USER) {
- throw new BadRequestError({
- message: `You have reached the maximum of ${MAX_WEB_SESSIONS_PER_USER} active web access sessions. Close an existing session and try again.`
- });
- }
-
- // Approval policy check
- const approvalPolicy = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.PamAccess](ApprovalPolicyType.PamAccess);
-
- const policyInputs = {
- resourceId: resource.id,
- resourceName: resource.name,
- accountName: accountIdentity
- };
-
- const approvalGrant = await approvalPolicy.canAccess(
- approvalRequestGrantsDAL,
- resource.projectId,
- actor.id,
- policyInputs
- );
-
- if (!approvalGrant) {
- const matchedPolicy = await approvalPolicy.matchPolicy(approvalPolicyDAL, resource.projectId, policyInputs);
-
- if (matchedPolicy) {
- throw new PolicyViolationError({
- message: "A policy is in place for this resource",
- details: {
- policyId: matchedPolicy.id,
- policyName: matchedPolicy.name,
- policyType: matchedPolicy.type,
- constraints: {
- accessDuration: {
- max: (matchedPolicy as TPamAccessPolicy).constraints.constraints.accessDuration.max
- }
- }
- }
- });
- }
-
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- projectId: account.projectId,
- actionProjectType: ActionProjectType.PAM
- });
-
- const accountMeta = await pamAccountDAL.findMetadataByAccountIds([account.id]);
-
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Access,
- subject(ProjectPermissionSub.PamAccounts, {
- resourceName: resource.name,
- accountName: account.name,
- resourceType: resource.resourceType,
- ...(domain && { domainName: domain.name, domainType: domain.domainType }),
- metadata: accountMeta[account.id] || []
- })
- );
- }
-
- // After auth gates so error code doesn't leak policy config to unauthorized actors
- if (account.policyId) {
- const policy = await pamAccountPolicyDAL.findById(account.policyId);
- const policyRules = (policy?.rules ?? {}) as TPolicyRules;
- if (policy?.isActive && policyRules[PamAccountPolicyRuleType.RequireReason] && !trimmedReason) {
- throw new BadRequestError({
- message: "A reason is required to access this account",
- name: "PAM_REASON_REQUIRED"
- });
- }
- }
-
- if (resource.resourceType === PamResource.Windows) {
- const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(projectId);
- if (!recordingConfig || recordingConfig.storageBackend === PamRecordingStorageBackend.Postgres) {
- throw new BadRequestError({
- message:
- "Windows resources require an external (S3) session recording configuration. Postgres storage is not supported for RDP sessions. Configure an S3 bucket in project settings before accessing Windows accounts."
- });
- }
- }
-
- // MFA check
- if (account.requireMfa && !mfaSessionId) {
- const project = await requestMemoize(requestMemoKeys.projectFindById(account.projectId), () =>
- projectDAL.findById(account.projectId)
- );
- if (!project) throw new NotFoundError({ message: `Project with ID '${account.projectId}' not found` });
-
- const actorUser = await requestMemoize(requestMemoKeys.userFindById(actor.id), () => userDAL.findById(actor.id));
- if (!actorUser) throw new NotFoundError({ message: `User with ID '${actor.id}' not found` });
-
- const org = await requestMemoize(requestMemoKeys.orgFindOrgById(project.orgId), () =>
- orgDAL.findOrgById(project.orgId)
- );
- if (!org) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });
-
- // Priority: org-enforced > user-selected > email fallback
- const orgMfaMethod = org.enforceMfa ? (org.selectedMfaMethod as MfaMethod | null) : undefined;
- const userMfaMethod = actorUser.isMfaEnabled ? (actorUser.selectedMfaMethod as MfaMethod | null) : undefined;
- const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
-
- const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, account.id, mfaMethod);
-
- if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
- await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
- }
-
- throw new BadRequestError({
- message: "MFA verification required to access PAM account",
- name: "SESSION_MFA_REQUIRED",
- details: {
- mfaSessionId: newMfaSessionId,
- mfaMethod
- }
- });
- }
-
- if (account.requireMfa && mfaSessionId) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (
- !mfaSession ||
- mfaSession.userId !== actor.id ||
- mfaSession.resourceId !== account.id ||
- mfaSession.status !== MfaSessionStatus.ACTIVE
- ) {
- throw new BadRequestError({ message: "Invalid or expired MFA session" });
- }
-
- await mfaSessionService.deleteMfaSession(mfaSessionId);
- }
-
- const token = await tokenService.createTokenForUser({
- type: TokenType.TOKEN_PAM_WS_TICKET,
- userId: actor.id,
- payload: JSON.stringify({
- accountId,
- projectId,
- orgId,
- resourceId: resource.id,
- resourceName: resource.name,
- accountName: account.name,
- actorEmail,
- actorName,
- auditLogInfo,
- reason: trimmedReason,
- grantExpiresAt: approvalGrant?.expiresAt?.toISOString() ?? null
- })
- });
-
- await auditLogService.createAuditLog({
- ...auditLogInfo,
- orgId,
- projectId,
- event: {
- type: EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,
- metadata: {
- accountId,
- resourceName: resource.name,
- accountName: account.name
- }
- }
- });
-
- return { ticket: `${actor.id}:${token}` };
- };
-
- const handleWebSocketConnection = async ({
- socket,
- accountId,
- projectId,
- orgId,
- resourceId: ticketResourceId,
- resourceName,
- accountName,
- auditLogInfo,
- userId,
- actorEmail,
- actorName,
- actorIp,
- actorUserAgent,
- reason: accessReason,
- grantExpiresAt: grantExpiresAtIso,
- preAuthMessages,
- preAuthHandler
- }: THandleWebSocketConnectionDTO): Promise<void> => {
- const earlyMessages: TEarlyBufferedMsg[] = preAuthMessages;
- const releaseEarlyBuffer = () => {
- socket.off("message", preAuthHandler);
- };
-
- let session: { id: string } | null = null;
- let cleanedUp = false;
- let handlerResult: TSessionHandlerResult | null = null;
- let relayServer: { port: number; cleanup: () => Promise<void> } | null = null;
- let relayCerts: {
- relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
- gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
- relayHost: string;
- } | null = null;
- let expiryTimer: ReturnType<typeof setTimeout> | null = null;
- let pingInterval: ReturnType<typeof setInterval> | null = null;
- let idleTimer: ReturnType<typeof setTimeout> | null = null;
-
- const cleanup = async () => {
- if (expiryTimer) {
- clearTimeout(expiryTimer);
- expiryTimer = null;
- }
- if (pingInterval) {
- clearInterval(pingInterval);
- pingInterval = null;
- }
- if (idleTimer) {
- clearTimeout(idleTimer);
- idleTimer = null;
- }
-
- if (handlerResult) {
- try {
- await handlerResult.cleanup();
- } catch (err) {
- logger.debug(err, "Error in handler cleanup");
- } finally {
- handlerResult = null;
- }
- }
-
- // Must come after handler cleanup
- if (relayServer) {
- try {
- await relayServer.cleanup();
- } catch (err) {
- logger.debug(err, "Error closing relay server");
- } finally {
- relayServer = null;
- }
- }
-
- if (session) {
- const sessionId = session.id;
- try {
- const updated = await pamSessionDAL.endSessionById(sessionId);
- if (updated) {
- await auditLogService.createAuditLog({
- ...auditLogInfo,
- orgId,
- projectId,
- event: {
- type: EventType.PAM_SESSION_END,
- metadata: {
- sessionId,
- accountName
- }
- }
- });
- }
- } catch (err) {
- logger.error(err, `Failed to end session in DB [sessionId=${sessionId}]`);
- } finally {
- session = null;
- }
- }
-
- // Best-effort ALPN session cancellation (fire-and-forget).
- // Triggers gateway-side cleanup: log upload, and session end via API.
- // If this fails, the scheduled queue job will expire the session at expiresAt time.
- if (relayCerts) {
- const certs = relayCerts;
- relayCerts = null;
- void (async () => {
- let relayConn: net.Socket | null = null;
- try {
- relayConn = await createRelayConnection({
- relayHost: certs.relayHost,
- clientCertificate: certs.relay.clientCertificate,
- clientPrivateKey: certs.relay.clientPrivateKey,
- serverCertificateChain: certs.relay.serverCertificateChain
- });
- const cancelConn = await createGatewayConnection(
- relayConn,
- certs.gateway,
- GatewayProxyProtocol.PamSessionCancellation
- );
- cancelConn.end();
- } catch (err) {
- logger.debug(err, "Session cancellation signal failed (best-effort)");
- } finally {
- relayConn?.destroy();
- }
- })();
- }
-
- cleanedUp = true;
- };
-
- try {
- // 1. VALIDATE
- const account = await pamAccountDAL.findById(accountId);
- if (!account || account.projectId !== projectId) {
- throw new BadRequestError({ message: "Invalid account or project" });
- }
-
- const effectiveResourceId = account.resourceId ?? ticketResourceId;
- if (!effectiveResourceId) {
- throw new BadRequestError({ message: "A resourceId is required for domain accounts" });
- }
-
- const resource = await pamResourceDAL.findById(effectiveResourceId);
- if (!resource || resource.projectId !== projectId) {
- throw new BadRequestError({ message: "Resource not found" });
- }
-
- if (!SUPPORTED_WEB_ACCESS_RESOURCES.includes(resource.resourceType as PamResource)) {
- throw new BadRequestError({ message: "Web access is not supported for this resource type" });
- }
-
- if (!account.resourceId) {
- if (resource.resourceType !== PamResource.Windows) {
- throw new BadRequestError({ message: "Domain account web access is only supported for Windows resources" });
- }
-
- if (!account.domainId || resource.domainId !== account.domainId) {
- throw new BadRequestError({ message: "Resource is not joined to this domain account's domain" });
- }
- }
-
- const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
- gatewayId: resource.gatewayId,
- gatewayPoolId: resource.gatewayPoolId
- });
- if (!effectiveGatewayId) {
- throw new BadRequestError({ message: "Gateway not configured for this resource" });
- }
-
- // Sessions that outlived their expiresAt may still show as active — end them so that they don't count against the session limit.
- await pamSessionDAL.endExpiredWebSessions(userId, projectId);
-
- // Check web session limit
- const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);
- if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {
- sendMessage(socket, {
- type: TerminalServerMessageType.Output,
- data: `${SessionEndReason.SessionLimitReached}\n`
- });
- sendSessionEndAndClose(socket, SessionEndReason.SessionLimitReached);
- return;
- }
-
- // 2. DECRYPT
- const resourceConnectionDetails = await decryptResourceConnectionDetails({
- projectId,
- encryptedConnectionDetails: resource.encryptedConnectionDetails,
- kmsService
- });
- const { host, port } = resourceConnectionDetails as { host: string; port: number };
-
- const accountCredentials = await decryptAccountCredentials({
- projectId,
- encryptedCredentials: account.encryptedCredentials,
- kmsService
- });
-
- // 3. CREATE SESSION
- const user = await requestMemoize(requestMemoKeys.userFindById(userId), () => userDAL.findById(userId));
- let sessionDurationMs = DEFAULT_WEB_SESSION_DURATION_MS;
- if (grantExpiresAtIso) {
- const grantRemainingMs = new Date(grantExpiresAtIso).getTime() - Date.now();
- if (grantRemainingMs <= 0) {
- sendSessionEndAndClose(socket, SessionEndReason.SessionGrantExpired);
- return;
- }
- sessionDurationMs = Math.min(sessionDurationMs, grantRemainingMs);
- }
- const expiresAt = new Date(Date.now() + sessionDurationMs);
-
- const isDomainAccount = !account.resourceId;
-
- session = await pamSessionDAL.create({
- status: PamSessionStatus.Starting,
- accessMethod: "web",
- expiresAt,
- accountName,
- actorEmail,
- actorIp,
- actorName,
- actorUserAgent,
- projectId,
- resourceName: resource.name,
- resourceType: resource.resourceType,
- accountId: account.id,
- resourceId: isDomainAccount ? null : resource.id,
- selectedResourceId: isDomainAccount ? resource.id : null,
- userId,
- gatewayId: effectiveGatewayId,
- reason: accessReason?.trim() || null
- });
-
- await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);
-
- // 4. GET CERTIFICATES
- const certs = await gatewayV2Service.getPAMConnectionDetails({
- gatewayId: effectiveGatewayId,
- sessionId: session.id,
- resourceType: resource.resourceType as PamResource,
- host,
- port,
- duration: sessionDurationMs,
- actorMetadata: {
- id: userId,
- type: ActorType.USER,
- name: user?.email ?? ""
- }
- });
-
- if (!certs) {
- throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
- }
-
- relayCerts = {
- relayHost: certs.relayHost,
- relay: certs.relay,
- gateway: certs.gateway
- };
-
- // 5. START TUNNEL
- const tunnelProtocol =
- resource.resourceType === PamResource.Windows ? GatewayProxyProtocol.PamRdpBrowser : GatewayProxyProtocol.Pam;
- relayServer = await setupRelayServer({
- protocol: tunnelProtocol,
- relayHost: certs.relayHost,
- relay: certs.relay,
- gateway: certs.gateway,
- longLived: true
- });
-
- // 30s tolerance for clock skew between us and gateway
- const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;
-
- // Bound message helpers for handlers
- const boundSendMessage = (msg: TWebSocketServerMessage) => sendMessage(socket, msg);
- const boundSendSessionEnd = (reason: SessionEndReason) => sendSessionEnd(socket, reason);
- const handlerCleanup = () => {
- if (!cleanedUp) {
- void cleanup();
- }
- };
-
- // Build session context once — passed to any handler
- const ctx: TSessionContext = {
- socket,
- relayPort: relayServer.port,
- resourceName: resource.name,
- sessionId: session.id,
- sendMessage: boundSendMessage,
- sendSessionEnd: boundSendSessionEnd,
- isNearSessionExpiry,
- onCleanup: handlerCleanup,
- earlyMessages,
- releaseEarlyBuffer
- };
-
- // 6. CONNECT TO RESOURCE (dispatch by type)
- try {
- if (resource.resourceType === PamResource.Postgres) {
- handlerResult = await handlePostgresSession(ctx, {
- connectionDetails: resourceConnectionDetails as TPostgresResourceConnectionDetails,
- credentials: accountCredentials as TPostgresAccountCredentials
- });
- } else if (resource.resourceType === PamResource.SSH) {
- handlerResult = await handleSSHSession(ctx, {
- connectionDetails: resourceConnectionDetails as TSSHResourceConnectionDetails,
- credentials: accountCredentials as TSSHAccountCredentials
- });
- } else if (resource.resourceType === PamResource.Redis) {
- handlerResult = await handleRedisSession(ctx, {
- connectionDetails: resourceConnectionDetails as TRedisResourceConnectionDetails,
- credentials: accountCredentials as TRedisAccountCredentials
- });
- } else if (resource.resourceType === PamResource.Windows) {
- handlerResult = await handleRdpSession(ctx);
- }
- } finally {
- releaseEarlyBuffer();
- }
-
- // 7. ACTIVATE SESSION
- // For RDP (Windows), the gateway calls getSessionCredentials which transitions
- // Starting -> Active via startSession() and generates recording secrets.
- // Setting Active here first would prevent recording secrets from being created.
- if (resource.resourceType !== PamResource.Windows) {
- await pamSessionDAL.activateSession(session.id);
- }
-
- logger.info({ accountId, sessionId: session.id }, "Web access session established");
-
- await auditLogService.createAuditLog({
- ...auditLogInfo,
- orgId,
- projectId,
- event: {
- type: EventType.PAM_ACCOUNT_ACCESS,
- metadata: {
- accountId,
- resourceName,
- accountName,
- duration: expiresAt.toISOString(),
- reason: accessReason ?? undefined
- }
- }
- });
-
- // 8. SET UP COMMON HANDLERS
-
- const resetIdleTimer = () => {
- if (idleTimer) clearTimeout(idleTimer);
- idleTimer = setTimeout(() => {
- if (!cleanedUp) {
- void cleanup();
- sendSessionEndAndClose(socket, SessionEndReason.IdleTimeout);
- }
- }, WS_IDLE_TIMEOUT_MS);
- };
-
- resetIdleTimer();
-
- let isAlive = true;
-
- socket.on("pong", () => {
- isAlive = true;
- });
-
- pingInterval = setInterval(() => {
- if (!isAlive) {
- // Client didn't respond to last ping — connection is dead
- socket.terminate();
- return;
- }
- isAlive = false;
- if (socket.readyState === socket.OPEN) {
- socket.ping();
- }
- }, WS_PING_INTERVAL_MS);
-
- // Reset idle timer on any incoming message
- socket.on("message", () => {
- resetIdleTimer();
- });
-
- // Session expiry timer
- expiryTimer = setTimeout(() => {
- if (!cleanedUp) {
- void cleanup();
- sendSessionEndAndClose(socket, SessionEndReason.SessionCompleted);
- }
- }, sessionDurationMs);
-
- // WebSocket close/error
- socket.on("close", () => {
- logger.info({ accountId, sessionId: session?.id }, "WebSocket connection closed");
- void cleanup();
- });
-
- socket.on("error", (err: Error) => {
- logger.error(err, "WebSocket error");
- void cleanup();
- });
- } catch (err) {
- logger.error(err, "Failed to establish web access session");
- await cleanup();
- sendSessionEndAndClose(socket, SessionEndReason.SetupFailed);
- }
- };
-
- return {
- issueWebSocketTicket,
- handleWebSocketConnection
- };
-};
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
deleted file mode 100644
index aab3c97876..0000000000
--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import type WebSocket from "ws";
-import { z } from "zod";
-
-import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
-import { ProjectServiceActor } from "@app/lib/types";
-
-export enum SessionEndReason {
- SessionCompleted = "Session duration complete",
- UserQuit = "Goodbye",
- ConnectionLost = "Connection lost",
- SetupFailed = "Failed to establish connection",
- IdleTimeout = "Session closed due to inactivity",
- SessionLimitReached = "Maximum concurrent sessions reached",
- SessionGrantExpired = "Approval grant has expired"
-}
-
-export enum TerminalServerMessageType {
- Ready = "ready",
- Output = "output",
- SessionEnd = "session_end"
-}
-
-// Terminal server message schema — used by TSessionContext.sendMessage
-export const WebSocketServerMessageSchema = z.discriminatedUnion("type", [
- z.object({
- type: z.enum([TerminalServerMessageType.Ready, TerminalServerMessageType.Output]),
- data: z.string(),
- prompt: z.string().default("")
- }),
- z.object({
- type: z.literal(TerminalServerMessageType.SessionEnd),
- reason: z.nativeEnum(SessionEndReason)
- })
-]);
-
-export type TWebSocketServerMessage = z.input<typeof WebSocketServerMessageSchema>;
-
-// Default session duration for web access sessions (1 hour in ms)
-export const DEFAULT_WEB_SESSION_DURATION_MS = 60 * 60 * 1000;
-
-// Maximum concurrent web access sessions per user per project
-export const MAX_WEB_SESSIONS_PER_USER = 5;
-
-// WebSocket ping interval (ms) — keeps ALB from killing idle connections (default 60s timeout)
-export const WS_PING_INTERVAL_MS = 30000;
-
-// Idle timeout (ms) — auto-close sessions with no inbound WS traffic. The FE
-// sends an `activity` heartbeat while its browser tab is visible, so this fires
-// only when the tab has been hidden/backgrounded for the full window.
-export const WS_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
-
-export type TEarlyBufferedMsg = { data: Buffer; isBinary: boolean };
-
-export type TSessionContext = {
- socket: WebSocket;
- relayPort: number;
- resourceName: string;
- sessionId: string;
- sendMessage: (msg: TWebSocketServerMessage) => void;
- sendSessionEnd: (reason: SessionEndReason) => void;
- isNearSessionExpiry: () => boolean;
- onCleanup: () => void;
- earlyMessages: TEarlyBufferedMsg[];
- releaseEarlyBuffer: () => void;
-};
-
-export type TSessionHandlerResult = {
- cleanup: () => Promise<void>;
-};
-
-export type TIssueWebSocketTicketDTO = {
- accountId: string;
- projectId: string;
- orgId: string;
- actor: ProjectServiceActor;
- actorEmail: string;
- actorName: string;
- auditLogInfo: AuditLogInfo;
- mfaSessionId?: string;
- reason?: string;
- resourceId?: string;
-};
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index 48c303e90e..222f24e93c 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -22,3 +22,8 @@ export enum PamProductRole {
Admin = "admin",
Member = "member"
}
+
+export enum PamRecordingStorageBackend {
+ Postgres = "postgres",
+ AwsS3 = "aws-s3"
+}
diff --git a/backend/src/ee/services/pam/pam-template-config-schemas.ts b/backend/src/ee/services/pam/pam-template-config-schemas.ts
index 8d693fb07d..df73789c66 100644
--- a/backend/src/ee/services/pam/pam-template-config-schemas.ts
+++ b/backend/src/ee/services/pam/pam-template-config-schemas.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { PamRecordingStorageBackend } from "../pam-session-recording-storage/pam-session-recording-storage-enums";
+import { PamRecordingStorageBackend } from "./pam-enums";
export const PamPasswordConstraintsSchema = z.object({
minLength: z.number().int().min(1).max(256),
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 26fa9f6299..1bd9c2a533 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -95,38 +95,7 @@ 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 { pamAccountPolicyDALFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-dal";
-import { pamAccountPolicyServiceFactory } from "@app/ee/services/pam-account-policy/pam-account-policy-service";
-import { pamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";
-import { pamDiscoveryQueueFactory } from "@app/ee/services/pam-discovery/pam-discovery-queue";
-import { pamDiscoverySourceAccountsDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-accounts-dal";
-import { pamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";
-import { pamDiscoverySourceDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dependencies-dal";
-import { pamDiscoverySourceResourcesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-resources-dal";
-import { pamDiscoveryRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-run-dal";
-import { pamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";
-import { pamDomainDALFactory } from "@app/ee/services/pam-domain/pam-domain-dal";
-import { pamDomainServiceFactory } from "@app/ee/services/pam-domain/pam-domain-service";
-import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";
-import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
-import { 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";
-import { pamResourceFavoriteDALFactory } from "@app/ee/services/pam-resource/pam-resource-favorite-dal";
-import { pamResourceRotationRulesDALFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-dal";
-import { pamResourceRotationRulesServiceFactory } from "@app/ee/services/pam-resource/pam-resource-rotation-rules-service";
-import { pamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";
-import { pamSessionAiSummaryServiceFactory } from "@app/ee/services/pam-session/pam-session-ai-summary-queue";
-import { pamSessionChunkServiceFactory } from "@app/ee/services/pam-session/pam-session-chunk-service";
-import { pamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
-import { pamSessionEventBatchDALFactory } from "@app/ee/services/pam-session/pam-session-event-batch-dal";
-import { pamSessionEventChunkDALFactory } from "@app/ee/services/pam-session/pam-session-event-chunk-dal";
-import { pamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
-import { pamWebAccessServiceFactory } from "@app/ee/services/pam-web-access/pam-web-access-service";
import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";
import { pitServiceFactory } from "@app/ee/services/pit/pit-service";
@@ -395,8 +364,6 @@ import { orgAssetDALFactory } from "@app/services/org-asset/org-asset-dal";
import { orgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
import { orgProductStatsDALFactory } from "@app/services/org-product-stats/org-product-stats-dal";
import { orgProductStatsServiceFactory } from "@app/services/org-product-stats/org-product-stats-service";
-import { pamAccountRotationServiceFactory } from "@app/services/pam-account-rotation/pam-account-rotation-queue";
-import { pamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
import { dailyExpiringPkiItemAlertQueueServiceFactory } from "@app/services/pki-alert/expiring-pki-item-alert-queue";
import { pkiAlertDALFactory } from "@app/services/pki-alert/pki-alert-dal";
import { pkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service";
@@ -1385,9 +1352,6 @@ export const registerRoutes = async (
const orgGatewayConfigV2DAL = orgGatewayConfigV2DalFactory(db);
- const pamResourceDAL = pamResourceDALFactory(db);
- const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);
- const pamDomainDAL = pamDomainDALFactory(db);
const aiMcpServerDAL = aiMcpServerDALFactory(db);
const sshCertificateAuthorityService = sshCertificateAuthorityServiceFactory({
@@ -1622,8 +1586,6 @@ export const registerRoutes = async (
smtpService,
appConnectionDAL,
dynamicSecretDAL,
- pamResourceDAL,
- pamDiscoverySourceDAL,
identityKubernetesAuthDAL,
aiMcpServerDAL,
pkiDiscoveryConfigDAL,
@@ -1639,9 +1601,6 @@ export const registerRoutes = async (
licenseService,
identityKubernetesAuthDAL,
pkiDiscoveryConfigDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamDiscoverySourceDAL,
appConnectionDAL,
dynamicSecretDAL
});
@@ -3210,21 +3169,6 @@ export const registerRoutes = async (
appConnectionDAL
});
- const pamFolderDAL = pamFolderDALFactory(db);
- const pamResourceFavoriteDAL = pamResourceFavoriteDALFactory(db);
- const pamAccountDAL = pamAccountDALFactory(db);
- const pamAccountPolicyDAL = pamAccountPolicyDALFactory(db);
- const pamSessionDAL = pamSessionDALFactory(db);
- const pamSessionEventBatchDAL = pamSessionEventBatchDALFactory(db);
- const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);
- const pamProjectRecordingConfigDAL = pamProjectRecordingConfigDALFactory(db);
- const pamDiscoveryRunDAL = pamDiscoveryRunDALFactory(db);
- const pamDiscoverySourceResourcesDAL = pamDiscoverySourceResourcesDALFactory(db);
- const pamDiscoverySourceAccountsDAL = pamDiscoverySourceAccountsDALFactory(db);
- const pamDiscoverySourceDependenciesDAL = pamDiscoverySourceDependenciesDALFactory(db);
- const pamAccountDependenciesDAL = pamAccountDependenciesDALFactory(db);
- const pamResourceRotationRulesDAL = pamResourceRotationRulesDALFactory(db);
-
const aiMcpServerToolDAL = aiMcpServerToolDALFactory(db);
const aiMcpServerUserCredentialDAL = aiMcpServerUserCredentialDALFactory(db);
const aiMcpActivityLogDAL = aiMcpActivityLogDALFactory(db);
@@ -3232,58 +3176,6 @@ export const registerRoutes = async (
const aiMcpEndpointServerDAL = aiMcpEndpointServerDALFactory(db);
const aiMcpEndpointServerToolDAL = aiMcpEndpointServerToolDALFactory(db);
- const pamFolderService = pamFolderServiceFactory({
- pamFolderDAL,
- permissionService
- });
-
- const pamProjectRecordingConfigService = pamProjectRecordingConfigServiceFactory({
- pamProjectRecordingConfigDAL,
- pamSessionDAL,
- permissionService,
- appConnectionService,
- appConnectionDAL,
- kmsService
- });
-
- const pamSessionChunkService = pamSessionChunkServiceFactory({
- pamSessionDAL,
- pamSessionEventChunkDAL,
- permissionService,
- kmsService,
- pamProjectRecordingConfigService
- });
-
- const pamResourceService = pamResourceServiceFactory({
- pamResourceDAL,
- pamResourceFavoriteDAL,
- pamDomainDAL,
- pamAccountDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- resourceMetadataDAL,
- appConnectionDAL,
- pamProjectRecordingConfigDAL
- });
-
- const pamDomainService = pamDomainServiceFactory({
- pamDomainDAL,
- pamResourceDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- resourceMetadataDAL
- });
-
- const pamResourceRotationRulesService = pamResourceRotationRulesServiceFactory({
- pamResourceRotationRulesDAL,
- pamResourceDAL,
- permissionService
- });
-
const mfaSessionService = mfaSessionServiceFactory({
keyStore,
tokenService,
@@ -3291,136 +3183,6 @@ export const registerRoutes = async (
totpService
});
- const pamSessionAiSummaryService = pamSessionAiSummaryServiceFactory({
- queueService,
- pamSessionDAL,
- pamSessionEventBatchDAL,
- pamResourceDAL,
- appConnectionDAL,
- kmsService
- });
-
- const pamSessionExpirationService = pamSessionExpirationServiceFactory({
- queueService,
- pamSessionDAL,
- pamSessionAiSummaryService
- });
-
- const pamAccountPolicyService = pamAccountPolicyServiceFactory({
- pamAccountPolicyDAL,
- permissionService
- });
-
- const pamAccountService = pamAccountServiceFactory({
- pamAccountDAL,
- pamDomainDAL,
- pamAccountPolicyDAL,
- pamResourceRotationRulesDAL,
- gatewayV2Service,
- gatewayPoolService,
- kmsService,
- pamResourceDAL,
- pamSessionDAL,
- permissionService,
- projectDAL,
- orgDAL,
- userDAL,
- auditLogService,
- mfaSessionService,
- tokenService,
- smtpService,
- approvalRequestGrantsDAL,
- approvalPolicyDAL,
- pamSessionExpirationService,
- resourceMetadataDAL,
- pamAccountDependenciesDAL,
- keyStore,
- pamProjectRecordingConfigDAL,
- pamProjectRecordingConfigService
- });
-
- const pamAccountRotation = pamAccountRotationServiceFactory({
- cronJob,
- pamAccountService
- });
-
- const pamSessionService = pamSessionServiceFactory({
- pamSessionDAL,
- pamSessionEventBatchDAL,
- projectDAL,
- userDAL,
- permissionService,
- kmsService,
- gatewayV2Service,
- pamSessionAiSummaryService
- });
-
- const pamInsightsService = pamInsightsServiceFactory({
- permissionService,
- pamSessionDAL,
- pamResourceDAL,
- pamAccountDAL,
- pamResourceRotationRulesDAL,
- keyStore
- });
-
- const pamWebAccessService = pamWebAccessServiceFactory({
- pamAccountDAL,
- pamDomainDAL,
- pamAccountPolicyDAL,
- pamResourceDAL,
- pamProjectRecordingConfigDAL,
- permissionService,
- auditLogService,
- tokenService,
- pamSessionDAL,
- pamSessionExpirationService,
- gatewayV2Service,
- gatewayPoolService,
- kmsService,
- userDAL,
- mfaSessionService,
- approvalPolicyDAL,
- approvalRequestGrantsDAL,
- orgDAL,
- projectDAL
- });
-
- const pamDiscoveryQueue = pamDiscoveryQueueFactory({
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamDomainDAL,
- pamResourceDAL,
- pamAccountDAL,
- kmsService,
- queueService,
- cronJob,
- gatewayV2Service,
- gatewayV2DAL,
- gatewayPoolService
- });
-
- const pamDiscoverySourceService = pamDiscoverySourceServiceFactory({
- pamDiscoverySourceDAL,
- pamDiscoveryRunDAL,
- pamDiscoverySourceResourcesDAL,
- pamDiscoverySourceAccountsDAL,
- pamDiscoverySourceDependenciesDAL,
- pamAccountDependenciesDAL,
- pamAccountDAL,
- pamResourceDAL,
- permissionService,
- kmsService,
- gatewayV2DAL,
- gatewayV2Service,
- gatewayPoolService,
- pamDiscoveryQueue
- });
-
const aiMcpServerService = aiMcpServerServiceFactory({
aiMcpServerDAL,
aiMcpServerToolDAL,
@@ -3510,10 +3272,6 @@ export const registerRoutes = async (
healthAlert.init();
pkiSyncCleanup.init();
pkiDiscoveryQueue.startPkiDiscoveryScanQueue();
- pamDiscoveryQueue.startPamDiscoveryQueue();
- pamAccountRotation.init();
- pamSessionExpirationService.init();
- pamSessionAiSummaryService.init();
dailyReminderQueueService.startDailyRemindersJob();
secretSyncQueue.startDailySecretSyncRetryJob();
dailyExpiringPkiItemAlert.startSendingAlerts();
@@ -3662,7 +3420,6 @@ export const registerRoutes = async (
microsoftTeams: microsoftTeamsService,
assumePrivileges: assumePrivilegeService,
insights: insightsService,
- pamInsights: pamInsightsService,
githubOrgSync: githubOrgSyncConfigService,
honeyTokenConfig: honeyTokenConfigService,
honeyToken: honeyTokenService,
@@ -3674,17 +3431,6 @@ export const registerRoutes = async (
projectEventsSSE: projectEventsSSEService,
notification: notificationService,
announcement: announcementService,
- pamFolder: pamFolderService,
- pamResource: pamResourceService,
- pamDomain: pamDomainService,
- pamResourceRotationRules: pamResourceRotationRulesService,
- pamAccount: pamAccountService,
- pamAccountPolicy: pamAccountPolicyService,
- pamSession: pamSessionService,
- pamSessionChunk: pamSessionChunkService,
- pamProjectRecordingConfig: pamProjectRecordingConfigService,
- pamWebAccess: pamWebAccessService,
- pamDiscoverySource: pamDiscoverySourceService,
mfaSession: mfaSessionService,
membershipUser: membershipUserService,
membershipIdentity: membershipIdentityService,
diff --git a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts b/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts
deleted file mode 100644
index 0f7b0f9dd2..0000000000
--- a/backend/src/services/pam-account-rotation/pam-account-rotation-queue.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
-import { getConfig } from "@app/lib/config/env";
-import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
-import { logger } from "@app/lib/logger";
-
-type TPamAccountRotationServiceFactoryDep = {
- cronJob: TCronJobFactory;
- pamAccountService: Pick<TPamAccountServiceFactory, "rotateAllDueAccounts">;
-};
-
-export type TPamAccountRotationServiceFactory = ReturnType<typeof pamAccountRotationServiceFactory>;
-
-export const pamAccountRotationServiceFactory = ({
- cronJob,
- pamAccountService
-}: TPamAccountRotationServiceFactoryDep) => {
- const appCfg = getConfig();
-
- const init = () => {
- cronJob.register({
- name: CronJobName.PamAccountRotation,
- pattern: "0 * * * *",
- runHashTtlS: 1 * 24 * 60 * 60,
- enabled: !appCfg.isSecondaryInstance,
- handler: async () => {
- logger.info("cron[pam-account-rotation]: task started");
- await pamAccountService.rotateAllDueAccounts();
- }
- });
- };
-
- return {
- init
- };
-};
diff --git a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts b/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts
deleted file mode 100644
index 572ff888ff..0000000000
--- a/backend/src/services/pam-session-expiration/pam-session-expiration-queue.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { TPamSessionAiSummaryServiceFactory } from "@app/ee/services/pam-session/pam-session-ai-summary-queue";
-import { TPamSessionDALFactory } from "@app/ee/services/pam-session/pam-session-dal";
-import { getConfig } from "@app/lib/config/env";
-import { logger } from "@app/lib/logger";
-import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
-
-type TPamSessionExpirationServiceFactoryDep = {
- queueService: TQueueServiceFactory;
- pamSessionDAL: Pick<TPamSessionDALFactory, "expireSessionById" | "findById">;
- pamSessionAiSummaryService: Pick<TPamSessionAiSummaryServiceFactory, "queueAiSummary">;
-};
-
-export type TPamSessionExpirationServiceFactory = ReturnType<typeof pamSessionExpirationServiceFactory>;
-
-export const pamSessionExpirationServiceFactory = ({
- queueService,
- pamSessionDAL,
- pamSessionAiSummaryService
-}: TPamSessionExpirationServiceFactoryDep) => {
- const appCfg = getConfig();
-
- const init = () => {
- if (appCfg.isSecondaryInstance) {
- return;
- }
-
- queueService.start(QueueName.PamSessionExpiration, async (job) => {
- const { sessionId } = job.data;
- try {
- logger.info({ sessionId }, `${QueueName.PamSessionExpiration}: expiring session [sessionId=${sessionId}]`);
- const updated = await pamSessionDAL.expireSessionById(sessionId);
- const session =
- updated > 0
- ? await pamSessionDAL.findById(sessionId).catch((err: unknown) => {
- logger.warn(
- { sessionId, err },
- `${QueueName.PamSessionExpiration}: failed to fetch session for AI summary, skipping [sessionId=${sessionId}]`
- );
- return null;
- })
- : null;
- if (updated > 0) {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionExpiration}: session expired successfully [sessionId=${sessionId}]`
- );
- if (session?.projectId) {
- void (async () => {
- try {
- await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
- } catch (err) {
- logger.error(
- { sessionId, err },
- `${QueueName.PamSessionExpiration}: failed to queue AI summary [sessionId=${sessionId}]`
- );
- }
- })();
- }
- } else {
- logger.info(
- { sessionId },
- `${QueueName.PamSessionExpiration}: session not expired (already ended or not found) [sessionId=${sessionId}]`
- );
- }
- } catch (error) {
- logger.error(error, `${QueueName.PamSessionExpiration}: failed to expire session [sessionId=${sessionId}]`);
- throw error;
- }
- });
- };
-
- // Schedule a session expiration job to run at the session's expiresAt time
- const scheduleSessionExpiration = async (sessionId: string, expiresAt: Date) => {
- const now = new Date();
- const delayMs = Math.max(0, expiresAt.getTime() - now.getTime());
- const startAfter = new Date(now.getTime() + delayMs);
-
- await queueService.queue(
- QueueName.PamSessionExpiration,
- QueueJobs.PamSessionExpiration,
- { sessionId },
- {
- jobId: `pam-session-expiration-${sessionId}`,
- delay: delayMs
- }
- );
-
- logger.info(
- { sessionId, expiresAt: expiresAt.toISOString(), scheduledFor: startAfter.toISOString() },
- `${QueueName.PamSessionExpiration}: scheduled session expiration`
- );
- };
-
- return {
- init,
- scheduleSessionExpiration
- };
-};