Skip to content

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

feat(kms): add encrypt-decrypt key rotation

bernie-gf8717a72608f
diff --git a/backend/scripts/seed-gamma-fixtures.ts b/backend/scripts/seed-gamma-fixtures.ts
index 136a04f91d..9103cd51d1 100644
--- a/backend/scripts/seed-gamma-fixtures.ts
+++ b/backend/scripts/seed-gamma-fixtures.ts
@@ -37,6 +37,7 @@ import { getConfig, getHsmConfig, initEnvConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { initLogger, logger } from "@app/lib/logger";
import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";
+import { internalKmsKeyVersionDALFactory } from "@app/services/kms/internal-kms-key-version-dal";
import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
import { kmsServiceFactory } from "@app/services/kms/kms-service";
@@ -145,12 +146,14 @@ const main = async () => {
// even though it's only used on the project-scoped path.
const kmsDAL = kmskeyDALFactory(knex);
const internalKmsDAL = internalKmsDALFactory(knex);
+ const internalKmsKeyVersionDAL = internalKmsKeyVersionDALFactory(knex);
const orgDAL = orgDALFactory(knex);
const projectDAL = projectDALFactory(knex);
const kmsService = kmsServiceFactory({
kmsRootConfigDAL,
kmsDAL,
internalKmsDAL,
+ internalKmsKeyVersionDAL,
orgDAL,
projectDAL,
hsmService,
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 7ebc208a22..b171f790cf 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -271,6 +271,9 @@ import {
TInternalCertificateAuthoritiesUpdate,
TInternalKms,
TInternalKmsInsert,
+ TInternalKmsKeyVersion,
+ TInternalKmsKeyVersionInsert,
+ TInternalKmsKeyVersionUpdate,
TInternalKmsUpdate,
TKeyValueStore,
TKeyValueStoreInsert,
@@ -1458,6 +1461,11 @@ declare module "knex/types/tables" {
TKmsRootConfigUpdate
>;
[TableName.InternalKms]: KnexOriginal.CompositeTableType<TInternalKms, TInternalKmsInsert, TInternalKmsUpdate>;
+ [TableName.InternalKmsKeyVersion]: KnexOriginal.CompositeTableType<
+ TInternalKmsKeyVersion,
+ TInternalKmsKeyVersionInsert,
+ TInternalKmsKeyVersionUpdate
+ >;
[TableName.ExternalKms]: KnexOriginal.CompositeTableType<TExternalKms, TExternalKmsInsert, TExternalKmsUpdate>;
[TableName.KmsKey]: KnexOriginal.CompositeTableType<TKmsKeys, TKmsKeysInsert, TKmsKeysUpdate>;
[TableName.KmsKeyVersion]: KnexOriginal.CompositeTableType<
diff --git a/backend/src/db/migrations/20260609000000_internal-kms-key-version-unique-index.ts b/backend/src/db/migrations/20260609000000_internal-kms-key-version-unique-index.ts
new file mode 100644
index 0000000000..8e39c58e95
--- /dev/null
+++ b/backend/src/db/migrations/20260609000000_internal-kms-key-version-unique-index.ts
@@ -0,0 +1,21 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { dropConstraintIfExists } from "./utils/dropConstraintIfExists";
+
+const UNIQUE_CONSTRAINT_NAME = "internal_kms_key_version_internalkmsid_version_unique";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.InternalKmsKeyVersion)) {
+ await knex.schema.alterTable(TableName.InternalKmsKeyVersion, (t) => {
+ // also serves as the FK index on internalKmsId (leftmost column)
+ t.unique(["internalKmsId", "version"], { indexName: UNIQUE_CONSTRAINT_NAME });
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.InternalKmsKeyVersion)) {
+ await dropConstraintIfExists(TableName.InternalKmsKeyVersion, UNIQUE_CONSTRAINT_NAME, knex);
+ }
+}
diff --git a/backend/src/db/migrations/utils/services.ts b/backend/src/db/migrations/utils/services.ts
index 09a04d0b28..4b9d8a087f 100644
--- a/backend/src/db/migrations/utils/services.ts
+++ b/backend/src/db/migrations/utils/services.ts
@@ -12,6 +12,7 @@ import { BadRequestError } from "@app/lib/errors";
import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { identityDALFactory } from "@app/services/identity/identity-dal";
import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";
+import { internalKmsKeyVersionDALFactory } from "@app/services/kms/internal-kms-key-version-dal";
import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
import { kmsServiceFactory } from "@app/services/kms/kms-service";
@@ -61,6 +62,7 @@ export const getMigrationEncryptionServices = async ({ envConfig, db, keyStore }
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
const kmsDAL = kmskeyDALFactory(db);
const internalKmsDAL = internalKmsDALFactory(db);
+ const internalKmsKeyVersionDAL = internalKmsKeyVersionDALFactory(db);
const additionalPrivilegeDAL = additionalPrivilegeDALFactory(db);
const groupDAL = groupDALFactory(db);
@@ -117,6 +119,7 @@ export const getMigrationEncryptionServices = async ({ envConfig, db, keyStore }
kmsRootConfigDAL,
kmsDAL,
internalKmsDAL,
+ internalKmsKeyVersionDAL,
orgDAL,
projectDAL,
hsmService,
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index c3260d5011..7b8e175d0a 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -99,6 +99,7 @@ export * from "./integration-auths";
export * from "./integrations";
export * from "./internal-certificate-authorities";
export * from "./internal-kms";
+export * from "./internal-kms-key-version";
export * from "./key-value-store";
export * from "./kmip-client-certificates";
export * from "./kmip-clients";
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 01bccd72ae..52958227f6 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -530,6 +530,7 @@ export enum EventType {
INTEGRATION_SYNCED = "integration-synced",
CREATE_CMEK = "create-cmek",
UPDATE_CMEK = "update-cmek",
+ ROTATE_CMEK = "rotate-cmek",
DELETE_CMEK = "delete-cmek",
GET_CMEKS = "get-cmeks",
GET_CMEK = "get-cmek",
@@ -4321,6 +4322,14 @@ interface UpdateCmekEvent {
};
}
+interface RotateCmekEvent {
+ type: EventType.ROTATE_CMEK;
+ metadata: {
+ keyId: string;
+ version: number;
+ };
+}
+
interface GetCmeksEvent {
type: EventType.GET_CMEKS;
metadata: {
@@ -7727,6 +7736,7 @@ export type Event =
| IntegrationSyncedEvent
| CreateCmekEvent
| UpdateCmekEvent
+ | RotateCmekEvent
| DeleteCmekEvent
| GetCmekEvent
| GetCmeksEvent
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 8492e44a37..27a9abed7b 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2490,6 +2490,9 @@ export const KMS = {
description: "The updated description of this key.",
isDisabled: "The flag to enable or disable this key."
},
+ ROTATE_KEY: {
+ keyId: "The ID of the key to be rotated."
+ },
DELETE_KEY: {
keyId: "The ID of the key to be deleted."
},
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e5470935f0..9d6929a138 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -374,6 +374,7 @@ import { integrationServiceFactory } from "@app/services/integration/integration
import { integrationAuthDALFactory } from "@app/services/integration-auth/integration-auth-dal";
import { integrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service";
import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";
+import { internalKmsKeyVersionDALFactory } from "@app/services/kms/internal-kms-key-version-dal";
import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";
import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
import { kmsServiceFactory } from "@app/services/kms/kms-service";
@@ -707,6 +708,7 @@ export const registerRoutes = async (
const kmsDAL = kmskeyDALFactory(db);
const internalKmsDAL = internalKmsDALFactory(db);
+ const internalKmsKeyVersionDAL = internalKmsKeyVersionDALFactory(db);
const externalKmsDAL = externalKmsDALFactory(db);
const slackIntegrationDAL = slackIntegrationDALFactory(db);
@@ -889,6 +891,7 @@ export const registerRoutes = async (
kmsRootConfigDAL,
kmsDAL,
internalKmsDAL,
+ internalKmsKeyVersionDAL,
orgDAL,
projectDAL,
hsmService,
diff --git a/backend/src/server/routes/v1/cmek-router.ts b/backend/src/server/routes/v1/cmek-router.ts
index fc88317bed..b8fa1067db 100644
--- a/backend/src/server/routes/v1/cmek-router.ts
+++ b/backend/src/server/routes/v1/cmek-router.ts
@@ -215,6 +215,53 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
}
});
+ // rotate KMS key
+ server.route({
+ method: "POST",
+ url: "/keys/:keyId/rotate",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "rotateKmsKey",
+ tags: [ApiDocsTags.KmsKeys],
+ description:
+ "Rotate KMS key. Generates new key material for the key and increments its version. Previous key material is retained so existing ciphertexts remain decryptable; new encrypt operations use the new material. Only supported for encrypt-decrypt keys.",
+ params: z.object({
+ keyId: z.string().uuid().describe(KMS.ROTATE_KEY.keyId)
+ }),
+ response: {
+ 200: z.object({
+ key: CmekSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const {
+ params: { keyId },
+ permission
+ } = req;
+
+ const cmek = await server.services.cmek.rotateCmekById(keyId, permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: cmek.projectId!,
+ event: {
+ type: EventType.ROTATE_CMEK,
+ metadata: {
+ keyId,
+ version: cmek.version
+ }
+ }
+ });
+
+ return { key: cmek };
+ }
+ });
+
// delete KMS key
server.route({
method: "DELETE",
diff --git a/backend/src/services/cmek/cmek-service.ts b/backend/src/services/cmek/cmek-service.ts
index 48a2b42640..e1cfe24192 100644
--- a/backend/src/services/cmek/cmek-service.ts
+++ b/backend/src/services/cmek/cmek-service.ts
@@ -125,6 +125,34 @@ export const cmekServiceFactory = ({
}
};
+ const rotateCmekById = async (keyId: string, actor: OrgServiceActor) => {
+ const key = await kmsDAL.findCmekById(keyId);
+
+ if (!key) throw new NotFoundError({ message: `Key with ID ${keyId} not found` });
+
+ if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });
+
+ if (key.isDisabled) throw new BadRequestError({ message: "Key is disabled" });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: key.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.KMS
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Edit, ProjectPermissionSub.Cmek);
+
+ const { version } = await kmsService.rotateKmsKey(keyId);
+
+ return {
+ ...key,
+ version
+ };
+ };
+
const deleteCmekById = async (keyId: string, actor: OrgServiceActor) => {
const key = await kmsDAL.findCmekById(keyId);
@@ -606,6 +634,7 @@ export const cmekServiceFactory = ({
return {
createCmek,
updateCmekById,
+ rotateCmekById,
deleteCmekById,
listCmeksByProjectId,
cmekEncrypt,
diff --git a/backend/src/services/kms/internal-kms-dal.ts b/backend/src/services/kms/internal-kms-dal.ts
index f038fc3dbb..159c84fb15 100644
--- a/backend/src/services/kms/internal-kms-dal.ts
+++ b/backend/src/services/kms/internal-kms-dal.ts
@@ -1,10 +1,23 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
export type TInternalKmsDALFactory = ReturnType<typeof internalKmsDALFactory>;
export const internalKmsDALFactory = (db: TDbClient) => {
const internalKmsOrm = ormify(db, TableName.InternalKms);
- return internalKmsOrm;
+
+ const findByKmsKeyIdForUpdate = async (kmsKeyId: string, tx: Knex) => {
+ try {
+ const doc = await tx(TableName.InternalKms).where({ kmsKeyId }).forUpdate().first();
+ return doc;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find by kms key id for update" });
+ }
+ };
+
+ return { ...internalKmsOrm, findByKmsKeyIdForUpdate };
};
diff --git a/backend/src/services/kms/internal-kms-key-version-dal.ts b/backend/src/services/kms/internal-kms-key-version-dal.ts
new file mode 100644
index 0000000000..e64834269f
--- /dev/null
+++ b/backend/src/services/kms/internal-kms-key-version-dal.ts
@@ -0,0 +1,10 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TInternalKmsKeyVersionDALFactory = ReturnType<typeof internalKmsKeyVersionDALFactory>;
+
+export const internalKmsKeyVersionDALFactory = (db: TDbClient) => {
+ const internalKmsKeyVersionOrm = ormify(db, TableName.InternalKmsKeyVersion);
+ return internalKmsKeyVersionOrm;
+};
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index fec6c1b0e0..2c741e8584 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -34,6 +34,7 @@ import {
import { TOrgDALFactory } from "../org/org-dal";
import { TProjectDALFactory } from "../project/project-dal";
import { TInternalKmsDALFactory } from "./internal-kms-dal";
+import { TInternalKmsKeyVersionDALFactory } from "./internal-kms-key-version-dal";
import { TKmsKeyDALFactory } from "./kms-key-dal";
import { TKmsRootConfigDALFactory } from "./kms-root-config-dal";
import {
@@ -61,7 +62,8 @@ type TKmsServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findById" | "updateById" | "transaction">;
orgDAL: Pick<TOrgDALFactory, "findById" | "updateById" | "transaction">;
kmsRootConfigDAL: Pick<TKmsRootConfigDALFactory, "findById" | "create" | "updateById" | "transaction">;
- internalKmsDAL: Pick<TInternalKmsDALFactory, "create">;
+ internalKmsDAL: Pick<TInternalKmsDALFactory, "create" | "findByKmsKeyIdForUpdate" | "updateById">;
+ internalKmsKeyVersionDAL: Pick<TInternalKmsKeyVersionDALFactory, "create" | "find">;
hsmService: THsmServiceFactory;
envConfig: Pick<TEnvConfig, "ENCRYPTION_KEY" | "ROOT_ENCRYPTION_KEY">;
};
@@ -71,6 +73,27 @@ export type TKmsServiceFactory = ReturnType<typeof kmsServiceFactory>;
// akhilmhdh: Don't edit this value. This is measured for blob concatination in kms
const KMS_VERSION = "v01";
const KMS_VERSION_BLOB_LENGTH = 3;
+// v02 blobs additionally embed the key material version that encrypted them: [ciphertext][4-byte BE version]["v02"]
+// Written only for keys with version > 1 so never-rotated keys keep producing byte-identical v01 blobs.
+const KMS_VERSION_V2 = "v02";
+const KMS_KEY_VERSION_BLOB_LENGTH = 4;
+// AES-GCM output is at minimum a 12-byte IV + 16-byte auth tag (empty plaintext). A real v02 blob therefore
+// cannot be shorter than this plus its 4-byte version + 3-byte suffix; anything shorter ending in "v02" is
+// malformed/attacker input and must fall through to the legacy path rather than reading out of bounds.
+const MIN_AES_GCM_BLOB_LENGTH = 12 + 16;
+const MIN_V02_BLOB_LENGTH = MIN_AES_GCM_BLOB_LENGTH + KMS_KEY_VERSION_BLOB_LENGTH + KMS_VERSION_BLOB_LENGTH;
+
+// Single source of truth for the cipher-blob trailer so the encode side here and the decode side in
+// decryptWithKmsKey can never drift: v1 keys get the legacy 3-byte "v01" suffix (byte-identical to pre-rotation
+// output); rotated keys get [4-byte BE keyVersion]["v02"].
+const buildKmsCipherTextBlob = (encryptedBlob: Buffer, keyVersion: number) => {
+ if (keyVersion > 1) {
+ const keyVersionBlob = Buffer.alloc(KMS_KEY_VERSION_BLOB_LENGTH);
+ keyVersionBlob.writeUInt32BE(keyVersion, 0);
+ return Buffer.concat([encryptedBlob, keyVersionBlob, Buffer.from(KMS_VERSION_V2, "utf8")]);
+ }
+ return Buffer.concat([encryptedBlob, Buffer.from(KMS_VERSION, "utf8")]);
+};
const KmsSanitizedSchema = KmsKeysSchema.extend({ isExternal: z.boolean() });
const OPENSSL_TO_KMS: Record<string, string> = Object.fromEntries(
Object.entries(KMS_TO_OPENSSL_NAME).map(([k, v]) => [v, k])
@@ -81,6 +104,7 @@ export const kmsServiceFactory = ({
kmsDAL,
kmsRootConfigDAL,
internalKmsDAL,
+ internalKmsKeyVersionDAL,
orgDAL,
projectDAL,
hsmService
@@ -159,6 +183,77 @@ export const kmsServiceFactory = ({
return doc;
};
+ /*
+ * Rotate KMS Key
+ * Archives the current key material in the key version table and generates fresh material.
+ * Old material is never deleted so existing ciphertexts stay decryptable.
+ */
+ const rotateKmsKey = async (kmsKeyId: string, tx?: Knex) => {
+ const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
+
+ // All validation reads run inside the rotation transaction (primary, not a lagging replica) so the guards
+ // and the FOR UPDATE-locked row can't drift, and the encryption algorithm used to size the new material is
+ // read from the same locked row that gets updated.
+ const dbQuery = async (db: Knex) => {
+ const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsKeyId, db);
+ if (!kmsDoc) {
+ throw new NotFoundError({ message: `KMS with ID '${kmsKeyId}' not found` });
+ }
+
+ if (kmsDoc.externalKms) {
+ throw new BadRequestError({
+ message: "Cannot rotate external KMS keys from Infisical. Rotate the key in your external provider instead."
+ });
+ }
+
+ // Reserved keys (org/project defaults) back the platform data-key paths, including the Go backend which has
+ // no v02 support. Rotation is only ever exposed for customer-managed keys; this engine-level guard prevents
+ // any present or future caller from pushing reserved-key blobs onto the v02 format.
+ if (kmsDoc.isReserved) {
+ throw new BadRequestError({ message: "Reserved Infisical-managed KMS keys cannot be rotated." });
+ }
+
+ if ((kmsDoc.keyUsage as KmsKeyUsage) !== KmsKeyUsage.ENCRYPT_DECRYPT) {
+ throw new BadRequestError({
+ message:
+ "Only encrypt-decrypt keys support rotation. Rotate sign-verify keys manually by creating a new key and updating your applications to use it."
+ });
+ }
+
+ const internalKms = await internalKmsDAL.findByKmsKeyIdForUpdate(kmsKeyId, db);
+ if (!internalKms) {
+ throw new NotFoundError({ message: `Internal KMS not found for KMS with ID '${kmsKeyId}'` });
+ }
+
+ const encryptionAlgorithm = internalKms.encryptionAlgorithm as SymmetricKeyAlgorithm;
+ const newKeyMaterial = crypto.randomBytes(getByteLengthForSymmetricEncryptionAlgorithm(encryptionAlgorithm));
+ const encryptedNewKeyMaterial = keyCipher.encrypt(newKeyMaterial, ROOT_ENCRYPTION_KEY);
+
+ // archive the current material BEFORE overwriting it; this ordering is the data-loss guard
+ await internalKmsKeyVersionDAL.create(
+ {
+ internalKmsId: internalKms.id,
+ encryptedKey: internalKms.encryptedKey,
+ version: internalKms.version
+ },
+ db
+ );
+
+ const updatedInternalKms = await internalKmsDAL.updateById(
+ internalKms.id,
+ {
+ encryptedKey: encryptedNewKeyMaterial,
+ version: internalKms.version + 1
+ },
+ db
+ );
+
+ return { id: kmsDoc.id, version: updatedInternalKms.version };
+ };
+
+ return tx ? dbQuery(tx) : kmsDAL.transaction(dbQuery);
+ };
+
const deleteInternalKms = async (kmsId: string, orgId: string, tx?: Knex) => {
const kms = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx);
if (kms.isExternal) return;
@@ -354,12 +449,82 @@ export const kmsServiceFactory = ({
// internal KMS
const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
const dataCipher = symmetricCipherService(encryptionAlgorithm);
+ const internalKmsId = kmsDoc.internalKms?.id as string;
+ const currentKeyVersion = kmsDoc.internalKms?.version as number; // NOT NULL, defaults to 1
const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
- return ({ cipherTextBlob: versionedCipherTextBlob }: Pick<TDecryptWithKmsDTO, "cipherTextBlob">) => {
+ // The current version's material lives only on internal_kms (never the archive table), so seed the cache
+ // with it. Archived versions are loaded lazily, in a single query, and only when the current material fails.
+ const keyMaterialByVersion = new Map<number, Buffer>([[currentKeyVersion, kmsKey]]);
+ let archivedVersionsLoaded = false;
+ const $loadArchivedVersions = async () => {
+ if (archivedVersionsLoaded) return;
+ // one query for all archived versions; DB errors propagate (never silently treated as a decrypt failure)
+ const archivedVersions = await internalKmsKeyVersionDAL.find({ internalKmsId }, { tx });
+ for (const archived of archivedVersions) {
+ if (!keyMaterialByVersion.has(archived.version)) {
+ keyMaterialByVersion.set(archived.version, keyCipher.decrypt(archived.encryptedKey, ROOT_ENCRYPTION_KEY));
+ }
+ }
+ archivedVersionsLoaded = true;
+ };
+
+ // Try the preferred version first (cheap, no DB), then the current material, then every archived version
+ // newest-first. Returns the plaintext, or null if no available material authenticates the blob. Trying the
+ // current material covers the export/import case where rotated material was re-imported as version 1, and
+ // trying older material covers stale-replica writers that used pre-rotation material.
+ const $tryDecryptWithAnyMaterial = async (cipherTextBlob: Buffer, preferredVersion: number) => {
+ const attempt = (material?: Buffer) => {
+ if (!material) return null;
+ try {
+ return dataCipher.decrypt(cipherTextBlob, material);
+ } catch {
+ return null; // GCM auth failure for this material; try the next candidate
+ }
+ };
+
+ const preferred = attempt(keyMaterialByVersion.get(preferredVersion));
+ if (preferred) return preferred;
+
+ const current = attempt(kmsKey);
+ if (current) return current;
+
+ await $loadArchivedVersions();
+ for (let version = currentKeyVersion - 1; version >= 1; version -= 1) {
+ const decrypted = attempt(keyMaterialByVersion.get(version));
+ if (decrypted) return decrypted;
+ }
+ return null;
+ };
+
+ return async ({ cipherTextBlob: versionedCipherTextBlob }: Pick<TDecryptWithKmsDTO, "cipherTextBlob">) => {
+ const suffix =
+ versionedCipherTextBlob.length >= KMS_VERSION_BLOB_LENGTH
+ ? versionedCipherTextBlob.subarray(-KMS_VERSION_BLOB_LENGTH).toString("utf8")
+ : "";
+
+ // v02 is recognized structurally (suffix + minimum length), never by trusting the embedded version: a blob
+ // too short to be real AES-GCM output that happens to end in "v02" is treated as legacy/garbage and falls
+ // through, so readUInt32BE can never run on a negative offset.
+ if (suffix === KMS_VERSION_V2 && versionedCipherTextBlob.length >= MIN_V02_BLOB_LENGTH) {
+ const keyVersionOffset = versionedCipherTextBlob.length - KMS_VERSION_BLOB_LENGTH - KMS_KEY_VERSION_BLOB_LENGTH;
+ const embeddedVersion = versionedCipherTextBlob.readUInt32BE(keyVersionOffset);
+ const cipherTextBlob = versionedCipherTextBlob.subarray(0, keyVersionOffset);
+
+ const decrypted = await $tryDecryptWithAnyMaterial(cipherTextBlob, embeddedVersion);
+ if (decrypted) return decrypted;
+
+ // Correctly framed v02 that no available material can authenticate (e.g. a replica that has not yet
+ // replicated freshly-rotated material). Surface a real crypto error on the correct byte range rather than
+ // mangling it through the legacy path.
+ return dataCipher.decrypt(cipherTextBlob, kmsKey);
+ }
+
+ // legacy v01 (or anything not validated as v02): strip the 3-byte suffix and try all available material
const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
- const decryptedBlob = dataCipher.decrypt(cipherTextBlob, kmsKey);
- return Promise.resolve(decryptedBlob);
+ const decrypted = await $tryDecryptWithAnyMaterial(cipherTextBlob, currentKeyVersion);
+ if (decrypted) return decrypted;
+ return dataCipher.decrypt(cipherTextBlob, kmsKey);
};
};
@@ -636,15 +801,12 @@ export const kmsServiceFactory = ({
// internal KMS
const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
const dataCipher = symmetricCipherService(encryptionAlgorithm);
+ const currentKeyVersion = kmsDoc.internalKms?.version as number; // NOT NULL, defaults to 1
const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
return ({ plainText }: Pick<TEncryptWithKmsDTO, "plainText">) => {
const encryptedPlainTextBlob = dataCipher.encrypt(plainText, kmsKey);
-
- // Buffer#1 encrypted text + Buffer#2 version number
- const versionBlob = Buffer.from(KMS_VERSION, "utf8"); // length is 3
- const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
-
+ const cipherTextBlob = buildKmsCipherTextBlob(encryptedPlainTextBlob, currentKeyVersion);
return Promise.resolve({ cipherTextBlob });
};
};
@@ -1157,6 +1319,7 @@ export const kmsServiceFactory = ({
return {
startService,
generateKmsKey,
+ rotateKmsKey,
deleteInternalKms,
encryptWithKmsKey,
decryptWithKmsKey,
diff --git a/docs/api-reference/endpoints/kms/keys/rotate.mdx b/docs/api-reference/endpoints/kms/keys/rotate.mdx
new file mode 100644
index 0000000000..cb065714c5
--- /dev/null
+++ b/docs/api-reference/endpoints/kms/keys/rotate.mdx
@@ -0,0 +1,4 @@
+---
+title: "Rotate Key"
+openapi: "POST /api/v1/kms/keys/{keyId}/rotate"
+---
diff --git a/docs/docs.json b/docs/docs.json
index 77f156417d..14520ec662 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -3504,6 +3504,7 @@
"api-reference/endpoints/kms/keys/get-by-name",
"api-reference/endpoints/kms/keys/create",
"api-reference/endpoints/kms/keys/update",
+ "api-reference/endpoints/kms/keys/rotate",
"api-reference/endpoints/kms/keys/delete",
"api-reference/endpoints/kms/keys/public-key",
"api-reference/endpoints/kms/keys/private-key",
diff --git a/docs/documentation/platform/kms/overview.mdx b/docs/documentation/platform/kms/overview.mdx
index 98106f4543..8765c4090c 100644
--- a/docs/documentation/platform/kms/overview.mdx
+++ b/docs/documentation/platform/kms/overview.mdx
@@ -365,6 +365,37 @@ In the following steps, we explore how to verify data using an existing key in I
</Tab>
</Tabs>
+## Key Rotation
+
+Every KMS key tracks a version, starting at 1. Rotating a key generates new cryptographic key material for it and increments the version. The key keeps the same ID and name, so applications referencing the key do not need any changes.
+
+Rotation works the same way as cloud KMS providers such as AWS KMS:
+
+- New encrypt operations use the latest key material.
+- All previous key material versions are retained inside Infisical, and decrypt operations automatically use the version that encrypted the ciphertext. Existing ciphertexts remain decryptable through Infisical without re-encryption.
+- Rotation does not re-encrypt data that was already encrypted with the key. If you need ciphertexts to use the new material, decrypt and re-encrypt them.
+
+To rotate a key:
+
+1. Navigate to **Project > Key Management**.
+2. Open the options menu for the key and select **Rotate Key**.
+3. Confirm the rotation. The key version increments immediately.
+
+Keys can also be rotated programmatically via the [rotate key API endpoint](/api-reference/endpoints/kms/keys/rotate).
+
+<Note>
+ Rotation is supported for encrypt-decrypt keys with Infisical-managed key material. Sign-verify keys
+ should be rotated manually by creating a new key and updating your applications to use it.
+</Note>
+
+<Warning>
+ Previous key material versions are retained only inside the Infisical instance where the key lives, and decrypt operations that resolve old versions automatically work only through Infisical's encrypt/decrypt API. Two workflows take key material outside of Infisical and only ever receive the current version, so rotation affects them:
+
+ - **Exported or imported key material.** [Bulk export](#bulk-export) and the private-key export endpoints return only the current key material, and [bulk import](#bulk-import) creates a key at version 1. A key exported before rotation, or imported into another instance, will not carry its earlier versions, so ciphertexts encrypted under those earlier versions cannot be decrypted from the exported material alone. If you rely on exported material for escrow or disaster recovery, re-export after each rotation and keep every exported version.
+
+ - **KMIP-managed keys.** A KMIP client retrieves raw key material and encrypts data itself. If you rotate a key that is used over KMIP, the client will retrieve different material on its next fetch and will no longer be able to decrypt data it encrypted with the previous material. Do not rotate a key that is in use by a KMIP client; provision a new key instead.
+</Warning>
+
## Bulk Export & Import
Infisical KMS supports bulk export and bulk import of key material, allowing you to export multiple keys at once or import keys in bulk from an external file.
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 0b2ce386bf..f9900a3e0b 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -143,6 +143,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.READ_SHARED_SECRET]: "Read shared secret",
[EventType.CREATE_CMEK]: "Create KMS key",
[EventType.UPDATE_CMEK]: "Update KMS key",
+ [EventType.ROTATE_CMEK]: "Rotate KMS key",
[EventType.DELETE_CMEK]: "Delete KMS key",
[EventType.GET_CMEKS]: "List KMS keys",
[EventType.GET_CMEK]: "Get KMS key",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index bce97ad16c..ce12229b49 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -154,6 +154,7 @@ export enum EventType {
READ_SHARED_SECRET = "read-shared-secret",
CREATE_CMEK = "create-cmek",
UPDATE_CMEK = "update-cmek",
+ ROTATE_CMEK = "rotate-cmek",
DELETE_CMEK = "delete-cmek",
GET_CMEKS = "get-cmeks",
GET_CMEK = "get-cmek",
diff --git a/frontend/src/hooks/api/cmeks/mutations.tsx b/frontend/src/hooks/api/cmeks/mutations.tsx
index c140b89a41..a5781840d2 100644
--- a/frontend/src/hooks/api/cmeks/mutations.tsx
+++ b/frontend/src/hooks/api/cmeks/mutations.tsx
@@ -18,6 +18,7 @@ import {
TCmekVerifyResponse,
TCreateCmek,
TDeleteCmek,
+ TRotateCmek,
TUpdateCmek
} from "@app/hooks/api/cmeks/types";
@@ -53,6 +54,20 @@ export const useUpdateCmek = () => {
});
};
+export const useRotateCmek = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ keyId }: TRotateCmek) => {
+ const { data } = await apiRequest.post(`/api/v1/kms/keys/${keyId}/rotate`);
+
+ return data;
+ },
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: cmekKeys.getCmeksByProjectId({ projectId }) });
+ }
+ });
+};
+
export const useDeleteCmek = () => {
const queryClient = useQueryClient();
return useMutation({
diff --git a/frontend/src/hooks/api/cmeks/types.ts b/frontend/src/hooks/api/cmeks/types.ts
index a1063db64b..c04f45935b 100644
--- a/frontend/src/hooks/api/cmeks/types.ts
+++ b/frontend/src/hooks/api/cmeks/types.ts
@@ -31,6 +31,7 @@ export type TUpdateCmek = KeyRef &
Partial<Pick<TCmek, "name" | "description" | "isDisabled">> &
ProjectRef;
export type TDeleteCmek = KeyRef & ProjectRef;
+export type TRotateCmek = KeyRef & ProjectRef;
export type TCmekEncrypt = KeyRef & { plaintext: string; isBase64Encoded?: boolean };
export type TCmekDecrypt = KeyRef & { ciphertext: string };
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
index 38ef988987..1953851cd1 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
@@ -14,6 +14,7 @@ import {
LockIcon,
PencilIcon,
PlusIcon,
+ RotateCwIcon,
SearchIcon,
TrashIcon,
UnlockIcon
@@ -96,6 +97,7 @@ import { CmekSignModal } from "./CmekSignModal";
import { CmekVerifyModal } from "./CmekVerifyModal";
import { DeleteCmekModal } from "./DeleteCmekModal";
import { cmekKeysToExportJSON, downloadJSON } from "./jsonExport";
+import { RotateCmekModal } from "./RotateCmekModal";
const getStatusBadgeProps = (
isDisabled: boolean
@@ -166,6 +168,7 @@ export const CmekTable = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"upsertKey",
"deleteKey",
+ "rotateKey",
"encryptData",
"decryptData",
"signData",
@@ -630,6 +633,15 @@ export const CmekTable = () => {
<PencilIcon className="mr-2 size-4" />
Edit Key
</DropdownMenuItem>
+ {keyUsage === KmsKeyUsage.ENCRYPT_DECRYPT && (
+ <DropdownMenuItem
+ onClick={() => handlePopUpOpen("rotateKey", cmek)}
+ isDisabled={cannotEditKey || isDisabled}
+ >
+ <RotateCwIcon className="mr-2 size-4" />
+ Rotate Key
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={() => handleDisableCmek(cmek)}
isDisabled={cannotEditKey}
@@ -686,6 +698,11 @@ export const CmekTable = () => {
onOpenChange={(isOpen) => handlePopUpToggle("upsertKey", isOpen)}
cmek={popUp.upsertKey.data as TCmek | null}
/>
+ <RotateCmekModal
+ isOpen={popUp.rotateKey.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("rotateKey", isOpen)}
+ cmek={popUp.rotateKey.data as TCmek}
+ />
<CmekEncryptModal
isOpen={popUp.encryptData.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("encryptData", isOpen)}
diff --git a/frontend/src/pages/kms/OverviewPage/components/RotateCmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/RotateCmekModal.tsx
new file mode 100644
index 0000000000..348ade361d
--- /dev/null
+++ b/frontend/src/pages/kms/OverviewPage/components/RotateCmekModal.tsx
@@ -0,0 +1,43 @@
+import { createNotification } from "@app/components/notifications";
+import { DeleteActionModal } from "@app/components/v2";
+import { TCmek, useRotateCmek } from "@app/hooks/api/cmeks";
+
+type Props = {
+ cmek: TCmek;
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const RotateCmekModal = ({ isOpen, onOpenChange, cmek }: Props) => {
+ const rotateCmek = useRotateCmek();
+
+ if (!cmek) return null;
+
+ const { id: keyId, projectId, name } = cmek;
+
+ const handleRotateCmek = async () => {
+ await rotateCmek.mutateAsync({
+ keyId,
+ projectId
+ });
+
+ createNotification({
+ text: "Key successfully rotated",
+ type: "success"
+ });
+
+ onOpenChange(false);
+ };
+
+ return (
+ <DeleteActionModal
+ isOpen={isOpen}
+ title={`Are you sure you want to rotate ${name}?`}
+ subTitle="This generates new key material and increments the key version. Data encrypted through Infisical stays decryptable. However, any system that holds this key's material directly, such as a KMIP client or an exported copy of the key, will receive the new material and may be unable to decrypt data it encrypted with the previous version. Do not rotate a key that is in use over KMIP."
+ onChange={onOpenChange}
+ deleteKey="confirm"
+ buttonText="Rotate"
+ onDeleteApproved={handleRotateCmek}
+ />
+ );
+};