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 auth methods in use to get secrets

adilsonedbdd98a42bf
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index 9382d91508..b695adfba9 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -13,6 +13,7 @@ import {
AuditReportType
} from "@app/ee/services/audit-report/audit-report-types";
import {
+ OrgAuthMethodDistributionSchema,
OrgSecretsAccessVolumeSchema,
SecretsProjectWarningsSchema,
SecretsUsageInsightsSchema
@@ -196,6 +197,49 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/secrets/auth-method-distribution",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ operationId: "getSecretsAuthMethodDistribution",
+ description:
+ "Get the number of times each machine identity authentication method was used to access a secret value in the requesting organization over the past week.",
+ security: [{ bearerAuth: [] }],
+ response: {
+ 200: z.object({
+ authMethodDistribution: OrgAuthMethodDistributionSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const authMethodDistribution = await server.services.insights.getOrgAuthMethodDistribution({
+ 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_AUTH_METHOD_DISTRIBUTION,
+ metadata: {
+ isSupported: authMethodDistribution.isSupported,
+ totalFetches: authMethodDistribution.totalFetches
+ }
+ }
+ });
+
+ return { authMethodDistribution };
+ }
+ });
+
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 abb5a1aa86..3b577f02d6 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
@@ -45,6 +45,13 @@ type TClickHouseDateVolumeRow = {
// count() is a UInt64, which ClickHouse quotes as a string in JSON output
type TClickHouseDateVolumeRawRow = Omit<TClickHouseDateVolumeRow, "count"> & { count: string };
+type TClickHouseAuthMethodRow = {
+ authMethod: string;
+ count: number;
+};
+
+type TClickHouseAuthMethodRawRow = Omit<TClickHouseAuthMethodRow, "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 = {
@@ -245,10 +252,6 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}
};
- // 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,
@@ -277,8 +280,6 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
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
},
@@ -294,5 +295,50 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}
};
- return { find, countByDateForOrg };
+ const countByIdentityAuthMethodForOrg = async ({
+ orgId,
+ eventTypes,
+ startDate,
+ endDate
+ }: TClickHouseCountByDateArg): Promise<TClickHouseAuthMethodRow[]> => {
+ const query = `
+ SELECT
+ JSONExtractString(actorMetadata, 'authMethod') AS authMethod,
+ 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)})
+ AND actor = {actorType:String}
+ GROUP BY authMethod
+ `;
+
+ 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,
+ actorType: ActorType.IDENTITY
+ },
+ clickhouse_settings: {
+ max_execution_time: 10
+ },
+ format: "JSONEachRow"
+ });
+
+ const rows = await result.json<TClickHouseAuthMethodRawRow>();
+
+ return rows.map((row) => ({ ...row, count: Number(row.count) }));
+ } catch (error) {
+ logger.error(error, `Failed to aggregate audit logs by identity auth method from ClickHouse [orgId=${orgId}]`);
+ throw new DatabaseError({ error });
+ }
+ };
+
+ return { find, countByDateForOrg, countByIdentityAuthMethodForOrg };
};
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 6047ae0fbd..fe7f5d6bd0 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -678,6 +678,7 @@ export enum EventType {
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_ORG_AUTH_METHOD_DISTRIBUTION = "view-insights-secrets-management-org-auth-method-distribution",
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",
@@ -5495,6 +5496,15 @@ interface ViewSecretManagementInsightsOrgAccessVolumeEvent {
};
}
+interface ViewSecretManagementInsightsOrgAuthMethodDistributionEvent {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION;
+ metadata: {
+ // false when the instance stores audit logs in Postgres, in which case no distribution was calculated
+ isSupported: boolean;
+ totalFetches: number;
+ };
+}
+
interface ViewSecretManagementInsightsAccessLocationsEvent {
type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS;
metadata: {
@@ -7497,6 +7507,7 @@ export type Event =
| ViewSecretManagementInsightsCalendarEvent
| ViewSecretManagementInsightsAccessVolumeEvent
| ViewSecretManagementInsightsOrgAccessVolumeEvent
+ | ViewSecretManagementInsightsOrgAuthMethodDistributionEvent
| ViewSecretManagementInsightsAccessLocationsEvent
| ViewInsightsAuthMethodsEvent
| ViewSecretManagementInsightsSummaryEvent
diff --git a/backend/src/ee/services/insights/insights-schemas.ts b/backend/src/ee/services/insights/insights-schemas.ts
index cb8c53e73e..dc0205b732 100644
--- a/backend/src/ee/services/insights/insights-schemas.ts
+++ b/backend/src/ee/services/insights/insights-schemas.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { IdentityAuthMethod } from "@app/db/schemas";
import { INSIGHTS } from "@app/lib/api-docs";
export const SecretsUsageInsightsSchema = z.object({
@@ -36,6 +37,19 @@ export const OrgSecretsAccessVolumeSchema = z.object({
.describe(INSIGHTS.GET_SECRETS_ACCESS_VOLUME.days)
});
+export const OrgAuthMethodDistributionSchema = z.object({
+ isSupported: z.boolean().describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.isSupported),
+ totalFetches: z.number().int().describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.totalFetches),
+ unknownCount: z.number().int().describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.unknownCount),
+ methods: z
+ .object({
+ authMethod: z.nativeEnum(IdentityAuthMethod).describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.authMethod),
+ count: z.number().int().describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.count)
+ })
+ .array()
+ .describe(INSIGHTS.GET_SECRETS_AUTH_METHOD_DISTRIBUTION.methods)
+});
+
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 4abd043f44..8021f81032 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -54,10 +54,12 @@ import {
TGetInsightsCountsDTO,
TGetInsightsSummaryDTO,
TGetOrgAccessVolumeDTO,
+ TGetOrgAuthMethodDistributionDTO,
TGetSecretsDuplicationDTO,
TGetSecretsProjectWarningsDTO,
TGetSecretsUsageInsightsDTO,
TOrgAccessVolume,
+ TOrgAuthMethodDistribution,
TOrgInsightsDTO,
TSecretsProjectWarnings,
TSecretsUsageInsights
@@ -67,9 +69,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">;
+ // Undefined when the instance has no ClickHouse configured. Only the org-wide aggregates use it,
+ // and each degrades to an unsupported no-op response in that case.
+ clickhouseAuditLogDAL?: Pick<TClickHouseAuditLogDALFactory, "countByDateForOrg" | "countByIdentityAuthMethodForOrg">;
secretRotationV2DAL: Pick<
TSecretRotationV2DALFactory,
"findByProjectAndDateRange" | "findByProject" | "countByProject"
@@ -685,10 +687,75 @@ export const insightsServiceFactory = ({
});
};
+ const getOrgAuthMethodDistribution = async (
+ dto: TGetOrgAuthMethodDistributionDTO
+ ): Promise<TOrgAuthMethodDistribution> => {
+ 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 { methods: [], totalFetches: 0, unknownCount: 0, isSupported: false };
+ }
+
+ const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, "org-auth-method-distribution");
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const { startDate, endDate } = buildAccessVolumeWindow();
+
+ const rows = await clickhouseAuditLogDAL.countByIdentityAuthMethodForOrg({
+ orgId: dto.orgId,
+ eventTypes: VALUE_EVENT_TYPES,
+ startDate: startDate.toISOString(),
+ endDate: endDate.toISOString()
+ });
+
+ const knownAuthMethods = new Set<string>(Object.values(IdentityAuthMethod));
+ const countsByAuthMethod = new Map<IdentityAuthMethod, number>();
+ let unknownCount = 0;
+ let totalFetches = 0;
+
+ rows.forEach((row) => {
+ totalFetches += row.count;
+
+ // 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.
+ if (!knownAuthMethods.has(row.authMethod)) {
+ unknownCount += row.count;
+ return;
+ }
+
+ const authMethod = row.authMethod as IdentityAuthMethod;
+ countsByAuthMethod.set(authMethod, (countsByAuthMethod.get(authMethod) ?? 0) + row.count);
+ });
+
+ const methods = Array.from(countsByAuthMethod.entries())
+ .map(([authMethod, count]) => ({ authMethod, count }))
+ .sort((a, b) => b.count - a.count);
+
+ return { methods, totalFetches, unknownCount, isSupported: true };
+ }
+ });
+ };
+
return {
getCalendar,
getAccessVolume,
getOrgAccessVolume,
+ getOrgAuthMethodDistribution,
getAuthMethodDistribution,
getSummary,
getSecretsDuplication,
diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.ts
index cdd90a9d57..6aee826d31 100644
--- a/backend/src/ee/services/insights/insights-types.ts
+++ b/backend/src/ee/services/insights/insights-types.ts
@@ -1,3 +1,4 @@
+import { IdentityAuthMethod } from "@app/db/schemas";
import { TOrgPermission } from "@app/lib/types";
// Project-scoped insights: the dashboard for a single secret management project.
@@ -104,3 +105,21 @@ export type TOrgAccessVolume = {
// the aggregate is not computed and `days` is empty.
isSupported: boolean;
};
+
+export type TGetOrgAuthMethodDistributionDTO = TOrgInsightsDTO;
+
+export type TOrgAuthMethodCount = {
+ authMethod: IdentityAuthMethod;
+ count: number;
+};
+
+export type TOrgAuthMethodDistribution = {
+ methods: TOrgAuthMethodCount[];
+ totalFetches: number;
+ // Fetches by a machine identity whose auth method the audit log did not record, or that this
+ // version does not recognise.
+ unknownCount: number;
+ // false when audit logs are served from Postgres rather than ClickHouse, in which case
+ // the aggregate is not computed and `methods` is empty.
+ isSupported: boolean;
+};
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 52cfd3bd3b..2c9c854538 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -926,6 +926,19 @@ export const INSIGHTS = {
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."
+ },
+ GET_SECRETS_AUTH_METHOD_DISTRIBUTION: {
+ isSupported:
+ "Whether the distribution 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 methods are returned.",
+ methods:
+ "One entry for each machine identity authentication method that was used to access a secret value in the last seven days, ordered from most to least used. Methods that were not used are not included.",
+ authMethod: "The machine identity authentication method that was used to authenticate the accesses.",
+ count:
+ "The number of times a secret value was accessed across every project in the organization using this authentication method.",
+ totalFetches:
+ "The total number of times a secret value was accessed by a machine identity across every project in the organization in the last seven days. Accesses by users are not counted.",
+ unknownCount:
+ "The number of accesses whose authentication method could not be determined, which happens for accesses recorded before the method was captured in audit logs. These are included in the total but not in the methods list."
}
} as const;