Skip to content

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

42.9 KB
Raw Blame
import z from "zod";

import { PamAccountsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ROTATION_STATUS } from "@app/ee/services/pam-account-rotation/pam-account-rotation-service";
import {
  PamAccountSettingsOverridesSchema,
  PamTemplateSettingsSchema
} from "@app/ee/services/pam-account-template/pam-account-template-schemas";
import {
  ACCOUNT_TYPE_CONFIGS,
  buildPamAccountTypeMetadata,
  PamAccountAccessibilityIssue,
  PamAccountTypeMetadataSchema,
  revealedCredentialsSchema
} from "@app/ee/services/pam-account/pam-account-schemas";
import { SESSION_HANDLERS } from "@app/ee/services/pam-web-access/pam-session-handlers";
import { PamAccountType, PamAccountWarning, PamHeartbeatStatus } from "@app/ee/services/pam/pam-enums";
import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general/password-requirements-schema";
import { ApiDocsTags } from "@app/lib/api-docs/constants";
import { BadRequestError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { auditSafeText, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { withRoutePrefix } from "@app/server/lib/with-route-prefix";
import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ApprovalAccessStatus } from "@app/services/approval-policy/approval-policy-types";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

type TSupportedConfigs = typeof ACCOUNT_TYPE_CONFIGS;
type TSupportedAccountType = keyof TSupportedConfigs;
type TSupportedConfigValue = TSupportedConfigs[TSupportedAccountType];

const BaseAccountFields = PamAccountsSchema.pick({
  id: true,
  name: true,
  description: true,
  folderId: true,
  templateId: true,
  gatewayId: true,
  gatewayPoolId: true,
  recordingConnectionId: true,
  settingsOverrides: true,
  createdAt: true,
  updatedAt: true
});

const SanitizedAccountListItemSchema = BaseAccountFields.extend({
  folderName: z.string().nullable().optional(),
  templateName: z.string(),
  accountType: z.string()
});

const PamAccountListItemSchema = SanitizedAccountListItemSchema.extend({
  isAccessible: z.boolean().describe("Whether the account is fully provisioned to launch a session"),
  accessibilityIssues: z
    .array(z.nativeEnum(PamAccountAccessibilityIssue))
    .describe("Reasons the account cannot launch a session, if any"),
  isStale: z.boolean().describe("Whether the discovery source's latest scan no longer found this account."),
  warnings: z
    .array(z.nativeEnum(PamAccountWarning))
    .describe("Conditions worth surfacing on the account that do not block launching a session."),
  heartbeatStatus: z
    .nativeEnum(PamHeartbeatStatus)
    .nullable()
    .optional()
    .describe("Result of the most recent credential health check, if one has run."),
  heartbeatEnabled: z
    .boolean()
    .describe("Whether the account's template has scheduled credential health checks turned on."),
  requiresApproval: z.boolean().describe("Whether this account requires approval before launching a session"),
  requireReason: z.boolean().describe("Whether the account's template requires a reason for access"),
  accessStatus: z.nativeEnum(ApprovalAccessStatus).describe("Current approval status for the caller"),
  grantExpiresAt: z.date().nullable().describe("When the current grant expires, if granted"),
  pendingRequestId: z.string().nullable().describe("The caller's pending access request for this account, if any"),
  canBreakGlass: z.boolean().describe("Whether the caller may self-approve their own pending request for this account"),
  supportsCredentialReveal: z.boolean().describe("Whether this account type stores a credential that can be revealed"),
  credentialAccessStatus: z
    .nativeEnum(ApprovalAccessStatus)
    .describe("Current credential-approval status for the caller"),
  credentialPendingRequestId: z
    .string()
    .nullable()
    .describe("The caller's pending credential access request for this account, if any"),
  permissions: z.any().array().describe("The caller's effective (packed) resource permissions on this account")
});

const accountDetailVariants = Object.entries(ACCOUNT_TYPE_CONFIGS).map(([accountType, config]) =>
  SanitizedAccountListItemSchema.extend({
    accountType: z.literal(accountType as TSupportedAccountType),
    connectionDetails: config.connectionDetails,
    templatePolicies: z.record(z.unknown()).nullable().optional(),
    templateSettings: PamTemplateSettingsSchema.nullable().optional(),
    credentials: config.sanitizedCredentials,
    isAccessible: z.boolean().describe("Whether the account is fully provisioned to launch a session"),
    accessibilityIssues: z
      .array(z.nativeEnum(PamAccountAccessibilityIssue))
      .describe("Reasons the account cannot launch a session, if any"),
    isStale: z.boolean().describe("Whether the discovery source's latest scan no longer found this account."),
    webAccessUnavailableReason: z
      .string()
      .nullable()
      .optional()
      .describe("Why a browser session cannot open this account, or null when it can")
  })
);

const SanitizedAccountDetailSchema = z.discriminatedUnion(
  "accountType",
  accountDetailVariants as [(typeof accountDetailVariants)[number], ...(typeof accountDetailVariants)[number][]]
);

const accountCredentialVariants = Object.keys(ACCOUNT_TYPE_CONFIGS).map((accountType) =>
  z.object({
    accountType: z.literal(accountType as TSupportedAccountType),
    credentials: revealedCredentialsSchema(accountType as TSupportedAccountType).describe(
      "The account's stored credentials, secrets included"
    )
  })
);

const PamAccountCredentialsSchema = z.discriminatedUnion(
  "accountType",
  accountCredentialVariants as [
    (typeof accountCredentialVariants)[number],
    ...(typeof accountCredentialVariants)[number][]
  ]
);

const toPascalCase = (s: string) =>
  s
    .split("-")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join("");

const registerPerTypeEndpoints = (
  server: FastifyZodProvider,
  accountType: PamAccountType,
  config: TSupportedConfigValue
) => {
  const typeId = toPascalCase(accountType);

  server.route({
    method: "POST",
    url: "/",
    schema: {
      operationId: `create${typeId}PamAccount`,
      description: `Create a new ${accountType} PAM account`,
      tags: [ApiDocsTags.PamAccounts],
      body: z.object({
        name: slugSchema({ field: "Name" }).describe("Name for the account"),
        description: z.string().trim().max(256).optional().describe("Optional description of the account"),
        folderId: z.string().uuid().describe("The ID of the folder to place the account in"),
        templateId: z.string().uuid().describe("The ID of the account template to use"),
        connectionDetails: config.connectionDetails,
        credentials: config.credentials,
        gatewayId: z.string().uuid().optional().describe("The ID of the gateway to use"),
        gatewayPoolId: z.string().uuid().optional().describe("The ID of the gateway pool to use"),
        recordingConnectionId: z.string().uuid().optional().describe("The ID of the recording connection to use"),
        settingsOverrides: PamAccountSettingsOverridesSchema.nullable()
          .optional()
          .describe("Account-level template settings overrides")
      }),
      response: {
        200: z.object({
          account: BaseAccountFields.extend({
            accountType: z.string(),
            folderName: z.string(),
            templateName: z.string(),
            connectionDetails: z.record(z.unknown())
          }),
          corsProbeUrl: z.string().nullable().optional()
        })
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { corsProbeUrl, ...account } = await server.services.pamAccount.create({
        accountType,
        ...req.body,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_CREATE,
          metadata: {
            accountId: account.id,
            accountType,
            folderId: req.body.folderId,
            templateId: req.body.templateId,
            name: req.body.name,
            description: req.body.description
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.PamAccountCreated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            accountType,
            orgId: req.permission.orgId
          }
        })
        .catch(() => {});

      return { account, corsProbeUrl };
    }
  });

  server.route({
    method: "PATCH",
    url: "/:accountId",
    schema: {
      operationId: `update${typeId}PamAccount`,
      description: `Update a ${accountType} PAM account`,
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account to update") }),
      body: z.object({
        name: slugSchema({ field: "Name" }).optional().describe("New name for the account"),
        description: z.string().trim().max(256).nullable().optional().describe("Optional description of the account"),
        folderId: z.string().uuid().optional().describe("The ID of the folder to move the account to"),
        templateId: z.string().uuid().optional().describe("The ID of the account template to use"),
        connectionDetails: config.connectionDetails.optional(),
        credentials: config.credentials.optional(),
        gatewayId: z.string().uuid().nullable().optional().describe("The ID of the gateway to use"),
        gatewayPoolId: z.string().uuid().nullable().optional().describe("The ID of the gateway pool to use"),
        recordingConnectionId: z
          .string()
          .uuid()
          .nullable()
          .optional()
          .describe("The ID of the recording connection to use"),
        settingsOverrides: PamAccountSettingsOverridesSchema.nullable()
          .optional()
          .describe("Account-level template settings overrides")
      }),
      response: {
        200: z.object({
          account: BaseAccountFields,
          corsProbeUrl: z.string().nullable().optional()
        })
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { corsProbeUrl, ...account } = await server.services.pamAccount.update({
        accountId: req.params.accountId,
        accountType,
        ...req.body,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_UPDATE,
          metadata: {
            accountId: account.id,
            accountType,
            name: req.body.name,
            description: req.body.description,
            folderId: req.body.folderId,
            templateId: req.body.templateId,
            gatewayId: req.body.gatewayId,
            gatewayPoolId: req.body.gatewayPoolId,
            connectionDetailsUpdated: !!req.body.connectionDetails,
            credentialsUpdated: !!req.body.credentials
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.PamAccountUpdated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            accountType,
            orgId: req.permission.orgId
          }
        })
        .catch(() => {});

      return { account, corsProbeUrl };
    }
  });

  server.route({
    method: "DELETE",
    url: "/:accountId",
    schema: {
      operationId: `delete${typeId}PamAccount`,
      description: `Delete a ${accountType} PAM account`,
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account to delete") }),
      response: {
        200: z.object({ account: BaseAccountFields })
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const account = await server.services.pamAccount.deleteAccount({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_DELETE,
          metadata: {
            accountId: account.id,
            accountType,
            accountName: account.name
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.PamAccountDeleted,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            accountType,
            orgId: req.permission.orgId
          }
        })
        .catch(() => {});

      return { account };
    }
  });
};

export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
  server.route({
    method: "GET",
    url: "/types",
    schema: {
      operationId: "listPamAccountTypes",
      description: "List supported PAM account types and their form field metadata",
      tags: [ApiDocsTags.PamAccounts],
      response: {
        200: z.object({
          accountTypes: z.array(PamAccountTypeMetadataSchema)
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async () => {
      return {
        // AWS IAM supports browser access (console URL redirect) but not WebSocket-based terminal,
        // so it's added separately from SESSION_HANDLERS
        accountTypes: buildPamAccountTypeMetadata(
          new Set([...Object.keys(SESSION_HANDLERS), PamAccountType.AwsIam] as PamAccountType[])
        )
      };
    }
  });

  server.route({
    method: "GET",
    url: "/",
    schema: {
      operationId: "listPamAccounts",
      description: "List all PAM accounts in the project",
      tags: [ApiDocsTags.PamAccounts],
      querystring: z.object({
        folderId: z.string().uuid().optional().describe("Filter accounts by folder ID"),
        templateId: z.string().uuid().optional().describe("Filter accounts by template ID"),
        accountType: z.nativeEnum(PamAccountType).optional().describe("Filter accounts by platform type"),
        search: z.string().trim().optional().describe("Filter accounts by name")
      }),
      response: {
        200: z.object({ accounts: z.array(PamAccountListItemSchema) })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const accounts = await server.services.pamAccount.list({
        projectId: req.internalPamProjectId,
        folderId: req.query.folderId,
        templateId: req.query.templateId,
        accountType: req.query.accountType,
        search: req.query.search,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      return { accounts };
    }
  });

  server.route({
    method: "GET",
    url: "/accessible",
    schema: {
      operationId: "listAccessiblePamAccounts",
      description: "List PAM accounts accessible to the current user",
      tags: [ApiDocsTags.PamAccounts],
      querystring: z.object({
        offset: z.coerce.number().min(0).default(0).optional().describe("Number of items to skip"),
        limit: z.coerce.number().min(1).max(100).default(20).optional().describe("Maximum number of items to return"),
        search: z.string().trim().optional().describe("Filter accounts by name (case-insensitive partial match)"),
        folderId: z.string().uuid().optional().describe("Filter accounts by folder ID"),
        accountType: z.nativeEnum(PamAccountType).optional().describe("Filter accounts by platform type")
      }),
      response: {
        200: z.object({
          accounts: z.array(
            SanitizedAccountListItemSchema.pick({
              id: true,
              name: true,
              description: true,
              folderId: true,
              templateId: true,
              createdAt: true,
              updatedAt: true,
              folderName: true,
              templateName: true,
              accountType: true
            }).extend({
              canLaunch: z.boolean().describe("Whether the caller can launch a session for this account"),
              requiresApproval: z
                .boolean()
                .describe("Whether this account requires approval before launching a session"),
              requireReason: z.boolean().describe("Whether the account's template requires a reason for access"),
              requireMfa: z
                .boolean()
                .describe(
                  "Whether launching a session for this account requires MFA verification. Machine identities cannot satisfy MFA, so launch is rejected for them when this is true."
                ),
              accessStatus: z.nativeEnum(ApprovalAccessStatus).describe("Current approval status for the caller"),
              grantExpiresAt: z.date().nullable().describe("When the current grant expires, if granted"),
              pendingRequestId: z
                .string()
                .nullable()
                .describe("The caller's pending access request for this account, if any"),
              canBreakGlass: z
                .boolean()
                .describe("Whether the caller may self-approve their own pending request for this account"),
              disabledReason: z.string().nullable().describe("Why this account is disabled, or null if usable")
            })
          ),
          totalCount: z.number()
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { accounts, totalCount } = await server.services.pamAccount.listAccessible({
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod,
        offset: req.query.offset,
        limit: req.query.limit,
        search: req.query.search,
        folderId: req.query.folderId,
        accountType: req.query.accountType
      });
      return { accounts, totalCount };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/permissions",
    config: { rateLimit: readLimit },
    schema: {
      operationId: "getPamAccountPermissions",
      description:
        "Get the caller's effective resource permissions on this account, merging folder-level and direct account-level roles.",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          data: z.object({
            permissions: z.any().array(),
            memberships: z
              .object({
                id: z.string(),
                actorUserId: z.string().nullish(),
                actorIdentityId: z.string().nullish(),
                actorGroupId: z.string().nullish(),
                roles: z.object({ role: z.string(), customRoleSlug: z.string().nullish() }).array()
              })
              .array()
          })
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const data = await server.services.pamAccount.getAccountPermissions({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      return { data };
    }
  });

  const RotationViewSchema = z.object({
    enabled: z.boolean(),
    intervalSeconds: z.number().nullable(),
    passwordRequirements: PasswordRequirementsSchema.nullable(),
    rotationAccountId: z.string().nullable(),
    rotationAccountName: z.string().nullable(),
    lastRotatedAt: z.date().nullable(),
    rotationStatus: z.string().nullable(),
    lastRotationError: z.string().nullable(),
    isReady: z.boolean(),
    sharedIdentity: z.object({ id: z.string(), name: z.string(), discoverySources: z.string().array() }).array()
  });

  server.route({
    method: "GET",
    url: "/:accountId/rotation",
    schema: {
      operationId: "getPamAccountRotation",
      description: "Get the credential rotation config and state for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: { 200: z.object({ rotation: RotationViewSchema }) }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const rotation = await server.services.pamAccountRotation.getRotation({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      return { rotation };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/dependencies",
    schema: {
      operationId: "listPamAccountDependencies",
      description:
        "List the detected dependencies (Windows services, scheduled tasks, IIS app pools) for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          dependencies: z.array(
            z.object({
              id: z.string(),
              type: z.string(),
              name: z.string(),
              machine: z.string(),
              data: z.unknown(),
              rotationStatus: z.string().nullable(),
              lastRotatedAt: z.date().nullable(),
              lastRotationMessage: z.string().nullable()
            })
          )
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const dependencies = await server.services.pamDiscovery.listAccountDependencies({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      return { dependencies };
    }
  });

  server.route({
    method: "PATCH",
    url: "/:accountId/rotation",
    schema: {
      operationId: "setPamAccountRotationAccount",
      description: "Set or clear the rotation account for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      body: z.object({
        rotationAccountId: z
          .string()
          .uuid()
          .nullable()
          .describe("Account that performs the rotation. Its own id for self-rotation, or null to clear")
      }),
      response: { 200: z.object({ rotationAccountId: z.string().nullable() }) }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pamAccountRotation.setRotationAccount({
        accountId: req.params.accountId,
        rotationAccountId: req.body.rotationAccountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_SET_ROTATION_ACCOUNT,
          metadata: {
            accountId: req.params.accountId,
            accountName: result.accountName,
            rotationAccountId: result.rotationAccountId,
            rotationAccountName: result.rotationAccountName
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.PamAccountRotationConfigured,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            accountType: result.accountType,
            orgId: req.permission.orgId,
            hasRotationAccount: Boolean(result.rotationAccountId),
            scheduledRotationEnabled: result.scheduledRotationEnabled
          }
        })
        .catch(() => {});

      return { rotationAccountId: result.rotationAccountId };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/health",
    schema: {
      operationId: "getPamAccountCredentialHealth",
      description: "Get a PAM account's credential health",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          heartbeat: z.object({
            enabled: z.boolean(),
            intervalSeconds: z.number().nullable(),
            status: z.nativeEnum(PamHeartbeatStatus).nullable().describe("Most recent check result"),
            lastCheckedAt: z.date().nullable(),
            lastHealthyAt: z.date().nullable(),
            nextCheckAt: z.date().nullable(),
            templateName: z.string(),
            lastMessage: z.string().nullable()
          })
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    handler: async (req) => {
      const heartbeat = await server.services.pamAccountHeartbeat.getHeartbeat(
        { accountId: req.params.accountId, projectId: req.internalPamProjectId },
        {
          actorId: req.permission.id,
          actor: req.permission.type,
          actorOrgId: req.permission.orgId,
          actorAuthMethod: req.permission.authMethod
        }
      );
      return { heartbeat };
    }
  });

  server.route({
    method: "POST",
    url: "/:accountId/health/check",
    schema: {
      operationId: "checkPamAccountCredentialHealth",
      description: "Run a credential health check on a PAM account now",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          heartbeatStatus: z.string(),
          message: z.string().optional()
        })
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    handler: async (req) => {
      const result = await server.services.pamAccountHeartbeat.checkAccount(
        { accountId: req.params.accountId, projectId: req.internalPamProjectId },
        {
          actorId: req.permission.id,
          actor: req.permission.type,
          actorOrgId: req.permission.orgId,
          actorAuthMethod: req.permission.authMethod
        }
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_HEARTBEAT,
          metadata: {
            accountId: req.params.accountId,
            accountName: result.accountName,
            accountType: result.accountType,
            heartbeatStatus: result.status,
            manual: true,
            ...(result.message ? { message: result.message } : {})
          }
        }
      });

      return { heartbeatStatus: result.status, ...(result.message ? { message: result.message } : {}) };
    }
  });

  server.route({
    method: "POST",
    url: "/:accountId/rotation/rotate",
    schema: {
      operationId: "rotatePamAccountCredentials",
      description: "Rotate a PAM account's credential now",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: { 200: z.object({ rotationStatus: z.string() }) }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pamAccountRotation.rotateNow({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS,
          metadata: {
            accountId: req.params.accountId,
            accountName: result.accountName,
            accountType: result.accountType,
            rotationStatus: result.rotationStatus,
            manual: true,
            rotationAccountId: result.rotationAccountId,
            rotationAccountName: result.rotationAccountName,
            ...(result.message ? { message: result.message } : {})
          }
        }
      });

      // Audited above first, so a failed rotation is logged before the request errors.
      if (result.rotationStatus !== ROTATION_STATUS.Success) {
        throw new BadRequestError({ message: result.message ?? "Rotation failed" });
      }

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.PamAccountRotated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            accountType: result.accountType,
            orgId: req.permission.orgId
          }
        })
        .catch(() => {});

      return { rotationStatus: result.rotationStatus };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/rotation/rotation-account-candidates",
    schema: {
      operationId: "listPamRotationAccountCandidates",
      description: "List accounts eligible to be this account's rotation account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          candidates: z.array(
            z.object({
              folderId: z.string().nullable(),
              folderName: z.string().nullable(),
              accounts: z.array(z.object({ id: z.string(), name: z.string(), host: z.string() }))
            })
          )
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      return server.services.pamAccountRotation.listRotationCandidates({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId",
    schema: {
      operationId: "getPamAccount",
      description: "Get a PAM account by ID",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({
          account: SanitizedAccountDetailSchema
        })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const account = await server.services.pamAccount.getById({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      return { account } as unknown as { account: z.infer<typeof SanitizedAccountDetailSchema> };
    }
  });

  server.route({
    method: "POST",
    url: "/:accountId/credentials",
    schema: {
      operationId: "getPamAccountCredentials",
      description: "Reveal the stored credentials for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      body: z.object({
        reason: auditSafeText(z.string().trim().max(500), { allowMultiline: true })
          .optional()
          .describe("Why the credentials are being viewed. Required when the template requires a reason."),
        mfaSessionId: z
          .string()
          .max(64)
          .optional()
          .describe("A verified MFA session ID. Required when the template requires MFA.")
      }),
      response: {
        200: PamAccountCredentialsSchema
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    handler: async (req) => {
      const result = await server.services.pamAccount.getCredentials({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorEmail: isUserSessionAuth(req.auth) ? (req.auth.user.email ?? "") : "",
        reason: req.body.reason,
        mfaSessionId: req.body.mfaSessionId,
        tokenVersionId: isUserSessionAuth(req.auth) ? req.auth.tokenVersionId : undefined,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: req.internalPamProjectId,
        event: {
          type: EventType.PAM_ACCOUNT_CREDENTIALS_VIEW,
          metadata: {
            accountId: result.accountId,
            accountName: result.accountName,
            accountType: result.accountType,
            folderId: result.folderId,
            folderName: result.folderName,
            reason: result.reason,
            grantExpiresAt: result.grantExpiresAt?.toISOString() ?? null
          }
        }
      });

      return { accountType: result.accountType, credentials: result.credentials } as unknown as z.infer<
        typeof PamAccountCredentialsSchema
      >;
    }
  });

  server.route({
    method: "POST",
    url: "/:accountId/ssh-ca",
    schema: {
      operationId: "getOrCreatePamSshCa",
      description: "Get or create an SSH certificate authority for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({ publicKey: z.string() })
      }
    },
    config: { rateLimit: writeLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pamAccount.getOrCreateSshCa({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      if (result.created) {
        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          orgId: req.permission.orgId,
          projectId: req.internalPamProjectId,
          event: {
            type: EventType.PAM_ACCOUNT_SSH_CA_CREATE,
            metadata: {
              accountId: req.params.accountId,
              keyAlgorithm: result.keyAlgorithm || "unknown"
            }
          }
        });
      }

      return { publicKey: result.publicKey };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/ssh-ca-public-key",
    schema: {
      operationId: "getPamSshCaPublicKey",
      description: "Get the SSH CA public key for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.object({ publicKey: z.string() })
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pamAccount.getOrCreateSshCa({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      if (result.created) {
        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          orgId: req.permission.orgId,
          projectId: req.internalPamProjectId,
          event: {
            type: EventType.PAM_ACCOUNT_SSH_CA_CREATE,
            metadata: {
              accountId: req.params.accountId,
              keyAlgorithm: result.keyAlgorithm!
            }
          }
        });
      }

      return { publicKey: result.publicKey };
    }
  });

  server.route({
    method: "GET",
    url: "/:accountId/ssh-ca-setup",
    schema: {
      operationId: "getPamSshCaSetupScript",
      description: "Get the SSH CA setup script for a PAM account",
      tags: [ApiDocsTags.PamAccounts],
      params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
      response: {
        200: z.string()
      }
    },
    config: { rateLimit: readLimit },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req, reply) => {
      const result = await server.services.pamAccount.getOrCreateSshCa({
        accountId: req.params.accountId,
        projectId: req.internalPamProjectId,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });
      // Trim trailing newline; otherwise the script's echo/grep treat it as a blank line and skip later keys.
      const caPublicKey = result.publicKey.trim();

      if (result.created) {
        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          orgId: req.permission.orgId,
          projectId: req.internalPamProjectId,
          event: {
            type: EventType.PAM_ACCOUNT_SSH_CA_CREATE,
            metadata: {
              accountId: req.params.accountId,
              keyAlgorithm: result.keyAlgorithm || "unknown"
            }
          }
        });
      }

      const setupScript = `#!/bin/bash
set -e

CA_PUBLIC_KEY="${caPublicKey}"
CA_FILE="/etc/ssh/infisical_ca.pub"
SSHD_CONFIG="/etc/ssh/sshd_config"

echo "==> Infisical SSH CA Setup"
echo ""

if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

echo "==> Configuring the trusted CA file..."

# Reuse the host's existing TrustedUserCAKeys file if set (sshd honors only the first); else use our own.
CONFIGURE_SSHD=true
if grep -qE "^[[:space:]]*TrustedUserCAKeys[[:space:]]" "\${SSHD_CONFIG}"; then
    EXISTING_CA_FILE=$(grep -E "^[[:space:]]*TrustedUserCAKeys[[:space:]]" "\${SSHD_CONFIG}" | head -n1 | awk '{print $2}')
    if [ -n "\${EXISTING_CA_FILE}" ]; then
        CA_FILE="\${EXISTING_CA_FILE}"
        CONFIGURE_SSHD=false
        echo "    Adding to existing TrustedUserCAKeys file: \${CA_FILE}"
    fi
fi

# Ensure the file exists and is sshd-readable (public keys are not secret)
touch "\${CA_FILE}"
chmod 644 "\${CA_FILE}"

# Additive + idempotent: append only if not already trusted; never removes existing CAs
if grep -qxF "\${CA_PUBLIC_KEY}" "\${CA_FILE}"; then
    echo "    CA key already present in \${CA_FILE}"
else
    echo "\${CA_PUBLIC_KEY}" >> "\${CA_FILE}"
    echo "    Added Infisical CA key to \${CA_FILE}"
fi

if [ "\${CONFIGURE_SSHD}" = "true" ]; then
    echo "==> Adding TrustedUserCAKeys to \${SSHD_CONFIG}..."
    echo "" >> "\${SSHD_CONFIG}"
    echo "# Infisical SSH CA - Added by setup script" >> "\${SSHD_CONFIG}"
    echo "TrustedUserCAKeys \${CA_FILE}" >> "\${SSHD_CONFIG}"
    echo "    Done."
fi

echo "==> Validating SSH configuration..."
if sshd -t; then
    echo "    Configuration is valid."
else
    echo "Error: SSH configuration is invalid. Please check \${SSHD_CONFIG}"
    exit 1
fi

echo "==> Restarting SSH service..."
if command -v systemctl &> /dev/null; then
    if systemctl cat sshd.service &>/dev/null; then
        systemctl restart sshd
    elif systemctl cat ssh.service &>/dev/null; then
        systemctl restart ssh
    else
        echo "Warning: Could not find SSH service. Please restart it manually."
    fi
elif command -v service &> /dev/null; then
    service sshd restart 2>/dev/null || service ssh restart
else
    echo "Warning: Could not detect init system. Please restart sshd manually."
fi
echo "    Done."

echo ""
echo "==> Setup complete!"
echo ""
echo "Your SSH server is now configured to trust certificates signed by the Infisical CA."
echo ""
`;

      void reply.header("Content-Type", "text/plain; charset=utf-8");
      return setupScript;
    }
  });

  await server.register(async (accountRouter) => {
    for (const [accountType, config] of Object.entries(ACCOUNT_TYPE_CONFIGS) as [
      TSupportedAccountType,
      TSupportedConfigValue
    ][]) {
      registerPerTypeEndpoints(withRoutePrefix(accountRouter, `/${accountType}`), accountType, config);
    }
  });
};