Skip to content

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

refactor(encryption): update key rotation logic and API to use staged keys

Victor Hugo dos Santos4787746a92ac
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 28f3f8c678..395b75af7b 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -457,16 +457,16 @@ 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), so
+staged keys 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, staged, retained), so
`kekLabel` is never a lookup key. It exists on both tables purely as a human label, derived from the key so
an operator can recompute it and match an archived key to a backup; nothing resolves a row by it.
-**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
+**A rotation is inert until a pod boots with the new key.** `POST /admin/encryption/root-key/rotations` writes
+a *staged* 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 replaced pending key left in someone's clipboard must not be able to promote
+ciphertext, the old one moves to a retained copy, and **every** staged row is dropped (an abandoned staged
+row is a live working key, so a replaced staged 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.
@@ -487,7 +487,7 @@ Consequences worth knowing:
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
+ `getRootKey` 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.
@@ -495,8 +495,8 @@ Consequences worth knowing:
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.
+ *superseded* row, which is positive evidence a straggler still holds that key and makes both the
+ expiring-key delete 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.
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index cdf2022f32..cf7c842eb9 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3950,41 +3950,64 @@ export const SECRET_VALIDATION_RULES = {
} as const;
export const ENCRYPTION_KEY_ROTATION = {
- STATUS: {
+ ROOT_KEY: {
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.",
- activeLabel:
- "A non-reversible label derived from the key this instance is currently running with. Recompute it from an archived key to confirm which one 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.",
- pendingLabel:
- "Label 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:
- "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."
+ "Report the state of the instance encryption key: which key is active, whether a replacement is staged, and whether the key it replaced is still accepted.",
+ encryptionStrategy: "How the root key is wrapped. A key wrapped by an HSM has no environment variable to rotate.",
+ active: {
+ label:
+ "Non-reversible label of the key this instance is running with. Record it next to the archived key so a backup can be matched later.",
+ activatedAt: "When this key took effect, which is the first time an instance started with it."
+ },
+ staged: {
+ description:
+ "A generated key that has not been applied yet. Null until you generate one. Nothing changes until an instance starts with it.",
+ label: "Label of the staged key, so you can confirm the value you are about to deploy is the one you copied.",
+ createdAt: "When this key was generated."
+ },
+ expiring: {
+ description:
+ "The key this instance used before the current one. Null if none is still accepted. It still starts an instance so a fleet can finish rolling over, and is removed automatically once the retention window passes.",
+ label: "Label of the previous key. Pass it when you remove that key.",
+ supersededAt: "When the current key took effect.",
+ 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."
+ }
+ },
+ ROTATIONS: {
+ description:
+ "List the rotations that have taken effect, newest first. A staged key appears here only once an instance has started with it. Kept after a key is removed, so a restored backup can be matched to an archived key.",
+ offset: "How many rotations to skip before the first returned.",
+ limit: "How many rotations to return.",
+ label: "A non-reversible label derived from the key. Match it to the label you stored with an archived key.",
+ activatedAt: "When this key took effect.",
+ supersededAt: "When the next key took effect. Null on the key currently in use.",
+ retiredAt: "When this key stopped being accepted and was removed. Null while it still starts an instance.",
+ totalCount: "How many rotations this instance has recorded in total."
},
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.",
- replacePending:
+ replaceStaged:
"Replace an already-generated key that has not been applied yet. The replaced key stops working immediately.",
label:
"A non-reversible label derived from 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.",
- removesRetainedKey:
+ removesExpiringKey:
"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: {
+ DELETE_STAGED: {
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."
+ label:
+ "Label of the staged key, which must match the key currently staged. It is a precondition, not an identifier: it fails the request rather than discarding a key another administrator staged after you loaded this page."
},
- COMPLETE: {
+ DELETE_EXPIRING: {
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.",
- acknowledged:
- "Remove the key even though an instance started on it recently. Any instance still using that key will fail its next restart until it is given the new one."
+ label:
+ "Label of the previous key, which must match the key currently held. It is a precondition, not an identifier: it fails the request rather than removing a key you have not seen.",
+ force:
+ "Remove the key even though an instance started on it recently. This overrides only that check: a label that does not match the key currently held still fails. Any instance still using that key will fail its next restart until it is given the new one."
}
};
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index c7577fe7bf..9f2d5b8e11 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -137,6 +137,18 @@ export class NotFoundError extends Error {
}
}
+export class ConflictError extends Error {
+ name: string;
+
+ error: unknown;
+
+ constructor({ name, error, message }: { message?: string; name?: string; error?: unknown }) {
+ super(message ?? "The request conflicts with the current state of the resource");
+ this.name = name || "Conflict";
+ this.error = error;
+ }
+}
+
export class DisableRotationErrors extends Error {
name: string;
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index b0a585c86b..d225a97780 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -8,6 +8,7 @@ import { AcmeError } from "@app/ee/services/pki-acme/pki-acme-errors";
import { getConfig } from "@app/lib/config/env";
import {
BadRequestError,
+ ConflictError,
CryptographyError,
DatabaseError,
ForbiddenRequestError,
@@ -40,6 +41,7 @@ enum JWTErrors {
enum HttpStatusCodes {
BadRequest = 400,
NotFound = 404,
+ Conflict = 409,
Unauthorized = 401,
Forbidden = 403,
UnprocessableContent = 422,
@@ -70,6 +72,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
const isExpectedClientError =
error instanceof BadRequestError ||
error instanceof NotFoundError ||
+ error instanceof ConflictError ||
error instanceof UnauthorizedError ||
error instanceof ForbiddenError ||
error instanceof ForbiddenRequestError ||
@@ -195,6 +198,10 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
error: error.name,
details: error.details
});
+ } else if (error instanceof ConflictError) {
+ void res
+ .status(HttpStatusCodes.Conflict)
+ .send({ reqId: req.id, statusCode: HttpStatusCodes.Conflict, message: error.message, error: error.name });
} else if (error instanceof NotFoundError) {
void res
.status(HttpStatusCodes.NotFound)
diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts
index b5fa3b4563..a8eedff786 100644
--- a/backend/src/server/routes/v1/admin-router.ts
+++ b/backend/src/server/routes/v1/admin-router.ts
@@ -23,7 +23,6 @@ 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";
@@ -641,44 +640,36 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/encryption/status",
+ url: "/encryption/root-key",
config: {
rateLimit: readLimit
},
schema: {
- operationId: "getAdminEncryptionStatus",
- description: ENCRYPTION_KEY_ROTATION.STATUS.description,
+ operationId: "getAdminEncryptionRootKey",
+ description: ENCRYPTION_KEY_ROTATION.ROOT_KEY.description,
response: {
200: z.object({
- status: z.object({
- activeLabel: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.activeLabel),
- encryptionStrategy: z.string().nullable(),
- pendingRotation: z
+ rootKey: z.object({
+ encryptionStrategy: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.encryptionStrategy),
+ active: z.object({
+ label: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.active.label),
+ activatedAt: z.date().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.active.activatedAt)
+ }),
+ staged: z
.object({
- id: z.string().uuid(),
- createdAt: z.date(),
- label: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.pendingLabel)
+ label: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.staged.label),
+ createdAt: z.date().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.staged.createdAt)
})
.nullable()
- .describe(ENCRYPTION_KEY_ROTATION.STATUS.pendingRotation),
- retainedKey: z
+ .describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.staged.description),
+ expiring: z
.object({
- id: z.string().uuid(),
- supersededAt: z.date(),
- lastResolvedAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.STATUS.lastResolvedAt),
- label: z.string().nullable()
+ label: z.string().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.label),
+ supersededAt: z.date().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.supersededAt),
+ lastResolvedAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.lastResolvedAt)
})
- .nullable(),
- history: z
- .object({
- label: 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()
+ .nullable()
+ .describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.description)
})
})
}
@@ -689,34 +680,73 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
});
},
handler: async () => {
- const status = await server.services.encryptionKeyRotation.getStatus();
+ const rootKey = await server.services.encryptionKeyRotation.getRootKey();
- return { status };
+ return { rootKey };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/encryption/root-key/rotations",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listAdminEncryptionKeyRotations",
+ description: ENCRYPTION_KEY_ROTATION.ROTATIONS.description,
+ querystring: z.object({
+ offset: z.coerce.number().int().min(0).default(0).describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.offset),
+ limit: z.coerce.number().int().min(1).max(100).default(20).describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.limit)
+ }),
+ response: {
+ 200: z.object({
+ rotations: z
+ .object({
+ label: z.string().describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.label),
+ activatedAt: z.date().describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.activatedAt),
+ supersededAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.supersededAt),
+ retiredAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.retiredAt)
+ })
+ .array(),
+ totalCount: z.number().describe(ENCRYPTION_KEY_ROTATION.ROTATIONS.totalCount)
+ })
+ }
+ },
+ onRequest: (req, res, done) => {
+ verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {
+ verifySuperAdmin(req, res, done);
+ });
+ },
+ handler: async (req) => {
+ return server.services.encryptionKeyRotation.listRotations({
+ offset: req.query.offset,
+ limit: req.query.limit
+ });
}
});
server.route({
method: "POST",
- url: "/encryption/rotations",
+ url: "/encryption/root-key/rotations",
config: {
rateLimit: writeLimit
},
schema: {
operationId: "createAdminEncryptionKeyRotation",
description: ENCRYPTION_KEY_ROTATION.CREATE.description,
- querystring: z.object({
- replacePending: booleanSchema.default(false).describe(ENCRYPTION_KEY_ROTATION.CREATE.replacePending)
+ body: z.object({
+ replaceStaged: z.boolean().default(false).describe(ENCRYPTION_KEY_ROTATION.CREATE.replaceStaged)
}),
response: {
201: z.object({
rotation: z.object({
- id: z.string().uuid(),
label: z.string().describe(ENCRYPTION_KEY_ROTATION.CREATE.label),
key: z.string().describe(ENCRYPTION_KEY_ROTATION.CREATE.key),
- removesRetainedKey: z
+ removesExpiringKey: z
.object({ label: z.string().nullable(), lastResolvedAt: z.date().nullable() })
.optional()
- .describe(ENCRYPTION_KEY_ROTATION.CREATE.removesRetainedKey)
+ .describe(ENCRYPTION_KEY_ROTATION.CREATE.removesExpiringKey)
})
})
}
@@ -728,7 +758,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
},
handler: async (req, res) => {
const rotation = await server.services.encryptionKeyRotation.createRotation({
- replacePending: req.query.replacePending
+ replaceStaged: req.body.replaceStaged
});
// The key appears here and nowhere else, so it must not be cached along the way.
@@ -740,15 +770,15 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
server.route({
method: "DELETE",
- url: "/encryption/rotations/:rotationId",
+ url: "/encryption/root-key/staged",
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)
+ operationId: "deleteAdminStagedEncryptionKey",
+ description: ENCRYPTION_KEY_ROTATION.DELETE_STAGED.description,
+ querystring: z.object({
+ label: z.string().trim().min(1).max(64).describe(ENCRYPTION_KEY_ROTATION.DELETE_STAGED.label)
})
},
onRequest: (req, res, done) => {
@@ -757,32 +787,25 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
});
},
handler: async (req, res) => {
- await server.services.encryptionKeyRotation.discardRotation(req.params.rotationId);
+ await server.services.encryptionKeyRotation.deleteStagedKey({ label: req.query.label });
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",
+ method: "DELETE",
+ url: "/encryption/root-key/expiring",
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)
- }),
- // Defaults to absent, so a scripted caller that says nothing still gets the guard.
- body: z
- .object({
- acknowledged: z.boolean().optional().describe(ENCRYPTION_KEY_ROTATION.COMPLETE.acknowledged)
- })
- .nullish()
+ operationId: "deleteAdminExpiringEncryptionKey",
+ description: ENCRYPTION_KEY_ROTATION.DELETE_EXPIRING.description,
+ querystring: z.object({
+ label: z.string().trim().min(1).max(64).describe(ENCRYPTION_KEY_ROTATION.DELETE_EXPIRING.label),
+ force: booleanSchema.default(false).describe(ENCRYPTION_KEY_ROTATION.DELETE_EXPIRING.force)
+ })
},
onRequest: (req, res, done) => {
verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN])(req, res, () => {
@@ -790,9 +813,9 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
});
},
handler: async (req, res) => {
- await server.services.encryptionKeyRotation.completeRotation({
- rotationId: req.params.rotationId,
- acknowledged: req.body?.acknowledged
+ await server.services.encryptionKeyRotation.deleteExpiringKey({
+ label: req.query.label,
+ force: req.query.force
});
void res.status(204);
diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-gc.test.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-gc.test.ts
index e1ab2ec0c4..2614fa6bfc 100644
--- a/backend/src/services/encryption-key-rotation/encryption-key-rotation-gc.test.ts
+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-gc.test.ts
@@ -1,5 +1,6 @@
import { beforeAll, describe, expect, it, vi } from "vitest";
+import { ConflictError } from "@app/lib/errors";
import { initLogger } from "@app/lib/logger";
import { encryptionKeyRotationServiceFactory } from "./encryption-key-rotation-service";
@@ -23,12 +24,12 @@ const buildService = (snapshot: ReturnType<typeof retainedRow>, underLock: unkno
const deleteById = vi.fn().mockResolvedValue({ id: snapshot.id });
const kmsRootConfigDAL = {
findRetained: vi.fn().mockResolvedValue([snapshot]),
- findPending: vi.fn().mockResolvedValue([]),
+ findStaged: vi.fn().mockResolvedValue([]),
findById: vi.fn().mockResolvedValue(underLock),
deleteById,
findAll: vi.fn(),
create: vi.fn(),
- deleteAllPending: vi.fn(),
+ deleteAllStaged: vi.fn(),
transaction: vi
.fn()
.mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) =>
@@ -36,9 +37,11 @@ const buildService = (snapshot: ReturnType<typeof retainedRow>, underLock: unkno
)
};
const kmsKekHistoryDAL = {
- findHistory: vi.fn().mockResolvedValue([]),
+ findHistoryPage: vi.fn().mockResolvedValue([]),
+ findActiveByLabel: vi.fn().mockResolvedValue(undefined),
findCurrent: vi.fn(),
- updateById: vi.fn()
+ updateById: vi.fn(),
+ countDocuments: vi.fn().mockResolvedValue(0)
};
const service = encryptionKeyRotationServiceFactory({
kmsService: { encryptRootKeyForKek: vi.fn(), getCurrentKekLabel: vi.fn() },
@@ -94,3 +97,48 @@ describe("encryption key rotation garbage collection", () => {
expect(deleteById).not.toHaveBeenCalled();
});
});
+
+describe("removing the expiring encryption key", () => {
+ beforeAll(() => {
+ initLogger();
+ });
+
+ it("refuses a label that is not the key currently held, even with force", async () => {
+ // force overrides the straggler check only. Left overridable, an admin acting on a stale view would
+ // destroy a key a second admin rotated in after that view was read, which is not recoverable.
+ const row = retainedRow({ lastResolvedAt: new Date() });
+ const { service, deleteById } = buildService(row, row);
+
+ await expect(service.deleteExpiringKey({ label: "b".repeat(32), force: true })).rejects.toBeInstanceOf(
+ ConflictError
+ );
+ expect(deleteById).not.toHaveBeenCalled();
+ });
+
+ it("refuses an unlabelled key rather than removing one nothing can name", async () => {
+ // Only reachable if the boot backfill's label write failed. Removing it is irreversible and the
+ // caller cannot have confirmed which key it is, so the refusal points at the restart that fixes it.
+ const row = retainedRow({ kekLabel: null });
+ const { service, deleteById } = buildService(row, row);
+
+ await expect(service.deleteExpiringKey({ label: "a".repeat(32) })).rejects.toThrow(/Restart the instance/);
+ expect(deleteById).not.toHaveBeenCalled();
+ });
+
+ it("asks for force while there is fresh evidence of a straggler", async () => {
+ const row = retainedRow({ lastResolvedAt: new Date() });
+ const { service, deleteById } = buildService(row, row);
+
+ await expect(service.deleteExpiringKey({ label: row.kekLabel })).rejects.toThrow(/force=true/);
+ expect(deleteById).not.toHaveBeenCalled();
+ });
+
+ it("removes the key with force despite fresh evidence of a straggler", async () => {
+ const row = retainedRow({ lastResolvedAt: new Date() });
+ const { service, deleteById } = buildService(row, row);
+
+ await service.deleteExpiringKey({ label: row.kekLabel, force: true });
+
+ expect(deleteById).toHaveBeenCalledWith(row.id, expect.anything());
+ });
+});
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 6193917890..b4d2028730 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
@@ -5,7 +5,7 @@ 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";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { getKekLabel, KMS_ROOT_CONFIG_UUID } from "@app/services/kms/kms-fns";
import { TKmsKekHistoryDALFactory } from "@app/services/kms/kms-kek-history-dal";
@@ -15,34 +15,32 @@ import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";
import { generateRootEncryptionKey, resolveKekBuffer } from "./encryption-key-rotation-fns";
import {
- RotationBlocker,
- TCompleteRotationDTO,
TCreatedRotation,
TCreateRotationDTO,
- TEncryptionStatus
+ TDeleteExpiringKeyDTO,
+ TDeleteStagedKeyDTO,
+ TListRotationsDTO,
+ TRootKeyStatus,
+ TRotationHistoryEntry
} 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 ask the
-// operator to confirm. Shorter than the GC's window on purpose: the GC is unattended and has nobody to
-// make that judgement, whereas an operator calling `complete` can look at their fleet.
+// How recent a superseded-key boot has to be for the expiring-key delete to treat it as a live straggler
+// and ask the operator to confirm. Shorter than the GC's window on purpose: the GC is unattended and has
+// nobody to make that judgement, whereas an operator removing the key can look at their fleet.
const STRAGGLER_EVIDENCE_WINDOW_MS = 60 * 60 * 1000; // 1 hour
type TEncryptionKeyRotationServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "encryptRootKeyForKek" | "getCurrentKekLabel">;
kmsRootConfigDAL: Pick<
TKmsRootConfigDALFactory,
- | "findById"
- | "findAll"
- | "findPending"
- | "findRetained"
- | "create"
- | "deleteById"
- | "deleteAllPending"
- | "transaction"
+ "findById" | "findAll" | "findStaged" | "findRetained" | "create" | "deleteById" | "deleteAllStaged" | "transaction"
+ >;
+ kmsKekHistoryDAL: Pick<
+ TKmsKekHistoryDALFactory,
+ "findHistoryPage" | "findActiveByLabel" | "findCurrent" | "updateById" | "countDocuments"
>;
- kmsKekHistoryDAL: Pick<TKmsKekHistoryDALFactory, "findHistory" | "findCurrent" | "updateById">;
envConfig: Pick<TEnvConfig, "KMS_ROOT_KEY_RETENTION_DAYS">;
cronJob: TCronJobFactory;
};
@@ -56,53 +54,60 @@ export const encryptionKeyRotationServiceFactory = ({
envConfig,
cronJob
}: TEncryptionKeyRotationServiceFactoryDep) => {
- const getStatus = async (): Promise<TEncryptionStatus> => {
- const [sentinel, pendingRows, retainedRows, history] = await Promise.all([
+ const getRootKey = async (): Promise<TRootKeyStatus> => {
+ const [sentinel, stagedRows, retainedRows] = await Promise.all([
kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID),
- kmsRootConfigDAL.findPending(),
- kmsRootConfigDAL.findRetained(),
- kmsKekHistoryDAL.findHistory()
+ kmsRootConfigDAL.findStaged(),
+ kmsRootConfigDAL.findRetained()
]);
- // 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);
+ if (!sentinel) throw new NotFoundError({ message: "KMS root config not found" });
+ const [staged] = stagedRows;
const [retained] = retainedRows;
return {
- activeLabel: kmsService.getCurrentKekLabel(),
- encryptionStrategy: sentinel?.encryptionStrategy ?? null,
- pendingRotation: pendingRows[0]
- ? {
- id: pendingRows[0].id,
- createdAt: pendingRows[0].createdAt,
- label: pendingRows[0].kekLabel ?? null
- }
- : null,
- retainedKey: retained
+ encryptionStrategy: sentinel.encryptionStrategy ?? null,
+ active: {
+ // The sentinel is the instance-wide answer. During a rolling restart the pod serving this
+ // request may still be on the older key, and reporting that would describe the pod, not the
+ // instance. The in-memory label is the fallback for a row the boot backfill has not labelled.
+ label: sentinel.kekLabel ?? kmsService.getCurrentKekLabel(),
+ activatedAt: sentinel.activatedAt ?? sentinel.createdAt
+ },
+ staged: staged ? { label: staged.kekLabel ?? null, createdAt: staged.createdAt } : null,
+ expiring: retained
? {
- id: retained.id,
+ label: retained.kekLabel ?? null,
supersededAt: retained.supersededAt as Date,
- lastResolvedAt: retained.lastResolvedAt ?? null,
- label: retained.kekLabel ?? null
+ lastResolvedAt: retained.lastResolvedAt ?? null
}
- : null,
- history: history.map(({ kekLabel, activatedAt, supersededAt, retiredAt }) => ({
+ : null
+ };
+ };
+
+ const listRotations = async ({
+ offset,
+ limit
+ }: TListRotationsDTO): Promise<{ rotations: TRotationHistoryEntry[]; totalCount: number }> => {
+ const [rows, totalCount] = await Promise.all([
+ kmsKekHistoryDAL.findHistoryPage({ offset, limit }),
+ kmsKekHistoryDAL.countDocuments()
+ ]);
+
+ return {
+ rotations: rows.map(({ kekLabel, activatedAt, supersededAt, retiredAt }) => ({
label: kekLabel,
activatedAt,
- supersededAt,
- retiredAt
+ supersededAt: supersededAt ?? null,
+ retiredAt: retiredAt ?? null
})),
- blockers
+ totalCount
};
};
/** Inert by design: the active key is untouched until a pod boots with the new value. */
- const createRotation = async ({ replacePending }: TCreateRotationDTO): Promise<TCreatedRotation> => {
+ const createRotation = async ({ replaceStaged }: TCreateRotationDTO): Promise<TCreatedRotation> => {
const sentinel = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID);
if (!sentinel) throw new NotFoundError({ message: "KMS root config not found" });
@@ -113,35 +118,34 @@ export const encryptionKeyRotationServiceFactory = ({
});
}
- const existingPending = await kmsRootConfigDAL.findPending();
- if (existingPending.length && !replacePending) {
+ const existingStaged = await kmsRootConfigDAL.findStaged();
+ if (existingStaged.length && !replaceStaged) {
throw new BadRequestError({
- message:
- "A rotation is already pending. Deploy that key, discard it, or retry with replacePending=true to replace it."
+ message: "A key is already staged. Deploy that key, discard it, or retry with replaceStaged=true to replace it."
});
}
- const staged = await kmsRootConfigDAL.transaction(async (tx) => {
+ const result = 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 (!replacePending) {
+ const stillStaged = await kmsRootConfigDAL.findStaged(tx);
+ if (stillStaged.length) {
+ if (!replaceStaged) {
throw new BadRequestError({
message:
- "A rotation is already pending. Deploy that key, discard it, or retry with replacePending=true to replace it."
+ "A key is already staged. Deploy that key, discard it, or retry with replaceStaged=true to replace it."
});
}
- await kmsRootConfigDAL.deleteAllPending(tx);
- } else if (existingPending.length) {
+ await kmsRootConfigDAL.deleteAllStaged(tx);
+ } else if (existingStaged.length) {
// We set out to replace a staged key and it is no longer staged, so an instance applied it while
// this request was in flight. Reporting it replaced would tell the operator a live key was retired.
- throw new BadRequestError({
+ throw new ConflictError({
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."
+ "The staged 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."
});
}
@@ -162,19 +166,17 @@ export const encryptionKeyRotationServiceFactory = ({
return { row, retained, key, label };
});
- const pending = staged.row;
- logger.info(`Encryption key rotation staged [rotationId=${pending.id}] [label=${staged.label}]`);
+ logger.info(`Encryption key rotation staged [rotationId=${result.row.id}] [label=${result.label}]`);
return {
- id: pending.id,
- label: staged.label,
- key: staged.key,
- ...(staged.retained
+ label: result.label,
+ key: result.key,
+ ...(result.retained
? {
- removesRetainedKey: {
- label: staged.retained.kekLabel ?? null,
- lastResolvedAt: staged.retained.lastResolvedAt ?? null
+ removesExpiringKey: {
+ label: result.retained.kekLabel ?? null,
+ lastResolvedAt: result.retained.lastResolvedAt ?? null
}
}
: {})
@@ -183,7 +185,7 @@ export const encryptionKeyRotationServiceFactory = ({
/**
* Removes a retained key and records it as retired, inside a transaction the caller has already locked.
- * Returns false when the row was already gone, so a concurrent completion or GC pass cannot report a
+ * Returns false when the row was already gone, so a concurrent removal or GC pass cannot report a
* deletion that did not happen.
*/
const $retireRetainedKey = async (tx: Knex, row: TKmsRootConfig) => {
@@ -191,88 +193,101 @@ export const encryptionKeyRotationServiceFactory = ({
if (!deleted) return false;
if (row.kekLabel) {
- const history = await kmsKekHistoryDAL.findHistory(tx);
- const entry = history.find((e) => e.kekLabel === row.kekLabel && !e.retiredAt);
+ const entry = await kmsKekHistoryDAL.findActiveByLabel(row.kekLabel, tx);
if (entry) await kmsKekHistoryDAL.updateById(entry.id, { retiredAt: new Date() }, tx);
}
return true;
};
- const discardRotation = async (rotationId: string) => {
+ const deleteStagedKey = async ({ label }: TDeleteStagedKeyDTO) => {
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` });
+ const [staged] = await kmsRootConfigDAL.findStaged(tx);
+ if (!staged) {
+ throw new NotFoundError({
+ message: "There is no staged encryption key to discard."
+ });
}
- 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."
+
+ if (staged.kekLabel !== label) {
+ throw new ConflictError({
+ message: staged.kekLabel
+ ? `The staged encryption key is '${staged.kekLabel}', not '${label}'. Someone else staged a key after you loaded this page. Re-read the current state before discarding.`
+ : "The staged encryption key carries no label to match against, so it cannot be named. Restart the instance to record one, then retry."
});
}
- const deleted = await kmsRootConfigDAL.deleteById(rotationId, tx);
+ const deleted = await kmsRootConfigDAL.deleteById(staged.id, tx);
if (!deleted) {
- throw new BadRequestError({
+ throw new ConflictError({
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}] [label=${row.kekLabel ?? "unknown"}]`);
+ logger.info(
+ `Encryption key rotation discarded [rotationId=${staged.id}] [label=${staged.kekLabel ?? "unknown"}]`
+ );
});
};
- const completeRotation = async ({ rotationId, acknowledged }: TCompleteRotationDTO) => {
+ const deleteExpiringKey = async ({ label, force }: TDeleteExpiringKeyDTO) => {
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 || !row.supersededAt) {
- throw new NotFoundError({ message: `Retained encryption key with ID '${rotationId}' not found` });
+ const [retained] = await kmsRootConfigDAL.findRetained(tx);
+ if (!retained) {
+ throw new NotFoundError({ message: "There is no previous encryption key to remove." });
+ }
+
+ if (retained.kekLabel !== label) {
+ throw new ConflictError({
+ message: retained.kekLabel
+ ? `The previous encryption key is '${retained.kekLabel}', not '${label}'. Another rotation has taken effect since you loaded this page. Re-read the current state before removing it.`
+ : "The previous encryption key carries no label to match against, so it cannot be named. Restart the instance to record one, then retry."
+ });
}
// An instance that started on this key within the hour is very likely still running, and removing
// the key would break its next restart. Nothing reports whether it has since rolled forward, so
// this asks the operator rather than refusing outright.
- const lastResolvedAt = row.lastResolvedAt ? new Date(row.lastResolvedAt).getTime() : null;
+ const lastResolvedAt = retained.lastResolvedAt ? new Date(retained.lastResolvedAt).getTime() : null;
if (lastResolvedAt && Date.now() - lastResolvedAt < STRAGGLER_EVIDENCE_WINDOW_MS) {
- if (!acknowledged) {
+ if (!force) {
throw new BadRequestError({
message: `An instance started on the previous encryption key at ${new Date(
lastResolvedAt
- ).toISOString()} and may still be running. It would fail to restart if the key were removed now. Roll that instance onto the current key first, or acknowledge this to remove the key anyway.`
+ ).toISOString()} and may still be running. It would fail to restart if the key were removed now. Roll that instance onto the current key first, or retry with force=true to remove the key anyway.`
});
}
logger.warn(
`Removing an encryption key an instance started on at ${new Date(
lastResolvedAt
- ).toISOString()}, acknowledged by the caller [retainedKeyId=${rotationId}]`
+ ).toISOString()}, forced by the caller [retainedKeyId=${retained.id}]`
);
}
- if (!(await $retireRetainedKey(tx, row))) {
- throw new BadRequestError({
+ if (!(await $retireRetainedKey(tx, retained))) {
+ throw new ConflictError({
message: "The previous encryption key was already removed while this request was in flight."
});
}
logger.info(
- `Encryption key rotation completed, previous key removed [retainedKeyId=${rotationId}] [label=${row.kekLabel ?? "unknown"}]`
+ `Encryption key rotation completed, previous key removed [retainedKeyId=${retained.id}] [label=${retained.kekLabel ?? "unknown"}]`
);
});
};
const runGarbageCollection = async () => {
- const [retained, pending] = await Promise.all([kmsRootConfigDAL.findRetained(), kmsRootConfigDAL.findPending()]);
+ const [retained, staged] = await Promise.all([kmsRootConfigDAL.findRetained(), kmsRootConfigDAL.findStaged()]);
- // replacePending caps pending at one, so this is for the admin who generated a key and walked away.
+ // replaceStaged caps staged keys 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);
+ const abandoned = staged.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
const removed = await kmsRootConfigDAL.transaction(async (tx) => {
@@ -339,5 +354,13 @@ export const encryptionKeyRotationServiceFactory = ({
});
};
- return { init, getStatus, createRotation, discardRotation, completeRotation, runGarbageCollection };
+ return {
+ init,
+ getRootKey,
+ listRotations,
+ createRotation,
+ deleteStagedKey,
+ deleteExpiringKey,
+ runGarbageCollection
+ };
};
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 b043ec6bf9..0b94fc540b 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
@@ -1,38 +1,36 @@
-export enum RotationBlocker {
- HsmStrategy = "hsm-strategy",
- RotationPending = "rotation-pending"
-}
-
-export type TEncryptionStatus = {
- activeLabel: string | null;
+export type TRootKeyStatus = {
encryptionStrategy: string | null;
- pendingRotation: { id: string; createdAt: Date; label: string | null } | null;
- retainedKey: {
- id: string;
- supersededAt: Date;
- lastResolvedAt: Date | null;
- label: string | null;
- } | null;
- history: {
- label: string;
- activatedAt: Date;
- supersededAt?: Date | null;
- retiredAt?: Date | null;
- }[];
- blockers: RotationBlocker[];
+ active: { label: string | null; activatedAt: Date };
+ staged: { label: string | null; createdAt: Date } | null;
+ expiring: { label: string | null; supersededAt: Date; lastResolvedAt: Date | null } | null;
};
export type TCreateRotationDTO = {
- replacePending?: boolean;
+ replaceStaged?: boolean;
+};
+
+export type TListRotationsDTO = {
+ offset: number;
+ limit: number;
+};
+
+export type TRotationHistoryEntry = {
+ label: string;
+ activatedAt: Date;
+ supersededAt: Date | null;
+ retiredAt: Date | null;
};
-export type TCompleteRotationDTO = {
- rotationId: string;
- acknowledged?: boolean;
+export type TDeleteStagedKeyDTO = {
+ label: string;
+};
+
+export type TDeleteExpiringKeyDTO = {
+ label: string;
+ force?: boolean;
};
export type TCreatedRotation = {
- id: string;
label: string;
/** Returned exactly once. Never stored, never logged. */
key: string;
@@ -40,5 +38,5 @@ export type TCreatedRotation = {
* 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.
*/
- removesRetainedKey?: { label: string | null; lastResolvedAt: Date | null };
+ removesExpiringKey?: { label: string | null; lastResolvedAt: Date | null };
};
diff --git a/backend/src/services/kms/kms-fns.ts b/backend/src/services/kms/kms-fns.ts
index 321ac6d008..5b05332e3e 100644
--- a/backend/src/services/kms/kms-fns.ts
+++ b/backend/src/services/kms/kms-fns.ts
@@ -13,7 +13,7 @@ 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
+ * this id up and knows nothing about staged or retained rows, so keeping the active key here is what
* lets it boot. New code finds rows by trial decryption.
*/
export const KMS_ROOT_CONFIG_UUID = "00000000-0000-0000-0000-000000000000";
diff --git a/backend/src/services/kms/kms-kek-history-dal.ts b/backend/src/services/kms/kms-kek-history-dal.ts
index 90476112a0..d22d944046 100644
--- a/backend/src/services/kms/kms-kek-history-dal.ts
+++ b/backend/src/services/kms/kms-kek-history-dal.ts
@@ -11,12 +11,24 @@ 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) => {
+ // an archived key. Nothing may read it unbounded for that reason.
+ const findHistoryPage = async ({ offset, limit }: { offset: number; limit: number }, tx?: Knex) => {
try {
- return await (tx || db.replicaNode())(TableName.KmsKekHistory).select("*").orderBy("activatedAt", "desc");
+ return await (tx || db.replicaNode())(TableName.KmsKekHistory)
+ .select("*")
+ .orderBy("activatedAt", "desc")
+ .offset(offset)
+ .limit(limit);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find kek history page" });
+ }
+ };
+
+ const findActiveByLabel = async (kekLabel: string, tx?: Knex) => {
+ try {
+ return await (tx || db)(TableName.KmsKekHistory).where({ kekLabel }).whereNull("retiredAt").first("*");
} catch (error) {
- throw new DatabaseError({ error, name: "Find kek history" });
+ throw new DatabaseError({ error, name: "Find active kek history by label" });
}
};
@@ -31,5 +43,5 @@ export const kmsKekHistoryDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, findHistory, findCurrent };
+ return { ...orm, findHistoryPage, findActiveByLabel, findCurrent };
};
diff --git a/backend/src/services/kms/kms-root-config-dal.ts b/backend/src/services/kms/kms-root-config-dal.ts
index 54f6a24100..b3e2831e05 100644
--- a/backend/src/services/kms/kms-root-config-dal.ts
+++ b/backend/src/services/kms/kms-root-config-dal.ts
@@ -33,14 +33,14 @@ export const kmsRootConfigDALFactory = (db: TDbClient) => {
}
};
- const findPending = async (tx?: Knex) => {
+ const findStaged = 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" });
+ throw new DatabaseError({ error, name: "Find staged kms root configs" });
}
};
@@ -56,18 +56,18 @@ export const kmsRootConfigDALFactory = (db: TDbClient) => {
}
};
- // Every pending row, not just the promoted one: an abandoned one is a live working key that would
+ // Every staged 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) => {
+ const deleteAllStaged = 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" });
+ throw new DatabaseError({ error, name: "Delete staged kms root configs" });
}
};
- return { ...kmsOrm, findById, findAll, findPending, findRetained, deleteAllPending };
+ return { ...kmsOrm, findById, findAll, findStaged, findRetained, deleteAllStaged };
};
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index c5a4176028..78f427dd26 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -81,13 +81,16 @@ type TKmsServiceFactoryDep = {
| "updateById"
| "transaction"
| "findAll"
- | "findPending"
+ | "findStaged"
| "findRetained"
- | "deleteAllPending"
+ | "deleteAllStaged"
| "deleteById"
>;
kmsLegacyEncryptionKeyDAL: Pick<TKmsLegacyEncryptionKeyDALFactory, "findById" | "create" | "transaction">;
- kmsKekHistoryDAL: Pick<TKmsKekHistoryDALFactory, "create" | "updateById" | "findHistory" | "findCurrent">;
+ kmsKekHistoryDAL: Pick<
+ TKmsKekHistoryDALFactory,
+ "create" | "updateById" | "findHistoryPage" | "findActiveByLabel" | "findCurrent"
+ >;
internalKmsDAL: Pick<TInternalKmsDALFactory, "create" | "findByKmsKeyIdForUpdate" | "updateById">;
internalKmsKeyVersionDAL: Pick<TInternalKmsKeyVersionDALFactory, "create" | "find">;
hsmService: THsmServiceFactory;
@@ -1507,13 +1510,13 @@ export const kmsServiceFactory = ({
* 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, label: string | null) => {
+ const $promoteRotation = async (stagedId: string, label: string | null) => {
return kmsRootConfigDAL.transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
- const pending = await kmsRootConfigDAL.findById(pendingId, tx);
+ const staged = await kmsRootConfigDAL.findById(stagedId, tx);
// Another pod promoted first, writing what we were about to write.
- if (!pending || pending.activatedAt) return false;
+ if (!staged || staged.activatedAt) return false;
const sentinel = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID, tx);
if (!sentinel) {
@@ -1539,18 +1542,18 @@ export const kmsServiceFactory = ({
await kmsRootConfigDAL.updateById(
KMS_ROOT_CONFIG_UUID,
{
- encryptedRootKey: pending.encryptedRootKey,
- encryptionStrategy: pending.encryptionStrategy,
- kekLabel: pending.kekLabel ?? label,
+ encryptedRootKey: staged.encryptedRootKey,
+ encryptionStrategy: staged.encryptionStrategy,
+ kekLabel: staged.kekLabel ?? label,
activatedAt: now,
supersededAt: null
},
tx
);
- await kmsRootConfigDAL.deleteAllPending(tx);
+ await kmsRootConfigDAL.deleteAllStaged(tx);
- const promotedLabel = pending.kekLabel ?? label;
+ const promotedLabel = staged.kekLabel ?? label;
const previous = await kmsKekHistoryDAL.findCurrent(tx);
if (previous) await kmsKekHistoryDAL.updateById(previous.id, { supersededAt: now }, tx);
if (promotedLabel) {
@@ -1558,11 +1561,11 @@ export const kmsServiceFactory = ({
}
// 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.kekLabel ? history.find((e) => e.kekLabel === stale.kekLabel && !e.retiredAt) : undefined;
+ // eslint-disable-next-line no-await-in-loop
+ const entry = stale.kekLabel ? await kmsKekHistoryDAL.findActiveByLabel(stale.kekLabel, tx) : undefined;
// eslint-disable-next-line no-await-in-loop
if (entry) await kmsKekHistoryDAL.updateById(entry.id, { retiredAt: now }, tx);
logger.info(
@@ -1639,7 +1642,7 @@ export const kmsServiceFactory = ({
const promoted = await $promoteRotation(row.id, label);
if (promoted) {
logger.info(
- `KMS: Promoted pending encryption key rotation [label=${label ?? "hsm"}] [rotationId=${row.id}]`
+ `KMS: Promoted staged encryption key rotation [label=${label ?? "hsm"}] [rotationId=${row.id}]`
);
}
}
@@ -1677,7 +1680,7 @@ export const kmsServiceFactory = ({
}
const label = $currentKekLabel();
- const history = await kmsKekHistoryDAL.findHistory().catch(() => []);
+ const history = await kmsKekHistoryDAL.findHistoryPage({ offset: 0, limit: 5 }).catch(() => []);
const known = history.map((entry) => entry.kekLabel).join(", ");
logger.error({ err: errors[0] }, "KMS: No stored root key could be decrypted with the configured encryption key");
throw new InternalServerError({
@@ -1803,8 +1806,8 @@ export const kmsServiceFactory = ({
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) {
+ const [staged, retained] = await Promise.all([kmsRootConfigDAL.findStaged(), kmsRootConfigDAL.findRetained()]);
+ if (staged.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."
@@ -1850,12 +1853,12 @@ export const kmsServiceFactory = ({
await kmsRootConfigDAL.transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);
- const [pendingNow, retainedNow, sentinelNow] = await Promise.all([
- kmsRootConfigDAL.findPending(tx),
+ const [stagedNow, retainedNow, sentinelNow] = await Promise.all([
+ kmsRootConfigDAL.findStaged(tx),
kmsRootConfigDAL.findRetained(tx),
kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID, tx)
]);
- if (pendingNow.length || retainedNow.length) {
+ if (stagedNow.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."
diff --git a/docs/self-hosting/guides/rotating-the-encryption-key.mdx b/docs/self-hosting/guides/rotating-the-encryption-key.mdx
index cbd31ea284..bb7f987647 100644
--- a/docs/self-hosting/guides/rotating-the-encryption-key.mdx
+++ b/docs/self-hosting/guides/rotating-the-encryption-key.mdx
@@ -3,24 +3,28 @@ title: "Rotating the Encryption Key"
description: "Replace the ENCRYPTION_KEY protecting your Infisical instance without downtime"
---
+<Info>
+ This guide is for instances that use `ENCRYPTION_KEY`. If you use an
+ [HSM](/self-hosting/guides/hsm-integration), rotate the key on the HSM instead.
+</Info>
+
[`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.
+Infisical generates a new key first. **The rotation only takes effect when an instance
+first starts with the new value**, so you can generate a key and discard it before you
+deploy without affecting the running instance.
<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.
+ Your secrets stay encrypted. Rotation changes which `ENCRYPTION_KEY` can decrypt them
+ rather than rewriting every secret, so it 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
@@ -65,11 +69,8 @@ one, think about it, and discard it with no consequences.
</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
- instance has since moved onto the new key. 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.
+ Infisical only sees instances that have restarted. Confirm every instance is on the new
+ key before you remove the previous one.
</Note>
</Step>
</Steps>
diff --git a/frontend/src/hooks/api/admin/mutation.ts b/frontend/src/hooks/api/admin/mutation.ts
index 4632ca27ba..808a519282 100644
--- a/frontend/src/hooks/api/admin/mutation.ts
+++ b/frontend/src/hooks/api/admin/mutation.ts
@@ -10,10 +10,11 @@ import {
AdminEmailDomain,
RootKeyEncryptionStrategy,
TAdminCreateEmailDomainDTO,
- TCompleteEncryptionKeyRotationDTO,
TCreateAdminUserDTO,
TCreatedEncryptionKeyRotation,
TCreateOrganizationDTO,
+ TDeleteExpiringEncryptionKeyDTO,
+ TDeleteStagedEncryptionKeyDTO,
TInvalidateCacheDTO,
TResendOrgInviteDTO,
TServerConfig,
@@ -196,41 +197,44 @@ export const useUpdateServerEncryptionStrategy = () => {
export const useCreateEncryptionKeyRotation = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ replacePending }: { replacePending?: boolean } = {}) => {
+ mutationFn: async ({ replaceStaged }: { replaceStaged?: boolean } = {}) => {
const { data } = await apiRequest.post<{ rotation: TCreatedEncryptionKeyRotation }>(
- `/api/v1/admin/encryption/rotations${replacePending ? "?replacePending=true" : ""}`
+ "/api/v1/admin/encryption/root-key/rotations",
+ { replaceStaged: Boolean(replaceStaged) }
);
return data.rotation;
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });
+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionRootKey() });
}
});
};
-export const useDiscardEncryptionKeyRotation = () => {
+export const useDeleteStagedEncryptionKey = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async (rotationId: string) => {
- await apiRequest.delete(`/api/v1/admin/encryption/rotations/${rotationId}`);
+ mutationFn: async ({ label }: TDeleteStagedEncryptionKeyDTO) => {
+ await apiRequest.delete("/api/v1/admin/encryption/root-key/staged", { params: { label } });
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });
+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionRootKey() });
}
});
};
-export const useCompleteEncryptionKeyRotation = () => {
+export const useDeleteExpiringEncryptionKey = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ rotationId, acknowledged }: TCompleteEncryptionKeyRotationDTO) => {
- await apiRequest.post(`/api/v1/admin/encryption/rotations/${rotationId}/complete`, {
- acknowledged
+ mutationFn: async ({ label, force }: TDeleteExpiringEncryptionKeyDTO) => {
+ await apiRequest.delete("/api/v1/admin/encryption/root-key/expiring", {
+ params: { label, ...(force ? { force: true } : {}) }
});
},
+ // Removing the expiring key retires its history row, so the rotations table is stale too.
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionStatus() });
+ queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionRootKey() });
+ queryClient.invalidateQueries({ queryKey: ["server-encryption-key-rotations"] });
}
});
};
diff --git a/frontend/src/hooks/api/admin/queries.ts b/frontend/src/hooks/api/admin/queries.ts
index e1f6518fc1..2f13ebff78 100644
--- a/frontend/src/hooks/api/admin/queries.ts
+++ b/frontend/src/hooks/api/admin/queries.ts
@@ -8,7 +8,8 @@ import {
AdminGetOrganizationsFilters,
AdminGetUsersFilters,
AdminIntegrationsConfig,
- TEncryptionStatus,
+ TEncryptionKeyRotationsPage,
+ TEncryptionRootKey,
TGetEmailDomainsResponse,
TGetEnvOverrides,
TGetIdentitiesResponse,
@@ -35,7 +36,9 @@ 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,
+ getEncryptionRootKey: () => ["server-encryption-root-key"] as const,
+ getEncryptionKeyRotations: (filters: { offset: number; limit: number }) =>
+ ["server-encryption-key-rotations", filters] as const,
getInvalidateCache: () => ["admin-invalidate-cache"] as const,
getAdminIntegrationsConfig: () => ["admin-integrations-config"] as const,
getEnvOverrides: () => ["env-overrides"] as const,
@@ -149,15 +152,35 @@ export const useGetServerRootKmsEncryptionDetails = () => {
});
};
-export const useGetEncryptionStatus = () => {
+export const useGetEncryptionRootKey = () => {
return useQuery({
- queryKey: adminQueryKeys.getEncryptionStatus(),
+ queryKey: adminQueryKeys.getEncryptionRootKey(),
queryFn: async () => {
- const { data } = await apiRequest.get<{ status: TEncryptionStatus }>(
- "/api/v1/admin/encryption/status"
+ const { data } = await apiRequest.get<{ rootKey: TEncryptionRootKey }>(
+ "/api/v1/admin/encryption/root-key"
);
- return data.status;
+ return data.rootKey;
+ }
+ });
+};
+
+export const useGetEncryptionKeyRotations = ({
+ offset,
+ limit
+}: {
+ offset: number;
+ limit: number;
+}) => {
+ return useQuery({
+ queryKey: adminQueryKeys.getEncryptionKeyRotations({ offset, limit }),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TEncryptionKeyRotationsPage>(
+ "/api/v1/admin/encryption/root-key/rotations",
+ { params: { offset, limit } }
+ );
+
+ return data;
}
});
};
diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts
index e32ad887da..286550b81f 100644
--- a/frontend/src/hooks/api/admin/types.ts
+++ b/frontend/src/hooks/api/admin/types.ts
@@ -241,38 +241,36 @@ export type TResendOrgInviteDTO = {
membershipId: string;
};
-export enum EncryptionRotationBlocker {
- HsmStrategy = "hsm-strategy",
- RotationPending = "rotation-pending"
-}
-
-export type TEncryptionStatus = {
- activeLabel: string | null;
+export type TEncryptionRootKey = {
encryptionStrategy: string | null;
- pendingRotation: { id: string; createdAt: string; label: string | null } | null;
- retainedKey: {
- id: string;
- supersededAt: string;
- lastResolvedAt: string | null;
- label: string | null;
- } | null;
- history: {
- label: string;
- activatedAt: string;
- supersededAt?: string | null;
- retiredAt?: string | null;
- }[];
- blockers: EncryptionRotationBlocker[];
+ active: { label: string | null; activatedAt: string };
+ staged: { label: string | null; createdAt: string } | null;
+ expiring: { label: string | null; supersededAt: string; lastResolvedAt: string | null } | null;
+};
+
+export type TEncryptionKeyRotation = {
+ label: string;
+ activatedAt: string;
+ supersededAt: string | null;
+ retiredAt: string | null;
+};
+
+export type TEncryptionKeyRotationsPage = {
+ rotations: TEncryptionKeyRotation[];
+ totalCount: number;
};
export type TCreatedEncryptionKeyRotation = {
- id: string;
label: string;
key: string;
- removesRetainedKey?: { label: string | null; lastResolvedAt: string | null };
+ removesExpiringKey?: { label: string | null; lastResolvedAt: string | null };
};
-export type TCompleteEncryptionKeyRotationDTO = {
- rotationId: string;
- acknowledged: boolean;
+export type TDeleteStagedEncryptionKeyDTO = {
+ label: string;
+};
+
+export type TDeleteExpiringEncryptionKeyDTO = {
+ label: string;
+ force?: boolean;
};
diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
index 42646dd171..65f3c04123 100644
--- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
+++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx
@@ -23,6 +23,7 @@ import {
DialogHeader,
DialogTitle,
Label,
+ Pagination,
Table,
TableBody,
TableCell,
@@ -31,34 +32,35 @@ import {
TableRow
} from "@app/components/v3";
import {
- useCompleteEncryptionKeyRotation,
useCreateEncryptionKeyRotation,
- useDiscardEncryptionKeyRotation,
- useGetEncryptionStatus
+ useDeleteExpiringEncryptionKey,
+ useDeleteStagedEncryptionKey,
+ useGetEncryptionKeyRotations,
+ useGetEncryptionRootKey
} from "@app/hooks/api";
import {
- EncryptionRotationBlocker,
+ RootKeyEncryptionStrategy,
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, isError } = useGetEncryptionStatus();
+ const { data: rootKey, isPending, isError } = useGetEncryptionRootKey();
const { mutateAsync: createRotation, isPending: isCreating } = useCreateEncryptionKeyRotation();
- const { mutateAsync: discardRotation } = useDiscardEncryptionKeyRotation();
- const { mutateAsync: completeRotation, isPending: isCompleting } =
- useCompleteEncryptionKeyRotation();
+ const { mutateAsync: deleteStagedKey } = useDeleteStagedEncryptionKey();
+ const { mutateAsync: deleteExpiringKey, isPending: isRemoving } =
+ useDeleteExpiringEncryptionKey();
const [generatedKey, setGeneratedKey] = useState<TCreatedEncryptionKeyRotation | null>(null);
const [acknowledged, setAcknowledged] = useState(false);
+ const [overrideStraggler, setOverrideStraggler] = useState(false);
+ const [page, setPage] = useState(1);
+ const [perPage, setPerPage] = useState(20);
+ const { data: rotationsPage } = useGetEncryptionKeyRotations({
+ offset: (page - 1) * perPage,
+ limit: perPage
+ });
- if (isError || (!isPending && !status)) {
+ if (isError || (!isPending && !rootKey)) {
return (
<Card className="mt-6">
<CardHeader>
@@ -78,28 +80,29 @@ export const EncryptionKeyRotationSection = () => {
);
}
- if (isPending || !status) return null;
+ if (isPending || !rootKey) return null;
- const rotateBlockers = status.blockers.filter(
- (blocker) => blocker !== EncryptionRotationBlocker.RotationPending
- );
- const canRotate = rotateBlockers.length === 0;
+ const isHsmManaged = rootKey.encryptionStrategy === RootKeyEncryptionStrategy.HSM;
const handleGenerate = async () => {
- const rotation = await createRotation({ replacePending: Boolean(status.pendingRotation) });
+ const rotation = await createRotation({ replaceStaged: Boolean(rootKey.staged) });
setGeneratedKey(rotation);
};
const handleDiscard = async () => {
- if (!status.pendingRotation) return;
- await discardRotation(status.pendingRotation.id);
+ if (!rootKey.staged?.label) return;
+ await deleteStagedKey({ label: rootKey.staged.label });
createNotification({ type: "success", text: "Generated encryption key discarded." });
};
- const handleComplete = async () => {
- if (!status.retainedKey) return;
- await completeRotation({ rotationId: status.retainedKey.id, acknowledged });
+ const handleRemoveExpiring = async () => {
+ if (!rootKey.expiring?.label) return;
+ await deleteExpiringKey({
+ label: rootKey.expiring.label,
+ force: overrideStraggler
+ });
setAcknowledged(false);
+ setOverrideStraggler(false);
createNotification({ type: "success", text: "Previous encryption key removed." });
};
@@ -119,43 +122,36 @@ export const EncryptionKeyRotationSection = () => {
<KeyRoundIcon className="size-4 text-foreground/60" />
<span className="text-foreground/70">Active key</span>
<Badge variant="neutral" className="font-mono">
- {status.activeLabel ?? "managed by HSM"}
+ {rootKey.active.label ?? "managed by HSM"}
</Badge>
+ <span className="text-xs text-foreground/60">
+ in use since {new Date(rootKey.active.activatedAt).toLocaleString()}
+ </span>
</div>
- {status.pendingRotation?.label && (
- <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.label}
- </Badge>
- </div>
- )}
-
- {status.blockers.map((blocker) => (
- <Alert
- key={blocker}
- variant={blocker === EncryptionRotationBlocker.RotationPending ? "info" : "warning"}
- >
+ {isHsmManaged ? (
+ <Alert variant="warning">
<AlertTriangleIcon />
- <AlertDescription>{BLOCKER_COPY[blocker]}</AlertDescription>
+ <AlertDescription>
+ 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.
+ </AlertDescription>
</Alert>
- ))}
-
- {canRotate && (
+ ) : (
<div className="flex flex-wrap gap-3">
<Button onClick={handleGenerate} isPending={isCreating}>
- {status.pendingRotation ? "Generate a replacement key" : "Generate new key"}
+ {rootKey.staged ? "Generate a replacement key" : "Generate new key"}
</Button>
- {status.pendingRotation && (
- <Button variant="danger" onClick={handleDiscard}>
+ {rootKey.staged && (
+ <Button variant="danger" isDisabled={!rootKey.staged.label} onClick={handleDiscard}>
Discard generated key
</Button>
)}
</div>
)}
- {status.retainedKey && (
+ {rootKey.expiring && (
<Alert variant="warning">
<ShieldAlertIcon />
<AlertTitle>The previous key still works</AlertTitle>
@@ -166,13 +162,26 @@ export const EncryptionKeyRotationSection = () => {
the new key can still start.
</p>
<p className="mt-2">
- {status.retainedKey.lastResolvedAt
+ {rootKey.expiring.lastResolvedAt
? `An instance last started on it ${new Date(
- status.retainedKey.lastResolvedAt
+ rootKey.expiring.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">
+ {rootKey.expiring.lastResolvedAt && (
+ <div className="flex items-start gap-2">
+ <Checkbox
+ id="override-straggler"
+ isChecked={overrideStraggler}
+ onCheckedChange={(value) => setOverrideStraggler(value === true)}
+ />
+ <Label htmlFor="override-straggler" className="text-xs font-normal">
+ Remove it even though an instance reported starting on it. That instance
+ will fail its next restart until it is given the new key.
+ </Label>
+ </div>
+ )}
<div className="flex items-start gap-2">
<Checkbox
id="ack-remove-old-key"
@@ -188,9 +197,9 @@ export const EncryptionKeyRotationSection = () => {
<Button
className="self-start"
variant="danger"
- isDisabled={!acknowledged}
- isPending={isCompleting}
- onClick={handleComplete}
+ isDisabled={!acknowledged || !rootKey.expiring.label}
+ isPending={isRemoving}
+ onClick={handleRemoveExpiring}
>
Remove previous key
</Button>
@@ -199,7 +208,7 @@ export const EncryptionKeyRotationSection = () => {
</Alert>
)}
- {status.history.length > 0 && (
+ {(rootKey.staged || (rotationsPage?.rotations.length ?? 0) > 0) && (
<div>
<p className="mb-2 text-sm font-medium">Key history</p>
<p className="mb-2 text-xs text-foreground/60">
@@ -215,14 +224,29 @@ export const EncryptionKeyRotationSection = () => {
</TableRow>
</TableHeader>
<TableBody>
- {status.history.map((entry) => (
+ {/* Pinned rather than a row of the list: a staged key has never encrypted anything,
+ so it is deliberately absent from the history the recovery path reads. */}
+ {rootKey.staged && page === 1 && (
+ <TableRow key="staged">
+ <TableCell className="font-mono text-xs">
+ {rootKey.staged.label ?? "unlabelled"}
+ </TableCell>
+ <TableCell className="text-foreground/50">
+ generated {new Date(rootKey.staged.createdAt).toLocaleString()}
+ </TableCell>
+ <TableCell>
+ <Badge variant="info">Staged, not applied</Badge>
+ </TableCell>
+ </TableRow>
+ )}
+ {rotationsPage?.rotations.map((entry) => (
<TableRow key={entry.label + entry.activatedAt}>
<TableCell className="font-mono text-xs">{entry.label}</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>
+ <Badge variant="neutral">Expiring</Badge>
)}
{entry.retiredAt && <Badge variant="neutral">Removed</Badge>}
</TableCell>
@@ -230,6 +254,18 @@ export const EncryptionKeyRotationSection = () => {
))}
</TableBody>
</Table>
+ {(rotationsPage?.totalCount ?? 0) > perPage && (
+ <Pagination
+ count={rotationsPage?.totalCount ?? 0}
+ page={page}
+ perPage={perPage}
+ onChangePage={setPage}
+ onChangePerPage={(rows) => {
+ setPerPage(rows);
+ setPage(1);
+ }}
+ />
+ )}
</div>
)}
</CardContent>
@@ -265,7 +301,7 @@ export const EncryptionKeyRotationSection = () => {
</p>
</div>
- {generatedKey?.removesRetainedKey && (
+ {generatedKey?.removesExpiringKey && (
<Alert variant="warning">
<AlertTriangleIcon />
<AlertTitle>This will remove your previous key</AlertTitle>
@@ -274,10 +310,10 @@ export const EncryptionKeyRotationSection = () => {
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.removesRetainedKey.lastResolvedAt && (
+ {generatedKey.removesExpiringKey.lastResolvedAt && (
<p className="mt-2">
An instance started on it{" "}
- {new Date(generatedKey.removesRetainedKey.lastResolvedAt).toLocaleString()}.
+ {new Date(generatedKey.removesExpiringKey.lastResolvedAt).toLocaleString()}.
</p>
)}
</AlertDescription>