Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Require an MFA code before adding a passkey (#4204)

GFR94c0a5d3e2c5
diff --git a/app/controllers/settings/webauthn_credentials_controller.rb b/app/controllers/settings/webauthn_credentials_controller.rb
index cfcadf3158..dd2a046475 100644
--- a/app/controllers/settings/webauthn_credentials_controller.rb
+++ b/app/controllers/settings/webauthn_credentials_controller.rb
@@ -5,7 +5,20 @@ class Settings::WebauthnCredentialsController < ApplicationController
before_action :ensure_mfa_enabled
+ # Adding a passkey is confirmed with an MFA code; keep a stolen session from
+ # guessing that code. Both steps check it, so each gets its own counter:
+ # guessing through either one alone stays at 10 a minute.
+ rate_limit to: 10, within: 1.minute, by: -> { Current.user.id }, only: :options, name: "code-check",
+ with: -> { render json: { error: t("webauthn_credentials.rate_limited") }, status: :too_many_requests }
+ rate_limit to: 10, within: 1.minute, by: -> { Current.user.id }, only: :create, name: "code-spend",
+ with: -> { render json: { error: t("webauthn_credentials.rate_limited") }, status: :too_many_requests }
+
def options
+ # Refuse a bad code before the browser runs its ceremony; otherwise the
+ # authenticator keeps a discoverable passkey the server never saves.
+ code_status = Current.user.otp_code_status(webauthn_credential_params[:code])
+ return render_code_error(code_status) unless code_status == :accepted
+
Current.user.ensure_webauthn_id!
registration_options = webauthn_relying_party.options_for_registration(
@@ -43,15 +56,29 @@ class Settings::WebauthnCredentialsController < ApplicationController
user_presence: true
)
- Current.user.webauthn_credentials.create!(
- nickname: webauthn_credential_name,
- credential_id: credential.id,
- public_key: credential.public_key,
- sign_count: credential.sign_count,
- transports: webauthn_credential_transports
- )
+ # A passkey is a lasting second factor and also a passwordless sign-in, so
+ # adding one must prove more than the session cookie. The code is spent in
+ # the same transaction as the save, so a registration that fails (or a
+ # cancelled browser prompt) never uses up a single-use code.
+ code_result = nil
+ Current.user.transaction do
+ code_result = Current.user.verify_otp(webauthn_credential_params[:code])
+ raise ActiveRecord::Rollback unless code_result == :accepted
+
+ Current.user.webauthn_credentials.create!(
+ nickname: webauthn_credential_name,
+ credential_id: credential.id,
+ public_key: credential.public_key,
+ sign_count: credential.sign_count,
+ transports: webauthn_credential_transports
+ )
+ end
- render json: { redirect_url: settings_security_path }
+ if code_result == :accepted
+ render json: { redirect_url: settings_security_path }
+ else
+ render_code_error(code_result)
+ end
rescue WebAuthn::Error, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique, ActionController::BadRequest, ActionController::ParameterMissing
render json: { error: t("webauthn_credentials.failure") }, status: :unprocessable_entity
end
@@ -79,8 +106,13 @@ class Settings::WebauthnCredentialsController < ApplicationController
Array(credential_response_params.dig(:response, :transports)).compact_blank
end
+ def render_code_error(code_status)
+ key = code_status == :replayed ? "webauthn_credentials.code_already_used" : "webauthn_credentials.invalid_code"
+ render json: { error: t(key) }, status: :unprocessable_entity
+ end
+
def webauthn_credential_params
- params.fetch(:webauthn_credential, ActionController::Parameters.new).permit(:nickname)
+ params.fetch(:webauthn_credential, ActionController::Parameters.new).permit(:nickname, :code)
end
def credential_response_params
diff --git a/app/javascript/controllers/webauthn_registration_controller.js b/app/javascript/controllers/webauthn_registration_controller.js
index 2e0325a6fd..52ff6c66fa 100644
--- a/app/javascript/controllers/webauthn_registration_controller.js
+++ b/app/javascript/controllers/webauthn_registration_controller.js
@@ -5,7 +5,7 @@ import {
} from "utils/webauthn";
export default class extends WebauthnController {
- static targets = ["error", "nickname"];
+ static targets = ["error", "nickname", "code"];
static values = {
optionsUrl: String,
createUrl: String,
@@ -39,6 +39,9 @@ export default class extends WebauthnController {
method: "POST",
headers: this.headers,
credentials: "same-origin",
+ body: JSON.stringify({
+ webauthn_credential: { code: this.enteredCode },
+ }),
});
if (!response.ok) throw new Error(await this.errorMessage(response));
@@ -46,6 +49,10 @@ export default class extends WebauthnController {
return response.json();
}
+ get enteredCode() {
+ return this.hasCodeTarget ? this.codeTarget.value : "";
+ }
+
async createCredential(credential) {
const response = await fetch(this.createUrlValue, {
method: "POST",
@@ -55,6 +62,7 @@ export default class extends WebauthnController {
credential,
webauthn_credential: {
nickname: this.hasNicknameTarget ? this.nicknameTarget.value : "",
+ code: this.enteredCode,
},
}),
});
diff --git a/app/models/user.rb b/app/models/user.rb
index e94793e00a..0bfb8b77e1 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -515,6 +515,25 @@ class User < ApplicationRecord
end
end
+ # Same answer as verify_otp, but spends nothing: lets a passkey registration
+ # refuse a bad code before the browser creates a credential the server would
+ # then throw away. The code is still consumed by verify_otp when it is saved.
+ def otp_code_status(code)
+ return :invalid if otp_secret.blank?
+
+ normalized_code = normalize_mfa_code(code)
+ return :invalid if normalized_code.blank?
+
+ return :accepted if totp.verify(normalized_code, drift_behind: 15, after: otp_last_used_at)
+
+ if backup_code_input?(normalized_code)
+ matched = Array(otp_backup_codes).any? { |stored_code| backup_code_matches?(stored_code, normalized_code) }
+ return matched ? :accepted : :invalid
+ end
+
+ totp.verify(normalized_code, drift_behind: 15) ? :replayed : :invalid
+ end
+
def verify_otp?(code)
verify_otp(code) == :accepted
end
diff --git a/app/views/settings/securities/show.html.erb b/app/views/settings/securities/show.html.erb
index 4ec0d554ae..dc97bb415d 100644
--- a/app/views/settings/securities/show.html.erb
+++ b/app/views/settings/securities/show.html.erb
@@ -120,6 +120,13 @@
label: t(".webauthn_name_label"),
data: { webauthn_registration_target: "nickname" } %>
+ <%= form.text_field :code,
+ required: true,
+ autocomplete: "one-time-code",
+ label: t(".webauthn_code_label"),
+ placeholder: t(".webauthn_code_placeholder"),
+ data: { webauthn_registration_target: "code" } %>
+
<p class="text-sm text-destructive" role="alert" aria-live="assertive" aria-atomic="true" aria-hidden="true" hidden data-webauthn-registration-target="error"></p>
<div>
diff --git a/config/locales/views/settings/securities/ca.yml b/config/locales/views/settings/securities/ca.yml
index dc60f7e7b0..7cbfbd9f7d 100644
--- a/config/locales/views/settings/securities/ca.yml
+++ b/config/locales/views/settings/securities/ca.yml
@@ -25,6 +25,8 @@ ca:
webauthn_empty: Encara no hi ha cap clau d'accés ni de seguretat registrada.
webauthn_last_used: Última utilització fa %{time_ago}
webauthn_name_label: Nom de la clau
+ webauthn_code_label: "Codi d'autenticador o de recuperació"
+ webauthn_code_placeholder: "Codi actual de l'autenticador o un codi de recuperació sense utilitzar"
webauthn_name_placeholder: Touch ID MacBook, YubiKey, etc.
webauthn_remove: Elimina
webauthn_remove_confirm: Segur que vols eliminar aquesta clau d'accés o de
@@ -35,6 +37,9 @@ ca:
webauthn_title: Claus d'accés i claus de seguretat
webauthn_unsupported: Aquest navegador no admet claus d'accés ni de seguretat.
webauthn_credentials:
+ code_already_used: "Aquest codi ja s'ha utilitzat. Espera el codi següent de l'aplicació d'autenticació."
+ invalid_code: "Aquest codi no és vàlid. Introdueix un codi actual de l'aplicació d'autenticació o un codi de recuperació sense utilitzar."
+ rate_limited: "Massa intents. Espera un minut i torna-ho a provar."
default_name: Clau de seguretat
failure: No s'ha pogut desar aquesta clau d'accés o de seguretat. Torna-ho a provar.
mfa_required: Activa l'autenticació en dos passos abans d'afegir una clau d'accés o
diff --git a/config/locales/views/settings/securities/de.yml b/config/locales/views/settings/securities/de.yml
index b3741e817a..a592468aad 100644
--- a/config/locales/views/settings/securities/de.yml
+++ b/config/locales/views/settings/securities/de.yml
@@ -14,6 +14,8 @@ de:
mfa_enabled_status_html: Zwei-Faktor-Authentifizierung ist <span class="font-medium text-green-600">aktiv</span>
webauthn_add: Passkey oder Sicherheitsschlüssel hinzufügen
webauthn_added: Hinzugefügt am %{date}
+ webauthn_code_label: Authenticator- oder Backup-Code
+ webauthn_code_placeholder: Aktueller Authenticator-Code oder unbenutzter Backup-Code
webauthn_description: Nutz einen Passkey, Touch ID, Windows Hello oder einen Hardware-Sicherheitsschlüssel als zweiten Faktor beim Anmelden.
webauthn_empty: Es sind noch keine Passkeys oder Sicherheitsschlüssel hinterlegt.
webauthn_last_used: Zuletzt genutzt vor %{time_ago}
@@ -25,7 +27,10 @@ de:
webauthn_title: Passkeys und Sicherheitsschlüssel
webauthn_unsupported: Dieser Browser unterstützt keine Passkeys oder Sicherheitsschlüssel.
webauthn_credentials:
+ code_already_used: Dieser Code wurde schon verwendet. Warte auf den nächsten Code aus deiner Authenticator-App.
default_name: Sicherheitsschlüssel
failure: Dieser Passkey oder Sicherheitsschlüssel ließ sich nicht speichern. Versuch es noch einmal.
+ invalid_code: Dieser Code ist ungültig. Gib einen aktuellen Code aus deiner Authenticator-App oder einen unbenutzten Backup-Code ein.
mfa_required: Aktivier die Zwei-Faktor-Authentifizierung, bevor du einen Passkey oder Sicherheitsschlüssel hinzufügst.
+ rate_limited: Zu viele Versuche. Warte eine Minute und versuch es dann noch einmal.
success: Passkey oder Sicherheitsschlüssel entfernt.
diff --git a/config/locales/views/settings/securities/en.yml b/config/locales/views/settings/securities/en.yml
index 1b8ae56418..f2b0081b37 100644
--- a/config/locales/views/settings/securities/en.yml
+++ b/config/locales/views/settings/securities/en.yml
@@ -16,6 +16,8 @@ en:
mfa_title: Two-Factor Authentication
webauthn_add: Add passkey or security key
webauthn_added: Added %{date}
+ webauthn_code_label: Authenticator or backup code
+ webauthn_code_placeholder: Current authenticator code or an unused backup code
webauthn_description: Use a passkey, Touch ID, Windows Hello, or a hardware
security key as a second factor when signing in.
webauthn_empty: No passkeys or security keys are registered yet.
@@ -31,8 +33,11 @@ en:
webauthn_unsupported: This browser does not support passkeys or security
keys.
webauthn_credentials:
+ code_already_used: That code was already used. Wait for the next code from your authenticator app.
default_name: Security key
failure: Could not save that passkey or security key. Please try again.
+ invalid_code: That code is not valid. Enter a current code from your authenticator app or an unused backup code.
mfa_required: Enable two-factor authentication before adding a passkey or security
key.
+ rate_limited: Too many attempts. Please wait a minute and try again.
success: Passkey or security key removed.
diff --git a/config/locales/views/settings/securities/es.yml b/config/locales/views/settings/securities/es.yml
index 9539cecbd7..b3039cd9af 100644
--- a/config/locales/views/settings/securities/es.yml
+++ b/config/locales/views/settings/securities/es.yml
@@ -18,6 +18,8 @@ es:
webauthn_empty: Aún no hay passkeys ni llaves de seguridad registradas.
webauthn_last_used: Último uso hace %{time_ago}
webauthn_name_label: Nombre de la llave
+ webauthn_code_label: "Código del autenticador o de respaldo"
+ webauthn_code_placeholder: "Código actual del autenticador o un código de respaldo sin usar"
webauthn_name_placeholder: Touch ID del MacBook, YubiKey, etc.
webauthn_remove: Eliminar
webauthn_remove_confirm: ¿Seguro que quieres eliminar esta passkey o llave de seguridad?
@@ -25,6 +27,9 @@ es:
webauthn_title: Passkeys y llaves de seguridad
webauthn_unsupported: Este navegador no admite passkeys ni llaves de seguridad.
webauthn_credentials:
+ code_already_used: "Ese código ya se ha usado. Espera al siguiente código de tu app de autenticación."
+ invalid_code: "Ese código no es válido. Introduce un código actual de tu app de autenticación o un código de respaldo sin usar."
+ rate_limited: "Demasiados intentos. Espera un minuto e inténtalo de nuevo."
default_name: Llave de seguridad
failure: No se pudo guardar esa passkey o llave de seguridad. Inténtalo de nuevo.
mfa_required: Activa la autenticación de dos factores antes de añadir una passkey o llave de seguridad.
diff --git a/config/locales/views/settings/securities/fr.yml b/config/locales/views/settings/securities/fr.yml
index 8891d48403..3115ed6000 100644
--- a/config/locales/views/settings/securities/fr.yml
+++ b/config/locales/views/settings/securities/fr.yml
@@ -25,6 +25,8 @@ fr:
webauthn_empty: Aucun mot de passe ou clé de sécurité n'est encore enregistré.
webauthn_last_used: Dernière utilisation il y a %{time_ago}
webauthn_name_label: Nom de la clé
+ webauthn_code_label: "Code d'authentification ou de sauvegarde"
+ webauthn_code_placeholder: "Code actuel de l'authentificateur ou code de sauvegarde inutilisé"
webauthn_name_placeholder: MacBook Touch ID, YubiKey, etc.
webauthn_remove: Supprimer
webauthn_remove_confirm: Êtes-vous sûr de vouloir supprimer ce mot de passe
@@ -36,6 +38,9 @@ fr:
webauthn_unsupported: Ce navigateur ne prend pas en charge les mots de passe
ou les clés de sécurité.
webauthn_credentials:
+ code_already_used: "Ce code a déjà été utilisé. Attendez le prochain code de votre application d'authentification."
+ invalid_code: "Ce code n'est pas valide. Saisissez un code actuel de votre application d'authentification ou un code de sauvegarde inutilisé."
+ rate_limited: "Trop de tentatives. Veuillez patienter une minute puis réessayer."
default_name: Clé de sécurité
failure: Impossible d'enregistrer ce mot de passe ou cette clé de sécurité. Veuillez
réessayer.
diff --git a/config/locales/views/settings/securities/hu.yml b/config/locales/views/settings/securities/hu.yml
index f3dddd8011..e7eaa5ca3c 100644
--- a/config/locales/views/settings/securities/hu.yml
+++ b/config/locales/views/settings/securities/hu.yml
@@ -21,6 +21,8 @@ hu:
webauthn_empty: Még nincsenek regisztrált hozzáférési kulcsok vagy biztonsági kulcsok.
webauthn_last_used: Utoljára használva %{time_ago} ezelőtt
webauthn_name_label: Kulcsnév
+ webauthn_code_label: "Hitelesítő- vagy tartalékkód"
+ webauthn_code_placeholder: "Aktuális hitelesítőkód vagy egy fel nem használt tartalékkód"
webauthn_name_placeholder: MacBook Touch ID, YubiKey stb.
webauthn_remove: Eltávolítás
webauthn_remove_confirm: Biztosan el szeretnéd távolítani ezt a hozzáférési kulcsot vagy
@@ -31,6 +33,9 @@ hu:
webauthn_unsupported: Ez a böngésző nem támogatja a hozzáférési kulcsokat és biztonsági
kulcsokat.
webauthn_credentials:
+ code_already_used: "Ezt a kódot már felhasználták. Várd meg a következő kódot a hitelesítő alkalmazásban."
+ invalid_code: "Ez a kód érvénytelen. Adj meg egy aktuális kódot a hitelesítő alkalmazásból vagy egy fel nem használt tartalékkódot."
+ rate_limited: "Túl sok próbálkozás. Várj egy percet, majd próbáld újra."
default_name: Biztonsági kulcs
failure: Nem sikerült menteni a hozzáférési kulcsot vagy biztonsági kulcsot. Kérjük, próbáld újra.
mfa_required: Engedélyezd a kétlépéses hitelesítést, mielőtt hozzáférési kulcsot vagy biztonsági kulcsot adsz hozzá.
diff --git a/config/locales/views/settings/securities/it.yml b/config/locales/views/settings/securities/it.yml
index 74a4bcf616..4c3887d40d 100644
--- a/config/locales/views/settings/securities/it.yml
+++ b/config/locales/views/settings/securities/it.yml
@@ -18,6 +18,8 @@ it:
webauthn_empty: Nessuna passkey o chiave di sicurezza registrata ancora.
webauthn_last_used: Usata l'ultima volta %{time_ago} fa
webauthn_name_label: Nome chiave
+ webauthn_code_label: "Codice dell'autenticatore o di backup"
+ webauthn_code_placeholder: "Codice attuale dell'autenticatore o un codice di backup non usato"
webauthn_name_placeholder: MacBook Touch ID, YubiKey, ecc.
webauthn_remove: Rimuovi
webauthn_remove_confirm: Sei sicuro di voler rimuovere questa passkey o chiave di sicurezza?
@@ -25,6 +27,9 @@ it:
webauthn_title: Passkey e chiavi di sicurezza
webauthn_unsupported: Questo browser non supporta passkey o chiavi di sicurezza.
webauthn_credentials:
+ code_already_used: "Questo codice è già stato usato. Attendi il prossimo codice dalla tua app di autenticazione."
+ invalid_code: "Questo codice non è valido. Inserisci un codice attuale dalla tua app di autenticazione o un codice di backup non usato."
+ rate_limited: "Troppi tentativi. Attendi un minuto e riprova."
default_name: Chiave di sicurezza
failure: Impossibile salvare la passkey o la chiave di sicurezza. Riprova.
mfa_required: Abilita l'autenticazione a due fattori prima di aggiungere una passkey o una chiave di sicurezza.
diff --git a/config/locales/views/settings/securities/pl.yml b/config/locales/views/settings/securities/pl.yml
index 2fe3569943..c0bed1e2d4 100644
--- a/config/locales/views/settings/securities/pl.yml
+++ b/config/locales/views/settings/securities/pl.yml
@@ -25,6 +25,8 @@ pl:
bezpieczeństwa.
webauthn_last_used: Ostatnio użyto %{time_ago} temu
webauthn_name_label: Nazwa klucza
+ webauthn_code_label: "Kod z aplikacji uwierzytelniającej lub zapasowy"
+ webauthn_code_placeholder: "Aktualny kod z aplikacji uwierzytelniającej lub nieużyty kod zapasowy"
webauthn_name_placeholder: MacBook Touch ID, YubiKey itp.
webauthn_remove: Usuń
webauthn_remove_confirm: Czy na pewno chcesz usunąć ten klucz dostępu lub
@@ -36,6 +38,9 @@ pl:
webauthn_unsupported: Ta przeglądarka nie obsługuje kluczy dostępu ani kluczy
bezpieczeństwa.
webauthn_credentials:
+ code_already_used: "Ten kod został już użyty. Poczekaj na kolejny kod z aplikacji uwierzytelniającej."
+ invalid_code: "Ten kod jest nieprawidłowy. Wpisz aktualny kod z aplikacji uwierzytelniającej lub nieużyty kod zapasowy."
+ rate_limited: "Zbyt wiele prób. Poczekaj minutę i spróbuj ponownie."
default_name: Klucz bezpieczeństwa
failure: Nie udało się zapisać klucza dostępu ani klucza bezpieczeństwa. Spróbuj
ponownie.
diff --git a/config/locales/views/settings/securities/pt-PT.yml b/config/locales/views/settings/securities/pt-PT.yml
index bc4084e76d..2baae20e85 100644
--- a/config/locales/views/settings/securities/pt-PT.yml
+++ b/config/locales/views/settings/securities/pt-PT.yml
@@ -21,6 +21,8 @@ pt-PT:
webauthn_empty: Ainda não existem chaves de acesso ou chaves de segurança registadas.
webauthn_last_used: Utilizada pela última vez há %{time_ago}
webauthn_name_label: Designação da chave
+ webauthn_code_label: "Código do autenticador ou de cópia de segurança"
+ webauthn_code_placeholder: "Código atual do autenticador ou um código de cópia de segurança não utilizado"
webauthn_name_placeholder: MacBook Touch ID, YubiKey, etc.
webauthn_remove: Eliminar
webauthn_remove_confirm: Tem a certeza de que pretende eliminar esta chave de
@@ -32,6 +34,9 @@ pt-PT:
webauthn_unsupported: Este navegador não suporta chaves de acesso ou chaves
de segurança.
webauthn_credentials:
+ code_already_used: "Esse código já foi utilizado. Aguarde o próximo código da sua aplicação de autenticação."
+ invalid_code: "Esse código não é válido. Introduza um código atual da sua aplicação de autenticação ou um código de cópia de segurança não utilizado."
+ rate_limited: "Demasiadas tentativas. Aguarde um minuto e tente novamente."
default_name: Chave de segurança
failure: Não foi possível guardar essa chave de acesso ou chave de segurança. Tente
novamente.
diff --git a/config/locales/views/settings/securities/ru.yml b/config/locales/views/settings/securities/ru.yml
index a6a1a29298..d06c03e8b7 100644
--- a/config/locales/views/settings/securities/ru.yml
+++ b/config/locales/views/settings/securities/ru.yml
@@ -21,6 +21,8 @@ ru:
webauthn_empty: Ключи доступа или ключи безопасности ещё не зарегистрированы.
webauthn_last_used: Последнее использование %{time_ago} назад
webauthn_name_label: Название ключа
+ webauthn_code_label: "Код из приложения-аутентификатора или резервный код"
+ webauthn_code_placeholder: "Текущий код аутентификатора или неиспользованный резервный код"
webauthn_name_placeholder: MacBook Touch ID, YubiKey и т.д.
webauthn_remove: Удалить
webauthn_remove_confirm: Вы уверены, что хотите удалить этот ключ доступа
@@ -32,6 +34,9 @@ ru:
webauthn_unsupported: Этот браузер не поддерживает ключи доступа или ключи
безопасности.
webauthn_credentials:
+ code_already_used: "Этот код уже использован. Дождитесь следующего кода в приложении-аутентификаторе."
+ invalid_code: "Этот код недействителен. Введите текущий код из приложения-аутентификатора или неиспользованный резервный код."
+ rate_limited: "Слишком много попыток. Подождите минуту и попробуйте снова."
default_name: Ключ безопасности
failure: Не удалось сохранить этот ключ доступа или ключ безопасности. Пожалуйста,
попробуйте снова.
diff --git a/config/locales/views/settings/securities/tr.yml b/config/locales/views/settings/securities/tr.yml
index e33c90fd73..18476673f5 100644
--- a/config/locales/views/settings/securities/tr.yml
+++ b/config/locales/views/settings/securities/tr.yml
@@ -24,6 +24,8 @@ tr:
webauthn_empty: Henüz kayıtlı geçiş anahtarı veya güvenlik anahtarı yok.
webauthn_last_used: Son kullanım %{time_ago} önce
webauthn_name_label: Anahtar adı
+ webauthn_code_label: "Doğrulayıcı veya yedek kod"
+ webauthn_code_placeholder: "Güncel doğrulayıcı kodu veya kullanılmamış bir yedek kod"
webauthn_name_placeholder: MacBook Touch ID, YubiKey vb.
webauthn_remove: Kaldır
webauthn_remove_confirm: Bu geçiş anahtarını veya güvenlik anahtarını kaldırmak
@@ -34,6 +36,9 @@ tr:
webauthn_unsupported: Bu tarayıcı geçiş anahtarlarını veya güvenlik anahtarlarını
desteklemiyor.
webauthn_credentials:
+ code_already_used: "Bu kod zaten kullanıldı. Doğrulayıcı uygulamanızdaki bir sonraki kodu bekleyin."
+ invalid_code: "Bu kod geçersiz. Doğrulayıcı uygulamanızdan güncel bir kod veya kullanılmamış bir yedek kod girin."
+ rate_limited: "Çok fazla deneme. Bir dakika bekleyip tekrar deneyin."
default_name: Güvenlik anahtarı
failure: Bu geçiş anahtarı veya güvenlik anahtarı kaydedilemedi. Lütfen tekrar
deneyin.
diff --git a/config/locales/views/settings/securities/uk.yml b/config/locales/views/settings/securities/uk.yml
index 4de27fe028..5f5dbc7574 100644
--- a/config/locales/views/settings/securities/uk.yml
+++ b/config/locales/views/settings/securities/uk.yml
@@ -20,6 +20,8 @@ uk:
webauthn_empty: Ще не зареєстровано жодного ключа доступу або ключа безпеки.
webauthn_last_used: Останнє використання %{time_ago} тому
webauthn_name_label: Назва ключа
+ webauthn_code_label: "Код з автентифікатора або резервний код"
+ webauthn_code_placeholder: "Поточний код автентифікатора або невикористаний резервний код"
webauthn_name_placeholder: MacBook Touch ID, YubiKey тощо.
webauthn_remove: Видалити
webauthn_remove_confirm: Ви впевнені, що хочете видалити цей ключ доступу або
@@ -30,6 +32,9 @@ uk:
webauthn_unsupported: Цей браузер не підтримує ключі доступу або ключі
безпеки.
webauthn_credentials:
+ code_already_used: "Цей код уже використано. Дочекайтеся наступного коду в застосунку-автентифікаторі."
+ invalid_code: "Цей код недійсний. Введіть поточний код із застосунку-автентифікатора або невикористаний резервний код."
+ rate_limited: "Забагато спроб. Зачекайте хвилину й спробуйте ще раз."
default_name: Ключ безпеки
failure: Не вдалося зберегти цей ключ доступу або ключ безпеки. Будь ласка, спробуйте ще раз.
mfa_required: Увімкніть двофакторну автентифікацію перед додаванням ключа доступу або ключа
diff --git a/config/locales/views/settings/securities/vi.yml b/config/locales/views/settings/securities/vi.yml
index 34b2dde360..2c3dd63f2a 100644
--- a/config/locales/views/settings/securities/vi.yml
+++ b/config/locales/views/settings/securities/vi.yml
@@ -18,6 +18,8 @@ vi:
webauthn_empty: Chưa có passkey hoặc khóa bảo mật nào được đăng ký.
webauthn_last_used: Sử dụng lần cuối %{time_ago} trước
webauthn_name_label: Tên khóa
+ webauthn_code_label: "Mã xác thực hoặc mã dự phòng"
+ webauthn_code_placeholder: "Mã hiện tại từ ứng dụng xác thực hoặc mã dự phòng chưa dùng"
webauthn_name_placeholder: MacBook Touch ID, YubiKey, v.v.
webauthn_remove: Xóa
webauthn_remove_confirm: Bạn có chắc chắn muốn xóa passkey hoặc khóa bảo mật này không?
@@ -25,6 +27,9 @@ vi:
webauthn_title: Passkey và khóa bảo mật
webauthn_unsupported: Trình duyệt này không hỗ trợ passkey hoặc khóa bảo mật.
webauthn_credentials:
+ code_already_used: "Mã này đã được sử dụng. Hãy chờ mã tiếp theo từ ứng dụng xác thực của bạn."
+ invalid_code: "Mã này không hợp lệ. Hãy nhập mã hiện tại từ ứng dụng xác thực hoặc một mã dự phòng chưa dùng."
+ rate_limited: "Quá nhiều lần thử. Vui lòng đợi một phút rồi thử lại."
default_name: Khóa bảo mật
failure: Không thể lưu passkey hoặc khóa bảo mật. Vui lòng thử lại.
mfa_required: Bật xác thực hai yếu tố trước khi thêm passkey hoặc khóa bảo mật.
diff --git a/config/locales/views/settings/securities/zh-CN.yml b/config/locales/views/settings/securities/zh-CN.yml
index 98d88ddabd..3bc714a639 100644
--- a/config/locales/views/settings/securities/zh-CN.yml
+++ b/config/locales/views/settings/securities/zh-CN.yml
@@ -18,6 +18,8 @@ zh-CN:
webauthn_empty: 暂未注册通行密钥或安全密钥。
webauthn_last_used: 上次使用于 %{time_ago} 前
webauthn_name_label: 密钥名称
+ webauthn_code_label: "验证器代码或备用代码"
+ webauthn_code_placeholder: "当前验证器代码或未使用的备用代码"
webauthn_name_placeholder: MacBook Touch ID、YubiKey 等
webauthn_remove: 移除
webauthn_remove_confirm: 确定要移除此通行密钥或安全密钥?
@@ -25,6 +27,9 @@ zh-CN:
webauthn_title: 通行密钥和安全密钥
webauthn_unsupported: 此浏览器不支持通行密钥或安全密钥。
webauthn_credentials:
+ code_already_used: "该代码已被使用。请等待验证器应用生成下一个代码。"
+ invalid_code: "该代码无效。请输入验证器应用中的当前代码或未使用的备用代码。"
+ rate_limited: "尝试次数过多。请等待一分钟后重试。"
default_name: 安全密钥
failure: 无法保存该通行密钥或安全密钥。请重试。
mfa_required: 添加通行密钥或安全密钥前,请先启用双重认证。
diff --git a/config/locales/views/settings/securities/zh-TW.yml b/config/locales/views/settings/securities/zh-TW.yml
index 7a19028566..600a65ae81 100644
--- a/config/locales/views/settings/securities/zh-TW.yml
+++ b/config/locales/views/settings/securities/zh-TW.yml
@@ -18,6 +18,8 @@ zh-TW:
webauthn_empty: 尚未註冊任何密碼金鑰或安全金鑰。
webauthn_last_used: 上次使用於 %{time_ago}前
webauthn_name_label: 金鑰名稱
+ webauthn_code_label: "驗證器代碼或備援代碼"
+ webauthn_code_placeholder: "目前的驗證器代碼或未使用的備援代碼"
webauthn_name_placeholder: MacBook Touch ID、YubiKey 等
webauthn_remove: 移除
webauthn_remove_confirm: 確定要移除此密碼金鑰或安全金鑰嗎?
@@ -25,6 +27,9 @@ zh-TW:
webauthn_title: 密碼金鑰與安全金鑰
webauthn_unsupported: 這個瀏覽器不支援密碼金鑰或安全金鑰。
webauthn_credentials:
+ code_already_used: "此代碼已被使用。請等待驗證器應用程式產生下一個代碼。"
+ invalid_code: "此代碼無效。請輸入驗證器應用程式中的目前代碼或未使用的備援代碼。"
+ rate_limited: "嘗試次數過多。請稍候一分鐘再試一次。"
default_name: 安全金鑰
failure: 無法儲存該密碼金鑰或安全金鑰,請再試一次。
mfa_required: 請先啟用雙重驗證,才能新增密碼金鑰或安全金鑰。
diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rb
index 691bcfb956..7b9e9f9f34 100644
--- a/test/controllers/mfa_controller_test.rb
+++ b/test/controllers/mfa_controller_test.rb
@@ -353,11 +353,14 @@ class MfaControllerTest < ActionDispatch::IntegrationTest
def register_webauthn_credential(origin: "http://www.example.com", rp_id: "www.example.com")
client = WebAuthn::FakeClient.new(origin)
- post options_settings_webauthn_credentials_path, as: :json
+ # A backup code confirms the registration so the current TOTP step stays
+ # free for the sign-in steps these tests go on to exercise.
+ code = @user.enable_mfa!.first
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
options = JSON.parse(response.body)
credential = client.create(challenge: options.fetch("challenge"), rp_id: rp_id)
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "MacBook Touch ID" },
+ webauthn_credential: { nickname: "MacBook Touch ID", code: code },
credential: credential
}, as: :json
assert_response :success
diff --git a/test/controllers/passkey_sessions_controller_test.rb b/test/controllers/passkey_sessions_controller_test.rb
index 7d17e84fea..fbd1d82b5f 100644
--- a/test/controllers/passkey_sessions_controller_test.rb
+++ b/test/controllers/passkey_sessions_controller_test.rb
@@ -213,11 +213,14 @@ class PasskeySessionsControllerTest < ActionDispatch::IntegrationTest
def register_webauthn_credential(origin: "http://www.example.com", rp_id: "www.example.com")
client = WebAuthn::FakeClient.new(origin)
- post options_settings_webauthn_credentials_path, as: :json
+ # A backup code confirms the registration so the current TOTP step stays
+ # free for the sign-in steps these tests go on to exercise.
+ code = @user.enable_mfa!.first
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
options = JSON.parse(response.body)
credential = client.create(challenge: options.fetch("challenge"), rp_id: rp_id)
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "MacBook Touch ID" },
+ webauthn_credential: { nickname: "MacBook Touch ID", code: code },
credential: credential
}, as: :json
assert_response :success
diff --git a/test/controllers/settings/webauthn_credentials_controller_test.rb b/test/controllers/settings/webauthn_credentials_controller_test.rb
index 444aceb052..c0cc848838 100644
--- a/test/controllers/settings/webauthn_credentials_controller_test.rb
+++ b/test/controllers/settings/webauthn_credentials_controller_test.rb
@@ -33,7 +33,7 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
assert_difference -> { @user.webauthn_credentials.count }, 1 do
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "MacBook Touch ID" },
+ webauthn_credential: { nickname: "MacBook Touch ID", code: @code },
credential: credential
}, as: :json
end
@@ -48,6 +48,164 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
assert @user.reload.webauthn_id.present?
end
+ test "registering a credential requires an MFA code" do
+ [ nil, "", "000000" ].each do |code|
+ options = registration_options
+ credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")
+
+ assert_no_difference -> { @user.webauthn_credentials.count } do
+ register(credential, code: code)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.invalid_code"), JSON.parse(response.body).fetch("error")
+ end
+ end
+
+ test "registering a credential accepts a current authenticator code" do
+ travel_to Time.zone.parse("2026-10-07 12:00:10") do
+ options = registration_options
+ credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")
+
+ assert_difference -> { @user.webauthn_credentials.count }, 1 do
+ register(credential, code: totp_code)
+ end
+
+ assert_response :success
+ end
+ end
+
+ test "an authenticator code that was already used is reported as such" do
+ travel_to Time.zone.parse("2026-10-07 12:00:10") do
+ code = totp_code
+ assert @user.verify_otp?(code)
+
+ options = registration_options
+ credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")
+
+ assert_no_difference -> { @user.webauthn_credentials.count } do
+ register(credential, code: code)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.code_already_used"), JSON.parse(response.body).fetch("error")
+ end
+ end
+
+ test "a backup code confirms only one registration" do
+ code = backup_code
+
+ options = registration_options(code: code)
+ register(@client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com"), code: code)
+ assert_response :success
+
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.invalid_code"), JSON.parse(response.body).fetch("error")
+ end
+
+ test "options refuse a missing or wrong code before the browser creates a passkey" do
+ [ nil, "", "000000" ].each do |code|
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
+
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.invalid_code"), JSON.parse(response.body).fetch("error")
+ assert_nil session[:webauthn_registration_challenge]
+ end
+ end
+
+ test "options report an authenticator code that was already used" do
+ travel_to Time.zone.parse("2026-10-07 12:00:10") do
+ code = totp_code
+ assert @user.verify_otp?(code)
+
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
+
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.code_already_used"), JSON.parse(response.body).fetch("error")
+ end
+ end
+
+ test "options check the code without spending it" do
+ code = backup_code
+
+ registration_options(code: code)
+
+ assert @user.reload.verify_otp?(code), "backup code should still be unused after options"
+ end
+
+ test "a registration that fails does not spend the backup code" do
+ code = backup_code
+
+ stale_options = registration_options(code: code)
+ registration_options(code: code)
+ stale_credential = @client.create(challenge: stale_options.fetch("challenge"), rp_id: "www.example.com")
+ register(stale_credential, code: code)
+ assert_response :unprocessable_entity
+ assert_equal I18n.t("webauthn_credentials.failure"), JSON.parse(response.body).fetch("error")
+
+ options = registration_options(code: code)
+ assert_difference -> { @user.webauthn_credentials.count }, 1 do
+ register(@client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com"), code: code)
+ end
+ assert_response :success
+ end
+
+ test "a duplicate credential does not spend the backup code" do
+ code = backup_code
+ registration_options(code: code)
+ @user.webauthn_credentials.create!(nickname: "Existing", credential_id: "duplicate-credential-id", public_key: "public-key")
+
+ verified_credential = Struct.new(:id, :public_key, :sign_count).new("duplicate-credential-id", "new-public-key", 0)
+ relying_party = mock("webauthn_relying_party")
+ relying_party.expects(:verify_registration).returns(verified_credential)
+ Settings::WebauthnCredentialsController.any_instance.stubs(:webauthn_relying_party).returns(relying_party)
+
+ register({ id: "duplicate-credential-id", response: {} }, code: code)
+ assert_response :unprocessable_entity
+
+ assert @user.reload.verify_otp?(code), "backup code should still be unused"
+ end
+
+ test "code attempts are rate limited per user" do
+ registration_options
+ Settings::WebauthnCredentialsController.cache_store.stubs(:increment).returns(11)
+
+ register({ id: "x", response: {} }, code: "000000")
+
+ assert_response :too_many_requests
+ assert_equal I18n.t("webauthn_credentials.rate_limited"), JSON.parse(response.body).fetch("error")
+ end
+
+ test "guessing codes through options alone is limited to 10 a minute" do
+ # The test cache is a null store, so hand out the counts a real store
+ # would return for the options counter, which create does not share.
+ Settings::WebauthnCredentialsController.cache_store.stubs(:increment)
+ .with { |key, *| key.include?("code-check") && key.exclude?("code-spend") }
+ .returns(*1..11)
+
+ 10.times do
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: "000000" } }, as: :json
+ assert_response :unprocessable_entity
+ end
+
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: "000000" } }, as: :json
+
+ assert_response :too_many_requests
+ assert_equal I18n.t("webauthn_credentials.rate_limited"), JSON.parse(response.body).fetch("error")
+ end
+
+ test "every locale that translates the passkey form also translates the code confirmation" do
+ I18n.available_locales.each do |locale|
+ next unless I18n.exists?("webauthn_credentials.failure", locale, fallback: false)
+
+ %w[webauthn_credentials.code_already_used webauthn_credentials.invalid_code webauthn_credentials.rate_limited
+ settings.securities.show.webauthn_code_label settings.securities.show.webauthn_code_placeholder].each do |key|
+ assert I18n.exists?(key, locale, fallback: false), "#{locale} is missing #{key}"
+ end
+ end
+ end
+
test "uses configured relying party id and allowed origin" do
with_webauthn_config(rp_id: "example.test", allowed_origins: [ "https://app.example.test" ]) do
client = WebAuthn::FakeClient.new("https://app.example.test")
@@ -59,7 +217,7 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
assert_difference -> { @user.webauthn_credentials.count }, 1 do
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "Configured origin key" },
+ webauthn_credential: { nickname: "Configured origin key", code: @code },
credential: credential
}, as: :json
end
@@ -73,14 +231,14 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "MacBook Touch ID" },
+ webauthn_credential: { nickname: "MacBook Touch ID", code: @code },
credential: credential
}, as: :json
assert_response :success
assert_no_difference -> { @user.webauthn_credentials.count } do
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "Replay" },
+ webauthn_credential: { nickname: "Replay", code: backup_code },
credential: credential
}, as: :json
end
@@ -93,7 +251,7 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
assert_no_difference -> { @user.webauthn_credentials.count } do
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "Malformed" },
+ webauthn_credential: { nickname: "Malformed", code: @code },
credential: []
}, as: :json
end
@@ -117,7 +275,7 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
assert_no_difference -> { @user.webauthn_credentials.count } do
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "Duplicate security key" },
+ webauthn_credential: { nickname: "Duplicate security key", code: @code },
credential: { id: "duplicate-credential-id", response: {} }
}, as: :json
end
@@ -131,7 +289,7 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")
post settings_webauthn_credentials_path, params: {
- webauthn_credential: { nickname: "" },
+ webauthn_credential: { nickname: "", code: @code },
credential: credential
}, as: :json
@@ -154,12 +312,30 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationT
end
private
- def registration_options
- post options_settings_webauthn_credentials_path, as: :json
+ # Options now check the code too; keep one valid code per test so the
+ # create call that follows can spend the same one.
+ def registration_options(code: nil)
+ @code = code || @code || backup_code
+ post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: @code } }, as: :json
assert_response :success
JSON.parse(response.body)
end
+ def backup_code
+ @user.enable_mfa!.first
+ end
+
+ def totp_code
+ ROTP::TOTP.new(@user.reload.otp_secret, issuer: "Sure Finances").now
+ end
+
+ def register(credential, code:)
+ post settings_webauthn_credentials_path, params: {
+ webauthn_credential: { nickname: "Attempt", code: code },
+ credential: credential
+ }, as: :json
+ end
+
def with_webauthn_config(rp_id:, allowed_origins:)
config = Rails.application.config.x.webauthn
previous_rp_id = config.rp_id
diff --git a/test/models/user_backup_code_concurrency_test.rb b/test/models/user_backup_code_concurrency_test.rb
new file mode 100644
index 0000000000..db754ea40e
--- /dev/null
+++ b/test/models/user_backup_code_concurrency_test.rb
@@ -0,0 +1,42 @@
+require "test_helper"
+require "concurrent"
+
+# A backup code is single use. Two requests redeeming the same code at once,
+# each on its own connection and its own stale User instance, must not both
+# succeed: consume_backup_code! takes a row lock and re-reads the codes, so the
+# second one sees the code already gone.
+#
+# Real threads on real connections, so this needs real commits.
+class UserBackupCodeConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ setup do
+ @user = users(:family_member)
+ @original = @user.attributes.slice("otp_secret", "otp_required", "otp_backup_codes")
+ @user.setup_mfa!
+ @codes = @user.enable_mfa!
+ end
+
+ teardown do
+ User.where(id: @user.id).update_all(@original)
+ end
+
+ test "two connections redeeming the same backup code consume it exactly once" do
+ code = @codes.first
+ latch = Concurrent::CountDownLatch.new(2)
+
+ results = 2.times.map do
+ instance = User.find(@user.id)
+ Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ latch.count_down
+ assert latch.wait(5), "both workers must reach the redemption checkpoint"
+ instance.send(:consume_backup_code!, code)
+ end
+ end
+ end.map(&:value)
+
+ assert_equal 1, results.count(true), "exactly one racing connection may redeem the code"
+ assert_equal @codes.size - 1, @user.reload.otp_backup_codes.size
+ end
+end
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index d40d2229f3..20a4d84e5e 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -238,6 +238,28 @@ class UserTest < ActiveSupport::TestCase
assert_not User.find(user.id).verify_otp?(code), "a freshly loaded user must reject it too"
end
+ test "otp_code_status answers like verify_otp without spending the code" do
+ user = users(:family_member)
+ user.setup_mfa!
+ backup_code = user.enable_mfa!.first
+
+ travel_to Time.zone.parse("2026-10-07 12:00:10") do
+ code = ROTP::TOTP.new(user.otp_secret, issuer: "Sure Finances").now
+
+ assert_equal :accepted, user.otp_code_status(code)
+ assert_equal :accepted, user.otp_code_status(code), "checking must not claim the time step"
+ assert_equal :accepted, user.otp_code_status(backup_code)
+ assert_equal :accepted, user.otp_code_status(backup_code), "checking must not consume the backup code"
+ assert_equal :invalid, user.otp_code_status("000000")
+ assert_equal :invalid, user.otp_code_status(nil)
+
+ assert_equal :accepted, user.verify_otp(code)
+ assert_equal :replayed, user.otp_code_status(code)
+ assert_equal :accepted, user.verify_otp(backup_code)
+ assert_equal :invalid, user.otp_code_status(backup_code)
+ end
+ end
+
test "verify_otp? accepts the next time step's code after one was used" do
user = users(:family_member)
user.setup_mfa!