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): gate org-wide value search on its own permission
Calvin1ef2d54c23d8
diff --git a/backend/e2e-test/insights-secrets-duplication.spec.ts b/backend/e2e-test/insights-secrets-duplication.spec.tsnew file mode 100644index 0000000000..eafa7279cd--- /dev/null+++ b/backend/e2e-test/insights-secrets-duplication.spec.ts@@ -0,0 +1,228 @@+import { randomUUID } from "node:crypto";++import { createMongoAbility, ForbiddenError } from "@casl/ability";+import { Knex } from "knex";+import { afterAll, beforeAll, describe, expect, test } from "vitest";++import {+ ProjectType,+ ProjectVersion,+ TableName,+ TOrganizationsInsert,+ TProjectEnvironmentsInsert,+ TProjectsInsert,+ TSecretFoldersInsert,+ TSecretsV2Insert+} from "@app/db/schemas";+import { insightsDALFactory } from "@app/ee/services/insights/insights-dal";+import { insightsServiceFactory, TInsightsServiceFactoryDep } from "@app/ee/services/insights/insights-service";+import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSet,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";+import { orgDALFactory } from "@app/services/org/org-dal";+import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";+import { secretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";++import { buildOrgInsightsGateStubs, projectScopedInsightsDepStubs, usageInsightsDepStubs } from "./testUtils/insights";++declare const testDb: Knex;+declare const testKeyStore: TKeyStoreFactory;++const ORG_ID = randomUUID();+const USER_ID = randomUUID();+const suffix = randomUUID().slice(0, 8);++const projects = {+ here: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `dup-here-${suffix}` },+ elsewhere: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `dup-else-${suffix}` }+};+const projectList = Object.values(projects);++const gate = buildOrgInsightsGateStubs();++let grantedInsightsActions = [OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues];++const insightsService = insightsServiceFactory({+ ...projectScopedInsightsDepStubs,+ ...usageInsightsDepStubs,+ permissionService: {+ ...gate.permissionService,+ getOrgPermission: async () => ({+ permission: createMongoAbility<OrgPermissionSet>(+ grantedInsightsActions.map((action) => ({ action, subject: OrgPermissionSubjects.SecretsManagementInsights }))+ ),+ memberships: [],+ hasRole: () => false+ })+ } as TInsightsServiceFactoryDep["permissionService"],+ licenseService: gate.licenseService,+ orgDAL: { ...usageInsightsDepStubs.orgDAL, findById: orgDALFactory(testDb).findById },+ folderDAL: {+ ...projectScopedInsightsDepStubs.folderDAL,+ findSecretPathByFolderIds: secretFolderDALFactory(testDb).findSecretPathByFolderIds+ },+ secretV2BridgeDAL: secretV2BridgeDALFactory({ db: testDb, keyStore: testKeyStore }),+ insightsDAL: insightsDALFactory(testDb),+ keyStore: testKeyStore+});++const orgActor = {+ actor: ActorType.USER,+ actorId: USER_ID,+ actorAuthMethod: AuthMethod.EMAIL,+ actorOrgId: ORG_ID,+ orgId: ORG_ID+};++// encryptedValue is left empty so the reference filter keeps every group without a KMS round trip,+// which is why the kmsService stub is never reached.+const secret = (folderId: string, key: string, digest: string): TSecretsV2Insert & { id: string } => ({+ id: randomUUID(),+ key,+ folderId,+ secretValueBlindIndex: `project-${digest}`,+ secretValueOrgBlindIndex: `org-${digest}`+});++const clearCaches = async () => {+ await testKeyStore.deleteItem(KeyStorePrefixes.InsightsCache(ORG_ID, "org-secrets-duplication"));+};++describe("insights secrets duplication", () => {+ beforeAll(async () => {+ const orgRows: (TOrganizationsInsert & { id: string })[] = [+ { id: ORG_ID, name: `dup-${suffix}`, slug: `dup-${suffix}`, orgWideSecretValueTrackingEnabled: true }+ ];+ await testDb(TableName.Organization).insert(orgRows);++ const projectRows: (TProjectsInsert & { id: string })[] = projectList.map((p) => ({+ id: p.projectId,+ name: p.name,+ slug: p.name,+ orgId: ORG_ID,+ type: ProjectType.SecretManager,+ version: ProjectVersion.V3,+ secretBlindIndexEnabled: true+ }));+ await testDb(TableName.Project).insert(projectRows);++ const environmentRows: (TProjectEnvironmentsInsert & { id: string })[] = projectList.map((p, index) => ({+ id: p.envId,+ name: "Development",+ slug: "dev",+ position: index + 1,+ projectId: p.projectId+ }));+ await testDb(TableName.Environment).insert(environmentRows);++ const folderRows: (TSecretFoldersInsert & { id: string })[] = projectList.map((p) => ({+ id: p.folderId,+ name: "root",+ envId: p.envId,+ parentId: null+ }));+ await testDb(TableName.SecretFolder).insert(folderRows);++ await testDb(TableName.SecretV2).insert([+ // Three copies inside one project+ secret(projects.here.folderId, "LOCAL_A", "local"),+ secret(projects.here.folderId, "LOCAL_B", "local"),+ secret(projects.here.folderId, "LOCAL_C", "local"),+ // Two copies across two projects: fewer rows, but the wider spread+ secret(projects.here.folderId, "SHARED_HERE", "shared"),+ secret(projects.elsewhere.folderId, "SHARED_ELSEWHERE", "shared")+ ]);++ await clearCaches();+ });++ afterAll(async () => {+ await clearCaches();+ const folderIds = projectList.map((p) => p.folderId);+ await testDb(TableName.SecretV2).whereIn("folderId", folderIds).delete();+ await testDb(TableName.SecretFolder).whereIn("id", folderIds).delete();+ await testDb(TableName.Environment)+ .whereIn(+ "id",+ projectList.map((p) => p.envId)+ )+ .delete();+ await testDb(TableName.Project)+ .whereIn(+ "id",+ projectList.map((p) => p.projectId)+ )+ .delete();+ await testDb(TableName.Organization).where("id", ORG_ID).delete();+ });++ describe("organization scope", () => {+ test("groups a value across projects and ranks the widest spread first", async () => {+ const { result } = await insightsService.getOrgSecretsDuplication({ ...orgActor, refresh: true });++ expect(result.orgWideSecretValueTrackingEnabled).toBe(true);+ expect(result.groups.map((g) => [g.projectCount, g.locationCount, g.secrets.length])).toEqual([+ [2, 2, 2],+ [1, 1, 3]+ ]);++ const [crossProject] = result.groups;+ expect(crossProject.secrets.map((s) => [s.key, s.projectId, s.projectName, s.secretPath]).sort()).toEqual(+ [+ ["SHARED_ELSEWHERE", projects.elsewhere.projectId, projects.elsewhere.name, "/"],+ ["SHARED_HERE", projects.here.projectId, projects.here.name, "/"]+ ].sort()+ );+ });++ test("reports when the answer was computed", async () => {+ const before = Date.now();+ const { result } = await insightsService.getOrgSecretsDuplication({ ...orgActor, refresh: true });++ expect(result.computedAt).toEqual(expect.any(String));+ expect(new Date(result.computedAt as string).getTime()).toBeGreaterThanOrEqual(before - 1000);+ });++ test("answers from the cache until asked to refresh", async () => {+ await insightsService.getOrgSecretsDuplication({ ...orgActor, refresh: true });++ const extra = secret(projects.elsewhere.folderId, "LATE_ARRIVAL", "shared");+ await testDb(TableName.SecretV2).insert(extra);+ try {+ const cached = await insightsService.getOrgSecretsDuplication(orgActor);+ expect(cached.result.groups[0].secrets).toHaveLength(2);++ const refreshed = await insightsService.getOrgSecretsDuplication({ ...orgActor, refresh: true });+ expect(refreshed.result.groups[0].secrets).toHaveLength(3);+ } finally {+ await testDb(TableName.SecretV2).where("id", extra.id).delete();+ }+ });++ // The groups name every project a value lives in, so reading the insights page is not enough.+ test("refuses a viewer who may read insights but not search all secret values", async () => {+ grantedInsightsActions = [OrgPermissionSecretsManagementInsightsActions.Read];+ try {+ await expect(insightsService.getOrgSecretsDuplication({ ...orgActor, refresh: true })).rejects.toThrow(+ ForbiddenError+ );+ } finally {+ grantedInsightsActions = [OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues];+ }+ });++ test("says tracking is off rather than returning an empty answer", async () => {+ await testDb(TableName.Organization).where("id", ORG_ID).update({ orgWideSecretValueTrackingEnabled: false });+ try {+ const { result } = await insightsService.getOrgSecretsDuplication(orgActor);+ expect(result).toEqual({ orgWideSecretValueTrackingEnabled: false, groups: [], computedAt: null });+ } finally {+ await testDb(TableName.Organization).where("id", ORG_ID).update({ orgWideSecretValueTrackingEnabled: true });+ }+ });+ });+});diff --git a/backend/e2e-test/routes/v1/org-secret-value-tracking.spec.ts b/backend/e2e-test/routes/v1/org-secret-value-tracking.spec.tsindex a5dbd9f623..f7045c6e88 100644--- a/backend/e2e-test/routes/v1/org-secret-value-tracking.spec.ts+++ b/backend/e2e-test/routes/v1/org-secret-value-tracking.spec.ts@@ -1,8 +1,13 @@+import { packRules } from "@casl/ability/extra";import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";import { createSecretV2, updateSecretV2 } from "e2e-test/testUtils/secrets";import jwt from "jsonwebtoken";import { AccessScope, OrgMembershipRole, OrgMembershipStatus, SecretType, TableName } from "@app/db/schemas";+import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";const ENV = "dev";@@ -108,6 +113,78 @@ const withOwnOrg = async (}};+// An org member with no project membership. With `insightsActions` they hold a custom org role+// granting exactly those Secrets Management Insights actions; without, the built-in member role.+const createOrgMemberToken = async (+ orgId: string,+ name: string,+ insightsActions?: OrgPermissionSecretsManagementInsightsActions[]+) => {+ const username = `${name}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@example.com`;+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })+ .returning("*");+ const [orgMembership] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorUserId: user.id,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");++ if (insightsActions) {+ const [role] = await testDb(TableName.Role)+ .insert({+ name: username,+ slug: `role-${user.id}`,+ orgId,+ permissions: JSON.stringify(+ packRules([{ subject: OrgPermissionSubjects.SecretsManagementInsights, action: insightsActions }] as never)+ )+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({+ membershipId: orgMembership.id,+ role: OrgMembershipRole.Custom,+ customRoleId: role.id+ });+ } else {+ await testDb(TableName.MembershipRole).insert({+ membershipId: orgMembership.id,+ role: OrgMembershipRole.Member+ });+ }++ const [tokenVersion] = await testDb(TableName.AuthTokenSession)+ .insert({+ userId: user.id,+ ip: "127.0.0.1",+ userAgent: "test",+ accessVersion: 1,+ refreshVersion: 1,+ lastUsed: new Date()+ })+ .returning("*");++ // Signed with jsonwebtoken directly rather than through the crypto wrapper: that module is a+ // singleton the spec worker has not initialised, and this only needs the same claims the test+ // environment mints for the seeded user.+ return jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId: user.id,+ tokenVersionId: tokenVersion.id,+ authMethod: AuthMethod.EMAIL,+ organizationId: orgId,+ accessVersion: 1+ },+ process.env.AUTH_SECRET as string,+ { expiresIn: "1h" }+ );+};+describe("Org-wide secret value tracking", () => {// The walk is a queue round trip per chunk, so it takes longer than the 5s default.vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });@@ -271,49 +348,7 @@ describe("Org-wide secret value tracking", () => {});// A member of the org with no project membership at all.- const username = `value-tracking-outsider-${Date.now()}@example.com`;- const [user] = await testDb(TableName.Users)- .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })- .returning("*");- const [orgMembership] = await testDb(TableName.Membership)- .insert({- scope: AccessScope.Organization,- scopeOrgId: orgId,- actorUserId: user.id,- status: OrgMembershipStatus.Accepted,- isActive: true- })- .returning("*");- await testDb(TableName.MembershipRole).insert({- membershipId: orgMembership.id,- role: OrgMembershipRole.Member- });- const [tokenVersion] = await testDb(TableName.AuthTokenSession)- .insert({- userId: user.id,- ip: "127.0.0.1",- userAgent: "test",- accessVersion: 1,- refreshVersion: 1,- lastUsed: new Date()- })- .returning("*");-- // Signed with jsonwebtoken directly rather than through the crypto wrapper: that module is a- // singleton the spec worker has not initialised, and this only needs the same claims the test- // environment mints for the seeded user.- const outsiderToken = jwt.sign(- {- authTokenType: AuthTokenType.ACCESS_TOKEN,- userId: user.id,- tokenVersionId: tokenVersion.id,- authMethod: AuthMethod.EMAIL,- organizationId: orgId,- accessVersion: 1- },- process.env.AUTH_SECRET as string,- { expiresIn: "1h" }- );+ const outsiderToken = await createOrgMemberToken(orgId, "value-tracking-outsider");const owner = await searchByValue(shared, authToken);expect(@@ -328,6 +363,51 @@ describe("Org-wide secret value tracking", () => {expect(outsider.json().secrets).toEqual([]);});+ test("reading insights is not enough to see or start the backfill", async () => {+ const readerToken = await createOrgMemberToken(orgId, "value-tracking-reader", [+ OrgPermissionSecretsManagementInsightsActions.Read+ ]);++ expect((await enable(readerToken)).statusCode).toBe(403);++ const statusRes = await testServer.inject({+ method: "GET",+ url: "/api/v1/organization/secret-value-tracking/status",+ headers: { authorization: `Bearer ${readerToken}` }+ });+ expect(statusRes.statusCode).toBe(403);+ });++ test("searching all secret values finds hits in projects the searcher is not a member of", async () => {+ const shared = `search-all-${Date.now()}`;++ const otherProjectRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: { authorization: `Bearer ${authToken}` },+ body: { projectName: `value-tracking-search-all-${Date.now()}` }+ });+ expect(otherProjectRes.statusCode).toBe(200);+ const otherProjectId = otherProjectRes.json().project.id as string;++ await createSecretV2({+ workspaceId: otherProjectId,+ environmentSlug: ENV,+ secretPath: "/",+ key: "IN_A_PROJECT_THEY_ARE_NOT_IN",+ value: shared,+ authToken+ });++ const searcherToken = await createOrgMemberToken(orgId, "value-tracking-searcher", [+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues+ ]);++ const res = await searchByValue(shared, searcherToken);+ expect(res.statusCode).toBe(200);+ expect(res.json().secrets.map((s: { key: string }) => s.key)).toEqual(["IN_A_PROJECT_THEY_ARE_NOT_IN"]);+ });+test("a second enable while a run is moving does not start a second walk", async () =>withOwnOrg("org-value-tracking-double", async (ctx) => {await makeOrgIncomplete(ctx.orgId);diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 9b1e124f93..d361f61878 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -518,6 +518,11 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {response: {200: z.object({orgWideSecretValueTrackingEnabled: z.boolean(),+ computedAt: z+ .string()+ .datetime()+ .nullable()+ .describe("When the groups were computed. Null when detection is not enabled."),groups: z.array(z.object({projectCount: z.number(),diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex 94f61ad391..8234cd76f8 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -163,8 +163,11 @@ export const insightsServiceFactory = ({dynamicSecretLeaseDAL,insightsDAL}: TInsightsServiceFactoryDep) => {- // Gate for every org-wide aggregate: the org-level read permission plus the insights entitlement.- const assertOrgInsightsRead = async ({ actor, actorId, orgId, actorAuthMethod, actorOrgId }: TOrgInsightsDTO) => {+ // Gate for every org-wide aggregate: an org-level insights permission plus the insights entitlement.+ const assertOrgInsightsRead = async (+ { actor, actorId, orgId, actorAuthMethod, actorOrgId }: TOrgInsightsDTO,+ action = OrgPermissionSecretsManagementInsightsActions.Read+ ) => {const { permission } = await permissionService.getOrgPermission({scope: OrganizationActionScope.Any,actor,@@ -174,10 +177,7 @@ export const insightsServiceFactory = ({actorOrgId});- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionSecretsManagementInsightsActions.Read,- OrgPermissionSubjects.SecretsManagementInsights- );+ ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.SecretsManagementInsights);await assertInsightsPlanEnabled(licenseService, orgId);};@@ -484,11 +484,11 @@ 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.+ // The org-wide view of the same question the project card answers. The groups name every project+ // a value lives in, so this needs SearchAllSecretValues rather than the page's plain read, and+ // there is no per-project filter: holding it is the grant to see across projects.const getOrgSecretsDuplication = async (dto: TGetOrgSecretsDuplicationDTO) => {- await assertOrgInsightsRead(dto);+ await assertOrgInsightsRead(dto, OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues);const org = await orgDAL.findById(dto.orgId);if (!org) throw new NotFoundError({ message: `Organization with ID '${dto.orgId}' not found` });@@ -496,7 +496,7 @@ export const insightsServiceFactory = ({// 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: [] } };+ return { result: { orgWideSecretValueTrackingEnabled: false as const, groups: [], computedAt: null } };}const cacheKey = KeyStorePrefixes.InsightsCache(dto.orgId, "org-secrets-duplication");@@ -507,8 +507,9 @@ export const insightsServiceFactory = ({key: cacheKey,ttlSeconds: KeyStoreTtls.InsightsDuplicationCacheInSeconds,fetcher: async () => {+ const computedAt = new Date().toISOString();const rawGroups = await secretV2BridgeDAL.findDuplicatedSecretValuesInOrg(dto.orgId);- if (!rawGroups.length) return { orgWideSecretValueTrackingEnabled: true as const, groups: [] };+ if (!rawGroups.length) return { orgWideSecretValueTrackingEnabled: true as const, groups: [], computedAt };// 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.@@ -577,13 +578,14 @@ export const insightsServiceFactory = ({// 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 };+ return { orgWideSecretValueTrackingEnabled: true as const, groups, computedAt };}});const remainingTTL = await getCacheTtl(keyStore, cacheKey);- return { result, remainingTTL };+ // An entry cached before computedAt existed lacks it until it expires.+ return { result: { ...result, computedAt: result.computedAt ?? null }, remainingTTL };};const getSecretsDuplication = async (dto: TGetSecretsDuplicationDTO, actorDto: OrgServiceActor) => {diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.tsindex 62d5ec0571..64d00c8837 100644--- a/backend/src/ee/services/permission/org-permission.ts+++ b/backend/src/ee/services/permission/org-permission.ts@@ -159,7 +159,8 @@ export enum OrgPermissionHoneyTokenActions {export enum OrgPermissionSecretsManagementInsightsActions {Read = "read",GenerateReport = "generate-report",- DeleteReport = "delete-report"+ DeleteReport = "delete-report",+ SearchAllSecretValues = "search-all-secret-values"}export enum OrgPermissionProjectActions {@@ -624,6 +625,10 @@ const buildAdminPermission = () => {can(OrgPermissionSecretsManagementInsightsActions.Read, OrgPermissionSubjects.SecretsManagementInsights);can(OrgPermissionSecretsManagementInsightsActions.GenerateReport, OrgPermissionSubjects.SecretsManagementInsights);can(OrgPermissionSecretsManagementInsightsActions.DeleteReport, OrgPermissionSubjects.SecretsManagementInsights);+ can(+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,+ OrgPermissionSubjects.SecretsManagementInsights+ );return rules;};diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.tsindex 3055b48787..77902813a4 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts@@ -4,6 +4,7 @@ import { z } from "zod";import {ActionProjectType,+ OrganizationActionScope,ProjectMembershipRole,ProjectType,SecretsV2Schema,@@ -11,6 +12,10 @@ import {TableName,TSecretsV2} from "@app/db/schemas";+import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import {hasSecretReadValueOrDescribePermission,throwIfMissingSecretReadValueOrDescribePermission@@ -154,7 +159,10 @@ type TSecretV2BridgeServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;secretVersionTagDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;secretTagDAL: TSecretTagDALFactory;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissionFingerprint">;+ permissionService: Pick<+ TPermissionServiceFactory,+ "getProjectPermission" | "getProjectPermissionFingerprint" | "getOrgPermission"+ >;folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne" | "findBySlugs">;folderDAL: Pick<@@ -4070,9 +4078,23 @@ export const secretV2BridgeServiceFactory = ({// what keeps this from being an oracle: a value held only in projects they cannot read costs the// same work, and takes the same time, as a value held nowhere. It also bounds the query, which// would otherwise fan out across every project in the org for a value like "true".- const readableProjectIds: string[] = [];+ const { permission: orgPermission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: actor.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });+ // Holding this is the grant to see a value's locations in every project, member or not.+ const canSearchAllProjects = orgPermission.can(+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,+ OrgPermissionSubjects.SecretsManagementInsights+ );++ const readableProjectIds: string[] = canSearchAllProjects ? candidates.map((project) => project.id) : [];await Promise.all(- candidates.map(async (project) => {+ (canSearchAllProjects ? [] : candidates).map(async (project) => {try {const { permission } = await permissionService.getProjectPermission({actor: actor.type,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 812474febc..d7c8f565f4 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@@ -37,10 +37,10 @@ export const secretValueTrackingServiceFactory = ({actorOrgId: actor.orgId,scope: OrganizationActionScope.Any});- // 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.+ // Whoever may search every secret value may also turn the index on: the backfill unlocks exactly+ // the searches this permission already allows, and nothing else.ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionSecretsManagementInsightsActions.Read,+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,OrgPermissionSubjects.SecretsManagementInsights);@@ -71,7 +71,7 @@ export const secretValueTrackingServiceFactory = ({scope: OrganizationActionScope.Any});ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionSecretsManagementInsightsActions.Read,+ OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,OrgPermissionSubjects.SecretsManagementInsights);diff --git a/docs/internals/permissions/organization-permissions.mdx b/docs/internals/permissions/organization-permissions.mdxindex 67b055f7e3..53291bca94 100644--- a/docs/internals/permissions/organization-permissions.mdx+++ b/docs/internals/permissions/organization-permissions.mdx@@ -240,11 +240,12 @@ Supports conditions and permission inversion#### Subject: `secrets-management-insights`-| Action | Description |-| ----------------- | ----------------------------------------------- |-| `read` | View secrets management insights |-| `generate-report` | Generate new secrets management insight reports |-| `delete-report` | Delete secrets management insight reports |+| Action | Description |+| -------------------------- | --------------------------------------------------------------------------------------------- |+| `read` | View secrets management insights |+| `generate-report` | Generate new secrets management insight reports |+| `delete-report` | Delete secrets management insight reports |+| `search-all-secret-values` | Find secrets that share a value in any project, including projects the user isn't a member of |### Admin tools