Skip to content

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

32.6 KB
Raw Blame
import RE2 from "re2";

import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { CliCapability, cliSupports } from "@app/lib/cli-version/cli-version-fns";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { createSshCert, createSshKeyPair, SshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";
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 { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";

import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import {
  buildSessionGatewayConnectionDetails,
  extractGatewayTarget,
  getAccountAccessibilityIssues,
  PamAccountAccessibilityIssue,
  parseInternalMetadata,
  qualifyUsernameWithDomain,
  resolveGatewayAccountType,
  resolveSelectedHost
} from "../pam-account/pam-account-schemas";
import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";
import { decryptSessionKey, generateSessionRecordingSecrets } from "../pam-session-recording/pam-recording-secrets";
import {
  accountTypeSupportsSessionLogMasking,
  PamAccessMethod,
  PamAccountType,
  PamPostgresAuthMethod,
  PamProductRole,
  PamSessionEndReason,
  PamSessionStatus
} from "../pam/pam-enums";
import { resolveAccountByPath as resolveAccountByPathFn } from "../pam/pam-fns";
import { enforceMfa } from "../pam/pam-mfa";
import {
  checkAccountAccess,
  getLaunchAccessRemainingMs,
  getResourceIdsWithActions,
  TActorContext,
  verifyProductMembership
} from "../pam/pam-permission";
import {
  buildPamPolicyRules,
  PamPolicyType,
  policyAppliesTo,
  resolveAccessControls,
  resolvePolicy,
  splitPatternString
} from "../pam/pam-policies";
import { ResourcePermissionPamResourceActions } from "../permission/resource-permission";
import {
  AWS_STS_MIN_DURATION_SECONDS,
  exchangeCredentialsForConsoleUrl,
  extractAwsAccountIdFromArn,
  generateAwsIamSessionCredentials,
  generateRdsAuthToken
} from "./aws-iam/aws-iam-federation";
import { getAzureAccessTokens } from "./azure/azure-federation";
import { mintGcpAccessToken } from "./gcp/gcp-federation";
import { assertUserStillActiveInOrg } from "./pam-session-access-fns";
import { DEFAULT_SESSION_DURATION_MS } from "./pam-session-constants";
import { TPamSessionDALFactory } from "./pam-session-dal";
import { TPamSessionExpirationServiceFactory } from "./pam-session-expiration-queue";
import {
  isPamSessionLive,
  pamSessionRemainingSeconds,
  reportPamSessionEnded,
  resolvePamSessionDistinctId,
  sendPamSessionCancellationSignal
} from "./pam-session-fns";

type TPamSessionServiceFactoryDep = {
  pamSessionDAL: Pick<
    TPamSessionDALFactory,
    | "findAccessibleByProjectId"
    | "findById"
    | "findOne"
    | "create"
    | "endSessionById"
    | "terminateSessionById"
    | "transaction"
    | "updateById"
    | "claimRecordingSecrets"
    | "activateSession"
  >;
  pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails" | "findOne">;
  pamFolderDAL: Pick<TPamFolderDALFactory, "findOne">;
  membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor" | "lockOrgMembershipForUser">;
  membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
  permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
  gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId" | "assertGatewayBindingInOrg">;
  userDAL: Pick<TUserDALFactory, "findById">;
  pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;
  mfaSessionService: Pick<
    TMfaSessionServiceFactory,
    "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
  >;
  orgDAL: Pick<TOrgDALFactory, "findOrgById" | "findById" | "lockActorsForOrgAccess" | "findActorsWithActiveOrgAccess">;
  pamAccessRequestService: Pick<
    TPamAccessRequestServiceFactory,
    "checkGrant" | "getAccessStatusBatch" | "getFolderPolicyConfigured"
  >;
  telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
};

export type TPamSessionServiceFactory = ReturnType<typeof pamSessionServiceFactory>;

export const pamSessionServiceFactory = ({
  pamSessionDAL,
  pamAccountDAL,
  pamFolderDAL,
  membershipDAL,
  membershipRoleDAL,
  permissionService,
  kmsService,
  gatewayV2Service,
  gatewayPoolService,
  userDAL,
  pamSessionExpirationService,
  mfaSessionService,
  orgDAL,
  pamAccessRequestService,
  telemetryService
}: TPamSessionServiceFactoryDep) => {
  const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
    const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
    return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;
  };

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

  const checkSession = async (
    session: { accountId?: string | null; projectId: string },
    action: ResourcePermissionPamResourceActions,
    ctx: TActorContext
  ) => {
    if (session.accountId) {
      const account = await pamAccountDAL.findByIdWithDetails(session.accountId);
      await checkAccount(session.accountId, account?.folderId, session.projectId, action, ctx);
      return;
    }

    const { hasRole } = await verifyProductMembership(permissionService, session.projectId, ctx);
    if (!hasRole(PamProductRole.Admin)) {
      throw new ForbiddenRequestError({
        message: "Only a project admin can access a session whose account has been deleted"
      });
    }
  };

  const enforceRecordingConfig = (account: Parameters<typeof getAccountAccessibilityIssues>[0]) => {
    const issues = getAccountAccessibilityIssues(account);
    if (issues.includes(PamAccountAccessibilityIssue.NoRecordingConfig)) {
      throw new BadRequestError({
        message: "S3 recording must be configured before launching this account"
      });
    }
  };

  const listSessions = async (
    projectId: string,
    ctx: TActorContext,
    pagination?: { offset?: number; limit?: number; search?: string; status?: string }
  ) => {
    const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);

    const { folderIds, accountIds } = await getResourceIdsWithActions(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      { allOf: [ResourcePermissionPamResourceActions.ViewSessions] },
      ctx
    );

    return pamSessionDAL.findAccessibleByProjectId(projectId, {
      viewSessionsFolderIds: folderIds,
      viewSessionsAccountIds: accountIds,
      includeOrphaned: hasRole(PamProductRole.Admin),
      ...pagination
    });
  };

  const getSessionById = async (sessionId: string, ctx: TActorContext) => {
    const session = await pamSessionDAL.findById(sessionId);
    if (!session) return null;

    await checkSession(session, ResourcePermissionPamResourceActions.ViewSessions, ctx);

    return session;
  };

  // Called by the gateway
  const getSessionCredentials = async (sessionId: string, gatewayId: string, orgId: string) => {
    const session = await pamSessionDAL.findOne({ id: sessionId, gatewayId });
    if (!session) {
      throw new NotFoundError({ message: "Session not found" });
    }

    if (!isPamSessionLive(session)) {
      throw new BadRequestError({ message: "Session is not active" });
    }

    if (!session.accountId) {
      throw new BadRequestError({ message: "Session has no linked account" });
    }

    const account = await pamAccountDAL.findByIdWithDetails(session.accountId);
    if (!account) {
      throw new NotFoundError({ message: "Account not found" });
    }

    const connectionDetails = await decrypt(session.projectId, account.encryptedConnectionDetails);
    const credentials = await decrypt(session.projectId, account.encryptedCredentials);
    const remainingSeconds = pamSessionRemainingSeconds(session);

    if (credentials.authMethod === "certificate" && account.encryptedInternalMetadata) {
      const internalMetadata = parseInternalMetadata(
        account.accountType as PamAccountType,
        await decrypt(session.projectId, account.encryptedInternalMetadata)
      );

      if (internalMetadata?.caPrivateKey) {
        const keyAlgorithm = (internalMetadata.caKeyAlgorithm as SshCertKeyAlgorithm) || SshCertKeyAlgorithm.ED25519;
        const { publicKey: clientPublicKey, privateKey: clientPrivateKey } = await createSshKeyPair(keyAlgorithm);

        const username = credentials.username as string;
        const { signedPublicKey } = await createSshCert({
          caPrivateKey: internalMetadata.caPrivateKey,
          clientPublicKey,
          keyId: `pam-session-${session.id}`,
          principals: [username],
          requestedTtl: `${remainingSeconds}s`,
          certType: SshCertType.USER
        });

        credentials.privateKey = clientPrivateKey;
        credentials.certificate = signedPublicKey;
      }
    }

    if (account.accountType === PamAccountType.GcpServiceAccount) {
      credentials.token = await mintGcpAccessToken({
        serviceAccountEmail: connectionDetails.serviceAccountEmail as string,
        authMethod: credentials.authMethod as string,
        serviceAccountKeyJson: credentials.serviceAccountKeyJson as string | undefined,
        orgId,
        ttlSeconds: Math.min(remainingSeconds, 3600)
      });
      delete credentials.serviceAccountKeyJson;
    }

    if (credentials.authMethod === PamPostgresAuthMethod.AwsIam) {
      const { host, port } = connectionDetails as { host: string; port: number };
      credentials.password = await generateRdsAuthToken({
        roleArn: credentials.roleArn as string,
        externalId: orgId,
        roleSessionName: `infisical-pam-${sessionId}`,
        region: credentials.awsRegion as string,
        host,
        port,
        username: credentials.username as string
      });
      delete credentials.awsRegion;
      delete credentials.roleArn;
    }

    if (account.accountType === PamAccountType.AzureCli) {
      credentials.tokens = await getAzureAccessTokens({
        tenantId: connectionDetails.tenantId as string,
        clientId: credentials.clientId as string,
        clientSecret: credentials.clientSecret as string
      });
      delete credentials.clientSecret;
    }

    const sessionStarted = session.status === PamSessionStatus.Starting;

    let actorDistinctId: string | undefined;
    if (sessionStarted) {
      await pamSessionDAL.activateSession(sessionId);
      actorDistinctId = await resolvePamSessionDistinctId({ session, userDAL });
    }

    const templateSettingsParsed = account.templateSettings
      ? PamTemplateSettingsSchema.safeParse(account.templateSettings)
      : null;
    const resolvedBackend =
      templateSettingsParsed?.success && templateSettingsParsed.data.recordingStorageBackend
        ? templateSettingsParsed.data.recordingStorageBackend
        : PamRecordingStorageBackend.Postgres;

    let recording: {
      sessionKey: string;
      uploadToken: string;
      storageBackend: PamRecordingStorageBackend;
      projectId: string;
      sessionId: string;
    } | null = null;

    let storedSessionKey = session.encryptedSessionKey ?? null;

    if (!storedSessionKey) {
      const secrets = await generateSessionRecordingSecrets({
        projectId: session.projectId,
        sessionId,
        kmsService
      });

      // A gateway fetches credentials per connection, so two can mint at once; without a single
      // claim the loser keeps a key the row no longer holds and its uploads fail forever.
      const claimed = await pamSessionDAL.claimRecordingSecrets(
        sessionId,
        secrets.encryptedSessionKey,
        secrets.uploadTokenHash
      );
      if (!claimed?.encryptedSessionKey) {
        throw new NotFoundError({ message: `Session with ID '${sessionId}' was not found` });
      }

      if (claimed.encryptedSessionKey.equals(secrets.encryptedSessionKey)) {
        recording = {
          sessionKey: secrets.sessionKey.toString("base64"),
          uploadToken: secrets.uploadToken.toString("base64"),
          storageBackend: resolvedBackend,
          projectId: session.projectId,
          sessionId
        };
      } else {
        storedSessionKey = claimed.encryptedSessionKey;
      }
    }

    if (!recording && storedSessionKey) {
      // On re-fetch (e.g. gateway restart) return the existing key; empty token since the gateway
      // restores its own from disk and the server only keeps the token hash.
      const sessionKey = await decryptSessionKey({
        projectId: session.projectId,
        sessionId,
        encryptedSessionKey: storedSessionKey,
        kmsService
      });

      recording = {
        sessionKey: sessionKey.toString("base64"),
        uploadToken: "",
        storageBackend: resolvedBackend,
        projectId: session.projectId,
        sessionId
      };
    }

    const commandBlockingPatterns = policyAppliesTo(
      PamPolicyType.CommandBlocking,
      account.accountType as PamAccountType
    )
      ? splitPatternString(resolvePolicy(account.templatePolicies, PamPolicyType.CommandBlocking))
      : [];

    const parsedSettings = PamTemplateSettingsSchema.safeParse(account.templateSettings ?? {});

    const policyRules = buildPamPolicyRules({
      commandBlockingPatterns,
      maskingPatterns: parsedSettings.success ? splitPatternString(parsedSettings.data.sessionLogMaskingPatterns) : [],
      // Never send a rule the gateway has no way to honour.
      maskingBuiltInDetection:
        accountTypeSupportsSessionLogMasking(account.accountType as PamAccountType) &&
        parsedSettings.success &&
        parsedSettings.data.sessionLogMaskingBuiltInDetection
    });

    const normalizedConnectionDetails = buildSessionGatewayConnectionDetails(
      account.accountType as PamAccountType,
      connectionDetails,
      session.selectedHost
    );

    if (account.accountType === PamAccountType.WindowsAd) {
      credentials.username = qualifyUsernameWithDomain(
        credentials.username as string,
        (connectionDetails as { domain: string }).domain
      );
    }

    return {
      credentials: { ...normalizedConnectionDetails, ...credentials },
      recording,
      policyRules,
      projectId: session.projectId,
      accountId: session.accountId,
      accountName: session.accountName,
      accountType: session.accountType,
      actorDistinctId,
      sessionStarted
    };
  };

  // Called by the gateway
  const endSessionFromGateway = async (sessionId: string, gatewayId: string, orgId: string) => {
    const session = await pamSessionDAL.findOne({ id: sessionId, gatewayId });
    if (!session) {
      throw new NotFoundError({ message: "Session not found" });
    }

    const updatedSession = await pamSessionDAL.endSessionById(sessionId);

    if (updatedSession) {
      void reportPamSessionEnded({
        session: updatedSession,
        orgId,
        endReason: PamSessionEndReason.Completed,
        telemetryService,
        userDAL
      });
    }

    return {
      projectId: session.projectId,
      accountId: session.accountId,
      accountName: session.accountName,
      alreadyEnded: !updatedSession
    };
  };

  const resolveAccountByPath = (projectId: string, path: string) =>
    resolveAccountByPathFn({ pamFolderDAL, pamAccountDAL }, projectId, path);

  const access = async ({
    path,
    projectId,
    actor,
    actorEmail,
    actorName,
    actorIp,
    actorUserAgent,
    reason,
    duration,
    mfaSessionId,
    tokenVersionId,
    accessMethod = PamAccessMethod.Cli,
    targetHost
  }: {
    path: string;
    projectId: string;
    actor: TActorContext;
    actorEmail: string;
    actorName: string;
    actorIp: string;
    actorUserAgent: string;
    reason?: string;
    duration?: string;
    mfaSessionId?: string;
    tokenVersionId?: string;
    accessMethod?: PamAccessMethod;
    targetHost?: string;
  }) => {
    const account = await resolveAccountByPath(projectId, path);

    // Machine identities launch sessions via identity access tokens; human-only controls
    // (MFA, access-request approval) cannot be satisfied by them and are rejected explicitly below.
    const isUserActor = actor.actor === ActorType.USER;

    const policy = resolveAccessControls(account.templatePolicies);
    const { requiresApproval } = policy;

    // Approval is a layer on top of standing access: gated accounts require LaunchSessions AND an
    // approved grant, so losing LaunchSessions blocks launch even while a grant is still active.
    await checkAccount(
      account.id,
      account.folderId,
      projectId,
      ResourcePermissionPamResourceActions.LaunchSessions,
      actor
    );

    const trimmedReason = reason?.trim() || null;

    if (policy.requireMfa) {
      if (!isUserActor) {
        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: actor.actorId,
          orgId: actor.actorOrgId,
          actorEmail,
          accountId: account.id,
          mfaSessionId,
          tokenVersionId,
          allowCliHandoff: accessMethod === PamAccessMethod.Cli
        }
      );
    }

    const maxDurationMs = policy.maxSessionDurationSeconds
      ? policy.maxSessionDurationSeconds * 1000
      : DEFAULT_SESSION_DURATION_MS;

    let sessionDurationMs = maxDurationMs;
    if (duration) {
      const parsed = ms(duration);
      if (!parsed || parsed <= 0) {
        throw new BadRequestError({ message: "Invalid duration format" });
      }
      sessionDurationMs = Math.min(parsed, maxDurationMs);
    }

    const launchAccessRemainingMs = await getLaunchAccessRemainingMs(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      account,
      actor
    );
    if (launchAccessRemainingMs !== null) {
      if (launchAccessRemainingMs <= 0) {
        throw new ForbiddenRequestError({ message: "Your access to this account is no longer active" });
      }
      sessionDurationMs = Math.min(sessionDurationMs, launchAccessRemainingMs);
    }

    // The approval gate comes before the launch-reason check: a user without a grant should be
    // guided into requesting access (where the request reason is collected) rather than being
    // blocked on a launch reason for a session they cannot start yet.
    if (requiresApproval) {
      const grant = await pamAccessRequestService.checkGrant({
        actorId: actor.actorId,
        actor: actor.actor,
        accountId: account.id,
        accountFolderId: account.folderId,
        projectId
      });
      if (!grant) {
        // Distinguish "no request yet" from "request awaiting review" and from "folder has no
        // approvers", so the CLI can guide the user instead of prompting into a 400
        const [statusMap, foldersWithApprovalPolicy] = await Promise.all([
          pamAccessRequestService.getAccessStatusBatch(
            { actorId: actor.actorId, actor: actor.actor },
            [account.id],
            projectId
          ),
          pamAccessRequestService.getFolderPolicyConfigured(account.folderId ? [account.folderId] : [])
        ]);
        throw new ForbiddenRequestError({
          name: "PAM_APPROVAL_REQUIRED",
          message: "Access request required",
          details: {
            requireReason: policy.requireReason,
            hasPendingRequest: statusMap.get(account.id)?.accessStatus === ApprovalAccessStatus.Pending,
            hasApprovalPolicy: Boolean(
              account.folderId && foldersWithApprovalPolicy.isConfiguredFor(account.folderId, policy.allowAutoApproval)
            )
          }
        });
      }
      // A null expiresAt means a never-expiring grant per the checkGrant contract
      if (grant.expiresAt) {
        const grantRemainingMs = new Date(grant.expiresAt).getTime() - Date.now();
        if (grantRemainingMs <= 0) {
          throw new ForbiddenRequestError({
            name: "PAM_GRANT_EXPIRED",
            message: "Your approved access has expired",
            details: { requireReason: policy.requireReason }
          });
        }
        sessionDurationMs = Math.min(sessionDurationMs, grantRemainingMs);
      }
    }

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

    // AWS IAM: no gateway, no proxy -- generate STS credentials directly
    if (account.accountType === PamAccountType.AwsIam) {
      const stsDurationSeconds = Math.floor(sessionDurationMs / 1000);

      if (stsDurationSeconds < AWS_STS_MIN_DURATION_SECONDS) {
        throw new BadRequestError({
          message: `AWS IAM sessions require a minimum duration of ${AWS_STS_MIN_DURATION_SECONDS} seconds (15 minutes)`
        });
      }

      const rawConnectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);
      const roleArn = rawConnectionDetails.roleArn as string;

      // Machine identities have no email; fall back to the identity name for STS attribution.
      const federatedUsername = actorEmail || actorName;

      // STS requires roleSessionName to be 2-64 chars; pad short names with random characters
      // so the actor's name stays recognizable in CloudTrail (1-char identity name, user with
      // no email and empty names)
      let roleSessionName = federatedUsername.replace(new RE2(/[^\w+=,.@-]/g), "_").substring(0, 64);
      if (roleSessionName.length < 2) {
        roleSessionName = `${roleSessionName}${alphaNumericNanoId(8)}`;
      }

      const stsCredentials = await generateAwsIamSessionCredentials({
        roleArn,
        // PAM is one project per org, so the actor's org owns this account. We use the org ID as the
        // STS External ID so the customer's role trust policy scopes assumption to this Infisical org.
        externalId: actor.actorOrgId,
        roleSessionName,
        sessionDuration: stsDurationSeconds
      });

      const { expiresAt } = stsCredentials;

      const metadata: Record<string, string> = {};

      if (accessMethod === PamAccessMethod.Web) {
        const consoleUrl = await exchangeCredentialsForConsoleUrl({
          accessKeyId: stsCredentials.accessKeyId,
          secretAccessKey: stsCredentials.secretAccessKey,
          sessionToken: stsCredentials.sessionToken
        });
        metadata.consoleUrl = consoleUrl;
      } else {
        metadata.accessKeyId = stsCredentials.accessKeyId;
        metadata.secretAccessKey = stsCredentials.secretAccessKey;
        metadata.sessionToken = stsCredentials.sessionToken;
        metadata.expiresAt = expiresAt.toISOString();
        metadata.roleArn = roleArn;
        metadata.federatedUsername = federatedUsername;

        const awsAccountId = extractAwsAccountIdFromArn(roleArn);
        if (awsAccountId) {
          metadata.awsAccountId = awsAccountId;
        }
      }

      const session = await pamSessionDAL.transaction(async (tx) => {
        if (isUserActor) {
          await assertUserStillActiveInOrg({
            orgId: actor.actorOrgId,
            userId: actor.actorId,
            membershipDAL,
            orgDAL,
            tx
          });
        }

        return pamSessionDAL.create(
          {
            status: PamSessionStatus.Active,
            accessMethod,
            expiresAt,
            startedAt: new Date(),
            accountName: account.name,
            accountType: account.accountType,
            actorEmail,
            actorIp,
            actorName,
            actorUserAgent,
            projectId,
            accountId: account.id,
            // userId FKs users and identityId FKs identities; exactly one is set based on the actor type
            userId: isUserActor ? actor.actorId : null,
            identityId: isUserActor ? null : actor.actorId,
            reason: trimmedReason,
            folderName: account.folderName
          },
          tx
        );
      });

      await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);

      return {
        sessionId: session.id,
        accountId: account.id,
        accountType: account.accountType as PamAccountType,
        accountName: account.name,
        metadata,
        sessionDurationMs,
        accessMethod
      };
    }

    enforceRecordingConfig(account);

    await gatewayPoolService.assertGatewayBindingInOrg({
      gatewayId: account.gatewayId ?? account.templateGatewayId,
      gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId,
      orgId: actor.actorOrgId
    });
    const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
      gatewayId: account.gatewayId ?? account.templateGatewayId,
      gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
    });
    if (!effectiveGatewayId) {
      throw new BadRequestError({ message: "Gateway not configured for this account" });
    }

    const rawConnectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);
    const rawCredentials = await decrypt(projectId, account.encryptedCredentials);
    const gatewayTarget = await extractGatewayTarget(account.accountType as PamAccountType, rawConnectionDetails);

    const connectHost =
      resolveSelectedHost(account.accountType as PamAccountType, rawConnectionDetails, targetHost) ??
      gatewayTarget.host;

    const user = isUserActor ? await userDAL.findById(actor.actorId) : null;
    const expiresAt = new Date(Date.now() + sessionDurationMs);

    const session = await pamSessionDAL.transaction(async (tx) => {
      if (isUserActor) {
        await assertUserStillActiveInOrg({ orgId: actor.actorOrgId, userId: actor.actorId, membershipDAL, orgDAL, tx });
      }

      return pamSessionDAL.create(
        {
          status: PamSessionStatus.Starting,
          accessMethod: PamAccessMethod.Cli,
          expiresAt,
          accountName: account.name,
          accountType: account.accountType,
          actorEmail,
          actorIp,
          actorName,
          actorUserAgent,
          projectId,
          accountId: account.id,
          // userId FKs users and identityId FKs identities; exactly one is set based on the actor type
          userId: isUserActor ? actor.actorId : null,
          identityId: isUserActor ? null : actor.actorId,
          gatewayId: effectiveGatewayId,
          reason: trimmedReason,
          folderName: account.folderName,
          selectedHost: connectHost
        },
        tx
      );
    });

    await pamSessionDAL.activateSession(session.id);
    await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);

    const certs = await gatewayV2Service.getPAMConnectionDetails({
      gatewayId: effectiveGatewayId,
      sessionId: session.id,
      accountType: resolveGatewayAccountType(account.accountType as PamAccountType),
      host: connectHost,
      port: gatewayTarget.port,
      duration: sessionDurationMs,
      actorMetadata: {
        id: actor.actorId,
        type: actor.actor,
        name: user?.email ?? actorName
      },
      // The platform dials for web sessions, so only a CLI caller is gated on its version.
      clientSupportsDirect:
        accessMethod === PamAccessMethod.Web || cliSupports(actorUserAgent, CliCapability.DirectGatewayTransport)
    });

    if (!certs) {
      throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
    }

    const metadata: Record<string, string> = {};

    if (account.accountType === PamAccountType.GcpServiceAccount) {
      metadata.serviceAccountEmail = rawConnectionDetails.serviceAccountEmail as string;
      metadata.authMethod = rawCredentials.authMethod as string;
    } else if (account.accountType === PamAccountType.AzureCli) {
      metadata.tenantId = rawConnectionDetails.tenantId as string;
      metadata.clientId = rawCredentials.clientId as string;
      if (rawConnectionDetails.subscriptionId) {
        metadata.subscriptionId = rawConnectionDetails.subscriptionId as string;
      }
    } else if (account.accountType === PamAccountType.Snowflake) {
      for (const key of ["account", "warehouse", "database", "schema", "role"]) {
        const value = rawConnectionDetails[key];
        if (typeof value === "string" && value) metadata[key] = value;
      }
    } else if (account.accountType === PamAccountType.Kubernetes) {
      metadata.authMethod = rawCredentials.authMethod as string;
      if (rawCredentials.namespace) {
        metadata.namespace = rawCredentials.namespace as string;
      }
      if (rawCredentials.serviceAccountName) {
        metadata.serviceAccountName = rawCredentials.serviceAccountName as string;
      }
    } else {
      metadata.username = rawCredentials.username as string;
      if (
        (account.accountType === PamAccountType.Postgres ||
          account.accountType === PamAccountType.MySQL ||
          account.accountType === PamAccountType.MongoDB ||
          account.accountType === PamAccountType.MsSQL ||
          account.accountType === PamAccountType.OracleDB ||
          account.accountType === PamAccountType.ClickHouse) &&
        rawConnectionDetails.database
      ) {
        metadata.database = rawConnectionDetails.database as string;
      }
    }

    return {
      sessionId: session.id,
      accountId: account.id,
      accountType: account.accountType as PamAccountType,
      accountName: account.name,
      metadata,
      sessionDurationMs,
      accessMethod: PamAccessMethod.Cli,
      gatewayId: certs.gatewayId,
      relayHost: certs.relayHost,
      directAddress: certs.directAddress,
      relayClientCertificate: certs.relay?.clientCertificate,
      relayClientPrivateKey: certs.relay?.clientPrivateKey,
      relayServerCertificateChain: certs.relay?.serverCertificateChain,
      gatewayClientCertificate: certs.gateway.clientCertificate,
      gatewayClientPrivateKey: certs.gateway.clientPrivateKey,
      gatewayServerCertificateChain: certs.gateway.serverCertificateChain
    };
  };

  const terminateSession = async (sessionId: string, ctx: TActorContext) => {
    const session = await pamSessionDAL.findById(sessionId);
    if (!session) {
      throw new NotFoundError({ message: "Session not found" });
    }

    if (session.status !== PamSessionStatus.Active && session.status !== PamSessionStatus.Starting) {
      throw new BadRequestError({ message: "Session is not active" });
    }

    await checkSession(session, ResourcePermissionPamResourceActions.TerminateSessions, ctx);

    const updated = await pamSessionDAL.terminateSessionById(sessionId);
    if (!updated) {
      throw new BadRequestError({ message: "Session could not be terminated" });
    }

    if (session.gatewayId) {
      const user = await userDAL.findById(ctx.actorId);
      sendPamSessionCancellationSignal({
        sessionId,
        gatewayId: session.gatewayId,
        accountType: session.accountType,
        actorId: ctx.actorId,
        actorEmail: user?.email ?? "",
        gatewayV2Service
      });
    }

    return { session: updated, projectId: session.projectId, accountName: session.accountName };
  };

  return {
    access,
    listSessions,
    getSessionById,
    getSessionCredentials,
    endSessionFromGateway,
    terminateSession
  };
};