Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Merge remote-tracking branch 'origin/main' into feature/PKI-25

Carlos Monastyrski7ec81b5f10a5
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 032b1f7500..40793d4e30 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -141,6 +141,7 @@ import { TSecretReplicationServiceFactory } from "@app/services/secret-replicati
import { TSecretSharingServiceFactory } from "@app/services/secret-sharing/secret-sharing-service";
import { TSecretSyncServiceFactory } from "@app/services/secret-sync/secret-sync-service";
import { TSecretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service";
+import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";
import { TServiceTokenServiceFactory } from "@app/services/service-token/service-token-service";
import { TSignerServiceFactory } from "@app/services/signer/signer-service";
import { TSlackServiceFactory } from "@app/services/slack/slack-service";
@@ -273,6 +274,7 @@ declare module "fastify" {
secret: TSecretServiceFactory;
secretReplication: TSecretReplicationServiceFactory;
secretTag: TSecretTagServiceFactory;
+ secretValidationRule: TSecretValidationRuleServiceFactory;
secretImport: TSecretImportServiceFactory;
projectBot: TProjectBotServiceFactory;
folder: TSecretFolderServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 925a0b05e8..4509f3da0e 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -732,6 +732,11 @@ import {
TSecretReminderRecipientsInsert,
TSecretReminderRecipientsUpdate
} from "@app/db/schemas/secret-reminder-recipients";
+import {
+ TSecretValidationRules,
+ TSecretValidationRulesInsert,
+ TSecretValidationRulesUpdate
+} from "@app/db/schemas/secret-validation-rules";
import {
TUserNotifications,
TUserNotificationsInsert,
@@ -1736,5 +1741,10 @@ declare module "knex/types/tables" {
TCertificateCleanupConfigsInsert,
TCertificateCleanupConfigsUpdate
>;
+ [TableName.SecretValidationRule]: KnexOriginal.CompositeTableType<
+ TSecretValidationRules,
+ TSecretValidationRulesInsert,
+ TSecretValidationRulesUpdate
+ >;
}
}
diff --git a/backend/src/db/migrations/20260319204352_secret-validation-rules.ts b/backend/src/db/migrations/20260319204352_secret-validation-rules.ts
new file mode 100644
index 0000000000..4446b1aa21
--- /dev/null
+++ b/backend/src/db/migrations/20260319204352_secret-validation-rules.ts
@@ -0,0 +1,39 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.SecretValidationRule))) {
+ await knex.schema.createTable(TableName.SecretValidationRule, (tb) => {
+ tb.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ tb.string("name").notNullable();
+ tb.string("description").nullable();
+ tb.string("projectId").notNullable();
+ tb.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+
+ // null = not scoped to a specific env
+ tb.uuid("envId").nullable();
+ tb.foreign("envId").references("id").inTable(TableName.Environment).onDelete("CASCADE");
+
+ // we store it as a string because it's a glob pattern that we need to evaluate against at a later stage, not a specific folder
+ tb.string("secretPath").notNullable();
+ tb.string("type").notNullable();
+ tb.binary("encryptedInputs").notNullable();
+ tb.boolean("isActive").notNullable().defaultTo(true);
+
+ tb.index("projectId");
+ tb.index("envId");
+ tb.index("secretPath");
+
+ tb.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.SecretValidationRule);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await dropOnUpdateTrigger(knex, TableName.SecretValidationRule);
+ await knex.schema.dropTableIfExists(TableName.SecretValidationRule);
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 734bd084e4..eaa8fe87fd 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -208,6 +208,7 @@ export * from "./secret-syncs";
export * from "./secret-tag-junction";
export * from "./secret-tags";
export * from "./secret-v2-tag-junction";
+export * from "./secret-validation-rules";
export * from "./secret-version-tag-junction";
export * from "./secret-version-v2-tag-junction";
export * from "./secret-versions";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 5e85b8992e..08b979fb34 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -278,7 +278,8 @@ export enum TableName {
PkiSigningOperations = "pki_signing_operations",
QueueJobs = "queue_jobs",
- CaSigningConfig = "ca_signing_configs"
+ CaSigningConfig = "ca_signing_configs",
+ SecretValidationRule = "secret_validation_rules"
}
export type TImmutableDBKeys = "id" | "createdAt" | "updatedAt" | "commitId";
diff --git a/backend/src/db/schemas/secret-validation-rules.ts b/backend/src/db/schemas/secret-validation-rules.ts
new file mode 100644
index 0000000000..cb4abd104c
--- /dev/null
+++ b/backend/src/db/schemas/secret-validation-rules.ts
@@ -0,0 +1,28 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const SecretValidationRulesSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ projectId: z.string(),
+ envId: z.string().uuid().nullable().optional(),
+ secretPath: z.string(),
+ type: z.string(),
+ encryptedInputs: zodBuffer,
+ isActive: z.boolean().default(true),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TSecretValidationRules = z.infer<typeof SecretValidationRulesSchema>;
+export type TSecretValidationRulesInsert = Omit<z.input<typeof SecretValidationRulesSchema>, TImmutableDBKeys>;
+export type TSecretValidationRulesUpdate = Partial<Omit<z.input<typeof SecretValidationRulesSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 4f0708c188..ac8ff7ee79 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -699,7 +699,12 @@ export enum EventType {
GET_PKI_SIGNING_OPERATIONS = "get-pki-signing-operations",
PKI_SIGNER_SIGN = "pki-signer-sign",
SCEP_ENROLLMENT = "scep-enrollment",
- SCEP_RENEWAL = "scep-renewal"
+ SCEP_RENEWAL = "scep-renewal",
+
+ // Secret Validation Rules
+ SECRET_VALIDATION_RULE_CREATE = "secret-validation-rule-create",
+ SECRET_VALIDATION_RULE_UPDATE = "secret-validation-rule-update",
+ SECRET_VALIDATION_RULE_DELETE = "secret-validation-rule-delete"
}
// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.
@@ -5515,6 +5520,37 @@ interface ScepRenewalEvent {
};
}
+interface SecretValidationRuleCreateEvent {
+ type: EventType.SECRET_VALIDATION_RULE_CREATE;
+ metadata: {
+ ruleId: string;
+ name: string;
+ type: string;
+ environmentSlug?: string;
+ secretPath: string;
+ };
+}
+
+interface SecretValidationRuleUpdateEvent {
+ type: EventType.SECRET_VALIDATION_RULE_UPDATE;
+ metadata: {
+ ruleId: string;
+ name?: string;
+ type?: string;
+ environmentSlug?: string | null;
+ secretPath?: string;
+ isActive?: boolean;
+ };
+}
+
+interface SecretValidationRuleDeleteEvent {
+ type: EventType.SECRET_VALIDATION_RULE_DELETE;
+ metadata: {
+ ruleId: string;
+ name: string;
+ };
+}
+
export type Event =
| CreateSubOrganizationEvent
| UpdateSubOrganizationEvent
@@ -6013,4 +6049,7 @@ export type Event =
| UpdateCertificateCleanupConfigEvent
| CertificateCleanupCompletedEvent
| ScepEnrollmentEvent
- | ScepRenewalEvent;
+ | ScepRenewalEvent
+ | SecretValidationRuleCreateEvent
+ | SecretValidationRuleUpdateEvent
+ | SecretValidationRuleDeleteEvent;
diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.ts
index 2c2fb21ff0..ae287bb39e 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -474,6 +474,25 @@ export const ldapConfigServiceFactory = ({
newUser = userWithSameUsername;
}
+ // Prevent cross-org account takeover: if an existing user was found by email,
+ // verify they are already a member of this org before binding the LDAP identity.
+ if (newUser) {
+ const [existingMembership] = await orgDAL.findMembership(
+ {
+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
+ },
+ { tx }
+ );
+ if (!existingMembership) {
+ throw new ForbiddenRequestError({
+ message:
+ "User is not a member of this organization. Please contact your organization admin to receive an invite."
+ });
+ }
+ }
+
if (!newUser) {
const uniqueUsername = await normalizeUsername(username, userDAL);
newUser = await userDAL.create(
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 6b764f2628..b3ac192177 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -278,6 +278,27 @@ export const oidcConfigServiceFactory = ({
}
}
+ // Prevent cross-org account takeover: if an existing user was found by email,
+ // verify they are already a member of this org before binding the SSO identity.
+ // Without this check, an attacker could configure OIDC on their own org with a
+ // victim's email and get a provider token signed for the victim's userId.
+ if (newUser) {
+ const [existingMembership] = await orgDAL.findMembership(
+ {
+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
+ },
+ { tx }
+ );
+ if (!existingMembership) {
+ throw new ForbiddenRequestError({
+ message:
+ "User is not a member of this organization. Please contact your organization admin to receive an invite."
+ });
+ }
+ }
+
if (!newUser) {
const uniqueUsername = await normalizeUsername(externalId, userDAL);
newUser = await userDAL.create(
diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts
index d987da6584..f3ff03e703 100644
--- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts
+++ b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts
@@ -105,7 +105,8 @@ const makeSqlConnection = (
// (like being able to do an auth handshake regardless pass or not)
if (
connectOnly &&
- error.message === `password authentication failed for user "${TEST_CONNECTION_USERNAME}"`
+ (error.message === `password authentication failed for user "${TEST_CONNECTION_USERNAME}"` ||
+ error.message === `role "${TEST_CONNECTION_USERNAME}" does not exist`)
) {
return;
}
@@ -343,7 +344,10 @@ export const sqlResourceFactory: TPamResourceFactory<
} catch (error) {
// TODO: extract these logic into each SQL connection
if (error instanceof BadRequestError) {
- if (error.message === `password authentication failed for user "${credentials.username}"`) {
+ if (
+ error.message === `password authentication failed for user "${credentials.username}"` ||
+ error.message === `role "${credentials.username}" does not exist`
+ ) {
throw new BadRequestError({
message: "Account credentials invalid: Username or password incorrect"
});
@@ -385,7 +389,10 @@ export const sqlResourceFactory: TPamResourceFactory<
);
} catch (error) {
if (error instanceof BadRequestError) {
- if (error.message === `password authentication failed for user "${rotationAccountCredentials.username}"`) {
+ if (
+ error.message === `password authentication failed for user "${rotationAccountCredentials.username}"` ||
+ error.message === `role "${rotationAccountCredentials.username}" does not exist`
+ ) {
throw new BadRequestError({
message: "Management credentials invalid: Username or password incorrect"
});
diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts
index 1745e08fe0..85fddab620 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -626,6 +626,25 @@ export const samlConfigServiceFactory = ({
newUser = userWithSameUsername;
}
+ // Prevent cross-org account takeover: if an existing user was found by email,
+ // verify they are already a member of this org before binding the SAML identity.
+ if (newUser) {
+ const [existingMembership] = await orgDAL.findMembership(
+ {
+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
+ },
+ { tx }
+ );
+ if (!existingMembership) {
+ throw new ForbiddenRequestError({
+ message:
+ "User is not a member of this organization. Please contact your organization admin to receive an invite."
+ });
+ }
+ }
+
if (!newUser) {
const uniqueUsername = await normalizeUsername(`${firstName ?? ""}-${lastName ?? ""}`, userDAL);
newUser = await userDAL.create(
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
index 29e9004892..bc40ea8db5 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
@@ -1190,7 +1190,7 @@ export const secretApprovalRequestServiceFactory = ({
events
});
- if (isSoftEnforcement) {
+ if (isSoftEnforcement && !hasMinApproval) {
const cfg = getConfig();
const env = await projectEnvDAL.findOne({ slug: environment, projectId });
const requestedByUser = await userDAL.findOne({ id: actorId });
@@ -1630,6 +1630,7 @@ export const secretApprovalRequestServiceFactory = ({
const cfg = getConfig();
const approvalUrl = `${cfg.SITE_URL}${approvalPath}?requestId=${secretApprovalRequest.id}`;
+ const project = await projectDAL.findById(projectId);
await triggerWorkflowIntegrationNotification({
input: {
projectId,
@@ -1640,6 +1641,7 @@ export const secretApprovalRequestServiceFactory = ({
environment: env.name,
secretPath,
projectId,
+ projectName: project.name,
requestId: secretApprovalRequest.id,
secretKeys: [...new Set(Object.values(data).flatMap((arr) => arr?.map((item) => item.secretName) ?? []))],
approvalUrl
@@ -2070,6 +2072,7 @@ export const secretApprovalRequestServiceFactory = ({
environment: env.name,
secretPath,
projectId,
+ projectName: project.name,
requestId: secretApprovalRequest.id,
secretKeys: [...new Set(Object.values(data).flatMap((arr) => arr?.map((item) => item.secretKey) ?? []))],
approvalUrl
diff --git a/backend/src/lib/validator/validate-string.test.ts b/backend/src/lib/validator/validate-string.test.ts
index 73e1728966..778fcbdc32 100644
--- a/backend/src/lib/validator/validate-string.test.ts
+++ b/backend/src/lib/validator/validate-string.test.ts
@@ -20,4 +20,37 @@ describe("validate-string", () => {
expect(characterValidator([CharacterType.AlphaNumeric, CharacterType.Colon])("Hello:World")).toBeTruthy();
expect(characterValidator([CharacterType.AlphaNumeric, CharacterType.Underscore])("Hello World")).toBeFalsy();
});
+
+ test("Check unicode letters and digits", () => {
+ const validator = characterValidator([CharacterType.UnicodeLettersAndDigits]);
+ // Unicode letters
+ expect(validator("hello")).toBeTruthy();
+ expect(validator("你好世界")).toBeTruthy();
+ expect(validator("Компания")).toBeTruthy();
+ expect(validator("テスト")).toBeTruthy();
+ expect(validator("شركة")).toBeTruthy();
+ expect(validator("café")).toBeTruthy();
+ expect(validator("München")).toBeTruthy();
+ // Digits
+ expect(validator("abc123")).toBeTruthy();
+ // Should reject special characters
+ expect(validator("hello world")).toBeFalsy();
+ expect(validator("test<script>")).toBeFalsy();
+ expect(validator("test()")).toBeFalsy();
+ });
+
+ test("Check unicode with additional character types", () => {
+ const validator = characterValidator([
+ CharacterType.UnicodeLettersAndDigits,
+ CharacterType.Spaces,
+ CharacterType.Period,
+ CharacterType.Hyphen
+ ]);
+ expect(validator("My Company 公司")).toBeTruthy();
+ expect(validator("Москва-Сити")).toBeTruthy();
+ expect(validator("example.com")).toBeTruthy();
+ expect(validator("日本語 テスト")).toBeTruthy();
+ // Should still reject dangerous characters
+ expect(validator("test<script>alert(1)</script>")).toBeFalsy();
+ });
});
diff --git a/backend/src/lib/validator/validate-string.ts b/backend/src/lib/validator/validate-string.ts
index 4e89d313fb..d88c2207a0 100644
--- a/backend/src/lib/validator/validate-string.ts
+++ b/backend/src/lib/validator/validate-string.ts
@@ -40,7 +40,8 @@ export enum CharacterType {
Comma = "comma", // ,
Semicolon = "semicolon", // ;
Exclamation = "exclamation", // !
- Fullstop = "fullStop" // .
+ Fullstop = "fullStop", // .
+ UnicodeLettersAndDigits = "unicodeLettersAndDigits" // Unicode letters (\p{L}) and digits (\p{N})
}
/**
@@ -86,7 +87,8 @@ export const characterValidator = (allowedCharacters: CharacterType[]) => {
[CharacterType.Comma]: ",",
[CharacterType.Semicolon]: ";",
[CharacterType.Exclamation]: "!",
- [CharacterType.Fullstop]: "."
+ [CharacterType.Fullstop]: ".",
+ [CharacterType.UnicodeLettersAndDigits]: "\\p{L}\\p{N}"
};
// Combine patterns from allowed characters
diff --git a/backend/src/lib/workflow-integrations/types.ts b/backend/src/lib/workflow-integrations/types.ts
index 6d81c9174a..7b68687a41 100644
--- a/backend/src/lib/workflow-integrations/types.ts
+++ b/backend/src/lib/workflow-integrations/types.ts
@@ -20,6 +20,7 @@ export type TNotification =
secretPath: string;
requestId: string;
projectId: string;
+ projectName: string;
secretKeys: string[];
approvalUrl: string;
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 635b36d091..ce34aa72a4 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -420,6 +420,8 @@ import { secretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-
import { secretV2BridgeServiceFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-service";
import { secretVersionV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
import { secretVersionV2TagBridgeDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
+import { secretValidationRuleDALFactory } from "@app/services/secret-validation-rule/secret-validation-rule-dal";
+import { secretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";
import { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";
import { serviceTokenServiceFactory } from "@app/services/service-token/service-token-service";
import { signerDALFactory, signerServiceFactory, signingOperationDALFactory } from "@app/services/signer";
@@ -513,6 +515,7 @@ export const registerRoutes = async (
const secretDAL = secretDALFactory(db);
const secretTagDAL = secretTagDALFactory(db);
+ const secretValidationRuleDAL = secretValidationRuleDALFactory(db);
const folderDAL = secretFolderDALFactory(db);
const folderVersionDAL = secretFolderVersionDALFactory(db);
const secretImportDAL = secretImportDALFactory(db);
@@ -1576,6 +1579,14 @@ export const registerRoutes = async (
});
const secretTagService = secretTagServiceFactory({ secretTagDAL, permissionService });
+ const secretValidationRuleService = secretValidationRuleServiceFactory({
+ secretValidationRuleDAL,
+ projectEnvDAL,
+ permissionService,
+ kmsService,
+ folderDAL,
+ secretDAL: secretV2BridgeDAL
+ });
const folderService = secretFolderServiceFactory({
permissionService,
folderDAL,
@@ -1627,7 +1638,8 @@ export const registerRoutes = async (
snapshotService,
resourceMetadataDAL,
reminderService,
- keyStore
+ keyStore,
+ secretValidationRuleService
});
const secretApprovalRequestService = secretApprovalRequestServiceFactory({
@@ -2999,6 +3011,7 @@ export const registerRoutes = async (
secret: secretService,
secretReplication: secretReplicationService,
secretTag: secretTagService,
+ secretValidationRule: secretValidationRuleService,
rateLimit: rateLimitService,
folder: folderService,
secretImport: secretImportService,
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 70775e57c1..c00256cc40 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -74,6 +74,7 @@ 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 { registerSignerRouter } from "./signer-router";
import { registerSlackRouter } from "./slack-router";
import { registerSsoRouter } from "./sso-router";
@@ -155,6 +156,7 @@ 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);
},
diff --git a/backend/src/server/routes/v1/secret-validation-rule-router.ts b/backend/src/server/routes/v1/secret-validation-rule-router.ts
new file mode 100644
index 0000000000..113cb6278a
--- /dev/null
+++ b/backend/src/server/routes/v1/secret-validation-rule-router.ts
@@ -0,0 +1,203 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import {
+ SecretValidationRuleInputSchema,
+ SecretValidationRuleResponseSchema,
+ staticSecretsInputsSchema
+} from "@app/services/secret-validation-rule/secret-validation-rule-schemas";
+import { SecretValidationRuleType } from "@app/services/secret-validation-rule/secret-validation-rule-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: false,
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ rules: SecretValidationRuleResponseSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ 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: false,
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ body: z.object({
+ name: z.string().trim().min(1).max(100),
+ description: z.string().trim().max(500).nullable().optional(),
+ environmentSlug: z.string().trim().min(1).optional(),
+ secretPath: z.string().trim().min(1),
+ rule: SecretValidationRuleInputSchema
+ }),
+ 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,
+ type: req.body.rule.type,
+ inputs: req.body.rule.inputs
+ });
+
+ 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
+ }
+ }
+ });
+
+ return { rule };
+ }
+ });
+
+ // Update a rule
+ server.route({
+ method: "PATCH",
+ url: "/:projectId/secret-validation-rules/:ruleId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ params: z.object({
+ projectId: z.string().trim(),
+ ruleId: z.string().uuid()
+ }),
+ body: z.object({
+ name: z.string().trim().min(1).max(100).optional(),
+ description: z.string().trim().max(500).nullable().optional(),
+ environmentSlug: z.string().trim().min(1).nullable().optional(),
+ secretPath: z.string().trim().min(1).optional(),
+ type: z.nativeEnum(SecretValidationRuleType).optional(),
+ inputs: staticSecretsInputsSchema.optional(),
+ isActive: z.boolean().optional()
+ }),
+ 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.type,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ isActive: req.body.isActive
+ }
+ }
+ });
+
+ return { rule };
+ }
+ });
+
+ // Delete a rule
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/secret-validation-rules/:ruleId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ params: z.object({
+ projectId: z.string().trim(),
+ ruleId: z.string().uuid()
+ }),
+ 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
+ }
+ }
+ });
+
+ return { rule };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index bd5c92080d..edd2eb9503 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -615,7 +615,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
{ skipDedup: true }
);
}
-
if ([AuthMethod.GOOGLE, AuthMethod.GITHUB, AuthMethod.GITLAB].includes(data.decodedProviderToken.authMethod)) {
void res.setCookie("jid", data.token.refresh, {
httpOnly: true,
@@ -630,6 +629,8 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
return {
encryptionVersion: data.user.encryptionVersion,
token: data.token.access,
+ isMfaEnabled: data.isMfaEnabled,
+ mfaMethod: data?.mfaMethod,
publicKey: data.user.publicKey,
encryptedPrivateKey: data.user.encryptedPrivateKey,
iv: data.user.iv,
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index ec42c01f37..1ff0e5cdf6 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -1310,6 +1310,7 @@ export const authLoginServiceFactory = ({
* 2. To avoid attaching the access token to the URL, which could be logged. The provider token has a very short lifespan, reducing security risks.
*/
const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => {
+ const appCfg = getConfig();
const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
const { authMethod, userName } = decodedProviderToken;
@@ -1329,6 +1330,48 @@ export const authLoginServiceFactory = ({
if (!userEnc) throw new BadRequestError({ message: "User encryption not found" });
+ // Check MFA before issuing tokens — mirrors the logic in selectOrganization
+ const user = await userDAL.findById(userEnc.userId);
+ const org = organizationId ? await orgDAL.findById(organizationId) : null;
+ // for now check mfa in this state when your token is org scoped. If not we will do it in select org step
+ const shouldCheckMfa = org?.enforceMfa || user?.isMfaEnabled;
+
+ if (shouldCheckMfa && organizationId) {
+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
+
+ const orgMfaMethod = org?.enforceMfa ? (org.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
+ const userMfaMethod = user.isMfaEnabled ? (user.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
+ const mfaMethod = orgMfaMethod ?? userMfaMethod;
+
+ const mfaToken = crypto.jwt().sign(
+ {
+ authMethod,
+ authTokenType: AuthTokenType.MFA_TOKEN,
+ userId: userEnc.userId,
+ organizationId
+ },
+ appCfg.AUTH_SECRET,
+ {
+ expiresIn: appCfg.JWT_MFA_LIFETIME
+ }
+ );
+
+ if (mfaMethod === MfaMethod.EMAIL && userEnc.email) {
+ await sendUserMfaCode({
+ userId: userEnc.userId,
+ email: userEnc.email
+ });
+ }
+
+ return {
+ token: { access: mfaToken, refresh: "" },
+ isMfaEnabled: true,
+ mfaMethod,
+ user: userEnc,
+ decodedProviderToken
+ } as const;
+ }
+
const token = await generateUserTokens({
user: { ...userEnc, id: userEnc.userId },
ip,
diff --git a/backend/src/services/certificate-template/certificate-template-validators.ts b/backend/src/services/certificate-template/certificate-template-validators.ts
index e33ddb0478..2f1ed03202 100644
--- a/backend/src/services/certificate-template/certificate-template-validators.ts
+++ b/backend/src/services/certificate-template/certificate-template-validators.ts
@@ -13,7 +13,7 @@ export const createTemplateFieldValidator = (options?: {
minLength = 1,
maxLength = 100,
allowedCharacters = [
- CharacterType.AlphaNumeric,
+ CharacterType.UnicodeLettersAndDigits,
CharacterType.Spaces, // (space)
CharacterType.Asterisk, // *
CharacterType.At, // @
diff --git a/backend/src/services/microsoft-teams/microsoft-teams-fns.ts b/backend/src/services/microsoft-teams/microsoft-teams-fns.ts
index 0fcfbbe01c..b9e92c72b3 100644
--- a/backend/src/services/microsoft-teams/microsoft-teams-fns.ts
+++ b/backend/src/services/microsoft-teams/microsoft-teams-fns.ts
@@ -383,6 +383,10 @@ export const buildTeamsPayload = (orgId: string, notification: TNotification) =>
{
type: "FactSet",
facts: [
+ {
+ title: "Project",
+ value: payload.projectName
+ },
{
title: "Environment",
value: payload.environment
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index 2fd2028254..8c6900b911 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -1,4 +1,4 @@
-import * as handlebars from "handlebars";
+import handlebars from "handlebars";
import { z, ZodSchema } from "zod";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index 2bc365cfa3..6e25be09c9 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -61,6 +61,7 @@ import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
import { fnSecretsV2FromImports } from "../secret-import/secret-import-fns";
import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
+import { TSecretValidationRuleServiceFactory } from "../secret-validation-rule/secret-validation-rule-service";
import { expandSecretReferencesFactory, getAllSecretReferences } from "./secret-reference-fns";
import {
MAX_SECRET_CACHE_BYTES,
@@ -135,6 +136,7 @@ type TSecretV2BridgeServiceFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setExpiry" | "setItemWithExpiry" | "deleteItem" | "pgGetIntItem">;
reminderService: Pick<TReminderServiceFactory, "createReminder" | "getReminder">;
+ secretValidationRuleService: Pick<TSecretValidationRuleServiceFactory, "validateSecrets">;
};
export type TSecretV2BridgeServiceFactory = ReturnType<typeof secretV2BridgeServiceFactory>;
@@ -161,7 +163,8 @@ export const secretV2BridgeServiceFactory = ({
kmsService,
resourceMetadataDAL,
keyStore,
- reminderService
+ reminderService,
+ secretValidationRuleService
}: TSecretV2BridgeServiceFactoryDep) => {
const $validateSecretReferences = async (
projectId: string,
@@ -346,6 +349,14 @@ export const secretV2BridgeServiceFactory = ({
project.secretDetectionIgnoreValues || []
);
+ await secretValidationRuleService.validateSecrets({
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: [{ key: inputSecret.secretName, value: inputSecret.secretValue }]
+ });
+
const { nestedReferences, localReferences } = getAllSecretReferences(inputSecret.secretValue);
const allSecretReferences = nestedReferences.concat(
localReferences.map((el) => ({ secretKey: el, secretPath, environment }))
@@ -597,6 +608,18 @@ export const secretV2BridgeServiceFactory = ({
);
}
+ // Validate against secret validation rules (key rename and/or value change)
+ const finalKey = inputSecret.newSecretName || secretName;
+ if (secretValue || inputSecret.newSecretName) {
+ await secretValidationRuleService.validateSecrets({
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: [{ key: finalKey, value: secretValue }]
+ });
+ }
+
if (secretValue) {
const { nestedReferences, localReferences } = getAllSecretReferences(secretValue);
const allSecretReferences = nestedReferences.concat(
@@ -1862,6 +1885,14 @@ export const secretV2BridgeServiceFactory = ({
project.secretDetectionIgnoreValues || []
);
+ await secretValidationRuleService.validateSecrets({
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue }))
+ });
+
// get all tags
const sanitizedTagIds = [...new Set(deduplicatedSecrets.flatMap(({ tagIds = [] }) => tagIds))];
const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : [];
@@ -2223,6 +2254,26 @@ export const secretV2BridgeServiceFactory = ({
project.secretDetectionIgnoreValues || []
);
+ // Validate against secret validation rules for all secrets being updated or created (upsert)
+ const secretsToValidate = [
+ ...secretsToUpdate
+ .filter((el) => el.secretValue || el.newSecretName)
+ .map((el) => ({ key: el.newSecretName || el.secretKey, value: el.secretValue })),
+ ...(updateMode === SecretUpdateMode.Upsert
+ ? secretsToCreate.map((el) => ({ key: el.secretKey, value: el.secretValue }))
+ : [])
+ ];
+ if (secretsToValidate.length) {
+ // eslint-disable-next-line no-await-in-loop
+ await secretValidationRuleService.validateSecrets({
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: secretsToValidate
+ });
+ }
+
const secretKeyUpdates: {
secretId: string;
oldSecretKey: string;
diff --git a/backend/src/services/secret-validation-rule/index.ts b/backend/src/services/secret-validation-rule/index.ts
new file mode 100644
index 0000000000..6dd3af636b
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/index.ts
@@ -0,0 +1,4 @@
+export type { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";
+export { secretValidationRuleDALFactory } from "./secret-validation-rule-dal";
+export type { TSecretValidationRuleServiceFactory } from "./secret-validation-rule-service";
+export { secretValidationRuleServiceFactory } from "./secret-validation-rule-service";
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.ts
new file mode 100644
index 0000000000..53e2282a03
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-dal.ts
@@ -0,0 +1,11 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TSecretValidationRuleDALFactory = ReturnType<typeof secretValidationRuleDALFactory>;
+
+export const secretValidationRuleDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.SecretValidationRule);
+
+ return orm;
+};
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.ts
new file mode 100644
index 0000000000..303a720f42
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts
@@ -0,0 +1,347 @@
+import picomatch from "picomatch";
+import RE2 from "re2";
+
+import { BadRequestError } from "@app/lib/errors";
+
+import {
+ ConstraintTarget,
+ ConstraintType,
+ SecretValidationRuleType,
+ TConstraint,
+ TSecretValidationRuleInputs,
+ TStaticSecretsInputs
+} from "./secret-validation-rule-types";
+
+type TExistingRule = {
+ id: string;
+ name: string;
+ envId?: string | null;
+ secretPath: string;
+ type: string;
+ inputs?: unknown;
+};
+
+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;
+ }
+
+ // 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;
+ }
+ }
+
+ return false;
+};
+
+const doEnvironmentsOverlap = (envIdA: string | null | undefined, envIdB: string | null | undefined): boolean => {
+ if (!envIdA || !envIdB) return true;
+ return envIdA === envIdB;
+};
+
+/**
+ * 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);
+ }
+ }
+ }
+
+ return overlapping;
+};
+
+type TOverlapChecker<TInputs = TSecretValidationRuleInputs> = (
+ incoming: TInputs,
+ existing: TInputs
+) => ConstraintType[];
+
+const overlapCheckersByType: Record<SecretValidationRuleType, TOverlapChecker> = {
+ [SecretValidationRuleType.StaticSecrets]: $checkStaticSecretsConstraintOverlap as TOverlapChecker
+};
+
+export const checkForOverlappingRules = ({
+ ruleType,
+ envId,
+ secretPath,
+ inputs,
+ existingRules,
+ excludeRuleId
+}: {
+ ruleType: SecretValidationRuleType;
+ envId: string | null;
+ secretPath: string;
+ inputs: TSecretValidationRuleInputs;
+ existingRules: TExistingRule[];
+ excludeRuleId?: string;
+}): void => {
+ const checker = overlapCheckersByType[ruleType as SecretValidationRuleType];
+ if (!checker) {
+ return;
+ }
+
+ 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;
+};
+
+type TValidationRule = {
+ name: string;
+ envId?: string | null;
+ secretPath: string;
+ type: string;
+ inputs: unknown;
+};
+
+type TValidationViolation = {
+ secretKey: string;
+ ruleName: string;
+ constraintType: ConstraintType;
+ message: string;
+};
+
+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"
+};
+
+const TARGET_LABELS: Record<ConstraintTarget, string> = {
+ [ConstraintTarget.SecretKey]: "key",
+ [ConstraintTarget.SecretValue]: "value"
+};
+
+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;
+ }
+ default:
+ return null;
+ }
+};
+
+/**
+ * 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
+ });
+ }
+ }
+ }
+ }
+
+ 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[];
+
+const ruleEnforcersByType: Record<SecretValidationRuleType, TRuleEnforcer> = {
+ [SecretValidationRuleType.StaticSecrets]: enforceStaticSecretsRules
+};
+
+/**
+ * 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 enforceSecretValidationRules = ({
+ projectRules,
+ envId,
+ secretPath,
+ secrets
+}: {
+ projectRules: TValidationRule[];
+ envId: string;
+ secretPath: string;
+ secrets: TSecretToValidate[];
+}): void => {
+ if (!projectRules.length || !secrets.length) return;
+
+ 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;
+ }
+ 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")}`
+ });
+ }
+};
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.ts
new file mode 100644
index 0000000000..b69d9a843b
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts
@@ -0,0 +1,43 @@
+import { z } from "zod";
+
+import { SecretValidationRulesSchema } from "@app/db/schemas";
+
+import {
+ ConstraintTarget,
+ ConstraintType,
+ SecretValidationRuleType,
+ TSecretValidationRuleInputs
+} from "./secret-validation-rule-types";
+
+export const constraintSchema = z.object({
+ type: z.nativeEnum(ConstraintType),
+ appliesTo: z.nativeEnum(ConstraintTarget),
+ value: z.string().min(1)
+});
+
+export const staticSecretsInputsSchema = z.object({
+ constraints: z.array(constraintSchema).min(1)
+});
+
+// Discriminated union for create/update request bodies
+export const SecretValidationRuleInputSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal(SecretValidationRuleType.StaticSecrets), inputs: staticSecretsInputsSchema })
+]);
+
+// Map of type → inputs schema, used for runtime parsing
+const inputsSchemaMap: Record<SecretValidationRuleType, z.ZodSchema<TSecretValidationRuleInputs>> = {
+ [SecretValidationRuleType.StaticSecrets]: staticSecretsInputsSchema
+};
+
+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 SecretValidationRuleResponseSchema = SecretValidationRulesSchema.omit({
+ type: true,
+ encryptedInputs: true
+}).and(SecretValidationRuleInputSchema);
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.ts
new file mode 100644
index 0000000000..5d8e56cf80
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
@@ -0,0 +1,384 @@
+import { ForbiddenError } from "@casl/ability";
+
+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 { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
+
+import { TKmsServiceFactory } from "../kms/kms-service";
+import { KmsDataKey } from "../kms/kms-types";
+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 { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";
+import { checkForOverlappingRules, enforceSecretValidationRules } from "./secret-validation-rule-fns";
+import { parseSecretValidationRuleInputs } from "./secret-validation-rule-schemas";
+import {
+ SecretValidationRuleType,
+ TCreateSecretValidationRuleDTO,
+ TDeleteSecretValidationRuleDTO,
+ TListSecretValidationRulesDTO,
+ TUpdateSecretValidationRuleDTO
+} from "./secret-validation-rule-types";
+
+type TSecretValidationRuleServiceFactoryDep = {
+ secretValidationRuleDAL: TSecretValidationRuleDALFactory;
+ projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
+ folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
+ secretDAL: TSecretV2BridgeDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: TKmsServiceFactory;
+};
+
+export type TSecretValidationRuleServiceFactory = ReturnType<typeof secretValidationRuleServiceFactory>;
+
+export const secretValidationRuleServiceFactory = ({
+ secretValidationRuleDAL,
+ projectEnvDAL,
+ folderDAL,
+ secretDAL,
+ permissionService,
+ kmsService
+}: TSecretValidationRuleServiceFactoryDep) => {
+ const listByProjectId = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId
+ }: TListSecretValidationRulesDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);
+
+ const rules = await secretValidationRuleDAL.find({ projectId });
+
+ const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const finalRules = (rules || []).map((rule) => ({
+ ...rule,
+ type: rule.type as SecretValidationRuleType,
+ inputs: parseSecretValidationRuleInputs(
+ rule.type,
+ JSON.parse(ruleInputsDecryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown
+ )
+ }));
+
+ return finalRules;
+ };
+
+ const createRule = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId,
+ name,
+ description,
+ environmentSlug,
+ secretPath,
+ type,
+ inputs
+ }: TCreateSecretValidationRuleDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, 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 parsedInputs = parseSecretValidationRuleInputs(type, inputs);
+
+ const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const existingRules = await secretValidationRuleDAL.find({ projectId });
+ checkForOverlappingRules({
+ ruleType: 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
+ )
+ }))
+ });
+
+ const { encryptor: ruleInputsEncryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const { cipherTextBlob: encryptedRuleInputs } = ruleInputsEncryptor({
+ plainText: Buffer.from(JSON.stringify(parsedInputs))
+ });
+
+ const rule = await secretValidationRuleDAL.create({
+ name,
+ description,
+ projectId,
+ envId,
+ secretPath,
+ type,
+ encryptedInputs: encryptedRuleInputs
+ });
+
+ return { ...rule, type: rule.type as SecretValidationRuleType, inputs: parsedInputs };
+ };
+
+ const updateRule = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId,
+ ruleId,
+ environmentSlug,
+ inputs,
+ ...dto
+ }: TUpdateSecretValidationRuleDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+
+ const existingRule = await secretValidationRuleDAL.findOne({ id: ruleId, projectId });
+ if (!existingRule) {
+ throw new NotFoundError({ message: `Secret validation rule with ID ${ruleId} not found` });
+ }
+
+ 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: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const decryptedExistingRuleInputs = ruleInputsDecryptor({
+ cipherTextBlob: existingRule.encryptedInputs
+ });
+
+ const ruleType = dto.type ?? existingRule.type;
+ const ruleInputs = inputs ?? (JSON.parse(decryptedExistingRuleInputs.toString()) as unknown);
+ const parsedInputs = parseSecretValidationRuleInputs(ruleType, ruleInputs);
+
+ const finalEnvId = envId !== undefined ? envId : (existingRule.envId as string | null);
+ const finalSecretPath = dto.secretPath ?? existingRule.secretPath;
+
+ 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
+ });
+
+ let updatedRuleInputs: Buffer | undefined;
+
+ if (inputs) {
+ const { encryptor: ruleInputsEncryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const { cipherTextBlob: encryptedRuleInputs } = ruleInputsEncryptor({
+ plainText: Buffer.from(JSON.stringify(parsedInputs))
+ });
+ updatedRuleInputs = encryptedRuleInputs;
+ }
+
+ const updatedRule = await secretValidationRuleDAL.updateById(ruleId, {
+ ...(envId !== undefined && { envId }),
+ ...(Boolean(updatedRuleInputs) && { encryptedInputs: updatedRuleInputs }),
+ ...dto
+ });
+
+ return {
+ ...updatedRule,
+ type: updatedRule.type as SecretValidationRuleType,
+ inputs: parseSecretValidationRuleInputs(
+ updatedRule.type,
+ JSON.parse(ruleInputsDecryptor({ cipherTextBlob: updatedRule.encryptedInputs }).toString()) as unknown
+ )
+ };
+ };
+
+ const deleteRule = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId,
+ ruleId
+ }: TDeleteSecretValidationRuleDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.Settings);
+
+ const existingRule = await secretValidationRuleDAL.findOne({ id: ruleId, projectId });
+ if (!existingRule) {
+ throw new NotFoundError({ message: `Secret validation rule with ID ${ruleId} not found` });
+ }
+
+ const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ await secretValidationRuleDAL.deleteById(ruleId);
+ return {
+ ...existingRule,
+ type: existingRule.type as SecretValidationRuleType,
+ inputs: parseSecretValidationRuleInputs(
+ existingRule.type,
+ JSON.parse(ruleInputsDecryptor({ cipherTextBlob: existingRule.encryptedInputs }).toString()) as unknown
+ )
+ };
+ };
+
+ /**
+ * 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.
+ */
+ const validateSecrets = async ({
+ projectId,
+ environment,
+ envId,
+ secretPath,
+ secrets
+ }: {
+ projectId: string;
+ environment: string;
+ envId: string;
+ secretPath: string;
+ secrets: { key: string; value?: string }[];
+ }) => {
+ if (!secrets.length) return;
+
+ const rules = await secretValidationRuleDAL.find({ projectId, isActive: true });
+ if (!rules.length) return;
+
+ 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
+ });
+
+ let resolvedSecrets = secrets;
+
+ resolvedSecrets = await Promise.all(
+ secrets.map(async (s) => ({
+ key: s.key,
+ value: await expandSecretReferences({
+ value: s.value,
+ secretPath,
+ environment,
+ secretKey: s.key
+ })
+ }))
+ );
+
+ const { decryptor: ruleInputsDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ enforceSecretValidationRules({
+ projectRules: rules.map((r) => ({
+ ...r,
+ inputs: parseSecretValidationRuleInputs(
+ r.type,
+ JSON.parse(ruleInputsDecryptor({ cipherTextBlob: r.encryptedInputs }).toString()) as unknown
+ )
+ })),
+ envId,
+ secretPath,
+ secrets: resolvedSecrets
+ });
+ };
+
+ return {
+ listByProjectId,
+ createRule,
+ updateRule,
+ deleteRule,
+ validateSecrets
+ };
+};
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.ts
new file mode 100644
index 0000000000..b71f2df8af
--- /dev/null
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts
@@ -0,0 +1,56 @@
+import { TProjectPermission } from "@app/lib/types";
+
+export enum SecretValidationRuleType {
+ StaticSecrets = "static-secrets"
+}
+
+export enum ConstraintType {
+ MinLength = "min-length",
+ MaxLength = "max-length",
+ RegexPattern = "regex-pattern",
+ RequiredPrefix = "required-prefix",
+ RequiredSuffix = "required-suffix"
+}
+
+export enum ConstraintTarget {
+ SecretKey = "key",
+ SecretValue = "value"
+}
+
+export type TConstraint = {
+ type: ConstraintType;
+ appliesTo: ConstraintTarget;
+ value: string;
+};
+
+export type TStaticSecretsInputs = {
+ constraints: TConstraint[];
+};
+
+export type TSecretValidationRuleInputs = TStaticSecretsInputs;
+
+export type TCreateSecretValidationRuleDTO = {
+ name: string;
+ description?: string | null;
+ environmentSlug?: string;
+ secretPath: string;
+ type: SecretValidationRuleType;
+ inputs: TSecretValidationRuleInputs;
+} & TProjectPermission;
+
+export type TUpdateSecretValidationRuleDTO = {
+ ruleId: string;
+ name?: string;
+ description?: string | null;
+ environmentSlug?: string | null;
+ secretPath?: string;
+ type?: SecretValidationRuleType;
+ inputs?: TSecretValidationRuleInputs;
+ isActive?: boolean;
+} & TProjectPermission;
+
+export type TDeleteSecretValidationRuleDTO = {
+ ruleId: string;
+} & TProjectPermission;
+
+export type TListSecretValidationRulesDTO = TProjectPermission;
diff --git a/backend/src/services/slack/slack-fns.ts b/backend/src/services/slack/slack-fns.ts
index aaeb28916f..eae9f36976 100644
--- a/backend/src/services/slack/slack-fns.ts
+++ b/backend/src/services/slack/slack-fns.ts
@@ -49,6 +49,7 @@ const buildSlackPayload = (notification: TNotification) => {
case TriggerFeature.SECRET_APPROVAL: {
const { payload } = notification;
const messageBody = `A secret approval request has been opened by ${payload.userEmail}.
+*Project*: ${payload.projectName}
*Environment*: ${payload.environment}
*Secret path*: ${payload.secretPath || "/"}
*Secret Key${payload.secretKeys.length > 1 ? "s" : ""}*: ${payload.secretKeys.join(", ")}`;
diff --git a/docs/docs.json b/docs/docs.json
index 557e96ccb0..f202e0bed6 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -510,7 +510,8 @@
"documentation/platform/dynamic-secrets/vertica"
]
},
- "documentation/platform/webhooks"
+ "documentation/platform/webhooks",
+ "documentation/platform/secret-validation-rules"
]
},
{
@@ -839,7 +840,8 @@
"documentation/platform/kms/overview",
"documentation/platform/kms/hsm-integration",
"documentation/platform/kms/kubernetes-encryption",
- "documentation/platform/kms/kmip"
+ "documentation/platform/kms/kmip",
+ "documentation/platform/kms/sigstore-cosign"
]
}
]
diff --git a/docs/documentation/guides/governance-models.mdx b/docs/documentation/guides/governance-models.mdx
index da0da973c7..aba0ea4228 100644
--- a/docs/documentation/guides/governance-models.mdx
+++ b/docs/documentation/guides/governance-models.mdx
@@ -232,7 +232,7 @@ Who creates, rotates, and retires secrets—and how—depends on your governance
### Secret Referencing Within Projects
-[Secret referencing](/documentation/platform/secret-references) and [imports](/documentation/platform/secret-references) allow secrets to be shared across environments and folders within the same project. This helps reduce duplication when the same secret is needed in multiple environments.
+[Secret referencing](/documentation/platform/secret-reference) and [imports](/documentation/platform/secret-reference) allow secrets to be shared across environments and folders within the same project. This helps reduce duplication when the same secret is needed in multiple environments.
| Approach | Centralized | Self-Service |
|----------|-------------|--------------|
diff --git a/docs/documentation/platform/kms/sigstore-cosign.mdx b/docs/documentation/platform/kms/sigstore-cosign.mdx
new file mode 100644
index 0000000000..b077926c29
--- /dev/null
+++ b/docs/documentation/platform/kms/sigstore-cosign.mdx
@@ -0,0 +1,71 @@
+---
+title: "Sigstore Cosign Integration"
+description: "Sign and verify container images and artifacts using Infisical KMS with Sigstore Cosign."
+---
+
+Infisical KMS integrates with [Sigstore Cosign](https://github.com/sigstore/cosign) through the [sigstore-kms-infisical](https://github.com/Infisical/sigstore-kms-infisical) plugin, enabling you to sign and verify container images and artifacts using keys managed in Infisical.
+
+### KMS Plugin Capabilities
+
+| Capability | Supported |
+| ---------- | --------- |
+| DefaultAlgorithm | RSA_4096 |
+| SupportedAlgorithms | RSA_4096, ECC_NIST_P256 |
+| CreateKey | ✅ |
+| PublicKey | ✅ |
+| SignMessage | ✅ |
+| VerifyMessage | ✅ |
+
+## Setup
+
+<Steps>
+ <Step title="Install the Plugin">
+ For the Sigstore library to invoke the plugin, the binary must be in your system's `PATH`.
+
+ ```bash
+ git clone https://github.com/Infisical/sigstore-kms-infisical.git
+ cd sigstore-kms-infisical
+ go build -o sigstore-kms-infisical
+ cp sigstore-kms-infisical /usr/local/bin
+ ```
+ </Step>
+
+ <Step title="Configure Environment Variables">
+ The plugin uses environment variables for authentication. Currently only [Machine Identity Universal Auth](/documentation/platform/identities/universal-auth) is supported.
+
+ Set the following environment variables:
+
+ ```bash
+ export INFISICAL_SITE_URL="https://app.infisical.com"
+ export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID="<machine-identity-client-id>"
+ export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET="<machine-identity-client-secret>"
+ export INFISICAL_PROJECT_ID="<infisical-kms-project-id>"
+ ```
+
+ <Note>
+ For self-hosted Infisical instances, set `INFISICAL_SITE_URL` to your instance's URL.
+ </Note>
+ </Step>
+</Steps>
+
+## Usage
+
+### Signing a Container Image
+
+```bash
+cosign sign --key "infisical://{KMS_KEY_NAME}" --tlog-upload=false my-repo/image:v1
+```
+
+### Verifying a Container Image
+
+```bash
+cosign verify --key "infisical://{KMS_KEY_NAME}" --insecure-ignore-tlog=true my-repo/image:v1
+```
+
+### Creating a New Key Pair
+
+```bash
+cosign generate-key-pair --kms infisical://{NEW_KEY_NAME}
+```
+
+This creates an RSA 4096 KMS key with the specified name, which you can then use for signing and verification.
diff --git a/docs/documentation/platform/secret-validation-rules.mdx b/docs/documentation/platform/secret-validation-rules.mdx
new file mode 100644
index 0000000000..d977528bad
--- /dev/null
+++ b/docs/documentation/platform/secret-validation-rules.mdx
@@ -0,0 +1,123 @@
+---
+title: "Secret Validation Rules"
+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 or updated. This helps teams enforce consistent naming conventions, prevent weak or malformed values, and maintain compliance standards across environments — all automatically at write time.
+
+For example, you can require that all secret keys in production follow `UPPER_SNAKE_CASE`, that values meet a minimum length, or that database connection strings always start with a specific prefix.
+
+![Secret Validation Rules overview](/images/platform/secret-validation-rules/overview.png)
+
+## How It Works
+
+When a 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. When a secret is rejected, the actor will see an error describing which rule and constraint was violated.
+
+<Note>
+ Validation rules are enforced on mutations only (such as create or update events). Existing secrets that were created before a rule was added are not retroactively validated.
+</Note>
+
+### Constraint Types
+
+Each rule contains one or more constraints. A constraint specifies what to check (the secret key or value) and how to check it.
+
+| Constraint | Description | Example |
+|---|---|---|
+| **Min Length** | The target must be at least N characters long | Value must be at least 8 characters |
+| **Max Length** | The target must be at most N characters long | Key must be at most 64 characters |
+| **Regex Pattern** | The target must match a regular expression | Key must match `^[A-Z][A-Z0-9_]*$` |
+| **Required Prefix** | The target must start with specific text | Value must start with `https://` |
+| **Required Suffix** | The target must end with specific text | Key must end with `_SECRET` |
+
+Each constraint can be applied to either the secret key or the secret value.
+
+### Scoping Rules
+
+Every rule is scoped to control where it applies:
+
+- **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`).
+
+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.
+
+## Creating a Rule
+
+<Steps>
+ <Step title="Navigate to Project Settings">
+ Go to **Project Settings** and select the **Secret Validation Rules** tab.
+
+ ![Navigate to Secret Validation Rules](/images/platform/secret-validation-rules/settings-tab.png)
+ </Step>
+
+ <Step title="Click Create Rule">
+ Click the **Create Rule** button to open the rule creation form.
+
+ ![Create Rule button](/images/platform/secret-validation-rules/create-button.png)
+ </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** — Currently supports **Static Secrets**.
+ - **Environment** — Choose a specific environment or "All Environments".
+ - **Folder Path** — The path scope, supporting glob patterns (e.g., `/**`).
+
+
+ **Constraints**
+
+ Click **Add Constraint** and choose from the available constraint types. For each constraint, select whether it applies to the secret **key** or **value**, then provide the constraint parameter (length, pattern, prefix, or suffix).
+ You can add multiple constraints to a single rule. All constraints must pass for a secret to be accepted.
+
+
+ ![Rule configuration form](/images/platform/secret-validation-rules/create-rule-form.png)
+ </Step>
+
+ <Step title="Save the rule">
+ Click **Create Rule** to save. The rule is immediately active and will be enforced on all subsequent secret writes within 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 (key or value), the second rule will be rejected.
+
+For example, you cannot 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.
+
+## Example Use Cases
+
+<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_]*$`
+
+ This ensures all secret keys follow the `UPPER_SNAKE_CASE` convention (e.g., `DATABASE_URL`, `API_KEY`), rejecting names like `mySecret` or `api-key`.
+ </Accordion>
+
+ <Accordion title="Require minimum value length">
+ Create a rule with a **Min Length** constraint on the **secret value**:
+
+ - Minimum: `8`
+
+ This prevents secrets with very short or empty-like values from being saved, helping catch accidental pastes or placeholder values.
+ </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://`
+
+ This ensures all secrets in the database folder contain valid PostgreSQL connection strings.
+ </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`
+
+ This helps distinguish production secrets from those in other environments.
+ </Accordion>
+</AccordionGroup>
diff --git a/docs/images/platform/secret-validation-rules/create-button.png b/docs/images/platform/secret-validation-rules/create-button.png
new file mode 100644
index 0000000000..04a7bae5b4
Binary files /dev/null and b/docs/images/platform/secret-validation-rules/create-button.png differ
diff --git a/docs/images/platform/secret-validation-rules/create-rule-button.png b/docs/images/platform/secret-validation-rules/create-rule-button.png
new file mode 100644
index 0000000000..cb29fa0e5f
Binary files /dev/null and b/docs/images/platform/secret-validation-rules/create-rule-button.png differ
diff --git a/docs/images/platform/secret-validation-rules/create-rule-form.png b/docs/images/platform/secret-validation-rules/create-rule-form.png
new file mode 100644
index 0000000000..e82e3d0f45
Binary files /dev/null and b/docs/images/platform/secret-validation-rules/create-rule-form.png differ
diff --git a/docs/images/platform/secret-validation-rules/overview.png b/docs/images/platform/secret-validation-rules/overview.png
new file mode 100644
index 0000000000..acdc29bbc0
Binary files /dev/null and b/docs/images/platform/secret-validation-rules/overview.png differ
diff --git a/docs/images/platform/secret-validation-rules/settings-tab.png b/docs/images/platform/secret-validation-rules/settings-tab.png
new file mode 100644
index 0000000000..e3fd2478aa
Binary files /dev/null and b/docs/images/platform/secret-validation-rules/settings-tab.png differ
diff --git a/frontend/src/components/notifications/Notifications.tsx b/frontend/src/components/notifications/Notifications.tsx
index 2727880382..121e840d69 100644
--- a/frontend/src/components/notifications/Notifications.tsx
+++ b/frontend/src/components/notifications/Notifications.tsx
@@ -23,7 +23,13 @@ export const NotificationContent = ({
return (
<div className="msg-container">
{title && <div className="text-md mb-1 font-medium">{title}</div>}
- <div className={title ? "text-sm text-neutral-400" : "text-md"}>{text}</div>
+ <div
+ className={
+ title ? "text-sm whitespace-pre-line text-neutral-400" : "text-md whitespace-pre-line"
+ }
+ >
+ {text}
+ </div>
{children && <div className="mt-2">{children}</div>}
{(callToAction || copyActions) && (
<div
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index e6eb3cdf97..768fcef6d4 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -358,7 +358,11 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.DELETE_DYNAMIC_SECRET_LEASE]: "Delete Dynamic Secret Lease",
[EventType.RENEW_DYNAMIC_SECRET_LEASE]: "Renew Dynamic Secret Lease",
[EventType.LIST_DYNAMIC_SECRET_LEASES]: "List Dynamic Secret Leases",
- [EventType.GET_DYNAMIC_SECRET_LEASE]: "Get Dynamic Secret Lease"
+ [EventType.GET_DYNAMIC_SECRET_LEASE]: "Get Dynamic Secret Lease",
+
+ [EventType.SECRET_VALIDATION_RULE_CREATE]: "Create Secret Validation Rule",
+ [EventType.SECRET_VALIDATION_RULE_UPDATE]: "Update Secret Validation Rule",
+ [EventType.SECRET_VALIDATION_RULE_DELETE]: "Delete Secret Validation Rule"
};
export const userAgentTypeToNameMap: { [K in UserAgentType]: string } = {
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index ce9b9e14eb..e5e3603435 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -355,5 +355,10 @@ export enum EventType {
DELETE_DYNAMIC_SECRET_LEASE = "delete-dynamic-secret-lease",
RENEW_DYNAMIC_SECRET_LEASE = "renew-dynamic-secret-lease",
LIST_DYNAMIC_SECRET_LEASES = "list-dynamic-secret-leases",
- GET_DYNAMIC_SECRET_LEASE = "get-dynamic-secret-lease"
+ GET_DYNAMIC_SECRET_LEASE = "get-dynamic-secret-lease",
+
+ // Secret Validation Rules
+ SECRET_VALIDATION_RULE_CREATE = "secret-validation-rule-create",
+ SECRET_VALIDATION_RULE_UPDATE = "secret-validation-rule-update",
+ SECRET_VALIDATION_RULE_DELETE = "secret-validation-rule-delete"
}
diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsx
index b4b002c610..9f88e71e4b 100644
--- a/frontend/src/hooks/api/auth/queries.tsx
+++ b/frontend/src/hooks/api/auth/queries.tsx
@@ -22,6 +22,7 @@ import {
LoginV3DTO,
LoginV3Res,
MfaMethod,
+ OauthTokenExchangeRes,
ResetPasswordDTO,
ResetPasswordV2DTO,
ResetUserPasswordV2DTO,
@@ -123,7 +124,10 @@ export const useLogin2 = () => {
};
export const oauthTokenExchange = async (details: TOauthTokenExchangeDTO) => {
- const { data } = await apiRequest.post<Login2Res>("/api/v1/sso/token-exchange", details);
+ const { data } = await apiRequest.post<OauthTokenExchangeRes>(
+ "/api/v1/sso/token-exchange",
+ details
+ );
return data;
};
diff --git a/frontend/src/hooks/api/auth/types.ts b/frontend/src/hooks/api/auth/types.ts
index 028a360460..f30f0eacfd 100644
--- a/frontend/src/hooks/api/auth/types.ts
+++ b/frontend/src/hooks/api/auth/types.ts
@@ -74,6 +74,11 @@ export type Login2Res = {
tag?: string;
};
+export type OauthTokenExchangeRes = Login2Res & {
+ isMfaEnabled?: boolean;
+ mfaMethod?: MfaMethod;
+};
+
export type LoginV3Res = {
accessToken: string;
mfaEnabled: boolean;
diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx
index 2a25f78a1e..8bbaf3567c 100644
--- a/frontend/src/hooks/api/index.tsx
+++ b/frontend/src/hooks/api/index.tsx
@@ -58,6 +58,7 @@ export * from "./secretRotation";
export * from "./secrets";
export * from "./secretSharing";
export * from "./secretSnapshots";
+export * from "./secretValidationRules";
export * from "./serverDetails";
export * from "./serviceTokens";
export * from "./sshCa";
diff --git a/frontend/src/hooks/api/secretValidationRules/index.ts b/frontend/src/hooks/api/secretValidationRules/index.ts
new file mode 100644
index 0000000000..6e26f65c67
--- /dev/null
+++ b/frontend/src/hooks/api/secretValidationRules/index.ts
@@ -0,0 +1,12 @@
+export {
+ useCreateSecretValidationRule,
+ useDeleteSecretValidationRule,
+ useUpdateSecretValidationRule
+} from "./mutations";
+export { useListSecretValidationRules } from "./queries";
+export type {
+ TCreateSecretValidationRuleDTO,
+ TDeleteSecretValidationRuleDTO,
+ TSecretValidationRule,
+ TUpdateSecretValidationRuleDTO
+} from "./types";
diff --git a/frontend/src/hooks/api/secretValidationRules/mutations.tsx b/frontend/src/hooks/api/secretValidationRules/mutations.tsx
new file mode 100644
index 0000000000..226024eaa5
--- /dev/null
+++ b/frontend/src/hooks/api/secretValidationRules/mutations.tsx
@@ -0,0 +1,58 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { secretValidationRuleKeys } from "./queries";
+import {
+ TCreateSecretValidationRuleDTO,
+ TDeleteSecretValidationRuleDTO,
+ TSecretValidationRule,
+ TUpdateSecretValidationRuleDTO
+} from "./types";
+
+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`,
+ body
+ );
+ return data.rule;
+ },
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: secretValidationRuleKeys.list(projectId) });
+ }
+ });
+};
+
+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}`,
+ body
+ );
+ return data.rule;
+ },
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: secretValidationRuleKeys.list(projectId) });
+ }
+ });
+};
+
+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}`
+ );
+ return data.rule;
+ },
+ 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.tsx
new file mode 100644
index 0000000000..e37a4ae55c
--- /dev/null
+++ b/frontend/src/hooks/api/secretValidationRules/queries.tsx
@@ -0,0 +1,35 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { TListSecretValidationRulesDTO, TSecretValidationRule } from "./types";
+
+export const secretValidationRuleKeys = {
+ all: ["secretValidationRules"] as const,
+ list: (projectId: string) => [...secretValidationRuleKeys.all, "list", projectId] as const
+};
+
+export const useListSecretValidationRules = (
+ { projectId }: TListSecretValidationRulesDTO,
+ options?: Omit<
+ UseQueryOptions<
+ TSecretValidationRule[],
+ unknown,
+ TSecretValidationRule[],
+ ReturnType<typeof secretValidationRuleKeys.list>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: secretValidationRuleKeys.list(projectId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ rules: TSecretValidationRule[] }>(
+ `/api/v1/projects/${projectId}/secret-validation-rules`
+ );
+ return data.rules;
+ },
+ enabled: Boolean(projectId) && (options?.enabled ?? true),
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/secretValidationRules/types.ts b/frontend/src/hooks/api/secretValidationRules/types.ts
new file mode 100644
index 0000000000..abd4bbbd52
--- /dev/null
+++ b/frontend/src/hooks/api/secretValidationRules/types.ts
@@ -0,0 +1,75 @@
+export enum SecretValidationRuleType {
+ StaticSecrets = "static-secrets"
+}
+
+export enum ConstraintType {
+ MinLength = "min-length",
+ MaxLength = "max-length",
+ RegexPattern = "regex-pattern",
+ RequiredPrefix = "required-prefix",
+ RequiredSuffix = "required-suffix"
+}
+
+export enum ConstraintTarget {
+ SecretKey = "key",
+ SecretValue = "value"
+}
+
+export type TConstraint = {
+ type: ConstraintType;
+ appliesTo: ConstraintTarget;
+ value: string;
+};
+
+export type TStaticSecretsInputs = {
+ constraints: TConstraint[];
+};
+
+export type TSecretValidationRuleInputs = TStaticSecretsInputs;
+
+export type TSecretValidationRule = {
+ id: string;
+ name: string;
+ description?: string | null;
+ projectId: string;
+ envId: string | null;
+ secretPath: string;
+ type: SecretValidationRuleType;
+ inputs: TSecretValidationRuleInputs;
+ isActive: boolean;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TListSecretValidationRulesDTO = {
+ projectId: string;
+};
+
+export type TCreateSecretValidationRuleDTO = {
+ projectId: string;
+ name: string;
+ description?: string | null;
+ environmentSlug?: string;
+ secretPath: string;
+ rule: {
+ type: SecretValidationRuleType;
+ inputs: TSecretValidationRuleInputs;
+ };
+};
+
+export type TUpdateSecretValidationRuleDTO = {
+ projectId: string;
+ ruleId: string;
+ name?: string;
+ description?: string | null;
+ environmentSlug?: string | null;
+ secretPath?: string;
+ type?: SecretValidationRuleType;
+ inputs?: TSecretValidationRuleInputs;
+ isActive?: boolean;
+};
+
+export type TDeleteSecretValidationRuleDTO = {
+ projectId: string;
+ ruleId: string;
+};
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index 88c52ed058..2d9968a947 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -338,7 +338,7 @@ export const clearSession = (keepQueryClient?: boolean) => {
sessionStorage.removeItem(SessionStorageKeys.CLI_TERMINAL_TOKEN);
if (!keepQueryClient) {
- qc.invalidateQueries();
+ qc.clear();
}
};
diff --git a/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx b/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx
index 8315833210..938a131715 100644
--- a/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx
+++ b/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx
@@ -62,6 +62,27 @@ export const PasswordStep = ({
providerAuthToken
});
+ if (oauthLogin.isMfaEnabled) {
+ SecurityClient.setMfaToken(oauthLogin.token);
+ if (oauthLogin.mfaMethod) {
+ setRequiredMfaMethod(oauthLogin.mfaMethod);
+ }
+ toggleShowMfa.on();
+ // After MFA verification succeeds, the Mfa component sets the real auth token.
+ // Navigate to org selection as the post-login step (do NOT re-call handleExchange
+ // which would hit the token exchange endpoint and trigger MFA again in a loop).
+ setMfaSuccessCallback(() => async () => {
+ SecurityClient.setProviderAuthToken("");
+ if (callbackPort) {
+ navigateToSelectOrganization(callbackPort, isAdminLogin);
+ } else {
+ navigateToSelectOrganization(undefined, isAdminLogin);
+ }
+ });
+ setIsLoading(false);
+ return;
+ }
+
// unset provider auth token in case it was used
SecurityClient.setProviderAuthToken("");
// set JWT token
diff --git a/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
index d14c59dc7b..e17219226e 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
@@ -10,6 +10,7 @@ import { ProjectGeneralTab } from "@app/pages/project/SettingsPage/components/Pr
import { EncryptionTab } from "./components/EncryptionTab";
import { SecretSettingsTab } from "./components/ProjectGeneralTab";
+import { SecretValidationRulesTab } from "./components/SecretValidationRulesTab";
import { WebhooksTab } from "./components/WebhooksTab";
import { WorkflowIntegrationTab } from "./components/WorkflowIntegrationSection";
@@ -21,6 +22,11 @@ export const SettingsPage = () => {
const tabs = [
{ name: "General", key: "tab-project-general", Component: ProjectGeneralTab },
{ name: "Secrets Management", key: "tab-secret-general", Component: SecretSettingsTab },
+ {
+ name: "Secret Validation Rules",
+ key: "tab-secret-validation-rules",
+ Component: SecretValidationRulesTab
+ },
{
name: "Encryption",
key: "tab-project-encryption",
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/ConstraintCard.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/ConstraintCard.tsx
new file mode 100644
index 0000000000..8732e1547f
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/ConstraintCard.tsx
@@ -0,0 +1,122 @@
+/* eslint-disable jsx-a11y/label-has-associated-control */
+import { Controller, useFormContext } from "react-hook-form";
+import { TrashIcon } from "lucide-react";
+
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ UnstableIconButton,
+ UnstableInput
+} from "@app/components/v3";
+
+import {
+ CONSTRAINT_OPTIONS,
+ CONSTRAINT_TYPE_LABELS,
+ CONSTRAINT_VALUE_LABELS,
+ ConstraintTarget,
+ ConstraintType,
+ TRuleForm
+} from "./SecretValidationRulesTab.utils";
+
+type Props = {
+ index: number;
+ onRemove: () => void;
+};
+
+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 constraintOption = CONSTRAINT_OPTIONS.find((o) => o.type === constraintType);
+
+ // Determine which targets are already used by other constraints of the same type
+ const otherTargets = new Set(
+ allConstraints
+ ?.filter((c, i) => i !== index && c.type === constraintType)
+ .map((c) => c.appliesTo)
+ );
+
+ const Icon = constraintOption?.icon;
+ const placeholder = constraintOption?.placeholder;
+
+ return (
+ <div className="rounded-md border border-border bg-card p-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ {Icon && <Icon className="size-4 text-muted" />}
+ <span className="text-sm font-medium text-foreground">
+ {CONSTRAINT_TYPE_LABELS[constraintType]}
+ </span>
+ </div>
+ <UnstableIconButton
+ aria-label="Remove constraint"
+ variant="danger"
+ size="xs"
+ onClick={onRemove}
+ >
+ <TrashIcon className="size-3.5" />
+ </UnstableIconButton>
+ </div>
+
+ <div className="mt-3 grid grid-cols-2 gap-3">
+ <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">
+ {CONSTRAINT_VALUE_LABELS[constraintType]}
+ </label>
+ <Controller
+ control={control}
+ name={`enforcement.inputs.constraints.${index}.value`}
+ render={({ field, fieldState: { error } }) => (
+ <div>
+ <UnstableInput
+ {...field}
+ type={
+ constraintType === ConstraintType.MinLength ||
+ constraintType === ConstraintType.MaxLength
+ ? "number"
+ : "text"
+ }
+ placeholder={placeholder?.toString() || undefined}
+ isError={Boolean(error)}
+ />
+ {error?.message && <p className="mt-1 text-xs text-danger">{error.message}</p>}
+ </div>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.tsx
new file mode 100644
index 0000000000..93d60383d4
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.tsx
@@ -0,0 +1,639 @@
+/* eslint-disable jsx-a11y/label-has-associated-control */
+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 { createNotification } from "@app/components/notifications";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Badge,
+ Button,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Switch,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ UnstableDropdownMenu,
+ UnstableDropdownMenuContent,
+ UnstableDropdownMenuItem,
+ UnstableDropdownMenuTrigger,
+ UnstableEmpty,
+ UnstableEmptyContent,
+ UnstableEmptyDescription,
+ UnstableEmptyHeader,
+ UnstableEmptyTitle,
+ UnstableIconButton,
+ UnstableInput,
+ UnstableTable,
+ UnstableTableBody,
+ UnstableTableCell,
+ UnstableTableHead,
+ UnstableTableHeader,
+ UnstableTableRow
+} from "@app/components/v3";
+import { useProject, useProjectPermission } from "@app/context";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import {
+ useCreateSecretValidationRule,
+ useDeleteSecretValidationRule,
+ useListSecretValidationRules,
+ useUpdateSecretValidationRule
+} from "@app/hooks/api/secretValidationRules";
+import { SecretValidationRuleType } from "@app/hooks/api/secretValidationRules/types";
+
+import { ConstraintCard } from "./ConstraintCard";
+import {
+ CONSTRAINT_OPTIONS,
+ ConstraintTarget,
+ RULE_TYPE_LABELS,
+ ruleFormSchema,
+ RuleType,
+ TRuleForm
+} from "./SecretValidationRulesTab.utils";
+
+const RuleFormContent = ({
+ defaultValues,
+ isEditing,
+ initialIsActive = true,
+ environments,
+ onClose,
+ onSubmit
+}: {
+ defaultValues?: Partial<TRuleForm>;
+ isEditing: boolean;
+ initialIsActive?: boolean;
+ environments: { slug: string; name: string }[];
+ onClose: () => void;
+ onSubmit: (data: TRuleForm, isActive?: boolean) => void;
+}) => {
+ const [isActive, setIsActive] = useState(initialIsActive);
+
+ const form = useForm<TRuleForm>({
+ resolver: zodResolver(ruleFormSchema),
+ defaultValues: defaultValues || {
+ name: "",
+ description: "",
+ environment: null,
+ folderPath: "/**",
+ enforcement: {
+ type: RuleType.StaticSecrets,
+ inputs: {
+ constraints: []
+ }
+ }
+ }
+ });
+
+ const {
+ handleSubmit,
+ control,
+ formState: { errors }
+ } = form;
+
+ const { fields, append, remove } = useFieldArray({
+ control,
+ name: "enforcement.inputs.constraints"
+ });
+
+ const watchedConstraints = form.watch("enforcement.inputs.constraints");
+ const usedConstraintPairs = new Set(watchedConstraints?.map((c) => `${c.type}:${c.appliesTo}`));
+ const availableConstraintOptions = CONSTRAINT_OPTIONS.filter(
+ (opt) =>
+ !usedConstraintPairs.has(`${opt.type}:${ConstraintTarget.SecretKey}`) ||
+ !usedConstraintPairs.has(`${opt.type}:${ConstraintTarget.SecretValue}`)
+ );
+
+ return (
+ <FormProvider {...form}>
+ <form
+ onSubmit={handleSubmit((data) => onSubmit(data, isEditing ? isActive : undefined))}
+ className="flex h-full flex-col"
+ >
+ {isEditing && (
+ <div className="flex items-center justify-between border-b border-border px-6 py-3">
+ <span className="text-xs text-muted">{isActive ? "Enabled" : "Disabled"}</span>
+ <Switch checked={isActive} onCheckedChange={setIsActive} variant="project" />
+ </div>
+ )}
+ <div
+ className={`flex-1 space-y-6 p-6 transition-opacity ${!isActive ? "pointer-events-none opacity-40" : ""}`}
+ >
+ {/* Name & Description */}
+ <div className="space-y-4">
+ <div className="flex flex-col gap-1">
+ <label className="text-xs font-medium text-muted">Name</label>
+ <Controller
+ control={control}
+ name="name"
+ render={({ field }) => (
+ <UnstableInput
+ {...field}
+ placeholder="e.g. Production key naming"
+ isError={Boolean(errors.name)}
+ />
+ )}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-xs font-medium text-muted">Description (optional)</label>
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }) => (
+ <UnstableInput
+ {...field}
+ value={field.value ?? ""}
+ placeholder="Brief description of this rule"
+ />
+ )}
+ />
+ </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>
+ )}
+ />
+ </div>
+
+ {/* Scope */}
+ <div>
+ <h4 className="mb-3 text-sm font-medium text-foreground">Scope</h4>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1">
+ <label className="text-xs font-medium text-muted">Environment</label>
+ <Controller
+ control={control}
+ name="environment"
+ render={({ field: { value, onChange } }) => (
+ <Select
+ value={value ?? "all"}
+ onValueChange={(val) => onChange(val === "all" ? null : val)}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="All Environments" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value="all">All Environments</SelectItem>
+ {environments.map((env) => (
+ <SelectItem key={env.slug} value={env.slug}>
+ {env.name}
+ </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-2">
+ <p>Folder Path</p>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-4 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs text-wrap">
+ {/* eslint-disable-next-line react/jsx-no-comment-textnodes */}
+ <p>
+ The folder path is a glob pattern to match secret paths. As an example,
+ /** will match all paths, /services/* will match all paths in the
+ /services folder and its subfolders.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </label>
+ <Controller
+ control={control}
+ name="folderPath"
+ render={({ field, fieldState: { error } }) => (
+ <div>
+ <UnstableInput {...field} placeholder="/**" isError={Boolean(error)} />
+ {error?.message && (
+ <p className="mt-1 text-xs text-danger">{error.message}</p>
+ )}
+ </div>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* Constraints */}
+ <div>
+ <div className="mb-3 flex items-center justify-between">
+ <h4 className="text-sm font-medium text-foreground">Validation Constraints</h4>
+ {availableConstraintOptions.length > 0 && (
+ <UnstableDropdownMenu>
+ <UnstableDropdownMenuTrigger asChild>
+ <Button type="button" variant="outline" size="xs">
+ <PlusIcon className="size-4" />
+ Add Constraint
+ </Button>
+ </UnstableDropdownMenuTrigger>
+ <UnstableDropdownMenuContent align="end">
+ {availableConstraintOptions.map((opt) => {
+ const valueUsed = usedConstraintPairs.has(
+ `${opt.type}:${ConstraintTarget.SecretValue}`
+ );
+ const defaultTarget = valueUsed
+ ? ConstraintTarget.SecretKey
+ : ConstraintTarget.SecretValue;
+
+ return (
+ <UnstableDropdownMenuItem
+ key={opt.type}
+ onClick={() =>
+ append({
+ type: opt.type,
+ appliesTo: defaultTarget,
+ value: ""
+ })
+ }
+ >
+ <opt.icon className="mr-2 size-4" />
+ <div>
+ <div className="text-sm">{opt.label}</div>
+ <div className="text-xs text-muted">{opt.description}</div>
+ </div>
+ </UnstableDropdownMenuItem>
+ );
+ })}
+ </UnstableDropdownMenuContent>
+ </UnstableDropdownMenu>
+ )}
+ </div>
+
+ {fields.length === 0 && (
+ <div className="rounded-md border border-dashed border-border py-8 text-center">
+ <p className="text-sm text-muted">No constraints added yet</p>
+ {(errors.enforcement?.inputs?.constraints?.root?.message ||
+ errors.enforcement?.inputs?.constraints?.message) && (
+ <p className="mt-1 text-xs text-danger">
+ {errors.enforcement?.inputs?.constraints?.root?.message ||
+ errors.enforcement?.inputs?.constraints?.message}
+ </p>
+ )}
+ </div>
+ )}
+
+ <div className="space-y-3">
+ {fields.map((field, idx) => (
+ <ConstraintCard key={field.id} index={idx} onRemove={() => remove(idx)} />
+ ))}
+ </div>
+
+ {fields.length > 0 &&
+ (errors.enforcement?.inputs?.constraints?.root?.message ||
+ errors.enforcement?.inputs?.constraints?.message) && (
+ <p className="mt-1 text-xs text-danger">
+ {errors.enforcement?.inputs?.constraints?.root?.message ||
+ errors.enforcement?.inputs?.constraints?.message}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <SheetFooter className="border-t">
+ <Button variant="project" type="submit">
+ {isEditing ? "Save Changes" : "Create Rule"}
+ </Button>
+ <Button type="button" variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ </SheetFooter>
+ </form>
+ </FormProvider>
+ );
+};
+
+type SheetState =
+ | { open: false }
+ | { open: true; mode: "create" }
+ | { open: true; mode: "edit"; ruleId: string };
+
+export const SecretValidationRulesTab = () => {
+ const { currentProject } = useProject();
+ const { permission } = useProjectPermission();
+ const canModifySettings = permission.can(
+ ProjectPermissionActions.Edit,
+ ProjectPermissionSub.Settings
+ );
+ 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 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 handleDelete = async () => {
+ if (!deleteRuleId) return;
+ await deleteRule
+ .mutateAsync({ projectId: currentProject.id, ruleId: deleteRuleId })
+ .finally(() => setDeleteRuleId(null));
+ };
+
+ const handleClose = () => setSheetState({ open: false });
+
+ const handleSubmit = async (data: TRuleForm, isActive?: boolean) => {
+ if (sheetState.open && sheetState.mode === "edit") {
+ await updateRule.mutateAsync({
+ projectId: currentProject.id,
+ ruleId: sheetState.ruleId,
+ name: data.name,
+ description: data.description,
+ isActive,
+ environmentSlug: data.environment ?? null,
+ secretPath: data.folderPath,
+ type: data.enforcement.type as string as SecretValidationRuleType,
+ inputs: data.enforcement.inputs
+ });
+ 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: {
+ type: data.enforcement.type as string as SecretValidationRuleType,
+ inputs: data.enforcement.inputs
+ }
+ });
+ createNotification({ text: "Rule created", type: "success" });
+ }
+ handleClose();
+ };
+
+ const editingRule =
+ sheetState.open && sheetState.mode === "edit"
+ ? rules.find((r) => r.id === sheetState.ruleId)
+ : undefined;
+
+ const editingDefaults = editingRule
+ ? {
+ name: editingRule.name,
+ description: editingRule.description ?? undefined,
+ environment: resolveEnvSlug(editingRule.envId),
+ folderPath: editingRule.secretPath,
+ enforcement: {
+ type: editingRule.type as string as RuleType,
+ inputs: editingRule.inputs
+ }
+ }
+ : undefined;
+
+ const isEditing = sheetState.open && sheetState.mode === "edit";
+
+ return (
+ <div className="w-full">
+ <div className="flex h-full w-full flex-1 flex-col rounded-lg border border-border bg-card py-4">
+ <div className="mx-4 flex items-center justify-between border-b border-border pb-4">
+ <div>
+ <h3 className="text-lg font-medium text-foreground">Secret Validation Rules</h3>
+ <p className="text-sm leading-3 text-muted">
+ Define validation constraints for secret keys and values
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={!canModifySettings}
+ onClick={() => setSheetState({ open: true, mode: "create" })}
+ >
+ <PlusIcon className="size-4" />
+ Create Rule
+ </Button>
+ </div>
+ <div className="flex flex-1 flex-col overflow-hidden px-4">
+ <div className="thin-scrollbar flex-1 overflow-y-scroll py-4">
+ {isLoading && (
+ <div className="flex items-center justify-center py-12">
+ <p className="text-sm text-muted">Loading rules...</p>
+ </div>
+ )}
+ {!isLoading && rules.length === 0 ? (
+ <UnstableEmpty className="border">
+ <UnstableEmptyHeader>
+ <UnstableEmptyTitle>No validation rules configured</UnstableEmptyTitle>
+ <UnstableEmptyDescription>
+ Create a rule to enforce validation constraints on secret keys and values
+ </UnstableEmptyDescription>
+ </UnstableEmptyHeader>
+ <UnstableEmptyContent>
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={!canModifySettings}
+ onClick={() => setSheetState({ open: true, mode: "create" })}
+ >
+ <PlusIcon className="size-4" />
+ Create Rule
+ </Button>
+ </UnstableEmptyContent>
+ </UnstableEmpty>
+ ) : (
+ !isLoading && (
+ <UnstableTable>
+ <UnstableTableHeader>
+ <UnstableTableRow>
+ <UnstableTableHead>Name</UnstableTableHead>
+ <UnstableTableHead>Type</UnstableTableHead>
+ <UnstableTableHead>Scope</UnstableTableHead>
+ <UnstableTableHead>Status</UnstableTableHead>
+ <UnstableTableHead className="w-12" />
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {rules.map((rule) => (
+ <UnstableTableRow key={rule.id}>
+ <UnstableTableCell className="py-3">
+ <div className="flex items-center">
+ <span className="text-sm font-medium text-foreground">{rule.name}</span>
+ {rule.description && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="ml-1.5 size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent>{rule.description}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </UnstableTableCell>
+ <UnstableTableCell className="py-3">
+ <Badge variant="neutral">
+ {RULE_TYPE_LABELS[rule.type as string as RuleType] ?? rule.type}
+ </Badge>
+ </UnstableTableCell>
+ <UnstableTableCell className="py-3">
+ <div className="flex items-center gap-1.5">
+ <Badge variant="neutral">{resolveEnvName(rule.envId)}</Badge>
+ <Badge variant="neutral">{rule.secretPath}</Badge>
+ </div>
+ </UnstableTableCell>
+ <UnstableTableCell className="py-3">
+ <Badge variant={rule.isActive ? "success" : "neutral"}>
+ {rule.isActive ? "Active" : "Inactive"}
+ </Badge>
+ </UnstableTableCell>
+ <UnstableTableCell className="py-3">
+ <UnstableDropdownMenu>
+ <UnstableDropdownMenuTrigger asChild>
+ <UnstableIconButton aria-label="Actions" variant="ghost" size="xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </UnstableIconButton>
+ </UnstableDropdownMenuTrigger>
+ <UnstableDropdownMenuContent align="end">
+ <UnstableDropdownMenuItem
+ isDisabled={!canModifySettings}
+ onClick={() =>
+ setSheetState({ open: true, mode: "edit", ruleId: rule.id })
+ }
+ >
+ <PencilIcon className="mr-2 size-4" />
+ Edit
+ </UnstableDropdownMenuItem>
+ <UnstableDropdownMenuItem
+ variant="danger"
+ isDisabled={!canModifySettings}
+ onClick={() => setDeleteRuleId(rule.id)}
+ >
+ <TrashIcon className="mr-2 size-4" />
+ Delete
+ </UnstableDropdownMenuItem>
+ </UnstableDropdownMenuContent>
+ </UnstableDropdownMenu>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ ))}
+ </UnstableTableBody>
+ </UnstableTable>
+ )
+ )}
+ </div>
+ </div>
+ </div>
+
+ <AlertDialog
+ open={deleteRuleId !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ setDeleteRuleId(null);
+ setDeleteConfirmation("");
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Validation Rule</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete this rule? This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <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
+ </p>
+ <UnstableInput
+ value={deleteConfirmation}
+ onChange={(e) => setDeleteConfirmation(e.target.value)}
+ placeholder={rules.find((r) => r.id === deleteRuleId)?.name}
+ />
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="danger"
+ onClick={handleDelete}
+ disabled={deleteConfirmation !== rules.find((r) => r.id === deleteRuleId)?.name}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
+ <Sheet open={sheetState.open} onOpenChange={(open) => !open && handleClose()}>
+ <SheetContent className="flex h-full flex-col gap-y-0 overflow-y-auto sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>{isEditing ? "Edit Rule" : "Create Rule"}</SheetTitle>
+ <SheetDescription>
+ {isEditing ? "Modify this validation rule" : "Define a new secret validation rule"}
+ </SheetDescription>
+ </SheetHeader>
+ {sheetState.open && (
+ <RuleFormContent
+ key={isEditing ? editingRule?.id : "create"}
+ defaultValues={editingDefaults}
+ isEditing={isEditing}
+ initialIsActive={editingRule?.isActive ?? true}
+ environments={currentProject.environments}
+ onClose={handleClose}
+ onSubmit={handleSubmit}
+ />
+ )}
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.utils.ts b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.utils.ts
new file mode 100644
index 0000000000..f0a8214fd2
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/SecretValidationRulesTab.utils.ts
@@ -0,0 +1,121 @@
+import { HashIcon, LucideIcon, RulerIcon, TextCursorInputIcon, TextIcon } from "lucide-react";
+import { z } from "zod";
+
+export enum ConstraintType {
+ MinLength = "min-length",
+ MaxLength = "max-length",
+ RegexPattern = "regex-pattern",
+ RequiredPrefix = "required-prefix",
+ RequiredSuffix = "required-suffix"
+}
+
+export enum ConstraintTarget {
+ SecretKey = "key",
+ SecretValue = "value"
+}
+
+export const CONSTRAINT_OPTIONS: {
+ type: ConstraintType;
+ label: string;
+ description: string;
+ placeholder: string | number;
+ icon: LucideIcon;
+}[] = [
+ {
+ type: ConstraintType.MinLength,
+ label: "Min Length",
+ description: "Minimum character count",
+ placeholder: 8,
+ icon: RulerIcon
+ },
+ {
+ type: ConstraintType.MaxLength,
+ label: "Max Length",
+ description: "Maximum character count",
+ placeholder: 256,
+ icon: RulerIcon
+ },
+ {
+ type: ConstraintType.RegexPattern,
+ label: "Regex Pattern",
+ description: "Must match a regular expression",
+ placeholder: "^[A-Z_]+$",
+ icon: HashIcon
+ },
+ {
+ type: ConstraintType.RequiredPrefix,
+ label: "Required Prefix",
+ description: "Must start with specific text",
+ placeholder: "PREFIX-",
+ icon: TextCursorInputIcon
+ },
+ {
+ type: ConstraintType.RequiredSuffix,
+ label: "Required Suffix",
+ description: "Must end with specific text",
+ placeholder: "-SUFFIX",
+ icon: TextIcon
+ }
+];
+
+export const CONSTRAINT_VALUE_LABELS: Record<ConstraintType, string> = {
+ [ConstraintType.MinLength]: "Characters",
+ [ConstraintType.MaxLength]: "Characters",
+ [ConstraintType.RegexPattern]: "Pattern",
+ [ConstraintType.RequiredPrefix]: "Text",
+ [ConstraintType.RequiredSuffix]: "Text"
+};
+
+export const CONSTRAINT_TYPE_LABELS: Record<ConstraintType, string> = {
+ [ConstraintType.MinLength]: "Min Length",
+ [ConstraintType.MaxLength]: "Max Length",
+ [ConstraintType.RegexPattern]: "Regex Pattern",
+ [ConstraintType.RequiredPrefix]: "Required Prefix",
+ [ConstraintType.RequiredSuffix]: "Required Suffix"
+};
+
+export enum RuleType {
+ StaticSecrets = "static-secrets"
+}
+
+export const RULE_TYPE_LABELS: Record<RuleType, string> = {
+ [RuleType.StaticSecrets]: "Static Secrets"
+};
+
+export const constraintSchema = z.object({
+ type: z.nativeEnum(ConstraintType),
+ appliesTo: z.nativeEnum(ConstraintTarget),
+ value: z.string().min(1, "Value is required")
+});
+
+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" }
+ )
+});
+
+export const ruleFormSchema = z.object({
+ name: z.string().min(1, "Name is required").max(100),
+ 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
+ })
+});
+
+export type TRuleForm = z.infer<typeof ruleFormSchema>;
+export type TConstraint = z.infer<typeof constraintSchema>;
+
+export type TRule = TRuleForm & {
+ id: string;
+ isActive: boolean;
+};
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/index.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/index.tsx
new file mode 100644
index 0000000000..b8917bf55c
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesTab/index.tsx
@@ -0,0 +1 @@
+export { SecretValidationRulesTab } from "./SecretValidationRulesTab";
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/index.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/index.tsx
index e386fe3365..7b58012626 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/index.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/index.tsx
@@ -3,3 +3,4 @@ export { BackfillSecretReferenceSecretion } from "./BackfillSecretReferenceSecti
export { EnforceEncryptedMetadataSection } from "./EnforceEncryptedMetadataSection";
export { EnvironmentSection } from "./EnvironmentSection";
export { SecretTagsSection } from "./SecretTagsSection";
+export { SecretValidationRulesTab } from "./SecretValidationRulesTab";