Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: secret reporting
varonix081323a71b22a
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 8252870535..c59af6a0c0 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -11,6 +11,7 @@ import { TAiMcpServerServiceFactory } from "@app/ee/services/ai-mcp-server/ai-mcimport { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";+import { TAuditReportServiceFactory } from "@app/ee/services/audit-report/audit-report-service";import { TCertificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-types";import { TCertificateEstServiceFactory } from "@app/ee/services/certificate-est/certificate-est-service";import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-types";@@ -405,6 +406,7 @@ declare module "fastify" {microsoftTeams: TMicrosoftTeamsServiceFactory;assumePrivileges: TAssumePrivilegeServiceFactory;insights: TInsightsServiceFactory;+ auditReport: TAuditReportServiceFactory;pamInsights: TPamInsightsServiceFactory;relay: TRelayServiceFactory;gatewayV2: TGatewayV2ServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 765cee30ad..366e43381b 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -80,6 +80,9 @@ import {TAuditLogStreamsInsert,TAuditLogStreamsUpdate,TAuditLogsUpdate,+ TAuditReports,+ TAuditReportsInsert,+ TAuditReportsUpdate,TAuthTokens,TAuthTokenSessions,TAuthTokenSessionsInsert,@@ -1398,6 +1401,7 @@ declare module "knex/types/tables" {TAuditLogStreamsInsert,TAuditLogStreamsUpdate>;+ [TableName.AuditReport]: KnexOriginal.CompositeTableType<TAuditReports, TAuditReportsInsert, TAuditReportsUpdate>;[TableName.GitAppInstallSession]: KnexOriginal.CompositeTableType<TGitAppInstallSessions,TGitAppInstallSessionsInsert,diff --git a/backend/src/db/migrations/20260629120000_create-audit-reports.ts b/backend/src/db/migrations/20260629120000_create-audit-reports.tsnew file mode 100644index 0000000000..3ed75ff852--- /dev/null+++ b/backend/src/db/migrations/20260629120000_create-audit-reports.ts@@ -0,0 +1,36 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "@app/db/utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.AuditReport))) {+ await knex.schema.createTable(TableName.AuditReport, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.string("projectId").notNullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ // The requester is retained for history/audit; null it out (rather than cascade-delete the+ // report row) when the user is removed so the audit trail survives.+ t.uuid("requestedByUserId");+ t.foreign("requestedByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ t.string("status").notNullable().defaultTo("pending");+ // [{ type, inputs }, ...] — the report types requested in this batch.+ t.jsonb("reportConfigs").notNullable();+ t.specificType("emailRecipients", "text[]").notNullable();+ // [{ type, rowCount, truncated }, ...] — populated by the generation worker on success.+ t.jsonb("resultSummary");+ t.text("errorMessage");+ t.timestamps(true, true, true);+ // FK indexes — Postgres does not auto-index FK columns.+ t.index(["projectId"]);+ t.index(["requestedByUserId"]);+ });++ await createOnUpdateTrigger(knex, TableName.AuditReport);+ }+}++export async function down(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.AuditReport);+ await knex.schema.dropTableIfExists(TableName.AuditReport);+}diff --git a/backend/src/db/schemas/audit-reports.ts b/backend/src/db/schemas/audit-reports.tsnew file mode 100644index 0000000000..c791f12e29--- /dev/null+++ b/backend/src/db/schemas/audit-reports.ts@@ -0,0 +1,25 @@+// 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 AuditReportsSchema = z.object({+ id: z.string().uuid(),+ projectId: z.string(),+ requestedByUserId: z.string().uuid().nullable().optional(),+ status: z.string().default("pending"),+ reportConfigs: z.unknown(),+ emailRecipients: z.string().array(),+ resultSummary: z.unknown().nullable().optional(),+ errorMessage: z.string().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAuditReports = z.infer<typeof AuditReportsSchema>;+export type TAuditReportsInsert = Omit<z.input<typeof AuditReportsSchema>, TImmutableDBKeys>;+export type TAuditReportsUpdate = Partial<Omit<z.input<typeof AuditReportsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/certificate-requests.ts b/backend/src/db/schemas/certificate-requests.tsindex 697e1508ed..c9a80c4f43 100644--- a/backend/src/db/schemas/certificate-requests.ts+++ b/backend/src/db/schemas/certificate-requests.ts@@ -40,8 +40,8 @@ export const CertificateRequestsSchema = z.object({state: z.string().nullable().optional(),locality: z.string().nullable().optional(),encryptedPrivateKey: zodBuffer.nullable().optional(),- pendingMessage: z.string().nullable().optional(),- applicationId: z.string().uuid().nullable().optional()+ applicationId: z.string().uuid().nullable().optional(),+ pendingMessage: z.string().nullable().optional()});export type TCertificateRequests = z.infer<typeof CertificateRequestsSchema>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 7ae6096cf1..f113fc7569 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -25,6 +25,7 @@ export * from "./approval-requests";export * from "./audit-log-stream-outbox";export * from "./audit-log-streams";export * from "./audit-logs";+export * from "./audit-reports";export * from "./auth-token-sessions";export * from "./auth-tokens";export * from "./backup-private-key";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex fce4dbef2a..9e8720b7f5 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -313,6 +313,9 @@ export enum TableName {HoneyTokenEvent = "honey_token_events",HoneyTokenSecretMapping = "honey_token_secret_mappings",+ // Audit Reports (exportable compliance reports)+ AuditReport = "audit_reports",+// Deprecated - Not used anymore now that Redis is persistentDeprecatedDurableQueueJobs = "queue_jobs",DeprecatedSecretRotationV1 = "secret_rotations",diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.tsindex 76ad1aa180..33fc6eff09 100644--- a/backend/src/db/schemas/organizations.ts+++ b/backend/src/db/schemas/organizations.ts@@ -43,7 +43,8 @@ export const OrganizationsSchema = z.object({rootOrgId: z.string().uuid().nullable().optional(),blockDuplicateSecretSyncDestinations: z.boolean().default(false),secretShareBrandConfig: z.unknown().nullable().optional(),- defaultCertManagerProjectId: z.string().nullable().optional()+ defaultCertManagerProjectId: z.string().nullable().optional(),+ allowCrossProjectSecretSharing: z.boolean().default(false)});export type TOrganizations = z.infer<typeof OrganizationsSchema>;diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.tsindex 230328fc54..30a52501fb 100644--- a/backend/src/db/schemas/pam-sessions.ts+++ b/backend/src/db/schemas/pam-sessions.ts@@ -34,9 +34,9 @@ export const PamSessionsSchema = z.object({aiInsightsStatus: z.string().nullable().optional(),aiInsightsError: z.string().nullable().optional(),reason: z.string().nullable().optional(),- selectedResourceId: z.string().uuid().nullable().optional(),encryptedSessionKey: zodBuffer.nullable().optional(),gatewayUploadTokenHash: zodBuffer.nullable().optional(),+ selectedResourceId: z.string().uuid().nullable().optional(),gatewayId: z.string().uuid().nullable().optional()});diff --git a/backend/src/db/schemas/project-folder-grants.ts b/backend/src/db/schemas/project-folder-grants.tsnew file mode 100644index 0000000000..141072ad6e--- /dev/null+++ b/backend/src/db/schemas/project-folder-grants.ts@@ -0,0 +1,21 @@+// 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 ProjectFolderGrantsSchema = z.object({+ id: z.string().uuid(),+ sourceProjectId: z.string(),+ sourceFolderId: z.string().uuid(),+ targetProjectId: z.string(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TProjectFolderGrants = z.infer<typeof ProjectFolderGrantsSchema>;+export type TProjectFolderGrantsInsert = Omit<z.input<typeof ProjectFolderGrantsSchema>, TImmutableDBKeys>;+export type TProjectFolderGrantsUpdate = Partial<Omit<z.input<typeof ProjectFolderGrantsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/ee/routes/v1/audit-report-router.ts b/backend/src/ee/routes/v1/audit-report-router.tsnew file mode 100644index 0000000000..cd9fcdf797--- /dev/null+++ b/backend/src/ee/routes/v1/audit-report-router.ts@@ -0,0 +1,176 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import {+ AuditReportResultEntrySchema,+ AuditReportStatus,+ AuditReportType+} from "@app/ee/services/audit-report/audit-report-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";++const AuditReportConfigSchema = z.object({+ type: z.nativeEnum(AuditReportType),+ inputs: z.record(z.unknown())+});++const AuditReportSchema = z.object({+ id: z.string().uuid(),+ projectId: z.string(),+ requestedByUserId: z.string().uuid().nullable(),+ status: z.nativeEnum(AuditReportStatus),+ reportConfigs: z.array(AuditReportConfigSchema),+ emailRecipients: z.string().array(),+ resultSummary: z.array(AuditReportResultEntrySchema).nullable(),+ errorMessage: z.string().nullable(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export const registerAuditReportRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "requestAuditReport",+ description: "Request generation of one or more audit reports, delivered by email as CSV attachments",+ security: [{ bearerAuth: [] }],+ body: z.object({+ projectId: z.string().trim(),+ reports: z+ .array(+ z.object({+ type: z.nativeEnum(AuditReportType),+ inputs: z.record(z.unknown()).optional()+ })+ )+ .min(1)+ .describe("The report types to generate, each with optional type-specific inputs."),+ emailRecipients: z+ .array(z.string().email())+ .optional()+ .describe("Email addresses to deliver the reports to. Defaults to the requesting user's email.")+ }),+ response: {+ 200: AuditReportSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const report = await server.services.auditReport.requestReport(req.body, req.permission);+ await server.services.auditLog.createAuditLog({+ projectId: report.projectId,+ event: {+ type: EventType.CREATE_AUDIT_REPORT,+ metadata: {+ auditReportId: report.id,+ projectId: report.projectId,+ reportTypes: report.reportConfigs.map((config) => config.type),+ recipientCount: report.emailRecipients.length+ }+ },+ ...req.auditLogInfo+ });+ return report;+ }+ });++ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "listAuditReports",+ description: "List audit reports for a project",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ projectId: z.string().trim(),+ offset: z.coerce.number().min(0).default(0),+ limit: z.coerce.number().min(1).max(100).default(10)+ }),+ response: {+ 200: z.object({ reports: z.array(AuditReportSchema), totalCount: z.number() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { projectId, offset, limit } = req.query;+ const { reports, totalCount } = await server.services.auditReport.listReports(+ { projectId, offset, limit },+ req.permission+ );+ await server.services.auditLog.createAuditLog({+ projectId,+ event: { type: EventType.GET_AUDIT_REPORTS, metadata: { projectId } },+ ...req.auditLogInfo+ });+ return { reports, totalCount };+ }+ });++ server.route({+ method: "GET",+ url: "/:auditReportId",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getAuditReport",+ description: "Get a single audit report by ID",+ security: [{ bearerAuth: [] }],+ params: z.object({ auditReportId: z.string().uuid() }),+ querystring: z.object({ projectId: z.string().trim() }),+ response: {+ 200: AuditReportSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const report = await server.services.auditReport.getReportById(+ { projectId: req.query.projectId, auditReportId: req.params.auditReportId },+ req.permission+ );+ await server.services.auditLog.createAuditLog({+ projectId: report.projectId,+ event: {+ type: EventType.GET_AUDIT_REPORT,+ metadata: { auditReportId: report.id, projectId: report.projectId }+ },+ ...req.auditLogInfo+ });+ return report;+ }+ });++ server.route({+ method: "DELETE",+ url: "/:auditReportId",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "deleteAuditReport",+ description: "Delete an audit report",+ security: [{ bearerAuth: [] }],+ params: z.object({ auditReportId: z.string().uuid() }),+ querystring: z.object({ projectId: z.string().trim() }),+ response: {+ 200: AuditReportSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const report = await server.services.auditReport.deleteReport(+ { projectId: req.query.projectId, auditReportId: req.params.auditReportId },+ req.permission+ );+ await server.services.auditLog.createAuditLog({+ projectId: report.projectId,+ event: {+ type: EventType.DELETE_AUDIT_REPORT,+ metadata: { auditReportId: report.id, projectId: report.projectId }+ },+ ...req.auditLogInfo+ });+ return report;+ }+ });+};diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.tsindex 79e9c7d8c1..f8f2586fb4 100644--- a/backend/src/ee/routes/v1/index.ts+++ b/backend/src/ee/routes/v1/index.ts@@ -9,6 +9,7 @@ import { registerAiMcpEndpointRouter } from "./ai-mcp-endpoint-router";import { registerAiMcpServerRouter } from "./ai-mcp-server-router";import { registerAssumePrivilegeRouter } from "./assume-privilege-router";import { AUDIT_LOG_STREAM_REGISTER_ROUTER_MAP, registerAuditLogStreamRouter } from "./audit-log-stream-routers";+import { registerAuditReportRouter } from "./audit-report-router";import { registerCaCrlRouter } from "./certificate-authority-crl-router";import { registerDeprecatedProjectRoleRouter } from "./deprecated-project-role-router";import { registerDeprecatedProjectRouter } from "./deprecated-project-router";@@ -132,6 +133,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {await server.register(registerInsightsRouter, { prefix: "/insights" });await server.register(registerPamInsightsRouter, { prefix: "/insights/pam" });+ await server.register(registerAuditReportRouter, { prefix: "/audit-reports" });await server.register(async (pkiRouter) => {diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 9797132ac5..4fdc84985d 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -705,6 +705,12 @@ export enum EventType {VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",VIEW_INSIGHTS_SECRETS_DUPLICATION = "view-insights-secrets-duplication",VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS = "view-insights-secrets-management-counts",++ CREATE_AUDIT_REPORT = "create-audit-report",+ GET_AUDIT_REPORTS = "get-audit-reports",+ GET_AUDIT_REPORT = "get-audit-report",+ DELETE_AUDIT_REPORT = "delete-audit-report",+VIEW_INSIGHTS_PAM_SUMMARY = "view-insights-pam-summary",VIEW_INSIGHTS_PAM_SESSION_ACTIVITY = "view-insights-pam-session-activity",VIEW_INSIGHTS_PAM_TOP_ACTORS = "view-insights-pam-top-actors",@@ -5761,6 +5767,39 @@ interface ViewSecretManagementInsightsCountsEvent {};}+interface CreateAuditReportEvent {+ type: EventType.CREATE_AUDIT_REPORT;+ metadata: {+ auditReportId: string;+ projectId: string;+ reportTypes: string[];+ recipientCount: number;+ };+}++interface GetAuditReportsEvent {+ type: EventType.GET_AUDIT_REPORTS;+ metadata: {+ projectId: string;+ };+}++interface GetAuditReportEvent {+ type: EventType.GET_AUDIT_REPORT;+ metadata: {+ auditReportId: string;+ projectId: string;+ };+}++interface DeleteAuditReportEvent {+ type: EventType.DELETE_AUDIT_REPORT;+ metadata: {+ auditReportId: string;+ projectId: string;+ };+}+interface ViewAuditLogsEvent {type: EventType.VIEW_AUDIT_LOGS;metadata?: Record<string, unknown>;@@ -7980,6 +8019,10 @@ export type Event =| ViewSecretManagementInsightsSummaryEvent| ViewInsightsSecretsDuplicationEvent| ViewSecretManagementInsightsCountsEvent+ | CreateAuditReportEvent+ | GetAuditReportsEvent+ | GetAuditReportEvent+ | DeleteAuditReportEvent| ViewAuditLogsEvent| ViewPamInsightsSummaryEvent| ViewPamInsightsSessionActivityEventdiff --git a/backend/src/ee/services/audit-report/audit-report-dal.ts b/backend/src/ee/services/audit-report/audit-report-dal.tsnew file mode 100644index 0000000000..02caa50c54--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-dal.ts@@ -0,0 +1,65 @@+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";++import { AuditReportStatus } from "./audit-report-types";++export type TAuditReportDALFactory = ReturnType<typeof auditReportDALFactory>;++const IN_FLIGHT_STATUSES = [AuditReportStatus.Pending, AuditReportStatus.Processing];++export const auditReportDALFactory = (db: TDbClient) => {+ const auditReportOrm = ormify(db, TableName.AuditReport);++ const findByProject = async (+ projectId: string,+ { offset = 0, limit = 50 }: { offset?: number; limit?: number },+ tx?: Knex+ ) => {+ try {+ const docs = await (tx || db.replicaNode())(TableName.AuditReport)+ .where(`${TableName.AuditReport}.projectId`, projectId)+ .orderBy(`${TableName.AuditReport}.createdAt`, "desc")+ .offset(offset)+ .limit(limit);+ return docs;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByProject - Audit Report" });+ }+ };++ const countByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.AuditReport)+ .where(`${TableName.AuditReport}.projectId`, projectId)+ .count("* as count")+ .first<{ count: string | number } | undefined>();+ return Number(result?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "CountByProject - Audit Report" });+ }+ };++ const countInFlightByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.AuditReport)+ .where(`${TableName.AuditReport}.projectId`, projectId)+ .whereIn(`${TableName.AuditReport}.status`, IN_FLIGHT_STATUSES)+ .count("* as count")+ .first<{ count: string | number } | undefined>();+ return Number(result?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "CountInFlightByProject - Audit Report" });+ }+ };++ return {+ ...auditReportOrm,+ findByProject,+ countByProject,+ countInFlightByProject+ };+};diff --git a/backend/src/ee/services/audit-report/audit-report-fns.ts b/backend/src/ee/services/audit-report/audit-report-fns.tsnew file mode 100644index 0000000000..7f9976b3c5--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-fns.ts@@ -0,0 +1,113 @@+import { z } from "zod";++import { TAuditReports } from "@app/db/schemas";+import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";++import {+ AuditReportResultEntrySchema,+ AuditReportStatus,+ AuditReportType,+ MAX_AUDIT_REPORT_ROWS,+ TGeneratedReport+} from "./audit-report-types";++export const DAY_IN_MS = 24 * 60 * 60 * 1000;++export const daysSince = (date: Date): number => Math.max(0, Math.floor((Date.now() - date.getTime()) / DAY_IN_MS));++const CSV_LINE_BREAK = "\r\n";++// RFC 4180 cell escaping: quote when the value contains a comma, quote, CR or LF; double embedded quotes.+const escapeCsvCell = (value: string | number | null): string => {+ if (value === null) return "";+ const str = String(value);+ return /[",\r\n]/.test(str) ? `"${str.replace(/"/g, '""')}"` : str;+};++const toCsvRow = (cells: (string | number | null)[]): string => cells.map(escapeCsvCell).join(",");++// One report's block within the bundled CSV: a labelled section with its own column headers.+export type TAuditReportSection = {+ title: string;+ report: TGeneratedReport;+};++// Serialize every requested report into a SINGLE CSV file. Each report becomes its own section+// (title row → its column headers → its rows) so heterogeneous reports keep their natural columns,+// preceded by a small metadata header. Sections are separated by a blank line for spreadsheet readability.+export const serializeReportBundle = ({+ projectName,+ generatedAt,+ sections+}: {+ projectName: string;+ generatedAt: Date;+ sections: TAuditReportSection[];+}): Buffer => {+ const lines: string[] = [+ toCsvRow(["Infisical Audit Report"]),+ toCsvRow(["Project", projectName]),+ toCsvRow(["Generated At", generatedAt.toISOString()])+ ];++ sections.forEach(({ title, report }) => {+ lines.push("");+ // The section title occupies the first column; the report's own column headers sit on the SAME row,+ // shifted one column to the right. Data/notes are indented by one empty leading column so they line up+ // beneath those headers when opened in a spreadsheet (the title column acts as a left-margin label).+ lines.push(toCsvRow([title.toUpperCase(), ...report.columns]));+ if (report.rows.length === 0) {+ lines.push(toCsvRow(["", "No matching records"]));+ } else {+ report.rows.forEach((row) => {+ lines.push(toCsvRow(["", ...report.columns.map((column) => row[column] ?? null)]));+ });+ }+ if (report.truncated) {+ lines.push(toCsvRow(["", `Note: results truncated at ${MAX_AUDIT_REPORT_ROWS.toLocaleString()} rows`]));+ }+ });++ return Buffer.from(lines.join(CSV_LINE_BREAK), "utf8");+};++// Resolve folder ids to their human-readable secret paths in a single batched query.+export const buildFolderPathMap = async (+ folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">,+ projectId: string,+ folderIds: string[]+): Promise<Record<string, string>> => {+ const uniqueIds = [...new Set(folderIds)];+ if (!uniqueIds.length) return {};++ const folders = await folderDAL.findSecretPathByFolderIds(projectId, uniqueIds);+ const pathByFolderId: Record<string, string> = {};+ folders.forEach((folder) => {+ if (folder) pathByFolderId[folder.id] = folder.path;+ });+ return pathByFolderId;+};++// jsonb columns surface as `unknown` from the generated schema; validate (never cast) on read.+const StoredReportConfigsSchema = z.array(+ z.object({+ type: z.nativeEnum(AuditReportType),+ inputs: z.record(z.unknown())+ })+);+const StoredResultSummarySchema = z.array(AuditReportResultEntrySchema);++export const presentAuditReport = (report: TAuditReports) => ({+ id: report.id,+ projectId: report.projectId,+ requestedByUserId: report.requestedByUserId ?? null,+ status: z.nativeEnum(AuditReportStatus).parse(report.status),+ reportConfigs: StoredReportConfigsSchema.parse(report.reportConfigs),+ emailRecipients: report.emailRecipients,+ resultSummary: report.resultSummary == null ? null : StoredResultSummarySchema.parse(report.resultSummary),+ errorMessage: report.errorMessage ?? null,+ createdAt: report.createdAt,+ updatedAt: report.updatedAt+});++export type TPresentedAuditReport = ReturnType<typeof presentAuditReport>;diff --git a/backend/src/ee/services/audit-report/audit-report-generators.ts b/backend/src/ee/services/audit-report/audit-report-generators.tsnew file mode 100644index 0000000000..81cb833e46--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-generators.ts@@ -0,0 +1,466 @@+import picomatch from "picomatch";+import { z } from "zod";++import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TReminderDALFactory } from "@app/services/reminder/reminder-dal";+import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";+import { containsSecretReference } from "@app/services/secret-v2-bridge/secret-reference-fns";+import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";+import { TSecretValidationRuleDALFactory } from "@app/services/secret-validation-rule/secret-validation-rule-dal";+import { evaluateStaticSecretConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-fns";+import { parseSecretValidationRuleInputs } from "@app/services/secret-validation-rule/secret-validation-rule-schemas";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-types";++import { buildFolderPathMap, DAY_IN_MS, daysSince } from "./audit-report-fns";+import { AuditReportType, MAX_AUDIT_REPORT_ROWS, TGeneratedReport, TReportRow } from "./audit-report-types";++// The DALs every generator may draw from. Narrowed with Pick so the dependency contract is explicit and+// the same data-access layer the Insights feature uses is reused verbatim (no duplicate queries).+export type TAuditReportGeneratorDALs = {+ secretV2BridgeDAL: Pick<+ TSecretV2BridgeDALFactory,+ "findStaleByProject" | "findDuplicatedSecretValues" | "findValueValidationCandidatesByProject"+ >;+ folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;+ secretRotationV2DAL: Pick<TSecretRotationV2DALFactory, "findByProjectAndDateRange" | "findByProject">;+ reminderDAL: Pick<TReminderDALFactory, "findByProjectAndDateRange">;+ auditLogDAL: Pick<TAuditLogDALFactory, "find">;+ secretValidationRuleDAL: Pick<TSecretValidationRuleDALFactory, "find">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TReportGenerationContext = {+ projectId: string;+ orgId: string;+ dal: TAuditReportGeneratorDALs;+};++// A report definition. `inputsSchema` is the single source of truth for that report's inputs: the service+// validates request inputs against it, and each `run` re-parses with the same (concrete) schema to apply+// defaults/coercion. Input types stay precise because every `run` owns its concrete schema.+export type TReportDefinition = {+ type: AuditReportType;+ label: string;+ inputsSchema: z.ZodTypeAny;+ run: (ctx: TReportGenerationContext, rawInputs: unknown) => Promise<TGeneratedReport>;+};++// Cap a fully-materialized result set at the row ceiling, reporting truncation.+const applyRowCap = <T>(items: T[]): { items: T[]; truncated: boolean } => {+ if (items.length > MAX_AUDIT_REPORT_ROWS) {+ return { items: items.slice(0, MAX_AUDIT_REPORT_ROWS), truncated: true };+ }+ return { items, truncated: false };+};++// ─── Shared mappers ───────────────────────────────────────────────────────────++const ROTATION_COLUMNS = [+ "rotationName",+ "secretKeys",+ "environment",+ "secretPath",+ "nextRotationAt",+ "rotationStatus",+ "rotationInterval"+];++type TRotation = Awaited<ReturnType<TSecretRotationV2DALFactory["findByProject"]>>[number];++const mapRotations = (rotations: TRotation[]): TGeneratedReport => {+ const { items, truncated } = applyRowCap(rotations);+ return {+ columns: ROTATION_COLUMNS,+ truncated,+ rows: items.map((rotation) => ({+ rotationName: rotation.name,+ secretKeys: rotation.secretKeys.join(";"),+ environment: rotation.environment.slug,+ secretPath: rotation.folder.path,+ nextRotationAt: rotation.nextRotationAt ? rotation.nextRotationAt.toISOString() : null,+ rotationStatus: rotation.rotationStatus ?? null,+ rotationInterval: rotation.rotationInterval+ }))+ };+};++const REMINDER_COLUMNS = ["secretKey", "environment", "secretPath", "nextReminderDate", "message"];++type TReminder = Awaited<ReturnType<TReminderDALFactory["findByProjectAndDateRange"]>>[number];++const mapReminders = async (+ dal: TAuditReportGeneratorDALs,+ projectId: string,+ reminders: TReminder[]+): Promise<TGeneratedReport> => {+ const { items, truncated } = applyRowCap(reminders);+ const folderPathMap = await buildFolderPathMap(+ dal.folderDAL,+ projectId,+ items.map((reminder) => reminder.folderId)+ );+ return {+ columns: REMINDER_COLUMNS,+ truncated,+ rows: items.map((reminder) => ({+ secretKey: reminder.secretKey,+ environment: reminder.envSlug,+ secretPath: folderPathMap[reminder.folderId] ?? "/",+ nextReminderDate: new Date(reminder.nextReminderDate).toISOString(),+ message: reminder.message ?? null+ }))+ };+};++// ─── Secret access log helpers ──────────────────────────────────────────────────++const SECRET_ACCESS_EVENT_TYPES = [+ EventType.GET_SECRETS,+ EventType.GET_SECRET,+ EventType.DASHBOARD_GET_SECRET_VALUE,+ EventType.CREATE_SECRET,+ EventType.CREATE_SECRETS,+ EventType.UPDATE_SECRET,+ EventType.UPDATE_SECRETS,+ EventType.DELETE_SECRET,+ EventType.DELETE_SECRETS+];++const ActorMetadataSchema = z+ .object({ name: z.string(), email: z.string(), username: z.string(), identityId: z.string() })+ .partial()+ .passthrough();++const EventMetadataSchema = z+ .object({ secretKey: z.string(), environment: z.string(), secretPath: z.string() })+ .partial()+ .passthrough();++const parseRecord = <T>(schema: z.ZodType<T>, raw: unknown, fallback: T): T => {+ const result = schema.safeParse(raw);+ return result.success ? result.data : fallback;+};++// ─── Input schemas ──────────────────────────────────────────────────────────────++const NoInputsSchema = z.object({}).default({});+const StaleSecretsInputsSchema = z.object({ staleDays: z.number().int().min(1).max(3650).default(90) });+const DaysAheadInputsSchema = z.object({ daysAhead: z.number().int().min(1).max(365).default(7) });+const SecretAccessLogInputsSchema = z+ .object({+ fromDate: z.coerce.date().optional(),+ toDate: z.coerce.date().optional()+ })+ .transform((value) => {+ const toDate = value.toDate ?? new Date();+ const fromDate = value.fromDate ?? new Date(toDate.getTime() - 30 * DAY_IN_MS);+ return { fromDate, toDate };+ })+ .refine((value) => value.toDate >= value.fromDate, { message: "toDate must be on or after fromDate" })+ .refine((value) => value.toDate.getTime() - value.fromDate.getTime() <= 90 * DAY_IN_MS, {+ message: "Secret access log range cannot exceed 90 days"+ });++// ─── Definitions ────────────────────────────────────────────────────────────────++const staleSecretsReport: TReportDefinition = {+ type: AuditReportType.StaleSecrets,+ label: "Stale Secrets",+ inputsSchema: StaleSecretsInputsSchema,+ run: async ({ projectId, dal }, rawInputs) => {+ const { staleDays } = StaleSecretsInputsSchema.parse(rawInputs ?? {});+ const staleThreshold = new Date(Date.now() - staleDays * DAY_IN_MS);+ // Fetch one past the cap to detect truncation without a separate count query.+ const secrets = await dal.secretV2BridgeDAL.findStaleByProject(projectId, staleThreshold, {+ offset: 0,+ limit: MAX_AUDIT_REPORT_ROWS + 1+ });+ const { items, truncated } = applyRowCap(secrets);+ const folderPathMap = await buildFolderPathMap(+ dal.folderDAL,+ projectId,+ items.map((secret) => secret.folderId)+ );+ return {+ columns: ["secretKey", "environment", "secretPath", "lastUpdatedAt", "daysSinceUpdate"],+ truncated,+ rows: items.map((secret) => ({+ secretKey: secret.key,+ environment: secret.environment,+ secretPath: folderPathMap[secret.folderId] ?? "/",+ lastUpdatedAt: secret.updatedAt.toISOString(),+ daysSinceUpdate: daysSince(secret.updatedAt)+ }))+ };+ }+};++const duplicateSecretsReport: TReportDefinition = {+ type: AuditReportType.DuplicateSecrets,+ label: "Duplicate Secrets",+ inputsSchema: NoInputsSchema,+ run: async ({ projectId, dal }) => {+ const columns = ["groupId", "secretKey", "environment", "secretPath"];+ const groups = await dal.secretV2BridgeDAL.findDuplicatedSecretValues(projectId);+ if (!groups.length) return { columns, rows: [], truncated: false };++ const { decryptor } = await dal.kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ // Drop groups whose shared value is actually a secret reference (false-positive duplicates),+ // mirroring the Insights duplication logic.+ const realGroups = groups.filter((group) => {+ const [firstSecret] = group.secrets;+ if (!firstSecret) return false;+ if (!firstSecret.encryptedValue) return true;+ const decryptedValue = decryptor({ cipherTextBlob: firstSecret.encryptedValue }).toString();+ return !containsSecretReference(decryptedValue);+ });++ const folderPathMap = await buildFolderPathMap(+ dal.folderDAL,+ projectId,+ realGroups.flatMap((group) => group.secrets.map((secret) => secret.folderId))+ );++ const rows: TReportRow[] = [];+ let truncated = false;+ realGroups.forEach((group, index) => {+ group.secrets.forEach((secret) => {+ if (rows.length >= MAX_AUDIT_REPORT_ROWS) {+ truncated = true;+ return;+ }+ rows.push({+ groupId: index + 1,+ secretKey: secret.key,+ environment: secret.environment,+ secretPath: folderPathMap[secret.folderId] ?? "/"+ });+ });+ });++ return { columns, rows, truncated };+ }+};++const secretValidationComplianceReport: TReportDefinition = {+ type: AuditReportType.SecretValidationCompliance,+ label: "Secret Validation Compliance Violations",+ inputsSchema: NoInputsSchema,+ run: async ({ projectId, dal }) => {+ const columns = ["secretKey", "environment", "secretPath", "ruleName", "constraintType", "violation"];++ // Only static-secret rules constrain stored secret values; generated-credential rule types are+ // enforced at generation time and have no stored value to scan here.+ const rules = await dal.secretValidationRuleDAL.find({+ projectId,+ isActive: true,+ type: SecretValidationRuleType.StaticSecrets+ });+ if (!rules.length) return { columns, rows: [], truncated: false };++ // The same SecretManager data key encrypts both rule inputs and secret values.+ const { decryptor } = await dal.kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ const parsedRules = rules.map((rule) => ({+ name: rule.name,+ envId: rule.envId ?? null,+ secretPath: rule.secretPath,+ constraints: parseSecretValidationRuleInputs(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ ).constraints+ }));++ const secrets = await dal.secretV2BridgeDAL.findValueValidationCandidatesByProject(projectId);+ if (!secrets.length) return { columns, rows: [], truncated: false };++ // Resolve each secret's folder path + environment so a rule's path (which may be a glob pattern,+ // not just an absolute path) can be matched against the secret's concrete location.+ const folders = await dal.folderDAL.findSecretPathByFolderIds(projectId, [+ ...new Set(secrets.map((secret) => secret.folderId))+ ]);+ const folderById: Record<string, { path: string; envId: string; envSlug: string }> = {};+ folders.forEach((folder) => {+ if (folder) {+ folderById[folder.id] = { path: folder.path, envId: folder.envId, envSlug: folder.environmentSlug };+ }+ });++ const rows: TReportRow[] = [];+ let truncated = false;++ for (const secret of secrets) {+ const folder = folderById[secret.folderId];+ if (!folder) {+ // eslint-disable-next-line no-continue+ continue;+ }++ const coveringRules = parsedRules.filter(+ (rule) =>+ (!rule.envId || rule.envId === folder.envId) &&+ picomatch.isMatch(folder.path, rule.secretPath, { strictSlashes: false })+ );+ if (!coveringRules.length) {+ // eslint-disable-next-line no-continue+ continue;+ }++ // Decrypt once per covered secret, then evaluate it against every rule that covers it.+ const value = decryptor({ cipherTextBlob: secret.encryptedValue }).toString();++ for (const rule of coveringRules) {+ const violations = evaluateStaticSecretConstraints(rule.constraints, { key: secret.key, value });+ for (const violation of violations) {+ if (rows.length >= MAX_AUDIT_REPORT_ROWS) {+ truncated = true;+ break;+ }+ rows.push({+ secretKey: secret.key,+ environment: folder.envSlug,+ secretPath: folder.path,+ ruleName: rule.name,+ constraintType: violation.constraintLabel,+ violation: violation.message+ });+ }+ if (truncated) break;+ }+ if (truncated) break;+ }++ return { columns, rows, truncated };+ }+};++const upcomingRotationsReport: TReportDefinition = {+ type: AuditReportType.UpcomingRotations,+ label: "Upcoming Rotations",+ inputsSchema: DaysAheadInputsSchema,+ run: async ({ projectId, dal }, rawInputs) => {+ const { daysAhead } = DaysAheadInputsSchema.parse(rawInputs ?? {});+ const now = new Date();+ const endDate = new Date(now.getTime() + daysAhead * DAY_IN_MS);+ const rotations = await dal.secretRotationV2DAL.findByProjectAndDateRange({ projectId, startDate: now, endDate });+ return mapRotations(rotations);+ }+};++const failedRotationsReport: TReportDefinition = {+ type: AuditReportType.FailedRotations,+ label: "Failed Rotations",+ inputsSchema: NoInputsSchema,+ run: async ({ projectId, dal }) => {+ const rotations = await dal.secretRotationV2DAL.findByProject(projectId);+ return mapRotations(rotations.filter((rotation) => rotation.rotationStatus === "failed"));+ }+};++const upcomingRemindersReport: TReportDefinition = {+ type: AuditReportType.UpcomingReminders,+ label: "Upcoming Reminders",+ inputsSchema: DaysAheadInputsSchema,+ run: async ({ projectId, dal }, rawInputs) => {+ const { daysAhead } = DaysAheadInputsSchema.parse(rawInputs ?? {});+ const now = new Date();+ const endDate = new Date(now.getTime() + daysAhead * DAY_IN_MS);+ const reminders = await dal.reminderDAL.findByProjectAndDateRange({ projectId, startDate: now, endDate });+ return mapReminders(+ dal,+ projectId,+ reminders.filter((reminder) => new Date(reminder.nextReminderDate) >= now)+ );+ }+};++const overdueRemindersReport: TReportDefinition = {+ type: AuditReportType.OverdueReminders,+ label: "Overdue Reminders",+ inputsSchema: NoInputsSchema,+ run: async ({ projectId, dal }) => {+ const now = new Date();+ const reminders = await dal.reminderDAL.findByProjectAndDateRange({+ projectId,+ startDate: new Date(0),+ endDate: now+ });+ return mapReminders(+ dal,+ projectId,+ reminders.filter((reminder) => new Date(reminder.nextReminderDate) < now)+ );+ }+};++const secretAccessLogReport: TReportDefinition = {+ type: AuditReportType.SecretAccessLog,+ label: "Secret Access Log",+ inputsSchema: SecretAccessLogInputsSchema,+ run: async ({ projectId, orgId, dal }, rawInputs) => {+ const { fromDate, toDate } = SecretAccessLogInputsSchema.parse(rawInputs ?? {});+ const logs = await dal.auditLogDAL.find({+ orgId,+ projectId,+ eventType: SECRET_ACCESS_EVENT_TYPES,+ startDate: fromDate.toISOString(),+ endDate: toDate.toISOString(),+ offset: 0,+ limit: MAX_AUDIT_REPORT_ROWS + 1+ });+ const { items, truncated } = applyRowCap(logs);++ return {+ columns: [+ "timestamp",+ "actorType",+ "actorName",+ "actorEmail",+ "eventType",+ "secretKey",+ "environment",+ "secretPath",+ "ipAddress"+ ],+ truncated,+ rows: items.map((log) => {+ const actorMetadata = parseRecord(ActorMetadataSchema, log.actorMetadata, {});+ const eventMetadata = parseRecord(EventMetadataSchema, log.eventMetadata, {});+ return {+ timestamp: log.createdAt.toISOString(),+ actorType: log.actor,+ actorName:+ actorMetadata.name ?? actorMetadata.username ?? actorMetadata.email ?? actorMetadata.identityId ?? "",+ actorEmail: actorMetadata.email ?? "",+ eventType: log.eventType,+ secretKey: eventMetadata.secretKey ?? "",+ environment: eventMetadata.environment ?? "",+ secretPath: eventMetadata.secretPath ?? "",+ ipAddress: log.ipAddress ?? ""+ };+ })+ };+ }+};++export const AUDIT_REPORT_DEFINITIONS: Record<AuditReportType, TReportDefinition> = {+ [AuditReportType.StaleSecrets]: staleSecretsReport,+ [AuditReportType.DuplicateSecrets]: duplicateSecretsReport,+ [AuditReportType.SecretValidationCompliance]: secretValidationComplianceReport,+ [AuditReportType.UpcomingRotations]: upcomingRotationsReport,+ [AuditReportType.FailedRotations]: failedRotationsReport,+ [AuditReportType.UpcomingReminders]: upcomingRemindersReport,+ [AuditReportType.OverdueReminders]: overdueRemindersReport,+ [AuditReportType.SecretAccessLog]: secretAccessLogReport+};diff --git a/backend/src/ee/services/audit-report/audit-report-queue.ts b/backend/src/ee/services/audit-report/audit-report-queue.tsnew file mode 100644index 0000000000..371ae67707--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-queue.ts@@ -0,0 +1,141 @@+import { logger } from "@app/lib/logger";+import { QueueName, TQueueServiceFactory } from "@app/queue";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";++import { TAuditReportDALFactory } from "./audit-report-dal";+import { presentAuditReport, serializeReportBundle, TAuditReportSection } from "./audit-report-fns";+import {+ AUDIT_REPORT_DEFINITIONS,+ TAuditReportGeneratorDALs,+ TReportGenerationContext+} from "./audit-report-generators";+import { AuditReportStatus, TAuditReportResultEntry } from "./audit-report-types";++const WORKER_CONCURRENCY = 2;+const RATE_LIMIT_MAX = 10;+const RATE_LIMIT_DURATION_MS = 60 * 1000;++type TAuditReportQueueServiceFactoryDep = {+ queueService: TQueueServiceFactory;+ auditReportDAL: Pick<TAuditReportDALFactory, "findById" | "updateById">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ smtpService: Pick<TSmtpService, "sendMail">;+} & TAuditReportGeneratorDALs;++export type TAuditReportQueueServiceFactory = ReturnType<typeof auditReportQueueServiceFactory>;++export const auditReportQueueServiceFactory = ({+ queueService,+ auditReportDAL,+ projectDAL,+ smtpService,+ secretV2BridgeDAL,+ folderDAL,+ secretRotationV2DAL,+ reminderDAL,+ auditLogDAL,+ secretValidationRuleDAL,+ kmsService+}: TAuditReportQueueServiceFactoryDep) => {+ const generatorDAL: TAuditReportGeneratorDALs = {+ secretV2BridgeDAL,+ folderDAL,+ secretRotationV2DAL,+ reminderDAL,+ auditLogDAL,+ secretValidationRuleDAL,+ kmsService+ };++ queueService.start(+ QueueName.AuditReportGeneration,+ async (job) => {+ const { auditReportId } = job.data;++ const report = await auditReportDAL.findById(auditReportId);+ if (!report) {+ logger.error(`Audit report generation skipped, report not found [auditReportId=${auditReportId}]`);+ return;+ }+ // A successfully delivered report is terminal; guard against duplicate job delivery.+ if (report.status === AuditReportStatus.Completed || report.status === AuditReportStatus.Partial) {+ return;+ }++ try {+ const project = await projectDAL.findById(report.projectId);+ if (!project) {+ throw new Error(`Project '${report.projectId}' not found`);+ }++ await auditReportDAL.updateById(auditReportId, { status: AuditReportStatus.Processing });++ const { reportConfigs, emailRecipients } = presentAuditReport(report);+ const context: TReportGenerationContext = {+ projectId: report.projectId,+ orgId: project.orgId,+ dal: generatorDAL+ };++ const sections: TAuditReportSection[] = [];+ const resultSummary: TAuditReportResultEntry[] = [];++ for (const config of reportConfigs) {+ const definition = AUDIT_REPORT_DEFINITIONS[config.type];+ // eslint-disable-next-line no-await-in-loop+ const generated = await definition.run(context, config.inputs);+ sections.push({ title: definition.label, report: generated });+ resultSummary.push({ type: config.type, rowCount: generated.rows.length, truncated: generated.truncated });+ }++ // All requested reports are combined into a single sectioned CSV attachment.+ const generatedAt = new Date();+ const csv = serializeReportBundle({ projectName: project.name, generatedAt, sections });++ await smtpService.sendMail({+ template: SmtpTemplates.AuditReport,+ subjectLine: `Your Infisical audit report for ${project.name}`,+ recipients: emailRecipients,+ substitutions: {+ projectName: project.name,+ reports: resultSummary.map((entry) => ({+ label: AUDIT_REPORT_DEFINITIONS[entry.type].label,+ rowCount: entry.rowCount,+ truncated: entry.truncated+ }))+ },+ attachments: [+ {+ filename: `infisical-audit-report-${generatedAt.toISOString().slice(0, 10)}.csv`,+ content: csv,+ contentType: "text/csv"+ }+ ]+ });++ const truncatedAny = resultSummary.some((entry) => entry.truncated);+ await auditReportDAL.updateById(auditReportId, {+ status: truncatedAny ? AuditReportStatus.Partial : AuditReportStatus.Completed,+ // jsonb must be serialized before write (see requestReport for context).+ resultSummary: JSON.stringify(resultSummary),+ errorMessage: null+ });++ logger.info(+ `auditReportQueue: Audit report generated [auditReportId=${auditReportId}] [projectId=${report.projectId}]`+ );+ } catch (error) {+ logger.error(error, `auditReportQueue: Audit report generation failed [auditReportId=${auditReportId}]`);+ await auditReportDAL.updateById(auditReportId, {+ status: AuditReportStatus.Failed,+ errorMessage: error instanceof Error ? error.message : "Unknown error during report generation"+ });+ throw error;+ }+ },+ { concurrency: WORKER_CONCURRENCY, limiter: { max: RATE_LIMIT_MAX, duration: RATE_LIMIT_DURATION_MS } }+ );++ return {};+};diff --git a/backend/src/ee/services/audit-report/audit-report-service.ts b/backend/src/ee/services/audit-report/audit-report-service.tsnew file mode 100644index 0000000000..15c996e24d--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-service.ts@@ -0,0 +1,225 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType } from "@app/db/schemas";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAuditReportActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, 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 { TProjectDALFactory } from "@app/services/project/project-dal";+import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";+import { TUserDALFactory } from "@app/services/user/user-dal";++import { TAuditReportDALFactory } from "./audit-report-dal";+import { presentAuditReport } from "./audit-report-fns";+import { AUDIT_REPORT_DEFINITIONS } from "./audit-report-generators";+import {+ AuditReportStatus,+ MAX_CONCURRENT_AUDIT_REPORTS,+ TAuditReportConfig,+ TAuditReportServiceActor,+ TDeleteAuditReportDTO,+ TGetAuditReportDTO,+ TListAuditReportsDTO,+ TRequestAuditReportDTO+} from "./audit-report-types";++const MAX_EMAIL_RECIPIENTS = 20;++type TAuditReportServiceFactoryDep = {+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ auditReportDAL: TAuditReportDALFactory;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;+ userDAL: Pick<TUserDALFactory, "findById">;+ queueService: Pick<TQueueServiceFactory, "queue">;+};++export type TAuditReportServiceFactory = ReturnType<typeof auditReportServiceFactory>;++export const auditReportServiceFactory = ({+ permissionService,+ licenseService,+ auditReportDAL,+ projectDAL,+ projectBotService,+ userDAL,+ queueService+}: TAuditReportServiceFactoryDep) => {+ // Audit reports share the Secret Insights entitlement (license) but have their own permission subject+ // with granular Create/Read/Delete actions.+ const checkPermission = async (+ projectId: string,+ actor: TAuditReportServiceActor,+ action: ProjectPermissionAuditReportActions+ ) => {+ const plan = await licenseService.getPlan(actor.orgId);+ if (!plan.secretAccessInsights) {+ throw new BadRequestError({+ message: "Audit reports are not available on your plan. Please upgrade to access audit reports."+ });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.AuditReports);+ };++ // Validate each requested report against its definition's input schema, applying defaults so the stored+ // config is canonical. Rejects unknown/duplicate types and malformed inputs before anything is persisted.+ const buildReportConfigs = (reports: TRequestAuditReportDTO["reports"]): TAuditReportConfig[] => {+ if (!reports.length) {+ throw new BadRequestError({ message: "At least one report must be requested" });+ }++ const seenTypes = new Set<string>();+ return reports.map(({ type, inputs }) => {+ const definition = AUDIT_REPORT_DEFINITIONS[type];+ if (!definition) {+ throw new BadRequestError({ message: `Unsupported report type: ${type}` });+ }+ if (seenTypes.has(type)) {+ throw new BadRequestError({ message: `Each report type can only be requested once per batch: ${type}` });+ }+ seenTypes.add(type);++ // Validate now so bad inputs are rejected before persistence; the raw inputs are stored as-is and the+ // generation worker re-parses (applying defaults/coercion) against the same schema at run time.+ const candidateInputs = inputs ?? {};+ const result = definition.inputsSchema.safeParse(candidateInputs);+ if (!result.success) {+ throw new BadRequestError({+ message: `Invalid inputs for ${type}: ${result.error.issues.map((issue) => issue.message).join(", ")}`+ });+ }+ return { type, inputs: candidateInputs };+ });+ };++ const resolveRecipients = async (+ requestedRecipients: string[] | undefined,+ actor: TAuditReportServiceActor+ ): Promise<string[]> => {+ if (requestedRecipients?.length) {+ if (requestedRecipients.length > MAX_EMAIL_RECIPIENTS) {+ throw new BadRequestError({ message: `A maximum of ${MAX_EMAIL_RECIPIENTS} recipients is allowed` });+ }+ return [...new Set(requestedRecipients.map((email) => email.trim().toLowerCase()))];+ }++ // Default to the requesting user's own email.+ if (actor.type === ActorType.USER) {+ const user = await userDAL.findById(actor.id);+ if (user?.email) return [user.email];+ }++ throw new BadRequestError({ message: "At least one email recipient is required" });+ };++ const requestReport = async (dto: TRequestAuditReportDTO, actor: TAuditReportServiceActor) => {+ await checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Create);++ const project = await projectDAL.findById(dto.projectId);+ if (!project) {+ throw new NotFoundError({ message: `Project with ID '${dto.projectId}' not found` });+ }++ // Reports draw exclusively from the secret v2 data model; reject legacy projects up front with a clear+ // error instead of silently producing empty reports.+ const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);+ if (!shouldUseSecretV2Bridge) {+ throw new BadRequestError({ message: "Audit reports are not supported for this project version" });+ }++ const reportConfigs = buildReportConfigs(dto.reports);+ const emailRecipients = await resolveRecipients(dto.emailRecipients, actor);++ const inFlightCount = await auditReportDAL.countInFlightByProject(dto.projectId);+ if (inFlightCount >= MAX_CONCURRENT_AUDIT_REPORTS) {+ throw new BadRequestError({+ message: `This project already has ${MAX_CONCURRENT_AUDIT_REPORTS} reports in progress. Please wait for them to finish.`+ });+ }++ const report = await auditReportDAL.create({+ projectId: dto.projectId,+ requestedByUserId: actor.type === ActorType.USER ? actor.id : null,+ status: AuditReportStatus.Pending,+ // jsonb columns must be serialized before insert — pg otherwise treats a top-level JS array as a+ // Postgres array literal rather than a JSON value.+ reportConfigs: JSON.stringify(reportConfigs),+ emailRecipients+ });++ await queueService.queue(+ QueueName.AuditReportGeneration,+ QueueJobs.GenerateAuditReport,+ { auditReportId: report.id },+ {+ jobId: `audit-report-${report.id}`,+ attempts: 3,+ backoff: { type: "exponential", delay: 5000 },+ removeOnComplete: true,+ removeOnFail: true+ }+ );++ logger.info(`Audit report requested [auditReportId=${report.id}] [projectId=${dto.projectId}]`);++ return presentAuditReport(report);+ };++ const listReports = async (dto: TListAuditReportsDTO, actor: TAuditReportServiceActor) => {+ await checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Read);++ const reports = await auditReportDAL.findByProject(dto.projectId, {+ offset: dto.offset,+ limit: dto.limit+ });+ const totalCount = await auditReportDAL.countByProject(dto.projectId);+ return { reports: reports.map(presentAuditReport), totalCount };+ };++ const getReportById = async (dto: TGetAuditReportDTO, actor: TAuditReportServiceActor) => {+ await checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Read);++ const report = await auditReportDAL.findById(dto.auditReportId);+ if (!report || report.projectId !== dto.projectId) {+ throw new NotFoundError({ message: `Audit report with ID '${dto.auditReportId}' not found` });+ }++ return presentAuditReport(report);+ };++ const deleteReport = async (dto: TDeleteAuditReportDTO, actor: TAuditReportServiceActor) => {+ await checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Delete);++ const report = await auditReportDAL.findById(dto.auditReportId);+ if (!report || report.projectId !== dto.projectId) {+ throw new NotFoundError({ message: `Audit report with ID '${dto.auditReportId}' not found` });+ }++ await auditReportDAL.deleteById(dto.auditReportId);+ return presentAuditReport(report);+ };++ return {+ requestReport,+ listReports,+ getReportById,+ deleteReport+ };+};diff --git a/backend/src/ee/services/audit-report/audit-report-types.ts b/backend/src/ee/services/audit-report/audit-report-types.tsnew file mode 100644index 0000000000..0637c75e2c--- /dev/null+++ b/backend/src/ee/services/audit-report/audit-report-types.ts@@ -0,0 +1,83 @@+import { z } from "zod";++import { OrgServiceActor } from "@app/lib/types";++export enum AuditReportType {+ StaleSecrets = "STALE_SECRETS",+ DuplicateSecrets = "DUPLICATE_SECRETS",+ SecretValidationCompliance = "SECRET_VALIDATION_COMPLIANCE",+ UpcomingRotations = "UPCOMING_ROTATIONS",+ FailedRotations = "FAILED_ROTATIONS",+ UpcomingReminders = "UPCOMING_REMINDERS",+ OverdueReminders = "OVERDUE_REMINDERS",+ SecretAccessLog = "SECRET_ACCESS_LOG"+}++export enum AuditReportStatus {+ Pending = "pending",+ Processing = "processing",+ Completed = "completed",+ // At least one report in the batch hit the row cap (the report is still delivered, just truncated).+ Partial = "partial",+ Failed = "failed"+}++// Hard ceiling on rows per individual report. Beyond this the report is marked truncated.+export const MAX_AUDIT_REPORT_ROWS = 100_000;+// Max number of in-flight (pending/processing) report batches per project, to bound DB-heavy work.+export const MAX_CONCURRENT_AUDIT_REPORTS = 5;++// One requested report within a batch. `inputs` is validated against the matching report definition's+// schema by the service before persistence, so stored inputs are always canonical.+export type TAuditReportConfig = {+ type: AuditReportType;+ inputs: Record<string, unknown>;+};++// Per-report outcome recorded on the batch once generation completes.+export const AuditReportResultEntrySchema = z.object({+ type: z.nativeEnum(AuditReportType),+ rowCount: z.number(),+ truncated: z.boolean()+});+export type TAuditReportResultEntry = z.infer<typeof AuditReportResultEntrySchema>;++// A single generated report's tabular payload. Cells are pre-stringified at the generator boundary so+// CSV serialization is a pure formatting step with no per-type knowledge.+export type TReportRow = Record<string, string | number | null>;+export type TGeneratedReport = {+ columns: string[];+ rows: TReportRow[];+ truncated: boolean;+};++// ─── Service DTOs ─────────────────────────────────────────────────────────────++export type TRequestAuditReportDTO = {+ projectId: string;+ reports: { type: AuditReportType; inputs?: Record<string, unknown> }[];+ emailRecipients?: string[];+};++export type TListAuditReportsDTO = {+ projectId: string;+ offset?: number;+ limit?: number;+};++export type TGetAuditReportDTO = {+ projectId: string;+ auditReportId: string;+};++export type TDeleteAuditReportDTO = {+ projectId: string;+ auditReportId: string;+};++export type TAuditReportServiceActor = OrgServiceActor;++// Job payload for the generation queue.+export type TGenerateAuditReportJobPayload = {+ auditReportId: string;+};diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex fad2c10ca4..bdcd87bb7a 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -7,6 +7,7 @@ import {ProjectPermissionApprovalRequestActions,ProjectPermissionApprovalRequestGrantActions,ProjectPermissionAuditLogsActions,+ ProjectPermissionAuditReportActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,ProjectPermissionCertificatePolicyActions,@@ -498,6 +499,15 @@ const buildAdminPermissionRules = () => {can([ProjectPermissionInsightsActions.Read], ProjectPermissionSub.Insights);+ can(+ [+ ProjectPermissionAuditReportActions.Create,+ ProjectPermissionAuditReportActions.Read,+ ProjectPermissionAuditReportActions.Delete+ ],+ ProjectPermissionSub.AuditReports+ );+return rules;};@@ -632,6 +642,7 @@ const buildMemberPermissionRules = () => {can([ProjectPermissionActions.Read], ProjectPermissionSub.Role);can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);+ can([ProjectPermissionAuditReportActions.Read], ProjectPermissionSub.AuditReports);can([ProjectPermissionActions.Read], ProjectPermissionSub.IpAllowList);can([ProjectPermissionCertificateAuthorityActions.Read], ProjectPermissionSub.CertificateAuthorities);@@ -762,6 +773,7 @@ const buildViewerPermissionRules = () => {can(ProjectPermissionActions.Read, ProjectPermissionSub.Environments);can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags);can(ProjectPermissionAuditLogsActions.Read, ProjectPermissionSub.AuditLogs);+ can(ProjectPermissionAuditReportActions.Read, ProjectPermissionSub.AuditReports);can(ProjectPermissionActions.Read, ProjectPermissionSub.IpAllowList);can(ProjectPermissionCertificateAuthorityActions.Read, ProjectPermissionSub.CertificateAuthorities);can(ProjectPermissionCertificateActions.Read, ProjectPermissionSub.Certificates);diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex a47d83b541..82a7d5de79 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -269,6 +269,12 @@ export enum ProjectPermissionInsightsActions {Read = "read"}+export enum ProjectPermissionAuditReportActions {+ Create = "create",+ Read = "read",+ Delete = "delete"+}+export enum ProjectPermissionPamAccountActions {Access = "access",Read = "read",@@ -403,7 +409,8 @@ export enum ProjectPermissionSub {McpServers = "mcp-servers",McpActivityLogs = "mcp-activity-logs",HoneyTokens = "honey-tokens",- Insights = "insights"+ Insights = "insights",+ AuditReports = "audit-reports"}// Structure: { [subject]: { [action]: allowedConditionKeys[] } }@@ -776,7 +783,8 @@ export type ProjectPermissionSet =| [ProjectPermissionApprovalRequestActions, ProjectPermissionSub.ApprovalRequests]| [ProjectPermissionApprovalRequestGrantActions, ProjectPermissionSub.ApprovalRequestGrants]| [ProjectPermissionSecretApprovalRequestActions, ProjectPermissionSub.SecretApprovalRequest]- | [ProjectPermissionInsightsActions, ProjectPermissionSub.Insights];+ | [ProjectPermissionInsightsActions, ProjectPermissionSub.Insights]+ | [ProjectPermissionAuditReportActions, ProjectPermissionSub.AuditReports];const SECRET_PATH_MISSING_SLASH_ERR_MSG = "Invalid Secret Path; it must start with a '/'";const SECRET_PATH_PERMISSION_OPERATOR_SCHEMA = z.union([@@ -1708,6 +1716,12 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),+ z.object({+ subject: z.literal(ProjectPermissionSub.AuditReports).describe("The entity this permission pertains to."),+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAuditReportActions).describe(+ "Describe what action an entity can take."+ )+ }),z.object({subject: z.literal(ProjectPermissionSub.IpAllowList).describe("The entity this permission pertains to."),action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex a6da7ffdab..7bcad96dbc 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -102,6 +102,7 @@ export enum QueueName {InvalidateCache = "invalidate-cache",SecretScanningV2 = "secret-scanning-v2",UserNotification = "user-notification",+ AuditReportGeneration = "audit-report-generation",PamSessionExpiration = "pam-session-expiration",PamSessionAiSummary = "pam-session-ai-summary",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",@@ -168,6 +169,7 @@ export enum QueueJobs {DailyReminders = "daily-reminders",SecretReminderMigration = "secret-reminder-migration",UserNotification = "user-notification-job",+ GenerateAuditReport = "generate-audit-report-job",HealthAlert = "health-alert",CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal",PamAccountRotation = "pam-account-rotation",@@ -454,6 +456,10 @@ export type TQueueJobTypes = {name: QueueJobs.UserNotification;payload: { notifications: TCreateUserNotificationDTO[] };};+ [QueueName.AuditReportGeneration]: {+ name: QueueJobs.GenerateAuditReport;+ payload: { auditReportId: string };+ };[QueueName.PamSessionExpiration]: {name: QueueJobs.PamSessionExpiration;payload: { sessionId: string };diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex cfc47a237e..9cfa9b58d5 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -46,6 +46,9 @@ import { auditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/import { auditLogStreamOutboxDALFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal";import { auditLogStreamOutboxQueueFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue";import { auditLogStreamOutboxServiceFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service";+import { auditReportDALFactory } from "@app/ee/services/audit-report/audit-report-dal";+import { auditReportQueueServiceFactory } from "@app/ee/services/audit-report/audit-report-queue";+import { auditReportServiceFactory } from "@app/ee/services/audit-report/audit-report-service";import { certificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";import { certificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-service";import { certificateEstServiceFactory } from "@app/ee/services/certificate-est/certificate-est-service";@@ -2800,6 +2803,31 @@ export const registerRoutes = async (keyStore});+ const auditReportDAL = auditReportDALFactory(db);+ const auditReportService = auditReportServiceFactory({+ permissionService,+ licenseService,+ auditReportDAL,+ projectDAL,+ projectBotService,+ userDAL,+ queueService+ });+ // Registers the BullMQ worker that generates the CSVs and emails them.+ auditReportQueueServiceFactory({+ queueService,+ auditReportDAL,+ projectDAL,+ smtpService,+ secretV2BridgeDAL,+ folderDAL,+ secretRotationV2DAL,+ reminderDAL,+ auditLogDAL,+ secretValidationRuleDAL,+ kmsService+ });+const pkiSyncQueue = pkiSyncQueueFactory({queueService,kmsService,@@ -3881,6 +3909,7 @@ export const registerRoutes = async (microsoftTeams: microsoftTeamsService,assumePrivileges: assumePrivilegeService,insights: insightsService,+ auditReport: auditReportService,pamInsights: pamInsightsService,githubOrgSync: githubOrgSyncConfigService,gitHubApp: gitHubAppService,diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.tsindex 6c6a2c202b..c73fa380ca 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts@@ -1348,6 +1348,26 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {}};+ // All non-personal secrets in a project that carry a value, with just the fields needed to evaluate+ // them against secret validation rules (key for key-constraints, encryptedValue for value-constraints,+ // folderId to resolve the secret's path/environment for rule matching).+ const findValueValidationCandidatesByProject = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.SecretV2)+ .leftJoin(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)+ .leftJoin(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .where(`${TableName.Environment}.projectId`, projectId)+ .whereNull(`${TableName.Environment}.deleteAfter`)+ .whereNull(`${TableName.SecretV2}.userId`)+ .whereNotNull(`${TableName.SecretV2}.encryptedValue`)+ .select(`${TableName.SecretV2}.key`, `${TableName.SecretV2}.folderId`, `${TableName.SecretV2}.encryptedValue`);++ return result as { key: string; folderId: string; encryptedValue: Buffer }[];+ } catch (error) {+ throw new DatabaseError({ error, name: "findValueValidationCandidatesByProject" });+ }+ };+const countStaleByProject = async (projectId: string, staleBeforeDate: Date, tx?: Knex) => {try {const result = await (tx || db.replicaNode())(TableName.SecretV2)@@ -1406,6 +1426,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {findStaleByProject,countStaleByProject,countByProject,+ findValueValidationCandidatesByProject,findDuplicatedSecretValues,findOne,find,diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.tsindex cac4dace45..06231c2796 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts@@ -289,6 +289,35 @@ const evaluateConstraint = (constraint: TConstraint, secret: TSecretToValidate):}};+export type TStaticSecretConstraintViolation = {+ constraintType: ConstraintType;+ constraintLabel: string;+ message: string;+};++/**+ * Evaluate a single secret against a set of static-secret constraints, returning every violation+ * (non-throwing). Reused by the audit-report compliance scan to surface already-stored secrets that do+ * not conform to a validation rule that was created after them.+ */+export const evaluateStaticSecretConstraints = (+ constraints: TConstraint[],+ secret: TSecretToValidate+): TStaticSecretConstraintViolation[] => {+ const violations: TStaticSecretConstraintViolation[] = [];+ for (const constraint of constraints) {+ const error = evaluateConstraint(constraint, secret);+ if (error) {+ violations.push({+ constraintType: constraint.type,+ constraintLabel: CONSTRAINT_LABELS[constraint.type],+ message: error+ });+ }+ }+ return violations;+};+/*** Evaluate static secret constraints against a set of secrets.*/diff --git a/backend/src/services/smtp/emails/AuditReportTemplate.tsx b/backend/src/services/smtp/emails/AuditReportTemplate.tsxnew file mode 100644index 0000000000..b33bcf0056--- /dev/null+++ b/backend/src/services/smtp/emails/AuditReportTemplate.tsx@@ -0,0 +1,43 @@+import { Heading, Section, Text } from "@react-email/components";+import React from "react";++import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";++interface AuditReportTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {+ projectName: string;+ reports: { label: string; rowCount: number; truncated: boolean }[];+}++export const AuditReportTemplate = ({ siteUrl, projectName, reports }: AuditReportTemplateProps) => {+ return (+ <BaseEmailWrapper title="Audit Report" preview="Your requested audit report is ready." siteUrl={siteUrl}>+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">+ Your <strong>audit report</strong> is ready+ </Heading>+ <Section className="px-[24px] mt-[36px] pt-[8px] pb-[8px] text-[14px] border border-solid border-gray-200 rounded-md bg-gray-50">+ <Text className="text-[14px]">+ The audit report you requested for the project <strong>{projectName}</strong> has been generated and is+ attached to this email as a CSV file. It includes the following {reports.length === 1 ? "report" : "reports"}:+ </Text>+ {reports.map((report) => (+ <Text key={report.label} className="text-[14px] text-slate-700 my-[4px]">+ <strong className="text-black">{report.label}:</strong> {report.rowCount.toLocaleString()} result+ {report.rowCount === 1 ? "" : "s"}+ {report.truncated ? " (truncated — row limit reached)" : ""}+ </Text>+ ))}+ </Section>+ </BaseEmailWrapper>+ );+};++export default AuditReportTemplate;++AuditReportTemplate.PreviewProps = {+ projectName: "Example Project",+ reports: [+ { label: "Stale Secrets", rowCount: 42, truncated: false },+ { label: "Secret Access Log", rowCount: 100000, truncated: true }+ ],+ siteUrl: "https://infisical.com"+} as AuditReportTemplateProps;diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.tsindex 33ed3c140e..2cbbcdff87 100644--- a/backend/src/services/smtp/emails/index.ts+++ b/backend/src/services/smtp/emails/index.ts@@ -3,6 +3,7 @@ export * from "./AccessApprovalRequestUpdatedTemplate";export * from "./AccessPamRequestBypassedTemplate";export * from "./AccountDeletionConfirmationTemplate";export * from "./AuditLogMigrationAlertTemplate";+export * from "./AuditReportTemplate";export * from "./CredentialRotationFailedTemplate";export * from "./EmailChangeRequestNotificationTemplate";export * from "./EmailMfaTemplate";diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.tsindex 52814d7246..f089a9d7d9 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -13,6 +13,7 @@ import {AccessPamRequestBypassedTemplate,AccountDeletionConfirmationTemplate,AuditLogMigrationAlertTemplate,+ AuditReportTemplate,CredentialRotationFailedTemplate,EmailChangeRequestNotificationTemplate,EmailMfaTemplate,@@ -54,11 +55,17 @@ import {import DynamicSecretLeaseRevocationFailedTemplate from "./emails/DynamicSecretLeaseRevocationFailedTemplate";export type TSmtpConfig = SMTPTransport.Options;+export type TSmtpAttachment = {+ filename: string;+ content: Buffer | string;+ contentType?: string;+};export type TSmtpSendMail = {template: SmtpTemplates;subjectLine: string;recipients: string[];substitutions: object;+ attachments?: TSmtpAttachment[];};export type TSmtpService = ReturnType<typeof smtpServiceFactory>;@@ -106,7 +113,8 @@ export enum SmtpTemplates {DynamicSecretLeaseRevocationFailed = "dynamicSecretLeaseRevocationFailed",CredentialRotationFailed = "credentialRotationFailed",AuditLogMigrationAlert = "auditLogMigrationAlert",- HoneyTokenTriggered = "honeyTokenTriggered"+ HoneyTokenTriggered = "honeyTokenTriggered",+ AuditReport = "auditReport"}export enum SmtpHost {@@ -162,14 +170,15 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {[SmtpTemplates.DynamicSecretLeaseRevocationFailed]: DynamicSecretLeaseRevocationFailedTemplate,[SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate,[SmtpTemplates.AuditLogMigrationAlert]: AuditLogMigrationAlertTemplate,- [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate+ [SmtpTemplates.HoneyTokenTriggered]: HoneyTokenTriggeredTemplate,+ [SmtpTemplates.AuditReport]: AuditReportTemplate};export const smtpServiceFactory = (cfg: TSmtpConfig) => {const smtp = createTransport(cfg);const isSmtpOn = Boolean(cfg.host);- const sendMail = async ({ substitutions, recipients, template, subjectLine }: TSmtpSendMail) => {+ const sendMail = async ({ substitutions, recipients, template, subjectLine, attachments }: TSmtpSendMail) => {const appCfg = getConfig();const EmailTemplate = EmailTemplateMap[template];@@ -191,7 +200,8 @@ export const smtpServiceFactory = (cfg: TSmtpConfig) => {from: cfg.from,to: recipients.join(", "),subject: subjectLine,- html: htmlToSend+ html: htmlToSend,+ attachments});} else {logger.info("SMTP is not configured. Outputting it in terminal");diff --git a/frontend/src/context/ProjectPermissionContext/index.tsx b/frontend/src/context/ProjectPermissionContext/index.tsxindex d2299b87ad..ea839cefc3 100644--- a/frontend/src/context/ProjectPermissionContext/index.tsx+++ b/frontend/src/context/ProjectPermissionContext/index.tsx@@ -3,6 +3,7 @@ export type { ProjectPermissionSet, TProjectPermission } from "./types";export {ProjectPermissionActions,ProjectPermissionAuditLogsActions,+ ProjectPermissionAuditReportActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,ProjectPermissionCertificatePolicyActions,diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex 2bbeb50f13..96a0c59ff0 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -233,6 +233,12 @@ export enum ProjectPermissionInsightsActions {Read = "read"}+export enum ProjectPermissionAuditReportActions {+ Create = "create",+ Read = "read",+ Delete = "delete"+}+export enum ProjectPermissionAppConnectionActions {Read = "read-app-connections",Create = "create-app-connections",@@ -477,7 +483,8 @@ export enum ProjectPermissionSub {HoneyTokens = "honey-tokens",ApprovalRequests = "approval-requests",ApprovalRequestGrants = "approval-request-grants",- Insights = "insights"+ Insights = "insights",+ AuditReports = "audit-reports"}export type SecretSubjectFields = {@@ -775,6 +782,7 @@ export type ProjectPermissionSet =| [ProjectPermissionApprovalRequestGrantActions, ProjectPermissionSub.ApprovalRequestGrants]| [ProjectPermissionSecretApprovalRequestActions, ProjectPermissionSub.SecretApprovalRequest]| [ProjectPermissionInsightsActions, ProjectPermissionSub.Insights]+ | [ProjectPermissionAuditReportActions, ProjectPermissionSub.AuditReports]| [ProjectPermissionHoneyTokenActions,(diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsxindex 7ad4f88de1..33176e3ac0 100644--- a/frontend/src/context/index.tsx+++ b/frontend/src/context/index.tsx@@ -18,6 +18,7 @@ export type { TProjectPermission } from "./ProjectPermissionContext";export {ProjectPermissionActions,ProjectPermissionAuditLogsActions,+ ProjectPermissionAuditReportActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,ProjectPermissionCertificatePolicyActions,diff --git a/frontend/src/hooks/api/auditReports/index.ts b/frontend/src/hooks/api/auditReports/index.tsnew file mode 100644index 0000000000..6220505978--- /dev/null+++ b/frontend/src/hooks/api/auditReports/index.ts@@ -0,0 +1,12 @@+export { useDeleteAuditReport, useRequestAuditReport } from "./mutations";+export { auditReportKeys, useGetAuditReports } from "./queries";+export {+ AuditReportStatus,+ AuditReportType,+ type TAuditReport,+ type TAuditReportConfig,+ type TAuditReportResultEntry,+ type TDeleteAuditReportDTO,+ type TGetAuditReportsDTO,+ type TRequestAuditReportDTO+} from "./types";diff --git a/frontend/src/hooks/api/auditReports/mutations.tsx b/frontend/src/hooks/api/auditReports/mutations.tsxnew file mode 100644index 0000000000..7bd17669f3--- /dev/null+++ b/frontend/src/hooks/api/auditReports/mutations.tsx@@ -0,0 +1,33 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { auditReportKeys } from "./queries";+import { TAuditReport, TDeleteAuditReportDTO, TRequestAuditReportDTO } from "./types";++export const useRequestAuditReport = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (dto: TRequestAuditReportDTO) => {+ const { data } = await apiRequest.post<TAuditReport>("/api/v1/audit-reports", dto);+ return data;+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: auditReportKeys.all() })+ });+};++export const useDeleteAuditReport = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ projectId, auditReportId }: TDeleteAuditReportDTO) => {+ const { data } = await apiRequest.delete<TAuditReport>(+ `/api/v1/audit-reports/${auditReportId}`,+ {+ params: { projectId }+ }+ );+ return data;+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: auditReportKeys.all() })+ });+};diff --git a/frontend/src/hooks/api/auditReports/queries.tsx b/frontend/src/hooks/api/auditReports/queries.tsxnew file mode 100644index 0000000000..de78792fb1--- /dev/null+++ b/frontend/src/hooks/api/auditReports/queries.tsx@@ -0,0 +1,46 @@+import { useQuery, UseQueryOptions } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { AuditReportStatus, TAuditReport, TGetAuditReportsDTO } from "./types";++type TGetAuditReportsResponse = { reports: TAuditReport[]; totalCount: number };++export const auditReportKeys = {+ all: () => ["audit-reports"] as const,+ list: (params: TGetAuditReportsDTO) => [...auditReportKeys.all(), "list", params] as const+};++// While any report is still generating, poll so the dashboard reflects status transitions in near real time.+const IN_FLIGHT_STATUSES = [AuditReportStatus.Pending, AuditReportStatus.Processing];+const POLL_INTERVAL_MS = 5_000;++export const useGetAuditReports = (+ params: TGetAuditReportsDTO,+ options?: Omit<+ UseQueryOptions<+ TGetAuditReportsResponse,+ unknown,+ TGetAuditReportsResponse,+ ReturnType<typeof auditReportKeys.list>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: auditReportKeys.list(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TGetAuditReportsResponse>("/api/v1/audit-reports", {+ params+ });+ return data;+ },+ refetchInterval: (query) => {+ const hasInFlight = query.state.data?.reports.some((report) =>+ IN_FLIGHT_STATUSES.includes(report.status)+ );+ return hasInFlight ? POLL_INTERVAL_MS : false;+ },+ ...options+ });+};diff --git a/frontend/src/hooks/api/auditReports/types.ts b/frontend/src/hooks/api/auditReports/types.tsnew file mode 100644index 0000000000..18a277c5df--- /dev/null+++ b/frontend/src/hooks/api/auditReports/types.ts@@ -0,0 +1,59 @@+export enum AuditReportType {+ StaleSecrets = "STALE_SECRETS",+ DuplicateSecrets = "DUPLICATE_SECRETS",+ SecretValidationCompliance = "SECRET_VALIDATION_COMPLIANCE",+ UpcomingRotations = "UPCOMING_ROTATIONS",+ FailedRotations = "FAILED_ROTATIONS",+ UpcomingReminders = "UPCOMING_REMINDERS",+ OverdueReminders = "OVERDUE_REMINDERS",+ SecretAccessLog = "SECRET_ACCESS_LOG"+}++export enum AuditReportStatus {+ Pending = "pending",+ Processing = "processing",+ Completed = "completed",+ Partial = "partial",+ Failed = "failed"+}++export type TAuditReportConfig = {+ type: AuditReportType;+ inputs: Record<string, unknown>;+};++export type TAuditReportResultEntry = {+ type: AuditReportType;+ rowCount: number;+ truncated: boolean;+};++export type TAuditReport = {+ id: string;+ projectId: string;+ requestedByUserId: string | null;+ status: AuditReportStatus;+ reportConfigs: TAuditReportConfig[];+ emailRecipients: string[];+ resultSummary: TAuditReportResultEntry[] | null;+ errorMessage: string | null;+ createdAt: string;+ updatedAt: string;+};++export type TGetAuditReportsDTO = {+ projectId: string;+ offset?: number;+ limit?: number;+};++export type TRequestAuditReportDTO = {+ projectId: string;+ reports: { type: AuditReportType; inputs?: Record<string, unknown> }[];+ emailRecipients?: string[];+};++export type TDeleteAuditReportDTO = {+ projectId: string;+ auditReportId: string;+};diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsxindex 008389655b..bd2d269ed4 100644--- a/frontend/src/hooks/api/index.tsx+++ b/frontend/src/hooks/api/index.tsx@@ -10,6 +10,7 @@ export * from "./approvalRequests";export * from "./assumePrivileges";export * from "./auditLogs";export * from "./auditLogStreams";+export * from "./auditReports";export * from "./auth";export * from "./billingV2";export * from "./bots";diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex 4d73a7d354..2c75be35e6 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -38,6 +38,7 @@ export type SubscriptionPlan = {samlSSO: boolean;sshHostGroups: boolean;secretAccessInsights: boolean;+ auditReports: boolean;hsm: boolean;oidcSSO: boolean;scim: boolean;diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex 745728163a..eb251448b1 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -16,6 +16,7 @@ import {ProjectPermissionApprovalRequestActions,ProjectPermissionApprovalRequestGrantActions,ProjectPermissionAuditLogsActions,+ ProjectPermissionAuditReportActions,ProjectPermissionCodeSigningActions,ProjectPermissionCommitsActions,ProjectPermissionDynamicSecretActions,@@ -67,6 +68,12 @@ const InsightsPolicyActionSchema = z.object({[ProjectPermissionInsightsActions.Read]: z.boolean().optional()});+const AuditReportPolicyActionSchema = z.object({+ [ProjectPermissionAuditReportActions.Create]: z.boolean().optional(),+ [ProjectPermissionAuditReportActions.Read]: z.boolean().optional(),+ [ProjectPermissionAuditReportActions.Delete]: z.boolean().optional()+});+const HoneyTokenPolicyActionSchema = z.object({[ProjectPermissionHoneyTokenActions.Read]: z.boolean().optional(),[ProjectPermissionHoneyTokenActions.ReadCredentials]: z.boolean().optional(),@@ -734,6 +741,7 @@ export const projectRoleFormSchema = z.object({[ProjectPermissionSub.Environments]: GeneralPolicyActionSchema.array().default([]),[ProjectPermissionSub.AuditLogs]: AuditLogsPolicyActionSchema.array().default([]),[ProjectPermissionSub.Insights]: InsightsPolicyActionSchema.array().default([]),+ [ProjectPermissionSub.AuditReports]: AuditReportPolicyActionSchema.array().default([]),[ProjectPermissionSub.IpAllowList]: GeneralPolicyActionSchema.array().default([]),[ProjectPermissionSub.CertificateAuthorities]: CertificateAuthorityPolicyActionSchema.extend({inverted: z.boolean().optional(),@@ -1112,7 +1120,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {ProjectPermissionSub.McpEndpoints,ProjectPermissionSub.McpServers,ProjectPermissionSub.McpActivityLogs,- ProjectPermissionSub.Insights+ ProjectPermissionSub.Insights,+ ProjectPermissionSub.AuditReports].includes(subject)) {// from above statement we are sure it won't be undefined@@ -2629,6 +2638,27 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {}]},+ [ProjectPermissionSub.AuditReports]: {+ title: "Audit Reports",+ description: "Generate and manage exportable compliance reports",+ actions: [+ {+ label: "Generate",+ value: ProjectPermissionAuditReportActions.Create,+ description: "Generate new audit reports"+ },+ {+ label: "Read",+ value: ProjectPermissionAuditReportActions.Read,+ description: "List audit reports and their status"+ },+ {+ label: "Delete",+ value: ProjectPermissionAuditReportActions.Delete,+ description: "Delete audit reports"+ }+ ]+ },[ProjectPermissionSub.IpAllowList]: {title: "IP Allowlist",description: "Restrict project access by IP address",@@ -3638,6 +3668,7 @@ const SecretsManagerPermissionSubjects = (enabled = false) => ({[ProjectPermissionSub.HoneyTokens]: enabled,[ProjectPermissionSub.Commits]: enabled,[ProjectPermissionSub.Insights]: enabled,+ [ProjectPermissionSub.AuditReports]: enabled,[ProjectPermissionSub.SecretEventSubscriptions]: enabled,[ProjectPermissionSub.SecretApprovalRequest]: enabled});diff --git a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsxindex 703c96ea89..b0e98103fc 100644--- a/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/InsightsPage.tsx@@ -25,6 +25,7 @@ import { useGetInsightsCounts } from "@app/hooks/api/secretInsights/queries";import { usePopUp } from "@app/hooks/usePopUp";import {+ AuditReportsCard,AuthMethodChart,CalendarCard,DuplicatedSecretsCard,@@ -126,6 +127,9 @@ export const InsightsPage = withProjectPermission(</PageHeader>{headerStats.length > 0 && renderStatStrip("mb-6 flex justify-start dashboard:hidden")}<InsightsSummaryCards />+ <div className="mt-6">+ <AuditReportsCard />+ </div><div className="mt-6 grid items-start gap-6 xl:grid-cols-[1.3fr_1fr]"><div className="flex flex-col gap-6"><DuplicatedSecretsCard />diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/AuditReportsCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/AuditReportsCard.tsxnew file mode 100644index 0000000000..2ab016272d--- /dev/null+++ b/frontend/src/pages/secret-manager/InsightsPage/components/AuditReportsCard.tsx@@ -0,0 +1,335 @@+import { formatRelative } from "date-fns";+import { FileTextIcon, PlusIcon, Trash2Icon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ProjectPermissionCan } from "@app/components/permissions";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ Pagination,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@app/components/v3";+import {+ ProjectPermissionAuditReportActions,+ ProjectPermissionSub,+ useProject,+ useProjectPermission+} from "@app/context";+import { usePagination, useResetPageHelper } from "@app/hooks";+import {+ AuditReportStatus,+ TAuditReport,+ useDeleteAuditReport,+ useGetAuditReports+} from "@app/hooks/api/auditReports";+import { usePopUp } from "@app/hooks/usePopUp";++import { AUDIT_REPORT_TYPE_LABELS, getAuditReportStatusBadge } from "./auditReportMeta";+import { RequestAuditReportModal } from "./RequestAuditReportModal";++const getStatusTooltip = (report: TAuditReport): string | null => {+ if (report.status === AuditReportStatus.Failed) return report.errorMessage;+ if (report.status === AuditReportStatus.Partial) {+ return "Some reports reached the row limit and were truncated.";+ }+ return null;+};++const ReportStatusBadge = ({ report }: { report: TAuditReport }) => {+ const { label, variant } = getAuditReportStatusBadge(report.status);+ const tooltip = getStatusTooltip(report);++ if (!tooltip) return <Badge variant={variant}>{label}</Badge>;++ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant={variant}>{label}</Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">{tooltip}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+};++export const AuditReportsCard = () => {+ const { projectId } = useProject();+ const { permission } = useProjectPermission();+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([+ "requestReport",+ "deleteReport"+ ] as const);++ const canReadReports = permission.can(+ ProjectPermissionAuditReportActions.Read,+ ProjectPermissionSub.AuditReports+ );++ const { offset, limit, page, perPage, setPage, setPerPage } = usePagination("createdAt", {+ initPerPage: 10+ });++ const { data, isPending } = useGetAuditReports(+ { projectId, offset, limit },+ { enabled: canReadReports && Boolean(projectId) }+ );+ const reports = data?.reports ?? [];+ const totalCount = data?.totalCount ?? 0;++ useResetPageHelper({ totalCount, offset, setPage });++ const deleteAuditReport = useDeleteAuditReport();++ const handleDeleteReport = async () => {+ const report = popUp.deleteReport.data as TAuditReport;+ try {+ await deleteAuditReport.mutateAsync({ projectId, auditReportId: report.id });+ createNotification({ type: "success", text: "Successfully deleted audit report" });+ } catch (error) {+ const message = error instanceof Error ? error.message : "Failed to delete audit report";+ createNotification({ type: "error", text: message });+ }+ };++ // Audit reports has its own permission subject; hide the card entirely without read access.+ if (!canReadReports) return null;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Audit Reports</CardTitle>+ <CardDescription>+ <span>+ Generate compliance reports and have them emailed to your team as CSV attachments+ </span>+ </CardDescription>+ <CardAction>+ <ProjectPermissionCan+ I={ProjectPermissionAuditReportActions.Create}+ a={ProjectPermissionSub.AuditReports}+ >+ {(isAllowed) => (+ <Button+ variant="project"+ size="xs"+ isDisabled={!isAllowed}+ onClick={() => handlePopUpOpen("requestReport")}+ >+ <PlusIcon className="size-3.5" />+ Generate Report+ </Button>+ )}+ </ProjectPermissionCan>+ </CardAction>+ </CardHeader>+ <CardContent>+ {isPending && <Skeleton className="h-[160px] w-full" />}+ {!isPending && totalCount === 0 && (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No audit reports yet</EmptyTitle>+ <EmptyDescription>+ Generate a report to have it emailed to your team as a CSV attachment.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ {!isPending && totalCount > 0 && (+ <Accordion type="single" collapsible defaultValue="history-closed">+ <AccordionItem value="history">+ <AccordionTrigger>+ <div className="flex flex-1 items-center gap-2">+ <FileTextIcon className="size-3.5 text-muted" />+ <span className="text-sm text-foreground">Report History</span>+ <Badge variant="neutral" className="font-normal">+ {totalCount}+ </Badge>+ </div>+ </AccordionTrigger>+ <AccordionContent className="group-data-[variant=default]/accordion:p-0">+ <Table+ containerClassName="rounded-t-none overflow-x-hidden"+ className="table-fixed"+ >+ <TableHeader className="bg-mineshaft-800">+ <TableRow>+ <TableHead className="h-10 w-[30%]">REPORTS</TableHead>+ <TableHead className="h-10 w-[28%]">RECIPIENTS</TableHead>+ <TableHead className="h-10 w-[14%]">STATUS</TableHead>+ <TableHead className="h-10">REQUESTED</TableHead>+ <TableHead className="h-10 w-12" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {reports.map((report) => (+ <TableRow key={report.id} className="group/row bg-mineshaft-900">+ <TableCell isTruncatable className="max-w-0">+ {report.reportConfigs.length <= 1 ? (+ <span className="block truncate">+ {report.reportConfigs[0]+ ? AUDIT_REPORT_TYPE_LABELS[report.reportConfigs[0].type]+ : ""}+ </span>+ ) : (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="block truncate">+ {report.reportConfigs+ .map((config) => AUDIT_REPORT_TYPE_LABELS[config.type])+ .join(", ")}+ </span>+ </TooltipTrigger>+ <TooltipContent className="flex max-w-sm flex-col gap-0.5">+ {report.reportConfigs.map((config) => (+ <span key={config.type}>+ {AUDIT_REPORT_TYPE_LABELS[config.type]}+ </span>+ ))}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </TableCell>+ <TableCell isTruncatable className="max-w-0">+ {report.emailRecipients.length <= 1 ? (+ <span className="block truncate text-muted">+ {report.emailRecipients[0] ?? ""}+ </span>+ ) : (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="flex items-center gap-1.5 text-muted">+ <span className="truncate">{report.emailRecipients[0]}</span>+ <Badge variant="neutral" className="shrink-0 font-normal">+ +{report.emailRecipients.length - 1} more+ </Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent className="flex max-w-sm flex-col gap-0.5">+ {report.emailRecipients.map((email) => (+ <span key={email}>{email}</span>+ ))}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </TableCell>+ <TableCell>+ <ReportStatusBadge report={report} />+ </TableCell>+ <TableCell>+ <span className="text-muted">+ {formatRelative(new Date(report.createdAt), new Date())}+ </span>+ </TableCell>+ <TableCell className="pr-5">+ <ProjectPermissionCan+ I={ProjectPermissionAuditReportActions.Delete}+ a={ProjectPermissionSub.AuditReports}+ >+ {(isAllowed) => (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ variant="ghost"+ size="sm"+ aria-label="Delete report"+ isDisabled={!isAllowed}+ className="opacity-0 transition-opacity group-hover/row:opacity-100"+ onClick={() => handlePopUpOpen("deleteReport", report)}+ >+ <Trash2Icon className="size-3.5" />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>Delete report</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </ProjectPermissionCan>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ <div className="p-2">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={setPerPage}+ />+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ )}+ </CardContent>+ <RequestAuditReportModal+ isOpen={popUp.requestReport.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("requestReport", isOpen)}+ projectId={projectId}+ />+ <AlertDialog+ open={popUp.deleteReport.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("deleteReport", isOpen)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <Trash2Icon />+ </AlertDialogMedia>+ <AlertDialogTitle>Delete this audit report?</AlertDialogTitle>+ <AlertDialogDescription>+ This removes the report record from the history. This action cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction variant="danger" onClick={handleDeleteReport}>+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </Card>+ );+};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsxnew file mode 100644index 0000000000..eb9607103c--- /dev/null+++ b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx@@ -0,0 +1,196 @@+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Checkbox,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ TextArea+} from "@app/components/v3";+import { AuditReportType, useRequestAuditReport } from "@app/hooks/api/auditReports";++import {+ AUDIT_REPORT_TYPE_DESCRIPTIONS,+ AUDIT_REPORT_TYPE_LABELS,+ AUDIT_REPORT_TYPES_ORDERED+} from "./auditReportMeta";++const parseEmails = (raw?: string): string[] =>+ (raw ?? "")+ .split(/[\s,]+/)+ .map((email) => email.trim())+ .filter(Boolean);++const formSchema = z.object({+ reportTypes: z.nativeEnum(AuditReportType).array().min(1, "Select at least one report type"),+ emailRecipients: z+ .string()+ .optional()+ .refine(+ (value) => parseEmails(value).every((email) => z.string().email().safeParse(email).success),+ {+ message: "Enter valid, comma-separated email addresses"+ }+ )+});++type TFormSchema = z.infer<typeof formSchema>;++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ projectId: string;+};++export const RequestAuditReportModal = ({ isOpen, onOpenChange, projectId }: Props) => {+ const requestAuditReport = useRequestAuditReport();++ const {+ control,+ handleSubmit,+ reset,+ formState: { isSubmitting }+ } = useForm<TFormSchema>({+ resolver: zodResolver(formSchema),+ defaultValues: { reportTypes: [...AUDIT_REPORT_TYPES_ORDERED], emailRecipients: "" }+ });++ const handleClose = (open: boolean) => {+ onOpenChange(open);+ if (!open) reset();+ };++ const onSubmit = async (data: TFormSchema) => {+ const recipients = parseEmails(data.emailRecipients);+ try {+ await requestAuditReport.mutateAsync({+ projectId,+ reports: data.reportTypes.map((type) => ({ type })),+ emailRecipients: recipients.length ? recipients : undefined+ });+ createNotification({+ type: "success",+ text: "Report requested. Recipients will receive an email once it's ready."+ });+ reset();+ onOpenChange(false);+ } catch (error) {+ const message =+ error instanceof Error ? error.message : "Failed to request report. Please try again.";+ createNotification({ type: "error", text: message });+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={handleClose}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Generate Audit Report</DialogTitle>+ <DialogDescription>+ Select the reports to generate. They will be emailed as CSV attachments once ready.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">+ <Controller+ control={control}+ name="reportTypes"+ render={({ field, fieldState: { error } }) => {+ const allSelected = field.value.length === AUDIT_REPORT_TYPES_ORDERED.length;+ return (+ <Field>+ <div className="flex items-center justify-between">+ <FieldLabel>Reports</FieldLabel>+ <button+ type="button"+ className="cursor-pointer text-xs font-medium text-muted transition-colors hover:text-mineshaft-300"+ onClick={() =>+ field.onChange(allSelected ? [] : [...AUDIT_REPORT_TYPES_ORDERED])+ }+ >+ {allSelected ? "Deselect All" : "Select All"}+ </button>+ </div>+ <FieldContent>+ <div className="flex flex-col gap-3">+ {AUDIT_REPORT_TYPES_ORDERED.map((type) => {+ const checkboxId = `audit-report-type-${type}`;+ return (+ <div key={type} className="flex items-start gap-3">+ <Checkbox+ id={checkboxId}+ variant="project"+ className="mt-0.5"+ isChecked={field.value.includes(type)}+ onCheckedChange={(isChecked) => {+ if (isChecked) field.onChange([...field.value, type]);+ else field.onChange(field.value.filter((value) => value !== type));+ }}+ />+ <label htmlFor={checkboxId} className="cursor-pointer leading-tight">+ <span className="block text-sm text-foreground">+ {AUDIT_REPORT_TYPE_LABELS[type]}+ </span>+ <span className="block text-xs text-muted">+ {AUDIT_REPORT_TYPE_DESCRIPTIONS[type]}+ </span>+ </label>+ </div>+ );+ })}+ </div>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ );+ }}+ />+ <Controller+ control={control}+ name="emailRecipients"+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Email recipients</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ isError={Boolean(error)}+ placeholder="[email protected], [email protected]"+ />+ <FieldDescription>+ Comma-separated emails. Defaults to your own email when left blank.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <DialogFooter className="gap-2 sm:gap-2">+ <Button type="button" variant="ghost" onClick={() => handleClose(false)}>+ Cancel+ </Button>+ <Button+ type="submit"+ variant="project"+ isPending={isSubmitting}+ isDisabled={isSubmitting}+ >+ Generate Report+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/auditReportMeta.ts b/frontend/src/pages/secret-manager/InsightsPage/components/auditReportMeta.tsnew file mode 100644index 0000000000..f2761645c2--- /dev/null+++ b/frontend/src/pages/secret-manager/InsightsPage/components/auditReportMeta.ts@@ -0,0 +1,56 @@+import { AuditReportStatus, AuditReportType } from "@app/hooks/api/auditReports";++export const AUDIT_REPORT_TYPE_LABELS: Record<AuditReportType, string> = {+ [AuditReportType.StaleSecrets]: "Stale Secrets",+ [AuditReportType.DuplicateSecrets]: "Duplicate Secrets",+ [AuditReportType.SecretValidationCompliance]: "Secret Validation Compliance Violations",+ [AuditReportType.UpcomingRotations]: "Upcoming Rotations",+ [AuditReportType.FailedRotations]: "Failed Rotations",+ [AuditReportType.UpcomingReminders]: "Upcoming Reminders",+ [AuditReportType.OverdueReminders]: "Overdue Reminders",+ [AuditReportType.SecretAccessLog]: "Secret Access Log"+};++export const AUDIT_REPORT_TYPE_DESCRIPTIONS: Record<AuditReportType, string> = {+ [AuditReportType.StaleSecrets]: "Secrets not updated within the last 90 days.",+ [AuditReportType.DuplicateSecrets]:+ "Secrets sharing the same value across environments and paths.",+ [AuditReportType.SecretValidationCompliance]:+ "Stored secrets that violate a secret validation rule covering them.",+ [AuditReportType.UpcomingRotations]: "Rotations scheduled within the next 7 days.",+ [AuditReportType.FailedRotations]: "Rotations currently in a failed state.",+ [AuditReportType.UpcomingReminders]: "Secret reminders due within the next 7 days.",+ [AuditReportType.OverdueReminders]: "Secret reminders that are past due.",+ [AuditReportType.SecretAccessLog]: "Who accessed secrets over the last 30 days."+};++export const AUDIT_REPORT_TYPES_ORDERED: AuditReportType[] = [+ AuditReportType.StaleSecrets,+ AuditReportType.DuplicateSecrets,+ AuditReportType.SecretValidationCompliance,+ AuditReportType.UpcomingRotations,+ AuditReportType.FailedRotations,+ AuditReportType.UpcomingReminders,+ AuditReportType.OverdueReminders,+ AuditReportType.SecretAccessLog+];++type AuditReportStatusBadgeVariant = "neutral" | "info" | "success" | "warning" | "danger";++export const getAuditReportStatusBadge = (+ status: AuditReportStatus+): { label: string; variant: AuditReportStatusBadgeVariant } => {+ switch (status) {+ case AuditReportStatus.Completed:+ return { label: "Completed", variant: "success" };+ case AuditReportStatus.Partial:+ return { label: "Partial", variant: "warning" };+ case AuditReportStatus.Failed:+ return { label: "Failed", variant: "danger" };+ case AuditReportStatus.Processing:+ return { label: "Generating", variant: "info" };+ case AuditReportStatus.Pending:+ default:+ return { label: "Pending", variant: "neutral" };+ }+};diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/index.ts b/frontend/src/pages/secret-manager/InsightsPage/components/index.tsindex d389b391fc..629fbd5337 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/index.ts+++ b/frontend/src/pages/secret-manager/InsightsPage/components/index.ts@@ -1,3 +1,4 @@+export { AuditReportsCard } from "./AuditReportsCard";export { AuthMethodChart } from "./AuthMethodChart";export { CalendarCard } from "./CalendarCard";export { CalendarGrid } from "./CalendarGrid";