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
udpate API to new format and add migration
Matheus Nogueira1e5b3b403570
diff --git a/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts b/backend/e2e-test/routes/v1/secret-validation-rules.spec.tsindex 8149ffee97..af6feb7ff4 100644--- a/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts+++ b/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts@@ -22,7 +22,7 @@ describe("Secret validation rules", () => {name: "no-duplicate-values-in-prod",environment: PROD_ENV,secretPath: "/",- valueConstraints: { reusePrevention: { otherSecretsInScope: true } },+ valueConstraints: { uniqueWithinScope: true },authToken});});diff --git a/backend/src/db/migrations/20260918104500_secret-validation-rule-flatten-reuse-prevention.ts b/backend/src/db/migrations/20260918104500_secret-validation-rule-flatten-reuse-prevention.tsnew file mode 100644index 0000000000..9151128e3a--- /dev/null+++ b/backend/src/db/migrations/20260918104500_secret-validation-rule-flatten-reuse-prevention.ts@@ -0,0 +1,132 @@+import { Knex } from "knex";++import { inMemoryKeyStore } from "@app/keystore/memory";+import { initLogger, logger } from "@app/lib/logger";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import { TableName } from "../schemas";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";+import { createCircularCache } from "./utils/ring-buffer";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";++const BATCH_SIZE = 500;++// Only a static-secrets rule carries valueConstraints, so the other types need no decryption at all.+const STATIC_SECRETS_TYPE = "static-secrets";++type TReusePrevention = { previousVersions?: number; otherSecretsInScope?: boolean };++type TValueConstraints = {+ reusePrevention?: TReusePrevention;+ uniqueAcrossLastVersions?: number;+ uniqueWithinScope?: boolean;+};++type TRuleConfig = { valueConstraints?: TValueConstraints };++const flattenReusePrevention = (config: TRuleConfig): TRuleConfig => {+ if (!config.valueConstraints?.reusePrevention) return config;++ const { reusePrevention, ...constraints } = config.valueConstraints;+ const { previousVersions, otherSecretsInScope } = reusePrevention;++ return {+ ...config,+ valueConstraints: {+ ...constraints,+ ...(previousVersions !== undefined && { uniqueAcrossLastVersions: previousVersions }),+ ...(otherSecretsInScope !== undefined && { uniqueWithinScope: otherSecretsInScope })+ }+ };+};++const nestReusePrevention = (config: TRuleConfig): TRuleConfig => {+ if (!config.valueConstraints) return config;++ const { uniqueAcrossLastVersions, uniqueWithinScope, ...constraints } = config.valueConstraints;+ if (uniqueAcrossLastVersions === undefined && uniqueWithinScope === undefined) return config;++ return {+ ...config,+ valueConstraints: {+ ...constraints,+ reusePrevention: {+ ...(uniqueAcrossLastVersions !== undefined && { previousVersions: uniqueAcrossLastVersions }),+ ...(uniqueWithinScope !== undefined && { otherSecretsInScope: uniqueWithinScope })+ }+ }+ };+};++const rewriteConfigs = async (knex: Knex, convert: (config: TRuleConfig) => TRuleConfig) => {+ const rules = await knex(TableName.SecretValidationRule)+ .where("type", STATIC_SECRETS_TYPE)+ .select("id", "projectId", "encryptedInputs");+ if (!rules.length) return;++ initLogger();++ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const superAdminDAL = superAdminDALFactory(knex);+ const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);+ const keyStore = inMemoryKeyStore();+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });+ const projectKmsCache =+ createCircularCache<Awaited<ReturnType<(typeof kmsService)["createCipherPairWithDataKey"]>>>(25);++ const updates: { id: string; encryptedInputs: Buffer }[] = [];++ for (const rule of rules) {+ let projectKms = projectKmsCache.getItem(rule.projectId);+ if (!projectKms) {+ // eslint-disable-next-line no-await-in-loop+ projectKms = await kmsService.createCipherPairWithDataKey(+ { type: KmsDataKey.SecretManager, projectId: rule.projectId },+ knex+ );+ projectKmsCache.push(rule.projectId, projectKms);+ }++ let config: TRuleConfig;+ try {+ config = JSON.parse(projectKms.decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as TRuleConfig;+ } catch (err) {+ // A rule we cannot read is a rule that would silently stop being enforced once the field is renamed.+ logger.error(err, `Migration failed to decrypt secret validation rule [ruleId=${rule.id}]`);+ throw err;+ }++ const converted = convert(config);+ // eslint-disable-next-line no-continue+ if (converted === config) continue;++ const { cipherTextBlob } = projectKms.encryptor({ plainText: Buffer.from(JSON.stringify(converted)) });+ updates.push({ id: rule.id, encryptedInputs: cipherTextBlob });+ }++ await knex.transaction(async (trx) => {+ for (let i = 0; i < updates.length; i += BATCH_SIZE) {+ // eslint-disable-next-line no-await-in-loop+ await Promise.all(+ updates+ .slice(i, i + BATCH_SIZE)+ .map((update) =>+ trx(TableName.SecretValidationRule)+ .where({ id: update.id })+ .update({ encryptedInputs: update.encryptedInputs })+ )+ );+ }+ });+};++export async function up(knex: Knex): Promise<void> {+ await rewriteConfigs(knex, flattenReusePrevention);+}++export async function down(knex: Knex): Promise<void> {+ await rewriteConfigs(knex, nestReusePrevention);+}diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex fba3548bed..3e12b0f144 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4128,10 +4128,8 @@ export const SecretValidationRules = {requiredSuffix: `A string the ${target} must end with.`}),REUSE_PREVENTION: {- reusePrevention:- "Rejects a value for repeating one already in use. Omit to allow any value the other constraints accept.",- previousVersions: `How many of the secret's own previous versions the new value must differ from. Between 1 and ${MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS}.`,- otherSecretsInScope:+ uniqueAcrossLastVersions: `How many of the secret's own previous versions the new value must differ from. Between 1 and ${MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS}. Omit to accept a value the secret has held before.`,+ uniqueWithinScope:"Set to true to reject a value that another secret in the rule's scope already holds. Requires blind indexing on the project."},STATIC_SECRETS: {diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.tsindex e9a78e58cd..ba362df927 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts@@ -42,21 +42,6 @@ const regexPatternSchema = zconst affixSchema = z.string().min(1).max(MAX_CONSTRAINT_AFFIX_LENGTH);-const ReusePreventionSchema = z- .object({- previousVersions: z- .number()- .int()- .min(1)- .max(MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS)- .optional()- .describe(SecretValidationRules.REUSE_PREVENTION.previousVersions),- otherSecretsInScope: z.boolean().optional().describe(SecretValidationRules.REUSE_PREVENTION.otherSecretsInScope)- })- .refine((reusePrevention) => Object.values(reusePrevention).some((value) => value !== undefined), {- message: "Set at least one reuse prevention option, or leave reusePrevention out entirely"- });-// the constraints every target supportsexport const BaseConstraintsSchema = z.object({minLength: lengthSchema(MAX_SECRET_CONSTRAINT_LENGTH).optional(),@@ -103,15 +88,20 @@ export const buildConstraintsSchema = (target: ConstraintTarget) =>export const buildValueConstraintsSchema = (target: ConstraintTarget) =>withLengthWindowCheck({...describedConstraintFields(target).shape,- reusePrevention: ReusePreventionSchema.optional().describe(SecretValidationRules.REUSE_PREVENTION.reusePrevention)+ uniqueAcrossLastVersions: z+ .number()+ .int()+ .min(1)+ .max(MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS)+ .optional()+ .describe(SecretValidationRules.REUSE_PREVENTION.uniqueAcrossLastVersions),+ uniqueWithinScope: z.boolean().optional().describe(SecretValidationRules.REUSE_PREVENTION.uniqueWithinScope)});export type TConstraints = z.infer<typeof BaseConstraintsSchema>;-export type TReusePrevention = { previousVersions?: number; otherSecretsInScope?: boolean };-// a secret value additionally supports being checked against values it has already had-export type TValueConstraints = TConstraints & { reusePrevention?: TReusePrevention };+export type TValueConstraints = TConstraints & { uniqueAcrossLastVersions?: number; uniqueWithinScope?: boolean };// true when at least one constraint field is set across every target on the ruleexport const hasAnyConstraint = (targets: (Record<string, unknown> | null | undefined)[]) =>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.tsindex 3ec84ec7a6..68dad69329 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@@ -52,7 +52,7 @@ import { TStaticSecretsRuleConfig } from "./static-secrets";/** Only static-secret rules can ask for a value no other secret already holds. */const $preventsReuseAcrossSecrets = (config: TSecretValidationRuleConfig) =>- Boolean((config as TStaticSecretsRuleConfig).valueConstraints?.reusePrevention?.otherSecretsInScope);+ Boolean((config as TStaticSecretsRuleConfig).valueConstraints?.uniqueWithinScope);type TSecretValidationRuleServiceFactoryDep = {secretValidationRuleDAL: TSecretValidationRuleDALFactory;@@ -503,7 +503,7 @@ export const secretValidationRuleServiceFactory = ({// reading version history is only worth it when a covering rule actually forbids reuseconst versionsToCheck = Math.max(0,- ...coveringRules.map((rule) => rule.config.valueConstraints?.reusePrevention?.previousVersions ?? 0)+ ...coveringRules.map((rule) => rule.config.valueConstraints?.uniqueAcrossLastVersions ?? 0));const previousValuesBySecretId: Record<string, string[]> = {};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 861b882668..a605cb08a0 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@@ -37,7 +37,7 @@ export const evaluateStaticSecretConstraints = (}));- const versionCount = config.valueConstraints.reusePrevention?.previousVersions;+ const versionCount = config.valueConstraints.uniqueAcrossLastVersions;if (versionCount !== undefined && secret.previousValues?.slice(0, versionCount).includes(secret.value)) {violations.push({kind: ConstraintKind.ReusePreviousVersions,@@ -47,7 +47,7 @@ export const evaluateStaticSecretConstraints = (}const { duplicateOf } = secret;- if (config.valueConstraints.reusePrevention?.otherSecretsInScope && duplicateOf) {+ if (config.valueConstraints.uniqueWithinScope && duplicateOf) {violations.push({kind: ConstraintKind.ReuseOtherSecretsInScope,label: CONSTRAINT_LABELS[ConstraintKind.ReuseOtherSecretsInScope],diff --git a/docs/documentation/platform/secret-validation-rules.mdx b/docs/documentation/platform/secret-validation-rules.mdxindex 054fcba9ba..a8bb272ac9 100644--- a/docs/documentation/platform/secret-validation-rules.mdx+++ b/docs/documentation/platform/secret-validation-rules.mdx@@ -47,22 +47,20 @@ Which targets a rule offers depends on its type:- A **Static Secrets** rule constrains the secret **key**, the secret **value**, or both.- A **Dynamic Secrets** or **Secret Rotations** rule constrains the **generated password**.-**Prevent value reuse** is available on the secret value only. A key has no version history, and a generated credential is produced rather than submitted. It sits under its own `reusePrevention` object, which holds the options for rejecting a repeated value:+**Prevent value reuse** is available on the secret value only. A key has no version history, and a generated credential is produced rather than submitted. Two fields on `valueConstraints` reject a repeated value:```json"valueConstraints": {- "reusePrevention": {- "previousVersions": 10,- "otherSecretsInScope": true- }+ "uniqueAcrossLastVersions": 10,+ "uniqueWithinScope": true}```-`previousVersions` is a whole number between 1 and 25. It rejects a new value that matches any of that many of the secret's own prior versions.+`uniqueAcrossLastVersions` is a whole number between 1 and 25. It rejects a new value that matches any of that many of the secret's own prior versions.-`otherSecretsInScope` rejects a value that another secret the rule covers already holds. It requires secret blind indexing on the project; Infisical offers to enable it when you turn the option on.+`uniqueWithinScope` rejects a value that another secret the rule covers already holds. It requires secret blind indexing on the project; Infisical offers to enable it when you turn the option on.-Set either option on its own or both together. Leave `reusePrevention` out to accept any value the other constraints allow.+Set either field on its own or both together. Leave both out to accept any value the other constraints allow.A rule has to set at least one constraint. Infisical rejects a rule that constrains nothing.@@ -168,7 +166,7 @@ curl --request POST \"valueConstraints": {"minLength": 16,"maxLength": 128,- "reusePrevention": { "previousVersions": 10 }+ "uniqueAcrossLastVersions": 10}}'```diff --git a/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx b/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsxindex 86916154a1..170e6e7eec 100644--- a/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx+++ b/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx@@ -112,8 +112,8 @@ const describeConstraints = (constraints: TValueConstraints) => {add("minLength", "Min length", constraints.minLength);add("maxLength", "Max length", constraints.maxLength);- if (constraints.reusePrevention?.previousVersions !== undefined) {- chips.push({ key: "reusePrevention", label: "Prevent reuse of previous secret values" });+ if (constraints.uniqueAcrossLastVersions !== undefined) {+ chips.push({ key: "uniqueAcrossLastVersions", label: "Prevent reuse of previous secret values" });}return chips;diff --git a/frontend/src/hooks/api/secretValidationRules/index.ts b/frontend/src/hooks/api/secretValidationRules/index.tsindex b630b4810e..82863ee851 100644--- a/frontend/src/hooks/api/secretValidationRules/index.ts+++ b/frontend/src/hooks/api/secretValidationRules/index.ts@@ -10,7 +10,6 @@ export type {TCreateSecretValidationRuleDTO,TDeleteSecretValidationRuleDTO,TGeneratedCredentialProvider,- TReusePrevention,TSecretValidationRule,TSecretValidationRuleConfig,TStaticSecretsRuleConfig,diff --git a/frontend/src/hooks/api/secretValidationRules/types.ts b/frontend/src/hooks/api/secretValidationRules/types.tsindex 9b198920df..2501643066 100644--- a/frontend/src/hooks/api/secretValidationRules/types.ts+++ b/frontend/src/hooks/api/secretValidationRules/types.ts@@ -46,13 +46,9 @@ export type TConstraints = {requiredSuffix?: string;};-export type TReusePrevention = {- previousVersions?: number;- otherSecretsInScope?: boolean;-};-export type TValueConstraints = TConstraints & {- reusePrevention?: TReusePrevention;+ uniqueAcrossLastVersions?: number;+ uniqueWithinScope?: boolean;};export type TStaticSecretsRuleConfig = {diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.tsindex 89423b1b47..cb10ac92df 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts@@ -300,8 +300,8 @@ export type TRule = TRuleForm & {isActive: boolean;};-// Each constraint kind maps to one field on the API's constraint object. Reuse prevention is grouped-// under its own key, so it is handled on its own rather than by a field name.+// Each constraint kind maps to one field on the API's constraint object. Reuse prevention spans two+// fields under a single form row, so it is handled on its own rather than by a field name.const CONSTRAINT_FIELDS: Record<string, keyof TConstraints> = {[ConstraintType.MinLength]: "minLength",[ConstraintType.MaxLength]: "maxLength",@@ -326,10 +326,8 @@ export const groupConstraintsByTarget = (constraints: TConstraint[]) => {if (type === ConstraintType.PreventValueReuse) {grouped[appliesTo] = {...current,- reusePrevention: {- ...(checkPreviousVersions && { previousVersions: Number(value) }),- ...(checkOtherSecretsInScope && { otherSecretsInScope: true })- }+ ...(checkPreviousVersions && { uniqueAcrossLastVersions: Number(value) }),+ ...(checkOtherSecretsInScope && { uniqueWithinScope: true })};} else {grouped[appliesTo] = {@@ -347,20 +345,20 @@ export const flattenConstraints = (constraints: TValueConstraints | null | undefined,appliesTo: ConstraintTarget): TConstraint[] => {- const { reusePrevention, ...fields } = constraints ?? {};+ const { uniqueAcrossLastVersions, uniqueWithinScope, ...fields } = constraints ?? {};const flattened: TConstraint[] = Object.entries(fields).filter(([, value]) => value !== undefined).map(([field, value]) => ({ type: CONSTRAINT_TYPES[field], appliesTo, value: String(value) }));- // `otherSecretsInScope` is absent on rules saved before the two checks were merged.- if (reusePrevention?.previousVersions !== undefined || reusePrevention?.otherSecretsInScope) {+ // `uniqueWithinScope` is absent on rules saved before the two checks were merged.+ if (uniqueAcrossLastVersions !== undefined || uniqueWithinScope) {flattened.push({type: ConstraintType.PreventValueReuse,appliesTo,- value: String(reusePrevention.previousVersions ?? DEFAULT_PREVENT_VALUE_REUSE_VERSIONS),- checkPreviousVersions: reusePrevention.previousVersions !== undefined,- checkOtherSecretsInScope: Boolean(reusePrevention.otherSecretsInScope)+ value: String(uniqueAcrossLastVersions ?? DEFAULT_PREVENT_VALUE_REUSE_VERSIONS),+ checkPreviousVersions: uniqueAcrossLastVersions !== undefined,+ checkOtherSecretsInScope: Boolean(uniqueWithinScope)});}