Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(encryption): implement key rotation and legacy key handling
Victor Hugo dos Santos817089fee7f6
diff --git a/backend/.eslintrc.js b/backend/.eslintrc.jsindex 1df84d6b15..d08a2c766a 100644--- a/backend/.eslintrc.js+++ b/backend/.eslintrc.js@@ -58,6 +58,20 @@ module.exports = {"@typescript-eslint/no-unsafe-return": "off","@typescript-eslint/no-unsafe-call": "off"}+ },+ {+ files: ["./src/db/migrations/**/*"],+ rules: {+ "no-restricted-syntax": [+ "error",+ {+ selector:+ "MemberExpression[property.name='encryptWithRootEncryptionKey'], MemberExpression[property.name='decryptWithRootEncryptionKey'], CallExpression[callee.name='buildSecretBlindIndexFromName']",+ message:+ "A migration cannot use the instance root encryption key: it runs before the key is loaded and would fall back to process.env, which is the wrong key on any instance that has rotated ENCRYPTION_KEY. Do this work in a post-boot background job instead."+ }+ ]+ }}],diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 453b42ffb3..bcd2999273 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -449,6 +449,50 @@ Two properties make the TTL safe to rely on:Nothing reads the pre-stream `telemetry-event-*` keys, so a deploy that changes this layout drops whatever is still buffered. That is acceptable for product analytics, and it is the reason there is no migration path to maintain.+### Instance Root Encryption Key (rotation)++`ENCRYPTION_KEY` wraps the in-DB root key in `kms_root_config`, which wraps everything else. It is+rotatable, and three invariants hold that up.++**The sentinel row always holds the active key.** `kms_root_config` can hold up to three rows, but+`KMS_ROOT_CONFIG_UUID` is always the current one. That id is no longer "the config row", it is a+compatibility handle: an app version predating rotation looks the row up by id and knows nothing about+pending rotations or retained copies, so keeping the active key there is what lets such a version boot. New+code never looks rows up by id — it **trial-decrypts** in a fixed order (sentinel, pending, retained), which+is why there is no `kekFingerprint` column. Fingerprints exist only as human labels in `kms_kek_history`.++**A rotation is inert until a pod boots with the new key.** `POST /admin/encryption/rotations` writes a+*pending* row and does not touch the sentinel, so generating a key changes nothing and discarding it is a row+delete. `$resolveRootKey` promotes it on the first boot that decrypts it: the sentinel takes the new+ciphertext, the old one moves to a retained copy, and **every** pending row is dropped (an abandoned pending+row is a live working key, so a superseded key left in someone's clipboard must not be able to promote+itself later). There is no rollback after promotion, only the retention window during which the old key still+boots.++**The legacy tier is pinned, not rotated.** `project_bots`, `user_encryption_keys.serverEncryptedPrivateKey`,+`secret_blind_indexes` and `org_bots` encrypt straight from the env var. `kms_legacy_encryption_keys` snapshots+those env values under the root key at boot, and `crypto.ts` / `encryption.ts` read the snapshot instead of+`process.env`, which is what decouples that tier from the environment. The snapshot holds **both** the+post-FIPS-relabel values (used for writes, so ciphertext is unchanged) and the pre-relabel ones (tried on+decrypt, because the relabel at `env.ts:746-748` overwrites its target unconditionally). That tier+is never rotated; `infisical.legacy_root_key.usage` is the evidence for when it can be deleted.++Consequences worth knowing:++- **A migration must never call `*WithRootEncryptionKey` or `buildSecretBlindIndexFromName`.** Migrations run+ before `kmsService.startService`, so they cannot reach the snapshot and fall back to `process.env`, which on+ a rotated instance is the wrong key: decrypts fail the auth tag, encrypts silently write unreadable rows.+ ESLint blocks this under `src/db/migrations/`; the pre-existing call sites carry a file-level disable+ explaining why they are safe.+- **`updateEncryptionStrategy` refuses while a rotation is in flight.** A switch to HSM would not otherwise be+ enforced, since a pod with the old env key would still trial-decrypt a retained software copy and boot+ without touching the device.+- **`lastResolvedAt` can prove presence, never absence.** An instance stamps it at boot only when it resolves a+ *superseded* row, which is positive evidence a straggler still holds that key and makes both `complete` and+ the GC decline. An instance that never restarts never stamps, so the retention window is what covers it.+ That is the deliberate limit: getting it wrong costs an instance that fails its next restart with an error+ naming the key it needs, not lost data.+### Database ConfigurationKnex config in `src/db/knexfile.ts`. Loads `.env.migration` then `.env`. Supports `DB_CONNECTION_URI` or individual host/port/user/name/password fields. Optional SSL via `DB_ROOT_CERT` (base64-encoded CA cert). Connection pool: min 2, max 10. Migrations table: `infisical_migrations`. Separate audit log DB supported via `auditlog-migration:*` scripts. ClickHouse for analytics (optional).diff --git a/backend/scripts/seed-gamma-fixtures.ts b/backend/scripts/seed-gamma-fixtures.tsindex 826a7724b2..84b279c61b 100644--- a/backend/scripts/seed-gamma-fixtures.ts+++ b/backend/scripts/seed-gamma-fixtures.ts@@ -40,6 +40,8 @@ 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 { kmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";+import { kmsLegacyEncryptionKeyDALFactory } from "@app/services/kms/kms-legacy-encryption-key-dal";import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";import { kmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -130,6 +132,8 @@ const main = async () => {const superAdminDAL = superAdminDALFactory(knex);const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);+ const kmsLegacyEncryptionKeyDAL = kmsLegacyEncryptionKeyDALFactory(knex);+ const kmsKekHistoryDAL = kmsKekHistoryDALFactory(knex);const hsmConfig = getHsmConfig(logger);const hsmModule = initializeHsmModule(hsmConfig);@@ -152,6 +156,8 @@ const main = async () => {const projectDAL = projectDALFactory(knex);const kmsService = kmsServiceFactory({kmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL,+ kmsKekHistoryDAL,kmsDAL,internalKmsDAL,internalKmsKeyVersionDAL,diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 3cfaee5827..e9e7af3ae7 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -100,6 +100,7 @@ import { TCertificateTemplateServiceFactory } from "@app/services/certificate-teimport { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";import { TCmekServiceFactory } from "@app/services/cmek/cmek-service";import { TConvertorServiceFactory } from "@app/services/convertor/convertor-service";+import { TEncryptionKeyRotationServiceFactory } from "@app/services/encryption-key-rotation/encryption-key-rotation-service";import { TExternalGroupOrgRoleMappingServiceFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-service";import { TExternalMigrationServiceFactory } from "@app/services/external-migration/external-migration-service";import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";@@ -294,6 +295,7 @@ declare module "fastify" {org: TOrgServiceFactory;oidc: TOidcConfigServiceFactory;superAdmin: TSuperAdminServiceFactory;+ encryptionKeyRotation: TEncryptionKeyRotationServiceFactory;user: TUserServiceFactory;group: TGroupServiceFactory;groupProject: TGroupProjectServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 30ee39af18..298cebc349 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -296,12 +296,18 @@ import {TKmipServers,TKmipServersInsert,TKmipServersUpdate,+ TKmsKekHistory,+ TKmsKekHistoryInsert,+ TKmsKekHistoryUpdate,TKmsKeys,TKmsKeysInsert,TKmsKeysUpdate,TKmsKeyVersions,TKmsKeyVersionsInsert,TKmsKeyVersionsUpdate,+ TKmsLegacyEncryptionKeys,+ TKmsLegacyEncryptionKeysInsert,+ TKmsLegacyEncryptionKeysUpdate,TKmsRootConfig,TKmsRootConfigInsert,TKmsRootConfigUpdate,@@ -1416,6 +1422,16 @@ declare module "knex/types/tables" {TKmsRootConfigInsert,TKmsRootConfigUpdate>;+ [TableName.KmsLegacyEncryptionKey]: KnexOriginal.CompositeTableType<+ TKmsLegacyEncryptionKeys,+ TKmsLegacyEncryptionKeysInsert,+ TKmsLegacyEncryptionKeysUpdate+ >;+ [TableName.KmsKekHistory]: KnexOriginal.CompositeTableType<+ TKmsKekHistory,+ TKmsKekHistoryInsert,+ TKmsKekHistoryUpdate+ >;[TableName.InternalKms]: KnexOriginal.CompositeTableType<TInternalKms, TInternalKmsInsert, TInternalKmsUpdate>;[TableName.InternalKmsKeyVersion]: KnexOriginal.CompositeTableType<TInternalKmsKeyVersion,diff --git a/backend/src/db/migrations/20250210101840_webhook-to-kms.ts b/backend/src/db/migrations/20250210101840_webhook-to-kms.tsindex 2fbf681284..3cd690d050 100644--- a/backend/src/db/migrations/20250210101840_webhook-to-kms.ts+++ b/backend/src/db/migrations/20250210101840_webhook-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250210101841_dynamic-secret-root-to-kms.ts b/backend/src/db/migrations/20250210101841_dynamic-secret-root-to-kms.tsindex 179cb9bd69..269d1439d6 100644--- a/backend/src/db/migrations/20250210101841_dynamic-secret-root-to-kms.ts+++ b/backend/src/db/migrations/20250210101841_dynamic-secret-root-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250210101841_secret-rotation-to-kms.ts b/backend/src/db/migrations/20250210101841_secret-rotation-to-kms.tsindex 4ce97480db..84000fb153 100644--- a/backend/src/db/migrations/20250210101841_secret-rotation-to-kms.ts+++ b/backend/src/db/migrations/20250210101841_secret-rotation-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250210101842_identity-k8-auth-to-kms.ts b/backend/src/db/migrations/20250210101842_identity-k8-auth-to-kms.tsindex f3fa630281..443b48d937 100644--- a/backend/src/db/migrations/20250210101842_identity-k8-auth-to-kms.ts+++ b/backend/src/db/migrations/20250210101842_identity-k8-auth-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250210101842_identity-oidc-auth-to-kms.ts b/backend/src/db/migrations/20250210101842_identity-oidc-auth-to-kms.tsindex f970043f05..9046f05b3c 100644--- a/backend/src/db/migrations/20250210101842_identity-oidc-auth-to-kms.ts+++ b/backend/src/db/migrations/20250210101842_identity-oidc-auth-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250210101845_directory-config-to-kms.ts b/backend/src/db/migrations/20250210101845_directory-config-to-kms.tsindex 62b4e85566..0e9a43a483 100644--- a/backend/src/db/migrations/20250210101845_directory-config-to-kms.ts+++ b/backend/src/db/migrations/20250210101845_directory-config-to-kms.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20250903191434_audit-log-stream-v2.ts b/backend/src/db/migrations/20250903191434_audit-log-stream-v2.tsindex 82fa4a0392..7aa69787fd 100644--- a/backend/src/db/migrations/20250903191434_audit-log-stream-v2.ts+++ b/backend/src/db/migrations/20250903191434_audit-log-stream-v2.ts@@ -1,3 +1,5 @@+/* eslint-disable no-restricted-syntax -- Historical: predates kms_legacy_encryption_keys, has already+ run everywhere, and on a fresh install runs against empty tables before a rotation is possible. */import { Knex } from "knex";import { inMemoryKeyStore } from "@app/keystore/memory";diff --git a/backend/src/db/migrations/20260819120000_kek-rotation.ts b/backend/src/db/migrations/20260819120000_kek-rotation.tsnew file mode 100644index 0000000000..dece4c8324--- /dev/null+++ b/backend/src/db/migrations/20260819120000_kek-rotation.ts@@ -0,0 +1,87 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++// kms_root_config becomes a small set of rows, but the fixed sentinel id always holds the *active*+// key. That is what keeps an app version predating this feature bootable: it looks the row up by id+// and finds whatever is current. Other rows are only ever found by trial decryption.+export async function up(knex: Knex): Promise<void> {+ const hasActivatedAt = await knex.schema.hasColumn(TableName.KmsServerRootConfig, "activatedAt");+ const hasSupersededAt = await knex.schema.hasColumn(TableName.KmsServerRootConfig, "supersededAt");+ const hasLastResolvedAt = await knex.schema.hasColumn(TableName.KmsServerRootConfig, "lastResolvedAt");++ if (!hasActivatedAt || !hasSupersededAt || !hasLastResolvedAt) {+ await knex.schema.alterTable(TableName.KmsServerRootConfig, (t) => {+ // NULL means a pending rotation nobody has booted with yet.+ if (!hasActivatedAt) t.timestamp("activatedAt");+ // Set on promotion, on the copy holding the key we just moved off.+ if (!hasSupersededAt) t.timestamp("supersededAt");+ // Stamped by each instance at boot on the row its key opened. Positive evidence that an instance+ // still holds that key; absence proves nothing, since an instance that never restarts never stamps.+ if (!hasLastResolvedAt) t.timestamp("lastResolvedAt");+ });+ }++ if (!hasActivatedAt) {+ // The pre-existing row is by definition active on an instance that has never rotated.+ await knex(TableName.KmsServerRootConfig).whereNull("activatedAt").update({ activatedAt: new Date() });+ }++ // The legacy env-var tier encrypts straight from the env var. Snapshotting those values under the+ // root key decouples it from the environment, so the env key can rotate without stranding it.+ if (!(await knex.schema.hasTable(TableName.KmsLegacyEncryptionKey))) {+ await knex.schema.createTable(TableName.KmsLegacyEncryptionKey, (t) => {+ // Fixed, so a concurrent seed is a PK conflict rather than a second row.+ t.uuid("id", { primaryKey: true });+ // Holds both the post-FIPS-relabel values (used for writes) and the pre-relabel ones, since the+ // relabel can drop a key that existing rows were written under.+ t.binary("encryptedKeySnapshot").notNullable();+ t.timestamps(true, true, true);+ });+ await createOnUpdateTrigger(knex, TableName.KmsLegacyEncryptionKey);+ }++ // Survives the ciphertext it describes: once the GC deletes a superseded copy, this is the only+ // record tying a fingerprint to the window it was active.+ if (!(await knex.schema.hasTable(TableName.KmsKekHistory))) {+ await knex.schema.createTable(TableName.KmsKekHistory, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.string("kekFingerprint", 64).notNullable();+ t.timestamp("activatedAt").notNullable();+ t.timestamp("supersededAt");+ t.timestamp("retiredAt");+ t.timestamps(true, true, true);+ t.index(["activatedAt"]);+ });+ await createOnUpdateTrigger(knex, TableName.KmsKekHistory);+ }+}++export async function down(knex: Knex): Promise<void> {+ // Only the sentinel is readable by pre-rotation code, so the other rows cannot survive.+ const columns = ["activatedAt", "supersededAt", "lastResolvedAt"];+ const present: string[] = [];+ for (const column of columns) {+ // eslint-disable-next-line no-await-in-loop+ if (await knex.schema.hasColumn(TableName.KmsServerRootConfig, column)) present.push(column);+ }+ if (present.length) {+ await knex(TableName.KmsServerRootConfig).whereNot("id", "00000000-0000-0000-0000-000000000000").delete();+ await knex.schema.alterTable(TableName.KmsServerRootConfig, (t) => {+ present.forEach((column) => t.dropColumn(column));+ });+ }++ if (await knex.schema.hasTable(TableName.KmsKekHistory)) {+ await dropOnUpdateTrigger(knex, TableName.KmsKekHistory);+ await knex.schema.dropTable(TableName.KmsKekHistory);+ }++ // Last: without it the legacy tier falls back to process.env, correct only while that is still the+ // key the snapshot was seeded from.+ if (await knex.schema.hasTable(TableName.KmsLegacyEncryptionKey)) {+ await dropOnUpdateTrigger(knex, TableName.KmsLegacyEncryptionKey);+ await knex.schema.dropTable(TableName.KmsLegacyEncryptionKey);+ }+}diff --git a/backend/src/db/migrations/utils/services.ts b/backend/src/db/migrations/utils/services.tsindex 7eaf1c908d..6a07238afd 100644--- a/backend/src/db/migrations/utils/services.ts+++ b/backend/src/db/migrations/utils/services.ts@@ -13,7 +13,9 @@ import { additionalPrivilegeDALFactory } from "@app/services/additional-privilegimport { 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 { kmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";+import { kmsLegacyEncryptionKeyDALFactory } from "@app/services/kms/kms-legacy-encryption-key-dal";import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";import { kmsServiceFactory } from "@app/services/kms/kms-service";import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";@@ -66,6 +68,8 @@ export const getMigrationEncryptionServices = async ({const identityDAL = identityDALFactory(db);const serviceTokenDAL = serviceTokenDALFactory(db);const kmsRootConfigDAL = kmsRootConfigDALFactory(db);+ const kmsLegacyEncryptionKeyDAL = kmsLegacyEncryptionKeyDALFactory(db);+ const kmsKekHistoryDAL = kmsKekHistoryDALFactory(db);const kmsDAL = kmskeyDALFactory(db);const internalKmsDAL = internalKmsDALFactory(db);const internalKmsKeyVersionDAL = internalKmsKeyVersionDALFactory(db);@@ -123,6 +127,8 @@ export const getMigrationEncryptionServices = async ({const kmsService = kmsServiceFactory({kmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL,+ kmsKekHistoryDAL,kmsDAL,internalKmsDAL,internalKmsKeyVersionDAL,diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 28d3bcb7c6..6035858224 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -107,8 +107,10 @@ export * from "./kmip-clients";export * from "./kmip-org-configs";export * from "./kmip-org-server-certificates";export * from "./kmip-servers";+export * from "./kms-kek-history";export * from "./kms-key-versions";export * from "./kms-keys";+export * from "./kms-legacy-encryption-keys";export * from "./kms-root-config";export * from "./ldap-configs";export * from "./ldap-group-maps";diff --git a/backend/src/db/schemas/kms-kek-history.ts b/backend/src/db/schemas/kms-kek-history.tsnew file mode 100644index 0000000000..b8542f2b5c--- /dev/null+++ b/backend/src/db/schemas/kms-kek-history.ts@@ -0,0 +1,22 @@+// 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 { TImmutableDBKeys } from "./models";++export const KmsKekHistorySchema = z.object({+ id: z.string().uuid(),+ kekFingerprint: z.string(),+ activatedAt: z.date(),+ supersededAt: z.date().nullable().optional(),+ retiredAt: z.date().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TKmsKekHistory = z.infer<typeof KmsKekHistorySchema>;+export type TKmsKekHistoryInsert = Omit<z.input<typeof KmsKekHistorySchema>, TImmutableDBKeys>;+export type TKmsKekHistoryUpdate = Partial<Omit<z.input<typeof KmsKekHistorySchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/kms-legacy-encryption-keys.ts b/backend/src/db/schemas/kms-legacy-encryption-keys.tsnew file mode 100644index 0000000000..1da95ea298--- /dev/null+++ b/backend/src/db/schemas/kms-legacy-encryption-keys.ts@@ -0,0 +1,23 @@+// 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 KmsLegacyEncryptionKeysSchema = z.object({+ id: z.string().uuid(),+ encryptedKeySnapshot: zodBuffer,+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TKmsLegacyEncryptionKeys = z.infer<typeof KmsLegacyEncryptionKeysSchema>;+export type TKmsLegacyEncryptionKeysInsert = Omit<z.input<typeof KmsLegacyEncryptionKeysSchema>, TImmutableDBKeys>;+export type TKmsLegacyEncryptionKeysUpdate = Partial<+ Omit<z.input<typeof KmsLegacyEncryptionKeysSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/kms-root-config.ts b/backend/src/db/schemas/kms-root-config.tsindex c9c1ebda57..85a25bba7f 100644--- a/backend/src/db/schemas/kms-root-config.ts+++ b/backend/src/db/schemas/kms-root-config.ts@@ -14,7 +14,10 @@ export const KmsRootConfigSchema = z.object({encryptedRootKey: zodBuffer,encryptionStrategy: z.string().default("SOFTWARE").nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ activatedAt: z.date().nullable().optional(),+ supersededAt: z.date().nullable().optional(),+ lastResolvedAt: z.date().nullable().optional()});export type TKmsRootConfig = z.infer<typeof KmsRootConfigSchema>;diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 9e31ccc2cf..a7c83104f6 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -178,6 +178,8 @@ export enum TableName {SecretVersionV2Tag = "secret_version_v2_tag_junction",// KMS ServiceKmsServerRootConfig = "kms_root_config",+ KmsLegacyEncryptionKey = "kms_legacy_encryption_keys",+ KmsKekHistory = "kms_kek_history",KmsKey = "kms_keys",ExternalKms = "external_kms",InternalKms = "internal_kms",diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex e986a30cb3..22e388b30f 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -156,8 +156,17 @@ export const auditLogServiceFactory = ({if (appCfg.DISABLE_AUDIT_LOG_GENERATION) {return;}- // Events that don't require projectId or orgId (login events where org context may not be available)- if (data.event.type !== EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH) {+ // Events with no inherent scope. Logins have no org context yet; instance root-key rotation is+ // instance-level, and req.permission.orgId is only guaranteed for machine identities, so requiring a+ // scope here would let the audit write fail an operation that has already happened.+ const SCOPELESS_EVENTS: EventType[] = [+ EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,+ EventType.GET_ENCRYPTION_STATUS,+ EventType.CREATE_ENCRYPTION_KEY_ROTATION,+ EventType.DELETE_ENCRYPTION_KEY_ROTATION,+ EventType.COMPLETE_ENCRYPTION_KEY_ROTATION+ ];+ if (!SCOPELESS_EVENTS.includes(data.event.type)) {if (!data.projectId && !data.orgId)throw new BadRequestError({ message: "Must specify either project id or org id" });}diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex f37c8b8473..745b74bbf5 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -891,7 +891,13 @@ export enum EventType {CREATE_ALERT = "create-alert",UPDATE_ALERT = "update-alert",DELETE_ALERT = "delete-alert",- TEST_ALERT_CHANNEL = "test-alert-channel"+ TEST_ALERT_CHANNEL = "test-alert-channel",++ // Instance root encryption key rotation+ GET_ENCRYPTION_STATUS = "get-encryption-status",+ CREATE_ENCRYPTION_KEY_ROTATION = "create-encryption-key-rotation",+ DELETE_ENCRYPTION_KEY_ROTATION = "delete-encryption-key-rotation",+ COMPLETE_ENCRYPTION_KEY_ROTATION = "complete-encryption-key-rotation"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -7093,6 +7099,39 @@ interface TestAlertChannelEvent {};}+interface GetEncryptionStatusEvent {+ type: EventType.GET_ENCRYPTION_STATUS;+ metadata: {+ activeFingerprint: string | null;+ hasPendingRotation: boolean;+ hasRetainedKey: boolean;+ };+}++interface CreateEncryptionKeyRotationEvent {+ type: EventType.CREATE_ENCRYPTION_KEY_ROTATION;+ metadata: {+ rotationId: string;+ fingerprint: string;+ supersededPending: boolean;+ };+}++interface DeleteEncryptionKeyRotationEvent {+ type: EventType.DELETE_ENCRYPTION_KEY_ROTATION;+ metadata: {+ rotationId: string;+ };+}++interface CompleteEncryptionKeyRotationEvent {+ type: EventType.COMPLETE_ENCRYPTION_KEY_ROTATION;+ metadata: {+ retainedKeyId: string;+ retiredFingerprint: string | null;+ };+}+export type Event =| CreateAlertEvent| UpdateAlertEvent@@ -7724,4 +7763,8 @@ export type Event =| UpdateGroupProjectMembershipEvent| RemoveGroupFromProjectEvent| CreateProjectFolderGrantEvent- | DeleteProjectFolderGrantEvent;+ | DeleteProjectFolderGrantEvent+ | GetEncryptionStatusEvent+ | CreateEncryptionKeyRotationEvent+ | DeleteEncryptionKeyRotationEvent+ | CompleteEncryptionKeyRotationEvent;diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.tsindex 2f07dd294d..95f2d66e92 100644--- a/backend/src/ee/services/group/group-fns.ts+++ b/backend/src/ee/services/group/group-fns.ts@@ -3,6 +3,8 @@ import { Knex } from "knex";import { AccessScope, ProjectVersion, SecretKeyEncoding, TableName, TUsers } from "@app/db/schemas";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, ForbiddenRequestError, NotFoundError, ScimRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { PamIdentities, SecretIdentities } from "@app/services/license-client";import {@@ -118,6 +120,8 @@ const addAcceptedUsersToGroup = async ({});}+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "project_bot" });+ logger.info(`Legacy root key used to read a project bot key for group sync [projectId=${project.id}]`);const botPrivateKey = crypto.encryption().symmetric()diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex bfd346a90b..0fe5ed28e6 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3948,3 +3948,37 @@ export const SECRET_VALIDATION_RULES = {ruleId: "The ID of the secret validation rule to delete."}} as const;++export const ENCRYPTION_KEY_ROTATION = {+ STATUS: {+ description:+ "Report the state of the instance encryption key: which key is active, whether a rotation is staged or awaiting completion, and what is blocking one.",+ activeFingerprint:+ "A non-reversible label for the key this instance is currently running with. Use it to identify which archived key a database backup needs.",+ pendingRotation:+ "A generated key that has not been applied yet. Staging a rotation changes nothing until an instance starts with the new key.",+ lastResolvedAt:+ "When an instance last started using the previous key. Recent means one is probably still running and would fail to restart if the key were removed. Null only means none has started since the rotation, not that none exists.",+ history:+ "Every key this instance has used, oldest last. Retained after a key is removed, so a restored backup can be matched to an archived key."+ },+ CREATE: {+ description:+ "Generate a new value for ENCRYPTION_KEY. The key is returned once and never stored, and nothing changes until an instance starts with it.",+ supersede:+ "Replace an already-generated key that has not been applied yet. The replaced key stops working immediately.",+ fingerprint:+ "A non-reversible label for the new key. Record it alongside the key so a backup can be matched to it later.",+ key: "The new value for ENCRYPTION_KEY. Shown only in this response and never recoverable. Store it before closing."+ },+ DISCARD: {+ description:+ "Discard a generated key that has not been applied. Use this immediately if the key may have been exposed.",+ rotationId: "ID of the staged rotation to discard."+ },+ COMPLETE: {+ description:+ "Remove the previous encryption key now that every instance is using the new one. This cannot be undone: after it, losing the new key means losing access to all stored secrets.",+ rotationId: "ID of the previous key to remove."+ }+};diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex f63e723fa8..e00bcd455a 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -200,6 +200,9 @@ const envSchema = z// TODO(akhilmhdh): will be changed to oneENCRYPTION_KEY: zpStr(z.string().optional()),ROOT_ENCRYPTION_KEY: zpStr(z.string().optional()),+ // A convergence window, not a rollback window: it lets instances that have not restarted onto the+ // new key keep booting, and covers a new key that turns out to be lost. Then the old key is gone.+ KMS_ROOT_KEY_RETENTION_DAYS: z.coerce.number().int().min(1).max(90).default(7),QUEUE_WORKERS_ENABLED: zodStrBool.default("true"),QUEUE_WORKER_PROFILE: z.nativeEnum(QueueWorkerProfile).default(QueueWorkerProfile.All),HTTPS_ENABLED: zodStrBool,diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex a8e79fd248..66aae4ff0f 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -10,6 +10,7 @@ import { ExecutionError, Redlock, ResourceLockedError } from "@app/lib/red-lock"export const CronJobName = {HealthAlert: "health-alert",+ KmsRootKeyCleanup: "kms-root-key-cleanup",DailyReminders: "daily-reminders",DailyResourceCleanup: "daily-resource-cleanup",DailySecretVersionCleanup: "daily-secret-version-cleanup",diff --git a/backend/src/lib/crypto/cryptography/crypto.ts b/backend/src/lib/crypto/cryptography/crypto.tsindex 6e2a157407..75785c1ddd 100644--- a/backend/src/lib/crypto/cryptography/crypto.ts+++ b/backend/src/lib/crypto/cryptography/crypto.ts@@ -21,6 +21,7 @@ import { isBase64 } from "../../base64";import { getConfig, TEnvConfig } from "../../config/env";import { CryptographyError } from "../../errors";import { logger } from "../../logger";+import { getLegacyDecryptionCandidates, getLegacyEncryptionSnapshot, TLegacyKeySnapshot } from "../legacy-key";import { asymmetricFipsValidated } from "./asymmetric-fips";import { hasherFipsValidated } from "./hash-fips";import type { TDecryptAsymmetricInput, TDecryptSymmetricInput, TEncryptSymmetricInput } from "./types";@@ -282,7 +283,9 @@ const cryptographyFactory = () => {data: string,appCfgOverride?: Pick<TEnvConfig, "ROOT_ENCRYPTION_KEY" | "ENCRYPTION_KEY">) => {- const appCfg = appCfgOverride || getConfig();+ // Snapshot over environment, so an ENCRYPTION_KEY rotation cannot strand these rows. It holds+ // the same values, so ciphertext is unchanged. The fallback covers migrations and early boot.+ const appCfg = getLegacyEncryptionSnapshot() || appCfgOverride || getConfig();const rootEncryptionKey = appCfg.ROOT_ENCRYPTION_KEY;const encryptionKey = appCfg.ENCRYPTION_KEY;@@ -334,41 +337,60 @@ const cryptographyFactory = () => {}: Omit<TDecryptSymmetricInput, "key" | "keySize"> & {keyEncoding: SecretKeyEncoding;}) => {- const appCfg = getConfig();- // the or gate is used used in migration- const rootEncryptionKey = appCfg?.ROOT_ENCRYPTION_KEY || process.env.ROOT_ENCRYPTION_KEY;- const encryptionKey = appCfg?.ENCRYPTION_KEY || process.env.ENCRYPTION_KEY;+ const $attempt = (snapshot: TLegacyKeySnapshot) => {+ const { ROOT_ENCRYPTION_KEY: rootEncryptionKey, ENCRYPTION_KEY: encryptionKey } = snapshot;++ if (rootEncryptionKey && keyEncoding === SecretKeyEncoding.BASE64) {+ return symmetric().decrypt({+ key: rootEncryptionKey,+ iv,+ tag,+ ciphertext,+ keySize: SymmetricKeySize.Bits256+ }) as T;+ }+ if (encryptionKey && keyEncoding === SecretKeyEncoding.UTF8) {+ return symmetric().decrypt({+ key: encryptionKey,+ iv,+ tag,+ ciphertext,+ keySize: SymmetricKeySize.Bits128+ }) as T;+ }+ throw new CryptographyError({ message: "Missing both encryption keys" });+ };++ // Current first, then pre-FIPS-relabel: the relabel can drop an operator-set+ // ROOT_ENCRYPTION_KEY that existing rows were written under.+ const candidates = getLegacyDecryptionCandidates();+ if (!candidates.length) {+ const appCfg = getConfig();+ // the or gate is used used in migration+ candidates.push({+ ROOT_ENCRYPTION_KEY: appCfg?.ROOT_ENCRYPTION_KEY || process.env.ROOT_ENCRYPTION_KEY,+ ENCRYPTION_KEY: appCfg?.ENCRYPTION_KEY || process.env.ENCRYPTION_KEY+ });+ }// Sanity check- if (!rootEncryptionKey && !encryptionKey) {+ if (!candidates.some((candidate) => candidate.ROOT_ENCRYPTION_KEY || candidate.ENCRYPTION_KEY)) {throw new CryptographyError({message: "Tried to decrypt with instance root encryption key, but no root encryption key is set."});}- if (rootEncryptionKey && keyEncoding === SecretKeyEncoding.BASE64) {- const data = symmetric().decrypt({- key: rootEncryptionKey,- iv,- tag,- ciphertext,- keySize: SymmetricKeySize.Bits256- });- return data as T;- }- if (encryptionKey && keyEncoding === SecretKeyEncoding.UTF8) {- const data = symmetric().decrypt({- key: encryptionKey,- iv,- tag,- ciphertext,- keySize: SymmetricKeySize.Bits128- });- return data as T;+ let lastError: unknown;+ for (const candidate of candidates) {+ try {+ return $attempt(candidate);+ } catch (err) {+ lastError = err;+ }}- throw new CryptographyError({- message: "Missing both encryption keys"- });+ throw lastError instanceof Error+ ? lastError+ : new CryptographyError({ message: "Failed to decrypt with instance root encryption key" });};return {diff --git a/backend/src/lib/crypto/encryption.ts b/backend/src/lib/crypto/encryption.tsindex 7d2710207f..f2a881a99b 100644--- a/backend/src/lib/crypto/encryption.ts+++ b/backend/src/lib/crypto/encryption.ts@@ -3,6 +3,7 @@ import argon2 from "argon2";import { SecretKeyEncoding } from "@app/db/schemas";import { crypto, SymmetricKeySize } from "./cryptography";+import { getLegacyDecryptionCandidates } from "./legacy-key";type TBuildSecretBlindIndexDTO = {secretName: string;@@ -27,18 +28,33 @@ export const buildSecretBlindIndexFromName = async ({encryptionKey,rootEncryptionKey}: TBuildSecretBlindIndexDTO) => {- if (!encryptionKey && !rootEncryptionKey) throw new Error("Missing secret blind index key");+ // Snapshot over the passed-in env keys: after a rotation the environment holds the new key while+ // this salt is still under the old one.+ const candidates = getLegacyDecryptionCandidates();+ if (!candidates.length) candidates.push({ ENCRYPTION_KEY: encryptionKey, ROOT_ENCRYPTION_KEY: rootEncryptionKey });++ if (!candidates.some((candidate) => candidate.ENCRYPTION_KEY || candidate.ROOT_ENCRYPTION_KEY)) {+ throw new Error("Missing secret blind index key");+ }+let salt = "";- if (rootEncryptionKey && keyEncoding === SecretKeyEncoding.BASE64) {- salt = crypto- .encryption()- .symmetric()- .decrypt({ iv, ciphertext, key: rootEncryptionKey, tag, keySize: SymmetricKeySize.Bits256 });- } else if (encryptionKey && keyEncoding === SecretKeyEncoding.UTF8) {- salt = crypto- .encryption()- .symmetric()- .decrypt({ iv, ciphertext, key: encryptionKey, tag, keySize: SymmetricKeySize.Bits128 });+ for (const candidate of candidates) {+ try {+ if (candidate.ROOT_ENCRYPTION_KEY && keyEncoding === SecretKeyEncoding.BASE64) {+ salt = crypto+ .encryption()+ .symmetric()+ .decrypt({ iv, ciphertext, key: candidate.ROOT_ENCRYPTION_KEY, tag, keySize: SymmetricKeySize.Bits256 });+ } else if (candidate.ENCRYPTION_KEY && keyEncoding === SecretKeyEncoding.UTF8) {+ salt = crypto+ .encryption()+ .symmetric()+ .decrypt({ iv, ciphertext, key: candidate.ENCRYPTION_KEY, tag, keySize: SymmetricKeySize.Bits128 });+ }+ } catch {+ salt = "";+ }+ if (salt) break;}if (!salt) throw new Error("Missing secret blind index key");diff --git a/backend/src/lib/crypto/legacy-key/index.ts b/backend/src/lib/crypto/legacy-key/index.tsnew file mode 100644index 0000000000..2d37dc699a--- /dev/null+++ b/backend/src/lib/crypto/legacy-key/index.ts@@ -0,0 +1,8 @@+export type { TLegacyKeyMaterial, TLegacyKeySnapshot } from "./legacy-key";+export {+ getLegacyDecryptionCandidates,+ getLegacyEncryptionSnapshot,+ getLegacyKeyMaterial,+ resetLegacyKeyMaterial,+ setLegacyKeyMaterial+} from "./legacy-key";diff --git a/backend/src/lib/crypto/legacy-key/legacy-key.ts b/backend/src/lib/crypto/legacy-key/legacy-key.tsnew file mode 100644index 0000000000..fb6cc6c0ba--- /dev/null+++ b/backend/src/lib/crypto/legacy-key/legacy-key.ts@@ -0,0 +1,56 @@+// Env-var key material for the legacy (pre-KMS) tier: project_bots,+// user_encryption_keys.serverEncryptedPrivateKey, secret_blind_indexes, org_bots. While those read+// process.env, rotating the env key strands every one of their rows, so the values are snapshotted into+// the database and served from here instead.++export type TLegacyKeySnapshot = {+ ENCRYPTION_KEY?: string;+ ROOT_ENCRYPTION_KEY?: string;+};++export type TLegacyKeyMaterial = {+ // Post-FIPS-relabel, what the legacy tier resolves today. Writes always use these.+ current: TLegacyKeySnapshot;+ // Pre-relabel. Decrypt-only fallback: the relabel can drop a key existing rows were written under.+ original?: TLegacyKeySnapshot;+};++let legacyKeyMaterial: TLegacyKeyMaterial | null = null;++export const setLegacyKeyMaterial = (material: TLegacyKeyMaterial) => {+ legacyKeyMaterial = material;+};++export const getLegacyKeyMaterial = () => legacyKeyMaterial;++export const resetLegacyKeyMaterial = () => {+ legacyKeyMaterial = null;+};++const hasAnyKey = (snapshot: TLegacyKeySnapshot | undefined): snapshot is TLegacyKeySnapshot =>+ Boolean(snapshot && (snapshot.ENCRYPTION_KEY || snapshot.ROOT_ENCRYPTION_KEY));++/** Empty means no snapshot is loaded yet: callers fall back to the environment. */+export const getLegacyDecryptionCandidates = (): TLegacyKeySnapshot[] => {+ if (!legacyKeyMaterial) return [];++ const candidates: TLegacyKeySnapshot[] = [];+ if (hasAnyKey(legacyKeyMaterial.current)) candidates.push(legacyKeyMaterial.current);++ const { original } = legacyKeyMaterial;+ if (+ hasAnyKey(original) &&+ (original.ENCRYPTION_KEY !== legacyKeyMaterial.current.ENCRYPTION_KEY ||+ original.ROOT_ENCRYPTION_KEY !== legacyKeyMaterial.current.ROOT_ENCRYPTION_KEY)+ ) {+ candidates.push(original);+ }++ return candidates;+};++/** Null means fall back to the environment. */+export const getLegacyEncryptionSnapshot = (): TLegacyKeySnapshot | null => {+ if (!legacyKeyMaterial || !hasAnyKey(legacyKeyMaterial.current)) return null;+ return legacyKeyMaterial.current;+};diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex be3bc6f8c7..ea0a0ba35e 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -791,3 +791,30 @@ export const registerInfrastructureMetrics = (db: Knex) => {result.observe(pool.numPendingAcquires?.() ?? 0, { "db.pool.state": "pending" });});};++// -- Legacy root-key usage (InfisicalCore meter) -----------------------------------------------------+// The pre-KMS tier pins the instance root encryption key, so it can never be rotated while anything+// still uses it. This counter is the evidence for when that tier can be deleted.+export const legacyRootKeyUsageCounter = infisicalCoreMeter.createCounter("infisical.legacy_root_key.usage", {+ description:+ "Reads and writes that still use the instance root encryption key directly instead of the KMS envelope, by surface."+});++export type LegacyRootKeySurface =+ | "project_bot"+ | "user_private_key"+ | "blind_index"+ | "external_migration"+ | "org_bot"+ | "project_ghost_user";++export const recordLegacyRootKeyUsageMetric = (params: {+ operation: "encrypt" | "decrypt";+ surface: LegacyRootKeySurface;+}) => {+ if (!isTelemetryEnabled()) return;+ legacyRootKeyUsageCounter.add(1, {+ "legacy_key.operation": params.operation,+ "legacy_key.surface": params.surface+ });+};diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.tsindex a6e47a43e3..65898a6f6d 100644--- a/backend/src/lib/telemetry/telemetry-attributes.ts+++ b/backend/src/lib/telemetry/telemetry-attributes.ts@@ -27,6 +27,9 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = ["sso.provider","sso.action","db.pool.state",+ // Closed enums on infisical.legacy_root_key.usage; per-project attribution is in logs, not here.+ "legacy_key.operation",+ "legacy_key.surface","cache.result","cache.if_none_match","cache.etag_miss_reason",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex c0f684b7ab..7c35562118 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -296,6 +296,7 @@ import { certificateV3QueueServiceFactory } from "@app/services/certificate-v3/cimport { certificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";import { cmekServiceFactory } from "@app/services/cmek/cmek-service";import { convertorServiceFactory } from "@app/services/convertor/convertor-service";+import { encryptionKeyRotationServiceFactory } from "@app/services/encryption-key-rotation/encryption-key-rotation-service";import { acmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";import { apiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";import { estEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";@@ -365,7 +366,9 @@ import { integrationAuthDALFactory } from "@app/services/integration-auth/integrimport { 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 { kmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";+import { kmsLegacyEncryptionKeyDALFactory } from "@app/services/kms/kms-legacy-encryption-key-dal";import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";import { kmsServiceFactory } from "@app/services/kms/kms-service";import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";@@ -700,6 +703,8 @@ export const registerRoutes = async (const kmsDAL = kmskeyDALFactory(db);const internalKmsDAL = internalKmsDALFactory(db);const internalKmsKeyVersionDAL = internalKmsKeyVersionDALFactory(db);+ const kmsLegacyEncryptionKeyDAL = kmsLegacyEncryptionKeyDALFactory(db);+ const kmsKekHistoryDAL = kmsKekHistoryDALFactory(db);const externalKmsDAL = externalKmsDALFactory(db);const slackIntegrationDAL = slackIntegrationDALFactory(db);@@ -933,6 +938,8 @@ export const registerRoutes = async (const kmsService = kmsServiceFactory({kmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL,+ kmsKekHistoryDAL,kmsDAL,internalKmsDAL,internalKmsKeyVersionDAL,@@ -943,6 +950,14 @@ export const registerRoutes = async (envConfig});+ const encryptionKeyRotationService = encryptionKeyRotationServiceFactory({+ kmsService,+ kmsRootConfigDAL,+ kmsKekHistoryDAL,+ envConfig,+ cronJob+ });+const resourceMetadataService = resourceMetadataServiceFactory({resourceMetadataDAL,permissionService,@@ -3855,6 +3870,7 @@ export const registerRoutes = async (await kmsService.startService(hsmStatus);// Register all cron jobs (synchronous registrations) before starting the scheduler+ encryptionKeyRotationService.init();telemetryQueue.startTelemetryCheck();telemetryQueue.startAggregatedEventsJob();updateCheckService.init();@@ -3903,6 +3919,7 @@ export const registerRoutes = async (authToken: tokenService,oauthClient: oauthClientService,superAdmin: superAdminService,+ encryptionKeyRotation: encryptionKeyRotationService,offlineUsageReport: offlineUsageReportService,orgProductStats: orgProductStatsService,project: projectService,diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.tsindex 8628d69f27..743c3d0623 100644--- a/backend/src/server/routes/v1/admin-router.ts+++ b/backend/src/server/routes/v1/admin-router.ts@@ -8,8 +8,10 @@ import {OrgMembershipsSchema,OrgMembershipStatus} from "@app/db/schemas";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { getLicenseKeyConfig } from "@app/ee/services/license/license-fns";import { LicenseType } from "@app/ee/services/license/license-types";+import { ENCRYPTION_KEY_ROTATION } from "@app/lib/api-docs";import { getConfig, overridableKeys } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError } from "@app/lib/errors";@@ -22,6 +24,7 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifySuperAdmin } from "@app/server/plugins/auth/superAdmin";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";+import { RotationBlocker } from "@app/services/encryption-key-rotation/encryption-key-rotation-types";import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";import { getServerCfg } from "@app/services/super-admin/super-admin-service";@@ -637,6 +640,191 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/encryption/status",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "getAdminEncryptionStatus",+ description: ENCRYPTION_KEY_ROTATION.STATUS.description,+ response: {+ 200: z.object({+ status: z.object({+ activeFingerprint: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.activeFingerprint),+ encryptionStrategy: z.string().nullable(),+ pendingRotation: z+ .object({ id: z.string().uuid(), createdAt: z.date() })+ .nullable()+ .describe(ENCRYPTION_KEY_ROTATION.STATUS.pendingRotation),+ retainedKey: z+ .object({+ id: z.string().uuid(),+ supersededAt: z.date(),+ lastResolvedAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.lastResolvedAt)+ })+ .nullable(),+ history: z+ .object({+ kekFingerprint: z.string(),+ activatedAt: z.date(),+ supersededAt: z.date().nullish(),+ retiredAt: z.date().nullish()+ })+ .array()+ .describe(ENCRYPTION_KEY_ROTATION.STATUS.history),+ blockers: z.nativeEnum(RotationBlocker).array()+ })+ })+ }+ },+ onRequest: (req, res, done) => {+ verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {+ verifySuperAdmin(req, res, done);+ });+ },+ handler: async (req) => {+ const status = await server.services.encryptionKeyRotation.getStatus();++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ event: {+ type: EventType.GET_ENCRYPTION_STATUS,+ metadata: {+ activeFingerprint: status.activeFingerprint,+ hasPendingRotation: Boolean(status.pendingRotation),+ hasRetainedKey: Boolean(status.retainedKey)+ }+ }+ });++ return { status };+ }+ });++ server.route({+ method: "POST",+ url: "/encryption/rotations",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "createAdminEncryptionKeyRotation",+ description: ENCRYPTION_KEY_ROTATION.CREATE.description,+ querystring: z.object({+ supersede: z.coerce.boolean().default(false).describe(ENCRYPTION_KEY_ROTATION.CREATE.supersede)+ }),+ response: {+ 201: z.object({+ rotation: z.object({+ id: z.string().uuid(),+ fingerprint: z.string().describe(ENCRYPTION_KEY_ROTATION.CREATE.fingerprint),+ key: z.string().describe(ENCRYPTION_KEY_ROTATION.CREATE.key)+ })+ })+ }+ },+ onRequest: (req, res, done) => {+ verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {+ verifySuperAdmin(req, res, done);+ });+ },+ handler: async (req, res) => {+ const rotation = await server.services.encryptionKeyRotation.createRotation({+ supersede: req.query.supersede+ });++ // Fingerprint only. The key itself is in the response body and must reach no other sink.+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ event: {+ type: EventType.CREATE_ENCRYPTION_KEY_ROTATION,+ metadata: {+ rotationId: rotation.id,+ fingerprint: rotation.fingerprint,+ supersededPending: req.query.supersede+ }+ }+ });++ // The key appears here and nowhere else, so it must not be cached along the way.+ void res.header("Cache-Control", "no-store");+ void res.status(201);+ return { rotation };+ }+ });++ server.route({+ method: "DELETE",+ url: "/encryption/rotations/:rotationId",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "deleteAdminEncryptionKeyRotation",+ description: ENCRYPTION_KEY_ROTATION.DISCARD.description,+ params: z.object({+ rotationId: z.string().uuid().describe(ENCRYPTION_KEY_ROTATION.DISCARD.rotationId)+ })+ },+ onRequest: (req, res, done) => {+ verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {+ verifySuperAdmin(req, res, done);+ });+ },+ handler: async (req, res) => {+ await server.services.encryptionKeyRotation.discardRotation(req.params.rotationId);++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ event: {+ type: EventType.DELETE_ENCRYPTION_KEY_ROTATION,+ metadata: { rotationId: req.params.rotationId }+ }+ });++ void res.status(204);+ }+ });++ // RPC-shaped on purpose: the operator is finishing a rotation, not deleting a key they may not know+ // exists, and "instances still use this" reads as a precondition on an action, oddly on a DELETE.+ server.route({+ method: "POST",+ url: "/encryption/rotations/:rotationId/complete",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ operationId: "completeAdminEncryptionKeyRotation",+ description: ENCRYPTION_KEY_ROTATION.COMPLETE.description,+ params: z.object({+ rotationId: z.string().uuid().describe(ENCRYPTION_KEY_ROTATION.COMPLETE.rotationId)+ })+ },+ onRequest: (req, res, done) => {+ verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {+ verifySuperAdmin(req, res, done);+ });+ },+ handler: async (req, res) => {+ const { retiredFingerprint } = await server.services.encryptionKeyRotation.completeRotation(+ req.params.rotationId+ );++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ event: {+ type: EventType.COMPLETE_ENCRYPTION_KEY_ROTATION,+ metadata: { retainedKeyId: req.params.rotationId, retiredFingerprint }+ }+ });++ void res.status(204);+ }+ });+server.route({method: "POST",url: "/signup",diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex faf320e898..3b7c5ddcc5 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -30,7 +30,8 @@ import {AuthAttemptAuthMethod,AuthAttemptAuthResult,authAttemptCounter,- recordAuthAttemptMetric+ recordAuthAttemptMetric,+ recordLegacyRootKeyUsageMetric} from "@app/lib/telemetry/metrics";import { matchesAllowedEmailDomain, sanitizeEmail, validateEmail } from "@app/lib/validator";import { getUserAgentType } from "@app/server/plugins/audit-log";@@ -483,6 +484,7 @@ export const authLoginServiceFactory = ({const hashedPassword = await crypto.hashing().createHash(password, cfg.SALT_ROUNDS);+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "user_private_key" });const { iv, tag, ciphertext, encoding } = crypto.encryption().symmetric()diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.tsnew file mode 100644index 0000000000..6cc08fd389--- /dev/null+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.ts@@ -0,0 +1,66 @@+import { crypto } from "@app/lib/crypto/cryptography";+import { initLogger } from "@app/lib/logger";+import { resolveInstanceEncryptionKeyBuffer } from "@app/services/kms/kms-fns";++import { generateRootEncryptionKey, resolveKekBuffer } from "./encryption-key-rotation-fns";++// The cryptography module logs during initialization, and the logger is a module-level singleton that+// only exists once initLogger has run.+beforeAll(async () => {+ initLogger();+ await crypto.initialize({ findById: async () => null } as never, {} as never, {} as never, {} as never);+});++describe("generateRootEncryptionKey", () => {+ // The 16-versus-32 slip: randomBytes(32).toString("hex") is 64 characters, utf8-decodes to 64 bytes,+ // and AES-256 rejects it, so the instance would not boot. Assert the resolved buffer, not the string.+ test.each([+ [false, 32],+ [true, 44]+ ])("fips=%s generates a key that resolves to 32 bytes", (fips, expectedLength) => {+ const key = generateRootEncryptionKey(fips);+ expect(key).toHaveLength(expectedLength);+ expect(resolveKekBuffer(key, fips)).toHaveLength(32);+ });++ test("off FIPS the key is 32 hex characters, so it survives a utf8 read", () => {+ const key = generateRootEncryptionKey(false);+ expect(key).toMatch(/^[0-9a-f]{32}$/);+ expect(Buffer.from(key, "utf8")).toHaveLength(32);+ });++ test("on FIPS the key decodes to exactly 256 bits", () => {+ expect(Buffer.from(generateRootEncryptionKey(true), "base64")).toHaveLength(32);+ });++ test("generated keys are not repeated", () => {+ const keys = new Set(Array.from({ length: 50 }, () => generateRootEncryptionKey(false)));+ expect(keys.size).toBe(50);+ });+});++describe("resolveKekBuffer", () => {+ test("rejects a key of the wrong length rather than producing a broken instance", () => {+ expect(() => resolveKekBuffer("tooshort", false)).toThrow();+ // the exact slip this guards: 32 random bytes rendered as hex+ expect(() => resolveKekBuffer(crypto.randomBytes(32).toString("hex"), false)).toThrow();+ });++ // The prediction has to agree with the boot path or the instance will not start. Both go through+ // resolveInstanceEncryptionKeyBuffer, so this asserts the simulated environments are the right ones:+ // off FIPS the operator's value lands in ENCRYPTION_KEY, on FIPS initEnvConfig relocates it.+ test("agrees with the boot path for the environment the operator will create", () => {+ const hexKey = generateRootEncryptionKey(false);+ expect(resolveKekBuffer(hexKey, false)).toEqual(resolveInstanceEncryptionKeyBuffer({ ENCRYPTION_KEY: hexKey }));++ const b64Key = generateRootEncryptionKey(true);+ expect(resolveKekBuffer(b64Key, true)).toEqual(resolveInstanceEncryptionKeyBuffer({ ROOT_ENCRYPTION_KEY: b64Key }));+ });++ test("a key generated for one mode does not resolve in the other", () => {+ // 32 hex characters base64-decode to 24 bytes, and a 44-character base64 value utf8-decodes to 44,+ // so a key generated for the wrong mode is caught rather than silently producing a bad AES key.+ expect(() => resolveKekBuffer(generateRootEncryptionKey(false), true)).toThrow();+ expect(() => resolveKekBuffer(generateRootEncryptionKey(true), false)).toThrow();+ });+});diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.tsnew file mode 100644index 0000000000..6510bd3dc7--- /dev/null+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.ts@@ -0,0 +1,8 @@+import { crypto } from "@app/lib/crypto/cryptography";+import { resolveInstanceEncryptionKeyBuffer } from "@app/services/kms/kms-fns";++export const generateRootEncryptionKey = (isFipsEnabled: boolean) =>+ isFipsEnabled ? crypto.randomBytes(32).toString("base64") : crypto.randomBytes(16).toString("hex");++export const resolveKekBuffer = (key: string, isFipsEnabled: boolean) =>+ resolveInstanceEncryptionKeyBuffer(isFipsEnabled ? { ROOT_ENCRYPTION_KEY: key } : { ENCRYPTION_KEY: key });diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-service.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-service.tsnew file mode 100644index 0000000000..d8e5233d16--- /dev/null+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-service.ts@@ -0,0 +1,223 @@+import { TEnvConfig } from "@app/lib/config/env";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { getKekFingerprint, KMS_ROOT_CONFIG_UUID } from "@app/services/kms/kms-fns";+import { TKmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";+import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";++import { generateRootEncryptionKey, resolveKekBuffer } from "./encryption-key-rotation-fns";+import {+ RotationBlocker,+ TCreatedRotation,+ TCreateRotationDTO,+ TEncryptionStatus+} from "./encryption-key-rotation-types";++const ABANDONED_ROTATION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days++// How recent a superseded-key boot has to be for `complete` to treat it as a live straggler and refuse.+// Shorter than the GC's window on purpose: the GC is unattended and conservative, whereas an operator+// calling `complete` is asserting their rollout is done, so only fresh evidence should override them.+const STRAGGLER_EVIDENCE_WINDOW_MS = 60 * 60 * 1000; // 1 hour++type TEncryptionKeyRotationServiceFactoryDep = {+ kmsService: Pick<TKmsServiceFactory, "encryptRootKeyForKek" | "getCurrentKekFingerprint">;+ kmsRootConfigDAL: Pick<+ TKmsRootConfigDALFactory,+ "findById" | "findAll" | "findPending" | "findRetained" | "create" | "deleteById" | "deleteAllPending"+ >;+ kmsKekHistoryDAL: Pick<TKmsKekHistoryDALFactory, "findHistory" | "findCurrent" | "updateById">;+ envConfig: Pick<TEnvConfig, "KMS_ROOT_KEY_RETENTION_DAYS">;+ cronJob: TCronJobFactory;+};++export type TEncryptionKeyRotationServiceFactory = ReturnType<typeof encryptionKeyRotationServiceFactory>;++export const encryptionKeyRotationServiceFactory = ({+ kmsService,+ kmsRootConfigDAL,+ kmsKekHistoryDAL,+ envConfig,+ cronJob+}: TEncryptionKeyRotationServiceFactoryDep) => {+ const getStatus = async (): Promise<TEncryptionStatus> => {+ const [sentinel, pendingRows, retainedRows, history] = await Promise.all([+ kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID),+ kmsRootConfigDAL.findPending(),+ kmsRootConfigDAL.findRetained(),+ kmsKekHistoryDAL.findHistory()+ ]);++ // No both-variables-set blocker: a rotation always targets ENCRYPTION_KEY, which+ // $getBasicEncryptionKey always resolves in preference to anything else, so it takes effect+ // regardless of what else the environment holds.+ const blockers: RotationBlocker[] = [];+ if (sentinel?.encryptionStrategy === RootKeyEncryptionStrategy.HSM) blockers.push(RotationBlocker.HsmStrategy);+ if (pendingRows.length) blockers.push(RotationBlocker.RotationPending);++ const [retained] = retainedRows;++ return {+ activeFingerprint: kmsService.getCurrentKekFingerprint(),+ encryptionStrategy: sentinel?.encryptionStrategy ?? null,+ pendingRotation: pendingRows[0] ? { id: pendingRows[0].id, createdAt: pendingRows[0].createdAt } : null,+ retainedKey: retained+ ? {+ id: retained.id,+ supersededAt: retained.supersededAt as Date,+ lastResolvedAt: retained.lastResolvedAt ?? null+ }+ : null,+ history: history.map(({ kekFingerprint, activatedAt, supersededAt, retiredAt }) => ({+ kekFingerprint,+ activatedAt,+ supersededAt,+ retiredAt+ })),+ blockers+ };+ };++ /** Inert by design: the active key is untouched until a pod boots with the new value. */+ const createRotation = async ({ supersede }: TCreateRotationDTO): Promise<TCreatedRotation> => {+ const sentinel = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID);+ if (!sentinel) throw new NotFoundError({ message: "KMS root config not found" });++ if (sentinel.encryptionStrategy === RootKeyEncryptionStrategy.HSM) {+ throw new BadRequestError({+ message:+ "This instance wraps its root key with an HSM, so there is no environment variable to rotate. Rotate the key on the HSM itself, or switch the encryption strategy to software first."+ });+ }++ const existingPending = await kmsRootConfigDAL.findPending();+ if (existingPending.length && !supersede) {+ throw new BadRequestError({+ message: "A rotation is already pending. Deploy that key, discard it, or retry with supersede to replace it."+ });+ }++ const isFipsEnabled = crypto.isFipsModeEnabled();+ const key = generateRootEncryptionKey(isFipsEnabled);+ const kekBuffer = resolveKekBuffer(key, isFipsEnabled);+ const encryptedRootKey = kmsService.encryptRootKeyForKek(kekBuffer);++ // Replace, never accumulate: every pending row is a live working key to the root key.+ if (existingPending.length) await kmsRootConfigDAL.deleteAllPending();++ const pending = await kmsRootConfigDAL.create({+ encryptedRootKey,+ encryptionStrategy: RootKeyEncryptionStrategy.Software,+ activatedAt: null+ });++ const fingerprint = getKekFingerprint(kekBuffer);+ logger.info(`Encryption key rotation staged [rotationId=${pending.id}] [fingerprint=${fingerprint}]`);++ return { id: pending.id, fingerprint, key };+ };++ const discardRotation = async (rotationId: string) => {+ const row = await kmsRootConfigDAL.findById(rotationId);+ if (!row || row.id === KMS_ROOT_CONFIG_UUID) {+ throw new NotFoundError({ message: `Pending encryption key rotation with ID '${rotationId}' not found` });+ }+ if (row.activatedAt) {+ throw new BadRequestError({+ message:+ "That rotation has already been applied by a running instance and cannot be discarded. There is no rollback once a rotation takes effect."+ });+ }+ await kmsRootConfigDAL.deleteById(rotationId);+ logger.info(`Encryption key rotation discarded [rotationId=${rotationId}]`);+ };++ const completeRotation = async (rotationId: string) => {+ const row = await kmsRootConfigDAL.findById(rotationId);+ if (!row || row.id === KMS_ROOT_CONFIG_UUID || !row.supersededAt) {+ throw new NotFoundError({ message: `Retained encryption key with ID '${rotationId}' not found` });+ }++ // Only fresh evidence overrides the operator. An instance that started on this key within the hour+ // is very likely still running, and removing the key would break its next restart.+ const lastResolvedAt = row.lastResolvedAt ? new Date(row.lastResolvedAt).getTime() : null;+ if (lastResolvedAt && Date.now() - lastResolvedAt < STRAGGLER_EVIDENCE_WINDOW_MS) {+ throw new BadRequestError({+ message: `An instance started on the previous encryption key at ${new Date(+ lastResolvedAt+ ).toISOString()} and is likely still running. It would fail to restart if the key were removed now. Roll that instance onto the current key first.`+ });+ }++ await kmsRootConfigDAL.deleteById(rotationId);++ const current = await kmsKekHistoryDAL.findCurrent();+ const history = await kmsKekHistoryDAL.findHistory();+ const retiredEntry = history.find((entry) => entry.id !== current?.id && !entry.retiredAt);+ if (retiredEntry) await kmsKekHistoryDAL.updateById(retiredEntry.id, { retiredAt: new Date() });++ logger.info(`Encryption key rotation completed, previous key removed [retainedKeyId=${rotationId}]`);++ return { retiredFingerprint: retiredEntry?.kekFingerprint ?? null };+ };++ const $runGarbageCollection = async () => {+ const [retained, pending] = await Promise.all([kmsRootConfigDAL.findRetained(), kmsRootConfigDAL.findPending()]);++ // Supersede caps pending at one, so this is for the admin who generated a key and walked away.+ const now = Date.now();+ const abandoned = pending.filter((row) => now - new Date(row.createdAt).getTime() >= ABANDONED_ROTATION_MAX_AGE_MS);+ for (const row of abandoned) {+ // eslint-disable-next-line no-await-in-loop -- at most one row in practice+ await kmsRootConfigDAL.deleteById(row.id);+ logger.info(`Discarded an encryption key rotation that was never applied [rotationId=${row.id}]`);+ }++ if (!retained.length) return;++ const retentionMs = envConfig.KMS_ROOT_KEY_RETENTION_DAYS * 24 * 60 * 60 * 1000;++ // Only the newest copy gets the retention window: it is the only key a lost new key can fall back+ // to. Older ones go as soon as nothing has been seen using them, which caps the table at three rows.+ //+ // lastResolvedAt is the only liveness signal there is, and it can only prove presence. A straggler+ // that never restarts leaves no stamp, so the retention window is what covers it. That is the+ // deliberate limit of this design: the cost of getting it wrong is an instance that fails its next+ // restart with an error naming the key it needs, not lost data.+ const eligible = retained.filter((row, index) => {+ const resolvedRecently = row.lastResolvedAt && now - new Date(row.lastResolvedAt).getTime() < retentionMs;+ if (resolvedRecently) return false;+ return index > 0 || now - new Date(row.supersededAt as Date).getTime() >= retentionMs;+ });++ for (const row of eligible) {+ // eslint-disable-next-line no-await-in-loop -- at most a couple of rows+ await kmsRootConfigDAL.deleteById(row.id);+ logger.info(`Removed a superseded encryption key [retainedKeyId=${row.id}]`);+ }++ const kept = retained.filter((row) => !eligible.includes(row) && row.lastResolvedAt);+ for (const row of kept) {+ logger.info(+ `Keeping the previous encryption key: an instance started on it at ${new Date(+ row.lastResolvedAt as Date+ ).toISOString()} [retainedKeyId=${row.id}]`+ );+ }+ };++ const init = () => {+ cronJob.register({+ name: CronJobName.KmsRootKeyCleanup,+ pattern: "0 3 * * 0",+ runHashTtlS: 60 * 60,+ handler: $runGarbageCollection+ });+ };++ return { init, getStatus, createRotation, discardRotation, completeRotation };+};diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-types.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-types.tsnew file mode 100644index 0000000000..67dc967ee9--- /dev/null+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-types.ts@@ -0,0 +1,29 @@+export enum RotationBlocker {+ HsmStrategy = "hsm-strategy",+ RotationPending = "rotation-pending"+}++export type TEncryptionStatus = {+ activeFingerprint: string | null;+ encryptionStrategy: string | null;+ pendingRotation: { id: string; createdAt: Date } | null;+ retainedKey: { id: string; supersededAt: Date; lastResolvedAt: Date | null } | null;+ history: {+ kekFingerprint: string;+ activatedAt: Date;+ supersededAt?: Date | null;+ retiredAt?: Date | null;+ }[];+ blockers: RotationBlocker[];+};++export type TCreateRotationDTO = {+ supersede?: boolean;+};++export type TCreatedRotation = {+ id: string;+ fingerprint: string;+ /** Returned exactly once. Never stored, never logged. */+ key: string;+};diff --git a/backend/src/services/external-migration/external-migration-queue.ts b/backend/src/services/external-migration/external-migration-queue.tsindex d1b0602536..10821859b8 100644--- a/backend/src/services/external-migration/external-migration-queue.ts+++ b/backend/src/services/external-migration/external-migration-queue.ts@@ -3,6 +3,7 @@ import { randomUUID } from "crypto";import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";import { crypto } from "@app/lib/crypto/cryptography";import { logger } from "@app/lib/logger";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TFolderCommitServiceFactory } from "../folder-commit/folder-commit-service";@@ -118,6 +119,7 @@ export const externalMigrationQueueFactory = ({template: SmtpTemplates.ExternalImportStarted});+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "external_migration" });const decrypted = crypto.encryption().symmetric().decryptWithRootEncryptionKey({ciphertext: data.ciphertext,iv: data.iv,diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.tsindex b620d7076b..58e762900f 100644--- a/backend/src/services/external-migration/external-migration-service.ts+++ b/backend/src/services/external-migration/external-migration-service.ts@@ -15,6 +15,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { GatewayVersion } from "@app/lib/gateway/types";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "../app-connection/app-connection-enums";@@ -187,6 +188,7 @@ export const externalMigrationServiceFactory = ({actorAuthMethod});+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "external_migration" });const encrypted = crypto.encryption().symmetric().encryptWithRootEncryptionKey(stringifiedJson);await externalMigrationQueue.startImport({@@ -277,6 +279,7 @@ export const externalMigrationServiceFactory = ({actorAuthMethod});+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "external_migration" });const encrypted = crypto.encryption().symmetric().encryptWithRootEncryptionKey(stringifiedJson);await externalMigrationQueue.startImport({diff --git a/backend/src/services/kms/kms-fns.ts b/backend/src/services/kms/kms-fns.tsindex 89693ca1d3..3e3b0a5031 100644--- a/backend/src/services/kms/kms-fns.ts+++ b/backend/src/services/kms/kms-fns.ts@@ -1,4 +1,5 @@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";import { BadRequestError } from "@app/lib/errors";@@ -8,8 +9,55 @@ 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 pending 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 buffer = Buffer.from(encryptionKey, envCfg.ENCRYPTION_KEY ? "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 'openssl rand -hex 16'.`+ });+ }++ return buffer;+};++const KEK_FINGERPRINT_DOMAIN = "infisical:kek-fingerprint:v1";++/**+ * A label, never a lookup key: it lets an operator match a restored dump against an archived key.+ * Truncated SHA-256 over a 128-bit-minimum key is not reversible, so it is safe to log and expose.+ */+export const getKekFingerprint = (keyBuffer: Buffer) =>+ crypto.nativeCrypto.createHash("sha256").update(KEK_FINGERPRINT_DOMAIN).update(keyBuffer).digest("hex").slice(0, 32);+export const getByteLengthForSymmetricEncryptionAlgorithm = (encryptionAlgorithm: SymmetricKeyAlgorithm) => {switch (encryptionAlgorithm) {case SymmetricKeyAlgorithm.AES_GCM_128:diff --git a/backend/src/services/kms/kms-kek-history-dal.ts b/backend/src/services/kms/kms-kek-history-dal.tsnew file mode 100644index 0000000000..90476112a0--- /dev/null+++ b/backend/src/services/kms/kms-kek-history-dal.ts@@ -0,0 +1,35 @@+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 TKmsKekHistoryDALFactory = ReturnType<typeof kmsKekHistoryDALFactory>;++export const kmsKekHistoryDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.KmsKekHistory);++ // Outlives the ciphertext it describes and is never pruned: it is how a restored dump is matched to+ // an archived key.+ const findHistory = async (tx?: Knex) => {+ try {+ return await (tx || db.replicaNode())(TableName.KmsKekHistory).select("*").orderBy("activatedAt", "desc");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find kek history" });+ }+ };++ const findCurrent = async (tx?: Knex) => {+ try {+ return await (tx || db)(TableName.KmsKekHistory)+ .whereNull("supersededAt")+ .orderBy("activatedAt", "desc")+ .first("*");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find current kek history" });+ }+ };++ return { ...orm, findHistory, findCurrent };+};diff --git a/backend/src/services/kms/kms-legacy-encryption-key-dal.ts b/backend/src/services/kms/kms-legacy-encryption-key-dal.tsnew file mode 100644index 0000000000..45c7029230--- /dev/null+++ b/backend/src/services/kms/kms-legacy-encryption-key-dal.ts@@ -0,0 +1,7 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TKmsLegacyEncryptionKeyDALFactory = ReturnType<typeof kmsLegacyEncryptionKeyDALFactory>;++export const kmsLegacyEncryptionKeyDALFactory = (db: TDbClient) => ormify(db, TableName.KmsLegacyEncryptionKey);diff --git a/backend/src/services/kms/kms-root-config-dal.ts b/backend/src/services/kms/kms-root-config-dal.tsindex 1b9b9a2301..f4316433ba 100644--- a/backend/src/services/kms/kms-root-config-dal.ts+++ b/backend/src/services/kms/kms-root-config-dal.ts@@ -5,6 +5,8 @@ import { TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify } from "@app/lib/knex";+import { KMS_ROOT_CONFIG_UUID } from "./kms-fns";+export type TKmsRootConfigDALFactory = ReturnType<typeof kmsRootConfigDALFactory>;export const kmsRootConfigDALFactory = (db: TDbClient) => {@@ -21,5 +23,52 @@ export const kmsRootConfigDALFactory = (db: TDbClient) => {}};- return { ...kmsOrm, findById };+ // Primary: a stale read here means failing to find the key this pod holds, or promoting against a+ // superseded view.+ const findAll = async (tx?: Knex) => {+ try {+ return await (tx || db)(TableName.KmsServerRootConfig).select("*");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find all kms root configs" });+ }+ };++ const findPending = async (tx?: Knex) => {+ try {+ return await (tx || db)(TableName.KmsServerRootConfig)+ .whereNull("activatedAt")+ .whereNot("id", KMS_ROOT_CONFIG_UUID)+ .select("*");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find pending kms root configs" });+ }+ };++ /** Newest first; the GC relies on that ordering. */+ const findRetained = async (tx?: Knex) => {+ try {+ return await (tx || db)(TableName.KmsServerRootConfig)+ .whereNotNull("supersededAt")+ .whereNot("id", KMS_ROOT_CONFIG_UUID)+ .select("*")+ .orderBy("supersededAt", "desc");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find retained kms root configs" });+ }+ };++ // Every pending row, not just the promoted one: an abandoned one is a live working key that would+ // otherwise promote itself if it ever reached a deployment.+ const deleteAllPending = async (tx?: Knex) => {+ try {+ return await (tx || db)(TableName.KmsServerRootConfig)+ .whereNull("activatedAt")+ .whereNot("id", KMS_ROOT_CONFIG_UUID)+ .delete();+ } catch (error) {+ throw new DatabaseError({ error, name: "Delete pending kms root configs" });+ }+ };++ return { ...kmsOrm, findById, findAll, findPending, findRetained, deleteAllPending };};diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.tsindex bbff4e5626..fdfcd34dde 100644--- a/backend/src/services/kms/kms-service.ts+++ b/backend/src/services/kms/kms-service.ts@@ -15,24 +15,28 @@ import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";import { THsmStatus } from "@app/ee/services/hsm/hsm-types";import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { withCache } from "@app/lib/cache/with-cache";-import { TEnvConfig } from "@app/lib/config/env";+import { getOriginalConfig, TEnvConfig } from "@app/lib/config/env";import { generateSecretValueBlindIndexFromKmsKey } from "@app/lib/crypto/blind-index";import { symmetricCipherService, SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";import { crypto } from "@app/lib/crypto/cryptography";import { HmacAlgorithm, hmacService } from "@app/lib/crypto/hmac";+import { setLegacyKeyMaterial, TLegacyKeyMaterial, TLegacyKeySnapshot } from "@app/lib/crypto/legacy-key";import { detectPqcVariantFromDer } from "@app/lib/crypto/pqc/pqc-crypto";import { AsymmetricKeyAlgorithm, isPqcKeyAlgorithm, KMS_TO_OPENSSL_NAME, signingService } from "@app/lib/crypto/sign";import { delay } from "@app/lib/delay";-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { alphaNumericNanoId } from "@app/lib/nanoid";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import {getByteLengthForSymmetricEncryptionAlgorithm,+ getKekFingerprint,+ KMS_LEGACY_ENCRYPTION_KEY_UUID,KMS_ROOT_CONFIG_UUID,MAX_HMAC_IMPORT_KEY_BYTE_LENGTH,MIN_HMAC_IMPORT_KEY_BYTE_LENGTH,+ resolveInstanceEncryptionKeyBuffer,verifyKeyTypeAndAlgorithm} from "@app/services/kms/kms-fns";@@ -40,7 +44,9 @@ 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 { TKmsKekHistoryDALFactory } from "./kms-kek-history-dal";import { TKmsKeyDALFactory } from "./kms-key-dal";+import { TKmsLegacyEncryptionKeyDALFactory } from "./kms-legacy-encryption-key-dal";import { TKmsRootConfigDALFactory } from "./kms-root-config-dal";import {KmsDataKey,@@ -68,7 +74,20 @@ type TKmsServiceFactoryDep = {kmsDAL: TKmsKeyDALFactory;projectDAL: Pick<TProjectDALFactory, "findById" | "updateById" | "transaction">;orgDAL: Pick<TOrgDALFactory, "findById" | "updateById" | "transaction">;- kmsRootConfigDAL: Pick<TKmsRootConfigDALFactory, "findById" | "create" | "updateById" | "transaction">;+ kmsRootConfigDAL: Pick<+ TKmsRootConfigDALFactory,+ | "findById"+ | "create"+ | "updateById"+ | "transaction"+ | "findAll"+ | "findPending"+ | "findRetained"+ | "deleteAllPending"+ | "deleteById"+ >;+ kmsLegacyEncryptionKeyDAL: Pick<TKmsLegacyEncryptionKeyDALFactory, "findById" | "create" | "transaction">;+ kmsKekHistoryDAL: Pick<TKmsKekHistoryDALFactory, "create" | "updateById" | "findHistory" | "findCurrent">;internalKmsDAL: Pick<TInternalKmsDALFactory, "create" | "findByKmsKeyIdForUpdate" | "updateById">;internalKmsKeyVersionDAL: Pick<TInternalKmsKeyVersionDALFactory, "create" | "find">;hsmService: THsmServiceFactory;@@ -118,6 +137,8 @@ export const kmsServiceFactory = ({envConfig,kmsDAL,kmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL,+ kmsKekHistoryDAL,internalKmsDAL,internalKmsKeyVersionDAL,orgDAL,@@ -1200,20 +1221,7 @@ export const kmsServiceFactory = ({}};- const $getBasicEncryptionKey = () => {- const encryptionKey = envConfig.ENCRYPTION_KEY || envConfig.ROOT_ENCRYPTION_KEY;-- const isBase64 = !envConfig.ENCRYPTION_KEY;- if (!encryptionKey)- throw new BadRequestError({- message:- "Root encryption key not found for KMS service. Did you set the ENCRYPTION_KEY or ROOT_ENCRYPTION_KEY environment variables?"- });-- const encryptionKeyBuffer = Buffer.from(encryptionKey, isBase64 ? "base64" : "utf8");-- return encryptionKeyBuffer;- };+ const $getBasicEncryptionKey = () => resolveInstanceEncryptionKeyBuffer(envConfig);const $decryptRootKey = async (kmsRootConfig: TKmsRootConfig) => {// case 1: root key is encrypted with HSM@@ -1475,42 +1483,281 @@ export const kmsServiceFactory = ({return { id, name, orgId, isExternal };};- const startService = async (hsmStatus: THsmStatus) => {- const kmsRootConfig = await kmsRootConfigDAL.transaction(async (tx) => {+ /** Null under HSM, where no env key is involved. */+ const $currentKekFingerprint = () => {+ try {+ return getKekFingerprint($getBasicEncryptionKey());+ } catch {+ return null;+ }+ };++ /**+ * The order matters twice: it keeps resolution deterministic when a key is rotated away from and+ * later back to (two rows then open with the same key), and it makes the steady state a single+ * decrypt, which under HSM is a device round trip.+ */+ const $orderRootConfigsForResolution = (rows: TKmsRootConfig[]) => {+ const sentinel = rows.filter((row) => row.id === KMS_ROOT_CONFIG_UUID);+ const others = rows.filter((row) => row.id !== KMS_ROOT_CONFIG_UUID);+ return [...sentinel, ...others.filter((row) => !row.activatedAt), ...others.filter((row) => row.activatedAt)];+ };++ /**+ * The moment a rotation takes effect. Driven by a booting pod rather than the rotate endpoint, so+ * that generating a key is inert and an operator who never deploys it has changed nothing.+ */+ const $promoteRotation = async (pendingId: string, fingerprint: string | null) => {+ return kmsRootConfigDAL.transaction(async (tx) => {await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);- // check if KMS root key was already generated and saved in DB- const existingRootConfig = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID);- if (existingRootConfig) return existingRootConfig;- const isHsmActive = hsmStatus.isHsmConfigured;+ const pending = await kmsRootConfigDAL.findById(pendingId, tx);+ // Another pod promoted first, writing what we were about to write.+ if (!pending || pending.activatedAt) return false;- logger.info(`KMS: Generating new ROOT Key with ${isHsmActive ? "HSM" : "software"} encryption`);- const newRootKey = isHsmActive ? await hsmService.randomBytes(32) : crypto.randomBytes(32);+ const sentinel = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID, tx);+ if (!sentinel) {+ throw new InternalServerError({ message: "KMS root config is missing its active row" });+ }- const encryptionStrategy = isHsmActive ? RootKeyEncryptionStrategy.HSM : RootKeyEncryptionStrategy.Software;+ const now = new Date();- const encryptedRootKey = await $encryptRootKey(newRootKey, encryptionStrategy).catch((err) => {- logger.error({ hsmEnabled: isHsmActive, encryptionStrategy }, "KMS: Failed to encrypt ROOT Key");- throw err;- });+ // The grace window, so pods that have not rolled over can still boot. Not a rollback path.+ await kmsRootConfigDAL.create(+ {+ encryptedRootKey: sentinel.encryptedRootKey,+ encryptionStrategy: sentinel.encryptionStrategy,+ activatedAt: sentinel.activatedAt ?? sentinel.createdAt,+ supersededAt: now+ },+ tx+ );- const newRootConfig = await kmsRootConfigDAL.create({- // @ts-expect-error id is kept as fixed for idempotence and to avoid race condition- id: KMS_ROOT_CONFIG_UUID,- encryptedRootKey,- encryptionStrategy- });- return newRootConfig;+ await kmsRootConfigDAL.updateById(+ KMS_ROOT_CONFIG_UUID,+ {+ encryptedRootKey: pending.encryptedRootKey,+ encryptionStrategy: pending.encryptionStrategy,+ activatedAt: now,+ supersededAt: null+ },+ tx+ );++ await kmsRootConfigDAL.deleteAllPending(tx);++ const previous = await kmsKekHistoryDAL.findCurrent(tx);+ if (previous) await kmsKekHistoryDAL.updateById(previous.id, { supersededAt: now }, tx);+ if (fingerprint) await kmsKekHistoryDAL.create({ kekFingerprint: fingerprint, activatedAt: now }, tx);++ return true;});+ };- const decryptedRootKey = await $decryptRootKey(kmsRootConfig);+ const $bootstrapRootKey = async (hsmStatus: THsmStatus) => {+ const isHsmActive = hsmStatus.isHsmConfigured;- logger.info("KMS: Loading ROOT Key into Memory.");+ logger.info(`KMS: Generating new ROOT Key with ${isHsmActive ? "HSM" : "software"} encryption`);+ const newRootKey = isHsmActive ? await hsmService.randomBytes(32) : crypto.randomBytes(32);+ const encryptionStrategy = isHsmActive ? RootKeyEncryptionStrategy.HSM : RootKeyEncryptionStrategy.Software;+ // Wrapped before the transaction opens: this can be an HSM round trip. If another pod wins the+ // race below, this key is discarded unused.+ const encryptedRootKey = await $encryptRootKey(newRootKey, encryptionStrategy).catch((err) => {+ logger.error({ hsmEnabled: isHsmActive, encryptionStrategy }, "KMS: Failed to encrypt ROOT Key");+ throw err;+ });++ return kmsRootConfigDAL.transaction(async (tx) => {+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);++ const existing = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID, tx);+ if (existing) return existing;++ return kmsRootConfigDAL.create(+ {+ // @ts-expect-error id is kept as fixed for idempotence and to avoid race condition+ id: KMS_ROOT_CONFIG_UUID,+ encryptedRootKey,+ encryptionStrategy,+ activatedAt: new Date()+ },+ tx+ );+ });+ };++ const $resolveRootKey = async (hsmStatus: THsmStatus) => {+ const rows = await kmsRootConfigDAL.findAll();+ if (!rows.length) {+ const created = await $bootstrapRootKey(hsmStatus);+ return $decryptRootKey(created);+ }++ const errors: unknown[] = [];+ for (const row of $orderRootConfigsForResolution(rows)) {+ // eslint-disable-next-line no-await-in-loop -- at most three rows, and the first hit returns+ const rootKey = await $decryptRootKey(row).then(+ (key) => key,+ (err: unknown) => {+ errors.push(err);+ return null;+ }+ );++ if (rootKey) {+ if (!row.activatedAt && row.id !== KMS_ROOT_CONFIG_UUID) {+ const fingerprint = $currentKekFingerprint();+ // eslint-disable-next-line no-await-in-loop+ const promoted = await $promoteRotation(row.id, fingerprint);+ if (promoted) {+ logger.info(+ `KMS: Promoted pending encryption key rotation [fingerprint=${fingerprint ?? "hsm"}] [rotationId=${+ row.id+ }]`+ );+ }+ }++ // Only a retained copy is worth stamping: it is positive evidence that a straggler still holds+ // that key, which is what makes the rotation GC decline to remove it. Absence proves nothing,+ // since an instance that never restarts never stamps. The sentinel is never deleted, so+ // stamping it would be a write on every boot for nothing.+ if (row.supersededAt) {+ // eslint-disable-next-line no-await-in-loop+ await kmsRootConfigDAL+ .updateById(row.id, { lastResolvedAt: new Date() })+ .catch((err: unknown) => logger.warn({ err }, "KMS: Failed to record use of a superseded root key"));+ logger.warn(+ `KMS: This instance started on a superseded encryption key [rootConfigId=${row.id}] [fingerprint=${+ $currentKekFingerprint() ?? "hsm"+ }]. Roll it onto the current key before the previous one is removed.`+ );+ }++ return rootKey;+ }+ }++ const fingerprint = $currentKekFingerprint();+ const history = await kmsKekHistoryDAL.findHistory().catch(() => []);+ const known = history.map((entry) => entry.kekFingerprint).join(", ");+ logger.error({ err: errors[0] }, "KMS: No stored root key could be decrypted with the configured encryption key");+ throw new InternalServerError({+ message: `The configured encryption key (fingerprint ${fingerprint ?? "unknown"}) does not decrypt this database's root key. ${+ known+ ? `This database was last written with encryption key fingerprint(s): ${known}. Set the matching key and restart.`+ : "Set the encryption key this database was created with and restart."+ }`+ });+ };++ const $parseLegacyKeySnapshot = (encryptedKeySnapshot: Buffer) =>+ JSON.parse(decryptWithRootKey()(encryptedKeySnapshot).toString("utf8")) as TLegacyKeyMaterial;++ /**+ * Snapshots the legacy tier's env keys under the in-DB root key, which survives an env-key rotation.+ * After this that tier no longer reads process.env, so rotating cannot strand its rows.+ */+ const $ensureLegacyKeyMaterial = async () => {+ const existing = await kmsLegacyEncryptionKeyDAL.findById(KMS_LEGACY_ENCRYPTION_KEY_UUID);+ if (existing) {+ setLegacyKeyMaterial($parseLegacyKeySnapshot(existing.encryptedKeySnapshot));+ return;+ }++ const current: TLegacyKeySnapshot = {+ ENCRYPTION_KEY: envConfig.ENCRYPTION_KEY,+ ROOT_ENCRYPTION_KEY: envConfig.ROOT_ENCRYPTION_KEY+ };++ // The FIPS relabel overwrites ROOT_ENCRYPTION_KEY unconditionally, so `current` can be missing the+ // key existing rows were written under. Capturing it also means fixing that later needs no repair.+ const originalCfg = getOriginalConfig() as TLegacyKeySnapshot | undefined;+ const original: TLegacyKeySnapshot | undefined = originalCfg+ ? { ENCRYPTION_KEY: originalCfg.ENCRYPTION_KEY, ROOT_ENCRYPTION_KEY: originalCfg.ROOT_ENCRYPTION_KEY }+ : undefined;++ const hasKey = (snapshot?: TLegacyKeySnapshot) =>+ Boolean(snapshot && (snapshot.ENCRYPTION_KEY || snapshot.ROOT_ENCRYPTION_KEY));++ // Pure HSM, no env key: leave the legacy tier throwing exactly as it does today.+ if (!hasKey(current) && !hasKey(original)) return;++ const material: TLegacyKeyMaterial = { current, original };+ const encryptedKeySnapshot = encryptWithRootKey()(Buffer.from(JSON.stringify(material), "utf8"));++ await kmsLegacyEncryptionKeyDAL.transaction(async (tx) => {+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);+ const alreadySeeded = await kmsLegacyEncryptionKeyDAL.findById(KMS_LEGACY_ENCRYPTION_KEY_UUID, tx);+ if (alreadySeeded) return;+ await kmsLegacyEncryptionKeyDAL.create(+ {+ // @ts-expect-error id is fixed so a concurrent seed conflicts rather than duplicating+ id: KMS_LEGACY_ENCRYPTION_KEY_UUID,+ encryptedKeySnapshot+ },+ tx+ );+ });++ // Re-read so every pod lands on the row that won the race, not its own candidate.+ const seeded = await kmsLegacyEncryptionKeyDAL.findById(KMS_LEGACY_ENCRYPTION_KEY_UUID);+ setLegacyKeyMaterial(seeded ? $parseLegacyKeySnapshot(seeded.encryptedKeySnapshot) : material);+ };++ /**+ * Backfills the key an instance already runs with, so a pre-rotation dump still has a fingerprint an+ * operator can match against an archived key.+ */+ const $ensureKekHistory = async () => {+ const fingerprint = $currentKekFingerprint();+ if (!fingerprint) return;++ const current = await kmsKekHistoryDAL.findCurrent();+ if (current) return;++ const sentinel = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID);+ await kmsKekHistoryDAL+ .create({ kekFingerprint: fingerprint, activatedAt: sentinel?.activatedAt ?? sentinel?.createdAt ?? new Date() })+ .catch((err: unknown) => {+ // Never block boot on a bookkeeping row.+ logger.warn({ err }, "KMS: Failed to record initial encryption key history entry");+ });+ };++ const startService = async (hsmStatus: THsmStatus) => {+ const decryptedRootKey = await $resolveRootKey(hsmStatus);++ logger.info("KMS: Loading ROOT Key into Memory.");ROOT_ENCRYPTION_KEY = decryptedRootKey;++ await $ensureLegacyKeyMaterial();+ await $ensureKekHistory();+ };++ /** How a rotation stages a key the instance is not running with yet. */+ const encryptRootKeyForKek = (kekBuffer: Buffer) => {+ if (!ROOT_ENCRYPTION_KEY.length) {+ throw new InternalServerError({ message: "KMS root key is not loaded" });+ }+ const cipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);+ return cipher.encrypt(ROOT_ENCRYPTION_KEY, kekBuffer);};+ const getCurrentKekFingerprint = () => $currentKekFingerprint();+const updateEncryptionStrategy = async (strategy: RootKeyEncryptionStrategy) => {+ // A fleet-wide cutover. Unguarded, a switch to HSM would not take effect while a retained software+ // copy exists: a pod with the old env key would resolve that copy and boot without the device.+ const [pending, retained] = await Promise.all([kmsRootConfigDAL.findPending(), kmsRootConfigDAL.findRetained()]);+ if (pending.length || retained.length) {+ throw new BadRequestError({+ message:+ "An encryption key rotation is still in progress. Complete or discard it before changing the root key encryption strategy."+ });+ }+const kmsRootConfig = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID);if (!kmsRootConfig) {throw new NotFoundError({ message: "KMS root config not found" });@@ -1529,6 +1776,7 @@ export const kmsServiceFactory = ({}}+ // Both can be HSM round trips, so they stay outside the transaction.const decryptedRootKey = await $decryptRootKey(kmsRootConfig);const encryptedRootKey = await $encryptRootKey(decryptedRootKey, strategy);@@ -1537,9 +1785,16 @@ export const kmsServiceFactory = ({throw new BadRequestError({ message: "Failed to re-encrypt ROOT Key with selected strategy" });}- await kmsRootConfigDAL.updateById(KMS_ROOT_CONFIG_UUID, {- encryptedRootKey,- encryptionStrategy: strategy+ await kmsRootConfigDAL.transaction(async (tx) => {+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);+ await kmsRootConfigDAL.updateById(+ KMS_ROOT_CONFIG_UUID,+ {+ encryptedRootKey,+ encryptionStrategy: strategy+ },+ tx+ );});ROOT_ENCRYPTION_KEY = decryptedRootKey;@@ -1547,6 +1802,8 @@ export const kmsServiceFactory = ({return {startService,+ encryptRootKeyForKek,+ getCurrentKekFingerprint,generateKmsKey,rotateKmsKey,deleteInternalKms,diff --git a/backend/src/services/project-bot/project-bot-fns.ts b/backend/src/services/project-bot/project-bot-fns.tsindex 5667f7cfa5..6a9a73f108 100644--- a/backend/src/services/project-bot/project-bot-fns.ts+++ b/backend/src/services/project-bot/project-bot-fns.ts@@ -1,14 +1,18 @@import { SecretKeyEncoding } from "@app/db/schemas";import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";import { TProjectDALFactory } from "../project/project-dal";import { TGetPrivateKeyDTO } from "./project-bot-types";export const getBotPrivateKey = ({ bot }: TGetPrivateKeyDTO) => {+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "project_bot" });+ logger.info(`Legacy root key used to read a project bot key [projectId=${bot.projectId}]`);return crypto.encryption().symmetric()@@ -60,6 +64,8 @@ export const getBotKeyFnFactory = (projectV1Keys.serverEncryptedPrivateKeyTag &&projectV1Keys.serverEncryptedPrivateKeyEncoding) {+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "user_private_key" });+ logger.info(`Legacy root key used to read a server-held user private key [projectId=${projectId}]`);userPrivateKey = crypto.encryption().symmetric()@@ -77,6 +83,8 @@ export const getBotKeyFnFactory = (privateKey: userPrivateKey});const botKey = await crypto.encryption().asymmetric().generateKeyPair();+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "project_bot" });+ logger.info(`Legacy root key used to create a project bot [projectId=${projectId}]`);const { iv, tag, ciphertext, encoding, algorithm } = crypto.encryption().symmetric()diff --git a/backend/src/services/project-bot/project-bot-service.ts b/backend/src/services/project-bot/project-bot-service.tsindex c6625c28a6..8bc7236cf7 100644--- a/backend/src/services/project-bot/project-bot-service.ts+++ b/backend/src/services/project-bot/project-bot-service.ts@@ -5,6 +5,8 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { TProjectDALFactory } from "../project/project-dal";import { TProjectBotDALFactory } from "./project-bot-dal";@@ -57,6 +59,8 @@ export const projectBotServiceFactory = ({const keys =privateKey && publicKey ? { privateKey, publicKey } : await crypto.encryption().asymmetric().generateKeyPair();+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "project_bot" });+ logger.info(`Legacy root key used to create a project bot [projectId=${projectId}]`);const { iv, tag, ciphertext, encoding, algorithm } = crypto.encryption().symmetric()diff --git a/backend/src/services/project/project-queue.ts b/backend/src/services/project/project-queue.tsindex 53dd41e2e2..8bde05c53e 100644--- a/backend/src/services/project/project-queue.ts+++ b/backend/src/services/project/project-queue.ts@@ -30,6 +30,7 @@ import {} from "@app/lib/crypto";import { crypto } from "@app/lib/crypto/cryptography";import { logger } from "@app/lib/logger";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueJobTypes, TQueueServiceFactory } from "@app/queue";import { JobState } from "@app/queue/queue-service";@@ -129,6 +130,8 @@ export const projectQueueFactory = ({await projectDAL.setProjectUpgradeStatus(data.projectId, ProjectUpgradeStatus.InProgress); // Set the status to in progress. This is important to prevent multiple upgrades at the same time.+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "user_private_key" });+ logger.info(`Legacy root key used during project upgrade [projectId=${data.projectId}]`);const userPrivateKey = crypto.encryption().symmetric().decryptWithRootEncryptionKey({keyEncoding: data.encryptedPrivateKey.keyEncoding,ciphertext: data.encryptedPrivateKey.encryptedKey,@@ -337,6 +340,7 @@ export const projectQueueFactory = ({await projectKeyDAL.insertMany(newProjectMembers, tx);// Encrypt the bot private key (which is the same as the ghost user)+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "project_ghost_user" });const { iv, tag, ciphertext, encoding, algorithm } = crypto.encryption().symmetric()@@ -361,6 +365,7 @@ export const projectQueueFactory = ({tx);+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "project_bot" });const botPrivateKey = crypto.encryption().symmetric()diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex dde4507539..76ab80a7c9 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -53,6 +53,7 @@ import { groupBy } from "@app/lib/fn";import { alphaNumericNanoId } from "@app/lib/nanoid";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { OrgServiceActor, TProjectPermission } from "@app/lib/types";import { PamIdentities, SecretIdentities } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";@@ -1147,6 +1148,7 @@ export const projectServiceFactory = ({});}+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "project_ghost_user" });const encryptedPrivateKey = crypto.encryption().symmetric().encryptWithRootEncryptionKey(userPrivateKey);await projectQueue.upgradeProject({diff --git a/backend/src/services/secret/secret-fns.ts b/backend/src/services/secret/secret-fns.tsindex d21d4c5293..2a33437582 100644--- a/backend/src/services/secret/secret-fns.ts+++ b/backend/src/services/secret/secret-fns.ts@@ -21,6 +21,7 @@ import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { groupBy, unique } from "@app/lib/fn";import { logger } from "@app/lib/logger";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { getAllSecretReferences } from "@app/services/secret-v2-bridge/secret-reference-fns";import {fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,@@ -52,6 +53,7 @@ export const INFISICAL_SECRET_VALUE_HIDDEN_MASK = "<hidden-by-infisical>";export const generateSecretBlindIndexBySalt = async (secretName: string, secretBlindIndexDoc: TSecretBlindIndexes) => {const appCfg = getConfig();+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "blind_index" });const secretBlindIndex = await buildSecretBlindIndexFromName({secretName,keyEncoding: secretBlindIndexDoc.keyEncoding as SecretKeyEncoding,diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.tsindex ad4df595ce..e5175e3a4d 100644--- a/backend/src/services/secret/secret-queue.ts+++ b/backend/src/services/secret/secret-queue.ts@@ -24,7 +24,7 @@ import { getTimeDifferenceInSeconds, groupBy, isSamePath, unique } from "@app/liimport { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";-import { highCardinalityMeter } from "@app/lib/telemetry/metrics";+import { highCardinalityMeter, recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";import { createManySecretsRawFnFactory, updateManySecretsRawFnFactory } from "@app/services/secret/secret-fns";@@ -1332,6 +1332,8 @@ export const secretQueueFactory = ({},tx);+ recordLegacyRootKeyUsageMetric({ operation: "encrypt", surface: "project_ghost_user" });+ logger.info(`Legacy root key used to create a project ghost user [projectId=${project.id}]`);const { iv, tag, ciphertext, encoding, algorithm } = crypto.encryption().symmetric()diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.tsindex 559a0a145d..86ba15ac19 100644--- a/backend/src/services/secret/secret-service.ts+++ b/backend/src/services/secret/secret-service.ts@@ -37,6 +37,7 @@ import { logger } from "@app/lib/logger";import { alphaNumericNanoId } from "@app/lib/nanoid";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";import { OrgServiceActor } from "@app/lib/types";import {SecretUpdateMode,@@ -214,6 +215,8 @@ export const secretServiceFactory = ({});}+ recordLegacyRootKeyUsageMetric({ operation: "decrypt", surface: "blind_index" });+ logger.info(`Legacy root key used for a v1 blind index [projectId=${projectId}]`);const secretBlindIndex = await buildSecretBlindIndexFromName({secretName,keyEncoding: secretBlindIndexDoc.keyEncoding as SecretKeyEncoding,diff --git a/docs/docs.json b/docs/docs.jsonindex 95e9e23114..3a7db8ef3c 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -413,6 +413,7 @@"self-hosting/guides/custom-certificates","self-hosting/guides/automated-bootstrapping","self-hosting/guides/production-hardening",+ "self-hosting/guides/rotating-the-encryption-key","self-hosting/guides/monitoring-telemetry"]},diff --git a/docs/images/self-hosting/guides/rotating-encryption-key/generate-key.png b/docs/images/self-hosting/guides/rotating-encryption-key/generate-key.pngnew file mode 100644index 0000000000..4aad1109a7Binary files /dev/null and b/docs/images/self-hosting/guides/rotating-encryption-key/generate-key.png differdiff --git a/docs/images/self-hosting/guides/rotating-encryption-key/remove-key.png b/docs/images/self-hosting/guides/rotating-encryption-key/remove-key.pngnew file mode 100644index 0000000000..3efbc55509Binary files /dev/null and b/docs/images/self-hosting/guides/rotating-encryption-key/remove-key.png differdiff --git a/docs/self-hosting/guides/rotating-the-encryption-key.mdx b/docs/self-hosting/guides/rotating-the-encryption-key.mdxnew file mode 100644index 0000000000..56566db345--- /dev/null+++ b/docs/self-hosting/guides/rotating-the-encryption-key.mdx@@ -0,0 +1,95 @@+---+title: "Rotating the Encryption Key"+description: "Replace the ENCRYPTION_KEY protecting your Infisical instance without downtime"+---++[`ENCRYPTION_KEY`](/self-hosting/configuration/envars#param-encryption-key) protects every secret in your+instance. Rotating it periodically limits how much a leaked key is worth, and some compliance programs+require it on a fixed schedule.++Rotating is a two-part process by design: Infisical generates a key, and **the rotation only takes effect+when an instance first starts with the new value**. Generating a key changes nothing, so you can generate+one, think about it, and discard it with no consequences.++<Note>+ Your secrets are never re-encrypted. Only a small internal wrapper changes, so a rotation is instant+ regardless of how many secrets you store, and there is no read-only window.+</Note>++## Before you start++- You need **server admin** access.+- If your instance uses an [HSM](/self-hosting/guides/hsm-integration), there is no environment variable+ to rotate. Rotate the key on the HSM instead.+- Decide where you will keep the **old** key. See [After the rotation](#after-the-rotation).++## Rotate++<Steps>+ <Step title="Generate a new key">+ Go to **Admin > Encryption** and select **Generate new key** under **Root encryption key**.++ + </Step>++ <Step title="Store the key">+ The key is shown once and is never recoverable. Copy it into your secret store before closing the+ dialog, together with the **fingerprint** shown beside it.++ If you think the key was exposed while copying it, select **Discard generated key**. It stops working+ immediately and you can generate another.+ </Step>++ <Step title="Deploy">+ Set `ENCRYPTION_KEY` to the new value and restart your instances as you normally would. A rolling+ restart works and needs no downtime.++ The first instance that starts with the new key applies the rotation. Instances that have not restarted+ yet keep serving normally, and instances that restart on the old key still start.+ </Step>++ <Step title="Remove the old key">+ Return to **Admin > Encryption**. The panel tells you when an instance last started on the previous+ key. Once you are satisfied your rollout is complete, select **Remove previous key**.++ Until you do, the old key still opens your database, so the rotation has not reduced your exposure yet.+ If you do nothing, Infisical removes it automatically once it has been superseded for+ `KMS_ROOT_KEY_RETENTION_DAYS` (7 by default).++ ++ <Note>+ Infisical can only see instances that have *started* on the previous key, so it will refuse to remove+ a key one started on recently. It cannot see an instance that has been running since before the+ rotation and has not restarted. If such an instance restarts after the key is gone, it fails to start+ with an error naming the key it needs; setting that key again brings it back.+ </Note>+ </Step>+</Steps>++## After the rotation++<Warning>+ Removing the previous key cannot be undone. Afterwards, losing the new key means losing access to every+ secret in the instance, and any database backup taken before the rotation needs the old key to restore.+</Warning>++Pick one of these and make it explicit, rather than leaving it to chance:++- **Archive the old key.** Keep it in your secret store for at least as long as your oldest restorable+ backup, labelled with the fingerprint from the **Key history** table. That table is kept permanently, so+ a restored backup can always be matched to the key it needs.+- **Crypto-shred.** Remove the old key, take a fresh full backup immediately, and expire backups taken+ before the rotation. A backup nobody can decrypt is also a backup that cannot leak.++The **Key history** table lists every key the instance has used and when. If an instance ever fails to+start with "the configured encryption key does not decrypt this database's root key", the error names the+fingerprint it needs, which you can look up there.++## Rolling back++There is no rollback once a rotation has been applied.++Before the first instance starts with the new key, nothing has changed, so reverting `ENCRYPTION_KEY` is+enough. After that, the old key keeps working only until it is removed, and that window exists so instances+can finish rolling over, not as a way to undo the rotation.diff --git a/frontend/src/hooks/api/admin/mutation.ts b/frontend/src/hooks/api/admin/mutation.tsindex 2381d5e2f9..14d180fdb2 100644--- a/frontend/src/hooks/api/admin/mutation.ts+++ b/frontend/src/hooks/api/admin/mutation.ts@@ -11,6 +11,7 @@ import {RootKeyEncryptionStrategy,TAdminCreateEmailDomainDTO,TCreateAdminUserDTO,+ TCreatedEncryptionKeyRotation,TCreateOrganizationDTO,TInvalidateCacheDTO,TResendOrgInviteDTO,@@ -191,6 +192,46 @@ export const useUpdateServerEncryptionStrategy = () => {});};+export const useCreateEncryptionKeyRotation = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ supersede }: { supersede?: boolean } = {}) => {+ const { data } = await apiRequest.post<{ rotation: TCreatedEncryptionKeyRotation }>(+ `/api/v1/admin/encryption/rotations${supersede ? "?supersede=true" : ""}`+ );++ return data.rotation;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });+ }+ });+};++export const useDiscardEncryptionKeyRotation = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (rotationId: string) => {+ await apiRequest.delete(`/api/v1/admin/encryption/rotations/${rotationId}`);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });+ }+ });+};++export const useCompleteEncryptionKeyRotation = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (rotationId: string) => {+ await apiRequest.post(`/api/v1/admin/encryption/rotations/${rotationId}/complete`);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });+ }+ });+};+export const useInvalidateCache = () => {const queryClient = useQueryClient();return useMutation<void, object, TInvalidateCacheDTO>({diff --git a/frontend/src/hooks/api/admin/queries.ts b/frontend/src/hooks/api/admin/queries.tsindex 8f6e708372..e1f6518fc1 100644--- a/frontend/src/hooks/api/admin/queries.ts+++ b/frontend/src/hooks/api/admin/queries.ts@@ -8,6 +8,7 @@ import {AdminGetOrganizationsFilters,AdminGetUsersFilters,AdminIntegrationsConfig,+ TEncryptionStatus,TGetEmailDomainsResponse,TGetEnvOverrides,TGetIdentitiesResponse,@@ -34,6 +35,7 @@ export const adminQueryKeys = {[adminStandaloneKeys.getIdentities, { filters }] as const,getAdminSlackConfig: () => ["admin-slack-config"] as const,getServerEncryptionStrategies: () => ["server-encryption-strategies"] as const,+ getEncryptionStatus: () => ["server-encryption-status"] as const,getInvalidateCache: () => ["admin-invalidate-cache"] as const,getAdminIntegrationsConfig: () => ["admin-integrations-config"] as const,getEnvOverrides: () => ["env-overrides"] as const,@@ -147,6 +149,19 @@ export const useGetServerRootKmsEncryptionDetails = () => {});};+export const useGetEncryptionStatus = () => {+ return useQuery({+ queryKey: adminQueryKeys.getEncryptionStatus(),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ status: TEncryptionStatus }>(+ "/api/v1/admin/encryption/status"+ );++ return data.status;+ }+ });+};+export const useGetInvalidatingCacheStatus = (enabled = true) => {return useQuery({queryKey: adminQueryKeys.getInvalidateCache(),diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.tsindex 52921ded05..dd3921c943 100644--- a/frontend/src/hooks/api/admin/types.ts+++ b/frontend/src/hooks/api/admin/types.ts@@ -240,3 +240,28 @@ export type TResendOrgInviteDTO = {organizationId: string;membershipId: string;};++export enum EncryptionRotationBlocker {+ HsmStrategy = "hsm-strategy",+ RotationPending = "rotation-pending"+}++export type TEncryptionStatus = {+ activeFingerprint: string | null;+ encryptionStrategy: string | null;+ pendingRotation: { id: string; createdAt: string } | null;+ retainedKey: { id: string; supersededAt: string; lastResolvedAt: string | null } | null;+ history: {+ kekFingerprint: string;+ activatedAt: string;+ supersededAt?: string | null;+ retiredAt?: string | null;+ }[];+ blockers: EncryptionRotationBlocker[];+};++export type TCreatedEncryptionKeyRotation = {+ id: string;+ fingerprint: string;+ key: string;+};diff --git a/frontend/src/pages/admin/EncryptionPage/EncryptionPage.tsx b/frontend/src/pages/admin/EncryptionPage/EncryptionPage.tsxindex f4aa50e0d1..df1a4b6b79 100644--- a/frontend/src/pages/admin/EncryptionPage/EncryptionPage.tsx+++ b/frontend/src/pages/admin/EncryptionPage/EncryptionPage.tsx@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";import { PageHeader } from "@app/components/v2";-import { EncryptionPageForm } from "./components";+import { EncryptionKeyRotationSection, EncryptionPageForm } from "./components";export const EncryptionPage = () => {const { t } = useTranslation();@@ -21,6 +21,7 @@ export const EncryptionPage = () => {description="Manage encryption settings for your Infisical instance."/><EncryptionPageForm />+ <EncryptionKeyRotationSection /></div></div></div>diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsxnew file mode 100644index 0000000000..06f574aa5d--- /dev/null+++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx@@ -0,0 +1,253 @@+import { useState } from "react";+import { AlertTriangleIcon, KeyRoundIcon, ShieldAlertIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Badge,+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ CopyButton,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import {+ useCompleteEncryptionKeyRotation,+ useCreateEncryptionKeyRotation,+ useDiscardEncryptionKeyRotation,+ useGetEncryptionStatus+} from "@app/hooks/api";+import {+ EncryptionRotationBlocker,+ TCreatedEncryptionKeyRotation+} from "@app/hooks/api/admin/types";++const BLOCKER_COPY: Record<EncryptionRotationBlocker, string> = {+ [EncryptionRotationBlocker.HsmStrategy]:+ "This instance wraps its root key with an HSM, so there is no environment variable to rotate. Rotate the key on the HSM itself.",+ [EncryptionRotationBlocker.RotationPending]:+ "A key has already been generated and is waiting to be applied. Apply it, discard it, or generate a replacement."+};++export const EncryptionKeyRotationSection = () => {+ const { data: status, isPending } = useGetEncryptionStatus();+ const { mutateAsync: createRotation, isPending: isCreating } = useCreateEncryptionKeyRotation();+ const { mutateAsync: discardRotation } = useDiscardEncryptionKeyRotation();+ const { mutateAsync: completeRotation, isPending: isCompleting } =+ useCompleteEncryptionKeyRotation();++ const [generatedKey, setGeneratedKey] = useState<TCreatedEncryptionKeyRotation | null>(null);+ const [acknowledged, setAcknowledged] = useState(false);++ if (isPending || !status) return null;++ const rotateBlockers = status.blockers.filter(+ (blocker) => blocker !== EncryptionRotationBlocker.RotationPending+ );+ const canRotate = rotateBlockers.length === 0;++ const handleGenerate = async () => {+ const rotation = await createRotation({ supersede: Boolean(status.pendingRotation) });+ setGeneratedKey(rotation);+ };++ const handleDiscard = async () => {+ if (!status.pendingRotation) return;+ await discardRotation(status.pendingRotation.id);+ createNotification({ type: "success", text: "Generated encryption key discarded." });+ };++ const handleComplete = async () => {+ if (!status.retainedKey) return;+ await completeRotation(status.retainedKey.id);+ setAcknowledged(false);+ createNotification({ type: "success", text: "Previous encryption key removed." });+ };++ return (+ <>+ <Card className="mt-6">+ <CardHeader>+ <CardTitle>Root encryption key</CardTitle>+ <CardDescription>+ Rotate the key that protects every secret in this instance. Generating a key changes+ nothing on its own: the rotation takes effect the first time an instance starts with the+ new value.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ <div className="flex items-center gap-2 text-sm">+ <KeyRoundIcon className="size-4 text-foreground/60" />+ <span className="text-foreground/70">Active key</span>+ <Badge variant="neutral" className="font-mono">+ {status.activeFingerprint ?? "managed by HSM"}+ </Badge>+ </div>++ {status.blockers.map((blocker) => (+ <Alert+ key={blocker}+ variant={blocker === EncryptionRotationBlocker.RotationPending ? "info" : "warning"}+ >+ <AlertTriangleIcon />+ <AlertDescription>{BLOCKER_COPY[blocker]}</AlertDescription>+ </Alert>+ ))}++ {canRotate && (+ <div className="flex flex-wrap gap-3">+ <Button onClick={handleGenerate} isPending={isCreating}>+ {status.pendingRotation ? "Generate a replacement key" : "Generate new key"}+ </Button>+ {status.pendingRotation && (+ <Button variant="danger" onClick={handleDiscard}>+ Discard generated key+ </Button>+ )}+ </div>+ )}++ {status.retainedKey && (+ <Alert variant="warning">+ <ShieldAlertIcon />+ <AlertTitle>The previous key still works</AlertTitle>+ <AlertDescription>+ <p>+ Until it is removed, the old key still opens this database, so the rotation has+ not reduced exposure yet. It also means an instance that has not restarted onto+ the new key can still start.+ </p>+ <p className="mt-2">+ {status.retainedKey.lastResolvedAt+ ? `An instance last started on it ${new Date(+ status.retainedKey.lastResolvedAt+ ).toLocaleString()}. Roll that instance onto the new key first.`+ : "No instance has started on it since the rotation. Instances that have not restarted yet will not have reported."}+ </p>+ <div className="mt-3 flex flex-col gap-2">+ <label className="flex items-start gap-2 text-xs" htmlFor="ack-remove-old-key">+ <input+ id="ack-remove-old-key"+ type="checkbox"+ checked={acknowledged}+ onChange={(e) => setAcknowledged(e.target.checked)}+ className="mt-0.5"+ />+ <span>+ I have stored the new key somewhere I can recover it, and I understand that+ database backups taken before this rotation will need the old key, which is+ about to be removed.+ </span>+ </label>+ <Button+ className="self-start"+ variant="danger"+ isDisabled={!acknowledged}+ isPending={isCompleting}+ onClick={handleComplete}+ >+ Remove previous key+ </Button>+ </div>+ </AlertDescription>+ </Alert>+ )}++ {status.history.length > 0 && (+ <div>+ <p className="mb-2 text-sm font-medium">Key history</p>+ <p className="mb-2 text-xs text-foreground/60">+ Kept after a key is removed. Use the fingerprint to work out which archived key a+ restored backup needs.+ </p>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Fingerprint</TableHead>+ <TableHead>Active from</TableHead>+ <TableHead>Status</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {status.history.map((entry) => (+ <TableRow key={entry.kekFingerprint + entry.activatedAt}>+ <TableCell className="font-mono text-xs">{entry.kekFingerprint}</TableCell>+ <TableCell>{new Date(entry.activatedAt).toLocaleString()}</TableCell>+ <TableCell>+ {!entry.supersededAt && <Badge variant="success">Active</Badge>}+ {entry.supersededAt && !entry.retiredAt && (+ <Badge variant="neutral">Superseded</Badge>+ )}+ {entry.retiredAt && <Badge variant="neutral">Removed</Badge>}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ </CardContent>+ </Card>++ <Dialog open={Boolean(generatedKey)} onOpenChange={(open) => !open && setGeneratedKey(null)}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Copy your new encryption key</DialogTitle>+ <DialogDescription>+ This is the only time it will be shown. If you lose it before applying it, discard it+ and generate another.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="flex flex-col gap-4">+ <div>+ <p className="mb-1.5 text-sm font-medium">Set this environment variable</p>+ <div className="flex items-center gap-2 rounded-md border border-border bg-container px-3 py-2 font-mono text-sm">+ <span className="flex-1 break-all">ENCRYPTION_KEY={generatedKey?.key}</span>+ <CopyButton+ value={`ENCRYPTION_KEY=${generatedKey?.key}`}+ ariaLabel="Copy encryption key"+ />+ </div>+ </div>++ <div>+ <p className="mb-1.5 text-sm font-medium">Fingerprint</p>+ <p className="font-mono text-xs text-foreground/70">{generatedKey?.fingerprint}</p>+ <p className="mt-1 text-xs text-foreground/60">+ Store this alongside the key. It is how you identify which key a database backup+ needs.+ </p>+ </div>++ <Alert variant="info">+ <AlertDescription>+ Nothing has changed yet. Deploy this value, and the rotation takes effect when the+ first instance starts with it.+ </AlertDescription>+ </Alert>+ </DialogBody>+ <DialogFooter>+ <Button onClick={() => setGeneratedKey(null)}>I have stored the key</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+};diff --git a/frontend/src/pages/admin/EncryptionPage/components/index.ts b/frontend/src/pages/admin/EncryptionPage/components/index.tsindex a9b82fdfed..43c2d9e959 100644--- a/frontend/src/pages/admin/EncryptionPage/components/index.ts+++ b/frontend/src/pages/admin/EncryptionPage/components/index.ts@@ -1 +1,2 @@+export { EncryptionKeyRotationSection } from "./EncryptionKeyRotationSection";export { EncryptionPageForm } from "./EncryptionPageForm";