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
update message to be displayed by consumer, not validator
Matheus Nogueirae44397e786d2
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.tsindex b2a19b0477..21d78b0e9d 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts@@ -69,7 +69,12 @@ import {import { SecretUpdateMode } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";+import {+ describeSecretValidationFailures,+ SecretValidationError+} from "@app/services/secret-validation-rule/secret-validation-rule-errors";import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";+import { TValidateSecretsDTO } from "@app/services/secret-validation-rule/secret-validation-rule-types";import { TProjectSlackConfigDALFactory } from "@app/services/slack/project-slack-config-dal";import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";@@ -207,13 +212,28 @@ export const secretApprovalRequestServiceFactory = ({queueService,secretValidationRuleService}: TSecretApprovalRequestServiceFactoryDep) => {- // A duplicate-value violation may only name where the value is already used when the writer can read there.- const $canDescribeSecretAt =- (permission: MongoAbility<ProjectPermissionSet>) => (environment: string, secretPath: string) =>- permission.can(- ProjectPermissionSecretActions.DescribeSecret,- subject(ProjectPermissionSub.Secrets, { environment, secretPath })- );+ // Which secret already holds a duplicated value is only named to a writer who may read there, so the+ // message is resolved against their permission rather than formatted inside validation.+ const $validateSecrets = async (+ dto: TValidateSecretsDTO,+ permission: MongoAbility<ProjectPermissionSet>,+ tx?: Knex+ ) => {+ try {+ await secretValidationRuleService.validateSecrets(dto, tx);+ } catch (error) {+ if (!(error instanceof SecretValidationError)) throw error;++ throw new BadRequestError({+ message: describeSecretValidationFailures(error.failures, (environment, secretPath) =>+ permission.can(+ ProjectPermissionSecretActions.DescribeSecret,+ subject(ProjectPermissionSub.Secrets, { environment, secretPath })+ )+ )+ });+ }+ };const requestCount = async ({projectId,@@ -936,15 +956,15 @@ export const secretApprovalRequestServiceFactory = ({if (secretsToValidate.length) {const folderPaths = await folderDAL.findSecretPathByFolderIds(projectId, [folderId], tx);- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: policyEnvId,secretPath: folderPaths?.[0]?.path || "/",- secrets: secretsToValidate,- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: secretsToValidate},+ permission,tx);}@@ -2514,15 +2534,15 @@ export const secretApprovalRequestServiceFactory = ({if (!commits.length) throw new BadRequestError({ message: "Empty commits" });if (secretsToValidate.length) {- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: folder.envId,secretPath,- secrets: secretsToValidate,- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: secretsToValidate},+ permission,providedTx);}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 e0ed128204..6bfdeafcca 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@@ -70,7 +70,12 @@ import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";import { fnSecretsV2FromImports } from "../secret-import/secret-import-fns";import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";+import {+ describeSecretValidationFailures,+ SecretValidationError+} 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 { secretMetadataServiceFactory } from "./secret-metadata-service";import { expandSecretReferencesFactory, getAllSecretReferences } from "./secret-reference-fns";import {@@ -214,13 +219,28 @@ export const secretV2BridgeServiceFactory = ({projectFolderGrantDAL,orgDAL}: TSecretV2BridgeServiceFactoryDep) => {- // A duplicate-value violation may only name where the value is already used when the writer can read there.- const $canDescribeSecretAt =- (permission: MongoAbility<ProjectPermissionSet>) => (environment: string, secretPath: string) =>- permission.can(- ProjectPermissionSecretActions.DescribeSecret,- subject(ProjectPermissionSub.Secrets, { environment, secretPath })- );+ // Which secret already holds a duplicated value is only named to a writer who may read there, so the+ // message is resolved against their permission rather than formatted inside validation.+ const $validateSecrets = async (+ dto: TValidateSecretsDTO,+ permission: MongoAbility<ProjectPermissionSet>,+ tx?: Knex+ ) => {+ try {+ await secretValidationRuleService.validateSecrets(dto, tx);+ } catch (error) {+ if (!(error instanceof SecretValidationError)) throw error;++ throw new BadRequestError({+ message: describeSecretValidationFailures(error.failures, (environment, secretPath) =>+ permission.can(+ ProjectPermissionSecretActions.DescribeSecret,+ subject(ProjectPermissionSub.Secrets, { environment, secretPath })+ )+ )+ });+ }+ };const { getSecretMetadata } = secretMetadataServiceFactory({permissionService,@@ -447,15 +467,15 @@ export const secretV2BridgeServiceFactory = ({? await generateSecretBlindIndex(Buffer.from(inputSecretData.secretValue)): undefined;const secret = await secretDAL.transaction(async (tx) => {- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: folder.envId,secretPath,- secrets: [{ key: inputSecret.secretName, value: inputSecret.secretValue }],- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: [{ key: inputSecret.secretName, value: inputSecret.secretValue }]},+ permission,tx);@@ -758,15 +778,15 @@ export const secretV2BridgeServiceFactory = ({const updatedSecret = await secretDAL.transaction(async (tx) => {if (secretValue || inputSecret.newSecretName) {- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: folder.envId,secretPath,- secrets: [{ key: finalKey, value: secretValue, secretId }],- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: [{ key: finalKey, value: secretValue, secretId }]},+ permission,tx);}@@ -2275,15 +2295,15 @@ export const secretV2BridgeServiceFactory = ({} = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }, providedTx);const executeBulkInsert = async (tx: Knex) => {- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: folder.envId,secretPath,- secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue })),- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue }))},+ permission,tx);@@ -2651,15 +2671,15 @@ export const secretV2BridgeServiceFactory = ({];if (secretsToValidate.length) {// eslint-disable-next-line no-await-in-loop- await secretValidationRuleService.validateSecrets(+ await $validateSecrets({projectId,environment,envId: folder.envId,secretPath,- secrets: secretsToValidate,- canAccessLocation: $canDescribeSecretAt(permission)+ secrets: secretsToValidate},+ permission,tx);}diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.tsindex 564c0f5296..97a7679705 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts@@ -14,10 +14,19 @@ export const CONSTRAINT_LABELS: Record<ConstraintKind, string> = {[ConstraintKind.ReuseOtherSecretsInScope]: "Prevent reuse of a value another secret in scope already holds"};+// Where a value that another secret already holds was found, once the service has looked it up.+export type TDuplicateSecret = {+ key: string;+ environment: string;+ secretPath: string;+};+export type TConstraintViolation = {kind: ConstraintKind;label: string;message: string;+ // Carried instead of written into the message, which never names a location. See secret-validation-rule-errors.+ duplicateOf?: TDuplicateSecret;};const violation = (kind: ConstraintKind, message: string): TConstraintViolation => ({diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-errors.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-errors.tsnew file mode 100644index 0000000000..007c3c76e8--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-errors.ts@@ -0,0 +1,41 @@+import { BadRequestError } from "@app/lib/errors";++import { TConstraintViolation } from "./secret-validation-rule-constraint-fns";++export type TCanDescribeLocation = (environment: string, secretPath: string) => boolean;++export type TSecretValidationFailure = {+ secretKey: string;+ ruleName: string;+ violation: TConstraintViolation;+};++const describeFailure = (+ { secretKey, ruleName, violation }: TSecretValidationFailure,+ canDescribeLocation?: TCanDescribeLocation+) => {+ const duplicate = violation.duplicateOf;+ const message =+ duplicate && canDescribeLocation?.(duplicate.environment, duplicate.secretPath)+ ? `value is already used by secret "${duplicate.key}" in environment "${duplicate.environment}" at path "${duplicate.secretPath}"`+ : violation.message;++ return `Secret "${secretKey}": ${message} (rule: "${ruleName}", constraint: ${violation.label})`;+};++export const describeSecretValidationFailures = (+ failures: TSecretValidationFailure[],+ canDescribeLocation?: TCanDescribeLocation+) => {+ const described = failures.map((failure) => describeFailure(failure, canDescribeLocation));+ return `Secret validation failed:\n${described.join("\n\n")}`;+};++export class SecretValidationError extends BadRequestError {+ readonly failures: TSecretValidationFailure[];++ constructor(failures: TSecretValidationFailure[]) {+ super({ message: describeSecretValidationFailures(failures) });+ this.failures = failures;+ }+}diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.tsindex c5f52b7029..c84e523066 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts@@ -13,6 +13,7 @@ import {SecretRotationRuleProvider,SecretValidationRuleType} from "./secret-validation-rule-enums";+import { SecretValidationError, TSecretValidationFailure } from "./secret-validation-rule-errors";import { SECRET_VALIDATION_RULE_NAME_MAP } from "./secret-validation-rule-maps";import { TValueConstraints } from "./secret-validation-rule-schemas";import { TGeneratedCredentialProvider, TSecretValidationRuleConfig } from "./secret-validation-rule-types";@@ -157,21 +158,17 @@ export const enforceSecretValidationRules = ({rules: TRuleToEnforce[];secrets: (TSecretToValidate & { previousValues?: string[] })[];}): void => {- const failures: string[] = [];+ const failures: TSecretValidationFailure[] = [];for (const rule of rules) {for (const secret of secrets) {for (const violation of evaluateStaticSecretConstraints(rule.config, secret)) {- failures.push(- `Secret "${secret.key}": ${violation.message} (rule: "${rule.name}", constraint: ${violation.label})`- );+ failures.push({ secretKey: secret.key, ruleName: rule.name, violation });}}}- if (failures.length) {- throw new BadRequestError({ message: `Secret validation failed:\n${failures.join("\n\n")}` });- }+ if (failures.length) throw new SecretValidationError(failures);};// Runtime provider types that validation rules can constrain. Anything unmapped returns null, whichdiff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-service.tsindex 6e7e344ca4..3ec84ec7a6 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@@ -19,7 +19,7 @@ import { containsSecretReference, expandSecretReferencesFactory } from "../secreimport { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";import { MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS } from "./secret-validation-rule-constants";-import { mergeConstraints } from "./secret-validation-rule-constraint-fns";+import { mergeConstraints, TDuplicateSecret } from "./secret-validation-rule-constraint-fns";import { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";import { ConstraintTarget, SecretValidationRuleType } from "./secret-validation-rule-enums";import {@@ -48,7 +48,7 @@ import {TUpdateSecretValidationRuleDTO,TValidateSecretsDTO} from "./secret-validation-rule-types";-import { TDuplicateSecret, TStaticSecretsRuleConfig } from "./static-secrets";+import { TStaticSecretsRuleConfig } from "./static-secrets";/** Only static-secret rules can ask for a value no other secret already holds. */const $preventsReuseAcrossSecrets = (config: TSecretValidationRuleConfig) =>@@ -410,9 +410,8 @@ export const secretValidationRuleServiceFactory = ({secretPath,secrets,scope,- canAccessLocation,generateSecretBlindIndex- }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets" | "canAccessLocation"> & {+ }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets"> & {scope: { envId?: string | null; secretPath: string };generateSecretBlindIndex: (value: Buffer) => Promise<string>;},@@ -452,20 +451,6 @@ export const secretValidationRuleServiceFactory = ({const folderPaths = await folderDAL.findSecretPathByFolderIds(projectId, folderIds, tx);const pathByFolderId = new Map(folderIds.map((id, idx) => [id, folderPaths[idx]?.path ?? "/"]));- const accessByLocation = new Map<string, boolean>();- const isHidden = (dupEnvironment: string, dupPath: string) => {- // A caller that cannot say what the writer may read gets the location withheld, never leaked.- if (!canAccessLocation) return true;-- const location = `${dupEnvironment}:${dupPath}`;- let hidden = accessByLocation.get(location);- if (hidden === undefined) {- hidden = !canAccessLocation(dupEnvironment, dupPath);- accessByLocation.set(location, hidden);- }- return hidden;- };-// The lookup spans the project, so drop the hits the rule's own path does not reach.const inScope = new Map<string, TDuplicateSecret>();existing.forEach((secret) => {@@ -477,8 +462,7 @@ export const secretValidationRuleServiceFactory = ({inScope.set(secret.secretValueBlindIndex, {key: secret.key,environment: secret.environment,- secretPath: dupPath,- hidden: isHidden(secret.environment, dupPath)+ secretPath: dupPath});});@@ -493,7 +477,7 @@ export const secretValidationRuleServiceFactory = ({};const validateSecrets = async (- { projectId, environment, envId, secretPath, secrets, canAccessLocation }: TValidateSecretsDTO,+ { projectId, environment, envId, secretPath, secrets }: TValidateSecretsDTO,tx?: Knex) => {if (!secrets.length) return;@@ -553,7 +537,6 @@ export const secretValidationRuleServiceFactory = ({secretPath,secrets,scope: reuseAcrossSecretsRule.scope,- canAccessLocation,generateSecretBlindIndex},txdiff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-types.tsindex df278dd10d..542584f604 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts@@ -129,10 +129,6 @@ export type TValidateSecretsDTO = {envId: string;secretPath: string;secrets: TSecretToValidate[];- // Whether the writer may read a location a duplicate value was found in. A violation must not name- // a secret they cannot see, telling them where a value they hold is also used, so a caller that- // omits this has every location hidden.- canAccessLocation?: (environment: string, secretPath: string) => boolean;};export type TFindConstraintsForGeneratedSecretDTO = {diff --git a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.tsindex cf077f5908..861b882668 100644--- a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts+++ b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts@@ -1,16 +1,12 @@-import { CONSTRAINT_LABELS, evaluateConstraints, TConstraintViolation } from "../secret-validation-rule-constraint-fns";+import {+ CONSTRAINT_LABELS,+ evaluateConstraints,+ TConstraintViolation,+ TDuplicateSecret+} from "../secret-validation-rule-constraint-fns";import { ConstraintKind, ConstraintTarget } from "../secret-validation-rule-enums";import { TStaticSecretsRuleConfig } from "./static-secrets-rule-types";-// Where a value that another secret already holds was found, once the service has looked it up.-export type TDuplicateSecret = {- key: string;- environment: string;- secretPath: string;- // Set when the writer cannot read the location, so the message has to stay vague.- hidden?: boolean;-};-export type TSecretToValidate = {key: string;value?: string;@@ -55,10 +51,8 @@ export const evaluateStaticSecretConstraints = (violations.push({kind: ConstraintKind.ReuseOtherSecretsInScope,label: CONSTRAINT_LABELS[ConstraintKind.ReuseOtherSecretsInScope],- // Naming a secret the writer cannot read would leak where a value they do know is also used.- message: duplicateOf.hidden- ? "value is already used by another secret in this project"- : `value is already used by secret "${duplicateOf.key}" in environment "${duplicateOf.environment}" at path "${duplicateOf.secretPath}"`+ message: "value is already used by another secret in this project",+ duplicateOf});}