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
requested changes
varonix047602af79bcf
diff --git a/backend/src/ee/routes/v1/audit-report-router.ts b/backend/src/ee/routes/v1/audit-report-router.tsindex f133dab39c..1544d46c30 100644--- a/backend/src/ee/routes/v1/audit-report-router.ts+++ b/backend/src/ee/routes/v1/audit-report-router.ts@@ -1,6 +1,12 @@import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import {+ DaysAheadInputsSchema,+ NoInputsSchema,+ SecretAccessLogInputsSchema,+ StaleSecretsInputsSchema+} from "@app/ee/services/audit-report/audit-report-generators";import {AuditReportResultEntrySchema,AuditReportStatus,@@ -10,6 +16,18 @@ 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";+// Each report type declares exactly which inputs it accepts. The `inputs` schemas are the same consts+// the generators use, so request validation and generation never drift.+const AuditReportRequestConfigSchema = z.discriminatedUnion("type", [+ z.object({ type: z.literal(AuditReportType.StaleSecrets), inputs: StaleSecretsInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.DuplicateSecrets), inputs: NoInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.SecretValidationCompliance), inputs: NoInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.UpcomingRotations), inputs: DaysAheadInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.FailedRotations), inputs: NoInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.UpcomingReminders), inputs: DaysAheadInputsSchema.optional() }),+ z.object({ type: z.literal(AuditReportType.SecretAccessLog), inputs: SecretAccessLogInputsSchema.optional() })+]);+const AuditReportConfigSchema = z.object({type: z.nativeEnum(AuditReportType),inputs: z.record(z.unknown())@@ -37,14 +55,7 @@ export const registerAuditReportRouter = async (server: FastifyZodProvider) => {hide: true,body: z.object({projectId: z.string().trim(),- reports: z- .array(- z.object({- type: z.nativeEnum(AuditReportType),- inputs: z.record(z.unknown()).optional()- })- )- .min(1),+ reports: AuditReportRequestConfigSchema.array().min(1),emailRecipients: z.array(z.string().email()).optional()}),response: {@@ -86,7 +97,7 @@ export const registerAuditReportRouter = async (server: FastifyZodProvider) => {200: z.object({ reports: z.array(AuditReportSchema), totalCount: z.number() })}},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const { projectId, offset, limit } = req.query;const { reports, totalCount } = await server.services.auditReport.listReports(@@ -109,15 +120,14 @@ export const registerAuditReportRouter = async (server: FastifyZodProvider) => {schema: {hide: true,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]),+ onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const report = await server.services.auditReport.getReportById(- { projectId: req.query.projectId, auditReportId: req.params.auditReportId },+ { auditReportId: req.params.auditReportId },req.permission);await server.services.auditLog.createAuditLog({diff --git a/backend/src/ee/services/audit-report/audit-report-fns.ts b/backend/src/ee/services/audit-report/audit-report-fns.tsindex abfff9cac5..a625961fa5 100644--- a/backend/src/ee/services/audit-report/audit-report-fns.ts+++ b/backend/src/ee/services/audit-report/audit-report-fns.ts@@ -13,7 +13,6 @@ import {AuditReportResultEntrySchema,AuditReportStatus,AuditReportType,- MAX_AUDIT_REPORT_ROWS,TGeneratedReport,TSecretToValidate} from "./audit-report-types";@@ -37,47 +36,18 @@ const escapeCsvCell = (value: string | number | null): string => {const toCsvRow = (cells: (string | number | null)[]): string => cells.map(escapeCsvCell).join(",");-export type TAuditReportSection = {- title: string;- report: TGeneratedReport;-};--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`]));- }- });-+// Serialize a single report into its own standalone CSV — a header row followed by its data rows.+export const serializeReport = ({ columns, rows }: TGeneratedReport): Buffer => {+ const lines = [toCsvRow(columns), ...rows.map((row) => toCsvRow(columns.map((column) => row[column] ?? null)))];return Buffer.from(lines.join(CSV_LINE_BREAK), "utf8");};+export const csvFileNameFromLabel = (label: string): string =>+ `${label+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")}.csv`;+// Resolve folder ids to their human-readable secret paths in a single batched query.export const buildFolderPathMap = async (folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">,diff --git a/backend/src/ee/services/audit-report/audit-report-generators.ts b/backend/src/ee/services/audit-report/audit-report-generators.tsindex f64757e177..ffff128c81 100644--- a/backend/src/ee/services/audit-report/audit-report-generators.ts+++ b/backend/src/ee/services/audit-report/audit-report-generators.ts@@ -143,10 +143,10 @@ const parseRecord = <T>(schema: z.ZodType<T>, raw: unknown, fallback: T): T => {// ─── 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+export const NoInputsSchema = z.object({}).default({});+export const StaleSecretsInputsSchema = z.object({ staleDays: z.number().int().min(1).max(3650).default(90) });+export const DaysAheadInputsSchema = z.object({ daysAhead: z.number().int().min(1).max(365).default(7) });+export const SecretAccessLogInputsSchema = z.object({fromDate: z.coerce.date().optional(),toDate: z.coerce.date().optional()diff --git a/backend/src/ee/services/audit-report/audit-report-queue.ts b/backend/src/ee/services/audit-report/audit-report-queue.tsindex 371ae67707..8c23f21e39 100644--- a/backend/src/ee/services/audit-report/audit-report-queue.ts+++ b/backend/src/ee/services/audit-report/audit-report-queue.ts@@ -4,7 +4,7 @@ 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 { csvFileNameFromLabel, presentAuditReport, serializeReport } from "./audit-report-fns";import {AUDIT_REPORT_DEFINITIONS,TAuditReportGeneratorDALs,@@ -78,21 +78,21 @@ export const auditReportQueueServiceFactory = ({dal: generatorDAL};- const sections: TAuditReportSection[] = [];+ const attachments: { filename: string; content: Buffer; contentType: string }[] = [];const resultSummary: TAuditReportResultEntry[] = [];for (const config of reportConfigs) {const definition = AUDIT_REPORT_DEFINITIONS[config.type];// eslint-disable-next-line no-await-in-loopconst generated = await definition.run(context, config.inputs);- sections.push({ title: definition.label, report: generated });+ attachments.push({+ filename: csvFileNameFromLabel(definition.label),+ content: serializeReport(generated),+ contentType: "text/csv"+ });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}`,@@ -105,13 +105,7 @@ export const auditReportQueueServiceFactory = ({truncated: entry.truncated}))},- attachments: [- {- filename: `infisical-audit-report-${generatedAt.toISOString().slice(0, 10)}.csv`,- content: csv,- contentType: "text/csv"- }- ]+ attachments});const truncatedAny = resultSummary.some((entry) => entry.truncated);diff --git a/backend/src/ee/services/audit-report/audit-report-service.ts b/backend/src/ee/services/audit-report/audit-report-service.tsindex 5b14866c5a..20b43f21a4 100644--- a/backend/src/ee/services/audit-report/audit-report-service.ts+++ b/backend/src/ee/services/audit-report/audit-report-service.ts@@ -11,21 +11,17 @@ import { PgSqlLock } from "@app/keystore/keystore";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";@@ -53,58 +49,17 @@ export const auditReportServiceFactory = ({userDAL,queueService}: TAuditReportServiceFactoryDep) => {- 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.+ // Report types and their inputs are validated at the request boundary by the router's discriminated+ // union, so here we only enforce that each report type appears at most once per batch (the array schema+ // can't express that) and normalize the stored shape.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 };+ return { type, inputs: inputs ?? {} };});};@@ -120,16 +75,35 @@ export const auditReportServiceFactory = ({}// 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];+ 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 generateReport = async (dto: TRequestAuditReportDTO, actor: TAuditReportServiceActor) => {- await $checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Create);+ 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: dto.projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAuditReportActions.Create,+ ProjectPermissionSub.AuditReports+ );const project = await projectDAL.findById(dto.projectId);if (!project) {@@ -159,7 +133,7 @@ export const auditReportServiceFactory = ({return auditReportDAL.create({projectId: dto.projectId,- requestedByUserId: actor.type === ActorType.USER ? actor.id : null,+ requestedByUserId: actor.id,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.@@ -189,7 +163,26 @@ export const auditReportServiceFactory = ({};const listReports = async (dto: TListAuditReportsDTO, actor: TAuditReportServiceActor) => {- await $checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Read);+ 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: dto.projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAuditReportActions.Read,+ ProjectPermissionSub.AuditReports+ );const reports = await auditReportDAL.findByProject(dto.projectId, {offset: dto.offset,@@ -199,26 +192,62 @@ export const auditReportServiceFactory = ({return { reports: reports.map(presentAuditReport), totalCount };};- const getReportById = async (dto: TGetAuditReportDTO, actor: TAuditReportServiceActor) => {- await $checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Read);+ const getReportById = async (auditReportId: string, actor: TAuditReportServiceActor) => {+ 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 report = await auditReportDAL.findById(auditReportId);++ if (!report) {+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ projectId: report.projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAuditReportActions.Read,+ ProjectPermissionSub.AuditReports+ );- 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` });+ if (!permission.can(ProjectPermissionAuditReportActions.Read, ProjectPermissionSub.AuditReports)) {+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });}return presentAuditReport(report);};- const deleteReport = async (dto: TDeleteAuditReportDTO, actor: TAuditReportServiceActor) => {- await $checkPermission(dto.projectId, actor, ProjectPermissionAuditReportActions.Delete);+ const deleteReport = async (auditReportId: string, actor: TAuditReportServiceActor) => {+ const report = await auditReportDAL.findById(auditReportId);++ if (!report) {+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor: actor.type,+ actorId: actor.id,+ projectId: report.projectId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ actionProjectType: ActionProjectType.SecretManager+ });- 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` });+ if (!permission.can(ProjectPermissionAuditReportActions.Delete, ProjectPermissionSub.AuditReports)) {+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });}- await auditReportDAL.deleteById(dto.auditReportId);+ await auditReportDAL.deleteById(report.id);return presentAuditReport(report);};diff --git a/backend/src/ee/services/audit-report/audit-report-types.ts b/backend/src/ee/services/audit-report/audit-report-types.tsindex 5a107fccb2..dacdd08070 100644--- a/backend/src/ee/services/audit-report/audit-report-types.ts+++ b/backend/src/ee/services/audit-report/audit-report-types.ts@@ -59,16 +59,6 @@ export type TListAuditReportsDTO = {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.diff --git a/backend/src/services/smtp/emails/AuditReportTemplate.tsx b/backend/src/services/smtp/emails/AuditReportTemplate.tsxindex b33bcf0056..87972e1558 100644--- a/backend/src/services/smtp/emails/AuditReportTemplate.tsx+++ b/backend/src/services/smtp/emails/AuditReportTemplate.tsx@@ -16,8 +16,9 @@ export const AuditReportTemplate = ({ siteUrl, projectName, reports }: AuditRepo</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"}:+ The audit report you requested for the project <strong>{projectName}</strong> has been generated. The+ following {reports.length === 1 ? "report is" : "reports are"} attached to this email+ {reports.length === 1 ? " as a CSV file" : ", each as its own CSV file"}:</Text>{reports.map((report) => (<Text key={report.label} className="text-[14px] text-slate-700 my-[4px]">diff --git a/docs/documentation/platform/insights.mdx b/docs/documentation/platform/insights.mdxindex 3d2a2b760b..64427fdc5c 100644--- a/docs/documentation/platform/insights.mdx+++ b/docs/documentation/platform/insights.mdx@@ -69,26 +69,9 @@ Stale secrets aren't necessarily a problem — long-lived configuration values a-----------------## Audit Reports-Audit Reports let you generate point-in-time compliance exports for a Secrets Management project — stale secrets, duplicate values, validation-rule violations, rotation status, upcoming reminders, and secret access history — and deliver them to one or more recipients as a single CSV file attached to an email.+Audit Reports let you generate point-in-time compliance exports for a Secrets Management project — stale secrets, duplicate values, validation-rule violations, rotation status, upcoming reminders, and secret access history — and deliver them to one or more recipients as CSV attachments (one file per report type) in an email.Where the rest of the Insights dashboard is a live, read-only view, an Audit Report is a snapshot you can hand to an auditor, attach to a ticket, or archive for SOC 2 / ISO 27001 evidence. You'll find it as the **Audit Reports** card on the Insights page.@@ -106,7 +89,7 @@ Where the rest of the Insights dashboard is a live, read-only view, an Audit Rep-The request is queued and generated in the background. When it finishes, every recipient receives an email with a single CSV file attached. You can keep working — the report's status updates live in the history table.+The request is queued and generated in the background. When it finishes, every recipient receives an email with one CSV file attached per requested report. You can keep working — the report's status updates live in the history table.<Note>Report generation is asynchronous. A project can have at most one report generating at once.@@ -147,21 +130,6 @@ A single request can include any combination of the following. Each becomes its| **Upcoming Reminders** | Secret reminders due within the next 7 days. || **Secret Access Log** | Who accessed secrets over the last 30 days (actor, event type, secret, environment, path, IP, timestamp). |---------------## Rotation & Reminder CalendarThe calendar panel shows every upcoming rotation and reminder laid out on a month grid, so you can see the cadence of upcoming work at a glance.diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsxindex 9bc3ef4f43..3a6c5380b5 100644--- a/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx+++ b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx@@ -64,7 +64,7 @@ export const RequestAuditReportModal = ({ isOpen, onOpenChange, projectId }: ProformState: { isSubmitting }} = useForm<TFormSchema>({resolver: zodResolver(formSchema),- defaultValues: { reportTypes: [...AUDIT_REPORT_TYPES_ORDERED], emailRecipients: "" }+ defaultValues: { reportTypes: [], emailRecipients: "" }});const handleClose = (open: boolean) => {