Skip to content

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

feat(encryption): enhance key rotation with kekFingerprint and related updates

Victor Hugo dos Santos17cf6a7107b5
diff --git a/backend/src/db/migrations/20260819120000_kek-rotation.ts b/backend/src/db/migrations/20260819120000_kek-rotation.ts
index dece4c8324..7ed7de27e5 100644
--- a/backend/src/db/migrations/20260819120000_kek-rotation.ts
+++ b/backend/src/db/migrations/20260819120000_kek-rotation.ts
@@ -10,8 +10,9 @@ 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");
+ const hasKekFingerprint = await knex.schema.hasColumn(TableName.KmsServerRootConfig, "kekFingerprint");
- if (!hasActivatedAt || !hasSupersededAt || !hasLastResolvedAt) {
+ if (!hasActivatedAt || !hasSupersededAt || !hasLastResolvedAt || !hasKekFingerprint) {
await knex.schema.alterTable(TableName.KmsServerRootConfig, (t) => {
// NULL means a pending rotation nobody has booted with yet.
if (!hasActivatedAt) t.timestamp("activatedAt");
@@ -20,6 +21,7 @@ export async function up(knex: Knex): Promise<void> {
// 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 (!hasKekFingerprint) t.string("kekFingerprint", 64);
});
}
@@ -60,7 +62,7 @@ export async function up(knex: Knex): Promise<void> {
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 columns = ["activatedAt", "supersededAt", "lastResolvedAt", "kekFingerprint"];
const present: string[] = [];
for (const column of columns) {
// eslint-disable-next-line no-await-in-loop
diff --git a/backend/src/db/migrations/utils/services.ts b/backend/src/db/migrations/utils/services.ts
index 6a07238afd..57e3359973 100644
--- a/backend/src/db/migrations/utils/services.ts
+++ b/backend/src/db/migrations/utils/services.ts
@@ -139,7 +139,7 @@ export const getMigrationEncryptionServices = async ({
envConfig
});
- await kmsService.startService(hsmStatus);
+ await kmsService.startService(hsmStatus, { skipRotationState: true });
return { kmsService, hsmService };
};
diff --git a/backend/src/db/schemas/kms-root-config.ts b/backend/src/db/schemas/kms-root-config.ts
index 85a25bba7f..d4fd09e499 100644
--- a/backend/src/db/schemas/kms-root-config.ts
+++ b/backend/src/db/schemas/kms-root-config.ts
@@ -17,7 +17,8 @@ export const KmsRootConfigSchema = z.object({
updatedAt: z.date(),
activatedAt: z.date().nullable().optional(),
supersededAt: z.date().nullable().optional(),
- lastResolvedAt: z.date().nullable().optional()
+ lastResolvedAt: z.date().nullable().optional(),
+ kekFingerprint: z.string().nullable().optional()
});
export type TKmsRootConfig = z.infer<typeof KmsRootConfigSchema>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 745b74bbf5..6326074e81 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -7121,6 +7121,7 @@ interface DeleteEncryptionKeyRotationEvent {
type: EventType.DELETE_ENCRYPTION_KEY_ROTATION;
metadata: {
rotationId: string;
+ fingerprint: string | null;
};
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index facbfc29b1..45b437e14a 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3957,6 +3957,8 @@ export const ENCRYPTION_KEY_ROTATION = {
"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.",
+ pendingFingerprint:
+ "Fingerprint of the generated key, so you can confirm the value you are about to deploy is the one you copied.",
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:
diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts
index 13efdc96ec..d1f6f52326 100644
--- a/backend/src/server/routes/v1/admin-router.ts
+++ b/backend/src/server/routes/v1/admin-router.ts
@@ -655,14 +655,19 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
activeFingerprint: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.activeFingerprint),
encryptionStrategy: z.string().nullable(),
pendingRotation: z
- .object({ id: z.string().uuid(), createdAt: z.date() })
+ .object({
+ id: z.string().uuid(),
+ createdAt: z.date(),
+ fingerprint: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.pendingFingerprint)
+ })
.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)
+ lastResolvedAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.lastResolvedAt),
+ fingerprint: z.string().nullable()
})
.nullable(),
history: z
@@ -774,13 +779,13 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
});
},
handler: async (req, res) => {
- await server.services.encryptionKeyRotation.discardRotation(req.params.rotationId);
+ const { fingerprint } = 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 }
+ metadata: { rotationId: req.params.rotationId, fingerprint }
}
});
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.ts
index c43d60aa8b..34654bc7ed 100644
--- a/backend/src/services/encryption-key-rotation/encryption-key-rotation-service.ts
+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-service.ts
@@ -1,3 +1,4 @@
+import { PgSqlLock } from "@app/keystore/keystore";
import { TEnvConfig } from "@app/lib/config/env";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { crypto } from "@app/lib/crypto/cryptography";
@@ -29,7 +30,14 @@ type TEncryptionKeyRotationServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "encryptRootKeyForKek" | "getCurrentKekFingerprint">;
kmsRootConfigDAL: Pick<
TKmsRootConfigDALFactory,
- "findById" | "findAll" | "findPending" | "findRetained" | "create" | "deleteById" | "deleteAllPending"
+ | "findById"
+ | "findAll"
+ | "findPending"
+ | "findRetained"
+ | "create"
+ | "deleteById"
+ | "deleteAllPending"
+ | "transaction"
>;
kmsKekHistoryDAL: Pick<TKmsKekHistoryDALFactory, "findHistory" | "findCurrent" | "updateById">;
envConfig: Pick<TEnvConfig, "KMS_ROOT_KEY_RETENTION_DAYS">;
@@ -65,12 +73,19 @@ export const encryptionKeyRotationServiceFactory = ({
return {
activeFingerprint: kmsService.getCurrentKekFingerprint(),
encryptionStrategy: sentinel?.encryptionStrategy ?? null,
- pendingRotation: pendingRows[0] ? { id: pendingRows[0].id, createdAt: pendingRows[0].createdAt } : null,
+ pendingRotation: pendingRows[0]
+ ? {
+ id: pendingRows[0].id,
+ createdAt: pendingRows[0].createdAt,
+ fingerprint: pendingRows[0].kekFingerprint ?? null
+ }
+ : null,
retainedKey: retained
? {
id: retained.id,
supersededAt: retained.supersededAt as Date,
- lastResolvedAt: retained.lastResolvedAt ?? null
+ lastResolvedAt: retained.lastResolvedAt ?? null,
+ fingerprint: retained.kekFingerprint ?? null
}
: null,
history: history.map(({ kekFingerprint, activatedAt, supersededAt, retiredAt }) => ({
@@ -108,33 +123,61 @@ export const encryptionKeyRotationServiceFactory = ({
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();
+ if (existingPending.length) {
+ await kmsRootConfigDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
+ const stillPending = await kmsRootConfigDAL.findPending(tx);
+ if (stillPending.some((row) => row.activatedAt)) {
+ throw new BadRequestError({
+ message:
+ "The pending key was applied by a running instance while this request was in flight, so it cannot be replaced. There is no rollback once a rotation takes effect."
+ });
+ }
+ await kmsRootConfigDAL.deleteAllPending(tx);
+ });
+ }
+ const fingerprint = getKekFingerprint(kekBuffer);
const pending = await kmsRootConfigDAL.create({
encryptedRootKey,
encryptionStrategy: RootKeyEncryptionStrategy.Software,
+ kekFingerprint: fingerprint,
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}]`);
+ return kmsRootConfigDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
+
+ const row = await kmsRootConfigDAL.findById(rotationId, tx);
+ 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."
+ });
+ }
+
+ const deleted = await kmsRootConfigDAL.deleteById(rotationId, tx);
+ if (!deleted) {
+ throw new BadRequestError({
+ message:
+ "The key was applied by a running instance while this request was in flight, so it could not be discarded. There is no rollback once a rotation takes effect."
+ });
+ }
+
+ logger.info(
+ `Encryption key rotation discarded [rotationId=${rotationId}] [fingerprint=${row.kekFingerprint ?? "unknown"}]`
+ );
+ return { fingerprint: row.kekFingerprint ?? null };
+ });
};
const completeRotation = async ({ rotationId, acknowledged }: TCompleteRotationDTO) => {
@@ -165,14 +208,15 @@ export const encryptionKeyRotationServiceFactory = ({
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);
+ const retiredEntry = row.kekFingerprint
+ ? history.find((entry) => entry.kekFingerprint === row.kekFingerprint && !entry.retiredAt)
+ : undefined;
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 };
+ return { retiredFingerprint: row.kekFingerprint ?? null };
};
const $runGarbageCollection = async () => {
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.ts
index 0a9be32635..b7c922f6e8 100644
--- a/backend/src/services/encryption-key-rotation/encryption-key-rotation-types.ts
+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-types.ts
@@ -6,8 +6,13 @@ export enum RotationBlocker {
export type TEncryptionStatus = {
activeFingerprint: string | null;
encryptionStrategy: string | null;
- pendingRotation: { id: string; createdAt: Date } | null;
- retainedKey: { id: string; supersededAt: Date; lastResolvedAt: Date | null } | null;
+ pendingRotation: { id: string; createdAt: Date; fingerprint: string | null } | null;
+ retainedKey: {
+ id: string;
+ supersededAt: Date;
+ lastResolvedAt: Date | null;
+ fingerprint: string | null;
+ } | null;
history: {
kekFingerprint: string;
activatedAt: Date;
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index fdfcd34dde..f7f673220d 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -1527,6 +1527,7 @@ export const kmsServiceFactory = ({
{
encryptedRootKey: sentinel.encryptedRootKey,
encryptionStrategy: sentinel.encryptionStrategy,
+ kekFingerprint: sentinel.kekFingerprint,
activatedAt: sentinel.activatedAt ?? sentinel.createdAt,
supersededAt: now
},
@@ -1538,6 +1539,7 @@ export const kmsServiceFactory = ({
{
encryptedRootKey: pending.encryptedRootKey,
encryptionStrategy: pending.encryptionStrategy,
+ kekFingerprint: pending.kekFingerprint ?? fingerprint,
activatedAt: now,
supersededAt: null
},
@@ -1546,15 +1548,18 @@ export const kmsServiceFactory = ({
await kmsRootConfigDAL.deleteAllPending(tx);
+ const promotedFingerprint = pending.kekFingerprint ?? fingerprint;
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);
+ if (promotedFingerprint) {
+ await kmsKekHistoryDAL.create({ kekFingerprint: promotedFingerprint, activatedAt: now }, tx);
+ }
return true;
});
};
- const $bootstrapRootKey = async (hsmStatus: THsmStatus) => {
+ const $bootstrapRootKey = async (hsmStatus: THsmStatus, skipRotationState = false) => {
const isHsmActive = hsmStatus.isHsmConfigured;
logger.info(`KMS: Generating new ROOT Key with ${isHsmActive ? "HSM" : "software"} encryption`);
@@ -1580,17 +1585,17 @@ export const kmsServiceFactory = ({
id: KMS_ROOT_CONFIG_UUID,
encryptedRootKey,
encryptionStrategy,
- activatedAt: new Date()
+ ...(skipRotationState ? {} : { activatedAt: new Date() })
},
tx
);
});
};
- const $resolveRootKey = async (hsmStatus: THsmStatus) => {
+ const $resolveRootKey = async (hsmStatus: THsmStatus, skipRotationState = false) => {
const rows = await kmsRootConfigDAL.findAll();
if (!rows.length) {
- const created = await $bootstrapRootKey(hsmStatus);
+ const created = await $bootstrapRootKey(hsmStatus, skipRotationState);
return $decryptRootKey(created);
}
@@ -1606,6 +1611,10 @@ export const kmsServiceFactory = ({
);
if (rootKey) {
+ // Everything below this point writes rotation-feature state, which the migration path must not
+ // touch: historical migrations boot this service long before the migration that adds it.
+ if (skipRotationState) return rootKey;
+
if (!row.activatedAt && row.id !== KMS_ROOT_CONFIG_UUID) {
const fingerprint = $currentKekFingerprint();
// eslint-disable-next-line no-await-in-loop
@@ -1619,6 +1628,18 @@ export const kmsServiceFactory = ({
}
}
+ // Rows written before the label existed get it from the pod that can actually decrypt them,
+ // which is the only place the value is derivable.
+ if (!row.kekFingerprint) {
+ const fingerprint = $currentKekFingerprint();
+ if (fingerprint) {
+ // eslint-disable-next-line no-await-in-loop
+ await kmsRootConfigDAL
+ .updateById(row.id, { kekFingerprint: fingerprint })
+ .catch((err: unknown) => logger.warn({ err }, "KMS: Failed to label a root key row"));
+ }
+ }
+
// 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
@@ -1726,12 +1747,21 @@ export const kmsServiceFactory = ({
});
};
- const startService = async (hsmStatus: THsmStatus) => {
- const decryptedRootKey = await $resolveRootKey(hsmStatus);
+ /**
+ * `skipRotationState` is for callers that run *inside* a database migration. Historical migrations boot
+ * this service to re-encrypt data, and they run long before the migration that adds the rotation
+ * columns and tables, so touching any of it there fails on a fresh database. Such a caller only needs
+ * the root key in memory; the legacy-key snapshot is deliberately skipped too, and the legacy helpers
+ * fall back to reading the environment, which is correct for a migration.
+ */
+ const startService = async (hsmStatus: THsmStatus, { skipRotationState = false } = {}) => {
+ const decryptedRootKey = await $resolveRootKey(hsmStatus, skipRotationState);
logger.info("KMS: Loading ROOT Key into Memory.");
ROOT_ENCRYPTION_KEY = decryptedRootKey;
+ if (skipRotationState) return;
+
await $ensureLegacyKeyMaterial();
await $ensureKekHistory();
};
@@ -1787,6 +1817,18 @@ export const kmsServiceFactory = ({
await kmsRootConfigDAL.transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
+
+ const [pendingNow, retainedNow] = await Promise.all([
+ kmsRootConfigDAL.findPending(tx),
+ kmsRootConfigDAL.findRetained(tx)
+ ]);
+ if (pendingNow.length || retainedNow.length) {
+ throw new BadRequestError({
+ message:
+ "An encryption key rotation is still in progress. Complete or discard it before changing the root key encryption strategy."
+ });
+ }
+
await kmsRootConfigDAL.updateById(
KMS_ROOT_CONFIG_UUID,
{
diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts
index f80b4f2a80..14089efdb2 100644
--- a/frontend/src/hooks/api/admin/types.ts
+++ b/frontend/src/hooks/api/admin/types.ts
@@ -249,8 +249,13 @@ export enum EncryptionRotationBlocker {
export type TEncryptionStatus = {
activeFingerprint: string | null;
encryptionStrategy: string | null;
- pendingRotation: { id: string; createdAt: string } | null;
- retainedKey: { id: string; supersededAt: string; lastResolvedAt: string | null } | null;
+ pendingRotation: { id: string; createdAt: string; fingerprint: string | null } | null;
+ retainedKey: {
+ id: string;
+ supersededAt: string;
+ lastResolvedAt: string | null;
+ fingerprint: string | null;
+ } | null;
history: {
kekFingerprint: string;
activatedAt: string;
diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
index a2dc551fa5..b26f63f2c6 100644
--- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
+++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
@@ -13,6 +13,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
+ Checkbox,
CopyButton,
Dialog,
DialogBody,
@@ -21,6 +22,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
+ Label,
Table,
TableBody,
TableCell,
@@ -101,6 +103,15 @@ export const EncryptionKeyRotationSection = () => {
</Badge>
</div>
+ {status.pendingRotation?.fingerprint && (
+ <div className="flex items-center gap-2 text-sm">
+ <span className="text-foreground/70">Generated key awaiting deployment</span>
+ <Badge variant="info" className="font-mono">
+ {status.pendingRotation.fingerprint}
+ </Badge>
+ </div>
+ )}
+
{status.blockers.map((blocker) => (
<Alert
key={blocker}
@@ -142,20 +153,18 @@ export const EncryptionKeyRotationSection = () => {
: "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
+ <div className="flex items-start gap-2">
+ <Checkbox
id="ack-remove-old-key"
- type="checkbox"
- checked={acknowledged}
- onChange={(e) => setAcknowledged(e.target.checked)}
- className="mt-0.5"
+ isChecked={acknowledged}
+ onCheckedChange={(value) => setAcknowledged(value === true)}
/>
- <span>
+ <Label htmlFor="ack-remove-old-key" className="text-xs font-normal">
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>
+ </Label>
+ </div>
<Button
className="self-start"
variant="danger"