Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Merge branch 'main' into PAM-331
x1efa8482934d
diff --cc backend/src/ee/services/pam/CLAUDE.mdindex 9b68fe2ea8,79adc83beb..b4e42a308d--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@@ -56,28 -96,97 +56,34 @@@ above. The `injectPamProjectId` hook re## Account Types-Defined in `pam/pam-enums.ts` as `PamAccountType`. Each type's full config lives in `pam-account/pam-account-schemas.ts` in the `ACCOUNT_TYPE_CONFIGS` map. A config entry holds everything the backend and frontend need for that type:--- `name` -- human-readable label (e.g. `"PostgreSQL"`), served to the frontend-- `icon` -- icon filename under the frontend's account-platform icons (e.g. `"Postgres.png"`)-- `connectionDetails` -- Zod schema for the non-secret connection fields-- `credentials` -- Zod schema for the secret credentials (a `ZodObject` or a `ZodDiscriminatedUnion`)-- `sanitizedCredentials` -- Zod allowlist of credential fields that are safe to return in API responses (e.g. `username` but never `password`). This is the single source of truth for what's a secret -- there is no string-matching denylist.-- `ui` -- optional sparse per-field hints (`{ label?, widget?, secret? }`) for fields whose label/widget can't be inferred from the schema. Anything not listed is inferred.--### Schema-Driven Forms--The frontend renders the create/edit account forms entirely from backend metadata -- there are **no per-type frontend components**. `buildPamAccountTypeMetadata(webAccessSupportedTypes)` walks each config's Zod schemas and emits `PamFieldDescriptor`s (`{ key, label, widget, required, secret, options?, defaultValue?, showWhen? }`). The `GET /pam/accounts/types` endpoint serves these as `PamAccountTypeMetadata` (`{ type, name, icon, supportsWebAccess, connectionFields, credentialFields }`). `supportsWebAccess` is derived from the `SESSION_HANDLERS` keys (passed in by the route) -- the single source of truth for browser-session support -- so the frontend gates Browser vs CLI launch without a separate list to maintain.--How descriptors are derived:-- **Label** -- `ui[key].label`, else humanized from the field key.-- **Widget** -- `ui[key].widget`, else inferred from the Zod base type (`ZodNumber` -> `number`, `ZodBoolean` -> `boolean`, `ZodEnum` -> `select` with `options`, else `text`). `password`/`textarea` must be set via `ui` since they're not inferable.-- **Required** -- a field is optional if its schema is `ZodOptional`/`ZodDefault`/nullable (the builder peels these via `unwrapField`).-- **Secret** -- `ui[key].secret`, else `true` when the widget is `password`. Secret fields use the write-only `PamPasswordInput` (sentinel-based, see below).-- **Discriminated unions** (e.g. SSH `authMethod`) -- the discriminator becomes a `select`; each variant's non-shared fields get a `showWhen: { field, equals }` so the renderer reveals them conditionally.--### Key Helpers--- **`extractGatewayTarget(accountType, rawConnectionDetails)`** -- validated extraction of `{ host, port }` from decrypted connection details, dispatched by account type. Used to set the cert routing extension (`getPAMConnectionDetails`) and the session's `selectedHost`. Use this instead of raw type casts.-- **`buildSessionGatewayConnectionDetails(accountType, rawConnectionDetails, selectedHost?)`** -- reshapes decrypted connection details into the blob the gateway reads for a live session (returned from `getSessionCredentials`). Most types pass through their validated connection details unchanged. Windows AD is the exception: it is brokered through the **Windows** RDP gateway protocol (`gatewayAccountType: Windows`), so it must be reduced to the Windows shape `{ host, port }` -- `host` is the `selectedHost` (the chosen entry from the account's `hosts` list) and `port` is `rdpPort`. The AD-only fields (FQDN/`domain`, `dcAddress`, the LDAP `port`, ldap settings) are intentionally **not** forwarded: they are not part of the RDP leg, and a stray `domain` alongside a `DOMAIN\username` credential makes the gateway's NLA credential resolution ambiguous and fails the session. Domain login is carried by the `DOMAIN\username` credential format (mirrors how `main`'s domain accounts brokered RDP through the Windows resource's `{ host, port }`). When adding a type that reuses another type's gateway protocol, reshape it here.-- **`getSelectableHosts(accountType, rawConnectionDetails)`** / **`resolveSelectedHost(accountType, rawConnectionDetails, requestedHost?)`** -- host-selection support for account types that hold a host list (Windows AD). `getSelectableHosts` returns the candidate hosts (or `null` for single-host types); `resolveSelectedHost` validates a launcher-requested host against that allow-list and returns the host to connect to (falling back to the first). The web-access ticket (`issueWebSocketTicket`) resolves the host **at issuance** and bakes it into the signed ticket payload, so the WS connection can't target an arbitrary host. The frontend `RdpLauncher` prompts for the host when there's more than one.-- **`sanitizeCredentials(accountType, decrypted)`** -- strips secret fields from decrypted credentials using the type's `sanitizedCredentials` allowlist; used by `getById` before returning credentials to the client.-- **`buildPamAccountTypeMetadata()`** -- builds the field descriptors served by `GET /pam/accounts/types`.-- **`PamAccessMethod`** enum (`Web`, `Cli`) -- use instead of hardcoded `"web"`/`"cli"` strings.--### Adding a New Account Type--Most types need only backend changes -- the frontend auto-renders from metadata.--1. Add the enum value to `PamAccountType` in `pam/pam-enums.ts` (and the matching frontend enum in `frontend/src/hooks/api/pam/enums.ts` -- the one shared string both sides need).-2. Add a config entry to `ACCOUNT_TYPE_CONFIGS` in `pam-account/pam-account-schemas.ts`: `name`, `icon`, `connectionDetails`, `credentials`, `sanitizedCredentials`, and any `ui` hints (set `widget: "password"`/`"textarea"` and `secret: true` where the schema can't express it).-3. Drop the icon image into `frontend/public/images/integrations/` matching the `icon` filename in the config. No component edit -- `AccountPlatformIcon` and the type pickers resolve the name/icon from `GET /pam/accounts/types`.-4. Add a case to `extractGatewayTarget` in `pam-account-schemas.ts`.-5. If it supports web access: add a session handler in `pam-web-access/` (export the handler function) and add an entry for it to the `SESSION_HANDLERS` map in `pam-session-handlers.ts`. If the entry reuses another type's `gatewayAccountType` (e.g. Windows AD → `Windows` for RDP), add a case to `buildSessionGatewayConnectionDetails` so the session credentials blob matches the shape that gateway protocol expects.--No changes to the account form components, router schemas, or field renderers are needed. The per-type route bodies use `config.connectionDetails`/`config.credentials` directly, the detail response (`SanitizedAccountDetailSchema`) is a discriminated union auto-derived from `ACCOUNT_TYPE_CONFIGS` (each variant pulls `connectionDetails` and `sanitizedCredentials` from the config), and the frontend forms render from `GET /pam/accounts/types`.--### Cloud account types--There are two brokering models for cloud types.--**Gateway-less (`AwsIam`)**: sets `requiresGateway: false` and branches early in `pam-session-service.access()` (before the gateway path) to mint short-lived STS credentials and return them in the session `metadata` map. The temporary credentials reach the client, but the root credentials never leave the backend. `extractGatewayTarget` `throw`s for it. Supports a browser flow (STS federation console URL) and is added to the web-access set explicitly in `pam-account-router.ts` (alongside `SESSION_HANDLERS` keys) so `supportsWebAccess` is true, with a dedicated frontend `AwsIamAccessContent` page. CLI side: `packages/pam/local/aws-iam-access.go` writes an isolated credentials profile.+Each type's full config (connection/credential schemas, icon, label, sanitized-credential allowlist) lives+in one `ACCOUNT_TYPE_CONFIGS` entry in `pam-account/pam-account-schemas.ts`. Forms are **schema-driven**:+the frontend renders create/edit forms from `GET /pam/accounts/types` metadata, so there are **no per-type+frontend components**. Adding a type is mostly a config entry + an icon; the gateway extension points are+`extractGatewayTarget` and `buildSessionGatewayConnectionDetails` in the same file.-**Gateway-injection (`GcpServiceAccount`, `AzureCli`)**: the preferred model. It is a normal gateway type (`requiresGateway` defaults to true) and reuses the full gateway path in `access()`. The gateway MITMs the cloud REST endpoint and injects a backend-minted **short-lived token** into every request, so **no credential of any kind reaches the client** and every request is captured to the session log. Conventions:++Cloud types use one of two brokering models instead of a plain gateway TCP proxy: **gateway-less** (`AwsIam`,++`requiresGateway: false`) mints short-lived STS credentials in `access()` and returns them in session++metadata; **gateway-injection** (`GcpServiceAccount`, `AzureCli`) proxies the cloud REST API through the++gateway and injects a backend-minted short-lived token so no credential reaches the client. See++`access()` / `getSessionCredentials` and the CLI `packages/pam/handlers/<provider>`.+-- `extractGatewayTarget` returns the cloud API host (`googleapis.com:443` for GCP, `management.azure.com:443` for Azure) so the session cert routes to it.-- The short-lived token is minted in `getSessionCredentials` (not `access()`), set as `credentials.token`, and the long-lived secret is deleted from the blob before it is returned to the gateway. GCP uses impersonation / a static-key JWT; Azure uses the client-credentials grant in `pam-session/azure/azure-federation.ts`. `HandlePAMProxy` caps `credentialExpiryTime` at ~1h for both since the tokens are short-lived.-- CLI/gateway side lives in the CLI repo. Gateway handler `packages/pam/handlers/<provider>/proxy.go` (a TLS-terminating HTTP proxy using a client-supplied ephemeral CA) overwrites the `Authorization` header with `credentials.Token` and logs each request/response via `SessionLogger.LogHttpEvent`. Client handler `packages/pam/local/<provider>-proxy.go` runs the local proxy tunnel and points the vendor CLI at it. `gcloud` is configured via `gcloud config` + a static-token-file placeholder; `az` (which has no static-token knob) is instead wired via `HTTPS_PROXY` + `REQUESTS_CA_BUNDLE` + an isolated `AZURE_CONFIG_DIR`, and the gateway additionally intercepts the Entra ID token endpoint to hand `az` a placeholder token so it believes login succeeded. Register the type in `pam-proxy.go` (`GetSupportedResourceTypes`, the `HandlePAMProxy` switch) and `session/uploader.go` (resource-type constant, filename regex, HTTP-events upload branch).-- Neither GCP nor Azure has a browser flow, so both stay out of the web-access set (`supportsWebAccess` false → `LaunchSessionSheet` shows the `infisical pam access` command). Neither has a `PamAccountAccessPage` entry (the browser web-access route is never linked for them); the launch sheet is the only surface.+## Policies & Settings-## Policies+**Policies** are governance controls on a template (MFA, reason, session duration, command-blocking),+registry-driven in `pam/pam-policies.ts` and stored in the template's `policies` jsonb. Server-enforced+policies apply before the session starts; gateway-enforced ones flow to the gateway via `policyRules`.+**Settings** (recording, password constraints, log masking) are a separate concept — they live in the+template's `settings` column, not `policies`. Both are edited on the template detail sheet's "General" tab.-Policies are the governance controls applied to a template (require MFA, require reason, max session duration). They are registry-driven, defined once in `PAM_POLICY_DEFINITIONS` in `pam/pam-policies.ts`, keyed by `PamPolicyType`. Each entry is `{ label, description, appliesTo, schema }` where `appliesTo` is an account-type list or `"all"`, and `schema` is the Zod schema for that policy's value (a primitive or object).--"Access policy" is the category, not a type: MFA, reason, and duration are individual peer policies that each `appliesTo: "all"`. `appliesTo` can also be a list to scope a policy to specific account types. This is distinct from **settings** (recording, password constraints), which are NOT policies, they live in the template's separate `settings` column with their own schema and bespoke UI.--In the template detail sheet (`frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx`), the **"General"** tab is for policies and system settings (gateway, session recording / storage backend, and similar template-level defaults); the **"Configuration"** tab is only for generic template metadata like name and description. When adding a new policy or setting, it belongs on the General tab, not Configuration.--Storage: a template's `policies` jsonb column is a flat map keyed by `PamPolicyType`, e.g. `{ "require-mfa": true, "max-session-duration": 3600 }`. No DB defaults and no per-policy migration: absence resolves to the policy's natural default in the resolver (a missing boolean is `false`, a missing duration falls back to `DEFAULT_SESSION_DURATION_MS`).--A registry entry flows automatically to:-- **`GET /pam/accounts/types`** (`applicablePolicies`), so the frontend renders the right editors per account type with no per-type wiring.-- **`validatePolicyValues`**, used by template create/update to reject policies that don't apply to the type or fail their schema (returns a result object; the caller maps `ok: false` to a `BadRequestError`).--Policies are either server-enforced or gateway-enforced:-- **Server-enforced** (MFA, reason, duration): `resolveAccessControls` reads the values and they're applied in `pam-session`/`pam-web-access` before the session starts.-- **Gateway-enforced** (command blocking): the value is read via `resolvePolicy` in `getSessionCredentials` and included in the `policyRules` response. The gateway compiles the patterns and enforces them during the session.--Command blocking (`PamPolicyType.CommandBlocking`) is the first gateway-enforced policy. It applies only to SSH (`appliesTo: [PamAccountType.SSH]`). Stored as a newline-separated string of regex patterns, split into an array at the credentials endpoint before sending to the gateway.--Session log masking (`sessionLogMaskingPatterns`) is a **setting**, not a policy. It lives in `PamTemplateSettingsSchema` and is read from `account.templateSettings` in `getSessionCredentials`. It also flows to the gateway via the `policyRules` response alongside command blocking patterns.--### Adding a New Policy--1. Add the value to `PamPolicyType` and an entry to `PAM_POLICY_DEFINITIONS` in `pam/pam-policies.ts` (`label`, `description`, `appliesTo`, `schema`). Mirror the enum value in `frontend/src/hooks/api/pam/enums.ts`.-2. Register the policy in `POLICY_EDITORS` (`frontend/src/pages/pam/components/policyEditors/`), keyed by the new `PamPolicyType`. Reuse an existing editor when the value shape matches (`BooleanPolicyEditor` for a `z.boolean()`, `DurationPolicyEditor` for a number); only write a new editor component for a novel value shape. Each editor receives `{ label, description, value, onChange }` and owns its own layout, booleans render inline, others vertical.-3. Enforcement: read it where it's enforced. A server-enforced policy extends `resolveAccessControls` and is applied in `pam-session`/`pam-web-access`. A gateway-enforced policy is read via `resolvePolicy` in `getSessionCredentials`, split/transformed as needed, and included in the `policyRules` response (see command blocking for the pattern). Both the service return and the router response schema must be updated atomically -- Fastify's Zod serializer strips unknown keys.--No migration, no router or response-schema change (beyond `policyRules` for gateway-enforced policies), and no DB default.--## Approval Chat Notifications (Slack)--Gated by the `pamSlackNotifications` license plan flag (off by default, enabled per org from the license server): saves of `notificationConfigs` are rejected and sends are skipped when the plan lacks it, and the frontend hides the Notifications card via `subscription.pamSlackNotifications`.--Folder-level, not project-level: each folder's Approvals tab can attach org `workflow_integrations` (Slack only for now) with channels and subscribed events, stored in `pam_folder_notification_configs` (`channels` and `events` are jsonb; channel objects are `{ id, name }` so the UI renders names without needing the org-gated Slack channel-list API). This intentionally does NOT use `project_slack_configs` or `triggerWorkflowIntegrationNotification`, which resolve config by projectId (the single PAM project would make the config org-wide).+## Discovery-Flow: `createRequest` and `reviewRequest` in `pam-access-request-service.ts` call `triggerFolderSlackNotifications`, which filters configs via the pure `getSlackSendTargets` (`pam-access-request-fns.ts`) and sends through the shared `sendSlackNotification` (`services/slack/slack-fns.ts`). Events are `PamNotificationEvent` in `pam/pam-enums.ts` (mirrored in the frontend enums file). New `TriggerFeature.PAM_*` variants carry the payloads; their Slack templates live in `buildSlackPayload`. All sends are fire-and-forget (never fail the request flow). Config writes ride the existing PUT approval-configuration endpoint (undefined `notificationConfigs` leaves configs unchanged; empty array deletes all). Additional chat platforms can be added later by branching on `integration` in the trigger helper, the table needs no change.+`pam-discovery/`: a **source** (a credential account + gateway) scans and stages **discovered accounts**+for import into a folder. Type registry is `DISCOVERY_TYPE_CONFIGS`; providers return+`{ validateConnection, scan }` and never touch the DB — the service owns encryption, staging, and+fingerprint dedupe. Discovery runs everything **through the gateway** (SSH-exec / port-sweep / WinRM RPCs),+so `ssh2` is never used on the backend and scans produce no session rows, recordings, or session audits.+Current types: Active Directory and Unix.## Credential Rotation