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
refactor(insights): move secret value search to the insights router
Calvin316cace8faac
diff --git a/backend/e2e-test/testUtils/insights.ts b/backend/e2e-test/testUtils/insights.tsindex 5cdf42c389..97f049a1ad 100644--- a/backend/e2e-test/testUtils/insights.ts+++ b/backend/e2e-test/testUtils/insights.ts@@ -61,6 +61,7 @@ export const projectScopedInsightsDepStubs: Pick<countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),findDuplicatedSecretValuesInOrg: unreachable("secretV2BridgeDAL.findDuplicatedSecretValuesInOrg"),+ findSecretsWithMatchingValue: unreachable("secretV2BridgeDAL.findSecretsWithMatchingValue"),countByProject: unreachable("secretV2BridgeDAL.countByProject")},dynamicSecretDAL: {diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.tsindex 84f550df59..7a23d509a4 100644--- a/backend/src/ee/routes/v1/insights-router.ts+++ b/backend/src/ee/routes/v1/insights-router.ts@@ -22,7 +22,7 @@ import {StaticSecretsUsageSchema} from "@app/ee/services/insights/insights-schemas";import { INSIGHTS } from "@app/lib/api-docs";-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { readLimit, secretsLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";@@ -556,6 +556,58 @@ export const registerInsightsRouter = async (server: FastifyZodProvider) => {}});+ // POST rather than GET because the secret value goes in the body. A GET would put it in the URL,+ // where it lands in access logs, proxy logs and browser history.+ server.route({+ method: "POST",+ url: "/secrets/search-by-value",+ config: { rateLimit: secretsLimit },+ schema: {+ operationId: "searchOrgInsightsSecretsByValue",+ description:+ "Find every secret in the organization holding the supplied value, including secrets in projects the caller is not a member of",+ security: [{ bearerAuth: [] }],+ body: z.object({+ secretValue: z.string().min(1)+ }),+ response: {+ 200: z.object({+ secrets: z+ .object({+ key: z.string(),+ projectId: z.string(),+ projectName: z.string(),+ environment: z.object({ name: z.string(), slug: z.string() }),+ secretPath: z.string()+ })+ .array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const secrets = await server.services.insights.searchOrgSecretsByValue({+ secretValue: req.body.secretValue,+ orgId: req.permission.orgId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.SEARCH_SECRETS_BY_VALUE,+ metadata: { matchCount: secrets.length }+ }+ });++ return { secrets };+ }+ });+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 2da2fc27d0..779d310141 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -68,10 +68,7 @@ import {TSecretSyncRaw,TUpdateSecretSyncDTO} from "@app/services/secret-sync/secret-sync-types";-import {- SecretValueSearchScope,- TDuplicateSecretAttributes-} from "@app/services/secret-v2-bridge/secret-v2-bridge-types";+import { TDuplicateSecretAttributes } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";import { CertKeySource } from "@app/services/signer/signer-enums";import { TSignerExternalConfigurationInput } from "@app/services/signer/signer-types";import { TWebhookPayloads } from "@app/services/webhook/webhook-types";@@ -1283,9 +1280,6 @@ interface MoveSecretsEvent {interface SearchSecretsByValueEvent {type: EventType.SEARCH_SECRETS_BY_VALUE;metadata: {- scope: SecretValueSearchScope;- projectId?: string;- projectName?: string;matchCount: number;};}diff --git a/backend/src/ee/services/insights/insights-search-by-value.test.ts b/backend/src/ee/services/insights/insights-search-by-value.test.tsnew file mode 100644index 0000000000..013c25f528--- /dev/null+++ b/backend/src/ee/services/insights/insights-search-by-value.test.ts@@ -0,0 +1,89 @@+import { createMongoAbility, ForbiddenError } from "@casl/ability";+import { vi } from "vitest";++import {+ OrgPermissionSecretsManagementInsightsActions,+ OrgPermissionSet,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";+import { BadRequestError } from "@app/lib/errors";+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";++import { insightsServiceFactory, TInsightsServiceFactoryDep } from "./insights-service";++const dto = {+ secretValue: "value",+ orgId: "org",+ actor: ActorType.USER,+ actorId: "user",+ actorAuthMethod: AuthMethod.EMAIL,+ actorOrgId: "org"+};++const buildService = ({+ insightsActions,+ hasInsightsPlan = true+}: {+ insightsActions: OrgPermissionSecretsManagementInsightsActions[];+ hasInsightsPlan?: boolean;+}) => {+ const orgDAL = { findById: vi.fn(async () => ({ id: "org", orgWideSecretValueTrackingEnabled: true })) };+ const secretV2BridgeDAL = { findSecretsWithMatchingValue: vi.fn(async () => []) };++ const service = insightsServiceFactory({+ orgDAL,+ secretV2BridgeDAL,+ kmsService: {+ createCipherPairWithDataKey: vi.fn(async () => ({+ generateSecretBlindIndex: async () => "digest"+ }))+ },+ licenseService: { getPlan: vi.fn(async () => ({ secretAccessInsights: hasInsightsPlan })) },+ permissionService: {+ getOrgPermission: vi.fn(async () => ({+ permission: createMongoAbility<OrgPermissionSet>(+ insightsActions.map((action) => ({ action, subject: OrgPermissionSubjects.SecretsManagementInsights }))+ ),+ memberships: [],+ hasRole: () => false+ })),+ getProjectPermission: vi.fn()+ }+ } as unknown as TInsightsServiceFactoryDep);++ return { service, orgDAL, secretV2BridgeDAL };+};++describe("searchOrgSecretsByValue", () => {+ // The results name secrets in projects the caller may not be a member of, so the org-wide+ // permission is the only way in. There is no narrower per-project path.+ test("refuses a caller without Search All Secret Values before reading anything", async () => {+ const { service, orgDAL, secretV2BridgeDAL } = buildService({+ insightsActions: [OrgPermissionSecretsManagementInsightsActions.Read]+ });++ await expect(service.searchOrgSecretsByValue(dto)).rejects.toThrow(ForbiddenError);++ expect(orgDAL.findById).not.toHaveBeenCalled();+ expect(secretV2BridgeDAL.findSecretsWithMatchingValue).not.toHaveBeenCalled();+ });++ test("refuses an org whose plan does not include insights", async () => {+ const { service, secretV2BridgeDAL } = buildService({+ insightsActions: [OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues],+ hasInsightsPlan: false+ });++ await expect(service.searchOrgSecretsByValue(dto)).rejects.toThrow(BadRequestError);++ expect(secretV2BridgeDAL.findSecretsWithMatchingValue).not.toHaveBeenCalled();+ });++ test("lets a caller with Search All Secret Values on an insights plan through", async () => {+ const { service } = buildService({+ insightsActions: [OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues]+ });++ await expect(service.searchOrgSecretsByValue(dto)).resolves.toEqual([]);+ });+});diff --git a/backend/src/ee/services/insights/insights-service.test.ts b/backend/src/ee/services/insights/insights-service.test.tsindex e6877a0344..d6e4420716 100644--- a/backend/src/ee/services/insights/insights-service.test.ts+++ b/backend/src/ee/services/insights/insights-service.test.ts@@ -54,6 +54,7 @@ const projectScopedDepStubs: Pick<countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),findDuplicatedSecretValuesInOrg: unreachable("secretV2BridgeDAL.findDuplicatedSecretValuesInOrg"),+ findSecretsWithMatchingValue: unreachable("secretV2BridgeDAL.findSecretsWithMatchingValue"),countByProject: unreachable("secretV2BridgeDAL.countByProject")},dynamicSecretDAL: {diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.tsindex 60d576f72e..d2425030d0 100644--- a/backend/src/ee/services/insights/insights-service.ts+++ b/backend/src/ee/services/insights/insights-service.ts@@ -33,6 +33,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";import { TReminderDALFactory } from "@app/services/reminder/reminder-dal";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";+import { createOrgSecretBlindIndexer } from "@app/services/secret-v2-bridge/secret-blind-index-fns";import { containsSecretReference } from "@app/services/secret-v2-bridge/secret-reference-fns";import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";import { TUserDALFactory } from "@app/services/user/user-dal";@@ -62,6 +63,7 @@ import {TOrgAccessVolume,TOrgAuthMethodDistribution,TOrgInsightsDTO,+ TSearchOrgSecretsByValueDTO,TSecretsProjectWarnings,TSecretsUsageInsights,TStaticSecretsUsage@@ -84,6 +86,7 @@ export type TInsightsServiceFactoryDep = {| "countStaleByProject"| "findDuplicatedSecretValues"| "findDuplicatedSecretValuesInOrg"+ | "findSecretsWithMatchingValue"| "countByProject">;dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "countByProject">;@@ -142,6 +145,10 @@ const checkInsightsPermission = async (export const PROJECT_WARNINGS_CHUNK_SIZE = 1000;+// One value genuinely can sit in thousands of places in a large org, and the caller is chasing a+// leak rather than paginating, so the answer is bounded and the client says when it was cut off.+const SECRET_VALUE_SEARCH_LIMIT = 1000;+export const insightsServiceFactory = ({permissionService,licenseService,@@ -585,6 +592,58 @@ export const insightsServiceFactory = ({return { result, remainingTTL };};+ // Answers "is this value in use anywhere", the question someone asks when they learn a value is+ // compromised. The caller supplies the value, so nothing here reveals a value that was not already+ // known; what it reveals is the locations, in every project of the org. That is exactly what Search+ // All Secret Values grants, so it is the only way in: a narrower per-project filter would have to+ // honour every environment, path, name and tag condition a role can carry, and still leak through+ // timing whatever it filtered out after the query.+ const searchOrgSecretsByValue = async ({ secretValue, ...dto }: TSearchOrgSecretsByValueDTO) => {+ 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` });++ // A partial index answering "this value is used nowhere" is the wrong answer to give someone+ // chasing a leaked credential.+ if (!org.orgWideSecretValueTrackingEnabled) {+ throw new BadRequestError({+ message:+ "Enable org-wide secret value tracking for this organization before searching for a secret by its value"+ });+ }++ // Every project in an org shares the org data key, so one digest answers for all of them.+ const { generateOrgLevelBlindIndex } = await createOrgSecretBlindIndexer({ orgId: dto.orgId, kmsService });+ const secretValueDigest = await generateOrgLevelBlindIndex(Buffer.from(secretValue));++ const matches = await secretV2BridgeDAL.findSecretsWithMatchingValue({+ orgId: dto.orgId,+ secretValueDigest,+ limit: SECRET_VALUE_SEARCH_LIMIT+ });+ if (!matches.length) return [];++ const pathByFolderId = new Map<string, string>();+ await Promise.all(+ [...new Set(matches.map((match) => match.projectId))].map(async (projectId) => {+ const folderIds = [...new Set(matches.filter((m) => m.projectId === projectId).map((m) => m.folderId))];+ const folders = await folderDAL.findSecretPathByFolderIds(projectId, folderIds);+ folders.forEach((folder) => {+ if (folder) pathByFolderId.set(folder.id, folder.path);+ });+ })+ );++ return matches.map((match) => ({+ key: match.key,+ projectId: match.projectId,+ projectName: match.projectName,+ environment: { name: match.environmentName, slug: match.environment },+ secretPath: pathByFolderId.get(match.folderId) ?? "/"+ }));+ };+const getSecretsDuplication = async (dto: TGetSecretsDuplicationDTO, actorDto: OrgServiceActor) => {await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);@@ -880,6 +939,7 @@ export const insightsServiceFactory = ({getSummary,getSecretsDuplication,getOrgSecretsDuplication,+ searchOrgSecretsByValue,getCounts,getSecretsUsageInsights,getSecretsProjects,diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.tsindex 025f9efdd1..e92f9ad6f7 100644--- a/backend/src/ee/services/insights/insights-types.ts+++ b/backend/src/ee/services/insights/insights-types.ts@@ -48,6 +48,8 @@ export type TOrgInsightsDTO = TOrgPermission;export type TGetOrgSecretsDuplicationDTO = TOrgInsightsDTO;+export type TSearchOrgSecretsByValueDTO = TOrgInsightsDTO & { secretValue: string };+export type TGetSecretsProjectWarningsDTO = TOrgInsightsDTO & {offset: number;limit: number;diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.tsindex 8ed03c99fa..1008481523 100644--- a/backend/src/server/routes/v4/secret-router.ts+++ b/backend/src/server/routes/v4/secret-router.ts@@ -20,7 +20,7 @@ import {SecretImportReferencesBehavior,SecretProtectionType} from "@app/services/secret/secret-types";-import { SecretUpdateMode, SecretValueSearchScope } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";+import { SecretUpdateMode } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { SanitizedTagSchema, secretRawSchema } from "../sanitizedSchemas";@@ -1628,79 +1628,4 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {return message;}});-- // POST rather than GET because the secret value goes in the body. A GET would put it in the URL,- // where it lands in access logs, proxy logs and browser history.- server.route({- method: "POST",- url: "/search-by-value",- config: {- rateLimit: secretsLimit- },- schema: {- hide: false,- operationId: "searchByValue",- tags: [ApiDocsTags.Secrets],- description:- "Find every secret holding the supplied value, across the organization or within one project. Requires the Search All Secret Values organization permission, and returns matches in every project, including ones the caller is not a member of.",- security: [{ bearerAuth: [] }],- body: z- .object({- secretValue: z.string().min(1).describe("The secret value to look for."),- scope: z- .nativeEnum(SecretValueSearchScope)- .default(SecretValueSearchScope.Organization)- .describe("Whether to search the whole organization or a single project."),- projectId: z.string().uuid().optional().describe("The project to search. Required when scope is project.")- })- .superRefine((data, ctx) => {- if (data.scope === SecretValueSearchScope.Project && !data.projectId) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["projectId"],- message: "projectId is required when scope is project"- });- }- }),- response: {- 200: z.object({- secrets: z- .object({- key: z.string(),- projectId: z.string(),- projectName: z.string(),- environment: z.object({ name: z.string(), slug: z.string() }),- secretPath: z.string()- })- .array()- })- }- },- onRequest: verifyAuth([AuthMode.JWT]),- handler: async (req) => {- const { secretValue, scope, projectId } = req.body;- const { secrets, searchedProject } = await server.services.secret.findSecretsByValue(- scope === SecretValueSearchScope.Project && projectId- ? { secretValue, scope, projectId }- : { secretValue, scope: SecretValueSearchScope.Organization },- req.permission- );-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- event: {- type: EventType.SEARCH_SECRETS_BY_VALUE,- metadata: {- scope,- projectId: searchedProject?.id,- projectName: searchedProject?.name,- matchCount: secrets.length- }- }- });-- return { secrets };- }- });};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 1678d7f6b8..4d4746843a 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@@ -1531,18 +1531,13 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {}};- // Finds secrets holding the given value within the given projects. The caller narrows those to- // what the actor may read BEFORE calling, so an unreadable project costs nothing here and cannot- // be inferred from how long this takes.const findSecretsWithMatchingValue = async ({orgId,- projectIds,secretValueDigest,limit}: {orgId: string;- projectIds: string[];secretValueDigest: string;limit: number;},@@ -1554,6 +1549,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {.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).where(`${TableName.SecretV2}.secretValueOrgBlindIndex`, secretValueDigest).whereNull(`${TableName.Environment}.deleteAfter`).whereNull(`${TableName.Project}.deleteAfter`)@@ -1568,7 +1564,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {db.ref("name").withSchema(TableName.Project).as("projectName"));- return await query.whereIn(`${TableName.Project}.id`, projectIds).limit(limit);+ return await query.limit(limit);} catch (error) {throw new DatabaseError({ error, name: "findSecretsWithMatchingValue" });}diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-search-by-value.test.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-search-by-value.test.tsdeleted file mode 100644index f7e087d36c..0000000000--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-search-by-value.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { createMongoAbility, ForbiddenError } from "@casl/ability";-import { vi } from "vitest";--import {- OrgPermissionSecretsManagementInsightsActions,- OrgPermissionSet,- OrgPermissionSubjects-} from "@app/ee/services/permission/org-permission";-import { ActorType, AuthMethod } from "@app/services/auth/auth-type";--import { secretV2BridgeServiceFactory } from "./secret-v2-bridge-service";-import { SecretValueSearchScope } from "./secret-v2-bridge-types";--const actor = {- type: ActorType.USER,- id: "user",- authMethod: AuthMethod.EMAIL,- orgId: "org",- rootOrgId: "org",- parentOrgId: "org"-};--const buildService = (insightsActions: OrgPermissionSecretsManagementInsightsActions[]) => {- const orgDAL = { findById: vi.fn(async () => ({ id: "org", orgWideSecretValueTrackingEnabled: true })) };- const projectDAL = { find: vi.fn(async () => []), findById: vi.fn() };-- const service = secretV2BridgeServiceFactory({- orgDAL,- projectDAL,- permissionService: {- getOrgPermission: vi.fn(async () => ({- permission: createMongoAbility<OrgPermissionSet>(- insightsActions.map((action) => ({ action, subject: OrgPermissionSubjects.SecretsManagementInsights }))- ),- memberships: [],- hasRole: () => false- })),- getProjectPermission: vi.fn(),- getProjectPermissionFingerprint: vi.fn()- }- } as unknown as Parameters<typeof secretV2BridgeServiceFactory>[0]);-- return { service, orgDAL, projectDAL };-};--describe("findSecretsByValue", () => {- // The results name secrets in projects the caller may not be a member of, so the org-wide- // permission is the only way in. There is no narrower per-project path.- test("refuses a caller without Search All Secret Values before reading anything", async () => {- const { service, orgDAL, projectDAL } = buildService([OrgPermissionSecretsManagementInsightsActions.Read]);-- await expect(- service.findSecretsByValue({ secretValue: "value", scope: SecretValueSearchScope.Organization }, actor)- ).rejects.toThrow(ForbiddenError);-- expect(orgDAL.findById).not.toHaveBeenCalled();- expect(projectDAL.find).not.toHaveBeenCalled();- });-- test("lets a caller with Search All Secret Values through", async () => {- const { service } = buildService([OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues]);-- await expect(- service.findSecretsByValue({ secretValue: "value", scope: SecretValueSearchScope.Organization }, actor)- ).resolves.toEqual({ secrets: [] });- });-});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 c47d9fff62..b42b3ff1f7 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,18 +4,12 @@ import { z } from "zod";import {ActionProjectType,- OrganizationActionScope,ProjectMembershipRole,- ProjectType,SecretsV2Schema,SecretType,TableName,TSecretsV2} from "@app/db/schemas";-import {- OrgPermissionSecretsManagementInsightsActions,- OrgPermissionSubjects-} from "@app/ee/services/permission/org-permission";import {hasSecretReadValueOrDescribePermission,throwIfMissingSecretReadValueOrDescribePermission@@ -52,7 +46,6 @@ import {SecretCacheAccessResult,SecretEtagMissReason} from "@app/lib/telemetry/metrics";-import { OrgServiceActor } from "@app/lib/types";import { ActorType } from "../auth/auth-type";import { TCommitResourceChangeDTO, TFolderCommitServiceFactory } from "../folder-commit/folder-commit-service";@@ -83,7 +76,7 @@ import {} from "../secret-validation-rule/secret-validation-rule-errors";import { TSecretValidationRuleServiceFactory } from "../secret-validation-rule/secret-validation-rule-service";import { TValidateSecretsDTO } from "../secret-validation-rule/secret-validation-rule-types";-import { createOrgSecretBlindIndexer, createSecretBlindIndexer } from "./secret-blind-index-fns";+import { createSecretBlindIndexer } from "./secret-blind-index-fns";import { secretMetadataServiceFactory } from "./secret-metadata-service";import { expandSecretReferencesFactory, getAllSecretReferences } from "./secret-reference-fns";import {@@ -108,7 +101,6 @@ import {} from "./secret-v2-bridge-fns";import {SecretUpdateMode,- SecretValueSearchScope,TBackFillSecretReferencesDTO,TCreateManySecretDTO,TCreateSecretDTO,@@ -116,7 +108,6 @@ import {TDeleteSecretDTO,TDispatchSecretCreateSideEffectsDTO,TDispatchSecretMoveSideEffectsDTO,- TFindSecretsByValueDTO,TGetAccessibleSecretsDTO,TGetASecretDTO,TGetSecretReferencesTreeDTO,@@ -160,10 +151,7 @@ type TSecretV2BridgeServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;secretVersionTagDAL: Pick<TSecretVersionV2TagDALFactory, "insertMany">;secretTagDAL: TSecretTagDALFactory;- permissionService: Pick<- TPermissionServiceFactory,- "getProjectPermission" | "getProjectPermissionFingerprint" | "getOrgPermission"- >;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissionFingerprint">;folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne" | "findBySlugs">;folderDAL: Pick<@@ -201,7 +189,7 @@ type TSecretV2BridgeServiceFactoryDep = {reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "validateSecrets">;projectFolderGrantDAL: Pick<TProjectFolderGrantDALFactory, "find">;- orgDAL: Pick<TOrgDALFactory, "findOrgById" | "findById">;+ orgDAL: Pick<TOrgDALFactory, "findOrgById">;};export type TSecretV2BridgeServiceFactory = ReturnType<typeof secretV2BridgeServiceFactory>;@@ -209,10 +197,6 @@ export type TSecretV2BridgeServiceFactory = ReturnType<typeof secretV2BridgeServ/** This service is a bridge from our old architecture towards the new architecture*/-// One value genuinely can sit in thousands of places in a large org, and the caller is chasing a-// leak rather than paginating, so the answer is bounded and the response says when it was cut off.-const SECRET_VALUE_SEARCH_LIMIT = 1000;-export const secretV2BridgeServiceFactory = ({secretDAL,projectDAL,@@ -4028,92 +4012,6 @@ export const secretV2BridgeServiceFactory = ({};};- // Answers "is this value in use anywhere", the question someone asks when they learn a value is- // compromised. The caller supplies the value, so nothing here reveals a value that was not already- // known; what it reveals is the locations, in every project of the org. That is exactly what Search- // All Secret Values grants, so it is the only way in: a narrower per-project filter would have to- // honour every environment, path, name and tag condition a role can carry, and still leak through- // timing whatever it filtered out after the query.- const findSecretsByValue = async (dto: TFindSecretsByValueDTO, actor: OrgServiceActor) => {- const { permission } = await permissionService.getOrgPermission({- actor: actor.type,- actorId: actor.id,- orgId: actor.orgId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- scope: OrganizationActionScope.Any- });- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionSecretsManagementInsightsActions.SearchAllSecretValues,- OrgPermissionSubjects.SecretsManagementInsights- );-- // findById rather than findOrgById: findOrgById takes no tx and reads the replica, which is the- // deadlock trigger CODE_QUALITY.md warns about if this ever moves inside a transaction.- const org = await orgDAL.findById(actor.orgId);- if (!org) throw new NotFoundError({ message: `Organization with ID '${actor.orgId}' not found` });-- // Both scopes match on the org digest, so both are only trustworthy once the org is complete.- // A partial index answering "this value is used nowhere" is the wrong answer to give someone- // chasing a leaked credential.- if (!org.orgWideSecretValueTrackingEnabled) {- throw new BadRequestError({- message:- "Enable org-wide secret value tracking for this organization before searching for a secret by its value"- });- }-- const candidates =- dto.scope === SecretValueSearchScope.Project- ? await projectDAL.find({ id: dto.projectId, orgId: actor.orgId, type: ProjectType.SecretManager })- : await projectDAL.find({ orgId: actor.orgId, type: ProjectType.SecretManager });-- if (dto.scope === SecretValueSearchScope.Project && !candidates.length) {- throw new NotFoundError({ message: `Secrets management project with ID '${dto.projectId}' not found` });- }-- // Named so the audit entry for a project-scoped search can say which project, not just its id.- const searchedProject =- dto.scope === SecretValueSearchScope.Project ? { id: candidates[0].id, name: candidates[0].name } : undefined;-- const projectIds = candidates.map((project) => project.id);- if (!projectIds.length) return { secrets: [], searchedProject };-- // Every project in an org shares the org data key, so one digest answers for all of them.- const { generateOrgLevelBlindIndex } = await createOrgSecretBlindIndexer({ orgId: actor.orgId, kmsService });- const secretValueDigest = await generateOrgLevelBlindIndex(Buffer.from(dto.secretValue));-- const visible = await secretDAL.findSecretsWithMatchingValue({- orgId: actor.orgId,- projectIds,- secretValueDigest,- limit: SECRET_VALUE_SEARCH_LIMIT- });- if (!visible.length) return { secrets: [], searchedProject };-- const pathsByProject = await Promise.all(- [...new Set(visible.map((match) => match.projectId))].map((projectId) => {- const folderIds = [...new Set(visible.filter((m) => m.projectId === projectId).map((m) => m.folderId))];- return folderDAL.findSecretPathByFolderIds(projectId, folderIds);- })- );- const pathByFolderId = new Map<string, string>();- pathsByProject.flat().forEach((folder) => {- if (folder) pathByFolderId.set(folder.id, folder.path);- });-- return {- searchedProject,- secrets: visible.map((match) => ({- key: match.key,- projectId: match.projectId,- projectName: match.projectName,- environment: { name: match.environmentName, slug: match.environment },- secretPath: pathByFolderId.get(match.folderId) ?? "/"- }))- };- };-return {createSecret: withSecretMetrics(createSecret, { duration: "write", write: "create" }),deleteSecret: withSecretMetrics(deleteSecret, { duration: "delete", write: "delete" }),@@ -4139,7 +4037,6 @@ export const secretV2BridgeServiceFactory = ({getSecretMetadata,getSecretVersionsByIds,findSecretIdsByFolderIdAndKeys,- findSecretsByValue,$validateSecretReferences,redactSecretVersionValue};diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.tsindex 1a92f5bafc..e67d302161 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts@@ -187,15 +187,6 @@ export type TGetSecretVersionsDTO = Omit<TProjectPermission, "projectId"> & {export type TSecretReference = { environment: string; secretPath: string; secretKey: string };-export enum SecretValueSearchScope {- Organization = "organization",- Project = "project"-}--export type TFindSecretsByValueDTO = {- secretValue: string;-} & ({ scope: SecretValueSearchScope.Organization } | { scope: SecretValueSearchScope.Project; projectId: string });-export type TFnSecretBulkInsert = {folderId: string;orgId: string;diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.tsindex 49d65eef0a..4c2565c69b 100644--- a/backend/src/services/secret/secret-service.ts+++ b/backend/src/services/secret/secret-service.ts@@ -44,7 +44,6 @@ import { OrgServiceActor } from "@app/lib/types";import {SecretUpdateMode,TDuplicateSecretDTO,- TFindSecretsByValueDTO,TGetSecretReferencesDTO,TGetSecretsRawByFolderMappingsDTO} from "@app/services/secret-v2-bridge/secret-v2-bridge-types";@@ -3906,9 +3905,6 @@ export const secretServiceFactory = ({return revokedSecretIds;};- const findSecretsByValue = (dto: TFindSecretsByValueDTO, actor: OrgServiceActor) =>- secretV2BridgeService.findSecretsByValue(dto, actor);-return {attachTags,detachTags,@@ -3946,7 +3942,6 @@ export const secretServiceFactory = ({getChangeVersions,redactSecretVersionValue,getSecretReferenceDependencyTree,- getSecretsWithRevokedProjectFolderGrant,- findSecretsByValue+ getSecretsWithRevokedProjectFolderGrant};};diff --git a/frontend/src/components/secrets/GoToSecretFolderButton.tsx b/frontend/src/components/secrets/GoToSecretButton.tsxsimilarity index 100%rename from frontend/src/components/secrets/GoToSecretFolderButton.tsxrename to frontend/src/components/secrets/GoToSecretButton.tsx