Skip to content

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

Address some reviews

xceadc0a2d33b
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 615e637630..f21bee750a 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -754,21 +754,6 @@ import {
TPamDiscoveredAccountsInsert,
TPamDiscoveredAccountsUpdate
} from "@app/db/schemas/pam-discovered-accounts";
-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 {
TPamDiscoverySourceRuns,
TPamDiscoverySourceRunsInsert,
@@ -1799,21 +1784,6 @@ declare module "knex/types/tables" {
TPamDiscoveredAccountsInsert,
TPamDiscoveredAccountsUpdate
>;
- [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,
diff --git a/backend/src/db/migrations/20260701000000_pam-discovery.ts b/backend/src/db/migrations/20260701000000_pam-discovery.ts
index f0f178405e..79ebba4558 100644
--- a/backend/src/db/migrations/20260701000000_pam-discovery.ts
+++ b/backend/src/db/migrations/20260701000000_pam-discovery.ts
@@ -27,7 +27,7 @@ export async function up(knex: Knex): Promise<void> {
t.uuid("gatewayPoolId");
t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("SET NULL");
t.uuid("credentialAccountId").notNullable();
- t.foreign("credentialAccountId").references("id").inTable(TableName.PamAccount).onDelete("RESTRICT");
+ t.foreign("credentialAccountId").references("id").inTable(TableName.PamAccount).deferrable("deferred");
t.jsonb("discoveryConfiguration").notNullable();
t.string("schedule").notNullable().defaultTo("manual");
t.timestamp("lastRunAt");
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 94adf1c464..abfcb629a2 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -132,9 +132,6 @@ export * from "./pam-account-policies";
export * from "./pam-account-templates";
export * from "./pam-accounts";
export * from "./pam-discovered-accounts";
-export * from "./pam-discovery-source-accounts";
-export * from "./pam-discovery-source-dependencies";
-export * from "./pam-discovery-source-resources";
export * from "./pam-discovery-source-runs";
export * from "./pam-discovery-sources";
export * from "./pam-domains";
diff --git a/backend/src/db/schemas/pam-discovery-source-accounts.ts b/backend/src/db/schemas/pam-discovery-source-accounts.ts
deleted file mode 100644
index 2c2b34333d..0000000000
--- a/backend/src/db/schemas/pam-discovery-source-accounts.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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
deleted file mode 100644
index f9596f39e6..0000000000
--- a/backend/src/db/schemas/pam-discovery-source-dependencies.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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
deleted file mode 100644
index 12f5c2a410..0000000000
--- a/backend/src/db/schemas/pam-discovery-source-resources.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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/ee/routes/v1/pam-routers/pam-discovery-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
index 6fc2022148..e65f800f8c 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-discovery-router.ts
@@ -2,7 +2,12 @@ import { z } from "zod";
import { PamDiscoverySourceRunsSchema, PamDiscoverySourcesSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { PamDiscoverySchedule } from "@app/ee/services/pam-discovery/pam-discovery-enums";
+import { PamAccountType } from "@app/ee/services/pam/pam-enums";
+import {
+ PamDiscoveryImportStatus,
+ PamDiscoveryRunStatus,
+ PamDiscoverySchedule
+} from "@app/ee/services/pam-discovery/pam-discovery-enums";
import {
buildPamDiscoveryTypeMetadata,
DISCOVERY_TYPE_CONFIGS,
@@ -21,13 +26,13 @@ type TSupportedConfigs = typeof DISCOVERY_TYPE_CONFIGS;
type TSupportedDiscoveryType = keyof TSupportedConfigs;
const SourceSchema = PamDiscoverySourcesSchema.extend({
- lastRunStatus: z.string().nullable().optional(),
+ lastRunStatus: z.nativeEnum(PamDiscoveryRunStatus).nullable().optional(),
lastRunError: z.string().nullable().optional()
});
const DiscoveredAccountSchema = z.object({
id: z.string(),
- accountType: z.string(),
+ accountType: z.nativeEnum(PamAccountType),
name: z.string(),
fingerprint: z.string(),
createdAt: z.date()
@@ -52,7 +57,7 @@ const registerPerTypeEndpoints = (
schema: {
operationId: `create${typeId}PamDiscoverySource`,
description: `Create a new ${discoveryType} PAM discovery source`,
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
body: z.object({
name: slugSchema({ field: "Name" }),
credentialAccountId: z.string().uuid().describe("The PAM account used to authenticate and scan"),
@@ -110,7 +115,7 @@ const registerPerTypeEndpoints = (
schema: {
operationId: `update${typeId}PamDiscoverySource`,
description: `Update a ${discoveryType} PAM discovery source`,
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
body: z.object({
name: slugSchema({ field: "Name" }).optional(),
@@ -165,7 +170,7 @@ const registerPerTypeEndpoints = (
schema: {
operationId: `get${typeId}PamDiscoverySource`,
description: `Get a ${discoveryType} PAM discovery source`,
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
response: { 200: z.object({ source: SourceSchema }) }
},
@@ -174,6 +179,7 @@ const registerPerTypeEndpoints = (
handler: async (req) => {
const source = await server.services.pamDiscovery.getById({
sourceId: req.params.sourceId,
+ discoveryType,
projectId: req.internalPamProjectId,
actorId: req.permission.id,
actor: req.permission.type,
@@ -190,7 +196,7 @@ const registerPerTypeEndpoints = (
schema: {
operationId: `delete${typeId}PamDiscoverySource`,
description: `Delete a ${discoveryType} PAM discovery source`,
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
response: { 200: z.object({ source: SourceSchema }) }
},
@@ -199,6 +205,7 @@ const registerPerTypeEndpoints = (
handler: async (req) => {
const source = await server.services.pamDiscovery.deleteSource({
sourceId: req.params.sourceId,
+ discoveryType,
projectId: req.internalPamProjectId,
actorId: req.permission.id,
actor: req.permission.type,
@@ -235,7 +242,7 @@ const registerPerTypeEndpoints = (
schema: {
operationId: `scan${typeId}PamDiscoverySource`,
description: `Trigger a scan for a ${discoveryType} PAM discovery source`,
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
response: { 200: z.object({ message: z.string() }) }
},
@@ -244,6 +251,7 @@ const registerPerTypeEndpoints = (
handler: async (req) => {
const result = await server.services.pamDiscovery.triggerScan({
sourceId: req.params.sourceId,
+ discoveryType,
projectId: req.internalPamProjectId,
actorId: req.permission.id,
actor: req.permission.type,
@@ -278,11 +286,11 @@ const registerPerTypeEndpoints = (
export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/options",
+ url: "/types",
schema: {
operationId: "listPamDiscoveryTypes",
description: "List supported PAM discovery source types",
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
response: { 200: z.object({ discoveryTypes: z.array(PamDiscoveryTypeMetadataSchema) }) }
},
config: { rateLimit: readLimit },
@@ -296,7 +304,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
schema: {
operationId: "listPamDiscoverySources",
description: "List PAM discovery sources",
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
querystring: z.object({ search: z.string().optional() }),
response: { 200: z.object({ sources: z.array(SourceSchema) }) }
},
@@ -321,7 +329,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
schema: {
operationId: "listPamDiscoveryRuns",
description: "List scan runs for a PAM discovery source",
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
querystring: z.object({
offset: z.coerce.number().min(0).default(0).optional(),
@@ -352,7 +360,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
schema: {
operationId: "listPamDiscoveredAccounts",
description: "List staged accounts discovered by a PAM discovery source",
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
querystring: z.object({ search: z.string().optional() }),
response: { 200: z.object({ discoveredAccounts: z.array(DiscoveredAccountSchema) }) }
@@ -379,7 +387,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
schema: {
operationId: "importPamDiscoveredAccounts",
description: "Import staged accounts into a folder",
- tags: [ApiDocsTags.PamAccounts],
+ tags: [ApiDocsTags.PamDiscovery],
params: z.object({ sourceId: z.string().uuid() }),
body: z.object({
folderId: z.string().uuid(),
@@ -391,14 +399,16 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
})
.array()
.min(1)
+ .max(1000)
}),
response: {
200: z.object({
results: z
.object({
discoveredAccountId: z.string(),
- status: z.string(),
+ status: z.nativeEnum(PamDiscoveryImportStatus),
accountId: z.string().optional(),
+ name: z.string().optional(),
message: z.string().optional()
})
.array()
@@ -419,7 +429,11 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod
});
- const importedCount = results.filter((r) => r.status === "imported").length;
+ const importedAccounts = results.flatMap((r) =>
+ r.status === PamDiscoveryImportStatus.Imported
+ ? [{ discoveredAccountId: r.discoveredAccountId, accountId: r.accountId, name: r.name }]
+ : []
+ );
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
@@ -427,7 +441,12 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
projectId: req.internalPamProjectId,
event: {
type: EventType.PAM_DISCOVERED_ACCOUNT_IMPORT,
- metadata: { sourceId: req.params.sourceId, folderId: req.body.folderId, importedCount }
+ metadata: {
+ sourceId: req.params.sourceId,
+ folderId: req.body.folderId,
+ importedCount: importedAccounts.length,
+ importedAccounts
+ }
}
});
@@ -436,7 +455,7 @@ export const registerPamDiscoveryRouter = async (server: FastifyZodProvider) =>
event: PostHogEventTypes.PamDiscoveredAccountsImported,
distinctId: getTelemetryDistinctId(req),
organizationId: req.permission.orgId,
- properties: { orgId: req.permission.orgId, importedCount }
+ properties: { orgId: req.permission.orgId, importedCount: importedAccounts.length }
})
.catch(() => {});
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 6b4415f340..4a57881893 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -6147,12 +6147,26 @@ interface PamDiscoverySourceDeleteEvent {
interface PamDiscoveryScanEvent {
type: EventType.PAM_DISCOVERY_SCAN;
- metadata: { sourceId: string; discoveryType: string };
+ metadata: {
+ sourceId: string;
+ discoveryType: string;
+ runId?: string;
+ status?: string;
+ triggeredBy?: string;
+ discoveredCount?: number;
+ newCount?: number;
+ errorMessage?: string;
+ };
}
interface PamDiscoveredAccountImportEvent {
type: EventType.PAM_DISCOVERED_ACCOUNT_IMPORT;
- metadata: { sourceId: string; folderId: string; importedCount: number };
+ metadata: {
+ sourceId: string;
+ folderId: string;
+ importedCount: number;
+ importedAccounts: { discoveredAccountId: string; accountId?: string; name?: string }[];
+ };
}
interface UpdateCertificateRenewalConfigEvent {
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
index 2e913411a4..6738e8a738 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
@@ -132,7 +132,8 @@ const runLdap = <T>(
...(conn.useLdaps && {
tlsOptions: {
rejectUnauthorized: conn.ldapRejectUnauthorized,
- ...(conn.ldapCaCert && { ca: [conn.ldapCaCert], servername: conn.ldapTlsServerName || conn.dcAddress })
+ servername: conn.ldapTlsServerName || conn.dcAddress,
+ ...(conn.ldapCaCert && { ca: [conn.ldapCaCert] })
}
})
});
diff --git a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
index 2762dbe926..e7346fe527 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovered-account-dal.ts
@@ -2,6 +2,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+import { sanitizeSqlLikeString } from "@app/lib/fn";
import { ormify } from "@app/lib/knex";
export type TPamDiscoveredAccountDALFactory = ReturnType<typeof pamDiscoveredAccountDALFactory>;
@@ -30,7 +31,7 @@ export const pamDiscoveredAccountDALFactory = (db: TDbClient) => {
.replicaNode()(TableName.PamDiscoveredAccount)
.where({ discoverySourceId })
.whereNull("importedAccountId");
- if (search) void query.andWhere("name", "ilike", `%${search}%`);
+ if (search) void query.andWhere("name", "ilike", `%${sanitizeSqlLikeString(search)}%`);
return query.orderBy("name", "asc");
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts
index ded72f031e..db33156173 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-enums.ts
@@ -18,3 +18,8 @@ export enum PamDiscoveryRunTrigger {
Manual = "manual",
Schedule = "schedule"
}
+
+export enum PamDiscoveryImportStatus {
+ Imported = "imported",
+ Error = "error"
+}
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
index 2cada1f0de..fc6b50d0a2 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts
@@ -1,3 +1,4 @@
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -9,6 +10,7 @@ import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -19,6 +21,7 @@ import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { TPamAccountServiceFactory } from "../pam-account/pam-account-service";
import { TPamDiscoveredAccountDALFactory } from "./pam-discovered-account-dal";
import {
+ PamDiscoveryImportStatus,
PamDiscoveryRunStatus,
PamDiscoveryRunTrigger,
PamDiscoverySchedule,
@@ -63,6 +66,7 @@ type TPamDiscoverySourceServiceFactoryDep = {
>;
queueService: Pick<TQueueServiceFactory, "queue" | "start">;
cronJob: TCronJobFactory;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
export type TPamDiscoverySourceServiceFactory = ReturnType<typeof pamDiscoverySourceServiceFactory>;
@@ -79,7 +83,8 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
gatewayV2Service,
gatewayPoolService,
queueService,
- cronJob
+ cronJob,
+ auditLogService
} = deps;
const enqueueScan = (sourceId: string, triggeredBy: PamDiscoveryRunTrigger) =>
@@ -145,16 +150,23 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
const withLastRunStatus = async <T extends { id: string }>(sources: T[]) => {
if (sources.length === 0) {
- return sources.map((s) => ({ ...s, lastRunStatus: null as string | null, lastRunError: null as string | null }));
+ return sources.map((s) => ({
+ ...s,
+ lastRunStatus: null as PamDiscoveryRunStatus | null,
+ lastRunError: null as string | null
+ }));
}
const runs = await pamDiscoverySourceRunDAL.find(
{ $in: { discoverySourceId: sources.map((s) => s.id) } },
{ sort: [["createdAt", "desc"]] }
);
- const latestBySource = new Map<string, { status: string; errorMessage?: string | null }>();
+ const latestBySource = new Map<string, { status: PamDiscoveryRunStatus; errorMessage?: string | null }>();
runs.forEach((r) => {
if (!latestBySource.has(r.discoverySourceId)) {
- latestBySource.set(r.discoverySourceId, { status: r.status, errorMessage: r.errorMessage });
+ latestBySource.set(r.discoverySourceId, {
+ status: r.status as PamDiscoveryRunStatus,
+ errorMessage: r.errorMessage
+ });
}
});
return sources.map((s) => {
@@ -172,10 +184,10 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
return withLastRunStatus(sources);
};
- const getById = async ({ projectId, sourceId, ...ctx }: TGetDiscoverySourceDTO) => {
+ const getById = async ({ projectId, sourceId, discoveryType, ...ctx }: TGetDiscoverySourceDTO) => {
await verifyAdmin(projectId, ctx);
const source = await pamDiscoverySourceDAL.findById(sourceId);
- if (!source || source.projectId !== projectId) {
+ if (!source || source.projectId !== projectId || source.discoveryType !== discoveryType) {
throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
}
const [withStatus] = await withLastRunStatus([source]);
@@ -234,7 +246,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
}: TUpdateDiscoverySourceDTO) => {
await verifyAdmin(projectId, ctx);
const source = await pamDiscoverySourceDAL.findById(sourceId);
- if (!source || source.projectId !== projectId) {
+ if (!source || source.projectId !== projectId || source.discoveryType !== discoveryType) {
throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
}
@@ -261,10 +273,10 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
}
};
- const deleteSource = async ({ projectId, sourceId, ...ctx }: TDeleteDiscoverySourceDTO) => {
+ const deleteSource = async ({ projectId, sourceId, discoveryType, ...ctx }: TDeleteDiscoverySourceDTO) => {
await verifyAdmin(projectId, ctx);
const source = await pamDiscoverySourceDAL.findById(sourceId);
- if (!source || source.projectId !== projectId) {
+ if (!source || source.projectId !== projectId || source.discoveryType !== discoveryType) {
throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
}
return pamDiscoverySourceDAL.deleteById(sourceId);
@@ -315,29 +327,64 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
)
);
+ const newCount = results.filter((r) => r.isNew).length;
await pamDiscoverySourceRunDAL.updateById(run.id, {
status: PamDiscoveryRunStatus.Completed,
discoveredCount: accounts.length,
- newCount: results.filter((r) => r.isNew).length,
+ newCount,
machineErrors: machineErrors.length ? JSON.stringify(machineErrors) : null,
completedAt: new Date()
});
+
+ await auditLogService.createAuditLog({
+ projectId: source.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PAM_DISCOVERY_SCAN,
+ metadata: {
+ sourceId,
+ discoveryType: source.discoveryType,
+ runId: run.id,
+ status: PamDiscoveryRunStatus.Completed,
+ triggeredBy,
+ discoveredCount: accounts.length,
+ newCount
+ }
+ }
+ });
} catch (err) {
logger.error(err, `PAM discovery scan failed [sourceId=${sourceId}]`);
+ const errorMessage = err instanceof Error ? err.message : "Scan failed";
await pamDiscoverySourceRunDAL.updateById(run.id, {
status: PamDiscoveryRunStatus.Failed,
- errorMessage: err instanceof Error ? err.message : "Scan failed",
+ errorMessage,
completedAt: new Date()
});
+
+ await auditLogService.createAuditLog({
+ projectId: source.projectId,
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ event: {
+ type: EventType.PAM_DISCOVERY_SCAN,
+ metadata: {
+ sourceId,
+ discoveryType: source.discoveryType,
+ runId: run.id,
+ status: PamDiscoveryRunStatus.Failed,
+ triggeredBy,
+ errorMessage
+ }
+ }
+ });
} finally {
await pamDiscoverySourceDAL.updateById(sourceId, { lastRunAt: new Date() });
}
};
- const triggerScan = async ({ projectId, sourceId, ...ctx }: TTriggerScanDTO) => {
+ const triggerScan = async ({ projectId, sourceId, discoveryType, ...ctx }: TTriggerScanDTO) => {
await verifyAdmin(projectId, ctx);
const source = await pamDiscoverySourceDAL.findById(sourceId);
- if (!source || source.projectId !== projectId) {
+ if (!source || source.projectId !== projectId || source.discoveryType !== discoveryType) {
throw new NotFoundError({ message: `Discovery source with ID '${sourceId}' not found` });
}
const running = await pamDiscoverySourceRunDAL.findOne({
@@ -372,7 +419,7 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
const accounts = await pamDiscoveredAccountDAL.listStaged(sourceId, search);
return accounts.map((a) => ({
id: a.id,
- accountType: a.accountType,
+ accountType: a.accountType as PamAccountType,
name: a.name,
fingerprint: a.fingerprint,
createdAt: a.createdAt
@@ -414,11 +461,16 @@ export const pamDiscoverySourceServiceFactory = (deps: TPamDiscoverySourceServic
});
await pamDiscoveredAccountDAL.updateById(discovered.id, { importedAccountId: account.id });
- return { discoveredAccountId: item.discoveredAccountId, status: "imported" as const, accountId: account.id };
+ return {
+ discoveredAccountId: item.discoveredAccountId,
+ status: PamDiscoveryImportStatus.Imported,
+ accountId: account.id,
+ name: item.name ?? discovered.name
+ };
} catch (err) {
return {
discoveredAccountId: item.discoveredAccountId,
- status: "error" as const,
+ status: PamDiscoveryImportStatus.Error,
message: err instanceof Error ? err.message : "Import failed"
};
}
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
index f997774887..30191ec408 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts
@@ -60,10 +60,22 @@ export type TUpdateDiscoverySourceDTO = {
configuration?: Record<string, unknown>;
} & TActorContext;
-export type TDeleteDiscoverySourceDTO = { projectId: string; sourceId: string } & TActorContext;
-export type TGetDiscoverySourceDTO = { projectId: string; sourceId: string } & TActorContext;
+export type TDeleteDiscoverySourceDTO = {
+ projectId: string;
+ sourceId: string;
+ discoveryType: PamDiscoveryType;
+} & TActorContext;
+export type TGetDiscoverySourceDTO = {
+ projectId: string;
+ sourceId: string;
+ discoveryType: PamDiscoveryType;
+} & TActorContext;
export type TListDiscoverySourcesDTO = { projectId: string; search?: string } & TActorContext;
-export type TTriggerScanDTO = { projectId: string; sourceId: string } & TActorContext;
+export type TTriggerScanDTO = {
+ projectId: string;
+ sourceId: string;
+ discoveryType: PamDiscoveryType;
+} & TActorContext;
export type TListRunsDTO = { projectId: string; sourceId: string; offset?: number; limit?: number } & TActorContext;
export type TListDiscoveredDTO = { projectId: string; sourceId: string; search?: string } & TActorContext;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 1b4e800b95..5e3a94ea15 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -99,6 +99,7 @@ export enum ApiDocsTags {
PamSessions = "PAM Sessions",
PamMemberships = "PAM Memberships",
PamRoles = "PAM Roles",
+ PamDiscovery = "PAM Discovery",
KmipServers = "KMIP Servers"
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 133d10be9f..148beda39b 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1840,7 +1840,8 @@ export const registerRoutes = async (
gatewayV2Service,
gatewayPoolService,
queueService,
- cronJob
+ cronJob,
+ auditLogService
});
const pamSessionDAL = pamSessionDALFactory(db);
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index a198954a07..2fdbdbe7e6 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -453,7 +453,7 @@ export const useListPamDiscoveryTypes = () => {
queryKey: pamKeys.discoveryTypes(),
queryFn: async () => {
const { data } = await apiRequest.get<{ discoveryTypes: TPamDiscoveryTypeOption[] }>(
- "/api/v1/pam/discovery-sources/options"
+ "/api/v1/pam/discovery-sources/types"
);
return data.discoveryTypes;
},
diff --git a/frontend/src/hooks/usePamSheetState.ts b/frontend/src/hooks/usePamSheetState.ts
index fcf62efba1..f047398b8e 100644
--- a/frontend/src/hooks/usePamSheetState.ts
+++ b/frontend/src/hooks/usePamSheetState.ts
@@ -6,6 +6,7 @@ export enum PamSheetTab {
Permissions = "permissions",
Configuration = "configuration",
Advanced = "advanced",
+ Runs = "runs",
General = "general"
}
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
index dba5e670e8..a2a20c9ee3 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoveryConfigFields.tsx
@@ -50,16 +50,13 @@ export const discoveryConfigFromSource = (
export const buildDiscoveryConfiguration = (
data: TDiscoveryConfigFields
-): Record<string, unknown> => {
- if (!data.scanLocalAccounts) return { scanLocalAccounts: false };
- return {
- scanLocalAccounts: true,
- winrmPort: data.winrmPort,
- useWinrmHttps: data.useWinrmHttps,
- winrmRejectUnauthorized: data.winrmRejectUnauthorized,
- ...(data.winrmCaCert.trim() ? { winrmCaCert: data.winrmCaCert.trim() } : {})
- };
-};
+): Record<string, unknown> => ({
+ scanLocalAccounts: data.scanLocalAccounts,
+ winrmPort: data.winrmPort,
+ useWinrmHttps: data.useWinrmHttps,
+ winrmRejectUnauthorized: data.winrmRejectUnauthorized,
+ ...(data.winrmCaCert.trim() ? { winrmCaCert: data.winrmCaCert.trim() } : {})
+});
type ToggleName = "scanLocalAccounts" | "useWinrmHttps" | "winrmRejectUnauthorized";
diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
index 7129f6e690..1fb56901c1 100644
--- a/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/DiscoverySourceDetailSheet.tsx
@@ -243,7 +243,12 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
if (!source) return;
triggerScan.mutate(
{ discoveryType: source.discoveryType, sourceId: source.id },
- { onSuccess: () => createNotification({ type: "success", text: "Scan started" }) }
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Scan started" });
+ setTab(PamSheetTab.Runs);
+ }
+ }
);
};
@@ -443,7 +448,7 @@ export const DiscoverySourceDetailSheet = ({ isOpen, sourceId, onOpenChange }: P
const tabContent: Partial<Record<PamSheetTab, ReactNode>> = {
[PamSheetTab.General]: stagedTab,
- [PamSheetTab.Advanced]: runsTab,
+ [PamSheetTab.Runs]: runsTab,
[PamSheetTab.Configuration]: source ? (
<ConfigurationTab source={source} onDirtyChange={setIsFormDirty} />
) : null
diff --git a/frontend/src/pages/pam/components/pamResourceTabs.ts b/frontend/src/pages/pam/components/pamResourceTabs.ts
index 8edde509ed..2fb75a142c 100644
--- a/frontend/src/pages/pam/components/pamResourceTabs.ts
+++ b/frontend/src/pages/pam/components/pamResourceTabs.ts
@@ -53,7 +53,7 @@ export const PAM_TEMPLATE_TABS: PamResourceTab[] = [
export const PAM_DISCOVERY_TABS: PamResourceTab[] = [
{ value: PamSheetTab.General, label: "Staged Accounts", icon: FolderOpen },
- { value: PamSheetTab.Advanced, label: "Runs", icon: History },
+ { value: PamSheetTab.Runs, label: "Runs", icon: History },
{ value: PamSheetTab.Configuration, label: "Configuration", icon: Settings }
];