The personal finance app for everyone (by everyone)
Ruby
security: add an audit log for sensitive account operations (#3264)
GFR6cb0850a9167
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex 8eba569b17..241346815f 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -103,7 +103,7 @@ module Admin)redirect_to admin_users_path, notice: t(".success_family")- elsif @user.update(user_update_attributes)+ elsif update_user_and_log_password_changechanges = []changes << :role if @user.saved_change_to_role?changes << :password if @user.saved_change_to_password_digest?@@ -126,7 +126,17 @@ module Adminredirect_to admin_users_path, alert: @user.errors.full_messages.to_sentence.presence || t(".failure")endrescue ActiveRecord::RecordInvalid => e- redirect_to admin_users_path, alert: e.record.errors.full_messages.to_sentence+ # e.record is the User for a validation failure on the user update, but+ # the SecurityAuditLog write inside the same transaction can also raise+ # RecordInvalid — in that case e.record.errors is empty (it's a valid+ # user, an invalid audit row) and would otherwise show a blank alert.+ if e.record.is_a?(User)+ redirect_to admin_users_path, alert: e.record.errors.full_messages.to_sentence+ else+ redirect_to admin_users_path, alert: t(".failure")+ end+ rescue ActiveRecord::ActiveRecordError+ redirect_to admin_users_path, alert: t(".failure")rescue ActiveRecord::RecordNotFoundredirect_to admin_users_path, alert: t(".failure")end@@ -185,6 +195,21 @@ module Admin@user = User.find(params[:id])end+ # Wrapped in a transaction so a failure writing the audit entry rolls+ # back the password/role change too, instead of leaving a sensitive+ # change committed with no trail of it.+ def update_user_and_log_password_change+ ActiveRecord::Base.transaction do+ next false unless @user.update(user_update_attributes)++ if @user.saved_change_to_password_digest?+ SecurityAuditLog.log_password_changed!(user: @user, request: request, actor: Current.true_user)+ end++ true+ end+ end+def user_paramsparams.require(:user).permit(:role, :family_id, :new_family_name, :new_family_moniker, :password)enddiff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rbindex de90ee499f..672a134842 100644--- a/app/controllers/mfa_controller.rb+++ b/app/controllers/mfa_controller.rb@@ -13,7 +13,8 @@ class MfaController < ApplicationControllerdef create# A duplicate submit of the enrollment form lands here again after the# first one already enabled MFA; it (or any stray POST) must not fall- # through to disable_mfa! and tear a finished setup down.+ # through to disable_mfa! and tear a finished setup down with no audit+ # trail.return redirect_to root_path if Current.user.otp_required?unless password_confirmed?@@ -26,7 +27,10 @@ class MfaController < ApplicationControllercase Current.user.verify_otp(params[:code])when :accepted- @backup_codes = Current.user.enable_mfa!+ ActiveRecord::Base.transaction do+ @backup_codes = Current.user.enable_mfa!+ SecurityAuditLog.log_mfa_enabled!(user: Current.user, request: request, actor: Current.true_user)+ endrender :backup_codeswhen :replayed# Correct code, but its time step was already claimed by a concurrent@@ -37,6 +41,8 @@ class MfaController < ApplicationControllerCurrent.user.disable_mfa!redirect_to new_mfa_path, alert: t(".invalid_code")end+ rescue ActiveRecord::RecordInvalid, ActiveRecord::ActiveRecordError+ redirect_to new_mfa_path, alert: t(".setup_failed")enddef verify@@ -139,7 +145,20 @@ class MfaController < ApplicationControllerendCurrent.user.disable_mfa!++ # Log-and-continue, not transactional: a security control the user is+ # actively trying to turn off (e.g. because they believe it's+ # compromised) shouldn't stay on just because the audit write failed.+ # Mirrors Settings::ApiKeysController#destroy.+ begin+ SecurityAuditLog.log_mfa_disabled!(user: Current.user, request: request, actor: Current.true_user)+ rescue ActiveRecord::ActiveRecordError => e+ Rails.logger.error("[Mfa] Failed to write audit log for disabled MFA (user #{Current.user.id}): #{e.message}")+ end+redirect_to settings_security_path, notice: t(".success")+ rescue ActiveRecord::RecordInvalid+ redirect_to settings_security_path, alert: t(".failure")endprivatediff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rbindex 482654a3a7..13f8d52e28 100644--- a/app/controllers/password_resets_controller.rb+++ b/app/controllers/password_resets_controller.rb@@ -37,15 +37,33 @@ class PasswordResetsController < ApplicationControllerreturnend- if @user.update(password_params)+ if update_password_and_log_changeredirect_to new_session_path, notice: t(".success")elserender :edit, status: :unprocessable_entityend+ rescue ActiveRecord::ActiveRecordError+ render :edit, status: :unprocessable_entityendprivate+ def update_password_and_log_change+ # has_secure_password ignores a blank password, so update would succeed without a change.+ if password_params[:password].blank?+ @user.errors.add(:password, :blank)+ return false+ end++ ActiveRecord::Base.transaction do+ next false unless @user.update(password_params)++ SecurityAuditLog.log_password_changed!(user: @user, request: request)++ true+ end+ end+def ensure_password_resets_enabledreturn if AuthConfig.password_features_enabled?diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rbindex 8c12136b30..e53eb7a1a7 100644--- a/app/controllers/passwords_controller.rb+++ b/app/controllers/passwords_controller.rb@@ -5,15 +5,33 @@ class PasswordsController < ApplicationControllerenddef update- if Current.user.update(password_params)+ if update_password_and_log_changeredirect_to root_path, notice: t(".success")elserender :edit, status: :unprocessable_entityend+ rescue ActiveRecord::ActiveRecordError+ render :edit, status: :unprocessable_entityendprivate+ def update_password_and_log_change+ # has_secure_password ignores a blank password, so update would succeed without a change.+ if password_params[:password].blank?+ Current.user.errors.add(:password, :blank)+ return false+ end++ ActiveRecord::Base.transaction do+ next false unless Current.user.update(password_params)++ SecurityAuditLog.log_password_changed!(user: Current.user, request: request, actor: Current.true_user)++ true+ end+ end+# Mirrors the local login policy: when only SSO is allowed, a local# password could not be used to sign in, so it must not be set here# either. Super admins keep this page under the local admin override,diff --git a/app/controllers/settings/api_keys_controller.rb b/app/controllers/settings/api_keys_controller.rbindex ac5d53aa4c..a44b6f3399 100644--- a/app/controllers/settings/api_keys_controller.rb+++ b/app/controllers/settings/api_keys_controller.rb@@ -31,20 +31,51 @@ class Settings::ApiKeysController < ApplicationController@api_key = Current.user.api_keys.build(api_key_params)@api_key.key = @plain_key- if @api_key.save+ # audit_log_failed distinguishes "the key itself is invalid" (@api_key+ # carries real validation errors, :new renders them) from "the audit+ # write failed" (the transaction rolls back @api_key to a fresh record+ # with no errors of its own — rendering :new for that case alone would be+ # a 422 with nothing on it explaining what happened).+ audit_log_failed = false++ ActiveRecord::Base.transaction do+ @api_key.save!++ begin+ SecurityAuditLog.log_api_key_created!(user: Current.user, api_key: @api_key, request: request, actor: Current.true_user)+ rescue ActiveRecord::ActiveRecordError => e+ Rails.logger.error("[Settings::ApiKeys] Failed to write audit log for created key: #{e.message}")+ audit_log_failed = true+ raise ActiveRecord::Rollback+ end+ end++ if audit_log_failed+ flash.now[:alert] = t(".creation_failed")+ render :new, status: :unprocessable_entity+ elseflash[:notice] = t(".success")redirect_to settings_api_key_path(@api_key, newly_created: true)- else- render :new, status: :unprocessable_entityend+ rescue ActiveRecord::RecordInvalid+ render :new, status: :unprocessable_entityenddef destroy- @api_key.revoke!+ begin+ @api_key.revoke!+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotDestroyed+ flash[:alert] = t(".revoke_failed")+ return redirect_to settings_api_keys_path+ end++ begin+ SecurityAuditLog.log_api_key_revoked!(user: Current.user, api_key: @api_key, request: request, actor: Current.true_user)+ rescue ActiveRecord::ActiveRecordError => e+ Rails.logger.error("[Settings::ApiKeys] Failed to write audit log for revoked key #{@api_key.id}: #{e.message}")+ end+flash[:notice] = t(".revoked_successfully")- rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotDestroyed- flash[:alert] = t(".revoke_failed")- ensureredirect_to settings_api_keys_pathenddiff --git a/app/controllers/settings/webauthn_credentials_controller.rb b/app/controllers/settings/webauthn_credentials_controller.rbindex dd2a046475..8cc297e38f 100644--- a/app/controllers/settings/webauthn_credentials_controller.rb+++ b/app/controllers/settings/webauthn_credentials_controller.rb@@ -65,13 +65,15 @@ class Settings::WebauthnCredentialsController < ApplicationControllercode_result = Current.user.verify_otp(webauthn_credential_params[:code])raise ActiveRecord::Rollback unless code_result == :accepted- Current.user.webauthn_credentials.create!(+ stored_credential = 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)++ SecurityAuditLog.log_webauthn_credential_added!(user: Current.user, credential: stored_credential, request: request, actor: Current.true_user)endif code_result == :accepted@@ -79,13 +81,26 @@ class Settings::WebauthnCredentialsController < ApplicationControllerelserender_code_error(code_result)end- rescue WebAuthn::Error, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique, ActionController::BadRequest, ActionController::ParameterMissing+ rescue WebAuthn::Error, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique, ActiveRecord::ActiveRecordError, ActionController::BadRequest, ActionController::ParameterMissingrender json: { error: t("webauthn_credentials.failure") }, status: :unprocessable_entityenddef destroy- Current.user.webauthn_credentials.find(params[:id]).destroy!+ credential = Current.user.webauthn_credentials.find(params[:id])+ credential.destroy!++ # Log-and-continue, not transactional: a failed audit write shouldn't+ # block removing a security key the user believes is compromised.+ # Mirrors Settings::ApiKeysController#destroy.+ begin+ SecurityAuditLog.log_webauthn_credential_removed!(user: Current.user, credential: credential, request: request, actor: Current.true_user)+ rescue ActiveRecord::ActiveRecordError => e+ Rails.logger.error("[Settings::WebauthnCredentials] Failed to write audit log for removed credential #{credential.id}: #{e.message}")+ end+redirect_to settings_security_path, notice: t("webauthn_credentials.success")+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotDestroyed+ redirect_to settings_security_path, alert: t("webauthn_credentials.failure")endprivatediff --git a/app/models/security_audit_log.rb b/app/models/security_audit_log.rbnew file mode 100644index 0000000000..daef8f8494--- /dev/null+++ b/app/models/security_audit_log.rb@@ -0,0 +1,153 @@+# frozen_string_literal: true++# Audit trail for security-sensitive account operations. Separate from+# SsoAuditLog (app/models/sso_audit_log.rb), which is specifically about SSO+# login/link/unlink events and has a `provider` column these events have no+# use for.+#+# Scope: API key create/revoke, MFA enable/disable, password changes and+# WebAuthn credential add/remove. Deliberately not (yet) covering email+# change, session revocation, backup-code consumption/regeneration or role+# elevation (the latter is Rails.logger-only in Admin::UsersController) —+# left out to keep this PR reviewable, not because they're lower value.+#+# Currently console-only: nothing in app/views or the API reads this table+# (same as SsoAuditLog). There's no retention/pruning job — rows are kept+# indefinitely, including after the user they're about is deleted, which is+# deliberate (see the FK comment in the migration) but still an open+# decision for a future PR rather than a default to leave unexamined.+class SecurityAuditLog < ApplicationRecord+ include Encryptable++ belongs_to :user, optional: true++ # Non-deterministic: none of these columns are ever queried by value, only+ # ever displayed to an investigator, so there's no reason to give up the+ # stronger (non-deterministic) ciphertext for lookup capability we don't+ # need. Keeping them out of `metadata` (plain jsonb) matters because these+ # rows deliberately survive the user's deletion (see the FK comment in the+ # migration) — plaintext copies would otherwise outlive and bypass the+ # encryption boundary `User#email` and `Session#user_agent` are under, and+ # the IP/user agent would otherwise be a GDPR-erasure gap for an account+ # that's supposed to be gone. Guarded like every other encrypted column in+ # the app (`User#email`, `Session#user_agent`): if encryption isn't+ # explicitly configured, these stay plaintext rather than silently+ # encrypting under a `SECRET_KEY_BASE`-derived key that later breaks when+ # the operator sets explicit keys (see `encryption_warning.rb`).+ if encryption_ready?+ encrypts :user_email+ encrypts :ip_address+ encrypts :user_agent+ end++ EVENT_TYPES = %w[+ api_key_created+ api_key_revoked+ mfa_enabled+ mfa_disabled+ password_changed+ webauthn_credential_added+ webauthn_credential_removed+ ].freeze++ validates :event_type, presence: true, inclusion: { in: EVENT_TYPES }++ scope :recent, -> { order(created_at: :desc) }+ scope :for_user, ->(user) { where(user: user) }+ scope :by_event, ->(event) { where(event_type: event) }++ class << self+ # actor is the user who performed the change when it wasn't the account+ # owner themselves — an admin resetting another user's password from+ # Admin::UsersController, or a super admin impersonating the account+ # owner. Callers should pass `Current.true_user`, not `Current.user`:+ # `Current.user` resolves to the impersonated user during impersonation,+ # which would attribute the actor's own action to their victim. Omitted+ # from metadata whenever actor == user, so genuinely self-service changes+ # don't carry a redundant actor_user_id.+ def log_api_key_created!(user:, api_key:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "api_key_created",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user, api_key_id: api_key.id, name: api_key.name, scopes: api_key.scopes)+ )+ end++ def log_api_key_revoked!(user:, api_key:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "api_key_revoked",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user, api_key_id: api_key.id, name: api_key.name)+ )+ end++ def log_mfa_enabled!(user:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "mfa_enabled",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user)+ )+ end++ def log_mfa_disabled!(user:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "mfa_disabled",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user)+ )+ end++ def log_webauthn_credential_added!(user:, credential:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "webauthn_credential_added",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user, credential_id: credential.id, nickname: credential.nickname)+ )+ end++ def log_webauthn_credential_removed!(user:, credential:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "webauthn_credential_removed",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user, credential_id: credential.id, nickname: credential.nickname)+ )+ end++ def log_password_changed!(user:, request:, actor: nil)+ create!(+ user: user,+ user_email: user.email,+ event_type: "password_changed",+ ip_address: request.remote_ip,+ user_agent: request.user_agent&.truncate(500),+ metadata: actor_metadata(actor, user)+ )+ end++ private++ def actor_metadata(actor, user, extra = {})+ metadata = extra.dup+ metadata[:actor_user_id] = actor.id if actor && actor.id != user.id+ metadata+ end+ end+enddiff --git a/app/models/user.rb b/app/models/user.rbindex 29bb1c2a24..7670c48042 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -54,6 +54,10 @@ class User < ApplicationRecord# SSO JIT users have password_digest = nil and authenticate via OIDC only.validates :password, presence: true, on: :create, unless: :skip_password_validation?validates :password, length: { minimum: 8 }, allow_nil: true+ # `validations: false` above also drops Rails' confirmation and current-password+ # (password_challenge) checks, so restore both here.+ validates :password, confirmation: true, allow_blank: true+ validate :password_challenge_matches, unless: -> { password_challenge.nil? }normalizes :email, with: ->(email) { email.strip.downcase }normalizes :unconfirmed_email, with: ->(email) { email&.strip&.downcase }normalizes :locale, with: ->(locale) { locale.presence }@@ -904,6 +908,13 @@ class User < ApplicationRecordskip_password_validation == trueend+ def password_challenge_matches+ digest_was = password_digest_was+ return if digest_was.present? && BCrypt::Password.new(digest_was).is_password?(password_challenge)++ errors.add(:password_challenge)+ end+# The dashboard only sends the order of the widgets it rendered, so put# each hidden widget back after the one it followed before.def keep_hidden_sections_in_order(new_order, old_order)diff --git a/config/locales/models/user/de.yml b/config/locales/models/user/de.ymlindex 96a2623714..86ced44f43 100644--- a/config/locales/models/user/de.yml+++ b/config/locales/models/user/de.yml@@ -10,6 +10,7 @@ de:last_name: Nachnamepassword: Passwortpassword_confirmation: Passwortbestätigung+ password_challenge: Aktuelles Passworterrors:models:user:diff --git a/config/locales/models/user/en.yml b/config/locales/models/user/en.ymlindex bca600838d..81698dfbc1 100644--- a/config/locales/models/user/en.yml+++ b/config/locales/models/user/en.yml@@ -10,6 +10,7 @@ en:last_name: Last Namepassword: Passwordpassword_confirmation: Password Confirmation+ password_challenge: Current Passworderrors:models:user:diff --git a/config/locales/views/mfa/ca.yml b/config/locales/views/mfa/ca.ymlindex 4359b70c96..b9343f1e57 100644--- a/config/locales/views/mfa/ca.yml+++ b/config/locales/views/mfa/ca.yml@@ -13,7 +13,9 @@ ca:create:code_already_used: Aquest codi ja s'ha utilitzat. Introdueix el codi següent de la teva aplicació d'autenticació.invalid_code: Codi de verificació invàlid. Torna-ho a provar.+ setup_failed: S'ha produït un error en activar l'autenticació de dos factors. Torna-ho a provar.disable:+ failure: S'ha produït un error en desactivar l'autenticació de dos factors. Torna-ho a provar.success: L'autenticació de dos factors s'ha desactivatnew:code_label: Codi de verificaciódiff --git a/config/locales/views/mfa/de.yml b/config/locales/views/mfa/de.ymlindex 18b79faa41..8d1b474dce 100644--- a/config/locales/views/mfa/de.yml+++ b/config/locales/views/mfa/de.yml@@ -11,7 +11,9 @@ de:create:code_already_used: Dieser Code wurde bereits verwendet. Bitte gib den nächsten Code aus deiner Authentifizierungs-App ein.invalid_code: Ungültiger Bestätigungscode Bitte versuche es erneut+ setup_failed: Beim Aktivieren der Zwei-Faktor-Authentifizierung ist ein Fehler aufgetreten. Bitte versuche es erneut.disable:+ failure: Beim Deaktivieren der Zwei-Faktor-Authentifizierung ist ein Fehler aufgetreten. Bitte versuche es erneut.success: Zwei-Faktor-Authentifizierung wurde deaktiviertnew:code_label: Bestätigungscodediff --git a/config/locales/views/mfa/en.yml b/config/locales/views/mfa/en.ymlindex e6679c0fd4..186cdae714 100644--- a/config/locales/views/mfa/en.yml+++ b/config/locales/views/mfa/en.yml@@ -15,8 +15,10 @@ en:create:code_already_used: That code was already used. Please enter the next code from your authenticator app.invalid_code: Invalid verification code. Please try again.+ setup_failed: Something went wrong enabling two-factor authentication. Please try again.invalid_password: Incorrect password. Please try again.disable:+ failure: Something went wrong disabling two-factor authentication. Please try again.invalid_password: Incorrect password. Please try again.success: Two-factor authentication has been disablednew:diff --git a/config/locales/views/mfa/es.yml b/config/locales/views/mfa/es.ymlindex 329f42dc05..7ee0fec296 100644--- a/config/locales/views/mfa/es.yml+++ b/config/locales/views/mfa/es.yml@@ -13,7 +13,9 @@ es:create:code_already_used: Ese código ya se ha utilizado. Por favor, introduce el siguiente código de tu aplicación de autenticación.invalid_code: Código de verificación inválido. Por favor, inténtalo de nuevo.+ setup_failed: Ocurrió un error al activar la autenticación de dos factores. Por favor, inténtalo de nuevo.disable:+ failure: Ocurrió un error al desactivar la autenticación de dos factores. Por favor, inténtalo de nuevo.success: La autenticación de dos factores ha sido desactivadanew:code_label: Código de Verificacióndiff --git a/config/locales/views/mfa/fr.yml b/config/locales/views/mfa/fr.ymlindex bbe29a48b5..eca4674185 100644--- a/config/locales/views/mfa/fr.yml+++ b/config/locales/views/mfa/fr.yml@@ -13,8 +13,9 @@ fr:create:code_already_used: Ce code a déjà été utilisé. Veuillez saisir le code suivant de votre application d'authentification.invalid_code: Code de vérification invalide. Veuillez essayer à nouveau.- invalid_password: Mot de passe incorrect. Veuillez réessayer.+ setup_failed: Une erreur s'est produite lors de l'activation de l'authentification à deux facteurs. Veuillez réessayer.disable:+ failure: Une erreur s'est produite lors de la désactivation de l'authentification à deux facteurs. Veuillez réessayer.invalid_password: Mot de passe incorrect. Veuillez réessayer.success: L'authentification à deux facteurs a été désactivée.local_password_required: L'authentification à deux facteurs nécessite un mot de passe local. Le vôtre est géré par votre fournisseur d'identité.diff --git a/config/locales/views/mfa/hu.yml b/config/locales/views/mfa/hu.ymlindex 5b1cdfbc1b..3696743f10 100644--- a/config/locales/views/mfa/hu.yml+++ b/config/locales/views/mfa/hu.yml@@ -11,7 +11,9 @@ hu:create:code_already_used: Ezt a kódot már felhasználtad. Kérjük, add meg a hitelesítő alkalmazás következő kódját.invalid_code: Érvénytelen ellenőrzőkód. Kérjük, próbáld újra.+ setup_failed: Hiba történt a kétlépéses hitelesítés bekapcsolása közben. Kérjük, próbáld újra.disable:+ failure: Hiba történt a kétlépéses hitelesítés kikapcsolása közben. Kérjük, próbáld újra.success: A kétlépéses hitelesítés le lett tiltvanew:code_label: Ellenőrzőkóddiff --git a/config/locales/views/mfa/it.yml b/config/locales/views/mfa/it.ymlindex 484bdf344f..d304cb4be4 100644--- a/config/locales/views/mfa/it.yml+++ b/config/locales/views/mfa/it.yml@@ -11,7 +11,9 @@ it:create:code_already_used: Questo codice è già stato utilizzato. Inserisci il codice successivo dalla tua app di autenticazione.invalid_code: Codice di verifica non valido. Riprova.+ setup_failed: Si è verificato un errore durante l'attivazione dell'autenticazione a due fattori. Riprova.disable:+ failure: Si è verificato un errore durante la disattivazione dell'autenticazione a due fattori. Riprova.success: L'autenticazione a due fattori è stata disabilitatanew:code_label: Codice di verificadiff --git a/config/locales/views/mfa/nb.yml b/config/locales/views/mfa/nb.ymlindex 7b01d03fdc..7252ffc000 100644--- a/config/locales/views/mfa/nb.yml+++ b/config/locales/views/mfa/nb.yml@@ -11,7 +11,9 @@ nb:create:code_already_used: Denne koden er allerede brukt. Skriv inn neste kode fra autentiseringsappen din.invalid_code: Ugyldig verifiseringskode. Prøv igjen.+ setup_failed: Noe gikk galt under aktivering av to-faktor autentisering. Prøv igjen.disable:+ failure: Noe gikk galt under deaktivering av to-faktor autentisering. Prøv igjen.success: To-faktor autentisering er deaktivertnew:code_label: Verifiseringskodediff --git a/config/locales/views/mfa/nl.yml b/config/locales/views/mfa/nl.ymlindex 3589c659c4..ea1bb767c1 100644--- a/config/locales/views/mfa/nl.yml+++ b/config/locales/views/mfa/nl.yml@@ -13,7 +13,9 @@ nl:code_already_used: "Deze code is al gebruikt. Voer de volgende code uit uw authenticatie-app in."invalid_code: "Ongeldige verificatiecode. Probeer het opnieuw."invalid_password: "Onjuist wachtwoord. Probeer het opnieuw."+ setup_failed: "Er is iets misgegaan bij het inschakelen van tweefactorauthenticatie. Probeer het opnieuw."disable:+ failure: "Er is iets misgegaan bij het uitschakelen van tweefactorauthenticatie. Probeer het opnieuw."invalid_password: "Onjuist wachtwoord. Probeer het opnieuw."success: "Tweefactorauthenticatie is uitgeschakeld"new:diff --git a/config/locales/views/mfa/pl.yml b/config/locales/views/mfa/pl.ymlindex d893d4d813..bdf06baa32 100644--- a/config/locales/views/mfa/pl.yml+++ b/config/locales/views/mfa/pl.yml@@ -12,7 +12,9 @@ pl:create:code_already_used: Ten kod został już użyty. Wprowadź następny kod z aplikacji uwierzytelniającej.invalid_code: Nieprawidłowy kod weryfikacyjny. Spróbuj ponownie.+ setup_failed: Coś poszło nie tak podczas włączania uwierzytelniania dwuskładnikowego. Spróbuj ponownie.disable:+ failure: Coś poszło nie tak podczas wyłączania uwierzytelniania dwuskładnikowego. Spróbuj ponownie.success: Uwierzytelnianie dwuskładnikowe zostało wyłączonenew:code_label: Kod weryfikacyjnydiff --git a/config/locales/views/mfa/pt-BR.yml b/config/locales/views/mfa/pt-BR.ymlindex 573406eb0c..7e545ce250 100644--- a/config/locales/views/mfa/pt-BR.yml+++ b/config/locales/views/mfa/pt-BR.yml@@ -13,7 +13,9 @@ pt-BR:create:code_already_used: Esse código já foi usado. Insira o próximo código do seu aplicativo autenticador.invalid_code: Código de verificação inválido. Tente novamente.+ setup_failed: Algo deu errado ao ativar a autenticação de dois fatores. Tente novamente.disable:+ failure: Algo deu errado ao desativar a autenticação de dois fatores. Tente novamente.success: Autenticação de dois fatores foi desabilitadanew:code_label: Código de Verificaçãodiff --git a/config/locales/views/mfa/pt-PT.yml b/config/locales/views/mfa/pt-PT.ymlindex 685655d31c..6f7cc3f367 100644--- a/config/locales/views/mfa/pt-PT.yml+++ b/config/locales/views/mfa/pt-PT.yml@@ -13,7 +13,9 @@ pt-PT:create:code_already_used: Esse código já foi utilizado. Introduza o próximo código da sua aplicação de autenticação.invalid_code: Código de verificação inválido. Tente novamente.+ setup_failed: Ocorreu um erro ao ativar a autenticação de dois fatores. Tente novamente.disable:+ failure: Ocorreu um erro ao desativar a autenticação de dois fatores. Tente novamente.success: A autenticação de dois fatores foi desativadanew:code_label: Código de Verificaçãodiff --git a/config/locales/views/mfa/ro.yml b/config/locales/views/mfa/ro.ymlindex a5546efc05..b60e41b046 100644--- a/config/locales/views/mfa/ro.yml+++ b/config/locales/views/mfa/ro.yml@@ -11,7 +11,9 @@ ro:create:code_already_used: Acest cod a fost deja utilizat. Vă rugăm să introduceți următorul cod din aplicația de autentificare.invalid_code: Cod de verificare invalid. Vă rugăm să încercați din nou.+ setup_failed: Ceva nu a mers bine la activarea autentificării cu doi factori. Vă rugăm să încercați din nou.disable:+ failure: Ceva nu a mers bine la dezactivarea autentificării cu doi factori. Vă rugăm să încercați din nou.success: Autentificarea cu doi factori a fost dezactivatănew:code_label: Cod de verificarediff --git a/config/locales/views/mfa/ru.yml b/config/locales/views/mfa/ru.ymlindex a6e7a39b98..1731516f4e 100644--- a/config/locales/views/mfa/ru.yml+++ b/config/locales/views/mfa/ru.yml@@ -13,7 +13,9 @@ ru:create:code_already_used: Этот код уже был использован. Пожалуйста, введите следующий код из приложения-аутентификатора.invalid_code: Неверный код подтверждения. Пожалуйста, попробуйте снова.+ setup_failed: Что-то пошло не так при включении двухфакторной аутентификации. Пожалуйста, попробуйте снова.disable:+ failure: Что-то пошло не так при отключении двухфакторной аутентификации. Пожалуйста, попробуйте снова.success: Двухфакторная аутентификация отключенаnew:code_label: Код подтвержденияdiff --git a/config/locales/views/mfa/tr.yml b/config/locales/views/mfa/tr.ymlindex fecde73423..e98c43f6af 100644--- a/config/locales/views/mfa/tr.yml+++ b/config/locales/views/mfa/tr.yml@@ -13,7 +13,9 @@ tr:create:code_already_used: Bu kod zaten kullanıldı. Lütfen kimlik doğrulayıcı uygulamanızdaki bir sonraki kodu girin.invalid_code: Geçersiz doğrulama kodu. Lütfen tekrar deneyin.+ setup_failed: İki faktörlü kimlik doğrulamayı etkinleştirirken bir sorun oluştu. Lütfen tekrar deneyin.disable:+ failure: İki faktörlü kimlik doğrulamayı devre dışı bırakırken bir sorun oluştu. Lütfen tekrar deneyin.success: İki faktörlü kimlik doğrulama devre dışı bırakıldınew:code_label: Doğrulama Kodudiff --git a/config/locales/views/mfa/uk.yml b/config/locales/views/mfa/uk.ymlindex a9486a3ca5..0ffe1bffd9 100644--- a/config/locales/views/mfa/uk.yml+++ b/config/locales/views/mfa/uk.yml@@ -10,7 +10,9 @@ uk:create:code_already_used: Цей код уже було використано. Будь ласка, введіть наступний код із застосунку автентифікації.invalid_code: Недійсний код підтвердження. Будь ласка, спробуйте ще раз.+ setup_failed: Під час увімкнення двофакторної автентифікації сталася помилка. Будь ласка, спробуйте ще раз.disable:+ failure: Під час вимкнення двофакторної автентифікації сталася помилка. Будь ласка, спробуйте ще раз.success: Двофакторну автентифікацію вимкненоnew:code_label: Код підтвердженняdiff --git a/config/locales/views/mfa/vi.yml b/config/locales/views/mfa/vi.ymlindex dfc7b5b3db..28e2e7f634 100644--- a/config/locales/views/mfa/vi.yml+++ b/config/locales/views/mfa/vi.yml@@ -11,7 +11,9 @@ vi:create:code_already_used: Mã này đã được sử dụng. Vui lòng nhập mã tiếp theo từ ứng dụng xác thực của bạn.invalid_code: Mã xác minh không hợp lệ. Vui lòng thử lại.+ setup_failed: Đã xảy ra lỗi khi bật xác thực hai yếu tố. Vui lòng thử lại.disable:+ failure: Đã xảy ra lỗi khi tắt xác thực hai yếu tố. Vui lòng thử lại.success: Xác thực hai yếu tố đã bị tắtnew:code_label: Mã xác minhdiff --git a/config/locales/views/mfa/zh-CN.yml b/config/locales/views/mfa/zh-CN.ymlindex d718614822..f32cc1260e 100644--- a/config/locales/views/mfa/zh-CN.yml+++ b/config/locales/views/mfa/zh-CN.yml@@ -11,7 +11,9 @@ zh-CN:create:code_already_used: 该验证码已被使用。请输入验证器应用中的下一个验证码。invalid_code: 验证码无效。请重试。+ setup_failed: 启用双重认证时出错,请重试。disable:+ failure: 禁用双重认证时出错,请重试。success: 双重认证已禁用new:code_label: 验证码diff --git a/config/locales/views/mfa/zh-TW.yml b/config/locales/views/mfa/zh-TW.ymlindex ea56df7baa..7b3b03d5f2 100644--- a/config/locales/views/mfa/zh-TW.yml+++ b/config/locales/views/mfa/zh-TW.yml@@ -11,7 +11,9 @@ zh-TW:create:code_already_used: 該驗證碼已被使用。請輸入驗證器應用程式中的下一個驗證碼。invalid_code: 驗證碼無效。請再試一次。+ setup_failed: 啟用雙重驗證時發生錯誤,請再試一次。disable:+ failure: 停用雙重驗證時發生錯誤,請再試一次。success: 雙重驗證已停用new:code_label: 驗證碼diff --git a/config/locales/views/settings/api_keys/ca.yml b/config/locales/views/settings/api_keys/ca.ymlindex 2b3af86f9b..051b568375 100644--- a/config/locales/views/settings/api_keys/ca.yml+++ b/config/locales/views/settings/api_keys/ca.yml@@ -4,6 +4,7 @@ ca:api_keys:create:success: La teva clau API s'ha creat correctament+ creation_failed: "No s'ha pogut crear la teva clau API. Torna-ho a provar."created:continue: Continua a la configuració de claus APIcopy_key: Copia la clau APIdiff --git a/config/locales/views/settings/api_keys/de.yml b/config/locales/views/settings/api_keys/de.ymlindex be6c5a91c2..231a75260b 100644--- a/config/locales/views/settings/api_keys/de.yml+++ b/config/locales/views/settings/api_keys/de.yml@@ -99,6 +99,7 @@ de:continue: Weiter zu den API-Schlüssel-Einstellungencreate:success: Dein API-Key wurde erstellt+ creation_failed: "Dein API-Key konnte nicht erstellt werden. Bitte versuche es erneut."destroy:revoke_failed: API-Key ließ sich nicht widerrufenrevoked_successfully: API-Key widerrufendiff --git a/config/locales/views/settings/api_keys/en.yml b/config/locales/views/settings/api_keys/en.ymlindex 49a2108b70..f0d1db65a3 100644--- a/config/locales/views/settings/api_keys/en.yml+++ b/config/locales/views/settings/api_keys/en.yml@@ -8,6 +8,7 @@ en:api_keys:create:success: "Your API key has been created successfully"+ creation_failed: "Couldn't create your API key. Please try again."destroy:revoked_successfully: "API key has been revoked successfully"revoke_failed: "Failed to revoke API key"diff --git a/config/locales/views/settings/api_keys/es.yml b/config/locales/views/settings/api_keys/es.ymlindex fdd92c5f1a..56aa41d790 100644--- a/config/locales/views/settings/api_keys/es.yml+++ b/config/locales/views/settings/api_keys/es.yml@@ -13,6 +13,7 @@ es:api_keys:create:success: Tu clave API se ha creado correctamente+ creation_failed: "No se pudo crear tu clave API. Inténtalo de nuevo."destroy:revoked_successfully: La clave API se ha revocado correctamenterevoke_failed: No se pudo revocar la clave APIdiff --git a/config/locales/views/settings/api_keys/fr.yml b/config/locales/views/settings/api_keys/fr.ymlindex 3c22368e64..9173a31e92 100644--- a/config/locales/views/settings/api_keys/fr.yml+++ b/config/locales/views/settings/api_keys/fr.yml@@ -4,6 +4,7 @@ fr:api_keys:create:success: Votre clé API a été créée avec succès+ creation_failed: "Impossible de créer votre clé API. Veuillez réessayer."created:continue: Continuer vers les paramètres de la clé APIcopy_key: Copier la clé APIdiff --git a/config/locales/views/settings/api_keys/hu.yml b/config/locales/views/settings/api_keys/hu.ymlindex 5d376caed6..fad0c83263 100644--- a/config/locales/views/settings/api_keys/hu.yml+++ b/config/locales/views/settings/api_keys/hu.yml@@ -13,6 +13,7 @@ hu:api_keys:create:success: "Az API-kulcsod sikeresen létrehozva"+ creation_failed: "Nem sikerült létrehozni az API-kulcsodat. Kérjük, próbáld újra."destroy:not_found: "Az API-kulcs nem található"cannot_revoke: "Ez az API-kulcs nem vonható vissza"diff --git a/config/locales/views/settings/api_keys/it.yml b/config/locales/views/settings/api_keys/it.ymlindex 8a31a622f4..ab1845d1b8 100644--- a/config/locales/views/settings/api_keys/it.yml+++ b/config/locales/views/settings/api_keys/it.yml@@ -13,6 +13,7 @@ it:api_keys:create:success: "La tua chiave API è stata creata con successo"+ creation_failed: "Impossibile creare la tua chiave API. Riprova."destroy:not_found: "Chiave API non trovata"cannot_revoke: "Questa chiave API non può essere revocata"diff --git a/config/locales/views/settings/api_keys/pl.yml b/config/locales/views/settings/api_keys/pl.ymlindex 1d75b7a127..b51405f601 100644--- a/config/locales/views/settings/api_keys/pl.yml+++ b/config/locales/views/settings/api_keys/pl.yml@@ -4,6 +4,7 @@ pl:api_keys:create:success: Twój klucz API został utworzony+ creation_failed: "Nie udało się utworzyć klucza API. Spróbuj ponownie."created:continue: Przejdź do ustawień klucza APIcopy_key: Skopiuj klucz APIdiff --git a/config/locales/views/settings/api_keys/pt-PT.yml b/config/locales/views/settings/api_keys/pt-PT.ymlindex f4ccd8ebbb..de963940bb 100644--- a/config/locales/views/settings/api_keys/pt-PT.yml+++ b/config/locales/views/settings/api_keys/pt-PT.yml@@ -8,6 +8,7 @@ pt-PT:api_keys:create:success: "A sua chave de API foi criada com sucesso"+ creation_failed: "Não foi possível criar a sua chave de API. Tente novamente."destroy:revoked_successfully: "A chave de API foi revogada com sucesso"revoke_failed: "Falha ao revogar a chave de API"diff --git a/config/locales/views/settings/api_keys/ru.yml b/config/locales/views/settings/api_keys/ru.ymlindex d210e67e89..fd79790efe 100644--- a/config/locales/views/settings/api_keys/ru.yml+++ b/config/locales/views/settings/api_keys/ru.yml@@ -4,6 +4,7 @@ ru:api_keys:create:success: Ваш API-ключ успешно создан+ creation_failed: "Не удалось создать API-ключ. Попробуйте ещё раз."created:continue: Перейти к настройкам API-ключаcopy_key: Скопировать API-ключdiff --git a/config/locales/views/settings/api_keys/tr.yml b/config/locales/views/settings/api_keys/tr.ymlindex 97ec5c6967..c42c592a10 100644--- a/config/locales/views/settings/api_keys/tr.yml+++ b/config/locales/views/settings/api_keys/tr.yml@@ -4,6 +4,7 @@ tr:api_keys:create:success: API anahtarınız başarıyla oluşturuldu+ creation_failed: "API anahtarınız oluşturulamadı. Lütfen tekrar deneyin."created:continue: API Anahtarı Ayarlarına Devam Etcopy_key: API Anahtarını Kopyaladiff --git a/config/locales/views/settings/api_keys/uk.yml b/config/locales/views/settings/api_keys/uk.ymlindex 6b7fca7880..08bb35aa3a 100644--- a/config/locales/views/settings/api_keys/uk.yml+++ b/config/locales/views/settings/api_keys/uk.yml@@ -7,6 +7,7 @@ uk:api_keys:create:success: "Ваш ключ API успішно створено"+ creation_failed: "Не вдалося створити ключ API. Спробуйте ще раз."destroy:revoked_successfully: "Ключ API успішно відкликано"revoke_failed: "Не вдалося відкликати ключ API"diff --git a/config/locales/views/settings/api_keys/vi.yml b/config/locales/views/settings/api_keys/vi.ymlindex 2920fb9e74..bca547c08a 100644--- a/config/locales/views/settings/api_keys/vi.yml+++ b/config/locales/views/settings/api_keys/vi.yml@@ -13,6 +13,7 @@ vi:api_keys:create:success: "Khóa API của bạn đã được tạo thành công"+ creation_failed: "Không thể tạo khóa API của bạn. Vui lòng thử lại."destroy:not_found: "Không tìm thấy khóa API"cannot_revoke: "Không thể thu hồi khóa API này"diff --git a/config/locales/views/settings/api_keys/zh-CN.yml b/config/locales/views/settings/api_keys/zh-CN.ymlindex 0bf0b7c61b..2c3e693c4b 100644--- a/config/locales/views/settings/api_keys/zh-CN.yml+++ b/config/locales/views/settings/api_keys/zh-CN.yml@@ -8,6 +8,7 @@ zh-CN:api_keys:create:success: 您的 API 密钥已成功创建+ creation_failed: "无法创建 API 密钥,请重试。"destroy:revoked_successfully: API 密钥已成功撤销revoke_failed: 撤销 API 密钥失败diff --git a/config/locales/views/settings/api_keys/zh-TW.yml b/config/locales/views/settings/api_keys/zh-TW.ymlindex 7c5435f511..9d65c0eb90 100644--- a/config/locales/views/settings/api_keys/zh-TW.yml+++ b/config/locales/views/settings/api_keys/zh-TW.yml@@ -13,6 +13,7 @@ zh-TW:api_keys:create:success: 您的 API 金鑰已成功建立+ creation_failed: "無法建立您的 API 金鑰,請再試一次。"destroy:revoked_successfully: API 金鑰已成功撤銷revoke_failed: 撤銷 API 金鑰失敗diff --git a/db/migrate/20261026120000_create_security_audit_logs.rb b/db/migrate/20261026120000_create_security_audit_logs.rbnew file mode 100644index 0000000000..aef29825b3--- /dev/null+++ b/db/migrate/20261026120000_create_security_audit_logs.rb@@ -0,0 +1,42 @@+# Audit trail for security-sensitive account operations that had no record+# at all before this: API key creation/revocation, MFA enable/disable,+# password changes. Deliberately a separate table from sso_audit_logs+# (app/models/sso_audit_log.rb) rather than repurposing it — that model's+# name, its `provider` column, and its existing 12 call sites are all+# SSO-specific; folding unrelated event types into it would make "Sso" a+# misnomer and risk touching working code for no benefit.+class CreateSecurityAuditLogs < ActiveRecord::Migration[8.1]+ def change+ create_table :security_audit_logs, id: :uuid do |t|+ # Nullable, not the FK's on_delete: :nullify, matching+ # debug_log_entries: an audit trail should outlive the account it's+ # about (an admin investigating a deleted account still needs to see+ # what it did beforehand), not disappear or block the deletion.+ t.uuid :user_id+ t.string :event_type, null: false+ # AR-encrypted (see SecurityAuditLog), like user_email below: these+ # rows deliberately outlive the user (see the FK below), so the IP and+ # user agent shouldn't be left recoverable in the clear once the+ # account behind them is gone. `text`, not `string` — ciphertext runs+ # longer than the plaintext and can exceed a varchar(255) limit.+ t.text :ip_address+ t.text :user_agent+ # AR-encrypted (see SecurityAuditLog) rather than folded into `metadata`+ # (plain jsonb): these rows deliberately outlive the user (see the FK+ # below), so this is the only copy of the user's email left once the+ # account is gone, and it needs the same encryption boundary that+ # `User#email` has.+ t.text :user_email+ t.jsonb :metadata, default: {}, null: false++ t.timestamps+ end++ add_index :security_audit_logs, :user_id+ add_index :security_audit_logs, [ :user_id, :created_at ]+ add_index :security_audit_logs, :event_type+ add_index :security_audit_logs, :created_at++ add_foreign_key :security_audit_logs, :users, on_delete: :nullify+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 13bebdc592..78e444bdae 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2357,6 +2357,21 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) dot.check_constraint "kind::text = ANY (ARRAY['standard'::character varying::text, 'cash'::character varying::text])", name: "chk_securities_kind"end+ create_table "security_audit_logs", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "created_at", null: false+ t.string "event_type", null: false+ t.text "ip_address"+ t.jsonb "metadata", default: {}, null: false+ t.datetime "updated_at", null: false+ t.text "user_agent"+ t.text "user_email"+ t.uuid "user_id"+ t.index ["created_at"], name: "index_security_audit_logs_on_created_at"+ t.index ["event_type"], name: "index_security_audit_logs_on_event_type"+ t.index ["user_id", "created_at"], name: "index_security_audit_logs_on_user_id_and_created_at"+ t.index ["user_id"], name: "index_security_audit_logs_on_user_id"+ end+create_table "security_prices", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "created_at", null: falset.string "currency", default: "USD", null: false@@ -3239,6 +3254,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) doadd_foreign_key "rule_runs", "rules"add_foreign_key "rules", "families"add_foreign_key "rules", "rule_groups", on_delete: :nullify+ add_foreign_key "security_audit_logs", "users", on_delete: :nullifyadd_foreign_key "security_prices", "securities"add_foreign_key "security_splits", "securities", on_delete: :cascadeadd_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id", on_delete: :nullifydiff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rbindex a553016a23..d016ac9196 100644--- a/test/controllers/admin/users_controller_test.rb+++ b/test/controllers/admin/users_controller_test.rb@@ -326,6 +326,52 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTestassert target.authenticate(new_password), "User should authenticate with the new password"end+ test "update logs an audit entry with the admin as actor when setting a new password" do+ target = users(:family_member)++ assert_difference "SecurityAuditLog.count", 1 do+ patch admin_user_url(target), params: {+ user: {+ role: target.role,+ password: "Secure1!pass"+ }+ }+ end++ log = SecurityAuditLog.last+ assert_equal "password_changed", log.event_type+ assert_equal target.id, log.user_id+ assert_equal users(:sure_support_staff).id, log.metadata["actor_user_id"]+ assert_equal target.email, log.user_email+ end++ test "update rolls back the password change when the audit log write fails" do+ target = users(:family_member)+ original_digest = target.password_digest++ SecurityAuditLog.stubs(:log_password_changed!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ patch admin_user_url(target), params: {+ user: {+ role: target.role,+ password: "Secure1!pass"+ }+ }++ assert_redirected_to admin_users_url+ assert_equal original_digest, target.reload.password_digest+ end++ test "update does not log an audit entry when the password is unchanged" do+ target = users(:family_member)++ assert_no_difference "SecurityAuditLog.count" do+ patch admin_user_url(target), params: {+ user: { role: "admin", password: "" }+ }+ end+ end+test "update shows descriptive notification for role change only" dotarget = users(:family_member)diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rbindex 37f919bc26..c6837f3d0b 100644--- a/test/controllers/mfa_controller_test.rb+++ b/test/controllers/mfa_controller_test.rb@@ -48,6 +48,20 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert_equal 8, rendered_codes.lengthassert rendered_codes.all? { |code| code.match?(/\A[0-9a-f]{16}\z/) }assert_empty rendered_codes & @user.otp_backup_codes++ assert SecurityAuditLog.exists?(user: @user, event_type: "mfa_enabled")+ end++ test "does not enable MFA when the audit log write fails" do+ @user.setup_mfa!+ totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")+ SecurityAuditLog.stubs(:log_mfa_enabled!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ post mfa_path, params: { code: totp.now }++ assert_redirected_to new_mfa_path+ assert_not @user.reload.otp_required?+ assert_empty @user.otp_backup_codesend# A double-click or browser resubmit replays the correct enrollment code;@@ -96,13 +110,29 @@ class MfaControllerTest < ActionDispatch::IntegrationTesttest "does not enable MFA with invalid code" do@user.setup_mfa!- post mfa_path, params: { code: "invalid", password: user_password_test }+ assert_no_difference "SecurityAuditLog.count" do+ post mfa_path, params: { code: "invalid", password: user_password_test }+ endassert_redirected_to new_mfa_pathassert_not @user.reload.otp_required?assert_empty @user.otp_backup_codesend+ test "create refuses to touch an already-enabled MFA even with a wrong code" do+ @user.setup_mfa!+ @user.enable_mfa!+ assert @user.otp_required?++ assert_no_difference "SecurityAuditLog.count" do+ post mfa_path, params: { code: "invalid" }+ end++ assert_redirected_to root_path+ assert @user.reload.otp_required?+ assert @user.otp_secret.present?+ end+test "verify shows MFA verification page" do@user.setup_mfa!@user.enable_mfa!@@ -347,6 +377,47 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert_nil @user.otp_secretassert_empty @user.otp_backup_codesassert_empty @user.webauthn_credentials++ assert SecurityAuditLog.exists?(user: @user, event_type: "mfa_disabled")+ end++ test "disable while impersonating attributes the audit entry to the impersonator, not the victim" do+ @user.setup_mfa!+ @user.enable_mfa!+ sign_out++ impersonator = users(:sure_support_staff)+ sign_in impersonator+ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonation_sessions(:in_progress).id }+ assert_response :redirect++ delete disable_mfa_path, params: { password: user_password_test }++ log = SecurityAuditLog.find_by(user: @user, event_type: "mfa_disabled")+ assert_not_nil log+ assert_equal impersonator.id, log.metadata["actor_user_id"]+ end++ test "still disables MFA when the audit log write fails" do+ # Log-and-continue, not transactional: a failed audit write must not+ # block turning off a security control the user is actively trying to+ # disable (e.g. because they believe it's compromised).+ @user.setup_mfa!+ @user.enable_mfa!+ @user.webauthn_credentials.create!(+ nickname: "YubiKey",+ credential_id: "disable-mfa-audit-fail-credential",+ public_key: "public-key"+ )+ SecurityAuditLog.stubs(:log_mfa_disabled!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ delete disable_mfa_path, params: { password: user_password_test }++ assert_redirected_to settings_security_path+ assert_not @user.reload.otp_required?+ assert_nil @user.otp_secret+ assert_empty @user.webauthn_credentials+ assert_not SecurityAuditLog.exists?(user: @user, event_type: "mfa_disabled")enddiff --git a/test/controllers/password_resets_controller_test.rb b/test/controllers/password_resets_controller_test.rbindex 288c8a57e5..8f01aeabb6 100644--- a/test/controllers/password_resets_controller_test.rb+++ b/test/controllers/password_resets_controller_test.rb@@ -26,6 +26,51 @@ class PasswordResetsControllerTest < ActionDispatch::IntegrationTestpatch password_reset_path(token: @user.generate_token_for(:password_reset)),params: { user: { password: "password", password_confirmation: "password" } }assert_redirected_to new_session_url++ assert SecurityAuditLog.exists?(user: @user, event_type: "password_changed")+ end++ test "update with an invalid password does not write an audit log" do+ assert_no_difference "SecurityAuditLog.count" do+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),+ params: { user: { password: "short", password_confirmation: "short" } }+ end+ assert_response :unprocessable_entity+ end++ test "update rejects a mismatched confirmation" do+ original_digest = @user.password_digest++ assert_no_difference "SecurityAuditLog.count" do+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),+ params: { user: { password: "password", password_confirmation: "different" } }+ end++ assert_response :unprocessable_entity+ assert_equal original_digest, @user.reload.password_digest+ end++ test "update with a blank password does not report success or write an audit log" do+ original_digest = @user.password_digest++ assert_no_difference "SecurityAuditLog.count" do+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),+ params: { user: { password: "", password_confirmation: "" } }+ end++ assert_response :unprocessable_entity+ assert_equal original_digest, @user.reload.password_digest+ end++ test "rolls back the password change when the audit log write fails" do+ SecurityAuditLog.stubs(:log_password_changed!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))+ original_digest = @user.password_digest++ patch password_reset_path(token: @user.generate_token_for(:password_reset)),+ params: { user: { password: "password", password_confirmation: "password" } }++ assert_response :unprocessable_entity+ assert_equal original_digest, @user.reload.password_digestendtest "all actions redirect when password features are disabled" dodiff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rbnew file mode 100644index 0000000000..16b7a05c44--- /dev/null+++ b/test/controllers/passwords_controller_test.rb@@ -0,0 +1,80 @@+require "test_helper"++class PasswordsControllerTest < ActionDispatch::IntegrationTest+ setup do+ @user = users(:family_admin)+ sign_in @user+ end++ test "edit" do+ get edit_password_path+ assert_response :ok+ end++ test "update changes the password and writes an audit log" do+ original_digest = @user.password_digest++ patch password_path, params: { user: { password_challenge: user_password_test, password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }++ assert_redirected_to root_path+ assert_not_equal original_digest, @user.reload.password_digest+ assert SecurityAuditLog.exists?(user: @user, event_type: "password_changed")+ end++ test "update rejects a wrong current password" do+ assert_password_unchanged do+ patch password_path, params: { user: { password_challenge: "wrongpassword123", password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }+ end+ end++ test "update rejects a blank or missing current password" do+ assert_password_unchanged do+ patch password_path, params: { user: { password_challenge: "", password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }+ end++ assert_password_unchanged do+ patch password_path, params: { user: { password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }+ end+ end++ test "update rejects a mismatched confirmation" do+ assert_password_unchanged do+ patch password_path, params: { user: { password_challenge: user_password_test, password: "newtestpassword817983172", password_confirmation: "differentpassword817983172" } }+ end+ end++ test "update rejects a blank new password" do+ assert_password_unchanged do+ patch password_path, params: { user: { password_challenge: user_password_test, password: "", password_confirmation: "" } }+ end+ end++ test "update with a too short password does not write an audit log" do+ assert_password_unchanged do+ patch password_path, params: { user: { password_challenge: user_password_test, password: "short", password_confirmation: "short" } }+ end+ end++ test "rolls back the password change when the audit log write fails" do+ SecurityAuditLog.stubs(:log_password_changed!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))+ original_digest = @user.password_digest++ patch password_path, params: { user: { password_challenge: user_password_test, password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }++ assert_response :unprocessable_entity+ assert_equal original_digest, @user.reload.password_digest+ end++ private++ def assert_password_unchanged+ original_digest = @user.reload.password_digest++ assert_no_difference "SecurityAuditLog.count" do+ yield+ end++ assert_response :unprocessable_entity+ assert_equal original_digest, @user.reload.password_digest+ end+enddiff --git a/test/controllers/settings/api_keys_controller_test.rb b/test/controllers/settings/api_keys_controller_test.rbindex b19469ff4f..ccd0d89f5a 100644--- a/test/controllers/settings/api_keys_controller_test.rb+++ b/test/controllers/settings/api_keys_controller_test.rb@@ -65,6 +65,29 @@ class Settings::ApiKeysControllerTest < ActionDispatch::IntegrationTestexisting.reloadrefute existing.revoked?assert_includes new_key.scopes, "read_write"++ log = SecurityAuditLog.where(user: @user, event_type: "api_key_created").last+ assert_equal new_key.id, log.metadata["api_key_id"]+ end++ test "create does not persist the key when the audit log write fails" do+ SecurityAuditLog.stubs(:log_api_key_created!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ assert_no_difference "ApiKey.count" do+ post settings_api_keys_path, params: {+ api_key: {+ name: "Never Persisted Key",+ scopes: "read"+ }+ }+ end++ assert_response :unprocessable_entity+ assert_nil @user.api_keys.find_by(name: "Never Persisted Key")+ # Distinct from a validation failure (blank name, etc.): the key itself+ # was valid, so the form re-render must say so rather than showing a+ # blank/misleading error with nothing on the form explaining it.+ assert_equal I18n.t("settings.api_keys.create.creation_failed"), flash[:alert]endtest "create rejects blank name" do@@ -175,6 +198,57 @@ class Settings::ApiKeysControllerTest < ActionDispatch::IntegrationTestkey2.reloadassert key1.revoked?refute key2.revoked?++ log = SecurityAuditLog.where(user: @user, event_type: "api_key_revoked").last+ assert_equal key1.id, log.metadata["api_key_id"]+ end++ test "destroy still revokes and reports success when the audit log write fails" do+ key = ApiKey.create!(+ user: @user,+ name: "Key One",+ display_key: "key_one_audit_fail_123",+ scopes: [ "read" ]+ )+ SecurityAuditLog.stubs(:log_api_key_revoked!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ delete settings_api_key_path(key)++ assert_redirected_to settings_api_keys_path+ assert_equal I18n.t("settings.api_keys.destroy.revoked_successfully"), flash[:notice]+ assert key.reload.revoked?+ end++ test "destroy still revokes and reports success when the audit log write raises a database error" do+ key = ApiKey.create!(+ user: @user,+ name: "Key One",+ display_key: "key_one_db_error_123",+ scopes: [ "read" ]+ )+ SecurityAuditLog.stubs(:log_api_key_revoked!).raises(ActiveRecord::StatementInvalid.new("connection lost"))++ delete settings_api_key_path(key)++ assert_redirected_to settings_api_keys_path+ assert_equal I18n.t("settings.api_keys.destroy.revoked_successfully"), flash[:notice]+ assert key.reload.revoked?+ end++ test "destroy of a nonexistent key does not write an audit log" do+ other_user = users(:family_member)+ other_user.api_keys.destroy_all+ other_key = ApiKey.create!(+ user: other_user,+ name: "Other User Key",+ display_key: "other_user_key_#{SecureRandom.hex(8)}",+ scopes: [ "read" ]+ )++ assert_no_difference "SecurityAuditLog.count" do+ delete settings_api_key_path(other_key)+ end+ assert_response :not_foundendtest "destroy cannot revoke demo monitoring key" dodiff --git a/test/controllers/settings/webauthn_credentials_controller_test.rb b/test/controllers/settings/webauthn_credentials_controller_test.rbindex c0cc848838..cfaa6d8a50 100644--- a/test/controllers/settings/webauthn_credentials_controller_test.rb+++ b/test/controllers/settings/webauthn_credentials_controller_test.rb@@ -48,6 +48,68 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationTassert @user.reload.webauthn_id.present?end+ test "creating a credential writes an audit log entry" do+ options = registration_options+ credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")++ assert_difference "SecurityAuditLog.count", 1 do+ post settings_webauthn_credentials_path, params: {+ webauthn_credential: { nickname: "MacBook Touch ID", code: @code },+ credential: credential+ }, as: :json+ end++ log = SecurityAuditLog.last+ stored_credential = @user.webauthn_credentials.reload.last+ assert_equal "webauthn_credential_added", log.event_type+ assert_equal stored_credential.id, log.metadata["credential_id"]+ assert_equal "MacBook Touch ID", log.metadata["nickname"]+ end++ test "does not persist the credential when the audit log write fails" do+ options = registration_options+ credential = @client.create(challenge: options.fetch("challenge"), rp_id: "www.example.com")+ SecurityAuditLog.stubs(:log_webauthn_credential_added!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ assert_no_difference -> { @user.webauthn_credentials.count } do+ post settings_webauthn_credentials_path, params: {+ webauthn_credential: { nickname: "MacBook Touch ID", code: @code },+ credential: credential+ }, as: :json+ end++ assert_response :unprocessable_entity+ end++ test "still destroys the credential when the audit log write fails" do+ # Log-and-continue, not transactional: a failed audit write must not+ # block removing a security key the user believes is compromised.+ credential = @user.webauthn_credentials.create!(+ nickname: "YubiKey",+ credential_id: "credential-audit-fail",+ public_key: "public-key"+ )+ SecurityAuditLog.stubs(:log_webauthn_credential_removed!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))++ assert_difference -> { @user.webauthn_credentials.count }, -1 do+ delete settings_webauthn_credential_path(credential)+ end++ assert_redirected_to settings_security_path+ assert_not SecurityAuditLog.exists?(user: @user, event_type: "webauthn_credential_removed")+ end++ test "a rejected registration does not write an audit log" do+ registration_options++ assert_no_difference "SecurityAuditLog.count" do+ post settings_webauthn_credentials_path, params: {+ webauthn_credential: { nickname: "Malformed" },+ credential: []+ }, as: :json+ end+ end+test "registering a credential requires an MFA code" do[ nil, "", "000000" ].each do |code|options = registration_options@@ -309,6 +371,10 @@ class Settings::WebauthnCredentialsControllerTest < ActionDispatch::IntegrationTendassert_redirected_to settings_security_path++ log = SecurityAuditLog.where(user: @user, event_type: "webauthn_credential_removed").last+ assert_equal credential.id, log.metadata["credential_id"]+ assert_equal "YubiKey", log.metadata["nickname"]endprivatediff --git a/test/encryption_verification_test.rb b/test/encryption_verification_test.rbindex 597b91d75b..ed37bdc5de 100644--- a/test/encryption_verification_test.rb+++ b/test/encryption_verification_test.rb@@ -199,6 +199,34 @@ class EncryptionVerificationTest < ActiveSupport::TestCaseendend+ # ============================================================================+ # SECURITY AUDIT LOG MODEL TESTS+ # ============================================================================++ test "security audit log user_email, ip_address and user_agent are encrypted at rest" do+ request = ActionDispatch::TestRequest.create+ request.remote_addr = "203.0.113.5"+ request.user_agent = "EncryptionVerification/1.0"++ log = SecurityAuditLog.log_mfa_enabled!(user: users(:family_admin), request: request)++ assert_equal users(:family_admin).email, log.user_email+ assert_equal "203.0.113.5", log.ip_address+ assert_equal "EncryptionVerification/1.0", log.user_agent++ raw_email = log.read_attribute_before_type_cast(:user_email).to_s+ raw_ip = log.read_attribute_before_type_cast(:ip_address).to_s+ raw_agent = log.read_attribute_before_type_cast(:user_agent).to_s+ assert_not_includes raw_email, users(:family_admin).email+ assert_not_includes raw_ip, "203.0.113.5"+ assert_not_includes raw_agent, "EncryptionVerification/1.0"++ log.reload+ assert_equal users(:family_admin).email, log.user_email+ assert_equal "203.0.113.5", log.ip_address+ assert_equal "EncryptionVerification/1.0", log.user_agent+ end+# ============================================================================# MOBILE DEVICE MODEL TESTS# ============================================================================diff --git a/test/models/security_audit_log_test.rb b/test/models/security_audit_log_test.rbnew file mode 100644index 0000000000..66803b6e6b--- /dev/null+++ b/test/models/security_audit_log_test.rb@@ -0,0 +1,102 @@+require "test_helper"++class SecurityAuditLogTest < ActiveSupport::TestCase+ setup do+ @user = users(:family_admin)+ @request = ActionDispatch::TestRequest.create+ @request.remote_addr = "203.0.113.5"+ @request.user_agent = "TestAgent/1.0"+ end++ test "rejects an event_type outside the allowlist" do+ log = SecurityAuditLog.new(user: @user, event_type: "not_a_real_event")+ assert_not log.valid?+ assert_includes log.errors[:event_type], "is not included in the list"+ end++ test "log_api_key_created! records the api key id, name, and scopes" do+ api_key = ApiKey.create!(user: @user, name: "Test Key", display_key: "test_key_#{SecureRandom.hex(8)}", scopes: [ "read" ]) # pipelock:ignore++ log = SecurityAuditLog.log_api_key_created!(user: @user, api_key: api_key, request: @request)++ assert_equal "api_key_created", log.event_type+ assert_equal api_key.id, log.metadata["api_key_id"]+ assert_equal "Test Key", log.metadata["name"]+ assert_equal @user.email, log.user_email+ assert_equal "203.0.113.5", log.ip_address+ end++ test "log_password_changed! does not include the password anywhere" do+ log = SecurityAuditLog.log_password_changed!(user: @user, request: @request)++ assert_equal "password_changed", log.event_type+ assert_equal @user.email, log.user_email+ assert_not_includes log.metadata.to_s, "password"+ end++ test "log_password_changed! records the actor when someone else changed the password" do+ admin = users(:family_admin)+ other_user = users(:family_member)++ log = SecurityAuditLog.log_password_changed!(user: other_user, request: @request, actor: admin)++ assert_equal admin.id, log.metadata["actor_user_id"]+ end++ test "log_password_changed! does not record an actor for self-service changes" do+ log = SecurityAuditLog.log_password_changed!(user: @user, request: @request, actor: @user)++ assert_nil log.metadata["actor_user_id"]+ end++ test "log_webauthn_credential_added! records the credential id and nickname" do+ credential = @user.webauthn_credentials.create!(+ nickname: "YubiKey",+ credential_id: "credential-added-test",+ public_key: "public-key"+ )++ log = SecurityAuditLog.log_webauthn_credential_added!(user: @user, credential: credential, request: @request)++ assert_equal "webauthn_credential_added", log.event_type+ assert_equal credential.id, log.metadata["credential_id"]+ assert_equal "YubiKey", log.metadata["nickname"]+ assert_equal @user.email, log.user_email+ end++ test "log_webauthn_credential_removed! records the credential id and nickname" do+ credential = @user.webauthn_credentials.create!(+ nickname: "YubiKey",+ credential_id: "credential-removed-test",+ public_key: "public-key"+ )++ log = SecurityAuditLog.log_webauthn_credential_removed!(user: @user, credential: credential, request: @request)++ assert_equal "webauthn_credential_removed", log.event_type+ assert_equal credential.id, log.metadata["credential_id"]+ assert_equal "YubiKey", log.metadata["nickname"]+ end++ # Encrypted-at-rest coverage lives in EncryptionVerificationTest, which+ # skips unless encryption is actually configured — encryption_ready? is+ # false in this test env (no ACTIVE_RECORD_ENCRYPTION_* vars), so a bare+ # assertion here would pass whether or not `encrypts` actually ran.++ test "survives its user being deleted, preserving the user's email" do+ disposable_user = User.create!(+ email: "[email protected]",+ password: "somesecurepassword12345",+ first_name: "Disposable",+ last_name: "User",+ family: families(:dylan_family)+ )+ log = SecurityAuditLog.log_mfa_enabled!(user: disposable_user, request: @request)++ disposable_user.destroy!++ log.reload+ assert_nil log.user_id+ assert_equal "[email protected]", log.user_email+ end+enddiff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 08dce692a9..18362b3e90 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -1517,6 +1517,31 @@ class UserTest < ActiveSupport::TestCaseassert token.reload.revoked_at.present?assert grant.reload.revoked_at.present?end+ test "password_challenge must match the current password when given" do+ @user.assign_attributes(password_challenge: "wrongpassword123", password: "newpassword123")+ assert_not @user.valid?+ assert @user.errors.of_kind?(:password_challenge, :invalid)++ @user.assign_attributes(password_challenge: "", password: "newpassword123")+ assert_not @user.valid?++ @user.assign_attributes(password_challenge: user_password_test, password: "newpassword123")+ assert @user.valid?+ end++ test "password_challenge is not checked when not given" do+ @user.password = "newpassword123"+ assert @user.valid?+ end++ test "password_confirmation must match when given" do+ @user.assign_attributes(password: "newpassword123", password_confirmation: "otherpassword123")+ assert_not @user.valid?+ assert @user.errors.of_kind?(:password_confirmation, :confirmation)++ @user.password_confirmation = "newpassword123"+ assert @user.valid?+ endtest "update_manual_account_order keeps other groups and only accessible accounts" do@user.update_manual_account_order("credit_card", [ accounts(:credit_card).id ])