Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor(encryption): enhance key rotation logic and API schema
Victor Hugo dos Santosa1f37074b0a6
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex cf7c842eb9..ee462a8b1a 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3970,6 +3970,8 @@ export const ENCRYPTION_KEY_ROTATION = {"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.",+ expiresAt:+ "When this key becomes eligible for automatic removal. An instance starting on it restarts this clock, since that is evidence one still needs it. The weekly cleanup removes the key on its first run after this time, so the key may outlive it by a few days.",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."}diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.tsindex a8eedff786..e987a0aff8 100644--- a/backend/src/server/routes/v1/admin-router.ts+++ b/backend/src/server/routes/v1/admin-router.ts@@ -29,7 +29,7 @@ import { getServerCfg } from "@app/services/super-admin/super-admin-service";import { CacheType, LoginMethod } from "@app/services/super-admin/super-admin-types";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-import { booleanSchema, SanitizedUserSchema } from "../sanitizedSchemas";+import { SanitizedUserSchema } from "../sanitizedSchemas";const SuperAdminSchema = SanitizedUserSchema.extend({superAdmin: z.boolean().optional().nullable()@@ -666,7 +666,8 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {.object({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)+ lastResolvedAt: z.date().nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.lastResolvedAt),+ expiresAt: z.date().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.expiresAt)}).nullable().describe(ENCRYPTION_KEY_ROTATION.ROOT_KEY.expiring.description)@@ -777,7 +778,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {schema: {operationId: "deleteAdminStagedEncryptionKey",description: ENCRYPTION_KEY_ROTATION.DELETE_STAGED.description,- querystring: z.object({+ body: z.object({label: z.string().trim().min(1).max(64).describe(ENCRYPTION_KEY_ROTATION.DELETE_STAGED.label)})},@@ -787,7 +788,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {});},handler: async (req, res) => {- await server.services.encryptionKeyRotation.deleteStagedKey({ label: req.query.label });+ await server.services.encryptionKeyRotation.deleteStagedKey({ label: req.body.label });void res.status(204);}@@ -802,9 +803,9 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {schema: {operationId: "deleteAdminExpiringEncryptionKey",description: ENCRYPTION_KEY_ROTATION.DELETE_EXPIRING.description,- querystring: z.object({+ body: 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)+ force: z.boolean().default(false).describe(ENCRYPTION_KEY_ROTATION.DELETE_EXPIRING.force)})},onRequest: (req, res, done) => {@@ -814,8 +815,8 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {},handler: async (req, res) => {await server.services.encryptionKeyRotation.deleteExpiringKey({- label: req.query.label,- force: req.query.force+ label: req.body.label,+ force: req.body.force});void res.status(204);diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.tsindex 7b9c6b2c60..6f66cfb9ef 100644--- a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.ts+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.test.ts@@ -2,7 +2,7 @@ import { crypto } from "@app/lib/crypto/cryptography";import { initLogger } from "@app/lib/logger";import { resolveInstanceEncryptionKeyBuffer } from "@app/services/kms/kms-fns";-import { generateRootEncryptionKey, resolveKekBuffer } from "./encryption-key-rotation-fns";+import { generateRootEncryptionKey, getKeyRemovalEligibleAt, resolveKekBuffer } from "./encryption-key-rotation-fns";// The cryptography module logs during initialization, and the logger is a module-level singleton that// only exists once initLogger has run.@@ -87,3 +87,31 @@ describe("resolveKekBuffer", () => {}});});++describe("getKeyRemovalEligibleAt", () => {+ const RETENTION_DAYS = 7;+ const DAY_MS = 24 * 60 * 60 * 1000;+ const supersededAt = new Date("2026-01-01T00:00:00.000Z");++ it("counts from when the key was superseded if nothing has started on it", () => {+ const at = getKeyRemovalEligibleAt({ supersededAt, lastResolvedAt: null }, RETENTION_DAYS);++ expect(at.toISOString()).toBe("2026-01-08T00:00:00.000Z");+ });++ it("restarts the clock when an instance starts on the key", () => {+ // The whole reason this is computed rather than shown as supersededAt plus the window: a straggler+ // boot is evidence the key is still needed, and the collector declines while that evidence is fresh.+ const lastResolvedAt = new Date(supersededAt.getTime() + 5 * DAY_MS);+ const at = getKeyRemovalEligibleAt({ supersededAt, lastResolvedAt }, RETENTION_DAYS);++ expect(at.toISOString()).toBe("2026-01-13T00:00:00.000Z");+ });++ it("ignores a stamp older than the supersede, which cannot be evidence about this key", () => {+ const lastResolvedAt = new Date(supersededAt.getTime() - 3 * DAY_MS);+ const at = getKeyRemovalEligibleAt({ supersededAt, lastResolvedAt }, RETENTION_DAYS);++ expect(at.toISOString()).toBe("2026-01-08T00:00:00.000Z");+ });+});diff --git a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.ts b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.tsindex 6510bd3dc7..4b77d8e3b9 100644--- a/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.ts+++ b/backend/src/services/encryption-key-rotation/encryption-key-rotation-fns.ts@@ -6,3 +6,14 @@ export const generateRootEncryptionKey = (isFipsEnabled: boolean) =>export const resolveKekBuffer = (key: string, isFipsEnabled: boolean) =>resolveInstanceEncryptionKeyBuffer(isFipsEnabled ? { ROOT_ENCRYPTION_KEY: key } : { ENCRYPTION_KEY: key });++/** Later of supersededAt and lastResolvedAt plus retention; a straggler boot restarts the clock. */+export const getKeyRemovalEligibleAt = (+ row: { supersededAt: Date; lastResolvedAt?: Date | null },+ retentionDays: number+) => {+ const supersededAt = new Date(row.supersededAt).getTime();+ const lastResolvedAt = row.lastResolvedAt ? new Date(row.lastResolvedAt).getTime() : supersededAt;++ return new Date(Math.max(supersededAt, lastResolvedAt) + retentionDays * 24 * 60 * 60 * 1000);+};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.tsindex b4d2028730..d1f52655a5 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@@ -13,7 +13,7 @@ import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal"import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";-import { generateRootEncryptionKey, resolveKekBuffer } from "./encryption-key-rotation-fns";+import { generateRootEncryptionKey, getKeyRemovalEligibleAt, resolveKekBuffer } from "./encryption-key-rotation-fns";import {TCreatedRotation,TCreateRotationDTO,@@ -80,7 +80,11 @@ export const encryptionKeyRotationServiceFactory = ({? {label: retained.kekLabel ?? null,supersededAt: retained.supersededAt as Date,- lastResolvedAt: retained.lastResolvedAt ?? null+ lastResolvedAt: retained.lastResolvedAt ?? null,+ expiresAt: getKeyRemovalEligibleAt(+ { supersededAt: retained.supersededAt as Date, lastResolvedAt: retained.lastResolvedAt },+ envConfig.KMS_ROOT_KEY_RETENTION_DAYS+ )}: null};@@ -282,7 +286,7 @@ export const encryptionKeyRotationServiceFactory = ({});};- const runGarbageCollection = async () => {+ const removeInactiveKeys = async () => {const [retained, staged] = await Promise.all([kmsRootConfigDAL.findRetained(), kmsRootConfigDAL.findStaged()]);// replaceStaged caps staged keys at one, so this is for the admin who generated a key and walked away.@@ -305,8 +309,6 @@ export const encryptionKeyRotationServiceFactory = ({if (!retained.length) return;- const retentionMs = envConfig.KMS_ROOT_KEY_RETENTION_DAYS * 24 * 60 * 60 * 1000;-// 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@@ -315,8 +317,10 @@ export const encryptionKeyRotationServiceFactory = ({// restart with an error naming the key it needs, not lost data.const eligible = retained.filter((row) =>- !(row.lastResolvedAt && now - new Date(row.lastResolvedAt).getTime() < retentionMs) &&- now - new Date(row.supersededAt as Date).getTime() >= retentionMs+ getKeyRemovalEligibleAt(+ { supersededAt: row.supersededAt as Date, lastResolvedAt: row.lastResolvedAt },+ envConfig.KMS_ROOT_KEY_RETENTION_DAYS+ ).getTime() <= now);for (const row of eligible) {@@ -325,7 +329,12 @@ export const encryptionKeyRotationServiceFactory = ({await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.KmsRootKeyInit]);const current = await kmsRootConfigDAL.findById(row.id, tx);if (!current || !current.supersededAt) return false;- if (current.lastResolvedAt && Date.now() - new Date(current.lastResolvedAt).getTime() < retentionMs)+ if (+ getKeyRemovalEligibleAt(+ { supersededAt: current.supersededAt, lastResolvedAt: current.lastResolvedAt },+ envConfig.KMS_ROOT_KEY_RETENTION_DAYS+ ).getTime() > Date.now()+ )return false;return $retireRetainedKey(tx, current);});@@ -350,7 +359,7 @@ export const encryptionKeyRotationServiceFactory = ({name: CronJobName.KmsRootKeyCleanup,pattern: "0 3 * * 0",runHashTtlS: 60 * 60,- handler: runGarbageCollection+ handler: removeInactiveKeys});};@@ -361,6 +370,6 @@ export const encryptionKeyRotationServiceFactory = ({createRotation,deleteStagedKey,deleteExpiringKey,- runGarbageCollection+ runGarbageCollection: removeInactiveKeys};};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.tsindex 0b94fc540b..7e5eb408e4 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@@ -2,7 +2,7 @@ export type TRootKeyStatus = {encryptionStrategy: string | null;active: { label: string | null; activatedAt: Date };staged: { label: string | null; createdAt: Date } | null;- expiring: { label: string | null; supersededAt: Date; lastResolvedAt: Date | null } | null;+ expiring: { label: string | null; supersededAt: Date; lastResolvedAt: Date | null; expiresAt: Date } | null;};export type TCreateRotationDTO = {diff --git a/frontend/src/hooks/api/admin/mutation.ts b/frontend/src/hooks/api/admin/mutation.tsindex 808a519282..1d669b84bc 100644--- a/frontend/src/hooks/api/admin/mutation.ts+++ b/frontend/src/hooks/api/admin/mutation.ts@@ -215,7 +215,7 @@ export const useDeleteStagedEncryptionKey = () => {const queryClient = useQueryClient();return useMutation({mutationFn: async ({ label }: TDeleteStagedEncryptionKeyDTO) => {- await apiRequest.delete("/api/v1/admin/encryption/root-key/staged", { params: { label } });+ await apiRequest.delete("/api/v1/admin/encryption/root-key/staged", { data: { label } });},onSuccess: () => {queryClient.invalidateQueries({ queryKey: adminQueryKeys.getEncryptionRootKey() });@@ -228,7 +228,7 @@ export const useDeleteExpiringEncryptionKey = () => {return useMutation({mutationFn: async ({ label, force }: TDeleteExpiringEncryptionKeyDTO) => {await apiRequest.delete("/api/v1/admin/encryption/root-key/expiring", {- params: { label, ...(force ? { force: true } : {}) }+ data: { label, force: Boolean(force) }});},// Removing the expiring key retires its history row, so the rotations table is stale too.diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.tsindex 286550b81f..e31907fe66 100644--- a/frontend/src/hooks/api/admin/types.ts+++ b/frontend/src/hooks/api/admin/types.ts@@ -245,7 +245,12 @@ export type TEncryptionRootKey = {encryptionStrategy: string | null;active: { label: string | null; activatedAt: string };staged: { label: string | null; createdAt: string } | null;- expiring: { label: string | null; supersededAt: string; lastResolvedAt: string | null } | null;+ expiring: {+ label: string | null;+ supersededAt: string;+ lastResolvedAt: string | null;+ expiresAt: string;+ } | null;};export type TEncryptionKeyRotation = {diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsxindex 65f3c04123..58f53b7068 100644--- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx+++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionKeyRotationSection.tsx@@ -168,6 +168,11 @@ export const EncryptionKeyRotationSection = () => {).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>+ <p className="mt-2">+ It is removed automatically after{" "}+ {new Date(rootKey.expiring.expiresAt).toLocaleString()}. If an instance starts+ with this key before the expiry date, it will delay removal.+ </p><div className="mt-3 flex flex-col gap-2">{rootKey.expiring.lastResolvedAt && (<div className="flex items-start gap-2">@@ -246,7 +251,11 @@ export const EncryptionKeyRotationSection = () => {<TableCell>{!entry.supersededAt && <Badge variant="success">Active</Badge>}{entry.supersededAt && !entry.retiredAt && (- <Badge variant="neutral">Expiring</Badge>+ <Badge variant="neutral">+ {rootKey.expiring?.label === entry.label+ ? `Expires ${new Date(rootKey.expiring.expiresAt).toLocaleDateString()}`+ : "Expiring"}+ </Badge>)}{entry.retiredAt && <Badge variant="neutral">Removed</Badge>}</TableCell>