Skip to content

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

feat(encryption): enhance key rotation with supersedesRetainedKey handling

Victor Hugo dos Santosd50ea4c46b2d
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index bcd2999273..61c5e3e01c 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -484,6 +484,12 @@ Consequences worth knowing:
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.
+- **Exactly one retained key survives a promotion, enforced at promotion, not by the GC.** A second
+ rotation before the first was completed would otherwise leave an older wrapper of the root key that
+ `getStatus` never reports (it returns only the newest), so an operator removing "the previous key" is
+ told the rotation is finished while a leaked older `ENCRYPTION_KEY` still opens the database. The cost is that an
+ instance two rotations behind cannot restart; staging a key warns about that and deliberately does not
+ block, since an operator responding to a leak has to be able to rotate again immediately.
- **`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.
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 45b437e14a..38483494d4 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3971,7 +3971,9 @@ export const ENCRYPTION_KEY_ROTATION = {
"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."
+ key: "The new value for ENCRYPTION_KEY. Shown only in this response and never recoverable. Store it before closing.",
+ supersedesRetainedKey:
+ "Present when the previous rotation's key has not been removed yet. Applying this key removes it immediately, so any instance still running it will fail to restart."
},
DISCARD: {
description:
diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts
index d1f6f52326..86a5344aa1 100644
--- a/backend/src/server/routes/v1/admin-router.ts
+++ b/backend/src/server/routes/v1/admin-router.ts
@@ -725,7 +725,11 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
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)
+ key: z.string().describe(ENCRYPTION_KEY_ROTATION.CREATE.key),
+ supersedesRetainedKey: z
+ .object({ fingerprint: z.string().nullable(), lastResolvedAt: z.date().nullable() })
+ .optional()
+ .describe(ENCRYPTION_KEY_ROTATION.CREATE.supersedesRetainedKey)
})
})
}
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 58001ea1af..90b921af7a 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
@@ -126,9 +126,12 @@ export const encryptionKeyRotationServiceFactory = ({
const encryptedRootKey = kmsService.encryptRootKeyForKek(kekBuffer);
const fingerprint = getKekFingerprint(kekBuffer);
- const pending = await kmsRootConfigDAL.transaction(async (tx) => {
+ const staged = await kmsRootConfigDAL.transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
+ // Read under the lock so the warning describes the key that will actually be removed on promotion.
+ const [retained] = await kmsRootConfigDAL.findRetained(tx);
+
const stillPending = await kmsRootConfigDAL.findPending(tx);
if (stillPending.length) {
if (!supersede) {
@@ -147,7 +150,7 @@ export const encryptionKeyRotationServiceFactory = ({
});
}
- return kmsRootConfigDAL.create(
+ const row = await kmsRootConfigDAL.create(
{
encryptedRootKey,
encryptionStrategy: RootKeyEncryptionStrategy.Software,
@@ -156,11 +159,26 @@ export const encryptionKeyRotationServiceFactory = ({
},
tx
);
+
+ return { row, retained };
});
+ const pending = staged.row;
logger.info(`Encryption key rotation staged [rotationId=${pending.id}] [fingerprint=${fingerprint}]`);
- return { id: pending.id, fingerprint, key };
+ return {
+ id: pending.id,
+ fingerprint,
+ key,
+ ...(staged.retained
+ ? {
+ supersedesRetainedKey: {
+ fingerprint: staged.retained.kekFingerprint ?? null,
+ lastResolvedAt: staged.retained.lastResolvedAt ?? null
+ }
+ }
+ : {})
+ };
};
/**
@@ -273,18 +291,17 @@ export const encryptionKeyRotationServiceFactory = ({
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.
+ // Promotion leaves exactly one retained key, so there is only ever one row to consider here.
//
// 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;
- });
+ const eligible = retained.filter(
+ (row) =>
+ !(row.lastResolvedAt && now - new Date(row.lastResolvedAt).getTime() < retentionMs) &&
+ 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
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 b7c922f6e8..f44240dbc2 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
@@ -36,4 +36,9 @@ export type TCreatedRotation = {
fingerprint: string;
/** Returned exactly once. Never stored, never logged. */
key: string;
+ /**
+ * Set when the previous rotation's key has not been removed yet. Applying this key removes it
+ * immediately, so an instance still running it will fail to restart.
+ */
+ supersedesRetainedKey?: { fingerprint: string | null; lastResolvedAt: Date | null };
};
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index f7f673220d..bbb29033a0 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -1522,6 +1522,8 @@ export const kmsServiceFactory = ({
const now = new Date();
+ const olderRetained = await kmsRootConfigDAL.findRetained(tx);
+
// The grace window, so pods that have not rolled over can still boot. Not a rollback path.
await kmsRootConfigDAL.create(
{
@@ -1555,6 +1557,23 @@ export const kmsServiceFactory = ({
await kmsKekHistoryDAL.create({ kekFingerprint: promotedFingerprint, activatedAt: now }, tx);
}
+ // Exactly one retained key survives a promotion.
+ const history = await kmsKekHistoryDAL.findHistory(tx);
+ for (const stale of olderRetained) {
+ // eslint-disable-next-line no-await-in-loop -- at most a couple of rows
+ await kmsRootConfigDAL.deleteById(stale.id, tx);
+ const entry = stale.kekFingerprint
+ ? history.find((e) => e.kekFingerprint === stale.kekFingerprint && !e.retiredAt)
+ : undefined;
+ // eslint-disable-next-line no-await-in-loop
+ if (entry) await kmsKekHistoryDAL.updateById(entry.id, { retiredAt: now }, tx);
+ logger.info(
+ `KMS: Removed a key superseded by an earlier rotation [rootConfigId=${stale.id}] [fingerprint=${
+ stale.kekFingerprint ?? "unknown"
+ }]`
+ );
+ }
+
return true;
});
};
diff --git a/docs/self-hosting/guides/rotating-the-encryption-key.mdx b/docs/self-hosting/guides/rotating-the-encryption-key.mdx
index 2e4b2a0c47..3ead89b6ec 100644
--- a/docs/self-hosting/guides/rotating-the-encryption-key.mdx
+++ b/docs/self-hosting/guides/rotating-the-encryption-key.mdx
@@ -58,6 +58,12 @@ one, think about it, and discard it with no consequences.
![Remove encryption key panel in the Server Console](/images/self-hosting/guides/rotating-encryption-key/remove-key.png)
+ <Note>
+ Rotating again before removing the previous key removes it for you, at the moment the new key is
+ first used. Infisical warns you about this when it generates the key. Only one previous key is ever
+ kept, so an instance two rotations behind will not be able to restart.
+ </Note>
+
<Note>
Infisical can only see instances that have *started* on the previous key. If one did so recently, it
asks you to confirm before removing the key, since you are the only one who can tell whether that
diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts
index 14089efdb2..1c56ce5174 100644
--- a/frontend/src/hooks/api/admin/types.ts
+++ b/frontend/src/hooks/api/admin/types.ts
@@ -269,6 +269,7 @@ export type TCreatedEncryptionKeyRotation = {
id: string;
fingerprint: string;
key: string;
+ supersedesRetainedKey?: { fingerprint: string | null; lastResolvedAt: string | null };
};
export type TCompleteEncryptionKeyRotationDTO = {
diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
index b26f63f2c6..bcd1bc659c 100644
--- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
+++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
@@ -245,6 +245,26 @@ export const EncryptionKeyRotationSection = () => {
</p>
</div>
+ {generatedKey?.supersedesRetainedKey && (
+ <Alert variant="warning">
+ <AlertTriangleIcon />
+ <AlertTitle>This will remove your previous key</AlertTitle>
+ <AlertDescription>
+ <p>
+ The key from your last rotation has not been removed yet. Applying this new key
+ removes it immediately, and any instance still running it will fail to restart.
+ </p>
+ {generatedKey.supersedesRetainedKey.lastResolvedAt && (
+ <p className="mt-2">
+ An instance started on it{" "}
+ {new Date(generatedKey.supersedesRetainedKey.lastResolvedAt).toLocaleString()}
+ .
+ </p>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+
<Alert variant="info">
<AlertDescription>
Nothing has changed yet. Deploy this value, and the rotation takes effect when the