Skip to content

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

1.9 KB
Raw Blame
import {
  CONSTRAINT_LABELS,
  evaluateConstraints,
  TConstraintViolation,
  TDuplicateSecret
} from "../secret-validation-rule-constraint-fns";
import { ConstraintKind, ConstraintTarget } from "../secret-validation-rule-enums";
import { TStaticSecretsRuleConfig } from "./static-secrets-rule-types";

export type TSecretToValidate = {
  key: string;
  value?: string;
  previousValues?: string[];
  duplicateOf?: TDuplicateSecret;
};

export const evaluateStaticSecretConstraints = (
  config: TStaticSecretsRuleConfig,
  secret: TSecretToValidate
): TConstraintViolation[] => {
  const violations = config.keyConstraints
    ? evaluateConstraints({
        constraints: config.keyConstraints,
        target: ConstraintTarget.SecretKey,
        value: secret.key
      })
    : [];

  // A key-only rename carries no value, so there is nothing to hold the value constraints against.
  if (!config.valueConstraints || secret.value === undefined) return violations;

  violations.push(
    ...evaluateConstraints({
      constraints: config.valueConstraints,
      target: ConstraintTarget.SecretValue,
      value: secret.value
    })
  );

  const versionCount = config.valueConstraints.uniqueAcrossLastVersions;
  if (versionCount !== undefined && secret.previousValues?.slice(0, versionCount).includes(secret.value)) {
    violations.push({
      kind: ConstraintKind.ReusePreviousVersions,
      label: CONSTRAINT_LABELS[ConstraintKind.ReusePreviousVersions],
      message: `value cannot reuse any of the last ${versionCount} values`
    });
  }

  const { duplicateOf } = secret;
  if (config.valueConstraints.uniqueWithinScope && duplicateOf) {
    violations.push({
      kind: ConstraintKind.ReuseOtherSecretsInScope,
      label: CONSTRAINT_LABELS[ConstraintKind.ReuseOtherSecretsInScope],
      message: "value is already used by another secret in this project",
      duplicateOf
    });
  }

  return violations;
};