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): discovery
x513831afb227
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex ad8c731cb2..5fd66d83fd 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -37,6 +37,7 @@ import { TLicenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";import { TPamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";+import { TPamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { TPamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";import { TPamProjectResolverFactory } from "@app/ee/services/pam-project/pam-project-resolver";@@ -428,6 +429,7 @@ declare module "fastify" {pamAccountTemplate: TPamAccountTemplateServiceFactory;pamFolder: TPamFolderServiceFactory;pamAccount: TPamAccountServiceFactory;+ pamDiscovery: TPamDiscoverySourceServiceFactory;pamMembership: TPamMembershipServiceFactory;pamSession: TPamSessionServiceFactory;pamSessionChunk: TPamSessionChunkServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 9622f97917..f17e14f4bf 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -743,6 +743,11 @@ import {TPamAccountTemplatesUpdate} from "@app/db/schemas/pam-account-templates";import { TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate } from "@app/db/schemas/pam-accounts";+import {+ TPamDiscoveredAccounts,+ TPamDiscoveredAccountsInsert,+ TPamDiscoveredAccountsUpdate+} from "@app/db/schemas/pam-discovered-accounts";import {TPamDiscoverySourceAccounts,TPamDiscoverySourceAccountsInsert,@@ -1777,6 +1782,11 @@ declare module "knex/types/tables" {TPamDiscoverySourceRunsInsert,TPamDiscoverySourceRunsUpdate>;+ [TableName.PamDiscoveredAccount]: KnexOriginal.CompositeTableType<+ TPamDiscoveredAccounts,+ TPamDiscoveredAccountsInsert,+ TPamDiscoveredAccountsUpdate+ >;[TableName.PamDiscoverySourceResource]: KnexOriginal.CompositeTableType<TPamDiscoverySourceResources,TPamDiscoverySourceResourcesInsert,diff --git a/backend/src/db/migrations/20260701000000_pam-discovery.ts b/backend/src/db/migrations/20260701000000_pam-discovery.tsnew file mode 100644index 0000000000..f0f178405e--- /dev/null+++ b/backend/src/db/migrations/20260701000000_pam-discovery.ts@@ -0,0 +1,90 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ // PamDiscoverySource is a reused name. credentialAccountId only exists on the new schema, so its presence means we've already migrated+ const sourcesMigrated =+ (await knex.schema.hasTable(TableName.PamDiscoverySource)) &&+ (await knex.schema.hasColumn(TableName.PamDiscoverySource, "credentialAccountId"));++ if (!sourcesMigrated) {+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceDependency);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceAccount);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceResource);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceRun);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySource);++ await knex.schema.createTable(TableName.PamDiscoverySource, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.string("projectId").notNullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ t.string("name").notNullable();+ t.string("discoveryType").notNullable();+ t.uuid("gatewayId");+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");+ t.uuid("gatewayPoolId");+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("SET NULL");+ t.uuid("credentialAccountId").notNullable();+ t.foreign("credentialAccountId").references("id").inTable(TableName.PamAccount).onDelete("RESTRICT");+ t.jsonb("discoveryConfiguration").notNullable();+ t.string("schedule").notNullable().defaultTo("manual");+ t.timestamp("lastRunAt");+ t.timestamps(true, true, true);+ t.unique(["projectId", "name"]);+ t.index("projectId");+ t.index("gatewayId");+ t.index("gatewayPoolId");+ t.index("credentialAccountId");+ });+ await createOnUpdateTrigger(knex, TableName.PamDiscoverySource);+ }++ if (!(await knex.schema.hasTable(TableName.PamDiscoverySourceRun))) {+ await knex.schema.createTable(TableName.PamDiscoverySourceRun, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("discoverySourceId").notNullable();+ t.foreign("discoverySourceId").references("id").inTable(TableName.PamDiscoverySource).onDelete("CASCADE");+ t.string("status").notNullable();+ t.string("triggeredBy").notNullable();+ t.integer("discoveredCount").notNullable().defaultTo(0);+ t.integer("newCount").notNullable().defaultTo(0);+ t.text("errorMessage");+ t.timestamp("startedAt");+ t.timestamp("completedAt");+ t.timestamps(true, true, true);+ t.index("discoverySourceId");+ });+ await createOnUpdateTrigger(knex, TableName.PamDiscoverySourceRun);+ }++ if (!(await knex.schema.hasTable(TableName.PamDiscoveredAccount))) {+ await knex.schema.createTable(TableName.PamDiscoveredAccount, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("discoverySourceId").notNullable();+ t.foreign("discoverySourceId").references("id").inTable(TableName.PamDiscoverySource).onDelete("CASCADE");+ t.string("accountType").notNullable();+ t.string("name").notNullable();+ t.string("fingerprint").notNullable();+ t.binary("encryptedDetails").notNullable();+ t.uuid("importedAccountId");+ t.foreign("importedAccountId").references("id").inTable(TableName.PamAccount).onDelete("SET NULL");+ t.timestamps(true, true, true);+ t.unique(["discoverySourceId", "fingerprint"]);+ t.index("discoverySourceId");+ t.index("importedAccountId");+ });+ await createOnUpdateTrigger(knex, TableName.PamDiscoveredAccount);+ }+}++export async function down(knex: Knex): Promise<void> {+ // Only drops the tables this migration created, so it's not a 100% restore+ await dropOnUpdateTrigger(knex, TableName.PamDiscoveredAccount);+ await knex.schema.dropTableIfExists(TableName.PamDiscoveredAccount);+ await dropOnUpdateTrigger(knex, TableName.PamDiscoverySourceRun);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceRun);+ await dropOnUpdateTrigger(knex, TableName.PamDiscoverySource);+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySource);+}diff --git a/backend/src/db/migrations/20260703120000_pam-discovery-run-machine-errors.ts b/backend/src/db/migrations/20260703120000_pam-discovery-run-machine-errors.tsnew file mode 100644index 0000000000..c754aac14d--- /dev/null+++ b/backend/src/db/migrations/20260703120000_pam-discovery-run-machine-errors.ts@@ -0,0 +1,19 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.PamDiscoverySourceRun, "machineErrors"))) {+ await knex.schema.alterTable(TableName.PamDiscoverySourceRun, (t) => {+ t.jsonb("machineErrors");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.PamDiscoverySourceRun, "machineErrors")) {+ await knex.schema.alterTable(TableName.PamDiscoverySourceRun, (t) => {+ t.dropColumn("machineErrors");+ });+ }+}diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 18920e7df1..3fb78abdbe 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -130,6 +130,7 @@ export * from "./pam-account-dependencies";export * from "./pam-account-policies";export * from "./pam-account-templates";export * from "./pam-accounts";+export * from "./pam-discovered-accounts";export * from "./pam-discovery-source-accounts";export * from "./pam-discovery-source-dependencies";export * from "./pam-discovery-source-resources";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex c976fc04d9..aa8c9eb94c 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -245,6 +245,7 @@ export enum TableName {PamProjectRecordingConfig = "pam_project_recording_configs",PamDiscoverySource = "pam_discovery_sources",PamDiscoverySourceRun = "pam_discovery_source_runs",+ PamDiscoveredAccount = "pam_discovered_accounts",PamDiscoverySourceResource = "pam_discovery_source_resources",PamDiscoverySourceAccount = "pam_discovery_source_accounts",PamDiscoverySourceDependency = "pam_discovery_source_dependencies",diff --git a/backend/src/db/schemas/pam-discovered-accounts.ts b/backend/src/db/schemas/pam-discovered-accounts.tsnew file mode 100644index 0000000000..983d4b6e37--- /dev/null+++ b/backend/src/db/schemas/pam-discovered-accounts.ts@@ -0,0 +1,26 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const PamDiscoveredAccountsSchema = z.object({+ id: z.string().uuid(),+ discoverySourceId: z.string().uuid(),+ accountType: z.string(),+ name: z.string(),+ fingerprint: z.string(),+ encryptedDetails: zodBuffer,+ importedAccountId: z.string().uuid().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPamDiscoveredAccounts = z.infer<typeof PamDiscoveredAccountsSchema>;+export type TPamDiscoveredAccountsInsert = Omit<z.input<typeof PamDiscoveredAccountsSchema>, TImmutableDBKeys>;+export type TPamDiscoveredAccountsUpdate = Partial<Omit<z.input<typeof PamDiscoveredAccountsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/pam-discovery-source-runs.ts b/backend/src/db/schemas/pam-discovery-source-runs.tsindex caf1353697..fd34cfccfa 100644--- a/backend/src/db/schemas/pam-discovery-source-runs.ts+++ b/backend/src/db/schemas/pam-discovery-source-runs.ts@@ -12,21 +12,14 @@ export const PamDiscoverySourceRunsSchema = z.object({discoverySourceId: z.string().uuid(),status: z.string(),triggeredBy: z.string(),- resourcesDiscoveredCount: z.number().default(0).nullable().optional(),- accountsDiscoveredCount: z.number().default(0).nullable().optional(),- dependenciesDiscoveredCount: z.number().default(0).nullable().optional(),- newResourcesCount: z.number().default(0).nullable().optional(),- staleResourcesCount: z.number().default(0).nullable().optional(),- newAccountsCount: z.number().default(0).nullable().optional(),- staleAccountsCount: z.number().default(0).nullable().optional(),- newDependenciesCount: z.number().default(0).nullable().optional(),- staleDependenciesCount: z.number().default(0).nullable().optional(),- progress: z.unknown(),+ discoveredCount: z.number().default(0),+ newCount: z.number().default(0),errorMessage: z.string().nullable().optional(),startedAt: z.date().nullable().optional(),completedAt: z.date().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ machineErrors: z.unknown().nullable().optional()});export type TPamDiscoverySourceRuns = z.infer<typeof PamDiscoverySourceRunsSchema>;diff --git a/backend/src/db/schemas/pam-discovery-sources.ts b/backend/src/db/schemas/pam-discovery-sources.tsindex 722b2a98d7..7b646b5c52 100644--- a/backend/src/db/schemas/pam-discovery-sources.ts+++ b/backend/src/db/schemas/pam-discovery-sources.ts@@ -5,8 +5,6 @@import { z } from "zod";-import { zodBuffer } from "@app/lib/zod";-import { TImmutableDBKeys } from "./models";export const PamDiscoverySourcesSchema = z.object({@@ -15,14 +13,13 @@ export const PamDiscoverySourcesSchema = z.object({name: z.string(),discoveryType: z.string(),gatewayId: z.string().uuid().nullable().optional(),- encryptedDiscoveryCredentials: zodBuffer,+ gatewayPoolId: z.string().uuid().nullable().optional(),+ credentialAccountId: z.string().uuid(),discoveryConfiguration: z.unknown(),schedule: z.string().default("manual"),lastRunAt: z.date().nullable().optional(),- status: z.string().default("active"),createdAt: z.date(),- updatedAt: z.date(),- gatewayPoolId: z.string().uuid().nullable().optional()+ updatedAt: z.date()});export type TPamDiscoverySources = z.infer<typeof PamDiscoverySourcesSchema>;diff --git a/backend/src/ee/routes/v1/pam-routers/index.ts b/backend/src/ee/routes/v1/pam-routers/index.tsindex 8294ee96b5..b026653695 100644--- a/backend/src/ee/routes/v1/pam-routers/index.ts+++ b/backend/src/ee/routes/v1/pam-routers/index.ts@@ -1,5 +1,6 @@import { registerPamAccountRouter } from "./pam-account-router";import { registerPamAccountTemplateRouter } from "./pam-account-template-router";+import { registerPamDiscoveryRouter } from "./pam-discovery-router";import { registerPamFolderRouter } from "./pam-folder-router";import {registerPamAccountMembershipRouter,@@ -17,6 +18,7 @@ export const registerPamRouters = async (server: FastifyZodProvider) => {await server.register(registerPamAccountRouter, { prefix: "/accounts" });await server.register(registerPamAccountMembershipRouter, { prefix: "/accounts" });await server.register(registerPamWebAccessRouter, { prefix: "/accounts" });+ await server.register(registerPamDiscoveryRouter, { prefix: "/discovery-sources" });await server.register(registerPamProductMembershipRouter, { prefix: "/memberships" });await server.register(registerPamResourceRoleRouter, { prefix: "/roles" });await server.register(registerPamSessionRouter, { prefix: "/sessions" });diff --git a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.tsnew file mode 100644index 0000000000..6fc2022148--- /dev/null+++ b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts@@ -0,0 +1,455 @@+import { z } from "zod";++import { PamDiscoverySourceRunsSchema, PamDiscoverySourcesSchema } from "@app/db/schemas";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { PamDiscoverySchedule } from "@app/ee/services/pam-discovery/pam-discovery-enums";+import {+ buildPamDiscoveryTypeMetadata,+ DISCOVERY_TYPE_CONFIGS,+ PamDiscoveryTypeMetadataSchema+} from "@app/ee/services/pam-discovery/pam-discovery-schemas";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { slugSchema } from "@app/server/lib/schemas";+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";+import { withRoutePrefix } from "@app/server/lib/with-route-prefix";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++type TSupportedConfigs = typeof DISCOVERY_TYPE_CONFIGS;+type TSupportedDiscoveryType = keyof TSupportedConfigs;++const SourceSchema = PamDiscoverySourcesSchema.extend({+ lastRunStatus: z.string().nullable().optional(),+ lastRunError: z.string().nullable().optional()+});++const DiscoveredAccountSchema = z.object({+ id: z.string(),+ accountType: z.string(),+ name: z.string(),+ fingerprint: z.string(),+ createdAt: z.date()+});++const toPascalCase = (s: string) =>+ s+ .split("-")+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join("");++const registerPerTypeEndpoints = (+ server: FastifyZodProvider,+ discoveryType: TSupportedDiscoveryType,+ config: TSupportedConfigs[TSupportedDiscoveryType]+) => {+ const typeId = toPascalCase(discoveryType);++ server.route({+ method: "POST",+ url: "/",+ schema: {+ operationId: `create${typeId}PamDiscoverySource`,+ description: `Create a new ${discoveryType} PAM discovery source`,+ tags: [ApiDocsTags.PamAccounts],+ body: z.object({+ name: slugSchema({ field: "Name" }),+ credentialAccountId: z.string().uuid().describe("The PAM account used to authenticate and scan"),+ gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional(),+ schedule: z.nativeEnum(PamDiscoverySchedule).default(PamDiscoverySchedule.Manual),+ configuration: config.configuration.optional()+ }),+ response: { 200: z.object({ source: SourceSchema }) }+ },+ config: { rateLimit: writeLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const source = await server.services.pamDiscovery.create({+ discoveryType,+ name: req.body.name,+ credentialAccountId: req.body.credentialAccountId,+ gatewayId: req.body.gatewayId,+ gatewayPoolId: req.body.gatewayPoolId,+ schedule: req.body.schedule,+ configuration: req.body.configuration ?? {},+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: {+ type: EventType.PAM_DISCOVERY_SOURCE_CREATE,+ metadata: { sourceId: source.id, discoveryType, name: req.body.name }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamDiscoverySourceCreated,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { discoveryType, orgId: req.permission.orgId }+ })+ .catch(() => {});++ return { source };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:sourceId",+ schema: {+ operationId: `update${typeId}PamDiscoverySource`,+ description: `Update a ${discoveryType} PAM discovery source`,+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ body: z.object({+ name: slugSchema({ field: "Name" }).optional(),+ credentialAccountId: z.string().uuid().optional(),+ gatewayId: z.string().uuid().nullable().optional(),+ gatewayPoolId: z.string().uuid().nullable().optional(),+ schedule: z.nativeEnum(PamDiscoverySchedule).optional(),+ configuration: config.configuration.optional()+ }),+ response: { 200: z.object({ source: SourceSchema }) }+ },+ config: { rateLimit: writeLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const source = await server.services.pamDiscovery.update({+ sourceId: req.params.sourceId,+ discoveryType,+ ...req.body,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: {+ type: EventType.PAM_DISCOVERY_SOURCE_UPDATE,+ metadata: { sourceId: source.id, discoveryType }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamDiscoverySourceUpdated,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { discoveryType, orgId: req.permission.orgId }+ })+ .catch(() => {});++ return { source };+ }+ });++ server.route({+ method: "GET",+ url: "/:sourceId",+ schema: {+ operationId: `get${typeId}PamDiscoverySource`,+ description: `Get a ${discoveryType} PAM discovery source`,+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ response: { 200: z.object({ source: SourceSchema }) }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const source = await server.services.pamDiscovery.getById({+ sourceId: req.params.sourceId,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ return { source };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:sourceId",+ schema: {+ operationId: `delete${typeId}PamDiscoverySource`,+ description: `Delete a ${discoveryType} PAM discovery source`,+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ response: { 200: z.object({ source: SourceSchema }) }+ },+ config: { rateLimit: writeLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const source = await server.services.pamDiscovery.deleteSource({+ sourceId: req.params.sourceId,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: {+ type: EventType.PAM_DISCOVERY_SOURCE_DELETE,+ metadata: { sourceId: source.id, discoveryType }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamDiscoverySourceDeleted,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { discoveryType, orgId: req.permission.orgId }+ })+ .catch(() => {});++ return { source };+ }+ });++ server.route({+ method: "POST",+ url: "/:sourceId/scan",+ schema: {+ operationId: `scan${typeId}PamDiscoverySource`,+ description: `Trigger a scan for a ${discoveryType} PAM discovery source`,+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ response: { 200: z.object({ message: z.string() }) }+ },+ config: { rateLimit: writeLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.pamDiscovery.triggerScan({+ sourceId: req.params.sourceId,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: {+ type: EventType.PAM_DISCOVERY_SCAN,+ metadata: { sourceId: req.params.sourceId, discoveryType }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamDiscoveryScanTriggered,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { discoveryType, orgId: req.permission.orgId }+ })+ .catch(() => {});++ return result;+ }+ });+};++export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/options",+ schema: {+ operationId: "listPamDiscoveryTypes",+ description: "List supported PAM discovery source types",+ tags: [ApiDocsTags.PamAccounts],+ response: { 200: z.object({ discoveryTypes: z.array(PamDiscoveryTypeMetadataSchema) }) }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async () => ({ discoveryTypes: buildPamDiscoveryTypeMetadata() })+ });++ server.route({+ method: "GET",+ url: "/",+ schema: {+ operationId: "listPamDiscoverySources",+ description: "List PAM discovery sources",+ tags: [ApiDocsTags.PamAccounts],+ querystring: z.object({ search: z.string().optional() }),+ response: { 200: z.object({ sources: z.array(SourceSchema) }) }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const sources = await server.services.pamDiscovery.list({+ projectId: req.internalPamProjectId,+ search: req.query.search,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ return { sources };+ }+ });++ server.route({+ method: "GET",+ url: "/:sourceId/runs",+ schema: {+ operationId: "listPamDiscoveryRuns",+ description: "List scan runs for a PAM discovery source",+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ querystring: z.object({+ offset: z.coerce.number().min(0).default(0).optional(),+ limit: z.coerce.number().min(1).max(100).default(20).optional()+ }),+ response: { 200: z.object({ runs: z.array(PamDiscoverySourceRunsSchema) }) }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const runs = await server.services.pamDiscovery.listRuns({+ sourceId: req.params.sourceId,+ projectId: req.internalPamProjectId,+ offset: req.query.offset,+ limit: req.query.limit,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ return { runs };+ }+ });++ server.route({+ method: "GET",+ url: "/:sourceId/discovered",+ schema: {+ operationId: "listPamDiscoveredAccounts",+ description: "List staged accounts discovered by a PAM discovery source",+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ querystring: z.object({ search: z.string().optional() }),+ response: { 200: z.object({ discoveredAccounts: z.array(DiscoveredAccountSchema) }) }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const discoveredAccounts = await server.services.pamDiscovery.listDiscovered({+ sourceId: req.params.sourceId,+ projectId: req.internalPamProjectId,+ search: req.query.search,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });+ return { discoveredAccounts };+ }+ });++ server.route({+ method: "POST",+ url: "/:sourceId/discovered/import",+ schema: {+ operationId: "importPamDiscoveredAccounts",+ description: "Import staged accounts into a folder",+ tags: [ApiDocsTags.PamAccounts],+ params: z.object({ sourceId: z.string().uuid() }),+ body: z.object({+ folderId: z.string().uuid(),+ accounts: z+ .object({+ discoveredAccountId: z.string().uuid(),+ templateId: z.string().uuid(),+ name: slugSchema({ field: "Name" }).optional()+ })+ .array()+ .min(1)+ }),+ response: {+ 200: z.object({+ results: z+ .object({+ discoveredAccountId: z.string(),+ status: z.string(),+ accountId: z.string().optional(),+ message: z.string().optional()+ })+ .array()+ })+ }+ },+ config: { rateLimit: writeLimit },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { results } = await server.services.pamDiscovery.importAccounts({+ sourceId: req.params.sourceId,+ folderId: req.body.folderId,+ accounts: req.body.accounts,+ projectId: req.internalPamProjectId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorOrgId: req.permission.orgId,+ actorAuthMethod: req.permission.authMethod+ });++ const importedCount = results.filter((r) => r.status === "imported").length;++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: {+ type: EventType.PAM_DISCOVERED_ACCOUNT_IMPORT,+ metadata: { sourceId: req.params.sourceId, folderId: req.body.folderId, importedCount }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.PamDiscoveredAccountsImported,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { orgId: req.permission.orgId, importedCount }+ })+ .catch(() => {});++ return { results };+ }+ });++ await server.register(async (typeRouter) => {+ for (const [discoveryType, config] of Object.entries(DISCOVERY_TYPE_CONFIGS) as [+ TSupportedDiscoveryType,+ TSupportedConfigs[TSupportedDiscoveryType]+ ][]) {+ registerPerTypeEndpoints(withRoutePrefix(typeRouter, `/${discoveryType}`), discoveryType, config);+ }+ });+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex cebdf472ab..71f582d39f 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -737,6 +737,11 @@ export enum EventType {PAM_ACCOUNT_UPDATE = "pam-account-update",PAM_ACCOUNT_DELETE = "pam-account-delete",PAM_ACCOUNT_SSH_CA_CREATE = "pam-account-ssh-ca-create",+ PAM_DISCOVERY_SOURCE_CREATE = "pam-discovery-source-create",+ PAM_DISCOVERY_SOURCE_UPDATE = "pam-discovery-source-update",+ PAM_DISCOVERY_SOURCE_DELETE = "pam-discovery-source-delete",+ PAM_DISCOVERY_SCAN = "pam-discovery-scan",+ PAM_DISCOVERED_ACCOUNT_IMPORT = "pam-discovered-account-import",PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",APPROVAL_POLICY_CREATE = "approval-policy-create",APPROVAL_POLICY_UPDATE = "approval-policy-update",@@ -6082,6 +6087,31 @@ interface PamAccountSshCaCreateEvent {};}+interface PamDiscoverySourceCreateEvent {+ type: EventType.PAM_DISCOVERY_SOURCE_CREATE;+ metadata: { sourceId: string; discoveryType: string; name: string };+}++interface PamDiscoverySourceUpdateEvent {+ type: EventType.PAM_DISCOVERY_SOURCE_UPDATE;+ metadata: { sourceId: string; discoveryType: string };+}++interface PamDiscoverySourceDeleteEvent {+ type: EventType.PAM_DISCOVERY_SOURCE_DELETE;+ metadata: { sourceId: string; discoveryType: string };+}++interface PamDiscoveryScanEvent {+ type: EventType.PAM_DISCOVERY_SCAN;+ metadata: { sourceId: string; discoveryType: string };+}++interface PamDiscoveredAccountImportEvent {+ type: EventType.PAM_DISCOVERED_ACCOUNT_IMPORT;+ metadata: { sourceId: string; folderId: string; importedCount: number };+}+interface UpdateCertificateRenewalConfigEvent {type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG;metadata: {@@ -7690,6 +7720,11 @@ export type Event =| PamAccountUpdateEvent| PamAccountDeleteEvent| PamAccountSshCaCreateEvent+ | PamDiscoverySourceCreateEvent+ | PamDiscoverySourceUpdateEvent+ | PamDiscoverySourceDeleteEvent+ | PamDiscoveryScanEvent+ | PamDiscoveredAccountImportEvent| UpdateCertificateRenewalConfigEvent| UpdateCertificateMetadataEvent| DisableCertificateRenewalConfigEventdiff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.tsindex a46f8aa7db..3a258c544f 100644--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts@@ -648,6 +648,22 @@ export const buildSessionGatewayConnectionDetails = (return validated;};+// A username already carries its domain if it's NT4 (`DOMAIN\user`) or UPN (`user@domain`)+export const isDomainQualifiedUsername = (username: string) => username.includes("\\") || username.includes("@");++// Domain-qualifies a bare username to `NETBIOS\user` for RDP/NLA; already-qualified forms pass through+export const qualifyUsernameWithDomain = (username: string, domainFqdn: string) => {+ if (isDomainQualifiedUsername(username)) return username;+ return `${domainFqdn.split(".")[0].toUpperCase()}\\${username}`;+};++// Normalizes any form to a NetBIOS `DOMAIN\user` login+export const toNetbiosUsername = (username: string, domainFqdn: string) => {+ if (username.includes("\\")) return username;+ const localPart = username.includes("@") ? username.split("@")[0] : username;+ return `${domainFqdn.split(".")[0].toUpperCase()}\\${localPart}`;+};+// -- Account accessibilityexport enum PamAccountAccessibilityIssue {diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 14e19d37a2..352bdbc005 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -423,24 +423,37 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>ctx);- return pamAccountDAL.transaction(async (tx) => {- const memberships = await membershipDAL.find(- {- scope: RESOURCE_SCOPE,- scopeResourceType: ResourceType.PamAccount,- scopeResourceId: accountId- },- { tx }- );-- if (memberships.length > 0) {- const ids = memberships.map((m) => m.id);- await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);- await membershipDAL.delete({ $in: { id: ids } }, tx);- }+ try {+ return await pamAccountDAL.transaction(async (tx) => {+ const memberships = await membershipDAL.find(+ {+ scope: RESOURCE_SCOPE,+ scopeResourceType: ResourceType.PamAccount,+ scopeResourceId: accountId+ },+ { tx }+ );++ if (memberships.length > 0) {+ const ids = memberships.map((m) => m.id);+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);+ await membershipDAL.delete({ $in: { id: ids } }, tx);+ }- return pamAccountDAL.deleteById(accountId, tx);- });+ return pamAccountDAL.deleteById(accountId, tx);+ });+ } catch (err) {+ // The only restricting reference to an account is a discovery source using it as its credential+ if (+ err instanceof DatabaseError &&+ (err.error as { code?: string })?.code === DatabaseErrorCode.ForeignKeyViolation+ ) {+ throw new BadRequestError({+ message: "This account is used as the credential for a discovery source. Delete that source first."+ });+ }+ throw err;+ }};const listAccessible = async ({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.tsnew file mode 100644index 0000000000..efe430e381--- /dev/null+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts@@ -0,0 +1,358 @@+import net from "node:net";++import ldapjs from "@infisical/ldapjs";+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 {+ TDiscoveredAccount,+ TDiscoveryMachineError,+ TDiscoveryScanResult,+ TPamDiscoveryFactory+} from "../pam-discovery-types";+import { resolveDnsTcp } from "./dns-over-dc";++const LDAP_TIMEOUT = 30 * 1000;+const LDAP_PAGE_SIZE = 500;++type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+type TLdapAttribute = { type: string; values: string[]; buffers: Buffer[] };+type TLdapComputer = { cn: string; dNSHostName: string; objectGUID: string; resolvedIp?: string };+type TLdapUser = { sAMAccountName: string; objectGUID: string };+type TWinRmLocalUser = { Name: string };++const buildDomainDN = (domainFqdn: string) =>+ domainFqdn+ .split(".")+ .map((part) => `DC=${part}`)+ .join(",");++const parseObjectGUID = (buf: Buffer | undefined): string => {+ if (buf && buf.length === 16) {+ const hex = buf.toString("hex");+ return [+ hex.substring(6, 8) + hex.substring(4, 6) + hex.substring(2, 4) + hex.substring(0, 2),+ hex.substring(10, 12) + hex.substring(8, 10),+ hex.substring(14, 16) + hex.substring(12, 14),+ hex.substring(16, 20),+ hex.substring(20, 32)+ ].join("-");+ }+ return "";+};++const getAttr = (entry: ldapjs.SearchEntry, name: string): string =>+ (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(+ (a) => a.type.toLowerCase() === name.toLowerCase()+ )?.values?.[0] ?? "";++const getAttrBuffer = (entry: ldapjs.SearchEntry, name: string): Buffer | undefined =>+ (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(+ (a) => a.type.toLowerCase() === name.toLowerCase()+ )?.buffers?.[0];++const ldapSearch = (client: ldapjs.Client, baseDN: string, filter: string, attributes: string[]) =>+ new Promise<ldapjs.SearchEntry[]>((resolve, reject) => {+ const results: ldapjs.SearchEntry[] = [];+ client.search(+ baseDN,+ { filter, scope: "sub", attributes, paged: { pageSize: LDAP_PAGE_SIZE }, timeLimit: LDAP_TIMEOUT / 1000 },+ (err, res) => {+ if (err) return reject(err);+ res.on("searchEntry", (entry) => results.push(entry));+ res.on("error", reject);+ res.on("end", (result) =>+ result?.status !== 0+ ? reject(new Error(`LDAP search failed with status ${result?.status}`))+ : resolve(results)+ );+ }+ );+ });++type TAdConnection = {+ domain: string;+ dcAddress: string;+ port: number;+ rdpPort: number;+ useLdaps: boolean;+ ldapRejectUnauthorized: boolean;+ ldapCaCert?: string;+ ldapTlsServerName?: string;+ username: string;+};++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 },+ gatewayId: string,+ gatewayV2Service: TGatewayDep,+ operation: (client: ldapjs.Client) => Promise<T>+): Promise<T> =>+ executeWithGateway(conn.dcAddress, conn.port, gatewayId, gatewayV2Service, async (proxyPort) => {+ const client = ldapjs.createClient({+ url: `${conn.useLdaps ? "ldaps" : "ldap"}://localhost:${proxyPort}`,+ connectTimeout: LDAP_TIMEOUT,+ timeout: LDAP_TIMEOUT,+ ...(conn.useLdaps && {+ tlsOptions: {+ rejectUnauthorized: conn.ldapRejectUnauthorized,+ ...(conn.ldapCaCert && { ca: [conn.ldapCaCert], servername: conn.ldapTlsServerName || conn.dcAddress })+ }+ })+ });++ // Unhandled 'error' events (e.g. TLS mismatch) would crash the process, so capture them+ let clientError: Error | null = null;+ client.on("error", (err: Error) => {+ clientError = err;+ });++ try {+ const bindDn = isDomainQualifiedUsername(conn.username) ? conn.username : `${conn.username}@${conn.domain}`;+ await new Promise<void>((resolve, reject) => {+ client.bind(bindDn, credentials.password ?? "", (err) => {+ if (clientError) reject(clientError);+ else if (err) reject(new Error(`LDAP bind failed: ${err.message}`));+ else resolve();+ });+ });+ return await operation(client);+ } finally {+ try {+ client.unbind();+ } catch {+ // client may already be destroyed+ }+ }+ });++// Resolve each server's hostname to an IP via the DC's DNS so the gateway can reach it for WinRM+const resolveHostnamesViaDc = (+ computers: TLdapComputer[],+ conn: TAdConnection,+ gatewayId: string,+ gatewayV2Service: TGatewayDep+): Promise<void> =>+ executeWithGateway(conn.dcAddress, 53, gatewayId, gatewayV2Service, async (proxyPort) => {+ for (const computer of computers) {+ const hostname = computer.dNSHostName || computer.cn;+ if (!hostname) {+ // no hostname to resolve+ } else if (net.isIP(hostname)) {+ computer.resolvedIp = hostname;+ } else {+ try {+ // eslint-disable-next-line no-await-in-loop+ const ip = await resolveDnsTcp(hostname, proxyPort);+ if (ip) computer.resolvedIp = ip;+ } catch (err) {+ logger.warn(err, `PAM AD discovery failed to resolve hostname [hostname=${hostname}]`);+ }+ }+ }+ });++const enumerateLocalUsers = (+ computer: TLdapComputer,+ conn: TAdConnection,+ password: string,+ winrm: TWinrmConfig,+ gatewayId: string,+ gatewayV2Service: TGatewayDep+): Promise<TWinRmLocalUser[]> => {+ const hostname = computer.dNSHostName || computer.cn;+ const targetAddress = computer.resolvedIp || hostname;++ return executeWithGateway(targetAddress, winrm.port, gatewayId, gatewayV2Service, async (proxyPort) => {+ const winrmUsername = toNetbiosUsername(conn.username, conn.domain);+ const script =+ "Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, Description, SID | ConvertTo-Json";++ const stdout = await runPowershell(+ script,+ "localhost",+ winrmUsername,+ password,+ proxyPort,+ winrm.useHttps,+ winrm.rejectUnauthorized,+ winrm.caCert,+ hostname+ );++ if (!stdout.trim()) return [];+ const parsed = JSON.parse(stdout) as TWinRmLocalUser | TWinRmLocalUser[];+ return Array.isArray(parsed) ? parsed : [parsed];+ });+};++export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({+ gatewayId,+ configuration,+ credentialAccount,+ gatewayV2Service+}) => {+ const connectionDetails = credentialAccount.connectionDetails as unknown as {+ domain: string;+ dcAddress: string;+ port: number;+ rdpPort: number;+ useLdaps: boolean;+ ldapRejectUnauthorized: boolean;+ ldapCaCert?: string;+ ldapTlsServerName?: string;+ };+ const credentials = credentialAccount.credentials as { username: string; password?: string };+ const conn: TAdConnection = { ...connectionDetails, username: credentials.username };+ const config = configuration as {+ scanLocalAccounts?: boolean;+ winrmPort?: number;+ useWinrmHttps?: boolean;+ winrmRejectUnauthorized?: boolean;+ winrmCaCert?: string;+ };++ const validateConnection = async () => {+ await runLdap(conn, credentials, gatewayId, gatewayV2Service, async () => undefined).catch((err) => {+ throw new BadRequestError({+ message: `Unable to connect to Active Directory: ${err instanceof Error ? err.message : "unknown error"}`+ });+ });+ };++ const scan = async (): Promise<TDiscoveryScanResult> => {+ const domain = connectionDetails.domain.toLowerCase();+ const baseDN = buildDomainDN(connectionDetails.domain);+ const machineErrors: TDiscoveryMachineError[] = [];++ const { users, computers } = await runLdap<{ users: TLdapUser[]; computers: TLdapComputer[] }>(+ conn,+ credentials,+ gatewayId,+ gatewayV2Service,+ async (client) => {+ const userEntries = await ldapSearch(client, baseDN, "(&(objectClass=user)(objectCategory=person))", [+ "sAMAccountName",+ "objectGUID"+ ]);+ const parsedUsers = userEntries+ .map((entry) => ({+ sAMAccountName: getAttr(entry, "sAMAccountName"),+ objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))+ }))+ .filter((u) => u.sAMAccountName && u.objectGUID);++ if (!config.scanLocalAccounts) return { users: parsedUsers, computers: [] as TLdapComputer[] };++ const computerEntries = await ldapSearch(+ client,+ baseDN,+ "(&(objectClass=computer)(operatingSystem=*Server*))",+ ["cn", "dNSHostName", "objectGUID"]+ );+ const parsedComputers = computerEntries+ .map((entry) => ({+ cn: getAttr(entry, "cn"),+ dNSHostName: getAttr(entry, "dNSHostName"),+ objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))+ }))+ .filter((c) => (c.dNSHostName || c.cn) && c.objectGUID);++ return { users: parsedUsers, computers: parsedComputers };+ }+ );++ logger.info(+ `PAM AD discovery enumerated ${users.length} domain accounts and ${computers.length} servers [domain=${domain}]`+ );++ // Domain accounts inherit the source's connection target; only the login user differs+ const discovered: TDiscoveredAccount[] = users.map((u) => ({+ accountType: PamAccountType.WindowsAd,+ name: u.sAMAccountName.toLowerCase(),+ fingerprint: `${domain}:${u.objectGUID}`,+ details: { connectionDetails, credentials: { username: u.sAMAccountName } }+ }));++ if (config.scanLocalAccounts && computers.length > 0) {+ await resolveHostnamesViaDc(computers, conn, gatewayId, gatewayV2Service);++ const winrm: TWinrmConfig = {+ port: config.winrmPort ?? 5985,+ useHttps: config.useWinrmHttps ?? false,+ rejectUnauthorized: config.winrmRejectUnauthorized ?? true,+ caCert: config.winrmCaCert+ };++ for (const computer of computers) {+ const host = computer.resolvedIp || computer.dNSHostName || computer.cn;+ try {+ // eslint-disable-next-line no-await-in-loop+ const localUsers = await enumerateLocalUsers(+ computer,+ conn,+ credentials.password ?? "",+ winrm,+ gatewayId,+ gatewayV2Service+ );++ for (const u of localUsers.filter((lu) => lu.Name)) {+ discovered.push({+ accountType: PamAccountType.Windows,+ name: u.Name.toLowerCase(),+ fingerprint: `${domain}:${computer.objectGUID}:${u.Name.toLowerCase()}`,+ details: {+ connectionDetails: { host, port: connectionDetails.rdpPort },+ credentials: { username: u.Name }+ }+ });+ }+ } catch (err) {+ const message = err instanceof Error ? err.message : "WinRM enumeration failed";+ logger.warn(err, `PAM AD discovery failed to enumerate local accounts [host=${host}]`);+ machineErrors.push({ machine: host, error: message });+ }+ }+ }++ return { accounts: discovered, machineErrors };+ };++ return { validateConnection, scan };+};diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.tsnew file mode 100644index 0000000000..bdae950eb3--- /dev/null+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts@@ -0,0 +1,9 @@+import { z } from "zod";++export const ActiveDirectoryDiscoveryConfigSchema = z.object({+ scanLocalAccounts: z.boolean().default(true),+ winrmPort: z.coerce.number().int().min(1).max(65535).default(5985),+ useWinrmHttps: z.boolean().default(false),+ winrmRejectUnauthorized: z.boolean().default(true),+ winrmCaCert: z.string().trim().optional()+});diff --git a/backend/src/ee/services/pam-discovery/active-directory/dns-over-dc.ts b/backend/src/ee/services/pam-discovery/active-directory/dns-over-dc.tsnew file mode 100644index 0000000000..f4bde5f2b3--- /dev/null+++ b/backend/src/ee/services/pam-discovery/active-directory/dns-over-dc.ts@@ -0,0 +1,60 @@+import net from "node:net";++import * as dnsPacket from "dns-packet";++// Resolve a hostname to an IP via DNS-over-TCP through a local proxy port+export const resolveDnsTcp = (hostname: string, proxyPort: number): Promise<string | null> => {+ return new Promise((resolve) => {+ const query = dnsPacket.streamEncode({+ type: "query",+ flags: dnsPacket.RECURSION_DESIRED,+ questions: [{ type: "A", name: hostname }]+ });++ const socket = net.connect({ host: "127.0.0.1", port: proxyPort }, () => {+ socket.write(query);+ });++ const MAX_DNS_TCP_SIZE = 2 + 65535;+ let responseData = Buffer.alloc(0);++ socket.on("data", (chunk: Buffer) => {+ responseData = Buffer.concat([responseData, chunk]);++ if (responseData.length > MAX_DNS_TCP_SIZE) {+ socket.destroy();+ resolve(null);+ return;+ }++ if (responseData.length >= 2) {+ const msgLen = responseData.readUInt16BE(0);+ if (responseData.length >= 2 + msgLen) {+ try {+ const response = dnsPacket.streamDecode(responseData);+ const aRecord = response.answers?.find((a) => a.type === "A");+ socket.destroy();+ resolve(aRecord && "data" in aRecord ? (aRecord.data as string) : null);+ } catch {+ socket.destroy();+ resolve(null);+ }+ }+ }+ });++ socket.on("error", () => {+ resolve(null);+ });++ // Peer may close before a full message arrives; resolve now instead of waiting for the timeout+ socket.on("close", () => {+ resolve(null);+ });++ socket.setTimeout(5000, () => {+ socket.destroy();+ resolve(null);+ });+ });+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.tsnew file mode 100644index 0000000000..2762dbe926--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts@@ -0,0 +1,38 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TPamDiscoveredAccountDALFactory = ReturnType<typeof pamDiscoveredAccountDALFactory>;++export const pamDiscoveredAccountDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamDiscoveredAccount);++ const upsertByFingerprint = async (+ discoverySourceId: string,+ fingerprint: string,+ data: { accountType: string; name: string; encryptedDetails: Buffer },+ tx?: Knex+ ): Promise<{ isNew: boolean }> => {+ const existing = await (tx || db)(TableName.PamDiscoveredAccount).where({ discoverySourceId, fingerprint }).first();+ if (existing) {+ if (existing.importedAccountId) return { isNew: false };+ await (tx || db)(TableName.PamDiscoveredAccount).where({ id: existing.id }).update(data);+ return { isNew: false };+ }+ await (tx || db)(TableName.PamDiscoveredAccount).insert({ discoverySourceId, fingerprint, ...data });+ return { isNew: true };+ };++ const listStaged = async (discoverySourceId: string, search?: string) => {+ const query = db+ .replicaNode()(TableName.PamDiscoveredAccount)+ .where({ discoverySourceId })+ .whereNull("importedAccountId");+ if (search) void query.andWhere("name", "ilike", `%${search}%`);+ return query.orderBy("name", "asc");+ };++ return { ...orm, upsertByFingerprint, listStaged };+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts b/backend/src/ee/services/pam-discovery/pam-discovery-enums.tsnew file mode 100644index 0000000000..ded72f031e--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts@@ -0,0 +1,20 @@+export enum PamDiscoveryType {+ ActiveDirectory = "active-directory"+}++export enum PamDiscoverySchedule {+ Manual = "manual",+ Daily = "daily",+ Weekly = "weekly"+}++export enum PamDiscoveryRunStatus {+ Running = "running",+ Completed = "completed",+ Failed = "failed"+}++export enum PamDiscoveryRunTrigger {+ Manual = "manual",+ Schedule = "schedule"+}diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts b/backend/src/ee/services/pam-discovery/pam-discovery-factory.tsnew file mode 100644index 0000000000..5b361623dd--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts@@ -0,0 +1,7 @@+import { activeDirectoryDiscoveryFactory } from "./active-directory/active-directory-discovery-factory";+import { PamDiscoveryType } from "./pam-discovery-enums";+import { TPamDiscoveryFactory } from "./pam-discovery-types";++export const PAM_DISCOVERY_FACTORY_MAP: Record<PamDiscoveryType, TPamDiscoveryFactory> = {+ [PamDiscoveryType.ActiveDirectory]: activeDirectoryDiscoveryFactory+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.tsnew file mode 100644index 0000000000..658c017caa--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts@@ -0,0 +1,58 @@+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";++export const DISCOVERY_TYPE_CONFIGS = {+ [PamDiscoveryType.ActiveDirectory]: {+ name: "Active Directory",+ icon: "ActiveDirectory.png",+ credentialAccountType: PamAccountType.WindowsAd,+ configuration: ActiveDirectoryDiscoveryConfigSchema+ }+} as const satisfies Partial<+ Record<+ PamDiscoveryType,+ {+ name: string;+ icon: string;+ credentialAccountType: PamAccountType;+ configuration: z.ZodTypeAny;+ }+ >+>;++type TSupportedDiscoveryType = keyof typeof DISCOVERY_TYPE_CONFIGS;++export const getDiscoveryTypeConfig = (discoveryType: PamDiscoveryType | string) => {+ const config = DISCOVERY_TYPE_CONFIGS[discoveryType as TSupportedDiscoveryType];+ if (!config) throw new Error(`Discovery type '${discoveryType}' is not supported`);+ return config;+};++export const validateDiscoveryConfiguration = (discoveryType: PamDiscoveryType, data: unknown) =>+ getDiscoveryTypeConfig(discoveryType).configuration.parse(data ?? {}) as Record<string, unknown>;++export const getCredentialAccountType = (discoveryType: PamDiscoveryType): PamAccountType =>+ getDiscoveryTypeConfig(discoveryType).credentialAccountType;++export const PamDiscoveryTypeMetadataSchema = z.object({+ type: z.nativeEnum(PamDiscoveryType),+ name: z.string(),+ icon: z.string(),+ credentialAccountType: z.nativeEnum(PamAccountType)+});++export const buildPamDiscoveryTypeMetadata = () =>+ (+ Object.entries(DISCOVERY_TYPE_CONFIGS) as [+ TSupportedDiscoveryType,+ (typeof DISCOVERY_TYPE_CONFIGS)[TSupportedDiscoveryType]+ ][]+ ).map(([type, config]) => ({+ type,+ name: config.name,+ icon: config.icon,+ credentialAccountType: config.credentialAccountType+ }));diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.tsnew file mode 100644index 0000000000..dfd1c44dc5--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts@@ -0,0 +1,18 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++import { PamDiscoverySchedule } from "./pam-discovery-enums";++export type TPamDiscoverySourceDALFactory = ReturnType<typeof pamDiscoverySourceDALFactory>;++export const pamDiscoverySourceDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PamDiscoverySource);++ const findScheduled = async () =>+ db+ .replicaNode()(TableName.PamDiscoverySource)+ .whereIn("schedule", [PamDiscoverySchedule.Daily, PamDiscoverySchedule.Weekly]);++ return { ...orm, findScheduled };+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.tsnew file mode 100644index 0000000000..4d2986c55d--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-run-dal.ts@@ -0,0 +1,7 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TPamDiscoverySourceRunDALFactory = ReturnType<typeof pamDiscoverySourceRunDALFactory>;++export const pamDiscoverySourceRunDALFactory = (db: TDbClient) => ormify(db, TableName.PamDiscoverySourceRun);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.tsnew file mode 100644index 0000000000..ac422678b1--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts@@ -0,0 +1,462 @@+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";+import { getConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { DatabaseErrorCode } from "@app/lib/error-codes";+import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";++import { PamAccountType, PamProductRole } 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";+import { TPamAccountServiceFactory } from "../pam-account/pam-account-service";+import { TPamDiscoveredAccountDALFactory } from "./pam-discovered-account-dal";+import {+ PamDiscoveryRunStatus,+ PamDiscoveryRunTrigger,+ PamDiscoverySchedule,+ PamDiscoveryType+} from "./pam-discovery-enums";+import { PAM_DISCOVERY_FACTORY_MAP } from "./pam-discovery-factory";+import {+ getCredentialAccountType,+ getDiscoveryTypeConfig,+ validateDiscoveryConfiguration+} from "./pam-discovery-schemas";+import { TPamDiscoverySourceDALFactory } from "./pam-discovery-source-dal";+import { TPamDiscoverySourceRunDALFactory } from "./pam-discovery-source-run-dal";+import {+ TCreateDiscoverySourceDTO,+ TDeleteDiscoverySourceDTO,+ TGetDiscoverySourceDTO,+ TImportDiscoveredDTO,+ TListDiscoveredDTO,+ TListDiscoverySourcesDTO,+ TListRunsDTO,+ TTriggerScanDTO,+ TUpdateDiscoverySourceDTO+} from "./pam-discovery-types";++type TPamDiscoverySourceServiceFactoryDep = {+ pamDiscoverySourceDAL: TPamDiscoverySourceDALFactory;+ pamDiscoverySourceRunDAL: TPamDiscoverySourceRunDALFactory;+ pamDiscoveredAccountDAL: TPamDiscoveredAccountDALFactory;+ pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findByIdWithDetails">;+ pamAccountService: Pick<TPamAccountServiceFactory, "create">;+ permissionService: Pick<+ TPermissionServiceFactory,+ "getProjectPermission" | "getResourcePermission" | "getOrgPermission"+ >;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"+ >;+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;+ cronJob: TCronJobFactory;+};++export type TPamDiscoverySourceServiceFactory = ReturnType<typeof pamDiscoverySourceServiceFactory>;++export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServiceFactoryDep) => {+ const {+ pamDiscoverySourceDAL,+ pamDiscoverySourceRunDAL,+ pamDiscoveredAccountDAL,+ pamAccountDAL,+ pamAccountService,+ permissionService,+ kmsService,+ gatewayV2Service,+ gatewayPoolService,+ queueService,+ cronJob+ } = deps;++ const enqueueScan = (sourceId: string, triggeredBy: PamDiscoveryRunTrigger) =>+ queueService.queue(+ QueueName.PamDiscoveryScan,+ QueueJobs.PamDiscoverySourceScan,+ { sourceId, triggeredBy },+ { jobId: `pam-discovery-scan-${sourceId}`, removeOnComplete: true, removeOnFail: true }+ );++ const getProjectCipher = (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ const decryptToObject = (blob: Buffer, decryptor: (i: { cipherTextBlob: Buffer }) => Buffer) =>+ JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;++ const verifyAdmin = async (projectId: string, ctx: TActorContext) => {+ const { hasRole } = await verifyProductMembership(permissionService, projectId, ctx);+ if (!hasRole(PamProductRole.Admin)) {+ throw new ForbiddenRequestError({ message: "Discovery requires the PAM product Admin role" });+ }+ };++ const resolveCredentialAccount = async (+ projectId: string,+ discoveryType: PamDiscoveryType,+ credentialAccountId: string,+ ctx: TActorContext+ ) => {+ const account = await pamAccountDAL.findByIdWithDetails(credentialAccountId);+ if (!account || account.projectId !== projectId) {+ throw new NotFoundError({ message: `Credential account with ID '${credentialAccountId}' not found` });+ }+ await checkAccountAccess(+ permissionService,+ credentialAccountId,+ account.folderId,+ projectId,+ ResourcePermissionPamResourceActions.ReadAccounts,+ ctx+ );+ const expectedType = getCredentialAccountType(discoveryType);+ if (account.accountType !== expectedType) {+ throw new BadRequestError({ message: `Credential account must be of type '${expectedType}'` });+ }+ return account;+ };++ const mapDbError = (err: unknown, name?: string): never => {+ if (err instanceof DatabaseError) {+ const code = (err.error as { code?: string })?.code;+ if (code === DatabaseErrorCode.UniqueViolation) {+ throw new BadRequestError({ message: `A discovery source named "${name}" already exists` });+ }+ if (code === DatabaseErrorCode.ForeignKeyViolation) {+ throw new BadRequestError({+ message: "Invalid reference: the specified gateway, pool, or account does not exist"+ });+ }+ }+ throw err;+ };++ const withLastRunStatus = async <T extends { id: string }>(sources: T[]) => {+ if (sources.length === 0) {+ return sources.map((s) => ({ ...s, lastRunStatus: null as string | null, lastRunError: null as string | null }));+ }+ const runs = await pamDiscoverySourceRunDAL.find(+ { $in: { discoverySourceId: sources.map((s) => s.id) } },+ { sort: [["createdAt", "desc"]] }+ );+ const latestBySource = new Map<string, { status: string; errorMessage?: string | null }>();+ runs.forEach((r) => {+ if (!latestBySource.has(r.discoverySourceId)) {+ latestBySource.set(r.discoverySourceId, { status: r.status, errorMessage: r.errorMessage });+ }+ });+ return sources.map((s) => {+ const latest = latestBySource.get(s.id);+ return { ...s, lastRunStatus: latest?.status ?? null, lastRunError: latest?.errorMessage ?? null };+ });+ };++ const list = async ({ projectId, search, ...ctx }: TListDiscoverySourcesDTO) => {+ await verifyAdmin(projectId, ctx);+ const sources = await pamDiscoverySourceDAL.find(+ { projectId, ...(search ? { $search: { name: search } } : {}) },+ { sort: [["name", "asc"]] }+ );+ return withLastRunStatus(sources);+ };++ const getById = async ({ projectId, sourceId, ...ctx }: TGetDiscoverySourceDTO) => {+ await verifyAdmin(projectId, ctx);+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source || source.projectId !== projectId) {+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });+ }+ const [withStatus] = await withLastRunStatus([source]);+ return withStatus;+ };++ const create = async ({+ projectId,+ discoveryType,+ name,+ credentialAccountId,+ gatewayId,+ gatewayPoolId,+ schedule,+ configuration,+ ...ctx+ }: TCreateDiscoverySourceDTO) => {+ await verifyAdmin(projectId, ctx);+ getDiscoveryTypeConfig(discoveryType);++ if (!gatewayId && !gatewayPoolId) {+ throw 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);++ try {+ return await pamDiscoverySourceDAL.create({+ projectId,+ discoveryType,+ name,+ credentialAccountId,+ gatewayId,+ gatewayPoolId,+ schedule,+ discoveryConfiguration+ });+ } catch (err) {+ return mapDbError(err, name);+ }+ };++ const update = async ({+ projectId,+ sourceId,+ discoveryType,+ name,+ credentialAccountId,+ gatewayId,+ gatewayPoolId,+ schedule,+ configuration,+ ...ctx+ }: TUpdateDiscoverySourceDTO) => {+ await verifyAdmin(projectId, ctx);+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source || source.projectId !== projectId) {+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });+ }++ if (gatewayId !== undefined || gatewayPoolId !== undefined) {+ await validateGatewayAttachment(deps, gatewayId, gatewayPoolId, ctx);+ }+ if (credentialAccountId) {+ await resolveCredentialAccount(projectId, discoveryType, credentialAccountId, ctx);+ }++ const updateData: Record<string, unknown> = {};+ if (name !== undefined) updateData.name = name;+ if (credentialAccountId !== undefined) updateData.credentialAccountId = credentialAccountId;+ if (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);++ try {+ return await pamDiscoverySourceDAL.updateById(sourceId, updateData);+ } catch (err) {+ return mapDbError(err, name ?? source.name);+ }+ };++ const deleteSource = async ({ projectId, sourceId, ...ctx }: TDeleteDiscoverySourceDTO) => {+ await verifyAdmin(projectId, ctx);+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source || source.projectId !== projectId) {+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });+ }+ return pamDiscoverySourceDAL.deleteById(sourceId);+ };++ const runScan = async (sourceId: string, triggeredBy: PamDiscoveryRunTrigger) => {+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source) return;++ const run = await pamDiscoverySourceRunDAL.create({+ discoverySourceId: sourceId,+ status: PamDiscoveryRunStatus.Running,+ triggeredBy,+ startedAt: new Date()+ });++ try {+ const credentialAccount = await pamAccountDAL.findByIdWithDetails(source.credentialAccountId);+ if (!credentialAccount) throw new BadRequestError({ message: "Credential account no longer exists" });++ const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: source.gatewayId,+ gatewayPoolId: source.gatewayPoolId+ });+ 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)+ },+ gatewayV2Service+ });++ const { accounts, machineErrors } = await provider.scan();+ const results = await Promise.all(+ accounts.map((d) =>+ pamDiscoveredAccountDAL.upsertByFingerprint(sourceId, d.fingerprint, {+ accountType: d.accountType,+ name: d.name,+ encryptedDetails: encryptor({ plainText: Buffer.from(JSON.stringify(d.details)) }).cipherTextBlob+ })+ )+ );++ await pamDiscoverySourceRunDAL.updateById(run.id, {+ status: PamDiscoveryRunStatus.Completed,+ discoveredCount: accounts.length,+ newCount: results.filter((r) => r.isNew).length,+ machineErrors: machineErrors.length ? JSON.stringify(machineErrors) : null,+ completedAt: new Date()+ });+ } catch (err) {+ logger.error(err, `PAM discovery scan failed [sourceId=${sourceId}]`);+ await pamDiscoverySourceRunDAL.updateById(run.id, {+ status: PamDiscoveryRunStatus.Failed,+ errorMessage: err instanceof Error ? err.message : "Scan failed",+ completedAt: new Date()+ });+ } finally {+ await pamDiscoverySourceDAL.updateById(sourceId, { lastRunAt: new Date() });+ }+ };++ const triggerScan = async ({ projectId, sourceId, ...ctx }: TTriggerScanDTO) => {+ await verifyAdmin(projectId, ctx);+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source || source.projectId !== projectId) {+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });+ }+ const running = await pamDiscoverySourceRunDAL.findOne({+ discoverySourceId: sourceId,+ status: PamDiscoveryRunStatus.Running+ });+ if (running) throw new BadRequestError({ message: "A scan is already in progress for this source" });++ await enqueueScan(sourceId, PamDiscoveryRunTrigger.Manual);+ return { message: "Scan started" };+ };++ const listRuns = async ({ projectId, sourceId, offset = 0, limit = 20, ...ctx }: TListRunsDTO) => {+ await verifyAdmin(projectId, ctx);+ const runs = await pamDiscoverySourceRunDAL.find(+ { discoverySourceId: sourceId },+ { sort: [["createdAt", "desc"]], offset, limit }+ );+ return runs;+ };++ const listDiscovered = async ({ projectId, sourceId, search, ...ctx }: TListDiscoveredDTO) => {+ await verifyAdmin(projectId, ctx);+ const accounts = await pamDiscoveredAccountDAL.listStaged(sourceId, search);+ return accounts.map((a) => ({+ id: a.id,+ accountType: a.accountType,+ name: a.name,+ fingerprint: a.fingerprint,+ createdAt: a.createdAt+ }));+ };++ const importAccounts = async ({ projectId, sourceId, folderId, accounts, ...ctx }: TImportDiscoveredDTO) => {+ await verifyAdmin(projectId, ctx);+ const source = await pamDiscoverySourceDAL.findById(sourceId);+ if (!source || source.projectId !== projectId) {+ throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });+ }++ const { decryptor } = await getProjectCipher(projectId);++ const results = await Promise.all(+ accounts.map(async (item) => {+ try {+ const discovered = await pamDiscoveredAccountDAL.findById(item.discoveredAccountId);+ if (!discovered || discovered.discoverySourceId !== sourceId) {+ throw new NotFoundError({ message: "Discovered account not found" });+ }+ if (discovered.importedAccountId) throw new BadRequestError({ message: "Already imported" });++ const details = decryptToObject(discovered.encryptedDetails, decryptor) as {+ connectionDetails: Record<string, unknown>;+ credentials: Record<string, unknown>;+ };++ const account = await pamAccountService.create({+ projectId,+ accountType: discovered.accountType as PamAccountType,+ name: item.name ?? discovered.name,+ folderId,+ templateId: item.templateId,+ connectionDetails: details.connectionDetails,+ credentials: details.credentials,+ ...ctx+ });++ await pamDiscoveredAccountDAL.updateById(discovered.id, { importedAccountId: account.id });+ return { discoveredAccountId: item.discoveredAccountId, status: "imported" as const, accountId: account.id };+ } catch (err) {+ return {+ discoveredAccountId: item.discoveredAccountId,+ status: "error" as const,+ message: err instanceof Error ? err.message : "Import failed"+ };+ }+ })+ );++ return { results };+ };++ // Runs on boot: processes scan jobs and registers the daily fan-out for scheduled sources+ const init = () => {+ const appCfg = getConfig();+ if (appCfg.isSecondaryInstance) return;++ queueService.start(QueueName.PamDiscoveryScan, async (job) => {+ await runScan(job.data.sourceId, job.data.triggeredBy as PamDiscoveryRunTrigger);+ });++ cronJob.register({+ name: CronJobName.PamDiscoveryScheduledScan,+ pattern: "0 3 * * *",+ runHashTtlS: 24 * 60 * 60,+ enabled: !appCfg.isSecondaryInstance,+ handler: async () => {+ const sources = await pamDiscoverySourceDAL.findScheduled();+ const now = Date.now();+ const due = sources.filter((s) => {+ const windowMs = (s.schedule === PamDiscoverySchedule.Weekly ? 7 : 1) * 24 * 60 * 60 * 1000;+ return !s.lastRunAt || now - new Date(s.lastRunAt).getTime() >= windowMs;+ });+ await Promise.all(due.map((s) => enqueueScan(s.id, PamDiscoveryRunTrigger.Schedule)));+ }+ });+ };++ return {+ init,+ list,+ getById,+ create,+ update,+ deleteSource,+ triggerScan,+ runScan,+ listRuns,+ listDiscovered,+ importAccounts+ };+};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.tsnew file mode 100644index 0000000000..f997774887--- /dev/null+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts@@ -0,0 +1,75 @@+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";++import { PamAccountType } from "../pam/pam-enums";+import { TActorContext } from "../pam/pam-permission";+import { PamDiscoverySchedule, PamDiscoveryType } from "./pam-discovery-enums";++export type TDiscoveredAccount = {+ accountType: PamAccountType;+ name: string;+ fingerprint: string;+ details: Record<string, unknown>;+};++export type TDiscoveryMachineError = { machine: string; error: string };++export type TDiscoveryScanResult = {+ accounts: TDiscoveredAccount[];+ machineErrors: TDiscoveryMachineError[];+};++export type TPamDiscoveryProvider = {+ validateConnection: () => Promise<void>;+ scan: () => Promise<TDiscoveryScanResult>;+};++export type TPamDiscoveryFactoryInput = {+ projectId: string;+ gatewayId: string;+ configuration: Record<string, unknown>;+ credentialAccount: {+ accountType: PamAccountType;+ connectionDetails: Record<string, unknown>;+ credentials: Record<string, unknown>;+ };+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+};++export type TPamDiscoveryFactory = (input: TPamDiscoveryFactoryInput) => TPamDiscoveryProvider;++export type TCreateDiscoverySourceDTO = {+ projectId: string;+ discoveryType: PamDiscoveryType;+ name: string;+ credentialAccountId: string;+ gatewayId?: string;+ gatewayPoolId?: string;+ schedule: PamDiscoverySchedule;+ configuration: Record<string, unknown>;+} & TActorContext;++export type TUpdateDiscoverySourceDTO = {+ projectId: string;+ sourceId: string;+ discoveryType: PamDiscoveryType;+ name?: string;+ credentialAccountId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ schedule?: PamDiscoverySchedule;+ configuration?: Record<string, unknown>;+} & TActorContext;++export type TDeleteDiscoverySourceDTO = { projectId: string; sourceId: string } & TActorContext;+export type TGetDiscoverySourceDTO = { projectId: string; sourceId: string } & TActorContext;+export type TListDiscoverySourcesDTO = { projectId: string; search?: string } & TActorContext;+export type TTriggerScanDTO = { projectId: string; sourceId: string } & TActorContext;+export type TListRunsDTO = { projectId: string; sourceId: string; offset?: number; limit?: number } & TActorContext;+export type TListDiscoveredDTO = { projectId: string; sourceId: string; search?: string } & TActorContext;++export type TImportDiscoveredDTO = {+ projectId: string;+ sourceId: string;+ folderId: string;+ accounts: { discoveredAccountId: string; templateId: string; name?: string }[];+} & TActorContext;diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex e8b01bf039..6e03bc8fb3 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -44,6 +44,7 @@ import {getAccountAccessibilityIssues,PamAccountAccessibilityIssue,parseInternalMetadata,+ qualifyUsernameWithDomain,resolveGatewayAccountType,resolveSelectedHost} from "../pam-account/pam-account-schemas";@@ -288,6 +289,13 @@ export const pamSessionServiceFactory = ({session.selectedHost);+ if (account.accountType === PamAccountType.WindowsAd) {+ credentials.username = qualifyUsernameWithDomain(+ credentials.username as string,+ (connectionDetails as { domain: string }).domain+ );+ }+if (sessionStarted) {await pamSessionDAL.activateSession(sessionId);}diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex 6108c21b1e..63e549666e 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -170,6 +170,28 @@ No migration, no router or response-schema change (beyond `policyRules` for gate- List queries that respect permissions use the accessible-resource pattern: join to the resource table and filter with `WHERE (folderId IN (...) OR accountId IN (...))`- Gateway joins (for `gatewayName`/`gatewayIdentityId`) are repeated per-method since the select/join context differs+## Search++Searchable lists filter on **both tiers** — server for correctness/scale, client for instant feedback:++- **Server**: the DAL filters with ormify's `$search` operator (case-insensitive ILIKE that wraps and sanitizes the term). Pass `{ $search: { name: term } }` — do NOT pre-wrap with `%…%`.+- **Frontend**: pass a **debounced** value (`useDebounce`) to the query so the server narrows results, and also filter the returned list **client-side on the immediate value** for instant feedback. Wrap every searchable field (names) in `<HighlightText text={value} highlight={search} />`.++`PamSessionsPage` and `PamDiscoveryPage` are the reference implementations.++## Discovery++Discovery 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.+- **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.++### Active Directory local accounts++Gated 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.+## 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.@@ -187,7 +209,7 @@ Old tables, columns, and code kept temporarily so data can be recovered if the m- `pam_account_dependencies`- `pam_resource_favorites`- `pam_project_recording_configs`-- `pam_discovery_sources`, `pam_discovery_source_runs`, `pam_discovery_source_resources`, `pam_discovery_source_accounts`, `pam_discovery_source_dependencies` (when discovery is reimplemented)+- The old discovery tables (`pam_discovery_source_resources`, `pam_discovery_source_accounts`, `pam_discovery_source_dependencies`) are already dropped by the reimplemented discovery migration, which recreates `pam_discovery_sources`/`pam_discovery_source_runs` and adds `pam_discovered_accounts` — nothing to defer here.- `pam_session_event_batches` (legacy logging, replaced by chunks)### Columns to drop from `pam_accounts`diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 20437fe652..0e36899a96 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -22,6 +22,7 @@ export const CronJobName = {PkiSyncCleanup: "pki-sync-cleanup",PkiSubscriberDailyAutoRenewal: "pki-subscriber-daily-auto-renewal",PkiDiscoveryScheduledScan: "pki-discovery-scheduled-scan",+ PamDiscoveryScheduledScan: "pam-discovery-scheduled-scan",DailySecretSyncRetry: "daily-secret-sync-retry",SecretRotationV2QueueRotations: "secret-rotation-v2-queue-rotations",AppConnectionCredentialRotationQueueRotations: "app-connection-credential-rotation-queue-rotations",diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 131da114d5..e942571b8d 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -100,6 +100,7 @@ export enum QueueName {SecretScanningV2 = "secret-scanning-v2",UserNotification = "user-notification",PamSessionExpiration = "pam-session-expiration",+ PamDiscoveryScan = "pam-discovery-scan",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",PkiDiscoveryScan = "pki-discovery-scan",AppConnectionCredentialRotation = "app-connection-credential-rotation",@@ -165,6 +166,7 @@ export enum QueueJobs {HealthAlert = "health-alert",CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal",PamSessionExpiration = "pam-session-expiration",+ PamDiscoverySourceScan = "pam-discovery-source-scan",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",PkiDiscoveryRunScan = "pki-discovery-run-scan",PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",@@ -444,6 +446,10 @@ export type TQueueJobTypes = {name: QueueJobs.PamSessionExpiration;payload: { sessionId: string };};+ [QueueName.PamDiscoveryScan]: {+ name: QueueJobs.PamDiscoverySourceScan;+ payload: { sourceId: string; triggeredBy: string };+ };[QueueName.PkiAcmeChallengeValidation]: {name: QueueJobs.PkiAcmeChallengeValidation;payload: { challengeId: string };@@ -662,7 +668,6 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa"pki-sync-cleanup","pam-account-rotation","pam-session-ai-summary",- "pam-discovery-scan","daily-pki-alert-v2-processing","daily-expiring-pki-item-alert","telemtry-self-hosted-stats", // note: typo from original enum valuediff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3e858dc931..c87f50be3a 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -106,6 +106,10 @@ import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dimport { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";import { pamAccountTemplateDALFactory } from "@app/ee/services/pam-account-template/pam-account-template-dal";import { pamAccountTemplateServiceFactory } from "@app/ee/services/pam-account-template/pam-account-template-service";+import { pamDiscoveredAccountDALFactory } from "@app/ee/services/pam-discovery/pam-discovered-account-dal";+import { pamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";+import { pamDiscoverySourceRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-run-dal";+import { pamDiscoverySourceServiceFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-service";import { pamFolderDALFactory } from "@app/ee/services/pam-folder/pam-folder-dal";import { pamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";import { pamMembershipServiceFactory } from "@app/ee/services/pam-membership/pam-membership-service";@@ -1811,6 +1815,25 @@ export const registerRoutes = async (appConnectionDAL});+ const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);+ const pamDiscoverySourceRunDAL = pamDiscoverySourceRunDALFactory(db);+ const pamDiscoveredAccountDAL = pamDiscoveredAccountDALFactory(db);++ const pamDiscoveryService = pamDiscoverySourceServiceFactory({+ pamDiscoverySourceDAL,+ pamDiscoverySourceRunDAL,+ pamDiscoveredAccountDAL,+ pamAccountDAL,+ pamAccountService,+ permissionService,+ kmsService,+ gatewayV2DAL,+ gatewayV2Service,+ gatewayPoolService,+ queueService,+ cronJob+ });+const pamSessionDAL = pamSessionDALFactory(db);const pamSessionEventChunkDAL = pamSessionEventChunkDALFactory(db);@@ -3604,6 +3627,7 @@ export const registerRoutes = async (healthAlert.init();auditLogStreamOutboxQueue.init();pkiSyncCleanup.init();+ pamDiscoveryService.init();pkiDiscoveryQueue.startPkiDiscoveryScanQueue();dailyReminderQueueService.startDailyRemindersJob();secretSyncQueue.startDailySecretSyncRetryJob();@@ -3712,6 +3736,7 @@ export const registerRoutes = async (pamAccountTemplate: pamAccountTemplateService,pamFolder: pamFolderService,pamAccount: pamAccountService,+ pamDiscovery: pamDiscoveryService,pamMembership: pamMembershipService,pamSession: pamSessionService,pamSessionChunk: pamSessionChunkService,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex fdb250e19a..e00e67090d 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -107,6 +107,11 @@ export enum PostHogEventTypes {PamAccountUpdated = "PAM Account Updated",PamAccountDeleted = "PAM Account Deleted",PamAccountAccessed = "PAM Account Accessed",+ PamDiscoverySourceCreated = "PAM Discovery Source Created",+ PamDiscoverySourceUpdated = "PAM Discovery Source Updated",+ PamDiscoverySourceDeleted = "PAM Discovery Source Deleted",+ PamDiscoveryScanTriggered = "PAM Discovery Scan Triggered",+ PamDiscoveredAccountsImported = "PAM Discovered Accounts Imported",PamSessionStarted = "PAM Session Started",PamSessionEnded = "PAM Session Ended",PamSessionTerminated = "PAM Session Terminated",@@ -994,6 +999,26 @@ export type TPamAccountEvent = {};};+export type TPamDiscoveryEvent = {+ event:+ | PostHogEventTypes.PamDiscoverySourceCreated+ | PostHogEventTypes.PamDiscoverySourceUpdated+ | PostHogEventTypes.PamDiscoverySourceDeleted+ | PostHogEventTypes.PamDiscoveryScanTriggered;+ properties: {+ discoveryType: string;+ orgId: string;+ };+};++export type TPamDiscoveredAccountsImportedEvent = {+ event: PostHogEventTypes.PamDiscoveredAccountsImported;+ properties: {+ orgId: string;+ importedCount: number;+ };+};+export type TPamAccountAccessedEvent = {event: PostHogEventTypes.PamAccountAccessed;properties: {@@ -1979,6 +2004,8 @@ export type TPostHogEvent = {| TPamAccountTemplateEvent| TPamFolderEvent| TPamAccountEvent+ | TPamDiscoveryEvent+ | TPamDiscoveredAccountsImportedEvent| TPamAccountAccessedEvent| TPamSessionStartedEvent| TPamSessionEndedEventdiff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.tsindex bb9401a8e6..b811ff9cd6 100644--- a/frontend/src/const/routes.ts+++ b/frontend/src/const/routes.ts@@ -436,6 +436,10 @@ export const ROUTE_PATHS = Object.freeze({TemplatesPage: setRoute("/organizations/$orgId/pam/templates","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates"+ ),+ DiscoveryPage: setRoute(+ "/organizations/$orgId/pam/discovery",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery")},Public: {diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex e9c85aaf07..c9d4c999f1 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -12,6 +12,16 @@ export enum PamAccountType {WindowsAd = "windows-ad"}+export enum PamDiscoveryType {+ ActiveDirectory = "active-directory"+}++export enum PamDiscoverySchedule {+ Manual = "manual",+ Daily = "daily",+ Weekly = "weekly"+}+export enum PamPolicyType {RequireMfa = "require-mfa",RequireReason = "require-reason",diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 24220a9e05..18ec190710 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -14,12 +14,17 @@ import {TAddPamProductIdentityMemberDTO,TCreatePamAccountDTO,TCreatePamAccountTemplateDTO,+ TCreatePamDiscoverySourceDTO,TCreatePamFolderDTO,TDeletePamAccountDTO,TDeletePamAccountTemplateDTO,+ TDeletePamDiscoverySourceDTO,TDeletePamFolderDTO,+ TImportPamDiscoveredAccountResult,+ TImportPamDiscoveredAccountsDTO,TPamAccessResponse,TPamAccountTemplate,+ TPamDiscoverySource,TPamFolder,TPamSession,TRemoveAccountGroupMemberDTO,@@ -29,6 +34,7 @@ import {TRemoveFolderIdentityMemberDTO,TRemoveFolderMemberDTO,TRemovePamProductIdentityMemberDTO,+ TTriggerPamDiscoveryScanDTO,TUpdateAccountGroupMemberRoleDTO,TUpdateAccountIdentityMemberRoleDTO,TUpdateAccountMemberRoleDTO,@@ -37,6 +43,7 @@ import {TUpdateFolderMemberRoleDTO,TUpdatePamAccountDTO,TUpdatePamAccountTemplateDTO,+ TUpdatePamDiscoverySourceDTO,TUpdatePamFolderDTO,TUpdatePamProductIdentityMemberDTO} from "./types";@@ -560,3 +567,70 @@ export const useRemoveFolderIdentityMember = () => {}});};++// Discovery+export const useCreatePamDiscoverySource = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ discoveryType, ...body }: TCreatePamDiscoverySourceDTO) => {+ const { data } = await apiRequest.post<{ source: TPamDiscoverySource }>(+ `/api/v1/pam/discovery-sources/${discoveryType}`,+ body+ );+ return data.source;+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: pamKeys.discovery() })+ });+};++export const useUpdatePamDiscoverySource = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ discoveryType, sourceId, ...body }: TUpdatePamDiscoverySourceDTO) => {+ const { data } = await apiRequest.patch<{ source: TPamDiscoverySource }>(+ `/api/v1/pam/discovery-sources/${discoveryType}/${sourceId}`,+ body+ );+ return data.source;+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: pamKeys.discovery() })+ });+};++export const useDeletePamDiscoverySource = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ discoveryType, sourceId }: TDeletePamDiscoverySourceDTO) => {+ await apiRequest.delete(`/api/v1/pam/discovery-sources/${discoveryType}/${sourceId}`);+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: pamKeys.discovery() })+ });+};++export const useTriggerPamDiscoveryScan = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ discoveryType, sourceId }: TTriggerPamDiscoveryScanDTO) => {+ await apiRequest.post(`/api/v1/pam/discovery-sources/${discoveryType}/${sourceId}/scan`);+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: pamKeys.discovery() })+ });+};++export const useImportPamDiscoveredAccounts = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ sourceId, ...body }: TImportPamDiscoveredAccountsDTO) => {+ const { data } = await apiRequest.post<{ results: TImportPamDiscoveredAccountResult[] }>(+ `/api/v1/pam/discovery-sources/${sourceId}/discovered/import`,+ body+ );+ return data.results;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: pamKeys.discovery() });+ queryClient.invalidateQueries({ queryKey: pamKeys.account() });+ queryClient.invalidateQueries({ queryKey: pamKeys.folder() });+ }+ });+};diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsxindex d806116955..1a6b73fc5e 100644--- a/frontend/src/hooks/api/pam/queries.tsx+++ b/frontend/src/hooks/api/pam/queries.tsx@@ -23,6 +23,10 @@ import {TPamAccountTemplateDetail,TPamAccountTemplateWithCount,TPamAccountTypeMetadata,+ TPamDiscoveredAccount,+ TPamDiscoveryRun,+ TPamDiscoverySource,+ TPamDiscoveryTypeOption,TPamFolderWithCount,TPamMember,TPamMembersData,@@ -62,7 +66,14 @@ export const pamKeys = {productIdentities: () => [...pamKeys.all, "product-identities"] as const,resourceRoles: () => [...pamKeys.all, "resource-roles"] as const,accessCapabilities: () => [...pamKeys.all, "access-capabilities"] as const,- accountTypes: () => [...pamKeys.all, "account-types"] as const+ accountTypes: () => [...pamKeys.all, "account-types"] as const,+ discovery: () => [...pamKeys.all, "discovery"] as const,+ discoveryTypes: () => [...pamKeys.discovery(), "types"] as const,+ listDiscoverySources: (params?: { search?: string }) =>+ [...pamKeys.discovery(), "sources", params] as const,+ listDiscoveryRuns: (sourceId: string) => [...pamKeys.discovery(), "runs", sourceId] as const,+ listDiscoveredAccounts: (sourceId: string, search?: string) =>+ [...pamKeys.discovery(), "discovered", sourceId, search] as const};const fetchFolderPermissions = async (folderId: string) => {@@ -430,3 +441,62 @@ export const useGetPamAccessCapabilities = () => {}});};++export const useListPamDiscoveryTypes = () => {+ return useQuery({+ queryKey: pamKeys.discoveryTypes(),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ discoveryTypes: TPamDiscoveryTypeOption[] }>(+ "/api/v1/pam/discovery-sources/options"+ );+ return data.discoveryTypes;+ },+ staleTime: Infinity+ });+};++export const useListPamDiscoverySources = (params?: { search?: string }) => {+ return useQuery({+ queryKey: pamKeys.listDiscoverySources(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ sources: TPamDiscoverySource[] }>(+ "/api/v1/pam/discovery-sources",+ { params }+ );+ return data.sources;+ },+ placeholderData: (prev) => prev+ });+};++export const useListPamDiscoveryRuns = (+ sourceId: string,+ options?: { refetchInterval?: number }+) => {+ return useQuery({+ queryKey: pamKeys.listDiscoveryRuns(sourceId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ runs: TPamDiscoveryRun[] }>(+ `/api/v1/pam/discovery-sources/${sourceId}/runs`+ );+ return data.runs;+ },+ enabled: Boolean(sourceId),+ refetchInterval: options?.refetchInterval+ });+};++export const useListPamDiscoveredAccounts = (sourceId: string, search?: string) => {+ return useQuery({+ queryKey: pamKeys.listDiscoveredAccounts(sourceId, search),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ discoveredAccounts: TPamDiscoveredAccount[] }>(+ `/api/v1/pam/discovery-sources/${sourceId}/discovered`,+ { params: { search } }+ );+ return data.discoveredAccounts;+ },+ enabled: Boolean(sourceId),+ placeholderData: (prev) => prev+ });+};diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex de8b237420..49bebd305d 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -3,6 +3,8 @@ import {PamAccountOrderBy,PamAccountType,PamAccountView,+ PamDiscoverySchedule,+ PamDiscoveryType,PamPolicyType,PamResourcePermissionActions,PamResourcePermissionSub,@@ -10,6 +12,88 @@ import {SessionChannelType} from "../enums";+export type TPamDiscoveryTypeOption = {+ type: PamDiscoveryType;+ name: string;+ icon: string;+ credentialAccountType: PamAccountType;+};++export type TPamDiscoverySource = {+ id: string;+ projectId: string;+ name: string;+ discoveryType: PamDiscoveryType;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ credentialAccountId: string;+ discoveryConfiguration: Record<string, unknown>;+ schedule: PamDiscoverySchedule;+ lastRunAt?: string | null;+ lastRunStatus?: string | null;+ lastRunError?: string | null;+ createdAt: string;+ updatedAt: string;+};++export type TPamDiscoveryRun = {+ id: string;+ discoverySourceId: string;+ status: string;+ triggeredBy: string;+ discoveredCount: number;+ newCount: number;+ errorMessage?: string | null;+ machineErrors?: { machine: string; error: string }[] | null;+ startedAt?: string | null;+ completedAt?: string | null;+ createdAt: string;+};++export type TPamDiscoveredAccount = {+ id: string;+ accountType: PamAccountType;+ name: string;+ fingerprint: string;+ createdAt: string;+};++export type TCreatePamDiscoverySourceDTO = {+ discoveryType: PamDiscoveryType;+ name: string;+ credentialAccountId: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ schedule: PamDiscoverySchedule;+ configuration?: Record<string, unknown>;+};++export type TUpdatePamDiscoverySourceDTO = {+ sourceId: string;+ discoveryType: PamDiscoveryType;+ name?: string;+ credentialAccountId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ schedule?: PamDiscoverySchedule;+ configuration?: Record<string, unknown>;+};++export type TDeletePamDiscoverySourceDTO = { sourceId: string; discoveryType: PamDiscoveryType };+export type TTriggerPamDiscoveryScanDTO = { sourceId: string; discoveryType: PamDiscoveryType };+export type TImportPamDiscoveredAccountsDTO = {+ sourceId: string;+ folderId: string;+ accounts: { discoveredAccountId: string; templateId: string; name?: string }[];+};++export type TImportPamDiscoveredAccountResult = {+ discoveredAccountId: string;+ status: string;+ accountId?: string;+ message?: string;+};+export type PamFolderPermissionSet = [PamResourcePermissionActions,PamResourcePermissionSub.PamResourcediff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.tsindex 32d620f9da..fcf62efba1 100644--- a/frontend/src/hooks/usePamSheetState.ts+++ b/frontend/src/hooks/usePamSheetState.ts@@ -14,10 +14,16 @@ export const pamSheetSearchParams = z.object({folderId: z.string().optional().catch(undefined),templateId: z.string().optional().catch(undefined),sessionId: z.string().optional().catch(undefined),+ discoverySourceId: z.string().optional().catch(undefined),tab: z.nativeEnum(PamSheetTab).optional().catch(undefined)});-export type PamSheetKey = "accountId" | "folderId" | "templateId" | "sessionId";+export type PamSheetKey =+ | "accountId"+ | "folderId"+ | "templateId"+ | "sessionId"+ | "discoverySourceId";export const usePamSheetState = (key: PamSheetKey) => {const navigate = useNavigate();diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsxindex 6a75e1a245..8d4cd582c0 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/PamNav.tsx@@ -1,4 +1,4 @@-import { ClipboardList, FileText, FolderOpen, KeyRound, Shield, Video } from "lucide-react";+import { ClipboardList, FileText, FolderOpen, KeyRound, Radar, Shield, Video } from "lucide-react";import { SidebarCollapsibleGroup } from "@app/components/v3";import { useGetPamAccessCapabilities } from "@app/hooks/api/pam";@@ -23,7 +23,8 @@ export const PamNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) =>: []),...(isProductAdmin? [{ label: "Account Templates", icon: ClipboardList, pathSuffix: "templates" }]- : [])+ : []),+ ...(isProductAdmin ? [{ label: "Discovery", icon: Radar, pathSuffix: "discovery" }] : [])];const monitorItems: NavItem[] = [diff --git a/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsxnew file mode 100644index 0000000000..89d8b5d420--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx@@ -0,0 +1,279 @@+import { useMemo, useState } from "react";+import { Helmet } from "react-helmet";+import { format } from "date-fns";+import { MoreHorizontal, Plus, Radar, Search, Trash2 } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { DeleteActionModal, PageHeader } from "@app/components/v2";+import { HighlightText } from "@app/components/v2/HighlightText";+import {+ Button,+ Card,+ CardContent,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { Skeleton } from "@app/components/v3/generic/Skeleton";+import {+ TPamDiscoverySource,+ useDeletePamDiscoverySource,+ useListPamDiscoverySources,+ useListPamDiscoveryTypes,+ useTriggerPamDiscoveryScan+} from "@app/hooks/api/pam";+import { ProjectType } from "@app/hooks/api/projects/types";+import { useDebounce } from "@app/hooks/useDebounce";+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 { DiscoverySourceDetailSheet } from "./components/DiscoverySourceDetailSheet";+import { DiscoveryStatusBadge } from "./components/DiscoveryStatusBadge";++export const PamDiscoveryPage = () => {+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const detailSheet = usePamSheetState("discoverySourceId");++ const { data: sources = [], isLoading } = useListPamDiscoverySources({+ search: debouncedSearch || undefined+ });+ const { data: discoveryTypes = [] } = useListPamDiscoveryTypes();+ const triggerScan = useTriggerPamDiscoveryScan();+ const deleteSource = useDeletePamDiscoverySource();++ const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([+ "addSource",+ "deleteSource"+ ] as const);++ const typeMap = useMemo(+ () => Object.fromEntries(discoveryTypes.map((t) => [t.type, t])),+ [discoveryTypes]+ );++ const filtered = useMemo(() => {+ const q = search.trim().toLowerCase();+ return q ? sources.filter((s) => s.name.toLowerCase().includes(q)) : sources;+ }, [sources, search]);++ const handleScan = (source: TPamDiscoverySource) => {+ triggerScan.mutate(+ { discoveryType: source.discoveryType, sourceId: source.id },+ { onSuccess: () => createNotification({ type: "success", text: "Scan started" }) }+ );+ };++ const handleDelete = async () => {+ const source = popUp.deleteSource.data as TPamDiscoverySource;+ await deleteSource.mutateAsync({ discoveryType: source.discoveryType, sourceId: source.id });+ createNotification({ type: "success", text: "Discovery source deleted" });+ handlePopUpClose("deleteSource");+ };++ return (+ <>+ <Helmet>+ <title>Discovery</title>+ </Helmet>+ <div className="mx-auto mb-6 w-full max-w-8xl">+ <PageHeader+ scope={ProjectType.PAM}+ icon={Radar}+ title="Discovery"+ description="Scan external systems for privileged accounts and import them into PAM."+ />++ <Card className="mt-4">+ <CardContent className="flex items-center gap-3">+ <InputGroup className="flex-1">+ <InputGroupAddon align="inline-start">+ <Search />+ </InputGroupAddon>+ <InputGroupInput+ placeholder="Search by name..."+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ />+ </InputGroup>+ <Button variant="pam" onClick={() => handlePopUpOpen("addSource")}>+ <Plus />+ Add Source+ </Button>+ </CardContent>++ {isLoading && (+ <CardContent>+ <div className="flex flex-col gap-3">+ <Skeleton className="h-10 w-full rounded-md" />+ <Skeleton className="h-10 w-full rounded-md" />+ </div>+ </CardContent>+ )}++ {!isLoading && filtered.length === 0 && (+ <CardContent>+ <Empty>+ <EmptyHeader>+ <EmptyTitle>No discovery sources yet</EmptyTitle>+ <EmptyDescription>Add a source to start discovering accounts.</EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ )}++ {!isLoading && filtered.length > 0 && (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Source</TableHead>+ <TableHead className="w-32">Status</TableHead>+ <TableHead className="w-32">Schedule</TableHead>+ <TableHead className="w-48">Last Run</TableHead>+ <TableHead className="w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {filtered.map((source) => {+ const meta = typeMap[source.discoveryType];+ return (+ <TableRow+ key={source.id}+ className="cursor-pointer"+ onClick={() => detailSheet.openSheet(source.id)}+ >+ <TableCell>+ <div className="flex items-center gap-2.5">+ {meta?.icon && (+ <img+ src={`/images/integrations/${meta.icon}`}+ alt={meta.name}+ className="size-5 rounded-sm"+ />+ )}+ <span className="font-medium text-foreground">+ <HighlightText text={source.name} highlight={search} />+ </span>+ <span className="text-sm text-muted">+ {meta?.name ?? source.discoveryType}+ </span>+ </div>+ </TableCell>+ <TableCell>+ <DiscoveryStatusBadge+ status={source.lastRunStatus}+ error={source.lastRunError}+ />+ </TableCell>+ <TableCell className="text-muted capitalize">{source.schedule}</TableCell>+ <TableCell className="text-muted">+ {source.lastRunAt+ ? format(new Date(source.lastRunAt), "MMM d, yyyy h:mm a")+ : "Never"}+ </TableCell>+ <TableCell className="w-12">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Source actions"+ className="text-muted"+ onClick={(e) => e.stopPropagation()}+ >+ <MoreHorizontal className="size-4" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={4}+ onClick={(e) => e.stopPropagation()}+ >+ {PAM_DISCOVERY_TABS.map((tab) => (+ <DropdownMenuItem+ key={tab.value}+ onClick={(e) => {+ e.stopPropagation();+ detailSheet.openSheet(source.id, tab.value);+ }}+ >+ <tab.icon />+ {tab.label}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ handleScan(source);+ }}+ >+ <Radar />+ Scan Now+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="danger"+ onClick={(e) => {+ e.stopPropagation();+ handlePopUpOpen("deleteSource", source);+ }}+ >+ <Trash2 />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}+ </Card>+ </div>++ <AddDiscoverySourceModal+ isOpen={popUp.addSource.isOpen}+ onOpenChange={(open) => {+ if (!open) handlePopUpClose("addSource");+ }}+ />++ <DiscoverySourceDetailSheet+ isOpen={detailSheet.isOpen}+ sourceId={detailSheet.selectedId}+ onOpenChange={(open) => {+ if (!open) detailSheet.closeSheet();+ }}+ />++ <DeleteActionModal+ isOpen={popUp.deleteSource.isOpen}+ onChange={(isOpen) => handlePopUpToggle("deleteSource", isOpen)}+ title={`Delete ${(popUp.deleteSource.data as TPamDiscoverySource | undefined)?.name ?? "source"}?`}+ deleteKey="confirm"+ onDeleteApproved={handleDelete}+ />+ </>+ );+};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsxnew file mode 100644index 0000000000..deebe769b5--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/AddDiscoverySourceModal.tsx@@ -0,0 +1,175 @@+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/DiscoveryConfigFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsxnew file mode 100644index 0000000000..dba5e670e8--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx@@ -0,0 +1,211 @@+import { Control, Controller, useWatch } from "react-hook-form";+import { z } from "zod";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ FilterableSelect,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+ TextArea+} from "@app/components/v3";+import { PamAccountType, PamDiscoverySchedule, useListPamAccountsAdmin } from "@app/hooks/api/pam";++export const discoveryConfigFormShape = {+ scanLocalAccounts: z.boolean(),+ winrmPort: z.coerce.number().int().min(1).max(65535),+ useWinrmHttps: z.boolean(),+ winrmRejectUnauthorized: z.boolean(),+ winrmCaCert: z.string()+};++export type TDiscoveryConfigFields = z.infer<z.ZodObject<typeof discoveryConfigFormShape>>;++export const DISCOVERY_CONFIG_DEFAULTS: TDiscoveryConfigFields = {+ scanLocalAccounts: true,+ winrmPort: 5985,+ useWinrmHttps: false,+ winrmRejectUnauthorized: true,+ winrmCaCert: ""+};++export const discoveryConfigFromSource = (+ config: Record<string, unknown>+): TDiscoveryConfigFields => ({+ scanLocalAccounts: config.scanLocalAccounts !== false,+ winrmPort:+ typeof config.winrmPort === "number" ? config.winrmPort : DISCOVERY_CONFIG_DEFAULTS.winrmPort,+ useWinrmHttps: Boolean(config.useWinrmHttps),+ winrmRejectUnauthorized: config.winrmRejectUnauthorized !== false,+ winrmCaCert: typeof config.winrmCaCert === "string" ? config.winrmCaCert : ""+});++export const buildDiscoveryConfiguration = (+ data: TDiscoveryConfigFields+): Record<string, unknown> => {+ if (!data.scanLocalAccounts) return { scanLocalAccounts: false };+ return {+ scanLocalAccounts: true,+ winrmPort: data.winrmPort,+ useWinrmHttps: data.useWinrmHttps,+ winrmRejectUnauthorized: data.winrmRejectUnauthorized,+ ...(data.winrmCaCert.trim() ? { winrmCaCert: data.winrmCaCert.trim() } : {})+ };+};++type ToggleName = "scanLocalAccounts" | "useWinrmHttps" | "winrmRejectUnauthorized";++const ToggleField = ({+ control,+ name,+ label+}: {+ control: Control<TDiscoveryConfigFields>;+ name: ToggleName;+ label: string;+}) => (+ <Controller+ control={control}+ name={name}+ render={({ field }) => (+ <Field>+ <div className="flex items-center justify-between gap-4">+ <FieldLabel htmlFor={name} className="mb-0">+ {label}+ </FieldLabel>+ <Switch id={name} variant="pam" checked={field.value} onCheckedChange={field.onChange} />+ </div>+ </Field>+ )}+ />+);++export const DiscoveryConfigFields = ({+ control+}: {+ control: Control<TDiscoveryConfigFields>;+}) => {+ const scanLocalAccounts = useWatch({ control, name: "scanLocalAccounts" });+ const useWinrmHttps = useWatch({ control, name: "useWinrmHttps" });++ return (+ <>+ <ToggleField control={control} name="scanLocalAccounts" label="Discover local accounts" />++ {scanLocalAccounts && (+ <>+ <Controller+ control={control}+ name="winrmPort"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>WinRM Port</FieldLabel>+ <FieldContent>+ <Input type="number" {...field} isError={!!fieldState.error} />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <ToggleField control={control} name="useWinrmHttps" label="Use HTTPS" />++ {useWinrmHttps && (+ <>+ <ToggleField+ control={control}+ name="winrmRejectUnauthorized"+ label="Reject Unauthorized"+ />++ <Controller+ control={control}+ name="winrmCaCert"+ render={({ field }) => (+ <Field>+ <FieldLabel>CA Certificate</FieldLabel>+ <FieldContent>+ <TextArea {...field} rows={4} placeholder="Optional PEM certificate" />+ <FieldDescription>Only needed with a private CA.</FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ </>+ )}+ </>+ )}+ </>+ );+};++// Shared credential-account + schedule fields, used by both the create modal and the edit tab.+export const CredentialAccountField = ({+ control+}: {+ control: Control<{ credentialAccountId: string }>;+}) => {+ const { data: accounts = [] } = useListPamAccountsAdmin();+ const credentialAccounts = accounts.filter((a) => a.accountType === PamAccountType.WindowsAd);++ return (+ <Controller+ control={control}+ name="credentialAccountId"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Credential Account</FieldLabel>+ <FieldContent>+ <FilterableSelect+ value={credentialAccounts.find((a) => a.id === field.value) ?? null}+ onChange={(val) =>+ field.onChange((val as (typeof credentialAccounts)[number] | null)?.id ?? "")+ }+ options={credentialAccounts}+ getOptionValue={(a) => a.id}+ getOptionLabel={(a) => (a.folderName ? `${a.folderName} / ${a.name}` : a.name)}+ placeholder="Select a Windows AD account"+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ );+};++export const ScheduleField = ({+ control+}: {+ control: Control<{ schedule: PamDiscoverySchedule }>;+}) => (+ <Controller+ control={control}+ name="schedule"+ render={({ field }) => (+ <Field>+ <FieldLabel>Scan Schedule</FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value={PamDiscoverySchedule.Manual}>Manual</SelectItem>+ <SelectItem value={PamDiscoverySchedule.Daily}>Daily</SelectItem>+ <SelectItem value={PamDiscoverySchedule.Weekly}>Weekly</SelectItem>+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ )}+ />+);diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsxnew file mode 100644index 0000000000..feda3b526c--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx@@ -0,0 +1,525 @@+import { Fragment, ReactNode, useEffect, useRef, useState } from "react";+import { Control, Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { useQueryClient } from "@tanstack/react-query";+import { format } from "date-fns";+import { Play, Radar, Search, TriangleAlert } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import { HighlightText } from "@app/components/v2/HighlightText";+import {+ Badge,+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyHeader,+ EmptyTitle,+ Field,+ FieldContent,+ FieldError,+ FieldLabel,+ GatewayPicker,+ Input,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { Checkbox } from "@app/components/v3/generic/Checkbox";+import {+ PamAccountType,+ PamDiscoverySchedule,+ pamKeys,+ TPamDiscoverySource,+ useListPamDiscoveredAccounts,+ useListPamDiscoveryRuns,+ useListPamDiscoverySources,+ useListPamDiscoveryTypes,+ usePamAccountTypeMap,+ useTriggerPamDiscoveryScan,+ useUpdatePamDiscoverySource+} from "@app/hooks/api/pam";+import { useDebounce } from "@app/hooks/useDebounce";+import { PamSheetTab, usePamSheetState } from "@app/hooks/usePamSheetState";++import { PamDetailSheet, PamDetailSheetTab } from "../../components/PamDetailSheet";+import { PAM_DISCOVERY_TABS } from "../../components/pamResourceTabs";+import { SheetSaveBar } from "../../components/SheetSaveBar";+import {+ buildDiscoveryConfiguration,+ CredentialAccountField,+ DiscoveryConfigFields,+ discoveryConfigFormShape,+ discoveryConfigFromSource,+ ScheduleField,+ TDiscoveryConfigFields+} from "./DiscoveryConfigFields";+import { DiscoveryStatusBadge } from "./DiscoveryStatusBadge";+import { ImportDiscoveredModal } from "./ImportDiscoveredModal";++const STATUS_VARIANT: Record<string, "info" | "success" | "danger" | "neutral"> = {+ running: "info",+ completed: "success",+ failed: "danger"+};++const RunStatusBadge = ({ status }: { status: string }) => (+ <Badge variant={STATUS_VARIANT[status] ?? "neutral"}>{status}</Badge>+);++const configSchema = z.object({+ name: z.string().min(1, "Name is required").max(64),+ credentialAccountId: z.string().uuid("Select a credential account"),+ schedule: z.nativeEnum(PamDiscoverySchedule),+ gatewayId: z.string().nullable(),+ gatewayPoolId: z.string().nullable(),+ ...discoveryConfigFormShape+});++type ConfigForm = z.infer<typeof configSchema>;++const ConfigurationTab = ({+ source,+ onDirtyChange+}: {+ source: TPamDiscoverySource;+ onDirtyChange: (isDirty: boolean) => void;+}) => {+ const updateSource = useUpdatePamDiscoverySource();++ const defaults: ConfigForm = {+ name: source.name,+ credentialAccountId: source.credentialAccountId,+ schedule: source.schedule,+ gatewayId: source.gatewayId ?? null,+ gatewayPoolId: source.gatewayPoolId ?? null,+ ...discoveryConfigFromSource(source.discoveryConfiguration)+ };++ const {+ control,+ handleSubmit,+ reset,+ watch,+ setValue,+ formState: { isDirty }+ } = useForm<ConfigForm>({ resolver: zodResolver(configSchema), defaultValues: defaults });++ useEffect(() => {+ onDirtyChange(isDirty);+ return () => onDirtyChange(false);+ }, [isDirty, onDirtyChange]);++ useEffect(() => {+ reset(defaults);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [source, reset]);++ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");++ const onSubmit = (data: ConfigForm) => {+ updateSource.mutate(+ {+ sourceId: source.id,+ discoveryType: source.discoveryType,+ name: data.name,+ credentialAccountId: data.credentialAccountId,+ schedule: data.schedule,+ gatewayId: data.gatewayId,+ gatewayPoolId: data.gatewayPoolId,+ configuration: buildDiscoveryConfiguration(data)+ },+ { onSuccess: () => createNotification({ type: "success", text: "Discovery source updated" }) }+ );+ };++ 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+ value={{ gatewayId, gatewayPoolId }}+ onChange={(value) => {+ setValue("gatewayId", value.gatewayId, { shouldDirty: true });+ setValue("gatewayPoolId", value.gatewayPoolId, { shouldDirty: true });+ }}+ />+ </FieldContent>+ </Field>++ <ScheduleField+ control={control as unknown as Control<{ schedule: PamDiscoverySchedule }>}+ />++ <DiscoveryConfigFields control={control as unknown as Control<TDiscoveryConfigFields>} />+ </CardContent>+ </Card>++ <div aria-hidden className="h-8 shrink-0" />+ {isDirty && <SheetSaveBar isPending={updateSource.isPending} onDiscard={() => reset()} />}+ </form>+ );+};++type Props = {+ isOpen: boolean;+ sourceId?: string;+ onOpenChange: (open: boolean) => void;+};++export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: Props) => {+ const [selected, setSelected] = useState<string[]>([]);+ const [isImportOpen, setIsImportOpen] = useState(false);+ const [isFormDirty, setIsFormDirty] = useState(false);+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);++ const { tab, setTab } = usePamSheetState("discoverySourceId");+ const { data: sources = [] } = useListPamDiscoverySources();+ const { data: discoveryTypes = [] } = useListPamDiscoveryTypes();+ const { map: accountTypeMap } = usePamAccountTypeMap();+ const source = sources.find((s) => s.id === sourceId);+ const typeMeta = discoveryTypes.find((t) => t.type === source?.discoveryType);++ const { data: runs = [] } = useListPamDiscoveryRuns(sourceId ?? "", {+ refetchInterval: isOpen ? 5000 : undefined+ });+ const { data: staged = [] } = useListPamDiscoveredAccounts(sourceId ?? "", debouncedSearch);+ const triggerScan = useTriggerPamDiscoveryScan();++ const queryClient = useQueryClient();+ const latestRunStatus = runs[0]?.status;+ const prevRunStatus = useRef(latestRunStatus);+ useEffect(() => {+ if (prevRunStatus.current === "running" && latestRunStatus && latestRunStatus !== "running") {+ queryClient.invalidateQueries({+ queryKey: [...pamKeys.discovery(), "discovered", sourceId ?? ""]+ });+ }+ prevRunStatus.current = latestRunStatus;+ }, [latestRunStatus, sourceId, queryClient]);++ const handleScan = () => {+ if (!source) return;+ triggerScan.mutate(+ { discoveryType: source.discoveryType, sourceId: source.id },+ { onSuccess: () => createNotification({ type: "success", text: "Scan started" }) }+ );+ };++ const q = search.trim().toLowerCase();+ const visibleStaged = q ? staged.filter((a) => a.name.toLowerCase().includes(q)) : staged;+ const selectedAccounts = staged.filter((a) => selected.includes(a.id));+ const allVisibleSelected =+ visibleStaged.length > 0 && visibleStaged.every((a) => selected.includes(a.id));+ const toggle = (id: string) =>+ setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));+ const toggleAll = () =>+ setSelected((prev) =>+ allVisibleSelected+ ? prev.filter((id) => !visibleStaged.some((a) => a.id === id))+ : Array.from(new Set([...prev, ...visibleStaged.map((a) => a.id)]))+ );++ const stagedTab: ReactNode = (+ <div className="flex flex-1 flex-col gap-4 p-4">+ <Card>+ <CardHeader className="border-b">+ <CardTitle className="text-base">Staged Accounts</CardTitle>+ <CardDescription>+ Accounts found by the last scan. Select accounts to import them into a folder.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ <InputGroup>+ <InputGroupAddon align="inline-start">+ <Search />+ </InputGroupAddon>+ <InputGroupInput+ placeholder="Search accounts..."+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ />+ </InputGroup>++ {visibleStaged.length === 0 ? (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>+ {search+ ? "No accounts match your search."+ : "No staged accounts. Run a scan to discover accounts."}+ </EmptyTitle>+ </EmptyHeader>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-8">+ <Checkbox+ id="select-all-discovered"+ isChecked={allVisibleSelected}+ onCheckedChange={toggleAll}+ />+ </TableHead>+ <TableHead>Name</TableHead>+ <TableHead className="w-40">Type</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {visibleStaged.map((account) => {+ const typeDetails = accountTypeMap[account.accountType as PamAccountType];+ return (+ <TableRow key={account.id}>+ <TableCell>+ <Checkbox+ id={`discovered-${account.id}`}+ isChecked={selected.includes(account.id)}+ onCheckedChange={() => toggle(account.id)}+ />+ </TableCell>+ <TableCell className="font-medium text-foreground">+ <HighlightText text={account.name} highlight={search} />+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ {typeDetails && (+ <img+ src={`/images/integrations/${typeDetails.icon}`}+ alt={typeDetails.name}+ className="size-5 shrink-0 rounded-sm"+ />+ )}+ <span className="text-sm">+ {typeDetails?.name ?? account.accountType}+ </span>+ </div>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>++ {selectedAccounts.length > 0 && (+ <div className="sticky bottom-0 -mx-4 mt-auto -mb-4 flex items-center gap-2 border-t border-border bg-popover px-4 py-3">+ <span className="mr-auto text-sm text-muted">{selectedAccounts.length} selected</span>+ <Button type="button" variant="ghost" onClick={() => setSelected([])}>+ Clear+ </Button>+ <Button type="button" variant="pam" onClick={() => setIsImportOpen(true)}>+ Import Accounts+ </Button>+ </div>+ )}+ </div>+ );++ const runsTab: ReactNode = (+ <div className="flex flex-1 flex-col gap-4 p-4">+ <Card>+ <CardHeader className="border-b">+ <CardTitle className="text-base">Scan History</CardTitle>+ <CardDescription>The result of each scan run for this source.</CardDescription>+ </CardHeader>+ <CardContent>+ {runs.length === 0 ? (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>This source has not been scanned yet.</EmptyTitle>+ </EmptyHeader>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Started</TableHead>+ <TableHead className="w-28">Status</TableHead>+ <TableHead>Result</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {runs.map((run) => {+ const machineErrors = run.machineErrors ?? [];+ // A completed run can still have per-machine failures; surface them full-width below the row+ const hasMachineErrors = run.status !== "failed" && machineErrors.length > 0;++ return (+ <Fragment key={run.id}>+ <TableRow className={hasMachineErrors ? "border-b-0" : undefined}>+ <TableCell className="text-muted">+ {run.startedAt+ ? format(new Date(run.startedAt), "MMM d, yyyy h:mm a")+ : "-"}+ </TableCell>+ <TableCell>+ <RunStatusBadge status={run.status} />+ </TableCell>+ <TableCell className="text-muted">+ {run.status === "failed" ? (+ <span className="whitespace-pre-line text-danger">+ {run.errorMessage}+ </span>+ ) : (+ `${run.discoveredCount} found, ${run.newCount} new`+ )}+ </TableCell>+ </TableRow>++ {hasMachineErrors && (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={3} className="pt-0 pb-4">+ <div className="rounded-md border border-warning/20 bg-warning/[0.06] p-3">+ <div className="flex items-center gap-2 text-sm font-medium text-warning">+ <TriangleAlert className="size-4 shrink-0" />+ The scan failed to find local accounts on certain machines+ </div>+ <ul className="mt-2 flex flex-col gap-1.5">+ {machineErrors.map((m) => (+ <li key={m.machine} className="text-xs">+ <span className="font-medium text-foreground">{m.machine}</span>+ <span className="text-muted">: {m.error}</span>+ </li>+ ))}+ </ul>+ </div>+ </TableCell>+ </TableRow>+ )}+ </Fragment>+ );+ })}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>+ </div>+ );++ const tabContent: Partial<Record<PamSheetTab, ReactNode>> = {+ [PamSheetTab.General]: stagedTab,+ [PamSheetTab.Advanced]: runsTab,+ [PamSheetTab.Configuration]: source ? (+ <ConfigurationTab source={source} onDirtyChange={setIsFormDirty} />+ ) : null+ };++ const tabs: PamDetailSheetTab[] = PAM_DISCOVERY_TABS.map((t) => ({+ value: t.value,+ label: t.label,+ icon: <t.icon className="mr-1 size-4" />,+ content: tabContent[t.value] ?? null+ }));++ return (+ <>+ <PamDetailSheet+ isOpen={isOpen}+ onOpenChange={(open) => {+ if (!open) {+ setSelected([]);+ setSearch("");+ }+ onOpenChange(open);+ }}+ isLoading={isOpen && !source}+ icon={+ <div className="mb-4 flex size-16 items-center justify-center rounded-lg border border-border bg-container">+ {typeMeta?.icon ? (+ <img+ src={`/images/integrations/${typeMeta.icon}`}+ alt={typeMeta.name}+ className="size-10 rounded-sm"+ />+ ) : (+ <Radar className="size-8 text-muted" />+ )}+ </div>+ }+ title={source?.name}+ typeBadge={typeMeta?.name ?? "Active Directory"}+ badges={<DiscoveryStatusBadge status={runs[0]?.status} error={runs[0]?.errorMessage} />}+ metadata={[+ { label: "Schedule", value: <span className="capitalize">{source?.schedule}</span> },+ {+ label: "Last Run",+ value: source?.lastRunAt+ ? format(new Date(source.lastRunAt), "MMM d, yyyy h:mm a")+ : "Never"+ }+ ]}+ footer={+ <Button+ variant="pam"+ size="xs"+ className="w-full"+ isPending={triggerScan.isPending}+ isDisabled={!source}+ onClick={handleScan}+ >+ <Play />+ Scan Now+ </Button>+ }+ tabs={tabs}+ activeTab={tab ?? PamSheetTab.General}+ onTabChange={setTab}+ isDirty={isFormDirty}+ />++ {sourceId && (+ <ImportDiscoveredModal+ isOpen={isImportOpen}+ onOpenChange={setIsImportOpen}+ sourceId={sourceId}+ accounts={selectedAccounts}+ onImported={() => setSelected([])}+ />+ )}+ </>+ );+};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryStatusBadge.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryStatusBadge.tsxnew file mode 100644index 0000000000..d0db124dcb--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryStatusBadge.tsx@@ -0,0 +1,35 @@+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";++const STATUS_MAP: Record<string, { label: string; variant: "info" | "success" | "danger" }> = {+ running: { label: "Running", variant: "info" },+ completed: { label: "Healthy", variant: "success" },+ failed: { label: "Failed", variant: "danger" }+};++export const DiscoveryStatusBadge = ({+ status,+ error+}: {+ status?: string | null;+ error?: string | null;+}) => {+ const meta = status ? STATUS_MAP[status] : undefined;+ if (!meta) return <Badge variant="neutral">Never scanned</Badge>;++ const badge = (+ <Badge variant={meta.variant} className={status === "running" ? "animate-pulse" : undefined}>+ {meta.label}+ </Badge>+ );++ if (status === "failed" && error) {+ return (+ <Tooltip>+ <TooltipTrigger>{badge}</TooltipTrigger>+ <TooltipContent>{error}</TooltipContent>+ </Tooltip>+ );+ }++ return badge;+};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsxnew file mode 100644index 0000000000..4dd59c1aa0--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/ImportDiscoveredModal.tsx@@ -0,0 +1,169 @@+import { useMemo, useState } from "react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import {+ PamAccountType,+ TPamDiscoveredAccount,+ useImportPamDiscoveredAccounts,+ useListPamAccountTemplates,+ useListPamFoldersAdmin,+ usePamAccountTypeMap+} from "@app/hooks/api/pam";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ sourceId: string;+ accounts: TPamDiscoveredAccount[];+ onImported: () => void;+};++export const ImportDiscoveredModal = ({+ isOpen,+ onOpenChange,+ sourceId,+ accounts,+ onImported+}: Props) => {+ const [folderId, setFolderId] = useState("");++ const [templateByType, setTemplateByType] = useState<Record<string, string>>({});++ const importAccounts = useImportPamDiscoveredAccounts();+ const { data: folders = [] } = useListPamFoldersAdmin();+ const { data: templates = [] } = useListPamAccountTemplates();+ const { map: accountTypeMap } = usePamAccountTypeMap();++ const accountTypes = useMemo(+ () => Array.from(new Set(accounts.map((a) => a.accountType))),+ [accounts]+ );++ const reset = () => {+ setFolderId("");+ setTemplateByType({});+ };++ const handleImport = () => {+ importAccounts.mutate(+ {+ sourceId,+ folderId,+ accounts: accounts.map((a) => ({+ discoveredAccountId: a.id,+ templateId: templateByType[a.accountType]+ }))+ },+ {+ onSuccess: (results) => {+ const imported = results.filter((r) => r.status === "imported").length;+ const failed = results.length - imported;+ createNotification({+ type: failed > 0 ? "info" : "success",+ text: `Imported ${imported} account${imported === 1 ? "" : "s"}${failed > 0 ? `, ${failed} failed` : ""}`+ });+ reset();+ onImported();+ onOpenChange(false);+ }+ }+ );+ };++ const canImport = Boolean(folderId) && accountTypes.every((type) => templateByType[type]);++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>+ Import {accounts.length} Account{accounts.length === 1 ? "" : "s"}+ </DialogTitle>+ </DialogHeader>+ <div className="flex flex-col gap-4">+ <Field>+ <FieldLabel>Destination Folder</FieldLabel>+ <FieldContent>+ <Select value={folderId} onValueChange={setFolderId}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a folder" />+ </SelectTrigger>+ <SelectContent position="popper">+ {folders.map((folder) => (+ <SelectItem key={folder.id} value={folder.id}>+ {folder.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>++ {accountTypes.map((type) => {+ const typeName = accountTypeMap[type as PamAccountType]?.name ?? type;+ const matchingTemplates = templates.filter((t) => t.type === type);+ return (+ <Field key={type}>+ <FieldLabel>{typeName} Template</FieldLabel>+ <FieldContent>+ <Select+ value={templateByType[type] ?? ""}+ onValueChange={(value) =>+ setTemplateByType((prev) => ({ ...prev, [type]: value }))+ }+ >+ <SelectTrigger className="w-full">+ <SelectValue placeholder={`Select a ${typeName} template`} />+ </SelectTrigger>+ <SelectContent position="popper">+ {matchingTemplates.map((template) => (+ <SelectItem key={template.id} value={template.id}>+ {template.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ );+ })}++ <p className="text-xs text-muted">+ Imported accounts come in without a credential and stay unusable until one is added.+ </p>+ </div>++ <DialogFooter>+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="pam"+ isDisabled={!canImport}+ isPending={importAccounts.isPending}+ onClick={handleImport}+ >+ Import+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/pam/PamDiscoveryPage/route.tsx b/frontend/src/pages/pam/PamDiscoveryPage/route.tsxnew file mode 100644index 0000000000..8627eb0122--- /dev/null+++ b/frontend/src/pages/pam/PamDiscoveryPage/route.tsx@@ -0,0 +1,19 @@+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";+import { zodValidator } from "@tanstack/zod-adapter";++import { pamSheetSearchParams } from "@app/hooks/usePamSheetState";++import { PamDiscoveryPage } from "./PamDiscoveryPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery"+)({+ validateSearch: zodValidator(pamSheetSearchParams),+ search: {+ middlewares: [stripSearchParams({ discoverySourceId: undefined })]+ },+ beforeLoad: ({ context }) => ({+ breadcrumbs: [...context.breadcrumbs, { label: "Discovery" }]+ }),+ component: PamDiscoveryPage+});diff --git a/frontend/src/pages/pam/components/PamDetailSheet.tsx b/frontend/src/pages/pam/components/PamDetailSheet.tsxindex 497e03df6c..4cac3a7e20 100644--- a/frontend/src/pages/pam/components/PamDetailSheet.tsx+++ b/frontend/src/pages/pam/components/PamDetailSheet.tsx@@ -50,8 +50,10 @@ type Props = {title?: string;subtitle?: ReactNode;typeBadge?: string;+ badges?: ReactNode;metadata?: MetadataField[];actions?: ReactNode;+ footer?: ReactNode;tabs?: PamDetailSheetTab[];activeTab?: string;onTabChange?: (tab: string) => void;@@ -107,8 +109,10 @@ export const PamDetailSheet = ({title,subtitle,typeBadge,+ badges,metadata = [],actions,+ footer,tabs,activeTab,onTabChange,@@ -161,9 +165,10 @@ export const PamDetailSheet = ({{title && <h2 className="text-lg font-semibold text-foreground">{title}</h2>}{subtitle && <p className="mt-0.5 text-sm text-muted">{subtitle}</p>}- {typeBadge && (- <div className="mt-2">- <Badge variant="neutral">{typeBadge}</Badge>+ {(typeBadge || badges) && (+ <div className="mt-2 flex flex-wrap items-center gap-2">+ {typeBadge && <Badge variant="neutral">{typeBadge}</Badge>}+ {badges}</div>)}@@ -179,6 +184,8 @@ export const PamDetailSheet = ({))}</div>)}++ {footer && <div className="mt-4">{footer}</div>}</div><div className="flex flex-1 flex-col overflow-y-auto">diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.tsindex e634d4bcb8..8edde509ed 100644--- a/frontend/src/pages/pam/components/pamResourceTabs.ts+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts@@ -1,4 +1,4 @@-import { type LucideIcon, Settings, Settings2, Users } from "lucide-react";+import { FolderOpen, History, type LucideIcon, Settings, Settings2, Users } from "lucide-react";import { PamResourcePermissionActions } from "@app/hooks/api/pam";import { PamSheetTab } from "@app/hooks/usePamSheetState";@@ -51,6 +51,12 @@ export const PAM_TEMPLATE_TABS: PamResourceTab[] = [{ value: PamSheetTab.Configuration, label: "Configuration", icon: Settings }];+export const PAM_DISCOVERY_TABS: PamResourceTab[] = [+ { value: PamSheetTab.General, label: "Staged Accounts", icon: FolderOpen },+ { value: PamSheetTab.Advanced, label: "Runs", icon: History },+ { value: PamSheetTab.Configuration, label: "Configuration", icon: Settings }+];+export const visiblePamTabs = (tabs: PamResourceTab[],can: (action: PamResourcePermissionActions) => booleandiff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex f350346b93..b1f2a77a56 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -86,6 +86,7 @@ import { Route as projectAccessControlPageRoutePamImport } from './pages/projectimport { Route as organizationSettingsPageOauthCallbackPageRouteImport } from './pages/organization/SettingsPage/OauthCallbackPage/route'import { Route as pamPamTemplatesPageRouteImport } from './pages/pam/PamTemplatesPage/route'import { Route as pamPamSessionsPageRouteImport } from './pages/pam/PamSessionsPage/route'+import { Route as pamPamDiscoveryPageRouteImport } from './pages/pam/PamDiscoveryPage/route'import { Route as pamPamAccountsPageRouteImport } from './pages/pam/PamAccountsPage/route'import { Route as organizationNetworkingPageRelayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/RelayDetailsByIDPage/route'import { Route as organizationNetworkingPageGatewayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/GatewayDetailsByIDPage/route'@@ -1109,6 +1110,12 @@ const pamPamSessionsPageRouteRoute = pamPamSessionsPageRouteImport.update({getParentRoute: () => pamLayoutRoute,} as any)+const pamPamDiscoveryPageRouteRoute = pamPamDiscoveryPageRouteImport.update({+ id: '/discovery',+ path: '/discovery',+ getParentRoute: () => pamLayoutRoute,+} as any)+const pamPamAccountsPageRouteRoute = pamPamAccountsPageRouteImport.update({id: '/accounts',path: '/accounts',@@ -3267,6 +3274,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof pamPamAccountsPageRouteImportparentRoute: typeof pamLayoutImport}+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery': {+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery'+ path: '/discovery'+ fullPath: '/organizations/$orgId/pam/discovery'+ preLoaderRoute: typeof pamPamDiscoveryPageRouteImport+ parentRoute: typeof pamLayoutImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions'path: '/sessions'@@ -5831,6 +5845,7 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRinterface pamLayoutRouteChildren {pamPamAccountsPageRouteRoute: typeof pamPamAccountsPageRouteRoute+ pamPamDiscoveryPageRouteRoute: typeof pamPamDiscoveryPageRouteRoutepamPamSessionsPageRouteRoute: typeof pamPamSessionsPageRouteRoutepamPamTemplatesPageRouteRoute: typeof pamPamTemplatesPageRouteRouteAuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren@@ -5844,6 +5859,7 @@ interface pamLayoutRouteChildren {const pamLayoutRouteChildren: pamLayoutRouteChildren = {pamPamAccountsPageRouteRoute: pamPamAccountsPageRouteRoute,+ pamPamDiscoveryPageRouteRoute: pamPamDiscoveryPageRouteRoute,pamPamSessionsPageRouteRoute: pamPamSessionsPageRouteRoute,pamPamTemplatesPageRouteRoute: pamPamTemplatesPageRouteRoute,AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRoute:@@ -6251,6 +6267,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/accounts': typeof pamPamAccountsPageRouteRoute+ '/organizations/$orgId/pam/discovery': typeof pamPamDiscoveryPageRouteRoute'/organizations/$orgId/pam/sessions': typeof pamPamSessionsPageRouteRoute'/organizations/$orgId/pam/templates': typeof pamPamTemplatesPageRouteRoute'/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute@@ -6537,6 +6554,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/accounts': typeof pamPamAccountsPageRouteRoute+ '/organizations/$orgId/pam/discovery': typeof pamPamDiscoveryPageRouteRoute'/organizations/$orgId/pam/sessions': typeof pamPamSessionsPageRouteRoute'/organizations/$orgId/pam/templates': typeof pamPamTemplatesPageRouteRoute'/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute@@ -6819,6 +6837,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts': typeof pamPamAccountsPageRouteRoute+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery': typeof pamPamDiscoveryPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions': typeof pamPamSessionsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates': typeof pamPamTemplatesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/settings/oauth/callback': typeof organizationSettingsPageOauthCallbackPageRouteRoute@@ -7120,6 +7139,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/accounts'+ | '/organizations/$orgId/pam/discovery'| '/organizations/$orgId/pam/sessions'| '/organizations/$orgId/pam/templates'| '/organizations/$orgId/settings/oauth/callback'@@ -7405,6 +7425,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/accounts'+ | '/organizations/$orgId/pam/discovery'| '/organizations/$orgId/pam/sessions'| '/organizations/$orgId/pam/templates'| '/organizations/$orgId/settings/oauth/callback'@@ -7685,6 +7706,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts'+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/settings/oauth/callback'@@ -8365,6 +8387,7 @@ export const routeTree = rootRoute"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam","children": ["/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/accounts",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/templates","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access",@@ -8403,6 +8426,10 @@ export const routeTree = rootRoute"filePath": "pam/PamAccountsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout"},+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/discovery": {+ "filePath": "pam/PamDiscoveryPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions": {"filePath": "pam/PamSessionsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 92e0bed2c6..3be9d572e3 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -399,6 +399,7 @@ const pamRoutes = route("/organizations/$orgId/pam", [route("/access", [index("pam/PamAccessPage/route.tsx")]),route("/accounts", "pam/PamAccountsPage/route.tsx"),route("/templates", "pam/PamTemplatesPage/route.tsx"),+ route("/discovery", "pam/PamDiscoveryPage/route.tsx"),route("/sessions", "pam/PamSessionsPage/route.tsx"),route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),