Skip to content

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

6.8 KB
Raw Blame
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
import { crypto } from "@app/lib/crypto/cryptography";
import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm } from "@app/lib/crypto/sign/types";
import { BadRequestError } from "@app/lib/errors";

import { KmsKeyUsage } from "./kms-types";

export const MIN_HMAC_IMPORT_KEY_BYTE_LENGTH = 16;
export const MAX_HMAC_IMPORT_KEY_BYTE_LENGTH = 1024;

/**
 * The row holding the *currently active* wrapped root key.
 *
 * Not "the config row" any more: it is a compatibility handle. An app version predating rotation looks
 * this id up and knows nothing about staged or retained rows, so keeping the active key here is what
 * lets it boot. New code finds rows by trial decryption.
 */
export const KMS_ROOT_CONFIG_UUID = "00000000-0000-0000-0000-000000000000";

/** Fixed so a concurrent seed is a PK conflict rather than a second row. */
export const KMS_LEGACY_ENCRYPTION_KEY_UUID = "00000000-0000-0000-0000-000000000001";

/**
 * The AES key a given environment resolves to.
 *
 * Single-sourced deliberately: a rotation has to predict exactly what a booting instance will compute
 * from the value it hands the operator, and a second copy of this rule would drift into a key that does
 * not boot. Callers that need the prediction pass a simulated environment rather than reimplementing it.
 */
export const resolveInstanceEncryptionKeyBuffer = (envCfg: {
  ENCRYPTION_KEY?: string;
  ROOT_ENCRYPTION_KEY?: string;
}) => {
  const encryptionKey = envCfg.ENCRYPTION_KEY || envCfg.ROOT_ENCRYPTION_KEY;
  if (!encryptionKey) {
    throw new BadRequestError({
      message: "Instance encryption key not found. Did you set the ENCRYPTION_KEY environment variable?"
    });
  }

  const isUtf8Key = Boolean(envCfg.ENCRYPTION_KEY);
  const buffer = Buffer.from(encryptionKey, isUtf8Key ? "utf8" : "base64");
  if (buffer.length !== 32) {
    throw new BadRequestError({
      message: `The configured encryption key resolves to ${buffer.length} bytes, but 32 are required. Generate one with '${
        isUtf8Key ? "openssl rand -hex 16" : "openssl rand -base64 32"
      }'.`
    });
  }

  return buffer;
};

const WRAPPED_KEY_LABEL_BYTES = 32;

const hashWrappedKeyLabel = (label: string) => crypto.nativeCrypto.createHash("sha256").update(label).digest();

// The data key wrap takes no context, so the label travels inside the payload: a key copied onto a row with another
// label fails to open there instead of being handed out. The layout, sha256(label) || key, is what Agent Vault
// session keys have always used, so existing keys keep opening.
export const buildWrappedKeyPayload = (label: string, key: Buffer) => Buffer.concat([hashWrappedKeyLabel(label), key]);

// Null when the payload wasn't wrapped for this label or isn't the expected size; the caller decides what that means.
export const openWrappedKey = ({ label, payload, keyBytes }: { label: string; payload: Buffer; keyBytes: number }) => {
  const belongs =
    payload.length === WRAPPED_KEY_LABEL_BYTES + keyBytes &&
    crypto.nativeCrypto.timingSafeEqual(payload.subarray(0, WRAPPED_KEY_LABEL_BYTES), hashWrappedKeyLabel(label));
  return belongs ? payload.subarray(WRAPPED_KEY_LABEL_BYTES) : null;
};

const KEK_LABEL_DOMAIN = "infisical:kek-fingerprint:v1";

/**
 * A label, never a lookup key: it lets an operator match a restored dump against an archived key.
 * Derived from the key, so an operator holding an archived key can recompute it and confirm the match.
 * Truncated SHA-256 over a 128-bit-minimum key is not reversible, so it is safe to log and expose.
 */
