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
feat(validation-rules): api revamp
varonixe8988b155540
diff --git a/backend/src/db/migrations/20260908120000_secret-validation-rule-named-constraints.ts b/backend/src/db/migrations/20260908120000_secret-validation-rule-named-constraints.tsnew file mode 100644index 0000000000..17812e4b77--- /dev/null+++ b/backend/src/db/migrations/20260908120000_secret-validation-rule-named-constraints.ts@@ -0,0 +1,217 @@+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;++const ACTIVE_RULE_INDEX = "secret_validation_rules_projectid_isactive_index";++type TLegacyConstraint = { type: string; appliesTo: string; value: string };+type TLegacyConfig = { constraints?: TLegacyConstraint[]; providers?: string[] };++type TNamedConstraints = {+ minLength?: number;+ maxLength?: number;+ regexPattern?: string;+ requiredPrefix?: string;+ requiredSuffix?: string;+ reusePrevention?: { previousVersions?: number };+};++type TNamedConfig = {+ keyConstraints?: TNamedConstraints;+ valueConstraints?: TNamedConstraints;+ passwordConstraints?: TNamedConstraints;+ providers?: string[];+};++type TConstraintField = "keyConstraints" | "valueConstraints" | "passwordConstraints";++const TARGET_TO_FIELD: Record<string, TConstraintField> = {+ key: "keyConstraints",+ value: "valueConstraints",+ password: "passwordConstraints"+};++// Reuse prevention is grouped under its own object, so the field is addressed by path.+const KIND_TO_PATH: Record<string, string[]> = {+ "min-length": ["minLength"],+ "max-length": ["maxLength"],+ "regex-pattern": ["regexPattern"],+ "required-prefix": ["requiredPrefix"],+ "required-suffix": ["requiredSuffix"],+ "prevent-value-reuse": ["reusePrevention", "previousVersions"]+};++const PATH_TO_KIND: Record<string, string> = Object.fromEntries(+ Object.entries(KIND_TO_PATH).map(([kind, path]) => [path.join("."), kind])+);++const NUMERIC_KINDS = new Set(["min-length", "max-length", "prevent-value-reuse"]);++// the old shape allowed the same check twice on one target, which nothing rejected and both halves of which were enforced.+// keep the stricter of the two so the rule carries over meaning what it did.++const strictest = (field: keyof TNamedConstraints, existing: number, incoming: number) =>+ field === "maxLength" ? Math.min(existing, incoming) : Math.max(existing, incoming);++// a non-numeric length rendered as NaN at enforcement time, so it constrained nothing.+const toFieldValue = (kind: string, raw: string): string | number | null => {+ if (!NUMERIC_KINDS.has(kind)) return raw;+ const parsed = Number(raw);+ return Number.isInteger(parsed) && parsed >= 1 ? parsed : null;+};++// walk to the object holding the leaf, creating the groups on the way.+const resolveHolder = (bucket: Record<string, unknown>, path: string[]) => {+ let holder = bucket;+ for (const group of path.slice(0, -1)) {+ if (!holder[group]) holder[group] = {};+ holder = holder[group] as Record<string, unknown>;+ }+ return holder as Record<string, string | number>;+};++const toNamedConfig = (legacy: TLegacyConfig, ruleId: string): TNamedConfig => {+ const config: TNamedConfig = {};+ if (legacy.providers) config.providers = legacy.providers;++ for (const constraint of legacy.constraints ?? []) {+ const target = TARGET_TO_FIELD[constraint.appliesTo];+ const path = KIND_TO_PATH[constraint.type];+ const value = target && path ? toFieldValue(constraint.type, constraint.value) : null;++ if (value === null) {+ logger.warn(+ `Dropping secret validation constraint with no equivalent [ruleId=${ruleId}] [type=${constraint.type}] [appliesTo=${constraint.appliesTo}] [value=${constraint.value}]`+ );+ // eslint-disable-next-line no-continue+ continue;+ }++ const bucket = (config[target] ?? {}) as Record<string, unknown>;+ const holder = resolveHolder(bucket, path);+ const leaf = path[path.length - 1];+ const existing = holder[leaf];++ if (existing === undefined) {+ holder[leaf] = value;+ } else if (typeof existing === "number" && typeof value === "number") {+ holder[leaf] = strictest(leaf as keyof TNamedConstraints, existing, value);+ logger.warn(`Collapsed duplicate secret validation constraint [ruleId=${ruleId}] [type=${constraint.type}]`);+ } else {+ logger.warn(`Discarding duplicate secret validation constraint [ruleId=${ruleId}] [type=${constraint.type}]`);+ }++ config[target] = bucket as TNamedConstraints;+ }++ return config;+};++const toLegacyConfig = (named: TNamedConfig): TLegacyConfig => {+ const constraints: TLegacyConstraint[] = [];++ const collect = (target: string, prefix: string[], holder: Record<string, unknown>) => {+ Object.entries(holder).forEach(([field, value]) => {+ if (value === undefined || value === null) return;+ const path = [...prefix, field];+ if (typeof value === "object") {+ collect(target, path, value as Record<string, unknown>);+ return;+ }+ constraints.push({ type: PATH_TO_KIND[path.join(".")], appliesTo: target, value: String(value) });+ });+ };++ Object.entries(TARGET_TO_FIELD).forEach(([target, field]) => {+ const bucket = named[field];+ if (bucket) collect(target, [], bucket as Record<string, unknown>);+ });++ return { ...(named.providers && { providers: named.providers }), constraints };+};++const rewriteConfigs = async (knex: Knex, convert: (config: never, ruleId: string) => unknown) => {+ const rules = await knex(TableName.SecretValidationRule).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: unknown;+ try {+ config = JSON.parse(projectKms.decryptor({ cipherTextBlob: rule.encryptedInputs }).toString());+ } catch (err) {+ logger.error(err, `Migration failed to decrypt secret validation rule [ruleId=${rule.id}]`);+ throw err;+ }++ const { cipherTextBlob } = projectKms.encryptor({+ plainText: Buffer.from(JSON.stringify(convert(config as never, rule.id)))+ });+ 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, toNamedConfig);++ await knex.schema.alterTable(TableName.SecretValidationRule, (tb) => {+ // Every secret write reads the project's active rules, and projectId alone does not narrow that.+ tb.index(["projectId", "isActive"], ACTIVE_RULE_INDEX);+ });+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.alterTable(TableName.SecretValidationRule, (tb) => {+ tb.dropIndex(["projectId", "isActive"], ACTIVE_RULE_INDEX);+ });++ await rewriteConfigs(knex, toLegacyConfig);+}diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 06ee4de354..8d73f79689 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6846,8 +6846,9 @@ interface SecretValidationRuleCreateEvent {ruleId: string;name: string;type: string;- environmentSlug?: string;+ environment?: string;secretPath: string;+ isActive: boolean;};}@@ -6868,6 +6869,7 @@ interface SecretValidationRuleDeleteEvent {metadata: {ruleId: string;name: string;+ type: string;};}diff --git a/backend/src/ee/services/audit-report/audit-report-fns.ts b/backend/src/ee/services/audit-report/audit-report-fns.tsindex fde179bf5d..d209258be8 100644--- a/backend/src/ee/services/audit-report/audit-report-fns.ts+++ b/backend/src/ee/services/audit-report/audit-report-fns.ts@@ -2,12 +2,6 @@ import { z } from "zod";import { TAuditReports } from "@app/db/schemas";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";-import {- CONSTRAINT_LABELS,- evaluateConstraint,- TStaticSecretConstraintViolation-} from "@app/services/secret-validation-rule/secret-validation-rule-fns";-import { TConstraint } from "@app/services/secret-validation-rule/secret-validation-rule-types";import {AuditReportResultEntrySchema,@@ -15,8 +9,7 @@ import {AuditReportType,OrgAuditReportResultEntrySchema,OrgAuditReportType,- TGeneratedReport,- TSecretToValidate+ TGeneratedReport} from "./audit-report-types";export const DAY_IN_MS = 24 * 60 * 60 * 1000;@@ -131,21 +124,3 @@ export const presentOrgAuditReport = (report: TAuditReports) => ({});export type TPresentedOrgAuditReport = ReturnType<typeof presentOrgAuditReport>;--export const evaluateStaticSecretConstraints = (- constraints: TConstraint[],- secret: TSecretToValidate-): TStaticSecretConstraintViolation[] => {- const violations: TStaticSecretConstraintViolation[] = [];- for (const constraint of constraints) {- const error = evaluateConstraint(constraint, secret);- if (error) {- violations.push({- constraintType: constraint.type,- constraintLabel: CONSTRAINT_LABELS[constraint.type],- message: error- });- }- }- return violations;-};diff --git a/backend/src/ee/services/audit-report/audit-report-generators.ts b/backend/src/ee/services/audit-report/audit-report-generators.tsindex ba0ba2a0fa..453a539136 100644--- a/backend/src/ee/services/audit-report/audit-report-generators.ts+++ b/backend/src/ee/services/audit-report/audit-report-generators.ts@@ -13,9 +13,12 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-foldimport { containsSecretReference } from "@app/services/secret-v2-bridge/secret-reference-fns";import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";import { TSecretValidationRuleDALFactory } from "@app/services/secret-validation-rule/secret-validation-rule-dal";-import { evaluateStaticSecretConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-fns";-import { parseSecretValidationRuleInputs } from "@app/services/secret-validation-rule/secret-validation-rule-schemas";-import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-types";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";+import { parseSecretValidationRuleConfig } from "@app/services/secret-validation-rule/secret-validation-rule-fns";+import {+ evaluateStaticSecretConstraints,+ TStaticSecretsRuleConfig+} from "@app/services/secret-validation-rule/static-secrets";import { buildFolderPathMap, DAY_IN_MS, daysSince } from "./audit-report-fns";import { AuditReportType, MAX_AUDIT_REPORT_ROWS, TGeneratedReport, TReportRow } from "./audit-report-types";@@ -273,10 +276,10 @@ const secretValidationComplianceReport: TReportDefinition = {name: rule.name,envId: rule.envId ?? null,secretPath: rule.secretPath,- constraints: parseSecretValidationRuleInputs(+ config: parseSecretValidationRuleConfig(rule.type,JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown- ).constraints+ ) as TStaticSecretsRuleConfig}));const secrets = await dal.secretV2BridgeDAL.findValueValidationCandidatesByProject(projectId);@@ -318,7 +321,7 @@ const secretValidationComplianceReport: TReportDefinition = {const value = decryptor({ cipherTextBlob: secret.encryptedValue }).toString();for (const rule of coveringRules) {- const violations = evaluateStaticSecretConstraints(rule.constraints, { key: secret.key, value });+ const violations = evaluateStaticSecretConstraints(rule.config, { key: secret.key, value });for (const violation of violations) {if (rows.length >= MAX_AUDIT_REPORT_ROWS) {truncated = true;@@ -329,7 +332,7 @@ const secretValidationComplianceReport: TReportDefinition = {environment: folder.envSlug,secretPath: folder.path,ruleName: rule.name,- constraintType: violation.constraintLabel,+ constraintType: violation.label,violation: violation.message});}diff --git a/backend/src/ee/services/audit-report/audit-report-types.ts b/backend/src/ee/services/audit-report/audit-report-types.tsindex ca7f98c400..7fa93e3bb0 100644--- a/backend/src/ee/services/audit-report/audit-report-types.ts+++ b/backend/src/ee/services/audit-report/audit-report-types.ts@@ -94,9 +94,3 @@ export type TAuditReportServiceActor = OrgServiceActor;export type TGenerateAuditReportJobPayload = {auditReportId: string;};--export type TSecretToValidate = {- key: string;- value?: string;- previousValues?: string[];-};diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.tsindex aef6e591fd..ff5f3ec3c2 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts@@ -20,9 +20,9 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";import { convertDynamicSecretProviderToValidationRuleProvider } from "@app/services/secret-validation-rule/secret-validation-rule-fns";import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";-import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-types";import { TUserDALFactory } from "@app/services/user/user-dal";import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";@@ -177,7 +177,7 @@ export const dynamicSecretLeaseServiceFactory = ({type: SecretValidationRuleType.DynamicSecrets,provider: ruleProvider});- if (matched.constraints.length) {+ if (matched.ruleNames.length) {passwordValidation = matched;}}diff --git a/backend/src/ee/services/dynamic-secret/providers/milvus.ts b/backend/src/ee/services/dynamic-secret/providers/milvus.tsindex 3e1121e042..95614f0d22 100644--- a/backend/src/ee/services/dynamic-secret/providers/milvus.ts+++ b/backend/src/ee/services/dynamic-secret/providers/milvus.ts@@ -236,7 +236,7 @@ export const MilvusProvider = ({},sanitizeMilvusUsername);- const password = metadata?.passwordValidation?.constraints?.length+ const password = metadata?.passwordValidation? generatePasswordWithConstraints(metadata.passwordValidation.constraints): generatePassword();const roleName = deriveRoleName(username);diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.tsindex b94ef3f2a9..b73c92f258 100644--- a/backend/src/ee/services/dynamic-secret/providers/models.ts+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts@@ -5,7 +5,7 @@ import { TDynamicSecrets } from "@app/db/schemas";import { SshCertKeyAlgorithm } from "@app/lib/ssh";import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";-import { TConstraint } from "@app/services/secret-validation-rule/secret-validation-rule-types";+import { TConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-types";import {ActorIdentityAttributes,@@ -1063,7 +1063,7 @@ export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [export type TDynamicProviderCreateMetadata = {projectId: string;passwordValidation?: {- constraints: TConstraint[];+ constraints: TConstraints;ruleNames: string[];};};diff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.tsindex ec40109c87..bc244e07be 100644--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts@@ -306,7 +306,7 @@ export const SqlDatabaseProvider = ({// When a secret validation rule covers this provider/scope, it fully// replaces the user-configured password requirements.- const password = metadata?.passwordValidation?.constraints?.length+ const password = metadata?.passwordValidation? generatePasswordWithConstraints(metadata.passwordValidation.constraints): generatePassword(providerInputs.client, providerInputs.passwordRequirements);const gatewayCallback = async (host = providerInputs.host, port = providerInputs.port) => {diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 77d7091a50..fff38d43bc 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -38,6 +38,7 @@ import {ProjectPermissionSecretScanningDataSourceActions,ProjectPermissionSecretScanningFindingActions,ProjectPermissionSecretSyncActions,+ ProjectPermissionSecretValidationRuleActions,ProjectPermissionSet,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";@@ -292,6 +293,16 @@ const buildAdminPermissionRules = () => {ProjectPermissionSub.SecretSyncs);+ can(+ [+ ProjectPermissionSecretValidationRuleActions.Create,+ ProjectPermissionSecretValidationRuleActions.Edit,+ ProjectPermissionSecretValidationRuleActions.Delete,+ ProjectPermissionSecretValidationRuleActions.Read+ ],+ ProjectPermissionSub.SecretValidationRules+ );+can([ProjectPermissionPkiSyncActions.Create,@@ -643,6 +654,8 @@ const buildMemberPermissionRules = () => {ProjectPermissionSub.SecretSyncs);+ can([ProjectPermissionSecretValidationRuleActions.Read], ProjectPermissionSub.SecretValidationRules);+can([ProjectPermissionSecretScanningDataSourceActions.Read,@@ -719,6 +732,7 @@ const buildViewerPermissionRules = () => {can(ProjectPermissionCertificatePolicyActions.Read, ProjectPermissionSub.CertificatePolicies);can(ProjectPermissionCmekActions.Read, ProjectPermissionSub.Cmek);can(ProjectPermissionSecretSyncActions.Read, ProjectPermissionSub.SecretSyncs);+ can(ProjectPermissionSecretValidationRuleActions.Read, ProjectPermissionSub.SecretValidationRules);can(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs);can([ProjectPermissionApplicationActions.Read, ProjectPermissionApplicationActions.List],diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex 2f488e0d14..18c4f4aa46 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -166,6 +166,13 @@ export enum ProjectPermissionSecretSyncActions {RemoveSecrets = "remove-secrets"}+export enum ProjectPermissionSecretValidationRuleActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionPkiSyncActions {Read = "read",Create = "create",@@ -347,6 +354,7 @@ export enum ProjectPermissionSub {Kms = "kms",Cmek = "cmek",SecretSyncs = "secret-syncs",+ SecretValidationRules = "secret-validation-rules",PkiSyncs = "pki-syncs",PkiDiscovery = "pki-discovery",PkiCertificateInstallations = "pki-certificate-installations",@@ -572,6 +580,7 @@ export type ProjectPermissionSet =ProjectPermissionSecretSyncActions,ProjectPermissionSub.SecretSyncs | (ForcedSubject<ProjectPermissionSub.SecretSyncs> & SecretSyncSubjectFields)]+ | [ProjectPermissionSecretValidationRuleActions, ProjectPermissionSub.SecretValidationRules]| [ProjectPermissionPkiSyncActions,ProjectPermissionSub.PkiSyncs | (ForcedSubject<ProjectPermissionSub.PkiSyncs> & PkiSyncSubjectFields)@@ -1448,6 +1457,12 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),+ z.object({+ subject: z.literal(ProjectPermissionSub.SecretValidationRules).describe("The entity this permission pertains to."),+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionSecretValidationRuleActions).describe(+ "Describe what action an entity can take."+ )+ }),z.object({subject: z.literal(ProjectPermissionSub.Environments).describe("The entity this permission pertains to."),action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(diff --git a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.tsindex 432744ecd3..51484e742c 100644--- a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts@@ -157,7 +157,7 @@ export const ldapPasswordRotationFactory: TRotationFactory<if (!credentials.url.startsWith("ldaps")) throw new Error("Password Rotation requires an LDAPS connection");const isConnectionRotation = credentials.dn === dn;- const password = passwordValidationContext?.constraints?.length+ const password = passwordValidationContext? generatePasswordWithConstraints(passwordValidationContext.constraints): generatePassword(passwordRequirements);diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.tsindex 3ccc7c4274..87f745ae37 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts@@ -96,9 +96,9 @@ import {} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";import { convertSecretRotationToValidationRuleProvider } from "@app/services/secret-validation-rule/secret-validation-rule-fns";import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";-import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-types";import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { WebhookEvents } from "@app/services/webhook/webhook-types";@@ -267,7 +267,7 @@ export const secretRotationV2ServiceFactory = ({type: SecretValidationRuleType.SecretRotations,provider});- if (!matched.constraints.length) return undefined;+ if (!matched.ruleNames.length) return undefined;return matched;};diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.tsindex 62d824c700..7c83c696d4 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts@@ -5,7 +5,7 @@ import { OrderByDirection } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { SecretsOrderBy } from "@app/services/secret/secret-types";-import { TConstraint } from "@app/services/secret-validation-rule/secret-validation-rule-types";+import { TConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-types";import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";@@ -512,7 +512,7 @@ export type TRotationFactoryCheckActiveCredentials<T extends TSecretRotationV2Ge// When present, factories that generate passwords must satisfy these// constraints and ignore any user-provided passwordRequirements.export type TRotationPasswordValidationContext = {- constraints: TConstraint[];+ constraints: TConstraints;ruleNames: string[];};diff --git a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.tsindex 0f3b236aa8..1a01d8be8d 100644--- a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts@@ -94,7 +94,7 @@ export const sqlCredentialsRotationFactory: TRotationFactory<// When a secret validation rule covers this rotation, its constraints// fully replace the user-configured passwordRequirements.const generateRotationPassword = () =>- passwordValidationContext?.constraints?.length+ passwordValidationContext? generatePasswordWithConstraints(passwordValidationContext.constraints): generatePassword(passwordRequirement);diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.tsindex 3019342b72..1b2b30111e 100644--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts@@ -455,7 +455,7 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<const $rotatePassword = async (currentPassword?: string): Promise<{ username: string; password: string }> => {const conn = await getResolvedConnection();const { credentials } = conn;- const newPassword = passwordValidationContext?.constraints?.length+ const newPassword = passwordValidationContext? generatePasswordWithConstraints(passwordValidationContext.constraints): generatePassword(passwordRequirements);diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 69104e1aae..0676bed76d 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -15,6 +15,9 @@ import { CaType } from "@app/services/certificate-authority/certificate-authoritimport { CERTIFICATE_AUTHORITIES_TYPE_MAP } from "@app/services/certificate-authority/certificate-authority-maps";import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";import { SECRET_SYNC_CONNECTION_MAP, SECRET_SYNC_NAME_MAP } from "@app/services/secret-sync/secret-sync-maps";+import { MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS } from "@app/services/secret-validation-rule/secret-validation-rule-constants";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";+import { SECRET_VALIDATION_RULE_NAME_MAP } from "@app/services/secret-validation-rule/secret-validation-rule-maps";const IDENTITY_AUTH_SUB_ORGANIZATION_NAME ="When set, this will scope the login session to the specified organization the machine identity has access to. If omitted, the session defaults to the organization where the machine identity was created in.";@@ -4039,50 +4042,71 @@ export const RELAYS = {}} as const;-export const SECRET_VALIDATION_RULES = {- RULE: {- type: "The kind of secret the rule applies to. Determines which fields the rule accepts and where the constraints are enforced: `static-secrets` constraints run on write, while `dynamic-secrets` and `secret-rotations` constraints shape the generated credential.",- constraints:- "The constraints enforced by this rule. Each constraint names what it checks (`type`), what it applies to (`appliesTo`), and its `value`, e.g. the minimum character count for `min-length` or the pattern for `regex-pattern`.",- dynamicSecretProviders:- "The dynamic secret providers this rule applies to. A lease is only constrained when its provider is listed here.",- secretRotationProviders:- "The secret rotation providers this rule applies to. A rotation is only constrained when its provider is listed here.",- appliesToStatic: "What the constraint checks: the secret key or the secret value.",- appliesToGenerated: "What the constraint checks: the generated credential.",- constraintTypeStatic:- "The kind of check this constraint performs, e.g. `min-length`, `regex-pattern`, `required-prefix`, or `prevent-value-reuse`.",- constraintTypeGenerated:- "The kind of check this constraint performs, e.g. `min-length`, `regex-pattern`, or `required-prefix`.",- constraintValue:- "The value the constraint is checked against, e.g. the minimum length, the regex pattern, or the required prefix/suffix string."- },- LIST: {- projectId: "The ID of the project to list secret validation rules for."- },- CREATE: {- projectId: "The ID of the project to create the secret validation rule in.",- name: "The name of the secret validation rule.",- description: "An optional description of the secret validation rule.",- environmentSlug:- "The slug of the environment this rule is scoped to. Omit to apply the rule to every environment in the project.",- secretPath: "The secret path this rule is scoped to.",- rule: "The rule configuration: which secret type it targets and the constraints to enforce."+export const SecretValidationRules = {+ LIST: (type?: SecretValidationRuleType) => ({+ projectId: `The ID of the project to list ${+ type ? SECRET_VALIDATION_RULE_NAME_MAP[type] : "Secret"+ } Validation Rules from.`+ }),+ GET_BY_ID: (type: SecretValidationRuleType) => ({+ ruleId: `The ID of the ${SECRET_VALIDATION_RULE_NAME_MAP[type]} Validation Rule to retrieve.`+ }),+ CREATE: (type: SecretValidationRuleType) => {+ const name = SECRET_VALIDATION_RULE_NAME_MAP[type];+ return {+ name: `The name of the ${name} Validation Rule to create.`,+ projectId: `The ID of the project to create the ${name} Validation Rule in.`,+ description: `An optional description of the ${name} Validation Rule.`,+ environment: `The slug of the environment to scope this rule to. Omit to enforce the rule in every environment of the project.`,+ secretPath: `The secret path to scope this rule to. Supports glob patterns such as \`/apps/**\`.`,+ isActive: `Whether the rule is enforced. An inactive rule is kept but ignored.`+ };},- UPDATE: {- projectId: "The ID of the project the secret validation rule belongs to.",- ruleId: "The ID of the secret validation rule to update.",- name: "The name of the secret validation rule.",- description: "An optional description of the secret validation rule.",- environmentSlug:- "The slug of the environment this rule is scoped to. Omit to leave the current scope unchanged; pass `null` to make the rule apply to every environment in the project.",- secretPath: "The secret path this rule is scoped to.",- rule: "The rule configuration: which secret type it targets and the constraints to enforce. Replaces the existing configuration as a whole, or omits to leave it untouched.",- isActive: "Whether the secret validation rule is active."+ UPDATE: (type: SecretValidationRuleType) => {+ const name = SECRET_VALIDATION_RULE_NAME_MAP[type];+ return {+ ruleId: `The ID of the ${name} Validation Rule to update.`,+ name: `The updated name of the ${name} Validation Rule.`,+ description: `The updated description of the ${name} Validation Rule.`,+ environment: `The slug of the environment to scope this rule to. Pass null to enforce the rule in every environment of the project.`,+ secretPath: `The secret path to scope this rule to. Supports glob patterns such as \`/apps/**\`.`,+ isActive: `Whether the rule is enforced. An inactive rule is kept but ignored.`+ };},- DELETE: {- projectId: "The ID of the project the secret validation rule belongs to.",- ruleId: "The ID of the secret validation rule to delete."+ DELETE: (type: SecretValidationRuleType) => ({+ ruleId: `The ID of the ${SECRET_VALIDATION_RULE_NAME_MAP[type]} Validation Rule to delete.`+ }),+ // Each constraint field reads the same way whichever target it sits on, so one template covers+ // the secret key, the secret value and a generated password.+ CONSTRAINTS: (target: string) => ({+ minLength: `The minimum number of characters the ${target} must contain.`,+ maxLength: `The maximum number of characters the ${target} may contain.`,+ regexPattern: `A regular expression the ${target} must match.`,+ requiredPrefix: `A string the ${target} must start with.`,+ 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}.`+ },+ STATIC_SECRETS: {+ keyConstraints:+ "Constraints enforced on the secret key when a secret is created or renamed. Omit to leave keys unconstrained.",+ valueConstraints:+ "Constraints enforced on the secret value when a secret is created or updated. Omit to leave values unconstrained."+ },+ GENERATED_CREDENTIALS: {+ passwordConstraints:+ "Constraints the generated password must satisfy. These replace any password requirements configured on the resource itself."+ },+ DYNAMIC_SECRETS: {+ providers:+ "The dynamic secret providers this rule applies to. A lease is only constrained when its provider is listed here."+ },+ SECRET_ROTATIONS: {+ providers:+ "The secret rotation providers this rule applies to. A rotation is only constrained when its provider is listed here."}} as const;diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex 06076dfc9b..782df31ebd 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -8,6 +8,10 @@ import {import { registerCmekRouter } from "@app/server/routes/v1/cmek-router";import { registerDashboardRouter } from "@app/server/routes/v1/dashboard-router";import { registerSecretSyncRouter, SECRET_SYNC_REGISTER_ROUTER_MAP } from "@app/server/routes/v1/secret-sync-routers";+import {+ registerSecretValidationRuleRouter,+ SECRET_VALIDATION_RULE_REGISTER_ROUTER_MAP+} from "@app/server/routes/v1/secret-validation-rule-routers";import { registerAccountRecoveryRouter } from "./account-recovery-router";import { registerAdminRouter } from "./admin-router";@@ -88,7 +92,6 @@ import { SECRET_REMINDER_REGISTER_ROUTER_MAP } from "./reminder-routers";import { registerSecretRequestsRouter } from "./secret-requests-router";import { registerSecretSharingRouter } from "./secret-sharing-router";import { registerSecretTagRouter } from "./secret-tag-router";-import { registerSecretValidationRuleRouter } from "./secret-validation-rule-router";import { registerSignerMembershipRoutes } from "./signer-membership-routers";import { registerSignerRouter } from "./signer-routers";import { registerSlackRouter } from "./slack-router";@@ -178,7 +181,6 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {await projectRouter.register(registerProjectIdentityRouter);await projectRouter.register(registerProjectEnvRouter);await projectRouter.register(registerSecretTagRouter);- await projectRouter.register(registerSecretValidationRuleRouter);await projectRouter.register(registerGroupProjectRouter);await projectRouter.register(registerDeprecatedIdentityProjectMembershipRouter);},@@ -351,6 +353,17 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {{ prefix: "/secret-syncs" });+ await server.register(+ async (validationRuleRouter) => {+ await validationRuleRouter.register(registerSecretValidationRuleRouter);++ for await (const [type, router] of Object.entries(SECRET_VALIDATION_RULE_REGISTER_ROUTER_MAP)) {+ await router(withRoutePrefix(validationRuleRouter, `/${type}`));+ }+ },+ { prefix: "/secret-validation-rules" }+ );+await server.register(async (reminderRouter) => {// register service specific reminder endpoints (reminders/secret)diff --git a/backend/src/server/routes/v1/secret-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-router.tsdeleted file mode 100644index 65d6268b75..0000000000--- a/backend/src/server/routes/v1/secret-validation-rule-router.ts+++ /dev/null@@ -1,268 +0,0 @@-import { z } from "zod";--import { EventType } from "@app/ee/services/audit-log/audit-log-types";-import { ApiDocsTags, SECRET_VALIDATION_RULES } from "@app/lib/api-docs";-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";-import { getTelemetryDistinctId } from "@app/server/lib/telemetry";-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { AuthMode } from "@app/services/auth/auth-type";-import {- SecretValidationRuleResponseSchema,- SecretValidationRuleSchema-} from "@app/services/secret-validation-rule/secret-validation-rule-schemas";-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";--export const registerSecretValidationRuleRouter = async (server: FastifyZodProvider) => {- // List all rules for a project- server.route({- method: "GET",- url: "/:projectId/secret-validation-rules",- config: { rateLimit: readLimit },- schema: {- hide: true,- operationId: "listSecretValidationRules",- tags: [ApiDocsTags.SecretValidationRules],- description: "List Secret Validation Rules",- params: z.object({- projectId: z.string().trim().describe(SECRET_VALIDATION_RULES.LIST.projectId)- }),- response: {- 200: z.object({- rules: SecretValidationRuleResponseSchema.array()- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),- handler: async (req) => {- const rules = await server.services.secretValidationRule.listByProjectId({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- projectId: req.params.projectId- });- return { rules };- }- });-- // Create a rule- server.route({- method: "POST",- url: "/:projectId/secret-validation-rules",- config: { rateLimit: writeLimit },- schema: {- hide: true,- operationId: "createSecretValidationRule",- tags: [ApiDocsTags.SecretValidationRules],- description: "Create Secret Validation Rule",- params: z.object({- projectId: z.string().trim().describe(SECRET_VALIDATION_RULES.CREATE.projectId)- }),- body: z.object({- name: z.string().trim().min(1).max(100).describe(SECRET_VALIDATION_RULES.CREATE.name),- description: z- .string()- .trim()- .max(500)- .nullable()- .optional()- .describe(SECRET_VALIDATION_RULES.CREATE.description),- environmentSlug: z.string().trim().min(1).optional().describe(SECRET_VALIDATION_RULES.CREATE.environmentSlug),- secretPath: z.string().trim().min(1).describe(SECRET_VALIDATION_RULES.CREATE.secretPath),- rule: SecretValidationRuleSchema.describe(SECRET_VALIDATION_RULES.CREATE.rule)- }),- response: {- 200: z.object({- rule: SecretValidationRuleResponseSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const rule = await server.services.secretValidationRule.createRule({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- projectId: req.params.projectId,- name: req.body.name,- description: req.body.description,- environmentSlug: req.body.environmentSlug,- secretPath: req.body.secretPath,- rule: req.body.rule- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- projectId: req.params.projectId,- event: {- type: EventType.SECRET_VALIDATION_RULE_CREATE,- metadata: {- ruleId: rule.id,- name: rule.name,- type: rule.type,- environmentSlug: req.body.environmentSlug,- secretPath: rule.secretPath- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.SecretValidationRuleCreated,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: { ruleId: rule.id, projectId: req.params.projectId }- })- .catch(() => {});-- return { rule };- }- });-- // Update a rule- server.route({- method: "PATCH",- url: "/:projectId/secret-validation-rules/:ruleId",- config: { rateLimit: writeLimit },- schema: {- hide: true,- operationId: "updateSecretValidationRule",- tags: [ApiDocsTags.SecretValidationRules],- description: "Update Secret Validation Rule",- params: z.object({- projectId: z.string().trim().describe(SECRET_VALIDATION_RULES.UPDATE.projectId),- ruleId: z.string().uuid().describe(SECRET_VALIDATION_RULES.UPDATE.ruleId)- }),- body: z.object({- name: z.string().trim().min(1).max(100).optional().describe(SECRET_VALIDATION_RULES.UPDATE.name),- description: z- .string()- .trim()- .max(500)- .nullable()- .optional()- .describe(SECRET_VALIDATION_RULES.UPDATE.description),- environmentSlug: z- .string()- .trim()- .min(1)- .nullable()- .optional()- .describe(SECRET_VALIDATION_RULES.UPDATE.environmentSlug),- secretPath: z.string().trim().min(1).optional().describe(SECRET_VALIDATION_RULES.UPDATE.secretPath),- // The rule config is replaced as a whole when supplied — `type` and the- // per-type fields have to move together for the discriminant to be- // meaningful. Omit it to leave the stored config untouched.- rule: SecretValidationRuleSchema.optional().describe(SECRET_VALIDATION_RULES.UPDATE.rule),- isActive: z.boolean().optional().describe(SECRET_VALIDATION_RULES.UPDATE.isActive)- }),- response: {- 200: z.object({- rule: SecretValidationRuleResponseSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const rule = await server.services.secretValidationRule.updateRule({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- projectId: req.params.projectId,- ruleId: req.params.ruleId,- ...req.body- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- projectId: req.params.projectId,- event: {- type: EventType.SECRET_VALIDATION_RULE_UPDATE,- metadata: {- ruleId: req.params.ruleId,- name: req.body.name,- type: req.body.rule?.type,- environmentSlug: req.body.environmentSlug,- secretPath: req.body.secretPath,- isActive: req.body.isActive- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.SecretValidationRuleUpdated,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: {- ruleId: rule.id,- projectId: req.params.projectId- }- })- .catch(() => {});-- return { rule };- }- });-- // Delete a rule- server.route({- method: "DELETE",- url: "/:projectId/secret-validation-rules/:ruleId",- config: { rateLimit: writeLimit },- schema: {- hide: true,- operationId: "deleteSecretValidationRule",- tags: [ApiDocsTags.SecretValidationRules],- description: "Delete Secret Validation Rule",- params: z.object({- projectId: z.string().trim().describe(SECRET_VALIDATION_RULES.DELETE.projectId),- ruleId: z.string().uuid().describe(SECRET_VALIDATION_RULES.DELETE.ruleId)- }),- response: {- 200: z.object({- rule: SecretValidationRuleResponseSchema- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),- handler: async (req) => {- const rule = await server.services.secretValidationRule.deleteRule({- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId,- projectId: req.params.projectId,- ruleId: req.params.ruleId- });-- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- projectId: req.params.projectId,- event: {- type: EventType.SECRET_VALIDATION_RULE_DELETE,- metadata: {- ruleId: req.params.ruleId,- name: rule.name- }- }- });-- void server.services.telemetry- .sendPostHogEvents({- event: PostHogEventTypes.SecretValidationRuleDeleted,- distinctId: getTelemetryDistinctId(req),- organizationId: req.permission.orgId,- properties: {- ruleId: rule.id,- projectId: req.params.projectId- }- })- .catch(() => {});-- return { rule };- }- });-};diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/dynamic-secrets-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/dynamic-secrets-validation-rule-router.tsnew file mode 100644index 0000000000..e1702a6a9e--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/dynamic-secrets-validation-rule-router.ts@@ -0,0 +1,17 @@+import {+ CreateDynamicSecretsValidationRuleSchema,+ DynamicSecretsValidationRuleSchema,+ UpdateDynamicSecretsValidationRuleSchema+} from "@app/services/secret-validation-rule/dynamic-secrets";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";++import { registerSecretValidationRuleEndpoints } from "./secret-validation-rule-endpoints";++export const registerDynamicSecretsValidationRuleRouter = async (server: FastifyZodProvider) =>+ registerSecretValidationRuleEndpoints({+ server,+ type: SecretValidationRuleType.DynamicSecrets,+ responseSchema: DynamicSecretsValidationRuleSchema,+ createSchema: CreateDynamicSecretsValidationRuleSchema,+ updateSchema: UpdateDynamicSecretsValidationRuleSchema+ });diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/index.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/index.tsnew file mode 100644index 0000000000..afda2e2a6f--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/index.ts@@ -0,0 +1,16 @@+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";++import { registerDynamicSecretsValidationRuleRouter } from "./dynamic-secrets-validation-rule-router";+import { registerSecretRotationsValidationRuleRouter } from "./secret-rotations-validation-rule-router";+import { registerStaticSecretsValidationRuleRouter } from "./static-secrets-validation-rule-router";++export * from "./secret-validation-rule-router";++export const SECRET_VALIDATION_RULE_REGISTER_ROUTER_MAP: Record<+ SecretValidationRuleType,+ (server: FastifyZodProvider) => Promise<void>+> = {+ [SecretValidationRuleType.StaticSecrets]: registerStaticSecretsValidationRuleRouter,+ [SecretValidationRuleType.DynamicSecrets]: registerDynamicSecretsValidationRuleRouter,+ [SecretValidationRuleType.SecretRotations]: registerSecretRotationsValidationRuleRouter+};diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/secret-rotations-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-rotations-validation-rule-router.tsnew file mode 100644index 0000000000..8b46127f25--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-rotations-validation-rule-router.ts@@ -0,0 +1,17 @@+import {+ CreateSecretRotationsValidationRuleSchema,+ SecretRotationsValidationRuleSchema,+ UpdateSecretRotationsValidationRuleSchema+} from "@app/services/secret-validation-rule/secret-rotations";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";++import { registerSecretValidationRuleEndpoints } from "./secret-validation-rule-endpoints";++export const registerSecretRotationsValidationRuleRouter = async (server: FastifyZodProvider) =>+ registerSecretValidationRuleEndpoints({+ server,+ type: SecretValidationRuleType.SecretRotations,+ responseSchema: SecretRotationsValidationRuleSchema,+ createSchema: CreateSecretRotationsValidationRuleSchema,+ updateSchema: UpdateSecretRotationsValidationRuleSchema+ });diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-endpoints.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-endpoints.tsnew file mode 100644index 0000000000..e34c68224e--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-endpoints.ts@@ -0,0 +1,233 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ApiDocsTags, SecretValidationRules } from "@app/lib/api-docs";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";+import { SECRET_VALIDATION_RULE_NAME_MAP } from "@app/services/secret-validation-rule/secret-validation-rule-maps";+import {+ TCreateSecretValidationRuleDTO,+ TSecretValidationRule,+ TUpdateSecretValidationRuleDTO+} from "@app/services/secret-validation-rule/secret-validation-rule-types";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++const toPascalCase = (type: SecretValidationRuleType) =>+ type+ .split("-")+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join("");++export const registerSecretValidationRuleEndpoints = <T extends TSecretValidationRule>({+ server,+ type,+ createSchema,+ updateSchema,+ responseSchema+}: {+ server: FastifyZodProvider;+ type: SecretValidationRuleType;+ // The input side is left open: each rule type's schema accepts its own config fields and applies+ // its own defaults, while the parsed body always lands on the shape the service takes.+ createSchema: z.ZodType<Omit<TCreateSecretValidationRuleDTO, "type">, z.ZodTypeDef, unknown>;+ updateSchema: z.ZodType<Omit<TUpdateSecretValidationRuleDTO, "type" | "ruleId">, z.ZodTypeDef, unknown>;+ responseSchema: z.ZodTypeAny;+}) => {+ const typeName = SECRET_VALIDATION_RULE_NAME_MAP[type];+ const opId = toPascalCase(type);++ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: `list${opId}ValidationRules`,+ tags: [ApiDocsTags.SecretValidationRules],+ description: `List the ${typeName} Validation Rules for the specified project.`,+ querystring: z.object({+ projectId: z.string().trim().min(1).max(36).describe(SecretValidationRules.LIST(type).projectId)+ }),+ response: { 200: z.object({ secretValidationRules: responseSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const secretValidationRules = (await server.services.secretValidationRule.listSecretValidationRules(+ { projectId: req.query.projectId, type },+ req.permission+ )) as T[];++ return { secretValidationRules };+ }+ });++ server.route({+ method: "GET",+ url: "/:ruleId",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: `get${opId}ValidationRule`,+ tags: [ApiDocsTags.SecretValidationRules],+ description: `Get the specified ${typeName} Validation Rule by ID.`,+ params: z.object({+ ruleId: z.string().uuid().describe(SecretValidationRules.GET_BY_ID(type).ruleId)+ }),+ response: { 200: z.object({ secretValidationRule: responseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const secretValidationRule = (await server.services.secretValidationRule.findSecretValidationRuleById(+ { ruleId: req.params.ruleId, type },+ req.permission+ )) as T;++ return { secretValidationRule };+ }+ });++ server.route({+ method: "POST",+ url: "/",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: `create${opId}ValidationRule`,+ tags: [ApiDocsTags.SecretValidationRules],+ description: `Create a ${typeName} Validation Rule for the specified project.`,+ body: createSchema,+ response: { 201: z.object({ secretValidationRule: responseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const secretValidationRule = (await server.services.secretValidationRule.createSecretValidationRule(+ { ...req.body, type },+ req.permission+ )) as T;++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: secretValidationRule.projectId,+ event: {+ type: EventType.SECRET_VALIDATION_RULE_CREATE,+ metadata: {+ ruleId: secretValidationRule.id,+ name: secretValidationRule.name,+ type,+ environment: secretValidationRule.environment?.slug,+ secretPath: secretValidationRule.secretPath,+ isActive: secretValidationRule.isActive+ }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.SecretValidationRuleCreated,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { ruleId: secretValidationRule.id, projectId: secretValidationRule.projectId, type }+ })+ .catch(() => {});++ return { secretValidationRule };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:ruleId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: `update${opId}ValidationRule`,+ tags: [ApiDocsTags.SecretValidationRules],+ description: `Update the specified ${typeName} Validation Rule.`,+ params: z.object({+ ruleId: z.string().uuid().describe(SecretValidationRules.UPDATE(type).ruleId)+ }),+ body: updateSchema,+ response: { 200: z.object({ secretValidationRule: responseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const secretValidationRule = (await server.services.secretValidationRule.updateSecretValidationRule(+ { ...req.body, ruleId: req.params.ruleId, type },+ req.permission+ )) as T;++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: secretValidationRule.projectId,+ event: {+ type: EventType.SECRET_VALIDATION_RULE_UPDATE,+ metadata: {+ ruleId: secretValidationRule.id,+ name: secretValidationRule.name,+ type,+ environmentSlug: secretValidationRule.environment?.slug ?? null,+ secretPath: secretValidationRule.secretPath,+ isActive: secretValidationRule.isActive+ }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.SecretValidationRuleUpdated,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { ruleId: secretValidationRule.id, projectId: secretValidationRule.projectId, type }+ })+ .catch(() => {});++ return { secretValidationRule };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:ruleId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: `delete${opId}ValidationRule`,+ tags: [ApiDocsTags.SecretValidationRules],+ description: `Delete the specified ${typeName} Validation Rule.`,+ params: z.object({+ ruleId: z.string().uuid().describe(SecretValidationRules.DELETE(type).ruleId)+ }),+ response: { 200: z.object({ secretValidationRule: responseSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const secretValidationRule = (await server.services.secretValidationRule.deleteSecretValidationRule(+ { ruleId: req.params.ruleId, type },+ req.permission+ )) as T;++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: secretValidationRule.projectId,+ event: {+ type: EventType.SECRET_VALIDATION_RULE_DELETE,+ metadata: { ruleId: secretValidationRule.id, name: secretValidationRule.name, type }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.SecretValidationRuleDeleted,+ distinctId: getTelemetryDistinctId(req),+ organizationId: req.permission.orgId,+ properties: { ruleId: secretValidationRule.id, projectId: secretValidationRule.projectId, type }+ })+ .catch(() => {});++ return { secretValidationRule };+ }+ });+};diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-router.tsnew file mode 100644index 0000000000..b909f19351--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/secret-validation-rule-router.ts@@ -0,0 +1,41 @@+import { z } from "zod";++import { ApiDocsTags, SecretValidationRules } from "@app/lib/api-docs";+import { readLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { DynamicSecretsValidationRuleSchema } from "@app/services/secret-validation-rule/dynamic-secrets";+import { SecretRotationsValidationRuleSchema } from "@app/services/secret-validation-rule/secret-rotations";+import { StaticSecretsValidationRuleSchema } from "@app/services/secret-validation-rule/static-secrets";++const SecretValidationRuleSchema = z.discriminatedUnion("type", [+ StaticSecretsValidationRuleSchema,+ DynamicSecretsValidationRuleSchema,+ SecretRotationsValidationRuleSchema+]);++export const registerSecretValidationRuleRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSecretValidationRules",+ tags: [ApiDocsTags.SecretValidationRules],+ description: "List every Secret Validation Rule in the specified project, of any type.",+ querystring: z.object({+ projectId: z.string().trim().min(1).max(36).describe(SecretValidationRules.LIST().projectId)+ }),+ response: { 200: z.object({ secretValidationRules: SecretValidationRuleSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const secretValidationRules = await server.services.secretValidationRule.listSecretValidationRules(+ { projectId: req.query.projectId },+ req.permission+ );+ return { secretValidationRules };+ }+ });+};diff --git a/backend/src/server/routes/v1/secret-validation-rule-routers/static-secrets-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-routers/static-secrets-validation-rule-router.tsnew file mode 100644index 0000000000..665cd6f999--- /dev/null+++ b/backend/src/server/routes/v1/secret-validation-rule-routers/static-secrets-validation-rule-router.ts@@ -0,0 +1,17 @@+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-enums";+import {+ CreateStaticSecretsValidationRuleSchema,+ StaticSecretsValidationRuleSchema,+ UpdateStaticSecretsValidationRuleSchema+} from "@app/services/secret-validation-rule/static-secrets";++import { registerSecretValidationRuleEndpoints } from "./secret-validation-rule-endpoints";++export const registerStaticSecretsValidationRuleRouter = async (server: FastifyZodProvider) =>+ registerSecretValidationRuleEndpoints({+ server,+ type: SecretValidationRuleType.StaticSecrets,+ responseSchema: StaticSecretsValidationRuleSchema,+ createSchema: CreateStaticSecretsValidationRuleSchema,+ updateSchema: UpdateStaticSecretsValidationRuleSchema+ });diff --git a/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-schemas.ts b/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-schemas.tsnew file mode 100644index 0000000000..ce0e3053e0--- /dev/null+++ b/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-schemas.ts@@ -0,0 +1,44 @@+import { z } from "zod";++import { SecretValidationRules } from "@app/lib/api-docs";++import { ConstraintTarget, DynamicSecretRuleProvider, SecretValidationRuleType } from "../secret-validation-rule-enums";+import {+ BaseSecretValidationRuleSchema,+ buildConstraintsSchema,+ GenericCreateSecretValidationRuleFieldsSchema,+ GenericUpdateSecretValidationRuleFieldsSchema,+ secretValidationRuleTitle+} from "../secret-validation-rule-schemas";++const TYPE = SecretValidationRuleType.DynamicSecrets;++const PasswordConstraintsSchema = buildConstraintsSchema(ConstraintTarget.GeneratedPassword);++const ProvidersSchema = z+ .array(z.nativeEnum(DynamicSecretRuleProvider))+ .min(1, "Select at least one provider")+ .describe(SecretValidationRules.DYNAMIC_SECRETS.providers);++export const DynamicSecretsRuleConfigSchema = z.object({+ providers: ProvidersSchema,+ passwordConstraints: PasswordConstraintsSchema.describe(+ SecretValidationRules.GENERATED_CREDENTIALS.passwordConstraints+ )+});++export const DynamicSecretsValidationRuleSchema = BaseSecretValidationRuleSchema.extend({+ type: z.literal(TYPE),+ ...DynamicSecretsRuleConfigSchema.shape+}).describe(secretValidationRuleTitle(TYPE));++export const CreateDynamicSecretsValidationRuleSchema = GenericCreateSecretValidationRuleFieldsSchema(TYPE).extend(+ DynamicSecretsRuleConfigSchema.shape+);++export const UpdateDynamicSecretsValidationRuleSchema = GenericUpdateSecretValidationRuleFieldsSchema(TYPE).extend({+ providers: ProvidersSchema.optional(),+ passwordConstraints: PasswordConstraintsSchema.optional().describe(+ SecretValidationRules.GENERATED_CREDENTIALS.passwordConstraints+ )+});diff --git a/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-types.ts b/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-types.tsnew file mode 100644index 0000000000..4127a92520--- /dev/null+++ b/backend/src/services/secret-validation-rule/dynamic-secrets/dynamic-secrets-rule-types.ts@@ -0,0 +1,13 @@+import { z } from "zod";++import {+ CreateDynamicSecretsValidationRuleSchema,+ DynamicSecretsRuleConfigSchema,+ DynamicSecretsValidationRuleSchema,+ UpdateDynamicSecretsValidationRuleSchema+} from "./dynamic-secrets-rule-schemas";++export type TDynamicSecretsValidationRule = z.infer<typeof DynamicSecretsValidationRuleSchema>;+export type TDynamicSecretsRuleConfig = z.infer<typeof DynamicSecretsRuleConfigSchema>;+export type TDynamicSecretsValidationRuleInput = z.infer<typeof CreateDynamicSecretsValidationRuleSchema>;+export type TDynamicSecretsValidationRuleUpdate = z.infer<typeof UpdateDynamicSecretsValidationRuleSchema>;diff --git a/backend/src/services/secret-validation-rule/dynamic-secrets/index.ts b/backend/src/services/secret-validation-rule/dynamic-secrets/index.tsnew file mode 100644index 0000000000..e6cfea9ce3--- /dev/null+++ b/backend/src/services/secret-validation-rule/dynamic-secrets/index.ts@@ -0,0 +1,2 @@+export * from "./dynamic-secrets-rule-schemas";+export * from "./dynamic-secrets-rule-types";diff --git a/backend/src/services/secret-validation-rule/secret-rotations/index.ts b/backend/src/services/secret-validation-rule/secret-rotations/index.tsnew file mode 100644index 0000000000..55da3374d0--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-rotations/index.ts@@ -0,0 +1,2 @@+export * from "./secret-rotations-rule-schemas";+export * from "./secret-rotations-rule-types";diff --git a/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-schemas.ts b/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-schemas.tsnew file mode 100644index 0000000000..551f09b5d0--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-schemas.ts@@ -0,0 +1,48 @@+import { z } from "zod";++import { SecretValidationRules } from "@app/lib/api-docs";++import {+ ConstraintTarget,+ SecretRotationRuleProvider,+ SecretValidationRuleType+} from "../secret-validation-rule-enums";+import {+ BaseSecretValidationRuleSchema,+ buildConstraintsSchema,+ GenericCreateSecretValidationRuleFieldsSchema,+ GenericUpdateSecretValidationRuleFieldsSchema,+ secretValidationRuleTitle+} from "../secret-validation-rule-schemas";++const TYPE = SecretValidationRuleType.SecretRotations;++const PasswordConstraintsSchema = buildConstraintsSchema(ConstraintTarget.GeneratedPassword);++const ProvidersSchema = z+ .array(z.nativeEnum(SecretRotationRuleProvider))+ .min(1, "Select at least one provider")+ .describe(SecretValidationRules.SECRET_ROTATIONS.providers);++export const SecretRotationsRuleConfigSchema = z.object({+ providers: ProvidersSchema,+ passwordConstraints: PasswordConstraintsSchema.describe(+ SecretValidationRules.GENERATED_CREDENTIALS.passwordConstraints+ )+});++export const SecretRotationsValidationRuleSchema = BaseSecretValidationRuleSchema.extend({+ type: z.literal(TYPE),+ ...SecretRotationsRuleConfigSchema.shape+}).describe(secretValidationRuleTitle(TYPE));++export const CreateSecretRotationsValidationRuleSchema = GenericCreateSecretValidationRuleFieldsSchema(TYPE).extend(+ SecretRotationsRuleConfigSchema.shape+);++export const UpdateSecretRotationsValidationRuleSchema = GenericUpdateSecretValidationRuleFieldsSchema(TYPE).extend({+ providers: ProvidersSchema.optional(),+ passwordConstraints: PasswordConstraintsSchema.optional().describe(+ SecretValidationRules.GENERATED_CREDENTIALS.passwordConstraints+ )+});diff --git a/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-types.ts b/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-types.tsnew file mode 100644index 0000000000..a7135e7039--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-rotations/secret-rotations-rule-types.ts@@ -0,0 +1,13 @@+import { z } from "zod";++import {+ CreateSecretRotationsValidationRuleSchema,+ SecretRotationsRuleConfigSchema,+ SecretRotationsValidationRuleSchema,+ UpdateSecretRotationsValidationRuleSchema+} from "./secret-rotations-rule-schemas";++export type TSecretRotationsValidationRule = z.infer<typeof SecretRotationsValidationRuleSchema>;+export type TSecretRotationsRuleConfig = z.infer<typeof SecretRotationsRuleConfigSchema>;+export type TSecretRotationsValidationRuleInput = z.infer<typeof CreateSecretRotationsValidationRuleSchema>;+export type TSecretRotationsValidationRuleUpdate = z.infer<typeof UpdateSecretRotationsValidationRuleSchema>;diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-constants.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-constants.tsnew file mode 100644index 0000000000..60a1587cad--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-constants.ts@@ -0,0 +1,8 @@+export const MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS = 25;++export const MAX_SECRET_CONSTRAINT_LENGTH = 65536;++export const MAX_GENERATED_CONSTRAINT_LENGTH = 2048;++export const MAX_CONSTRAINT_PATTERN_LENGTH = 4096;+export const MAX_CONSTRAINT_AFFIX_LENGTH = 1024;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.tsnew file mode 100644index 0000000000..c93a43d36e--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts@@ -0,0 +1,90 @@+import RE2 from "re2";++import { ConstraintKind, ConstraintTarget } from "./secret-validation-rule-enums";+import { CONSTRAINT_TARGET_LABELS } from "./secret-validation-rule-maps";+import { TConstraints } from "./secret-validation-rule-schemas";++export const CONSTRAINT_LABELS: Record<ConstraintKind, string> = {+ [ConstraintKind.MinLength]: "Minimum length",+ [ConstraintKind.MaxLength]: "Maximum length",+ [ConstraintKind.RegexPattern]: "Regex pattern",+ [ConstraintKind.RequiredPrefix]: "Required prefix",+ [ConstraintKind.RequiredSuffix]: "Required suffix",+ [ConstraintKind.ReusePreviousVersions]: "Prevent reuse of previous secret values"+};++export type TConstraintViolation = {+ kind: ConstraintKind;+ label: string;+ message: string;+};++const violation = (kind: ConstraintKind, message: string): TConstraintViolation => ({+ kind,+ label: CONSTRAINT_LABELS[kind],+ message+});++export const evaluateConstraints = ({+ constraints,+ target,+ value+}: {+ constraints: TConstraints;+ target: ConstraintTarget;+ value: string;+}): TConstraintViolation[] => {+ const { minLength, maxLength, regexPattern, requiredPrefix, requiredSuffix } = constraints;+ const label = CONSTRAINT_TARGET_LABELS[target];+ const violations: TConstraintViolation[] = [];++ if (minLength !== undefined && value.length < minLength) {+ violations.push(+ violation(ConstraintKind.MinLength, `${label} must be at least ${minLength} characters (got ${value.length})`)+ );+ }++ if (maxLength !== undefined && value.length > maxLength) {+ violations.push(+ violation(ConstraintKind.MaxLength, `${label} must be at most ${maxLength} characters (got ${value.length})`)+ );+ }++ if (regexPattern !== undefined && !new RE2(regexPattern).test(value)) {+ violations.push(violation(ConstraintKind.RegexPattern, `${label} must match pattern ${regexPattern}`));+ }++ if (requiredPrefix !== undefined && !value.startsWith(requiredPrefix)) {+ violations.push(violation(ConstraintKind.RequiredPrefix, `${label} must start with "${requiredPrefix}"`));+ }++ if (requiredSuffix !== undefined && !value.endsWith(requiredSuffix)) {+ violations.push(violation(ConstraintKind.RequiredSuffix, `${label} must end with "${requiredSuffix}"`));+ }++ return violations;+};++// combine the constraints of every rule covering the same generated credential. lengths take the strictest bound; the remaining fields can only come from one rule+// two rules setting the same field in overlapping scope are rejected when the second is saved+export const mergeConstraints = (constraintSets: TConstraints[]): TConstraints =>+ constraintSets.reduce<TConstraints>((merged, constraints) => {+ const { minLength, maxLength, regexPattern, requiredPrefix, requiredSuffix } = constraints;++ return {+ minLength: minLength === undefined ? merged.minLength : Math.max(minLength, merged.minLength ?? minLength),+ maxLength: maxLength === undefined ? merged.maxLength : Math.min(maxLength, merged.maxLength ?? maxLength),+ regexPattern: regexPattern ?? merged.regexPattern,+ requiredPrefix: requiredPrefix ?? merged.requiredPrefix,+ requiredSuffix: requiredSuffix ?? merged.requiredSuffix+ };+ }, {});++const namedFields = (path: string, value: unknown): string[] => {+ if (value === undefined || value === null) return [];+ if (typeof value !== "object") return [path];+ return Object.entries(value).flatMap(([field, nested]) => namedFields(`${path}.${field}`, nested));+};++export const listSetConstraintFields = (constraintsByTarget: Record<string, TConstraints | null | undefined>) =>+ new Set(Object.entries(constraintsByTarget).flatMap(([target, constraints]) => namedFields(target, constraints)));diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-dal.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-dal.tsindex 53e2282a03..e14f58a912 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-dal.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-dal.ts@@ -1,11 +1,82 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";-import { ormify } from "@app/lib/knex";+import { TableName, TSecretValidationRules } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex";++import { SecretValidationRuleType } from "./secret-validation-rule-enums";export type TSecretValidationRuleDALFactory = ReturnType<typeof secretValidationRuleDALFactory>;+type TFilter = Parameters<typeof buildFindFilter<TSecretValidationRules>>[0];++const baseQuery = ({ db, filter, tx }: { db: TDbClient; filter?: TFilter; tx?: Knex }) => {+ const query = (tx || db.replicaNode())(TableName.SecretValidationRule)+ .leftJoin(TableName.Environment, `${TableName.SecretValidationRule}.envId`, `${TableName.Environment}.id`)+ .join(TableName.Project, `${TableName.SecretValidationRule}.projectId`, `${TableName.Project}.id`)+ .whereNull(`${TableName.Project}.deleteAfter`)+ .select(selectAllTableCols(TableName.SecretValidationRule))+ .select(+ db.ref("name").withSchema(TableName.Environment).as("envName"),+ db.ref("slug").withSchema(TableName.Environment).as("envSlug")+ );++ if (filter) {+ /* eslint-disable @typescript-eslint/no-misused-promises */+ void query.where(buildFindFilter(prependTableNameToFindFilter(TableName.SecretValidationRule, filter)));+ }++ return query;+};++const expandRule = (rule: TSecretValidationRules & { envName: string; envSlug: string }) => {+ const { envId, envName, envSlug, type, ...el } = rule;++ return {+ ...el,+ envId: envId ?? null,+ type: type as SecretValidationRuleType,+ environment: envId ? { id: envId, name: envName, slug: envSlug } : null+ };+};+export const secretValidationRuleDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.SecretValidationRule);- return orm;+ const findWithEnv = async (filter: TFilter, tx?: Knex) => {+ try {+ const rules = await baseQuery({ db, filter, tx });+ return rules.map(expandRule);+ } catch (error) {+ throw new DatabaseError({ error, name: "Find - Secret Validation Rule" });+ }+ };++ const findOneWithEnv = async (filter: TFilter, tx?: Knex) => {+ try {+ const rule = await baseQuery({ db, filter, tx }).first();+ return rule ? expandRule(rule) : undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find One - Secret Validation Rule" });+ }+ };++ const createWithEnv = async (data: Parameters<(typeof orm)["create"]>[0]) => {+ const rule = await orm.transaction(async (tx) => {+ const created = await orm.create(data, tx);+ return baseQuery({ db, filter: { id: created.id }, tx }).first();+ });+ return expandRule(rule!);+ };++ const updateByIdWithEnv = async (ruleId: string, data: Parameters<(typeof orm)["updateById"]>[1]) => {+ const rule = await orm.transaction(async (tx) => {+ await orm.updateById(ruleId, data, tx);+ return baseQuery({ db, filter: { id: ruleId }, tx }).first();+ });+ return expandRule(rule!);+ };++ return { ...orm, findWithEnv, findOneWithEnv, createWithEnv, updateByIdWithEnv };};diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-enums.tsnew file mode 100644index 0000000000..97684edf42--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts@@ -0,0 +1,36 @@+export enum SecretValidationRuleType {+ StaticSecrets = "static-secrets",+ DynamicSecrets = "dynamic-secrets",+ SecretRotations = "secret-rotations"+}++export enum ConstraintKind {+ MinLength = "min-length",+ MaxLength = "max-length",+ RegexPattern = "regex-pattern",+ RequiredPrefix = "required-prefix",+ RequiredSuffix = "required-suffix",+ ReusePreviousVersions = "reuse-previous-versions"+}++export enum ConstraintTarget {+ SecretKey = "key",+ SecretValue = "value",+ GeneratedPassword = "password"+}++// Providers selectable in a dynamic secret rule. Keep aligned with `DynamicSecretProviders`.+export enum DynamicSecretRuleProvider {+ SqlDatabase = "sql-database",+ Milvus = "milvus"+}++// Providers selectable in a secret rotation rule. Keep aligned with `SecretRotation`.+export enum SecretRotationRuleProvider {+ PostgresCredentials = "postgres-credentials",+ MySqlCredentials = "mysql-credentials",+ MsSqlCredentials = "mssql-credentials",+ OracleDBCredentials = "oracledb-credentials",+ UnixLinuxLocalAccount = "unix-linux-local-account",+ LdapPassword = "ldap-password"+}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 ea78e92d79..900bbf018a 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@@ -1,467 +1,203 @@import picomatch from "picomatch";-import RE2 from "re2";import { DynamicSecretProviders } from "@app/ee/services/dynamic-secret/providers/models";import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";-import { BadRequestError } from "@app/lib/errors";+import { BadRequestError, InternalServerError } from "@app/lib/errors";-import { MAX_PREVENT_VALUE_REUSE_VERSIONS } from "./secret-validation-rule-schemas";+import { DynamicSecretsRuleConfigSchema, TDynamicSecretsRuleConfig } from "./dynamic-secrets";+import { SecretRotationsRuleConfigSchema, TSecretRotationsRuleConfig } from "./secret-rotations";+import { listSetConstraintFields } from "./secret-validation-rule-constraint-fns";import {ConstraintTarget,- ConstraintType,DynamicSecretRuleProvider,SecretRotationRuleProvider,- SecretValidationRuleType,- TConstraint,- TDynamicSecretsInputs,- TSecretRotationsInputs,- TSecretValidationRuleInputs,- TStaticSecretsInputs-} from "./secret-validation-rule-types";+ SecretValidationRuleType+} from "./secret-validation-rule-enums";+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";+import {+ evaluateStaticSecretConstraints,+ StaticSecretsRuleConfigSchema,+ TSecretToValidate,+ TStaticSecretsRuleConfig+} from "./static-secrets";-type TExistingRule = {- id: string;- name: string;- envId?: string | null;- secretPath: string;- type: string;- inputs?: unknown;+const CONFIG_SCHEMA_MAP = {+ [SecretValidationRuleType.StaticSecrets]: StaticSecretsRuleConfigSchema,+ [SecretValidationRuleType.DynamicSecrets]: DynamicSecretsRuleConfigSchema,+ [SecretValidationRuleType.SecretRotations]: SecretRotationsRuleConfigSchema};-const doPathsOverlap = (pathA: string, pathB: string): boolean => {- const opts: picomatch.PicomatchOptions = { strictSlashes: false };-- if (picomatch.isMatch(pathA, pathB, opts) || picomatch.isMatch(pathB, pathA, opts)) {- return true;+export const parseSecretValidationRuleConfig = (type: string, config: unknown): TSecretValidationRuleConfig => {+ const schema = CONFIG_SCHEMA_MAP[type as SecretValidationRuleType];+ if (!schema) {+ throw new InternalServerError({ message: `Unsupported secret validation rule type '${type}'` });}+ return schema.parse(config);+};- // When both sides are globs, check if the non-glob prefix of one is- // reachable from the other pattern. e.g. "/a/**" vs "/a/b/*" → the- // prefix "/a/b" is matched by "/a/**".- const scanA = picomatch.scan(pathA);- const scanB = picomatch.scan(pathB);-- if (scanA.isGlob && scanB.isGlob) {- const prefixA = scanA.base || "/";- const prefixB = scanB.base || "/";-- if (picomatch.isMatch(prefixA, pathB, opts) || picomatch.isMatch(prefixB, pathA, opts)) {- return true;- }+/** A rule's constraints keyed by what they apply to, so any two rules can be compared field by field. */+export const getConstraintsByTarget = (+ type: SecretValidationRuleType,+ config: TSecretValidationRuleConfig+): Record<string, TValueConstraints | undefined> => {+ if (type === SecretValidationRuleType.StaticSecrets) {+ const { keyConstraints, valueConstraints } = config as TStaticSecretsRuleConfig;+ return { [ConstraintTarget.SecretKey]: keyConstraints, [ConstraintTarget.SecretValue]: valueConstraints };}- return false;+ const { passwordConstraints } = config as TDynamicSecretsRuleConfig | TSecretRotationsRuleConfig;+ return { [ConstraintTarget.GeneratedPassword]: passwordConstraints };};-const doEnvironmentsOverlap = (envIdA: string | null | undefined, envIdB: string | null | undefined): boolean => {- if (!envIdA || !envIdB) return true;- return envIdA === envIdB;+/** The providers a generated-credential rule covers, or null for static-secret rules. */+export const getRuleProviders = (+ type: SecretValidationRuleType,+ config: TSecretValidationRuleConfig+): TGeneratedCredentialProvider[] | null => {+ if (type === SecretValidationRuleType.StaticSecrets) return null;+ return (config as TDynamicSecretsRuleConfig | TSecretRotationsRuleConfig).providers;};-/**- * For static secrets: two rules conflict if they share any constraint of the- * same type + appliesTo target in overlapping scope. This is because two- * constraints of the same kind on the same target can contradict each other- * (e.g. two different regex patterns on the value).- */-const $checkStaticSecretsConstraintOverlap = (- incoming: TStaticSecretsInputs,- existing: TStaticSecretsInputs-): ConstraintType[] => {- const overlapping: ConstraintType[] = [];-- for (const incomingConstraint of incoming.constraints) {- for (const existingConstraint of existing.constraints) {- if (- incomingConstraint.type === existingConstraint.type &&- incomingConstraint.appliesTo === existingConstraint.appliesTo- ) {- overlapping.push(incomingConstraint.type);- }- }- }+const doPathsOverlap = (pathA: string, pathB: string): boolean => {+ const opts: picomatch.PicomatchOptions = { strictSlashes: false };- return overlapping;-};+ if (picomatch.isMatch(pathA, pathB, opts) || picomatch.isMatch(pathB, pathA, opts)) return true;-/**- * For dynamic-secret / secret-rotation rules: two rules conflict only if their- * selected provider sets intersect AND they share at least one constraint type- * targeting the same generated field (e.g. two regex patterns on the password).- */-const $checkGeneratedSecretConstraintOverlap = (- incoming: TDynamicSecretsInputs | TSecretRotationsInputs,- existing: TDynamicSecretsInputs | TSecretRotationsInputs-): ConstraintType[] => {- const incomingProviders = new Set<string>(incoming.providers as string[]);- const sharesProvider = (existing.providers as string[]).some((p) => incomingProviders.has(p));- if (!sharesProvider) return [];+ // When both sides are globs, check whether the non-glob prefix of one is reachable from the other+ // pattern, e.g. "/a/**" vs "/a/b/*" — the prefix "/a/b" is matched by "/a/**".+ const scanA = picomatch.scan(pathA);+ const scanB = picomatch.scan(pathB);+ if (!scanA.isGlob || !scanB.isGlob) return false;- const overlapping: ConstraintType[] = [];- for (const incomingConstraint of incoming.constraints) {- for (const existingConstraint of existing.constraints) {- if (- incomingConstraint.type === existingConstraint.type &&- incomingConstraint.appliesTo === existingConstraint.appliesTo- ) {- overlapping.push(incomingConstraint.type);- }- }- }- return overlapping;+ return picomatch.isMatch(scanA.base || "/", pathB, opts) || picomatch.isMatch(scanB.base || "/", pathA, opts);};-type TOverlapChecker<TInputs = TSecretValidationRuleInputs> = (- incoming: TInputs,- existing: TInputs-) => ConstraintType[];+// A rule with no environment covers every environment, so it overlaps with all of them.+const doEnvironmentsOverlap = (envIdA?: string | null, envIdB?: string | null) =>+ !envIdA || !envIdB || envIdA === envIdB;-const overlapCheckersByType: Record<SecretValidationRuleType, TOverlapChecker> = {- [SecretValidationRuleType.StaticSecrets]: $checkStaticSecretsConstraintOverlap as TOverlapChecker,- [SecretValidationRuleType.DynamicSecrets]: $checkGeneratedSecretConstraintOverlap as TOverlapChecker,- [SecretValidationRuleType.SecretRotations]: $checkGeneratedSecretConstraintOverlap as TOverlapChecker+export type TExistingRule = {+ id: string;+ name: string;+ envId?: string | null;+ secretPath: string;+ type: string;+ config: TSecretValidationRuleConfig;};+/**+ * Two rules of the same type conflict when they cover the same secrets and constrain the same thing.+ * Each would impose its own bound, so the second is rejected rather than both silently enforced.+ */export const checkForOverlappingRules = ({- ruleType,+ type,envId,secretPath,- inputs,+ config,existingRules,excludeRuleId}: {- ruleType: SecretValidationRuleType;+ type: SecretValidationRuleType;envId: string | null;secretPath: string;- inputs: TSecretValidationRuleInputs;+ config: TSecretValidationRuleConfig;existingRules: TExistingRule[];excludeRuleId?: string;}): void => {- const checker = overlapCheckersByType[ruleType as SecretValidationRuleType];- if (!checker) {- return;- }+ const incomingFields = listSetConstraintFields(getConstraintsByTarget(type, config));+ const incomingProviders = getRuleProviders(type, config);for (const existing of existingRules) {- // if the rule is the one being updated, skip the check- if (excludeRuleId && existing.id === excludeRuleId) {- // eslint-disable-next-line no-continue- continue;- }-- // if the rule type doesn't match, skip the check- if (existing.type !== ruleType) {- // eslint-disable-next-line no-continue- continue;- }-- // if the env or folder ID doesn't overlap, skip the check- if (!doEnvironmentsOverlap(envId, existing.envId) || !doPathsOverlap(secretPath, existing.secretPath)) {- // eslint-disable-next-line no-continue- continue;- }-- // at this point we're sure that the rule is overlapping with other rules, so we check if the constraints themselves are overlapping- const overlappingConstraints = checker(inputs, existing.inputs as TSecretValidationRuleInputs);-- if (overlappingConstraints.length > 0) {- const constraintList = [...new Set(overlappingConstraints)].join(", ");- throw new BadRequestError({- message:- `Rule "${existing.name}" already enforces overlapping constraints (${constraintList}) ` +- `on the same scope. Adjust the environment, path, or constraints to avoid conflicts.`- });- }- }-};--// ----------------------------------------------------------------------------// Constraint enforcement — evaluate rules against secrets-// -----------------------------------------------------------------------------type TSecretToValidate = {- key: string;- value?: string;- previousValues?: string[];-};--type TValidationRule = {- name: string;- envId?: string | null;- secretPath: string;- type: string;- inputs: unknown;-};--type TValidationViolation = {- secretKey: string;- ruleName: string;- constraintType: ConstraintType;- message: string;-};--export const CONSTRAINT_LABELS: Record<ConstraintType, string> = {- [ConstraintType.MinLength]: "Minimum length",- [ConstraintType.MaxLength]: "Maximum length",- [ConstraintType.RegexPattern]: "Regex pattern",- [ConstraintType.RequiredPrefix]: "Required prefix",- [ConstraintType.RequiredSuffix]: "Required suffix",- [ConstraintType.PreventValueReuse]: "Prevent reuse of previous secret values"-};--const TARGET_LABELS: Record<ConstraintTarget, string> = {- [ConstraintTarget.SecretKey]: "key",- [ConstraintTarget.SecretValue]: "value",- [ConstraintTarget.GeneratedPassword]: "password"-};--export const evaluateConstraint = (constraint: TConstraint, secret: TSecretToValidate): string | null => {- // Skip value constraints when no value mutation is occurring (e.g. key-only rename)- if (constraint.appliesTo === ConstraintTarget.SecretValue && secret.value === undefined) {- return null;- }-- const targetValue = constraint.appliesTo === ConstraintTarget.SecretKey ? secret.key : (secret.value ?? "");- const targetLabel = TARGET_LABELS[constraint.appliesTo];-- switch (constraint.type) {- case ConstraintType.MinLength: {- const min = Number(constraint.value);-- if (Number.isNaN(min)) {- return `${targetLabel} must be at least ${min} characters (got ${targetValue.length})`;- }-- if (targetValue.length < min) {- return `${targetLabel} must be at least ${min} characters (got ${targetValue.length})`;- }- return null;- }- case ConstraintType.MaxLength: {- const max = Number(constraint.value);-- if (Number.isNaN(max)) {- return `${targetLabel} must be at most ${max} characters (got ${targetValue.length})`;- }-- if (targetValue.length > max) {- return `${targetLabel} must be at most ${max} characters (got ${targetValue.length})`;- }- return null;- }- case ConstraintType.RegexPattern: {- try {- const regex = new RE2(constraint.value);- if (!regex.test(targetValue)) {- return `${targetLabel} must match pattern ${constraint.value}`;- }- return null;- } catch {- // re2 throws an error if the pattern is invalid- return `${targetLabel} must match pattern ${constraint.value}`;- }- }- case ConstraintType.RequiredPrefix: {- if (!targetValue.startsWith(constraint.value)) {- return `${targetLabel} must start with "${constraint.value}"`;- }- return null;- }- case ConstraintType.RequiredSuffix: {- if (!targetValue.endsWith(constraint.value)) {- return `${targetLabel} must end with "${constraint.value}"`;- }- return null;- }- case ConstraintType.PreventValueReuse: {- if (secret.value === undefined || !secret.previousValues?.length) {- return null;- }- const versionCount = Number(constraint.value) || MAX_PREVENT_VALUE_REUSE_VERSIONS;- const valuesToCheck = secret.previousValues.slice(0, versionCount);- if (valuesToCheck.includes(secret.value)) {- return `${targetLabel} cannot reuse any of the last ${versionCount} values`;- }- return null;- }- default:- return null;- }-};--export type TStaticSecretConstraintViolation = {- constraintType: ConstraintType;- constraintLabel: string;- message: string;-};--/**- * Evaluate a single secret against a set of static-secret constraints, returning every violation- * (non-throwing). Reused by the audit-report compliance scan to surface already-stored secrets that do- * not conform to a validation rule that was created after them.- */-export const evaluateStaticSecretConstraints = (- constraints: TConstraint[],- secret: TSecretToValidate-): TStaticSecretConstraintViolation[] => {- const violations: TStaticSecretConstraintViolation[] = [];- for (const constraint of constraints) {- const error = evaluateConstraint(constraint, secret);- if (error) {- violations.push({- constraintType: constraint.type,- constraintLabel: CONSTRAINT_LABELS[constraint.type],- message: error- });- }- }- return violations;-};--/**- * Evaluate static secret constraints against a set of secrets.- */-const enforceStaticSecretsRules = (rules: TValidationRule[], secrets: TSecretToValidate[]): TValidationViolation[] => {- const violations: TValidationViolation[] = [];-- for (const rule of rules) {- const inputs = rule.inputs as TStaticSecretsInputs | undefined;- if (!inputs?.constraints?.length) {- // eslint-disable-next-line no-continue- continue;- }-- for (const secret of secrets) {- for (const constraint of inputs.constraints) {- const error = evaluateConstraint(constraint, secret);- if (error) {- violations.push({- secretKey: secret.key,- ruleName: rule.name,- constraintType: constraint.type,- message: error+ const sharesScope =+ existing.id !== excludeRuleId &&+ existing.type === type &&+ doEnvironmentsOverlap(envId, existing.envId) &&+ doPathsOverlap(secretPath, existing.secretPath);++ if (sharesScope) {+ const existingProviders = getRuleProviders(type, existing.config);+ const sharesProvider =+ !incomingProviders || !existingProviders || existingProviders.some((p) => incomingProviders.includes(p));++ if (sharesProvider) {+ const existingFields = listSetConstraintFields(getConstraintsByTarget(type, existing.config));+ const conflicts = [...incomingFields].filter((field) => existingFields.has(field));++ if (conflicts.length) {+ throw new BadRequestError({+ message: `Rule "${existing.name}" already constrains ${conflicts.join(", ")} over the same secrets. Change the environment, the secret path, or the constraints so the two rules do not overlap.`});}}}}-- return violations;};-// Registry of enforcement functions per rule type.-// To add a new rule type, implement an enforcer and add it here.-type TRuleEnforcer = (rules: TValidationRule[], secrets: TSecretToValidate[]) => TValidationViolation[];--// Generated-credential rule types (dynamic-secrets / secret-rotations) are-// enforced inline at password generation time, not through this enforcement-// path, so they intentionally have no entry here.-const ruleEnforcersByType: Partial<Record<SecretValidationRuleType, TRuleEnforcer>> = {- [SecretValidationRuleType.StaticSecrets]: enforceStaticSecretsRules+/** Only static-secret rules reach this path; generated credentials are shaped at generation. */+export type TRuleToEnforce = {+ name: string;+ config: TStaticSecretsRuleConfig;};-/**- * Finds matching rules for the given scope and evaluates all constraints- * against the provided secrets. Throws a BadRequestError if any violation- * is found.- *- * @param projectRules All rules for the project (caller fetches from DAL)- * @param envId The environment ID of the secrets being written- * @param secretPath The path where secrets are being written (concrete, not a glob)- * @param secrets The plaintext secrets to validate- */+export const findRulesCoveringScope = <T extends { envId?: string | null; secretPath: string }>(+ rules: T[],+ { envId, secretPath }: { envId: string; secretPath: string }+) =>+ rules.filter(+ (rule) =>+ (!rule.envId || rule.envId === envId) && picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })+ );+export const enforceSecretValidationRules = ({- projectRules,- envId,- secretPath,+ rules,secrets}: {- projectRules: TValidationRule[];- envId: string;- secretPath: string;- secrets: TSecretToValidate[];+ rules: TRuleToEnforce[];+ secrets: (TSecretToValidate & { previousValues?: string[] })[];}): void => {- if (!projectRules.length || !secrets.length) return;+ const failures: string[] = [];- const matchingRulesByType = new Map<SecretValidationRuleType, TValidationRule[]>();-- for (const rule of projectRules) {- // Check environment match (null envId on rule = all environments)- if (rule.envId && rule.envId !== envId) {- // eslint-disable-next-line no-continue- continue;- }-- // Check path match (rule.secretPath may be a glob)- if (!picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })) {- // eslint-disable-next-line no-continue- continue;- }-- const ruleType = rule.type as SecretValidationRuleType;- const existing = matchingRulesByType.get(ruleType) || [];- existing.push(rule);- matchingRulesByType.set(ruleType, existing);- }-- const allViolations: TValidationViolation[] = [];-- for (const [ruleType, matchedRules] of matchingRulesByType) {- const enforcer = ruleEnforcersByType[ruleType];- if (!enforcer) {- // eslint-disable-next-line no-continue- continue;+ 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})`+ );+ }}- const violations = enforcer(matchedRules, secrets);- allViolations.push(...violations);}- if (allViolations.length > 0) {- const details = allViolations.map(- (v) =>- `Secret "${v.secretKey}": ${v.message} (rule: "${v.ruleName}", constraint: ${CONSTRAINT_LABELS[v.constraintType]})`- );-- throw new BadRequestError({- message: `Secret validation failed:\n${details.join("\n\n")}`- });+ if (failures.length) {+ throw new BadRequestError({ message: `Secret validation failed:\n${failures.join("\n\n")}` });}};-// Maps a runtime dynamic-secret provider type to the rule-provider slug-// selectable in a secret validation rule. Providers that aren't yet-// covered by validation rules return null, which short-circuits the lookup.+// Runtime provider types that validation rules can constrain. Anything unmapped returns null, which+// short-circuits the rule lookup for that provider.export const convertDynamicSecretProviderToValidationRuleProvider = (type: DynamicSecretProviders): DynamicSecretRuleProvider | null => {- if (type === DynamicSecretProviders.SqlDatabase) return DynamicSecretRuleProvider.SqlDatabase;- if (type === DynamicSecretProviders.Milvus) return DynamicSecretRuleProvider.Milvus;-- return null;+ const map: Partial<Record<DynamicSecretProviders, DynamicSecretRuleProvider>> = {+ [DynamicSecretProviders.SqlDatabase]: DynamicSecretRuleProvider.SqlDatabase,+ [DynamicSecretProviders.Milvus]: DynamicSecretRuleProvider.Milvus+ };+ return map[type] ?? null;};-// Maps a runtime rotation type to the rule-provider slug selectable in a-// secret validation rule. Rotation types not yet covered return null.export const convertSecretRotationToValidationRuleProvider = (type: SecretRotation): SecretRotationRuleProvider | null => {- if (type === SecretRotation.PostgresCredentials) {- return SecretRotationRuleProvider.PostgresCredentials;- }- if (type === SecretRotation.MySqlCredentials) {- return SecretRotationRuleProvider.MySqlCredentials;- }- if (type === SecretRotation.MsSqlCredentials) {- return SecretRotationRuleProvider.MsSqlCredentials;- }- if (type === SecretRotation.OracleDBCredentials) {- return SecretRotationRuleProvider.OracleDBCredentials;- }- if (type === SecretRotation.UnixLinuxLocalAccount) {- return SecretRotationRuleProvider.UnixLinuxLocalAccount;- }- if (type === SecretRotation.LdapPassword) {- return SecretRotationRuleProvider.LdapPassword;- }- return null;-};+ const map: Partial<Record<SecretRotation, SecretRotationRuleProvider>> = {+ [SecretRotation.PostgresCredentials]: SecretRotationRuleProvider.PostgresCredentials,+ [SecretRotation.MySqlCredentials]: SecretRotationRuleProvider.MySqlCredentials,+ [SecretRotation.MsSqlCredentials]: SecretRotationRuleProvider.MsSqlCredentials,+ [SecretRotation.OracleDBCredentials]: SecretRotationRuleProvider.OracleDBCredentials,+ [SecretRotation.UnixLinuxLocalAccount]: SecretRotationRuleProvider.UnixLinuxLocalAccount,+ [SecretRotation.LdapPassword]: SecretRotationRuleProvider.LdapPassword+ };+ return map[type] ?? null;+};++export const secretValidationRuleName = (type: SecretValidationRuleType) => SECRET_VALIDATION_RULE_NAME_MAP[type];diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-maps.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-maps.tsnew file mode 100644index 0000000000..d3a99bc69a--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-maps.ts@@ -0,0 +1,21 @@+import { ConstraintTarget, SecretValidationRuleType } from "./secret-validation-rule-enums";++export const SECRET_VALIDATION_RULE_NAME_MAP = {+ [SecretValidationRuleType.StaticSecrets]: "Static Secrets",+ [SecretValidationRuleType.DynamicSecrets]: "Dynamic Secrets",+ [SecretValidationRuleType.SecretRotations]: "Secret Rotations"+} as const satisfies Record<SecretValidationRuleType, string>;++// how a target is named inside a violation message shown to whoever made the write+export const CONSTRAINT_TARGET_LABELS: Record<ConstraintTarget, string> = {+ [ConstraintTarget.SecretKey]: "key",+ [ConstraintTarget.SecretValue]: "value",+ [ConstraintTarget.GeneratedPassword]: "password"+};++// how a target is named in the API reference, where there is no surrounding context to lean on+export const CONSTRAINT_TARGET_DOC_LABELS: Record<ConstraintTarget, string> = {+ [ConstraintTarget.SecretKey]: "secret key",+ [ConstraintTarget.SecretValue]: "secret value",+ [ConstraintTarget.GeneratedPassword]: "generated password"+};diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-password-generator.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-password-generator.tsindex 7306f58e5d..cd87c0f6ad 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-password-generator.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-password-generator.ts@@ -4,7 +4,7 @@ import RE2 from "re2";import { crypto } from "@app/lib/crypto";import { BadRequestError } from "@app/lib/errors";-import { ConstraintTarget, ConstraintType, TConstraint } from "./secret-validation-rule-types";+import { TConstraints } from "./secret-validation-rule-types";const DEFAULT_MIN_LENGTH = 16;const DEFAULT_MAX_LENGTH = 64;@@ -34,87 +34,68 @@ const buildSecureRandExp = (pattern: RegExp): RandExp => {/*** Mirrors the frontend `generateFromConstraints` in PasswordGenerator.tsx.*- * When a regex constraint is present it takes full precedence: RandExp generates- * the middle segment directly from the pattern, making the result structurally- * valid without a retry loop. Length constraints only apply when there is no- * regex. Prefix and suffix are always prepended/appended to the middle.- *- * The tradeoff is explicit: if a user combines regex with min/max length they- * should express the length requirement inside the pattern itself — the same- * warning shown in the frontend UI.+ * A regex pattern takes full precedence: RandExp generates the middle segment straight from the+ * pattern, so the result is structurally valid without a retry loop, and the length bounds are+ * ignored. Express a length requirement inside the pattern when you combine the two — the frontend+ * shows the same warning. Prefix and suffix always wrap the middle.*/-export const generatePasswordWithConstraints = (constraints: TConstraint[]): string => {- let prefixConstraint: TConstraint | undefined;- let suffixConstraint: TConstraint | undefined;- let regexConstraint: TConstraint | undefined;- let minLengthConstraint: TConstraint | undefined;- let maxLengthConstraint: TConstraint | undefined;-- for (const c of constraints) {- // eslint-disable-next-line no-continue- if (c.appliesTo !== ConstraintTarget.GeneratedPassword) continue;- if (c.type === ConstraintType.RequiredPrefix) prefixConstraint = c;- else if (c.type === ConstraintType.RequiredSuffix) suffixConstraint = c;- else if (c.type === ConstraintType.RegexPattern) regexConstraint = c;- else if (c.type === ConstraintType.MinLength) minLengthConstraint = c;- else if (c.type === ConstraintType.MaxLength) maxLengthConstraint = c;- }-- const prefix = prefixConstraint?.value ?? "";- const suffix = suffixConstraint?.value ?? "";+export const generatePasswordWithConstraints = (constraints: TConstraints): string => {+ const { minLength, maxLength, regexPattern, requiredPrefix, requiredSuffix } = constraints;+ const prefix = requiredPrefix ?? "";+ const suffix = requiredSuffix ?? "";let middle: string;- if (regexConstraint) {+ if (regexPattern) {// Validate the pattern first with RE2 (ReDoS-safe), then generate with RandExp.let validatedPattern: string;try {- // RE2 constructor throws on invalid or ReDoS-prone patterns- const validated = new RE2(regexConstraint.value);- validatedPattern = validated.source;+ validatedPattern = new RE2(regexPattern).source;} catch {throw new BadRequestError({- message: `Secret validation rule contains an invalid regex pattern: ${regexConstraint.value}`+ message: `Secret validation rule contains an invalid regex pattern: ${regexPattern}`});}try {middle = buildSecureRandExp(new RegExp(validatedPattern)).gen();} catch {throw new BadRequestError({- message: `Could not generate a value from regex pattern: ${regexConstraint.value}`+ message: `Could not generate a value from regex pattern: ${regexPattern}`});}} else {- const minLength = minLengthConstraint ? Number(minLengthConstraint.value) : DEFAULT_MIN_LENGTH;- // When no max is set, default to at least minLength so a min-only rule never- // produces an impossible length window.- const maxLength = maxLengthConstraint ? Number(maxLengthConstraint.value) : Math.max(DEFAULT_MAX_LENGTH, minLength);-- if (!Number.isFinite(minLength) || !Number.isFinite(maxLength) || minLength > maxLength) {+ const min = minLength ?? DEFAULT_MIN_LENGTH;+ // With no maximum, hold the ceiling at or above the minimum so a min-only rule never asks for an+ // impossible length window.+ const max = maxLength ?? Math.max(DEFAULT_MAX_LENGTH, min);++ // The schema only compares two bounds the caller supplied, so a maximum below the default+ // minimum reaches here as an impossible window.+ if (min > max) {throw new BadRequestError({- message: "Secret validation rule has impossible length constraints"+ message:+ minLength === undefined+ ? `Secret validation rule sets a maximum length of ${max}, below the ${DEFAULT_MIN_LENGTH} character minimum used when no minimum is set. Set a minimum length as well.`+ : `Secret validation rule has a minimum length (${min}) above its maximum length (${max})`});}- if (maxLength > MAX_GENERATED_PASSWORD_LENGTH || minLength > MAX_GENERATED_PASSWORD_LENGTH) {+ if (max > MAX_GENERATED_PASSWORD_LENGTH) {throw new BadRequestError({message: `Secret validation rule length constraints exceed the maximum allowed (${MAX_GENERATED_PASSWORD_LENGTH} characters)`});}const fixedLength = prefix.length + suffix.length;- if (fixedLength > maxLength) {+ if (fixedLength > max) {throw new BadRequestError({- message: "Secret validation rule prefix/suffix exceeds max length"+ message: `Secret validation rule requires a prefix and suffix longer than its maximum length (${max} characters)`});}- const targetMinFill = Math.max(0, minLength - fixedLength);- const targetMaxFill = maxLength - fixedLength;- const fillLength =- targetMaxFill === targetMinFill- ? targetMinFill- : targetMinFill + crypto.randomInt(0, targetMaxFill - targetMinFill + 1);+ const minFill = Math.max(0, min - fixedLength);+ const maxFill = max - fixedLength;+ const fillLength = maxFill === minFill ? minFill : minFill + crypto.randomInt(0, maxFill - minFill + 1);middle = generateRandomString(fillLength);}@@ -138,7 +119,7 @@ export const generatePasswordWithConstraints = (constraints: TConstraint[]): strreturn finalPassword;};-export const assertConstraintsProduceSafePasswords = (constraints: TConstraint[]): void => {+export const assertConstraintsProduceSafePasswords = (constraints: TConstraints): void => {for (let i = 0; i < DRY_RUN_ITERATIONS; i += 1) {generatePasswordWithConstraints(constraints);}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 6890fefdb9..58e73e5145 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@@ -1,155 +1,166 @@+import RE2 from "re2";import { z } from "zod";import { SecretValidationRulesSchema } from "@app/db/schemas";-import { SECRET_VALIDATION_RULES } from "@app/lib/api-docs";+import { SecretValidationRules } from "@app/lib/api-docs";+import { removeTrailingSlash } from "@app/lib/fn";+import { GenericResourceNameSchema, slugSchema } from "@app/server/lib/schemas";import {- ConstraintTarget,- ConstraintType,- DynamicSecretRuleProvider,- SecretRotationRuleProvider,- SecretValidationRuleType,- TSecretValidationRuleInputs-} from "./secret-validation-rule-types";--export const MAX_PREVENT_VALUE_REUSE_VERSIONS = 25;--const STATIC_RULE_TARGETS = [ConstraintTarget.SecretKey, ConstraintTarget.SecretValue] as const;-const GENERATED_RULE_TARGETS = [ConstraintTarget.GeneratedPassword] as const;--const GENERATED_CONSTRAINT_TYPES = [- ConstraintType.MinLength,- ConstraintType.MaxLength,- ConstraintType.RegexPattern,- ConstraintType.RequiredPrefix,- ConstraintType.RequiredSuffix-] as const;-const STATIC_CONSTRAINT_TYPES = [...GENERATED_CONSTRAINT_TYPES, ConstraintType.PreventValueReuse] as const;--/** Embed description + example so Mintlify/OpenAPI curl samples include enum fields. */-const openApiField = (description: string, example: string) => JSON.stringify({ description, example });--type TConstraintInput = {- type: ConstraintType;- appliesTo: ConstraintTarget;- value: string;+ MAX_CONSTRAINT_AFFIX_LENGTH,+ MAX_CONSTRAINT_PATTERN_LENGTH,+ MAX_GENERATED_CONSTRAINT_LENGTH,+ MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS,+ MAX_SECRET_CONSTRAINT_LENGTH+} from "./secret-validation-rule-constants";+import { ConstraintTarget, SecretValidationRuleType } from "./secret-validation-rule-enums";+import { CONSTRAINT_TARGET_DOC_LABELS, SECRET_VALIDATION_RULE_NAME_MAP } from "./secret-validation-rule-maps";++const lengthSchema = (max: number) => z.number().int().min(1).max(max);++// A generated credential is bounded by what the generator can produce; a stored secret is not.+const maxLengthFor = (target: ConstraintTarget) =>+ target === ConstraintTarget.GeneratedPassword ? MAX_GENERATED_CONSTRAINT_LENGTH : MAX_SECRET_CONSTRAINT_LENGTH;++const regexPatternSchema = z+ .string()+ .trim()+ .min(1)+ .max(MAX_CONSTRAINT_PATTERN_LENGTH)+ .refine(+ (pattern) => {+ try {+ // eslint-disable-next-line no-new+ new RE2(pattern);+ return true;+ } catch {+ return false;+ }+ },+ { message: "Must be a valid regular expression" }+ );++const 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)+ })+ .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 supports+export const BaseConstraintsSchema = z.object({+ minLength: lengthSchema(MAX_SECRET_CONSTRAINT_LENGTH).optional(),+ maxLength: lengthSchema(MAX_SECRET_CONSTRAINT_LENGTH).optional(),+ regexPattern: regexPatternSchema.optional(),+ requiredPrefix: affixSchema.optional(),+ requiredSuffix: affixSchema.optional()+});++const withLengthWindowCheck = <T extends z.ZodRawShape>(shape: T) =>+ z.object(shape).superRefine((constraints, ctx) => {+ const { minLength, maxLength } = constraints as { minLength?: number; maxLength?: number };+ if (minLength !== undefined && maxLength !== undefined && minLength > maxLength) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["minLength"],+ message: `Minimum length (${minLength}) cannot be greater than maximum length (${maxLength})`+ });+ }+ });++const describedConstraintFields = (target: ConstraintTarget) => {+ const docs = SecretValidationRules.CONSTRAINTS(CONSTRAINT_TARGET_DOC_LABELS[target]);+ const { regexPattern, requiredPrefix, requiredSuffix } = BaseConstraintsSchema.shape;+ const length = lengthSchema(maxLengthFor(target)).optional();++ return {+ docs,+ shape: {+ minLength: length.describe(docs.minLength),+ maxLength: length.describe(docs.maxLength),+ regexPattern: regexPattern.describe(docs.regexPattern),+ requiredPrefix: requiredPrefix.describe(docs.requiredPrefix),+ requiredSuffix: requiredSuffix.describe(docs.requiredSuffix)+ }+ };};-const valueRequiredRefinement = (c: TConstraintInput) =>- c.type === ConstraintType.PreventValueReuse || c.value.length > 0;+// the constraint object for one target. every field is optional; a field left out is not enforced+export const buildConstraintsSchema = (target: ConstraintTarget) =>+ withLengthWindowCheck(describedConstraintFields(target).shape);-const preventValueReuseTargetRefinement = (c: TConstraintInput) =>- c.type !== ConstraintType.PreventValueReuse || c.appliesTo === ConstraintTarget.SecretValue;+// a stored secret value can also be checked against values it has already had; a key cannot+export const buildValueConstraintsSchema = (target: ConstraintTarget) =>+ withLengthWindowCheck({+ ...describedConstraintFields(target).shape,+ reusePrevention: ReusePreventionSchema.optional().describe(SecretValidationRules.REUSE_PREVENTION.reusePrevention)+ });-const preventValueReuseRangeRefinement = (c: TConstraintInput) => {- if (c.type !== ConstraintType.PreventValueReuse) return true;- const num = Number(c.value);- return Number.isInteger(num) && num >= 1 && num <= MAX_PREVENT_VALUE_REUSE_VERSIONS;-};+export type TConstraints = z.infer<typeof BaseConstraintsSchema>;-const withConstraintRefinements = <T extends z.ZodType<TConstraintInput>>(schema: T) =>- schema- .refine(valueRequiredRefinement, { message: "Value is required", path: ["value"] })- .refine(preventValueReuseTargetRefinement, {- message: "No value reuse constraint can only apply to secret values",- path: ["appliesTo"]- })- .refine(preventValueReuseRangeRefinement, {- message: `Prevent value reuse version count must be between 1 and ${MAX_PREVENT_VALUE_REUSE_VERSIONS}`,- path: ["value"]- });--const buildConstraintSchemaForRuleType = (ruleType: SecretValidationRuleType) => {- if (ruleType === SecretValidationRuleType.StaticSecrets) {- return withConstraintRefinements(- z.object({- type: z- .enum(STATIC_CONSTRAINT_TYPES)- .describe(openApiField(SECRET_VALIDATION_RULES.RULE.constraintTypeStatic, ConstraintType.MinLength)),- appliesTo: z- .enum(STATIC_RULE_TARGETS)- .describe(openApiField(SECRET_VALIDATION_RULES.RULE.appliesToStatic, ConstraintTarget.SecretValue)),- value: z.string().describe(openApiField(SECRET_VALIDATION_RULES.RULE.constraintValue, "8"))- })- );- }-- return withConstraintRefinements(- z.object({- type: z- .enum(GENERATED_CONSTRAINT_TYPES)- .describe(openApiField(SECRET_VALIDATION_RULES.RULE.constraintTypeGenerated, ConstraintType.MinLength)),- appliesTo: z- .enum(GENERATED_RULE_TARGETS)- .describe(openApiField(SECRET_VALIDATION_RULES.RULE.appliesToGenerated, ConstraintTarget.GeneratedPassword)),- value: z.string().describe(openApiField(SECRET_VALIDATION_RULES.RULE.constraintValue, "8"))- })- );-};+export type TReusePrevention = { previousVersions?: number };-export const staticSecretsInputsSchema = z.object({- constraints: z- .array(buildConstraintSchemaForRuleType(SecretValidationRuleType.StaticSecrets))- .min(1)- .describe(SECRET_VALIDATION_RULES.RULE.constraints)-});+// a secret value additionally supports being checked against values it has already had+export type TValueConstraints = TConstraints & { reusePrevention?: TReusePrevention };-export const dynamicSecretsInputsSchema = z.object({- providers: z- .array(z.nativeEnum(DynamicSecretRuleProvider))- .min(1, "Select at least one provider")- .describe(SECRET_VALIDATION_RULES.RULE.dynamicSecretProviders),- constraints: z- .array(buildConstraintSchemaForRuleType(SecretValidationRuleType.DynamicSecrets))- .min(1)- .describe(SECRET_VALIDATION_RULES.RULE.constraints)-});+// true when at least one constraint field is set across every target on the rule+export const hasAnyConstraint = (targets: (Record<string, unknown> | null | undefined)[]) =>+ targets.some((target) => target && Object.values(target).some((value) => value !== undefined));-export const secretRotationsInputsSchema = z.object({- providers: z- .array(z.nativeEnum(SecretRotationRuleProvider))- .min(1, "Select at least one provider")- .describe(SECRET_VALIDATION_RULES.RULE.secretRotationProviders),- constraints: z- .array(buildConstraintSchemaForRuleType(SecretValidationRuleType.SecretRotations))- .min(1)- .describe(SECRET_VALIDATION_RULES.RULE.constraints)+export const BaseSecretValidationRuleSchema = SecretValidationRulesSchema.omit({+ type: true,+ encryptedInputs: true,+ envId: true+}).extend({+ environment: z.object({ id: z.string().uuid(), name: z.string(), slug: z.string() }).nullable()});-// Discriminated union for create request bodies / API responses.-// Constraints (and providers for generated-credential rules) sit directly on-// the rule object — there is no nested `inputs` wrapper at the HTTP boundary.-export const SecretValidationRuleSchema = z.discriminatedUnion("type", [- z.object({- type: z.literal(SecretValidationRuleType.StaticSecrets).describe(SECRET_VALIDATION_RULES.RULE.type),- ...staticSecretsInputsSchema.shape- }),- z.object({- type: z.literal(SecretValidationRuleType.DynamicSecrets).describe(SECRET_VALIDATION_RULES.RULE.type),- ...dynamicSecretsInputsSchema.shape- }),- z.object({- type: z.literal(SecretValidationRuleType.SecretRotations).describe(SECRET_VALIDATION_RULES.RULE.type),- ...secretRotationsInputsSchema.shape- })-]);--// Map of type → inputs schema, used for runtime parsing-const inputsSchemaMap: Record<SecretValidationRuleType, z.ZodSchema<TSecretValidationRuleInputs>> = {- [SecretValidationRuleType.StaticSecrets]: staticSecretsInputsSchema,- [SecretValidationRuleType.DynamicSecrets]: dynamicSecretsInputsSchema,- [SecretValidationRuleType.SecretRotations]: secretRotationsInputsSchema+export const GenericCreateSecretValidationRuleFieldsSchema = (type: SecretValidationRuleType) => {+ const docs = SecretValidationRules.CREATE(type);++ return z.object({+ name: GenericResourceNameSchema.describe(docs.name),+ projectId: z.string().trim().min(1, "Project ID required").max(36).describe(docs.projectId),+ description: z.string().trim().max(500).nullish().describe(docs.description),+ environment: slugSchema({ field: "environment", max: 64 }).optional().describe(docs.environment),+ secretPath: z+ .string()+ .trim()+ .min(1, "Secret path required")+ .max(1024)+ .transform(removeTrailingSlash)+ .describe(docs.secretPath),+ isActive: z.boolean().default(true).describe(docs.isActive)+ });};-export const parseSecretValidationRuleInputs = (type: string, inputs: unknown) => {- const schema = inputsSchemaMap[type as SecretValidationRuleType];- if (!schema) {- throw new Error(`Unknown secret validation rule type: ${type}`);- }- return schema.parse(inputs);+export const GenericUpdateSecretValidationRuleFieldsSchema = (type: SecretValidationRuleType) => {+ const docs = SecretValidationRules.UPDATE(type);++ return z.object({+ name: GenericResourceNameSchema.optional().describe(docs.name),+ description: z.string().trim().max(500).nullish().describe(docs.description),+ environment: slugSchema({ field: "environment", max: 64 }).nullish().describe(docs.environment),+ secretPath: z+ .string()+ .trim()+ .min(1, "Secret path required")+ .max(1024)+ .transform(removeTrailingSlash)+ .optional()+ .describe(docs.secretPath),+ isActive: z.boolean().optional().describe(docs.isActive)+ });};-export const SecretValidationRuleResponseSchema = SecretValidationRulesSchema.omit({- type: true,- encryptedInputs: true-}).and(SecretValidationRuleSchema);+export const secretValidationRuleTitle = (type: SecretValidationRuleType) =>+ JSON.stringify({ title: SECRET_VALIDATION_RULE_NAME_MAP[type] });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 b5b5857e00..1ff4644ebe 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@@ -1,10 +1,14 @@import { ForbiddenError } from "@casl/ability";-import picomatch from "picomatch";+import { Knex } from "knex";-import { ActionProjectType, TSecretValidationRules } from "@app/db/schemas";+import { ActionProjectType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";-import { NotFoundError } from "@app/lib/errors";+import {+ ProjectPermissionSecretValidationRuleActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { OrgServiceActor } from "@app/lib/types";import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";import { TKmsServiceFactory } from "../kms/kms-service";@@ -13,45 +17,36 @@ import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";import { expandSecretReferencesFactory } from "../secret-v2-bridge/secret-reference-fns";import { 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 { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";-import { checkForOverlappingRules, enforceSecretValidationRules } from "./secret-validation-rule-fns";+import { ConstraintTarget, SecretValidationRuleType } from "./secret-validation-rule-enums";+import {+ checkForOverlappingRules,+ enforceSecretValidationRules,+ findRulesCoveringScope,+ getConstraintsByTarget,+ getRuleProviders,+ parseSecretValidationRuleConfig,+ secretValidationRuleName+} from "./secret-validation-rule-fns";import { assertConstraintsProduceSafePasswords } from "./secret-validation-rule-password-generator";-import { MAX_PREVENT_VALUE_REUSE_VERSIONS, parseSecretValidationRuleInputs } from "./secret-validation-rule-schemas";+import { hasAnyConstraint } from "./secret-validation-rule-schemas";import {- ConstraintTarget,- ConstraintType,- DynamicSecretRuleProvider,- SecretRotationRuleProvider,- SecretValidationRuleType,- TConstraint,+ TConstraints,TCreateSecretValidationRuleDTO,TDeleteSecretValidationRuleDTO,- TDynamicSecretsInputs,+ TFindConstraintsForGeneratedSecretDTO,+ TFindSecretValidationRuleByIdDTO,+ TGeneratedPasswordValidation,TListSecretValidationRulesDTO,- TSecretRotationsInputs,- TSecretValidationRuleInputs,- TSecretValidationRuleRecord,- TUpdateSecretValidationRuleDTO+ TSecretValidationRule,+ TSecretValidationRuleConfig,+ TSecretValidationRuleWithEnv,+ TUpdateSecretValidationRuleDTO,+ TValidateSecretsDTO} from "./secret-validation-rule-types";--// Builds the API-facing rule record: the selected row fields plus the rule's-// type-specific fields flattened alongside `type`. Selecting explicitly keeps-// `encryptedInputs` (and any column added later) out of responses rather than-// relying on the response schema to strip it.-const $toRuleRecord = (rule: TSecretValidationRules, inputs: TSecretValidationRuleInputs) =>- ({- id: rule.id,- name: rule.name,- description: rule.description,- projectId: rule.projectId,- envId: rule.envId,- secretPath: rule.secretPath,- isActive: rule.isActive,- createdAt: rule.createdAt,- updatedAt: rule.updatedAt,- type: rule.type,- ...inputs- }) as TSecretValidationRuleRecord;+import { TStaticSecretsRuleConfig } from "./static-secrets";type TSecretValidationRuleServiceFactoryDep = {secretValidationRuleDAL: TSecretValidationRuleDALFactory;@@ -74,384 +69,391 @@ export const secretValidationRuleServiceFactory = ({permissionService,kmsService}: TSecretValidationRuleServiceFactoryDep) => {- const listByProjectId = async ({- actor,- actorId,- actorAuthMethod,- actorOrgId,- projectId- }: TListSecretValidationRulesDTO) => {+ const $getPermission = async (projectId: string, actor: OrgServiceActor) => {const { permission } = await permissionService.getProjectPermission({- actor,- actorId,+ actor: actor.type,+ actorId: actor.id,projectId,- actorAuthMethod,- actorOrgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,actionProjectType: ActionProjectType.SecretManager});- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);-- const rules = await secretValidationRuleDAL.find({ projectId });+ return permission;+ };- const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId+ const $ruleNotFound = (type: SecretValidationRuleType, label: string) =>+ new NotFoundError({+ message: `${secretValidationRuleName(type)} validation rule with ${label} not found`});- const finalRules = (rules || []).map((rule) =>- $toRuleRecord(- rule,- parseSecretValidationRuleInputs(- rule.type,- JSON.parse(ruleInputsDecryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown- )- )- );-- return finalRules;+ /**+ * A rule is addressed by ID alone, so refusing one in an unreachable project would confirm it+ * exists. Reads as missing instead. A member lacking the action still gets a refusal.+ */+ const $getPermissionForRule = async (projectId: string, actor: OrgServiceActor, notFound: Error) => {+ try {+ return await $getPermission(projectId, actor);+ } catch (error) {+ if (error instanceof ForbiddenRequestError || error instanceof NotFoundError) throw notFound;+ throw error;+ }};- const createRule = async ({- actor,- actorId,- actorAuthMethod,- actorOrgId,- projectId,- name,- description,- environmentSlug,- secretPath,- rule: { type, ...inputs }- }: TCreateSecretValidationRuleDTO) => {- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,- projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager- });- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);-- let envId: string | null = null;- if (environmentSlug) {- const env = await projectEnvDAL.findOne({ projectId, slug: environmentSlug });- if (!env) {- throw new NotFoundError({ message: `Environment with slug '${environmentSlug}' not found in project` });- }- envId = env.id;+ const $getCipher = (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ // Listed rather than spread so `encryptedInputs` can never reach a response.+ const $toRecord = (rule: TSecretValidationRuleWithEnv, config: TSecretValidationRuleConfig) =>+ ({+ id: rule.id,+ name: rule.name,+ description: rule.description,+ projectId: rule.projectId,+ secretPath: rule.secretPath,+ environment: rule.environment,+ isActive: rule.isActive,+ type: rule.type,+ createdAt: rule.createdAt,+ updatedAt: rule.updatedAt,+ ...config+ }) as TSecretValidationRule;++ const $resolveEnvId = async (projectId: string, environmentSlug: string) => {+ const env = await projectEnvDAL.findOne({ projectId, slug: environmentSlug });+ if (!env) {+ throw new NotFoundError({+ message: `Environment '${environmentSlug}' not found in project with ID '${projectId}'`+ });}+ return env.id;+ };- const parsedInputs = parseSecretValidationRuleInputs(type, inputs);-- // For generated-credential rules, do a dry run before storing the rule so- // infeasible constraints (impossible length window, bad regex, etc.) fail- // at save time rather than silently breaking lease/rotation creation later.- if (type === SecretValidationRuleType.DynamicSecrets || type === SecretValidationRuleType.SecretRotations) {- assertConstraintsProduceSafePasswords(- (parsedInputs as TDynamicSecretsInputs | TSecretRotationsInputs).constraints- );+ const $assertRuleType = (rule: TSecretValidationRuleWithEnv, type: SecretValidationRuleType) => {+ if (rule.type !== type) {+ throw new BadRequestError({+ message: `Secret validation rule with ID '${rule.id}' is a ${secretValidationRuleName(+ rule.type as SecretValidationRuleType+ )} rule, not a ${secretValidationRuleName(type)} rule`+ });}+ };- const { encryptor: ruleInputsEncryptor, decryptor: ruleInputsDecryptor } =- await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });+ const $assertNoOverlap = async ({+ projectId,+ type,+ envId,+ secretPath,+ config,+ excludeRuleId+ }: {+ projectId: string;+ type: SecretValidationRuleType;+ envId: string | null;+ secretPath: string;+ config: TSecretValidationRuleConfig;+ excludeRuleId?: string;+ }) => {+ const existingRules = await secretValidationRuleDAL.find({ projectId, type });+ if (!existingRules.length) return;- const existingRules = await secretValidationRuleDAL.find({ projectId });+ const { decryptor } = await $getCipher(projectId);checkForOverlappingRules({- ruleType: type,+ type,envId,secretPath,- inputs: parsedInputs,- existingRules: existingRules.map((r) => ({- id: r.id,- name: r.name,- envId: r.envId,- secretPath: r.secretPath,- type: r.type,- inputs: parseSecretValidationRuleInputs(- r.type,- JSON.parse(ruleInputsDecryptor({ cipherTextBlob: r.encryptedInputs }).toString()) as unknown+ config,+ excludeRuleId,+ existingRules: existingRules.map((rule) => ({+ id: rule.id,+ name: rule.name,+ envId: rule.envId,+ secretPath: rule.secretPath,+ type: rule.type,+ config: parseSecretValidationRuleConfig(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown)}))});+ };- const { cipherTextBlob: encryptedRuleInputs } = ruleInputsEncryptor({- plainText: Buffer.from(JSON.stringify(parsedInputs))- });-- const rule = await secretValidationRuleDAL.create({- name,- description,- projectId,- envId,- secretPath,- type,- encryptedInputs: encryptedRuleInputs- });+ const $assertConstrainsSomething = (type: SecretValidationRuleType, config: TSecretValidationRuleConfig) => {+ if (!hasAnyConstraint(Object.values(getConstraintsByTarget(type, config)))) {+ throw new BadRequestError({ message: "A secret validation rule must set at least one constraint" });+ }+ };- return $toRuleRecord(rule, parsedInputs);+ // Dry run at save time, so infeasible constraints fail here rather than on the next lease.+ const $assertGeneratorCanSatisfy = (type: SecretValidationRuleType, config: TSecretValidationRuleConfig) => {+ if (type === SecretValidationRuleType.StaticSecrets) return;+ assertConstraintsProduceSafePasswords(+ getConstraintsByTarget(type, config)[ConstraintTarget.GeneratedPassword] ?? {}+ );};- const updateRule = async ({- actor,- actorId,- actorAuthMethod,- actorOrgId,- projectId,- ruleId,- environmentSlug,- rule,- ...dto- }: TUpdateSecretValidationRuleDTO) => {- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,- projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager- });- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);+ const listSecretValidationRules = async (+ { projectId, type }: TListSecretValidationRulesDTO,+ actor: OrgServiceActor+ ) => {+ const permission = await $getPermission(projectId, actor);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionSecretValidationRuleActions.Read,+ ProjectPermissionSub.SecretValidationRules+ );- const existingRule = await secretValidationRuleDAL.findOne({ id: ruleId, projectId });- if (!existingRule) {- throw new NotFoundError({ message: `Secret validation rule with ID ${ruleId} not found` });- }+ const rules = await secretValidationRuleDAL.findWithEnv({ projectId, ...(type && { type }) });+ if (!rules.length) return [];- let envId: string | null | undefined;- if (environmentSlug !== undefined) {- if (environmentSlug) {- const env = await projectEnvDAL.findOne({ projectId, slug: environmentSlug });- if (!env) {- throw new NotFoundError({ message: `Environment with slug '${environmentSlug}' not found in project` });- }- envId = env.id;- } else {- envId = null;- }- }+ const { decryptor } = await $getCipher(projectId);+ return rules.map((rule) =>+ $toRecord(+ rule,+ parseSecretValidationRuleConfig(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ )+ )+ );+ };- const { encryptor: ruleInputsEncryptor, decryptor: ruleInputsDecryptor } =- await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });+ const $findRuleOrThrow = async (ruleId: string, type: SecretValidationRuleType, actor: OrgServiceActor) => {+ const notFound = $ruleNotFound(type, `ID '${ruleId}'`);+ const rule = await secretValidationRuleDAL.findOneWithEnv({ id: ruleId });+ if (!rule) throw notFound;- // An update either replaces the whole config or leaves the stored one- // untouched. `type` has its own column and the per-type input schemas strip- // it, so the incoming config can go straight in — only the per-type input- // fields reach the blob.- const ruleType = rule?.type ?? existingRule.type;- const parsedInputs = parseSecretValidationRuleInputs(- ruleType,- rule ?? (JSON.parse(ruleInputsDecryptor({ cipherTextBlob: existingRule.encryptedInputs }).toString()) as unknown)+ const permission = await $getPermissionForRule(rule.projectId, actor, notFound);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionSecretValidationRuleActions.Read,+ ProjectPermissionSub.SecretValidationRules);+ $assertRuleType(rule, type);- if (ruleType === SecretValidationRuleType.DynamicSecrets || ruleType === SecretValidationRuleType.SecretRotations) {- assertConstraintsProduceSafePasswords(- (parsedInputs as TDynamicSecretsInputs | TSecretRotationsInputs).constraints- );- }+ const { decryptor } = await $getCipher(rule.projectId);+ const config = parseSecretValidationRuleConfig(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ );- const finalEnvId = envId !== undefined ? envId : (existingRule.envId as string | null);- const finalSecretPath = dto.secretPath ?? existingRule.secretPath;+ return { rule, config };+ };- const existingRules = await secretValidationRuleDAL.find({ projectId });- checkForOverlappingRules({- ruleType: ruleType as SecretValidationRuleType,- envId: finalEnvId,- secretPath: finalSecretPath,- inputs: parsedInputs,- existingRules: existingRules.map((r) => ({- id: r.id,- name: r.name,- envId: r.envId,- secretPath: r.secretPath,- type: r.type,- inputs: parseSecretValidationRuleInputs(- r.type,- JSON.parse(ruleInputsDecryptor({ cipherTextBlob: r.encryptedInputs }).toString()) as unknown- )- })),- excludeRuleId: ruleId- });+ const findSecretValidationRuleById = async (+ { ruleId, type }: TFindSecretValidationRuleByIdDTO,+ actor: OrgServiceActor+ ) => {+ const { rule, config } = await $findRuleOrThrow(ruleId, type, actor);+ return $toRecord(rule, config);+ };++ const createSecretValidationRule = async (+ {+ type,+ name,+ projectId,+ description,+ environment,+ secretPath,+ isActive,+ ...configInput+ }: TCreateSecretValidationRuleDTO,+ actor: OrgServiceActor+ ) => {+ const permission = await $getPermission(projectId, actor);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionSecretValidationRuleActions.Create,+ ProjectPermissionSub.SecretValidationRules+ );- // The rule config moves as a unit: `type` and the re-encrypted inputs are- // written together, or neither is.- const encryptedInputs = rule- ? ruleInputsEncryptor({ plainText: Buffer.from(JSON.stringify(parsedInputs)) }).cipherTextBlob- : undefined;+ const envId = environment ? await $resolveEnvId(projectId, environment) : null;+ const config = parseSecretValidationRuleConfig(type, configInput);- const updatedRule = await secretValidationRuleDAL.updateById(ruleId, {- ...dto,- ...(envId !== undefined && { envId }),- ...(rule && { type: rule.type, encryptedInputs })- });+ $assertConstrainsSomething(type, config);+ $assertGeneratorCanSatisfy(type, config);+ await $assertNoOverlap({ projectId, type, envId, secretPath, config });- return $toRuleRecord(updatedRule, parsedInputs);- };+ const { encryptor } = await $getCipher(projectId);+ const { cipherTextBlob: encryptedInputs } = encryptor({ plainText: Buffer.from(JSON.stringify(config)) });- const deleteRule = async ({- actor,- actorId,- actorAuthMethod,- actorOrgId,- projectId,- ruleId- }: TDeleteSecretValidationRuleDTO) => {- const { permission } = await permissionService.getProjectPermission({- actor,- actorId,+ const rule = await secretValidationRuleDAL.createWithEnv({+ name,+ description,projectId,- actorAuthMethod,- actorOrgId,- actionProjectType: ActionProjectType.SecretManager+ envId,+ secretPath,+ type,+ isActive,+ encryptedInputs});- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);+ return $toRecord(rule, config);+ };- const existingRule = await secretValidationRuleDAL.findOne({ id: ruleId, projectId });- if (!existingRule) {- throw new NotFoundError({ message: `Secret validation rule with ID ${ruleId} not found` });- }+ const updateSecretValidationRule = async (+ {+ ruleId,+ type,+ name,+ description,+ environment,+ secretPath,+ isActive,+ ...configPatch+ }: TUpdateSecretValidationRuleDTO,+ actor: OrgServiceActor+ ) => {+ const notFound = $ruleNotFound(type, `ID '${ruleId}'`);+ const existingRule = await secretValidationRuleDAL.findOneWithEnv({ id: ruleId });+ if (!existingRule) throw notFound;++ const { projectId } = existingRule;+ const permission = await $getPermissionForRule(existingRule.projectId, actor, notFound);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionSecretValidationRuleActions.Edit,+ ProjectPermissionSub.SecretValidationRules+ );+ $assertRuleType(existingRule, type);++ let envId = existingRule.envId ?? null;+ if (environment !== undefined) envId = environment ? await $resolveEnvId(projectId, environment) : null;++ const { encryptor, decryptor } = await $getCipher(projectId);+ const storedConfig = JSON.parse(decryptor({ cipherTextBlob: existingRule.encryptedInputs }).toString()) as Record<+ string,+ unknown+ >;++ // Each constraint target is replaced when supplied, cleared when null, and left alone otherwise.+ const mergedConfig = { ...storedConfig };+ Object.entries(configPatch).forEach(([field, value]) => {+ if (value === undefined) return;+ if (value === null) delete mergedConfig[field];+ else mergedConfig[field] = value;+ });++ const config = parseSecretValidationRuleConfig(type, mergedConfig);+ const finalSecretPath = secretPath ?? existingRule.secretPath;- const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId+ $assertConstrainsSomething(type, config);+ $assertGeneratorCanSatisfy(type, config);+ await $assertNoOverlap({ projectId, type, envId, secretPath: finalSecretPath, config, excludeRuleId: ruleId });++ const rule = await secretValidationRuleDAL.updateByIdWithEnv(ruleId, {+ ...(name !== undefined && { name }),+ ...(description !== undefined && { description }),+ ...(environment !== undefined && { envId }),+ ...(secretPath !== undefined && { secretPath }),+ ...(isActive !== undefined && { isActive }),+ encryptedInputs: encryptor({ plainText: Buffer.from(JSON.stringify(config)) }).cipherTextBlob});+ return $toRecord(rule, config);+ };- await secretValidationRuleDAL.deleteById(ruleId);- return $toRuleRecord(- existingRule,- parseSecretValidationRuleInputs(- existingRule.type,- JSON.parse(ruleInputsDecryptor({ cipherTextBlob: existingRule.encryptedInputs }).toString()) as unknown- )+ const deleteSecretValidationRule = async (+ { ruleId, type }: TDeleteSecretValidationRuleDTO,+ actor: OrgServiceActor+ ) => {+ const notFound = $ruleNotFound(type, `ID '${ruleId}'`);+ const rule = await secretValidationRuleDAL.findOneWithEnv({ id: ruleId });+ if (!rule) throw notFound;++ const permission = await $getPermissionForRule(rule.projectId, actor, notFound);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionSecretValidationRuleActions.Delete,+ ProjectPermissionSub.SecretValidationRules);+ $assertRuleType(rule, type);++ const { decryptor } = await $getCipher(rule.projectId);+ const config = parseSecretValidationRuleConfig(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ );++ await secretValidationRuleDAL.deleteById(ruleId);+ return $toRecord(rule, config);};/**- * Fetch all rules for a project and enforce them against the given secrets.- * Called by secret write paths before the DB transaction starts.- *- * When `expandSecretReferences` is provided, secret values containing- * interpolation references (e.g. `${env.key}`) will be expanded to their- * resolved values before validation so that constraints apply to the true- * secret value rather than the raw reference string.+ * Pass `tx` when the caller already holds a transaction, or this checks out a second connection.+ * `${env.key}` references are expanded first, so constraints see the resolved value.*/- const validateSecrets = async ({- projectId,- environment,- envId,- secretPath,- secrets- }: {- projectId: string;- environment: string;- envId: string;- secretPath: string;- secrets: { key: string; value?: string; secretId?: string }[];- }) => {+ const validateSecrets = async (+ { projectId, environment, envId, secretPath, secrets }: TValidateSecretsDTO,+ tx?: Knex+ ) => {if (!secrets.length) return;- const rules = await secretValidationRuleDAL.find({ projectId, isActive: true });+ const rules = await secretValidationRuleDAL.find(+ { projectId, isActive: true, type: SecretValidationRuleType.StaticSecrets },+ { tx }+ );if (!rules.length) return;- // Secret values and rule inputs share the SecretManager data key, so one- // cipher pair serves both — this runs on every secret write.- const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });-- const { expandSecretReferences } = expandSecretReferencesFactory({- projectId,- folderDAL,- secretDAL,- decryptSecretValue: (value) => (value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : undefined),- canExpandValue: () => true- });+ const { decryptor } = await $getCipher(projectId);- const parsedRules = rules.map((r) => ({- ...r,- inputs: parseSecretValidationRuleInputs(- r.type,- JSON.parse(secretManagerDecryptor({ cipherTextBlob: r.encryptedInputs }).toString()) as unknown- )+ const coveringRules = findRulesCoveringScope(rules, { envId, secretPath }).map((rule) => ({+ name: rule.name,+ config: parseSecretValidationRuleConfig(+ rule.type,+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ ) as TStaticSecretsRuleConfig}));+ if (!coveringRules.length) return;- // filter to rules that actually match this environment + path so we don't trigger expensive version-history lookups for unrelated PreventValueReuse rules.- const matchingRules = parsedRules.filter((r) => {- if (r.envId && r.envId !== envId) return false;- return picomatch.isMatch(secretPath, r.secretPath, { strictSlashes: false });- });-- const hasPreventValueReuseConstraint = matchingRules.some((r) =>- r.inputs.constraints?.some(- (c) => c.type === ConstraintType.PreventValueReuse && c.appliesTo === ConstraintTarget.SecretValue- )+ // reading version history is only worth it when a covering rule actually forbids reuse+ const versionsToCheck = Math.max(+ 0,+ ...coveringRules.map((rule) => rule.config.valueConstraints?.reusePrevention?.previousVersions ?? 0));- const previousValuesMap: Record<string, string[]> = {};- if (hasPreventValueReuseConstraint) {- const secretIdsToCheck = secrets.filter((s) => s.secretId).map((s) => s.secretId!);- if (secretIdsToCheck.length) {- const allVersions = await Promise.all(- secretIdsToCheck.map((sId) =>- secretVersionV2BridgeDAL.find(- { secretId: sId },- { sort: [["version", "desc"]], limit: MAX_PREVENT_VALUE_REUSE_VERSIONS }- )+ const previousValuesBySecretId: Record<string, string[]> = {};+ if (versionsToCheck > 0) {+ const secretIds = secrets.map((secret) => secret.secretId).filter(Boolean) as string[];+ const versionsPerSecret = await Promise.all(+ secretIds.map((secretId) =>+ secretVersionV2BridgeDAL.find(+ { secretId },+ { sort: [["version", "desc"]], limit: MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS, tx })- );+ )+ );- for (const versions of allVersions) {- for (const version of versions) {- if (!version.encryptedValue) {- // eslint-disable-next-line no-continue- continue;- }- const decryptedValue = secretManagerDecryptor({ cipherTextBlob: version.encryptedValue }).toString();- if (!previousValuesMap[version.secretId]) {- previousValuesMap[version.secretId] = [];- }- previousValuesMap[version.secretId].push(decryptedValue);- }- }- }+ versionsPerSecret.flat().forEach((version) => {+ if (!version.encryptedValue) return;+ previousValuesBySecretId[version.secretId] ??= [];+ previousValuesBySecretId[version.secretId].push(+ decryptor({ cipherTextBlob: version.encryptedValue }).toString()+ );+ });}+ const { expandSecretReferences } = expandSecretReferencesFactory({+ projectId,+ folderDAL,+ secretDAL,+ decryptSecretValue: (value) => (value ? decryptor({ cipherTextBlob: value }).toString() : undefined),+ canExpandValue: () => true+ });+const resolvedSecrets = await Promise.all(- secrets.map(async (s) => ({- key: s.key,+ secrets.map(async (secret) => ({+ key: secret.key,value: await expandSecretReferences({- value: s.value,+ value: secret.value,secretPath,environment,- secretKey: s.key+ secretKey: secret.key}),- ...(s.secretId && previousValuesMap[s.secretId] ? { previousValues: previousValuesMap[s.secretId] } : {})+ ...(secret.secretId && { previousValues: previousValuesBySecretId[secret.secretId] })})));- enforceSecretValidationRules({- projectRules: parsedRules,- envId,- secretPath,- secrets: resolvedSecrets- });+ enforceSecretValidationRules({ rules: coveringRules, secrets: resolvedSecrets });};/**- * Finds active validation rules that match a generated-credential flow- * (dynamic secret lease or secret rotation) and returns the union of- * their constraints for the password target.- *- * Multiple matching rules contribute their constraints additively — the- * generator must satisfy all of them. Overlap is prevented at rule- * creation time, so contradictions across rules are not expected here.+ * The constraints a dynamic secret lease or a secret rotation has to generate within. Rules that+ * cover the same credential contribute together, and overlap is rejected when a rule is saved, so+ * the merged set can never contradict itself.*/const findConstraintsForGeneratedSecret = async ({projectId,@@ -459,57 +461,37 @@ export const secretValidationRuleServiceFactory = ({secretPath,type,provider- }: {- projectId: string;- envId: string;- secretPath: string;- type: SecretValidationRuleType.DynamicSecrets | SecretValidationRuleType.SecretRotations;- provider: DynamicSecretRuleProvider | SecretRotationRuleProvider;- }): Promise<{ constraints: TConstraint[]; ruleNames: string[] }> => {+ }: TFindConstraintsForGeneratedSecretDTO): Promise<TGeneratedPasswordValidation> => {const rules = await secretValidationRuleDAL.find({ projectId, isActive: true, type });- if (!rules.length) return { constraints: [], ruleNames: [] };+ if (!rules.length) return { constraints: {}, ruleNames: [] };- const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });+ const { decryptor } = await $getCipher(projectId);- const constraints: TConstraint[] = [];+ const constraintSets: TConstraints[] = [];const ruleNames: string[] = [];- for (const rule of rules) {- // Scope: rule envId null = applies to all environments- if (rule.envId && rule.envId !== envId) {- // eslint-disable-next-line no-continue- continue;- }- if (!picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })) {- // eslint-disable-next-line no-continue- continue;- }-- const parsed = parseSecretValidationRuleInputs(+ findRulesCoveringScope(rules, { envId, secretPath }).forEach((rule) => {+ const config = parseSecretValidationRuleConfig(rule.type,- JSON.parse(ruleInputsDecryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown- ) as TDynamicSecretsInputs | TSecretRotationsInputs;+ JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ );- if (!parsed.providers?.includes(provider as never)) {- // eslint-disable-next-line no-continue- continue;- }+ if (!getRuleProviders(type, config)?.includes(provider)) return;- constraints.push(...parsed.constraints);+ const passwordConstraints = getConstraintsByTarget(type, config)[ConstraintTarget.GeneratedPassword];+ if (passwordConstraints) constraintSets.push(passwordConstraints);ruleNames.push(rule.name);- }+ });- return { constraints, ruleNames };+ return { constraints: mergeConstraints(constraintSets), ruleNames };};return {- listByProjectId,- createRule,- updateRule,- deleteRule,+ listSecretValidationRules,+ findSecretValidationRuleById,+ createSecretValidationRule,+ updateSecretValidationRule,+ deleteSecretValidationRule,validateSecrets,findConstraintsForGeneratedSecret};diff --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 971f4e5418..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@@ -1,105 +1,148 @@import { TSecretValidationRules } from "@app/db/schemas";-import { TProjectPermission } from "@app/lib/types";--export enum SecretValidationRuleType {- StaticSecrets = "static-secrets",- DynamicSecrets = "dynamic-secrets",- SecretRotations = "secret-rotations"-}--export enum ConstraintType {- MinLength = "min-length",- MaxLength = "max-length",- RegexPattern = "regex-pattern",- RequiredPrefix = "required-prefix",- RequiredSuffix = "required-suffix",- PreventValueReuse = "prevent-value-reuse"-}--export enum ConstraintTarget {- SecretKey = "key",- SecretValue = "value",- GeneratedPassword = "password"- // Future: GeneratedUsername = "username"-}--// Provider identifiers selectable in dynamic-secret rules.-// Keep aligned with `DynamicSecretProviders` in dynamic-secret/providers/models.ts.-export enum DynamicSecretRuleProvider {- SqlDatabase = "sql-database",- Milvus = "milvus"-}--// Provider identifiers selectable in secret-rotation rules.-// Keep aligned with `SecretRotation` in secret-rotation-v2-enums.ts.-export enum SecretRotationRuleProvider {- PostgresCredentials = "postgres-credentials",- MySqlCredentials = "mysql-credentials",- MsSqlCredentials = "mssql-credentials",- OracleDBCredentials = "oracledb-credentials",- UnixLinuxLocalAccount = "unix-linux-local-account",- LdapPassword = "ldap-password"-}--export type TConstraint = {- type: ConstraintType;- appliesTo: ConstraintTarget;- value: string;-};-export type TStaticSecretsInputs = {- constraints: TConstraint[];-};+import {+ TDynamicSecretsRuleConfig,+ TDynamicSecretsValidationRule,+ TDynamicSecretsValidationRuleInput,+ TDynamicSecretsValidationRuleUpdate+} from "./dynamic-secrets";+import {+ TSecretRotationsRuleConfig,+ TSecretRotationsValidationRule,+ TSecretRotationsValidationRuleInput,+ TSecretRotationsValidationRuleUpdate+} from "./secret-rotations";+import {+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,+ SecretValidationRuleType+} from "./secret-validation-rule-enums";+import { TConstraints, TValueConstraints } from "./secret-validation-rule-schemas";+import {+ TStaticSecretsRuleConfig,+ TStaticSecretsValidationRule,+ TStaticSecretsValidationRuleInput,+ TStaticSecretsValidationRuleUpdate+} from "./static-secrets";++export type TSecretValidationRule =+ | TStaticSecretsValidationRule+ | TDynamicSecretsValidationRule+ | TSecretRotationsValidationRule;++export type TSecretValidationRuleInput =+ | TStaticSecretsValidationRuleInput+ | TDynamicSecretsValidationRuleInput+ | TSecretRotationsValidationRuleInput;++export type TSecretValidationRuleUpdate =+ | TStaticSecretsValidationRuleUpdate+ | TDynamicSecretsValidationRuleUpdate+ | TSecretRotationsValidationRuleUpdate;-export type TDynamicSecretsInputs = {- providers: DynamicSecretRuleProvider[];- constraints: TConstraint[];-};--export type TSecretRotationsInputs = {- providers: SecretRotationRuleProvider[];- constraints: TConstraint[];-};--export type TSecretValidationRuleInputs = TStaticSecretsInputs | TDynamicSecretsInputs | TSecretRotationsInputs;--// A rule's type-specific configuration as it appears on the wire: the per-type-// fields sit alongside `type` rather than under an `inputs` wrapper, so `type`-// discriminates them. The stored blob (`encryptedInputs`) holds the same fields-// minus `type`, which has its own column.export type TSecretValidationRuleConfig =- | ({ type: SecretValidationRuleType.StaticSecrets } & TStaticSecretsInputs)- | ({ type: SecretValidationRuleType.DynamicSecrets } & TDynamicSecretsInputs)- | ({ type: SecretValidationRuleType.SecretRotations } & TSecretRotationsInputs);+ | TStaticSecretsRuleConfig+ | TDynamicSecretsRuleConfig+ | TSecretRotationsRuleConfig;-// Discriminated rule shape returned by the service. The `type` field narrows-// the matching per-type fields so the response schema (which is a-// discriminated union over `type`) is satisfied without manual casts at-// each handler.-type TRuleCommonFields = Omit<TSecretValidationRules, "type" | "encryptedInputs">;+export type TGeneratedCredentialProvider = DynamicSecretRuleProvider | SecretRotationRuleProvider;-export type TSecretValidationRuleRecord = TRuleCommonFields & TSecretValidationRuleConfig;--export type TCreateSecretValidationRuleDTO = {+type TRuleScopeCreateFields = {name: string;+ projectId: string;description?: string | null;- environmentSlug?: string;+ environment?: string;secretPath: string;- rule: TSecretValidationRuleConfig;-} & TProjectPermission;+ isActive?: boolean;+};-export type TUpdateSecretValidationRuleDTO = {- ruleId: string;+type TRuleScopeUpdateFields = {name?: string;description?: string | null;- environmentSlug?: string | null;+ environment?: string | null;secretPath?: string;- rule?: TSecretValidationRuleConfig;isActive?: boolean;-} & TProjectPermission;+};++/**+ * Every config field any rule type accepts, all optional. The service is type-agnostic, so it takes+ * the widest shape and hands it to that type's config schema, which narrows it and rejects the rest.+ */+type TAnyRuleConfigFields = {+ keyConstraints?: TValueConstraints;+ valueConstraints?: TValueConstraints;+ providers?: TGeneratedCredentialProvider[];+ passwordConstraints?: TConstraints;+};++/** The same fields on update, where null clears an optional constraint target. */+type TAnyRuleConfigPatch = {+ [K in keyof TAnyRuleConfigFields]: TAnyRuleConfigFields[K] | null;+};++export type TSecretValidationRuleWithEnv = TSecretValidationRules & {+ type: SecretValidationRuleType;+ envId: string | null;+ environment: {+ id: string;+ name: string;+ slug: string;+ } | null;+};++export type TListSecretValidationRulesDTO = {+ projectId: string;+ type?: SecretValidationRuleType;+};++export type TFindSecretValidationRuleByIdDTO = {+ ruleId: string;+ type: SecretValidationRuleType;+};++export type TCreateSecretValidationRuleDTO = TRuleScopeCreateFields &+ TAnyRuleConfigFields & {+ type: SecretValidationRuleType;+ };++export type TUpdateSecretValidationRuleDTO = TRuleScopeUpdateFields &+ TAnyRuleConfigPatch & {+ ruleId: string;+ type: SecretValidationRuleType;+ };export type TDeleteSecretValidationRuleDTO = {ruleId: string;-} & TProjectPermission;+ type: SecretValidationRuleType;+};++/** A secret about to be written, as the static-secret rules see it. */+export type TSecretToValidate = {+ key: string;+ value?: string;+ secretId?: string;+};++export type TValidateSecretsDTO = {+ projectId: string;+ environment: string;+ envId: string;+ secretPath: string;+ secrets: TSecretToValidate[];+};++export type TFindConstraintsForGeneratedSecretDTO = {+ projectId: string;+ envId: string;+ secretPath: string;+ type: SecretValidationRuleType.DynamicSecrets | SecretValidationRuleType.SecretRotations;+ provider: TGeneratedCredentialProvider;+};++/** The constraints a generated credential has to satisfy, and the rules that asked for them. */+export type TGeneratedPasswordValidation = {+ constraints: TConstraints;+ ruleNames: string[];+};-export type TListSecretValidationRulesDTO = TProjectPermission;+export type { TConstraints, TValueConstraints };diff --git a/backend/src/services/secret-validation-rule/static-secrets/index.ts b/backend/src/services/secret-validation-rule/static-secrets/index.tsnew file mode 100644index 0000000000..de3c6bf64f--- /dev/null+++ b/backend/src/services/secret-validation-rule/static-secrets/index.ts@@ -0,0 +1,3 @@+export * from "./static-secrets-rule-fns";+export * from "./static-secrets-rule-schemas";+export * from "./static-secrets-rule-types";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.tsnew file mode 100644index 0000000000..ab0e92dcac--- /dev/null+++ b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts@@ -0,0 +1,44 @@+import { CONSTRAINT_LABELS, evaluateConstraints, TConstraintViolation } from "../secret-validation-rule-constraint-fns";+import { ConstraintKind, ConstraintTarget } from "../secret-validation-rule-enums";+import { TStaticSecretsRuleConfig } from "./static-secrets-rule-types";++export type TSecretToValidate = {+ key: string;+ value?: string;+ previousValues?: string[];+};++export const evaluateStaticSecretConstraints = (+ config: TStaticSecretsRuleConfig,+ secret: TSecretToValidate+): TConstraintViolation[] => {+ const violations = config.keyConstraints+ ? evaluateConstraints({+ constraints: config.keyConstraints,+ target: ConstraintTarget.SecretKey,+ value: secret.key+ })+ : [];++ // A key-only rename carries no value, so there is nothing to hold the value constraints against.+ if (!config.valueConstraints || secret.value === undefined) return violations;++ violations.push(+ ...evaluateConstraints({+ constraints: config.valueConstraints,+ target: ConstraintTarget.SecretValue,+ value: secret.value+ })+ );++ const versionCount = config.valueConstraints.reusePrevention?.previousVersions;+ if (versionCount !== undefined && secret.previousValues?.slice(0, versionCount).includes(secret.value)) {+ violations.push({+ kind: ConstraintKind.ReusePreviousVersions,+ label: CONSTRAINT_LABELS[ConstraintKind.ReusePreviousVersions],+ message: `value cannot reuse any of the last ${versionCount} values`+ });+ }++ return violations;+};diff --git a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-schemas.ts b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-schemas.tsnew file mode 100644index 0000000000..fb8e93d301--- /dev/null+++ b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-schemas.ts@@ -0,0 +1,44 @@+import { z } from "zod";++import { SecretValidationRules } from "@app/lib/api-docs";++import { ConstraintTarget, SecretValidationRuleType } from "../secret-validation-rule-enums";+import {+ BaseSecretValidationRuleSchema,+ buildConstraintsSchema,+ buildValueConstraintsSchema,+ GenericCreateSecretValidationRuleFieldsSchema,+ GenericUpdateSecretValidationRuleFieldsSchema,+ hasAnyConstraint,+ secretValidationRuleTitle+} from "../secret-validation-rule-schemas";++const TYPE = SecretValidationRuleType.StaticSecrets;++const KeyConstraintsSchema = buildConstraintsSchema(ConstraintTarget.SecretKey);+const ValueConstraintsSchema = buildValueConstraintsSchema(ConstraintTarget.SecretValue);++export const StaticSecretsRuleConfigSchema = z.object({+ keyConstraints: KeyConstraintsSchema.optional().describe(SecretValidationRules.STATIC_SECRETS.keyConstraints),+ valueConstraints: ValueConstraintsSchema.optional().describe(SecretValidationRules.STATIC_SECRETS.valueConstraints)+});++const NO_CONSTRAINTS_MESSAGE = "A rule must set at least one key or value constraint";++export const StaticSecretsValidationRuleSchema = BaseSecretValidationRuleSchema.extend({+ type: z.literal(TYPE),+ ...StaticSecretsRuleConfigSchema.shape+}).describe(secretValidationRuleTitle(TYPE));++export const CreateStaticSecretsValidationRuleSchema = GenericCreateSecretValidationRuleFieldsSchema(TYPE)+ .extend(StaticSecretsRuleConfigSchema.shape)+ .superRefine((rule, ctx) => {+ if (!hasAnyConstraint([rule.keyConstraints, rule.valueConstraints])) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["keyConstraints"], message: NO_CONSTRAINTS_MESSAGE });+ }+ });++export const UpdateStaticSecretsValidationRuleSchema = GenericUpdateSecretValidationRuleFieldsSchema(TYPE).extend({+ keyConstraints: KeyConstraintsSchema.nullish().describe(SecretValidationRules.STATIC_SECRETS.keyConstraints),+ valueConstraints: ValueConstraintsSchema.nullish().describe(SecretValidationRules.STATIC_SECRETS.valueConstraints)+});diff --git a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-types.ts b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-types.tsnew file mode 100644index 0000000000..b69a5e851f--- /dev/null+++ b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-types.ts@@ -0,0 +1,13 @@+import { z } from "zod";++import {+ CreateStaticSecretsValidationRuleSchema,+ StaticSecretsRuleConfigSchema,+ StaticSecretsValidationRuleSchema,+ UpdateStaticSecretsValidationRuleSchema+} from "./static-secrets-rule-schemas";++export type TStaticSecretsValidationRule = z.infer<typeof StaticSecretsValidationRuleSchema>;+export type TStaticSecretsRuleConfig = z.infer<typeof StaticSecretsRuleConfigSchema>;+export type TStaticSecretsValidationRuleInput = z.infer<typeof CreateStaticSecretsValidationRuleSchema>;+export type TStaticSecretsValidationRuleUpdate = z.infer<typeof UpdateStaticSecretsValidationRuleSchema>;diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 7c6587a1c6..657f522276 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -2171,6 +2171,7 @@ export type TSecretValidationRuleCreatedEvent = {properties: {ruleId: string;projectId: string;+ type: string;};};@@ -2179,6 +2180,7 @@ export type TSecretValidationRuleUpdatedEvent = {properties: {ruleId: string;projectId: string;+ type: string;};};@@ -2187,6 +2189,7 @@ export type TSecretValidationRuleDeletedEvent = {properties: {ruleId: string;projectId: string;+ type: string;};};diff --git a/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/create.mdx b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/create.mdxnew file mode 100644index 0000000000..e35ce9d238--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/secret-validation-rules/dynamic-secrets"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/delete.mdx b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/delete.mdxnew file mode 100644index 0000000000..ce716c87e0--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete"+openapi: "DELETE /api/v1/secret-validation-rules/dynamic-secrets/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/get-by-id.mdx b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/get-by-id.mdxnew file mode 100644index 0000000000..06b862b95b--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/secret-validation-rules/dynamic-secrets/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/list.mdx b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/list.mdxnew file mode 100644index 0000000000..9bc3603bde--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/secret-validation-rules/dynamic-secrets"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/update.mdx b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/update.mdxnew file mode 100644index 0000000000..6269212ba0--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/dynamic-secrets/update.mdx@@ -0,0 +1,4 @@+---+title: "Update"+openapi: "PATCH /api/v1/secret-validation-rules/dynamic-secrets/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/list.mdx b/docs/api-reference/endpoints/secret-validation-rules/list.mdxnew file mode 100644index 0000000000..a28e49b81e--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/secret-validation-rules"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/create.mdx b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/create.mdxnew file mode 100644index 0000000000..aba652895e--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/secret-validation-rules/secret-rotations"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/delete.mdx b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/delete.mdxnew file mode 100644index 0000000000..0e120beba5--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete"+openapi: "DELETE /api/v1/secret-validation-rules/secret-rotations/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/get-by-id.mdx b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/get-by-id.mdxnew file mode 100644index 0000000000..695306e29c--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/secret-validation-rules/secret-rotations/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/list.mdx b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/list.mdxnew file mode 100644index 0000000000..fb8ae8dc32--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/secret-validation-rules/secret-rotations"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/update.mdx b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/update.mdxnew file mode 100644index 0000000000..0d1ce3bc32--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/secret-rotations/update.mdx@@ -0,0 +1,4 @@+---+title: "Update"+openapi: "PATCH /api/v1/secret-validation-rules/secret-rotations/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/static-secrets/create.mdx b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/create.mdxnew file mode 100644index 0000000000..a568c94949--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/secret-validation-rules/static-secrets"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/static-secrets/delete.mdx b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/delete.mdxnew file mode 100644index 0000000000..82b6fd38b5--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete"+openapi: "DELETE /api/v1/secret-validation-rules/static-secrets/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/static-secrets/get-by-id.mdx b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/get-by-id.mdxnew file mode 100644index 0000000000..4242c06749--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/secret-validation-rules/static-secrets/{ruleId}"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/static-secrets/list.mdx b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/list.mdxnew file mode 100644index 0000000000..0fcc5ed89a--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/secret-validation-rules/static-secrets"+---diff --git a/docs/api-reference/endpoints/secret-validation-rules/static-secrets/update.mdx b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/update.mdxnew file mode 100644index 0000000000..0802e191b9--- /dev/null+++ b/docs/api-reference/endpoints/secret-validation-rules/static-secrets/update.mdx@@ -0,0 +1,4 @@+---+title: "Update"+openapi: "PATCH /api/v1/secret-validation-rules/static-secrets/{ruleId}"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 0d84571d62..95cb4cd564 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -3722,6 +3722,42 @@]}]+ },+ {+ "group": "Secret validation rules",+ "pages": [+ "api-reference/endpoints/secret-validation-rules/list",+ {+ "group": "Static secrets",+ "pages": [+ "api-reference/endpoints/secret-validation-rules/static-secrets/list",+ "api-reference/endpoints/secret-validation-rules/static-secrets/get-by-id",+ "api-reference/endpoints/secret-validation-rules/static-secrets/create",+ "api-reference/endpoints/secret-validation-rules/static-secrets/update",+ "api-reference/endpoints/secret-validation-rules/static-secrets/delete"+ ]+ },+ {+ "group": "Dynamic secrets",+ "pages": [+ "api-reference/endpoints/secret-validation-rules/dynamic-secrets/list",+ "api-reference/endpoints/secret-validation-rules/dynamic-secrets/get-by-id",+ "api-reference/endpoints/secret-validation-rules/dynamic-secrets/create",+ "api-reference/endpoints/secret-validation-rules/dynamic-secrets/update",+ "api-reference/endpoints/secret-validation-rules/dynamic-secrets/delete"+ ]+ },+ {+ "group": "Secret rotations",+ "pages": [+ "api-reference/endpoints/secret-validation-rules/secret-rotations/list",+ "api-reference/endpoints/secret-validation-rules/secret-rotations/get-by-id",+ "api-reference/endpoints/secret-validation-rules/secret-rotations/create",+ "api-reference/endpoints/secret-validation-rules/secret-rotations/update",+ "api-reference/endpoints/secret-validation-rules/secret-rotations/delete"+ ]+ }+ ]}]},@@ -5027,4 +5063,4 @@"destination": "/integrations/all?type=Framework"}]-}\ No newline at end of file+}diff --git a/docs/documentation/platform/secret-validation-rules.mdx b/docs/documentation/platform/secret-validation-rules.mdxindex cce3c5e826..6811d7608c 100644--- a/docs/documentation/platform/secret-validation-rules.mdx+++ b/docs/documentation/platform/secret-validation-rules.mdx@@ -4,178 +4,210 @@ sidebarTitle: "Secret validation rules"description: "Enforce naming conventions, format requirements, and content policies on secrets."----Secret Validation Rules let you define constraints that secrets must satisfy before they can be created, updated, or generated. This helps teams enforce consistent naming conventions, prevent weak or malformed values, and maintain compliance standards across environments — all automatically at write time.+A secret validation rule sets the constraints a secret has to satisfy before Infisical will store it, and the constraints a generated credential has to satisfy before Infisical will issue it. Use rules to keep naming consistent, to keep weak or malformed values out, and to hold a compliance standard across environments without anyone checking by hand.-For example, you can require that all secret keys in production follow `UPPER_SNAKE_CASE`, that values meet a minimum length, that database connection strings always start with a specific prefix, or that passwords generated by a dynamic secret or rotation always match a particular pattern.+You can require that every production secret key is `UPPER_SNAKE_CASE`, that values are at least 16 characters, that a connection string starts with a given prefix, or that the password behind a dynamic secret or a rotation matches a particular pattern.## Rule types-Infisical supports three rule types, each targeting a different kind of secret:+There are three rule types, one per kind of secret:-- **Static Secrets** — applied when a user-managed secret is created or updated.-- **Dynamic Secrets** — applied to the credentials generated when a dynamic secret lease is issued, for selected dynamic secret providers.-- **Secret Rotations** — applied to the credentials generated on each rotation, for selected rotation providers.+- **Static Secrets** — checked when someone creates or updates a secret.+- **Dynamic Secrets** — applied to the credential Infisical generates when it issues a lease.+- **Secret Rotations** — applied to the credential Infisical generates on each rotation.-For dynamic-secret and rotation rules, you must select one or more **providers** the rule applies to. Currently supported providers:+A dynamic secret rule and a rotation rule each name one or more **providers**. The rule applies only to the providers you list.-| Rule Type | Supported Providers |+| Rule type | Supported providers ||---|---|| Dynamic Secrets | SQL Database (PostgreSQL, MySQL, Oracle, Microsoft SQL Server), Milvus |-| Secret Rotations | PostgreSQL Credentials |+| Secret Rotations | PostgreSQL Credentials, MySQL Credentials, Microsoft SQL Server Credentials, OracleDB Credentials, Unix/Linux Local Account, LDAP Password |<Note>- When a dynamic-secret or rotation rule covers a provider, any user-configured **password configuration / password requirements** on that dynamic secret or rotation are ignored — the rule's constraints take precedence. The UI surfaces a warning in the affected forms when this is the case.+ A rule that covers a provider replaces the password configuration set on the dynamic secret or the rotation itself. The affected forms show a warning when that happens.</Note>-## How it works+## Constraints++A rule groups its constraints by what they apply to. Set only the fields you want enforced and leave the rest blank.++| Constraint | What it checks | Example |+|---|---|---|+| **Minimum length** | Fewest characters allowed | `16` |+| **Maximum length** | Most characters allowed | `128` |+| **Regex pattern** | Regular expression the value has to match | `^[A-Z][A-Z0-9_]*$` |+| **Required prefix** | Text the value has to start with | `APP_` |+| **Required suffix** | Text the value has to end with | `_KEY` |+| **Prevent value reuse** | Prior versions the new value has to differ from | `10` |++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 is where the options for rejecting a repeated value will live:++```json+"valueConstraints": {+ "reusePrevention": { "previousVersions": 10 }+}+```++`previousVersions` is a whole number between 1 and 25. Leave `reusePrevention` 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.++## How enforcement works### Static secrets-When a static secret is created or updated, Infisical checks it against all active validation rules whose scope (environment and folder path) matches the secret's location. If any constraint is violated, the secret is rejected and an error is thrown describing which rule and constraint was violated.+When someone creates or updates a secret, Infisical checks it against every active rule whose environment and folder path cover that secret. A violation rejects the write and returns a message naming the rule and the constraint it broke.<Note>- Static-secret validation rules are enforced on mutations only (create or update). Existing secrets that were created before a rule was added aren't retroactively validated.+ A static secret rule applies to writes only. Secrets that already existed when you created the rule aren't rechecked. To find them, run the **Secret Validation Compliance** audit report.</Note>### Dynamic secrets and secret rotations-For dynamic secrets and secret rotations, validation rules drive the **generation** of credentials rather than rejecting input. When a lease is issued (dynamic secret) or credentials are rotated (rotation), Infisical generates a password that satisfies the matching rule's constraints, replacing the default password generation logic.+For a dynamic secret or a rotation, a rule shapes the credential rather than rejecting an input. Infisical generates a password that satisfies the covering rule's constraints, in place of its default generation.-If the rule has a **Regex Pattern** constraint, the password is generated directly from that pattern, and **min/max length constraints are ignored** for that rule. To enforce length when using a regex, express it inside the pattern itself (e.g. `[A-Z0-9]{16,24}`).+Set a **regex pattern** and Infisical builds the password from that pattern, ignoring the length constraints on the same rule. Put the length requirement inside the pattern instead, as in `[A-Z0-9]{16,24}`.-If the rule's constraints are statically infeasible (e.g. an invalid regex, or a min length larger than the max), the rule is rejected at save time so the issue surfaces immediately rather than at lease/rotation time.+Infisical dry runs a dynamic secret rule and a rotation rule when you save it, so constraints the generator can't satisfy — an invalid pattern, or a minimum length above the maximum — fail at that point rather than on the next lease or rotation.-### Constraint types+## Scope-Each rule contains one or more constraints. A constraint specifies what to check and how to check it.+Three fields decide where a rule applies:-| Constraint | Description | Example | Static Secrets | Dynamic Secrets | Secret Rotations |-|---|---|---|---|---|---|-| **Min Length** | Target must be at least N characters | At least 8 characters | ✓ | ✓ | ✓ |-| **Max Length** | Target must be at most N characters | At most 64 characters | ✓ | ✓ | ✓ |-| **Regex Pattern** | Target must match a regular expression | `^[A-Z][A-Z0-9_]*$` | ✓ | ✓ | ✓ |-| **Required Prefix** | Target must start with specific text | `https://` | ✓ | ✓ | ✓ |-| **Required Suffix** | Target must end with specific text | `_SECRET` | ✓ | ✓ | ✓ |-| **Prevent Value Reuse** | New value must not match any of the last N versions | Last 10 versions | ✓ | — | — |+- **Environment** — one environment, or every environment in the project.+- **Folder path** — a path, or a glob pattern such as `/**` for every path or `/services/*` for the immediate subfolders of `/services`.+- **Providers** — dynamic secret and rotation rules only. The rule applies only to the providers you list.-**Applies To** target by rule type:+Scope is what lets one project hold different standards side by side. You can require longer values in production than in development, or longer generated passwords for the rotations on your production databases.++## Overlapping rules-- **Static Secrets** — each constraint applies to the secret **key** or **value**. *Prevent Value Reuse* only applies to the value.-- **Dynamic Secrets** and **Secret Rotations** — constraints apply to the **generated password**.+Two rules of the same type conflict when they cover the same secrets and both set the same constraint field. Infisical rejects the second one, because each side would impose its own bound on the same thing.-### Scoping rules+Two regex patterns on the secret key in overlapping scopes is the common case. Combine them into one rule instead.-Every rule is scoped to control where it applies:+Provider sets narrow this for dynamic secret and rotation rules. A PostgreSQL rotation rule on `/db/*` conflicts with another PostgreSQL rotation rule on `/**`, because the providers and the paths both overlap. A Milvus rule on that same path doesn't conflict with a PostgreSQL rule, because no provider is shared.-- **Environment**: Restrict the rule to a specific environment (e.g., `production`), or apply it to all environments.-- **Folder Path**: Restrict the rule to a specific folder path. Supports glob patterns (e.g., `/**` for all paths, `/services/*` for immediate subfolders of `/services`).-- **Providers** (dynamic-secret and rotation rules only): One or more providers the rule applies to. A rule fires only when the dynamic secret / rotation in scope also matches one of the selected providers.+## Permissions-This means you can have different validation standards for different parts of your project. For instance, you might enforce stricter naming in production while keeping development more flexible, or require longer generated passwords for rotations on production databases.+Secret validation rules have their own permission subject. A project role needs **Read** to see rules, and **Create**, **Modify**, or **Remove** to change them. The **Admin** and **Member** roles hold all four; **Viewer** holds **Read**.-## Creating a rule+## Create a rule<Steps><Step title="Open the Policies tab">- Go to **Project Settings** and select the **Policies** tab, then find the **Secret Validation Rules** section.+ Go to **Project Settings**, select the **Policies** tab, and find the **Secret Validation Rules** section.</Step>- <Step title="Create a rule">- Select **Create Rule** to open the rule creation form.+ <Step title="Start a new rule">+ Select **Create Rule**.</Step>- <Step title="Configure the rule">- **Rule Details**-- - **Name** — A descriptive name (e.g., "Production key naming convention").- - **Description** (optional) — A brief explanation of what the rule enforces and why.- - **Rule Type** — **Static Secrets**, **Dynamic Secrets**, or **Secret Rotations**.- - **Providers** (dynamic-secret and rotation rules only) — Select one or more providers the rule applies to.- - **Environment** — Choose a specific environment or "All Environments".- - **Folder Path** — The path scope, supporting glob patterns (e.g., `/**`).-+ <Step title="Describe the rule">+ - **Name**: what the rule enforces, such as `production-key-naming`.+ - **Description**: optional, for why the rule exists.+ - **Rule Type**: **Static Secrets**, **Dynamic Secrets**, or **Secret Rotations**. You can't change the type after you save.+ - **Providers**: dynamic secret and rotation rules only.+ </Step>- **Constraints**+ <Step title="Set the scope">+ Choose an **Environment**, or **All Environments**. Then set the **Folder Path**, which accepts a glob pattern.+ </Step>- Click **Add Constraint** and choose from the available constraint types. For static-secret rules, select whether each constraint applies to the secret **key** or **value**. For dynamic-secret and rotation rules, constraints apply to the **generated password**, then provide the constraint parameter (length, pattern, prefix, or suffix).- You can add multiple constraints to a single rule. All constraints must be satisfied — for static secrets the value/key must satisfy them, and for dynamic/rotation rules the generated password is built to satisfy them.+ <Step title="Set the constraints">+ Fill in the constraint fields you want enforced and leave the rest blank. A static secret rule offers one group for the secret key and one for the secret value. A dynamic secret or rotation rule offers one group for the generated password.-- + </Step>- <Step title="Save the rule">- Select **Create Rule** to save. The rule is active immediately and applies to every secret write within its scope from then on.+ <Step title="Save">+ Select **Create Rule**. The rule takes effect on the next write in its scope.</Step></Steps>-## Overlapping rules--Infisical prevents you from creating rules that would conflict with each other. If two rules apply to the same scope (overlapping environment and folder path) and share a constraint of the same type targeting the same field, the second rule will be rejected.--For example, you can't have two separate "Regex Pattern on key" constraints in overlapping scopes, as they could contradict each other. Instead, combine the patterns into a single rule.--For dynamic-secret and rotation rules, two rules also conflict only if their selected **provider sets intersect**. For example, a PostgreSQL-only rotation rule on `/db/*` and a separate PostgreSQL rotation rule on `/**` overlap on PostgreSQL + the path glob, and the second one would be rejected. A Milvus-only rule on the same path wouldn't conflict with a PostgreSQL rule, because the providers don't overlap.--## Example use cases+## Manage rules through the API++Each rule type has its own set of endpoints under `/api/v1/secret-validation-rules`, so the request body carries only the fields that type accepts:++- [Static secrets](/api-reference/endpoints/secret-validation-rules/static-secrets/create)+- [Dynamic secrets](/api-reference/endpoints/secret-validation-rules/dynamic-secrets/create)+- [Secret rotations](/api-reference/endpoints/secret-validation-rules/secret-rotations/create)++To read every rule in a project whatever its type, use [List secret validation rules](/api-reference/endpoints/secret-validation-rules/list).++Creating the production key naming rule looks like this:++```bash+curl --request POST \+ --url https://app.infisical.com/api/v1/secret-validation-rules/static-secrets \+ --header 'Authorization: Bearer <token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "production-key-naming",+ "projectId": "<project-id>",+ "environment": "prod",+ "secretPath": "/**",+ "keyConstraints": {+ "regexPattern": "^[A-Z][A-Z0-9_]*$",+ "requiredPrefix": "APP_"+ },+ "valueConstraints": {+ "minLength": 16,+ "maxLength": 128,+ "reusePrevention": { "previousVersions": 10 }+ }+ }'+```++## Examples<AccordionGroup>- <Accordion title="Enforce UPPER_SNAKE_CASE naming">- Create a rule scoped to all environments with a **Regex Pattern** constraint on the **secret key**:-- - Pattern: `^[A-Z][A-Z0-9_]*$`+ <Accordion title="Enforce UPPER_SNAKE_CASE keys">+ A static secret rule across all environments, with `^[A-Z][A-Z0-9_]*$` as the key **regex pattern**.- This ensures all secret keys follow the `UPPER_SNAKE_CASE` convention (e.g., `DATABASE_URL`, `API_KEY`), rejecting names like `mySecret` or `api-key`.+ Keys such as `DATABASE_URL` and `API_KEY` pass. `mySecret` and `api-key` are rejected.</Accordion>- <Accordion title="Require minimum value length">- Create a rule with a **Min Length** constraint on the **secret value**:+ <Accordion title="Require a minimum value length">+ A static secret rule with a value **minimum length** of `16`.- - Minimum: `8`-- This prevents secrets with very short or empty-like values from being saved, helping catch accidental pastes or placeholder values.+ This catches placeholder values and truncated pastes before they reach an environment.</Accordion>- <Accordion title="Enforce URL format for connection strings">- Create a rule scoped to a specific folder path (e.g., `/database/*`) with a **Required Prefix** constraint on the **secret value**:-- - Prefix: `postgresql://`+ <Accordion title="Enforce a connection string format">+ A static secret rule scoped to `/database/*`, with `postgresql://` as the value **required prefix**.- This ensures all secrets in the database folder contain valid PostgreSQL connection strings.+ Every secret in that folder then has to be a PostgreSQL connection string.</Accordion>- <Accordion title="Enforce environment-specific key suffixes">- Create a rule scoped to the `production` environment with a **Required Suffix** constraint on the **secret key**:-- - Suffix: `_PROD`+ <Accordion title="Mark production keys with a suffix">+ A static secret rule scoped to the `production` environment, with `_PROD` as the key **required suffix**.- This helps distinguish production secrets from those in other environments.+ Production secrets are then distinguishable from the rest by name alone.</Accordion>- <Accordion title="Prevent reuse of old secret values">- Create a rule with a **Prevent Value Reuse** constraint on the **secret value**:+ <Accordion title="Stop old values coming back">+ A static secret rule with **prevent value reuse** set to `10` previous versions on the value.- - Previous versions: `10`-- When a secret is updated, its new value is validated against the specified number of prior versions. This is useful for enforcing rotation policies and ensuring that secrets are not recycled.+ Updating a secret to any of its last 10 values is rejected, which is what makes a rotation policy stick.</Accordion>- <Accordion title="Generate strong passwords for SQL dynamic secrets">- Create a **Dynamic Secrets** rule scoped to all environments and `/**`, with `SQL Database` selected as a provider:-- - **Min Length**: `24`- - **Required Prefix**: `INF_`+ <Accordion title="Generate strong SQL dynamic secret passwords">+ A dynamic secret rule across all environments on `/**`, with `SQL Database` as its provider, a password **minimum length** of `24`, and `INF_` as the password **required prefix**.- Every SQL dynamic-secret lease issued in the project will now produce a password that is at least 24 characters long and starts with `INF_`. The password configuration on individual SQL dynamic secrets is ignored while the rule is active.+ Every SQL lease in the project then produces a password of at least 24 characters starting with `INF_`, and the password configuration on each dynamic secret no longer applies.</Accordion>- <Accordion title="Pattern-based passwords for Postgres rotations">- Create a **Secret Rotations** rule scoped to the `production` environment, with `PostgreSQL Credentials` selected as a provider:-- - **Regex Pattern**: `^[A-Z][A-Za-z0-9]{19,29}$`+ <Accordion title="Generate rotation passwords from a pattern">+ A secret rotation rule scoped to the `production` environment, with `PostgreSQL Credentials` as its provider and `^[A-Z][A-Za-z0-9]{19,29}$` as the password **regex pattern**.- PostgreSQL rotations in production will now produce passwords that start with an uppercase letter and are 20–30 characters of mixed-case alphanumerics. Because a regex is set, separate min/max length constraints would be ignored — express the length window inside the pattern instead.+ Production PostgreSQL rotations then produce a password of 20 to 30 mixed-case alphanumerics starting with a capital. The pattern carries the length window, because a rule that sets a pattern ignores its length constraints.</Accordion></AccordionGroup>diff --git a/docs/internals/permissions/project-permissions.mdx b/docs/internals/permissions/project-permissions.mdxindex 0a9ee7a09e..a8b712d40a 100644--- a/docs/internals/permissions/project-permissions.mdx+++ b/docs/internals/permissions/project-permissions.mdx@@ -286,6 +286,15 @@ Supports conditions and permission inversion.| `import-secrets` | Import secrets from sync sources | `environment`, `secretPath`, `connectionId` || `remove-secrets` | Remove secrets from sync destinations | `environment`, `secretPath`, `connectionId` |+#### Subject: `secret-validation-rules`++| Action | Description |+| -------- | --------------------------------------------- |+| `read` | View secret validation rules |+| `create` | Add new secret validation rules |+| `edit` | Modify existing secret validation rules |+| `delete` | Remove secret validation rules |+#### Subject: `dynamic-secrets`Supports conditions and permission inversion.diff --git a/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx b/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsxindex 68798d6f45..0e0d5b943c 100644--- a/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx+++ b/frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx@@ -8,16 +8,15 @@ import {ShieldCheckIcon,TriangleAlertIcon} from "lucide-react";-import picomatch from "picomatch";import RandExp from "randexp";import { twMerge } from "tailwind-merge";import { useTimedReset } from "@app/hooks";import {- ConstraintTarget,- ConstraintType,- TConstraint,+ doesRuleCoverScope,+ SecretValidationRuleType,TSecretValidationRule,+ TValueConstraints,useListSecretValidationRules} from "@app/hooks/api/secretValidationRules";@@ -50,43 +49,20 @@ const NONE_RULE_OPTION: RuleOption = {matchesCurrentScope: false};-const getValueConstraints = (rule: TSecretValidationRule): TConstraint[] =>- rule.constraints.filter((c) => c.appliesTo === ConstraintTarget.SecretValue);+// Only a static-secret rule constrains a value a person types; the other two shape a credential the+// platform generates for itself.+const getValueConstraints = (rule: TSecretValidationRule): TValueConstraints | undefined =>+ rule.type === SecretValidationRuleType.StaticSecrets ? rule.valueConstraints : undefined;const hasValueConstraints = (rule: TSecretValidationRule): boolean =>- getValueConstraints(rule).length > 0;--const doesRuleMatchScope = (- rule: TSecretValidationRule,- secretPath?: string,- selectedEnvironments?: { slug: string }[],- environments?: { id: string; slug: string }[]-): boolean => {- if (!secretPath) return false;-- if (!picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })) {- return false;- }-- if (rule.envId && environments && selectedEnvironments?.length) {- const ruleEnvSlug = environments.find((e) => e.id === rule.envId)?.slug;- if (!ruleEnvSlug) return false;- return selectedEnvironments.some((se) => se.slug === ruleEnvSlug);- }+ Object.values(getValueConstraints(rule) ?? {}).some((value) => value !== undefined);- // Rule applies to all environments (envId is null) and path matches- return true;-};--const generateFromConstraints = (constraints: TConstraint[]): string => {- const prefix = constraints.find((c) => c.type === ConstraintType.RequiredPrefix)?.value || "";- const suffix = constraints.find((c) => c.type === ConstraintType.RequiredSuffix)?.value || "";- const regexValue = constraints.find((c) => c.type === ConstraintType.RegexPattern)?.value;- const minLengthStr = constraints.find((c) => c.type === ConstraintType.MinLength)?.value;- const maxLengthStr = constraints.find((c) => c.type === ConstraintType.MaxLength)?.value;-- const minLength = minLengthStr ? parseInt(minLengthStr, 10) : 16;- const maxLength = maxLengthStr ? parseInt(maxLengthStr, 10) : 64;+const generateFromConstraints = (constraints: TValueConstraints): string => {+ const prefix = constraints.requiredPrefix ?? "";+ const suffix = constraints.requiredSuffix ?? "";+ const regexValue = constraints.regexPattern;+ const minLength = constraints.minLength ?? 16;+ const maxLength = constraints.maxLength ?? 64;let middle: string | undefined;@@ -122,13 +98,25 @@ const generateFromConstraints = (constraints: TConstraint[]): string => {return prefix + middle + suffix;};-const CONSTRAINT_LABELS: Record<ConstraintType, string> = {- [ConstraintType.RequiredPrefix]: "Prefix",- [ConstraintType.RequiredSuffix]: "Suffix",- [ConstraintType.RegexPattern]: "Pattern",- [ConstraintType.MinLength]: "Min length",- [ConstraintType.MaxLength]: "Max length",- [ConstraintType.PreventValueReuse]: "Prevent reuse of previous values"+// The rule's constraints as chips. Reuse prevention carries no value of its own to show, so it+// reads as a statement rather than a "label: value" pair.+const describeConstraints = (constraints: TValueConstraints) => {+ const chips: { key: string; label: string; value?: string }[] = [];+ const add = (key: string, label: string, value?: string | number) => {+ if (value !== undefined) chips.push({ key, label, value: String(value) });+ };++ add("requiredPrefix", "Prefix", constraints.requiredPrefix);+ add("requiredSuffix", "Suffix", constraints.requiredSuffix);+ add("regexPattern", "Pattern", constraints.regexPattern);+ 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" });+ }++ return chips;};const RuleOptionComponent = ({ isSelected, children, ...props }: OptionProps<RuleOption>) => (@@ -162,7 +150,6 @@ export type PasswordGeneratorProps = {maxLength?: number;projectId?: string;secretPath?: string;- environments?: { id: string; slug: string }[];selectedEnvironments?: { slug: string }[];};@@ -173,7 +160,6 @@ export const PasswordGenerator = ({maxLength = 64,projectId,secretPath,- environments,selectedEnvironments}: PasswordGeneratorProps) => {const [isOpen, setIsOpen] = useState(false);@@ -208,10 +194,13 @@ export const PasswordGenerator = ({value: r.id,matchesCurrentScope:selectedEnvironments?.length === 1 &&- doesRuleMatchScope(r, secretPath, selectedEnvironments, environments)+ doesRuleCoverScope(r, {+ secretPath,+ environmentSlugs: selectedEnvironments?.map((e) => e.slug)+ })}))],- [applicableRules, secretPath, selectedEnvironments, environments]+ [applicableRules, secretPath, selectedEnvironments]);const selectedRule = useMemo(@@ -225,17 +214,14 @@ export const PasswordGenerator = ({);const valueConstraints = useMemo(- () => (selectedRule ? getValueConstraints(selectedRule) : []),+ () => (selectedRule ? getValueConstraints(selectedRule) : undefined),[selectedRule]);- const hasRegexLengthConflict = useMemo(() => {- const hasRegex = valueConstraints.some((c) => c.type === ConstraintType.RegexPattern);- const hasLength = valueConstraints.some(- (c) => c.type === ConstraintType.MinLength || c.type === ConstraintType.MaxLength- );- return hasRegex && hasLength;- }, [valueConstraints]);+ const hasRegexLengthConflict = Boolean(+ valueConstraints?.regexPattern &&+ (valueConstraints.minLength !== undefined || valueConstraints.maxLength !== undefined)+ );// Auto-select matching rule only when exactly one environment is selecteduseEffect(() => {@@ -251,13 +237,16 @@ export const PasswordGenerator = ({}const match = applicableRules.find((rule) =>- doesRuleMatchScope(rule, secretPath, selectedEnvironments, environments)+ doesRuleCoverScope(rule, {+ secretPath,+ environmentSlugs: selectedEnvironments?.map((e) => e.slug)+ }));setSelectedRuleId(match?.id || "");- }, [applicableRules, selectedEnvironments, secretPath, environments]);+ }, [applicableRules, selectedEnvironments, secretPath]);const password = useMemo(() => {- if (selectedRule && valueConstraints.length > 0) {+ if (selectedRule && valueConstraints) {return generateFromConstraints(valueConstraints);}@@ -374,19 +363,19 @@ export const PasswordGenerator = ({</div><div className="flex flex-wrap gap-x-4 gap-y-1">- {valueConstraints.map((constraint) => (- <span key={constraint.type} className="text-xs">+ {describeConstraints(valueConstraints ?? {}).map(({ key, label, value }) => (+ <span key={key} className="text-xs"><spanclassName={twMerge("font-medium text-muted",- constraint.type === ConstraintType.PreventValueReuse && "text-label"+ value === undefined && "text-label")}>- {CONSTRAINT_LABELS[constraint.type]}+ {label}</span>- {constraint.type !== ConstraintType.PreventValueReuse && (+ {value !== undefined && (<>- : <span className="font-mono text-label">{constraint.value}</span>+ : <span className="font-mono text-label">{value}</span></>)}</span>diff --git a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.tsindex 7ae69a4b75..76627208f3 100644--- a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts+++ b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts@@ -22,6 +22,7 @@ import {KeyIcon,KeyRoundIcon,LayersIcon,+ ListChecksIcon,LockIcon,type LucideIcon,PenLineIcon,@@ -180,6 +181,7 @@ export const PROJECT_PERMISSION_SUBJECT_PRESENTATION = {[ProjectPermissionSub.SecretApproval]: sm(FileCheckIcon),[ProjectPermissionSub.SecretApprovalRequest]: sm(FileClockIcon),[ProjectPermissionSub.SecretSyncs]: sm(RefreshCwIcon),+ [ProjectPermissionSub.SecretValidationRules]: sm(ListChecksIcon),[ProjectPermissionSub.SecretEventSubscriptions]: sm(RadioIcon),[ProjectPermissionSub.Environments]: sm(LayersIcon),[ProjectPermissionSub.Tags]: sm(TagIcon),diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex 059b23d481..0650b5b768 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -68,6 +68,13 @@ export enum ProjectPermissionSecretSyncActions {RemoveSecrets = "remove-secrets"}+export enum ProjectPermissionSecretValidationRuleActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionPkiSyncActions {Read = "read",Create = "create",@@ -421,6 +428,7 @@ export enum ProjectPermissionSub {Kms = "kms",Cmek = "cmek",SecretSyncs = "secret-syncs",+ SecretValidationRules = "secret-validation-rules",PkiSyncs = "pki-syncs",PkiDiscovery = "pki-discovery",PkiCertificateInstallations = "pki-certificate-installations",@@ -605,6 +613,7 @@ export type ProjectPermissionSet =| [ProjectPermissionActions, ProjectPermissionSub.Environments]| [ProjectPermissionActions, ProjectPermissionSub.IpAllowList]| [ProjectPermissionActions, ProjectPermissionSub.Settings]+ | [ProjectPermissionSecretValidationRuleActions, ProjectPermissionSub.SecretValidationRules]| [ProjectPermissionActions, ProjectPermissionSub.ServiceTokens]| [ProjectPermissionActions, ProjectPermissionSub.SecretApproval]| [diff --git a/frontend/src/hooks/api/secretValidationRules/index.ts b/frontend/src/hooks/api/secretValidationRules/index.tsindex 22d1d35426..b630b4810e 100644--- a/frontend/src/hooks/api/secretValidationRules/index.ts+++ b/frontend/src/hooks/api/secretValidationRules/index.ts@@ -4,18 +4,23 @@ export {useUpdateSecretValidationRule} from "./mutations";export { useListSecretValidationRules } from "./queries";+export { doesRuleCoverScope } from "./scope";export type {- TConstraint,+ TConstraints,TCreateSecretValidationRuleDTO,TDeleteSecretValidationRuleDTO,+ TGeneratedCredentialProvider,+ TReusePrevention,TSecretValidationRule,TSecretValidationRuleConfig,- TUpdateSecretValidationRuleDTO+ TStaticSecretsRuleConfig,+ TUpdateSecretValidationRuleDTO,+ TValueConstraints} from "./types";export {- ConstraintTarget,- ConstraintType,DynamicSecretRuleProvider,+ MAX_CONSTRAINT_LENGTH,+ MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS,SECRET_ROTATION_TO_RULE_PROVIDER,SecretRotationRuleProvider,SecretValidationRuleTypediff --git a/frontend/src/hooks/api/secretValidationRules/mutations.tsx b/frontend/src/hooks/api/secretValidationRules/mutations.tsxindex 226024eaa5..8d34e1d397 100644--- a/frontend/src/hooks/api/secretValidationRules/mutations.tsx+++ b/frontend/src/hooks/api/secretValidationRules/mutations.tsx@@ -10,15 +10,17 @@ import {TUpdateSecretValidationRuleDTO} from "./types";+type TRuleResponse = { secretValidationRule: TSecretValidationRule };+export const useCreateSecretValidationRule = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ projectId, ...body }: TCreateSecretValidationRuleDTO) => {- const { data } = await apiRequest.post<{ rule: TSecretValidationRule }>(- `/api/v1/projects/${projectId}/secret-validation-rules`,+ mutationFn: async ({ type, ...body }: TCreateSecretValidationRuleDTO) => {+ const { data } = await apiRequest.post<TRuleResponse>(+ `/api/v1/secret-validation-rules/${type}`,body);- return data.rule;+ return data.secretValidationRule;},onSuccess: (_, { projectId }) => {queryClient.invalidateQueries({ queryKey: secretValidationRuleKeys.list(projectId) });@@ -29,12 +31,12 @@ export const useCreateSecretValidationRule = () => {export const useUpdateSecretValidationRule = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ projectId, ruleId, ...body }: TUpdateSecretValidationRuleDTO) => {- const { data } = await apiRequest.patch<{ rule: TSecretValidationRule }>(- `/api/v1/projects/${projectId}/secret-validation-rules/${ruleId}`,+ mutationFn: async ({ type, ruleId, projectId: _, ...body }: TUpdateSecretValidationRuleDTO) => {+ const { data } = await apiRequest.patch<TRuleResponse>(+ `/api/v1/secret-validation-rules/${type}/${ruleId}`,body);- return data.rule;+ return data.secretValidationRule;},onSuccess: (_, { projectId }) => {queryClient.invalidateQueries({ queryKey: secretValidationRuleKeys.list(projectId) });@@ -45,11 +47,11 @@ export const useUpdateSecretValidationRule = () => {export const useDeleteSecretValidationRule = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ projectId, ruleId }: TDeleteSecretValidationRuleDTO) => {- const { data } = await apiRequest.delete<{ rule: TSecretValidationRule }>(- `/api/v1/projects/${projectId}/secret-validation-rules/${ruleId}`+ mutationFn: async ({ type, ruleId }: TDeleteSecretValidationRuleDTO) => {+ const { data } = await apiRequest.delete<TRuleResponse>(+ `/api/v1/secret-validation-rules/${type}/${ruleId}`);- return data.rule;+ return data.secretValidationRule;},onSuccess: (_, { projectId }) => {queryClient.invalidateQueries({ queryKey: secretValidationRuleKeys.list(projectId) });diff --git a/frontend/src/hooks/api/secretValidationRules/queries.tsx b/frontend/src/hooks/api/secretValidationRules/queries.tsxindex e37a4ae55c..d1ae8030e1 100644--- a/frontend/src/hooks/api/secretValidationRules/queries.tsx+++ b/frontend/src/hooks/api/secretValidationRules/queries.tsx@@ -24,10 +24,11 @@ export const useListSecretValidationRules = (return useQuery({queryKey: secretValidationRuleKeys.list(projectId),queryFn: async () => {- const { data } = await apiRequest.get<{ rules: TSecretValidationRule[] }>(- `/api/v1/projects/${projectId}/secret-validation-rules`+ const { data } = await apiRequest.get<{ secretValidationRules: TSecretValidationRule[] }>(+ "/api/v1/secret-validation-rules",+ { params: { projectId } });- return data.rules;+ return data.secretValidationRules;},enabled: Boolean(projectId) && (options?.enabled ?? true),...optionsdiff --git a/frontend/src/hooks/api/secretValidationRules/scope.ts b/frontend/src/hooks/api/secretValidationRules/scope.tsnew file mode 100644index 0000000000..62ac11c228--- /dev/null+++ b/frontend/src/hooks/api/secretValidationRules/scope.ts@@ -0,0 +1,17 @@+import picomatch from "picomatch";++import { TSecretValidationRule } from "./types";++// whether a rule covers a given environment and path+export const doesRuleCoverScope = (+ rule: TSecretValidationRule,+ { secretPath, environmentSlugs }: { secretPath?: string; environmentSlugs?: string[] }+): boolean => {+ if (!secretPath) return false;+ if (!picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })) return false;+ if (!rule.environment) return true;++ // With no environment to compare against, the path match is all there is to go on.+ if (!environmentSlugs?.length) return true;+ return environmentSlugs.includes(rule.environment.slug);+};diff --git a/frontend/src/hooks/api/secretValidationRules/types.ts b/frontend/src/hooks/api/secretValidationRules/types.tsindex 5246cd4479..ff9e58c266 100644--- a/frontend/src/hooks/api/secretValidationRules/types.ts+++ b/frontend/src/hooks/api/secretValidationRules/types.ts@@ -6,29 +6,12 @@ export enum SecretValidationRuleType {SecretRotations = "secret-rotations"}-export enum ConstraintType {- MinLength = "min-length",- MaxLength = "max-length",- RegexPattern = "regex-pattern",- RequiredPrefix = "required-prefix",- RequiredSuffix = "required-suffix",- PreventValueReuse = "prevent-value-reuse"-}--export enum ConstraintTarget {- SecretKey = "key",- SecretValue = "value",- GeneratedPassword = "password"-}--// Provider identifiers selectable in dynamic-secret rules.// Mirror of backend `DynamicSecretRuleProvider`.export enum DynamicSecretRuleProvider {SqlDatabase = "sql-database",Milvus = "milvus"}-// Provider identifiers selectable in secret-rotation rules.// Mirror of backend `SecretRotationRuleProvider`.export enum SecretRotationRuleProvider {PostgresCredentials = "postgres-credentials",@@ -39,8 +22,7 @@ export enum SecretRotationRuleProvider {LdapPassword = "ldap-password"}-// Maps SecretRotation types to their corresponding validation rule provider.-// Used by rotation forms to look up the correct provider for ValidationRuleOverrideNotice.+// Rotation forms use this to find the provider a ValidationRuleOverrideNotice should look up.export const SECRET_ROTATION_TO_RULE_PROVIDER: Partial<Record<SecretRotation, SecretRotationRuleProvider>> = {@@ -52,39 +34,53 @@ export const SECRET_ROTATION_TO_RULE_PROVIDER: Partial<[SecretRotation.LdapPassword]: SecretRotationRuleProvider.LdapPassword};-export type TConstraint = {- type: ConstraintType;- appliesTo: ConstraintTarget;- value: string;+export const MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS = 25;+export const MAX_CONSTRAINT_LENGTH = 2048;++// every constraint field a target supports. a field left out is not enforced+export type TConstraints = {+ minLength?: number;+ maxLength?: number;+ regexPattern?: string;+ requiredPrefix?: string;+ requiredSuffix?: string;+};++export type TReusePrevention = {+ previousVersions?: number;+};++export type TValueConstraints = TConstraints & {+ reusePrevention?: TReusePrevention;};-export type TStaticSecretsInputs = {- constraints: TConstraint[];+export type TStaticSecretsRuleConfig = {+ keyConstraints?: TConstraints;+ valueConstraints?: TValueConstraints;};-export type TDynamicSecretsInputs = {+export type TDynamicSecretsRuleConfig = {providers: DynamicSecretRuleProvider[];- constraints: TConstraint[];+ passwordConstraints: TConstraints;};-export type TSecretRotationsInputs = {+export type TSecretRotationsRuleConfig = {providers: SecretRotationRuleProvider[];- constraints: TConstraint[];+ passwordConstraints: TConstraints;};-// A rule's type-specific configuration: the per-type fields sit alongside-// `type`, which discriminates them. Mirror of backend `TSecretValidationRuleConfig`.export type TSecretValidationRuleConfig =- | ({ type: SecretValidationRuleType.StaticSecrets } & TStaticSecretsInputs)- | ({ type: SecretValidationRuleType.DynamicSecrets } & TDynamicSecretsInputs)- | ({ type: SecretValidationRuleType.SecretRotations } & TSecretRotationsInputs);+ | ({ type: SecretValidationRuleType.StaticSecrets } & TStaticSecretsRuleConfig)+ | ({ type: SecretValidationRuleType.DynamicSecrets } & TDynamicSecretsRuleConfig)+ | ({ type: SecretValidationRuleType.SecretRotations } & TSecretRotationsRuleConfig);type TSecretValidationRuleBase = {id: string;name: string;description?: string | null;projectId: string;- envId: string | null;+ // Null when the rule covers every environment in the project.+ environment: { id: string; name: string; slug: string } | null;secretPath: string;isActive: boolean;createdAt: string;@@ -97,28 +93,44 @@ export type TListSecretValidationRulesDTO = {projectId: string;};-export type TCreateSecretValidationRuleDTO = {- projectId: string;+type TRuleScopeFields = {name: string;description?: string | null;- environmentSlug?: string;+ environment?: string;secretPath: string;- rule: TSecretValidationRuleConfig;+ isActive?: boolean;+};++export type TGeneratedCredentialProvider = DynamicSecretRuleProvider | SecretRotationRuleProvider;++type TAnyRuleConfigFields = {+ keyConstraints?: TConstraints;+ valueConstraints?: TValueConstraints;+ providers?: TGeneratedCredentialProvider[];+ passwordConstraints?: TConstraints;};-export type TUpdateSecretValidationRuleDTO = {+export type TCreateSecretValidationRuleDTO = TRuleScopeFields &+ TAnyRuleConfigFields & {+ projectId: string;+ type: SecretValidationRuleType;+ };++export type TUpdateSecretValidationRuleDTO = Partial<Omit<TRuleScopeFields, "environment">> & {projectId: string;ruleId: string;- name?: string;- description?: string | null;- environmentSlug?: string | null;- secretPath?: string;- // Replaced as a whole when supplied; omit to leave the stored config untouched.- rule?: TSecretValidationRuleConfig;- isActive?: boolean;+ type: SecretValidationRuleType;+ // Null makes the rule cover every environment in the project.+ environment?: string | null;+ // Each constraint target is replaced when supplied, cleared when null, left alone when omitted.+ keyConstraints?: TConstraints | null;+ valueConstraints?: TValueConstraints | null;+ providers?: TGeneratedCredentialProvider[];+ passwordConstraints?: TConstraints;};export type TDeleteSecretValidationRuleDTO = {projectId: string;ruleId: string;+ type: SecretValidationRuleType;};diff --git a/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.ts b/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.tsindex ff17bfd812..c3ded796a3 100644--- a/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.ts+++ b/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.ts@@ -1,9 +1,9 @@import { useMemo } from "react";-import picomatch from "picomatch";import { useProject } from "@app/context";import { useListSecretValidationRules } from "./queries";+import { doesRuleCoverScope } from "./scope";import {DynamicSecretRuleProvider,SecretRotationRuleProvider,@@ -35,17 +35,14 @@ export const useMatchingValidationRules = ({const matchingRules = useMemo(() => {if (!environmentSlug || !secretPath) return [];- const env = currentProject.environments.find((e) => e.slug === environmentSlug);- const envId = env?.id;-return rules.filter((rule) => {if (!rule.isActive) return false;if (rule.type !== type) return false;- if (rule.envId && rule.envId !== envId) return false;- if (!picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })) return false;+ if (!doesRuleCoverScope(rule, { secretPath, environmentSlugs: [environmentSlug] }))+ return false;return "providers" in rule && rule.providers.includes(provider as never);});- }, [rules, type, provider, environmentSlug, secretPath, currentProject.environments]);+ }, [rules, type, provider, environmentSlug, secretPath]);return matchingRules;};diff --git a/frontend/src/lib/fn/permission.ts b/frontend/src/lib/fn/permission.tsindex 91e42e33ea..ad146a324c 100644--- a/frontend/src/lib/fn/permission.ts+++ b/frontend/src/lib/fn/permission.ts@@ -138,6 +138,7 @@ const PERMISSION_DISPLAY_NAMES: Record<string, string> = {[ProjectPermissionSub.DynamicSecrets]: "Dynamic Secrets",[ProjectPermissionSub.SecretRotation]: "Secret Rotation",[ProjectPermissionSub.SecretSyncs]: "Secret Syncs",+ [ProjectPermissionSub.SecretValidationRules]: "Secret Validation Rules",[ProjectPermissionSub.SecretEventSubscriptions]: "Secret Event Subscriptions",[ProjectPermissionSub.SecretApproval]: "Secret Approval Policies",[ProjectPermissionSub.SecretApprovalRequest]: "Secret Approval Requests",diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex 0391fd2541..fc61d11e6a 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -711,6 +711,7 @@ export const projectRoleFormSchema = z.object({.array().default([]),[ProjectPermissionSub.Settings]: GeneralPolicyActionSchema.array().default([]),+ [ProjectPermissionSub.SecretValidationRules]: GeneralPolicyActionSchema.array().default([]),[ProjectPermissionSub.Environments]: GeneralPolicyActionSchema.array().default([]),[ProjectPermissionSub.AuditLogs]: AuditLogsPolicyActionSchema.array().default([]),[ProjectPermissionSub.Insights]: InsightsPolicyActionSchema.array().default([]),@@ -1034,6 +1035,7 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {ProjectPermissionSub.SecretRotation,ProjectPermissionSub.Kms,ProjectPermissionSub.SecretSyncs,+ ProjectPermissionSub.SecretValidationRules,ProjectPermissionSub.PkiSyncs,ProjectPermissionSub.SecretEventSubscriptions,ProjectPermissionSub.AppConnections,@@ -2485,6 +2487,16 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {{ label: "Modify", value: "edit", description: "Change project settings and configuration" }]},+ [ProjectPermissionSub.SecretValidationRules]: {+ title: "Secret Validation Rules",+ description: "Define the constraints secrets and generated credentials must satisfy",+ actions: [+ { label: "Read", value: "read", description: "View validation rules" },+ { label: "Create", value: "create", description: "Add validation rules" },+ { label: "Modify", value: "edit", description: "Change validation rules" },+ { label: "Remove", value: "delete", description: "Delete validation rules" }+ ]+ },[ProjectPermissionSub.Environments]: {title: "Environment Management",description: "Create and manage project environments",@@ -3276,6 +3288,7 @@ const SecretsManagerPermissionSubjects = (enabled = false) => ({[ProjectPermissionSub.SecretApproval]: enabled,[ProjectPermissionSub.Integrations]: enabled,[ProjectPermissionSub.SecretSyncs]: enabled,+ [ProjectPermissionSub.SecretValidationRules]: enabled,[ProjectPermissionSub.Kms]: enabled,[ProjectPermissionSub.Environments]: enabled,[ProjectPermissionSub.Tags]: enabled,diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsxindex a70094028b..6fb699a09b 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx@@ -546,7 +546,6 @@ export const CreateSecretForm = ({onUsePassword={field.onChange}projectId={projectId}secretPath={secretPath}- environments={environments}/></div><FieldError errors={[errors.value]} />diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsxindex e2ed392d96..21efc8a8f5 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx@@ -68,14 +68,13 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useProject } from "@app/context";+import { useProject, useProjectPermission } from "@app/context";import {- ProjectPermissionActions,+ ProjectPermissionSecretValidationRuleActions,ProjectPermissionSub} from "@app/context/ProjectPermissionContext/types";import {SecretValidationRuleType,- TSecretValidationRuleConfig,useCreateSecretValidationRule,useDeleteSecretValidationRule,useListSecretValidationRules,@@ -90,6 +89,8 @@ import {DYNAMIC_SECRET_PROVIDER_OPTIONS,DYNAMIC_SECRET_RULE_DISALLOWED_CONSTRAINTS,DynamicSecretRuleProvider,+ flattenConstraints,+ groupConstraintsByTarget,RULE_TYPE_LABELS,ruleFormSchema,RuleType,@@ -532,68 +533,86 @@ type SheetState =export const SecretValidationRulesSection = () => {const { currentProject } = useProject();+ const { permission } = useProjectPermission();++ const canReadRules = permission.can(+ ProjectPermissionSecretValidationRuleActions.Read,+ ProjectPermissionSub.SecretValidationRules+ );const [sheetState, setSheetState] = useState<SheetState>({ open: false });const [deleteRuleId, setDeleteRuleId] = useState<string | null>(null);const [deleteConfirmation, setDeleteConfirmation] = useState("");- const { data: rules = [], isLoading } = useListSecretValidationRules({- projectId: currentProject.id- });+ const { data: rules = [], isLoading } = useListSecretValidationRules(+ { projectId: currentProject.id },+ { enabled: canReadRules }+ );const createRule = useCreateSecretValidationRule();const updateRule = useUpdateSecretValidationRule();const deleteRule = useDeleteSecretValidationRule();- const resolveEnvSlug = (envId: string | null) => {- if (!envId) return null;- const env = currentProject.environments.find((e) => e.id === envId);- return env?.slug ?? null;- };-- const resolveEnvName = (envId: string | null) => {- if (!envId) return "All Environments";- const env = currentProject.environments.find((e) => e.id === envId);- return env?.name ?? envId;- };+ const ruleToDelete = rules.find((rule) => rule.id === deleteRuleId);const handleDelete = async () => {- if (!deleteRuleId) return;+ if (!ruleToDelete) return;await deleteRule- .mutateAsync({ projectId: currentProject.id, ruleId: deleteRuleId })+ .mutateAsync({+ projectId: currentProject.id,+ ruleId: ruleToDelete.id,+ type: ruleToDelete.type+ }).finally(() => setDeleteRuleId(null));};const handleClose = () => setSheetState({ open: false });const handleSubmit = async (data: TRuleForm, isActive?: boolean) => {- // The form mirrors the API rule config field-for-field; only the enum- // identity differs (local `RuleType` vs `SecretValidationRuleType`).- const rule = {- ...data.enforcement,- type: data.enforcement.type as string as SecretValidationRuleType- } as TSecretValidationRuleConfig;+ // The editor keeps constraints in a list; the API groups them by what they apply to.+ const { type } = data.enforcement;+ const grouped = groupConstraintsByTarget(data.enforcement.constraints);+ const isStaticRule = type === RuleType.StaticSecrets;++ const generatedConfig = {+ providers: "providers" in data.enforcement ? data.enforcement.providers : [],+ passwordConstraints: grouped[ConstraintTarget.GeneratedPassword] ?? {}+ };++ const scope = {+ projectId: currentProject.id,+ type,+ name: data.name,+ description: data.description,+ secretPath: data.folderPath+ };if (sheetState.open && sheetState.mode === "edit") {await updateRule.mutateAsync({- projectId: currentProject.id,+ ...scope,ruleId: sheetState.ruleId,- name: data.name,- description: data.description,isActive,- environmentSlug: data.environment ?? null,- secretPath: data.folderPath,- rule+ environment: data.environment,+ // A target with no constraints left is sent as null, so removing its last card clears it on+ // the rule rather than reading as "leave it alone".+ ...(isStaticRule+ ? {+ keyConstraints: grouped[ConstraintTarget.SecretKey] ?? null,+ valueConstraints: grouped[ConstraintTarget.SecretValue] ?? null+ }+ : generatedConfig)});createNotification({ text: "Rule updated", type: "success" });} else {await createRule.mutateAsync({- projectId: currentProject.id,- name: data.name,- description: data.description,- environmentSlug: data.environment ?? undefined,- secretPath: data.folderPath,- rule+ ...scope,+ environment: data.environment ?? undefined,+ ...(isStaticRule+ ? {+ keyConstraints: grouped[ConstraintTarget.SecretKey],+ valueConstraints: grouped[ConstraintTarget.SecretValue]+ }+ : generatedConfig)});createNotification({ text: "Rule created", type: "success" });}@@ -609,11 +628,20 @@ export const SecretValidationRulesSection = () => {? ({name: editingRule.name,description: editingRule.description ?? undefined,- environment: resolveEnvSlug(editingRule.envId),+ environment: editingRule.environment?.slug ?? null,folderPath: editingRule.secretPath,enforcement: {- type: editingRule.type as string as RuleType,- constraints: editingRule.constraints,+ type: editingRule.type,+ constraints:+ editingRule.type === SecretValidationRuleType.StaticSecrets+ ? [+ ...flattenConstraints(editingRule.keyConstraints, ConstraintTarget.SecretKey),+ ...flattenConstraints(editingRule.valueConstraints, ConstraintTarget.SecretValue)+ ]+ : flattenConstraints(+ editingRule.passwordConstraints,+ ConstraintTarget.GeneratedPassword+ ),...("providers" in editingRule && { providers: editingRule.providers })}} as Partial<TRuleForm>)@@ -621,6 +649,8 @@ export const SecretValidationRulesSection = () => {const isEditing = sheetState.open && sheetState.mode === "edit";+ if (!canReadRules) return null;+return (<Card className="mb-6"><CardHeader>@@ -630,7 +660,10 @@ export const SecretValidationRulesSection = () => {generated for dynamic secrets and secret rotations.</CardDescription><CardAction>- <ProjectPermissionCan I={ProjectPermissionActions.Edit} a={ProjectPermissionSub.Settings}>+ <ProjectPermissionCan+ I={ProjectPermissionSecretValidationRuleActions.Create}+ a={ProjectPermissionSub.SecretValidationRules}+ >{(isAllowed) => (<Tooltip><TooltipTrigger asChild>@@ -670,8 +703,8 @@ export const SecretValidationRulesSection = () => {</EmptyHeader><EmptyContent><ProjectPermissionCan- I={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Settings}+ I={ProjectPermissionSecretValidationRuleActions.Create}+ a={ProjectPermissionSub.SecretValidationRules}>{(isAllowed) => (<Tooltip>@@ -725,13 +758,13 @@ export const SecretValidationRulesSection = () => {</div></TableCell><TableCell className="py-3">- <Badge variant="neutral">- {RULE_TYPE_LABELS[rule.type as string as RuleType] ?? rule.type}- </Badge>+ <Badge variant="neutral">{RULE_TYPE_LABELS[rule.type]}</Badge></TableCell><TableCell className="py-3"><div className="flex items-center gap-1.5">- <Badge variant="neutral">{resolveEnvName(rule.envId)}</Badge>+ <Badge variant="neutral">+ {rule.environment?.name ?? "All Environments"}+ </Badge><Badge variant="neutral">{rule.secretPath}</Badge></div></TableCell>@@ -761,8 +794,8 @@ export const SecretValidationRulesSection = () => {Copy Rule ID</DropdownMenuItem><ProjectPermissionCan- I={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Settings}+ I={ProjectPermissionSecretValidationRuleActions.Edit}+ a={ProjectPermissionSub.SecretValidationRules}>{(isAllowed) => (<DropdownMenuItem@@ -777,8 +810,8 @@ export const SecretValidationRulesSection = () => {)}</ProjectPermissionCan><ProjectPermissionCan- I={ProjectPermissionActions.Edit}- a={ProjectPermissionSub.Settings}+ I={ProjectPermissionSecretValidationRuleActions.Delete}+ a={ProjectPermissionSub.SecretValidationRules}>{(isAllowed) => (<DropdownMenuItem@@ -821,15 +854,13 @@ export const SecretValidationRulesSection = () => {<div className="w-full pb-4"><p className="mb-2 text-sm text-muted">Enter the rule name{" "}- <span className="font-medium text-foreground">- {rules.find((r) => r.id === deleteRuleId)?.name}- </span>{" "}- to confirm the deletion+ <span className="font-medium text-foreground">{ruleToDelete?.name}</span> to confirm+ the deletion</p><Inputvalue={deleteConfirmation}onChange={(e) => setDeleteConfirmation(e.target.value)}- placeholder={rules.find((r) => r.id === deleteRuleId)?.name}+ placeholder={ruleToDelete?.name}/></div><AlertDialogFooter>@@ -837,7 +868,7 @@ export const SecretValidationRulesSection = () => {<AlertDialogActionvariant="danger"onClick={handleDelete}- disabled={deleteConfirmation !== rules.find((r) => r.id === deleteRuleId)?.name}+ disabled={deleteConfirmation !== ruleToDelete?.name}>Delete</AlertDialogAction>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 130d9b2419..9bb5e74963 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@@ -12,6 +12,22 @@ import {} from "lucide-react";import { z } from "zod";+import {+ DynamicSecretRuleProvider,+ MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS,+ SecretRotationRuleProvider,+ SecretValidationRuleType,+ TConstraints,+ TValueConstraints+} from "@app/hooks/api/secretValidationRules";++export { DynamicSecretRuleProvider, SecretRotationRuleProvider };++// The editor works in a list of constraints; the API groups them by target. `RuleType` is the local+// alias the form and the cards were built against.+export const RuleType = SecretValidationRuleType;+export type RuleType = SecretValidationRuleType;+export enum ConstraintType {MinLength = "min-length",MaxLength = "max-length",@@ -101,36 +117,12 @@ export const CONSTRAINT_TYPE_LABELS: Record<ConstraintType, string> = {[ConstraintType.PreventValueReuse]: "Prevent Value Reuse"};-export enum RuleType {- StaticSecrets = "static-secrets",- DynamicSecrets = "dynamic-secrets",- SecretRotations = "secret-rotations"-}-export const RULE_TYPE_LABELS: Record<RuleType, string> = {[RuleType.StaticSecrets]: "Static Secrets",[RuleType.DynamicSecrets]: "Dynamic Secrets",[RuleType.SecretRotations]: "Secret Rotations"};-// Provider identifiers selectable in dynamic-secret rules. Keep aligned with-// backend `DynamicSecretRuleProvider`.-export enum DynamicSecretRuleProvider {- SqlDatabase = "sql-database",- Milvus = "milvus"-}--// Provider identifiers selectable in secret-rotation rules. Keep aligned with-// backend `SecretRotationRuleProvider`.-export enum SecretRotationRuleProvider {- PostgresCredentials = "postgres-credentials",- MySqlCredentials = "mysql-credentials",- MsSqlCredentials = "mssql-credentials",- OracleDBCredentials = "oracledb-credentials",- UnixLinuxLocalAccount = "unix-linux-local-account",- LdapPassword = "ldap-password"-}-export type TProviderOption<T extends string> = {value: T;label: string;@@ -187,7 +179,7 @@ export const SECRET_ROTATION_RULE_DISALLOWED_CONSTRAINTS: ConstraintType[] = [ConstraintType.PreventValueReuse];-export const MAX_PREVENT_VALUE_REUSE_VERSIONS = 25;+export const MAX_PREVENT_VALUE_REUSE_VERSIONS = MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS;export const constraintSchema = z.object({@@ -290,3 +282,62 @@ export type TRule = TRuleForm & {id: string;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.+const CONSTRAINT_FIELDS: Record<string, keyof TConstraints> = {+ [ConstraintType.MinLength]: "minLength",+ [ConstraintType.MaxLength]: "maxLength",+ [ConstraintType.RegexPattern]: "regexPattern",+ [ConstraintType.RequiredPrefix]: "requiredPrefix",+ [ConstraintType.RequiredSuffix]: "requiredSuffix"+};++const CONSTRAINT_TYPES = Object.fromEntries(+ Object.entries(CONSTRAINT_FIELDS).map(([type, field]) => [field, type as ConstraintType])+) as Record<string, ConstraintType>;++const NUMERIC_CONSTRAINTS: ConstraintType[] = [ConstraintType.MinLength, ConstraintType.MaxLength];++export const groupConstraintsByTarget = (constraints: TConstraint[]) => {+ const grouped: Partial<Record<ConstraintTarget, TValueConstraints>> = {};++ constraints.forEach(({ type, appliesTo, value }) => {+ const current = grouped[appliesTo] ?? {};++ grouped[appliesTo] =+ type === ConstraintType.PreventValueReuse+ ? {+ ...current,+ reusePrevention: { ...current.reusePrevention, previousVersions: Number(value) }+ }+ : {+ ...current,+ [CONSTRAINT_FIELDS[type]]: NUMERIC_CONSTRAINTS.includes(type) ? Number(value) : value+ };+ });++ return grouped;+};++export const flattenConstraints = (+ constraints: TValueConstraints | null | undefined,+ appliesTo: ConstraintTarget+): TConstraint[] => {+ const { reusePrevention, ...fields } = constraints ?? {};++ const flattened = Object.entries(fields)+ .filter(([, value]) => value !== undefined)+ .map(([field, value]) => ({ type: CONSTRAINT_TYPES[field], appliesTo, value: String(value) }));++ if (reusePrevention?.previousVersions === undefined) return flattened;++ return [+ ...flattened,+ {+ type: ConstraintType.PreventValueReuse,+ appliesTo,+ value: String(reusePrevention.previousVersions)+ }+ ];+};