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): dynamic secrets and rotations support
Daniel38c1e993da4a
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 739d21d7ce..18428a251d 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -141,6 +141,7 @@"pkijs": "^3.2.4","posthog-node": "^5.28.1","probot": "^13.3.8",+ "randexp": "^0.5.3","re2": "^1.21.4","react": "19.1.0","react-dom": "19.1.0",@@ -16039,6 +16040,15 @@"url": "https://github.com/motdotla/dotenv?sponsor=1"}},+ "node_modules/drange": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/drange/-/drange-1.1.1.tgz",+ "integrity": "sha512-pYxfDYpued//QpnLIm4Avk7rsNtAtQkUES2cwAYSvD/wd2pKD71gN2Ebj3e7klzXwjocvE8c5vx/1fxwpqmSxA==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },"node_modules/dunder-proto": {"version": "1.0.1","resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",@@ -24067,6 +24077,28 @@"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz","integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="},+ "node_modules/randexp": {+ "version": "0.5.3",+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.5.3.tgz",+ "integrity": "sha512-U+5l2KrcMNOUPYvazA3h5ekF80FHTUG+87SEAmHZmolh1M+i/WyTCxVzmi+tidIa1tM4BSe8g2Y/D3loWDjj+w==",+ "license": "MIT",+ "dependencies": {+ "drange": "^1.0.2",+ "ret": "^0.2.0"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/randexp/node_modules/ret": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.2.2.tgz",+ "integrity": "sha512-M0b3YWQs7R3Z917WRQy1HHA7Ba7D8hvZg6UE5mLykJxQVE2ju0IXbGlaHPPlkY+WN7wFP+wUMXmBFA0aV6vYGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },"node_modules/random-bytes": {"version": "1.0.0","resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",diff --git a/backend/package.json b/backend/package.jsonindex 9df0b0eebb..e488afa629 100644--- a/backend/package.json+++ b/backend/package.json@@ -197,10 +197,10 @@"@opentelemetry/exporter-prometheus": "^0.217.0","@opentelemetry/instrumentation": "^0.217.0","@opentelemetry/instrumentation-http": "^0.217.0",+ "@opentelemetry/instrumentation-runtime-node": "^0.31.0","@opentelemetry/resources": "^2.7.1","@opentelemetry/sdk-metrics": "^2.7.1","@opentelemetry/semantic-conventions": "^1.34.0",- "@opentelemetry/instrumentation-runtime-node": "^0.31.0","@peculiar/asn1-schema": "^2.3.8","@peculiar/x509": "^1.12.1","@react-email/components": "^1.0.1",@@ -277,6 +277,7 @@"pkijs": "^3.2.4","posthog-node": "^5.28.1","probot": "^13.3.8",+ "randexp": "^0.5.3","re2": "^1.21.4","react": "19.1.0","react-dom": "19.1.0",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 41899ab65c..6c545a1f3e 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,6 +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 { 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";@@ -44,6 +47,7 @@ type TDynamicSecretLeaseServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;userDAL: Pick<TUserDALFactory, "findById">;identityDAL: TIdentityDALFactory;+ secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "findConstraintsForGeneratedSecret">;};export const dynamicSecretLeaseServiceFactory = ({@@ -57,7 +61,8 @@ export const dynamicSecretLeaseServiceFactory = ({licenseService,kmsService,userDAL,- identityDAL+ identityDAL,+ secretValidationRuleService}: TDynamicSecretLeaseServiceFactoryDep): TDynamicSecretLeaseServiceFactory => {const extractEmailUsername = (email: string) => {const regex = new RE2(/^([^@]+)/);@@ -158,13 +163,32 @@ export const dynamicSecretLeaseServiceFactory = ({identity.name = machineIdentity.name;}}+ const ruleProvider = convertDynamicSecretProviderToValidationRuleProvider(+ dynamicSecretCfg.type as DynamicSecretProviders+ );+ let passwordValidation:+ | Awaited<ReturnType<typeof secretValidationRuleService.findConstraintsForGeneratedSecret>>+ | undefined;+ if (ruleProvider) {+ const matched = await secretValidationRuleService.findConstraintsForGeneratedSecret({+ projectId,+ envId: folder.envId,+ secretPath: path,+ type: SecretValidationRuleType.DynamicSecrets,+ provider: ruleProvider+ });+ if (matched.constraints.length) {+ passwordValidation = matched;+ }+ }+result = await selectedProvider.create({inputs: decryptedStoredInput,expireAt: expireAt.getTime(),usernameTemplate: dynamicSecretCfg.usernameTemplate,identity,dynamicSecret: dynamicSecretCfg,- metadata: { projectId },+ metadata: { projectId, passwordValidation },config});} catch (error: unknown) {diff --git a/backend/src/ee/services/dynamic-secret/providers/milvus.ts b/backend/src/ee/services/dynamic-secret/providers/milvus.tsindex e589891d3b..4e65e8bf04 100644--- a/backend/src/ee/services/dynamic-secret/providers/milvus.ts+++ b/backend/src/ee/services/dynamic-secret/providers/milvus.ts@@ -11,13 +11,14 @@ import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";+import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator";import { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";-import { DynamicSecretMilvusSchema, TDynamicProviderFns } from "./models";+import { DynamicSecretMilvusSchema, TDynamicProviderCreateMetadata, TDynamicProviderFns } from "./models";import { generateUsername } from "./templateUtils";type TMilvusProviderInputs = z.infer<typeof DynamicSecretMilvusSchema>;@@ -222,8 +223,9 @@ export const MilvusProvider = ({usernameTemplate?: string | null;identity: ActorIdentityAttributes;dynamicSecret: TDynamicSecrets;+ metadata?: TDynamicProviderCreateMetadata;}) => {- const { inputs, usernameTemplate, identity, dynamicSecret } = data;+ const { inputs, usernameTemplate, identity, dynamicSecret, metadata } = data;const providerInputs = await validateProviderInputs(inputs as object);const username = await generateUsername(@@ -236,7 +238,9 @@ export const MilvusProvider = ({},sanitizeMilvusUsername);- const password = generatePassword();+ const password = metadata?.passwordValidation?.constraints?.length+ ? generatePasswordWithConstraints(metadata.passwordValidation.constraints)+ : generatePassword();const roleName = deriveRoleName(username);const gatewayCallback = async (host: string, port: number) => {diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.tsindex 2ba4b7f9c1..62b875b025 100644--- a/backend/src/ee/services/dynamic-secret/providers/models.ts+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts@@ -5,6 +5,7 @@ import { TDynamicSecrets } from "@app/db/schemas";import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";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 {ActorIdentityAttributes,@@ -826,6 +827,19 @@ export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [z.object({ type: z.literal(DynamicSecretProviders.Ssh), inputs: DynamicSecretSshSchema })]);+// Extended metadata passed to a provider's create() call. When the project+// has a matching secret validation rule, `passwordValidation` carries the+// constraints that any generated password must satisfy; providers that+// generate passwords (e.g. sql-database, milvus) honor it in place of the+// user-configured passwordRequirements.+export type TDynamicProviderCreateMetadata = {+ projectId: string;+ passwordValidation?: {+ constraints: TConstraint[];+ ruleNames: string[];+ };+};+export type TDynamicProviderFns = {create: (arg: {inputs: unknown;@@ -833,7 +847,7 @@ export type TDynamicProviderFns = {usernameTemplate?: string | null;identity: ActorIdentityAttributes;dynamicSecret: TDynamicSecrets;- metadata: { projectId: string };+ metadata: TDynamicProviderCreateMetadata;config?: TDynamicSecretLeaseConfig;}) => Promise<{ entityId: string; data: unknown }>;validateConnection: (inputs: unknown, metadata: { projectId: string }) => Promise<boolean>;diff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.tsindex 559f3d96fe..717a9b5d53 100644--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts@@ -10,13 +10,20 @@ import { sanitizeString } from "@app/lib/fn";import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";+import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator";import { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";-import { DynamicSecretSqlDBSchema, PasswordRequirements, SqlProviders, TDynamicProviderFns } from "./models";+import {+ DynamicSecretSqlDBSchema,+ PasswordRequirements,+ SqlProviders,+ TDynamicProviderCreateMetadata,+ TDynamicProviderFns+} from "./models";import { generateUsername } from "./templateUtils";const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;@@ -287,8 +294,9 @@ export const SqlDatabaseProvider = ({usernameTemplate?: string | null;identity: ActorIdentityAttributes;dynamicSecret: TDynamicSecrets;+ metadata?: TDynamicProviderCreateMetadata;}) => {- const { inputs, expireAt, usernameTemplate, identity, dynamicSecret } = data;+ const { inputs, expireAt, usernameTemplate, identity, dynamicSecret, metadata } = data;const providerInputs = await validateProviderInputs(inputs);const { database } = providerInputs;@@ -298,7 +306,11 @@ export const SqlDatabaseProvider = ({identity});- const password = generatePassword(providerInputs.client, providerInputs.passwordRequirements);+ // When a secret validation rule covers this provider/scope, it fully+ // replaces the user-configured password requirements.+ const password = metadata?.passwordValidation?.constraints?.length+ ? generatePasswordWithConstraints(metadata.passwordValidation.constraints)+ : generatePassword(providerInputs.client, providerInputs.passwordRequirements);const gatewayCallback = async (host = providerInputs.host, port = providerInputs.port) => {const db = await $getClient({...providerInputs,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 4917ae1dca..7ff45d3f89 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@@ -89,6 +89,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 { 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";@@ -164,6 +167,7 @@ export type TSecretRotationV2ServiceFactoryDep = {gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;+ secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "findConstraintsForGeneratedSecret">;};export type TSecretRotationV2ServiceFactory = ReturnType<typeof secretRotationV2ServiceFactory>;@@ -224,8 +228,34 @@ export const secretRotationV2ServiceFactory = ({gatewayService,gatewayV2Service,gatewayPoolService,- telemetryService+ telemetryService,+ secretValidationRuleService}: TSecretRotationV2ServiceFactoryDep) => {+ const $resolvePasswordValidationContext = async ({+ projectId,+ envId,+ secretPath,+ type+ }: {+ projectId: string;+ envId: string;+ secretPath: string;+ type: SecretRotation;+ }) => {+ const provider = convertSecretRotationToValidationRuleProvider(type);+ if (!provider) return undefined;++ const matched = await secretValidationRuleService.findConstraintsForGeneratedSecret({+ projectId,+ envId,+ secretPath,+ type: SecretValidationRuleType.SecretRotations,+ provider+ });+ if (!matched.constraints.length) return undefined;+ return matched;+ };+const $queueSendSecretRotationStatusNotification = async (secretRotation: TSecretRotationV2Raw) => {const appCfg = getConfig();if (!appCfg.isSmtpConfigured) return; // comment out if testing email sending@@ -559,6 +589,13 @@ export const secretRotationV2ServiceFactory = ({actor);+ const passwordValidationContext = await $resolvePasswordValidationContext({+ projectId,+ envId: folder.envId,+ secretPath,+ type: payload.type+ });+const rotationFactory = SECRET_ROTATION_FACTORY_MAP[payload.type]({parameters: payload.parameters,@@ -570,7 +607,8 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayService,gatewayV2Service,- gatewayPoolService+ gatewayPoolService,+ passwordValidationContext);// Perform ALL validation checks BEFORE rotating credentials on the external system.@@ -931,6 +969,13 @@ export const secretRotationV2ServiceFactory = ({if (revokeGeneratedCredentials) {const appConnection = await decryptAppConnection(connection, kmsService);+ const passwordValidationContext = await $resolvePasswordValidationContext({+ projectId,+ envId: environment.id,+ secretPath: folder.path,+ type+ });+const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type]({...secretRotation,@@ -940,7 +985,8 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayService,gatewayV2Service,- gatewayPoolService+ gatewayPoolService,+ passwordValidationContext);const generatedCredentials = await decryptSecretRotationCredentials({@@ -1257,6 +1303,13 @@ export const secretRotationV2ServiceFactory = ({const inactiveCredentials = generatedCredentials[inactiveIndex];const activeCredentials = generatedCredentials[activeIndex];+ const passwordValidationContext = await $resolvePasswordValidationContext({+ projectId,+ envId: environment.id,+ secretPath: folder.path,+ type: type as SecretRotation+ });+const rotationFactory = SECRET_ROTATION_FACTORY_MAP[type as SecretRotation]({...secretRotation,@@ -1266,7 +1319,8 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayService,gatewayV2Service,- gatewayPoolService+ gatewayPoolService,+ passwordValidationContext);const updatedRotation = await rotationFactory.rotateCredentials(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 e7a2ad0f6f..ab67332094 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@@ -410,6 +410,15 @@ export type TRotationFactoryCheckActiveCredentials<T extends TSecretRotationV2GeactiveCredentials: T[number]) => Promise<void>;+// Password validation context passed to factories when an active+// secret-validation rule covers the rotation's project/env/path/provider.+// When present, factories that generate passwords must satisfy these+// constraints and ignore any user-provided passwordRequirements.+export type TRotationPasswordValidationContext = {+ constraints: import("@app/services/secret-validation-rule/secret-validation-rule-types").TConstraint[];+ ruleNames: string[];+};+export type TRotationFactory<T extends TSecretRotationV2WithConnection,C extends TSecretRotationV2GeneratedCredentials,@@ -420,7 +429,8 @@ export type TRotationFactory<kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,+ passwordValidationContext?: TRotationPasswordValidationContext) => {issueCredentials: TRotationFactoryIssueCredentials<C, P>;revokeCredentials: TRotationFactoryRevokeCredentials<C>;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 6b15850017..457bf0c105 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@@ -15,6 +15,7 @@ import {executeWithPotentialGateway,SQL_CONNECTION_ALTER_LOGIN_STATEMENT} from "@app/services/app-connection/shared/sql";+import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator";import { DEFAULT_PASSWORD_REQUIREMENTS, generatePassword } from "../utils";import {@@ -44,7 +45,15 @@ const ORACLE_PASSWORD_REQUIREMENTS = {export const sqlCredentialsRotationFactory: TRotationFactory<TSqlCredentialsRotationWithConnection,TSqlCredentialsRotationGeneratedCredentials-> = (secretRotation, _appConnectionDAL, _kmsService, gatewayService, gatewayV2Service, gatewayPoolService) => {+> = (+ secretRotation,+ _appConnectionDAL,+ _kmsService,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ passwordValidationContext+) => {const {connection,parameters: {@@ -68,6 +77,13 @@ export const sqlCredentialsRotationFactory: TRotationFactory<connection.app === AppConnection.OracleDB ? ORACLE_PASSWORD_REQUIREMENTS : DEFAULT_PASSWORD_REQUIREMENTS;const passwordRequirement = userProvidedPasswordRequirements || defaultPasswordRequirement;+ // When a secret validation rule covers this rotation, its constraints+ // fully replace the user-configured passwordRequirements.+ const generateRotationPassword = () =>+ passwordValidationContext?.constraints?.length+ ? generatePasswordWithConstraints(passwordValidationContext.constraints)+ : generatePassword(passwordRequirement);+let resolvedConnection: typeof connection | undefined;const getResolvedConnection = async () => {if (!resolvedConnection) {@@ -132,10 +148,10 @@ export const sqlCredentialsRotationFactory: TRotationFactory<) => {// For SQL, since we get existing users, we change both their passwords// on issue to invalidate their existing passwords- const credentialsSet = [{ username: username1, password: generatePassword(passwordRequirement) }];+ const credentialsSet = [{ username: username1, password: generateRotationPassword() }];// if both are same username like for mysql dual password rotation - we don't want to reissue twice loosing first cred accessif (username1 !== username2) {- credentialsSet.push({ username: username2, password: generatePassword(passwordRequirement) });+ credentialsSet.push({ username: username2, password: generateRotationPassword() });}try {@@ -163,7 +179,7 @@ export const sqlCredentialsRotationFactory: TRotationFactory<) => {const revokedCredentials = credentialsToRevoke.map(({ username }) => ({username,- password: generatePassword(passwordRequirement)+ password: generateRotationPassword()}));try {@@ -189,7 +205,7 @@ export const sqlCredentialsRotationFactory: TRotationFactory<// generate new password for the next active userconst credentials = {username: activeIndex === 0 ? username2 : username1,- password: generatePassword(passwordRequirement)+ password: generateRotationPassword()};try {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3f60027115..ec8d3098f0 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2355,7 +2355,8 @@ export const registerRoutes = async (licenseService,kmsService,userDAL,- identityDAL+ identityDAL,+ secretValidationRuleService});const emailDomainService = emailDomainServiceFactory({@@ -2600,7 +2601,8 @@ export const registerRoutes = async (gatewayService,gatewayV2Service,gatewayPoolService,- telemetryService+ telemetryService,+ secretValidationRuleService});const insightsService = insightsServiceFactory({diff --git a/backend/src/server/routes/v1/secret-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-router.tsindex ed0411b652..4076311e6c 100644--- a/backend/src/server/routes/v1/secret-validation-rule-router.ts+++ b/backend/src/server/routes/v1/secret-validation-rule-router.ts@@ -6,6 +6,8 @@ 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 {+ dynamicSecretsInputsSchema,+ secretRotationsInputsSchema,SecretValidationRuleInputSchema,SecretValidationRuleResponseSchema,staticSecretsInputsSchema@@ -127,7 +129,9 @@ export const registerSecretValidationRuleRouter = async (server: FastifyZodProvienvironmentSlug: z.string().trim().min(1).nullable().optional(),secretPath: z.string().trim().min(1).optional(),type: z.nativeEnum(SecretValidationRuleType).optional(),- inputs: staticSecretsInputsSchema.optional(),+ inputs: z+ .union([staticSecretsInputsSchema, dynamicSecretsInputsSchema, secretRotationsInputsSchema])+ .optional(),isActive: z.boolean().optional()}),response: {diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.tsindex 3c489ffaf1..8b5a5bb58a 100644--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts@@ -993,7 +993,9 @@ export const getHCVaultSecretsForPaths = async (return [];}- const fetchParams = {+ let skipNamespaceHeader = false;++ const parameters = {namespace,mounts,instanceUrl,@@ -1001,43 +1003,36 @@ export const getHCVaultSecretsForPaths = async (connection,gatewayService,gatewayV2Service- };+ } as const;- const fetchOne = async (vaultSecretPath: string, skipNamespaceHeader: boolean) => ({- vaultSecretPath,- secrets: await fetchVaultSecretAtPath({- ...fetchParams,- secretPath: vaultSecretPath,- skipNamespaceHeader- })- });-- const [firstPath, ...restPaths] = secretPaths;+ const [firstSecretPath, ...restSecretPaths] = secretPaths;// Probe with the first path: Vault 1.0.0 returns 301 for root/"/" when the namespace header is sent.// so we need to remove the namespace header and retry the request.- let skipNamespaceHeader = false;- let firstResult: { vaultSecretPath: string; secrets: Record<string, JsonValue> };- try {- firstResult = await fetchOne(firstPath, false);- } catch (error) {- if (error instanceof NamespaceHeaderNotSupportedError) {+ await fetchVaultSecretAtPath({+ ...parameters,+ secretPath: firstSecretPath,+ skipNamespaceHeader+ }).catch((err) => {+ if (err instanceof NamespaceHeaderNotSupportedError) {skipNamespaceHeader = true;- firstResult = await fetchOne(firstPath, true);} else {- throw error;+ throw err;}- }-- if (restPaths.length === 0) {- return [firstResult];- }+ });- const restResults = await Promise.all(- restPaths.map((vaultSecretPath) => limiter(() => fetchOne(vaultSecretPath, skipNamespaceHeader)))+ return Promise.all(+ secretPaths.map((vaultSecretPath) =>+ limiter(async () => {+ const secrets = await fetchVaultSecretAtPath({+ ...parameters,+ secretPath: vaultSecretPath,+ skipNamespaceHeader+ });+ return { vaultSecretPath, secrets };+ })+ ));-- return [firstResult, ...restResults];};export const getHCVaultAuthMounts = async (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 82299190ec..cac4dace45 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,14 +1,20 @@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 { MAX_PREVENT_VALUE_REUSE_VERSIONS } from "./secret-validation-rule-schemas";import {ConstraintTarget,ConstraintType,+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,SecretValidationRuleType,TConstraint,+ TDynamicSecretsInputs,+ TSecretRotationsInputs,TSecretValidationRuleInputs,TStaticSecretsInputs} from "./secret-validation-rule-types";@@ -78,13 +84,42 @@ const $checkStaticSecretsConstraintOverlap = (return overlapping;};+/**+ * 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 [];++ 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;+};+type TOverlapChecker<TInputs = TSecretValidationRuleInputs> = (incoming: TInputs,existing: TInputs) => ConstraintType[];const overlapCheckersByType: Record<SecretValidationRuleType, TOverlapChecker> = {- [SecretValidationRuleType.StaticSecrets]: $checkStaticSecretsConstraintOverlap as TOverlapChecker+ [SecretValidationRuleType.StaticSecrets]: $checkStaticSecretsConstraintOverlap as TOverlapChecker,+ [SecretValidationRuleType.DynamicSecrets]: $checkGeneratedSecretConstraintOverlap as TOverlapChecker,+ [SecretValidationRuleType.SecretRotations]: $checkGeneratedSecretConstraintOverlap as TOverlapChecker};export const checkForOverlappingRules = ({@@ -176,7 +211,8 @@ const CONSTRAINT_LABELS: Record<ConstraintType, string> = {const TARGET_LABELS: Record<ConstraintTarget, string> = {[ConstraintTarget.SecretKey]: "key",- [ConstraintTarget.SecretValue]: "value"+ [ConstraintTarget.SecretValue]: "value",+ [ConstraintTarget.GeneratedPassword]: "password"};const evaluateConstraint = (constraint: TConstraint, secret: TSecretToValidate): string | null => {@@ -288,7 +324,10 @@ const enforceStaticSecretsRules = (rules: TValidationRule[], secrets: TSecretToV// To add a new rule type, implement an enforcer and add it here.type TRuleEnforcer = (rules: TValidationRule[], secrets: TSecretToValidate[]) => TValidationViolation[];-const ruleEnforcersByType: Record<SecretValidationRuleType, TRuleEnforcer> = {+// 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};@@ -359,3 +398,26 @@ export const enforceSecretValidationRules = ({});}};++// 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.+export const convertDynamicSecretProviderToValidationRuleProvider = (+ type: DynamicSecretProviders+): DynamicSecretRuleProvider | null => {+ if (type === DynamicSecretProviders.SqlDatabase) return DynamicSecretRuleProvider.SqlDatabase;+ if (type === DynamicSecretProviders.Milvus) return DynamicSecretRuleProvider.Milvus;++ return 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;+ }+ return null;+};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.tsnew file mode 100644index 0000000000..465b30b2ee--- /dev/null+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-password-generator.ts@@ -0,0 +1,103 @@+import { randomInt } from "crypto";+import RandExp from "randexp";+import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";++import { ConstraintTarget, ConstraintType, TConstraint } from "./secret-validation-rule-types";++const DEFAULT_MIN_LENGTH = 16;+const DEFAULT_MAX_LENGTH = 64;++const CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*";++const generateRandomString = (length: number): string => {+ let out = "";+ for (let i = 0; i < length; i += 1) {+ out += CHAR_POOL[randomInt(0, CHAR_POOL.length)];+ }+ return out;+};++/**+ * 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.+ */+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 ?? "";++ let middle: string;++ if (regexConstraint) {+ // 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;+ } catch {+ throw new BadRequestError({+ message: `Secret validation rule contains an invalid regex pattern: ${regexConstraint.value}`+ });+ }+ try {+ middle = new RandExp(new RegExp(validatedPattern)).gen();+ } catch {+ throw new BadRequestError({+ message: `Could not generate a value from regex pattern: ${regexConstraint.value}`+ });+ }+ } 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) {+ throw new BadRequestError({+ message: "Secret validation rule has impossible length constraints"+ });+ }++ const fixedLength = prefix.length + suffix.length;+ if (fixedLength > maxLength) {+ throw new BadRequestError({+ message: "Secret validation rule prefix/suffix exceeds max length"+ });+ }++ const targetMinFill = Math.max(0, minLength - fixedLength);+ const targetMaxFill = maxLength - fixedLength;+ const fillLength =+ targetMaxFill === targetMinFill ? targetMinFill : targetMinFill + randomInt(0, targetMaxFill - targetMinFill + 1);++ middle = generateRandomString(fillLength);+ }++ return `${prefix}${middle}${suffix}`;+};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 b00d1e3f08..be1b6ebb0c 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@@ -5,50 +5,105 @@ import { SecretValidationRulesSchema } from "@app/db/schemas";import {ConstraintTarget,ConstraintType,+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,SecretValidationRuleType,TSecretValidationRuleInputs} from "./secret-validation-rule-types";export const MAX_PREVENT_VALUE_REUSE_VERSIONS = 25;-export const constraintSchema = z- .object({- type: z.nativeEnum(ConstraintType),- appliesTo: z.nativeEnum(ConstraintTarget),- value: z.string()- })- .refine((c) => c.type === ConstraintType.PreventValueReuse || c.value.length > 0, {- message: "Value is required",- path: ["value"]- })- .refine((c) => c.type !== ConstraintType.PreventValueReuse || c.appliesTo === ConstraintTarget.SecretValue, {+// Targets that constraints are allowed to apply to per rule type.+// Generated-credential rules currently only target the generated password+// (the username slot is reserved for future use).+const STATIC_RULE_TARGETS = new Set<ConstraintTarget>([ConstraintTarget.SecretKey, ConstraintTarget.SecretValue]);+const GENERATED_RULE_TARGETS = new Set<ConstraintTarget>([ConstraintTarget.GeneratedPassword]);++// Constraint types not meaningful for the given rule type. PreventValueReuse+// requires a version history, which dynamic secrets (ephemeral leases) do not have.+const DYNAMIC_DISALLOWED_CONSTRAINTS = new Set<ConstraintType>([ConstraintType.PreventValueReuse]);++const baseConstraintSchema = z.object({+ type: z.nativeEnum(ConstraintType),+ appliesTo: z.nativeEnum(ConstraintTarget),+ value: z.string()+});++const valueRequiredRefinement = (c: z.infer<typeof baseConstraintSchema>) =>+ c.type === ConstraintType.PreventValueReuse || c.value.length > 0;++const preventValueReuseTargetRefinement = (c: z.infer<typeof baseConstraintSchema>) =>+ c.type !== ConstraintType.PreventValueReuse || c.appliesTo === ConstraintTarget.SecretValue;++const preventValueReuseRangeRefinement = (c: z.infer<typeof baseConstraintSchema>) => {+ 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 const constraintSchema = baseConstraintSchema+ .refine(valueRequiredRefinement, { message: "Value is required", path: ["value"] })+ .refine(preventValueReuseTargetRefinement, {message: "No value reuse constraint can only apply to secret values",path: ["appliesTo"]})- .refine(- (c) => {- if (c.type !== ConstraintType.PreventValueReuse) return true;- const num = Number(c.value);- return Number.isInteger(num) && num >= 1 && num <= MAX_PREVENT_VALUE_REUSE_VERSIONS;- },- {+ .refine(preventValueReuseRangeRefinement, {+ message: `Prevent value reuse version count must be between 1 and ${MAX_PREVENT_VALUE_REUSE_VERSIONS}`,+ path: ["value"]+ });++const buildConstraintSchemaForRuleType = (ruleType: SecretValidationRuleType) => {+ const allowedTargets =+ ruleType === SecretValidationRuleType.StaticSecrets ? STATIC_RULE_TARGETS : GENERATED_RULE_TARGETS;+ const disallowedTypes =+ ruleType === SecretValidationRuleType.StaticSecrets ? new Set<ConstraintType>() : DYNAMIC_DISALLOWED_CONSTRAINTS;++ return baseConstraintSchema+ .refine((c) => allowedTargets.has(c.appliesTo), {+ message: `Constraint target is not allowed for ${ruleType} rules`,+ path: ["appliesTo"]+ })+ .refine((c) => !disallowedTypes.has(c.type), {+ message: `Constraint type is not supported for ${ruleType} rules`,+ path: ["type"]+ })+ .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"]- }- );+ });+};export const staticSecretsInputsSchema = z.object({- constraints: z.array(constraintSchema).min(1)+ constraints: z.array(buildConstraintSchemaForRuleType(SecretValidationRuleType.StaticSecrets)).min(1)+});++export const dynamicSecretsInputsSchema = z.object({+ providers: z.array(z.nativeEnum(DynamicSecretRuleProvider)).min(1, "Select at least one provider"),+ constraints: z.array(buildConstraintSchemaForRuleType(SecretValidationRuleType.DynamicSecrets)).min(1)+});++export const secretRotationsInputsSchema = z.object({+ providers: z.array(z.nativeEnum(SecretRotationRuleProvider)).min(1, "Select at least one provider"),+ constraints: z.array(buildConstraintSchemaForRuleType(SecretValidationRuleType.SecretRotations)).min(1)});// Discriminated union for create/update request bodiesexport const SecretValidationRuleInputSchema = z.discriminatedUnion("type", [- z.object({ type: z.literal(SecretValidationRuleType.StaticSecrets), inputs: staticSecretsInputsSchema })+ z.object({ type: z.literal(SecretValidationRuleType.StaticSecrets), inputs: staticSecretsInputsSchema }),+ z.object({ type: z.literal(SecretValidationRuleType.DynamicSecrets), inputs: dynamicSecretsInputsSchema }),+ z.object({ type: z.literal(SecretValidationRuleType.SecretRotations), inputs: secretRotationsInputsSchema })]);// Map of type → inputs schema, used for runtime parsingconst inputsSchemaMap: Record<SecretValidationRuleType, z.ZodSchema<TSecretValidationRuleInputs>> = {- [SecretValidationRuleType.StaticSecrets]: staticSecretsInputsSchema+ [SecretValidationRuleType.StaticSecrets]: staticSecretsInputsSchema,+ [SecretValidationRuleType.DynamicSecrets]: dynamicSecretsInputsSchema,+ [SecretValidationRuleType.SecretRotations]: secretRotationsInputsSchema};export const parseSecretValidationRuleInputs = (type: string, inputs: unknown) => {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 b7ccc1e8d3..0770de6511 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@@ -15,14 +15,20 @@ import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";import { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";import { checkForOverlappingRules, enforceSecretValidationRules } from "./secret-validation-rule-fns";+import { generatePasswordWithConstraints } from "./secret-validation-rule-password-generator";import { MAX_PREVENT_VALUE_REUSE_VERSIONS, parseSecretValidationRuleInputs } from "./secret-validation-rule-schemas";import {ConstraintTarget,ConstraintType,+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,SecretValidationRuleType,+ TConstraint,TCreateSecretValidationRuleDTO,TDeleteSecretValidationRuleDTO,+ TDynamicSecretsInputs,TListSecretValidationRulesDTO,+ TSecretRotationsInputs,TUpdateSecretValidationRuleDTO} from "./secret-validation-rule-types";@@ -117,6 +123,13 @@ export const secretValidationRuleServiceFactory = ({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) {+ generatePasswordWithConstraints((parsedInputs as TDynamicSecretsInputs | TSecretRotationsInputs).constraints);+ }+const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.SecretManager,projectId@@ -215,6 +228,10 @@ export const secretValidationRuleServiceFactory = ({const ruleInputs = inputs ?? (JSON.parse(decryptedExistingRuleInputs.toString()) as unknown);const parsedInputs = parseSecretValidationRuleInputs(ruleType, ruleInputs);+ if (ruleType === SecretValidationRuleType.DynamicSecrets || ruleType === SecretValidationRuleType.SecretRotations) {+ generatePasswordWithConstraints((parsedInputs as TDynamicSecretsInputs | TSecretRotationsInputs).constraints);+ }+const finalEnvId = envId !== undefined ? envId : (existingRule.envId as string | null);const finalSecretPath = dto.secretPath ?? existingRule.secretPath;@@ -422,11 +439,73 @@ export const secretValidationRuleServiceFactory = ({});};+ /**+ * 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.+ */+ const findConstraintsForGeneratedSecret = async ({+ projectId,+ envId,+ secretPath,+ type,+ provider+ }: {+ projectId: string;+ envId: string;+ secretPath: string;+ type: SecretValidationRuleType.DynamicSecrets | SecretValidationRuleType.SecretRotations;+ provider: DynamicSecretRuleProvider | SecretRotationRuleProvider;+ }): Promise<{ constraints: TConstraint[]; ruleNames: string[] }> => {+ const rules = await secretValidationRuleDAL.find({ projectId, isActive: true, type });+ if (!rules.length) return { constraints: [], ruleNames: [] };++ const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ const constraints: TConstraint[] = [];+ 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(+ rule.type,+ JSON.parse(ruleInputsDecryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown+ ) as TDynamicSecretsInputs | TSecretRotationsInputs;++ if (!parsed.providers?.includes(provider as never)) {+ // eslint-disable-next-line no-continue+ continue;+ }++ constraints.push(...parsed.constraints);+ ruleNames.push(rule.name);+ }++ return { constraints, ruleNames };+ };+return {listByProjectId,createRule,updateRule,deleteRule,- validateSecrets+ 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 c41e30b544..2a4c37025c 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,7 +1,9 @@import { TProjectPermission } from "@app/lib/types";export enum SecretValidationRuleType {- StaticSecrets = "static-secrets"+ StaticSecrets = "static-secrets",+ DynamicSecrets = "dynamic-secrets",+ SecretRotations = "secret-rotations"}export enum ConstraintType {@@ -15,7 +17,22 @@ export enum ConstraintType {export enum ConstraintTarget {SecretKey = "key",- SecretValue = "value"+ 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"}export type TConstraint = {@@ -28,7 +45,17 @@ export type TStaticSecretsInputs = {constraints: TConstraint[];};-export type TSecretValidationRuleInputs = TStaticSecretsInputs;+export type TDynamicSecretsInputs = {+ providers: DynamicSecretRuleProvider[];+ constraints: TConstraint[];+};++export type TSecretRotationsInputs = {+ providers: SecretRotationRuleProvider[];+ constraints: TConstraint[];+};++export type TSecretValidationRuleInputs = TStaticSecretsInputs | TDynamicSecretsInputs | TSecretRotationsInputs;export type TCreateSecretValidationRuleDTO = {name: string;diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/shared/SqlCredentialsRotationParametersFields.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/shared/SqlCredentialsRotationParametersFields.tsxindex 19f4e1cd7c..4474de14c1 100644--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/shared/SqlCredentialsRotationParametersFields.tsx+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/shared/SqlCredentialsRotationParametersFields.tsx@@ -2,12 +2,17 @@ import { Controller, useFormContext } from "react-hook-form";import { ClipboardCheckIcon, CopyIcon } from "lucide-react";import { TSecretRotationV2Form } from "@app/components/secret-rotations-v2/forms/schemas";+import { ValidationRuleOverrideNotice } from "@app/components/secret-validation/ValidationRuleOverrideNotice";import { FormControl, Input, Tab, TabList, TabPanel, Tabs, TextArea } from "@app/components/v2";import { NoticeBannerV2 } from "@app/components/v2/NoticeBannerV2/NoticeBannerV2";import { IconButton, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";import { useTimedReset } from "@app/hooks";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { SecretRotation, useSecretRotationV2Option } from "@app/hooks/api/secretRotationsV2";+import {+ SecretRotationRuleProvider,+ SecretValidationRuleType+} from "@app/hooks/api/secretValidationRules";import { DEFAULT_PASSWORD_REQUIREMENTS } from "../../schemas/shared";@@ -29,6 +34,8 @@ export const SqlCredentialsRotationParametersFields = () => {const { rotationOption } = useSecretRotationV2Option(type);const [, isCopied, setCopyState] = useTimedReset({ initialState: false });+ const environmentSlug = watch("environment")?.slug;+ const secretPath = watch("secretPath");const handleCopy = () => {navigator.clipboard.writeText(rotationOption!.template.createUserStatement);@@ -147,6 +154,14 @@ export const SqlCredentialsRotationParametersFields = () => {)}/><div className="flex flex-col gap-3">+ {type === SecretRotation.PostgresCredentials && (+ <ValidationRuleOverrideNotice+ type={SecretValidationRuleType.SecretRotations}+ provider={SecretRotationRuleProvider.PostgresCredentials}+ environmentSlug={environmentSlug}+ secretPath={secretPath}+ />+ )}<div className="w-full border-b border-mineshaft-600"><span className="text-sm text-mineshaft-300">Password Requirements</span></div>diff --git a/frontend/src/components/secret-validation/ValidationRuleOverrideNotice.tsx b/frontend/src/components/secret-validation/ValidationRuleOverrideNotice.tsxnew file mode 100644index 0000000000..236e6a0a87--- /dev/null+++ b/frontend/src/components/secret-validation/ValidationRuleOverrideNotice.tsx@@ -0,0 +1,43 @@+import { InfoIcon } from "lucide-react";++import {+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,+ SecretValidationRuleType,+ useMatchingValidationRules+} from "@app/hooks/api/secretValidationRules";++type Props = {+ type: SecretValidationRuleType.DynamicSecrets | SecretValidationRuleType.SecretRotations;+ provider: DynamicSecretRuleProvider | SecretRotationRuleProvider;+ environmentSlug?: string | null;+ secretPath?: string;+};++/**+ * Renders a low-key info banner when at least one active secret-validation+ * rule covers the given generated-credential scope. Surfaces that the+ * user-configured password requirements will be ignored in favor of the+ * rule's constraints.+ */+export const ValidationRuleOverrideNotice = ({+ type,+ provider,+ environmentSlug,+ secretPath+}: Props) => {+ const matching = useMatchingValidationRules({ type, provider, environmentSlug, secretPath });+ if (!matching.length) return null;++ const ruleLabel =+ matching.length === 1 ? `rule "${matching[0].name}"` : `${matching.length} rules`;+ return (+ <div className="mb-3 flex items-start gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-800 px-3 py-2 text-xs text-mineshaft-200">+ <InfoIcon className="mt-0.5 size-4 shrink-0 text-mineshaft-400" />+ <span>+ A secret validation {ruleLabel} applies to this scope. The password configuration below will+ be ignored in favor of the rule's constraints.+ </span>+ </div>+ );+};diff --git a/frontend/src/hooks/api/secretValidationRules/index.ts b/frontend/src/hooks/api/secretValidationRules/index.tsindex 2a2bbd7969..d0cee27f3e 100644--- a/frontend/src/hooks/api/secretValidationRules/index.ts+++ b/frontend/src/hooks/api/secretValidationRules/index.ts@@ -11,4 +11,11 @@ export type {TSecretValidationRule,TUpdateSecretValidationRuleDTO} from "./types";-export { ConstraintTarget, ConstraintType } from "./types";+export {+ ConstraintTarget,+ ConstraintType,+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,+ SecretValidationRuleType+} from "./types";+export { useMatchingValidationRules } from "./useMatchingValidationRules";diff --git a/frontend/src/hooks/api/secretValidationRules/types.ts b/frontend/src/hooks/api/secretValidationRules/types.tsindex ebcc0bbca9..6b86086442 100644--- a/frontend/src/hooks/api/secretValidationRules/types.ts+++ b/frontend/src/hooks/api/secretValidationRules/types.ts@@ -1,5 +1,7 @@export enum SecretValidationRuleType {- StaticSecrets = "static-secrets"+ StaticSecrets = "static-secrets",+ DynamicSecrets = "dynamic-secrets",+ SecretRotations = "secret-rotations"}export enum ConstraintType {@@ -13,7 +15,21 @@ export enum ConstraintType {export enum ConstraintTarget {SecretKey = "key",- SecretValue = "value"+ 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"}export type TConstraint = {@@ -26,7 +42,20 @@ export type TStaticSecretsInputs = {constraints: TConstraint[];};-export type TSecretValidationRuleInputs = TStaticSecretsInputs;+export type TDynamicSecretsInputs = {+ providers: DynamicSecretRuleProvider[];+ constraints: TConstraint[];+};++export type TSecretRotationsInputs = {+ providers: SecretRotationRuleProvider[];+ constraints: TConstraint[];+};++export type TSecretValidationRuleInputs =+ | TStaticSecretsInputs+ | TDynamicSecretsInputs+ | TSecretRotationsInputs;export type TSecretValidationRule = {id: string;diff --git a/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.ts b/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.tsnew file mode 100644index 0000000000..26ecc2b98d--- /dev/null+++ b/frontend/src/hooks/api/secretValidationRules/useMatchingValidationRules.ts@@ -0,0 +1,54 @@+import { useMemo } from "react";+import picomatch from "picomatch";++import { useProject } from "@app/context";++import { useListSecretValidationRules } from "./queries";+import {+ DynamicSecretRuleProvider,+ SecretRotationRuleProvider,+ SecretValidationRuleType,+ TDynamicSecretsInputs,+ TSecretRotationsInputs+} from "./types";++type TParams = {+ type: SecretValidationRuleType.DynamicSecrets | SecretValidationRuleType.SecretRotations;+ provider: DynamicSecretRuleProvider | SecretRotationRuleProvider;+ environmentSlug?: string | null;+ secretPath?: string;+};++/**+ * Returns the active validation rules that cover the given+ * generated-credential scope (env + path + provider + rule type).+ * Used by dynamic-secret and rotation forms to surface a warning that+ * user-configured password requirements will be ignored.+ */+export const useMatchingValidationRules = ({+ type,+ provider,+ environmentSlug,+ secretPath+}: TParams) => {+ const { currentProject } = useProject();+ const { data: rules = [] } = useListSecretValidationRules({ projectId: currentProject.id });++ 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;+ const inputs = rule.inputs as TDynamicSecretsInputs | TSecretRotationsInputs;+ return inputs.providers?.includes(provider as never);+ });+ }, [rules, type, provider, environmentSlug, secretPath, currentProject.environments]);++ return matchingRules;+};diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsxindex 3a3ba64771..e642e630e3 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx@@ -9,6 +9,7 @@ import { z } from "zod";import { TtlFormLabel } from "@app/components/features";import { createNotification } from "@app/components/notifications";import { OrgPermissionCan } from "@app/components/permissions";+import { ValidationRuleOverrideNotice } from "@app/components/secret-validation/ValidationRuleOverrideNotice";import {Accordion,AccordionContent,@@ -37,6 +38,10 @@ import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { DynamicSecretProviders, SqlProviders } from "@app/hooks/api/dynamicSecret/types";import { VaultDatabaseRole } from "@app/hooks/api/migration/types";+import {+ DynamicSecretRuleProvider,+ SecretValidationRuleType+} from "@app/hooks/api/secretValidationRules";import { ProjectEnv } from "@app/hooks/api/types";import { slugSchema } from "@app/lib/schemas";@@ -752,6 +757,12 @@ export const SqlDatabaseInputForm = ({<AccordionItem value="password-config"><AccordionTrigger>Password Configuration (optional)</AccordionTrigger><AccordionContent>+ <ValidationRuleOverrideNotice+ type={SecretValidationRuleType.DynamicSecrets}+ provider={DynamicSecretRuleProvider.SqlDatabase}+ environmentSlug={watch("environment")?.slug}+ secretPath={secretPath}+ /><div className="mb-4 text-sm text-mineshaft-300">Set constraints on the generated database password</div>diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsxindex b5423d4f19..d45be477ee 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx@@ -22,6 +22,7 @@ import {ConstraintTarget,ConstraintType,MAX_PREVENT_VALUE_REUSE_VERSIONS,+ RuleType,TRuleForm} from "./SecretValidationRulesSection.utils";@@ -34,6 +35,10 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {const { control, watch } = useFormContext<TRuleForm>();const constraintType = watch(`enforcement.inputs.constraints.${index}.type`);const allConstraints = watch("enforcement.inputs.constraints");+ const ruleType = watch("enforcement.type");+ // Generated-credential rules currently only target the generated password.+ const isGeneratedCredentialRule =+ ruleType === RuleType.DynamicSecrets || ruleType === RuleType.SecretRotations;const constraintOption = CONSTRAINT_OPTIONS.find((o) => o.type === constraintType);@@ -71,41 +76,54 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {)}<div className="mt-3 grid grid-cols-2 gap-3">- {isPreventValueReuse ? (- <div className="flex flex-col gap-1">- <label className="text-xs font-medium text-muted">Applies to</label>- <Input value="Secret Value" readOnly className="cursor-default opacity-60" />- </div>- ) : (- <div className="flex flex-col gap-1">- <label className="text-xs font-medium text-muted">Applies to</label>- <Controller- control={control}- name={`enforcement.inputs.constraints.${index}.appliesTo`}- render={({ field: { value, onChange } }) => (- <Select value={value} onValueChange={onChange}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem- value={ConstraintTarget.SecretKey}- disabled={otherTargets.has(ConstraintTarget.SecretKey)}- >- Secret Key- </SelectItem>- <SelectItem- value={ConstraintTarget.SecretValue}- disabled={otherTargets.has(ConstraintTarget.SecretValue)}- >- Secret Value- </SelectItem>- </SelectContent>- </Select>- )}- />- </div>- )}+ {(() => {+ if (isGeneratedCredentialRule) {+ return (+ <div className="flex flex-col gap-1">+ <label className="text-xs font-medium text-muted">Applies to</label>+ <Input value="Generated Password" readOnly className="cursor-default opacity-60" />+ </div>+ );+ }+ if (isPreventValueReuse) {+ return (+ <div className="flex flex-col gap-1">+ <label className="text-xs font-medium text-muted">Applies to</label>+ <Input value="Secret Value" readOnly className="cursor-default opacity-60" />+ </div>+ );+ }+ return (+ <div className="flex flex-col gap-1">+ <label className="text-xs font-medium text-muted">Applies to</label>+ <Controller+ control={control}+ name={`enforcement.inputs.constraints.${index}.appliesTo`}+ render={({ field: { value, onChange } }) => (+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem+ value={ConstraintTarget.SecretKey}+ disabled={otherTargets.has(ConstraintTarget.SecretKey)}+ >+ Secret Key+ </SelectItem>+ <SelectItem+ value={ConstraintTarget.SecretValue}+ disabled={otherTargets.has(ConstraintTarget.SecretValue)}+ >+ Secret Value+ </SelectItem>+ </SelectContent>+ </Select>+ )}+ />+ </div>+ );+ })()}<div className="flex flex-col gap-1"><label className="text-xs font-medium text-muted"><div className="flex items-center gap-1">diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsxindex 9c29371576..108be1df52 100644--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.tsx@@ -2,11 +2,20 @@import { useState } from "react";import { Controller, FormProvider, useFieldArray, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { EllipsisVerticalIcon, InfoIcon, PencilIcon, PlusIcon, TrashIcon } from "lucide-react";+import {+ EllipsisVerticalIcon,+ InfoIcon,+ PencilIcon,+ PlusIcon,+ TrashIcon,+ TriangleAlertIcon+} from "lucide-react";import { createNotification } from "@app/components/notifications";import { GlobPatternTooltip, ProjectPermissionCan } from "@app/components/permissions";import {+ Alert,+ AlertDescription,AlertDialog,AlertDialogAction,AlertDialogCancel,@@ -15,6 +24,7 @@ import {AlertDialogFooter,AlertDialogHeader,AlertDialogTitle,+ AlertTitle,Badge,Button,Card,@@ -32,6 +42,7 @@ import {EmptyDescription,EmptyHeader,EmptyTitle,+ FilterableSelect,IconButton,Input,Select,@@ -74,12 +85,63 @@ import {CONSTRAINT_OPTIONS,ConstraintTarget,ConstraintType,+ DYNAMIC_SECRET_PROVIDER_OPTIONS,+ DYNAMIC_SECRET_RULE_DISALLOWED_CONSTRAINTS,+ DynamicSecretRuleProvider,RULE_TYPE_LABELS,ruleFormSchema,RuleType,+ SECRET_ROTATION_PROVIDER_OPTIONS,+ SECRET_ROTATION_RULE_DISALLOWED_CONSTRAINTS,+ SecretRotationRuleProvider,+ TProviderOption,TRuleForm} from "./SecretValidationRulesSection.utils";+const ProviderMultiSelect = <T extends string>({+ label,+ options,+ control,+ error+}: {+ label: string;+ options: TProviderOption<T>[];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ control: any;+ error?: string;+}) => {+ return (+ <div className="flex flex-col gap-1">+ <label className="text-xs font-medium text-muted">{label}</label>+ <Controller+ control={control}+ name="enforcement.inputs.providers"+ render={({ field }) => {+ const selected = options.filter((opt) =>+ (field.value as T[] | undefined)?.includes(opt.value)+ );+ return (+ <FilterableSelect+ isMulti+ placeholder="Select provider(s)..."+ value={selected}+ onChange={(next) => {+ const arr = (next as TProviderOption<T>[] | null) ?? [];+ field.onChange(arr.map((o) => o.value));+ }}+ options={options}+ getOptionValue={(o) => (o as TProviderOption<T>).value}+ getOptionLabel={(o) => (o as TProviderOption<T>).label}+ isError={Boolean(error)}+ />+ );+ }}+ />+ {error && <p className="mt-1 text-xs text-danger">{error}</p>}+ </div>+ );+};+const RuleFormContent = ({defaultValues,isEditing,@@ -119,18 +181,38 @@ const RuleFormContent = ({formState: { errors }} = form;- const { fields, append, remove } = useFieldArray({+ const { fields, append, remove, replace } = useFieldArray({control,name: "enforcement.inputs.constraints"});const watchedConstraints = form.watch("enforcement.inputs.constraints");+ const watchedRuleType = form.watch("enforcement.type");+ const isGeneratedCredentialRule =+ watchedRuleType === RuleType.DynamicSecrets || watchedRuleType === RuleType.SecretRotations;+ const disallowedConstraintTypes = (() => {+ if (watchedRuleType === RuleType.DynamicSecrets)+ return DYNAMIC_SECRET_RULE_DISALLOWED_CONSTRAINTS;+ if (watchedRuleType === RuleType.SecretRotations)+ return SECRET_ROTATION_RULE_DISALLOWED_CONSTRAINTS;+ return [] as ConstraintType[];+ })();const usedConstraintPairs = new Set(watchedConstraints?.map((c) => `${c.type}:${c.appliesTo}`));+ // Regex generation uses RandExp on the produced string and cannot honor+ // separate min/max length constraints — the regex pattern dictates the+ // output length. Warn when both are configured.+ const hasRegexLengthConflict = (() => {+ const hasRegex = watchedConstraints?.some((c) => c.type === ConstraintType.RegexPattern);+ const hasLength = watchedConstraints?.some(+ (c) => c.type === ConstraintType.MinLength || c.type === ConstraintType.MaxLength+ );+ return Boolean(hasRegex && hasLength);+ })();const availableConstraintOptions = CONSTRAINT_OPTIONS.filter((opt) => {- const targets = opt.allowedTargets || [- ConstraintTarget.SecretKey,- ConstraintTarget.SecretValue- ];+ if (disallowedConstraintTypes.includes(opt.type)) return false;+ const targets = isGeneratedCredentialRule+ ? [ConstraintTarget.GeneratedPassword]+ : opt.allowedTargets || [ConstraintTarget.SecretKey, ConstraintTarget.SecretValue];return targets.some((target) => !usedConstraintPairs.has(`${opt.type}:${target}`));});@@ -181,25 +263,64 @@ const RuleFormContent = ({</div></div>- {/* Enforcement Type */}- <div className="flex flex-col gap-1">- <label className="text-xs font-medium text-muted">Rule Type</label>- <Controller- control={control}- name="enforcement.type"- render={({ field: { value, onChange } }) => (- <Select value={value} onValueChange={onChange}>- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={RuleType.StaticSecrets}>- {RULE_TYPE_LABELS[RuleType.StaticSecrets]}- </SelectItem>- </SelectContent>- </Select>- )}- />+ {/* Enforcement Type + Providers */}+ <div className="grid grid-cols-2 gap-4">+ <div className="flex flex-col gap-1">+ <label className="text-xs font-medium text-muted">Rule Type</label>+ <Controller+ control={control}+ name="enforcement.type"+ render={({ field: { value, onChange } }) => (+ <Select+ value={value}+ onValueChange={(next) => {+ onChange(next);+ replace([]);+ if (next !== RuleType.StaticSecrets) {+ form.setValue("enforcement.inputs.providers" as never, [] as never, {+ shouldDirty: true,+ shouldValidate: false+ });+ }+ }}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ {(Object.values(RuleType) as RuleType[]).map((t) => (+ <SelectItem key={t} value={t}>+ {RULE_TYPE_LABELS[t]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </div>+ {watchedRuleType === RuleType.DynamicSecrets && (+ <ProviderMultiSelect<DynamicSecretRuleProvider>+ label="Dynamic Secret Providers"+ options={DYNAMIC_SECRET_PROVIDER_OPTIONS}+ control={control}+ error={+ // discriminated form types: providers only exists on this arm+ (errors.enforcement?.inputs as { providers?: { message?: string } } | undefined)+ ?.providers?.message+ }+ />+ )}+ {watchedRuleType === RuleType.SecretRotations && (+ <ProviderMultiSelect<SecretRotationRuleProvider>+ label="Rotation Providers"+ options={SECRET_ROTATION_PROVIDER_OPTIONS}+ control={control}+ error={+ (errors.enforcement?.inputs as { providers?: { message?: string } } | undefined)+ ?.providers?.message+ }+ />+ )}</div>{/* Scope */}@@ -261,6 +382,23 @@ const RuleFormContent = ({</div></div>+ {hasRegexLengthConflict && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertTitle>Regex pattern takes precedence over length constraints</AlertTitle>+ <AlertDescription>+ <p>+ When a regex pattern is set, generated values are produced directly from the+ pattern and the min/max length constraints are ignored. Define the length+ requirement inside the regex pattern itself+ <br /> (e.g.{" "}+ <code className="rounded-md bg-mineshaft-700 px-1 py-0.5">{"[A-Z]{12,20}"}</code>+ ).+ </p>+ </AlertDescription>+ </Alert>+ )}+{/* Constraints */}<div><div className="mb-3 flex items-center justify-between">@@ -275,10 +413,12 @@ const RuleFormContent = ({</DropdownMenuTrigger><DropdownMenuContent align="end">{availableConstraintOptions.map((opt) => {- const targets = opt.allowedTargets || [- ConstraintTarget.SecretValue,- ConstraintTarget.SecretKey- ];+ const targets = isGeneratedCredentialRule+ ? [ConstraintTarget.GeneratedPassword]+ : opt.allowedTargets || [+ ConstraintTarget.SecretValue,+ ConstraintTarget.SecretKey+ ];const defaultTarget =targets.find((t) => !usedConstraintPairs.has(`${opt.type}:${t}`)) ??targets[0];@@ -431,8 +571,8 @@ export const SecretValidationRulesSection = () => {? rules.find((r) => r.id === sheetState.ruleId): undefined;- const editingDefaults = editingRule- ? {+ const editingDefaults: Partial<TRuleForm> | undefined = editingRule+ ? ({name: editingRule.name,description: editingRule.description ?? undefined,environment: resolveEnvSlug(editingRule.envId),@@ -441,7 +581,7 @@ export const SecretValidationRulesSection = () => {type: editingRule.type as string as RuleType,inputs: editingRule.inputs}- }+ } as Partial<TRuleForm>): undefined;const isEditing = sheetState.open && sheetState.mode === "edit";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 6e143e091b..3245fcbb26 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@@ -1,6 +1,8 @@import {+ DatabaseIcon,HashIcon,HistoryIcon,+ LayersIcon,LucideIcon,RulerIcon,TextCursorInputIcon,@@ -19,7 +21,8 @@ export enum ConstraintType {export enum ConstraintTarget {SecretKey = "key",- SecretValue = "value"+ SecretValue = "value",+ GeneratedPassword = "password"}export const CONSTRAINT_OPTIONS: {@@ -97,13 +100,59 @@ export const CONSTRAINT_TYPE_LABELS: Record<ConstraintType, string> = {};export enum RuleType {- StaticSecrets = "static-secrets"+ StaticSecrets = "static-secrets",+ DynamicSecrets = "dynamic-secrets",+ SecretRotations = "secret-rotations"}export const RULE_TYPE_LABELS: Record<RuleType, string> = {- [RuleType.StaticSecrets]: "Static Secrets"+ [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"+}++export type TProviderOption<T extends string> = {+ value: T;+ label: string;+ icon: LucideIcon;+};++export const DYNAMIC_SECRET_PROVIDER_OPTIONS: TProviderOption<DynamicSecretRuleProvider>[] = [+ { value: DynamicSecretRuleProvider.SqlDatabase, label: "SQL Database", icon: DatabaseIcon },+ { value: DynamicSecretRuleProvider.Milvus, label: "Milvus", icon: LayersIcon }+];++export const SECRET_ROTATION_PROVIDER_OPTIONS: TProviderOption<SecretRotationRuleProvider>[] = [+ {+ value: SecretRotationRuleProvider.PostgresCredentials,+ label: "PostgreSQL Credentials",+ icon: DatabaseIcon+ }+];++// Constraints supported for generated-credential rules. PreventValueReuse is+// excluded for dynamic secrets (ephemeral leases, no version history) but+// supported for rotations.+export const DYNAMIC_SECRET_RULE_DISALLOWED_CONSTRAINTS: ConstraintType[] = [+ ConstraintType.PreventValueReuse+];+export const SECRET_ROTATION_RULE_DISALLOWED_CONSTRAINTS: ConstraintType[] = [+ ConstraintType.PreventValueReuse+];+export const MAX_PREVENT_VALUE_REUSE_VERSIONS = 25;export const constraintSchema = z@@ -128,17 +177,38 @@ export const constraintSchema = z});+const duplicateConstraintRefinement = (+ constraints: { type: ConstraintType; appliesTo: ConstraintTarget }[]+) => {+ const pairs = constraints.map((c) => `${c.type}:${c.appliesTo}`);+ return new Set(pairs).size === pairs.length;+};+const staticSecretsInputsSchema = z.object({constraints: z.array(constraintSchema).min(1, "At least one constraint is required")- .refine(- (constraints) => {- const pairs = constraints.map((c) => `${c.type}:${c.appliesTo}`);- return new Set(pairs).size === pairs.length;- },- { message: "Duplicate constraint for the same target" }- )+ .refine(duplicateConstraintRefinement, { message: "Duplicate constraint for the same target" })+});++const dynamicSecretsInputsSchema = z.object({+ providers: z+ .array(z.nativeEnum(DynamicSecretRuleProvider))+ .min(1, "Select at least one provider"),+ constraints: z+ .array(constraintSchema)+ .min(1, "At least one constraint is required")+ .refine(duplicateConstraintRefinement, { message: "Duplicate constraint for the same target" })+});++const secretRotationsInputsSchema = z.object({+ providers: z+ .array(z.nativeEnum(SecretRotationRuleProvider))+ .min(1, "Select at least one provider"),+ constraints: z+ .array(constraintSchema)+ .min(1, "At least one constraint is required")+ .refine(duplicateConstraintRefinement, { message: "Duplicate constraint for the same target" })});export const ruleFormSchema = z.object({@@ -146,10 +216,11 @@ export const ruleFormSchema = z.object({description: z.string().max(500).optional(),environment: z.string().nullable().default(null),folderPath: z.string().min(1, "Folder path is required").default("/**"),- enforcement: z.object({- type: z.nativeEnum(RuleType),- inputs: staticSecretsInputsSchema- })+ enforcement: z.discriminatedUnion("type", [+ z.object({ type: z.literal(RuleType.StaticSecrets), inputs: staticSecretsInputsSchema }),+ z.object({ type: z.literal(RuleType.DynamicSecrets), inputs: dynamicSecretsInputsSchema }),+ z.object({ type: z.literal(RuleType.SecretRotations), inputs: secretRotationsInputsSchema })+ ])});export type TRuleForm = z.infer<typeof ruleFormSchema>;