Skip to content

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

feat: add endpoint to calculate the amount of secrets fetched on last 7 days

adilson7be3f33176ac
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 7b09e6cc2c..9382d91508 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -12,7 +12,11 @@ import {
AuditReportStatus,
AuditReportType
} from "@app/ee/services/audit-report/audit-report-types";
-import { SecretsProjectWarningsSchema, SecretsUsageInsightsSchema } from "@app/ee/services/insights/insights-schemas";
+import {
+ OrgSecretsAccessVolumeSchema,
+ SecretsProjectWarningsSchema,
+ SecretsUsageInsightsSchema
+} from "@app/ee/services/insights/insights-schemas";
import { INSIGHTS } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -149,6 +153,49 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/secrets/access-volume",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ operationId: "getSecretsAccessVolume",
+ description:
+ "Get secret access volume for the requesting organization, aggregated by day and actor for the past week.",
+ security: [{ bearerAuth: [] }],
+ response: {
+ 200: z.object({
+ accessVolume: OrgSecretsAccessVolumeSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const accessVolume = await server.services.insights.getOrgAccessVolume({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ orgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_ACCESS_VOLUME,
+ metadata: {
+ isSupported: accessVolume.isSupported,
+ totalEvents: accessVolume.days.reduce((sum, day) => sum + day.total, 0)
+ }
+ }
+ });
+
+ return { accessVolume };
+ }
+ });
+
server.route({
method: "GET",
url: "/:projectId/secrets/calendar",
diff --git a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
index f545e5dfe4..abb5a1aa86 100644
--- a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
@@ -30,6 +30,21 @@ type TClickHouseFindArg = {
pamScope?: TPamAuditLogScope;
};
+type TClickHouseCountByDateArg = {
+ orgId: string;
+ eventTypes: EventType[];
+ startDate: string;
+ endDate: string;
+};
+
+type TClickHouseDateVolumeRow = {
+ date: string;
+ count: number;
+};
+
+// count() is a UInt64, which ClickHouse quotes as a string in JSON output
+type TClickHouseDateVolumeRawRow = Omit<TClickHouseDateVolumeRow, "count"> & { count: string };
+
// Shape of a row returned from ClickHouse's JSONEachRow format
// actorMetadata and eventMetadata are String columns — they come back as raw JSON strings
type TClickHouseAuditLogRow = {
@@ -230,5 +245,54 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}
};
- return { find };
+ // Org-wide access volume aggregate. Only orgId is filtered, so the scan rides the
+ // (orgId, projectId, createdAt, id) primary key prefix and spans every project in the org.
+ // Grouping by day alone keeps this to at most one row per day in the window and avoids
+ // touching actorMetadata, which would otherwise have to be JSON-parsed for every matched row.
+ const countByDateForOrg = async ({
+ orgId,
+ eventTypes,
+ startDate,
+ endDate
+ }: TClickHouseCountByDateArg): Promise<TClickHouseDateVolumeRow[]> => {
+ const query = `
+ SELECT
+ toDate(createdAt) AS date,
+ count() AS count
+ FROM ${tableName}
+ WHERE orgId = {orgId:UUID}
+ AND createdAt >= {startDate:DateTime64(6)}
+ AND createdAt < {endDate:DateTime64(6)}
+ AND eventType IN ({eventTypes:Array(String)})
+ GROUP BY date
+ `;
+
+ try {
+ const result = await clickhouseClient.query({
+ query,
+ query_params: {
+ orgId,
+ // ClickHouse's DateTime64 parser rejects the trailing 'Z'
+ startDate: startDate.replace("Z", ""),
+ endDate: endDate.replace("Z", ""),
+ eventTypes
+ },
+ // The client-level request_timeout is 30s; this bounds the aggregate server-side so a
+ // runaway query doesn't keep burning ClickHouse resources after the client has given up.
+ clickhouse_settings: {
+ max_execution_time: 10
+ },
+ format: "JSONEachRow"
+ });
+
+ const rows = await result.json<TClickHouseDateVolumeRawRow>();
+
+ return rows.map((row) => ({ ...row, count: Number(row.count) }));
+ } catch (error) {
+ logger.error(error, `Failed to aggregate audit logs by date from ClickHouse [orgId=${orgId}]`);
+ throw new DatabaseError({ error });
+ }
+ };
+
+ return { find, countByDateForOrg };
};
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 cf5472214c..6047ae0fbd 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -677,6 +677,7 @@ export enum EventType {
VIEW_INSIGHTS_AUTH_METHODS = "view-insights-auth-methods",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR = "view-insights-secrets-management-calendar",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME = "view-insights-secrets-management-access-volume",
+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_ACCESS_VOLUME = "view-insights-secrets-management-org-access-volume",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS = "view-insights-secrets-management-access-locations",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY = "view-insights-secrets-management-summary",
VIEW_INSIGHTS_SECRETS_DUPLICATION = "view-insights-secrets-duplication",
@@ -5485,6 +5486,15 @@ interface ViewSecretManagementInsightsAccessVolumeEvent {
};
}
+interface ViewSecretManagementInsightsOrgAccessVolumeEvent {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_ACCESS_VOLUME;
+ metadata: {
+ // false when the instance stores audit logs in Postgres, in which case no volume was calculated
+ isSupported: boolean;
+ totalEvents: number;
+ };
+}
+
interface ViewSecretManagementInsightsAccessLocationsEvent {
type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS;
metadata: {
@@ -7486,6 +7496,7 @@ export type Event =
| DashboardGetSecretVersionValueEvent
| ViewSecretManagementInsightsCalendarEvent
| ViewSecretManagementInsightsAccessVolumeEvent
+ | ViewSecretManagementInsightsOrgAccessVolumeEvent
| ViewSecretManagementInsightsAccessLocationsEvent
| ViewInsightsAuthMethodsEvent
| ViewSecretManagementInsightsSummaryEvent
diff --git a/backend/src/ee/services/insights/insights-fns.ts b/backend/src/ee/services/insights/insights-fns.ts
new file mode 100644
index 0000000000..aefd9e70d7
--- /dev/null
+++ b/backend/src/ee/services/insights/insights-fns.ts
@@ -0,0 +1,69 @@
+import { TUserDALFactory } from "@app/services/user/user-dal";
+
+import { TAccessVolumeActor, TAccessVolumeDay } from "./insights-types";
+
+const ACCESS_VOLUME_DAYS = 7;
+
+export const buildAccessVolumeWindow = () => {
+ const todayStr = new Date().toISOString().slice(0, 10);
+ const endDate = new Date(`${todayStr}T23:59:59.999Z`);
+ const startDate = new Date(`${todayStr}T00:00:00.000Z`);
+ startDate.setUTCDate(startDate.getUTCDate() - (ACCESS_VOLUME_DAYS - 1));
+
+ return { todayStr, startDate, endDate };
+};
+
+// Every date in the window, oldest first, so days with no access still appear in the response
+// rather than being skipped.
+export const listAccessVolumeDates = (todayStr: string) => {
+ const dates: string[] = [];
+ for (let i = ACCESS_VOLUME_DAYS - 1; i >= 0; i -= 1) {
+ const d = new Date(`${todayStr}T00:00:00.000Z`);
+ d.setUTCDate(d.getUTCDate() - i);
+ dates.push(d.toISOString().slice(0, 10));
+ }
+
+ return dates;
+};
+
+export const buildAccessVolumeDayBuckets = (todayStr: string) =>
+ new Map(listAccessVolumeDates(todayStr).map((date) => [date, new Map<string, TAccessVolumeActor>()]));
+
+// Rows outside the window are dropped. The same actor can arrive as several rows when the
+// underlying aggregate groups on fields we do not surface, so counts are summed per actor.
+export const addAccessVolumeEntry = (
+ dayMap: Map<string, Map<string, TAccessVolumeActor>>,
+ { date, type, name, count }: TAccessVolumeActor & { date: string }
+) => {
+ const actorMap = dayMap.get(date);
+ if (!actorMap) return;
+
+ const actorKey = `${type}:${name}`;
+ const existing = actorMap.get(actorKey);
+ if (existing) {
+ existing.count += count;
+ } else {
+ actorMap.set(actorKey, { name, type, count });
+ }
+};
+
+export const collapseAccessVolumeDays = (dayMap: Map<string, Map<string, TAccessVolumeActor>>): TAccessVolumeDay[] =>
+ Array.from(dayMap.entries()).map(([date, actorMap]) => {
+ const actors = Array.from(actorMap.values()).sort((a, b) => b.count - a.count);
+ const total = actors.reduce((sum, actor) => sum + actor.count, 0);
+ return { date, total, actors };
+ });
+
+// Audit log metadata only carries the userId, so display names come from the users table.
+export const resolveUserDisplayNames = async (userDAL: Pick<TUserDALFactory, "find">, userIds: string[]) => {
+ const userNameMap = new Map<string, string>();
+ if (!userIds.length) return userNameMap;
+
+ const users = await userDAL.find({ $in: { id: userIds } });
+ users.forEach((user) => {
+ const displayName = [user.firstName, user.lastName].filter(Boolean).join(" ");
+ if (displayName) userNameMap.set(user.id, displayName);
+ });
+
+ return userNameMap;
+};
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index 5efc0d1f66..cb8c53e73e 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -25,6 +25,17 @@ export const SecretsProjectWarningSchema = z.object({
.describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.warnings)
});
+export const OrgSecretsAccessVolumeSchema = z.object({
+ isSupported: z.boolean().describe(INSIGHTS.GET_SECRETS_ACCESS_VOLUME.isSupported),
+ days: z
+ .object({
+ date: z.string().describe(INSIGHTS.GET_SECRETS_ACCESS_VOLUME.date),
+ total: z.number().int().describe(INSIGHTS.GET_SECRETS_ACCESS_VOLUME.total)
+ })
+ .array()
+ .describe(INSIGHTS.GET_SECRETS_ACCESS_VOLUME.days)
+});
+
export const SecretsProjectWarningsSchema = z.object({
projects: SecretsProjectWarningSchema.array(),
totalProjects: z.number().int().describe(INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalProjects),
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index fab9273d21..4abd043f44 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -2,6 +2,7 @@ import { ForbiddenError } from "@casl/ability";
// import geoip from "geoip-lite";
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";
@@ -21,6 +22,7 @@ import {
import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getCacheTtl, withCache } from "@app/lib/cache/with-cache";
+import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
@@ -38,15 +40,24 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
import { TInsightsDALFactory } from "./insights-dal";
import {
- // TGetAccessLocationsDTO,
+ addAccessVolumeEntry,
+ buildAccessVolumeDayBuckets,
+ buildAccessVolumeWindow,
+ collapseAccessVolumeDays,
+ listAccessVolumeDates,
+ resolveUserDisplayNames
+} from "./insights-fns";
+import {
TGetAccessVolumeDTO,
TGetAuthMethodDistributionDTO,
TGetInsightsCalendarDTO,
TGetInsightsCountsDTO,
TGetInsightsSummaryDTO,
+ TGetOrgAccessVolumeDTO,
TGetSecretsDuplicationDTO,
TGetSecretsProjectWarningsDTO,
TGetSecretsUsageInsightsDTO,
+ TOrgAccessVolume,
TOrgInsightsDTO,
TSecretsProjectWarnings,
TSecretsUsageInsights
@@ -56,6 +67,9 @@ export type TInsightsServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByIpAddress" | "countByAuthMethod">;
+ // Undefined when the instance has no ClickHouse configured. Org-wide access volume is the only
+ // consumer and degrades to a no-op response in that case.
+ clickhouseAuditLogDAL?: Pick<TClickHouseAuditLogDALFactory, "countByDateForOrg">;
secretRotationV2DAL: Pick<
TSecretRotationV2DALFactory,
"findByProjectAndDateRange" | "findByProject" | "countByProject"
@@ -146,6 +160,7 @@ export const insightsServiceFactory = ({
permissionService,
licenseService,
auditLogDAL,
+ clickhouseAuditLogDAL,
secretRotationV2DAL,
reminderDAL,
folderDAL,
@@ -235,11 +250,7 @@ export const insightsServiceFactory = ({
key: cacheKey,
ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
fetcher: async () => {
- const now = new Date();
- const todayStr = now.toISOString().slice(0, 10);
- const endDate = new Date(`${todayStr}T23:59:59.999Z`);
- const startDate = new Date(`${todayStr}T00:00:00.000Z`);
- startDate.setUTCDate(startDate.getUTCDate() - 6);
+ const { todayStr, startDate, endDate } = buildAccessVolumeWindow();
const rows = await auditLogDAL.countByDateAndActor({
orgId: actorDto.orgId,
@@ -249,37 +260,18 @@ export const insightsServiceFactory = ({
endDate: endDate.toISOString()
});
- // Resolve user display names from userIds in audit log metadata
- const userIds = [
+ const userNameMap = await resolveUserDisplayNames(userDAL, [
...new Set(
rows
.filter((r) => r.actor === ActorType.USER)
.map((r) => (r.actorMetadata as Record<string, string> | null)?.userId)
.filter(Boolean) as string[]
)
- ];
- const userNameMap = new Map<string, string>();
- if (userIds.length > 0) {
- const users = await userDAL.find({ $in: { id: userIds } });
- users.forEach((u) => {
- const displayName = [u.firstName, u.lastName].filter(Boolean).join(" ");
- if (displayName) userNameMap.set(u.id, displayName);
- });
- }
+ ]);
- // Pre-populate the last 7 days
- const dayMap = new Map<string, Map<string, { name: string; type: string; count: number }>>();
- for (let i = 6; i >= 0; i -= 1) {
- const d = new Date(`${todayStr}T00:00:00.000Z`);
- d.setUTCDate(d.getUTCDate() - i);
- dayMap.set(d.toISOString().slice(0, 10), new Map());
- }
+ const dayMap = buildAccessVolumeDayBuckets(todayStr);
rows.forEach((row) => {
- const dateKey = typeof row.date === "string" ? row.date : new Date(row.date).toISOString().slice(0, 10);
- const actorMap = dayMap.get(dateKey);
- if (!actorMap) return;
-
const actorMeta = row.actorMetadata as Record<string, string> | null;
let actorName: string;
if (row.actor === ActorType.USER && actorMeta?.userId) {
@@ -289,106 +281,20 @@ export const insightsServiceFactory = ({
} else {
actorName = actorMeta?.name || actorMeta?.identityId || "Unknown";
}
- const actorKey = `${row.actor}:${actorName}`;
-
- const existing = actorMap.get(actorKey);
- if (existing) {
- existing.count += row.count;
- } else {
- actorMap.set(actorKey, { name: actorName, type: row.actor, count: row.count });
- }
- });
- const days = Array.from(dayMap.entries()).map(([date, actorMap]) => {
- const actors = Array.from(actorMap.values()).sort((a, b) => b.count - a.count);
- const total = actors.reduce((sum, a) => sum + a.count, 0);
- return { date, total, actors };
+ addAccessVolumeEntry(dayMap, {
+ date: typeof row.date === "string" ? row.date : new Date(row.date).toISOString().slice(0, 10),
+ type: row.actor,
+ name: actorName,
+ count: row.count
+ });
});
- return { days };
+ return { days: collapseAccessVolumeDays(dayMap) };
}
});
};
- // const getAccessLocations = async (dto: TGetAccessLocationsDTO, actorDto: OrgServiceActor) => {
- // await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
-
- // const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, `access-locations:${dto.days}`);
- // return withCache(cacheKey, async () => {
- // const endDate = new Date();
- // const startDate = new Date();
- // startDate.setUTCDate(startDate.getUTCDate() - dto.days);
-
- // const ipRows = await auditLogDAL.countByIpAddress({
- // orgId: actorDto.orgId,
- // projectId: dto.projectId,
- // eventTypes: VALUE_EVENT_TYPES,
- // startDate: startDate.toISOString(),
- // endDate: endDate.toISOString()
- // });
-
- // const locationMap = new Map<string, { lat: number; lng: number; city: string; country: string; count: number }>();
-
- // const isPrivateIp = (ip: string) =>
- // ip === "127.0.0.1" ||
- // ip === "::1" ||
- // ip === "::ffff:127.0.0.1" ||
- // ip.startsWith("10.") ||
- // ip.startsWith("172.16.") ||
- // ip.startsWith("172.17.") ||
- // ip.startsWith("172.18.") ||
- // ip.startsWith("172.19.") ||
- // ip.startsWith("172.20.") ||
- // ip.startsWith("172.21.") ||
- // ip.startsWith("172.22.") ||
- // ip.startsWith("172.23.") ||
- // ip.startsWith("172.24.") ||
- // ip.startsWith("172.25.") ||
- // ip.startsWith("172.26.") ||
- // ip.startsWith("172.27.") ||
- // ip.startsWith("172.28.") ||
- // ip.startsWith("172.29.") ||
- // ip.startsWith("172.30.") ||
- // ip.startsWith("172.31.") ||
- // ip.startsWith("192.168.");
-
- // ipRows.forEach(({ ipAddress: ip, count }) => {
- // if (isPrivateIp(ip)) {
- // const key = "Local Network:LOCAL";
- // const existing = locationMap.get(key);
- // if (existing) {
- // existing.count += count;
- // } else {
- // locationMap.set(key, { lat: 0, lng: 0, city: "Local Network", country: "LOCAL", count });
- // }
- // return;
- // }
-
- // const geo = geoip.lookup(ip);
- // if (!geo || !geo.ll) return;
-
- // const city = geo.city || geo.region || "";
- // const key = `${city}:${geo.country}`;
- // const existing = locationMap.get(key);
- // if (existing) {
- // existing.count += count;
- // } else {
- // locationMap.set(key, {
- // lat: geo.ll[0],
- // lng: geo.ll[1],
- // city,
- // country: geo.country,
- // count
- // });
- // }
- // });
-
- // return {
- // locations: Array.from(locationMap.values()).sort((a, b) => b.count - a.count)
- // };
- // });
- // };
-
const getAuthMethodDistribution = async (dto: TGetAuthMethodDistributionDTO, actorDto: OrgServiceActor) => {
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
@@ -735,10 +641,54 @@ export const insightsServiceFactory = ({
});
};
+ const getOrgAccessVolume = async (dto: TGetOrgAccessVolumeDTO): Promise<TOrgAccessVolume> => {
+ await checkSecretsManagementInsightsPermission(
+ permissionService,
+ OrgPermissionSecretsManagementInsightsActions.Read,
+ dto
+ );
+
+ const plan = await licenseService.getPlan(dto.orgId);
+ if (!plan.secretAccessInsights) {
+ throw new BadRequestError({
+ message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
+ });
+ }
+
+ const appCfg = getConfig();
+ if (!appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED || !clickhouseAuditLogDAL) {
+ return { days: [], isSupported: false };
+ }
+
+ const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, "org-access-volume");
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const { todayStr, startDate, endDate } = buildAccessVolumeWindow();
+
+ const rows = await clickhouseAuditLogDAL.countByDateForOrg({
+ orgId: dto.orgId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
+ });
+
+ const countsByDate = new Map(rows.map((row) => [row.date, row.count]));
+
+ return {
+ days: listAccessVolumeDates(todayStr).map((date) => ({ date, total: countsByDate.get(date) ?? 0 })),
+ isSupported: true
+ };
+ }
+ });
+ };
+
return {
getCalendar,
getAccessVolume,
- // getAccessLocations,
+ getOrgAccessVolume,
getAuthMethodDistribution,
getSummary,
getSecretsDuplication,
diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.ts
index 6332807186..cdd90a9d57 100644
--- a/backend/src/ee/services/insights/insights-types.ts
+++ b/backend/src/ee/services/insights/insights-types.ts
@@ -78,3 +78,29 @@ export type TSecretsProjectWarnings = {
offset: number;
limit: number;
};
+
+export type TGetOrgAccessVolumeDTO = TOrgInsightsDTO;
+
+export type TAccessVolumeActor = {
+ name: string;
+ type: string;
+ count: number;
+};
+
+export type TAccessVolumeDay = {
+ date: string;
+ total: number;
+ actors: TAccessVolumeActor[];
+};
+
+export type TOrgAccessVolumeDay = {
+ date: string;
+ total: number;
+};
+
+export type TOrgAccessVolume = {
+ days: TOrgAccessVolumeDay[];
+ // false when audit logs are served from Postgres rather than ClickHouse, in which case
+ // the aggregate is not computed and `days` is empty.
+ isSupported: boolean;
+};
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index f0ed300cfc..52cfd3bd3b 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -918,6 +918,14 @@ export const INSIGHTS = {
"A relative score used to rank projects by the severity of their outstanding issues. The scoring heuristic may change over time.",
totalProjects: "The total number of secret management projects in the organization.",
projectsWithIssues: "The number of secret management projects in the organization with at least one issue."
+ },
+ GET_SECRETS_ACCESS_VOLUME: {
+ isSupported:
+ "Whether access volume could be calculated. This endpoint requires the instance to store audit logs in ClickHouse. When audit logs are stored in PostgreSQL this is false and no days are returned.",
+ days: "One entry for each of the last seven days, oldest first. Days with no secret access are included with a total of zero.",
+ date: "The day the accesses happened on, in UTC, as YYYY-MM-DD.",
+ total:
+ "The number of times a secret value was accessed across every project in the organization on this day, by any user or machine identity."
}
} as const;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 6be97cfb6c..437420d3bc 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3076,6 +3076,7 @@ export const registerRoutes = async (
permissionService,
licenseService,
auditLogDAL,
+ clickhouseAuditLogDAL,
secretRotationV2DAL,
reminderDAL,
folderDAL,