Skip to content

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

feat: add support for encrypted values

adilsonbbc207b63b7e
diff --git a/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts b/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts
index 443f7444bb..6666f218e6 100644
--- a/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts
+++ b/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts
@@ -23,7 +23,10 @@ const ENV_KEY = "e2e-search-env";
const TEAM_KEY = "e2e-search-team";
const TEST_PATH = "/";
-const createSecretWithMetadata = async (dto: { key: string; metadata: { key: string; value: string }[] }) => {
+const createSecretWithMetadata = async (dto: {
+ key: string;
+ metadata: { key: string; value: string; isEncrypted?: boolean }[];
+}) => {
const res = await testServer.inject({
method: "POST",
url: `/api/v3/secrets/raw/${dto.key}`,
@@ -121,13 +124,7 @@ describe("Dashboard - search secrets by metadata", async () => {
secretCId = secretC.id;
});
- afterAll(async () => {
- await Promise.all([
- deleteSecret({ key: secretKeys.a }),
- deleteSecret({ key: secretKeys.b }),
- deleteSecret({ key: secretKeys.c })
- ]);
- });
+ afterAll(() => Promise.all(Object.values(secretKeys).map((key) => deleteSecret({ key }))));
test("OR operator returns secrets matching any condition", async () => {
const secrets = await searchSecretMetadata({
@@ -188,3 +185,108 @@ describe("Dashboard - search secrets by metadata", async () => {
expect(matchedIds).toEqual(expect.not.arrayContaining([secretAId, secretBId]));
});
});
+
+// distinctive keys so the org-wide search only ever matches the secrets seeded by this block
+const ENC_ENV_KEY = "e2e-search-enc-env";
+const ENC_TEAM_KEY = "e2e-search-enc-team";
+
+describe("Dashboard - search secrets by encrypted metadata", async () => {
+ const secretKeys = {
+ d: "E2E_METADATA_SEARCH_ENC_D",
+ e: "E2E_METADATA_SEARCH_ENC_E",
+ f: "E2E_METADATA_SEARCH_ENC_F"
+ };
+
+ let secretDId = "";
+ let secretEId = "";
+ let secretFId = "";
+
+ beforeAll(async () => {
+ // D -> env=prod, team=payments (both encrypted)
+ // E -> env=prod (plaintext) + team=payments (encrypted) — mixed, exercises the and-across-storage path
+ // F -> env=staging, team=billing (both encrypted)
+ const [secretD, secretE, secretF] = await Promise.all([
+ createSecretWithMetadata({
+ key: secretKeys.d,
+ metadata: [
+ { key: ENC_ENV_KEY, value: "prod", isEncrypted: true },
+ { key: ENC_TEAM_KEY, value: "payments", isEncrypted: true }
+ ]
+ }),
+ createSecretWithMetadata({
+ key: secretKeys.e,
+ metadata: [
+ { key: ENC_ENV_KEY, value: "prod", isEncrypted: false },
+ { key: ENC_TEAM_KEY, value: "payments", isEncrypted: true }
+ ]
+ }),
+ createSecretWithMetadata({
+ key: secretKeys.f,
+ metadata: [
+ { key: ENC_ENV_KEY, value: "staging", isEncrypted: true },
+ { key: ENC_TEAM_KEY, value: "billing", isEncrypted: true }
+ ]
+ })
+ ]);
+
+ secretDId = secretD.id;
+ secretEId = secretE.id;
+ secretFId = secretF.id;
+ });
+
+ afterAll(() => Promise.all(Object.values(secretKeys).map((key) => deleteSecret({ key }))));
+
+ test("OR matches encrypted values by decrypting server-side", async () => {
+ const secrets = await searchSecretMetadata({
+ operator: "or",
+ filters: [
+ { key: ENC_ENV_KEY, value: "prod" },
+ { key: ENC_TEAM_KEY, value: "payments" }
+ ]
+ });
+
+ const matchedIds = secrets.map((secret) => secret.secretId);
+ // D and E both hold env=prod / team=payments; F (staging/billing) matches neither
+ expect(matchedIds).toEqual(expect.arrayContaining([secretDId, secretEId]));
+ expect(matchedIds).toEqual(expect.not.arrayContaining([secretFId]));
+
+ // the decrypted value is surfaced in the response, not the ciphertext
+ const secretD = secrets.find((secret) => secret.secretId === secretDId);
+ expect(secretD?.metadata).toEqual(expect.arrayContaining([{ key: ENC_ENV_KEY, value: "prod" }]));
+ });
+
+ test("AND matches every condition, including across mixed plaintext + encrypted rows", async () => {
+ const secrets = await searchSecretMetadata({
+ operator: "and",
+ filters: [
+ { key: ENC_ENV_KEY, value: "prod" },
+ { key: ENC_TEAM_KEY, value: "payments" }
+ ]
+ });
+
+ const matchedIds = secrets.map((secret) => secret.secretId);
+ // D (both encrypted) and E (env plaintext + team encrypted) satisfy both conditions; F does not
+ expect(matchedIds).toEqual(expect.arrayContaining([secretDId, secretEId]));
+ expect(matchedIds).toEqual(expect.not.arrayContaining([secretFId]));
+
+ const secretE = secrets.find((secret) => secret.secretId === secretEId);
+ expect(secretE?.metadata).toEqual(
+ expect.arrayContaining([
+ { key: ENC_ENV_KEY, value: "prod" },
+ { key: ENC_TEAM_KEY, value: "payments" }
+ ])
+ );
+ });
+
+ test("does not match a non-matching encrypted value", async () => {
+ const secrets = await searchSecretMetadata({
+ operator: "and",
+ filters: [{ key: ENC_TEAM_KEY, value: "billing" }]
+ });
+
+ const matchedIds = secrets.map((secret) => secret.secretId);
+ // only F has team=billing
+ expect(matchedIds).toEqual(expect.arrayContaining([secretFId]));
+ expect(matchedIds).toEqual(expect.not.arrayContaining([secretDId, secretEId]));
+ });
+});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index ec2583c032..e230eabbb8 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -802,12 +802,6 @@ export const registerRoutes = async (
groupDAL
});
- const resourceMetadataService = resourceMetadataServiceFactory({
- resourceMetadataDAL,
- permissionService,
- folderDAL
- });
-
const assumePrivilegeService = assumePrivilegeServiceFactory({
permissionService
});
@@ -972,6 +966,13 @@ export const registerRoutes = async (
envConfig
});
+ const resourceMetadataService = resourceMetadataServiceFactory({
+ resourceMetadataDAL,
+ permissionService,
+ folderDAL,
+ kmsService
+ });
+
const externalKmsService = externalKmsServiceFactory({
kmsDAL,
kmsService,
diff --git a/backend/src/services/resource-metadata/resource-metadata-dal.ts b/backend/src/services/resource-metadata/resource-metadata-dal.ts
index 29ed683f55..e79a13482c 100644
--- a/backend/src/services/resource-metadata/resource-metadata-dal.ts
+++ b/backend/src/services/resource-metadata/resource-metadata-dal.ts
@@ -27,11 +27,86 @@ export const resourceMetadataDALFactory = (db: TDbClient) => {
});
};
+ const buildScopedSecretMetadataQuery = (knex: Knex, orgId: string, projectId: string) =>
+ knex(TableName.ResourceMetadata)
+ .join(TableName.SecretV2, `${TableName.SecretV2}.id`, `${TableName.ResourceMetadata}.secretId`)
+ .join(TableName.SecretFolder, `${TableName.SecretFolder}.id`, `${TableName.SecretV2}.folderId`)
+ .join(TableName.Environment, `${TableName.Environment}.id`, `${TableName.SecretFolder}.envId`)
+ .join(TableName.Project, `${TableName.Project}.id`, `${TableName.Environment}.projectId`)
+ .where(`${TableName.ResourceMetadata}.orgId`, orgId)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .whereNotNull(`${TableName.ResourceMetadata}.secretId`)
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.SecretV2}.type`, SecretType.Shared);
+
+ // Shared step-2 hydration: for the resolved candidate secretIds, fetch the metadata rows matching
+ // `applyMetadataMatch` plus the secret key and tags, and nest into
+ // { secretId, secretKey, folderId, metadata: [{ key, value, encryptedValue }], tags: [{ id, slug }] }.
+ // encryptedValue is always selected (null for plaintext rows); the service decrypts it when present.
+ const hydrateMatchedSecretMetadata = async (
+ knex: Knex,
+ secretIds: string[],
+ applyMetadataMatch: (qb: Knex.QueryBuilder) => void
+ ) => {
+ const rows = await knex(TableName.ResourceMetadata)
+ .join(TableName.SecretV2, `${TableName.SecretV2}.id`, `${TableName.ResourceMetadata}.secretId`)
+ .leftJoin(
+ TableName.SecretV2JnTag,
+ `${TableName.SecretV2}.id`,
+ `${TableName.SecretV2JnTag}.${TableName.SecretV2}Id`
+ )
+ .leftJoin(TableName.SecretTag, `${TableName.SecretV2JnTag}.${TableName.SecretTag}Id`, `${TableName.SecretTag}.id`)
+ .whereIn(`${TableName.ResourceMetadata}.secretId`, secretIds)
+ .where(applyMetadataMatch)
+ .select(
+ db.ref("secretId").withSchema(TableName.ResourceMetadata).as("secretId"),
+ db.ref("id").withSchema(TableName.ResourceMetadata).as("metadataId"),
+ db.ref("key").withSchema(TableName.ResourceMetadata).as("metadataKey"),
+ db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue"),
+ db.ref("encryptedValue").withSchema(TableName.ResourceMetadata).as("metadataEncryptedValue"),
+ db.ref("key").withSchema(TableName.SecretV2).as("secretKey"),
+ db.ref("folderId").withSchema(TableName.SecretV2).as("folderId"),
+ db.ref("id").withSchema(TableName.SecretTag).as("tagId"),
+ db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug")
+ );
+
+ return sqlNestRelationships({
+ data: rows,
+ key: "secretId",
+ parentMapper: (row) => ({
+ secretId: row.secretId as string,
+ secretKey: row.secretKey,
+ folderId: row.folderId
+ }),
+ childrenMapper: [
+ {
+ key: "metadataId",
+ label: "metadata" as const,
+ mapper: ({ metadataKey, metadataValue, metadataEncryptedValue }) => ({
+ key: metadataKey,
+ value: metadataValue as string | null,
+ encryptedValue: metadataEncryptedValue as Buffer | null
+ })
+ },
+ {
+ key: "tagId",
+ label: "tags" as const,
+ mapper: ({ tagId, tagSlug }) => ({
+ id: tagId,
+ slug: tagSlug
+ })
+ }
+ ]
+ });
+ };
+
// Project-scoped search of secret metadata. A resource_metadata row holds a single key/value and a
// secret has many rows, so the and/or combinator is evaluated per secret:
// - or -> a secret matches if any condition matches one of its rows
// - and -> a secret matches only if every condition matches some row of that secret
- // Only plaintext `value` is matched (encrypted metadata values cannot be matched by equality).
+ // Only plaintext `value` is matched here; encrypted values are handled by
+ // searchSecretMetadataWithEncryptedValues.
const searchSecretMetadata = async (
{ orgId, projectId, filters, operator, limit = MAX_SECRET_METADATA_SEARCH_SECRETS }: TSearchSecretMetadataDALDTO,
tx?: Knex
@@ -39,18 +114,8 @@ export const resourceMetadataDALFactory = (db: TDbClient) => {
try {
const knex = tx || db.replicaNode();
- // step 1: resolve the bounded set of matching secret ids (org-scoped, non-soft-deleted, shared).
- const matchedSecretIdsQuery = knex(TableName.ResourceMetadata)
- .join(TableName.SecretV2, `${TableName.SecretV2}.id`, `${TableName.ResourceMetadata}.secretId`)
- .join(TableName.SecretFolder, `${TableName.SecretFolder}.id`, `${TableName.SecretV2}.folderId`)
- .join(TableName.Environment, `${TableName.Environment}.id`, `${TableName.SecretFolder}.envId`)
- .join(TableName.Project, `${TableName.Project}.id`, `${TableName.Environment}.projectId`)
- .where(`${TableName.ResourceMetadata}.orgId`, orgId)
- .where(`${TableName.Environment}.projectId`, projectId)
- .whereNotNull(`${TableName.ResourceMetadata}.secretId`)
- .whereNull(`${TableName.Environment}.deleteAfter`)
- .whereNull(`${TableName.Project}.deleteAfter`)
- .where(`${TableName.SecretV2}.type`, SecretType.Shared);
+ // step 1: resolve the bounded set of matching secret ids (scoping enforced by the shared builder).
+ const matchedSecretIdsQuery = buildScopedSecretMetadataQuery(knex, orgId, projectId);
if (operator === SecretMetadataSearchLogicalOperator.And) {
// and: every condition must match a row of the secret. Drive the scan from the first condition
@@ -85,65 +150,51 @@ export const resourceMetadataDALFactory = (db: TDbClient) => {
const secretIds = matchedSecretRows.map((row) => row.secretId as string);
if (!secretIds.length) return [];
- // step 2: hydrate the matched metadata rows + tags + permission context for those secrets, then nest.
- const rows = await knex(TableName.ResourceMetadata)
- .join(TableName.SecretV2, `${TableName.SecretV2}.id`, `${TableName.ResourceMetadata}.secretId`)
- .leftJoin(
- TableName.SecretV2JnTag,
- `${TableName.SecretV2}.id`,
- `${TableName.SecretV2JnTag}.${TableName.SecretV2}Id`
- )
- .leftJoin(
- TableName.SecretTag,
- `${TableName.SecretV2JnTag}.${TableName.SecretTag}Id`,
- `${TableName.SecretTag}.id`
- )
- .whereIn(`${TableName.ResourceMetadata}.secretId`, secretIds)
- .where(buildMatchesAnyCondition(filters))
- .select(
- db.ref("secretId").withSchema(TableName.ResourceMetadata).as("secretId"),
- db.ref("id").withSchema(TableName.ResourceMetadata).as("metadataId"),
- db.ref("key").withSchema(TableName.ResourceMetadata).as("metadataKey"),
- db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue"),
- db.ref("key").withSchema(TableName.SecretV2).as("secretKey"),
- db.ref("folderId").withSchema(TableName.SecretV2).as("folderId"),
- db.ref("id").withSchema(TableName.SecretTag).as("tagId"),
- db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug")
- );
-
- const docs = sqlNestRelationships({
- data: rows,
- key: "secretId",
- parentMapper: (row) => ({
- secretId: row.secretId as string,
- secretKey: row.secretKey,
- folderId: row.folderId
- }),
- childrenMapper: [
- {
- key: "metadataId",
- label: "metadata" as const,
- mapper: ({ metadataKey, metadataValue }) => ({
- key: metadataKey,
- value: metadataValue as string | null
- })
- },
- {
- key: "tagId",
- label: "tags" as const,
- mapper: ({ tagId, tagSlug }) => ({
- id: tagId,
- slug: tagSlug
- })
- }
- ]
- });
-
+ // step 2: hydrate the matched metadata rows + tags for those secrets, then nest.
+ const docs = await hydrateMatchedSecretMetadata(knex, secretIds, buildMatchesAnyCondition(filters));
return docs;
} catch (error) {
throw new DatabaseError({ error, name: "SearchSecretMetadata" });
}
};
- return { ...orm, searchSecretMetadata };
+ // Companion to searchSecretMetadata for encrypted metadata. Encrypted values are stored as
+ // non-deterministic KMS ciphertext, so they cannot be equality-matched in SQL. This query therefore
+ // bounds candidates by KEY only (the requested filter keys) among rows that carry an encryptedValue,
+ // then returns every requested-key row (plaintext `value` + `encryptedValue`) for those secrets so the
+ // service can decrypt and match the value in-app. Plaintext rows are included so an `and` query
+ // satisfied partly by plaintext and partly by encrypted rows still matches after decryption. Kept as a
+ // separate query so the common plaintext path stays untouched, and it returns early (no hydration) when
+ // a project has no encrypted metadata for the requested keys.
+ const searchSecretMetadataWithEncryptedValues = async (
+ { orgId, projectId, filters, limit = MAX_SECRET_METADATA_SEARCH_SECRETS }: TSearchSecretMetadataDALDTO,
+ tx?: Knex
+ ) => {
+ try {
+ const knex = tx || db.replicaNode();
+ const keys = [...new Set(filters.map((filter) => filter.key))];
+
+ // step 1: bounded set of secrets holding at least one encrypted metadata row for a requested key
+ // — narrowed by the (orgId, key) partial index.
+ const matchedSecretRows = await buildScopedSecretMetadataQuery(knex, orgId, projectId)
+ .whereNotNull(`${TableName.ResourceMetadata}.encryptedValue`)
+ .whereIn(`${TableName.ResourceMetadata}.key`, keys)
+ .distinct(`${TableName.ResourceMetadata}.secretId`)
+ .orderBy(`${TableName.ResourceMetadata}.secretId`)
+ .limit(limit);
+
+ const secretIds = matchedSecretRows.map((row) => row.secretId as string);
+ if (!secretIds.length) return [];
+
+ // step 2: hydrate every requested-key row (plaintext value + encryptedValue) + tags for those secrets.
+ const docs = await hydrateMatchedSecretMetadata(knex, secretIds, (qb) => {
+ void qb.whereIn(`${TableName.ResourceMetadata}.key`, keys);
+ });
+ return docs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "SearchSecretMetadataWithEncryptedValues" });
+ }
+ };
+
+ return { ...orm, searchSecretMetadata, searchSecretMetadataWithEncryptedValues };
};
diff --git a/backend/src/services/resource-metadata/resource-metadata-fns.ts b/backend/src/services/resource-metadata/resource-metadata-fns.ts
index 22ed687008..111a03bea8 100644
--- a/backend/src/services/resource-metadata/resource-metadata-fns.ts
+++ b/backend/src/services/resource-metadata/resource-metadata-fns.ts
@@ -1,8 +1,14 @@
import { Knex } from "knex";
import { TableName } from "@app/db/schemas";
+import { unique } from "@app/lib/fn";
import { TResourceMetadataDALFactory } from "./resource-metadata-dal";
+import {
+ SecretMetadataSearchLogicalOperator,
+ TResolvedSecretMetadata,
+ TSecretMetadataSearchFilter
+} from "./resource-metadata-types";
type TResourceMetadataDAL = Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
@@ -157,3 +163,35 @@ export const applyMetadataFilter = <T extends Knex.QueryBuilder>(
});
}) as T;
};
+
+// de-duplicates resolved metadata entries by (key, value), keeping the first occurrence.
+export const dedupeMetadata = (metadata: TResolvedSecretMetadata[]): TResolvedSecretMetadata[] =>
+ unique(metadata, (entry) => JSON.stringify([entry.key, entry.value]));
+
+// Evaluates the and/or search conditions against a secret's already-resolved metadata entries (plaintext
+// values + decrypted encrypted values). This is the in-app value match: encrypted metadata is stored as
+// non-deterministic KMS ciphertext and cannot be equality-matched in SQL, so the DB only bounds candidates
+// by key and the exact value comparison happens here.
+// - or -> the secret matches if any condition matches one of its entries
+// - and -> the secret matches only if every condition matches some entry (each condition may be satisfied
+// by a different entry, so a secret can match across mixed plaintext + encrypted metadata)
+// Returns the subset of entries that satisfied at least one condition, de-duplicated by key/value, to mirror
+// the "matched metadata" surfaced by the plaintext DAL search.
+export const matchesSecretMetadataFilters = (
+ operator: SecretMetadataSearchLogicalOperator,
+ filters: TSecretMetadataSearchFilter[],
+ metadata: TResolvedSecretMetadata[]
+): { matched: boolean; matchedMetadata: TResolvedSecretMetadata[] } => {
+ const perFilterMatches = filters.map((filter) =>
+ metadata.filter((entry) => entry.key === filter.key && entry.value === filter.value)
+ );
+
+ const matched =
+ operator === SecretMetadataSearchLogicalOperator.And
+ ? perFilterMatches.every((entries) => entries.length > 0)
+ : perFilterMatches.some((entries) => entries.length > 0);
+
+ if (!matched) return { matched: false, matchedMetadata: [] };
+
+ return { matched: true, matchedMetadata: dedupeMetadata(perFilterMatches.flat()) };
+};
diff --git a/backend/src/services/resource-metadata/resource-metadata-service.ts b/backend/src/services/resource-metadata/resource-metadata-service.ts
index bcd78e1781..02dc8bae6b 100644
--- a/backend/src/services/resource-metadata/resource-metadata-service.ts
+++ b/backend/src/services/resource-metadata/resource-metadata-service.ts
@@ -3,23 +3,41 @@ import { hasSecretReadValueOrDescribePermission } from "@app/ee/services/permiss
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
import { BadRequestError } from "@app/lib/errors";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TResourceMetadataDALFactory } from "./resource-metadata-dal";
-import { TSearchSecretMetadataDTO } from "./resource-metadata-types";
+import { dedupeMetadata, matchesSecretMetadataFilters } from "./resource-metadata-fns";
+import { TResolvedSecretMetadata, TSearchSecretMetadataDTO } from "./resource-metadata-types";
type TResourceMetadataServiceFactoryDep = {
- resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "searchSecretMetadata" | "transaction">;
+ resourceMetadataDAL: Pick<
+ TResourceMetadataDALFactory,
+ "searchSecretMetadata" | "searchSecretMetadataWithEncryptedValues" | "transaction"
+ >;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
export type TResourceMetadataServiceFactory = ReturnType<typeof resourceMetadataServiceFactory>;
+// merged match accumulator: a secret can be matched via plaintext and/or decrypted encrypted metadata,
+// so matched entries are de-duplicated by key/value before being surfaced in the response.
+type TMatchedSecret = {
+ secretId: string;
+ secretKey: string;
+ folderId: string;
+ tags: { id: string; slug: string }[];
+ metadata: TResolvedSecretMetadata[];
+};
+
export const resourceMetadataServiceFactory = ({
resourceMetadataDAL,
permissionService,
- folderDAL
+ folderDAL,
+ kmsService
}: TResourceMetadataServiceFactoryDep) => {
// Project-scoped secret metadata search. The base query matches on org + project + key/value; the
// results are then filtered so the requester actually has DescribeSecret permission on each returned
@@ -38,19 +56,64 @@ export const resourceMetadataServiceFactory = ({
actionProjectType: ActionProjectType.SecretManager
});
- // run on primary via a transaction so recently written metadata is visible (avoids replica lag)
- const matchedSecrets = await resourceMetadataDAL.transaction((tx) =>
- resourceMetadataDAL.searchSecretMetadata(
- {
- orgId: actor.orgId,
- projectId,
- filters,
- operator
- },
+ // run both searches on primary via a transaction so recently written metadata is visible (avoids
+ // replica lag). Plaintext values are matched in SQL; encrypted values can't be (non-deterministic
+ // ciphertext), so their candidates are fetched by key and matched in-app after decryption below.
+ const { plaintextMatched, encryptedCandidates } = await resourceMetadataDAL.transaction(async (tx) => {
+ const plaintext = await resourceMetadataDAL.searchSecretMetadata(
+ { orgId: actor.orgId, projectId, filters, operator },
+ tx
+ );
+ const encrypted = await resourceMetadataDAL.searchSecretMetadataWithEncryptedValues(
+ { orgId: actor.orgId, projectId, filters, operator },
tx
- )
- );
+ );
+ return { plaintextMatched: plaintext, encryptedCandidates: encrypted };
+ });
+
+ const matchedSecretById = new Map<string, TMatchedSecret>();
+
+ const addMatch = (
+ secret: Pick<TMatchedSecret, "secretId" | "secretKey" | "folderId" | "tags">,
+ metadata: TResolvedSecretMetadata[]
+ ) => {
+ const existing = matchedSecretById.get(secret.secretId);
+ if (existing) {
+ existing.metadata.push(...metadata);
+ } else {
+ matchedSecretById.set(secret.secretId, { ...secret, metadata: [...metadata] });
+ }
+ };
+
+ // plaintext secrets are already matched in SQL — their hydrated rows are the matched metadata
+ plaintextMatched.forEach((secret) => {
+ addMatch(
+ secret,
+ secret.metadata.map((entry) => ({ key: entry.key, value: entry.value ?? "" }))
+ );
+ });
+
+ // decrypt encrypted candidates once per project (data key is resolved lazily), then match in-app
+ if (encryptedCandidates.length) {
+ const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ encryptedCandidates.forEach((secret) => {
+ const resolvedMetadata = secret.metadata.map((entry) => ({
+ key: entry.key,
+ value: entry.encryptedValue
+ ? secretManagerDecryptor({ cipherTextBlob: entry.encryptedValue }).toString()
+ : (entry.value ?? "")
+ }));
+
+ const { matched, matchedMetadata } = matchesSecretMetadataFilters(operator, filters, resolvedMetadata);
+ if (matched) addMatch(secret, matchedMetadata);
+ });
+ }
+ const matchedSecrets = [...matchedSecretById.values()];
if (!matchedSecrets.length) return { secrets: [] };
const folderIds = [...new Set(matchedSecrets.map((secret) => secret.folderId))];
@@ -83,7 +146,7 @@ export const resourceMetadataServiceFactory = ({
secretKey: secret.secretKey,
environment: folder.environmentSlug,
secretPath: folder.path,
- metadata: secret.metadata
+ metadata: dedupeMetadata(secret.metadata)
}
];
});
diff --git a/backend/src/services/resource-metadata/resource-metadata-types.ts b/backend/src/services/resource-metadata/resource-metadata-types.ts
index 16be6f6961..f4ebc950f1 100644
--- a/backend/src/services/resource-metadata/resource-metadata-types.ts
+++ b/backend/src/services/resource-metadata/resource-metadata-types.ts
@@ -18,6 +18,9 @@ export type TSecretMetadataSearchFilter = {
operator: SecretMetadataSearchOperator;
};
+// A secret's metadata entry after any encrypted value has been decrypted (value is always plaintext here).
+export type TResolvedSecretMetadata = { key: string; value: string };
+
// DAL input
export type TSearchSecretMetadataDALDTO = {
orgId: string;