Skip to content

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

feat: add endpoint to create a new report for org insights

adilsonbdd26b60a3a1
diff --git a/backend/src/db/migrations/20260807120000_add-org-scope-to-audit-reports.ts b/backend/src/db/migrations/20260807120000_add-org-scope-to-audit-reports.ts
new file mode 100644
index 0000000000..aaa1f76e80
--- /dev/null
+++ b/backend/src/db/migrations/20260807120000_add-org-scope-to-audit-reports.ts
@@ -0,0 +1,40 @@
+import { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+
+// Audit reports gain an org scope: a report row is either project-scoped (projectId set) or
+// org-scoped (orgId set), never both. Raw SQL is used for the NOT NULL toggle so the existing
+// projectId FK and index are left untouched.
+export async function up(knex: Knex): Promise<void> {
+ const hasOrgId = await knex.schema.hasColumn(TableName.AuditReport, "orgId");
+ if (!hasOrgId) {
+ await knex.raw(`ALTER TABLE "${TableName.AuditReport}" ALTER COLUMN "projectId" DROP NOT NULL`);
+
+ await knex.schema.alterTable(TableName.AuditReport, (t) => {
+ t.uuid("orgId").nullable();
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ t.index(["orgId"]);
+ });
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.AuditReport}" ADD CONSTRAINT "audit_reports_one_scope_check"
+ CHECK ((("projectId" IS NOT NULL)::int + ("orgId" IS NOT NULL)::int) = 1)`
+ );
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasOrgId = await knex.schema.hasColumn(TableName.AuditReport, "orgId");
+ if (hasOrgId) {
+ await knex.raw(`ALTER TABLE "${TableName.AuditReport}" DROP CONSTRAINT IF EXISTS "audit_reports_one_scope_check"`);
+
+ // Org-scoped rows cannot survive the NOT NULL restore on projectId.
+ await knex(TableName.AuditReport).whereNull("projectId").delete();
+
+ await knex.schema.alterTable(TableName.AuditReport, (t) => {
+ t.dropColumn("orgId");
+ });
+
+ await knex.raw(`ALTER TABLE "${TableName.AuditReport}" ALTER COLUMN "projectId" SET NOT NULL`);
+ }
+}
diff --git a/backend/src/db/schemas/audit-reports.ts b/backend/src/db/schemas/audit-reports.ts
index c791f12e29..d05eec805f 100644
--- a/backend/src/db/schemas/audit-reports.ts
+++ b/backend/src/db/schemas/audit-reports.ts
@@ -9,7 +9,7 @@ import { TImmutableDBKeys } from "./models";
export const AuditReportsSchema = z.object({
id: z.string().uuid(),
- projectId: z.string(),
+ projectId: z.string().nullable().optional(),
requestedByUserId: z.string().uuid().nullable().optional(),
status: z.string().default("pending"),
reportConfigs: z.unknown(),
@@ -17,7 +17,8 @@ export const AuditReportsSchema = z.object({
resultSummary: z.unknown().nullable().optional(),
errorMessage: z.string().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ orgId: z.string().uuid().nullable().optional()
});
export type TAuditReports = z.infer<typeof AuditReportsSchema>;
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index bdf8fab6f1..78be5c2b24 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -10,7 +10,9 @@ import {
import {
AuditReportResultEntrySchema,
AuditReportStatus,
- AuditReportType
+ AuditReportType,
+ OrgAuditReportResultEntrySchema,
+ OrgAuditReportType
} from "@app/ee/services/audit-report/audit-report-types";
import {
OrgAuthMethodDistributionSchema,
@@ -55,6 +57,34 @@ const AuditReportSchema = z.object({
updatedAt: z.date()
});
+// Org-scoped counterparts. None of the org report types take inputs today; the discriminated union
+// mirrors the project one so a type can grow inputs later without reshaping the request.
+const OrgAuditReportRequestConfigSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal(OrgAuditReportType.OrgUsageSummary), inputs: NoInputsSchema.optional() }),
+ z.object({ type: z.literal(OrgAuditReportType.OrgNeedsAttention), inputs: NoInputsSchema.optional() }),
+ z.object({ type: z.literal(OrgAuditReportType.OrgAuthMethods), inputs: NoInputsSchema.optional() }),
+ z.object({ type: z.literal(OrgAuditReportType.OrgStaticSecretUsage), inputs: NoInputsSchema.optional() }),
+ z.object({ type: z.literal(OrgAuditReportType.OrgSecretAccessVolume), inputs: NoInputsSchema.optional() })
+]);
+
+const OrgAuditReportSchema = z.object({
+ id: z.string().uuid(),
+ orgId: z.string().uuid(),
+ requestedByUserId: z.string().uuid().nullable(),
+ status: z.nativeEnum(AuditReportStatus),
+ reportConfigs: z.array(
+ z.object({
+ type: z.nativeEnum(OrgAuditReportType),
+ inputs: z.record(z.unknown())
+ })
+ ),
+ emailRecipients: z.string().array(),
+ resultSummary: z.array(OrgAuditReportResultEntrySchema).nullable(),
+ errorMessage: z.string().nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
export const registerInsightsRouter = async (server: FastifyZodProvider) => {
// Org scoped insights don't have a :projectId, so they are gated on the org-level Secrets Management Insights subject.
@@ -315,6 +345,98 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/secrets/reports",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: true,
+ body: z.object({
+ reports: OrgAuditReportRequestConfigSchema.array().min(1).max(5),
+ emailRecipients: z.array(z.string().trim().email().max(255)).max(20).optional()
+ }),
+ response: {
+ 200: OrgAuditReportSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const report = await server.services.auditReport.generateOrgReport(req.body, req.permission);
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.CREATE_ORG_AUDIT_REPORT,
+ metadata: {
+ auditReportId: report.id,
+ reportTypes: report.reportConfigs.map((config) => config.type),
+ recipientCount: report.emailRecipients.length
+ }
+ }
+ });
+ return report;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/secrets/reports",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: true,
+ querystring: z.object({
+ offset: z.coerce.number().int().min(0).max(10000).default(0),
+ limit: z.coerce.number().int().min(1).max(100).default(10)
+ }),
+ response: {
+ 200: z.object({ reports: z.array(OrgAuditReportSchema), totalCount: z.number() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { offset, limit } = req.query;
+ const { reports, totalCount } = await server.services.auditReport.listOrgReports(
+ { offset, limit },
+ req.permission
+ );
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.GET_ORG_AUDIT_REPORTS,
+ metadata: { offset, limit }
+ }
+ });
+ return { reports, totalCount };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/secrets/reports/:reportId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: true,
+ params: z.object({ reportId: z.string().uuid() }),
+ response: {
+ 200: OrgAuditReportSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const report = await server.services.auditReport.deleteOrgReport(req.params.reportId, req.permission);
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.DELETE_ORG_AUDIT_REPORT,
+ metadata: { auditReportId: report.id }
+ }
+ });
+ return report;
+ }
+ });
+
server.route({
method: "GET",
url: "/:projectId/secrets/calendar",
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 56679e8a7c..e84874fabd 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -693,6 +693,10 @@ export enum EventType {
GET_AUDIT_REPORT = "get-audit-report",
DELETE_AUDIT_REPORT = "delete-audit-report",
+ CREATE_ORG_AUDIT_REPORT = "create-org-audit-report",
+ GET_ORG_AUDIT_REPORTS = "get-org-audit-reports",
+ DELETE_ORG_AUDIT_REPORT = "delete-org-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",
@@ -5613,6 +5617,31 @@ interface DeleteAuditReportEvent {
};
}
+// Org-scoped report events carry no org id in metadata: the audit log row itself is org-scoped.
+interface CreateOrgAuditReportEvent {
+ type: EventType.CREATE_ORG_AUDIT_REPORT;
+ metadata: {
+ auditReportId: string;
+ reportTypes: string[];
+ recipientCount: number;
+ };
+}
+
+interface GetOrgAuditReportsEvent {
+ type: EventType.GET_ORG_AUDIT_REPORTS;
+ metadata: {
+ offset: number;
+ limit: number;
+ };
+}
+
+interface DeleteOrgAuditReportEvent {
+ type: EventType.DELETE_ORG_AUDIT_REPORT;
+ metadata: {
+ auditReportId: string;
+ };
+}
+
interface ViewAuditLogsEvent {
type: EventType.VIEW_AUDIT_LOGS;
metadata?: Record<string, unknown>;
@@ -7540,6 +7569,9 @@ export type Event =
| GetAuditReportsEvent
| GetAuditReportEvent
| DeleteAuditReportEvent
+ | CreateOrgAuditReportEvent
+ | GetOrgAuditReportsEvent
+ | DeleteOrgAuditReportEvent
| ViewAuditLogsEvent
| ProjectRoleCreateEvent
| ProjectRoleUpdateEvent
diff --git a/backend/src/ee/services/audit-report/audit-report-dal.ts b/backend/src/ee/services/audit-report/audit-report-dal.ts
index 352987de96..f968d1cdde 100644
--- a/backend/src/ee/services/audit-report/audit-report-dal.ts
+++ b/backend/src/ee/services/audit-report/audit-report-dal.ts
@@ -56,10 +56,55 @@ export const auditReportDALFactory = (db: TDbClient) => {
}
};
+ const findByOrg = async (
+ orgId: string,
+ { offset = 0, limit = 50 }: { offset?: number; limit?: number },
+ tx?: Knex
+ ) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.AuditReport)
+ .where(`${TableName.AuditReport}.orgId`, orgId)
+ .orderBy(`${TableName.AuditReport}.createdAt`, "desc")
+ .offset(offset)
+ .limit(limit);
+ return docs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindAuditReportsByOrg" });
+ }
+ };
+
+ const countByOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = await (tx || db.replicaNode())(TableName.AuditReport)
+ .where(`${TableName.AuditReport}.orgId`, orgId)
+ .count("* as count")
+ .first<{ count: string | number } | undefined>();
+ return Number(result?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountAuditReportsByOrg" });
+ }
+ };
+
+ const countInFlightByOrg = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = await (tx || db.replicaNode())(TableName.AuditReport)
+ .where(`${TableName.AuditReport}.orgId`, orgId)
+ .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: "CountInFlightAuditReportsByOrg" });
+ }
+ };
+
return {
...auditReportOrm,
findByProject,
countByProject,
- countInFlightByProject
+ countInFlightByProject,
+ findByOrg,
+ countByOrg,
+ countInFlightByOrg
};
};
diff --git a/backend/src/ee/services/audit-report/audit-report-fns.ts b/backend/src/ee/services/audit-report/audit-report-fns.ts
index 094ce43b01..fde179bf5d 100644
--- a/backend/src/ee/services/audit-report/audit-report-fns.ts
+++ b/backend/src/ee/services/audit-report/audit-report-fns.ts
@@ -13,6 +13,8 @@ import {
AuditReportResultEntrySchema,
AuditReportStatus,
AuditReportType,
+ OrgAuditReportResultEntrySchema,
+ OrgAuditReportType,
TGeneratedReport,
TSecretToValidate
} from "./audit-report-types";
@@ -90,7 +92,9 @@ const StoredReportConfigsSchema = z.array(
export const presentAuditReport = (report: TAuditReports) => ({
id: report.id,
- projectId: report.projectId,
+ // Callers only ever pass project-scoped rows here; org-scoped rows go through
+ // presentOrgAuditReport. The cast preserves the non-null projectId response contract.
+ projectId: report.projectId as string,
requestedByUserId: report.requestedByUserId ?? null,
status: z.nativeEnum(AuditReportStatus).parse(report.status),
reportConfigs: StoredReportConfigsSchema.parse(report.reportConfigs),
@@ -104,6 +108,30 @@ export const presentAuditReport = (report: TAuditReports) => ({
export type TPresentedAuditReport = ReturnType<typeof presentAuditReport>;
+const StoredOrgReportConfigsSchema = z.array(
+ z.object({
+ type: z.nativeEnum(OrgAuditReportType),
+ inputs: z.record(z.unknown())
+ })
+);
+
+export const presentOrgAuditReport = (report: TAuditReports) => ({
+ id: report.id,
+ // Callers only ever pass org-scoped rows here (project rows go through presentAuditReport).
+ orgId: report.orgId as string,
+ requestedByUserId: report.requestedByUserId ?? null,
+ status: z.nativeEnum(AuditReportStatus).parse(report.status),
+ reportConfigs: StoredOrgReportConfigsSchema.parse(report.reportConfigs),
+ emailRecipients: report.emailRecipients,
+ resultSummary:
+ report.resultSummary == null ? null : z.array(OrgAuditReportResultEntrySchema).parse(report.resultSummary),
+ errorMessage: report.errorMessage ?? null,
+ createdAt: report.createdAt,
+ updatedAt: report.updatedAt
+});
+
+export type TPresentedOrgAuditReport = ReturnType<typeof presentOrgAuditReport>;
+
export const evaluateStaticSecretConstraints = (
constraints: TConstraint[],
secret: TSecretToValidate
diff --git a/backend/src/ee/services/audit-report/audit-report-generators.ts b/backend/src/ee/services/audit-report/audit-report-generators.ts
index c31d132f47..ba0ba2a0fa 100644
--- a/backend/src/ee/services/audit-report/audit-report-generators.ts
+++ b/backend/src/ee/services/audit-report/audit-report-generators.ts
@@ -51,7 +51,7 @@ export type TReportDefinition = {
};
// Cap a fully-materialized result set at the row ceiling, reporting truncation.
-const applyRowCap = <T>(items: T[]): { items: T[]; truncated: boolean } => {
+export 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 };
}
diff --git a/backend/src/ee/services/audit-report/audit-report-org-generators.ts b/backend/src/ee/services/audit-report/audit-report-org-generators.ts
new file mode 100644
index 0000000000..6c6d16d2b0
--- /dev/null
+++ b/backend/src/ee/services/audit-report/audit-report-org-generators.ts
@@ -0,0 +1,243 @@
+import { z } from "zod";
+
+import { IdentityAuthMethod, TableName } from "@app/db/schemas";
+import { TClickHouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";
+import { TDynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
+import { TInsightsDALFactory } from "@app/ee/services/insights/insights-dal";
+import {
+ buildAccessVolumeWindow,
+ buildStaticSecretUsageWindow,
+ STALE_SECRET_THRESHOLD_DAYS,
+ toUtcDateString,
+ VALUE_EVENT_TYPES
+} from "@app/ee/services/insights/insights-fns";
+import { TSecretsProjectWarning } from "@app/ee/services/insights/insights-types";
+import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+
+import { applyRowCap, NoInputsSchema } from "./audit-report-generators";
+import { MAX_AUDIT_REPORT_ROWS, OrgAuditReportType, TGeneratedReport } from "./audit-report-types";
+
+export type TOrgAuditReportGeneratorDALs = {
+ insightsDAL: Pick<
+ TInsightsDALFactory,
+ "findProjectWarningsForOrg" | "findSecretCreationsByWeekForOrg" | "countSecretCreationsForOrg"
+ >;
+ dynamicSecretLeaseDAL: Pick<TDynamicSecretLeaseDALFactory, "countLeasesForOrg">;
+ orgDAL: Pick<TOrgDALFactory, "countAllOrgMembers">;
+ identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "countAllOrgIdentities">;
+ // Undefined when the instance has no ClickHouse configured. Reports that need it are rejected at
+ // request time; the run-time throw below is a defensive fallback for config changes in between.
+ clickhouseAuditLogDAL?: Pick<TClickHouseAuditLogDALFactory, "countByDateForOrg" | "countByIdentityAuthMethodForOrg">;
+};
+
+export type TOrgReportGenerationContext = {
+ orgId: string;
+ dal: TOrgAuditReportGeneratorDALs;
+};
+
+// Mirrors TReportDefinition for project reports. `requiresClickhouse` lets the service reject a
+// report the instance cannot produce before persisting anything.
+export type TOrgReportDefinition = {
+ type: OrgAuditReportType;
+ label: string;
+ inputsSchema: z.ZodTypeAny;
+ requiresClickhouse?: boolean;
+ run: (ctx: TOrgReportGenerationContext, rawInputs: unknown) => Promise<TGeneratedReport>;
+};
+
+const missingClickhouseError = (reportLabel: string) =>
+ new Error(
+ `The '${reportLabel}' report requires audit logs to be stored in ClickHouse, which is not enabled on this instance`
+ );
+
+const usageSummaryReport: TOrgReportDefinition = {
+ type: OrgAuditReportType.OrgUsageSummary,
+ label: "Usage Summary",
+ inputsSchema: NoInputsSchema,
+ run: async ({ orgId, dal }) => {
+ const [activeLeases, users, machineIdentities] = await Promise.all([
+ dal.dynamicSecretLeaseDAL.countLeasesForOrg(orgId),
+ dal.orgDAL.countAllOrgMembers(orgId),
+ dal.identityOrgMembershipDAL.countAllOrgIdentities({
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId
+ })
+ ]);
+
+ return {
+ columns: ["activeLeases", "users", "machineIdentities"],
+ rows: [{ activeLeases, users, machineIdentities }],
+ truncated: false
+ };
+ }
+};
+
+const NEEDS_ATTENTION_PAGE_SIZE = 500;
+
+const needsAttentionReport: TOrgReportDefinition = {
+ type: OrgAuditReportType.OrgNeedsAttention,
+ label: "Needs Attention",
+ inputsSchema: NoInputsSchema,
+ run: async ({ orgId, dal }) => {
+ const staleBefore = new Date();
+ staleBefore.setDate(staleBefore.getDate() - STALE_SECRET_THRESHOLD_DAYS);
+
+ const projectsWithIssues: TSecretsProjectWarning[] = [];
+ // One page beyond the row cap so a full-capacity result can still be detected as truncated.
+ const maxPages = Math.ceil(MAX_AUDIT_REPORT_ROWS / NEEDS_ATTENTION_PAGE_SIZE) + 1;
+
+ // The DAL orders by severityScore desc, so the first zero-severity project marks the end of the
+ // projects with outstanding issues — everything after it is clean and stays out of the report.
+ for (let page = 0; page < maxPages; page += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const { projects } = await dal.insightsDAL.findProjectWarningsForOrg(orgId, {
+ offset: page * NEEDS_ATTENTION_PAGE_SIZE,
+ limit: NEEDS_ATTENTION_PAGE_SIZE,
+ staleBefore
+ });
+
+ const firstCleanIndex = projects.findIndex((project) => project.severityScore === 0);
+ projectsWithIssues.push(...(firstCleanIndex === -1 ? projects : projects.slice(0, firstCleanIndex)));
+
+ const reachedCleanProjects = firstCleanIndex !== -1;
+ const reachedLastPage = projects.length < NEEDS_ATTENTION_PAGE_SIZE;
+ if (reachedCleanProjects || reachedLastPage || projectsWithIssues.length > MAX_AUDIT_REPORT_ROWS) break;
+ }
+
+ const { items, truncated } = applyRowCap(projectsWithIssues);
+
+ return {
+ columns: [
+ "projectName",
+ "projectSlug",
+ "duplicatedSecrets",
+ "staleSecrets",
+ "failedRotations",
+ "failedSyncs",
+ "orphanedLeases",
+ "severityScore"
+ ],
+ truncated,
+ rows: items.map((project) => ({
+ projectName: project.projectName,
+ projectSlug: project.projectSlug,
+ // null (not 0) when the project has value blind indexing disabled: unknowable, not zero.
+ duplicatedSecrets: project.warnings.duplicatedSecrets,
+ staleSecrets: project.warnings.staleSecrets,
+ failedRotations: project.warnings.failedRotations,
+ failedSyncs: project.warnings.failedSyncs,
+ orphanedLeases: project.warnings.orphanedLeases,
+ severityScore: project.severityScore
+ }))
+ };
+ }
+};
+
+const authMethodsReport: TOrgReportDefinition = {
+ type: OrgAuditReportType.OrgAuthMethods,
+ label: "Auth Methods (Past 7 Days)",
+ inputsSchema: NoInputsSchema,
+ requiresClickhouse: true,
+ run: async ({ orgId, dal }) => {
+ if (!dal.clickhouseAuditLogDAL) throw missingClickhouseError(authMethodsReport.label);
+
+ const { startDate, endDate } = buildAccessVolumeWindow();
+ const rows = await dal.clickhouseAuditLogDAL.countByIdentityAuthMethodForOrg({
+ orgId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
+ });
+
+ // Logs written before the auth method was captured have no authMethod, and an instance reading
+ // logs written by a newer version can see a method it does not know yet — both land in "unknown".
+ const knownAuthMethods = new Set<string>(Object.values(IdentityAuthMethod));
+ const countsByAuthMethod = new Map<string, number>();
+ let unknownCount = 0;
+
+ rows.forEach((row) => {
+ if (!knownAuthMethods.has(row.authMethod)) {
+ unknownCount += row.count;
+ return;
+ }
+ countsByAuthMethod.set(row.authMethod, (countsByAuthMethod.get(row.authMethod) ?? 0) + row.count);
+ });
+
+ const methodRows = Array.from(countsByAuthMethod.entries())
+ .map(([authMethod, count]) => ({ authMethod, count }))
+ .sort((a, b) => b.count - a.count);
+
+ if (unknownCount > 0) {
+ methodRows.push({ authMethod: "unknown", count: unknownCount });
+ }
+
+ return { columns: ["authMethod", "count"], rows: methodRows, truncated: false };
+ }
+};
+
+const staticSecretUsageReport: TOrgReportDefinition = {
+ type: OrgAuditReportType.OrgStaticSecretUsage,
+ label: "Static Secret Usage (Past 12 Weeks)",
+ inputsSchema: NoInputsSchema,
+ run: async ({ orgId, dal }) => {
+ const { windowStart, currentWeekStart, weekStarts } = buildStaticSecretUsageWindow();
+ const currentWeekStartStr = toUtcDateString(currentWeekStart);
+
+ const [priorWeeks, createdThisWeek] = await Promise.all([
+ dal.insightsDAL.findSecretCreationsByWeekForOrg(orgId, {
+ createdAtOrAfter: windowStart,
+ createdBefore: currentWeekStart
+ }),
+ dal.insightsDAL.countSecretCreationsForOrg(orgId, { createdAtOrAfter: currentWeekStart })
+ ]);
+
+ const creationsByWeek = new Map(priorWeeks.map((row) => [row.weekStart, row.count]));
+ creationsByWeek.set(currentWeekStartStr, createdThisWeek);
+
+ return {
+ columns: ["weekStart", "totalSecrets", "isPartial"],
+ // Weeks with no creations are zero-filled so the series stays at one row per week.
+ rows: weekStarts.map((weekStart) => ({
+ weekStart,
+ totalSecrets: creationsByWeek.get(weekStart) ?? 0,
+ // Report cells are string | number | null, so the in-progress-week flag is stringified.
+ isPartial: String(weekStart === currentWeekStartStr)
+ })),
+ truncated: false
+ };
+ }
+};
+
+const secretAccessVolumeReport: TOrgReportDefinition = {
+ type: OrgAuditReportType.OrgSecretAccessVolume,
+ label: "Secret Access Volume (Past 7 Days)",
+ inputsSchema: NoInputsSchema,
+ requiresClickhouse: true,
+ run: async ({ orgId, dal }) => {
+ if (!dal.clickhouseAuditLogDAL) throw missingClickhouseError(secretAccessVolumeReport.label);
+
+ const { dates, startDate, endDate } = buildAccessVolumeWindow();
+ const rows = await dal.clickhouseAuditLogDAL.countByDateForOrg({
+ orgId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
+ });
+
+ const countsByDate = new Map(rows.map((row) => [row.date, row.count]));
+
+ return {
+ columns: ["date", "total"],
+ rows: dates.map((date) => ({ date, total: countsByDate.get(date) ?? 0 })),
+ truncated: false
+ };
+ }
+};
+
+export const ORG_AUDIT_REPORT_DEFINITIONS: Record<OrgAuditReportType, TOrgReportDefinition> = {
+ [OrgAuditReportType.OrgUsageSummary]: usageSummaryReport,
+ [OrgAuditReportType.OrgNeedsAttention]: needsAttentionReport,
+ [OrgAuditReportType.OrgAuthMethods]: authMethodsReport,
+ [OrgAuditReportType.OrgStaticSecretUsage]: staticSecretUsageReport,
+ [OrgAuditReportType.OrgSecretAccessVolume]: secretAccessVolumeReport
+};
diff --git a/backend/src/ee/services/audit-report/audit-report-queue.ts b/backend/src/ee/services/audit-report/audit-report-queue.ts
index 325c248d4b..b7e67f45bc 100644
--- a/backend/src/ee/services/audit-report/audit-report-queue.ts
+++ b/backend/src/ee/services/audit-report/audit-report-queue.ts
@@ -1,16 +1,18 @@
import { logger } from "@app/lib/logger";
import { QueueName, TQueueServiceFactory } from "@app/queue";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TAuditReportDALFactory } from "./audit-report-dal";
-import { csvFileNameFromLabel, presentAuditReport, serializeReport } from "./audit-report-fns";
+import { csvFileNameFromLabel, presentAuditReport, presentOrgAuditReport, serializeReport } from "./audit-report-fns";
import {
AUDIT_REPORT_DEFINITIONS,
TAuditReportGeneratorDALs,
TReportGenerationContext
} from "./audit-report-generators";
-import { AuditReportStatus, TAuditReportResultEntry } from "./audit-report-types";
+import { ORG_AUDIT_REPORT_DEFINITIONS, TOrgAuditReportGeneratorDALs } from "./audit-report-org-generators";
+import { AuditReportStatus, TAuditReportResultEntry, TOrgAuditReportResultEntry } from "./audit-report-types";
const WORKER_CONCURRENCY = 2;
const RATE_LIMIT_MAX = 10;
@@ -20,8 +22,12 @@ type TAuditReportQueueServiceFactoryDep = {
queueService: TQueueServiceFactory;
auditReportDAL: Pick<TAuditReportDALFactory, "findById" | "updateById">;
projectDAL: Pick<TProjectDALFactory, "findById">;
+ orgDAL: Pick<TOrgDALFactory, "findOrgById" | "countAllOrgMembers">;
smtpService: Pick<TSmtpService, "sendMail">;
-} & TAuditReportGeneratorDALs;
+} & TAuditReportGeneratorDALs &
+ // orgDAL is declared above with the union of what the worker and the org generators need;
+ // clickhouseAuditLogDAL intersects with the project generators' narrower Pick.
+ Omit<TOrgAuditReportGeneratorDALs, "orgDAL">;
export type TAuditReportQueueServiceFactory = ReturnType<typeof auditReportQueueServiceFactory>;
@@ -29,6 +35,7 @@ export const auditReportQueueServiceFactory = ({
queueService,
auditReportDAL,
projectDAL,
+ orgDAL,
smtpService,
secretV2BridgeDAL,
folderDAL,
@@ -37,7 +44,10 @@ export const auditReportQueueServiceFactory = ({
auditLogDAL,
clickhouseAuditLogDAL,
secretValidationRuleDAL,
- kmsService
+ kmsService,
+ insightsDAL,
+ dynamicSecretLeaseDAL,
+ identityOrgMembershipDAL
}: TAuditReportQueueServiceFactoryDep) => {
const generatorDAL: TAuditReportGeneratorDALs = {
secretV2BridgeDAL,
@@ -50,6 +60,145 @@ export const auditReportQueueServiceFactory = ({
kmsService
};
+ const orgGeneratorDAL: TOrgAuditReportGeneratorDALs = {
+ insightsDAL,
+ dynamicSecretLeaseDAL,
+ orgDAL,
+ identityOrgMembershipDAL,
+ clickhouseAuditLogDAL
+ };
+
+ // Delivery and terminal-status handling are identical for both scopes; only the scope resolution,
+ // the definition registry, and the email wording differ.
+ const $deliverReport = async ({
+ auditReportId,
+ targetName,
+ targetType,
+ recipients,
+ attachments,
+ emailReports,
+ resultSummary
+ }: {
+ auditReportId: string;
+ targetName: string;
+ targetType: "project" | "organization";
+ recipients: string[];
+ attachments: { filename: string; content: Buffer; contentType: string }[];
+ emailReports: { label: string; rowCount: number; truncated: boolean }[];
+ resultSummary: TAuditReportResultEntry[] | TOrgAuditReportResultEntry[];
+ }) => {
+ await smtpService.sendMail({
+ template: SmtpTemplates.AuditReport,
+ subjectLine: `Your Infisical report for ${targetName}`,
+ recipients,
+ substitutions: {
+ targetName,
+ targetType,
+ reports: emailReports
+ },
+ attachments
+ });
+
+ const truncatedAny = emailReports.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
+ });
+ };
+
+ const $generateProjectReport = async (auditReportId: string, report: Parameters<typeof presentAuditReport>[0]) => {
+ const projectId = report.projectId as string;
+ const project = await projectDAL.findById(projectId);
+ if (!project) {
+ throw new Error(`Project '${projectId}' not found`);
+ }
+
+ await auditReportDAL.updateById(auditReportId, { status: AuditReportStatus.Processing });
+
+ const { reportConfigs, emailRecipients } = presentAuditReport(report);
+ const context: TReportGenerationContext = {
+ projectId,
+ orgId: project.orgId,
+ dal: generatorDAL
+ };
+
+ 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-loop
+ const generated = await definition.run(context, config.inputs);
+ attachments.push({
+ filename: csvFileNameFromLabel(definition.label),
+ content: serializeReport(generated),
+ contentType: "text/csv"
+ });
+ resultSummary.push({ type: config.type, rowCount: generated.rows.length, truncated: generated.truncated });
+ }
+
+ await $deliverReport({
+ auditReportId,
+ targetName: project.name,
+ targetType: "project",
+ recipients: emailRecipients,
+ attachments,
+ emailReports: resultSummary.map((entry) => ({
+ label: AUDIT_REPORT_DEFINITIONS[entry.type].label,
+ rowCount: entry.rowCount,
+ truncated: entry.truncated
+ })),
+ resultSummary
+ });
+
+ logger.info(`auditReportQueue: Audit report generated [auditReportId=${auditReportId}] [projectId=${projectId}]`);
+ };
+
+ const $generateOrgReport = async (auditReportId: string, report: Parameters<typeof presentOrgAuditReport>[0]) => {
+ const orgId = report.orgId as string;
+ const org = await orgDAL.findOrgById(orgId);
+ if (!org) {
+ throw new Error(`Organization '${orgId}' not found`);
+ }
+
+ await auditReportDAL.updateById(auditReportId, { status: AuditReportStatus.Processing });
+
+ const { reportConfigs, emailRecipients } = presentOrgAuditReport(report);
+
+ const attachments: { filename: string; content: Buffer; contentType: string }[] = [];
+ const resultSummary: TOrgAuditReportResultEntry[] = [];
+
+ for (const config of reportConfigs) {
+ const definition = ORG_AUDIT_REPORT_DEFINITIONS[config.type];
+ // eslint-disable-next-line no-await-in-loop
+ const generated = await definition.run({ orgId, dal: orgGeneratorDAL }, config.inputs);
+ attachments.push({
+ filename: csvFileNameFromLabel(definition.label),
+ content: serializeReport(generated),
+ contentType: "text/csv"
+ });
+ resultSummary.push({ type: config.type, rowCount: generated.rows.length, truncated: generated.truncated });
+ }
+
+ await $deliverReport({
+ auditReportId,
+ targetName: org.name,
+ targetType: "organization",
+ recipients: emailRecipients,
+ attachments,
+ emailReports: resultSummary.map((entry) => ({
+ label: ORG_AUDIT_REPORT_DEFINITIONS[entry.type].label,
+ rowCount: entry.rowCount,
+ truncated: entry.truncated
+ })),
+ resultSummary
+ });
+
+ logger.info(`auditReportQueue: Org audit report generated [auditReportId=${auditReportId}] [orgId=${orgId}]`);
+ };
+
queueService.start(
QueueName.AuditReportGeneration,
async (job) => {
@@ -66,61 +215,11 @@ export const auditReportQueueServiceFactory = ({
}
try {
- const project = await projectDAL.findById(report.projectId);
- if (!project) {
- throw new Error(`Project '${report.projectId}' not found`);
+ if (report.orgId) {
+ await $generateOrgReport(auditReportId, report);
+ } else {
+ await $generateProjectReport(auditReportId, report);
}
-
- await auditReportDAL.updateById(auditReportId, { status: AuditReportStatus.Processing });
-
- const { reportConfigs, emailRecipients } = presentAuditReport(report);
- const context: TReportGenerationContext = {
- projectId: report.projectId,
- orgId: project.orgId,
- dal: generatorDAL
- };
-
- 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-loop
- const generated = await definition.run(context, config.inputs);
- attachments.push({
- filename: csvFileNameFromLabel(definition.label),
- content: serializeReport(generated),
- contentType: "text/csv"
- });
- resultSummary.push({ type: config.type, rowCount: generated.rows.length, truncated: generated.truncated });
- }
-
- await smtpService.sendMail({
- template: SmtpTemplates.AuditReport,
- subjectLine: `Your Infisical 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
- });
-
- 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, {
diff --git a/backend/src/ee/services/audit-report/audit-report-service.ts b/backend/src/ee/services/audit-report/audit-report-service.ts
index a68c2400c2..e0c8f511f1 100644
--- a/backend/src/ee/services/audit-report/audit-report-service.ts
+++ b/backend/src/ee/services/audit-report/audit-report-service.ts
@@ -1,10 +1,15 @@
import { ForbiddenError } from "@casl/ability";
-import { ActionProjectType } from "@app/db/schemas";
+import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import {
+ OrgPermissionSecretsManagementInsightsActions,
+ OrgPermissionSubjects
+} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { PgSqlLock } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
@@ -13,20 +18,22 @@ import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAuditReportDALFactory } from "./audit-report-dal";
-import { presentAuditReport } from "./audit-report-fns";
+import { presentAuditReport, presentOrgAuditReport } from "./audit-report-fns";
+import { ORG_AUDIT_REPORT_DEFINITIONS } from "./audit-report-org-generators";
import {
AuditReportStatus,
MAX_CONCURRENT_AUDIT_REPORTS,
- TAuditReportConfig,
TAuditReportServiceActor,
TListAuditReportsDTO,
- TRequestAuditReportDTO
+ TListOrgAuditReportsDTO,
+ TRequestAuditReportDTO,
+ TRequestOrgAuditReportDTO
} from "./audit-report-types";
const MAX_EMAIL_RECIPIENTS = 20;
type TAuditReportServiceFactoryDep = {
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
auditReportDAL: TAuditReportDALFactory;
projectDAL: Pick<TProjectDALFactory, "findById">;
@@ -48,8 +55,11 @@ export const auditReportServiceFactory = ({
}: TAuditReportServiceFactoryDep) => {
// 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[] => {
+ // can't express that) and normalize the stored shape. Generic over the type enum so the project and
+ // org report DTOs share it.
+ const $buildReportConfigs = <TType extends string>(
+ reports: { type: TType; inputs?: Record<string, unknown> }[]
+ ): { type: TType; inputs: Record<string, unknown> }[] => {
const seenTypes = new Set<string>();
return reports.map(({ type, inputs }) => {
if (seenTypes.has(type)) {
@@ -199,7 +209,8 @@ export const auditReportServiceFactory = ({
const report = await auditReportDAL.findById(auditReportId);
- if (!report) {
+ // An org-scoped report id presents as not found on the project endpoints (and vice versa).
+ if (!report?.projectId) {
throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });
}
@@ -223,7 +234,8 @@ export const auditReportServiceFactory = ({
const deleteReport = async (auditReportId: string, actor: TAuditReportServiceActor) => {
const report = await auditReportDAL.findById(auditReportId);
- if (!report) {
+ // An org-scoped report id presents as not found on the project endpoints (and vice versa).
+ if (!report?.projectId) {
throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });
}
@@ -244,10 +256,142 @@ export const auditReportServiceFactory = ({
return presentAuditReport(report);
};
+ // Resolves the requesting actor's org-level permission; org reports are always scoped to the
+ // actor's own org, so no caller-supplied org id is involved.
+ const $getOrgInsightsPermission = async (actor: TAuditReportServiceActor) => {
+ const { permission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor: actor.type,
+ actorId: actor.id,
+ orgId: actor.orgId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId
+ });
+ return permission;
+ };
+
+ const generateOrgReport = async (dto: TRequestOrgAuditReportDTO, 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 permission = await $getOrgInsightsPermission(actor);
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionSecretsManagementInsightsActions.GenerateReport,
+ OrgPermissionSubjects.SecretsManagementInsights
+ );
+
+ const reportConfigs = $buildReportConfigs(dto.reports);
+
+ // Reports the instance cannot produce are rejected before anything is persisted, instead of
+ // failing at generation time and wasting the org's concurrent-report slot.
+ const appCfg = getConfig();
+ const unsupported = reportConfigs.filter(
+ (config) => ORG_AUDIT_REPORT_DEFINITIONS[config.type].requiresClickhouse && !appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED
+ );
+ if (unsupported.length) {
+ const labels = unsupported.map((config) => `'${ORG_AUDIT_REPORT_DEFINITIONS[config.type].label}'`).join(", ");
+ throw new BadRequestError({
+ message: `The following reports require audit logs to be stored in ClickHouse, which is not enabled on this instance: ${labels}`
+ });
+ }
+
+ const emailRecipients = await $resolveRecipients(dto.emailRecipients, actor);
+
+ const report = await auditReportDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgAuditReportRequest(actor.orgId)]);
+
+ const inFlightCount = await auditReportDAL.countInFlightByOrg(actor.orgId, tx);
+ if (inFlightCount >= MAX_CONCURRENT_AUDIT_REPORTS) {
+ throw new BadRequestError({
+ message: `This organization already has ${MAX_CONCURRENT_AUDIT_REPORTS} reports in progress. Please wait for them to finish.`
+ });
+ }
+
+ return auditReportDAL.create(
+ {
+ orgId: actor.orgId,
+ 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.
+ reportConfigs: JSON.stringify(reportConfigs),
+ emailRecipients
+ },
+ tx
+ );
+ });
+
+ 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(`Org audit report requested [auditReportId=${report.id}] [orgId=${actor.orgId}]`);
+
+ return presentOrgAuditReport(report);
+ };
+
+ const listOrgReports = async (dto: TListOrgAuditReportsDTO, 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 permission = await $getOrgInsightsPermission(actor);
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionSecretsManagementInsightsActions.Read,
+ OrgPermissionSubjects.SecretsManagementInsights
+ );
+
+ const reports = await auditReportDAL.findByOrg(actor.orgId, { offset: dto.offset, limit: dto.limit });
+ const totalCount = await auditReportDAL.countByOrg(actor.orgId);
+ return { reports: reports.map(presentOrgAuditReport), totalCount };
+ };
+
+ const deleteOrgReport = async (auditReportId: string, actor: TAuditReportServiceActor) => {
+ const report = await auditReportDAL.findById(auditReportId);
+
+ // A missing report, a project-scoped report, and another org's report all present as not found,
+ // so report ids cannot be probed across scopes or tenants.
+ if (!report || !report.orgId || report.orgId !== actor.orgId) {
+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });
+ }
+
+ const permission = await $getOrgInsightsPermission(actor);
+ if (
+ !permission.can(
+ OrgPermissionSecretsManagementInsightsActions.DeleteReport,
+ OrgPermissionSubjects.SecretsManagementInsights
+ )
+ ) {
+ throw new NotFoundError({ message: `Audit report with ID '${auditReportId}' not found` });
+ }
+
+ await auditReportDAL.deleteById(report.id);
+ return presentOrgAuditReport(report);
+ };
+
return {
generateReport,
listReports,
getReportById,
- deleteReport
+ deleteReport,
+ generateOrgReport,
+ listOrgReports,
+ deleteOrgReport
};
};
diff --git a/backend/src/ee/services/audit-report/audit-report-types.ts b/backend/src/ee/services/audit-report/audit-report-types.ts
index dacdd08070..28a4b607bb 100644
--- a/backend/src/ee/services/audit-report/audit-report-types.ts
+++ b/backend/src/ee/services/audit-report/audit-report-types.ts
@@ -12,6 +12,16 @@ export enum AuditReportType {
SecretAccessLog = "SECRET_ACCESS_LOG"
}
+// Org-scoped report types. Kept in a separate enum (with non-overlapping value strings) so the org
+// and project request schemas stay disjoint and stored configs are unambiguous about their scope.
+export enum OrgAuditReportType {
+ OrgUsageSummary = "ORG_USAGE_SUMMARY",
+ OrgNeedsAttention = "ORG_NEEDS_ATTENTION",
+ OrgAuthMethods = "ORG_AUTH_METHODS",
+ OrgStaticSecretUsage = "ORG_STATIC_SECRET_USAGE",
+ OrgSecretAccessVolume = "ORG_SECRET_ACCESS_VOLUME"
+}
+
export enum AuditReportStatus {
Pending = "pending",
Processing = "processing",
@@ -31,6 +41,11 @@ export type TAuditReportConfig = {
inputs: Record<string, unknown>;
};
+export type TOrgAuditReportConfig = {
+ type: OrgAuditReportType;
+ inputs: Record<string, unknown>;
+};
+
export const AuditReportResultEntrySchema = z.object({
type: z.nativeEnum(AuditReportType),
rowCount: z.number(),
@@ -39,6 +54,14 @@ export const AuditReportResultEntrySchema = z.object({
export type TAuditReportResultEntry = z.infer<typeof AuditReportResultEntrySchema>;
+export const OrgAuditReportResultEntrySchema = z.object({
+ type: z.nativeEnum(OrgAuditReportType),
+ rowCount: z.number(),
+ truncated: z.boolean()
+});
+
+export type TOrgAuditReportResultEntry = z.infer<typeof OrgAuditReportResultEntrySchema>;
+
export type TReportRow = Record<string, string | number | null>;
export type TGeneratedReport = {
@@ -59,6 +82,17 @@ export type TListAuditReportsDTO = {
limit?: number;
};
+// Org-scoped report DTOs carry no scope id: the org is always the requesting actor's org.
+export type TRequestOrgAuditReportDTO = {
+ reports: { type: OrgAuditReportType; inputs?: Record<string, unknown> }[];
+ emailRecipients?: string[];
+};
+
+export type TListOrgAuditReportsDTO = {
+ offset?: number;
+ limit?: number;
+};
+
export type TAuditReportServiceActor = OrgServiceActor;
// Job payload for the generation queue.
diff --git a/backend/src/ee/services/insights/insights-fns.ts b/backend/src/ee/services/insights/insights-fns.ts
index b2b3222346..f8e5da6af4 100644
--- a/backend/src/ee/services/insights/insights-fns.ts
+++ b/backend/src/ee/services/insights/insights-fns.ts
@@ -1,3 +1,4 @@
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TAccessVolumeActor, TAccessVolumeDay } from "./insights-types";
@@ -5,6 +6,17 @@ import { TAccessVolumeActor, TAccessVolumeDay } from "./insights-types";
const ACCESS_VOLUME_DAYS = 7;
const STATIC_SECRET_USAGE_WEEKS = 12;
+export const STALE_SECRET_THRESHOLD_DAYS = 90;
+
+export const VALUE_EVENT_TYPES = [
+ EventType.GET_SECRETS,
+ EventType.GET_SECRET,
+ EventType.DASHBOARD_GET_SECRET_VALUE,
+ EventType.DASHBOARD_GET_SECRET_VERSION_VALUE,
+ EventType.GET_SECRET_ROTATION_GENERATED_CREDENTIALS,
+ EventType.CREATE_DYNAMIC_SECRET_LEASE
+];
+
export const toUtcDateString = (date: Date) => date.toISOString().slice(0, 10);
const startOfUtcDay = (date: Date) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index 1c3c8a2b51..f357732e59 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -4,7 +4,6 @@ import { ForbiddenError } from "@casl/ability";
import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope, TableName } from "@app/db/schemas";
import { TClickHouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";
import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { TDynamicSecretDALFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-dal";
import { TDynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
import { THoneyTokenDALFactory } from "@app/ee/services/honey-token/honey-token-dal";
@@ -46,7 +45,9 @@ import {
buildStaticSecretUsageWindow,
collapseAccessVolumeDays,
resolveUserDisplayNames,
- toUtcDateString
+ STALE_SECRET_THRESHOLD_DAYS,
+ toUtcDateString,
+ VALUE_EVENT_TYPES
} from "./insights-fns";
import {
TGetAccessVolumeDTO,
@@ -103,17 +104,6 @@ export type TInsightsServiceFactoryDep = {
export type TInsightsServiceFactory = ReturnType<typeof insightsServiceFactory>;
-const STALE_SECRET_THRESHOLD_DAYS = 90;
-
-const VALUE_EVENT_TYPES = [
- EventType.GET_SECRETS,
- EventType.GET_SECRET,
- EventType.DASHBOARD_GET_SECRET_VALUE,
- EventType.DASHBOARD_GET_SECRET_VERSION_VALUE,
- EventType.GET_SECRET_ROTATION_GENERATED_CREDENTIALS,
- EventType.CREATE_DYNAMIC_SECRET_LEASE
-];
-
// Both halves of the product (the per-project dashboard and the org-wide aggregates) are gated on the
// same entitlement, so the check and its message live in one place.
const assertInsightsPlanEnabled = async (
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index eccff70a4a..bce710e038 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -39,6 +39,7 @@ export const PgSqlLock = {
ScimGroupUpdate: (groupId: string) => pgAdvisoryLockHashText(`scim-group-update:${groupId}`),
LastAdminGuard: (scope: "org", scopeId: string) => pgAdvisoryLockHashText(`last-admin-guard:${scope}:${scopeId}`),
AuditReportRequest: (projectId: string) => pgAdvisoryLockHashText(`audit-report-request:${projectId}`),
+ OrgAuditReportRequest: (orgId: string) => pgAdvisoryLockHashText(`audit-report-request:org:${orgId}`),
OrgAgentProxyConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-agent-proxy-config-init:${orgId}`)
} as const;
@@ -197,9 +198,9 @@ export const KeyStoreTtls = {
RefreshTokenGraceInSeconds: 10,
EmailSignupOtpInSeconds: 300, // 5 minutes
EmailSignupResendCooldownInSeconds: 60, // 1 minute
- InsightsCacheInSeconds: 300, // 5 minutes
- InsightsDuplicationCacheInSeconds: 3600, // 1 hour
- InsightsWeeklyHistoryCacheInSeconds: 86400, // 24 hours
+ InsightsCacheInSeconds: 60, // 5 minutes
+ InsightsDuplicationCacheInSeconds: 60, // 1 hour
+ InsightsWeeklyHistoryCacheInSeconds: 60, // 24 hours
AdminConfigInSeconds: 60,
UpdateCheckLatestVersionInSeconds: 1209600, // 14 days (survives one missed weekly check)
InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation job
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 437420d3bc..5bffcc21bf 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3109,6 +3109,7 @@ export const registerRoutes = async (
queueService,
auditReportDAL,
projectDAL,
+ orgDAL,
smtpService,
secretV2BridgeDAL,
folderDAL,
@@ -3117,7 +3118,10 @@ export const registerRoutes = async (
auditLogDAL,
clickhouseAuditLogDAL,
secretValidationRuleDAL,
- kmsService
+ kmsService,
+ insightsDAL,
+ dynamicSecretLeaseDAL,
+ identityOrgMembershipDAL
});
const pkiSyncQueue = pkiSyncQueueFactory({
diff --git a/backend/src/services/smtp/emails/AuditReportTemplate.tsx b/backend/src/services/smtp/emails/AuditReportTemplate.tsx
index 1ce65ffeff..d93a8bd702 100644
--- a/backend/src/services/smtp/emails/AuditReportTemplate.tsx
+++ b/backend/src/services/smtp/emails/AuditReportTemplate.tsx
@@ -4,11 +4,12 @@ import React from "react";
import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
interface AuditReportTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
- projectName: string;
+ targetName: string;
+ targetType: "project" | "organization";
reports: { label: string; rowCount: number; truncated: boolean }[];
}
-export const AuditReportTemplate = ({ siteUrl, projectName, reports }: AuditReportTemplateProps) => {
+export const AuditReportTemplate = ({ siteUrl, targetName, targetType, reports }: AuditReportTemplateProps) => {
return (
<BaseEmailWrapper title="Report" preview="Your requested report is ready." siteUrl={siteUrl}>
<Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
@@ -16,7 +17,7 @@ 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 report you requested for the project <strong>{projectName}</strong> has been generated. The
+ The report you requested for the {targetType} <strong>{targetName}</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>
@@ -35,7 +36,8 @@ export const AuditReportTemplate = ({ siteUrl, projectName, reports }: AuditRepo
export default AuditReportTemplate;
AuditReportTemplate.PreviewProps = {
- projectName: "Example Project",
+ targetName: "Example Project",
+ targetType: "project",
reports: [
{ label: "Stale Secrets", rowCount: 42, truncated: false },
{ label: "Secret Access Log", rowCount: 100000, truncated: true }