Skip to content

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

add validation rule

Matheus Nogueiraa61bf7f884eb
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a04df5a307..cd7e5f6a4b 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -40,7 +40,8 @@ export const PgSqlLock = {
LastAdminGuard: (scope: "org", scopeId: string) => pgAdvisoryLockHashText(`last-admin-guard:${scope}:${scopeId}`),
AuditReportRequest: (projectId: string) => pgAdvisoryLockHashText(`audit-report-request:${projectId}`),
OrgAuditReportRequest: (orgId: string) => pgAdvisoryLockHashText(`audit-report-request:org:${orgId}`),
- OrgAgentProxyConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-agent-proxy-config-init:${orgId}`)
+ OrgAgentProxyConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-agent-proxy-config-init:${orgId}`),
+ SecretValueUniqueCheck: (projectId: string) => pgAdvisoryLockHashText(`secret-value-unique-check:${projectId}`)
} as const;
// all the key prefixes used must be set here to avoid conflict
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index d540ee1d7c..4c1efb6066 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4090,7 +4090,9 @@ export const SecretValidationRules = {
REUSE_PREVENTION: {
reusePrevention:
"Rejects a value for repeating one already in use. Omit to allow any value the other constraints accept.",
- previousVersions: `How many of the secret's own previous versions the new value must differ from. Between 1 and ${MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS}.`
+ previousVersions: `How many of the secret's own previous versions the new value must differ from. Between 1 and ${MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS}.`,
+ otherSecrets:
+ "Set to true to reject a value that another secret in the rule's scope already holds. Requires blind indexing on the project."
},
STATIC_SECRETS: {
keyConstraints:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 39a2e89949..e095ca0244 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2301,7 +2301,8 @@ export const registerRoutes = async (
kmsService,
folderDAL,
secretDAL: secretV2BridgeDAL,
- secretVersionV2BridgeDAL
+ secretVersionV2BridgeDAL,
+ projectDAL
});
const secretImportService = secretImportServiceFactory({
licenseService,
diff --git a/backend/src/server/routes/sanitizedSchemas.ts b/backend/src/server/routes/sanitizedSchemas.ts
index 626c7d4b77..6d2bde616b 100644
--- a/backend/src/server/routes/sanitizedSchemas.ts
+++ b/backend/src/server/routes/sanitizedSchemas.ts
@@ -337,6 +337,7 @@ export const SanitizedProjectSchema = ProjectsSchema.pick({
showSnapshotsLegacy: true,
secretDetectionIgnoreValues: true,
enforceEncryptedSecretManagerSecretMetadata: true,
+ secretBlindIndexEnabled: true,
isLegacyAdditionalPrivilegesEnabled: true
});
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index 0d0c094045..646d38dedf 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -1527,6 +1527,45 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
+ const findExistingSecretsByBlindIndexes = async (
+ projectId: string,
+ blindIndexes: string[],
+ excludeSecretIds?: string[],
+ envId?: string,
+ tx?: Knex
+ ) => {
+ try {
+ if (!blindIndexes.length) return [];
+
+ let query = (tx || db)(TableName.SecretV2)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .whereNull(`${TableName.SecretV2}.userId`)
+ .whereIn(`${TableName.SecretV2}.secretValueBlindIndex`, blindIndexes)
+ .select(
+ db.ref("id").withSchema(TableName.SecretV2),
+ db.ref("key").withSchema(TableName.SecretV2),
+ db.ref("folderId").withSchema(TableName.SecretV2),
+ db.ref("secretValueBlindIndex").withSchema(TableName.SecretV2),
+ db.ref("slug").withSchema(TableName.Environment).as("environment")
+ );
+
+ if (envId) {
+ query = query.where(`${TableName.Environment}.id`, envId);
+ }
+
+ if (excludeSecretIds?.length) {
+ query = query.whereNotIn(`${TableName.SecretV2}.id`, excludeSecretIds);
+ }
+
+ return await query;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "findExistingSecretsByBlindIndexes" });
+ }
+ };
+
const countStaleByProject = async (projectId: string, staleBeforeDate: Date, tx?: Knex) => {
try {
const result = await (tx || db.replicaNode())(TableName.SecretV2)
@@ -1587,6 +1626,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
countByProject,
findValueValidationCandidatesByProject,
findDuplicatedSecretValues,
+ findExistingSecretsByBlindIndexes,
findOne,
find,
invalidateSecretCacheByProjectId,
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 178099cadd..9364604435 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
@@ -211,6 +211,14 @@ export const secretV2BridgeServiceFactory = ({
projectFolderGrantDAL,
orgDAL
}: TSecretV2BridgeServiceFactoryDep) => {
+ // A duplicate-value violation may only name where the value is already used when the writer can read there.
+ const $canDescribeSecretAt =
+ (permission: MongoAbility<ProjectPermissionSet>) => (environment: string, secretPath: string) =>
+ permission.can(
+ ProjectPermissionSecretActions.DescribeSecret,
+ subject(ProjectPermissionSub.Secrets, { environment, secretPath })
+ );
+
const $validateSecretReferences = async (
projectId: string,
permission: MongoAbility<ProjectPermissionSet>,
@@ -410,14 +418,6 @@ 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 }))
@@ -434,6 +434,18 @@ export const secretV2BridgeServiceFactory = ({
? await generateSecretBlindIndex(Buffer.from(inputSecretData.secretValue))
: undefined;
const secret = await secretDAL.transaction(async (tx) => {
+ await secretValidationRuleService.validateSecrets(
+ {
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: [{ key: inputSecret.secretName, value: inputSecret.secretValue }],
+ canAccessLocation: $canDescribeSecretAt(permission)
+ },
+ tx
+ );
+
const [createdSecret] = await fnSecretBulkInsert({
folderId,
orgId: actorOrgId,
@@ -698,16 +710,6 @@ 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, secretId }]
- });
- }
-
if (secretValue) {
const { nestedReferences, localReferences } = getAllSecretReferences(secretValue);
const allSecretReferences = nestedReferences.concat(
@@ -742,6 +744,20 @@ export const secretV2BridgeServiceFactory = ({
}
const updatedSecret = await secretDAL.transaction(async (tx) => {
+ if (secretValue || inputSecret.newSecretName) {
+ await secretValidationRuleService.validateSecrets(
+ {
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: [{ key: finalKey, value: secretValue, secretId }],
+ canAccessLocation: $canDescribeSecretAt(permission)
+ },
+ tx
+ );
+ }
+
const modifiedSecretsInDB = await fnSecretBulkUpdate({
folderId,
orgId: actorOrgId,
@@ -2156,14 +2172,6 @@ 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) : [];
@@ -2205,6 +2213,18 @@ export const secretV2BridgeServiceFactory = ({
} = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
const executeBulkInsert = async (tx: Knex) => {
+ await secretValidationRuleService.validateSecrets(
+ {
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue })),
+ canAccessLocation: $canDescribeSecretAt(permission)
+ },
+ tx
+ );
+
const inputSecretsWithBlindIndex = await Promise.all(
deduplicatedSecrets.map(async (el) => {
const references = secretReferencesGroupByInputSecretKey[el.secretKey]?.nestedReferences;
@@ -2576,13 +2596,17 @@ export const secretV2BridgeServiceFactory = ({
];
if (secretsToValidate.length) {
// eslint-disable-next-line no-await-in-loop
- await secretValidationRuleService.validateSecrets({
- projectId,
- environment,
- envId: folder.envId,
- secretPath,
- secrets: secretsToValidate
- });
+ await secretValidationRuleService.validateSecrets(
+ {
+ projectId,
+ environment,
+ envId: folder.envId,
+ secretPath,
+ secrets: secretsToValidate,
+ canAccessLocation: $canDescribeSecretAt(permission)
+ },
+ tx
+ );
}
const secretKeyUpdates: {
diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts
index c93a43d36e..004498114f 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-constraint-fns.ts
@@ -10,7 +10,8 @@ export const CONSTRAINT_LABELS: Record<ConstraintKind, string> = {
[ConstraintKind.RegexPattern]: "Regex pattern",
[ConstraintKind.RequiredPrefix]: "Required prefix",
[ConstraintKind.RequiredSuffix]: "Required suffix",
- [ConstraintKind.ReusePreviousVersions]: "Prevent reuse of previous secret values"
+ [ConstraintKind.ReusePreviousVersions]: "Prevent reuse of previous secret values",
+ [ConstraintKind.ReuseOtherSecrets]: "Prevent reuse of a value another secret already holds"
};
export type TConstraintViolation = {
diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts
index 97684edf42..9c685fdadd 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-enums.ts
@@ -10,7 +10,8 @@ export enum ConstraintKind {
RegexPattern = "regex-pattern",
RequiredPrefix = "required-prefix",
RequiredSuffix = "required-suffix",
- ReusePreviousVersions = "reuse-previous-versions"
+ ReusePreviousVersions = "reuse-previous-versions",
+ ReuseOtherSecrets = "reuse-other-secrets"
}
export enum ConstraintTarget {
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
index 900bbf018a..7b81170fac 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-fns.ts
@@ -141,14 +141,14 @@ export type TRuleToEnforce = {
config: TStaticSecretsRuleConfig;
};
+/** Whether a rule scoped to `rulePath` reaches a secret sitting at `secretPath`. */
+export const doesRulePathCover = (rulePath: string, secretPath: string) =>
+ picomatch.isMatch(secretPath, rulePath, { strictSlashes: false });
+
export const findRulesCoveringScope = <T extends { envId?: string | null; secretPath: string }>(
rules: T[],
{ envId, secretPath }: { envId: string; secretPath: string }
-) =>
- rules.filter(
- (rule) =>
- (!rule.envId || rule.envId === envId) && picomatch.isMatch(secretPath, rule.secretPath, { strictSlashes: false })
- );
+) => rules.filter((rule) => (!rule.envId || rule.envId === envId) && doesRulePathCover(rule.secretPath, secretPath));
export const enforceSecretValidationRules = ({
rules,
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
index 58e73e5145..11f19e5086 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-schemas.ts
@@ -50,7 +50,8 @@ const ReusePreventionSchema = z
.min(1)
.max(MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS)
.optional()
- .describe(SecretValidationRules.REUSE_PREVENTION.previousVersions)
+ .describe(SecretValidationRules.REUSE_PREVENTION.previousVersions),
+ otherSecrets: z.boolean().optional().describe(SecretValidationRules.REUSE_PREVENTION.otherSecrets)
})
.refine((reusePrevention) => Object.values(reusePrevention).some((value) => value !== undefined), {
message: "Set at least one reuse prevention option, or leave reusePrevention out entirely"
@@ -107,7 +108,7 @@ export const buildValueConstraintsSchema = (target: ConstraintTarget) =>
export type TConstraints = z.infer<typeof BaseConstraintsSchema>;
-export type TReusePrevention = { previousVersions?: number };
+export type TReusePrevention = { previousVersions?: number; otherSecrets?: boolean };
// a secret value additionally supports being checked against values it has already had
export type TValueConstraints = TConstraints & { reusePrevention?: TReusePrevention };
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
index 1ff4644ebe..eaad5e6505 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts
@@ -7,14 +7,16 @@ import {
ProjectPermissionSecretValidationRuleActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
+import { PgSqlLock } from "@app/keystore/keystore";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
+import { TProjectDALFactory } from "../project/project-dal";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
-import { expandSecretReferencesFactory } from "../secret-v2-bridge/secret-reference-fns";
+import { containsSecretReference, expandSecretReferencesFactory } from "../secret-v2-bridge/secret-reference-fns";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
import { MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS } from "./secret-validation-rule-constants";
@@ -23,6 +25,7 @@ import { TSecretValidationRuleDALFactory } from "./secret-validation-rule-dal";
import { ConstraintTarget, SecretValidationRuleType } from "./secret-validation-rule-enums";
import {
checkForOverlappingRules,
+ doesRulePathCover,
enforceSecretValidationRules,
findRulesCoveringScope,
getConstraintsByTarget,
@@ -46,14 +49,19 @@ import {
TUpdateSecretValidationRuleDTO,
TValidateSecretsDTO
} from "./secret-validation-rule-types";
-import { TStaticSecretsRuleConfig } from "./static-secrets";
+import { TDuplicateSecret, TStaticSecretsRuleConfig } from "./static-secrets";
+
+/** Only static-secret rules can ask for a value no other secret already holds. */
+const $wantsCrossSecretUniqueness = (config: TSecretValidationRuleConfig) =>
+ Boolean((config as TStaticSecretsRuleConfig).valueConstraints?.reusePrevention?.otherSecrets);
type TSecretValidationRuleServiceFactoryDep = {
secretValidationRuleDAL: TSecretValidationRuleDALFactory;
projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
- folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
+ folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findSecretPathByFolderIds">;
secretDAL: TSecretV2BridgeDALFactory;
secretVersionV2BridgeDAL: Pick<TSecretVersionV2DALFactory, "find">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
kmsService: TKmsServiceFactory;
};
@@ -66,6 +74,7 @@ export const secretValidationRuleServiceFactory = ({
folderDAL,
secretDAL,
secretVersionV2BridgeDAL,
+ projectDAL,
permissionService,
kmsService
}: TSecretValidationRuleServiceFactoryDep) => {
@@ -191,6 +200,19 @@ export const secretValidationRuleServiceFactory = ({
);
};
+ // Cross-secret uniqueness is answered from the blind index, so a project without one cannot enforce it.
+ const $assertBlindIndexingAvailable = async (projectId: string, config: TSecretValidationRuleConfig) => {
+ if (!$wantsCrossSecretUniqueness(config)) return;
+
+ const project = await projectDAL.findById(projectId);
+ if (!project.secretBlindIndexEnabled) {
+ throw new BadRequestError({
+ message:
+ "Enable secret blind indexing on this project before preventing reuse of a value another secret already holds"
+ });
+ }
+ };
+
const listSecretValidationRules = async (
{ projectId, type }: TListSecretValidationRulesDTO,
actor: OrgServiceActor
@@ -269,6 +291,7 @@ export const secretValidationRuleServiceFactory = ({
$assertConstrainsSomething(type, config);
$assertGeneratorCanSatisfy(type, config);
+ await $assertBlindIndexingAvailable(projectId, config);
await $assertNoOverlap({ projectId, type, envId, secretPath, config });
const { encryptor } = await $getCipher(projectId);
@@ -334,6 +357,7 @@ export const secretValidationRuleServiceFactory = ({
$assertConstrainsSomething(type, config);
$assertGeneratorCanSatisfy(type, config);
+ await $assertBlindIndexingAvailable(projectId, config);
await $assertNoOverlap({ projectId, type, envId, secretPath: finalSecretPath, config, excludeRuleId: ruleId });
const rule = await secretValidationRuleDAL.updateByIdWithEnv(ruleId, {
@@ -372,12 +396,112 @@ export const secretValidationRuleServiceFactory = ({
return $toRecord(rule, config);
};
+ /**
+ * The secret already holding each incoming value, keyed by the incoming key, for the secrets that
+ * collide with one. Values are matched through the project's blind index rather than by reading
+ * every secret in the project back out.
+ *
+ * The index is built over the value as stored, so a value carrying a `${...}` reference is skipped:
+ * its stored form would never line up with the resolved one anyway.
+ */
+ const $findDuplicatesInScope = async (
+ {
+ projectId,
+ environment,
+ secretPath,
+ secrets,
+ scope,
+ canAccessLocation,
+ generateSecretBlindIndex
+ }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets" | "canAccessLocation"> & {
+ scope: { envId?: string | null; secretPath: string };
+ generateSecretBlindIndex: (value: Buffer) => Promise<string>;
+ },
+ tx?: Knex
+ ): Promise<Record<string, TDuplicateSecret>> => {
+ const candidates = secrets.filter(
+ (secret): secret is typeof secret & { value: string } =>
+ secret.value !== undefined && !containsSecretReference(secret.value)
+ );
+ if (!candidates.length) return {};
+
+ // Two writes of the same value would each find no duplicate and both land. The lock makes this
+ // check and the write that follows it atomic, so the second one sees the first.
+ if (tx) await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.SecretValueUniqueCheck(projectId)]);
+
+ const blindIndexes = await Promise.all(
+ candidates.map((secret) => generateSecretBlindIndex(Buffer.from(secret.value)))
+ );
+
+ const duplicates: Record<string, TDuplicateSecret> = {};
+
+ // Two secrets in one request can collide with each other before either exists in the database.
+ const seenInBatch = new Map<string, TDuplicateSecret>();
+ candidates.forEach((secret, idx) => {
+ const seen = seenInBatch.get(blindIndexes[idx]);
+ if (seen) duplicates[secret.key] = seen;
+ else seenInBatch.set(blindIndexes[idx], { key: secret.key, environment, secretPath });
+ });
+
+ const excludedSecretIds = candidates.map((secret) => secret.secretId).filter(Boolean) as string[];
+ const existing = await secretDAL.findExistingSecretsByBlindIndexes(
+ projectId,
+ [...new Set(blindIndexes)],
+ excludedSecretIds.length ? excludedSecretIds : undefined,
+ scope.envId ?? undefined,
+ tx
+ );
+ if (!existing.length) return duplicates;
+
+ const folderIds = [...new Set(existing.map((secret) => secret.folderId))];
+ const folderPaths = await folderDAL.findSecretPathByFolderIds(projectId, folderIds, tx);
+ const pathByFolderId = new Map(folderIds.map((id, idx) => [id, folderPaths[idx]?.path ?? "/"]));
+
+ const accessByLocation = new Map<string, boolean>();
+ const isHidden = (dupEnvironment: string, dupPath: string) => {
+ if (!canAccessLocation) return false;
+
+ const location = `${dupEnvironment}:${dupPath}`;
+ let hidden = accessByLocation.get(location);
+ if (hidden === undefined) {
+ hidden = !canAccessLocation(dupEnvironment, dupPath);
+ accessByLocation.set(location, hidden);
+ }
+ return hidden;
+ };
+
+ // The lookup spans the project, so drop the hits the rule's own path does not reach.
+ const inScope = new Map<string, TDuplicateSecret>();
+ existing.forEach((secret) => {
+ if (!secret.secretValueBlindIndex || inScope.has(secret.secretValueBlindIndex)) return;
+
+ const dupPath = pathByFolderId.get(secret.folderId) ?? "/";
+ if (!doesRulePathCover(scope.secretPath, dupPath)) return;
+
+ inScope.set(secret.secretValueBlindIndex, {
+ key: secret.key,
+ environment: secret.environment,
+ secretPath: dupPath,
+ hidden: isHidden(secret.environment, dupPath)
+ });
+ });
+
+ candidates.forEach((secret, idx) => {
+ if (duplicates[secret.key]) return;
+
+ const duplicate = inScope.get(blindIndexes[idx]);
+ if (duplicate) duplicates[secret.key] = duplicate;
+ });
+
+ return duplicates;
+ };
+
/**
* Pass `tx` when the caller already holds a transaction, or this checks out a second connection.
* `${env.key}` references are expanded first, so constraints see the resolved value.
*/
const validateSecrets = async (
- { projectId, environment, envId, secretPath, secrets }: TValidateSecretsDTO,
+ { projectId, environment, envId, secretPath, secrets, canAccessLocation }: TValidateSecretsDTO,
tx?: Knex
) => {
if (!secrets.length) return;
@@ -388,10 +512,11 @@ export const secretValidationRuleServiceFactory = ({
);
if (!rules.length) return;
- const { decryptor } = await $getCipher(projectId);
+ const { decryptor, generateSecretBlindIndex } = await $getCipher(projectId);
const coveringRules = findRulesCoveringScope(rules, { envId, secretPath }).map((rule) => ({
name: rule.name,
+ scope: { envId: rule.envId, secretPath: rule.secretPath },
config: parseSecretValidationRuleConfig(
rule.type,
JSON.parse(decryptor({ cipherTextBlob: rule.encryptedInputs }).toString()) as unknown
@@ -426,6 +551,23 @@ export const secretValidationRuleServiceFactory = ({
});
}
+ // Only one covering rule can ask for cross-secret uniqueness; overlap is rejected at save time.
+ const uniquenessRule = coveringRules.find((rule) => $wantsCrossSecretUniqueness(rule.config));
+ const duplicates = uniquenessRule
+ ? await $findDuplicatesInScope(
+ {
+ projectId,
+ environment,
+ secretPath,
+ secrets,
+ scope: uniquenessRule.scope,
+ canAccessLocation,
+ generateSecretBlindIndex
+ },
+ tx
+ )
+ : {};
+
const { expandSecretReferences } = expandSecretReferencesFactory({
projectId,
folderDAL,
@@ -443,7 +585,8 @@ export const secretValidationRuleServiceFactory = ({
environment,
secretKey: secret.key
}),
- ...(secret.secretId && { previousValues: previousValuesBySecretId[secret.secretId] })
+ ...(secret.secretId && { previousValues: previousValuesBySecretId[secret.secretId] }),
+ ...(duplicates[secret.key] && { duplicateOf: duplicates[secret.key] })
}))
);
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
index 542584f604..4d85a3ed3e 100644
--- a/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts
+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts
@@ -129,6 +129,11 @@ export type TValidateSecretsDTO = {
envId: string;
secretPath: string;
secrets: TSecretToValidate[];
+ /**
+ * Whether the writer may read a location a duplicate value was found in. Without it the violation
+ * would name a secret they cannot see, telling them where a value they hold is also used.
+ */
+ canAccessLocation?: (environment: string, secretPath: string) => boolean;
};
export type TFindConstraintsForGeneratedSecretDTO = {
diff --git a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts
index ab0e92dcac..5baa64d8d4 100644
--- a/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts
+++ b/backend/src/services/secret-validation-rule/static-secrets/static-secrets-rule-fns.ts
@@ -2,10 +2,20 @@ import { CONSTRAINT_LABELS, evaluateConstraints, TConstraintViolation } from "..
import { ConstraintKind, ConstraintTarget } from "../secret-validation-rule-enums";
import { TStaticSecretsRuleConfig } from "./static-secrets-rule-types";
+/** Where a value that another secret already holds was found, once the service has looked it up. */
+export type TDuplicateSecret = {
+ key: string;
+ environment: string;
+ secretPath: string;
+ /** Set when the writer cannot read the location, so the message has to stay vague. */
+ hidden?: boolean;
+};
+
export type TSecretToValidate = {
key: string;
value?: string;
previousValues?: string[];
+ duplicateOf?: TDuplicateSecret;
};
export const evaluateStaticSecretConstraints = (
@@ -40,5 +50,17 @@ export const evaluateStaticSecretConstraints = (
});
}
+ const { duplicateOf } = secret;
+ if (config.valueConstraints.reusePrevention?.otherSecrets && duplicateOf) {
+ violations.push({
+ kind: ConstraintKind.ReuseOtherSecrets,
+ label: CONSTRAINT_LABELS[ConstraintKind.ReuseOtherSecrets],
+ // Naming a secret the writer cannot read would leak where a value they do know is also used.
+ message: duplicateOf.hidden
+ ? "value is already used by another secret in this project"
+ : `value is already used by secret "${duplicateOf.key}" in environment "${duplicateOf.environment}" at path "${duplicateOf.secretPath}"`
+ });
+ }
+
return violations;
};
diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.ts
index 3ab59728a1..44918c8aa5 100644
--- a/frontend/src/hooks/api/projects/types.ts
+++ b/frontend/src/hooks/api/projects/types.ts
@@ -43,6 +43,7 @@ export type Project = {
showSnapshotsLegacy: boolean;
secretDetectionIgnoreValues: string[];
enforceEncryptedSecretManagerSecretMetadata: boolean;
+ secretBlindIndexEnabled: boolean;
isLegacyAdditionalPrivilegesEnabled: boolean;
};
diff --git a/frontend/src/hooks/api/secretValidationRules/types.ts b/frontend/src/hooks/api/secretValidationRules/types.ts
index ff9e58c266..b47e41b18b 100644
--- a/frontend/src/hooks/api/secretValidationRules/types.ts
+++ b/frontend/src/hooks/api/secretValidationRules/types.ts
@@ -48,6 +48,7 @@ export type TConstraints = {
export type TReusePrevention = {
previousVersions?: number;
+ otherSecrets?: boolean;
};
export type TValueConstraints = TConstraints & {
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx
index ab18e663a6..387efebba2 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/ConstraintCard.tsx
@@ -21,6 +21,7 @@ import {
CONSTRAINT_VALUE_LABELS,
ConstraintTarget,
ConstraintType,
+ isValuelessConstraint,
MAX_PREVENT_VALUE_REUSE_VERSIONS,
RuleType,
TRuleForm
@@ -52,6 +53,9 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {
const Icon = constraintOption?.icon;
const placeholder = constraintOption?.placeholder;
const isPreventValueReuse = constraintType === ConstraintType.PreventValueReuse;
+ const isValueless = isValuelessConstraint(constraintType);
+ // Both of these only ever apply to the secret value, so there is nothing to choose.
+ const hasFixedTarget = isPreventValueReuse || isValueless;
const isNumericInput =
constraintType === ConstraintType.MinLength ||
constraintType === ConstraintType.MaxLength ||
@@ -75,7 +79,7 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {
<p className="mt-1.5 text-xs text-muted">{constraintOption.cardDescription}</p>
)}
- <div className="mt-3 grid grid-cols-2 gap-3">
+ <div className={`mt-3 grid gap-3 ${isValueless ? "grid-cols-1" : "grid-cols-2"}`}>
{(() => {
if (isGeneratedCredentialRule) {
return (
@@ -85,7 +89,7 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {
</div>
);
}
- if (isPreventValueReuse) {
+ if (hasFixedTarget) {
return (
<div className="flex flex-col gap-1">
<label className="text-xs font-medium text-muted">Applies to</label>
@@ -124,44 +128,46 @@ export const ConstraintCard = ({ index, onRemove }: Props) => {
</div>
);
})()}
- <div className="flex flex-col gap-1">
- <label className="text-xs font-medium text-muted">
- <div className="flex items-center gap-1">
- {CONSTRAINT_VALUE_LABELS[constraintType]}
- {constraintType === ConstraintType.PreventValueReuse && (
- <Tooltip>
- <TooltipTrigger asChild>
- <InfoIcon className="ml-1 size-3.5 text-muted" />
- </TooltipTrigger>
- <TooltipContent side="left" align="start" className="max-w-xs">
- <p className="text-sm">
- When a secret is updated, its new value is validated against the specified
- number of prior versions.
- </p>
- <p className="mt-2 text-xs text-muted">Maximum: 25 versions</p>
- </TooltipContent>
- </Tooltip>
- )}
- </div>
- </label>
- <Controller
- control={control}
- name={`enforcement.constraints.${index}.value`}
- render={({ field, fieldState: { error } }) => (
- <div>
- <Input
- {...field}
- type={isNumericInput ? "number" : "text"}
- min={isPreventValueReuse ? 1 : undefined}
- max={isPreventValueReuse ? MAX_PREVENT_VALUE_REUSE_VERSIONS : undefined}
- placeholder={placeholder?.toString() || undefined}
- isError={Boolean(error)}
- />
- {error?.message && <p className="mt-1 text-xs text-danger">{error.message}</p>}
+ {!isValueless && (
+ <div className="flex flex-col gap-1">
+ <label className="text-xs font-medium text-muted">
+ <div className="flex items-center gap-1">
+ {CONSTRAINT_VALUE_LABELS[constraintType]}
+ {constraintType === ConstraintType.PreventValueReuse && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="ml-1 size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent side="left" align="start" className="max-w-xs">
+ <p className="text-sm">
+ When a secret is updated, its new value is validated against the specified
+ number of prior versions.
+ </p>
+ <p className="mt-2 text-xs text-muted">Maximum: 25 versions</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
</div>
- )}
- />
- </div>
+ </label>
+ <Controller
+ control={control}
+ name={`enforcement.constraints.${index}.value`}
+ render={({ field, fieldState: { error } }) => (
+ <div>
+ <Input
+ {...field}
+ type={isNumericInput ? "number" : "text"}
+ min={isPreventValueReuse ? 1 : undefined}
+ max={isPreventValueReuse ? MAX_PREVENT_VALUE_REUSE_VERSIONS : undefined}
+ 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/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts
index 9bb5e74963..aef00a0dc4 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretValidationRulesSection/SecretValidationRulesSection.utils.ts
@@ -1,4 +1,5 @@
import {
+ CopyIcon,
DatabaseIcon,
HashIcon,
HistoryIcon,
@@ -34,7 +35,8 @@ export enum ConstraintType {
RegexPattern = "regex-pattern",
RequiredPrefix = "required-prefix",
RequiredSuffix = "required-suffix",
- PreventValueReuse = "prevent-value-reuse"
+ PreventValueReuse = "prevent-value-reuse",
+ PreventDuplicateValues = "prevent-duplicate-values"
}
export enum ConstraintTarget {
@@ -96,6 +98,15 @@ export const CONSTRAINT_OPTIONS: {
placeholder: 10,
icon: HistoryIcon,
allowedTargets: [ConstraintTarget.SecretValue]
+ },
+ {
+ type: ConstraintType.PreventDuplicateValues,
+ label: "Prevent Duplicate Values",
+ description: "Prevent reusing a value another secret holds",
+ cardDescription:
+ "A secret cannot be given a value that another secret in this rule's scope already holds. Requires secret blind indexing on the project.",
+ icon: CopyIcon,
+ allowedTargets: [ConstraintTarget.SecretValue]
}
];
@@ -105,7 +116,8 @@ export const CONSTRAINT_VALUE_LABELS: Record<ConstraintType, string> = {
[ConstraintType.RegexPattern]: "Pattern",
[ConstraintType.RequiredPrefix]: "Text",
[ConstraintType.RequiredSuffix]: "Text",
- [ConstraintType.PreventValueReuse]: "Previous versions"
+ [ConstraintType.PreventValueReuse]: "Previous versions",
+ [ConstraintType.PreventDuplicateValues]: "Enabled"
};
export const CONSTRAINT_TYPE_LABELS: Record<ConstraintType, string> = {
@@ -114,7 +126,8 @@ export const CONSTRAINT_TYPE_LABELS: Record<ConstraintType, string> = {
[ConstraintType.RegexPattern]: "Regex Pattern",
[ConstraintType.RequiredPrefix]: "Required Prefix",
[ConstraintType.RequiredSuffix]: "Required Suffix",
- [ConstraintType.PreventValueReuse]: "Prevent Value Reuse"
+ [ConstraintType.PreventValueReuse]: "Prevent Value Reuse",
+ [ConstraintType.PreventDuplicateValues]: "Prevent Duplicate Values"
};
export const RULE_TYPE_LABELS: Record<RuleType, string> = {
@@ -167,30 +180,42 @@ export const SECRET_ROTATION_PROVIDER_OPTIONS: TProviderOption<SecretRotationRul
}
];
-// PreventValueReuse is intentionally static-secret-only. For dynamic secrets
+// Both reuse checks are intentionally static-secret-only. For dynamic secrets
// each lease is independent so reuse has no meaning; for rotations we drive
// uniqueness through password generation (length/regex) rather than failing a
-// rotation at issue time because the generator happened to land on a prior
-// value.
+// rotation at issue time because the generator happened to land on a value
+// that is already in use.
export const DYNAMIC_SECRET_RULE_DISALLOWED_CONSTRAINTS: ConstraintType[] = [
- ConstraintType.PreventValueReuse
+ ConstraintType.PreventValueReuse,
+ ConstraintType.PreventDuplicateValues
];
export const SECRET_ROTATION_RULE_DISALLOWED_CONSTRAINTS: ConstraintType[] = [
- ConstraintType.PreventValueReuse
+ ConstraintType.PreventValueReuse,
+ ConstraintType.PreventDuplicateValues
];
export const MAX_PREVENT_VALUE_REUSE_VERSIONS = MAX_PREVENT_DUPLICATE_SECRET_VALUE_VERSIONS;
+// Switching this one on is the whole setting, so the form carries no value alongside it.
+export const isValuelessConstraint = (type: ConstraintType) =>
+ type === ConstraintType.PreventDuplicateValues;
+
export const constraintSchema = z
.object({
type: z.nativeEnum(ConstraintType),
appliesTo: z.nativeEnum(ConstraintTarget),
value: z.string()
})
- .refine((c) => c.type === ConstraintType.PreventValueReuse || c.value.length > 0, {
- message: "Value is required",
- path: ["value"]
- })
+ .refine(
+ (c) =>
+ c.type === ConstraintType.PreventValueReuse ||
+ isValuelessConstraint(c.type) ||
+ c.value.length > 0,
+ {
+ message: "Value is required",
+ path: ["value"]
+ }
+ )
.superRefine((c, ctx) => {
if (c.type === ConstraintType.PreventValueReuse) {
const num = Number(c.value);
@@ -305,16 +330,22 @@ export const groupConstraintsByTarget = (constraints: TConstraint[]) => {
constraints.forEach(({ type, appliesTo, value }) => {
const current = grouped[appliesTo] ?? {};
- grouped[appliesTo] =
- type === ConstraintType.PreventValueReuse
- ? {
- ...current,
- reusePrevention: { ...current.reusePrevention, previousVersions: Number(value) }
- }
- : {
- ...current,
- [CONSTRAINT_FIELDS[type]]: NUMERIC_CONSTRAINTS.includes(type) ? Number(value) : value
- };
+ if (type === ConstraintType.PreventValueReuse) {
+ grouped[appliesTo] = {
+ ...current,
+ reusePrevention: { ...current.reusePrevention, previousVersions: Number(value) }
+ };
+ } else if (type === ConstraintType.PreventDuplicateValues) {
+ grouped[appliesTo] = {
+ ...current,
+ reusePrevention: { ...current.reusePrevention, otherSecrets: true }
+ };
+ } else {
+ grouped[appliesTo] = {
+ ...current,
+ [CONSTRAINT_FIELDS[type]]: NUMERIC_CONSTRAINTS.includes(type) ? Number(value) : value
+ };
+ }
});
return grouped;
@@ -330,14 +361,17 @@ export const flattenConstraints = (
.filter(([, value]) => value !== undefined)
.map(([field, value]) => ({ type: CONSTRAINT_TYPES[field], appliesTo, value: String(value) }));
- if (reusePrevention?.previousVersions === undefined) return flattened;
-
- return [
- ...flattened,
- {
+ if (reusePrevention?.previousVersions !== undefined) {
+ flattened.push({
type: ConstraintType.PreventValueReuse,
appliesTo,
value: String(reusePrevention.previousVersions)
- }
- ];
+ });
+ }
+
+ if (reusePrevention?.otherSecrets) {
+ flattened.push({ type: ConstraintType.PreventDuplicateValues, appliesTo, value: "" });
+ }
+
+ return flattened;
};