export const getKekLabel = (keyBuffer: Buffer) =>
  crypto.nativeCrypto.createHash("sha256").update(KEK_LABEL_DOMAIN).update(keyBuffer).digest("hex").slice(0, 32);

export const getByteLengthForSymmetricEncryptionAlgorithm = (encryptionAlgorithm: SymmetricKeyAlgorithm) => {
  switch (encryptionAlgorithm) {
    case SymmetricKeyAlgorithm.AES_GCM_128:
      return 16;
    case SymmetricKeyAlgorithm.AES_GCM_256:
    default:
      return 32;
  }
};

type TClassicalKeyShape = {
  keyType: string;
  modulusLength?: number;
  namedCurve?: string;
  label: string;
};

const CLASSICAL_KEY_SHAPES: Partial<Record<AsymmetricKeyAlgorithm, TClassicalKeyShape>> = {
  [AsymmetricKeyAlgorithm.RSA_4096]: { keyType: "rsa", modulusLength: 4096, label: "an RSA 4096-bit key" },
  [AsymmetricKeyAlgorithm.ECC_NIST_P256]: { keyType: "ec", namedCurve: "prime256v1", label: "an EC P-256 key" },
  [AsymmetricKeyAlgorithm.ECC_NIST_P384]: { keyType: "ec", namedCurve: "secp384r1", label: "an EC P-384 key" },
  [AsymmetricKeyAlgorithm.ECC_NIST_P521]: { keyType: "ec", namedCurve: "secp521r1", label: "an EC P-521 key" },
  [AsymmetricKeyAlgorithm.ED25519]: { keyType: "ed25519", label: "an Ed25519 key" }
};

export const validateClassicalKeyMaterial = (key: Buffer, algorithm: AsymmetricKeyAlgorithm) => {
  const expected = CLASSICAL_KEY_SHAPES[algorithm];
  if (!expected) return;

  const keyObj = crypto.nativeCrypto.createPrivateKey({ key, format: "pem", type: "pkcs8" });
  const details = keyObj.asymmetricKeyDetails;
  const matches =
    keyObj.asymmetricKeyType === expected.keyType &&
    (expected.modulusLength === undefined || details?.modulusLength === expected.modulusLength) &&
    (expected.namedCurve === undefined || details?.namedCurve === expected.namedCurve);

  if (!matches) {
    throw new BadRequestError({
      message: `Key material does not match the declared algorithm. Expected ${expected.label}.`
    });
  }
};

export const verifyKeyTypeAndAlgorithm = (
  keyUsage: KmsKeyUsage,
  algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm,
  extra?: {
    forceType?: KmsKeyUsage;
  }
) => {
  if (extra?.forceType && keyUsage !== extra.forceType) {
    throw new BadRequestError({
      message: `Unsupported key type, expected ${extra.forceType} but got ${keyUsage}`
    });
  }

  if (keyUsage === KmsKeyUsage.ENCRYPT_DECRYPT) {
    if (!Object.values(SymmetricKeyAlgorithm).includes(algorithm as SymmetricKeyAlgorithm)) {
      throw new BadRequestError({
        message: `Unsupported encryption algorithm for encrypt/decrypt key: ${algorithm as string}`
      });
    }

    return true;
  }

  if (keyUsage === KmsKeyUsage.SIGN_VERIFY) {
    if (!Object.values(AsymmetricKeyAlgorithm).includes(algorithm as AsymmetricKeyAlgorithm)) {
      throw new BadRequestError({
        message: `Unsupported sign/verify algorithm for sign/verify key: ${algorithm as string}`
      });
    }

    return true;
  }

  if (keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
    if (!Object.values(HmacAlgorithm).includes(algorithm as HmacAlgorithm)) {
      throw new BadRequestError({
        message: `Unsupported HMAC algorithm for generate/verify MAC key: ${algorithm as string}`
      });
    }

    return true;
  }

  throw new BadRequestError({
    message: `Unsupported key type: ${keyUsage as string}`
  });
};