Skip to content

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

58.6 KB
Raw Blame
import { createMongoAbility, ForbiddenError, MongoAbility, MongoQuery, RawRuleOf } from "@casl/ability";
import { packRules } from "@casl/ability/extra";

import { RESOURCE_SCOPE, ResourceType, TPamAccountTemplates } from "@app/db/schemas";
import { TGatewayPoolMembershipDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-membership-dal";
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 { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
  ResourcePermissionPamResourceActions,
  ResourcePermissionSet,
  ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
import { conditionsMatcher } from "@app/lib/casl";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { hasPostgresErrorCode } from "@app/lib/errors/postgres";
import { logger } from "@app/lib/logger";
import { createSshKeyPair, SshCertKeyAlgorithm } from "@app/lib/ssh";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { ApprovalAccessStatus } from "@app/services/approval-policy/approval-policy-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 { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";

import { testBuiltConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";
import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import {
  HEARTBEAT_PAUSED_FOR_ROUTING_CHANGE,
  pausesHeartbeatForRoutingChange
} from "../pam-account-heartbeat/pam-heartbeat-fns";
import { TPamAccountTemplateDALFactory } from "../pam-account-template/pam-account-template-dal";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import { terminatePamSessions } from "../pam-session/pam-session-fns";
import {
  accountTypeSupportsSessionLogMasking,
  PamAccessType,
  PamAccountType,
  PamAccountWarning,
  PamHeartbeatStatus,
  PamProductRole,
  PamSessionStatus
} from "../pam/pam-enums";
import { enforceMfa } from "../pam/pam-mfa";
import {
  accountAccessAllows,
  checkAccountAccess,
  checkFolderPermission,
  getAccountPermissionRulesMap,
  getResourceIdsWithActions,
  TActorContext,
  verifyProductMembership
} from "../pam/pam-permission";
import { resolveAccessControls } from "../pam/pam-policies";
import {
  getInheritedRecordingS3Config,
  mintCorsProbeUrl,
  resolveOverridesS3Config,
  validateGatewayAttachment,
  validateRecordingConnection
} from "../pam/pam-validators";
import {
  buildGatewayConnectionTest,
  CLOUD_CONNECTION_VALIDATORS,
  testVerifiesCredential
} from "./pam-account-connection-test";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
  ACCOUNT_TYPE_CONFIGS,
  applyForcedFields,
  gatewaySupportsAccountType,
  gatewaySupportsClickHouseNative,
  getAccountAccessibilityIssues,
  hasRevealableCredential,
  isCredentialConfigured,
  noRevealableCredentialMessage,
  normalizeCredentialAuthMethod,
  ORACLE_MAX_PASSWORD_LENGTH,
  PamAccountAccessibilityIssue,
  parseInternalMetadata,
  requiresClickHouseNative,
  sanitizeCredentials,
  suppliesCredentialSecret,
  type TSshInternalMetadata,
  type TSupportedAccountType,
  validateConnectionDetails,
  validateCredentials,
  webAccessUnavailableReason
} from "./pam-account-schemas";
import {
  TCreatePamAccountDTO,
  TDeletePamAccountDTO,
  TGetPamAccountCredentialsDTO,
  TGetPamAccountDTO,
  TListAccessibleAccountsDTO,
  TListPamAccountsDTO,
  TUpdatePamAccountDTO
} from "./pam-account-types";

type TPamAccountServiceFactoryDep = {
  pamAccountDAL: TPamAccountDALFactory;
  pamFolderDAL: Pick<TPamFolderDALFactory, "findById">;
  pamAccountTemplateDAL: Pick<TPamAccountTemplateDALFactory, "findById">;
  membershipDAL: Pick<TMembershipDALFactory, "find" | "delete" | "findResourceMembershipsForActor">;
  membershipRoleDAL: Pick<TMembershipRoleDALFactory, "delete" | "find">;
  pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;
  pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "find">;
  userDAL: Pick<TUserDALFactory, "findById">;
  orgDAL: Pick<TOrgDALFactory, "findOrgById" | "findById">;
  mfaSessionService: Pick<
    TMfaSessionServiceFactory,
    "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
  >;
  permissionService: Pick<
    TPermissionServiceFactory,
    "getProjectPermission" | "getResourcePermission" | "getOrgPermission"
  >;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne" | "find">;
  gatewayPoolMembershipDAL: Pick<TGatewayPoolMembershipDALFactory, "findHealthyGatewaysByPoolId">;
  gatewayV2Service: Pick<
    TGatewayV2ServiceFactory,
    "getPlatformConnectionDetailsByGatewayId" | "getPAMConnectionDetails"
  >;
  gatewayPoolService: Pick<
    TGatewayPoolServiceFactory,
    "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "assertGatewayBindingInOrg"
  >;
  appConnectionDAL: Pick<TAppConnectionDALFactory, "findOne" | "findById">;
  pamAccessRequestService: Pick<
    TPamAccessRequestServiceFactory,
    | "getAccessStatusBatch"
    | "getFolderPolicyConfigured"
    | "getBreakGlassUserFolders"
    | "cleanupAccountResources"
    | "checkGrant"
  >;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
};

const assertOraclePasswordIsUsable = (accountType: PamAccountType, credentials: unknown) => {
  if (accountType !== PamAccountType.OracleDB) return;
  const { password } = credentials as { password?: string };
  if (!password || password.length <= ORACLE_MAX_PASSWORD_LENGTH) return;
  throw new BadRequestError({
    message: `The gateway cannot sign in to Oracle with a password longer than ${ORACLE_MAX_PASSWORD_LENGTH} characters, so this account could not be checked or rotated. Use a password of ${ORACLE_MAX_PASSWORD_LENGTH} characters or fewer.`
  });
};

const assertPasswordMeetsRequirements = (credentials: unknown, templateSettings: unknown) => {
  const requirements = PamTemplateSettingsSchema.safeParse(templateSettings).data?.passwordRequirements;
  const { password } = credentials as { password?: string };
  if (!requirements || !password) return;

  let upper = 0;
  let lower = 0;
  let digit = 0;
  let symbol = 0;
  const allowed = requirements.allowedSymbols ? new Set(requirements.allowedSymbols.split("")) : null;
  const disallowed = new Set<string>();
  for (const ch of password) {
    if (ch >= "A" && ch <= "Z") upper += 1;
    else if (ch >= "a" && ch <= "z") lower += 1;
    else if (ch >= "0" && ch <= "9") digit += 1;
    else {
      symbol += 1;
      if (allowed && !allowed.has(ch)) disallowed.add(ch);
    }
  }

  const violations: string[] = [];
  if (password.length < requirements.length) violations.push(`be at least ${requirements.length} characters long`);
  if (upper < requirements.required.uppercase)
    violations.push(`include at least ${requirements.required.uppercase} uppercase letter(s)`);
  if (lower < requirements.required.lowercase)
    violations.push(`include at least ${requirements.required.lowercase} lowercase letter(s)`);
  if (digit < requirements.required.digits)
    violations.push(`include at least ${requirements.required.digits} number(s)`);
  if (symbol < requirements.required.symbols)
    violations.push(`include at least ${requirements.required.symbols} symbol(s)`);
  if (allowed && disallowed.size > 0) violations.push(`only use these symbols: ${requirements.allowedSymbols}`);

  if (violations.length > 0) {
    throw new BadRequestError({
      message: `Password does not meet this template's requirements: it must ${violations.join(", ")}.`
    });
  }
};

const CONNECTION_TEST_TIMEOUT_MS = 15_000;

export type TPamAccountServiceFactory = ReturnType<typeof pamAccountServiceFactory>;

export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) => {
  const {
    pamAccountDAL,
    pamFolderDAL,
    pamAccountTemplateDAL,
    membershipDAL,
    membershipRoleDAL,
    pamSessionDAL,
    pamDiscoverySourceDAL,
    userDAL,
    orgDAL,
    mfaSessionService,
    permissionService,
    kmsService,
    gatewayV2Service,
    gatewayPoolService,
    gatewayPoolMembershipDAL,
    gatewayV2DAL,
    licenseService
  } = deps;

  const getProjectCipher = async (projectId: string) =>
    kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });

  const encrypt = async (projectId: string, data: Record<string, unknown>) => {
    const { encryptor } = await getProjectCipher(projectId);
    return encryptor({ plainText: Buffer.from(JSON.stringify(data)) }).cipherTextBlob;
  };

  const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
    const { decryptor } = await getProjectCipher(projectId);
    return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;
  };

  const computeAccessibility = (a: {
    accountType: string;
    gatewayId?: string | null;
    gatewayPoolId?: string | null;
    recordingConnectionId?: string | null;
    templateGatewayId: string | null;
    templateGatewayPoolId: string | null;
    templateRecordingConnectionId: string | null;
    settingsOverrides?: unknown;
    templateSettings: unknown;
    credentialConfigured: boolean;
  }) => {
    const accessibilityIssues = getAccountAccessibilityIssues(a);
    return { isAccessible: accessibilityIssues.length === 0, accessibilityIssues };
  };

  // The gateway performs the masking, so a build predating built-in detection ignores the
  // template's setting without reporting anything. Derived server-side because listing gateways is
  // an org-admin permission, and a PAM member who can see the account must still see this.
  const $resolveMaskingDegraded = async (
    orgId: string,
    accounts: {
      accountType: string;
      gatewayId?: string | null;
      gatewayPoolId?: string | null;
      templateGatewayId: string | null;
      templateGatewayPoolId: string | null;
      templateSettings: unknown;
    }[]
  ) => {
    const candidates = accounts.map((a) => ({
      enabled:
        accountTypeSupportsSessionLogMasking(a.accountType as PamAccountType) &&
        PamTemplateSettingsSchema.safeParse(a.templateSettings).data?.sessionLogMaskingBuiltInDetection === true,
      // Mirrors the session launch path: each field falls back to the template independently,
      // and a direct gateway wins over a pool.
      gatewayId: a.gatewayId ?? a.templateGatewayId,
      gatewayPoolId: a.gatewayPoolId ?? a.templateGatewayPoolId
    }));

    if (!candidates.some((c) => c.enabled)) return candidates.map(() => false);

    const supportsMasking = (gateway: { capabilities?: unknown }) =>
      (gateway.capabilities as { sessionLogMaskingBuiltInDetection?: boolean } | undefined)
        ?.sessionLogMaskingBuiltInDetection === true;

    // Only reachable members can serve a session, so an offline one lacking the capability must not
    // make the account look degraded. Same reachability filter pool selection uses.
    const poolIds = [
      ...new Set(candidates.filter((c) => c.enabled && !c.gatewayId && c.gatewayPoolId).map((c) => c.gatewayPoolId!))
    ];
    const poolDegraded = new Map<string, boolean>();
    await Promise.all(
      poolIds.map(async (poolId) => {
        const healthy = await gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);
        poolDegraded.set(
          poolId,
          healthy.some((gateway) => !supportsMasking(gateway))
        );
      })
    );

    const directIds = [...new Set(candidates.filter((c) => c.enabled && c.gatewayId).map((c) => c.gatewayId!))];
    const unsupported = new Set(
      directIds.length
        ? (await gatewayV2DAL.find({ orgId, $in: { id: directIds } }))
            .filter((g) => !supportsMasking(g))
            .map((g) => g.id)
        : []
    );

    return candidates.map((c) => {
      if (!c.enabled) return false;
      if (c.gatewayId) return unsupported.has(c.gatewayId);
      return poolDegraded.get(c.gatewayPoolId ?? "") ?? false;
    });
  };

  const verifyMembership = (projectId: string, ctx: TActorContext) =>
    verifyProductMembership(permissionService, projectId, ctx);

  const checkFolder = (folderId: string, projectId: string, ctx: TActorContext) =>
    checkFolderPermission(permissionService, folderId, projectId, ctx);

  const list = async ({
    projectId,
    folderId,
    templateId,
    accountType,
    search,
    ...ctx
  }: TListPamAccountsDTO & TActorContext) => {
    await verifyMembership(projectId, ctx);

    const { folderIds, accountIds } = await getResourceIdsWithActions(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      { allOf: [ResourcePermissionPamResourceActions.ReadAccounts] },
      ctx
    );
    if (folderIds.length === 0 && accountIds.length === 0) return [];

    const { accounts } = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds, {
      folderId,
      templateId,
      accountType,
      search
    });

    const accountsRequiringApproval = accounts.filter(
      (a) => resolveAccessControls(a.templatePolicies).requiresApproval
    );
    const accountIdsRequiringApproval = accountsRequiringApproval.map((a) => a.id);

    const folderIdsRequiringApproval = [
      ...new Set(accountsRequiringApproval.map((a) => a.folderId).filter(Boolean) as string[])
    ];

    const { decryptor } = await getProjectCipher(projectId);
    const revealableById = new Map(
      accounts.map((a) => [
        a.id,
        hasRevealableCredential(
          a.accountType as PamAccountType,
          JSON.parse(decryptor({ cipherTextBlob: a.encryptedCredentials }).toString("utf-8")) as Record<string, unknown>
        )
      ])
    );

    const [
      accessStatusMap,
      credentialAccessStatusMap,
      foldersWithApprovalPolicy,
      breakGlassFolders,
      permissionsByAccountId
    ] = await Promise.all([
      deps.pamAccessRequestService.getAccessStatusBatch(
        { actorId: ctx.actorId, actor: ctx.actor },
        accountIdsRequiringApproval,
        projectId
      ),
      deps.pamAccessRequestService.getAccessStatusBatch(
        { actorId: ctx.actorId, actor: ctx.actor },
        accountIdsRequiringApproval,
        projectId,
        PamAccessType.Credential
      ),
      deps.pamAccessRequestService.getFolderPolicyConfigured(folderIdsRequiringApproval),
      deps.pamAccessRequestService.getBreakGlassUserFolders(
        folderIdsRequiringApproval,
        { actorId: ctx.actorId, actor: ctx.actor },
        ctx.actorOrgId
      ),
      // Resolve every account's effective permissions in one membership fetch
      getAccountPermissionRulesMap(
        membershipDAL,
        membershipRoleDAL,
        projectId,
        accounts.map((a) => ({ id: a.id, folderId: a.folderId })),
        ctx
      )
    ]);

    const maskingDegraded = await $resolveMaskingDegraded(ctx.actorOrgId, accounts);

    return accounts.map((a, idx) => {
      const { accessibilityIssues, isAccessible } = computeAccessibility(a);
      const { requiresApproval, requireReason, allowBreakGlass, allowAutoApproval } = resolveAccessControls(
        a.templatePolicies
      );
      const statusEntry = accessStatusMap.get(a.id);
      const credentialStatusEntry = credentialAccessStatusMap.get(a.id);
      const canBreakGlass = allowBreakGlass && !!a.folderId && breakGlassFolders.has(a.folderId);
      const hasGrant =
        statusEntry?.accessStatus === ApprovalAccessStatus.Granted ||
        credentialStatusEntry?.accessStatus === ApprovalAccessStatus.Granted;
      // Break-glass users and current grant holders can still reach a folder whose approvers and rules can't
      // grant this account; only new requests are blocked
      if (
        requiresApproval &&
        a.folderId &&
        !canBreakGlass &&
        !hasGrant &&
        !foldersWithApprovalPolicy.isConfiguredFor(a.folderId, allowAutoApproval)
      ) {
        accessibilityIssues.push(PamAccountAccessibilityIssue.NoApprovalConfig);
      }
      return {
        id: a.id,
        name: a.name,
        description: a.description,
        folderId: a.folderId,
        folderName: a.folderName,
        templateId: a.templateId,
        templateName: a.templateName,
        accountType: a.accountType,
        projectId: a.projectId,
        gatewayId: a.gatewayId,
        gatewayPoolId: a.gatewayPoolId,
        recordingConnectionId: a.recordingConnectionId,
        isAccessible: isAccessible && accessibilityIssues.length === 0,
        accessibilityIssues,
        isStale: a.isStale,
        warnings: maskingDegraded[idx] ? [PamAccountWarning.SessionLogMaskingDegraded] : [],
        heartbeatStatus: (a.heartbeatStatus as PamHeartbeatStatus | null) ?? null,
        heartbeatEnabled: Boolean(a.heartbeatEnabled),
        requiresApproval,
        supportsCredentialReveal: revealableById.get(a.id) ?? false,
        requireReason,
        accessStatus: requiresApproval
          ? (statusEntry?.accessStatus ?? ApprovalAccessStatus.None)
          : ApprovalAccessStatus.None,
        grantExpiresAt: statusEntry?.grantExpiresAt ?? null,
        pendingRequestId: statusEntry?.pendingRequestId ?? null,
        canBreakGlass,
        credentialAccessStatus: requiresApproval
          ? (credentialStatusEntry?.accessStatus ?? ApprovalAccessStatus.None)
          : ApprovalAccessStatus.None,
        credentialPendingRequestId: credentialStatusEntry?.pendingRequestId ?? null,
        permissions: permissionsByAccountId.get(a.id) ?? [],
        createdAt: a.createdAt,
        updatedAt: a.updatedAt
      };
    });
  };

  const checkAccount = (
    accountId: string,
    folderId: string | null | undefined,
    projectId: string,
    action: ResourcePermissionPamResourceActions,
    ctx: TActorContext
  ) => checkAccountAccess(permissionService, accountId, folderId, projectId, action, ctx);

  const getById = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {
    const account = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!account || account.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.ReadAccounts, ctx);

    const connectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);
    const credentials = sanitizeCredentials(
      account.accountType as PamAccountType,
      await decrypt(projectId, account.encryptedCredentials)
    );

    return {
      id: account.id,
      name: account.name,
      description: account.description,
      folderId: account.folderId,
      folderName: account.folderName,
      templateId: account.templateId,
      templateName: account.templateName,
      templatePolicies: account.templatePolicies,
      templateSettings: account.templateSettings,
      accountType: account.accountType,
      projectId: account.projectId,
      gatewayId: account.gatewayId,
      gatewayPoolId: account.gatewayPoolId,
      recordingConnectionId: account.recordingConnectionId,
      settingsOverrides: account.settingsOverrides ?? null,
      connectionDetails,
      credentials,
      webAccessUnavailableReason: webAccessUnavailableReason(account.accountType as PamAccountType, connectionDetails),
      ...computeAccessibility(account),
      isStale: account.isStale,
      createdAt: account.createdAt,
      updatedAt: account.updatedAt
    };
  };

  const getCredentials = async ({
    accountId,
    projectId,
    actorEmail,
    reason,
    mfaSessionId,
    tokenVersionId,
    ...ctx
  }: TGetPamAccountCredentialsDTO & TActorContext) => {
    await verifyMembership(projectId, ctx);

    const account = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!account || account.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    await checkAccount(
      accountId,
      account.folderId,
      projectId,
      ResourcePermissionPamResourceActions.ViewCredentials,
      ctx
    );

    const accountType = account.accountType as PamAccountType;
    const policy = resolveAccessControls(account.templatePolicies);
    const trimmedReason = reason?.trim() || null;

    let grantExpiresAt: Date | null = null;
    if (policy.requiresApproval) {
      const grant = await deps.pamAccessRequestService.checkGrant({
        actorId: ctx.actorId,
        actor: ctx.actor,
        accountId: account.id,
        accountFolderId: account.folderId,
        projectId,
        accessType: PamAccessType.Credential
      });
      if (!grant) {
        throw new ForbiddenRequestError({
          name: "PAM_APPROVAL_REQUIRED",
          message: "Approval is required to view this account's credentials"
        });
      }

      if (grant.expiresAt) {
        if (new Date(grant.expiresAt).getTime() <= Date.now()) {
          throw new ForbiddenRequestError({
            name: "PAM_GRANT_EXPIRED",
            message: "Your approved credential access has expired"
          });
        }
        grantExpiresAt = new Date(grant.expiresAt);
      }
    }

    if (policy.requireReason && !trimmedReason) {
      throw new BadRequestError({
        name: "PAM_REASON_REQUIRED",
        message: "A reason is required to view this account's credentials"
      });
    }

    if (policy.requireMfa) {
      if (ctx.actor !== ActorType.USER) {
        throw new ForbiddenRequestError({
          message:
            "This account requires MFA verification, which machine identities cannot perform. Remove the MFA policy from the account's template to allow machine identity access."
        });
      }
      await enforceMfa(
        { mfaSessionService, orgDAL, userDAL },
        {
          userId: ctx.actorId,
          orgId: ctx.actorOrgId,
          actorEmail,
          accountId: account.id,
          mfaSessionId,
          tokenVersionId
        }
      );
    }

    const credentials = normalizeCredentialAuthMethod(
      accountType,
      await decrypt(projectId, account.encryptedCredentials)
    );
    if (!hasRevealableCredential(accountType, credentials)) {
      throw new BadRequestError({ message: noRevealableCredentialMessage(account.name) });
    }

    return {
      accountId: account.id,
      accountName: account.name,
      folderName: account.folderName,
      accountType,
      folderId: account.folderId,
      credentials,
      grantExpiresAt,
      reason: trimmedReason
    };
  };

  // Returns whether the credential itself was proven, which is false when the probe only reached the host.
  const assertConnectionOk = async (
    accountType: PamAccountType,
    connectionDetails: Record<string, unknown>,
    credentials: Record<string, unknown> | null,
    gateway: {
      gatewayId?: string | null;
      gatewayPoolId?: string | null;
      templateGatewayId?: string | null;
      templateGatewayPoolId?: string | null;
    },
    orgId: string
  ): Promise<boolean> => {
    const validateCloud = CLOUD_CONNECTION_VALIDATORS[accountType];
    if (validateCloud) {
      try {
        await validateCloud({ connectionDetails, credentials, orgId });
      } catch (err) {
        throw new BadRequestError({
          message: `Connection test failed: ${err instanceof Error ? err.message : "unable to validate credentials"}`
        });
      }
      return true;
    }

    await gatewayPoolService.assertGatewayBindingInOrg({
      gatewayId: gateway.gatewayId ?? gateway.templateGatewayId,
      gatewayPoolId: gateway.gatewayPoolId ?? gateway.templateGatewayPoolId,
      orgId
    });

    const effectiveGatewayId = gateway.gatewayId ?? gateway.templateGatewayId;
    const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
      gatewayId: effectiveGatewayId,
      gatewayPoolId: effectiveGatewayId ? null : (gateway.gatewayPoolId ?? gateway.templateGatewayPoolId)
    });

    if (!gatewayId) {
      throw new BadRequestError({ message: "A gateway must be attached to this account." });
    }

    const attachedGateway = await gatewayV2DAL.findOne({ id: gatewayId });
    const capabilities = attachedGateway?.capabilities as {
      supported_account_types?: string[];
      clickhouseNativeProtocol?: boolean;
    } | null;
    if (!gatewaySupportsAccountType(accountType, capabilities?.supported_account_types)) {
      throw new BadRequestError({
        message: `Gateway '${attachedGateway?.name ?? gatewayId}' does not support ${ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType].name} accounts. Update the gateway, then try again.`
      });
    }

    // Otherwise this passes over HTTP and every native client fails at session time, with nothing to point at.
    if (requiresClickHouseNative(accountType, connectionDetails) && !gatewaySupportsClickHouseNative(capabilities)) {
      throw new BadRequestError({
        message: `Gateway '${attachedGateway?.name ?? gatewayId}' does not support ClickHouse's native protocol. Update the gateway, or clear the native port to use this account over HTTP only.`
      });
    }

    const test = await buildGatewayConnectionTest(accountType, connectionDetails, credentials, orgId);
    if (!test) return false;

    const result = await testBuiltConnectionWithGateway(test, gatewayId, gatewayV2Service, CONNECTION_TEST_TIMEOUT_MS);

    // a null result means the gateway couldn't be reached (offline / pre-protocol) — skip rather than block
    if (result && !result.ok) {
      throw new BadRequestError({ message: `Connection test failed: ${result.errorMessage}` });
    }

    return Boolean(result?.ok) && testVerifiesCredential(test.request);
  };

  const create = async ({
    projectId,
    accountType,
    name,
    description,
    folderId,
    templateId,
    connectionDetails,
    credentials,
    gatewayId,
    gatewayPoolId,
    recordingConnectionId,
    settingsOverrides,
    skipConnectionTest,
    ...ctx
  }: TCreatePamAccountDTO & TActorContext) => {
    const { permission } = await checkFolder(folderId, projectId, ctx);
    ForbiddenError.from(permission).throwUnlessCan(
      ResourcePermissionPamResourceActions.CreateAccounts,
      ResourcePermissionSub.PamResource
    );

    const plan = await licenseService.getPlan(ctx.actorOrgId);
    if (typeof plan.pam === "boolean" && !plan.pam) {
      throw new BadRequestError({
        message: "PAM is not available on your current plan. Please upgrade to continue."
      });
    }

    if (
      (accountType === PamAccountType.Windows || accountType === PamAccountType.WindowsAd) &&
      typeof plan.enterprisePamAccount === "boolean" &&
      !plan.enterprisePamAccount
    ) {
      throw new BadRequestError({
        message: "Windows PAM accounts are not available on your current plan. Please upgrade to continue."
      });
    }

    // maxPamAccounts is uncapped by default (null); only enforce a cap when the plan configures a numeric
    // limit. Counted org-wide right before creation.
    if (typeof plan.maxPamAccounts === "number") {
      const currentPamAccountCount = await pamAccountDAL.countByOrgId(ctx.actorOrgId);
      if (currentPamAccountCount >= plan.maxPamAccounts) {
        throw new BadRequestError({
          name: "PAM_ACCOUNT_LIMIT_REACHED",
          message: "Failed to create PAM account due to plan limit reached. Upgrade plan to add more PAM accounts."
        });
      }
    }

    const folder = await pamFolderDAL.findById(folderId);
    if (!folder || folder.projectId !== projectId) {
      throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
    }

    const template = await pamAccountTemplateDAL.findById(templateId);
    if (!template || template.projectId !== projectId) {
      throw new NotFoundError({ message: `Template with ID '${templateId}' not found` });
    }
    if (template.type !== accountType) {
      throw new BadRequestError({
        message: `Template type '${template.type}' does not match account type '${accountType}'`
      });
    }

    const effectiveGatewayId = gatewayId ?? template.gatewayId;
    await validateGatewayAttachment(
      deps,
      effectiveGatewayId,
      gatewayPoolId ?? (effectiveGatewayId ? null : template.gatewayPoolId),
      ctx,
      { inheritedFrom: gatewayId ? undefined : `Account template '${template.name}'` }
    );
    await validateRecordingConnection(deps, recordingConnectionId, ctx);

    const resolvedS3Config = await resolveOverridesS3Config(
      deps,
      settingsOverrides,
      recordingConnectionId ?? template.recordingConnectionId,
      ctx,
      recordingConnectionId ? getInheritedRecordingS3Config(settingsOverrides, template.settings) : undefined
    );

    const forced = applyForcedFields(accountType, {
      connectionDetails,
      credentials: normalizeCredentialAuthMethod(accountType, credentials)
    });
    const validatedConnectionDetails = validateConnectionDetails(accountType, forced.connectionDetails);
    const validatedCredentials = validateCredentials(accountType, forced.credentials);
    assertOraclePasswordIsUsable(accountType, validatedCredentials);
    assertPasswordMeetsRequirements(validatedCredentials, template.settings);

    // discovery import creates accounts in bulk from a scan that already reached them, so it skips the test
    let credentialVerified = false;
    if (!skipConnectionTest) {
      credentialVerified = await assertConnectionOk(
        accountType,
        validatedConnectionDetails,
        validatedCredentials,
        {
          gatewayId,
          gatewayPoolId,
          templateGatewayId: template.gatewayId,
          templateGatewayPoolId: template.gatewayPoolId
        },
        ctx.actorOrgId
      );
    }

    const encryptedConnectionDetails = await encrypt(projectId, validatedConnectionDetails);
    const encryptedCredentials = await encrypt(projectId, validatedCredentials);

    const credentialProvenAt = credentialVerified ? new Date() : null;

    try {
      const account = await pamAccountDAL.transaction(async (tx) => {
        const created = await pamAccountDAL.create(
          {
            projectId,
            name,
            description,
            folderId,
            templateId,
            encryptedConnectionDetails,
            encryptedCredentials,
            credentialConfigured: isCredentialConfigured(accountType, validatedCredentials),
            gatewayId,
            gatewayPoolId,
            recordingConnectionId,
            settingsOverrides: settingsOverrides ?? null,
            ...(credentialProvenAt
              ? {
                  heartbeatStatus: PamHeartbeatStatus.Healthy,
                  lastHeartbeatAt: credentialProvenAt,
                  lastHeartbeatHealthyAt: credentialProvenAt
                }
              : {})
          },
          tx
        );
        await pamAccountDAL.reconcileHeartbeatScheduleForAccount(created.id, tx);
        return created;
      });

      const corsProbeUrl = resolvedS3Config ? await mintCorsProbeUrl(resolvedS3Config) : null;

      return {
        id: account.id,
        name: account.name,
        description: account.description,
        folderId: account.folderId ?? null,
        templateId: account.templateId,
        projectId: account.projectId,
        gatewayId: account.gatewayId,
        gatewayPoolId: account.gatewayPoolId,
        recordingConnectionId: account.recordingConnectionId,
        settingsOverrides: account.settingsOverrides ?? null,
        createdAt: account.createdAt,
        updatedAt: account.updatedAt,
        accountType,
        folderName: folder.name,
        templateName: template.name,
        connectionDetails: validatedConnectionDetails,
        corsProbeUrl
      };
    } catch (err) {
      if (err instanceof DatabaseError) {
        const code = (err.error as { code?: string })?.code;
        if (code === DatabaseErrorCode.UniqueViolation) {
          throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });
        }
        if (code === DatabaseErrorCode.ForeignKeyViolation) {
          throw new BadRequestError({
            message: "Invalid reference: the specified gateway, pool, or template does not exist"
          });
        }
      }
      throw err;
    }
  };

  const update = async ({
    accountId,
    projectId,
    accountType,
    name,
    description,
    folderId,
    templateId,
    connectionDetails,
    credentials,
    gatewayId,
    gatewayPoolId,
    recordingConnectionId,
    settingsOverrides,
    ...ctx
  }: TUpdatePamAccountDTO & TActorContext) => {
    const existing = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!existing || existing.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    if (existing.accountType !== accountType) {
      throw new BadRequestError({
        message: `Account '${accountId}' is type '${existing.accountType}', not '${accountType}'`
      });
    }

    await checkAccount(accountId, existing.folderId, projectId, ResourcePermissionPamResourceActions.EditAccounts, ctx);

    if (folderId) {
      const folder = await pamFolderDAL.findById(folderId);
      if (!folder || folder.projectId !== projectId) {
        throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });
      }
      // Moving an account into a different folder requires create rights on the destination: folder
      // roles cascade to the accounts inside, so EditAccounts alone must not relocate an account into a
      // folder where the actor would gain ViewCredentials/LaunchSessions.
      if (folderId !== existing.folderId) {
        const { permission } = await checkFolder(folderId, projectId, ctx);
        ForbiddenError.from(permission).throwUnlessCan(
          ResourcePermissionPamResourceActions.CreateAccounts,
          ResourcePermissionSub.PamResource
        );
      }
    }

    let template: TPamAccountTemplates | undefined;
    if (templateId) {
      template = await pamAccountTemplateDAL.findById(templateId);
      if (!template || template.projectId !== projectId) {
        throw new NotFoundError({ message: `Template with ID '${templateId}' not found` });
      }
      if (template.type !== accountType) {
        throw new BadRequestError({
          message: `Template '${templateId}' is for type '${template.type}', not '${accountType}'`
        });
      }
      // A template carries governance settings (e.g. requiresApproval) and is product-admin-managed, so
      // re-pointing an account's template is an admin-only action to prevent bypassing those controls.
      if (templateId !== existing.templateId) {
        const { hasRole } = await verifyMembership(projectId, ctx);
        if (!hasRole(PamProductRole.Admin)) {
          throw new ForbiddenRequestError({ message: "Only PAM admins can change an account's template" });
        }
      }
    }

    // Re-validate whenever the effective gateway binding could change. The binding is the account's own
    // gateway/pool falling back to the template's, so an inherited gateway still requires AttachGateways.
    if (gatewayId !== undefined || gatewayPoolId !== undefined || templateId !== undefined) {
      const nextGatewayId = gatewayId !== undefined ? gatewayId : existing.gatewayId;
      const nextGatewayPoolId = gatewayPoolId !== undefined ? gatewayPoolId : existing.gatewayPoolId;
      const nextTemplateGatewayId = template ? template.gatewayId : existing.templateGatewayId;
      const nextTemplateGatewayPoolId = template ? template.gatewayPoolId : existing.templateGatewayPoolId;

      const effectiveGatewayId = nextGatewayId ?? nextTemplateGatewayId;
      await validateGatewayAttachment(
        deps,
        effectiveGatewayId,
        gatewayPoolId ?? (effectiveGatewayId ? null : (nextGatewayPoolId ?? nextTemplateGatewayPoolId)),
        ctx,
        {
          previousGatewayId: existing.gatewayId ?? existing.templateGatewayId,
          inheritedFrom: nextGatewayId ? undefined : `Account template '${template?.name ?? existing.templateName}'`
        }
      );
    }
    await validateRecordingConnection(deps, recordingConnectionId, ctx);

    const resolvedS3Config = await resolveOverridesS3Config(
      deps,
      settingsOverrides,
      (recordingConnectionId !== undefined ? recordingConnectionId : existing.recordingConnectionId) ??
        existing.templateRecordingConnectionId,
      ctx,
      recordingConnectionId
        ? getInheritedRecordingS3Config(
            settingsOverrides === undefined ? existing.settingsOverrides : settingsOverrides,
            template ? template.settings : existing.templateSettings
          )
        : undefined
    );

    const updateData: Record<string, unknown> = {};
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (folderId !== undefined) updateData.folderId = folderId;
    if (templateId !== undefined) updateData.templateId = templateId;
    if (gatewayId !== undefined) updateData.gatewayId = gatewayId;
    if (gatewayPoolId !== undefined) updateData.gatewayPoolId = gatewayPoolId;
    if (recordingConnectionId !== undefined) updateData.recordingConnectionId = recordingConnectionId;
    if (settingsOverrides !== undefined) updateData.settingsOverrides = settingsOverrides;

    // Forced fields cross the two groups, so a change to either side is resolved against the merged
    // view and both are rewritten
    let principalChanged = false;
    let authMethodChanged = false;
    let connectionTargetChanged = false;
    let effectiveConnectionDetails: Record<string, unknown> | null = null;
    let effectiveCredentials: Record<string, unknown> | null = null;

    if (connectionDetails || credentials) {
      const existingConnectionDetails = await decrypt(projectId, existing.encryptedConnectionDetails);
      const existingCredentials = await decrypt(projectId, existing.encryptedCredentials);

      const forced = applyForcedFields(accountType, {
        connectionDetails: connectionDetails ?? existingConnectionDetails,
        credentials: normalizeCredentialAuthMethod(accountType, { ...existingCredentials, ...(credentials ?? {}) })
      });

      effectiveConnectionDetails = validateConnectionDetails(accountType, forced.connectionDetails);
      effectiveCredentials = validateCredentials(accountType, forced.credentials);

      if (credentials) {
        const templateSettings = templateId
          ? (await pamAccountTemplateDAL.findById(templateId))?.settings
          : existing.templateSettings;
        if ((credentials as { password?: string }).password) {
          assertOraclePasswordIsUsable(accountType, effectiveCredentials);
        }
        assertPasswordMeetsRequirements(effectiveCredentials, templateSettings);
      }

      updateData.encryptedConnectionDetails = await encrypt(projectId, effectiveConnectionDetails);
      updateData.encryptedCredentials = await encrypt(projectId, effectiveCredentials);
      updateData.credentialConfigured = isCredentialConfigured(accountType, effectiveCredentials);

      const oldConn = validateConnectionDetails(accountType, existingConnectionDetails) as {
        host?: string;
        port?: number;
        nativePort?: number;
      };
      const newConn = effectiveConnectionDetails as { host?: string; port?: number; nativePort?: number };
      // Re-pointing nativePort sends the stored credential somewhere new on the next heartbeat.
      if (oldConn.host !== newConn.host || oldConn.port !== newConn.port || oldConn.nativePort !== newConn.nativePort)
        connectionTargetChanged = true;

      const oldUsername = (existingCredentials as { username?: string }).username;
      const newUsername = (effectiveCredentials as { username?: string }).username;
      if (oldUsername !== newUsername) principalChanged = true;

      // Normalized on both sides so an older account without a stored auth method doesn't read as a change
      const oldAuthMethod = normalizeCredentialAuthMethod(accountType, existingCredentials).authMethod;
      if (oldAuthMethod !== (effectiveCredentials as { authMethod?: string }).authMethod) authMethodChanged = true;
    }

    const routingChanged =
      connectionTargetChanged ||
      authMethodChanged ||
      (gatewayId !== undefined && gatewayId !== existing.gatewayId) ||
      (gatewayPoolId !== undefined && gatewayPoolId !== existing.gatewayPoolId);
    if ((routingChanged || principalChanged) && existing.rotationAccountId) {
      updateData.rotationAccountId = null;
    }

    let credentialVerified = false;
    // re-test whenever the connection could have changed
    if (
      connectionDetails !== undefined ||
      credentials !== undefined ||
      gatewayId !== undefined ||
      gatewayPoolId !== undefined ||
      templateId !== undefined
    ) {
      const testConnectionDetails =
        effectiveConnectionDetails ??
        validateConnectionDetails(accountType, await decrypt(projectId, existing.encryptedConnectionDetails));

      // only test with credentials supplied in this request to prevent exfiltration
      let testCredentials = credentials ? validateCredentials(accountType, credentials) : null;
      if (!testCredentials && CLOUD_CONNECTION_VALIDATORS[accountType]) {
        testCredentials = validateCredentials(accountType, await decrypt(projectId, existing.encryptedCredentials));
      }
      credentialVerified = await assertConnectionOk(
        accountType,
        testConnectionDetails,
        testCredentials,
        {
          gatewayId: gatewayId !== undefined ? gatewayId : existing.gatewayId,
          gatewayPoolId: gatewayPoolId !== undefined ? gatewayPoolId : existing.gatewayPoolId,
          templateGatewayId: template ? template.gatewayId : existing.templateGatewayId,
          templateGatewayPoolId: template ? template.gatewayPoolId : existing.templateGatewayPoolId
        },
        ctx.actorOrgId
      );
    }

    const credentialSecretSupplied = suppliesCredentialSecret(accountType, credentials);

    // Only asked when it can change the outcome, so an ordinary edit costs no extra permission read.
    const actorCanViewCredentials =
      routingChanged && !credentialSecretSupplied
        ? await accountAccessAllows(
            permissionService,
            accountId,
            existing.folderId,
            projectId,
            ResourcePermissionPamResourceActions.ViewCredentials,
            ctx
          )
        : true;
    const pausedForRoutingChange = pausesHeartbeatForRoutingChange({
      routingChanged,
      credentialsSupplied: credentialSecretSupplied,
      actorCanViewCredentials
    });
    if (pausedForRoutingChange) {
      updateData.nextHeartbeatAt = null;
      updateData.heartbeatStatus = PamHeartbeatStatus.Unknown;
      updateData.encryptedLastHeartbeatMessage = await encrypt(projectId, {
        message: HEARTBEAT_PAUSED_FOR_ROUTING_CHANGE
      });
    }

    // Clearing the old verdict resumes checking; types unverifiable here would otherwise stay stopped.
    if (credentialSecretSupplied) {
      updateData.heartbeatStatus = credentialVerified ? PamHeartbeatStatus.Healthy : null;
      updateData.encryptedLastHeartbeatMessage = null;
      if (credentialVerified) {
        const verifiedAt = new Date();
        updateData.lastHeartbeatAt = verifiedAt;
        updateData.lastHeartbeatHealthyAt = verifiedAt;
      }
    }

    try {
      const account = await pamAccountDAL.transaction(async (tx) => {
        const updated = await pamAccountDAL.updateById(accountId, updateData, tx);
        if (routingChanged) {
          await pamAccountDAL.update(
            { rotationAccountId: accountId },
            { rotationAccountId: null, nextRotationAt: null },
            tx
          );
        }
        // A template move, credential change, or a cleared binding can flip rotation readiness; re-derive the schedule
        // atomically with the write so a failure can't leave a stale nextRotationAt.
        if (templateId !== undefined || credentials || routingChanged) {
          await pamAccountDAL.reconcileRotationScheduleForAccount(accountId, tx);
          if (!pausedForRoutingChange) {
            await pamAccountDAL.reconcileHeartbeatScheduleForAccount(accountId, tx);
          }
        }
        return updated;
      });
      const corsProbeUrl = resolvedS3Config ? await mintCorsProbeUrl(resolvedS3Config) : null;
      return { ...account, corsProbeUrl };
    } catch (err) {
      if (err instanceof DatabaseError) {
        const code = (err.error as { code?: string })?.code;
        if (code === DatabaseErrorCode.UniqueViolation) {
          throw new BadRequestError({ message: `An account named "${name}" already exists in this folder` });
        }
        if (code === DatabaseErrorCode.ForeignKeyViolation) {
          throw new BadRequestError({
            message: "Invalid reference: the specified gateway, pool, or template does not exist"
          });
        }
      }
      throw err;
    }
  };

  const deleteAccount = async ({ accountId, projectId, ...ctx }: TDeletePamAccountDTO & TActorContext) => {
    const existing = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!existing || existing.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    await checkAccount(
      accountId,
      existing.folderId,
      projectId,
      ResourcePermissionPamResourceActions.DeleteAccounts,
      ctx
    );

    try {
      // Every session cancellation this delete triggers is held back until COMMIT: the delete can still
      // fail on the rotationAccountId FK guard below, and a cut tunnel can't be brought back.
      let sendSessionCancellations: (() => void) | undefined;

      const deleted = await pamAccountDAL.transaction(async (tx) => {
        const memberships = await membershipDAL.find(
          {
            scope: RESOURCE_SCOPE,
            scopeResourceType: ResourceType.PamAccount,
            scopeResourceId: accountId
          },
          { tx }
        );

        if (memberships.length > 0) {
          const ids = memberships.map((m) => m.id);
          await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
          await membershipDAL.delete({ $in: { id: ids } }, tx);
        }

        await pamAccountDAL.updateById(accountId, { rotationAccountId: null }, tx);

        const sendGrantCancellations = await deps.pamAccessRequestService.cleanupAccountResources(
          { accountId, folderId: existing.folderId, projectId, actorId: ctx.actorId },
          tx
        );

        // Sweep every live session on the account, not just the ones grant revocation reached: an
        // account in a folder with no approval policy has no grant rows at all, and a session can be
        // held by someone who is not a grantee. The account row is about to disappear (pam_sessions
        // keeps history with a null accountId), so there is no access left to re-evaluate.
        const liveSessions = await pamSessionDAL.find(
          { accountId, $in: { status: [PamSessionStatus.Active, PamSessionStatus.Starting] } },
          { tx }
        );

        let sendSweepCancellations: (() => void) | undefined;
        if (liveSessions.length > 0) {
          const actor = await userDAL.findById(ctx.actorId, tx);
          sendSweepCancellations = await terminatePamSessions({
            sessions: liveSessions,
            actorId: ctx.actorId,
            actorEmail: actor?.email ?? "",
            pamSessionDAL,
            gatewayV2Service,
            tx
          });
        }

        sendSessionCancellations = () => {
          sendGrantCancellations();
          sendSweepCancellations?.();
        };

        return pamAccountDAL.deleteById(accountId, tx);
      });

      sendSessionCancellations?.();
      return deleted;
    } catch (err) {
      if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {
        const dependents = (await pamAccountDAL.find({ rotationAccountId: accountId })).filter(
          (dependent) => dependent.id !== accountId
        );
        if (dependents.length) {
          const readChecks = await Promise.all(
            dependents.map(async (dependent) => ({
              name: dependent.name,
              canRead: await checkAccount(
                dependent.id,
                dependent.folderId,
                projectId,
                ResourcePermissionPamResourceActions.ReadAccounts,
                ctx
              )
                .then(() => true)
                .catch(() => false)
            }))
          );
          const readableNames = readChecks.filter((c) => c.canRead).map((c) => c.name);
          const hiddenCount = readChecks.length - readableNames.length;
          const parts = [
            ...(readableNames.length ? [readableNames.join(", ")] : []),
            ...(hiddenCount ? [`${hiddenCount} other account${hiddenCount > 1 ? "s" : ""}`] : [])
          ];
          throw new BadRequestError({
            message: parts.length
              ? `This account is the rotation account for: ${parts.join(", and ")}. Reassign or clear their rotation account before deleting this one.`
              : "This account is used as the rotation account for another account. Reassign it before deleting this one."
          });
        }
        const sources = await pamDiscoverySourceDAL.find({ credentialAccountId: accountId });
        if (sources.length) {
          // Discovery is Admin-only, so a non-admin gets the count rather than the source names.
          const { hasRole } = await verifyMembership(projectId, ctx);
          const plural = sources.length > 1;
          const subject = hasRole(PamProductRole.Admin)
            ? `discovery source${plural ? "s" : ""} ${sources.map((source) => `'${source.name}'`).join(", ")}`
            : `${sources.length} discovery source${plural ? "s" : ""}`;
          throw new BadRequestError({
            message: `This account is the credential for ${subject}. Point ${
              plural ? "them" : "it"
            } at another account, or delete ${plural ? "them" : "it"}, before deleting this account.`
          });
        }

        logger.error(err, `Unhandled FK violation deleting PAM account [accountId=${accountId}]`);
        throw new BadRequestError({
          message: "This account is still referenced by another resource. Remove that reference before deleting it."
        });
      }
      throw err;
    }
  };

  const listAccessible = async ({
    projectId,
    offset,
    limit,
    search,
    folderId,
    accountType,
    ...ctx
  }: TListAccessibleAccountsDTO & TActorContext & { offset?: number; limit?: number }) => {
    await verifyMembership(projectId, ctx);

    const { folderIds, accountIds } = await getResourceIdsWithActions(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      { allOf: [ResourcePermissionPamResourceActions.ReadAccounts] },
      ctx
    );
    if (folderIds.length === 0 && accountIds.length === 0) return { accounts: [], totalCount: 0 };

    const launchScopes = await getResourceIdsWithActions(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      { allOf: [ResourcePermissionPamResourceActions.LaunchSessions] },
      ctx
    );
    const launchFolderIds = new Set(launchScopes.folderIds);
    const launchAccountIds = new Set(launchScopes.accountIds);

    const { accounts, totalCount } = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds, {
      offset,
      limit,
      search,
      folderId,
      accountType,
      onlyAccessible: true
    });

    const accountsRequiringApproval = accounts.filter(
      (a) => resolveAccessControls(a.templatePolicies).requiresApproval
    );
    const accountIdsRequiringApproval = accountsRequiringApproval.map((a) => a.id);

    const folderIdsRequiringApproval = [
      ...new Set(accountsRequiringApproval.map((a) => a.folderId).filter(Boolean) as string[])
    ];
    const [accessStatusMap, foldersWithApprovalPolicy, breakGlassFolders] = await Promise.all([
      deps.pamAccessRequestService.getAccessStatusBatch(
        { actorId: ctx.actorId, actor: ctx.actor },
        accountIdsRequiringApproval,
        projectId
      ),
      deps.pamAccessRequestService.getFolderPolicyConfigured(folderIdsRequiringApproval),
      deps.pamAccessRequestService.getBreakGlassUserFolders(
        folderIdsRequiringApproval,
        { actorId: ctx.actorId, actor: ctx.actor },
        ctx.actorOrgId
      )
    ]);

    return {
      accounts: accounts.map((a) => {
        const { requiresApproval, requireReason, requireMfa, allowBreakGlass, allowAutoApproval } =
          resolveAccessControls(a.templatePolicies);
        const statusEntry = accessStatusMap.get(a.id);
        const canBreakGlass = allowBreakGlass && !!a.folderId && breakGlassFolders.has(a.folderId);
        const hasPolicyConfigured = a.folderId
          ? canBreakGlass ||
            statusEntry?.accessStatus === ApprovalAccessStatus.Granted ||
            foldersWithApprovalPolicy.isConfiguredFor(a.folderId, allowAutoApproval)
          : false;
        let disabledReason: string | null = null;
        if (requiresApproval && !hasPolicyConfigured) {
          disabledReason =
            "This account requires approval, but its folder has no approvers yet. Ask a folder admin to add approvers under the folder's Approvals tab.";
        }
        return {
          id: a.id,
          name: a.name,
          description: a.description,
          folderId: a.folderId,
          folderName: a.folderName,
          templateId: a.templateId,
          templateName: a.templateName,
          accountType: a.accountType,
          projectId: a.projectId,
          canLaunch: launchAccountIds.has(a.id) || (!!a.folderId && launchFolderIds.has(a.folderId)),
          requiresApproval,
          requireReason,
          // Machine identities cannot satisfy MFA, so launch rejects them outright (see
          // pam-session-service). Callers acting as an identity should treat this as unusable.
          requireMfa,
          accessStatus: requiresApproval
            ? (statusEntry?.accessStatus ?? ApprovalAccessStatus.None)
            : ApprovalAccessStatus.None,
          grantExpiresAt: statusEntry?.grantExpiresAt ?? null,
          pendingRequestId: statusEntry?.pendingRequestId ?? null,
          canBreakGlass,
          disabledReason,
          createdAt: a.createdAt,
          updatedAt: a.updatedAt
        };
      }),
      totalCount
    };
  };

  const decryptInternalMetadata = async (projectId: string, blob: Buffer | null | undefined) => {
    if (!blob) return null;
    return decrypt(projectId, blob);
  };

  const getOrCreateSshCa = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {
    const account = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!account || account.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.EditAccounts, ctx);

    const existing = parseInternalMetadata(
      account.accountType as PamAccountType,
      await decryptInternalMetadata(projectId, account.encryptedInternalMetadata)
    );

    if (existing?.caPublicKey) {
      return { publicKey: existing.caPublicKey, created: false };
    }

    const keyAlgorithm = SshCertKeyAlgorithm.ED25519;
    const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);

    const metadata: TSshInternalMetadata = {
      caPublicKey: publicKey,
      caKeyAlgorithm: keyAlgorithm,
      caPrivateKey: privateKey
    };

    await pamAccountDAL.updateById(accountId, {
      encryptedInternalMetadata: await encrypt(projectId, metadata)
    });

    return { publicKey, created: true, keyAlgorithm };
  };

  const getAccountPermissions = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {
    const account = await pamAccountDAL.findById(accountId);
    if (!account || account.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    const allRules: RawRuleOf<MongoAbility<ResourcePermissionSet, MongoQuery>>[] = [];
    const allMemberships: Awaited<ReturnType<typeof permissionService.getResourcePermission>>["memberships"] = [];

    if (account.folderId) {
      try {
        const folderResult = await permissionService.getResourcePermission({
          actor: ctx.actor,
          actorId: ctx.actorId,
          projectId,
          resourceType: ResourceType.PamFolder,
          resourceId: account.folderId,
          actorAuthMethod: ctx.actorAuthMethod,
          actorOrgId: ctx.actorOrgId
        });
        allRules.push(...folderResult.permission.rules);
        allMemberships.push(...folderResult.memberships);
      } catch (err) {
        if (!(err instanceof ForbiddenRequestError)) throw err;
      }
    }

    try {
      const accountResult = await permissionService.getResourcePermission({
        actor: ctx.actor,
        actorId: ctx.actorId,
        projectId,
        resourceType: ResourceType.PamAccount,
        resourceId: accountId,
        actorAuthMethod: ctx.actorAuthMethod,
        actorOrgId: ctx.actorOrgId
      });
      allRules.push(...accountResult.permission.rules);
      allMemberships.push(...accountResult.memberships);
    } catch (err) {
      if (!(err instanceof ForbiddenRequestError)) throw err;
    }

    const mergedPermission = createMongoAbility<ResourcePermissionSet>(allRules, { conditionsMatcher });

    ForbiddenError.from(mergedPermission).throwUnlessCan(
      ResourcePermissionPamResourceActions.ReadAccounts,
      ResourcePermissionSub.PamResource
    );

    // Only member managers get the roster; read-only roles must not enumerate members.
    const canManageMembers = mergedPermission.can(
      ResourcePermissionPamResourceActions.ManageMembers,
      ResourcePermissionSub.PamResource
    );

    return {
      permissions: packRules(mergedPermission.rules),
      memberships: canManageMembers ? allMemberships : []
    };
  };

  return {
    list,
    listAccessible,
    getById,
    getCredentials,
    create,
    update,
    deleteAccount,
    getOrCreateSshCa,
    getAccountPermissions
  };
};