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
fix(insights): credit the secrets a reference resolved to when reads use personal overrides
Dimitris Staratzisa3525cc26161
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 7e56fff04a..1c67984c42 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1120,7 +1120,12 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through toA narrow 304 carries no secrets and records nothing, which is safe only because ETags are stored per UTC day,so each client's first read of the day is a full response. Single reads record the secret. A read withreferences unexpanded is stored as `secret-unexpanded` and credits only that secret, not the values it- references, which is why `objectType` is part of the primary key. A Redis `SET NX` gate (25h TTL) keyed on+ references, which is why `objectType` is part of the primary key. A read that expands references with the reader's+ personal overrides (v4 bulk with `includePersonalOverrides`, v4 single read of a personal secret) records the+ returned secrets plus the ones its references resolved to, all as `secret-unexpanded`: matching references by key+ would credit a shared secret an override replaced. The expander reports those through `onSecretReferenced`, and+ the bulk read caches them with its result (only for these reads, so every other cached payload and ETag is+ unchanged) so a cache hit replays them. A Redis `SET NX` gate (25h TTL) keyed onthe reader, the day and the request (or the hash of the returned ids) lets only the first identical readper day through. It is keyed on the request, not the ETag, since older clients never send one. Gated reads go to aRedis stream drained the way the audit log ingest stream is (collect, write, then trim, under adiff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.tsindex 5e060711cf..1fb28a6905 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-queue.ts@@ -148,7 +148,8 @@ export const secretReadActivityQueueServiceFactory = ({includesPersonalOverrides,notModified,secrets,- imports = []+ imports = [],+ referencedSecretIds}: TRecordBulkSecretReadDTO) => {if (!$isTrackedReader(actor)) return;@@ -172,10 +173,13 @@ export const secretReadActivityQueueServiceFactory = ({actor,actorId,projectId,- secretIds: [...secrets, ...imports.flatMap((secretImport) => secretImport.secrets)]- .filter((secret) => !secret.secretValueHidden)- .map((secret) => secret.id),- referencesExpanded: expandSecretReferences+ secretIds: [+ ...[...secrets, ...imports.flatMap((secretImport) => secretImport.secrets)]+ .filter((secret) => !secret.secretValueHidden)+ .map((secret) => secret.id),+ ...(referencedSecretIds ?? [])+ ],+ referencesExpanded: referencedSecretIds ? false : expandSecretReferences});} catch (error) {logger.warn(error, `Failed to record secret read [projectId=${projectId}] [actorId=${actorId}]`);diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.tsindex 535877000c..31366a3a73 100644--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-types.ts@@ -78,6 +78,9 @@ export type TRecordBulkSecretReadDTO = TSecretReader & {notModified?: boolean;secrets: TReturnedSecret[];imports?: { secrets: TReturnedSecret[] }[];+ // Set when references were expanded with the reader's personal overrides: the secrets they resolved to, credited+ // in place of matching references by key, which would credit a shared secret an override replaced.+ referencedSecretIds?: string[];};// What the request path appends to the stream; the consumer resolves it to folders and secrets.diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.tsindex 6667a43d16..f4c0b94eb2 100644--- a/backend/src/server/routes/v4/secret-router.ts+++ b/backend/src/server/routes/v4/secret-router.ts@@ -201,7 +201,10 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {if (!projectId || !environment) throw new BadRequestError({ message: "Missing project id or environment" });+ // References expanded with the reader's own overrides are credited to the secrets they resolved to.+ const referencedSecretIds: string[] = [];const result = await server.services.secret.getSecretsRaw({+ onSecretReferenced: (secretId) => referencedSecretIds.push(secretId),actorId: req.permission.id,actor: req.permission.type,actorOrgId: req.permission.orgId,@@ -241,7 +244,9 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {includesPersonalOverrides: req.query.includePersonalOverrides,notModified,secrets,- imports+ imports,+ referencedSecretIds:+ req.query.includePersonalOverrides && req.query.expandSecretReferences ? referencedSecretIds : undefined});}@@ -392,7 +397,9 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {throw new BadRequestError({ message: "You must provide workspaceId" });}+ const referencedSecretIds: string[] = [];const secret = await server.services.secret.getSecretByNameRaw({+ onSecretReferenced: (secretId) => referencedSecretIds.push(secretId),actorId: req.permission.id,actor: req.permission.type,actorAuthMethod: req.permission.authMethod,@@ -410,12 +417,15 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {});if (req.query.viewSecretValue) {+ // A personal secret expands through the reader's own overrides, so the secrets its references resolved to are+ // credited in place of matching references by key.+ const usesOverrides = req.query.type === SecretType.Personal && req.query.expandSecretReferences;void server.services.secretReadActivity.recordRead({actor: req.permission.type,actorId: req.permission.id,projectId,- secretIds: [secret.id],- referencesExpanded: req.query.expandSecretReferences+ secretIds: usesOverrides ? [secret.id, ...referencedSecretIds] : [secret.id],+ referencesExpanded: usesOverrides ? false : req.query.expandSecretReferences});}diff --git a/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts b/backend/src/services/secret-v2-bridge/secret-reference-fns.test.tsindex 2429b9591c..a7d3fd83e0 100644--- a/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts+++ b/backend/src/services/secret-v2-bridge/secret-reference-fns.test.ts@@ -217,3 +217,50 @@ describe("getAllSecretReferences", () => {expect(getAllSecretReferences(value)).toEqual({ localReferences: [], nestedReferences: [] });});});++describe("expandSecretReferencesFactory onSecretReferenced", () => {+ const row = (id: string, value: string, userId: string | null) => ({+ id,+ _id: id,+ key: "DB_PASSWORD",+ version: 1,+ type: userId ? "personal" : "shared",+ folderId: "folder",+ createdAt: new Date(0),+ updatedAt: new Date(0),+ encryptedValue: Buffer.from(value),+ tags: [],+ secretMetadata: [],+ userId+ });+ const expand = async (rows: ReturnType<typeof row>[], userId?: string) => {+ const referenced: string[] = [];+ const { findBySecretPath } = makeDALs();+ const { expandSecretReferences } = expandSecretReferencesFactory({+ projectId: "project",+ folderDAL: { findBySecretPath },+ secretDAL: { findByFolderId: vi.fn<Args["secretDAL"]["findByFolderId"]>().mockResolvedValue(rows) },+ decryptSecretValue: (value) => value?.toString(),+ canExpandValue: vi.fn(() => true),+ userId,+ onSecretReferenced: (secretId) => referenced.push(secretId)+ });+ const value = await expandSecretReferences({+ secretKey: "URL",+ value: `postgres://\${DB_PASSWORD}@db`,+ environment: "prod",+ secretPath: "/"+ });+ return { value, referenced };+ };++ it("reports the reader's own override, not the shared secret it replaced", async () => {+ const result = await expand([row("shared-db", "shared", null), row("alice-db", "mine", "alice")], "alice");+ expect(result).toEqual({ value: "postgres://mine@db", referenced: ["alice-db"] });+ });++ it("reports the shared secret when no override is used", async () => {+ const result = await expand([row("shared-db", "shared", null)]);+ expect(result).toEqual({ value: "postgres://shared@db", referenced: ["shared-db"] });+ });+});diff --git a/backend/src/services/secret-v2-bridge/secret-reference-fns.ts b/backend/src/services/secret-v2-bridge/secret-reference-fns.tsindex bc104cddd4..4950b920d4 100644--- a/backend/src/services/secret-v2-bridge/secret-reference-fns.ts+++ b/backend/src/services/secret-v2-bridge/secret-reference-fns.ts@@ -112,10 +112,16 @@ type TInterpolateSecretArg = {// same-project relative references; cross-project reads must stay raw so source// project imports are not resolved through the target project context.crossProjectSecretDAL?: Pick<TSecretV2BridgeDALFactory, "findByFolderId">;+ // Called with the id of each secret in this project whose value a reference resolved to, a personal override+ // included, so a caller can tell which secrets a read actually delivered.+ onSecretReferenced?: (secretId: string) => void;abortSignal?: AbortSignal;tx?: Knex;};+// A cross-project secret carries no id: only this project's secrets are reported to onSecretReferenced.+type TCachedReferencedSecret = { id?: string; value: string; tags: string[]; exists: boolean };+const MAX_SECRET_REFERENCE_DEPTH = 10;export const expandSecretReferencesFactory = ({projectId,@@ -130,10 +136,11 @@ export const expandSecretReferencesFactory = ({projectDAL,kmsService,crossProjectSecretDAL,+ onSecretReferenced,abortSignal,tx}: TInterpolateSecretArg) => {- const secretCache: Record<string, Record<string, { value: string; tags: string[]; exists: boolean }>> = {};+ const secretCache: Record<string, Record<string, TCachedReferencedSecret>> = {};let crossProjectAllowedCache: boolean | undefined;const hasCrossProjectConfig = Boolean(actorOrgId && orgDAL && projectFolderGrantDAL && projectDAL && kmsService);const checkCrossProjectAllowed = async () => {@@ -179,25 +186,23 @@ export const expandSecretReferencesFactory = ({const secrets = await secretDAL.findByFolderId({ folderId: folder.id, userId, tx });throwIfClientDisconnected(abortSignal);- const decryptedSecret = secrets.reduce<Record<string, { value: string; tags: string[]; exists: boolean }>>(- (prev, secret) => {- // When userId is set, personal overrides (userId !== null) should take precedence- // over shared secrets for the same key. We skip overwriting if a personal override- // is already stored and the current secret is a shared one.- if (userId && prev[secret.key] && !secret.userId) {- return prev;- }-- // eslint-disable-next-line no-param-reassign- prev[secret.key] = {- value: decryptSecret(secret.encryptedValue) || "",- tags: secret.tags?.map((el) => el.slug),- exists: true- };+ const decryptedSecret = secrets.reduce<Record<string, TCachedReferencedSecret>>((prev, secret) => {+ // When userId is set, personal overrides (userId !== null) should take precedence+ // over shared secrets for the same key. We skip overwriting if a personal override+ // is already stored and the current secret is a shared one.+ if (userId && prev[secret.key] && !secret.userId) {return prev;- },- {}- );+ }++ // eslint-disable-next-line no-param-reassign+ prev[secret.key] = {+ id: secret.id,+ value: decryptSecret(secret.encryptedValue) || "",+ tags: secret.tags?.map((el) => el.slug),+ exists: true+ };+ return prev;+ }, {});secretCache[cacheKey] = decryptedSecret;} catch (error) {@@ -211,7 +216,7 @@ export const expandSecretReferencesFactory = ({environment: string,secretPath: string,secretKey: string- ): Promise<{ value: string; tags: string[]; exists: boolean }> => {+ ): Promise<TCachedReferencedSecret> => {const cacheKey = getCacheUniqueKey(environment, secretPath);if (!secretCache[cacheKey]) {@@ -320,6 +325,7 @@ export const expandSecretReferencesFactory = ({const cacheKey = getCacheUniqueKey(environment, secretPath);if (!secretCache[cacheKey]) secretCache[cacheKey] = {};secretCache[cacheKey][secretKey] = referredValue;+ if (referredValue.id) onSecretReferenced?.(referredValue.id);referencedSecretValue = referredValue.value;referencedSecretExists = referredValue.exists;@@ -444,6 +450,7 @@ export const expandSecretReferencesFactory = ({const cacheKey = getCacheUniqueKey(secretReferenceEnvironment, secretReferencePath);if (!secretCache[cacheKey]) secretCache[cacheKey] = {};secretCache[cacheKey][secretReferenceKey] = referedValue;+ if (referedValue.id) onSecretReferenced?.(referedValue.id);referencedSecretValue = referedValue.value;referencedSecretExists = referedValue.exists;diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.tsindex 7aea0a997e..a145d2b154 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts@@ -1477,6 +1477,7 @@ type TCreateRelativeImportExpanderArg = {decryptSecretValue: (value?: Buffer | null) => string;canExpandValue: (environment: string, secretPath: string, secretKey: string, secretTagSlugs: string[]) => boolean;userId?: string;+ onSecretReferenced?: (secretId: string) => void;abortSignal?: AbortSignal;};@@ -1490,6 +1491,7 @@ export const createRelativeImportExpander = ({decryptSecretValue,canExpandValue,userId,+ onSecretReferenced,abortSignal}: TCreateRelativeImportExpanderArg): {expandImportedSecretReferences: (inputSecret: {@@ -1570,6 +1572,7 @@ export const createRelativeImportExpander = ({return canExpandValue(environment, secretPath, secretKey, secretTagSlugs);},userId,+ onSecretReferenced,abortSignal});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 1502aff3a8..9b36931b3a 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@@ -1348,6 +1348,7 @@ export const secretV2BridgeServiceFactory = ({throwOnMissingReadValuePermission = true,ifNoneMatch,abortSignal,+ onSecretReferenced,...params} = dto;@@ -1446,10 +1447,16 @@ export const secretV2BridgeServiceFactory = ({// Decrypted bytes are the exact serialized payload the miss path hashed, so hashing them reproduces// the same ETag without re-serializing the object.const cachedEtag = `"${generateCacheKeyFromBuffer(cachedSecrets)}"`;- const { secrets, imports = [] } = JSON.parse(cachedSecrets.toString("utf8")) as {+ const {+ secrets,+ imports = [],+ referencedSecretIds: cachedReferencedSecretIds = []+ } = JSON.parse(cachedSecrets.toString("utf8")) as {secrets: typeof decryptedSecrets;imports: typeof importedSecrets;+ referencedSecretIds?: string[];};+ cachedReferencedSecretIds.forEach((secretId) => onSecretReferenced?.(secretId));// Parsed array is owned here, so rehydrate dates in place instead of cloning every secret.for (const secret of secrets) {secret.createdAt = new Date(secret.createdAt);@@ -1629,6 +1636,19 @@ export const secretV2BridgeServiceFactory = ({// note(daniel): when in relative mode, direct secret references also resolve through imported secrets.// wrap secretDAL with import-aware fetch so the expander sees the full merged view.+ // A read that expands references with the reader's personal overrides keeps the ids its references resolved to,+ // since matching a reference by key would credit the shared secret an override replaced. They are cached with+ // the result, as a cache hit expands nothing. Every other read caches exactly what it did before.+ const referencedSecretIds = new Set<string>();+ const collectReferencedSecret = expandPersonalOverrides+ ? (secretId: string) => {+ referencedSecretIds.add(secretId);+ }+ : undefined;+ const withReferencedSecretIds = <T extends object>(payload: T) =>+ referencedSecretIds.size ? { ...payload, referencedSecretIds: [...referencedSecretIds].sort() } : payload;+ const reportReferencedSecrets = () => referencedSecretIds.forEach((secretId) => onSecretReferenced?.(secretId));+const mainExpanderSecretDAL =secretImportReferencesBehavior === SecretImportReferencesBehavior.Relative? { findByFolderId: createFetchFolderSecretsWithImports({ projectId, secretDAL, secretImportDAL, folderDAL }) }@@ -1660,6 +1680,7 @@ export const secretV2BridgeServiceFactory = ({// mainExpanderSecretDAL may be import-aware in relative mode. Keep cross-project// reads on the raw DAL so source imports are not resolved through this target project.crossProjectSecretDAL: secretDAL,+ onSecretReferenced: collectReferencedSecret,abortSignal});@@ -1680,7 +1701,7 @@ export const secretV2BridgeServiceFactory = ({if (!includeImports) {const payload = { secrets: decryptedSecrets, imports: [] };- const serializedPayload = Buffer.from(JSON.stringify(payload));+ const serializedPayload = Buffer.from(JSON.stringify(withReferencedSecretIds(payload)));const computedEtag = `"${generateCacheKeyFromBuffer(serializedPayload)}"`;const encryptedUpdatedCachedSecrets = secretManagerEncryptor({ plainText: serializedPayload }).cipherTextBlob;const cacheBytes = encryptedUpdatedCachedSecrets.byteLength;@@ -1692,6 +1713,7 @@ export const secretV2BridgeServiceFactory = ({recordSecretCacheAccessMetric(SecretCacheAccessResult.MISS, { hasIfNoneMatch, etagMissReason });await keyStore.hashSet(etagRedisKey, etagField, computedEtag);await keyStore.setExpiry(etagRedisKey, KeyStoreTtls.SecretEtagInSeconds);+ reportReferencedSecrets();return { ...payload, etag: computedEtag };}@@ -1716,6 +1738,7 @@ export const secretV2BridgeServiceFactory = ({secretTags: expandSecretTags}),userId: expandPersonalOverrides ? actorId : undefined,+ onSecretReferenced: collectReferencedSecret,abortSignal});@@ -1775,7 +1798,7 @@ export const secretV2BridgeServiceFactory = ({});const payload = { secrets: decryptedSecrets, imports: importedSecrets };- const serializedPayload = Buffer.from(JSON.stringify(payload));+ const serializedPayload = Buffer.from(JSON.stringify(withReferencedSecretIds(payload)));const computedEtag = `"${generateCacheKeyFromBuffer(serializedPayload)}"`;const encryptedUpdatedCachedSecrets = secretManagerEncryptor({ plainText: serializedPayload }).cipherTextBlob;const cacheBytes = encryptedUpdatedCachedSecrets.byteLength;@@ -1787,6 +1810,7 @@ export const secretV2BridgeServiceFactory = ({recordSecretCacheAccessMetric(SecretCacheAccessResult.MISS, { hasIfNoneMatch, etagMissReason });await keyStore.hashSet(etagRedisKey, etagField, computedEtag);await keyStore.setExpiry(etagRedisKey, KeyStoreTtls.SecretEtagInSeconds);+ reportReferencedSecrets();return { ...payload, etag: computedEtag };};@@ -1881,7 +1905,8 @@ export const secretV2BridgeServiceFactory = ({viewSecretValue,includeImports,expandSecretReferences: shouldExpandSecretReferences,- expandPersonalOverrides+ expandPersonalOverrides,+ onSecretReferenced}: TGetASecretDTO) => {const { permission } = await permissionService.getProjectPermission({actor,@@ -1984,7 +2009,8 @@ export const secretV2BridgeServiceFactory = ({orgDAL,projectFolderGrantDAL,projectDAL,- kmsService+ kmsService,+ onSecretReferenced});// now if secret is not founddiff --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 14606fbf49..f2caad4ed0 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@@ -71,6 +71,8 @@ export type TGetSecretsDTO = {excludeRotatedSecrets?: boolean;ifNoneMatch?: string;abortSignal?: AbortSignal;+ // Called with each secret in the project a reference resolved to, a personal override included.+ onSecretReferenced?: (secretId: string) => void;} & TProjectPermission;export type TGetSecretsMissingReadValuePermissionDTO = Omit<@@ -89,6 +91,8 @@ export type TGetASecretDTO = {version?: number;projectId: string;viewSecretValue: boolean;+ // Called with each secret in the project a reference resolved to, a personal override included.+ onSecretReferenced?: (secretId: string) => void;} & Omit<TProjectPermission, "projectId">;export type TCreateSecretDTO = TProjectPermission & {diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.tsindex e477ecfe5d..22934f9337 100644--- a/backend/src/services/secret/secret-service.ts+++ b/backend/src/services/secret/secret-service.ts@@ -1456,12 +1456,14 @@ export const secretServiceFactory = ({throwOnMissingReadValuePermission = true,ifNoneMatch,abortSignal,+ onSecretReferenced,...paramsV2}: TGetSecretsRawDTO) => {const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);if (shouldUseSecretV2Bridge) {const result = await secretV2BridgeService.getSecrets({abortSignal,+ onSecretReferenced,projectId,expandSecretReferences,personalOverridesBehavior,@@ -1652,11 +1654,13 @@ export const secretServiceFactory = ({actorAuthMethod,secretName,includeImports,- version+ version,+ onSecretReferenced}: TGetASecretRawDTO) => {const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);if (shouldUseSecretV2Bridge) {const secret = await secretV2BridgeService.getSecretByName({+ onSecretReferenced,environment,projectId,includeImports,diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.tsindex 84547a42a4..838ec37713 100644--- a/backend/src/services/secret/secret-types.ts+++ b/backend/src/services/secret/secret-types.ts@@ -253,6 +253,8 @@ export type TGetSecretsRawDTO = {excludeRotatedSecrets?: boolean;ifNoneMatch?: string;abortSignal?: AbortSignal;+ // Called with each secret in the project a reference resolved to, a personal override included.+ onSecretReferenced?: (secretId: string) => void;} & TProjectPermission;export type TGetSecretAccessListDTO = {@@ -273,6 +275,8 @@ export type TGetASecretRawDTO = {includeImports?: boolean;version?: number;projectId: string;+ // Called with each secret in the project a reference resolved to, a personal override included.+ onSecretReferenced?: (secretId: string) => void;} & Omit<TProjectPermission, "projectId">;export type TGetASecretByIdRawDTO = {