Skip to content

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

refactor(blind-index): move the value search onto the secrets management API

Calvin626a6d04146f
diff --git a/backend/e2e-test/routes/v1/insights-secret-value-search.spec.ts b/backend/e2e-test/routes/v1/insights-secret-value-search.spec.ts
deleted file mode 100644
index dc0e74e798..0000000000
--- a/backend/e2e-test/routes/v1/insights-secret-value-search.spec.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
-import { createFolder } from "e2e-test/testUtils/folders";
-import { createSecretV2, deleteSecretV2, updateSecretV2 } from "e2e-test/testUtils/secrets";
-
-const DEV_ENV = "dev";
-const PROD_ENV = "prod";
-
-type TFoundSecret = {
- key: string;
- projectId: string;
- projectName: string;
- environment: { name: string; slug: string };
- secretPath: string;
-};
-
-const searchByValue = async (secretValue: string, authToken: string) => {
- const res = await testServer.inject({
- method: "POST",
- url: "/api/v1/insights/secrets/search-by-value",
- headers: { authorization: `Bearer ${authToken}` },
- body: { secretValue }
- });
- expect(res.statusCode).toBe(200);
- return res.json().secrets as TFoundSecret[];
-};
-
-const at = (secrets: TFoundSecret[]) =>
- secrets.map((s) => `${s.environment.slug}${s.secretPath}${s.key}`).sort();
-
-describe("Finding a secret by its value across an organization", () => {
- let orgId: string;
- let projectId: string;
- let authToken: string;
- let cleanup: () => Promise<void>;
-
- beforeAll(async () => {
- ({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("org-secret-search-e2e"));
- });
-
- afterAll(async () => {
- await cleanup();
- });
-
- test("a value that nothing holds is not found", async () => {
- expect(await searchByValue("a-value-no-secret-holds", authToken)).toEqual([]);
- });
-
- test("a value is found at the one place that holds it", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "FINDABLE",
- value: "find-me-please",
- authToken
- });
-
- const found = await searchByValue("find-me-please", authToken);
-
- expect(found).toHaveLength(1);
- expect(found[0]).toMatchObject({
- key: "FINDABLE",
- projectId,
- environment: { slug: DEV_ENV },
- secretPath: "/"
- });
- });
-
- // The question this API exists to answer: a value is believed compromised, so where else is it?
- test("a value copied across environments and folders is found in every one of them", async () => {
- await createFolder({ workspaceId: projectId, environmentSlug: DEV_ENV, secretPath: "/", name: "nested", authToken });
-
- const shared = "the-same-value-everywhere";
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "COPY_ROOT",
- value: shared,
- authToken
- });
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/nested",
- key: "COPY_NESTED",
- value: shared,
- authToken
- });
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "COPY_PROD",
- value: shared,
- authToken
- });
-
- expect(at(await searchByValue(shared, authToken))).toEqual([
- `${DEV_ENV}/COPY_ROOT`,
- `${DEV_ENV}/nestedCOPY_NESTED`,
- `${PROD_ENV}/COPY_PROD`
- ]);
- });
-
- test("a near-miss value is not found", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "EXACT",
- value: "case-sensitive-value",
- authToken
- });
-
- expect(await searchByValue("Case-Sensitive-Value", authToken)).toEqual([]);
- expect(await searchByValue("case-sensitive-valu", authToken)).toEqual([]);
- });
-
- test("a rotated value stops being found and the new one starts", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "ROTATES",
- value: "the-old-value",
- authToken
- });
- expect(await searchByValue("the-old-value", authToken)).toHaveLength(1);
-
- await updateSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "ROTATES",
- value: "the-new-value",
- authToken
- });
-
- expect(await searchByValue("the-old-value", authToken)).toEqual([]);
- expect(await searchByValue("the-new-value", authToken)).toHaveLength(1);
- });
-
- // A rename carries no value, so the secret must still be findable by the value it still holds.
- test("renaming a secret does not stop it being found by its value", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "BEFORE_RENAME",
- value: "survives-a-rename",
- authToken
- });
-
- await updateSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "BEFORE_RENAME",
- newKey: "AFTER_RENAME",
- authToken
- });
-
- const found = await searchByValue("survives-a-rename", authToken);
- expect(found).toHaveLength(1);
- expect(found[0].key).toBe("AFTER_RENAME");
- });
-
- test("a deleted secret stops being found", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "TEMPORARY",
- value: "here-then-gone",
- authToken
- });
- expect(await searchByValue("here-then-gone", authToken)).toHaveLength(1);
-
- await deleteSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "TEMPORARY",
- authToken
- });
-
- expect(await searchByValue("here-then-gone", authToken)).toEqual([]);
- });
-
- // This is the test the org-scoped index exists for. The project-scoped digest cannot match across
- // projects, so a search that found only the first project would pass every test above and still be
- // broken for the case the feature was built for.
- test("a value held in a second project of the same org is found in both", async () => {
- const shared = `across-projects-${Date.now()}`;
-
- const secondProjectRes = await testServer.inject({
- method: "POST",
- url: "/api/v1/projects",
- headers: { authorization: `Bearer ${authToken}` },
- body: { projectName: "org-secret-search-e2e-second" }
- });
- expect(secondProjectRes.statusCode).toBe(200);
- const secondProjectId = secondProjectRes.json().project.id as string;
-
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "IN_FIRST_PROJECT",
- value: shared,
- authToken
- });
- await createSecretV2({
- workspaceId: secondProjectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "IN_SECOND_PROJECT",
- value: shared,
- authToken
- });
-
- const found = await searchByValue(shared, authToken);
-
- expect(found.map((f) => f.key).sort()).toEqual(["IN_FIRST_PROJECT", "IN_SECOND_PROJECT"]);
- expect(new Set(found.map((f) => f.projectId))).toEqual(new Set([projectId, secondProjectId]));
- });
-
- // The org digest is keyed by the org data key, so one org's values must never match another's.
- test("a value held in another organization is not found", async () => {
- const other = await createIsolatedOrgAndProject("org-secret-search-e2e-other");
- try {
- const value = "value-in-a-different-org";
- await createSecretV2({
- workspaceId: other.projectId,
- environmentSlug: DEV_ENV,
- secretPath: "/",
- key: "OTHER_ORG",
- value,
- authToken: other.authToken
- });
-
- expect(await searchByValue(value, other.authToken)).toHaveLength(1);
- expect(await searchByValue(value, authToken)).toEqual([]);
- expect(other.orgId).not.toBe(orgId);
- } finally {
- await other.cleanup();
- }
- });
-});
diff --git a/backend/e2e-test/routes/v3/secrets-management.spec.ts b/backend/e2e-test/routes/v3/secrets-management.spec.ts
index 26d411ba3d..502e365d2b 100644
--- a/backend/e2e-test/routes/v3/secrets-management.spec.ts
+++ b/backend/e2e-test/routes/v3/secrets-management.spec.ts
@@ -1,33 +1,68 @@
import { createFakeWebhookServer, TFakeWebhookServer } from "e2e-test/fakes/webhook-destination";
import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
-import { createSecretV2 } from "e2e-test/testUtils/secrets";
+import { createFolder } from "e2e-test/testUtils/folders";
+import { createSecretV2, deleteSecretV2, updateSecretV2 } from "e2e-test/testUtils/secrets";
import { createWebhook, waitForWebhookRun } from "e2e-test/testUtils/webhooks";
const ENV = "dev";
+const PROD_ENV = "prod";
+
+type TFoundSecret = {
+ key: string;
+ projectId: string;
+ projectName: string;
+ environment: { name: string; slug: string };
+ secretPath: string;
+};
+
+const searchByValue = async (
+ secretValue: string,
+ authToken: string,
+ scope?: { scope: "project"; projectId: string }
+) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: "/api/v4/secrets/search-by-value",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { secretValue, ...scope }
+ });
+ expect(res.statusCode).toBe(200);
+ return res.json().secrets as TFoundSecret[];
+};
+
+const at = (secrets: TFoundSecret[]) => secrets.map((s) => `${s.environment.slug}${s.secretPath}${s.key}`).sort();
// Covers domain-level side effects of secrets management actions, as distinct from the routes'
// own CRUD behavior (secrets.spec.ts / secrets-v2.spec.ts). A webhook is the observable signal
// used here, but the thing under test is that the domain action fires the event, not webhook
// delivery mechanics.
describe("Secrets management", () => {
- describe("Secret changes trigger webhook events", () => {
- // A run is a queue round trip (1s debounce delay + the HTTP attempt), so it takes longer
- // than the 5s default.
- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });
+ // A webhook run is a queue round trip (1s debounce delay + the HTTP attempt), so it takes longer
+ // than the 5s default.
+ vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });
+
+ let orgId: string;
+ let projectId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("secrets-management-e2e"));
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ });
- let projectId: string;
- let authToken: string;
- let cleanup: () => Promise<void>;
+ describe("Secret changes trigger webhook events", () => {
let fakeWebhookServer: TFakeWebhookServer;
beforeAll(async () => {
- ({ projectId, authToken, cleanup } = await createIsolatedOrgAndProject("secrets-management-e2e"));
fakeWebhookServer = await createFakeWebhookServer();
});
afterAll(async () => {
await fakeWebhookServer.stop();
- await cleanup();
});
test("a secret change enqueues and runs a webhook delivery", async () => {
@@ -64,4 +99,251 @@ describe("Secrets management", () => {
expect(ranWebhook.lastStatus).toBe("success");
});
});
+
+ describe("Finding a secret by its value", () => {
+ test("a value that nothing holds is not found", async () => {
+ expect(await searchByValue("a-value-no-secret-holds", authToken)).toEqual([]);
+ });
+
+ test("a value is found at the one place that holds it", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "FINDABLE",
+ value: "find-me-please",
+ authToken
+ });
+
+ const found = await searchByValue("find-me-please", authToken);
+
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({
+ key: "FINDABLE",
+ projectId,
+ environment: { slug: ENV },
+ secretPath: "/"
+ });
+ });
+
+ // The question this API exists to answer: a value is believed compromised, so where else is it?
+ test("a value copied across environments and folders is found in every one of them", async () => {
+ await createFolder({ workspaceId: projectId, environmentSlug: ENV, secretPath: "/", name: "nested", authToken });
+
+ const shared = "the-same-value-everywhere";
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "COPY_ROOT",
+ value: shared,
+ authToken
+ });
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/nested",
+ key: "COPY_NESTED",
+ value: shared,
+ authToken
+ });
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: PROD_ENV,
+ secretPath: "/",
+ key: "COPY_PROD",
+ value: shared,
+ authToken
+ });
+
+ expect(at(await searchByValue(shared, authToken))).toEqual([
+ `${ENV}/COPY_ROOT`,
+ `${ENV}/nestedCOPY_NESTED`,
+ `${PROD_ENV}/COPY_PROD`
+ ]);
+ });
+
+ test("a near-miss value is not found", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "EXACT",
+ value: "case-sensitive-value",
+ authToken
+ });
+
+ expect(await searchByValue("Case-Sensitive-Value", authToken)).toEqual([]);
+ expect(await searchByValue("case-sensitive-valu", authToken)).toEqual([]);
+ });
+
+ // Whitespace is part of the value, not decoration around it, so the search hashes what it was
+ // given and never trims it. Note the asymmetry with writes: the secret write API has always
+ // trimmed surrounding whitespace off a submitted value (see secretValue in v4/secret-router.ts),
+ // so a value typed with padding is stored, and therefore found, under its trimmed form. Inner
+ // whitespace survives both sides.
+ test("whitespace counts as part of the value", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "INNER_SPACE",
+ value: "two spaces",
+ authToken
+ });
+
+ expect(await searchByValue("two spaces", authToken)).toEqual([]);
+ expect((await searchByValue("two spaces", authToken)).map((s) => s.key)).toEqual(["INNER_SPACE"]);
+
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "PADDED",
+ value: " padded-value ",
+ authToken
+ });
+
+ // The search does not trim its own input, so padding the query stops it matching.
+ expect(await searchByValue(" padded-value ", authToken)).toEqual([]);
+ expect(await searchByValue(" padded-value ", authToken)).toEqual([]);
+
+ const found = await searchByValue("padded-value", authToken);
+ expect(found).toHaveLength(1);
+ expect(found[0].key).toBe("PADDED");
+ });
+
+ test("a rotated value stops being found and the new one starts", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "ROTATES",
+ value: "the-old-value",
+ authToken
+ });
+ expect(await searchByValue("the-old-value", authToken)).toHaveLength(1);
+
+ await updateSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "ROTATES",
+ value: "the-new-value",
+ authToken
+ });
+
+ expect(await searchByValue("the-old-value", authToken)).toEqual([]);
+ expect(await searchByValue("the-new-value", authToken)).toHaveLength(1);
+ });
+
+ // A rename carries no value, so the secret must still be findable by the value it still holds.
+ test("renaming a secret does not stop it being found by its value", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "BEFORE_RENAME",
+ value: "survives-a-rename",
+ authToken
+ });
+
+ await updateSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "BEFORE_RENAME",
+ newKey: "AFTER_RENAME",
+ authToken
+ });
+
+ const found = await searchByValue("survives-a-rename", authToken);
+ expect(found).toHaveLength(1);
+ expect(found[0].key).toBe("AFTER_RENAME");
+ });
+
+ test("a deleted secret stops being found", async () => {
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "TEMPORARY",
+ value: "here-then-gone",
+ authToken
+ });
+ expect(await searchByValue("here-then-gone", authToken)).toHaveLength(1);
+
+ await deleteSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "TEMPORARY",
+ authToken
+ });
+
+ expect(await searchByValue("here-then-gone", authToken)).toEqual([]);
+ });
+
+ // This is the test the org-scoped index exists for. The project-scoped digest cannot match across
+ // projects, so a search that found only the first project would pass every test above and still be
+ // broken for the case the feature was built for.
+ test("a value held in a second project of the same org is found in both, and project scope narrows it", async () => {
+ const shared = `across-projects-${Date.now()}`;
+
+ const secondProjectRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/projects",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { projectName: "secrets-management-e2e-second" }
+ });
+ expect(secondProjectRes.statusCode).toBe(200);
+ const secondProjectId = secondProjectRes.json().project.id as string;
+
+ await createSecretV2({
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "IN_FIRST_PROJECT",
+ value: shared,
+ authToken
+ });
+ await createSecretV2({
+ workspaceId: secondProjectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "IN_SECOND_PROJECT",
+ value: shared,
+ authToken
+ });
+
+ const found = await searchByValue(shared, authToken);
+ expect(found.map((f) => f.key).sort()).toEqual(["IN_FIRST_PROJECT", "IN_SECOND_PROJECT"]);
+ expect(new Set(found.map((f) => f.projectId))).toEqual(new Set([projectId, secondProjectId]));
+
+ const inSecondOnly = await searchByValue(shared, authToken, { scope: "project", projectId: secondProjectId });
+ expect(inSecondOnly.map((f) => f.key)).toEqual(["IN_SECOND_PROJECT"]);
+ });
+
+ // The org digest is keyed by the org data key, so one org's values must never match another's.
+ test("a value held in another organization is not found", async () => {
+ const other = await createIsolatedOrgAndProject("secrets-management-e2e-other");
+ try {
+ const value = "value-in-a-different-org";
+ await createSecretV2({
+ workspaceId: other.projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ key: "OTHER_ORG",
+ value,
+ authToken: other.authToken
+ });
+
+ expect(await searchByValue(value, other.authToken)).toHaveLength(1);
+ expect(await searchByValue(value, authToken)).toEqual([]);
+ expect(other.orgId).not.toBe(orgId);
+ } finally {
+ await other.cleanup();
+ }
+ });
+ });
});
diff --git a/backend/e2e-test/testUtils/insights.ts b/backend/e2e-test/testUtils/insights.ts
index 0fef6ea21a..2312e7015e 100644
--- a/backend/e2e-test/testUtils/insights.ts
+++ b/backend/e2e-test/testUtils/insights.ts
@@ -63,7 +63,6 @@ export const projectScopedInsightsDepStubs: Pick<
findStaleByProject: unreachable("secretV2BridgeDAL.findStaleByProject"),
countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),
findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),
- findSecretsByOrgBlindIndex: unreachable("secretV2BridgeDAL.findSecretsByOrgBlindIndex"),
countByProject: unreachable("secretV2BridgeDAL.countByProject")
},
dynamicSecretDAL: {
@@ -76,8 +75,7 @@ export const projectScopedInsightsDepStubs: Pick<
getBotKey: unreachable("projectBotService.getBotKey")
},
projectDAL: {
- findById: unreachable("projectDAL.findById"),
- find: unreachable("projectDAL.find")
+ findById: unreachable("projectDAL.findById")
},
userDAL: {
find: unreachable("userDAL.find")
diff --git a/backend/src/ee/routes/v1/insights-router.ts b/backend/src/ee/routes/v1/insights-router.ts
index c7429d4c7b..a87b827f8e 100644
--- a/backend/src/ee/routes/v1/insights-router.ts
+++ b/backend/src/ee/routes/v1/insights-router.ts
@@ -124,56 +124,6 @@ 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: writeLimit
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- schema: {
- operationId: "searchInsightsSecretsByValue",
- description:
- "Find every secret in the organization whose value matches the one supplied, in projects the caller can read.",
- security: [{ bearerAuth: [] }],
- body: z.object({
- secretValue: z.string().min(1).max(10_000).describe("The secret value to look for.")
- }),
- 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()
- })
- }
- },
- handler: async (req) => {
- const result = await server.services.insights.findSecretsByValue(
- { secretValue: req.body.secretValue },
- req.permission
- );
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.SEARCH_INSIGHTS_SECRETS_BY_VALUE,
- metadata: { matchCount: result.secrets.length }
- }
- });
-
- return result;
- }
- });
-
server.route({
method: "GET",
url: "/secrets/projects",
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 2a189cf29d..6f0c25b142 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -64,7 +64,10 @@ import {
TSecretSyncRaw,
TUpdateSecretSyncDTO
} from "@app/services/secret-sync/secret-sync-types";
-import { TDuplicateSecretAttributes } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
+import {
+ SecretValueSearchScope,
+ 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";
@@ -200,6 +203,7 @@ export enum EventType {
UPDATE_SECRET = "update-secret",
UPDATE_SECRETS = "update-secrets",
MOVE_SECRETS = "move-secrets",
+ SEARCH_SECRETS_BY_VALUE = "search-secrets-by-value",
DUPLICATE_SECRET = "duplicate-secret",
DELETE_SECRET = "delete-secret",
DELETE_SECRETS = "delete-secrets",
@@ -708,7 +712,6 @@ 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",
- SEARCH_INSIGHTS_SECRETS_BY_VALUE = "search-insights-secrets-by-value",
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",
@@ -1266,6 +1269,17 @@ interface MoveSecretsEvent {
};
}
+// The searched value is never recorded, only how many places it was found in. An audit log is read by
+// more people than the search itself is run by, so logging the value would widen who learns it.
+interface SearchSecretsByValueEvent {
+ type: EventType.SEARCH_SECRETS_BY_VALUE;
+ metadata: {
+ scope: SecretValueSearchScope;
+ projectId?: string;
+ matchCount: number;
+ };
+}
+
interface DuplicateSecretEvent {
type: EventType.DUPLICATE_SECRET;
metadata: {
@@ -5859,15 +5873,6 @@ interface ViewSecretManagementInsightsSummaryEvent {
};
}
-// The searched value is never recorded, only how many places it was found in. An audit log is read by
-// more people than the search itself is run by, so logging the value would widen who learns it.
-interface SearchInsightsSecretsByValueEvent {
- type: EventType.SEARCH_INSIGHTS_SECRETS_BY_VALUE;
- metadata: {
- matchCount: number;
- };
-}
-
interface ViewInsightsSecretsDuplicationEvent {
type: EventType.VIEW_INSIGHTS_SECRETS_DUPLICATION;
metadata: {
@@ -7792,6 +7797,7 @@ export type Event =
| UpdateSecretEvent
| UpdateSecretBatchEvent
| MoveSecretsEvent
+ | SearchSecretsByValueEvent
| DuplicateSecretEvent
| DeleteSecretEvent
| DeleteSecretBatchEvent
@@ -8249,7 +8255,6 @@ export type Event =
| ViewInsightsAuthMethodsEvent
| ViewSecretManagementInsightsSummaryEvent
| ViewInsightsSecretsDuplicationEvent
- | SearchInsightsSecretsByValueEvent
| ViewSecretManagementInsightsCountsEvent
| ViewSecretManagementInsightsUsageEvent
| ViewSecretManagementInsightsProjectWarningsEvent
diff --git a/backend/src/ee/services/insights/insights-service.test.ts b/backend/src/ee/services/insights/insights-service.test.ts
index 397b33fcb1..9925d1e2db 100644
--- a/backend/src/ee/services/insights/insights-service.test.ts
+++ b/backend/src/ee/services/insights/insights-service.test.ts
@@ -53,7 +53,6 @@ const projectScopedDepStubs: Pick<
findStaleByProject: unreachable("secretV2BridgeDAL.findStaleByProject"),
countStaleByProject: unreachable("secretV2BridgeDAL.countStaleByProject"),
findDuplicatedSecretValues: unreachable("secretV2BridgeDAL.findDuplicatedSecretValues"),
- findSecretsByOrgBlindIndex: unreachable("secretV2BridgeDAL.findSecretsByOrgBlindIndex"),
countByProject: unreachable("secretV2BridgeDAL.countByProject")
},
dynamicSecretDAL: {
@@ -66,8 +65,7 @@ const projectScopedDepStubs: Pick<
getBotKey: unreachable("projectBotService.getBotKey")
},
projectDAL: {
- findById: unreachable("projectDAL.findById"),
- find: unreachable("projectDAL.find")
+ findById: unreachable("projectDAL.findById")
},
userDAL: {
find: unreachable("userDAL.find")
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index 6121359983..9eca72645f 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -1,7 +1,7 @@
import { ForbiddenError } from "@casl/ability";
// import geoip from "geoip-lite";
-import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope, ProjectType } from "@app/db/schemas";
+import { ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
import { TClickHouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";
import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";
import { TDynamicSecretDALFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-dal";
@@ -16,7 +16,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import {
ProjectPermissionHoneyTokenActions,
ProjectPermissionInsightsActions,
- ProjectPermissionSecretActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";
@@ -34,7 +33,6 @@ 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 { createSecretBlindIndexer } 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";
@@ -53,7 +51,6 @@ import {
VALUE_EVENT_TYPES
} from "./insights-fns";
import {
- TFindSecretsByValueDTO,
TGetAccessVolumeDTO,
TGetAuthMethodDistributionDTO,
TGetInsightsCalendarDTO,
@@ -82,16 +79,12 @@ export type TInsightsServiceFactoryDep = {
folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds" | "countByProject">;
secretV2BridgeDAL: Pick<
TSecretV2BridgeDALFactory,
- | "findStaleByProject"
- | "countStaleByProject"
- | "findDuplicatedSecretValues"
- | "findSecretsByOrgBlindIndex"
- | "countByProject"
+ "findStaleByProject" | "countStaleByProject" | "findDuplicatedSecretValues" | "countByProject"
>;
dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "countByProject">;
honeyTokenDAL: Pick<THoneyTokenDALFactory, "countByProjectId">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
- projectDAL: Pick<TProjectDALFactory, "findById" | "find">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
userDAL: Pick<TUserDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "ttl">;
@@ -486,79 +479,6 @@ export const insightsServiceFactory = ({
});
};
- // Answers "is this value in use anywhere in my organization", 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, which is why each hit is filtered against
- // the actor's permission on the project holding it.
- //
- // Deliberately not gated on the insights entitlement. It only reads, and CODE_QUALITY.md's license
- // rule is that reads are never gated; a customer answering "where else is this leaked credential"
- // should not be blocked on their plan.
- const findSecretsByValue = async (dto: TFindSecretsByValueDTO, actorDto: OrgServiceActor) => {
- const projects = await projectDAL.find({ orgId: actorDto.orgId, type: ProjectType.SecretManager });
- if (!projects.length) return { secrets: [] };
-
- // Every project in an org shares the org data key, so one indexer answers for all of them.
- const { generateOrgLevelBlindIndex } = await createSecretBlindIndexer({
- projectId: projects[0].id,
- orgId: actorDto.orgId,
- kmsService
- });
- const secretValueOrgBlindIndex = await generateOrgLevelBlindIndex(Buffer.from(dto.secretValue));
-
- const matches = await secretV2BridgeDAL.findSecretsByOrgBlindIndex(actorDto.orgId, secretValueOrgBlindIndex);
- if (!matches.length) return { secrets: [] };
-
- const readableProjectIds = new Set<string>();
- await Promise.all(
- [...new Set(matches.map((match) => match.projectId))].map(async (projectId) => {
- try {
- const { permission } = await permissionService.getProjectPermission({
- actor: actorDto.type,
- actorId: actorDto.id,
- projectId,
- actorAuthMethod: actorDto.authMethod,
- actorOrgId: actorDto.orgId,
- actionProjectType: ActionProjectType.SecretManager
- });
- // DescribeSecret, not a read of the value: this answers where a value the caller already has
- // is used, so the permission that matters is whether they may know the secret exists.
- if (permission.can(ProjectPermissionSecretActions.DescribeSecret, ProjectPermissionSub.Secrets)) {
- readableProjectIds.add(projectId);
- }
- } catch {
- // No membership in that project. A value the actor cannot see the location of is simply absent
- // from their results rather than an error, so one inaccessible project does not fail the search.
- }
- })
- );
-
- const visible = matches.filter((match) => readableProjectIds.has(match.projectId));
- if (!visible.length) return { secrets: [] };
-
- const pathsByProject = await Promise.all(
- [...new Set(visible.map((match) => match.projectId))].map(async (projectId) => {
- const folderIds = [...new Set(visible.filter((m) => m.projectId === projectId).map((m) => m.folderId))];
- const folders = await folderDAL.findSecretPathByFolderIds(projectId, folderIds);
- return folders;
- })
- );
- const pathByFolderId = new Map<string, string>();
- pathsByProject.flat().forEach((folder) => {
- if (folder) pathByFolderId.set(folder.id, folder.path);
- });
-
- return {
- 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) ?? "/"
- }))
- };
- };
-
const getSecretsDuplication = async (dto: TGetSecretsDuplicationDTO, actorDto: OrgServiceActor) => {
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
@@ -853,7 +773,6 @@ export const insightsServiceFactory = ({
getAuthMethodDistribution,
getSummary,
getSecretsDuplication,
- findSecretsByValue,
getCounts,
getSecretsUsageInsights,
getSecretsProjects,
diff --git a/backend/src/ee/services/insights/insights-types.ts b/backend/src/ee/services/insights/insights-types.ts
index 30d9f68858..7af2b9d9a1 100644
--- a/backend/src/ee/services/insights/insights-types.ts
+++ b/backend/src/ee/services/insights/insights-types.ts
@@ -34,10 +34,6 @@ export type TGetInsightsSummaryDTO = {
staleSecretsLimit?: number;
};
-export type TFindSecretsByValueDTO = {
- secretValue: string;
-};
-
export type TGetSecretsDuplicationDTO = {
projectId: string;
};
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
index db82009321..3411b2c0de 100644
--- a/backend/src/server/routes/v4/secret-router.ts
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -7,7 +7,7 @@ import { ApiDocsTags, RAW_SECRETS } from "@app/lib/api-docs";
import { AUDIT_LOG_SENSITIVE_VALUE } from "@app/lib/config/const";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { secretsLimit } from "@app/server/config/rateLimiter";
+import { secretsLimit, writeLimit } from "@app/server/config/rateLimiter";
import { BaseSecretNameSchema, SecretNameSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
@@ -19,7 +19,7 @@ import {
SecretImportReferencesBehavior,
SecretProtectionType
} from "@app/services/secret/secret-types";
-import { SecretUpdateMode } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
+import { SecretUpdateMode, SecretValueSearchScope } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { SanitizedTagSchema, secretRawSchema } from "../sanitizedSchemas";
@@ -1626,4 +1626,78 @@ 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: writeLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "searchByValue",
+ tags: [ApiDocsTags.Secrets],
+ description:
+ "Find every secret holding the supplied value, across the organization or within one project, in projects the caller can read.",
+ security: [{ bearerAuth: [] }],
+ body: z
+ .object({
+ secretValue: z.string().min(1).max(10_000).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 result = 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,
+ matchCount: result.secrets.length
+ }
+ }
+ });
+
+ return result;
+ }
+ });
};
diff --git a/backend/src/services/project/project-queue.ts b/backend/src/services/project/project-queue.ts
index 457b241dcc..47574b212b 100644
--- a/backend/src/services/project/project-queue.ts
+++ b/backend/src/services/project/project-queue.ts
@@ -711,7 +711,7 @@ export const projectQueueFactory = ({
if (secrets.length === 0) break;
- const updates: { id: string; secretValueBlindIndex: string; secretValueOrgBlindIndex: string | null }[] = [];
+ const updates: { id: string; secretValueBlindIndex: string; secretValueOrgBlindIndex: string }[] = [];
for (const secret of secrets) {
if (secret.encryptedValue) {
const decryptedValue = decryptor({ cipherTextBlob: secret.encryptedValue });
diff --git a/backend/src/services/secret-v2-bridge/secret-blind-index-fns.ts b/backend/src/services/secret-v2-bridge/secret-blind-index-fns.ts
index 9b08429e49..01aed577c6 100644
--- a/backend/src/services/secret-v2-bridge/secret-blind-index-fns.ts
+++ b/backend/src/services/secret-v2-bridge/secret-blind-index-fns.ts
@@ -21,6 +21,18 @@ export type TCreateSecretBlindIndexerDTO = {
tx?: Knex;
};
+export type TCreateOrgSecretBlindIndexerDTO = Omit<TCreateSecretBlindIndexerDTO, "projectId">;
+
+// Searching an org by value needs the org digest alone, so this resolves only the org data key
+// rather than paying for a project key it would never use.
+export const createOrgSecretBlindIndexer = async ({ orgId, kmsService, tx }: TCreateOrgSecretBlindIndexerDTO) => {
+ const orgCipher = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.Organization, orgId }, tx);
+
+ return {
+ generateOrgLevelBlindIndex: (secretValue: Buffer) => orgCipher.generateSecretBlindIndex(secretValue)
+ };
+};
+
// Build one of these per request and reuse it for every secret in that request. A bulk write can
// carry thousands of values, and resolving a data key per value would hit an external KMS that many
// times.
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.ts
index de11bc1564..0b4fd74f57 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
@@ -1284,13 +1284,13 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
};
const batchSetBlindIndexes = async (
- updates: { id: string; secretValueBlindIndex: string; secretValueOrgBlindIndex: string | null }[],
+ updates: { id: string; secretValueBlindIndex: string; secretValueOrgBlindIndex: string }[],
tx?: Knex
) => {
if (updates.length === 0) return;
try {
- const bindings: (string | null)[] = [];
+ const bindings: string[] = [];
const valuePlaceholders = updates.map(({ id, secretValueBlindIndex, secretValueOrgBlindIndex }) => {
bindings.push(id, secretValueBlindIndex, secretValueOrgBlindIndex);
return "(CAST(? AS uuid), ?, CAST(? AS varchar))";
@@ -1500,16 +1500,29 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
- // Finds every secret in the org whose value hashes to the given org-scoped digest. The caller is
- // responsible for dropping the projects the actor cannot read before returning anything.
- const findSecretsByOrgBlindIndex = async (orgId: string, secretValueOrgBlindIndex: string, tx?: Knex) => {
+ // Finds every secret holding the given value, either across an organization or within one of its
+ // projects. Matching is on the org-scoped digest in both cases, so the two scopes agree on which
+ // rows are searchable. The caller is responsible for dropping the projects the actor cannot read
+ // before returning anything.
+ const findSecretsWithMatchingValue = async (
+ {
+ orgId,
+ projectId,
+ secretValueDigest
+ }: {
+ orgId: string;
+ projectId?: string;
+ secretValueDigest: string;
+ },
+ tx?: Knex
+ ) => {
try {
- return await (tx || db.replicaNode())(TableName.SecretV2)
+ let query = (tx || db.replicaNode())(TableName.SecretV2)
.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.SecretV2}.secretValueOrgBlindIndex`, secretValueOrgBlindIndex)
+ .where(`${TableName.SecretV2}.secretValueOrgBlindIndex`, secretValueDigest)
.whereNull(`${TableName.Environment}.deleteAfter`)
.whereNull(`${TableName.Project}.deleteAfter`)
.whereNull(`${TableName.SecretV2}.userId`)
@@ -1522,8 +1535,12 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
db.ref("id").withSchema(TableName.Project).as("projectId"),
db.ref("name").withSchema(TableName.Project).as("projectName")
);
+
+ if (projectId) query = query.where(`${TableName.Project}.id`, projectId);
+
+ return await query;
} catch (error) {
- throw new DatabaseError({ error, name: "findSecretsByOrgBlindIndex" });
+ throw new DatabaseError({ error, name: "findSecretsWithMatchingValue" });
}
};
@@ -1626,7 +1643,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
- const findExistingSecretsByBlindIndexes = async (
+ const findExistingSecretsWithMatchingValues = async (
projectId: string,
blindIndexes: string[],
excludeSecretIds?: string[],
@@ -1661,7 +1678,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
return await query;
} catch (error) {
- throw new DatabaseError({ error, name: "findExistingSecretsByBlindIndexes" });
+ throw new DatabaseError({ error, name: "findExistingSecretsWithMatchingValues" });
}
};
@@ -1726,8 +1743,8 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
countByProject,
findValueValidationCandidatesByProject,
findDuplicatedSecretValues,
- findSecretsByOrgBlindIndex,
- findExistingSecretsByBlindIndexes,
+ findSecretsWithMatchingValue,
+ findExistingSecretsWithMatchingValues,
findOne,
find,
invalidateSecretCacheByProjectId,
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.ts
index f54fb39298..14251aeda2 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
@@ -5,6 +5,7 @@ import { z } from "zod";
import {
ActionProjectType,
ProjectMembershipRole,
+ ProjectType,
SecretsV2Schema,
SecretType,
TableName,
@@ -46,6 +47,7 @@ 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";
@@ -76,7 +78,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 { createSecretBlindIndexer } from "./secret-blind-index-fns";
+import { createOrgSecretBlindIndexer, createSecretBlindIndexer } from "./secret-blind-index-fns";
import { secretMetadataServiceFactory } from "./secret-metadata-service";
import { expandSecretReferencesFactory, getAllSecretReferences } from "./secret-reference-fns";
import {
@@ -100,6 +102,7 @@ import {
} from "./secret-v2-bridge-fns";
import {
SecretUpdateMode,
+ SecretValueSearchScope,
TBackFillSecretReferencesDTO,
TCreateManySecretDTO,
TCreateSecretDTO,
@@ -107,6 +110,7 @@ import {
TDeleteSecretDTO,
TDispatchSecretCreateSideEffectsDTO,
TDispatchSecretMoveSideEffectsDTO,
+ TFindSecretsByValueDTO,
TGetAccessibleSecretsDTO,
TGetASecretDTO,
TGetSecretReferencesTreeDTO,
@@ -4029,6 +4033,81 @@ 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, which is why each hit is filtered against the actor's
+ // permission on the project holding it.
+ const findSecretsByValue = async (dto: TFindSecretsByValueDTO, actor: OrgServiceActor) => {
+ if (dto.scope === SecretValueSearchScope.Project) {
+ const [project] = await projectDAL.find({
+ id: dto.projectId,
+ orgId: actor.orgId,
+ type: ProjectType.SecretManager
+ });
+ if (!project)
+ throw new NotFoundError({ message: `Secrets management project with ID '${dto.projectId}' not found` });
+ }
+
+ // 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 matches = await secretDAL.findSecretsWithMatchingValue({
+ orgId: actor.orgId,
+ projectId: dto.scope === SecretValueSearchScope.Project ? dto.projectId : undefined,
+ secretValueDigest
+ });
+ if (!matches.length) return { secrets: [] };
+
+ const readableProjectIds = new Set<string>();
+ await Promise.all(
+ [...new Set(matches.map((match) => match.projectId))].map(async (projectId) => {
+ try {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ // DescribeSecret, not a read of the value: this answers where a value the caller already has
+ // is used, so the permission that matters is whether they may know the secret exists.
+ if (permission.can(ProjectPermissionSecretActions.DescribeSecret, ProjectPermissionSub.Secrets)) {
+ readableProjectIds.add(projectId);
+ }
+ } catch {
+ // No membership in that project. A value the actor cannot see the location of is simply absent
+ // from their results rather than an error, so one inaccessible project does not fail the search.
+ }
+ })
+ );
+
+ const visible = matches.filter((match) => readableProjectIds.has(match.projectId));
+ if (!visible.length) return { secrets: [] };
+
+ 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 {
+ 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" }),
@@ -4054,6 +4133,7 @@ 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.ts
index cd9ac20369..1ca174aa8f 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
@@ -186,6 +186,15 @@ 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-validation-rule/secret-validation-rule-service.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
index 68dad69329..be9d65b88c 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
@@ -438,7 +438,7 @@ export const secretValidationRuleServiceFactory = ({
});
const excludedSecretIds = candidates.map((secret) => secret.secretId).filter(Boolean) as string[];
- const existing = await secretDAL.findExistingSecretsByBlindIndexes(
+ const existing = await secretDAL.findExistingSecretsWithMatchingValues(
projectId,
[...new Set(blindIndexes)],
excludedSecretIds.length ? excludedSecretIds : undefined,
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 0cdc96ef90..8d6b954f6f 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -44,6 +44,7 @@ import { OrgServiceActor } from "@app/lib/types";
import {
SecretUpdateMode,
TDuplicateSecretDTO,
+ TFindSecretsByValueDTO,
TGetSecretReferencesDTO,
TGetSecretsRawByFolderMappingsDTO
} from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
@@ -3892,6 +3893,9 @@ export const secretServiceFactory = ({
return revokedSecretIds;
};
+ const findSecretsByValue = (dto: TFindSecretsByValueDTO, actor: OrgServiceActor) =>
+ secretV2BridgeService.findSecretsByValue(dto, actor);
+
return {
attachTags,
detachTags,
@@ -3929,6 +3933,7 @@ export const secretServiceFactory = ({
getChangeVersions,
redactSecretVersionValue,
getSecretReferenceDependencyTree,
- getSecretsWithRevokedProjectFolderGrant
+ getSecretsWithRevokedProjectFolderGrant,
+ findSecretsByValue
};
};