Skip to content

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

feat(pam): windows discovery base

x032205ef6efffb4182
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 917caa95a0..b8464a162e 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -29,6 +29,7 @@ import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-con
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-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 { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";
import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
@@ -368,6 +369,7 @@ declare module "fastify" {
pamAccount: TPamAccountServiceFactory;
pamSession: TPamSessionServiceFactory;
pamWebAccess: TPamWebAccessServiceFactory;
+ pamDiscoverySource: TPamDiscoverySourceServiceFactory;
mfaSession: TMfaSessionServiceFactory;
upgradePath: TUpgradePathService;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 09136cd3fa..d694721162 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -649,7 +649,37 @@ import {
TMicrosoftTeamsIntegrationsInsert,
TMicrosoftTeamsIntegrationsUpdate
} from "@app/db/schemas/microsoft-teams-integrations";
+import {
+ TPamAccountDependencies,
+ TPamAccountDependenciesInsert,
+ TPamAccountDependenciesUpdate
+} from "@app/db/schemas/pam-account-dependencies";
import { TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate } from "@app/db/schemas/pam-accounts";
+import {
+ TPamDiscoveryRuns,
+ TPamDiscoveryRunsInsert,
+ TPamDiscoveryRunsUpdate
+} from "@app/db/schemas/pam-discovery-runs";
+import {
+ TPamDiscoverySourceAccounts,
+ TPamDiscoverySourceAccountsInsert,
+ TPamDiscoverySourceAccountsUpdate
+} from "@app/db/schemas/pam-discovery-source-accounts";
+import {
+ TPamDiscoverySourceDependencies,
+ TPamDiscoverySourceDependenciesInsert,
+ TPamDiscoverySourceDependenciesUpdate
+} from "@app/db/schemas/pam-discovery-source-dependencies";
+import {
+ TPamDiscoverySourceResources,
+ TPamDiscoverySourceResourcesInsert,
+ TPamDiscoverySourceResourcesUpdate
+} from "@app/db/schemas/pam-discovery-source-resources";
+import {
+ TPamDiscoverySources,
+ TPamDiscoverySourcesInsert,
+ TPamDiscoverySourcesUpdate
+} from "@app/db/schemas/pam-discovery-sources";
import { TPamFolders, TPamFoldersInsert, TPamFoldersUpdate } from "@app/db/schemas/pam-folders";
import { TPamResources, TPamResourcesInsert, TPamResourcesUpdate } from "@app/db/schemas/pam-resources";
import { TPamSessions, TPamSessionsInsert, TPamSessionsUpdate } from "@app/db/schemas/pam-sessions";
@@ -1501,6 +1531,36 @@ declare module "knex/types/tables" {
[TableName.PamResource]: KnexOriginal.CompositeTableType<TPamResources, TPamResourcesInsert, TPamResourcesUpdate>;
[TableName.PamAccount]: KnexOriginal.CompositeTableType<TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate>;
[TableName.PamSession]: KnexOriginal.CompositeTableType<TPamSessions, TPamSessionsInsert, TPamSessionsUpdate>;
+ [TableName.PamDiscoverySource]: KnexOriginal.CompositeTableType<
+ TPamDiscoverySources,
+ TPamDiscoverySourcesInsert,
+ TPamDiscoverySourcesUpdate
+ >;
+ [TableName.PamDiscoveryRun]: KnexOriginal.CompositeTableType<
+ TPamDiscoveryRuns,
+ TPamDiscoveryRunsInsert,
+ TPamDiscoveryRunsUpdate
+ >;
+ [TableName.PamDiscoverySourceResource]: KnexOriginal.CompositeTableType<
+ TPamDiscoverySourceResources,
+ TPamDiscoverySourceResourcesInsert,
+ TPamDiscoverySourceResourcesUpdate
+ >;
+ [TableName.PamDiscoverySourceAccount]: KnexOriginal.CompositeTableType<
+ TPamDiscoverySourceAccounts,
+ TPamDiscoverySourceAccountsInsert,
+ TPamDiscoverySourceAccountsUpdate
+ >;
+ [TableName.PamDiscoverySourceDependency]: KnexOriginal.CompositeTableType<
+ TPamDiscoverySourceDependencies,
+ TPamDiscoverySourceDependenciesInsert,
+ TPamDiscoverySourceDependenciesUpdate
+ >;
+ [TableName.PamAccountDependency]: KnexOriginal.CompositeTableType<
+ TPamAccountDependencies,
+ TPamAccountDependenciesInsert,
+ TPamAccountDependenciesUpdate
+ >;
[TableName.Namespace]: KnexOriginal.CompositeTableType<TNamespaces, TNamespacesInsert, TNamespacesUpdate>;
[TableName.Membership]: KnexOriginal.CompositeTableType<TMemberships, TMembershipsInsert, TMembershipsUpdate>;
diff --git a/backend/src/db/migrations/20260219070359_pam-discovery.ts b/backend/src/db/migrations/20260219070359_pam-discovery.ts
new file mode 100644
index 0000000000..acc5b26e63
--- /dev/null
+++ b/backend/src/db/migrations/20260219070359_pam-discovery.ts
@@ -0,0 +1,195 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ // PAM Discovery Sources
+ if (!(await knex.schema.hasTable(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.unique(["projectId", "name"], { indexName: "uidx_pam_discovery_source_project_name" });
+
+ t.string("discoveryType").notNullable();
+
+ t.uuid("gatewayId").notNullable();
+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");
+ t.index("gatewayId");
+
+ t.binary("encryptedDiscoveryCredentials").notNullable();
+ t.jsonb("discoveryConfiguration").notNullable();
+
+ t.string("schedule").notNullable().defaultTo("manual");
+ t.datetime("lastRunAt").nullable();
+
+ t.string("status").notNullable().defaultTo("active");
+
+ t.timestamps(true, true, true);
+ });
+ }
+
+ // PAM Discovery Runs
+ if (!(await knex.schema.hasTable(TableName.PamDiscoveryRun))) {
+ await knex.schema.createTable(TableName.PamDiscoveryRun, (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.index("discoverySourceId");
+
+ t.string("status").notNullable();
+ t.string("triggeredBy").notNullable();
+
+ t.integer("resourcesDiscovered").defaultTo(0);
+ t.integer("accountsDiscovered").defaultTo(0);
+ t.integer("dependenciesDiscovered").defaultTo(0);
+ t.integer("newSinceLastRun").defaultTo(0);
+ t.integer("staleSinceLastRun").defaultTo(0);
+
+ t.jsonb("progress").notNullable();
+ t.text("errorMessage").nullable();
+
+ t.datetime("startedAt").nullable();
+ t.datetime("completedAt").nullable();
+
+ t.timestamps(true, true, true);
+ });
+ }
+
+ // PAM Account Dependencies
+ if (!(await knex.schema.hasTable(TableName.PamAccountDependency))) {
+ await knex.schema.createTable(TableName.PamAccountDependency, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("accountId").notNullable();
+ t.foreign("accountId").references("id").inTable(TableName.PamAccount).onDelete("CASCADE");
+ t.index("accountId");
+
+ t.uuid("resourceId").notNullable();
+ t.foreign("resourceId").references("id").inTable(TableName.PamResource).onDelete("CASCADE");
+ t.index("resourceId");
+
+ t.string("dependencyType").notNullable();
+ t.string("name").notNullable();
+ t.string("displayName").nullable();
+
+ t.string("state").nullable();
+ t.jsonb("data").notNullable();
+
+ t.string("source").notNullable();
+ t.boolean("isEnabled").defaultTo(false);
+
+ t.unique(["accountId", "resourceId", "dependencyType", "name"], {
+ indexName: "uidx_pam_account_dependency"
+ });
+
+ t.timestamps(true, true, true);
+ });
+ }
+
+ // PAM Discovery Source Resources (junction)
+ if (!(await knex.schema.hasTable(TableName.PamDiscoverySourceResource))) {
+ await knex.schema.createTable(TableName.PamDiscoverySourceResource, (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.index("discoverySourceId");
+
+ t.uuid("resourceId").notNullable();
+ t.foreign("resourceId").references("id").inTable(TableName.PamResource).onDelete("CASCADE");
+ t.index("resourceId");
+
+ t.datetime("lastDiscoveredAt").notNullable();
+
+ t.uuid("lastDiscoveredRunId").nullable();
+ t.foreign("lastDiscoveredRunId").references("id").inTable(TableName.PamDiscoveryRun).onDelete("SET NULL");
+
+ t.boolean("isStale").defaultTo(false);
+
+ t.timestamp("createdAt", { useTz: true }).defaultTo(knex.fn.now());
+
+ t.unique(["discoverySourceId", "resourceId"], {
+ indexName: "uidx_pam_discovery_source_resource"
+ });
+ });
+ }
+
+ // PAM Discovery Source Accounts (junction)
+ if (!(await knex.schema.hasTable(TableName.PamDiscoverySourceAccount))) {
+ await knex.schema.createTable(TableName.PamDiscoverySourceAccount, (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.index("discoverySourceId");
+
+ t.uuid("accountId").notNullable();
+ t.foreign("accountId").references("id").inTable(TableName.PamAccount).onDelete("CASCADE");
+ t.index("accountId");
+
+ t.datetime("lastDiscoveredAt").notNullable();
+
+ t.uuid("lastDiscoveredRunId").nullable();
+ t.foreign("lastDiscoveredRunId").references("id").inTable(TableName.PamDiscoveryRun).onDelete("SET NULL");
+
+ t.boolean("isStale").defaultTo(false);
+
+ t.timestamp("createdAt", { useTz: true }).defaultTo(knex.fn.now());
+
+ t.unique(["discoverySourceId", "accountId"], {
+ indexName: "uidx_pam_discovery_source_account"
+ });
+ });
+ }
+
+ // PAM Discovery Source Dependencies (junction)
+ if (!(await knex.schema.hasTable(TableName.PamDiscoverySourceDependency))) {
+ await knex.schema.createTable(TableName.PamDiscoverySourceDependency, (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.index("discoverySourceId");
+
+ t.uuid("dependencyId").notNullable();
+ t.foreign("dependencyId").references("id").inTable(TableName.PamAccountDependency).onDelete("CASCADE");
+ t.index("dependencyId");
+
+ t.datetime("lastSeenAt").notNullable();
+
+ t.uuid("lastSeenRunId").nullable();
+ t.foreign("lastSeenRunId").references("id").inTable(TableName.PamDiscoveryRun).onDelete("SET NULL");
+
+ t.boolean("isStale").defaultTo(false);
+
+ t.timestamp("createdAt", { useTz: true }).defaultTo(knex.fn.now());
+
+ t.unique(["discoverySourceId", "dependencyId"], {
+ indexName: "uidx_pam_discovery_source_dependency"
+ });
+ });
+ }
+
+ await createOnUpdateTrigger(knex, TableName.PamDiscoverySource);
+ await createOnUpdateTrigger(knex, TableName.PamDiscoveryRun);
+ await createOnUpdateTrigger(knex, TableName.PamAccountDependency);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceDependency);
+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceAccount);
+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySourceResource);
+ await knex.schema.dropTableIfExists(TableName.PamAccountDependency);
+ await knex.schema.dropTableIfExists(TableName.PamDiscoveryRun);
+ await knex.schema.dropTableIfExists(TableName.PamDiscoverySource);
+
+ await dropOnUpdateTrigger(knex, TableName.PamAccountDependency);
+ await dropOnUpdateTrigger(knex, TableName.PamDiscoveryRun);
+ await dropOnUpdateTrigger(knex, TableName.PamDiscoverySource);
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 9e017b7a62..5155dc6e19 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -106,7 +106,13 @@ export * from "./org-relay-config";
export * from "./org-roles";
export * from "./organization-assets";
export * from "./organizations";
+export * from "./pam-account-dependencies";
export * from "./pam-accounts";
+export * from "./pam-discovery-runs";
+export * from "./pam-discovery-source-accounts";
+export * from "./pam-discovery-source-dependencies";
+export * from "./pam-discovery-source-resources";
+export * from "./pam-discovery-sources";
export * from "./pam-folders";
export * from "./pam-resources";
export * from "./pam-sessions";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 61e0e88a31..f7835036d9 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -223,6 +223,12 @@ export enum TableName {
PamResource = "pam_resources",
PamAccount = "pam_accounts",
PamSession = "pam_sessions",
+ PamDiscoverySource = "pam_discovery_sources",
+ PamDiscoveryRun = "pam_discovery_runs",
+ PamDiscoverySourceResource = "pam_discovery_source_resources",
+ PamDiscoverySourceAccount = "pam_discovery_source_accounts",
+ PamDiscoverySourceDependency = "pam_discovery_source_dependencies",
+ PamAccountDependency = "pam_account_dependencies",
VaultExternalMigrationConfig = "vault_external_migration_configs",
diff --git a/backend/src/db/schemas/pam-account-dependencies.ts b/backend/src/db/schemas/pam-account-dependencies.ts
new file mode 100644
index 0000000000..2c26e7d171
--- /dev/null
+++ b/backend/src/db/schemas/pam-account-dependencies.ts
@@ -0,0 +1,29 @@
+// 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 { TImmutableDBKeys } from "./models";
+
+export const PamAccountDependenciesSchema = z.object({
+ id: z.string().uuid(),
+ accountId: z.string().uuid(),
+ resourceId: z.string().uuid(),
+ dependencyType: z.string(),
+ name: z.string(),
+ displayName: z.string().nullable().optional(),
+ state: z.string().nullable().optional(),
+ data: z.unknown(),
+ source: z.string(),
+ isEnabled: z.boolean().default(false).nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPamAccountDependencies = z.infer<typeof PamAccountDependenciesSchema>;
+export type TPamAccountDependenciesInsert = Omit<z.input<typeof PamAccountDependenciesSchema>, TImmutableDBKeys>;
+export type TPamAccountDependenciesUpdate = Partial<
+ Omit<z.input<typeof PamAccountDependenciesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pam-discovery-runs.ts b/backend/src/db/schemas/pam-discovery-runs.ts
new file mode 100644
index 0000000000..27921bd159
--- /dev/null
+++ b/backend/src/db/schemas/pam-discovery-runs.ts
@@ -0,0 +1,30 @@
+// 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 { TImmutableDBKeys } from "./models";
+
+export const PamDiscoveryRunsSchema = z.object({
+ id: z.string().uuid(),
+ discoverySourceId: z.string().uuid(),
+ status: z.string(),
+ triggeredBy: z.string(),
+ resourcesDiscovered: z.number().default(0).nullable().optional(),
+ accountsDiscovered: z.number().default(0).nullable().optional(),
+ dependenciesDiscovered: z.number().default(0).nullable().optional(),
+ newSinceLastRun: z.number().default(0).nullable().optional(),
+ staleSinceLastRun: z.number().default(0).nullable().optional(),
+ progress: z.unknown(),
+ errorMessage: z.string().nullable().optional(),
+ startedAt: z.date().nullable().optional(),
+ completedAt: z.date().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPamDiscoveryRuns = z.infer<typeof PamDiscoveryRunsSchema>;
+export type TPamDiscoveryRunsInsert = Omit<z.input<typeof PamDiscoveryRunsSchema>, TImmutableDBKeys>;
+export type TPamDiscoveryRunsUpdate = Partial<Omit<z.input<typeof PamDiscoveryRunsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/pam-discovery-source-accounts.ts b/backend/src/db/schemas/pam-discovery-source-accounts.ts
new file mode 100644
index 0000000000..2c2b34333d
--- /dev/null
+++ b/backend/src/db/schemas/pam-discovery-source-accounts.ts
@@ -0,0 +1,27 @@
+// 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 { TImmutableDBKeys } from "./models";
+
+export const PamDiscoverySourceAccountsSchema = z.object({
+ id: z.string().uuid(),
+ discoverySourceId: z.string().uuid(),
+ accountId: z.string().uuid(),
+ lastDiscoveredAt: z.date(),
+ lastDiscoveredRunId: z.string().uuid().nullable().optional(),
+ isStale: z.boolean().default(false).nullable().optional(),
+ createdAt: z.date().nullable().optional()
+});
+
+export type TPamDiscoverySourceAccounts = z.infer<typeof PamDiscoverySourceAccountsSchema>;
+export type TPamDiscoverySourceAccountsInsert = Omit<
+ z.input<typeof PamDiscoverySourceAccountsSchema>,
+ TImmutableDBKeys
+>;
+export type TPamDiscoverySourceAccountsUpdate = Partial<
+ Omit<z.input<typeof PamDiscoverySourceAccountsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pam-discovery-source-dependencies.ts b/backend/src/db/schemas/pam-discovery-source-dependencies.ts
new file mode 100644
index 0000000000..f9596f39e6
--- /dev/null
+++ b/backend/src/db/schemas/pam-discovery-source-dependencies.ts
@@ -0,0 +1,27 @@
+// 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 { TImmutableDBKeys } from "./models";
+
+export const PamDiscoverySourceDependenciesSchema = z.object({
+ id: z.string().uuid(),
+ discoverySourceId: z.string().uuid(),
+ dependencyId: z.string().uuid(),
+ lastSeenAt: z.date(),
+ lastSeenRunId: z.string().uuid().nullable().optional(),
+ isStale: z.boolean().default(false).nullable().optional(),
+ createdAt: z.date().nullable().optional()
+});
+
+export type TPamDiscoverySourceDependencies = z.infer<typeof PamDiscoverySourceDependenciesSchema>;
+export type TPamDiscoverySourceDependenciesInsert = Omit<
+ z.input<typeof PamDiscoverySourceDependenciesSchema>,
+ TImmutableDBKeys
+>;
+export type TPamDiscoverySourceDependenciesUpdate = Partial<
+ Omit<z.input<typeof PamDiscoverySourceDependenciesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pam-discovery-source-resources.ts b/backend/src/db/schemas/pam-discovery-source-resources.ts
new file mode 100644
index 0000000000..12f5c2a410
--- /dev/null
+++ b/backend/src/db/schemas/pam-discovery-source-resources.ts
@@ -0,0 +1,27 @@
+// 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 { TImmutableDBKeys } from "./models";
+
+export const PamDiscoverySourceResourcesSchema = z.object({
+ id: z.string().uuid(),
+ discoverySourceId: z.string().uuid(),
+ resourceId: z.string().uuid(),
+ lastDiscoveredAt: z.date(),
+ lastDiscoveredRunId: z.string().uuid().nullable().optional(),
+ isStale: z.boolean().default(false).nullable().optional(),
+ createdAt: z.date().nullable().optional()
+});
+
+export type TPamDiscoverySourceResources = z.infer<typeof PamDiscoverySourceResourcesSchema>;
+export type TPamDiscoverySourceResourcesInsert = Omit<
+ z.input<typeof PamDiscoverySourceResourcesSchema>,
+ TImmutableDBKeys
+>;
+export type TPamDiscoverySourceResourcesUpdate = Partial<
+ Omit<z.input<typeof PamDiscoverySourceResourcesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pam-discovery-sources.ts b/backend/src/db/schemas/pam-discovery-sources.ts
new file mode 100644
index 0000000000..d4d6e3bcf4
--- /dev/null
+++ b/backend/src/db/schemas/pam-discovery-sources.ts
@@ -0,0 +1,29 @@
+// 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 PamDiscoverySourcesSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ name: z.string(),
+ discoveryType: z.string(),
+ gatewayId: z.string().uuid(),
+ encryptedDiscoveryCredentials: zodBuffer,
+ discoveryConfiguration: z.unknown(),
+ schedule: z.string().default("manual"),
+ lastRunAt: z.date().nullable().optional(),
+ status: z.string().default("active"),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPamDiscoverySources = z.infer<typeof PamDiscoverySourcesSchema>;
+export type TPamDiscoverySourcesInsert = Omit<z.input<typeof PamDiscoverySourcesSchema>, TImmutableDBKeys>;
+export type TPamDiscoverySourcesUpdate = Partial<Omit<z.input<typeof PamDiscoverySourcesSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index ff8aceba03..254858742b 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -29,6 +29,8 @@ import { registerOidcRouter } from "./oidc-router";
import { registerOrgRoleRouter } from "./org-role-router";
import { PAM_ACCOUNT_REGISTER_ROUTER_MAP } from "./pam-account-routers";
import { registerPamAccountRouter } from "./pam-account-routers/pam-account-router";
+import { PAM_DISCOVERY_REGISTER_ROUTER_MAP } from "./pam-discovery-routers";
+import { registerPamDiscoveryRouter } from "./pam-discovery-routers/pam-discovery-router";
import { registerPamFolderRouter } from "./pam-folder-router";
import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";
import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";
@@ -199,6 +201,19 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
async (pamRouter) => {
await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });
await pamRouter.register(registerPamSessionRouter, { prefix: "/sessions" });
+ await pamRouter.register(
+ async (pamDiscoveryRouter) => {
+ await pamDiscoveryRouter.register(registerPamDiscoveryRouter);
+
+ // Discovery-type-specific endpoints
+ await Promise.all(
+ Object.entries(PAM_DISCOVERY_REGISTER_ROUTER_MAP).map(([provider, router]) =>
+ pamDiscoveryRouter.register(router, { prefix: `/${provider}` })
+ )
+ );
+ },
+ { prefix: "/discovery" }
+ );
await pamRouter.register(
async (pamAccountRouter) => {
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/index.ts b/backend/src/ee/routes/v1/pam-discovery-routers/index.ts
new file mode 100644
index 0000000000..fe1a4a773f
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-discovery-routers/index.ts
@@ -0,0 +1,25 @@
+import {
+ ActiveDirectoryDiscoverySourceRunSchema,
+ CreateActiveDirectoryDiscoverySourceSchema,
+ SanitizedActiveDirectoryDiscoverySourceSchema,
+ UpdateActiveDirectoryDiscoverySourceSchema
+} from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas";
+import { PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
+
+import { registerPamDiscoveryEndpoints } from "./pam-discovery-endpoints";
+
+export const PAM_DISCOVERY_REGISTER_ROUTER_MAP: Record<
+ PamDiscoveryType,
+ (server: FastifyZodProvider) => Promise<void>
+> = {
+ [PamDiscoveryType.ActiveDirectory]: async (server: FastifyZodProvider) => {
+ registerPamDiscoveryEndpoints({
+ server,
+ discoveryType: PamDiscoveryType.ActiveDirectory,
+ createDiscoverySourceSchema: CreateActiveDirectoryDiscoverySourceSchema,
+ updateDiscoverySourceSchema: UpdateActiveDirectoryDiscoverySourceSchema,
+ discoveryResponseSchema: SanitizedActiveDirectoryDiscoverySourceSchema,
+ discoveryRunResponseSchema: ActiveDirectoryDiscoverySourceRunSchema
+ });
+ }
+};
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts
new file mode 100644
index 0000000000..fad3e76d6c
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts
@@ -0,0 +1,351 @@
+import { z } from "zod";
+
+import { PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
+import {
+ DiscoveredAccountSchema,
+ DiscoveredResourceSchema
+} from "@app/ee/services/pam-discovery/pam-discovery-schemas";
+import { TPamDiscoverySource } from "@app/ee/services/pam-discovery/pam-discovery-types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerPamDiscoveryEndpoints = <T extends TPamDiscoverySource>({
+ server,
+ discoveryType,
+ createDiscoverySourceSchema,
+ updateDiscoverySourceSchema,
+ discoveryResponseSchema,
+ discoveryRunResponseSchema
+}: {
+ server: FastifyZodProvider;
+ discoveryType: PamDiscoveryType;
+ createDiscoverySourceSchema: z.ZodType<{
+ name: T["name"];
+ projectId: T["projectId"];
+ discoveryConfiguration: T["discoveryConfiguration"];
+ discoveryCredentials: T["discoveryCredentials"];
+ schedule: T["schedule"];
+ gatewayId: T["gatewayId"];
+ }>;
+ updateDiscoverySourceSchema: z.ZodType<{
+ name?: T["name"];
+ discoveryConfiguration?: T["discoveryConfiguration"];
+ discoveryCredentials?: T["discoveryCredentials"];
+ schedule?: T["schedule"];
+ gatewayId?: T["gatewayId"];
+ }>;
+ discoveryResponseSchema: z.ZodTypeAny;
+ discoveryRunResponseSchema: z.ZodTypeAny;
+}) => {
+ // Convert discovery type enum value to PascalCase for operation IDs
+ // e.g., "active-directory" -> "ActiveDirectory"
+ const discoveryTypeId = discoveryType
+ .split("-")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join("");
+
+ server.route({
+ method: "GET",
+ url: "/:discoverySourceId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `get${discoveryTypeId}PamDiscoverySource`,
+ description: "Get PAM Discovery Source",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ source: discoveryResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const source = await server.services.pamDiscoverySource.getById(
+ req.params.discoverySourceId,
+ discoveryType,
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { source };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: `create${discoveryTypeId}PamDiscoverySource`,
+ description: "Create PAM Discovery Source",
+ body: createDiscoverySourceSchema,
+ response: {
+ 200: z.object({
+ source: discoveryResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const source = await server.services.pamDiscoverySource.create(
+ {
+ ...req.body,
+ discoveryType
+ },
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { source };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:discoverySourceId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: `update${discoveryTypeId}PamDiscoverySource`,
+ description: "Update PAM Discovery Source",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ body: updateDiscoverySourceSchema,
+ response: {
+ 200: z.object({
+ source: discoveryResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const source = await server.services.pamDiscoverySource.updateById(
+ {
+ ...req.body,
+ discoverySourceId: req.params.discoverySourceId
+ },
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { source };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:discoverySourceId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: `delete${discoveryTypeId}PamDiscoverySource`,
+ description: "Delete PAM Discovery Source",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ source: discoveryResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const source = await server.services.pamDiscoverySource.deleteById(req.params.discoverySourceId, req.permission);
+
+ // TODO(andrey): Audit log
+
+ return { source };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:discoverySourceId/scan",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: `trigger${discoveryTypeId}PamDiscoverySourceScan`,
+ description: "Trigger PAM Discovery Source scan",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { message } = await server.services.pamDiscoverySource.triggerScanById(
+ req.params.discoverySourceId,
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { message };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:discoverySourceId/runs",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `get${discoveryTypeId}PamDiscoverySourceRuns`,
+ description: "Get PAM Discovery Source runs",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0),
+ limit: z.coerce.number().min(1).max(100).default(25)
+ }),
+ response: {
+ 200: z.object({
+ runs: discoveryRunResponseSchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { runs, totalCount } = await server.services.pamDiscoverySource.getDiscoveryRuns(
+ {
+ ...req.query,
+ discoverySourceId: req.params.discoverySourceId
+ },
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { runs, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:discoverySourceId/runs/:runId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `get${discoveryTypeId}PamDiscoverySourceRun`,
+ description: "Get PAM Discovery Source run",
+ params: z.object({
+ discoverySourceId: z.string().uuid(),
+ runId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ run: discoveryRunResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const run = await server.services.pamDiscoverySource.getDiscoveryRunById(req.params, req.permission);
+
+ // TODO(andrey): Audit log
+
+ return { run };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:discoverySourceId/resources",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `get${discoveryTypeId}PamDiscoverySourceResources`,
+ description: "Get PAM Discovery Source resources",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0),
+ limit: z.coerce.number().min(1).max(100).default(25)
+ }),
+ response: {
+ 200: z.object({
+ resources: DiscoveredResourceSchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { resources, totalCount } = await server.services.pamDiscoverySource.getDiscoveredResources(
+ {
+ ...req.query,
+ discoverySourceId: req.params.discoverySourceId
+ },
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { resources, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:discoverySourceId/accounts",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `get${discoveryTypeId}PamDiscoverySourceAccounts`,
+ description: "Get PAM Discovery Source accounts",
+ params: z.object({
+ discoverySourceId: z.string().uuid()
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0),
+ limit: z.coerce.number().min(1).max(100).default(25)
+ }),
+ response: {
+ 200: z.object({
+ accounts: DiscoveredAccountSchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { accounts, totalCount } = await server.services.pamDiscoverySource.getDiscoveredAccounts(
+ {
+ ...req.query,
+ discoverySourceId: req.params.discoverySourceId
+ },
+ req.permission
+ );
+
+ // TODO(andrey): Audit log
+
+ return { accounts, totalCount };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts
new file mode 100644
index 0000000000..47e8d053e5
--- /dev/null
+++ b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-router.ts
@@ -0,0 +1,88 @@
+import { z } from "zod";
+
+import {
+ ActiveDirectoryDiscoveryListItemSchema,
+ SanitizedActiveDirectoryDiscoverySourceSchema
+} from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas";
+import { PamDiscoveryOrderBy } from "@app/ee/services/pam-discovery/pam-discovery-enums";
+import { OrderByDirection } from "@app/lib/types";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const SanitizedDiscoverySourcesSchema = z.discriminatedUnion("discoveryType", [
+ SanitizedActiveDirectoryDiscoverySourceSchema
+]);
+
+const DiscoveryOptionsSchema = z.discriminatedUnion("discoveryType", [ActiveDirectoryDiscoveryListItemSchema]);
+
+export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/options",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "List PAM discovery types",
+ response: {
+ 200: z.object({
+ discoveryOptions: DiscoveryOptionsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: () => {
+ const discoveryOptions = server.services.pamDiscoverySource.listDiscoverySourceOptions();
+ return { discoveryOptions };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "List PAM discovery sources",
+ querystring: z.object({
+ projectId: z.string().uuid(),
+ offset: z.coerce.number().min(0).default(0),
+ limit: z.coerce.number().min(1).max(100).default(100),
+ orderBy: z.nativeEnum(PamDiscoveryOrderBy).default(PamDiscoveryOrderBy.Name),
+ orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC),
+ search: z.string().trim().optional(),
+ filterDiscoveryTypes: z
+ .string()
+ .transform((val) =>
+ val
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean)
+ )
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ sources: SanitizedDiscoverySourcesSchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { sources, totalCount } = await server.services.pamDiscoverySource.list({
+ ...req.query,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ // TODO(andrey): Audit log
+
+ return { sources, totalCount };
+ }
+ });
+};
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts
new file mode 100644
index 0000000000..64facb5bdc
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-fns.ts
@@ -0,0 +1,8 @@
+import { ActiveDirectoryDiscoveryListItemSchema } from "./active-directory-discovery-schemas";
+
+export const getActiveDirectorySourceListItem = () => {
+ return {
+ name: ActiveDirectoryDiscoveryListItemSchema.shape.name.value,
+ discoveryType: ActiveDirectoryDiscoveryListItemSchema.shape.discoveryType.value
+ };
+};
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.ts
new file mode 100644
index 0000000000..3531ffbd57
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-schemas.ts
@@ -0,0 +1,78 @@
+import { z } from "zod";
+
+import { PamDiscoveryType } from "../pam-discovery-enums";
+import {
+ BaseCreatePamDiscoverySourceSchema,
+ BasePamDiscoverySourceRunSchema,
+ BasePamDiscoverySourceSchema,
+ BaseUpdatePamDiscoverySourceSchema
+} from "../pam-discovery-schemas";
+
+// Discovery Source
+const BaseActiveDirectoryDiscoverySourceSchema = BasePamDiscoverySourceSchema.extend({
+ discoveryType: z.literal(PamDiscoveryType.ActiveDirectory)
+});
+
+export const ActiveDirectoryDiscoveryListItemSchema = z.object({
+ name: z.literal("Active Directory"),
+ discoveryType: z.literal(PamDiscoveryType.ActiveDirectory)
+});
+
+export const ActiveDirectoryDiscoveryConfigurationSchema = z.object({
+ domainFQDN: z.string().trim().min(1).max(255),
+ dcAddress: z.string().trim().min(1).max(255),
+ port: z.coerce.number().int().min(1).max(65535)
+});
+
+export const ActiveDirectoryDiscoveryCredentialsSchema = z.object({
+ username: z.string().trim().min(1).max(255),
+ password: z.string().trim().min(1).max(255)
+});
+
+export const ActiveDirectoryDiscoverySourceSchema = BaseActiveDirectoryDiscoverySourceSchema.extend({
+ discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
+ discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema
+});
+
+export const SanitizedActiveDirectoryDiscoverySourceSchema = BaseActiveDirectoryDiscoverySourceSchema.extend({
+ discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
+ discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema.pick({
+ username: true
+ })
+});
+
+export const CreateActiveDirectoryDiscoverySourceSchema = BaseCreatePamDiscoverySourceSchema.extend({
+ discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema,
+ discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema
+});
+
+export const UpdateActiveDirectoryDiscoverySourceSchema = BaseUpdatePamDiscoverySourceSchema.extend({
+ discoveryConfiguration: ActiveDirectoryDiscoveryConfigurationSchema.optional(),
+ discoveryCredentials: ActiveDirectoryDiscoveryCredentialsSchema.optional()
+});
+
+// Discovery Run
+const ActiveDirectoryDiscoverySourceRunProgressSchema = z.object({
+ // TODO(andrey): Revisit this schema
+ adEnumeration: z
+ .object({
+ status: z.enum(["running", "completed", "failed"]),
+ completedAt: z.date().optional(),
+ error: z.string().optional()
+ })
+ .optional(),
+ dependencyScan: z
+ .object({
+ status: z.enum(["running", "completed", "failed", "skipped"]),
+ totalMachines: z.number().optional(),
+ scannedMachines: z.number().optional(),
+ failedMachines: z.number().optional(),
+ reason: z.string().optional()
+ })
+ .optional(),
+ machineErrors: z.record(z.string(), z.string()).optional()
+});
+
+export const ActiveDirectoryDiscoverySourceRunSchema = BasePamDiscoverySourceRunSchema.extend({
+ progress: ActiveDirectoryDiscoverySourceRunProgressSchema
+});
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts
new file mode 100644
index 0000000000..6794315a65
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-types.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+
+import {
+ ActiveDirectoryDiscoveryConfigurationSchema,
+ ActiveDirectoryDiscoveryCredentialsSchema,
+ ActiveDirectoryDiscoverySourceSchema
+} from "./active-directory-discovery-schemas";
+
+export type TActiveDirectoryDiscoverySource = z.infer<typeof ActiveDirectoryDiscoverySourceSchema>;
+export type TActiveDirectoryDiscoveryCredentials = z.infer<typeof ActiveDirectoryDiscoveryCredentialsSchema>;
+export type TActiveDirectoryDiscoveryConfiguration = z.infer<typeof ActiveDirectoryDiscoveryConfigurationSchema>;
diff --git a/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts b/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts
new file mode 100644
index 0000000000..76d5f84599
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-account-dependencies-dal.ts
@@ -0,0 +1,79 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TPamAccountDependencies } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TPamAccountDependenciesDALFactory = ReturnType<typeof pamAccountDependenciesDALFactory>;
+
+export const pamAccountDependenciesDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamAccountDependency);
+
+ const findByAccountId = async (accountId: string, tx?: Knex) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.PamAccountDependency)
+ .where({ accountId })
+ .orderBy("name", "asc");
+
+ return docs as TPamAccountDependencies[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PAM account dependencies by account ID" });
+ }
+ };
+
+ const findByResourceId = async (resourceId: string, tx?: Knex) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.PamAccountDependency)
+ .where({ resourceId })
+ .orderBy("name", "asc");
+
+ return docs as TPamAccountDependencies[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PAM account dependencies by resource ID" });
+ }
+ };
+
+ const upsertDependency = async (
+ data: {
+ accountId: string;
+ resourceId: string;
+ dependencyType: string;
+ name: string;
+ displayName?: string | null;
+ state?: string | null;
+ data: Record<string, unknown>;
+ source: string;
+ },
+ tx?: Knex
+ ) => {
+ try {
+ const knex = tx || db;
+
+ const [doc] = await knex(TableName.PamAccountDependency)
+ .insert({
+ ...data,
+ isEnabled: false
+ })
+ .onConflict(["accountId", "resourceId", "dependencyType", "name"])
+ .merge({
+ displayName: data.displayName,
+ state: data.state,
+ data: data.data
+ // Note: isEnabled is NOT merged - preserves admin's explicit enable/disable
+ })
+ .returning("*");
+
+ return doc;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Upsert PAM account dependency" });
+ }
+ };
+
+ return {
+ ...orm,
+ findByAccountId,
+ findByResourceId,
+ upsertDependency
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts
new file mode 100644
index 0000000000..6545376a6c
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts
@@ -0,0 +1,47 @@
+// Discovery Sources
+export enum PamDiscoveryType {
+ ActiveDirectory = "active-directory"
+}
+
+export enum PamDiscoverySourceStatus {
+ Active = "active",
+ Paused = "paused",
+ Error = "error"
+}
+
+export enum PamDiscoverySchedule {
+ Manual = "manual",
+ Daily = "daily",
+ Weekly = "weekly"
+}
+
+export enum PamDiscoveryOrderBy {
+ Name = "name"
+}
+
+// Discovery Runs
+export enum PamDiscoveryRunStatus {
+ Pending = "pending",
+ Running = "running",
+ Completed = "completed",
+ CompletedWithErrors = "completed_with_errors",
+ Failed = "failed",
+ Stopped = "stopped"
+}
+
+export enum PamDiscoveryRunTrigger {
+ Manual = "manual",
+ Schedule = "schedule"
+}
+
+// Dependencies
+export enum PamAccountDependencyType {
+ WindowsService = "windows-service",
+ ScheduledTask = "scheduled-task",
+ IisAppPool = "iis-app-pool"
+}
+
+export enum PamAccountDependencySource {
+ Discovery = "discovery",
+ Manual = "manual"
+}
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts b/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts
new file mode 100644
index 0000000000..131e6fc9a5
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-factory.ts
@@ -0,0 +1,41 @@
+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TPamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
+import { activeDirectoryDiscoveryFactory } from "@app/ee/services/pam-discovery/active-directory/active-directory-discovery-factory";
+import { TPamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";
+import { PamDiscoveryType } from "@app/ee/services/pam-discovery/pam-discovery-enums";
+import { TPamDiscoveryRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-run-dal";
+import { TPamDiscoverySourceAccountsDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-accounts-dal";
+import { TPamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";
+import { TPamDiscoverySourceDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dependencies-dal";
+import { TPamDiscoverySourceResourcesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-resources-dal";
+import {
+ TPamDiscoveryConfiguration,
+ TPamDiscoveryCredentials,
+ TPamDiscoveryFactory
+} from "@app/ee/services/pam-discovery/pam-discovery-types";
+import { TPamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+export type TPamDiscoveryScanDeps = {
+ pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findById" | "updateById">;
+ pamDiscoveryRunDAL: Pick<TPamDiscoveryRunDALFactory, "create" | "updateById">;
+ pamDiscoverySourceResourcesDAL: Pick<TPamDiscoverySourceResourcesDALFactory, "upsertJunction" | "markStaleForRun">;
+ pamDiscoverySourceAccountsDAL: Pick<TPamDiscoverySourceAccountsDALFactory, "upsertJunction" | "markStaleForRun">;
+ pamDiscoverySourceDependenciesDAL: Pick<
+ TPamDiscoverySourceDependenciesDALFactory,
+ "upsertJunction" | "markStaleForRun"
+ >;
+ pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "upsertDependency">;
+ pamResourceDAL: Pick<TPamResourceDALFactory, "create" | "find" | "findById">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
+};
+
+type TPamDiscoveryFactoryImplementation = TPamDiscoveryFactory<TPamDiscoveryConfiguration, TPamDiscoveryCredentials>;
+
+export const PAM_DISCOVERY_FACTORY_MAP: Record<PamDiscoveryType, TPamDiscoveryFactoryImplementation> = {
+ [PamDiscoveryType.ActiveDirectory]: activeDirectoryDiscoveryFactory as TPamDiscoveryFactoryImplementation
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
new file mode 100644
index 0000000000..e4b979fa48
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -0,0 +1,70 @@
+import { TPamDiscoverySources } from "@app/db/schemas";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+import { getActiveDirectorySourceListItem } from "./active-directory/active-directory-discovery-fns";
+import { TPamDiscoveryConfiguration, TPamDiscoveryCredentials, TPamDiscoverySource } from "./pam-discovery-types";
+
+export const listDiscoverySourceOptions = () => {
+ return [getActiveDirectorySourceListItem()].sort((a, b) => a.name.localeCompare(b.name));
+};
+
+export const encryptDiscoveryCredentials = async ({
+ projectId,
+ credentials,
+ kmsService
+}: {
+ projectId: string;
+ credentials: TPamDiscoveryCredentials;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const { cipherTextBlob } = encryptor({
+ plainText: Buffer.from(JSON.stringify(credentials))
+ });
+
+ return cipherTextBlob;
+};
+
+export const decryptDiscoveryCredentials = async ({
+ projectId,
+ encryptedCredentials,
+ kmsService
+}: {
+ projectId: string;
+ encryptedCredentials: Buffer;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+}) => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const decryptedPlainTextBlob = decryptor({
+ cipherTextBlob: encryptedCredentials
+ });
+
+ return JSON.parse(decryptedPlainTextBlob.toString()) as TPamDiscoveryCredentials;
+};
+
+export const decryptDiscoverySource = async (
+ source: TPamDiscoverySources,
+ projectId: string,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+) => {
+ return {
+ ...source,
+ discoveryConfiguration: source.discoveryConfiguration as TPamDiscoveryConfiguration,
+ discoveryCredentials: source.encryptedDiscoveryCredentials
+ ? await decryptDiscoveryCredentials({
+ encryptedCredentials: source.encryptedDiscoveryCredentials,
+ projectId,
+ kmsService
+ })
+ : null
+ } as TPamDiscoverySource;
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
new file mode 100644
index 0000000000..5598348f01
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts
@@ -0,0 +1,155 @@
+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
+import { TPamAccountDependenciesDALFactory } from "./pam-account-dependencies-dal";
+import { PamDiscoveryType } from "./pam-discovery-enums";
+import { PAM_DISCOVERY_FACTORY_MAP } from "./pam-discovery-factory";
+import { decryptDiscoveryCredentials } from "./pam-discovery-fns";
+import { TPamDiscoveryRunDALFactory } from "./pam-discovery-run-dal";
+import { TPamDiscoverySourceAccountsDALFactory } from "./pam-discovery-source-accounts-dal";
+import { TPamDiscoverySourceDALFactory } from "./pam-discovery-source-dal";
+import { TPamDiscoverySourceDependenciesDALFactory } from "./pam-discovery-source-dependencies-dal";
+import { TPamDiscoverySourceResourcesDALFactory } from "./pam-discovery-source-resources-dal";
+import { TPamDiscoveryConfiguration } from "./pam-discovery-types";
+
+type TPamDiscoveryQueueFactoryDep = {
+ pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findById" | "updateById" | "findDueForScan">;
+ pamDiscoveryRunDAL: Pick<TPamDiscoveryRunDALFactory, "create" | "updateById">;
+ pamDiscoverySourceResourcesDAL: Pick<TPamDiscoverySourceResourcesDALFactory, "upsertJunction" | "markStaleForRun">;
+ pamDiscoverySourceAccountsDAL: Pick<TPamDiscoverySourceAccountsDALFactory, "upsertJunction" | "markStaleForRun">;
+ pamDiscoverySourceDependenciesDAL: Pick<
+ TPamDiscoverySourceDependenciesDALFactory,
+ "upsertJunction" | "markStaleForRun"
+ >;
+ pamAccountDependenciesDAL: Pick<TPamAccountDependenciesDALFactory, "upsertDependency">;
+ pamResourceDAL: Pick<TPamResourceDALFactory, "create" | "find" | "findById">;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "create" | "find">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ queueService: TQueueServiceFactory;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
+};
+
+export type TPamDiscoveryQueueFactory = ReturnType<typeof pamDiscoveryQueueFactory>;
+
+export const pamDiscoveryQueueFactory = ({
+ pamDiscoverySourceDAL,
+ pamDiscoveryRunDAL,
+ pamDiscoverySourceResourcesDAL,
+ pamDiscoverySourceAccountsDAL,
+ pamDiscoverySourceDependenciesDAL,
+ pamAccountDependenciesDAL,
+ pamResourceDAL,
+ pamAccountDAL,
+ kmsService,
+ queueService,
+ gatewayV2Service,
+ gatewayV2DAL
+}: TPamDiscoveryQueueFactoryDep) => {
+ const startPamDiscoveryQueue = () => {
+ queueService.start(QueueName.PamDiscoveryScan, async (job) => {
+ try {
+ if (job.name === QueueJobs.PamDiscoveryRunScan) {
+ const { discoverySourceId } = job.data as { discoverySourceId: string };
+
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ logger.error({ discoverySourceId }, "PAM Discovery Source not found, skipping scan");
+ return;
+ }
+
+ if (!discoverySource.gatewayId) {
+ logger.error({ discoverySourceId }, "PAM Discovery Source has no gateway configured, skipping scan");
+ return;
+ }
+
+ const discoveryType = discoverySource.discoveryType as PamDiscoveryType;
+
+ const credentials = await decryptDiscoveryCredentials({
+ projectId: discoverySource.projectId,
+ encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
+ kmsService
+ });
+
+ const configuration = discoverySource.discoveryConfiguration as TPamDiscoveryConfiguration;
+
+ const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](
+ discoveryType,
+ configuration,
+ credentials,
+ discoverySource.gatewayId,
+ discoverySource.projectId,
+ gatewayV2Service
+ );
+
+ const scanDeps = {
+ pamDiscoverySourceDAL,
+ pamDiscoveryRunDAL,
+ pamDiscoverySourceResourcesDAL,
+ pamDiscoverySourceAccountsDAL,
+ pamDiscoverySourceDependenciesDAL,
+ pamAccountDependenciesDAL,
+ pamResourceDAL,
+ pamAccountDAL,
+ kmsService,
+ gatewayV2Service,
+ gatewayV2DAL
+ };
+
+ await factory.scan(discoverySourceId, scanDeps);
+ } else if (job.name === QueueJobs.PamDiscoveryScheduledScan) {
+ const dueSources = await pamDiscoverySourceDAL.findDueForScan();
+
+ for await (const src of dueSources) {
+ await queueService.queue(
+ QueueName.PamDiscoveryScan,
+ QueueJobs.PamDiscoveryRunScan,
+ { discoverySourceId: src.id },
+ { jobId: `pam-discovery-scan-${src.id}` }
+ );
+ }
+ }
+ } catch (error) {
+ logger.error({ error, jobName: job.name, jobId: job.id }, "PAM Discovery queue job failed");
+ throw error;
+ }
+ });
+
+ void queueService
+ .queue(QueueName.PamDiscoveryScan, QueueJobs.PamDiscoveryScheduledScan, undefined, {
+ repeat: {
+ // runs every day at 3:00 AM
+ pattern: "0 3 * * *",
+ utc: true,
+ key: "pam-discovery-scheduled-scan"
+ },
+ jobId: "pam-discovery-scheduled-scan-cron"
+ })
+ .catch((err) => logger.error(err, "Failed to schedule PAM Discovery cron"));
+ };
+
+ const queuePamDiscoveryScan = async (discoverySourceId: string) => {
+ const jobId = `pam-discovery-scan-${discoverySourceId}-${Date.now()}`;
+ await queueService.queue(
+ QueueName.PamDiscoveryScan,
+ QueueJobs.PamDiscoveryRunScan,
+ { discoverySourceId },
+ {
+ jobId,
+ attempts: 1,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ };
+
+ return {
+ startPamDiscoveryQueue,
+ queuePamDiscoveryScan
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-run-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-run-dal.ts
new file mode 100644
index 0000000000..30e7338c98
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-run-dal.ts
@@ -0,0 +1,58 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TPamDiscoveryRuns } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+export type TPamDiscoveryRunDALFactory = ReturnType<typeof pamDiscoveryRunDALFactory>;
+
+export const pamDiscoveryRunDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamDiscoveryRun);
+
+ const findByDiscoverySourceId = async (
+ discoverySourceId: string,
+ { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
+ ) => {
+ try {
+ const dbInstance = tx || db.replicaNode();
+ const query = dbInstance(TableName.PamDiscoveryRun).where({ discoverySourceId });
+
+ const countQuery = query.clone().count("*", { as: "count" }).first();
+
+ void query.select(selectAllTableCols(TableName.PamDiscoveryRun));
+
+ void query.orderBy("createdAt", "desc");
+
+ if (typeof limit === "number") {
+ void query.limit(limit).offset(offset);
+ }
+
+ const [runs, countResult] = await Promise.all([query, countQuery]);
+ const totalCount = Number(countResult?.count || 0);
+
+ return { runs, totalCount };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PAM discovery runs by source ID" });
+ }
+ };
+
+ const findLatestBySourceId = async (discoverySourceId: string, tx?: Knex) => {
+ try {
+ const doc = await (tx || db.replicaNode())(TableName.PamDiscoveryRun)
+ .where({ discoverySourceId })
+ .orderBy("createdAt", "desc")
+ .first();
+
+ return (doc as TPamDiscoveryRuns) || null;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find latest PAM discovery run by source ID" });
+ }
+ };
+
+ return {
+ ...orm,
+ findByDiscoverySourceId,
+ findLatestBySourceId
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts
new file mode 100644
index 0000000000..a5cde51ac5
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts
@@ -0,0 +1,63 @@
+import { z } from "zod";
+
+import {
+ PamDiscoveryRunsSchema,
+ PamDiscoverySourceAccountsSchema,
+ PamDiscoverySourceResourcesSchema,
+ PamDiscoverySourcesSchema
+} from "@app/db/schemas";
+import { slugSchema } from "@app/server/lib/schemas";
+
+import { ActiveDirectoryAccountMetadataSchema } from "../pam-resource/active-directory/active-directory-resource-schemas";
+import { PamResource } from "../pam-resource/pam-resource-enums";
+import { WindowsAccountMetadataSchema } from "../pam-resource/windows-server/windows-server-resource-schemas";
+import {
+ PamDiscoveryRunStatus,
+ PamDiscoveryRunTrigger,
+ PamDiscoverySchedule,
+ PamDiscoverySourceStatus
+} from "./pam-discovery-enums";
+
+// Discovery Sources
+export const BasePamDiscoverySourceSchema = PamDiscoverySourcesSchema.omit({
+ discoveryType: true,
+ discoveryConfiguration: true,
+ encryptedDiscoveryCredentials: true
+}).extend({
+ schedule: z.nativeEnum(PamDiscoverySchedule),
+ status: z.nativeEnum(PamDiscoverySourceStatus)
+});
+
+export const BaseCreatePamDiscoverySourceSchema = z.object({
+ projectId: z.string().uuid(),
+ name: slugSchema({ field: "name" }),
+ gatewayId: z.string().uuid(),
+ schedule: z.nativeEnum(PamDiscoverySchedule)
+});
+
+export const BaseUpdatePamDiscoverySourceSchema = z.object({
+ name: slugSchema({ field: "name" }).optional(),
+ gatewayId: z.string().uuid().optional(),
+ schedule: z.nativeEnum(PamDiscoverySchedule).optional()
+});
+
+// Discovery Runs
+export const BasePamDiscoverySourceRunSchema = PamDiscoveryRunsSchema.omit({
+ progress: true
+}).extend({
+ status: z.nativeEnum(PamDiscoveryRunStatus),
+ triggeredBy: z.nativeEnum(PamDiscoveryRunTrigger)
+});
+
+export const DiscoveredResourceSchema = PamDiscoverySourceResourcesSchema.extend({
+ resourceName: z.string(),
+ resourceType: z.nativeEnum(PamResource)
+});
+
+export const DiscoveredAccountSchema = PamDiscoverySourceAccountsSchema.extend({
+ resourceType: z.nativeEnum(PamResource),
+ resourceName: z.string(),
+ resourceId: z.string().uuid(),
+ accountName: z.string(),
+ metadata: z.union([ActiveDirectoryAccountMetadataSchema, WindowsAccountMetadataSchema])
+});
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts
new file mode 100644
index 0000000000..3f44197d23
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-accounts-dal.ts
@@ -0,0 +1,115 @@
+import { Knex } from "knex";
+import { z } from "zod";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+import { DiscoveredAccountSchema } from "./pam-discovery-schemas";
+
+export type TPamDiscoverySourceAccountsDALFactory = ReturnType<typeof pamDiscoverySourceAccountsDALFactory>;
+
+export const pamDiscoverySourceAccountsDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamDiscoverySourceAccount);
+
+ const findByDiscoverySourceIdWithAccounts = async (
+ discoverySourceId: string,
+ { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
+ ) => {
+ try {
+ const dbInstance = tx || db.replicaNode();
+ const query = dbInstance(TableName.PamDiscoverySourceAccount)
+ .join(TableName.PamAccount, `${TableName.PamDiscoverySourceAccount}.accountId`, `${TableName.PamAccount}.id`)
+ .join(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`)
+ .where(`${TableName.PamDiscoverySourceAccount}.discoverySourceId`, discoverySourceId);
+
+ const countQuery = query.clone().count("*", { as: "count" }).first();
+
+ void query.select(
+ selectAllTableCols(TableName.PamDiscoverySourceResource),
+ db.ref("name").withSchema(TableName.PamAccount).as("accountName"),
+ db.ref("resourceId").withSchema(TableName.PamAccount).as("resourceId"),
+ db.ref("resourceType").withSchema(TableName.PamResource).as("resourceType"),
+ db.ref("metadata").withSchema(TableName.PamAccount).as("metadata"),
+ db.ref("name").withSchema(TableName.PamResource).as("resourceName")
+ );
+
+ void query.orderBy(`${TableName.PamAccount}.name`, "asc");
+
+ if (typeof limit === "number") {
+ void query.limit(limit).offset(offset);
+ }
+
+ const [accounts, countResult] = await Promise.all([query, countQuery]);
+ const totalCount = Number(countResult?.count || 0);
+
+ return {
+ accounts: accounts as unknown as z.infer<typeof DiscoveredAccountSchema>[],
+ totalCount
+ };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find discovered accounts by source ID" });
+ }
+ };
+
+ const upsertJunction = async (
+ {
+ discoverySourceId,
+ accountId,
+ lastDiscoveredRunId
+ }: {
+ discoverySourceId: string;
+ accountId: string;
+ lastDiscoveredRunId: string;
+ },
+ tx?: Knex
+ ) => {
+ try {
+ const now = new Date();
+ const knex = tx || db;
+
+ await knex(TableName.PamDiscoverySourceAccount)
+ .insert({
+ discoverySourceId,
+ accountId,
+ lastDiscoveredAt: now,
+ lastDiscoveredRunId,
+ isStale: false
+ })
+ .onConflict(["discoverySourceId", "accountId"])
+ .merge({
+ lastDiscoveredAt: now,
+ lastDiscoveredRunId,
+ isStale: false
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Upsert PAM discovery source account junction" });
+ }
+ };
+
+ const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
+ try {
+ const knex = tx || db;
+
+ const result = await knex(TableName.PamDiscoverySourceAccount)
+ .where({ discoverySourceId })
+ .andWhere((qb) => {
+ void qb.whereNull("lastDiscoveredRunId").orWhereNot("lastDiscoveredRunId", runId);
+ })
+ .andWhere("isStale", false)
+ .update({ isStale: true });
+
+ return result;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Mark stale PAM discovery source accounts" });
+ }
+ };
+
+ return {
+ ...orm,
+ findByDiscoverySourceIdWithAccounts,
+ upsertJunction,
+ markStaleForRun
+ };
+};
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.ts
new file mode 100644
index 0000000000..802c46a05c
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts
@@ -0,0 +1,119 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TPamDiscoverySources } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+import { OrderByDirection } from "@app/lib/types";
+
+import { PamDiscoveryOrderBy, PamDiscoveryRunStatus } from "./pam-discovery-enums";
+
+export type TPamDiscoverySourceDALFactory = ReturnType<typeof pamDiscoverySourceDALFactory>;
+
+export const pamDiscoverySourceDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamDiscoverySource);
+
+ const findByProjectId = async (
+ projectId: string,
+ {
+ offset = 0,
+ limit = 25,
+ search,
+ orderBy = PamDiscoveryOrderBy.Name,
+ orderDirection = OrderByDirection.ASC,
+ filterDiscoveryTypes,
+ tx
+ }: {
+ offset?: number;
+ limit?: number;
+ search?: string;
+ orderBy?: PamDiscoveryOrderBy;
+ orderDirection?: OrderByDirection;
+ filterDiscoveryTypes?: string[];
+ tx?: Knex;
+ } = {}
+ ) => {
+ try {
+ const dbInstance = tx || db.replicaNode();
+ const query = dbInstance(TableName.PamDiscoverySource).where(
+ `${TableName.PamDiscoverySource}.projectId`,
+ projectId
+ );
+
+ if (search) {
+ // escape special characters (`%`, `_`) and the escape character itself (`\`)
+ const escapedSearch = search.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
+ const pattern = `%${escapedSearch}%`;
+ void query.where((q) => {
+ void q
+ .whereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDiscoverySource, "name", pattern])
+ .orWhereRaw(`??.?? ILIKE ? ESCAPE '\\'`, [TableName.PamDiscoverySource, "discoveryType", pattern]);
+ });
+ }
+
+ if (filterDiscoveryTypes && filterDiscoveryTypes.length) {
+ void query.whereIn(`${TableName.PamDiscoverySource}.discoveryType`, filterDiscoveryTypes);
+ }
+
+ const countQuery = query.clone().count("*", { as: "count" }).first();
+
+ void query.select(selectAllTableCols(TableName.PamDiscoverySource));
+
+ const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC";
+
+ void query.orderByRaw(`${TableName.PamDiscoverySource}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]);
+
+ if (typeof limit === "number") {
+ void query.limit(limit).offset(offset);
+ }
+
+ const [sources, countResult] = await Promise.all([query, countQuery]);
+ const totalCount = Number(countResult?.count || 0);
+
+ return { sources, totalCount };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PAM Discovery Sources by project ID" });
+ }
+ };
+
+ const findDueForScan = async (tx?: Knex) => {
+ try {
+ const now = new Date();
+ const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
+
+ const docs = await (tx || db.replicaNode())(TableName.PamDiscoverySource)
+ .where({ status: "active" })
+ .andWhere((qb) => {
+ void qb.where({ schedule: "daily" }).orWhere({ schedule: "weekly" });
+ })
+ .andWhere((qb) => {
+ void qb
+ .whereNull("lastRunAt")
+ .orWhere((sub) => {
+ void sub.where({ schedule: "daily" }).andWhere("lastRunAt", "<=", oneDayAgo);
+ })
+ .orWhere((sub) => {
+ void sub.where({ schedule: "weekly" }).andWhere("lastRunAt", "<=", sevenDaysAgo);
+ });
+ })
+ // Exclude sources that have a running scan
+ .whereNotExists(
+ (tx || db.replicaNode())(TableName.PamDiscoveryRun)
+ .select(db.raw("1"))
+ .whereRaw(`"discoverySourceId" = ${TableName.PamDiscoverySource}."id"`)
+ .whereIn("status", [PamDiscoveryRunStatus.Pending, PamDiscoveryRunStatus.Running])
+ );
+
+ return docs as TPamDiscoverySources[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PAM Discovery Sources due for scan" });
+ }
+ };
+
+ return {
+ ...orm,
+ findByProjectId,
+ findDueForScan
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts
new file mode 100644
index 0000000000..2cff3a3937
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-dependencies-dal.ts
@@ -0,0 +1,85 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TPamDiscoverySourceDependenciesDALFactory = ReturnType<typeof pamDiscoverySourceDependenciesDALFactory>;
+
+export const pamDiscoverySourceDependenciesDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamDiscoverySourceDependency);
+
+ const countByDiscoverySourceId = async (discoverySourceId: string, tx?: Knex) => {
+ try {
+ const result = await (tx || db.replicaNode())(TableName.PamDiscoverySourceDependency)
+ .where({ discoverySourceId })
+ .count("id")
+ .first();
+
+ return parseInt(String(result?.count || "0"), 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count discovered dependencies by source ID" });
+ }
+ };
+
+ const upsertJunction = async (
+ {
+ discoverySourceId,
+ dependencyId,
+ lastSeenRunId
+ }: {
+ discoverySourceId: string;
+ dependencyId: string;
+ lastSeenRunId: string;
+ },
+ tx?: Knex
+ ) => {
+ try {
+ const now = new Date();
+ const knex = tx || db;
+
+ await knex(TableName.PamDiscoverySourceDependency)
+ .insert({
+ discoverySourceId,
+ dependencyId,
+ lastSeenAt: now,
+ lastSeenRunId,
+ isStale: false
+ })
+ .onConflict(["discoverySourceId", "dependencyId"])
+ .merge({
+ lastSeenAt: now,
+ lastSeenRunId,
+ isStale: false
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Upsert PAM discovery source dependency junction" });
+ }
+ };
+
+ const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
+ try {
+ const knex = tx || db;
+
+ const result = await knex(TableName.PamDiscoverySourceDependency)
+ .where({ discoverySourceId })
+ .andWhere((qb) => {
+ void qb.whereNull("lastSeenRunId").orWhereNot("lastSeenRunId", runId);
+ })
+ .andWhere("isStale", false)
+ .update({ isStale: true });
+
+ return result;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Mark stale PAM discovery source dependencies" });
+ }
+ };
+
+ return {
+ ...orm,
+ countByDiscoverySourceId,
+ upsertJunction,
+ markStaleForRun
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts
new file mode 100644
index 0000000000..5becc95379
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-resources-dal.ts
@@ -0,0 +1,115 @@
+import { Knex } from "knex";
+import { z } from "zod";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify, selectAllTableCols } from "@app/lib/knex";
+
+import { DiscoveredResourceSchema } from "./pam-discovery-schemas";
+
+export type TPamDiscoverySourceResourcesDALFactory = ReturnType<typeof pamDiscoverySourceResourcesDALFactory>;
+
+export const pamDiscoverySourceResourcesDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PamDiscoverySourceResource);
+
+ const findByDiscoverySourceIdWithResources = async (
+ discoverySourceId: string,
+ { offset = 0, limit = 25, tx }: { offset?: number; limit?: number; tx?: Knex } = {}
+ ) => {
+ try {
+ const dbInstance = tx || db.replicaNode();
+ const query = dbInstance(TableName.PamDiscoverySourceResource)
+ .join(
+ TableName.PamResource,
+ `${TableName.PamDiscoverySourceResource}.resourceId`,
+ `${TableName.PamResource}.id`
+ )
+ .where(`${TableName.PamDiscoverySourceResource}.discoverySourceId`, discoverySourceId);
+
+ const countQuery = query.clone().count("*", { as: "count" }).first();
+
+ void query.select(
+ selectAllTableCols(TableName.PamDiscoverySourceResource),
+ db.ref("name").withSchema(TableName.PamResource).as("resourceName"),
+ db.ref("resourceType").withSchema(TableName.PamResource).as("resourceType")
+ );
+
+ void query.orderBy(`${TableName.PamResource}.name`, "asc");
+
+ if (typeof limit === "number") {
+ void query.limit(limit).offset(offset);
+ }
+
+ const [resources, countResult] = await Promise.all([query, countQuery]);
+ const totalCount = Number(countResult?.count || 0);
+
+ return {
+ resources: resources as unknown as z.infer<typeof DiscoveredResourceSchema>[],
+ totalCount
+ };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find discovered resources by source ID" });
+ }
+ };
+
+ const upsertJunction = async (
+ {
+ discoverySourceId,
+ resourceId,
+ lastDiscoveredRunId
+ }: {
+ discoverySourceId: string;
+ resourceId: string;
+ lastDiscoveredRunId: string;
+ },
+ tx?: Knex
+ ) => {
+ try {
+ const now = new Date();
+ const knex = tx || db;
+
+ await knex(TableName.PamDiscoverySourceResource)
+ .insert({
+ discoverySourceId,
+ resourceId,
+ lastDiscoveredAt: now,
+ lastDiscoveredRunId,
+ isStale: false
+ })
+ .onConflict(["discoverySourceId", "resourceId"])
+ .merge({
+ lastDiscoveredAt: now,
+ lastDiscoveredRunId,
+ isStale: false
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Upsert PAM discovery source resource junction" });
+ }
+ };
+
+ const markStaleForRun = async (discoverySourceId: string, runId: string, tx?: Knex) => {
+ try {
+ const knex = tx || db;
+
+ const result = await knex(TableName.PamDiscoverySourceResource)
+ .where({ discoverySourceId })
+ .andWhere((qb) => {
+ void qb.whereNull("lastDiscoveredRunId").orWhereNot("lastDiscoveredRunId", runId);
+ })
+ .andWhere("isStale", false)
+ .update({ isStale: true });
+
+ return result;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Mark stale PAM discovery source resources" });
+ }
+ };
+
+ return {
+ ...orm,
+ findByDiscoverySourceIdWithResources,
+ upsertJunction,
+ markStaleForRun
+ };
+};
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.ts
new file mode 100644
index 0000000000..d9a062b0d4
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
@@ -0,0 +1,524 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, TPamDiscoverySources } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionPamDiscoveryActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { OrgServiceActor } from "@app/lib/types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
+import { PamDiscoveryRunStatus, PamDiscoverySourceStatus, PamDiscoveryType } from "./pam-discovery-enums";
+import { PAM_DISCOVERY_FACTORY_MAP } from "./pam-discovery-factory";
+import {
+ decryptDiscoveryCredentials,
+ decryptDiscoverySource,
+ encryptDiscoveryCredentials,
+ listDiscoverySourceOptions
+} from "./pam-discovery-fns";
+import { TPamDiscoveryQueueFactory } from "./pam-discovery-queue";
+import { TPamDiscoveryRunDALFactory } from "./pam-discovery-run-dal";
+import { TPamDiscoverySourceAccountsDALFactory } from "./pam-discovery-source-accounts-dal";
+import { TPamDiscoverySourceDALFactory } from "./pam-discovery-source-dal";
+import { TPamDiscoverySourceResourcesDALFactory } from "./pam-discovery-source-resources-dal";
+import {
+ TCreatePamDiscoverySourceDTO,
+ TGetDiscoveredAccountsDTO,
+ TGetDiscoveredResourcesDTO,
+ TGetPamDiscoveryRunDTO,
+ TGetPamDiscoveryRunsDTO,
+ TListPamDiscoverySourcesDTO,
+ TPamDiscoveryConfiguration,
+ TPamDiscoveryCredentials,
+ TUpdatePamDiscoverySourceDTO
+} from "./pam-discovery-types";
+
+type TPamDiscoverySourceServiceFactoryDep = {
+ pamDiscoverySourceDAL: Pick<
+ TPamDiscoverySourceDALFactory,
+ "create" | "findById" | "updateById" | "deleteById" | "findByProjectId"
+ >;
+ pamDiscoveryRunDAL: Pick<
+ TPamDiscoveryRunDALFactory,
+ "findByDiscoverySourceId" | "findLatestBySourceId" | "findById" | "find"
+ >;
+ pamDiscoverySourceResourcesDAL: Pick<TPamDiscoverySourceResourcesDALFactory, "findByDiscoverySourceIdWithResources">;
+ pamDiscoverySourceAccountsDAL: Pick<TPamDiscoverySourceAccountsDALFactory, "findByDiscoverySourceIdWithAccounts">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ pamDiscoveryQueue: Pick<TPamDiscoveryQueueFactory, "queuePamDiscoveryScan">;
+};
+
+export type TPamDiscoverySourceServiceFactory = ReturnType<typeof pamDiscoverySourceServiceFactory>;
+
+export const pamDiscoverySourceServiceFactory = ({
+ pamDiscoverySourceDAL,
+ pamDiscoveryRunDAL,
+ pamDiscoverySourceResourcesDAL,
+ pamDiscoverySourceAccountsDAL,
+ permissionService,
+ kmsService,
+ gatewayV2DAL,
+ gatewayV2Service,
+ pamDiscoveryQueue
+}: TPamDiscoverySourceServiceFactoryDep) => {
+ const create = async (
+ {
+ projectId,
+ name,
+ discoveryType,
+ gatewayId,
+ discoveryCredentials,
+ discoveryConfiguration,
+ schedule
+ }: TCreatePamDiscoverySourceDTO,
+ actor: OrgServiceActor
+ ) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Create,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ // Validate gateway exists
+ const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });
+ if (!gateway) {
+ throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });
+ }
+
+ const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](
+ discoveryType,
+ discoveryConfiguration,
+ discoveryCredentials,
+ gatewayId,
+ projectId,
+ gatewayV2Service
+ );
+ await factory.validateConnection();
+
+ const encryptedDiscoveryCredentials = await encryptDiscoveryCredentials({
+ projectId,
+ credentials: discoveryCredentials,
+ kmsService
+ });
+
+ try {
+ const discoverySource = await pamDiscoverySourceDAL.create({
+ projectId,
+ name,
+ discoveryType,
+ gatewayId,
+ encryptedDiscoveryCredentials,
+ discoveryConfiguration,
+ schedule,
+ status: PamDiscoverySourceStatus.Active
+ });
+
+ return await decryptDiscoverySource(discoverySource, projectId, kmsService);
+ } catch (err) {
+ if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ throw new BadRequestError({
+ message: `Discovery Source with name '${name}' already exists for this project`
+ });
+ }
+ throw err;
+ }
+ };
+
+ const updateById = async (
+ {
+ discoverySourceId,
+ name,
+ gatewayId,
+ discoveryCredentials,
+ discoveryConfiguration,
+ schedule
+ }: TUpdatePamDiscoverySourceDTO,
+ actor: OrgServiceActor
+ ) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Edit,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const updateDoc: Partial<TPamDiscoverySources> = {};
+
+ if (gatewayId) {
+ const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });
+ if (!gateway) {
+ throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });
+ }
+ updateDoc.gatewayId = gatewayId;
+ }
+
+ if (name !== undefined) updateDoc.name = name;
+ if (discoveryConfiguration !== undefined) updateDoc.discoveryConfiguration = discoveryConfiguration;
+ if (schedule !== undefined) updateDoc.schedule = schedule;
+
+ let finalCredentials: TPamDiscoveryCredentials | undefined;
+ if (discoveryCredentials) {
+ finalCredentials = { ...discoveryCredentials };
+
+ // Handle unchanged password sentinel
+ if (discoverySource.encryptedDiscoveryCredentials) {
+ const currentCredentials = await decryptDiscoveryCredentials({
+ projectId: discoverySource.projectId,
+ encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
+ kmsService
+ });
+
+ if (
+ "password" in finalCredentials &&
+ (finalCredentials as { password?: string }).password === "__INFISICAL_UNCHANGED__" &&
+ "password" in currentCredentials
+ ) {
+ finalCredentials = {
+ ...finalCredentials,
+ password: (currentCredentials as { password: string }).password
+ };
+ }
+ }
+
+ updateDoc.encryptedDiscoveryCredentials = await encryptDiscoveryCredentials({
+ projectId: discoverySource.projectId,
+ credentials: finalCredentials,
+ kmsService
+ });
+ }
+
+ // Validate if connection details changed
+ if (gatewayId || discoveryConfiguration || discoveryCredentials) {
+ const effectiveGatewayId = gatewayId ?? discoverySource.gatewayId;
+ const effectiveConfiguration = (discoveryConfiguration ??
+ discoverySource.discoveryConfiguration) as TPamDiscoveryConfiguration;
+
+ let effectiveCredentials = finalCredentials;
+ if (!effectiveCredentials && discoverySource.encryptedDiscoveryCredentials) {
+ effectiveCredentials = await decryptDiscoveryCredentials({
+ projectId: discoverySource.projectId,
+ encryptedCredentials: discoverySource.encryptedDiscoveryCredentials,
+ kmsService
+ });
+ }
+
+ if (effectiveGatewayId && effectiveCredentials) {
+ const factory = PAM_DISCOVERY_FACTORY_MAP[discoverySource.discoveryType as PamDiscoveryType](
+ discoverySource.discoveryType as PamDiscoveryType,
+ effectiveConfiguration,
+ effectiveCredentials,
+ effectiveGatewayId,
+ discoverySource.projectId,
+ gatewayV2Service
+ );
+ await factory.validateConnection();
+ }
+ }
+
+ // If nothing was updated, return the fetched resource
+ if (Object.keys(updateDoc).length === 0) {
+ return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
+ }
+
+ try {
+ const updatedResource = await pamDiscoverySourceDAL.updateById(discoverySourceId, updateDoc);
+ return await decryptDiscoverySource(updatedResource, discoverySource.projectId, kmsService);
+ } catch (err) {
+ if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ throw new BadRequestError({
+ message: `Discovery Source with name '${name}' already exists for this project`
+ });
+ }
+ throw err;
+ }
+ };
+
+ const deleteById = async (id: string, actor: OrgServiceActor) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(id);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${id}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Delete,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ await pamDiscoverySourceDAL.deleteById(id);
+
+ return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
+ };
+
+ const getById = async (id: string, discoveryType: PamDiscoveryType, actor: OrgServiceActor) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(id);
+ if (!discoverySource) throw new NotFoundError({ message: `Discovery source with ID '${id}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ if (discoverySource.discoveryType !== discoveryType) {
+ throw new BadRequestError({
+ message: `Discovery source with ID '${id}' is not of type '${discoveryType}'`
+ });
+ }
+
+ return decryptDiscoverySource(discoverySource, discoverySource.projectId, kmsService);
+ };
+
+ const list = async ({
+ projectId,
+ offset,
+ limit,
+ search,
+ orderBy,
+ orderDirection,
+ filterDiscoveryTypes,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TListPamDiscoverySourcesDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const { sources, totalCount } = await pamDiscoverySourceDAL.findByProjectId(projectId, {
+ offset,
+ limit,
+ search,
+ orderBy,
+ orderDirection,
+ filterDiscoveryTypes
+ });
+
+ return {
+ sources: await Promise.all(sources.map((src) => decryptDiscoverySource(src, projectId, kmsService))),
+ totalCount
+ };
+ };
+
+ const triggerScanById = async (id: string, actor: OrgServiceActor) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(id);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${id}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.RunScan,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ if (discoverySource.status !== PamDiscoverySourceStatus.Active) {
+ throw new BadRequestError({ message: "Cannot trigger scan on a non-active Discovery Source" });
+ }
+
+ // Check if a scan is already running
+ const latestRun = await pamDiscoveryRunDAL.findLatestBySourceId(id);
+ if (
+ latestRun &&
+ (latestRun.status === PamDiscoveryRunStatus.Pending || latestRun.status === PamDiscoveryRunStatus.Running)
+ ) {
+ throw new BadRequestError({ message: "A scan is already in progress for this Discovery Source" });
+ }
+
+ await pamDiscoveryQueue.queuePamDiscoveryScan(id);
+
+ return { message: "Scan queued successfully" };
+ };
+
+ const getDiscoveryRuns = async (
+ { discoverySourceId, offset, limit }: TGetPamDiscoveryRunsDTO,
+ actor: OrgServiceActor
+ ) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const result = await pamDiscoveryRunDAL.findByDiscoverySourceId(discoverySourceId, { offset, limit });
+ return result;
+ };
+
+ const getDiscoveryRunById = async ({ discoverySourceId, runId }: TGetPamDiscoveryRunDTO, actor: OrgServiceActor) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const run = await pamDiscoveryRunDAL.findById(runId);
+ if (!run || run.discoverySourceId !== discoverySourceId) {
+ throw new NotFoundError({ message: `Discovery Run with ID '${runId}' not found` });
+ }
+
+ return run;
+ };
+
+ const getDiscoveredResources = async (
+ { discoverySourceId, offset, limit }: TGetDiscoveredResourcesDTO,
+ actor: OrgServiceActor
+ ) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const result = await pamDiscoverySourceResourcesDAL.findByDiscoverySourceIdWithResources(discoverySourceId, {
+ offset,
+ limit
+ });
+ return result;
+ };
+
+ const getDiscoveredAccounts = async (
+ { discoverySourceId, offset, limit }: TGetDiscoveredAccountsDTO,
+ actor: OrgServiceActor
+ ) => {
+ const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);
+ if (!discoverySource) {
+ throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId: discoverySource.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionSub.PamDiscovery
+ );
+
+ const result = await pamDiscoverySourceAccountsDAL.findByDiscoverySourceIdWithAccounts(discoverySourceId, {
+ offset,
+ limit
+ });
+ return result;
+ };
+
+ return {
+ create,
+ updateById,
+ deleteById,
+ getById,
+ list,
+ triggerScanById,
+ getDiscoveryRuns,
+ getDiscoveryRunById,
+ getDiscoveredResources,
+ getDiscoveredAccounts,
+ listDiscoverySourceOptions
+ };
+};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
new file mode 100644
index 0000000000..43539ca390
--- /dev/null
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
@@ -0,0 +1,76 @@
+import { OrderByDirection, TProjectPermission } from "@app/lib/types";
+
+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
+import {
+ TActiveDirectoryDiscoveryConfiguration,
+ TActiveDirectoryDiscoveryCredentials,
+ TActiveDirectoryDiscoverySource
+} from "./active-directory/active-directory-discovery-types";
+import { PamDiscoveryOrderBy, PamDiscoveryType } from "./pam-discovery-enums";
+import { TPamDiscoveryScanDeps } from "./pam-discovery-factory";
+
+export type TPamDiscoverySource = TActiveDirectoryDiscoverySource;
+export type TPamDiscoveryCredentials = TActiveDirectoryDiscoveryCredentials;
+export type TPamDiscoveryConfiguration = TActiveDirectoryDiscoveryConfiguration;
+
+// Discovery Source DTOs
+export type TCreatePamDiscoverySourceDTO = Pick<
+ TPamDiscoverySource,
+ "name" | "projectId" | "discoveryType" | "discoveryConfiguration" | "schedule" | "gatewayId"
+> & {
+ discoveryCredentials: TPamDiscoveryCredentials;
+};
+
+export type TUpdatePamDiscoverySourceDTO = Partial<
+ Omit<TCreatePamDiscoverySourceDTO, "projectId" | "discoveryType">
+> & {
+ discoverySourceId: string;
+};
+
+export type TListPamDiscoverySourcesDTO = {
+ projectId: string;
+ offset?: number;
+ limit?: number;
+ search?: string;
+ orderBy?: PamDiscoveryOrderBy;
+ orderDirection?: OrderByDirection;
+ filterDiscoveryTypes?: string[];
+} & Omit<TProjectPermission, "projectId">;
+
+// Discovery Run DTOs
+export type TGetPamDiscoveryRunsDTO = {
+ discoverySourceId: string;
+ offset?: number;
+ limit?: number;
+};
+
+export type TGetPamDiscoveryRunDTO = {
+ discoverySourceId: string;
+ runId: string;
+};
+
+// Discovered items DTOs
+export type TGetDiscoveredResourcesDTO = {
+ discoverySourceId: string;
+ offset?: number;
+ limit?: number;
+};
+
+export type TGetDiscoveredAccountsDTO = {
+ discoverySourceId: string;
+ offset?: number;
+ limit?: number;
+};
+
+// Factory
+export type TPamDiscoveryFactory<T extends TPamDiscoveryConfiguration, C extends TPamDiscoveryCredentials> = (
+ discoveryType: PamDiscoveryType,
+ configuration: T,
+ credentials: C,
+ gatewayId: string,
+ projectId: string,
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
+) => {
+ validateConnection: () => Promise<void>;
+ scan: (discoverySourceId: string, deps: TPamDiscoveryScanDeps) => Promise<void>;
+};
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 369d1f3745..b9f7ae3ce5 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -19,6 +19,7 @@ import {
ProjectPermissionMcpEndpointActions,
ProjectPermissionMemberActions,
ProjectPermissionPamAccountActions,
+ ProjectPermissionPamDiscoveryActions,
ProjectPermissionPamSessionActions,
ProjectPermissionPkiCertificateInstallationActions,
ProjectPermissionPkiDiscoveryActions,
@@ -379,6 +380,17 @@ const buildAdminPermissionRules = () => {
can([ProjectPermissionPamSessionActions.Read], ProjectPermissionSub.PamSessions);
+ can(
+ [
+ ProjectPermissionPamDiscoveryActions.Read,
+ ProjectPermissionPamDiscoveryActions.Create,
+ ProjectPermissionPamDiscoveryActions.Edit,
+ ProjectPermissionPamDiscoveryActions.Delete,
+ ProjectPermissionPamDiscoveryActions.RunScan
+ ],
+ ProjectPermissionSub.PamDiscovery
+ );
+
can(
[
ProjectPermissionMcpEndpointActions.Read,
@@ -653,6 +665,8 @@ const buildMemberPermissionRules = () => {
ProjectPermissionSub.PamAccounts
);
+ can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);
+
can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);
can([ProjectPermissionActions.Read], ProjectPermissionSub.McpServers);
can([ProjectPermissionActions.Read], ProjectPermissionSub.McpActivityLogs);
@@ -729,6 +743,8 @@ const buildViewerPermissionRules = () => {
can([ProjectPermissionPamAccountActions.Read], ProjectPermissionSub.PamAccounts);
+ can([ProjectPermissionPamDiscoveryActions.Read], ProjectPermissionSub.PamDiscovery);
+
can([ProjectPermissionMcpEndpointActions.Read], ProjectPermissionSub.McpEndpoints);
can([ProjectPermissionActions.Read], ProjectPermissionSub.McpServers);
can([ProjectPermissionActions.Read], ProjectPermissionSub.McpActivityLogs);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 5103f01145..39cbe8f178 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -246,6 +246,14 @@ export enum ProjectPermissionPamSessionActions {
// Terminate = "terminate"
}
+export enum ProjectPermissionPamDiscoveryActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ RunScan = "run-scan"
+}
+
export enum ProjectPermissionMcpEndpointActions {
Read = "read",
Create = "create",
@@ -321,6 +329,7 @@ export enum ProjectPermissionSub {
PamResources = "pam-resources",
PamAccounts = "pam-accounts",
PamSessions = "pam-sessions",
+ PamDiscovery = "pam-discovery",
CertificateProfiles = "certificate-profiles",
CertificatePolicies = "certificate-policies",
ApprovalRequests = "approval-requests",
@@ -557,6 +566,7 @@ export type ProjectPermissionSet =
ProjectPermissionSub.PamAccounts | (ForcedSubject<ProjectPermissionSub.PamAccounts> & PamAccountSubjectFields)
]
| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]
+ | [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]
| [
ProjectPermissionMcpEndpointActions,
ProjectPermissionSub.McpEndpoints | (ForcedSubject<ProjectPermissionSub.McpEndpoints> & McpEndpointSubjectFields)
@@ -1247,6 +1257,12 @@ const GeneralPermissionSchema = [
"Describe what action an entity can take."
)
}),
+ z.object({
+ subject: z.literal(ProjectPermissionSub.PamDiscovery).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionPamDiscoveryActions).describe(
+ "Describe what action an entity can take."
+ )
+ }),
z.object({
subject: z.literal(ProjectPermissionSub.McpEndpoints).describe("The entity this permission pertains to."),
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 0fa2884eec..451586b162 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -95,7 +95,8 @@ export enum QueueName {
PamAccountRotation = "pam-account-rotation",
PamSessionExpiration = "pam-session-expiration",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
- PkiDiscoveryScan = "pki-discovery-scan"
+ PkiDiscoveryScan = "pki-discovery-scan",
+ PamDiscoveryScan = "pam-discovery-scan"
}
export enum QueueJobs {
@@ -158,7 +159,9 @@ export enum QueueJobs {
PamSessionExpiration = "pam-session-expiration",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryRunScan = "pki-discovery-run-scan",
- PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan"
+ PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",
+ PamDiscoveryRunScan = "pam-discovery-run-scan",
+ PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan"
}
export type TQueueOptions = {
@@ -480,6 +483,15 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiDiscoveryScheduledScan;
payload: undefined;
};
+ [QueueName.PamDiscoveryScan]:
+ | {
+ name: QueueJobs.PamDiscoveryRunScan;
+ payload: { discoverySourceId: string };
+ }
+ | {
+ name: QueueJobs.PamDiscoveryScheduledScan;
+ payload: undefined;
+ };
};
const SECRET_SCANNING_QUEUES = [
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7334d3bf6e..285aa20601 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -83,6 +83,14 @@ import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
import { pamAccountDALFactory } from "@app/ee/services/pam-account/pam-account-dal";
import { pamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
+import { pamAccountDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-account-dependencies-dal";
+import { pamDiscoveryQueueFactory } from "@app/ee/services/pam-discovery/pam-discovery-queue";
+import { pamDiscoveryRunDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-run-dal";
+import { pamDiscoverySourceAccountsDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-accounts-dal";
+import { pamDiscoverySourceDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dal";
+import { pamDiscoverySourceDependenciesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-dependencies-dal";
+import { pamDiscoverySourceResourcesDALFactory } from "@app/ee/services/pam-discovery/pam-discovery-source-resources-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 { pamResourceDALFactory } from "@app/ee/services/pam-resource/pam-resource-dal";
@@ -2598,6 +2606,12 @@ export const registerRoutes = async (
const pamResourceDAL = pamResourceDALFactory(db);
const pamAccountDAL = pamAccountDALFactory(db);
const pamSessionDAL = pamSessionDALFactory(db);
+ const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);
+ const pamDiscoveryRunDAL = pamDiscoveryRunDALFactory(db);
+ const pamDiscoverySourceResourcesDAL = pamDiscoverySourceResourcesDALFactory(db);
+ const pamDiscoverySourceAccountsDAL = pamDiscoverySourceAccountsDALFactory(db);
+ const pamDiscoverySourceDependenciesDAL = pamDiscoverySourceDependenciesDALFactory(db);
+ const pamAccountDependenciesDAL = pamAccountDependenciesDALFactory(db);
const aiMcpServerDAL = aiMcpServerDALFactory(db);
const aiMcpServerToolDAL = aiMcpServerToolDALFactory(db);
const aiMcpServerUserCredentialDAL = aiMcpServerUserCredentialDALFactory(db);
@@ -2680,6 +2694,33 @@ export const registerRoutes = async (
projectDAL
});
+ const pamDiscoveryQueue = pamDiscoveryQueueFactory({
+ pamDiscoverySourceDAL,
+ pamDiscoveryRunDAL,
+ pamDiscoverySourceResourcesDAL,
+ pamDiscoverySourceAccountsDAL,
+ pamDiscoverySourceDependenciesDAL,
+ pamAccountDependenciesDAL,
+ pamResourceDAL,
+ pamAccountDAL,
+ kmsService,
+ queueService,
+ gatewayV2Service,
+ gatewayV2DAL
+ });
+
+ const pamDiscoverySourceService = pamDiscoverySourceServiceFactory({
+ pamDiscoverySourceDAL,
+ pamDiscoveryRunDAL,
+ pamDiscoverySourceResourcesDAL,
+ pamDiscoverySourceAccountsDAL,
+ permissionService,
+ kmsService,
+ gatewayV2DAL,
+ gatewayV2Service,
+ pamDiscoveryQueue
+ });
+
const aiMcpServerService = aiMcpServerServiceFactory({
aiMcpServerDAL,
aiMcpServerToolDAL,
@@ -2765,6 +2806,7 @@ export const registerRoutes = async (
await healthAlert.init();
await pkiSyncCleanup.init();
pkiDiscoveryQueue.startPkiDiscoveryScanQueue();
+ pamDiscoveryQueue.startPamDiscoveryQueue();
await pamAccountRotation.init();
pamSessionExpirationService.init();
await dailyReminderQueueService.startDailyRemindersJob();
@@ -2902,6 +2944,7 @@ export const registerRoutes = async (
pamAccount: pamAccountService,
pamSession: pamSessionService,
pamWebAccess: pamWebAccessService,
+ pamDiscoverySource: pamDiscoverySourceService,
mfaSession: mfaSessionService,
upgradePath: upgradePathService,
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index 27ddc3fa58..5452bf154e 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -381,6 +381,14 @@ export const ROUTE_PATHS = Object.freeze({
PamAccountAccessPage: setRoute(
"/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",
"/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"
+ ),
+ DiscoveryPage: setRoute(
+ "/organizations/$orgId/projects/pam/$projectId/discovery",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/"
+ ),
+ PamDiscoveryByIDPage: setRoute(
+ "/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId"
)
},
Public: {
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index d4c50f7704..1450ace810 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -250,6 +250,14 @@ export enum ProjectPermissionPamSessionActions {
// Terminate = "terminate"
}
+export enum ProjectPermissionPamDiscoveryActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ RunScan = "run-scan"
+}
+
export enum ProjectPermissionMcpEndpointActions {
Read = "read",
Create = "create",
@@ -390,6 +398,7 @@ export enum ProjectPermissionSub {
PamResources = "pam-resources",
PamAccounts = "pam-accounts",
PamSessions = "pam-sessions",
+ PamDiscovery = "pam-discovery",
McpEndpoints = "mcp-endpoints",
McpServers = "mcp-servers",
McpActivityLogs = "mcp-activity-logs",
@@ -654,6 +663,7 @@ export type ProjectPermissionSet =
)
]
| [ProjectPermissionPamSessionActions, ProjectPermissionSub.PamSessions]
+ | [ProjectPermissionPamDiscoveryActions, ProjectPermissionSub.PamDiscovery]
| [ProjectPermissionApprovalRequestActions, ProjectPermissionSub.ApprovalRequests]
| [ProjectPermissionApprovalRequestGrantActions, ProjectPermissionSub.ApprovalRequestGrants]
| [ProjectPermissionSecretApprovalRequestActions, ProjectPermissionSub.SecretApprovalRequest]
diff --git a/frontend/src/hooks/api/pamDiscovery/index.tsx b/frontend/src/hooks/api/pamDiscovery/index.tsx
new file mode 100644
index 0000000000..177955438b
--- /dev/null
+++ b/frontend/src/hooks/api/pamDiscovery/index.tsx
@@ -0,0 +1,3 @@
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/pamDiscovery/mutations.tsx b/frontend/src/hooks/api/pamDiscovery/mutations.tsx
new file mode 100644
index 0000000000..4749195ffa
--- /dev/null
+++ b/frontend/src/hooks/api/pamDiscovery/mutations.tsx
@@ -0,0 +1,78 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { pamDiscoveryKeys } from "./queries";
+import {
+ TCreatePamDiscoverySourceDTO,
+ TDeletePamDiscoverySourceDTO,
+ TPamDiscoverySource,
+ TTriggerPamDiscoveryScanDTO,
+ TUpdatePamDiscoverySourceDTO
+} from "./types";
+
+export const useCreatePamDiscoverySource = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ discoveryType, ...dto }: TCreatePamDiscoverySourceDTO) => {
+ const { data } = await apiRequest.post<{ source: TPamDiscoverySource }>(
+ `/api/v1/pam/discovery/${discoveryType}`,
+ dto
+ );
+ return data.source;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.sources() });
+ }
+ });
+};
+
+export const useUpdatePamDiscoverySource = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ discoverySourceId,
+ discoveryType,
+ ...dto
+ }: TUpdatePamDiscoverySourceDTO) => {
+ const { data } = await apiRequest.patch<{ source: TPamDiscoverySource }>(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}`,
+ dto
+ );
+ return data.source;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.all });
+ }
+ });
+};
+
+export const useDeletePamDiscoverySource = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ discoverySourceId, discoveryType }: TDeletePamDiscoverySourceDTO) => {
+ const { data } = await apiRequest.delete(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}`
+ );
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.sources() });
+ }
+ });
+};
+
+export const useTriggerPamDiscoveryScan = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ discoverySourceId, discoveryType }: TTriggerPamDiscoveryScanDTO) => {
+ const { data } = await apiRequest.post(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}/scan`
+ );
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.all });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/pamDiscovery/queries.tsx b/frontend/src/hooks/api/pamDiscovery/queries.tsx
new file mode 100644
index 0000000000..8465f9d2c2
--- /dev/null
+++ b/frontend/src/hooks/api/pamDiscovery/queries.tsx
@@ -0,0 +1,202 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import {
+ PamDiscoveryType,
+ TDiscoveredAccount,
+ TDiscoveredResource,
+ TListPamDiscoverySourcesDTO,
+ TPamDiscoveryRun,
+ TPamDiscoverySource,
+ TPamDiscoverySourceOption
+} from "./types";
+
+export const pamDiscoveryKeys = {
+ all: ["pam-discovery"] as const,
+ options: () => [...pamDiscoveryKeys.all, "options"] as const,
+ sources: () => [...pamDiscoveryKeys.all, "sources"] as const,
+ listSources: (params: TListPamDiscoverySourcesDTO) =>
+ [...pamDiscoveryKeys.sources(), "list", params] as const,
+ getSource: (discoverySourceId: string) =>
+ [...pamDiscoveryKeys.sources(), "get", discoverySourceId] as const,
+ runs: (discoverySourceId: string) =>
+ [...pamDiscoveryKeys.all, "runs", discoverySourceId] as const,
+ listRuns: (discoverySourceId: string, params: { offset?: number; limit?: number }) =>
+ [...pamDiscoveryKeys.runs(discoverySourceId), "list", params] as const,
+ getRun: (discoverySourceId: string, runId: string) =>
+ [...pamDiscoveryKeys.runs(discoverySourceId), "get", runId] as const,
+ discoveredResources: (discoverySourceId: string, params: { offset?: number; limit?: number }) =>
+ [...pamDiscoveryKeys.all, "discovered-resources", discoverySourceId, params] as const,
+ discoveredAccounts: (discoverySourceId: string, params: { offset?: number; limit?: number }) =>
+ [...pamDiscoveryKeys.all, "discovered-accounts", discoverySourceId, params] as const
+};
+
+export const useListPamDiscoverySourceOptions = (
+ options?: Omit<
+ UseQueryOptions<
+ TPamDiscoverySourceOption[],
+ unknown,
+ TPamDiscoverySourceOption[],
+ ReturnType<typeof pamDiscoveryKeys.options>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.options(),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ discoveryOptions: TPamDiscoverySourceOption[] }>(
+ "/api/v1/pam/discovery/options"
+ );
+ return data.discoveryOptions;
+ },
+ ...options
+ });
+};
+
+type TListSourcesResponse = { sources: TPamDiscoverySource[]; totalCount: number };
+
+export const useListPamDiscoverySources = (
+ params: TListPamDiscoverySourcesDTO,
+ options?: Omit<
+ UseQueryOptions<
+ TListSourcesResponse,
+ unknown,
+ TListSourcesResponse,
+ ReturnType<typeof pamDiscoveryKeys.listSources>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.listSources(params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TListSourcesResponse>("/api/v1/pam/discovery", {
+ params
+ });
+ return data;
+ },
+ placeholderData: (prev) => prev,
+ ...options
+ });
+};
+
+export const useGetPamDiscoverySource = (
+ discoverySourceId: string,
+ discoveryType: PamDiscoveryType,
+ options?: Omit<
+ UseQueryOptions<
+ TPamDiscoverySource,
+ unknown,
+ TPamDiscoverySource,
+ ReturnType<typeof pamDiscoveryKeys.getSource>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.getSource(discoverySourceId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ source: TPamDiscoverySource }>(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}`
+ );
+ return data.source;
+ },
+ enabled: !!discoverySourceId && !!discoveryType && (options?.enabled ?? true),
+ ...options
+ });
+};
+
+type TListRunsResponse = { runs: TPamDiscoveryRun[]; totalCount: number };
+
+export const useListPamDiscoveryRuns = (
+ discoverySourceId: string,
+ discoveryType: PamDiscoveryType,
+ params: { offset?: number; limit?: number },
+ options?: Omit<
+ UseQueryOptions<
+ TListRunsResponse,
+ unknown,
+ TListRunsResponse,
+ ReturnType<typeof pamDiscoveryKeys.listRuns>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.listRuns(discoverySourceId, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TListRunsResponse>(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}/runs`,
+ { params }
+ );
+ return data;
+ },
+ enabled: !!discoverySourceId && !!discoveryType && (options?.enabled ?? true),
+ placeholderData: (prev) => prev,
+ ...options
+ });
+};
+
+type TListDiscoveredResourcesResponse = { resources: TDiscoveredResource[]; totalCount: number };
+
+export const useGetDiscoveredResources = (
+ discoverySourceId: string,
+ discoveryType: PamDiscoveryType,
+ params: { offset?: number; limit?: number },
+ options?: Omit<
+ UseQueryOptions<
+ TListDiscoveredResourcesResponse,
+ unknown,
+ TListDiscoveredResourcesResponse,
+ ReturnType<typeof pamDiscoveryKeys.discoveredResources>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.discoveredResources(discoverySourceId, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TListDiscoveredResourcesResponse>(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}/resources`,
+ { params }
+ );
+ return data;
+ },
+ enabled: !!discoverySourceId && !!discoveryType && (options?.enabled ?? true),
+ placeholderData: (prev) => prev,
+ ...options
+ });
+};
+
+type TListDiscoveredAccountsResponse = { accounts: TDiscoveredAccount[]; totalCount: number };
+
+export const useGetDiscoveredAccounts = (
+ discoverySourceId: string,
+ discoveryType: PamDiscoveryType,
+ params: { offset?: number; limit?: number },
+ options?: Omit<
+ UseQueryOptions<
+ TListDiscoveredAccountsResponse,
+ unknown,
+ TListDiscoveredAccountsResponse,
+ ReturnType<typeof pamDiscoveryKeys.discoveredAccounts>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: pamDiscoveryKeys.discoveredAccounts(discoverySourceId, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TListDiscoveredAccountsResponse>(
+ `/api/v1/pam/discovery/${discoveryType}/${discoverySourceId}/accounts`,
+ { params }
+ );
+ return data;
+ },
+ enabled: !!discoverySourceId && !!discoveryType && (options?.enabled ?? true),
+ placeholderData: (prev) => prev,
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/pamDiscovery/types.ts b/frontend/src/hooks/api/pamDiscovery/types.ts
new file mode 100644
index 0000000000..21669362f6
--- /dev/null
+++ b/frontend/src/hooks/api/pamDiscovery/types.ts
@@ -0,0 +1,106 @@
+export enum PamDiscoveryType {
+ ActiveDirectory = "active-directory"
+}
+
+export const PAM_DISCOVERY_TYPE_MAP: Record<PamDiscoveryType, { name: string; image: string }> = {
+ [PamDiscoveryType.ActiveDirectory]: { name: "Active Directory", image: "ActiveDirectory.png" }
+};
+
+export type TPamDiscoverySourceOption = {
+ name: string;
+ discoveryType: PamDiscoveryType;
+};
+
+export type TPamDiscoverySource = {
+ id: string;
+ projectId: string;
+ name: string;
+ discoveryType: PamDiscoveryType;
+ gatewayId?: string | null;
+ discoveryConfiguration?: Record<string, unknown>;
+ discoveryCredentials?: Record<string, unknown>;
+ schedule?: string | null;
+ lastRunAt?: string | null;
+ nextRunAt?: string | null;
+ status: string;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TPamDiscoveryRun = {
+ id: string;
+ discoverySourceId: string;
+ status: string;
+ triggeredBy: string;
+ resourcesDiscovered: number;
+ accountsDiscovered: number;
+ dependenciesDiscovered: number;
+ newSinceLastRun: number;
+ staleSinceLastRun: number;
+ progress?: unknown;
+ errorMessage?: string | null;
+ startedAt?: string | null;
+ completedAt?: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TDiscoveredResource = {
+ id: string;
+ resourceId: string;
+ resourceName: string;
+ resourceType: string;
+ lastDiscoveredAt: string;
+ isStale: boolean;
+ createdAt: string;
+};
+
+export type TDiscoveredAccount = {
+ id: string;
+ accountId: string;
+ accountName: string;
+ resourceId: string;
+ resourceName: string;
+ lastDiscoveredAt: string;
+ isStale: boolean;
+ metadata?: unknown;
+ createdAt: string;
+};
+
+export type TListPamDiscoverySourcesDTO = {
+ projectId: string;
+ offset?: number;
+ limit?: number;
+ search?: string;
+};
+
+export type TCreatePamDiscoverySourceDTO = {
+ projectId: string;
+ name: string;
+ discoveryType: PamDiscoveryType;
+ gatewayId: string;
+ discoveryCredentials: Record<string, unknown>;
+ discoveryConfiguration: Record<string, unknown>;
+ schedule?: string;
+};
+
+export type TUpdatePamDiscoverySourceDTO = {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+ name?: string;
+ gatewayId?: string;
+ discoveryCredentials?: Record<string, unknown>;
+ discoveryConfiguration?: Record<string, unknown>;
+ schedule?: string;
+ status?: string;
+};
+
+export type TDeletePamDiscoverySourceDTO = {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+};
+
+export type TTriggerPamDiscoveryScanDTO = {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+};
diff --git a/frontend/src/layouts/PamLayout/PamLayout.tsx b/frontend/src/layouts/PamLayout/PamLayout.tsx
index 25e8c92285..7a62752fe5 100644
--- a/frontend/src/layouts/PamLayout/PamLayout.tsx
+++ b/frontend/src/layouts/PamLayout/PamLayout.tsx
@@ -44,6 +44,23 @@ export const PamLayout = () => {
>
{({ isActive }) => <Tab value={isActive ? "selected" : ""}>Sessions</Tab>}
</Link>
+ <Link
+ to="/organizations/$orgId/projects/pam/$projectId/discovery"
+ params={{
+ orgId: currentOrg.id,
+ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <Tab
+ value={
+ isActive || location.pathname.includes("/discovery/") ? "selected" : ""
+ }
+ >
+ Discovery
+ </Tab>
+ )}
+ </Link>
<Link
to="/organizations/$orgId/projects/pam/$projectId/approvals"
params={{
diff --git a/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx b/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx
new file mode 100644
index 0000000000..acd1a5267d
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx
@@ -0,0 +1,671 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { faChevronLeft } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useQuery } from "@tanstack/react-query";
+import { useNavigate, useParams } from "@tanstack/react-router";
+import { format } from "date-fns";
+import { BanIcon, EllipsisVerticalIcon, PencilIcon, PlayIcon, TrashIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { DeleteActionModal, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Detail,
+ DetailLabel,
+ DetailValue,
+ UnstableDropdownMenu,
+ UnstableDropdownMenuContent,
+ UnstableDropdownMenuItem,
+ UnstableDropdownMenuTrigger,
+ UnstableEmpty,
+ UnstableEmptyHeader,
+ UnstableEmptyTitle,
+ UnstableIconButton,
+ UnstablePageLoader,
+ UnstablePagination,
+ UnstableTable,
+ UnstableTableBody,
+ UnstableTableCell,
+ UnstableTableHead,
+ UnstableTableHeader,
+ UnstableTableRow
+} from "@app/components/v3";
+import { ProjectPermissionSub, useOrganization } from "@app/context";
+import { ProjectPermissionPamDiscoveryActions } from "@app/context/ProjectPermissionContext/types";
+import { usePagination } from "@app/hooks";
+import { gatewaysQueryKeys } from "@app/hooks/api";
+import type { PamDiscoveryType, TPamDiscoverySource } from "@app/hooks/api/pamDiscovery";
+import {
+ PAM_DISCOVERY_TYPE_MAP,
+ useDeletePamDiscoverySource,
+ useGetDiscoveredAccounts,
+ useGetDiscoveredResources,
+ useGetPamDiscoverySource,
+ useListPamDiscoveryRuns,
+ useTriggerPamDiscoveryScan
+} from "@app/hooks/api/pamDiscovery";
+
+import { PamUpdateDiscoverySourceModal } from "../PamDiscoveryPage/components/PamUpdateDiscoverySourceModal";
+
+const STATUS_BADGE_MAP: Record<string, "success" | "danger" | "info"> = {
+ active: "success",
+ paused: "info",
+ error: "danger",
+ completed: "success",
+ running: "info",
+ failed: "danger",
+ pending: "info"
+};
+
+const DiscoveryDetailsSection = ({
+ source,
+ onEdit
+}: {
+ source: TPamDiscoverySource;
+ onEdit: VoidFunction;
+}) => {
+ return (
+ <div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">
+ <div className="flex items-center justify-between border-b border-border pb-2">
+ <h3 className="text-lg font-medium">Details</h3>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Edit}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableIconButton variant="ghost" size="xs" onClick={onEdit} isDisabled={!isAllowed}>
+ <PencilIcon />
+ </UnstableIconButton>
+ )}
+ </ProjectPermissionCan>
+ </div>
+ <div className="space-y-4">
+ <Detail>
+ <DetailLabel>Name</DetailLabel>
+ <DetailValue>{source.name}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Status</DetailLabel>
+ <DetailValue>
+ <Badge variant={STATUS_BADGE_MAP[source.status] || "info"}>{source.status}</Badge>
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Schedule</DetailLabel>
+ <DetailValue className="capitalize">{source.schedule || "Manual"}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Last Run</DetailLabel>
+ <DetailValue>
+ {source.lastRunAt ? format(new Date(source.lastRunAt), "MM/dd/yyyy, hh:mm a") : "Never"}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Created</DetailLabel>
+ <DetailValue>{format(new Date(source.createdAt), "MM/dd/yyyy, hh:mm a")}</DetailValue>
+ </Detail>
+ </div>
+ </div>
+ );
+};
+
+const DiscoveryConfigurationSection = ({
+ source,
+ onEdit
+}: {
+ source: TPamDiscoverySource;
+ onEdit: VoidFunction;
+}) => {
+ const { data: gateways } = useQuery(gatewaysQueryKeys.list());
+ const gateway = gateways?.find((g) => g.id === source.gatewayId);
+
+ return (
+ <div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">
+ <div className="flex items-center justify-between border-b border-border pb-2">
+ <h3 className="text-lg font-medium">Configuration</h3>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Edit}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableIconButton variant="ghost" size="xs" onClick={onEdit} isDisabled={!isAllowed}>
+ <PencilIcon />
+ </UnstableIconButton>
+ )}
+ </ProjectPermissionCan>
+ </div>
+ <div className="space-y-4">
+ {source.gatewayId && (
+ <Detail>
+ <DetailLabel>Gateway</DetailLabel>
+ <DetailValue>{gateway?.name ?? "Unknown"}</DetailValue>
+ </Detail>
+ )}
+ <Detail>
+ <DetailLabel>Domain FQDN</DetailLabel>
+ <DetailValue>{(source.discoveryConfiguration?.domainFQDN as string) || "-"}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>DC Address</DetailLabel>
+ <DetailValue>{(source.discoveryConfiguration?.dcAddress as string) || "-"}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Port</DetailLabel>
+ <DetailValue>{(source.discoveryConfiguration?.port as number) ?? "-"}</DetailValue>
+ </Detail>
+ </div>
+ </div>
+ );
+};
+
+const DiscoveryCredentialsSection = ({
+ source,
+ onEdit
+}: {
+ source: TPamDiscoverySource;
+ onEdit: VoidFunction;
+}) => {
+ return (
+ <div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">
+ <div className="flex items-center justify-between border-b border-border pb-2">
+ <h3 className="text-lg font-medium">Credentials</h3>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Edit}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableIconButton variant="ghost" size="xs" onClick={onEdit} isDisabled={!isAllowed}>
+ <PencilIcon />
+ </UnstableIconButton>
+ )}
+ </ProjectPermissionCan>
+ </div>
+ <div className="space-y-4">
+ <Detail>
+ <DetailLabel>Username</DetailLabel>
+ <DetailValue>{(source.discoveryCredentials?.username as string) || "-"}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Password</DetailLabel>
+ <DetailValue>••••••••</DetailValue>
+ </Detail>
+ </div>
+ </div>
+ );
+};
+
+const RunsTab = ({
+ discoverySourceId,
+ discoveryType
+}: {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+}) => {
+ const { page, perPage, setPage, setPerPage, offset } = usePagination("", {
+ initPerPage: 20
+ });
+
+ const { data, isPending } = useListPamDiscoveryRuns(discoverySourceId, discoveryType, {
+ offset,
+ limit: perPage
+ });
+
+ const runs = data?.runs || [];
+ const totalCount = data?.totalCount || 0;
+
+ return (
+ <div>
+ <UnstableTable>
+ <UnstableTableHeader>
+ <UnstableTableRow>
+ <UnstableTableHead>Status</UnstableTableHead>
+ <UnstableTableHead>Triggered By</UnstableTableHead>
+ <UnstableTableHead>Started</UnstableTableHead>
+ <UnstableTableHead>Completed</UnstableTableHead>
+ <UnstableTableHead>Resources</UnstableTableHead>
+ <UnstableTableHead>Accounts</UnstableTableHead>
+ <UnstableTableHead>New</UnstableTableHead>
+ <UnstableTableHead>Stale</UnstableTableHead>
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {isPending && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={8} className="text-center text-muted">
+ Loading runs...
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending && runs.length === 0 && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={8}>
+ <UnstableEmpty className="border-0 bg-transparent py-8 shadow-none">
+ <UnstableEmptyHeader>
+ <UnstableEmptyTitle>No discovery runs yet</UnstableEmptyTitle>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending &&
+ runs.map((run) => (
+ <UnstableTableRow key={run.id}>
+ <UnstableTableCell>
+ <Badge variant={STATUS_BADGE_MAP[run.status] || "info"}>{run.status}</Badge>
+ </UnstableTableCell>
+ <UnstableTableCell className="text-muted">{run.triggeredBy}</UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {run.startedAt ? format(new Date(run.startedAt), "MMM d, yyyy HH:mm") : "-"}
+ </UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {run.completedAt ? format(new Date(run.completedAt), "MMM d, yyyy HH:mm") : "-"}
+ </UnstableTableCell>
+ <UnstableTableCell>{run.resourcesDiscovered}</UnstableTableCell>
+ <UnstableTableCell>{run.accountsDiscovered}</UnstableTableCell>
+ <UnstableTableCell>{run.newSinceLastRun}</UnstableTableCell>
+ <UnstableTableCell>{run.staleSinceLastRun}</UnstableTableCell>
+ </UnstableTableRow>
+ ))}
+ </UnstableTableBody>
+ </UnstableTable>
+ {Boolean(totalCount) && !isPending && (
+ <UnstablePagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={setPerPage}
+ />
+ )}
+ </div>
+ );
+};
+
+const ResourcesTab = ({
+ discoverySourceId,
+ discoveryType
+}: {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+}) => {
+ const { page, perPage, setPage, setPerPage, offset } = usePagination("", {
+ initPerPage: 20
+ });
+
+ const { data, isPending } = useGetDiscoveredResources(discoverySourceId, discoveryType, {
+ offset,
+ limit: perPage
+ });
+
+ const resources = data?.resources || [];
+ const totalCount = data?.totalCount || 0;
+
+ return (
+ <div>
+ <UnstableTable>
+ <UnstableTableHeader>
+ <UnstableTableRow>
+ <UnstableTableHead>Name</UnstableTableHead>
+ <UnstableTableHead>Type</UnstableTableHead>
+ <UnstableTableHead>Last Discovered</UnstableTableHead>
+ <UnstableTableHead>Status</UnstableTableHead>
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {isPending && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={4} className="text-center text-muted">
+ Loading resources...
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending && resources.length === 0 && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={4}>
+ <UnstableEmpty className="border-0 bg-transparent py-8 shadow-none">
+ <UnstableEmptyHeader>
+ <UnstableEmptyTitle>No discovered resources</UnstableEmptyTitle>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending &&
+ resources.map((resource) => (
+ <UnstableTableRow key={resource.id}>
+ <UnstableTableCell className="font-medium">
+ {resource.resourceName}
+ </UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {resource.resourceType}
+ </UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {format(new Date(resource.lastDiscoveredAt), "MMM d, yyyy HH:mm")}
+ </UnstableTableCell>
+ <UnstableTableCell>
+ {resource.isStale ? (
+ <Badge variant="danger">Stale</Badge>
+ ) : (
+ <Badge variant="success">Active</Badge>
+ )}
+ </UnstableTableCell>
+ </UnstableTableRow>
+ ))}
+ </UnstableTableBody>
+ </UnstableTable>
+ {Boolean(totalCount) && !isPending && (
+ <UnstablePagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={setPerPage}
+ />
+ )}
+ </div>
+ );
+};
+
+const AccountsTab = ({
+ discoverySourceId,
+ discoveryType
+}: {
+ discoverySourceId: string;
+ discoveryType: PamDiscoveryType;
+}) => {
+ const { page, perPage, setPage, setPerPage, offset } = usePagination("", {
+ initPerPage: 20
+ });
+
+ const { data, isPending } = useGetDiscoveredAccounts(discoverySourceId, discoveryType, {
+ offset,
+ limit: perPage
+ });
+
+ const accounts = data?.accounts || [];
+ const totalCount = data?.totalCount || 0;
+
+ return (
+ <div>
+ <UnstableTable>
+ <UnstableTableHeader>
+ <UnstableTableRow>
+ <UnstableTableHead>Name</UnstableTableHead>
+ <UnstableTableHead>Resource</UnstableTableHead>
+ <UnstableTableHead>Last Discovered</UnstableTableHead>
+ <UnstableTableHead>Status</UnstableTableHead>
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {isPending && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={4} className="text-center text-muted">
+ Loading accounts...
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending && accounts.length === 0 && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={4}>
+ <UnstableEmpty className="border-0 bg-transparent py-8 shadow-none">
+ <UnstableEmptyHeader>
+ <UnstableEmptyTitle>No discovered accounts</UnstableEmptyTitle>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending &&
+ accounts.map((account) => (
+ <UnstableTableRow key={account.id}>
+ <UnstableTableCell className="font-medium">{account.accountName}</UnstableTableCell>
+ <UnstableTableCell className="text-muted">{account.resourceName}</UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {format(new Date(account.lastDiscoveredAt), "MMM d, yyyy HH:mm")}
+ </UnstableTableCell>
+ <UnstableTableCell>
+ {account.isStale ? (
+ <Badge variant="danger">Stale</Badge>
+ ) : (
+ <Badge variant="success">Active</Badge>
+ )}
+ </UnstableTableCell>
+ </UnstableTableRow>
+ ))}
+ </UnstableTableBody>
+ </UnstableTable>
+ {Boolean(totalCount) && !isPending && (
+ <UnstablePagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={setPerPage}
+ />
+ )}
+ </div>
+ );
+};
+
+const PageContent = () => {
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const params = useParams({ strict: false }) as {
+ discoverySourceId?: string;
+ discoveryType?: string;
+ projectId?: string;
+ };
+
+ const { discoverySourceId, projectId } = params;
+ const discoveryType = params.discoveryType as PamDiscoveryType;
+
+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
+
+ const { data: source, isPending } = useGetPamDiscoverySource(
+ discoverySourceId || "",
+ discoveryType,
+ {
+ enabled: Boolean(discoverySourceId) && Boolean(discoveryType)
+ }
+ );
+
+ const deleteMutation = useDeletePamDiscoverySource();
+ const triggerScanMutation = useTriggerPamDiscoveryScan();
+
+ if (isPending) {
+ return <UnstablePageLoader />;
+ }
+
+ if (!source) {
+ return (
+ <div className="flex h-full w-full items-center justify-center px-20">
+ <UnstableEmpty className="max-w-2xl">
+ <UnstableEmptyHeader>
+ <BanIcon className="size-8 text-muted" />
+ <UnstableEmptyTitle className="text-muted">
+ Could not find discovery source with ID {discoverySourceId}
+ </UnstableEmptyTitle>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+ </div>
+ );
+ }
+
+ const discoveryTypeInfo = PAM_DISCOVERY_TYPE_MAP[source.discoveryType];
+
+ const handleBack = () => {
+ navigate({
+ to: "/organizations/$orgId/projects/pam/$projectId/discovery",
+ params: { orgId: currentOrg.id, projectId: projectId! }
+ });
+ };
+
+ const handleTriggerScan = async () => {
+ try {
+ await triggerScanMutation.mutateAsync({
+ discoverySourceId: source.id,
+ discoveryType: source.discoveryType
+ });
+ createNotification({ text: "Scan triggered successfully", type: "success" });
+ } catch {
+ createNotification({ text: "Failed to trigger scan", type: "error" });
+ }
+ };
+
+ const handleDeleteConfirm = async () => {
+ try {
+ await deleteMutation.mutateAsync({
+ discoverySourceId: source.id,
+ discoveryType: source.discoveryType
+ });
+ createNotification({ text: "Discovery source deleted", type: "success" });
+ handleBack();
+ } catch {
+ createNotification({ text: "Failed to delete discovery source", type: "error" });
+ }
+ };
+
+ return (
+ <div className="container mx-auto flex max-w-7xl flex-col px-6 py-6 text-mineshaft-50">
+ <button
+ type="button"
+ onClick={handleBack}
+ className="mb-4 flex items-center gap-1 text-sm text-bunker-300 hover:text-primary-400"
+ >
+ <FontAwesomeIcon icon={faChevronLeft} className="text-xs" />
+ Discovery Sources
+ </button>
+
+ <div className="mb-6 flex items-center justify-between">
+ <div className="flex items-center gap-4">
+ <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-mineshaft-700">
+ <img
+ alt={discoveryTypeInfo.name}
+ src={`/images/integrations/${discoveryTypeInfo.image}`}
+ className="size-6"
+ />
+ </div>
+ <div>
+ <h1 className="text-2xl font-semibold text-mineshaft-100">{source.name}</h1>
+ <p className="text-sm text-bunker-300">{discoveryTypeInfo.name} Discovery Source</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-3">
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.RunScan}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="neutral"
+ onClick={handleTriggerScan}
+ isDisabled={!isAllowed}
+ isPending={triggerScanMutation.isPending}
+ >
+ <PlayIcon className="size-4" />
+ Trigger Scan
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ <UnstableDropdownMenu>
+ <UnstableDropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm">
+ <EllipsisVerticalIcon />
+ </Button>
+ </UnstableDropdownMenuTrigger>
+ <UnstableDropdownMenuContent align="end" sideOffset={2}>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Edit}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableDropdownMenuItem
+ onClick={() => setIsEditModalOpen(true)}
+ isDisabled={!isAllowed}
+ >
+ Edit Source
+ </UnstableDropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Delete}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableDropdownMenuItem
+ onClick={() => setIsDeleteModalOpen(true)}
+ variant="danger"
+ isDisabled={!isAllowed}
+ >
+ <TrashIcon className="size-4" />
+ Delete Source
+ </UnstableDropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ </UnstableDropdownMenuContent>
+ </UnstableDropdownMenu>
+ </div>
+ </div>
+
+ <div className="flex gap-6">
+ {/* Left Column */}
+ <div className="flex w-80 flex-col gap-4">
+ <DiscoveryDetailsSection source={source} onEdit={() => setIsEditModalOpen(true)} />
+ <DiscoveryConfigurationSection source={source} onEdit={() => setIsEditModalOpen(true)} />
+ <DiscoveryCredentialsSection source={source} onEdit={() => setIsEditModalOpen(true)} />
+ </div>
+
+ {/* Right Column - Tabbed Content */}
+ <div className="flex-1">
+ <Tabs defaultValue="runs">
+ <TabList>
+ <Tab value="runs">Runs</Tab>
+ <Tab value="resources">Resources</Tab>
+ <Tab value="accounts">Accounts</Tab>
+ </TabList>
+ <TabPanel value="runs">
+ <RunsTab discoverySourceId={source.id} discoveryType={source.discoveryType} />
+ </TabPanel>
+ <TabPanel value="resources">
+ <ResourcesTab discoverySourceId={source.id} discoveryType={source.discoveryType} />
+ </TabPanel>
+ <TabPanel value="accounts">
+ <AccountsTab discoverySourceId={source.id} discoveryType={source.discoveryType} />
+ </TabPanel>
+ </Tabs>
+ </div>
+ </div>
+
+ <PamUpdateDiscoverySourceModal
+ isOpen={isEditModalOpen}
+ onOpenChange={setIsEditModalOpen}
+ source={source}
+ />
+
+ <DeleteActionModal
+ isOpen={isDeleteModalOpen}
+ title={`Delete discovery source "${source.name}"?`}
+ subTitle="This will permanently remove this discovery source and all its run history."
+ onChange={(isOpen) => setIsDeleteModalOpen(isOpen)}
+ deleteKey="confirm"
+ onDeleteApproved={handleDeleteConfirm}
+ />
+ </div>
+ );
+};
+
+export const PamDiscoveryDetailPage = () => {
+ return (
+ <>
+ <Helmet>
+ <title>Discovery Source | Infisical</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Helmet>
+ <PageContent />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryDetailPage/route.tsx b/frontend/src/pages/pam/PamDiscoveryDetailPage/route.tsx
new file mode 100644
index 0000000000..b00c4cc47a
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryDetailPage/route.tsx
@@ -0,0 +1,14 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { PamDiscoveryDetailPage } from "./PamDiscoveryDetailPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId"
+)({
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [...context.breadcrumbs, { label: "Discovery" }, { label: "Details" }]
+ };
+ },
+ component: PamDiscoveryDetailPage
+});
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx
new file mode 100644
index 0000000000..0914648220
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/PamDiscoveryPage.tsx
@@ -0,0 +1,33 @@
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+
+import { PageHeader } from "@app/components/v2/PageHeader";
+import { useProject } from "@app/context";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+import { PamDiscoverySourcesTable } from "./components/PamDiscoverySourcesTable";
+
+export const PamDiscoveryPage = () => {
+ const { t } = useTranslation();
+ const { currentProject } = useProject();
+
+ return (
+ <>
+ <Helmet>
+ <title>{t("common.head-title", { title: "PAM Discovery" })}</title>
+ </Helmet>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.PAM}
+ title="Discovery"
+ description="Discover Active Directory resources, accounts, and dependencies automatically."
+ />
+ <PamDiscoverySourcesTable projectId={currentProject.id} />
+ </div>
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryTypeSelect.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryTypeSelect.tsx
new file mode 100644
index 0000000000..e8f98172dc
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryTypeSelect.tsx
@@ -0,0 +1,50 @@
+import { Spinner } from "@app/components/v2";
+import {
+ PAM_DISCOVERY_TYPE_MAP,
+ PamDiscoveryType,
+ useListPamDiscoverySourceOptions
+} from "@app/hooks/api/pamDiscovery";
+
+type Props = {
+ onSelect: (discoveryType: PamDiscoveryType) => void;
+};
+
+export const DiscoveryTypeSelect = ({ onSelect }: Props) => {
+ const { isPending, data: discoveryOptions } = useListPamDiscoverySourceOptions();
+
+ if (isPending) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center py-2.5">
+ <Spinner size="lg" className="text-mineshaft-500" />
+ <p className="mt-4 text-sm text-mineshaft-400">Loading options...</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-3 gap-2">
+ {(discoveryOptions || []).map((option) => {
+ const details = PAM_DISCOVERY_TYPE_MAP[option.discoveryType];
+ return (
+ <button
+ key={option.discoveryType}
+ type="button"
+ onClick={() => onSelect(option.discoveryType)}
+ className="group flex h-28 cursor-pointer flex-col items-center justify-center rounded-md border border-mineshaft-600 bg-mineshaft-700 p-4 duration-200 hover:bg-mineshaft-600"
+ >
+ <div className="relative my-auto">
+ <img
+ src={`/images/integrations/${details.image}`}
+ className="size-10"
+ alt={`${details.name} logo`}
+ />
+ </div>
+ <div className="max-w-xs text-center text-xs font-medium text-gray-300 duration-200 group-hover:text-gray-200">
+ {details.name}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamAddDiscoverySourceModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamAddDiscoverySourceModal.tsx
new file mode 100644
index 0000000000..8815c84120
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamAddDiscoverySourceModal.tsx
@@ -0,0 +1,49 @@
+import { useState } from "react";
+
+import { Modal, ModalContent } from "@app/components/v2";
+import { PamDiscoveryType } from "@app/hooks/api/pamDiscovery";
+
+import { PamDiscoverySourceForm } from "./PamDiscoverySourceForm/PamDiscoverySourceForm";
+import { DiscoveryTypeSelect } from "./DiscoveryTypeSelect";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ projectId: string;
+};
+
+type ContentProps = {
+ onComplete: () => void;
+ projectId: string;
+};
+
+const Content = ({ onComplete, projectId }: ContentProps) => {
+ const [selectedType, setSelectedType] = useState<PamDiscoveryType | null>(null);
+
+ if (selectedType) {
+ return (
+ <PamDiscoverySourceForm
+ onComplete={onComplete}
+ onBack={() => setSelectedType(null)}
+ discoveryType={selectedType}
+ projectId={projectId}
+ />
+ );
+ }
+
+ return <DiscoveryTypeSelect onSelect={setSelectedType} />;
+};
+
+export const PamAddDiscoverySourceModal = ({ isOpen, onOpenChange, projectId }: Props) => {
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ className="max-w-2xl"
+ title="Add Discovery Source"
+ subTitle="Select a discovery source type to add."
+ >
+ <Content projectId={projectId} onComplete={() => onOpenChange(false)} />
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx
new file mode 100644
index 0000000000..e4d56c0d9a
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx
@@ -0,0 +1,200 @@
+import { useEffect, useState } from "react";
+import { Controller, FormProvider, useForm, useWatch } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { Button, FormControl, Input, ModalClose } from "@app/components/v2";
+import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
+import { PamDiscoveryType, TPamDiscoverySource } from "@app/hooks/api/pamDiscovery";
+
+import { GenericDiscoveryFields, genericDiscoveryFieldsSchema } from "./GenericDiscoveryFields";
+
+type Props = {
+ source?: TPamDiscoverySource;
+ onSubmit: (formData: FormData) => Promise<void>;
+};
+
+const formSchema = genericDiscoveryFieldsSchema.extend({
+ discoveryType: z.literal(PamDiscoveryType.ActiveDirectory),
+ discoveryConfiguration: z.object({
+ domainFQDN: z.string().trim().min(1, "Domain FQDN is required").max(255),
+ dcAddress: z.string().trim().min(1, "DC Address is required").max(255),
+ port: z.coerce.number().int().min(1).max(65535)
+ }),
+ discoveryCredentials: z.object({
+ username: z.string().trim().min(1, "Username is required").max(255),
+ password: z.string().max(255)
+ })
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+export const ActiveDirectoryDiscoveryForm = ({ source, onSubmit }: Props) => {
+ const isUpdate = Boolean(source);
+
+ const form = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: source
+ ? {
+ discoveryType: PamDiscoveryType.ActiveDirectory,
+ name: source.name,
+ gatewayId: source.gatewayId || "",
+ schedule: source.schedule || "manual",
+ discoveryConfiguration: {
+ domainFQDN: (source.discoveryConfiguration?.domainFQDN as string) || "",
+ dcAddress: (source.discoveryConfiguration?.dcAddress as string) || "",
+ port: (source.discoveryConfiguration?.port as number) || 389
+ },
+ discoveryCredentials: {
+ username: (source.discoveryCredentials?.username as string) || "",
+ password: UNCHANGED_PASSWORD_SENTINEL
+ }
+ }
+ : {
+ discoveryType: PamDiscoveryType.ActiveDirectory,
+ discoveryConfiguration: {
+ domainFQDN: "",
+ dcAddress: "",
+ port: 389
+ },
+ discoveryCredentials: {
+ username: "",
+ password: ""
+ }
+ }
+ });
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isSubmitting, isDirty }
+ } = form;
+
+ const [showPassword, setShowPassword] = useState(false);
+ const password = useWatch({ control, name: "discoveryCredentials.password" });
+
+ useEffect(() => {
+ if (password === UNCHANGED_PASSWORD_SENTINEL) {
+ setShowPassword(false);
+ }
+ }, [password]);
+
+ return (
+ <FormProvider {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <GenericDiscoveryFields />
+ <div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3 pb-0">
+ <Controller
+ name="discoveryConfiguration.domainFQDN"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="mb-3"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Domain FQDN"
+ >
+ <Input placeholder="corp.example.com" {...field} />
+ </FormControl>
+ )}
+ />
+ <div className="flex items-start gap-2">
+ <Controller
+ name="discoveryConfiguration.dcAddress"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="flex-1"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="DC Address"
+ >
+ <Input placeholder="dc01.corp.example.com" {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="discoveryConfiguration.port"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="w-28"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Port"
+ >
+ <Input type="number" {...field} />
+ </FormControl>
+ )}
+ />
+ </div>
+ </div>
+ <div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3 pb-0">
+ <div className="flex items-start gap-2">
+ <Controller
+ name="discoveryCredentials.username"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="flex-1"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Username"
+ >
+ <Input placeholder="admin" autoComplete="off" {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="discoveryCredentials.password"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="flex-1"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Password"
+ >
+ <Input
+ {...field}
+ type={showPassword ? "text" : "password"}
+ autoComplete="new-password"
+ onFocus={() => {
+ if (isUpdate && field.value === UNCHANGED_PASSWORD_SENTINEL) {
+ field.onChange("");
+ }
+ setShowPassword(true);
+ }}
+ onBlur={() => {
+ if (isUpdate && field.value === "") {
+ field.onChange(UNCHANGED_PASSWORD_SENTINEL);
+ }
+ setShowPassword(false);
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ </div>
+ </div>
+ <div className="mt-6 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ colorSchema="secondary"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting || !isDirty}
+ >
+ {isUpdate ? "Update Details" : "Create Discovery Source"}
+ </Button>
+ <ModalClose asChild>
+ <Button colorSchema="secondary" variant="plain">
+ Cancel
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ </FormProvider>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx
new file mode 100644
index 0000000000..6a5c9b9431
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx
@@ -0,0 +1,73 @@
+import { Controller, useFormContext } from "react-hook-form";
+import { useQuery } from "@tanstack/react-query";
+import { z } from "zod";
+
+import { FormControl, Input, Select, SelectItem } from "@app/components/v2";
+import { gatewaysQueryKeys } from "@app/hooks/api";
+
+export const genericDiscoveryFieldsSchema = z.object({
+ name: z.string().trim().min(1, "Name is required").max(255),
+ gatewayId: z.string().min(1, "Gateway is required"),
+ schedule: z.string().default("manual")
+});
+
+export const GenericDiscoveryFields = () => {
+ const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());
+
+ const { control } = useFormContext<{ name: string; gatewayId: string; schedule: string }>();
+
+ return (
+ <>
+ <Controller
+ name="name"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl errorText={error?.message} isError={Boolean(error?.message)} label="Name">
+ <Input autoFocus placeholder="my-discovery-source" {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="gatewayId"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl isError={Boolean(error?.message)} errorText={error?.message} label="Gateway">
+ <Select
+ value={value || (null as unknown as string)}
+ onValueChange={onChange}
+ className="w-full border border-mineshaft-500"
+ dropdownContainerClassName="max-w-none"
+ isLoading={isGatewaysLoading}
+ placeholder="Select a Gateway..."
+ position="popper"
+ >
+ {(gateways || []).map((el) => (
+ <SelectItem value={el.id} key={el.id}>
+ {el.name}
+ </SelectItem>
+ ))}
+ </Select>
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="schedule"
+ render={({ field: { value, onChange } }) => (
+ <FormControl label="Schedule">
+ <Select
+ value={value}
+ onValueChange={onChange}
+ className="w-full border border-mineshaft-500"
+ position="popper"
+ >
+ <SelectItem value="manual">Manual</SelectItem>
+ <SelectItem value="daily">Daily</SelectItem>
+ <SelectItem value="weekly">Weekly</SelectItem>
+ </Select>
+ </FormControl>
+ )}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx
new file mode 100644
index 0000000000..2bffa3c6a5
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx
@@ -0,0 +1,120 @@
+import { createNotification } from "@app/components/notifications";
+import {
+ PAM_DISCOVERY_TYPE_MAP,
+ PamDiscoveryType,
+ TPamDiscoverySource,
+ useCreatePamDiscoverySource,
+ useUpdatePamDiscoverySource
+} from "@app/hooks/api/pamDiscovery";
+
+import { PamDiscoverySourceHeader } from "../PamDiscoverySourceHeader";
+import { ActiveDirectoryDiscoveryForm } from "./ActiveDirectoryDiscoveryForm";
+
+type FormProps = {
+ onComplete: (source: TPamDiscoverySource) => void;
+} & ({ source: TPamDiscoverySource } | { discoveryType: PamDiscoveryType });
+
+type CreateFormProps = FormProps & {
+ discoveryType: PamDiscoveryType;
+ projectId: string;
+};
+
+type UpdateFormProps = FormProps & {
+ source: TPamDiscoverySource;
+};
+
+const CreateForm = ({ discoveryType, onComplete, projectId }: CreateFormProps) => {
+ const createPamDiscoverySource = useCreatePamDiscoverySource();
+ const { name: discoveryName } = PAM_DISCOVERY_TYPE_MAP[discoveryType];
+
+ const onSubmit = async (formData: {
+ name: string;
+ gatewayId: string;
+ schedule: string;
+ discoveryType: PamDiscoveryType;
+ discoveryConfiguration: Record<string, unknown>;
+ discoveryCredentials: Record<string, unknown>;
+ }) => {
+ const source = await createPamDiscoverySource.mutateAsync({
+ projectId,
+ name: formData.name,
+ discoveryType: formData.discoveryType,
+ gatewayId: formData.gatewayId,
+ discoveryConfiguration: formData.discoveryConfiguration,
+ discoveryCredentials: formData.discoveryCredentials,
+ schedule: formData.schedule
+ });
+ createNotification({
+ text: `Successfully created ${discoveryName} discovery source`,
+ type: "success"
+ });
+ onComplete(source);
+ };
+
+ switch (discoveryType) {
+ case PamDiscoveryType.ActiveDirectory:
+ return <ActiveDirectoryDiscoveryForm onSubmit={onSubmit} />;
+ default:
+ throw new Error(`Unhandled discovery type: ${discoveryType}`);
+ }
+};
+
+const UpdateForm = ({ source, onComplete }: UpdateFormProps) => {
+ const updatePamDiscoverySource = useUpdatePamDiscoverySource();
+ const { name: discoveryName } = PAM_DISCOVERY_TYPE_MAP[source.discoveryType];
+
+ const onSubmit = async (formData: {
+ name: string;
+ gatewayId: string;
+ schedule: string;
+ discoveryType: PamDiscoveryType;
+ discoveryConfiguration: Record<string, unknown>;
+ discoveryCredentials: Record<string, unknown>;
+ }) => {
+ const updatedSource = await updatePamDiscoverySource.mutateAsync({
+ discoverySourceId: source.id,
+ discoveryType: formData.discoveryType,
+ name: formData.name,
+ gatewayId: formData.gatewayId,
+ discoveryConfiguration: formData.discoveryConfiguration,
+ discoveryCredentials: formData.discoveryCredentials,
+ schedule: formData.schedule
+ });
+ createNotification({
+ text: `Successfully updated ${discoveryName} discovery source`,
+ type: "success"
+ });
+ onComplete(updatedSource);
+ };
+
+ switch (source.discoveryType) {
+ case PamDiscoveryType.ActiveDirectory:
+ return <ActiveDirectoryDiscoveryForm source={source} onSubmit={onSubmit} />;
+ default:
+ throw new Error(`Unhandled discovery type: ${source.discoveryType}`);
+ }
+};
+
+type Props = { onBack?: () => void; projectId: string } & Pick<FormProps, "onComplete"> &
+ (
+ | { discoveryType: PamDiscoveryType; source?: undefined }
+ | { discoveryType?: undefined; source: TPamDiscoverySource }
+ );
+
+export const PamDiscoverySourceForm = ({ onBack, projectId, ...props }: Props) => {
+ const { source, discoveryType } = props;
+
+ return (
+ <div>
+ <PamDiscoverySourceHeader
+ discoveryType={discoveryType || source.discoveryType}
+ onBack={onBack}
+ />
+ {source ? (
+ <UpdateForm {...props} source={source} />
+ ) : (
+ <CreateForm {...props} discoveryType={discoveryType} projectId={projectId} />
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceHeader.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceHeader.tsx
new file mode 100644
index 0000000000..5ddbc852df
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceHeader.tsx
@@ -0,0 +1,33 @@
+import { PAM_DISCOVERY_TYPE_MAP, PamDiscoveryType } from "@app/hooks/api/pamDiscovery";
+
+type Props = {
+ discoveryType: PamDiscoveryType;
+ onBack?: () => void;
+};
+
+export const PamDiscoverySourceHeader = ({ discoveryType, onBack }: Props) => {
+ const details = PAM_DISCOVERY_TYPE_MAP[discoveryType];
+
+ return (
+ <div className="mb-4 flex w-full items-start gap-2 border-b border-mineshaft-500 pb-4">
+ <img
+ alt={`${details.name} logo`}
+ src={`/images/integrations/${details.image}`}
+ className="h-12 w-12 rounded-md bg-bunker-500 p-2"
+ />
+ <div>
+ <div className="text-mineshaft-300">{details.name}</div>
+ <p className="text-sm leading-4 text-mineshaft-400">Discovery Source</p>
+ </div>
+ {onBack && (
+ <button
+ type="button"
+ className="mt-1 ml-auto text-xs text-mineshaft-400 underline underline-offset-2 hover:text-mineshaft-300"
+ onClick={onBack}
+ >
+ Select another discovery type
+ </button>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourcesTable.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourcesTable.tsx
new file mode 100644
index 0000000000..dabf8772b5
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourcesTable.tsx
@@ -0,0 +1,278 @@
+import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate } from "@tanstack/react-router";
+import { format } from "date-fns";
+import { EllipsisVerticalIcon, PlayIcon, PlusIcon, TrashIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { DeleteActionModal, Input } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ UnstableDropdownMenu,
+ UnstableDropdownMenuContent,
+ UnstableDropdownMenuItem,
+ UnstableDropdownMenuTrigger,
+ UnstableEmpty,
+ UnstableEmptyHeader,
+ UnstableEmptyTitle,
+ UnstableIconButton,
+ UnstablePagination,
+ UnstableTable,
+ UnstableTableBody,
+ UnstableTableCell,
+ UnstableTableHead,
+ UnstableTableHeader,
+ UnstableTableRow
+} from "@app/components/v3";
+import { ProjectPermissionSub, useOrganization, useProject } from "@app/context";
+import { ProjectPermissionPamDiscoveryActions } from "@app/context/ProjectPermissionContext/types";
+import { usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
+import type { TPamDiscoverySource } from "@app/hooks/api/pamDiscovery";
+import {
+ useDeletePamDiscoverySource,
+ useListPamDiscoverySources,
+ useTriggerPamDiscoveryScan
+} from "@app/hooks/api/pamDiscovery";
+
+import { PamAddDiscoverySourceModal } from "./PamAddDiscoverySourceModal";
+
+const STATUS_BADGE_MAP: Record<string, "success" | "danger" | "info"> = {
+ active: "success",
+ paused: "info",
+ error: "danger"
+};
+
+type Props = {
+ projectId: string;
+};
+
+export const PamDiscoverySourcesTable = ({ projectId }: Props) => {
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const { currentProject } = useProject();
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
+ "addSource",
+ "deleteSource"
+ ] as const);
+
+ const { search, debouncedSearch, setSearch, setPage, page, perPage, setPerPage, offset } =
+ usePagination("", { initPerPage: 20 });
+
+ const { data, isPending } = useListPamDiscoverySources({
+ projectId,
+ offset,
+ limit: perPage,
+ search: debouncedSearch
+ });
+
+ const sources = data?.sources || [];
+ const totalCount = data?.totalCount || 0;
+
+ useResetPageHelper({ totalCount, offset, setPage });
+
+ const deleteMutation = useDeletePamDiscoverySource();
+ const triggerScanMutation = useTriggerPamDiscoveryScan();
+
+ const handleDelete = async () => {
+ const source = popUp.deleteSource.data as TPamDiscoverySource;
+ if (!source) return;
+ try {
+ await deleteMutation.mutateAsync({
+ discoverySourceId: source.id,
+ discoveryType: source.discoveryType
+ });
+ createNotification({ text: "Discovery source deleted", type: "success" });
+ handlePopUpClose("deleteSource");
+ } catch {
+ createNotification({ text: "Failed to delete discovery source", type: "error" });
+ }
+ };
+
+ const handleTriggerScan = async (source: TPamDiscoverySource) => {
+ try {
+ await triggerScanMutation.mutateAsync({
+ discoverySourceId: source.id,
+ discoveryType: source.discoveryType
+ });
+ createNotification({ text: "Scan triggered successfully", type: "success" });
+ } catch {
+ createNotification({ text: "Failed to trigger scan", type: "error" });
+ }
+ };
+
+ return (
+ <div>
+ <div className="flex gap-2">
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
+ placeholder="Search discovery sources..."
+ className="h-full flex-1"
+ containerClassName="h-9"
+ />
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Create}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="neutral"
+ onClick={() => handlePopUpOpen("addSource")}
+ isDisabled={!isAllowed}
+ >
+ <PlusIcon />
+ Add Discovery Source
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </div>
+
+ <div className="mt-4">
+ <UnstableTable>
+ <UnstableTableHeader>
+ <UnstableTableRow>
+ <UnstableTableHead>Name</UnstableTableHead>
+ <UnstableTableHead>Domain</UnstableTableHead>
+ <UnstableTableHead>Status</UnstableTableHead>
+ <UnstableTableHead>Last Run</UnstableTableHead>
+ <UnstableTableHead className="w-5" />
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {isPending && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={5} className="text-center text-muted">
+ Loading discovery sources...
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending && sources.length === 0 && (
+ <UnstableTableRow>
+ <UnstableTableCell colSpan={5}>
+ <UnstableEmpty className="border-0 bg-transparent py-8 shadow-none">
+ <UnstableEmptyHeader>
+ <UnstableEmptyTitle>
+ {search ? "No discovery sources match search" : "No discovery sources"}
+ </UnstableEmptyTitle>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ )}
+ {!isPending &&
+ sources.map((source) => (
+ <UnstableTableRow
+ key={source.id}
+ className="group cursor-pointer"
+ onClick={() =>
+ navigate({
+ to: "/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId",
+ params: {
+ orgId: currentOrg.id,
+ projectId: currentProject.id,
+ discoveryType: source.discoveryType,
+ discoverySourceId: source.id
+ }
+ })
+ }
+ >
+ <UnstableTableCell className="font-medium">{source.name}</UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {(source.discoveryConfiguration?.domainFQDN as string) || "-"}
+ </UnstableTableCell>
+ <UnstableTableCell>
+ <Badge variant={STATUS_BADGE_MAP[source.status] || "info"}>
+ {source.status}
+ </Badge>
+ </UnstableTableCell>
+ <UnstableTableCell className="text-muted">
+ {source.lastRunAt
+ ? format(new Date(source.lastRunAt), "MMM d, yyyy HH:mm")
+ : "Never"}
+ </UnstableTableCell>
+ <UnstableTableCell>
+ <UnstableDropdownMenu>
+ <UnstableDropdownMenuTrigger asChild>
+ <UnstableIconButton
+ variant="ghost"
+ size="xs"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <EllipsisVerticalIcon />
+ </UnstableIconButton>
+ </UnstableDropdownMenuTrigger>
+ <UnstableDropdownMenuContent sideOffset={2} align="end">
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.RunScan}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableDropdownMenuItem
+ isDisabled={!isAllowed}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleTriggerScan(source);
+ }}
+ >
+ <PlayIcon className="size-4" />
+ Trigger Scan
+ </UnstableDropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ <ProjectPermissionCan
+ I={ProjectPermissionPamDiscoveryActions.Delete}
+ a={ProjectPermissionSub.PamDiscovery}
+ >
+ {(isAllowed) => (
+ <UnstableDropdownMenuItem
+ isDisabled={!isAllowed}
+ variant="danger"
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("deleteSource", source);
+ }}
+ >
+ <TrashIcon className="size-4" />
+ Delete
+ </UnstableDropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ </UnstableDropdownMenuContent>
+ </UnstableDropdownMenu>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ ))}
+ </UnstableTableBody>
+ </UnstableTable>
+ {Boolean(totalCount) && !isPending && (
+ <UnstablePagination
+ count={totalCount}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={setPerPage}
+ />
+ )}
+ </div>
+
+ <PamAddDiscoverySourceModal
+ isOpen={popUp.addSource.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addSource", isOpen)}
+ projectId={projectId}
+ />
+
+ <DeleteActionModal
+ isOpen={popUp.deleteSource.isOpen}
+ title={`Delete discovery source "${(popUp.deleteSource.data as TPamDiscoverySource)?.name}"?`}
+ subTitle="This will permanently remove this discovery source and all its run history."
+ onChange={(isOpen) => handlePopUpToggle("deleteSource", isOpen)}
+ deleteKey="confirm"
+ onDeleteApproved={handleDelete}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamUpdateDiscoverySourceModal.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamUpdateDiscoverySourceModal.tsx
new file mode 100644
index 0000000000..c5855ea68a
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamUpdateDiscoverySourceModal.tsx
@@ -0,0 +1,32 @@
+import { Modal, ModalContent } from "@app/components/v2";
+import { PAM_DISCOVERY_TYPE_MAP, TPamDiscoverySource } from "@app/hooks/api/pamDiscovery";
+
+import { PamDiscoverySourceForm } from "./PamDiscoverySourceForm/PamDiscoverySourceForm";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ source?: TPamDiscoverySource;
+};
+
+export const PamUpdateDiscoverySourceModal = ({ isOpen, onOpenChange, source }: Props) => {
+ if (!source) return null;
+
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ className="max-w-2xl"
+ title="Edit Discovery Source"
+ subTitle={`Update details for this ${
+ PAM_DISCOVERY_TYPE_MAP[source.discoveryType].name
+ } discovery source.`}
+ >
+ <PamDiscoverySourceForm
+ onComplete={() => onOpenChange(false)}
+ source={source}
+ projectId={source.projectId}
+ />
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/route.tsx b/frontend/src/pages/pam/PamDiscoveryPage/route.tsx
new file mode 100644
index 0000000000..f200db55ac
--- /dev/null
+++ b/frontend/src/pages/pam/PamDiscoveryPage/route.tsx
@@ -0,0 +1,26 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { PamDiscoveryPage } from "./PamDiscoveryPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/"
+)({
+ validateSearch: zodValidator(
+ z.object({
+ search: z.string().optional()
+ })
+ ),
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "Discovery"
+ }
+ ]
+ };
+ },
+ component: PamDiscoveryPage
+});
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 1db0590c06..de06dbcb6d 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -27,6 +27,7 @@ import {
ProjectPermissionMcpEndpointActions,
ProjectPermissionMemberActions,
ProjectPermissionPamAccountActions,
+ ProjectPermissionPamDiscoveryActions,
ProjectPermissionPamSessionActions,
ProjectPermissionPkiCertificateInstallationActions,
ProjectPermissionPkiDiscoveryActions,
@@ -273,6 +274,14 @@ const PamSessionPolicyActionSchema = z.object({
[ProjectPermissionPamSessionActions.Read]: z.boolean().optional()
});
+const PamDiscoveryPolicyActionSchema = z.object({
+ [ProjectPermissionPamDiscoveryActions.RunScan]: z.boolean().optional(),
+ [ProjectPermissionPamDiscoveryActions.Create]: z.boolean().optional(),
+ [ProjectPermissionPamDiscoveryActions.Read]: z.boolean().optional(),
+ [ProjectPermissionPamDiscoveryActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionPamDiscoveryActions.Delete]: z.boolean().optional()
+});
+
const McpEndpointPolicyActionSchema = z.object({
[ProjectPermissionMcpEndpointActions.Read]: z.boolean().optional(),
[ProjectPermissionMcpEndpointActions.Create]: z.boolean().optional(),
@@ -541,6 +550,7 @@ export const projectRoleFormSchema = z.object({
.array()
.default([]),
[ProjectPermissionSub.PamSessions]: PamSessionPolicyActionSchema.array().default([]),
+ [ProjectPermissionSub.PamDiscovery]: PamDiscoveryPolicyActionSchema.array().default([]),
[ProjectPermissionSub.McpEndpoints]: McpEndpointPolicyActionSchema.extend({
inverted: z.boolean().optional(),
conditions: ConditionSchema
@@ -1445,6 +1455,22 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
if (canRead) formVal[subject]![0][ProjectPermissionPamAccountActions.Read] = true;
}
+ if (subject === ProjectPermissionSub.PamDiscovery) {
+ const canRead = action.includes(ProjectPermissionPamDiscoveryActions.Read);
+ const canCreate = action.includes(ProjectPermissionPamDiscoveryActions.Create);
+ const canDelete = action.includes(ProjectPermissionPamDiscoveryActions.Delete);
+ const canEdit = action.includes(ProjectPermissionPamDiscoveryActions.Edit);
+ const canRunScan = action.includes(ProjectPermissionPamDiscoveryActions.RunScan);
+
+ if (!formVal[subject]) formVal[subject] = [{}];
+
+ if (canRead) formVal[subject]![0][ProjectPermissionPamDiscoveryActions.Read] = true;
+ if (canCreate) formVal[subject]![0][ProjectPermissionPamDiscoveryActions.Create] = true;
+ if (canDelete) formVal[subject]![0][ProjectPermissionPamDiscoveryActions.Delete] = true;
+ if (canEdit) formVal[subject]![0][ProjectPermissionPamDiscoveryActions.Edit] = true;
+ if (canRunScan) formVal[subject]![0][ProjectPermissionPamDiscoveryActions.RunScan] = true;
+ }
+
if (subject === ProjectPermissionSub.McpEndpoints) {
const canRead = action.includes(ProjectPermissionMcpEndpointActions.Read);
const canCreate = action.includes(ProjectPermissionMcpEndpointActions.Create);
@@ -2217,6 +2243,16 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
title: "Sessions",
actions: [{ label: "Read", value: ProjectPermissionPamSessionActions.Read }]
},
+ [ProjectPermissionSub.PamDiscovery]: {
+ title: "Discovery",
+ actions: [
+ { label: "Read", value: ProjectPermissionPamDiscoveryActions.Read },
+ { label: "Create", value: ProjectPermissionPamDiscoveryActions.Create },
+ { label: "Modify", value: ProjectPermissionPamDiscoveryActions.Edit },
+ { label: "Remove", value: ProjectPermissionPamDiscoveryActions.Delete },
+ { label: "Run Scan", value: ProjectPermissionPamDiscoveryActions.RunScan }
+ ]
+ },
[ProjectPermissionSub.ApprovalRequests]: {
title: "Approval Requests",
actions: [
@@ -2330,7 +2366,8 @@ const PamPermissionSubjects = (enabled = false) => ({
[ProjectPermissionSub.PamFolders]: enabled,
[ProjectPermissionSub.PamResources]: enabled,
[ProjectPermissionSub.PamAccounts]: enabled,
- [ProjectPermissionSub.PamSessions]: enabled
+ [ProjectPermissionSub.PamSessions]: enabled,
+ [ProjectPermissionSub.PamDiscovery]: enabled
});
const AiPermissionSubjects = (enabled = false) => ({
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index da47070241..ddd89062d8 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -174,6 +174,7 @@ import { Route as secretScanningSecretScanningDataSourcesPageRouteImport } from
import { Route as secretManagerIntegrationsListPageRouteImport } from './pages/secret-manager/IntegrationsListPage/route'
import { Route as pamPamSessionsPageRouteImport } from './pages/pam/PamSessionsPage/route'
import { Route as pamPamResourcesPageRouteImport } from './pages/pam/PamResourcesPage/route'
+import { Route as pamPamDiscoveryPageRouteImport } from './pages/pam/PamDiscoveryPage/route'
import { Route as certManagerPkiSubscribersPageRouteImport } from './pages/cert-manager/PkiSubscribersPage/route'
import { Route as certManagerIntegrationsListPageRouteImport } from './pages/cert-manager/IntegrationsListPage/route'
import { Route as certManagerDiscoveryPageRouteImport } from './pages/cert-manager/DiscoveryPage/route'
@@ -244,6 +245,7 @@ import { Route as secretManagerIntegrationsAwsSecretManagerConfigurePageRouteImp
import { Route as secretManagerIntegrationsAwsSecretManagerAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/route'
import { Route as secretManagerIntegrationsAwsParameterStoreConfigurePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreConfigurePage/route'
import { Route as secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/route'
+import { Route as pamPamDiscoveryDetailPageRouteImport } from './pages/pam/PamDiscoveryDetailPage/route'
import { Route as certManagerInstallationDetailsByIDPageRouteImport } from './pages/cert-manager/InstallationDetailsByIDPage/route'
import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'
import { Route as secretManagerIntegrationsVercelOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/VercelOauthCallbackPage/route'
@@ -351,6 +353,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectI
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery',
+ )()
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutSubscribersImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers',
@@ -1145,6 +1151,15 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectI
} as any,
)
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryImport.update(
+ {
+ id: '/discovery',
+ path: '/discovery',
+ getParentRoute: () => pamLayoutRoute,
+ } as any,
+ )
+
const projectAuditLogsPageRoutePamRoute =
projectAuditLogsPageRoutePamImport.update({
id: '/audit-logs',
@@ -1738,6 +1753,13 @@ const pamPamResourcesPageRouteRoute = pamPamResourcesPageRouteImport.update({
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRoute,
} as any)
+const pamPamDiscoveryPageRouteRoute = pamPamDiscoveryPageRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute,
+} as any)
+
const certManagerPkiSubscribersPageRouteRoute =
certManagerPkiSubscribersPageRouteImport.update({
id: '/',
@@ -2323,6 +2345,14 @@ const secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRoute,
} as any)
+const pamPamDiscoveryDetailPageRouteRoute =
+ pamPamDiscoveryDetailPageRouteImport.update({
+ id: '/$discoveryType/$discoverySourceId',
+ path: '/$discoveryType/$discoverySourceId',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute,
+ } as any)
+
const certManagerInstallationDetailsByIDPageRouteRoute =
certManagerInstallationDetailsByIDPageRouteImport.update({
id: '/installations/$installationId',
@@ -3381,6 +3411,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAuditLogsPageRoutePamImport
parentRoute: typeof pamLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery'
+ path: '/discovery'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/discovery'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryImport
+ parentRoute: typeof pamLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources'
path: '/resources'
@@ -3493,6 +3530,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerPkiSubscribersPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutSubscribersImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/'
+ path: '/'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/discovery/'
+ preLoaderRoute: typeof pamPamDiscoveryPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/'
path: '/'
@@ -3836,6 +3880,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerInstallationDetailsByIDPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutDiscoveryImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId'
+ path: '/$discoveryType/$discoverySourceId'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId'
+ preLoaderRoute: typeof pamPamDiscoveryDetailPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/authorize': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/authorize'
path: '/aws-parameter-store/authorize'
@@ -4726,6 +4777,22 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsProjectI
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsProjectIdRouteChildren,
)
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteChildren {
+ pamPamDiscoveryPageRouteRoute: typeof pamPamDiscoveryPageRouteRoute
+ pamPamDiscoveryDetailPageRouteRoute: typeof pamPamDiscoveryDetailPageRouteRoute
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteChildren =
+ {
+ pamPamDiscoveryPageRouteRoute: pamPamDiscoveryPageRouteRoute,
+ pamPamDiscoveryDetailPageRouteRoute: pamPamDiscoveryDetailPageRouteRoute,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteChildren,
+ )
+
interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteChildren {
pamPamAccountByIDPageRouteRoute: typeof pamPamAccountByIDPageRouteRoute
}
@@ -4795,6 +4862,7 @@ interface pamLayoutRouteChildren {
pamSettingsPageRouteRoute: typeof pamSettingsPageRouteRoute
projectAccessControlPageRoutePamRoute: typeof projectAccessControlPageRoutePamRoute
projectAuditLogsPageRoutePamRoute: typeof projectAuditLogsPageRoutePamRoute
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutSessionsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutSessionsRouteWithChildren
pamApprovalRequestDetailPageRouteRoute: typeof pamApprovalRequestDetailPageRouteRoute
@@ -4809,6 +4877,8 @@ const pamLayoutRouteChildren: pamLayoutRouteChildren = {
pamSettingsPageRouteRoute: pamSettingsPageRouteRoute,
projectAccessControlPageRoutePamRoute: projectAccessControlPageRoutePamRoute,
projectAuditLogsPageRoutePamRoute: projectAuditLogsPageRoutePamRoute,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRoute:
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutSessionsRoute:
@@ -5784,6 +5854,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/kms/$projectId/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
'/organizations/$orgId/projects/pam/$projectId/access-management': typeof projectAccessControlPageRoutePamRoute
'/organizations/$orgId/projects/pam/$projectId/audit-logs': typeof projectAuditLogsPageRoutePamRoute
+ '/organizations/$orgId/projects/pam/$projectId/discovery': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteWithChildren
'/organizations/$orgId/projects/pam/$projectId/resources': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRouteWithChildren
'/organizations/$orgId/projects/pam/$projectId/sessions': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutSessionsRouteWithChildren
'/organizations/$orgId/projects/secret-management/$projectId/access-management': typeof projectAccessControlPageRouteSecretManagerRoute
@@ -5800,6 +5871,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/cert-manager/$projectId/discovery/': typeof certManagerDiscoveryPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/integrations/': typeof certManagerIntegrationsListPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/subscribers/': typeof certManagerPkiSubscribersPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/discovery/': typeof pamPamDiscoveryPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/resources/': typeof pamPamResourcesPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/sessions/': typeof pamPamSessionsPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/': typeof secretManagerIntegrationsListPageRouteRoute
@@ -5849,6 +5921,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/ssh/$projectId/members/$membershipId': typeof projectMemberDetailsByIDPageRouteSshRoute
'/organizations/$orgId/projects/ssh/$projectId/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteSshRoute
'/organizations/$orgId/projects/cert-manager/$projectId/discovery/installations/$installationId': typeof certManagerInstallationDetailsByIDPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId': typeof pamPamDiscoveryDetailPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/authorize': typeof secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/create': typeof secretManagerIntegrationsAwsParameterStoreConfigurePageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-secret-manager/authorize': typeof secretManagerIntegrationsAwsSecretManagerAuthorizePageRouteRoute
@@ -6055,6 +6128,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/cert-manager/$projectId/discovery': typeof certManagerDiscoveryPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/integrations': typeof certManagerIntegrationsListPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/subscribers': typeof certManagerPkiSubscribersPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/discovery': typeof pamPamDiscoveryPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/resources': typeof pamPamResourcesPageRouteRoute
'/organizations/$orgId/projects/pam/$projectId/sessions': typeof pamPamSessionsPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations': typeof secretManagerIntegrationsListPageRouteRoute
@@ -6104,6 +6178,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/ssh/$projectId/members/$membershipId': typeof projectMemberDetailsByIDPageRouteSshRoute
'/organizations/$orgId/projects/ssh/$projectId/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteSshRoute
'/organizations/$orgId/projects/cert-manager/$projectId/discovery/installations/$installationId': typeof certManagerInstallationDetailsByIDPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId': typeof pamPamDiscoveryDetailPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/authorize': typeof secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/create': typeof secretManagerIntegrationsAwsParameterStoreConfigurePageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-secret-manager/authorize': typeof secretManagerIntegrationsAwsSecretManagerAuthorizePageRouteRoute
@@ -6318,6 +6393,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/access-management': typeof projectAccessControlPageRoutePamRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/audit-logs': typeof projectAuditLogsPageRoutePamRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutDiscoveryRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutSessionsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/access-management': typeof projectAccessControlPageRouteSecretManagerRoute
@@ -6334,6 +6410,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/': typeof certManagerDiscoveryPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/': typeof certManagerIntegrationsListPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers/': typeof certManagerPkiSubscribersPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/': typeof pamPamDiscoveryPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/': typeof pamPamResourcesPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/': typeof pamPamSessionsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/': typeof secretManagerIntegrationsListPageRouteRoute
@@ -6383,6 +6460,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/members/$membershipId': typeof projectMemberDetailsByIDPageRouteSshRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/roles/$roleSlug': typeof projectRoleDetailsBySlugPageRouteSshRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/installations/$installationId': typeof certManagerInstallationDetailsByIDPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId': typeof pamPamDiscoveryDetailPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/authorize': typeof secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/create': typeof secretManagerIntegrationsAwsParameterStoreConfigurePageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-secret-manager/authorize': typeof secretManagerIntegrationsAwsSecretManagerAuthorizePageRouteRoute
@@ -6590,6 +6668,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/kms/$projectId/audit-logs'
| '/organizations/$orgId/projects/pam/$projectId/access-management'
| '/organizations/$orgId/projects/pam/$projectId/audit-logs'
+ | '/organizations/$orgId/projects/pam/$projectId/discovery'
| '/organizations/$orgId/projects/pam/$projectId/resources'
| '/organizations/$orgId/projects/pam/$projectId/sessions'
| '/organizations/$orgId/projects/secret-management/$projectId/access-management'
@@ -6606,6 +6685,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery/'
| '/organizations/$orgId/projects/cert-manager/$projectId/integrations/'
| '/organizations/$orgId/projects/cert-manager/$projectId/subscribers/'
+ | '/organizations/$orgId/projects/pam/$projectId/discovery/'
| '/organizations/$orgId/projects/pam/$projectId/resources/'
| '/organizations/$orgId/projects/pam/$projectId/sessions/'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/'
@@ -6655,6 +6735,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/ssh/$projectId/members/$membershipId'
| '/organizations/$orgId/projects/ssh/$projectId/roles/$roleSlug'
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery/installations/$installationId'
+ | '/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/authorize'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/create'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-secret-manager/authorize'
@@ -6860,6 +6941,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery'
| '/organizations/$orgId/projects/cert-manager/$projectId/integrations'
| '/organizations/$orgId/projects/cert-manager/$projectId/subscribers'
+ | '/organizations/$orgId/projects/pam/$projectId/discovery'
| '/organizations/$orgId/projects/pam/$projectId/resources'
| '/organizations/$orgId/projects/pam/$projectId/sessions'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations'
@@ -6909,6 +6991,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/ssh/$projectId/members/$membershipId'
| '/organizations/$orgId/projects/ssh/$projectId/roles/$roleSlug'
| '/organizations/$orgId/projects/cert-manager/$projectId/discovery/installations/$installationId'
+ | '/organizations/$orgId/projects/pam/$projectId/discovery/$discoveryType/$discoverySourceId'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/authorize'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-parameter-store/create'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/aws-secret-manager/authorize'
@@ -7121,6 +7204,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/audit-logs'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/access-management'
@@ -7137,6 +7221,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers/'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/'
@@ -7186,6 +7271,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/members/$membershipId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/roles/$roleSlug'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/installations/$installationId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/authorize'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/create'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-secret-manager/authorize'
@@ -7850,6 +7936,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/access-management",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/audit-logs",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/approval-requests/$approvalRequestId",
@@ -8074,6 +8161,14 @@ export const routeTree = rootRoute
"filePath": "project/AuditLogsPage/route-pam.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId"
+ ]
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout",
@@ -8230,6 +8325,10 @@ export const routeTree = rootRoute
"filePath": "cert-manager/PkiSubscribersPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/subscribers"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/": {
+ "filePath": "pam/PamDiscoveryPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/": {
"filePath": "pam/PamResourcesPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources"
@@ -8426,6 +8525,10 @@ export const routeTree = rootRoute
"filePath": "cert-manager/InstallationDetailsByIDPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery/$discoveryType/$discoverySourceId": {
+ "filePath": "pam/PamDiscoveryDetailPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/discovery"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/aws-parameter-store/authorize": {
"filePath": "secret-manager/integrations/AwsParameterStoreAuthorizePage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 25262eb6e8..2bae9a42a9 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -387,6 +387,10 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", [
route("/accounts/$accountId", [index("pam/PamAccountByIDPage/route.tsx")])
])
]),
+ route("/discovery", [
+ index("pam/PamDiscoveryPage/route.tsx"),
+ route("/$discoveryType/$discoverySourceId", "pam/PamDiscoveryDetailPage/route.tsx")
+ ]),
route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),
route("/settings", "pam/SettingsPage/route.tsx"),
route("/approvals", "pam/ApprovalsPage/route.tsx"),