Skip to content

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

fix migration

Thiago Araujo da Silva2a6c7ef1f5db
diff --git a/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
index 5999d493db..27b9e0702b 100644
--- a/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
+++ b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
@@ -1,7 +1,39 @@
import { Knex } from "knex";
+import { inMemoryKeyStore } from "@app/keystore/memory";
+import { initLogger } from "@app/lib/logger";
+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
+import { generateRecoveryCode } from "@app/services/mfa-recovery-code/mfa-recovery-code-fns";
+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
+
import { TableName } from "../schemas";
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
+import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
+
+const BATCH_SIZE = 500;
+// Keep in sync with MAX_RECOVERY_CODE_LIMIT in mfa-recovery-code-service.ts.
+const RECOVERY_CODE_COUNT = 10;
+
+// Boots just enough of the KMS stack to mint root-key ciphertext from within a
+// migration, mirroring the runtime mfaRecoveryCodeService.
+const startRootEncryptor = async (knex: Knex) => {
+ initLogger();
+ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
+ const superAdminDAL = superAdminDALFactory(knex);
+ const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
+ const keyStore = inMemoryKeyStore();
+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
+ return kmsService.encryptWithRootKey();
+};
+
+// Same code count + encoding as generateEncryptedRecoveryCodes in the service,
+// so the ciphertext decrypts identically in either store.
+const generateEncryptedRecoveryCodes = (encryptWithRoot: (plainText: Buffer) => Buffer) => {
+ const recoveryCodes = Array.from({ length: RECOVERY_CODE_COUNT }).map(generateRecoveryCode);
+ return encryptWithRoot(Buffer.from(recoveryCodes.join(",")));
+};
export async function up(knex: Knex): Promise<void> {
if (!(await knex.schema.hasTable(TableName.UserMfaRecoveryCode))) {
@@ -31,6 +63,33 @@ export async function up(knex: Knex): Promise<void> {
);
}
+ // Some MFA-enabled users have no pool after the copy above: email-MFA users
+ // (no TOTP config at all) and users whose TOTP config was never verified.
+ // Going forward the disabled->enabled transition mints codes, but these
+ // pre-existing users would be stuck — unable to finish org-enforced
+ // enrollment or use recovery-code login — so generate a fresh pool for them.
+ const usersMissingRecoveryCodes = await knex(TableName.Users)
+ .leftJoin(TableName.UserMfaRecoveryCode, `${TableName.UserMfaRecoveryCode}.userId`, `${TableName.Users}.id`)
+ .where(`${TableName.Users}.isMfaEnabled`, true)
+ .whereNull(`${TableName.UserMfaRecoveryCode}.id`)
+ .select(`${TableName.Users}.id`);
+
+ if (usersMissingRecoveryCodes.length) {
+ const encryptWithRoot = await startRootEncryptor(knex);
+ const rows = usersMissingRecoveryCodes.map(({ id }) => ({
+ userId: id,
+ encryptedRecoveryCodes: generateEncryptedRecoveryCodes(encryptWithRoot)
+ }));
+
+ for (let i = 0; i < rows.length; i += BATCH_SIZE) {
+ // eslint-disable-next-line no-await-in-loop
+ await knex(TableName.UserMfaRecoveryCode)
+ .insert(rows.slice(i, i + BATCH_SIZE))
+ .onConflict("userId")
+ .ignore();
+ }
+ }
+
// Recovery codes now live in user_mfa_recovery_codes. The values were copied
// above, so drop the legacy column from totp_configs.
if (await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes")) {
@@ -41,10 +100,8 @@ export async function up(knex: Knex): Promise<void> {
}
export async function down(knex: Knex): Promise<void> {
- // Recreate the legacy column so the pre-migration TOTP code can read recovery
- // codes again. It is nullable because TOTP configs created after the column
- // was dropped have no ciphertext to restore (their codes only live in the
- // account-level store, which may have no row for a given user).
+ // Recreate the legacy column nullable for now so the backfill below can
+ // populate it; the original NOT NULL constraint is restored at the end.
if (!(await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes"))) {
await knex.schema.alterTable(TableName.TotpConfig, (t) => {
t.binary("encryptedRecoveryCodes").nullable();
@@ -65,4 +122,33 @@ export async function down(knex: Knex): Promise<void> {
await dropOnUpdateTrigger(knex, TableName.UserMfaRecoveryCode);
await knex.schema.dropTable(TableName.UserMfaRecoveryCode);
}
+
+ // TOTP configs created after the column was dropped (or whose account-level
+ // pool was missing) still have NULL. The pre-migration TOTP code decrypts this
+ // column unconditionally and the original schema was NOT NULL, so mint a fresh
+ // pool for those rows before restoring the constraint — otherwise the rolled-
+ // back code throws a 500 on every TOTP settings load / login for those users.
+ const totpConfigsMissingCodes = await knex(TableName.TotpConfig).whereNull("encryptedRecoveryCodes").select("id");
+
+ if (totpConfigsMissingCodes.length) {
+ const encryptWithRoot = await startRootEncryptor(knex);
+
+ for (const { id } of totpConfigsMissingCodes) {
+ // Raw update: encryptedRecoveryCodes was dropped from the generated schema,
+ // so the typed query builder no longer knows the (recreated) column.
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(`UPDATE ?? SET "encryptedRecoveryCodes" = ? WHERE "id" = ?`, [
+ TableName.TotpConfig,
+ generateEncryptedRecoveryCodes(encryptWithRoot),
+ id
+ ]);
+ }
+ }
+
+ // Restore the original NOT NULL constraint now that every row has ciphertext.
+ if (await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes")) {
+ await knex.schema.alterTable(TableName.TotpConfig, (t) => {
+ t.binary("encryptedRecoveryCodes").notNullable().alter();
+ });
+ }
}
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index f657eef233..1e822c4f0d 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -744,6 +744,12 @@ export const authLoginServiceFactory = ({
});
}
} catch (err) {
+ if (isRecoveryCode && err instanceof NotFoundError) {
+ throw new BadRequestError({
+ message: "No recovery codes are configured for this account. Please use another MFA method."
+ });
+ }
+
const updatedUser = await processFailedMfaAttempt(userId);
if (updatedUser.isLocked) {
if (updatedUser.email) {
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index 767857b755..2e6a495c10 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -24,7 +24,7 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
const [phase, setPhase] = useState<"preparing" | "verify" | "recovery">("preparing");
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
const [isLoadingCodes, setIsLoadingCodes] = useState(false);
- const [hasDownloaded, setHasDownloaded] = useState(false);
+ const [hasSaved, setHasSaved] = useState(false);
const hasPrepared = useRef(false);
const hasRecoveryCodes = recoveryCodes.length > 0;
@@ -110,7 +110,7 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
</Alert>
<RecoveryCodesView
recoveryCodes={recoveryCodes}
- onDownloaded={() => setHasDownloaded(true)}
+ onSaved={() => setHasSaved(true)}
/>
</>
) : (
@@ -129,7 +129,7 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
<Button
variant="org"
isFullWidth
- isDisabled={!hasRecoveryCodes || !hasDownloaded}
+ isDisabled={!hasRecoveryCodes || !hasSaved}
onClick={handleContinue}
>
Continue
diff --git a/frontend/src/components/mfa/setup/RecoveryCodesView.tsx b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
index 4c96b99640..367489be75 100644
--- a/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
+++ b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
@@ -5,10 +5,10 @@ import { Button } from "@app/components/v3";
type Props = {
recoveryCodes: string[];
- onDownloaded?: () => void;
+ onSaved?: () => void;
};
-export const RecoveryCodesView = ({ recoveryCodes, onDownloaded }: Props) => {
+export const RecoveryCodesView = ({ recoveryCodes, onSaved }: Props) => {
const [copied, setCopied] = useState(false);
const handleDownload = () => {
@@ -22,7 +22,7 @@ export const RecoveryCodesView = ({ recoveryCodes, onDownloaded }: Props) => {
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
- onDownloaded?.();
+ onSaved?.();
};
const handleCopy = async () => {
@@ -30,6 +30,7 @@ export const RecoveryCodesView = ({ recoveryCodes, onDownloaded }: Props) => {
await navigator.clipboard.writeText(recoveryCodes.join("\n"));
setCopied(true);
setTimeout(() => setCopied(false), 2000);
+ onSaved?.();
} catch {
// ignore clipboard failures
}
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index 5f44067b6c..8b8636e9b4 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -107,8 +107,8 @@ export const useRotateMfaRecoveryCodes = () => {
return data;
},
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });
+ onSuccess: (data) => {
+ queryClient.setQueryData(userKeys.mfaRecoveryCodes, data.recoveryCodes);
queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });
}
});
diff --git a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
index 286a681a99..180348de77 100644
--- a/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
+++ b/frontend/src/hooks/api/webauthn/useRegisterPasskey.tsx
@@ -24,6 +24,16 @@ export const useRegisterPasskey = () => {
return false;
}
+ const isAuthenticatorAvailable =
+ await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
+ if (!isAuthenticatorAvailable) {
+ createNotification({
+ text: "No passkey-compatible authenticator found on this device",
+ type: "error"
+ });
+ return false;
+ }
+
setIsRegistering(true);
try {
const options = await generateOptions();
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
index 3ecfb4cc08..671149f272 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaSetupWizard/MfaSetupWizard.tsx
@@ -35,7 +35,7 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
const [step, setStep] = useState(0);
const [selectedMethod, setSelectedMethod] = useState<MfaMethod>(MfaMethod.TOTP);
- const [hasDownloaded, setHasDownloaded] = useState(false);
+ const [hasSaved, setHasSaved] = useState(false);
const {
data: recoveryCodes = [],
@@ -50,7 +50,7 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
// Reset once the close animation is unlikely to be visible.
setStep(0);
setSelectedMethod(MfaMethod.TOTP);
- setHasDownloaded(false);
+ setHasSaved(false);
}
}, [isOpen]);
@@ -122,7 +122,7 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
</Alert>
<RecoveryCodesView
recoveryCodes={recoveryCodes}
- onDownloaded={() => setHasDownloaded(true)}
+ onSaved={() => setHasSaved(true)}
/>
</>
) : (
@@ -160,7 +160,7 @@ export const MfaSetupWizard = ({ isOpen, onOpenChange }: Props) => {
{step === 2 && (
<Button
variant="org"
- isDisabled={!hasRecoveryCodes || !hasDownloaded}
+ isDisabled={!hasRecoveryCodes || !hasSaved}
onClick={handleDone}
>
Done
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
index c1a43bd460..0f9c5a5b51 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/RecoveryOptionsCard.tsx
@@ -23,13 +23,13 @@ import {
import { useGetMfaRecoveryCodes, useRotateMfaRecoveryCodes } from "@app/hooks/api/users";
export const RecoveryOptionsCard = () => {
- const { data: recoveryCodes = [] } = useGetMfaRecoveryCodes(true);
- const { mutateAsync: rotate, isPending: isRotating } = useRotateMfaRecoveryCodes();
-
const [isViewOpen, setIsViewOpen] = useState(false);
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
const [hasViewed, setHasViewed] = useState(false);
+ const { data: recoveryCodes = [] } = useGetMfaRecoveryCodes(isViewOpen);
+ const { mutateAsync: rotate, isPending: isRotating } = useRotateMfaRecoveryCodes();
+
const handleRegenerate = async () => {
try {
await rotate();