Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(insights): org-wide duplicate secret detection
Calvin519ce296b93d
diff --git a/backend/e2e-test/testUtils/insights.ts b/backend/e2e-test/testUtils/insights.tsindex 2312e7015e..7fa5b90cd0 100644--- a/backend/e2e-test/testUtils/insights.ts+++ b/backend/e2e-test/testUtils/insights.ts@@ -22,10 +22,7 @@ const unreachable = (method: string) => (): never => {};// Specs supply their own getOrgPermission; this fills the other half of the permissionService contract.-const unreachableGetProjectPermission: Pick<- TInsightsServiceFactoryDep["permissionService"],- "getProjectPermission"-> = {+const unreachableGetProjectPermission: Pick<TInsightsServiceFactoryDep["permissionService"], "getProjectPermission"> = {getProjectPermission: unreachable("permissionService.getProjectPermission")};@@ -63,6 +60,7 @@ export const projectScopedInsightsDepStubs: Pick<findStaleByProject: unreachable("secretV2BridgeDAL.findStaleByProject"),countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),+ findDuplicatedSecretValuesInOrg: unreachable("secretV2BridgeDAL.findDuplicatedSecretValuesInOrg"),countByProject: unreachable("secretV2BridgeDAL.countByProject")},dynamicSecretDAL: {@@ -93,7 +91,8 @@ export const usageInsightsDepStubs: Pick<"orgDAL" | "identityOrgMembershipDAL" | "dynamicSecretLeaseDAL"> = {orgDAL: {- countSecretManagerProjectMembers: unreachable("orgDAL.countSecretManagerProjectMembers")+ countSecretManagerProjectMembers: unreachable("orgDAL.countSecretManagerProjectMembers"),+ findById: unreachable("orgDAL.findById")},identityOrgMembershipDAL: {countSecretManagerProjectIdentities: unreachable("identityOrgMembershipDAL.countSecretManagerProjectIdentities")@@ -147,5 +146,6 @@ export const buildOrgInsightsGateStubs = () => {export const passThroughKeyStore: TInsightsServiceFactoryDep["keyStore"] = {getItem: async () => null,setItemWithExpiry: async () => "OK",- ttl: async () => -2+ ttl: async () => -2,+ deleteItem: async () => 1};diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex a87b827f8e..9b1e124f93 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -500,6 +500,70 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/secrets/secrets-duplication",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "getOrgInsightsSecretsDuplication",+ description: "Get groups of secrets that share a value anywhere in the organization",+ security: [{ bearerAuth: [] }],+ querystring: z.object({+ refresh: z+ .enum(["true", "false"])+ .default("false")+ .transform((value) => value === "true")+ .describe("Recompute now instead of answering from the cached result.")+ }),+ response: {+ 200: z.object({+ orgWideSecretValueTrackingEnabled: z.boolean(),+ groups: z.array(+ z.object({+ projectCount: z.number(),+ locationCount: z.number(),+ secrets: z.array(+ z.object({+ key: z.string(),+ projectId: z.string(),+ projectName: z.string(),+ environment: z.object({ name: z.string(), slug: z.string() }),+ secretPath: z.string()+ })+ )+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),+ handler: async (req, reply) => {+ const { result, remainingTTL } = await server.services.insights.getOrgSecretsDuplication({+ orgId: req.permission.orgId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ refresh: req.query.refresh+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.VIEW_INSIGHTS_ORG_SECRETS_DUPLICATION,+ metadata: { groupCount: result.groups.length }+ }+ });++ if (remainingTTL && remainingTTL >= 0) {+ void reply.header("X-Cache-TTL", remainingTTL);+ }++ return result;+ }+ });+server.route({method: "GET",url: "/:projectId/secrets/secrets-duplication",diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex f2c25c6f0c..a4813f8f61 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -713,6 +713,7 @@ export enum EventType {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",+ VIEW_INSIGHTS_ORG_SECRETS_DUPLICATION = "view-insights-org-secrets-duplication",VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS = "view-insights-secrets-management-counts",VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE = "view-insights-secrets-management-usage",VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS = "view-insights-secrets-management-project-warnings",@@ -5881,6 +5882,13 @@ interface ViewSecretManagementInsightsSummaryEvent {};}+interface ViewInsightsOrgSecretsDuplicationEvent {+ type: EventType.VIEW_INSIGHTS_ORG_SECRETS_DUPLICATION;+ metadata: {+ groupCount: number;+ };+}+interface ViewInsightsSecretsDuplicationEvent {type: EventType.VIEW_INSIGHTS_SECRETS_DUPLICATION;metadata: {@@ -8264,6 +8272,7 @@ export type Event =| ViewInsightsAuthMethodsEvent| ViewSecretManagementInsightsSummaryEvent| ViewInsightsSecretsDuplicationEvent+ | ViewInsightsOrgSecretsDuplicationEvent| ViewSecretManagementInsightsCountsEvent| ViewSecretManagementInsightsUsageEvent| ViewSecretManagementInsightsProjectWarningsEventdiff --git a/backend/src/ee/services/insights/insights-service.test.ts b/backend/src/ee/services/insights/insights-service.test.tsindex 9925d1e2db..c171627bdf 100644--- a/backend/src/ee/services/insights/insights-service.test.ts+++ b/backend/src/ee/services/insights/insights-service.test.ts@@ -53,6 +53,7 @@ const projectScopedDepStubs: Pick<findStaleByProject: unreachable("secretV2BridgeDAL.findStaleByProject"),countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),+ findDuplicatedSecretValuesInOrg: unreachable("secretV2BridgeDAL.findDuplicatedSecretValuesInOrg"),countByProject: unreachable("secretV2BridgeDAL.countByProject")},dynamicSecretDAL: {@@ -119,9 +120,13 @@ const buildService = (catalog: TSecretsProjectWarning[]) => {keyStore: {getItem: async () => null,setItemWithExpiry: async () => "OK",- ttl: async () => -2+ ttl: async () => -2,+ deleteItem: async () => 1+ },+ orgDAL: {+ countSecretManagerProjectMembers: unreachable("orgDAL.countSecretManagerProjectMembers"),+ findById: unreachable("orgDAL.findById")},- orgDAL: { countSecretManagerProjectMembers: unreachable("orgDAL.countSecretManagerProjectMembers") },identityOrgMembershipDAL: {countSecretManagerProjectIdentities: unreachable("identityOrgMembershipDAL.countSecretManagerProjectIdentities")},diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex 9eca72645f..94f61ad391 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -22,7 +22,7 @@ import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2import { 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 { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";@@ -56,6 +56,7 @@ import {TGetInsightsCalendarDTO,TGetInsightsCountsDTO,TGetInsightsSummaryDTO,+ TGetOrgSecretsDuplicationDTO,TGetSecretsDuplicationDTO,TGetSecretsProjectWarningsDTO,TOrgAccessVolume,@@ -79,7 +80,11 @@ export type TInsightsServiceFactoryDep = {folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds" | "countByProject">;secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory,- "findStaleByProject" | "countStaleByProject" | "findDuplicatedSecretValues" | "countByProject"+ | "findStaleByProject"+ | "countStaleByProject"+ | "findDuplicatedSecretValues"+ | "findDuplicatedSecretValuesInOrg"+ | "countByProject">;dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "countByProject">;honeyTokenDAL: Pick<THoneyTokenDALFactory, "countByProjectId">;@@ -87,8 +92,8 @@ export type TInsightsServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findById">;userDAL: Pick<TUserDALFactory, "find">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl">;- orgDAL: Pick<TOrgDALFactory, "countSecretManagerProjectMembers">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl" | "deleteItem">;+ orgDAL: Pick<TOrgDALFactory, "countSecretManagerProjectMembers" | "findById">;identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "countSecretManagerProjectIdentities">;dynamicSecretLeaseDAL: Pick<TDynamicSecretLeaseDALFactory, "countLeasesForOrg">;insightsDAL: Pick<@@ -479,6 +484,108 @@ export const insightsServiceFactory = ({});};+ // The org-wide view of the same question the project card answers. Permission is the org insights+ // read, which already grants cross-project visibility elsewhere on this page (getSecretsProjects+ // reads every project in the org behind the same assert), so there is no per-project filter here.+ const getOrgSecretsDuplication = async (dto: TGetOrgSecretsDuplicationDTO) => {+ await assertOrgInsightsRead(dto);++ const org = await orgDAL.findById(dto.orgId);+ if (!org) throw new NotFoundError({ message: `Organization with ID '${dto.orgId}' not found` });++ // Org-scoped digests only exist once the backfill has run, so an empty answer before then would+ // read as "no duplicates" when it means "nothing has been indexed".+ if (!org.orgWideSecretValueTrackingEnabled) {+ return { result: { orgWideSecretValueTrackingEnabled: false as const, groups: [] } };+ }++ const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, "org-secrets-duplication");+ if (dto.refresh) await keyStore.deleteItem(cacheKey);++ const result = await withCache({+ keyStore,+ key: cacheKey,+ ttlSeconds: KeyStoreTtls.InsightsDuplicationCacheInSeconds,+ fetcher: async () => {+ const rawGroups = await secretV2BridgeDAL.findDuplicatedSecretValuesInOrg(dto.orgId);+ if (!rawGroups.length) return { orgWideSecretValueTrackingEnabled: true as const, groups: [] };++ // One decryptor per project rather than per group: the value is encrypted under the owning+ // project's data key, and resolving that key can reach an external KMS.+ const decryptors = new Map<string, (input: { cipherTextBlob: Buffer }) => Buffer>();+ const $decryptorFor = async (projectId: string) => {+ const cached = decryptors.get(projectId);+ if (cached) return cached;+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ decryptors.set(projectId, decryptor);+ return decryptor;+ };++ const filteredGroups: typeof rawGroups = [];+ for await (const group of rawGroups) {+ const first = group.secrets[0];+ if (!first) continue;+ if (!first.encryptedValue) {+ filteredGroups.push(group);+ continue;+ }+ const decryptor = await $decryptorFor(first.projectId);+ const value = decryptor({ cipherTextBlob: first.encryptedValue }).toString();+ if (!containsSecretReference(value)) filteredGroups.push(group);+ }++ // Paths resolve per project, since a folder id only means something inside its own project.+ const folderIdsByProject = new Map<string, Set<string>>();+ filteredGroups.forEach((group) =>+ group.secrets.forEach((secret) => {+ const forProject = folderIdsByProject.get(secret.projectId) ?? new Set<string>();+ forProject.add(secret.folderId);+ folderIdsByProject.set(secret.projectId, forProject);+ })+ );++ const pathByFolderId = new Map<string, string>();+ await Promise.all(+ [...folderIdsByProject].map(async ([projectId, folderIds]) => {+ const folders = await folderDAL.findSecretPathByFolderIds(projectId, [...folderIds]);+ folders.forEach((folder) => {+ if (folder) pathByFolderId.set(folder.id, folder.path);+ });+ })+ );++ const groups = filteredGroups+ .map((group) => ({+ projectCount: new Set(group.secrets.map((secret) => secret.projectId)).size,+ locationCount: new Set(+ group.secrets.map(+ (secret) => `${secret.projectId}:${secret.environment}:${pathByFolderId.get(secret.folderId) ?? "/"}`+ )+ ).size,+ secrets: group.secrets.map((secret) => ({+ key: secret.key,+ projectId: secret.projectId,+ projectName: secret.projectName,+ environment: { name: secret.environmentName, slug: secret.environment },+ secretPath: pathByFolderId.get(secret.folderId) ?? "/"+ }))+ }))+ // Blast radius first: a value in three projects needs three teams to agree a rotation+ // window, which is a different problem from three copies inside one project.+ .sort((a, b) => b.projectCount - a.projectCount || b.locationCount - a.locationCount);++ return { orgWideSecretValueTrackingEnabled: true as const, groups };+ }+ });++ const remainingTTL = await getCacheTtl(keyStore, cacheKey);++ return { result, remainingTTL };+ };+const getSecretsDuplication = async (dto: TGetSecretsDuplicationDTO, actorDto: OrgServiceActor) => {await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);@@ -773,6 +880,7 @@ export const insightsServiceFactory = ({getAuthMethodDistribution,getSummary,getSecretsDuplication,+ getOrgSecretsDuplication,getCounts,getSecretsUsageInsights,getSecretsProjects,diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.tsindex 7af2b9d9a1..06ac2deddf 100644--- a/backend/src/ee/services/insights/insights-types.ts+++ b/backend/src/ee/services/insights/insights-types.ts@@ -46,6 +46,12 @@ export type TGetInsightsCountsDTO = {export type TOrgInsightsDTO = TOrgPermission;+// `refresh` lets the card recompute on demand rather than wait out the cache, which is the whole+// point of the control that replaced the countdown badge.+export type TGetOrgSecretsDuplicationDTO = TOrgInsightsDTO & {+ refresh?: boolean;+};+export type TGetSecretsProjectWarningsDTO = TOrgInsightsDTO & {offset: number;limit: number;diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 5b295b7bfe..8078a845f9 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -249,7 +249,10 @@ export const KeyStoreTtls = {EmailDispatchMailboxWindowInSeconds: 86400, // 24 hoursEmailDispatchAbuseProbeInSeconds: 7200, // 2 hoursInsightsCacheInSeconds: 300, // 5 minutes- InsightsDuplicationCacheInSeconds: 3600, // 1 hour+ // Five minutes, matching every other insight on the page. An hour was far more than the query+ // costs, and nothing invalidates this key when a secret changes, so a longer window meant the card+ // could sit on a stale empty answer long after the duplicates it exists to find were created.+ InsightsDuplicationCacheInSeconds: 300,InsightsWeeklyHistoryCacheInSeconds: 86400, // 24 hoursInsightsOrgCacheInSeconds: 900, // 15 minutesAdminConfigInSeconds: 60,diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.tsindex 4f7cd757e3..ee7e8ca3c8 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts@@ -1563,6 +1563,72 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {}};+ // The org-wide sibling of findDuplicatedSecretValues. Groups on the org-scoped digest, which is+ // the only one that can match across projects, and carries the owning project on every row so the+ // caller can say where each copy lives.+ const findDuplicatedSecretValuesInOrg = async (orgId: string, tx?: Knex) => {+ try {+ const scoped = (qb: Knex.QueryBuilder) =>+ qb+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.Project}.orgId`, orgId)+ .where(`${TableName.Project}.type`, ProjectType.SecretManager)+ .whereNull(`${TableName.Project}.deleteAfter`)+ .whereNull(`${TableName.Environment}.deleteAfter`)+ .whereNull(`${TableName.SecretV2}.userId`)+ .whereNotNull(`${TableName.SecretV2}.secretValueOrgBlindIndex`);++ const duplicateDigests = scoped((tx || db.replicaNode())(TableName.SecretV2))+ .groupBy(`${TableName.SecretV2}.secretValueOrgBlindIndex`)+ .having(db.raw("count(*) > 1"))+ .select(`${TableName.SecretV2}.secretValueOrgBlindIndex`);++ const rows = (await scoped((tx || db.replicaNode())(TableName.SecretV2))+ .whereIn(`${TableName.SecretV2}.secretValueOrgBlindIndex`, duplicateDigests)+ .select(+ `${TableName.SecretV2}.key`,+ `${TableName.SecretV2}.folderId`,+ `${TableName.SecretV2}.encryptedValue`,+ `${TableName.SecretV2}.secretValueOrgBlindIndex`,+ `${TableName.Environment}.slug as environment`,+ `${TableName.Environment}.name as environmentName`,+ `${TableName.Project}.id as projectId`,+ `${TableName.Project}.name as projectName`+ )+ .orderBy(`${TableName.SecretV2}.secretValueOrgBlindIndex`)) as {+ key: string;+ folderId: string;+ encryptedValue: Buffer | null;+ secretValueOrgBlindIndex: string;+ environment: string;+ environmentName: string;+ projectId: string;+ projectName: string;+ }[];++ type TOrgDuplicateSecret = Omit<(typeof rows)[number], "secretValueOrgBlindIndex">;+ const groups: { secrets: TOrgDuplicateSecret[] }[] = [];+ let currentDigest: string | null = null;+ let currentGroup: TOrgDuplicateSecret[] = [];++ for (const { secretValueOrgBlindIndex, ...secret } of rows) {+ if (secretValueOrgBlindIndex !== currentDigest) {+ if (currentGroup.length > 0) groups.push({ secrets: currentGroup });+ currentDigest = secretValueOrgBlindIndex;+ currentGroup = [];+ }+ currentGroup.push(secret);+ }+ if (currentGroup.length > 0) groups.push({ secrets: currentGroup });++ return groups;+ } catch (error) {+ throw new DatabaseError({ error, name: "findDuplicatedSecretValuesInOrg" });+ }+ };+const findDuplicatedSecretValues = async (projectId: string, tx?: Knex) => {try {const duplicateBlindIndexes = (tx || db.replicaNode())(TableName.SecretV2)@@ -1762,6 +1828,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {countByProject,findValueValidationCandidatesByProject,findDuplicatedSecretValues,+ findDuplicatedSecretValuesInOrg,findSecretsWithMatchingValue,findExistingSecretsWithMatchingValues,findOne,diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-service.tsindex a78c5fae2d..812474febc 100644--- a/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts@@ -1,7 +1,10 @@import { ForbiddenError } from "@casl/ability";import { ActionProjectType, OrganizationActionScope, ProjectType } from "@app/db/schemas";-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { NotFoundError } from "@app/lib/errors";@@ -34,7 +37,12 @@ export const secretValueTrackingServiceFactory = ({actorOrgId: actor.orgId,scope: OrganizationActionScope.Any});- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);+ // The permission that grants org-wide secrets insights also grants turning the index on: the+ // backfill unlocks exactly the reads this permission already allows, and nothing else.+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionSecretsManagementInsightsActions.Read,+ OrgPermissionSubjects.SecretsManagementInsights+ );const org = await orgDAL.findById(actor.orgId);if (!org) throw new NotFoundError({ message: `Organization with ID '${actor.orgId}' not found` });@@ -62,7 +70,10 @@ export const secretValueTrackingServiceFactory = ({actorOrgId: actor.orgId,scope: OrganizationActionScope.Any});- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionSecretsManagementInsightsActions.Read,+ OrgPermissionSubjects.SecretsManagementInsights+ );const org = await orgDAL.findById(actor.orgId);if (!org) throw new NotFoundError({ message: `Organization with ID '${actor.orgId}' not found` });