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
feat(pam): unix discovery
x9172a8fdeee9
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.tsindex 50ff0cb749..b43f33e9a6 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts@@ -721,7 +721,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {config: { rateLimit: readLimit },onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- return server.services.pamAccount.getSshCaPublicKey({+ const result = await server.services.pamAccount.getOrCreateSshCa({accountId: req.params.accountId,projectId: req.internalPamProjectId,actorId: req.permission.id,@@ -729,6 +729,23 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {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 };}});@@ -747,7 +764,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {config: { rateLimit: readLimit },onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req, reply) => {- const { publicKey: caPublicKey } = await server.services.pamAccount.getSshCaPublicKey({+ const result = await server.services.pamAccount.getOrCreateSshCa({accountId: req.params.accountId,projectId: req.internalPamProjectId,actorId: req.permission.id,@@ -755,6 +772,22 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {actorOrgId: req.permission.orgId,actorAuthMethod: req.permission.authMethod});+ const caPublicKey = result.publicKey;++ 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!+ }+ }+ });+ }const setupScript = `#!/bin/bashset -ediff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.tsindex 239c550702..6dabcacb4d 100644--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts@@ -7,7 +7,7 @@ import { z } from "zod";import { BadRequestError } from "@app/lib/errors";-import { GcpServiceAccountAuthMethod, PamAccountType } from "../pam/pam-enums";+import { GcpServiceAccountAuthMethod, PamAccountType, PamSshAuthMethod } from "../pam/pam-enums";import { getApplicablePolicies, PamPolicyDescriptorSchema } from "../pam/pam-policies";import {PamAccountSettingsOverridesSchema,@@ -319,12 +319,12 @@ export const ACCOUNT_TYPE_CONFIGS = {}),credentials: z.discriminatedUnion("authMethod", [z.object({- authMethod: z.literal("password"),+ authMethod: z.literal(PamSshAuthMethod.Password),username: z.string().trim().min(1),password: optionalTrimmedString}),z.object({- authMethod: z.literal("public-key"),+ authMethod: z.literal(PamSshAuthMethod.PublicKey),username: z.string().trim().min(1),privateKey: z.string()@@ -333,7 +333,7 @@ export const ACCOUNT_TYPE_CONFIGS = {.transform((v) => v || undefined).optional()}),- z.object({ authMethod: z.literal("certificate"), username: z.string().trim().min(1) })+ z.object({ authMethod: z.literal(PamSshAuthMethod.Certificate), username: z.string().trim().min(1) })]),sanitizedCredentials: z.object({authMethod: z.string(),diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex a5f2d995cb..afbee06b0b 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -764,25 +764,6 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>return { publicKey, created: true, keyAlgorithm };};- const getSshCaPublicKey = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {- const account = await pamAccountDAL.findByIdWithDetails(accountId);- if (!account || account.projectId !== projectId) {- throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });- }-- await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.EditAccounts, ctx);-- const metadata = parseInternalMetadata(- account.accountType as PamAccountType,- await decryptInternalMetadata(projectId, account.encryptedInternalMetadata)- );-- if (!metadata?.caPublicKey) {- throw new BadRequestError({ message: "SSH CA has not been configured for this account" });- }- return { publicKey: metadata.caPublicKey };- };-const getAccountPermissions = async ({ accountId, projectId, ...ctx }: TGetPamAccountDTO & TActorContext) => {const account = await pamAccountDAL.findById(accountId);if (!account || account.projectId !== projectId) {@@ -853,7 +834,6 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>update,deleteAccount,getOrCreateSshCa,- getSshCaPublicKey,getAccountPermissions};};diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.tsindex 6738e8a738..e2f2593977 100644--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts@@ -2,17 +2,16 @@ import net from "node:net";import ldapjs from "@infisical/ldapjs";import slugify from "@sindresorhus/slugify";+import RE2 from "re2";import { runPowershell } from "winrm-client";import { BadRequestError } from "@app/lib/errors";-import { GatewayProxyProtocol } from "@app/lib/gateway";-import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";-import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { PamAccountType } from "../../pam/pam-enums";import { isDomainQualifiedUsername, toNetbiosUsername } from "../../pam-account/pam-account-schemas";+import { executeWithGateway } from "../pam-discovery-fns";import {TDiscoveredAccount,TDiscoveryMachineError,@@ -23,6 +22,7 @@ import { resolveDnsTcp } from "./dns-over-dc";const LDAP_TIMEOUT = 30 * 1000;const LDAP_PAGE_SIZE = 500;+const TRAILING_HYPHENS_REGEX = new RE2(/-+$/);type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;type TLdapAttribute = { type: string; values: string[]; buffers: Buffer[] };@@ -93,30 +93,6 @@ type TAdConnection = {type TWinrmConfig = { port: number; useHttps: boolean; rejectUnauthorized: boolean; caCert?: string };-// Opens a gateway TCP proxy to targetHost:targetPort and runs the operation against the local proxy port-const executeWithGateway = async <T>(- targetHost: string,- targetPort: number,- gatewayId: string,- gatewayV2Service: TGatewayDep,- operation: (proxyPort: number) => Promise<T>-): Promise<T> => {- const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });- const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId,- targetHost: host,- targetPort- });- if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });-- return withGatewayV2Proxy((proxyPort) => operation(proxyPort), {- protocol: GatewayProxyProtocol.Tcp,- relayHost: platform.relayHost,- gateway: platform.gateway,- relay: platform.relay- });-};-const runLdap = <T>(conn: TAdConnection,credentials: { username: string; password?: string },@@ -226,9 +202,10 @@ const enumerateLocalUsers = (export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({gatewayId,configuration,- credentialAccount,+ credentialAccounts,gatewayV2Service}) => {+ const [credentialAccount] = credentialAccounts;const connectionDetails = credentialAccount.connectionDetails as unknown as {domain: string;dcAddress: string;@@ -307,7 +284,9 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({const domainShortName = domain.split(".")[0];const discovered: TDiscoveredAccount[] = users.map((u) => ({accountType: PamAccountType.WindowsAd,- name: slugify(`${domainShortName} ${u.sAMAccountName}`, { lowercase: true }).slice(0, 64).replace(/-+$/, ""),+ name: slugify(`${domainShortName} ${u.sAMAccountName}`, { lowercase: true })+ .slice(0, 64)+ .replace(TRAILING_HYPHENS_REGEX, ""),fingerprint: `${domain}:${u.objectGUID}`,details: { connectionDetails, credentials: { username: u.sAMAccountName } }}));@@ -339,7 +318,9 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({for (const u of localUsers.filter((lu) => lu.Name)) {discovered.push({accountType: PamAccountType.Windows,- name: slugify(`${hostLabel} ${u.Name}`, { lowercase: true }).slice(0, 64).replace(/-+$/, ""),+ name: slugify(`${hostLabel} ${u.Name}`, { lowercase: true })+ .slice(0, 64)+ .replace(TRAILING_HYPHENS_REGEX, ""),fingerprint: `${domain}:${computer.objectGUID}:${u.Name.toLowerCase()}`,details: {connectionDetails: { host, port: connectionDetails.rdpPort },diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts b/backend/src/ee/services/pam-discovery/pam-discovery-enums.tsindex db33156173..cec493e4c6 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts@@ -1,5 +1,6 @@export enum PamDiscoveryType {- ActiveDirectory = "active-directory"+ ActiveDirectory = "active-directory",+ Unix = "unix"}export enum PamDiscoverySchedule {diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts b/backend/src/ee/services/pam-discovery/pam-discovery-factory.tsindex 5b361623dd..44d2fcac65 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts@@ -1,7 +1,9 @@import { activeDirectoryDiscoveryFactory } from "./active-directory/active-directory-discovery-factory";import { PamDiscoveryType } from "./pam-discovery-enums";import { TPamDiscoveryFactory } from "./pam-discovery-types";+import { unixDiscoveryFactory } from "./unix/unix-discovery-factory";export const PAM_DISCOVERY_FACTORY_MAP: Record<PamDiscoveryType, TPamDiscoveryFactory> = {- [PamDiscoveryType.ActiveDirectory]: activeDirectoryDiscoveryFactory+ [PamDiscoveryType.ActiveDirectory]: activeDirectoryDiscoveryFactory,+ [PamDiscoveryType.Unix]: unixDiscoveryFactory};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.tsnew file mode 100644index 0000000000..7791fdece2--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts@@ -0,0 +1,127 @@+import net from "node:net";++import { BadRequestError } from "@app/lib/errors";+import { GatewayProxyProtocol } from "@app/lib/gateway";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { callSshExec, SshExecCredentials } from "@app/lib/gateway-v2/ssh-rpc";++import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";++type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;++const SWEEP_RESPONSE_TIMEOUT_MS = 10 * 60 * 1000;++// runs a command on the target via the gateway's ssh-exec handler; the gateway performs the ssh login (any auth+// method, including certificates), so the backend never needs an ssh client of its own+export const sshExecWithGateway = async (+ targetHost: string,+ targetPort: number,+ gatewayId: string,+ gatewayV2Service: TGatewayDep,+ command: string,+ credentials: SshExecCredentials,+ timeoutMs: number+): Promise<string> => {+ const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });+ const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: host,+ targetPort+ });+ if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });++ return withGatewayV2Proxy(+ async (proxyPort) => {+ const response = await callSshExec({ port: proxyPort, command, credentials, timeoutMs });+ if (!response.ok) throw new Error(response.errorMessage);+ return response.result.stdout;+ },+ {+ protocol: GatewayProxyProtocol.SshExec,+ relayHost: platform.relayHost,+ gateway: platform.gateway,+ relay: platform.relay+ }+ );+};++// opens a gateway TCP proxy to targetHost:targetPort and runs the operation against the local proxy port+export const executeWithGateway = async <T>(+ targetHost: string,+ targetPort: number,+ gatewayId: string,+ gatewayV2Service: TGatewayDep,+ operation: (proxyPort: number) => Promise<T>+): Promise<T> => {+ const [host] = await verifyHostInputValidity({ host: targetHost, isGateway: true, isDynamicSecret: false });+ const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: host,+ targetPort+ });+ if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });++ return withGatewayV2Proxy((proxyPort) => operation(proxyPort), {+ protocol: GatewayProxyProtocol.Tcp,+ relayHost: platform.relayHost,+ gateway: platform.gateway,+ relay: platform.relay+ });+};++// one gateway round-trip that TCP-probes every target and returns the reachable "host:port" set,+// so a scan can filter a whole CIDR to live hosts+export const sweepReachableTargets = async (+ targets: { host: string; port: number }[],+ gatewayId: string,+ gatewayV2Service: TGatewayDep,+ dialTimeoutMs: number+): Promise<Set<string>> => {+ if (!targets.length) return new Set();++ const platform = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost: targets[0].host,+ targetPort: targets[0].port+ });+ if (!platform) throw new BadRequestError({ message: "Unable to connect to gateway" });++ const request = `${JSON.stringify({ targets: targets.map((t) => `${t.host}:${t.port}`), timeoutMs: dialTimeoutMs })}\n`;++ return withGatewayV2Proxy(+ (proxyPort) =>+ new Promise<Set<string>>((resolve, reject) => {+ const socket = net.connect({ host: "localhost", port: proxyPort });+ let buffer = "";+ const timer = setTimeout(() => {+ socket.destroy();+ reject(new Error("Port sweep timed out"));+ }, SWEEP_RESPONSE_TIMEOUT_MS);+ const finish = (err: Error | null) => {+ clearTimeout(timer);+ socket.destroy();+ if (err) return reject(err);+ try {+ const parsed = JSON.parse(buffer) as { open?: string[] };+ return resolve(new Set(parsed.open ?? []));+ } catch {+ return reject(new Error("Invalid port sweep response"));+ }+ };+ socket.on("connect", () => socket.write(request));+ socket.on("data", (chunk) => {+ buffer += chunk.toString("utf-8");+ });+ socket.on("end", () => finish(null));+ socket.on("error", (err) => finish(err));+ }),+ {+ protocol: GatewayProxyProtocol.PortSweep,+ relayHost: platform.relayHost,+ gateway: platform.gateway,+ relay: platform.relay,+ longLived: true+ }+ );+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.tsindex 658c017caa..2b7d57fc2b 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { PamAccountType } from "../pam/pam-enums";import { ActiveDirectoryDiscoveryConfigSchema } from "./active-directory/active-directory-discovery-schemas";import { PamDiscoveryType } from "./pam-discovery-enums";+import { UnixDiscoveryConfigSchema } from "./unix/unix-discovery-schemas";export const DISCOVERY_TYPE_CONFIGS = {[PamDiscoveryType.ActiveDirectory]: {@@ -10,6 +11,12 @@ export const DISCOVERY_TYPE_CONFIGS = {icon: "ActiveDirectory.png",credentialAccountType: PamAccountType.WindowsAd,configuration: ActiveDirectoryDiscoveryConfigSchema+ },+ [PamDiscoveryType.Unix]: {+ name: "Unix",+ icon: "SSH.png",+ credentialAccountType: PamAccountType.SSH,+ configuration: UnixDiscoveryConfigSchema}} as const satisfies Partial<Record<diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.tsindex 910bd200ab..fc146924cb 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts@@ -4,6 +4,9 @@ import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dalimport { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";+import { createSshCert, createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";+import { SshCertType } from "@app/ee/services/ssh/ssh-certificate-authority-types";+import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { DatabaseErrorCode } from "@app/lib/error-codes";@@ -14,7 +17,7 @@ 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 { PamAccountType, PamProductRole } from "../pam/pam-enums";+import { PamAccountType, PamProductRole, PamSshAuthMethod } from "../pam/pam-enums";import { checkAccountAccess, TActorContext, verifyProductMembership } from "../pam/pam-permission";import { validateGatewayAttachment } from "../pam/pam-validators";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";@@ -101,6 +104,54 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicconst decryptToObject = (blob: Buffer, decryptor: (i: { cipherTextBlob: Buffer }) => Buffer) =>JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;+ const SSH_CERT_TTL = "10m";++ // certificate accounts can't be presented by an ssh client, so sign an ephemeral user cert the gateway will present;+ // password/private-key accounts pass through unchanged+ const buildGatewaySshCredentials = async (+ account: {+ accountType: string;+ encryptedCredentials: Buffer;+ encryptedInternalMetadata?: Buffer | null;+ id: string;+ },+ decryptor: (i: { cipherTextBlob: Buffer }) => Buffer+ ): Promise<Record<string, unknown>> => {+ const credentials = decryptToObject(account.encryptedCredentials, decryptor) as {+ authMethod: string;+ username: string;+ privateKey?: string;+ certificate?: string;+ };++ if (+ account.accountType === PamAccountType.SSH &&+ credentials.authMethod === PamSshAuthMethod.Certificate &&+ account.encryptedInternalMetadata+ ) {+ const metadata = decryptToObject(account.encryptedInternalMetadata, decryptor) as {+ caPrivateKey?: string;+ caKeyAlgorithm?: string;+ };+ if (metadata.caPrivateKey) {+ const keyAlgorithm = (metadata.caKeyAlgorithm as SshCertKeyAlgorithm) || SshCertKeyAlgorithm.ED25519;+ const { publicKey, privateKey } = await createSshKeyPair(keyAlgorithm);+ const { signedPublicKey } = await createSshCert({+ caPrivateKey: metadata.caPrivateKey,+ clientPublicKey: publicKey,+ keyId: `pam-discovery-${account.id}`,+ principals: [credentials.username],+ requestedTtl: SSH_CERT_TTL,+ certType: SshCertType.USER+ });+ credentials.privateKey = privateKey;+ credentials.certificate = signedPublicKey;+ }+ }++ return credentials as Record<string, unknown>;+ };+const verifyAdmin = async (projectId: string, ctx: TActorContext) => {const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);if (!hasRole(PamProductRole.Admin)) {@@ -108,6 +159,14 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic}};+ // unix sources scan with several ssh accounts, stored in the per-type configuration; other types use the single column+ const getCredentialAccountIds = (credentialAccountId: string, configuration: Record<string, unknown>) => {+ const configIds = Array.isArray(configuration.credentialAccountIds)+ ? (configuration.credentialAccountIds as string[])+ : [];+ return Array.from(new Set([credentialAccountId, ...configIds]));+ };+const resolveCredentialAccount = async (projectId: string,discoveryType: PamDiscoveryType,@@ -212,9 +271,13 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicthrow new BadRequestError({ message: "A gateway or gateway pool is required" });}await validateGatewayAttachment(deps, gatewayId, gatewayPoolId, ctx);- await resolveCredentialAccount(projectId, discoveryType, credentialAccountId, ctx);const discoveryConfiguration = validateDiscoveryConfiguration(discoveryType, configuration);+ await Promise.all(+ getCredentialAccountIds(credentialAccountId, discoveryConfiguration).map((id) =>+ resolveCredentialAccount(projectId, discoveryType, id, ctx)+ )+ );try {return await pamDiscoverySourceDAL.create({@@ -253,8 +316,17 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicif (gatewayId !== undefined || gatewayPoolId !== undefined) {await validateGatewayAttachment(deps, gatewayId, gatewayPoolId, ctx);}- if (credentialAccountId) {- await resolveCredentialAccount(projectId, discoveryType, credentialAccountId, ctx);++ const discoveryConfiguration =+ configuration !== undefined+ ? validateDiscoveryConfiguration(discoveryType, configuration)+ : ((source.discoveryConfiguration as Record<string, unknown>) ?? {});+ if (credentialAccountId !== undefined || configuration !== undefined) {+ await Promise.all(+ getCredentialAccountIds(credentialAccountId ?? source.credentialAccountId, discoveryConfiguration).map((id) =>+ resolveCredentialAccount(projectId, discoveryType, id, ctx)+ )+ );}const updateData: Record<string, unknown> = {};@@ -263,8 +335,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServicif (gatewayId !== undefined) updateData.gatewayId = gatewayId;if (gatewayPoolId !== undefined) updateData.gatewayPoolId = gatewayPoolId;if (schedule !== undefined) updateData.schedule = schedule;- if (configuration !== undefined)- updateData.discoveryConfiguration = validateDiscoveryConfiguration(discoveryType, configuration);+ if (configuration !== undefined) updateData.discoveryConfiguration = discoveryConfiguration;try {return await pamDiscoverySourceDAL.updateById(sourceId, updateData);@@ -294,8 +365,24 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic});try {- const credentialAccount = await pamAccountDAL.findByIdWithDetails(source.credentialAccountId);- if (!credentialAccount) throw new BadRequestError({ message: "Credential account no longer exists" });+ const configuration = (source.discoveryConfiguration as Record<string, unknown>) ?? {};+ const { encryptor, decryptor } = await getProjectCipher(source.projectId);++ const resolvedAccounts = await Promise.all(+ getCredentialAccountIds(source.credentialAccountId, configuration).map((id) =>+ pamAccountDAL.findByIdWithDetails(id)+ )+ );+ const credentialAccounts = await Promise.all(+ resolvedAccounts+ .filter((account): account is NonNullable<typeof account> => Boolean(account))+ .map(async (account) => ({+ accountType: account.accountType as PamAccountType,+ connectionDetails: decryptToObject(account.encryptedConnectionDetails, decryptor),+ credentials: await buildGatewaySshCredentials(account, decryptor)+ }))+ );+ if (!credentialAccounts.length) throw new BadRequestError({ message: "No credential accounts available" });const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({gatewayId: source.gatewayId,@@ -303,16 +390,11 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic});if (!gatewayId) throw new BadRequestError({ message: "No healthy gateway available for this source" });- const { encryptor, decryptor } = await getProjectCipher(source.projectId);const provider = PAM_DISCOVERY_FACTORY_MAP[source.discoveryType as PamDiscoveryType]({projectId: source.projectId,gatewayId,- configuration: (source.discoveryConfiguration as Record<string, unknown>) ?? {},- credentialAccount: {- accountType: credentialAccount.accountType as PamAccountType,- connectionDetails: decryptToObject(credentialAccount.encryptedConnectionDetails, decryptor),- credentials: decryptToObject(credentialAccount.encryptedCredentials, decryptor)- },+ configuration,+ credentialAccounts,gatewayV2Service});diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.tsindex 2befd95b13..9320a8a3e4 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts@@ -23,15 +23,17 @@ export type TPamDiscoveryProvider = {scan: () => Promise<TDiscoveryScanResult>;};+export type TDiscoveryCredentialAccount = {+ accountType: PamAccountType;+ connectionDetails: Record<string, unknown>;+ credentials: Record<string, unknown>;+};+export type TPamDiscoveryFactoryInput = {projectId: string;gatewayId: string;configuration: Record<string, unknown>;- credentialAccount: {- accountType: PamAccountType;- connectionDetails: Record<string, unknown>;- credentials: Record<string, unknown>;- };+ credentialAccounts: TDiscoveryCredentialAccount[];gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;};diff --git a/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.tsnew file mode 100644index 0000000000..bac41d323d--- /dev/null+++ b/backend/src/ee/services/pam-discovery/unix/unix-discovery-factory.ts@@ -0,0 +1,241 @@+import net from "node:net";++import slugify from "@sindresorhus/slugify";+import { Netmask } from "netmask";+import pLimit from "p-limit";+import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";+import { SshExecCredentials } from "@app/lib/gateway-v2/ssh-rpc";+import { logger } from "@app/lib/logger";++import { PamAccountType, PamSshAuthMethod } from "../../pam/pam-enums";+import { sshExecWithGateway, sweepReachableTargets } from "../pam-discovery-fns";+import {+ TDiscoveredAccount,+ TDiscoveryCredentialAccount,+ TDiscoveryMachineError,+ TDiscoveryScanResult,+ TPamDiscoveryFactory+} from "../pam-discovery-types";++const SSH_EXEC_TIMEOUT_MS = 20 * 1000;+const SCAN_CONCURRENCY = 64;+const SWEEP_DIAL_TIMEOUT_MS = 3 * 1000;+const MAX_TARGET_HOSTS = 65536;+const PASSWD_MARKER = "__INFISICAL_PASSWD__";+const DEFAULT_UID_MIN = 1000;+const DEFAULT_UID_MAX = 60000;++// one round-trip that returns the login.defs uid bounds followed by the passwd database+const ENUMERATION_COMMAND = `grep -E '^UID_(MIN|MAX)' /etc/login.defs 2>/dev/null; echo '${PASSWD_MARKER}'; getent passwd 2>/dev/null || cat /etc/passwd 2>/dev/null`;++const NOLOGIN_SHELL_REGEX = new RE2(/(nologin|\/false|\/true|\/sync|\/shutdown|\/halt)$/);+const UID_MIN_REGEX = new RE2(/^UID_MIN\s+(\d+)/m);+const UID_MAX_REGEX = new RE2(/^UID_MAX\s+(\d+)/m);+const TRAILING_HYPHENS_REGEX = new RE2(/-+$/);++const SYSTEM_ACCOUNT_NAMES = new Set([+ "daemon",+ "bin",+ "sys",+ "adm",+ "lp",+ "sync",+ "shutdown",+ "halt",+ "mail",+ "news",+ "uucp",+ "operator",+ "games",+ "gopher",+ "ftp",+ "nobody",+ "dbus",+ "sshd",+ "www-data",+ "backup",+ "list",+ "irc",+ "gnats",+ "proxy",+ "man"+]);++type TUnixAccount = { host: string; port: number; credentials: SshExecCredentials };++const toUnixAccount = (account: TDiscoveryCredentialAccount): TUnixAccount => {+ const connectionDetails = account.connectionDetails as { host: string; port: number };+ return {+ host: connectionDetails.host,+ port: connectionDetails.port,+ credentials: account.credentials as unknown as SshExecCredentials+ };+};++// the gateway performs the ssh login, so an account is usable as long as it carries the secret its auth method needs+const isUsableAccount = (account: TUnixAccount) => {+ const { authMethod, password, privateKey, certificate } = account.credentials;+ if (authMethod === PamSshAuthMethod.Password) return Boolean(password);+ if (authMethod === PamSshAuthMethod.PublicKey) return Boolean(privateKey);+ if (authMethod === PamSshAuthMethod.Certificate) return Boolean(privateKey && certificate);+ return false;+};++const expandTargets = (cidrRanges: string[]): string[] => {+ const hosts = new Set<string>();+ for (const range of cidrRanges) {+ const trimmed = range.trim();+ if (trimmed) {+ if (trimmed.includes("/")) {+ if (!net.isIPv4(trimmed.split("/")[0])) {+ throw new BadRequestError({ message: `Only IPv4 CIDR ranges are supported: ${trimmed}` });+ }+ const block = new Netmask(trimmed);+ if (hosts.size + block.size > MAX_TARGET_HOSTS) {+ throw new BadRequestError({ message: `Targets expand to more than ${MAX_TARGET_HOSTS} hosts` });+ }+ block.forEach((ip) => hosts.add(ip));+ } else {+ hosts.add(trimmed);+ if (hosts.size > MAX_TARGET_HOSTS) {+ throw new BadRequestError({ message: `Targets expand to more than ${MAX_TARGET_HOSTS} hosts` });+ }+ }+ }+ }+ return [...hosts];+};++const isLoginAccount = (name: string, uidStr: string, shell: string, uidMin: number, uidMax: number) => {+ const uid = Number(uidStr);+ if (Number.isNaN(uid) || uid < uidMin || uid > uidMax) return false;+ if (name.startsWith("_") || SYSTEM_ACCOUNT_NAMES.has(name)) return false;+ if (shell && NOLOGIN_SHELL_REGEX.test(shell)) return false;+ return true;+};++const parseUnixUsernames = (output: string, includeSystemAccounts: boolean): string[] => {+ const [defsPart = "", passwdPart = ""] = output.split(PASSWD_MARKER);++ const uidMin = Number(defsPart.match(UID_MIN_REGEX)?.[1]) || DEFAULT_UID_MIN;+ const uidMax = Number(defsPart.match(UID_MAX_REGEX)?.[1]) || DEFAULT_UID_MAX;++ const usernames = new Set<string>();+ for (const line of passwdPart.split("\n")) {+ const [name, , uidStr, , , , shell = ""] = line.trim().split(":");+ if (name) {+ if (name === "root" || includeSystemAccounts || isLoginAccount(name, uidStr, shell, uidMin, uidMax)) {+ usernames.add(name);+ }+ }+ }+ return [...usernames];+};++export const unixDiscoveryFactory: TPamDiscoveryFactory = ({+ gatewayId,+ configuration,+ credentialAccounts,+ gatewayV2Service+}) => {+ const accounts = credentialAccounts.map(toUnixAccount);+ const config = configuration as { cidrRanges: string[]; includeSystemAccounts?: boolean };++ // accounts whose stored host matches the target are tried first, then every other account+ const orderAccountsForHost = (host: string) => [+ ...accounts.filter((a) => a.host === host),+ ...accounts.filter((a) => a.host !== host)+ ];++ const enumerateHost = (host: string, account: TUnixAccount) =>+ sshExecWithGateway(+ host,+ account.port,+ gatewayId,+ gatewayV2Service,+ ENUMERATION_COMMAND,+ account.credentials,+ SSH_EXEC_TIMEOUT_MS+ );++ const scanHost = async (+ host: string,+ open: Set<string>+ ): Promise<{ accounts: TDiscoveredAccount[]; error?: TDiscoveryMachineError }> => {+ const isKnownHost = accounts.some((a) => a.host === host);+ const candidates = orderAccountsForHost(host).filter(+ (account) => isUsableAccount(account) && (isKnownHost || open.has(`${host}:${account.port}`))+ );++ let lastError = "no credential account could authenticate";+ for (const account of candidates) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const output = await enumerateHost(host, account);+ return {+ accounts: parseUnixUsernames(output, config.includeSystemAccounts ?? false).map((username) => ({+ accountType: PamAccountType.SSH,+ name: slugify(`${host} ${username}`, { lowercase: true }).slice(0, 64).replace(TRAILING_HYPHENS_REGEX, ""),+ fingerprint: `${host}:${username}`,+ details: {+ connectionDetails: { host, port: account.port },+ credentials: { authMethod: PamSshAuthMethod.Password, username }+ }+ }))+ };+ } catch (err) {+ lastError = err instanceof Error ? err.message : "SSH enumeration failed";+ }+ }++ if (candidates.length) {+ logger.warn(`PAM Unix discovery failed to scan host [host=${host}] [error=${lastError}]`);+ return { accounts: [], error: { machine: host, error: lastError } };+ }+ return { accounts: [] };+ };++ const validateConnection = async () => {+ const account = accounts.find(isUsableAccount);+ if (!account) {+ throw new BadRequestError({+ message: "No credential account has usable authentication (password, private key, or certificate)"+ });+ }+ await enumerateHost(account.host, account).catch((err) => {+ throw new BadRequestError({+ message: `Unable to connect over SSH: ${err instanceof Error ? err.message : "unknown error"}`+ });+ });+ };++ const scan = async (): Promise<TDiscoveryScanResult> => {+ if (!accounts.some(isUsableAccount)) {+ throw new BadRequestError({+ message: "No credential account has usable authentication (password, private key, or certificate)"+ });+ }++ const targets = expandTargets(config.cidrRanges);+ const usablePorts = [...new Set(accounts.filter(isUsableAccount).map((a) => a.port))];++ const sweepTargets = targets.flatMap((host) => usablePorts.map((port) => ({ host, port })));+ const open = await sweepReachableTargets(sweepTargets, gatewayId, gatewayV2Service, SWEEP_DIAL_TIMEOUT_MS);++ const hostsToScan = targets.filter(+ (host) => accounts.some((a) => a.host === host) || usablePorts.some((port) => open.has(`${host}:${port}`))+ );++ const limit = pLimit(SCAN_CONCURRENCY);+ const results = await Promise.all(hostsToScan.map((host) => limit(() => scanHost(host, open))));++ return {+ accounts: results.flatMap((r) => r.accounts),+ machineErrors: results.flatMap((r) => (r.error ? [r.error] : []))+ };+ };++ return { validateConnection, scan };+};diff --git a/backend/src/ee/services/pam-discovery/unix/unix-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/unix/unix-discovery-schemas.tsnew file mode 100644index 0000000000..ee93d7b510--- /dev/null+++ b/backend/src/ee/services/pam-discovery/unix/unix-discovery-schemas.ts@@ -0,0 +1,22 @@+import RE2 from "re2";+import { z } from "zod";++import { isValidIpOrCidr } from "@app/lib/ip";++const HOSTNAME_REGEX = new RE2(+ /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/+);++const isValidTarget = (value: string) => isValidIpOrCidr(value) || (value.length <= 253 && HOSTNAME_REGEX.test(value));++export const UnixDiscoveryConfigSchema = z.object({+ cidrRanges: z+ .array(z.string().trim().min(1))+ .min(1)+ .max(50)+ .refine((ranges) => ranges.every(isValidTarget), {+ message: "Each target must be a valid IP address, CIDR range, or hostname"+ }),+ credentialAccountIds: z.array(z.string().uuid()).min(1).max(50),+ includeSystemAccounts: z.boolean().default(false)+});diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex cdd28309f2..2ecc65f8f6 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -217,7 +217,8 @@ Searchable lists filter on **both tiers** — server for correctness/scale, clieDiscovery lives in `backend/src/ee/services/pam-discovery/`. A **source** references an existing PAM **credential account** (+ gateway) and, on scan, stages **discovered accounts** for import into a folder.- **Registry**: `DISCOVERY_TYPE_CONFIGS` (`pam-discovery-schemas.ts`) mirrors `ACCOUNT_TYPE_CONFIGS`. Adding a source type = one entry (`name`, `icon`, `credentialAccountType`, `configuration` zod schema) + a factory in `PAM_DISCOVERY_FACTORY_MAP`.-- **Provider contract** (`TPamDiscoveryFactory`): returns `{ validateConnection, scan }`. `scan()` returns `TDiscoveredAccount[]` (`accountType`, `name`, `fingerprint`, `details`); the **service** owns encryption, staging, and fingerprint dedupe. Providers never touch the DB.+- **Provider contract** (`TPamDiscoveryFactory`): returns `{ validateConnection, scan }`. `scan()` returns `TDiscoveredAccount[]` (`accountType`, `name`, `fingerprint`, `details`); the **service** owns encryption, staging, and fingerprint dedupe. Providers never touch the DB. `executeWithGateway` (`pam-discovery-fns.ts`) is the shared helper that opens a gateway TCP proxy to `targetHost:targetPort` and runs an operation against the local proxy port; both factories use it.+- **Credential accounts are a list.** The factory receives `credentialAccounts: TDiscoveryCredentialAccount[]`. Single-account types (AD) read `credentialAccounts[0]`. Unix scans with several SSH accounts, whose ids live in `configuration.credentialAccountIds`; `getCredentialAccountIds` in the service unions them with the source's primary `credentialAccountId` column, and create/update validate every id. `credentialAccountId` (the column) stays the primary for FK integrity and gateway resolution.- **Config vs credential split**: connection settings that identify the target (domain, DC, LDAP) come from the **credential account**; discovery-only settings live in the per-type `configuration` blob (e.g. `active-directory-discovery-schemas.ts`).- **A single source can stage multiple account types.** AD stages `windows-ad` (domain, via LDAP) and, when `scanLocalAccounts` is enabled, `windows` (local) accounts. Import maps each staged account to a template of the matching type.@@ -225,6 +226,14 @@ Discovery lives in `backend/src/ee/services/pam-discovery/`. A **source** refereGated by `scanLocalAccounts` in the AD config (default on, matching `main`). When on, `scan()` also: enumerates domain servers over LDAP (`(&(objectClass=computer)(operatingSystem=*Server*))`) → resolves each hostname to an IP via **DNS-over-TCP through the DC** (`dns-over-dc.ts`, port 53) so the gateway can reach it → WinRM `Get-LocalUser` per server (`winrm-client`) → stages each as a `windows` account pointed at that server's host + the AD account's `rdpPort`. A single unreachable server is logged and skipped, never aborting the scan. Domain/resource/dependency objects from `main`'s discovery were intentionally dropped in the revamp — discovery only produces accounts.+### Unix discovery++`unix/unix-discovery-factory.ts` scans Unix hosts over SSH (via `ssh2`) and stages `ssh` accounts. Config (`unix/unix-discovery-schemas.ts`): `cidrRanges` (IPs, IPv4 CIDR ranges, or hostnames — CIDRs expand, IPs/hostnames pass through and the gateway resolves hostnames in the target network), `credentialAccountIds` (the SSH accounts to scan with), `includeSystemAccounts`. Per target host it orders the credential accounts (host match first, then each account) and tries them until one authenticates, reading `/etc/passwd` via `getent passwd` in one exec that also returns the `login.defs` uid bounds. Unless `includeSystemAccounts` is on it keeps only login-capable accounts (uid within `UID_MIN`/`UID_MAX`, no `nologin`/`false` shell, not a `_`-prefixed or well-known system name; `root` always kept). Each account stages with `fingerprint = host:username` and `credentials: { authMethod: "password", username }` so imports arrive without a secret. Unreachable/auth-failed hosts go to `machineErrors`, never aborting the scan (dead IPs in a range are dropped silently; only hosts that answered SSH, or hosts explicitly named as a credential account's host, are reported).++Auth methods (all run through the gateway, so `ssh2` is never used on the backend for discovery): the gateway has a dedicated **SSH-exec RPC** handler (CLI repo `packages/gateway-v2/ssh_handler.go`, ALPN `infisical-ssh-exec`) that performs the SSH login itself and runs one command. The backend `sshExecWithGateway` (`pam-discovery-fns.ts`) opens `getPlatformConnectionDetailsByGatewayId` + `withGatewayV2Proxy(SshExec)` and POSTs `{ command, credentials }` to `/v1/exec` via `callSshExec` (`lib/gateway-v2/ssh-rpc.ts`); the target host/port come from the signed gateway cert (SSRF-safe), credentials from the body. This handles password, private-key, **and certificate** auth uniformly — the gateway's Go SSH client can present a cert, which `ssh2` cannot. For certificate accounts the backend signs an ephemeral user cert in `runScan` (`buildGatewaySshCredentials`, reusing `createSshCert`) and sends `privateKey`+`certificate` in the RPC body. This path touches nothing in the PAM session machinery, so scans produce no session rows, recordings, or `PAM_SESSION_START` audit. It mirrors the WinRM RPC handler pattern (Infisical/cli #309, Infisical/infisical #7258).++Speed: before enumerating, `scan()` does one **port sweep** (gateway ALPN `infisical-port-sweep`, `handlePortSweep`) that TCP-probes the whole expanded target set in-network and returns the reachable `host:port` set (`sweepReachableTargets`). Only reachable hosts (plus explicitly-named credential-account hosts) get the per-host SSH-exec, at `SCAN_CONCURRENCY` parallelism — so a sparse CIDR costs one sweep op instead of a gateway op per dead IP.+## Deferred CleanupOld tables, columns, and code kept temporarily so data can be recovered if the migration causes issues. Target removal: ~1 month after all deployments are running the new model (safe after 2026-08-01). A follow-up migration should handle the drops.diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex a077a790fb..174de5b51e 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -41,6 +41,12 @@ export enum PamAccessMethod {Cli = "cli"}+export enum PamSshAuthMethod {+ Password = "password",+ PublicKey = "public-key",+ Certificate = "certificate"+}+// The caller's just-in-time approval state for an account gated behind an access request flowexport enum PamAccessStatus {None = "none",diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex dafd9eea30..828956abde 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -97,7 +97,9 @@ export const createGatewayConnection = async ([GatewayProxyProtocol.PamRdpBrowser]: ["infisical-pam-rdp-browser"],[GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"],[GatewayProxyProtocol.Pkcs11]: ["infisical-pkcs11"],- [GatewayProxyProtocol.Adcs]: ["infisical-adcs"]+ [GatewayProxyProtocol.Adcs]: ["infisical-adcs"],+ [GatewayProxyProtocol.PortSweep]: ["infisical-port-sweep"],+ [GatewayProxyProtocol.SshExec]: ["infisical-ssh-exec"]};const tlsOptions: tls.ConnectionOptions = {@@ -271,16 +273,19 @@ export const withGatewayV2Proxy = async <T>(options: {protocol: GatewayProxyProtocol;httpsAgent?: https.Agent;+ // keeps the relay connection alive through long idle stretches (e.g. a port sweep dialing many hosts)+ longLived?: boolean;} & TGatewayV2ConnectionDetails): Promise<T> => {- const { protocol, relayHost, gateway, relay, httpsAgent } = options;+ const { protocol, relayHost, gateway, relay, httpsAgent, longLived } = options;const { port, cleanup, getRelayError } = await setupRelayServer({protocol,relayHost,gateway,relay,- httpsAgent+ httpsAgent,+ longLived});try {diff --git a/backend/src/lib/gateway-v2/ssh-rpc.ts b/backend/src/lib/gateway-v2/ssh-rpc.tsnew file mode 100644index 0000000000..a8ad3886d5--- /dev/null+++ b/backend/src/lib/gateway-v2/ssh-rpc.ts@@ -0,0 +1,89 @@+import http from "node:http";++import { logger } from "@app/lib/logger";++export type SshExecCredentials = {+ authMethod: string;+ username: string;+ password?: string;+ privateKey?: string;+ certificate?: string;+};++export type SshExecResult = { stdout: string; stderr: string; exitCode: number };++export type SshExecSuccess = { ok: true; status: number; result: SshExecResult };+export type SshExecFailure = { ok: false; status: number; errorMessage: string };+export type SshExecResponse = SshExecSuccess | SshExecFailure;++export const SSH_EXEC_RPC_TIMEOUT_MS = 120_000;++// calls the gateway's ssh-exec handler over the local relay proxy; the gateway performs the ssh login (any auth+// method, including certificates the node client can't present) and returns the command output+export const callSshExec = (args: {+ port: number;+ command: string;+ credentials: SshExecCredentials;+ timeoutMs: number;+}): Promise<SshExecResponse> => {+ const payload = JSON.stringify({ command: args.command, ...args.credentials, timeoutMs: args.timeoutMs });+ return new Promise<SshExecResponse>((resolve, reject) => {+ const req = http.request(+ {+ host: "127.0.0.1",+ port: args.port,+ path: "/v1/exec",+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Content-Length": Buffer.byteLength(payload).toString(),+ Connection: "close"+ },+ timeout: SSH_EXEC_RPC_TIMEOUT_MS+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => {+ const text = Buffer.concat(chunks).toString("utf8");+ const status = res.statusCode ?? 0;+ if (!text) {+ resolve({ ok: false, status, errorMessage: `Empty response from gateway (status ${status})` });+ return;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ resolve({ ok: false, status, errorMessage: `Malformed response from gateway: ${text.slice(0, 256)}` });+ return;+ }+ if (status >= 200 && status < 300) {+ const { result } = parsed as { result?: SshExecResult };+ if (!result) {+ resolve({ ok: false, status, errorMessage: "Gateway response missing `result` field" });+ return;+ }+ resolve({ ok: true, status, result });+ return;+ }+ const errEnv = (parsed as { error?: { message?: string } }).error;+ resolve({ ok: false, status, errorMessage: errEnv?.message ?? `Gateway returned HTTP ${status}` });+ });+ res.on("error", (err) => {+ logger.warn({ err }, `SSH exec RPC response stream error [port=${args.port}]`);+ reject(err);+ });+ }+ );+ req.on("timeout", () => {+ req.destroy(new Error(`SSH exec RPC timed out after ${SSH_EXEC_RPC_TIMEOUT_MS}ms`));+ });+ req.on("error", (err) => {+ logger.warn({ err }, `SSH exec RPC request error [port=${args.port}]`);+ reject(err);+ });+ req.write(payload);+ req.end();+ });+};diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.tsindex a874846fc3..af807b5821 100644--- a/backend/src/lib/gateway/types.ts+++ b/backend/src/lib/gateway/types.ts@@ -13,7 +13,9 @@ export enum GatewayProxyProtocol {PamRdpBrowser = "pam-rdp-browser",PamSessionCancellation = "pam-session-cancellation",Pkcs11 = "pkcs11",- Adcs = "adcs"+ Adcs = "adcs",+ PortSweep = "port-sweep",+ SshExec = "ssh-exec"}export enum GatewayHttpProxyActions {diff --git a/docs/docs.json b/docs/docs.jsonindex 9cc34c7911..7c8b1124d6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1090,7 +1090,8 @@"group": "Discovery","pages": ["documentation/platform/pam/discovery/overview",- "documentation/platform/pam/discovery/active-directory"+ "documentation/platform/pam/discovery/active-directory",+ "documentation/platform/pam/discovery/unix"]},{diff --git a/docs/documentation/platform/pam/discovery/active-directory.mdx b/docs/documentation/platform/pam/discovery/active-directory.mdxindex fbb494c842..fc696245e4 100644--- a/docs/documentation/platform/pam/discovery/active-directory.mdx+++ b/docs/documentation/platform/pam/discovery/active-directory.mdx@@ -38,7 +38,7 @@ To discover local Windows accounts, the credential account must include a **pass<Steps><Step title="Start adding a source">- Go to **Privileged Access Management → Discovery** and click **Add Source**, then choose **Active Directory**.+ Go to **Privileged Access Manager → Discovery** and click **Add Source**, then choose **Active Directory**.</Step><Step title="Configure the source">| Field | Description |diff --git a/docs/documentation/platform/pam/discovery/overview.mdx b/docs/documentation/platform/pam/discovery/overview.mdxindex e5725d58e5..af18e07b79 100644--- a/docs/documentation/platform/pam/discovery/overview.mdx+++ b/docs/documentation/platform/pam/discovery/overview.mdx@@ -33,6 +33,9 @@ Discovery is available to **Product Admins**. See [Access Control](/documentatio<Card title="Active Directory" icon="windows" href="/documentation/platform/pam/discovery/active-directory">Scan an Active Directory environment for domain accounts and local Windows accounts.</Card>+ <Card title="Unix" icon="terminal" href="/documentation/platform/pam/discovery/unix">+ Scan Unix hosts over SSH for local accounts.+ </Card></CardGroup><Note>@@ -88,6 +91,9 @@ Scheduled scans are evaluated once a day, so a source runs on its next scheduled<Card title="Active Directory" icon="windows" href="/documentation/platform/pam/discovery/active-directory">Configure an Active Directory discovery source.</Card>+ <Card title="Unix" icon="terminal" href="/documentation/platform/pam/discovery/unix">+ Configure a Unix discovery source.+ </Card><Card title="Accounts" icon="user-lock" href="/documentation/platform/pam/accounts/overview">Manage the accounts you import.</Card>diff --git a/docs/documentation/platform/pam/discovery/unix.mdx b/docs/documentation/platform/pam/discovery/unix.mdxnew file mode 100644index 0000000000..ab40076a09--- /dev/null+++ b/docs/documentation/platform/pam/discovery/unix.mdx@@ -0,0 +1,93 @@+---+title: "Unix Discovery"+sidebarTitle: "Unix"+description: "Scan Unix hosts over SSH for local accounts and import them into PAM."+---++Unix discovery scans a set of Unix hosts over SSH, enumerates their local accounts, stages them for review, and lets you import them into PAM as [SSH accounts](/documentation/platform/pam/accounts/ssh). Because there is no central directory to read from, you point a source at the hosts to scan and the [SSH accounts](/documentation/platform/pam/accounts/ssh) to scan with.++All scan traffic is tunneled through an Infisical [Gateway](/documentation/platform/gateways/overview).++## How It Works++A Unix scan connects entirely through the Gateway:++1. Each **CIDR range** is expanded into a list of target hosts; individual IPs and hostnames are used as-is (hostnames are resolved by the gateway in the target network).+2. For each host, discovery picks a credential account: it first tries an account whose stored host matches the target, otherwise it tries each account in turn until one authenticates.+3. It reads the host's local accounts from `/etc/passwd` (via `getent passwd`) over SSH.+4. Each account it keeps is staged as an **SSH** account scoped to that host. `root` on two hosts becomes two separate staged accounts.++Hosts that no credential can reach or authenticate to are reported on the run and skipped; the rest of the scan still completes.++## Prerequisites++Before creating a Unix discovery source, make sure you have:++- A [Gateway](/documentation/platform/gateways/overview) (or Gateway pool) with network access to the hosts you want to scan.+- One or more [SSH accounts](/documentation/platform/pam/accounts/ssh) in PAM to use as **credential accounts**. Discovery authenticates to each host as one of these accounts, using its port. Password, private-key, and certificate (SSH CA) auth are all supported for scanning; certificate accounts are brokered through the gateway and require the target hosts to trust the account's CA.+- The **Product Admin** role. See [Access Control](/documentation/platform/pam/concepts/access-control).++<Note>+A scanning identity is typically provisioned uniformly across the fleet, most reliably as a key-based [SSH account](/documentation/platform/pam/accounts/ssh) whose key is trusted on every host.+</Note>++## Creating a Source++<Steps>+ <Step title="Start adding a source">+ Go to **Privileged Access Manager → Discovery** and click **Add Source**, then choose **Unix**.+ </Step>+ <Step title="Configure the source">+ | Field | Description |+ |-------|-------------|+ | **Name** | A descriptive name (e.g., `corp-servers`) |+ | **Credential Accounts** | One or more [SSH accounts](/documentation/platform/pam/accounts/ssh) used to authenticate and scan |+ | **Gateway** | The [Gateway](/documentation/platform/gateways/overview) or Gateway pool that scan traffic tunnels through |+ | **Scan Schedule** | How often to scan automatically: **Manual**, **Daily**, or **Weekly** |+ | **Targets** | IP addresses, IPv4 CIDR ranges, or hostnames to scan, one per line or comma-separated. Hostnames are resolved by the gateway in the target network |+ </Step>+ <Step title="Choose which accounts to surface">+ Leave **Include system/service accounts** off to surface only real login accounts, or turn it on to surface every account in `/etc/passwd`. See [Account Filtering](#account-filtering).+ </Step>+ <Step title="Save">+ Click **Add Source**. The source appears in the Discovery table.+ </Step>+</Steps>++## Account Filtering++By default discovery surfaces only login-capable accounts and excludes daemon and system accounts. It reads the UID bounds from each host's `/etc/login.defs` and drops accounts outside that range, accounts with a `nologin`/`false` shell, and well-known system account names.++Turn on **Include system/service accounts** to skip this filtering and surface every account in `/etc/passwd`, including daemon accounts.++## Running a Scan++Trigger a scan manually with **Scan Now** from the source's row menu or its detail panel. Scans run in the background, and a source can only have one scan running at a time.++If the source is on a **Daily** or **Weekly** schedule, Infisical also scans it automatically when its interval has elapsed. **Manual** sources are only scanned when you trigger them.++## Importing Accounts++From the **Staged Accounts** tab, select the accounts you want and click **Import Accounts**. Then choose:++| Field | Description |+|-------|-------------|+| **Destination Folder** | The [folder](/documentation/platform/pam/folders/overview) to import the accounts into |+| **Template** | An [SSH account template](/documentation/platform/pam/templates/overview) to apply |++Once imported, the accounts become regular PAM SSH accounts in the chosen folder and inherit their template's rules.++<Warning>+Imported accounts arrive without a credential because discovery finds accounts with a username but no password. Open each imported account and add a credential before connecting.+</Warning>++## Next Steps++<CardGroup cols={2}>+ <Card title="Discovery Overview" icon="radar" href="/documentation/platform/pam/discovery/overview">+ Understand staging, importing, and schedules.+ </Card>+ <Card title="SSH Accounts" icon="terminal" href="/documentation/platform/pam/accounts/ssh">+ Learn about the account type used to authenticate scans.+ </Card>+</CardGroup>diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 4f9faf4f39..0e05185aa1 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -14,7 +14,8 @@ export enum PamAccountType {}export enum PamDiscoveryType {- ActiveDirectory = "active-directory"+ ActiveDirectory = "active-directory",+ Unix = "unix"}export enum PamDiscoverySchedule {diff --git a/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsxindex 89d8b5d420..ea4b530526 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx@@ -44,7 +44,7 @@ import { usePamSheetState } from "@app/hooks/usePamSheetState";import { usePopUp } from "@app/hooks/usePopUp";import { PAM_DISCOVERY_TABS } from "../components/pamResourceTabs";-import { AddDiscoverySourceModal } from "./components/AddDiscoverySourceModal";+import { AddDiscoverySourceSheet } from "./components/AddDiscoverySourceSheet";import { DiscoverySourceDetailSheet } from "./components/DiscoverySourceDetailSheet";import { DiscoveryStatusBadge } from "./components/DiscoveryStatusBadge";@@ -252,7 +252,7 @@ export const PamDiscoveryPage = () => {</Card></div>- <AddDiscoverySourceModal+ <AddDiscoverySourceSheetisOpen={popUp.addSource.isOpen}onOpenChange={(open) => {if (!open) handlePopUpClose("addSource");diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsxdeleted file mode 100644index deebe769b5..0000000000--- a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsx+++ /dev/null@@ -1,175 +0,0 @@-import { useState } from "react";-import { Control, useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { z } from "zod";--import { createNotification } from "@app/components/notifications";-import {- Button,- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- Field,- FieldContent,- FieldError,- FieldLabel,- GatewayPicker,- Input-} from "@app/components/v3";-import {- PamDiscoverySchedule,- PamDiscoveryType,- useCreatePamDiscoverySource-} from "@app/hooks/api/pam";--import {- buildDiscoveryConfiguration,- CredentialAccountField,- DISCOVERY_CONFIG_DEFAULTS,- DiscoveryConfigFields,- discoveryConfigFormShape,- ScheduleField,- TDiscoveryConfigFields-} from "./DiscoveryConfigFields";--const formSchema = z.object({- name: z.string().min(1, "Name is required").max(64),- credentialAccountId: z.string().uuid("Select a credential account"),- schedule: z.nativeEnum(PamDiscoverySchedule),- ...discoveryConfigFormShape-});--type FormData = z.infer<typeof formSchema>;--type Props = {- isOpen: boolean;- onOpenChange: (open: boolean) => void;-};--export const AddDiscoverySourceModal = ({ isOpen, onOpenChange }: Props) => {- const createSource = useCreatePamDiscoverySource();-- const [gateway, setGateway] = useState<{- gatewayId: string | null;- gatewayPoolId: string | null;- }>({- gatewayId: null,- gatewayPoolId: null- });- const [gatewayError, setGatewayError] = useState(false);-- const {- register,- handleSubmit,- control,- reset,- formState: { errors }- } = useForm<FormData>({- resolver: zodResolver(formSchema),- defaultValues: {- name: "",- credentialAccountId: "",- schedule: PamDiscoverySchedule.Manual,- ...DISCOVERY_CONFIG_DEFAULTS- }- });-- const resetForm = () => {- reset();- setGateway({ gatewayId: null, gatewayPoolId: null });- setGatewayError(false);- };-- const onSubmit = (data: FormData) => {- if (!gateway.gatewayId && !gateway.gatewayPoolId) {- setGatewayError(true);- return;- }-- createSource.mutate(- {- discoveryType: PamDiscoveryType.ActiveDirectory,- name: data.name,- credentialAccountId: data.credentialAccountId,- schedule: data.schedule,- configuration: buildDiscoveryConfiguration(data),- ...(gateway.gatewayId ? { gatewayId: gateway.gatewayId } : {}),- ...(gateway.gatewayPoolId ? { gatewayPoolId: gateway.gatewayPoolId } : {})- },- {- onSuccess: () => {- createNotification({ type: "success", text: "Discovery source created" });- resetForm();- onOpenChange(false);- }- }- );- };-- return (- <Dialog- open={isOpen}- onOpenChange={(open) => {- if (!open) resetForm();- onOpenChange(open);- }}- >- <DialogContent className="max-w-xl">- <DialogHeader>- <DialogTitle>Add Active Directory Discovery Source</DialogTitle>- </DialogHeader>- <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">- <Field>- <FieldLabel htmlFor="source-name">Name</FieldLabel>- <FieldContent>- <Input- id="source-name"- placeholder="e.g. corp-active-directory"- isError={!!errors.name}- {...register("name")}- />- <FieldError>{errors.name?.message}</FieldError>- </FieldContent>- </Field>-- <CredentialAccountField- control={control as unknown as Control<{ credentialAccountId: string }>}- />-- <Field>- <FieldLabel>Gateway</FieldLabel>- <FieldContent>- <GatewayPicker- isRequired- isError={gatewayError}- value={gateway}- onChange={(value) => {- setGateway(value);- setGatewayError(false);- }}- />- {gatewayError && <FieldError>A gateway is required</FieldError>}- </FieldContent>- </Field>-- <ScheduleField- control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}- />-- <DiscoveryConfigFields control={control as unknown as Control<TDiscoveryConfigFields>} />-- <DialogFooter>- <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" variant="pam" isPending={createSource.isPending}>- Add Source- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- );-};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsxnew file mode 100644index 0000000000..96901c146a--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceSheet.tsx@@ -0,0 +1,453 @@+import { useEffect, useState } from "react";+import { Control, Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { AlertTriangle } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+ Button,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ GatewayPicker,+ Input,+ RadioGroup,+ RadioGroupItem,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";+import {+ PamDiscoverySchedule,+ PamDiscoveryType,+ TPamDiscoveryTypeOption,+ useCreatePamDiscoverySource,+ useListPamDiscoveryTypes+} from "@app/hooks/api/pam";++import {+ buildDiscoveryConfiguration,+ buildUnixDiscoveryConfiguration,+ CredentialAccountField,+ DISCOVERY_CONFIG_DEFAULTS,+ DiscoveryConfigFields,+ discoveryConfigFormShape,+ ScheduleField,+ SshCredentialAccountsField,+ TDiscoveryConfigFields,+ TUnixDiscoveryConfigFields,+ UNIX_DISCOVERY_CONFIG_DEFAULTS,+ UnixDiscoveryConfigFields,+ unixDiscoveryConfigFormShape+} from "./DiscoveryConfigFields";++type FormProps = {+ onBack: () => void;+ onClose: () => void;+ onDirtyChange: (dirty: boolean) => void;+};++const useGatewaySelection = () => {+ const [gateway, setGateway] = useState<{+ gatewayId: string | null;+ gatewayPoolId: string | null;+ }>({+ gatewayId: null,+ gatewayPoolId: null+ });+ const [gatewayError, setGatewayError] = useState(false);+ return { gateway, setGateway, gatewayError, setGatewayError };+};++const GatewayField = ({+ value,+ isError,+ onChange+}: {+ value: { gatewayId: string | null; gatewayPoolId: string | null };+ isError: boolean;+ onChange: (value: { gatewayId: string | null; gatewayPoolId: string | null }) => void;+}) => (+ <Field>+ <FieldLabel>Gateway</FieldLabel>+ <FieldContent>+ <GatewayPicker isRequired isError={isError} value={value} onChange={onChange} />+ {isError && <FieldError>A gateway is required</FieldError>}+ </FieldContent>+ </Field>+);++const NameField = ({ control }: { control: Control<{ name: string }> }) => (+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel htmlFor="source-name">Name</FieldLabel>+ <FieldContent>+ <Input+ id="source-name"+ placeholder="e.g. corp-servers"+ isError={!!fieldState.error}+ {...field}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+);++const FormShell = ({+ children,+ footer+}: {+ children: React.ReactNode;+ footer: React.ReactNode;+}) => (+ <>+ <div className="flex thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto px-4">+ {children}+ <div aria-hidden className="h-4 shrink-0" />+ </div>+ <SheetFooter className="justify-end border-t">{footer}</SheetFooter>+ </>+);++const activeDirectorySchema = z.object({+ name: z.string().min(1, "Name is required").max(64),+ credentialAccountId: z.string().uuid("Select a credential account"),+ schedule: z.nativeEnum(PamDiscoverySchedule),+ ...discoveryConfigFormShape+});++const ActiveDirectorySourceForm = ({ onBack, onClose, onDirtyChange }: FormProps) => {+ const createSource = useCreatePamDiscoverySource();+ const { gateway, setGateway, gatewayError, setGatewayError } = useGatewaySelection();++ const {+ handleSubmit,+ control,+ formState: { isDirty }+ } = useForm<z.infer<typeof activeDirectorySchema>>({+ resolver: zodResolver(activeDirectorySchema),+ defaultValues: {+ name: "",+ credentialAccountId: "",+ schedule: PamDiscoverySchedule.Manual,+ ...DISCOVERY_CONFIG_DEFAULTS+ }+ });++ useEffect(() => {+ onDirtyChange(isDirty);+ return () => onDirtyChange(false);+ }, [isDirty, onDirtyChange]);++ const onSubmit = (data: z.infer<typeof activeDirectorySchema>) => {+ if (!gateway.gatewayId && !gateway.gatewayPoolId) {+ setGatewayError(true);+ return;+ }+ createSource.mutate(+ {+ discoveryType: PamDiscoveryType.ActiveDirectory,+ name: data.name,+ credentialAccountId: data.credentialAccountId,+ schedule: data.schedule,+ configuration: buildDiscoveryConfiguration(data),+ ...(gateway.gatewayId ? { gatewayId: gateway.gatewayId } : {}),+ ...(gateway.gatewayPoolId ? { gatewayPoolId: gateway.gatewayPoolId } : {})+ },+ {+ onSuccess: () => {+ createNotification({ type: "success", text: "Discovery source created" });+ onClose();+ }+ }+ );+ };++ return (+ <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">+ <FormShell+ footer={+ <>+ <Button type="button" variant="ghost" onClick={onBack}>+ Back+ </Button>+ <Button type="submit" variant="pam" isPending={createSource.isPending}>+ Add Source+ </Button>+ </>+ }+ >+ <NameField control={control as unknown as Control<{ name: string }>} />+ <CredentialAccountField+ control={control as unknown as Control<{ credentialAccountId: string }>}+ />+ <GatewayField+ value={gateway}+ isError={gatewayError}+ onChange={(value) => {+ setGateway(value);+ setGatewayError(false);+ }}+ />+ <ScheduleField+ control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}+ />+ <DiscoveryConfigFields control={control as unknown as Control<TDiscoveryConfigFields>} />+ </FormShell>+ </form>+ );+};++const unixSchema = z.object({+ name: z.string().min(1, "Name is required").max(64),+ schedule: z.nativeEnum(PamDiscoverySchedule),+ ...unixDiscoveryConfigFormShape+});++const UnixSourceForm = ({ onBack, onClose, onDirtyChange }: FormProps) => {+ const createSource = useCreatePamDiscoverySource();+ const { gateway, setGateway, gatewayError, setGatewayError } = useGatewaySelection();++ const {+ handleSubmit,+ control,+ formState: { isDirty }+ } = useForm<z.infer<typeof unixSchema>>({+ resolver: zodResolver(unixSchema),+ defaultValues: {+ name: "",+ schedule: PamDiscoverySchedule.Manual,+ ...UNIX_DISCOVERY_CONFIG_DEFAULTS+ }+ });++ useEffect(() => {+ onDirtyChange(isDirty);+ return () => onDirtyChange(false);+ }, [isDirty, onDirtyChange]);++ const onSubmit = (data: z.infer<typeof unixSchema>) => {+ if (!gateway.gatewayId && !gateway.gatewayPoolId) {+ setGatewayError(true);+ return;+ }+ createSource.mutate(+ {+ discoveryType: PamDiscoveryType.Unix,+ name: data.name,+ credentialAccountId: data.credentialAccountIds[0],+ schedule: data.schedule,+ configuration: buildUnixDiscoveryConfiguration(data),+ ...(gateway.gatewayId ? { gatewayId: gateway.gatewayId } : {}),+ ...(gateway.gatewayPoolId ? { gatewayPoolId: gateway.gatewayPoolId } : {})+ },+ {+ onSuccess: () => {+ createNotification({ type: "success", text: "Discovery source created" });+ onClose();+ }+ }+ );+ };++ return (+ <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">+ <FormShell+ footer={+ <>+ <Button type="button" variant="ghost" onClick={onBack}>+ Back+ </Button>+ <Button type="submit" variant="pam" isPending={createSource.isPending}>+ Add Source+ </Button>+ </>+ }+ >+ <NameField control={control as unknown as Control<{ name: string }>} />+ <SshCredentialAccountsField+ control={control as unknown as Control<{ credentialAccountIds: string[] }>}+ />+ <GatewayField+ value={gateway}+ isError={gatewayError}+ onChange={(value) => {+ setGateway(value);+ setGatewayError(false);+ }}+ />+ <ScheduleField+ control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}+ />+ <UnixDiscoveryConfigFields+ control={control as unknown as Control<TUnixDiscoveryConfigFields>}+ />+ </FormShell>+ </form>+ );+};++const TypeSelectorStep = ({+ types,+ selectedType,+ onSelect,+ onCancel,+ onNext+}: {+ types: TPamDiscoveryTypeOption[];+ selectedType: PamDiscoveryType | null;+ onSelect: (type: PamDiscoveryType) => void;+ onCancel: () => void;+ onNext: () => void;+}) => (+ <>+ <div className="flex min-h-0 flex-1 flex-col px-4">+ <RadioGroup+ value={selectedType ?? ""}+ onValueChange={(value) => onSelect(value as PamDiscoveryType)}+ className="flex thin-scrollbar flex-1 flex-col gap-2 overflow-y-auto"+ >+ {types.map((type) => (+ <FieldLabel key={type.type} htmlFor={`discovery-type-${type.type}`} variant="pam">+ <Field orientation="horizontal" className="items-center gap-3">+ <img+ src={`/images/integrations/${type.icon}`}+ alt={type.name}+ className="size-7 shrink-0 rounded-sm"+ />+ <div className="min-w-0 flex-1 text-left">+ <p className="truncate text-sm font-medium text-foreground">{type.name}</p>+ </div>+ <RadioGroupItem+ id={`discovery-type-${type.type}`}+ value={type.type}+ className="sr-only"+ />+ </Field>+ </FieldLabel>+ ))}+ </RadioGroup>+ </div>++ <SheetFooter className="justify-end border-t">+ <Button type="button" variant="ghost" onClick={onCancel}>+ Cancel+ </Button>+ <Button type="button" variant="pam" isDisabled={!selectedType} onClick={onNext}>+ Next+ </Button>+ </SheetFooter>+ </>+);++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+};++export const AddDiscoverySourceSheet = ({ isOpen, onOpenChange }: Props) => {+ const { data: discoveryTypes = [] } = useListPamDiscoveryTypes();+ const [step, setStep] = useState<1 | 2>(1);+ const [selectedType, setSelectedType] = useState<PamDiscoveryType | null>(null);+ const [isFormDirty, setIsFormDirty] = useState(false);+ const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);++ useEffect(() => {+ if (isOpen) {+ setStep(1);+ setSelectedType(null);+ setIsFormDirty(false);+ }+ }, [isOpen]);++ const close = () => onOpenChange(false);++ // warn before discarding a partially filled form+ const handleOpenChange = (nextOpen: boolean) => {+ if (!nextOpen && isFormDirty) {+ setConfirmDiscardOpen(true);+ return;+ }+ onOpenChange(nextOpen);+ };++ return (+ <>+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>Add Discovery Source</SheetTitle>+ </SheetHeader>++ {step === 1 && (+ <TypeSelectorStep+ types={discoveryTypes}+ selectedType={selectedType}+ onSelect={setSelectedType}+ onCancel={() => handleOpenChange(false)}+ onNext={() => setStep(2)}+ />+ )}+ {step === 2 &&+ (selectedType === PamDiscoveryType.Unix ? (+ <UnixSourceForm+ onBack={() => setStep(1)}+ onClose={close}+ onDirtyChange={setIsFormDirty}+ />+ ) : (+ <ActiveDirectorySourceForm+ onBack={() => setStep(1)}+ onClose={close}+ onDirtyChange={setIsFormDirty}+ />+ ))}+ </SheetContent>+ </Sheet>++ <AlertDialog open={confirmDiscardOpen} onOpenChange={setConfirmDiscardOpen}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <AlertTriangle />+ </AlertDialogMedia>+ <AlertDialogTitle>Discard source setup?</AlertDialogTitle>+ <AlertDialogDescription>+ Your progress creating this discovery source will be lost.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep Editing</AlertDialogCancel>+ <AlertDialogAction+ variant="danger"+ onClick={() => {+ setConfirmDiscardOpen(false);+ onOpenChange(false);+ }}+ >+ Discard+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsxindex a2a20c9ee3..07dfdf2d94 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx@@ -144,6 +144,128 @@ export const DiscoveryConfigFields = ({);};+export const unixDiscoveryConfigFormShape = {+ cidrRanges: z.string().min(1, "At least one target is required"),+ credentialAccountIds: z.array(z.string()).min(1, "Select at least one account"),+ includeSystemAccounts: z.boolean()+};++export type TUnixDiscoveryConfigFields = z.infer<z.ZodObject<typeof unixDiscoveryConfigFormShape>>;++export const UNIX_DISCOVERY_CONFIG_DEFAULTS: TUnixDiscoveryConfigFields = {+ cidrRanges: "",+ credentialAccountIds: [],+ includeSystemAccounts: false+};++const parseCidrRanges = (value: string): string[] =>+ value+ .split(/[\n,]/)+ .map((v) => v.trim())+ .filter(Boolean);++export const unixDiscoveryConfigFromSource = (+ config: Record<string, unknown>+): TUnixDiscoveryConfigFields => ({+ cidrRanges: Array.isArray(config.cidrRanges) ? (config.cidrRanges as string[]).join("\n") : "",+ credentialAccountIds: Array.isArray(config.credentialAccountIds)+ ? (config.credentialAccountIds as string[])+ : [],+ includeSystemAccounts: Boolean(config.includeSystemAccounts)+});++export const buildUnixDiscoveryConfiguration = (+ data: TUnixDiscoveryConfigFields+): Record<string, unknown> => ({+ cidrRanges: parseCidrRanges(data.cidrRanges),+ credentialAccountIds: data.credentialAccountIds,+ includeSystemAccounts: data.includeSystemAccounts+});++export const SshCredentialAccountsField = ({+ control+}: {+ control: Control<{ credentialAccountIds: string[] }>;+}) => {+ const { data: accounts = [] } = useListPamAccountsAdmin();+ const sshAccounts = accounts.filter((a) => a.accountType === PamAccountType.SSH);++ return (+ <Controller+ control={control}+ name="credentialAccountIds"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Credential Accounts</FieldLabel>+ <FieldContent>+ <FilterableSelect+ isMulti+ value={sshAccounts.filter((a) => field.value?.includes(a.id))}+ onChange={(val) =>+ field.onChange(((val as typeof sshAccounts | null) ?? []).map((a) => a.id))+ }+ options={sshAccounts}+ getOptionValue={(a) => a.id}+ getOptionLabel={(a) => (a.folderName ? `${a.folderName} / ${a.name}` : a.name)}+ placeholder="Select SSH accounts"+ />+ <FieldDescription>+ A target is matched to an account by host, otherwise each account is tried until one+ connects.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ );+};++export const UnixDiscoveryConfigFields = ({+ control+}: {+ control: Control<TUnixDiscoveryConfigFields>;+}) => (+ <>+ <Controller+ control={control}+ name="cidrRanges"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Targets</FieldLabel>+ <FieldContent>+ <TextArea {...field} rows={3} placeholder="10.0.0.0/24, 192.168.1.10, host.internal" />+ <FieldDescription>+ IP addresses, IPv4 CIDR ranges, or hostnames, one per line or comma-separated.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="includeSystemAccounts"+ render={({ field }) => (+ <Field>+ <div className="flex items-center justify-between gap-4">+ <FieldLabel htmlFor="includeSystemAccounts" className="mb-0">+ Include system/service accounts+ </FieldLabel>+ <Switch+ id="includeSystemAccounts"+ variant="pam"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </div>+ </Field>+ )}+ />+ </>+);+// Shared credential-account + schedule fields, used by both the create modal and the edit tab.export const CredentialAccountField = ({controldiff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsxindex 2ab689d1e1..e03ef98e31 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx@@ -47,6 +47,7 @@ import {import {PamAccountType,PamDiscoverySchedule,+ PamDiscoveryType,pamKeys,TPamDiscoveredAccount,TPamDiscoverySource,@@ -67,12 +68,18 @@ import { PAM_DISCOVERY_TABS } from "../../components/pamResourceTabs";import { SheetSaveBar } from "../../components/SheetSaveBar";import {buildDiscoveryConfiguration,+ buildUnixDiscoveryConfiguration,CredentialAccountField,DiscoveryConfigFields,discoveryConfigFormShape,discoveryConfigFromSource,ScheduleField,- TDiscoveryConfigFields+ SshCredentialAccountsField,+ TDiscoveryConfigFields,+ TUnixDiscoveryConfigFields,+ UnixDiscoveryConfigFields,+ unixDiscoveryConfigFormShape,+ unixDiscoveryConfigFromSource} from "./DiscoveryConfigFields";import { DiscoveryStatusBadge } from "./DiscoveryStatusBadge";import { ImportDiscoveredModal } from "./ImportDiscoveredModal";@@ -87,7 +94,52 @@ const RunStatusBadge = ({ status }: { status: string }) => (<Badge variant={STATUS_VARIANT[status] ?? "neutral"}>{status}</Badge>);-const configSchema = z.object({+const NameField = ({ control }: { control: Control<{ name: string }> }) => (+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Name</FieldLabel>+ <FieldContent>+ <Input {...field} isError={!!fieldState.error} />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+);++const GatewayField = ({+ gatewayId,+ gatewayPoolId,+ onChange+}: {+ gatewayId: string | null;+ gatewayPoolId: string | null;+ onChange: (value: { gatewayId: string | null; gatewayPoolId: string | null }) => void;+}) => (+ <Field>+ <FieldLabel>Gateway</FieldLabel>+ <FieldContent>+ <GatewayPicker isRequired value={{ gatewayId, gatewayPoolId }} onChange={onChange} />+ </FieldContent>+ </Field>+);++const ConfigCard = ({ children }: { children: ReactNode }) => (+ <Card>+ <CardHeader className="border-b">+ <CardTitle className="text-base">Configuration</CardTitle>+ <CardDescription>+ Edit the source name, credential accounts, gateway, schedule, and account discovery.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">{children}</CardContent>+ </Card>+);++const activeDirectoryConfigSchema = z.object({name: z.string().min(1, "Name is required").max(64),credentialAccountId: z.string().uuid("Select a credential account"),schedule: z.nativeEnum(PamDiscoverySchedule),@@ -96,9 +148,7 @@ const configSchema = z.object({...discoveryConfigFormShape});-type ConfigForm = z.infer<typeof configSchema>;--const ConfigurationTab = ({+const ActiveDirectoryConfigForm = ({source,onDirtyChange}: {@@ -107,7 +157,7 @@ const ConfigurationTab = ({}) => {const updateSource = useUpdatePamDiscoverySource();- const defaults: ConfigForm = {+ const defaults: z.infer<typeof activeDirectoryConfigSchema> = {name: source.name,credentialAccountId: source.credentialAccountId,schedule: source.schedule,@@ -123,7 +173,7 @@ const ConfigurationTab = ({watch,setValue,formState: { isDirty }- } = useForm<ConfigForm>({ resolver: zodResolver(configSchema), defaultValues: defaults });+ } = useForm({ resolver: zodResolver(activeDirectoryConfigSchema), defaultValues: defaults });useEffect(() => {onDirtyChange(isDirty);@@ -135,10 +185,7 @@ const ConfigurationTab = ({// eslint-disable-next-line react-hooks/exhaustive-deps}, [source, reset]);- const gatewayId = watch("gatewayId");- const gatewayPoolId = watch("gatewayPoolId");-- const onSubmit = (data: ConfigForm) => {+ const onSubmit = (data: z.infer<typeof activeDirectoryConfigSchema>) => {updateSource.mutate({sourceId: source.id,@@ -156,54 +203,113 @@ const ConfigurationTab = ({return (<form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">- <Card>- <CardHeader className="border-b">- <CardTitle className="text-base">Configuration</CardTitle>- <CardDescription>- Edit the source name, credential account, gateway, schedule, and local-account- discovery.- </CardDescription>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <Controller- control={control}- name="name"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>Name</FieldLabel>- <FieldContent>- <Input {...field} isError={!!fieldState.error} />- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />-- <CredentialAccountField- control={control as unknown as Control<{ credentialAccountId: string }>}- />-- <Field>- <FieldLabel>Gateway</FieldLabel>- <FieldContent>- <GatewayPicker- isRequired- value={{ gatewayId, gatewayPoolId }}- onChange={(value) => {- setValue("gatewayId", value.gatewayId, { shouldDirty: true });- setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });- }}- />- </FieldContent>- </Field>+ <ConfigCard>+ <NameField control={control as unknown as Control<{ name: string }>} />+ <CredentialAccountField+ control={control as unknown as Control<{ credentialAccountId: string }>}+ />+ <GatewayField+ gatewayId={watch("gatewayId")}+ gatewayPoolId={watch("gatewayPoolId")}+ onChange={(value) => {+ setValue("gatewayId", value.gatewayId, { shouldDirty: true });+ setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });+ }}+ />+ <ScheduleField+ control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}+ />+ <DiscoveryConfigFields control={control as unknown as Control<TDiscoveryConfigFields>} />+ </ConfigCard>- <ScheduleField- control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}- />+ <div aria-hidden className="h-8 shrink-0" />+ {isDirty && <SheetSaveBar isPending={updateSource.isPending} onDiscard={() => reset()} />}+ </form>+ );+};- <DiscoveryConfigFields control={control as unknown as Control<TDiscoveryConfigFields>} />- </CardContent>- </Card>+const unixConfigSchema = z.object({+ name: z.string().min(1, "Name is required").max(64),+ schedule: z.nativeEnum(PamDiscoverySchedule),+ gatewayId: z.string().nullable(),+ gatewayPoolId: z.string().nullable(),+ ...unixDiscoveryConfigFormShape+});++const UnixConfigForm = ({+ source,+ onDirtyChange+}: {+ source: TPamDiscoverySource;+ onDirtyChange: (isDirty: boolean) => void;+}) => {+ const updateSource = useUpdatePamDiscoverySource();++ const defaults: z.infer<typeof unixConfigSchema> = {+ name: source.name,+ schedule: source.schedule,+ gatewayId: source.gatewayId ?? null,+ gatewayPoolId: source.gatewayPoolId ?? null,+ ...unixDiscoveryConfigFromSource(source.discoveryConfiguration)+ };++ const {+ control,+ handleSubmit,+ reset,+ watch,+ setValue,+ formState: { isDirty }+ } = useForm({ resolver: zodResolver(unixConfigSchema), defaultValues: defaults });++ useEffect(() => {+ onDirtyChange(isDirty);+ return () => onDirtyChange(false);+ }, [isDirty, onDirtyChange]);++ useEffect(() => {+ reset(defaults);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [source, reset]);++ const onSubmit = (data: z.infer<typeof unixConfigSchema>) => {+ updateSource.mutate(+ {+ sourceId: source.id,+ discoveryType: source.discoveryType,+ name: data.name,+ credentialAccountId: data.credentialAccountIds[0],+ schedule: data.schedule,+ gatewayId: data.gatewayId,+ gatewayPoolId: data.gatewayPoolId,+ configuration: buildUnixDiscoveryConfiguration(data)+ },+ { onSuccess: () => createNotification({ type: "success", text: "Discovery source updated" }) }+ );+ };++ return (+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-1 flex-col gap-4 p-4">+ <ConfigCard>+ <NameField control={control as unknown as Control<{ name: string }>} />+ <SshCredentialAccountsField+ control={control as unknown as Control<{ credentialAccountIds: string[] }>}+ />+ <GatewayField+ gatewayId={watch("gatewayId")}+ gatewayPoolId={watch("gatewayPoolId")}+ onChange={(value) => {+ setValue("gatewayId", value.gatewayId, { shouldDirty: true });+ setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });+ }}+ />+ <ScheduleField+ control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}+ />+ <UnixDiscoveryConfigFields+ control={control as unknown as Control<TUnixDiscoveryConfigFields>}+ />+ </ConfigCard><div aria-hidden className="h-8 shrink-0" />{isDirty && <SheetSaveBar isPending={updateSource.isPending} onDiscard={() => reset()} />}@@ -211,6 +317,19 @@ const ConfigurationTab = ({);};+const ConfigurationTab = ({+ source,+ onDirtyChange+}: {+ source: TPamDiscoverySource;+ onDirtyChange: (isDirty: boolean) => void;+}) =>+ source.discoveryType === PamDiscoveryType.Unix ? (+ <UnixConfigForm source={source} onDirtyChange={onDirtyChange} />+ ) : (+ <ActiveDirectoryConfigForm source={source} onDirtyChange={onDirtyChange} />+ );+type Props = {isOpen: boolean;sourceId?: string;