The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Native 2FA: EE scaffold, TOTP core, two-step login, recovery codes (#77449)
bryanf4d3f6901094
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 648840580ca..6afe479774b 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -453,6 +453,9 @@metabase-enterprise.action-v2.test-util/with-test-tables! clojure.core/letmetabase-enterprise.content-translation.routes-test/with-new-secret-key! clojure.core/fnmetabase-enterprise.entity-retrieval.reconcile-test/with-isolated-index clojure.core/fn+ metabase-enterprise.mfa.enrollment-flow-test/with-fresh-user-session! clojure.core/fn+ metabase-enterprise.mfa.login-flow-test/with-enrolled-rasta! clojure.core/fn+ metabase-enterprise.mfa.recovery-codes-test/with-confirmed-enrollment! clojure.core/fnmetabase-enterprise.serialization.metadata-file-import.wire-format-test/with-tiny-fixture! clojure.core/fnmetabase-enterprise.serialization.test-util/with-dbs clojure.core/fnmetabase-enterprise.serialization.test-util/with-random-dump-dir clojure.core/letdiff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex ed284454e66..110c7599f1b 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2090,6 +2090,7 @@channelconfigevents+ premium-featuresrequestsettingssso@@ -2871,6 +2872,7 @@:uses #{driverpremium-featuresenterprise/advanced-config+ enterprise/mfaenterprise/scimenterprise/semantic-searchenterprise/sso}@@ -3342,6 +3344,22 @@util}:model-imports #{:model/MetabotConversation :model/MetabotFeedback :model/MetabotMessage}}+ enterprise/mfa+ {:team "Graphy"+ :api #{metabase-enterprise.mfa.core+ metabase-enterprise.mfa.init+ metabase-enterprise.mfa.routes}+ :uses #{api+ appearance+ channel+ config+ events+ premium-features+ settings+ sso+ util}+ :model-imports #{:model/AuthIdentity :model/User}}+enterprise/permission-debug{:team "UX West":api #{metabase-enterprise.permission-debug.api}diff --git a/.gitignore b/.gitignoreindex 39846c01cd0..5ca874c6bbd 100644--- a/.gitignore+++ b/.gitignore@@ -204,3 +204,4 @@ __pycache__/# dependency-cruiser outputdependency-graph.json+.playwright-cli/diff --git a/bun.lock b/bun.lockindex 0e74861cd3d..09d16e5a073 100644--- a/bun.lock+++ b/bun.lock@@ -143,6 +143,7 @@"react-innertext": "^1.1.5","react-is": "^18.2.0","react-markdown": "^9.0.0",+ "react-qr-code": "^2.0.15","react-redux": "^9.1.2","react-resizable": "^3.1.3","react-router": "3",@@ -4630,6 +4631,8 @@"qified": ["[email protected]", "", { "dependencies": { "hookified": "^1.12.1" } }, "sha512-Zj6Q/Vc/SQ+Fzc87N90jJUzBzxD7MVQ2ZvGyMmYtnl2u1a07CejAhvtk4ZwASos+SiHKCAIylyGHJKIek75QBw=="],+ "qrcode-generator": ["[email protected]", "", {}, "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g=="],+"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],"query-string": ["[email protected]", "", { "dependencies": { "object-assign": "^4.1.0", "strict-uri-encode": "^1.0.0" } }, "sha1-u7aTucqRXCMlFbIosaArYJBD2+s="],@@ -4702,6 +4705,8 @@"react-number-format": ["[email protected]", "", {}, "sha512-wOmoNZoOpvMminhifQYiYSTCLUDOiUbBunrMrMjA+dV52sY+vck1S4UhR6PkgnoCquvvMSeJjErXZ4qSaWCliA=="],+ "react-qr-code": ["[email protected]", "", { "dependencies": { "prop-types": "^15.8.1", "qrcode-generator": "^2.0.4" }, "peerDependencies": { "react": "*" } }, "sha512-e5nS0UUN22K3Nf8KBRUzemfdJ6OmnN5w+kbnj1lvJaol9RyVRFeGl05bCkxSN2ZegbLxjjYjX1+mmAoX9+fAhw=="],+"react-reconciler": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", "scheduler": "^0.20.2" } }, "sha512-nK6kgY28HwrMNwDnMui3dvm3rCFjZrcGiuwLc5COUipBK5hWHLOxMJhSnSomirqWwjPBJKV1QcbkI0VJr7Gl1Q=="],"react-redux": ["[email protected]", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.3", "use-sync-external-store": "^1.0.0" } }, "sha512-0OA4dhM1W48l3uzmv6B7TXPCGmokUU4p1M44DGN2/D9a1FjVPukVjER1PcPX97jIg6aUeLq1XJo1IpfbgULn0w=="],diff --git a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj b/enterprise/backend/src/metabase_enterprise/analytics/stats.cljindex e05430b7c03..2c801c2e49a 100644--- a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj+++ b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.analytics.stats(:require[metabase-enterprise.advanced-config.settings :as advanced-config.settings]+ [metabase-enterprise.mfa.core :as mfa][metabase-enterprise.scim.core :as scim][metabase-enterprise.semantic-search.core :as semantic-search][metabase-enterprise.sso.settings :as ee-sso-settings]@@ -22,6 +23,12 @@{:name :scim:available (premium-features/enable-scim?):enabled (boolean (scim/scim-enabled))}+ ;; the `and` upholds this ping's enabled⊆available invariant: MFA enforcement survives a+ ;; license lapse (fail-closed), so mfa-enabled? alone can be true on an unlicensed instance+ {:name :multi-factor-auth+ :available (premium-features/enable-multi-factor-auth?)+ :enabled (and (premium-features/enable-multi-factor-auth?)+ (mfa/mfa-enabled?))}{:name :sandboxes:available (and (premium-features/enable-official-collections?)(t2/exists? :model/Database :engine [:in (descendants driver/hierarchy :sql)]))diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.cljindex 9b068d27335..cc29f573dd2 100644--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj@@ -30,6 +30,7 @@[metabase-enterprise.metabot-analytics.api][metabase-enterprise.metabot.api][metabase-enterprise.metabot.api.routes]+ [metabase-enterprise.mfa.routes][metabase-enterprise.permission-debug.api][metabase-enterprise.remote-sync.api][metabase-enterprise.replacement.api]@@ -132,6 +133,11 @@"/logs" (premium-handler 'metabase-enterprise.advanced-config.api.logs :audit-app)"/metabot" (premium-handler 'metabase-enterprise.metabot.api :metabot-v3)"/metabot-analytics" (premium-handler metabase-enterprise.metabot-analytics.api/routes :audit-app)+ ;; Deliberately NOT premium-handler-gated: managing an existing enrollment (disable/status/recover)+ ;; must keep working through a license lapse — the fail-closed rationale applies here too, since+ ;; a lapsed-license user still needs to manage their enrolled second factor. The :multi-factor-auth+ ;; feature gates setup paths. MFA verification lives under /api/session/mfa/* (OSS mount).+ "/mfa" metabase-enterprise.mfa.routes/routes"/permission_debug" (premium-handler metabase-enterprise.permission-debug.api/routes :advanced-permissions);; TODO (Ngoc 2026-03-25) -- use :transforms-advanced feature flag once it exists"/transforms" (premium-handler metabase-enterprise.transforms.api/routes :transforms-python)diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.cljindex 48a421ba076..e0aef1c4c4c 100644--- a/enterprise/backend/src/metabase_enterprise/core/init.clj+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj@@ -19,6 +19,7 @@[metabase-enterprise.mcp.init][metabase-enterprise.memoize-monitor.init][metabase-enterprise.metabot.init]+ [metabase-enterprise.mfa.init][metabase-enterprise.remote-sync.init][metabase-enterprise.scim.init][metabase-enterprise.security-center.init]diff --git a/enterprise/backend/src/metabase_enterprise/mfa/core.clj b/enterprise/backend/src/metabase_enterprise/mfa/core.cljnew file mode 100644index 00000000000..ccd969183e3--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/core.clj@@ -0,0 +1,69 @@+(ns metabase-enterprise.mfa.core+ "Public API of the mfa module. All cross-boundary entry points live here.++ Consumers outside this module must go through this namespace; they must not require mfa.gate,+ or mfa.settings directly."+ (:require+ [metabase-enterprise.mfa.gate :as gate]+ [metabase-enterprise.mfa.settings]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.channel.email.messages :as messages]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log]+ [potemkin :as p]+ [toucan2.core :as t2]))++(comment metabase-enterprise.mfa.settings/keep-me)++(p/import-vars+ [metabase-enterprise.mfa.settings+ mfa-enforcement+ mfa-enabled?])++(defenterprise apply-mfa-gate+ "Decide whether a successful first-factor login must complete a second factor before a session is+ created. Sets `:mfa/pending?` (which suppresses session creation in the `login!` pipeline) and,+ for challenged providers, attaches `:mfa/first-factor` and `:mfa/methods` so the OSS session API can+ sign the relay token.++ Uses `:feature :none` deliberately: enforcement must not depend on the current token, so a lapsed+ license never silently stops challenging enrolled users. The token instead gates setup — setting+ `mfa-enforcement` to a non-`:off` value and (in later PRs) starting new enrollments."+ :feature :none+ [provider login-result]+ (gate/apply-mfa-gate provider login-result))++(defenterprise verify-second-factor!+ "Verify a second-factor code (TOTP, recovery, or emailed one-time code) for user-id, atomically+ consuming it plus the challenge jti. Returns boolean.++ OSS fallback returns false — OSS can never have issued a challenge token (the MFA gate lives in+ EE), so this is unreachable in practice."+ :feature :none+ [user-id code jti]+ (verification/verify-attempt! user-id code jti))++(defenterprise send-mfa-email-otp!+ "Generate + email a one-time fallback code for user-id's confirmed enrollment; rejects a jti that+ already minted a session.++ OSS fallback throws (unreachable, as above)."+ :feature :none+ [user-id jti]+ ;; a token that already minted a session must not keep sending codes for its remaining TTL+ (when (verification/jti-consumed? user-id jti)+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ (let [code (or (verification/set-email-otp! user-id)+ ;; nil = no confirmed enrollment — same message, no oracle semantics+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ user-email (t2/select-one-fn :email :model/User :id user-id)]+ (try+ (messages/send-mfa-login-code-email! user-email code)+ (catch Throwable e+ (log/warn e "Failed to send MFA email OTP")+ ;; don't tell an unauthenticated caller "the code exists but the email failed"+ (throw (ex-info (tru "Failed to send the sign-in code. Please try again or contact your administrator.")+ {:status-code 500}))))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.cljnew file mode 100644index 00000000000..9c08b54ea14--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj@@ -0,0 +1,113 @@+(ns metabase-enterprise.mfa.enrollment+ "Manages the lifecycle of a user's TOTP enrollment: starting, confirming, disabling, and+ regenerating recovery codes. State is stored in the user's `auth_identity` row (provider+ `\"totp\"`) inside the `:credentials` JSON column.++ A user is enrolled only once `:confirmed_at` is present. Encryption at rest is the model's+ responsibility, not this namespace's: `:credentials` is whole-column encrypted-json (see the+ `:model/AuthIdentity` transforms) and covered by `rotate-encryption-key`, so code here reads and+ writes plaintext maps. Do NOT `maybe-encrypt` individual fields — a field encrypted inside the+ JSON is invisible to key rotation and dies with the old key.++ Verification (proving you hold the factor) lives in+ `metabase-enterprise.mfa.verification`."+ (:require+ [java-time.api :as t]+ [metabase-enterprise.mfa.recovery-codes :as recovery-codes]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.util.password :as u.password]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn enrolled-method+ "The user's confirmed MFA method keyword (currently only `:totp`), or nil if not enrolled."+ [user-id]+ (when (some-> (verification/totp-identity user-id) verification/confirmed?)+ :totp))++;;; -------------------------------------------------- Enrollment lifecycle --------------------------------------------------++(defn pending?+ "Does `user-id` have a started-but-unconfirmed enrollment?"+ [user-id]+ (boolean (some-> (verification/totp-identity user-id) verification/confirmed? not)))++(defn start-enrollment!+ "Start (or restart a pending) TOTP enrollment for `user-id`: generate a fresh secret and store it+ pending confirmation (the model encrypts the credentials column at rest). Returns the plaintext+ secret for QR display, or nil when the user already has a *confirmed* enrollment (disable it+ first — silently replacing a working second factor would let a session thief swap in their own+ authenticator)."+ [user-id]+ (t2/with-transaction [_conn]+ ;; serialize concurrent enrollments for the same user by locking the User row: with no totp+ ;; row yet there is nothing else to lock, and racing inserts would abort the transaction on+ ;; the unique (user_id, provider) constraint+ (t2/select-one [:model/User :id] :id user-id {:for :update})+ (let [auth-identity (t2/select-one :model/AuthIdentity+ :user_id user-id+ :provider "totp"+ {:for :update})]+ (when-not (some-> auth-identity verification/confirmed?)+ (let [secret (totp/generate-secret)+ credentials {:secret secret}]+ (if auth-identity+ (t2/update! :model/AuthIdentity (:id auth-identity) {:credentials credentials})+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :credentials credentials}))+ secret)))))++(defn confirm-enrollment!+ "Confirm a pending enrollment by verifying a live `code` against the pending secret. On success+ marks the enrollment confirmed, consumes the code's time step (so it can't also complete a+ login), generates the recovery-code set, and returns the plaintext recovery codes. Nil on+ failure or when there is no pending enrollment."+ [user-id code]+ (t2/with-transaction [_conn]+ (when-let [auth-identity (t2/select-one :model/AuthIdentity+ :user_id user-id+ :provider "totp"+ {:for :update})]+ (when-not (verification/confirmed? auth-identity)+ (when-let [secret (verification/stored-secret auth-identity)]+ (when-let [step (totp/matching-time-step secret code)]+ (let [codes (recovery-codes/generate-codes)]+ (t2/update! :model/AuthIdentity (:id auth-identity)+ {:confirmed_at (t/instant)+ :credentials (assoc (:credentials auth-identity)+ :last_used_step step+ :recovery_codes (mapv u.password/hash-bcrypt codes))})+ codes)))))))++(defn disable!+ "Remove `user-id`'s TOTP enrollment entirely (re-auth is the caller's responsibility). True when+ something was removed."+ [user-id]+ (pos? (t2/delete! :model/AuthIdentity :user_id user-id :provider "totp")))++;;; -------------------------------------------------- Recovery-code management --------------------------------------------------++(defn reset-recovery-codes!+ "Generate a fresh recovery-code set for `user-id`'s confirmed enrollment, replacing (and thereby+ invalidating) the entire previous set. Returns the plaintext codes — the only time they exist in+ plaintext; only bcrypt hashes are stored. Nil when the user has no confirmed enrollment."+ [user-id]+ (t2/with-transaction [_conn]+ (when-let [auth-identity (t2/select-one :model/AuthIdentity+ :user_id user-id+ :provider "totp"+ {:for :update})]+ (when (verification/confirmed? auth-identity)+ (let [codes (recovery-codes/generate-codes)]+ (t2/update! :model/AuthIdentity (:id auth-identity)+ {:credentials (assoc (:credentials auth-identity)+ :recovery_codes (mapv u.password/hash-bcrypt codes))})+ codes)))))++(defn recovery-codes-remaining+ "How many unused recovery codes `user-id` has left."+ [user-id]+ (count (get-in (verification/totp-identity user-id) [:credentials :recovery_codes])))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/gate.clj b/enterprise/backend/src/metabase_enterprise/mfa/gate.cljnew file mode 100644index 00000000000..6295c35f0b9--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/gate.clj@@ -0,0 +1,63 @@+(ns metabase-enterprise.mfa.gate+ "Login-flow gate for native multi-factor authentication.++ Session-issuance coverage, decided per provider (the login! pipeline is the only place+ interactive sessions are minted; API keys and MCP OAuth never pass through it):++ - `:provider/password`, `:provider/ldap` — challenged (the OSS session API signs the relay token+ from :mfa/first-factor; no token is issued here).+ - `:provider/emailed-secret-password-reset` — the password change completes but no session is+ issued for an enrolled user; they go through normal, gated login. Otherwise anyone who can+ trigger a reset email routes around the second factor.+ - `:provider/support-access-grant` — exempt: support sessions are admin-granted, time-boxed, and+ audited, and Metabase staff cannot hold the user's second factor.+ - SSO providers — exempt: the identity provider owns MFA there."+ (:require+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.settings :as mfa.settings]+ [metabase.channel.settings :as channel.settings]))++(set! *warn-on-reflection* true)++(defn- available-methods+ "Second-factor methods the challenge UI may offer. Email OTP is a fallback to TOTP, advertised+ only when the instance can actually send email."+ []+ (cond-> ["totp"]+ (channel.settings/email-configured?) (conj "email")))++(def ^:private challenged-providers+ #{:provider/password :provider/ldap})++(def ^:private session-suppressed-providers+ #{:provider/emailed-secret-password-reset})++(defn apply-mfa-gate+ "Decide whether a successful first-factor login must complete a second factor before a session is+ created. Sets `:mfa/pending?` (which suppresses session creation in the `login!` pipeline) and,+ for challenged providers, attaches `:mfa/first-factor` (the provider keyword) and `:mfa/methods` so+ the OSS session API can sign the relay token."+ [provider login-result]+ (if-not (and (true? (:success? login-result))+ (:user login-result)+ (mfa.settings/mfa-enabled?))+ login-result+ (let [user-id (get-in login-result [:user :id])+ method (when user-id (enrollment/enrolled-method user-id))]+ (cond+ (nil? method)+ login-result++ (contains? challenged-providers provider)+ (assoc login-result+ :success? :mfa-required+ :mfa/pending? true+ :mfa/methods (available-methods)+ :mfa/first-factor provider)++ (contains? session-suppressed-providers provider)+ (assoc login-result+ :mfa/pending? true)++ :else+ login-result))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/init.clj b/enterprise/backend/src/metabase_enterprise/mfa/init.cljnew file mode 100644index 00000000000..8198859a93f--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/init.clj@@ -0,0 +1,10 @@+(ns metabase-enterprise.mfa.init+ "Loads MFA namespaces that must be present at launch for side effects."+ (:require+ ;; core loads gate transitively+ [metabase-enterprise.mfa.core]+ [metabase-enterprise.mfa.settings]+ ;; verification carries the (derive :provider/totp ...) that AuthIdentity validation needs;+ ;; require it explicitly: core requires verification, but an explicit require is more+ ;; robust and clearly documents the side-effect dependency+ [metabase-enterprise.mfa.verification]))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/management.clj b/enterprise/backend/src/metabase_enterprise/mfa/management.cljnew file mode 100644index 00000000000..21c8631cc5d--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/management.clj@@ -0,0 +1,212 @@+(ns metabase-enterprise.mfa.management+ "/api/ee/mfa endpoints that require a signed-in user (mounted behind auth in+ `metabase-enterprise.mfa.routes`).++ Feature gating follows the fail-closed license-lapse split: *starting* an enrollment requires+ the `:multi-factor-auth` feature (setup), while disable, status, and recovery-code regeneration+ never do — a lapsed license must not strand an enrolled user.++ Re-auth model: enroll with the factor you have (your password — local hash for password users,+ LDAP bind for LDAP users); disable/regenerate with the factor you're managing (a fresh TOTP or+ recovery code), so a stolen password alone can never remove or weaken 2FA."+ (:require+ [clojure.string :as str]+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.settings :as mfa.settings]+ [metabase-enterprise.mfa.throttling :as mfa.throttling]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.appearance.core :as appearance]+ [metabase.channel.email.messages :as messages]+ [metabase.events.core :as events]+ [metabase.premium-features.core :as premium-features]+ [metabase.sso.core :as sso]+ [metabase.util.encryption :as encryption]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.schema :as ms]+ [metabase.util.password :as u.password]+ [throttle.core :as throttle]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++;;; -------------------------------------------------- Helpers --------------------------------------------------++(def ^:private throttlers+ ;; second-factor re-auth takes a 6-digit code, so these paths need brute-force limits like+ ;; /verify. Only failed attempts count (see `mfa.throttling`).+ {:enroll (throttle/make-throttler :user-id, :attempts-threshold 5)+ :regenerate (throttle/make-throttler :user-id, :attempts-threshold 5)+ :disable (throttle/make-throttler :user-id, :attempts-threshold 5)})++(defn- throttled [throttler-key f]+ (mfa.throttling/call-with-failure-throttling+ [[(throttlers throttler-key) api/*current-user-id*]]+ f))++(defn- verify-user-password+ "Re-verify the signed-in user's first-factor password, dispatched by how they authenticate:+ against the local hash for password users, by LDAP bind for LDAP-only users.++ Rejects blank passwords itself rather than trusting callers' schemas: an empty password sent to+ `ldap/bind?` is an *anonymous bind*, which succeeds on directories that allow it."+ [user-id password]+ (boolean+ (when-not (str/blank? password)+ (or (when-let [{:keys [password_hash password_salt]}+ (t2/select-one-fn :credentials :model/AuthIdentity :user_id user-id :provider "password")]+ (and password_hash (u.password/verify-password password password_salt password_hash)))+ (when (sso/ldap-enabled)+ (when-let [user-email (t2/select-one-fn :email :model/User user-id)]+ (when-let [user-info (sso/find-user user-email)]+ (sso/verify-password user-info password))))))))++;; Notification emails here are fire-and-log by construction: the messages/send-mfa-*-email!+;; senders route through email/send-message!, which catches and logs delivery failures — so an+;; unreachable SMTP server never fails an operation that has already committed.++(defn- invalid-code-ex []+ (ex-info (tru "Invalid authentication code.") {:status-code 400}))++;;; -------------------------------------------------- Enrollment --------------------------------------------------++(api.macros/defendpoint :post "/enroll" :- [:map+ [:secret ms/NonBlankString]+ [:otpauth_uri ms/NonBlankString]]+ "Start TOTP enrollment for the current user. Requires the account password (LDAP users re-bind+ against the directory) and the `:multi-factor-auth` feature. Returns the Base32 `secret` and an+ `otpauth_uri` for QR display; enrollment is not active until confirmed with a live code."+ [_route-params+ _query-params+ {:keys [password]} :- [:map [:password ms/NonBlankString]]]+ (premium-features/assert-has-feature :multi-factor-auth (tru "Multi-factor authentication"))+ (when-not (mfa.settings/mfa-enabled?)+ (throw (ex-info (tru "Two-factor authentication is not enabled on this instance.")+ {:status-code 400})))+ (throttled :enroll+ (fn []+ (when-not (verify-user-password api/*current-user-id* password)+ ;; 400, not 401: the session is fine, the re-auth input is wrong. The FE (and any+ ;; well-behaved client) treats a 401 as an expired session and bounces to login.+ (throw (ex-info (tru "Invalid password.")+ {:status-code 400+ :errors {:password (tru "Invalid password.")}})))+ (let [secret (or (enrollment/start-enrollment! api/*current-user-id*)+ (throw (ex-info (tru "Two-factor authentication is already set up. Disable it before re-enrolling.")+ {:status-code 400})))+ user-email (t2/select-one-fn :email :model/User api/*current-user-id*)]+ {:secret secret+ :otpauth_uri (totp/otpauth-uri {:issuer (or (appearance/site-name) "Metabase")+ :account user-email+ :secret secret})}))))++(api.macros/defendpoint :post "/enroll/confirm" :- [:map+ [:recovery_codes [:sequential ms/NonBlankString]]]+ "Confirm TOTP enrollment by verifying a code from the authenticator app. Activates the second+ factor and returns the single-use recovery codes — the only time they exist in plaintext."+ [_route-params+ _query-params+ {:keys [code]} :- [:map [:code ms/NonBlankString]]]+ (premium-features/assert-has-feature :multi-factor-auth (tru "Multi-factor authentication"))+ (let [codes (throttled :enroll+ (fn []+ (or (enrollment/confirm-enrollment! api/*current-user-id* code)+ (throw (invalid-code-ex)))))+ user (t2/select-one :model/User :id api/*current-user-id*)]+ (messages/send-mfa-enabled-email! (:email user))+ (events/publish-event! :event/mfa-enrolled {:object user})+ {:recovery_codes codes}))++(api.macros/defendpoint :post "/disable" :- nil+ "Disable two-factor authentication for the current user. Re-auth is a fresh second factor — a+ TOTP code or an unused recovery code — never just the password."+ [_route-params+ _query-params+ {:keys [code]} :- [:map [:code ms/NonBlankString]]]+ (throttled :disable+ (fn []+ ;; one transaction so a consumed recovery code and the enrollment removal land together+ (t2/with-transaction [_conn]+ (when-not (verification/verify-attempt! api/*current-user-id* code nil)+ (throw (invalid-code-ex)))+ (enrollment/disable! api/*current-user-id*))))+ (let [user (t2/select-one :model/User :id api/*current-user-id*)]+ (messages/send-mfa-disabled-email! (:email user))+ (events/publish-event! :event/mfa-disabled {:object user}))+ api/generic-204-no-content)++(api.macros/defendpoint :get "/status" :- [:map+ [:mfa_enabled :boolean]+ [:enrolled :boolean]+ [:pending :boolean]+ [:method [:maybe :string]]+ [:recovery_codes_remaining :int]]+ "The current user's MFA status, for the account-settings UI."+ []+ (let [user-id api/*current-user-id*+ method (enrollment/enrolled-method user-id)]+ {:mfa_enabled (mfa.settings/mfa-enabled?)+ :enrolled (boolean method)+ :pending (enrollment/pending? user-id)+ :method (some-> method name)+ :recovery_codes_remaining (enrollment/recovery-codes-remaining user-id)}))++;;; -------------------------------------------------- Admin --------------------------------------------------++(api.macros/defendpoint :post "/admin/remove" :- nil+ "Admin: remove a user's two-factor enrollment entirely — the lockout escape hatch for a lost+ authenticator with no recovery codes. Never feature-gated (a lapsed license must not make+ lockouts permanent). The affected user is notified by email. They re-enroll from scratch —+ there is nothing to \"reset\", the secret lives on their device."+ [_route-params+ _query-params+ {user-id :user_id} :- [:map [:user_id ms/PositiveInt]]]+ (api/check-superuser)+ (when (enrollment/disable! user-id)+ (let [user (t2/select-one :model/User :id user-id)]+ (messages/send-mfa-removed-by-admin-email! (:email user))+ (events/publish-event! :event/mfa-disabled {:object user})))+ api/generic-204-no-content)++(def ^:private unenrolled-user-where+ ;; active personal users without a confirmed TOTP enrollment; enrollment state is the+ ;; auth_identity.confirmed_at COLUMN (queryable), not the encrypted credentials JSON+ [:and+ [:= :core_user.is_active true]+ [:= :core_user.type "personal"]+ [:not [:exists {:select [1]+ :from [:auth_identity]+ :where [:and+ [:= :auth_identity.user_id :core_user.id]+ [:= :auth_identity.provider "totp"]+ [:not= :auth_identity.confirmed_at nil]]}]]])++(api.macros/defendpoint :get "/admin/overview" :- [:map+ [:encryption_key_set :boolean]+ [:enrolled_count :int]+ [:unenrolled_count :int]]+ "Admin: enrollment overview — how many users have (and haven't) set up a second factor, and+ whether the instance encrypts secrets at rest."+ []+ (api/check-superuser)+ {:encryption_key_set (encryption/default-encryption-enabled?)+ :enrolled_count (t2/count :model/AuthIdentity :provider "totp" :confirmed_at [:not= nil])+ :unenrolled_count (t2/count :model/User {:where unenrolled-user-where})})++;;; -------------------------------------------------- Recovery codes --------------------------------------------------++(api.macros/defendpoint :post "/recovery-codes" :- [:map [:recovery_codes [:sequential ms/NonBlankString]]]+ "Regenerate the current user's recovery codes, invalidating the entire previous set. Re-auth is a+ fresh second factor — a TOTP code or an unused recovery code — so a stolen password alone can+ never rotate the codes. The plaintext codes are returned exactly once; only hashes are stored."+ [_route-params+ _query-params+ {:keys [code]} :- [:map [:code ms/NonBlankString]]]+ (throttled :regenerate+ (fn []+ (t2/with-transaction [_conn]+ (when-not (verification/verify-attempt! api/*current-user-id* code nil)+ (throw (invalid-code-ex)))+ {:recovery_codes (enrollment/reset-recovery-codes! api/*current-user-id*)}))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/recovery_codes.clj b/enterprise/backend/src/metabase_enterprise/mfa/recovery_codes.cljnew file mode 100644index 00000000000..c2ee8151fb8--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/recovery_codes.clj@@ -0,0 +1,34 @@+(ns metabase-enterprise.mfa.recovery-codes+ "Recovery-code generation and format. Codes are single-use fallbacks for a lost authenticator:+ generated from a CSPRNG, shown to the user exactly once, and stored only as bcrypt hashes — a+ recovery code is only ever compared, never recovered, so hashed storage is safe even when no+ `MB_ENCRYPTION_SECRET_KEY` is set."+ (:import+ (java.security SecureRandom)))++(set! *warn-on-reflection* true)++(def num-codes+ "How many recovery codes a user gets per set."+ 10)++;; no ambiguous chars (0/o, 1/l/i) — users type these from a printout+(def ^:private alphabet "abcdefghjkmnpqrstvwxyz23456789")++(def code-pattern+ "What a recovery code looks like: two 5-char groups, ~49 bits of entropy."+ (re-pattern (format "[%s]{5}-[%s]{5}" alphabet alphabet)))++(defn recovery-code?+ "Is `s` shaped like a recovery code (as opposed to a 6-digit TOTP code)?"+ [s]+ (boolean (and (string? s) (re-matches code-pattern s))))++(defn- random-group ^String [^SecureRandom rng]+ (apply str (repeatedly 5 #(nth alphabet (.nextInt rng (count alphabet))))))++(defn generate-codes+ "A fresh set of [[num-codes]] plaintext recovery codes."+ []+ (let [rng (SecureRandom.)]+ (vec (repeatedly num-codes #(str (random-group rng) "-" (random-group rng))))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/routes.clj b/enterprise/backend/src/metabase_enterprise/mfa/routes.cljnew file mode 100644index 00000000000..6d55f757aa3--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/routes.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.mfa.routes+ "Ring handler for /api/ee/mfa. Mounted without a premium-feature gate: managing an existing+ enrollment (disable/status/recover) must survive license lapse — the feature check guards setup+ paths. All routes here require a session; MFA verification lives under /api/session/mfa/* and is+ mounted there without an auth requirement (the caller is mid-login)."+ (:require+ [metabase-enterprise.mfa.management]+ [metabase.api.macros :as api.macros]+ [metabase.api.routes.common :refer [+auth]]))++(comment metabase-enterprise.mfa.management/keep-me)++(def ^{:arglists '([request respond raise])} routes+ "/api/ee/mfa routes"+ (+auth (api.macros/ns-handler 'metabase-enterprise.mfa.management)))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/settings.clj b/enterprise/backend/src/metabase_enterprise/mfa/settings.cljnew file mode 100644index 00000000000..73131f3cb0b--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/settings.clj@@ -0,0 +1,38 @@+(ns metabase-enterprise.mfa.settings+ "Settings for native multi-factor authentication.++ `mfa-enforcement` is deliberately NOT `:feature`-gated on read: `defsetting`'s `:feature` option+ returns the default value when the feature is absent, which on license lapse would read as+ `:off` and silently fail open. Instead the feature check lives on the write path — and only for+ turning the setting ON (any value other than `:off`), so an admin on a lapsed license can always+ set enforcement back to `:off`."+ (:require+ [metabase.premium-features.core :as premium-features]+ [metabase.settings.core :as setting :refer [defsetting]]+ [metabase.util.i18n :refer [deferred-tru tru]]))++(set! *warn-on-reflection* true)++(def ^:private valid-enforcement-values #{:off :optional})++(defsetting mfa-enforcement+ (deferred-tru "Controls whether two-factor authentication is available to users. :off disables it entirely; :optional allows users to enroll voluntarily.")+ :visibility :public+ :type :keyword+ :default :off+ :export? false+ :audit :raw-value+ :setter (fn [new-value]+ (let [new-value (keyword new-value)]+ (when-not (contains? valid-enforcement-values new-value)+ (throw (ex-info (tru "Invalid value for mfa-enforcement: {0}. Allowed values are :off and :optional. (:required is reserved for a future release.)"+ new-value)+ {:status-code 400})))+ (when (not= new-value :off)+ (premium-features/assert-has-feature :multi-factor-auth (tru "Multi-factor authentication")))+ (setting/set-value-of-type! :keyword :mfa-enforcement new-value))))++(defn mfa-enabled?+ "True when MFA is available to users at all (enforcement is not :off)."+ []+ (not= (mfa-enforcement) :off))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/throttling.clj b/enterprise/backend/src/metabase_enterprise/mfa/throttling.cljnew file mode 100644index 00000000000..5e6b68d8acd--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/throttling.clj@@ -0,0 +1,41 @@+(ns metabase-enterprise.mfa.throttling+ "Brute-force throttling helpers shared by the MFA endpoints.++ Second-factor codes are 6 digits, so these limits are load-bearing. Verification-style paths+ must count only *failed* attempts (like the first-factor login throttle) — counting successes+ locks out a legitimately busy user. Send-style paths (emailing a code) count every call, because+ there the success is the thing being rate-limited."+ (:require+ [metabase.config.core :as config]+ [throttle.core :as throttle]))++(set! *warn-on-reflection* true)++(def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle))++(defn check+ "Record an attempt on `throttler` for `throttle-key` and throw when over the limit. Counts every+ call, success or failure — use only where success itself must be rate-limited (e.g. sends).+ No-op when `MB_DISABLE_SESSION_THROTTLE` is set."+ [throttler throttle-key]+ (when-not throttling-disabled?+ (throttle/check throttler throttle-key)))++(defn call-with-failure-throttling+ "Run `f` guarded by `pairs` of `[throttler throttle-key]`. Only a thrown exception counts as an+ attempt; successful calls are free. No-op when `MB_DISABLE_SESSION_THROTTLE` is set."+ [pairs f]+ (if throttling-disabled?+ (f)+ (try+ ((reduce (fn [g [throttler throttle-key]]+ (fn [] (throttle/do-with-throttling throttler throttle-key g)))+ f+ pairs))+ (catch clojure.lang.ExceptionInfo e+ ;; `throttle/do-with-throttling`'s over-the-limit exception carries `:errors` but no+ ;; `:status-code` (unlike `throttle/check`'s), which would surface as a 500+ (let [data (ex-data e)]+ (if (and (:errors data) (nil? (:status-code data)))+ (throw (ex-info (ex-message e) (assoc data :status-code 400) e))+ (throw e)))))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/totp.clj b/enterprise/backend/src/metabase_enterprise/mfa/totp.cljnew file mode 100644index 00000000000..c13ea90ab6a--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/totp.clj@@ -0,0 +1,108 @@+(ns metabase-enterprise.mfa.totp+ "RFC 6238 TOTP (time-based one-time password) primitives for native MFA.++ Deliberately has no third-party TOTP dependency: HMAC comes from `buddy-core` and Base32 secret+ encoding from Apache Commons Codec, both already on the classpath. Codes are SHA1 / 6-digit /+ 30-second period, which is what Google Authenticator, 1Password, Authy, etc. default to.++ Validation accepts a ±1 time-step window. RFC 6238 §5.2 recommends tolerating only *earlier*+ steps (network delay); we also accept one step ahead so clients whose clock runs slightly fast+ can still log in, which is the norm among large providers. Replay protection (callers reject any+ step at or before the last accepted one — see `metabase-enterprise.mfa.enrollment`) caps the+ exposure this adds."+ (:require+ [buddy.core.mac :as mac]+ [clojure.string :as str]+ [metabase.util :as u])+ (:import+ (java.net URLEncoder)+ (java.nio ByteBuffer)+ (java.security MessageDigest SecureRandom)+ (org.apache.commons.codec.binary Base32)))++(set! *warn-on-reflection* true)++(def ^:private ^:const time-step-seconds 30)+(def ^:private ^:const num-digits 6)+(def ^:private ^:const modulo 1000000) ; 10^num-digits+;; 160-bit secret, the size RFC 4226 recommends for HMAC-SHA1.+(def ^:private ^:const secret-num-bytes 20)++(defn generate-secret+ "Generate a new random Base32-encoded TOTP secret (uppercase, unpadded), suitable for an+ `otpauth://` URI / QR code."+ ^String []+ (let [bytes (byte-array secret-num-bytes)]+ (.nextBytes (SecureRandom.) bytes)+ (-> (.encodeToString (Base32.) bytes)+ (str/replace "=" ""))))++(defn- decode-secret ^bytes [^String secret]+ (.decode (Base32.) (u/upper-case-en secret)))++(defn- counter->bytes ^bytes [^long counter]+ (-> (ByteBuffer/allocate 8) (.putLong counter) .array))++(defn- hotp+ "HOTP value (RFC 4226) for Base32 `secret` and integer `counter`."+ ^long [^String secret ^long counter]+ (let [^bytes hs (mac/hash (counter->bytes counter) {:key (decode-secret secret) :alg :hmac+sha1})+ offset (int (bit-and (aget hs (dec (alength hs))) 0xf))+ binary (bit-or (bit-shift-left (bit-and (long (aget hs offset)) 0x7f) 24)+ (bit-shift-left (bit-and (long (aget hs (inc offset))) 0xff) 16)+ (bit-shift-left (bit-and (long (aget hs (+ offset 2))) 0xff) 8)+ (bit-and (long (aget hs (+ offset 3))) 0xff))]+ (mod binary modulo)))++(defn- format-code ^String [^long code]+ (format (str "%0" num-digits "d") code))++(defn current-time-step+ "The current 30-second time-step counter."+ []+ (quot (quot (System/currentTimeMillis) 1000) time-step-seconds))++(defn code-for-unix-time+ "TOTP code for `secret` at a given absolute `unix-seconds`. Exposed mainly for deterministic tests."+ ^String [^String secret ^long unix-seconds]+ (format-code (hotp secret (quot unix-seconds time-step-seconds))))++(defn generate-code+ "Current TOTP code for `secret` (for tests and enrollment-confirmation helpers)."+ ^String [^String secret]+ (code-for-unix-time secret (quot (System/currentTimeMillis) 1000)))++(defn- code-matches-step?+ "Constant-time comparison of `code` against the TOTP for `secret` at `step`."+ [^String secret ^String code ^long step]+ ;; the ^String call-site hint is load-bearing: format-code's return hint is lost through its+ ;; primitive-arg (^long) signature, leaving a reflective .getBytes on every comparison+ (MessageDigest/isEqual (.getBytes ^String (format-code (hotp secret step)) "UTF-8")+ (.getBytes code "UTF-8")))++(defn matching-time-step+ "The time step whose TOTP code for `secret` equals `code`, searching the current step and one step+ either side. Returns nil when nothing matches. Callers enforcing one-time use (RFC 6238 §5.2)+ compare the returned step against the last accepted one."+ [^String secret code]+ (when (and secret (string? code) (re-matches #"\d{6}" code))+ (let [now (current-time-step)]+ (some (fn [^long step]+ (when (code-matches-step? secret code step)+ step))+ [(dec now) now (inc now)]))))++(defn valid-code?+ "True if `code` matches the TOTP for `secret` within the validation window. Use+ [[matching-time-step]] instead wherever replay protection applies."+ [^String secret code]+ (some? (matching-time-step secret code)))++(defn otpauth-uri+ "Build an `otpauth://totp/...` URI for QR-code enrollment."+ ^String [{:keys [issuer account secret]}]+ ;; URLEncoder form-encodes spaces as "+", which authenticator apps display literally+ ;; ("Acme+Analytics"); otpauth URIs need percent-encoding.+ (let [enc (fn [s] (str/replace (URLEncoder/encode (str s) "UTF-8") "+" "%20"))]+ (format "otpauth://totp/%s:%s?secret=%s&issuer=%s&digits=%d&period=%d"+ (enc issuer) (enc account) secret (enc issuer) num-digits time-step-seconds)))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/verification.clj b/enterprise/backend/src/metabase_enterprise/mfa/verification.cljnew file mode 100644index 00000000000..f95c9705036--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/verification.clj@@ -0,0 +1,156 @@+(ns metabase-enterprise.mfa.verification+ "Proves that a caller holds a registered second factor — 'something you have'. Owns the+ verification engine: accepting a TOTP code, a single-use recovery code, or a pending emailed+ one-time code, atomically consuming whichever credential is presented so a replayed or+ concurrently submitted credential can never pass twice.++ Row-level helpers (`provider-name`, `totp-identity`, `confirmed?`, `stored-secret`) live here+ as the lower layer; `metabase-enterprise.mfa.enrollment` requires this namespace for them.++ One-time-use state lives in the same `:credentials` JSON column as the enrollment secret:+ - `:last_used_step` — last accepted TOTP time step; RFC 6238 §5.2 requires strict monotonicity.+ - `:used_jtis` — `[{:jti ... :exp ...}]` consumed challenge-token ids, pruned by expiry.+ - `:recovery_codes` — bcrypt hashes of unused recovery codes; removed on use.+ - `:email_otp` — `{:hash ... :exp ...}` bcrypt hash of a pending emailed code; removed on use."+ (:require+ [metabase-enterprise.mfa.recovery-codes :as recovery-codes]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.util.password :as u.password]+ [toucan2.core :as t2])+ (:import+ (java.security SecureRandom)))++(set! *warn-on-reflection* true)++;; Register "totp" in the AuthIdentity provider hierarchy so the model's before-insert/-update+;; validation accepts its rows (the default `validate` method applies).+(derive :provider/totp :metabase.auth-identity.provider/provider)++(def ^:private provider-name "totp")++(defn totp-identity+ "The AuthIdentity row for `user-id`'s TOTP enrollment, or nil."+ [user-id]+ (t2/select-one :model/AuthIdentity :user_id user-id :provider provider-name))++(defn confirmed?+ "Has `auth-identity` been confirmed (i.e. is it a usable second factor)?++ Confirmation lives in the `confirmed_at` COLUMN (not the encrypted credentials JSON) so+ enrollment state is queryable in SQL; rows written before the column existed are covered by+ the BackfillMfaConfirmedAt migration."+ [auth-identity]+ (some? (:confirmed_at auth-identity)))++(defn stored-secret+ "The TOTP secret from `auth-identity`'s credentials, or nil."+ [auth-identity]+ (get-in auth-identity [:credentials :secret]))++(defn- jti-used? [credentials jti]+ (boolean (some #(= (:jti %) jti) (:used_jtis credentials))))++(defn jti-consumed?+ "Has this challenge `jti` already been consumed by a successful verification for `user-id`?"+ [user-id jti]+ (boolean (some-> (totp-identity user-id) :credentials (jti-used? jti))))++(defn- consume-jti+ "Record `jti` as used (nil jti = session re-auth, nothing to record), pruning expired entries."+ [credentials jti]+ (if-not jti+ credentials+ (let [now (quot (System/currentTimeMillis) 1000)]+ (update credentials :used_jtis+ (fn [jtis]+ (conj (filterv #(> (:exp % 0) now) jtis)+ {:jti jti :exp (+ now (* 2 60 60))}))))))++(defn- write-credentials!+ "Persist a successful attempt's credential changes. Any pending emailed one-time code dies with+ the successful verification — otherwise it would stay valid for its remaining ~10-minute TTL,+ including as re-auth for disable/regenerate."+ [auth-identity credentials jti]+ (t2/update! :model/AuthIdentity (:id auth-identity)+ {:credentials (-> credentials (dissoc :email_otp) (consume-jti jti))}))++(defn- totp-attempt!+ "When `code` is a valid, not-yet-used TOTP code: consume its time step (RFC 6238 §5.2) and return+ true."+ [auth-identity code jti]+ (let [credentials (:credentials auth-identity)]+ (when-let [secret (stored-secret auth-identity)]+ (when-let [step (totp/matching-time-step secret code)]+ (when (> step (long (:last_used_step credentials 0)))+ (write-credentials! auth-identity (assoc credentials :last_used_step step) jti)+ true)))))++(defn- recovery-attempt!+ "When `code` matches one of the stored (bcrypt-hashed) recovery codes: remove it — single-use —+ and return true."+ [auth-identity code jti]+ (when (recovery-codes/recovery-code? code)+ (let [credentials (:credentials auth-identity)+ hashes (:recovery_codes credentials)]+ (when-let [used (first (filter #(u.password/bcrypt-verify code %) hashes))]+ (write-credentials! auth-identity+ (assoc credentials :recovery_codes (filterv #(not= used %) hashes))+ jti)+ true))))++(defn- email-otp-attempt!+ "When `code` matches the pending (bcrypt-hashed, 10-minute) emailed one-time code: consume it —+ single-use — and return true."+ [auth-identity code jti]+ (let [{:keys [hash exp]} (get-in auth-identity [:credentials :email_otp])+ now (quot (System/currentTimeMillis) 1000)]+ (when (and hash+ (> (long (or exp 0)) now)+ (string? code)+ (re-matches #"\d{6}" code)+ (u.password/bcrypt-verify code hash))+ (write-credentials! auth-identity+ (dissoc (:credentials auth-identity) :email_otp)+ jti)+ true)))++(defn verify-attempt!+ "Verify a second-factor `code` — a 6-digit TOTP code, a recovery code, or a pending emailed+ one-time code — for `user-id`, atomically consuming whatever it uses: the TOTP time step, the+ recovery code, or the emailed code, plus the challenge `jti` when one is given (pass nil for+ session re-auth, where no challenge token exists).++ True only for a confirmed enrollment with an unused jti and an unconsumed code. Runs in a+ transaction with the enrollment row locked so a concurrently replayed code, recovery code, or+ token cannot pass twice."+ [user-id code jti]+ (t2/with-transaction [_conn]+ (boolean+ (when-let [auth-identity (t2/select-one :model/AuthIdentity+ :user_id user-id+ :provider provider-name+ {:for :update})]+ (when (and (confirmed? auth-identity)+ (not (jti-used? (:credentials auth-identity) jti)))+ (or (totp-attempt! auth-identity code jti)+ (recovery-attempt! auth-identity code jti)+ (email-otp-attempt! auth-identity code jti)))))))++(defn set-email-otp!+ "Generate a 6-digit emailed one-time code for `user-id`'s confirmed enrollment, replacing any+ pending one. Stored bcrypt-hashed with a 10-minute expiry; single-use. Returns the plaintext+ code for the caller to email, or nil when the user has no confirmed enrollment."+ [user-id]+ (t2/with-transaction [_conn]+ (when-let [auth-identity (t2/select-one :model/AuthIdentity+ :user_id user-id+ :provider provider-name+ {:for :update})]+ (when (confirmed? auth-identity)+ (let [code (format "%06d" (.nextInt (SecureRandom.) 1000000))]+ (t2/update! :model/AuthIdentity (:id auth-identity)+ {:credentials (assoc (:credentials auth-identity)+ :email_otp {:hash (u.password/hash-bcrypt code)+ :exp (+ (quot (System/currentTimeMillis) 1000)+ (* 10 60))})})+ code)))))diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.cljindex 2f3a45d5a93..8a290330b7b 100644--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj@@ -41,6 +41,7 @@:hosting:metabase-ai-managed:metabot-v3+ :multi-factor-auth:offer-metabase-ai-managed:no-upsell:official-collections@@ -93,6 +94,7 @@:hosting true:metabase-ai-managed true:metabot-v3 true+ :multi-factor-auth true:offer-metabase-ai-managed true:official_collections true:query_reference_validation truediff --git a/enterprise/backend/test/metabase_enterprise/mfa/admin_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/admin_test.cljnew file mode 100644index 00000000000..c49d61bc6ee--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/admin_test.clj@@ -0,0 +1,52 @@+(ns metabase-enterprise.mfa.admin-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(deftest admin-remove-test+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret (totp/generate-secret)}}]+ (testing "requires superuser"+ (mt/user-http-request :rasta :post 403 "ee/mfa/admin/remove" {:user_id user-id}))+ (testing "removes the enrollment, even with zero premium features (lockout escape hatch)"+ (mt/with-premium-features #{}+ (mt/user-http-request :crowberto :post 204 "ee/mfa/admin/remove" {:user_id user-id})+ (is (nil? (enrollment/enrolled-method user-id)))))))++(deftest admin-remove-is-audited-test+ ;; audit rows require the :audit-app feature at event time (premium-features/log-enabled?)+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret (totp/generate-secret)}}]+ (mt/user-http-request :crowberto :post 204 "ee/mfa/admin/remove" {:user_id user-id})+ (testing "the removal is audited against the affected user"+ (is (=? {:topic :mfa-disabled}+ (mt/latest-audit-log-entry :mfa-disabled user-id)))))))++(deftest admin-overview-test+ (mt/with-temp [:model/User {enrolled-id :id} {}+ :model/AuthIdentity _ {:user_id enrolled-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret (totp/generate-secret)}}+ :model/User _ {}]+ (testing "requires superuser"+ (mt/user-http-request :rasta :get 403 "ee/mfa/admin/overview"))+ (let [overview (mt/user-http-request :crowberto :get 200 "ee/mfa/admin/overview")]+ (is (boolean? (:encryption_key_set overview)))+ (is (pos? (:enrolled_count overview)))+ (testing "unenrolled count covers active users without a confirmed enrollment"+ ;; both temp users are active + personal; only one is enrolled+ (is (pos? (:unenrolled_count overview)))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.cljnew file mode 100644index 00000000000..513b9b1a07a--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.clj@@ -0,0 +1,168 @@+(ns metabase-enterprise.mfa.email-otp-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.channel.email :as channel.email]+ [metabase.channel.settings :as channel.settings]+ [metabase.channel.template.core :as channel.template]+ [metabase.session.api :as api.session]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(defn- reset-throttlers []+ (doseq [throttler (concat (vals @#'api.session/verify-throttlers)+ (vals @#'api.session/login-throttlers)+ (vals @#'api.session/email-otp-send-throttlers))]+ (reset! (:attempts throttler) nil)))++(use-fixtures :each (fn [f] (reset-throttlers) (f)))++(defn- fresh-jti [] (str (random-uuid)))++(deftest email-otp-round-trip-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}]+ (let [code (verification/set-email-otp! user-id)]+ (is (re-matches #"\d{6}" code))+ (is (true? (verification/verify-attempt! user-id code (fresh-jti))))+ (testing "single-use"+ (is (false? (verification/verify-attempt! user-id code (fresh-jti)))))))))++(deftest successful-verify-clears-pending-email-otp-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}]+ (let [email-code (verification/set-email-otp! user-id)]+ (is (true? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti))))+ (testing "a successful TOTP verification kills the pending emailed code for its whole TTL"+ (is (false? (verification/verify-attempt! user-id email-code (fresh-jti)))))))))++(deftest email-otp-requires-confirmed-enrollment-test+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :credentials {:secret (totp/generate-secret)}}]+ (is (nil? (verification/set-email-otp! user-id)))))++(deftest expired-email-otp-rejected-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity {ai-id :id} {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}]+ (let [code (verification/set-email-otp! user-id)]+ ;; back-date the expiry+ (let [ai (t2/select-one :model/AuthIdentity :id ai-id)]+ (t2/update! :model/AuthIdentity ai-id+ {:credentials (assoc-in (:credentials ai) [:email_otp :exp]+ (dec (quot (System/currentTimeMillis) 1000)))}))+ (is (false? (verification/verify-attempt! user-id code (fresh-jti))))))))++(deftest send-email-otp-e2e-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (let [secret (totp/generate-secret)+ sent (atom nil)]+ (t2/insert! :model/AuthIdentity {:user_id (mt/user->id :rasta)+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}})+ (try+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly true)+ channel.email/send-message-or-throw! (fn [msg] (reset! sent msg) msg)]+ (let [challenge (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (testing "the challenge advertises the email method when email is configured"+ (is (= ["totp" "email"] (:methods challenge))))+ (is (true? (:success (mt/client :post 200 "session/mfa/send-email-otp"+ {:challenge_token (:challenge_token challenge)}))))+ (let [[_ code] (re-find #"(?s)sign-in code.*?(\d{6})" (:message @sent))]+ (is (some? code) "the email contains the code")+ (testing "the emailed code completes the login"+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token challenge) :code code}))))+ (testing "a consumed challenge token cannot keep sending codes"+ (mt/client :post 401 "session/mfa/send-email-otp" {:challenge_token (:challenge_token challenge)})))))+ (testing "a bogus challenge token cannot trigger a send"+ (mt/client :post 401 "session/mfa/send-email-otp" {:challenge_token "bogus"}))+ (finally+ (t2/delete! :model/AuthIdentity :user_id (mt/user->id :rasta) :provider "totp")))))))++(deftest send-email-otp-surfaces-delivery-failure-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (let [secret (totp/generate-secret)]+ (t2/insert! :model/AuthIdentity {:user_id (mt/user->id :rasta)+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}})+ (try+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly true)+ channel.email/send-message-or-throw! (fn [& _]+ (throw (Exception. "SMTP down")))]+ (let [challenge (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (testing "an SMTP failure is an error, not {:success true} with no email"+ (mt/client :post 500 "session/mfa/send-email-otp" {:challenge_token (:challenge_token challenge)}))))+ (finally+ (t2/delete! :model/AuthIdentity :user_id (mt/user->id :rasta) :provider "totp")))))))++(deftest send-email-otp-requires-configured-email-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (let [secret (totp/generate-secret)]+ (t2/insert! :model/AuthIdentity {:user_id (mt/user->id :rasta)+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}})+ (try+ (mt/with-dynamic-fn-redefs [channel.settings/email-configured? (constantly false)]+ (let [challenge (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (testing "the challenge does not advertise email"+ (is (= ["totp"] (:methods challenge))))+ (mt/client :post 400 "session/mfa/send-email-otp" {:challenge_token (:challenge_token challenge)})))+ (finally+ (t2/delete! :model/AuthIdentity :user_id (mt/user->id :rasta) :provider "totp")))))))++(deftest mfa-email-templates-render-test+ (testing "all four MFA email templates render without error and contain their key sentences"+ (testing "mfa_enabled template"+ (let [html (channel.template/render "mfa_enabled" {:applicationName "Metabase"+ :siteUrl "http://localhost:3000"+ :logoHeader false})]+ (is (string? html))+ (is (str/includes? html "Two-factor authentication is now required"))))+ (testing "mfa_disabled template"+ (let [html (channel.template/render "mfa_disabled" {:applicationName "Metabase"+ :siteUrl "http://localhost:3000"+ :logoHeader false})]+ (is (string? html))+ (is (str/includes? html "using a verification code"))))+ (testing "mfa_removed_by_admin template"+ (let [html (channel.template/render "mfa_removed_by_admin" {:applicationName "Metabase"+ :siteUrl "http://localhost:3000"+ :logoHeader false})]+ (is (string? html))+ (is (str/includes? html "administrator removed two-factor authentication"))))+ (testing "mfa_login_code template"+ (let [html (channel.template/render "mfa_login_code" {:applicationName "Metabase"+ :siteUrl "http://localhost:3000"+ :logoHeader false+ :code "123456"})]+ (is (string? html))+ (is (re-find #"(?s)sign-in code.*?(\d{6})" html))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.cljnew file mode 100644index 00000000000..6a62878bff8--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj@@ -0,0 +1,151 @@+(ns metabase-enterprise.mfa.enrollment-flow-test+ "End-to-end enrollment lifecycle over the HTTP API."+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.mfa.management :as mfa.management]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.sso.core :as sso]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(defn- reset-throttlers []+ (doseq [throttler (vals @#'mfa.management/throttlers)]+ (reset! (:attempts throttler) nil)))++(use-fixtures :each (fn [f] (reset-throttlers) (f)))++(defn- wrong-code [secret]+ (let [current (totp/generate-code secret)]+ (if (= current "000000") "111111" "000000")))++(defmacro ^:private with-fresh-user-session!+ "Temp password user + a real session from a normal (not-yet-enrolled) login."+ [[session-binding email-binding password-binding] & body]+ `(let [~password-binding (str "Pw-" (random-uuid))]+ (mt/with-temp [:model/User {~'_user-id :id, ~email-binding :email} {:password ~password-binding}]+ (let [~session-binding (:id (mt/client :post 200 "session" {:username ~email-binding+ :password ~password-binding}))]+ ~@body))))++(deftest full-enrollment-lifecycle-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key email password]+ (testing "enroll requires the right password — 400 with a field error, NOT 401 (clients+ treat a 401 on a session-authenticated endpoint as an expired session)"+ (is (=? {:errors {:password some?}}+ (mt/client session-key :post 400 "ee/mfa/enroll" {:password "not-the-password"}))))+ (let [{:keys [secret otpauth_uri]} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})]+ (is (re-find #"^otpauth://totp/" otpauth_uri))+ (testing "a wrong code does not confirm"+ (mt/client session-key :post 400 "ee/mfa/enroll/confirm" {:code (wrong-code secret)}))+ (let [{:keys [recovery_codes]} (mt/client session-key :post 200 "ee/mfa/enroll/confirm"+ {:code (totp/generate-code secret)})]+ (is (= 10 (count recovery_codes)))+ (testing "status reflects the confirmed enrollment"+ (is (=? {:enrolled true, :method "totp", :pending false, :recovery_codes_remaining 10}+ (mt/client session-key :get 200 "ee/mfa/status"))))+ (testing "re-enrolling over a confirmed enrollment is rejected"+ (mt/client session-key :post 400 "ee/mfa/enroll" {:password password}))+ (testing "the next login is challenged"+ (is (true? (:mfa_required (mt/client :post 200 "session" {:username email :password password})))))+ (testing "disable works with a recovery code even with zero premium features (lapse escape hatch)"+ (mt/with-premium-features #{}+ (mt/client session-key :post 204 "ee/mfa/disable" {:code (first recovery_codes)})))+ (testing "after disable, login issues a session directly again"+ (is (string? (:id (mt/client :post 200 "session" {:username email :password password})))))))))))++(deftest enrollment-lifecycle-is-audited-test+ ;; audit rows are written only when the :audit-app feature is active AT EVENT TIME+ ;; (premium-features/log-enabled?), so this runs the whole lifecycle with it on+ (mt/with-premium-features #{:multi-factor-auth :audit-app}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key email password]+ (let [{:keys [secret]} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})+ {:keys [recovery_codes]} (mt/client session-key :post 200 "ee/mfa/enroll/confirm"+ {:code (totp/generate-code secret)})+ user-id (t2/select-one-fn :id :model/User :email email)]+ (testing "enrollment is audited"+ (is (=? {:topic :mfa-enrolled}+ (mt/latest-audit-log-entry :mfa-enrolled user-id))))+ (mt/client session-key :post 204 "ee/mfa/disable" {:code (first recovery_codes)})+ (testing "self-disable is audited"+ (is (=? {:topic :mfa-disabled}+ (mt/latest-audit-log-entry :mfa-disabled user-id)))))))))++(deftest enroll-requires-feature-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key _email password]+ (testing "starting an enrollment is setup — gated on the feature"+ (mt/with-premium-features #{}+ (mt/client session-key :post 402 "ee/mfa/enroll" {:password password})))))))++(deftest enroll-requires-setting-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (with-fresh-user-session! [session-key _email password]+ (mt/client session-key :post 400 "ee/mfa/enroll" {:password password})))))++(deftest ldap-users-re-auth-by-bind-test+ (testing "verify-user-password falls through to an LDAP bind for users with no password identity"+ (mt/with-temp [:model/User {user-id :id, email :email} {}]+ ;; temp users get a password identity; simulate an LDAP-only user by proving dispatch order:+ ;; when the local hash fails, the LDAP branch decides.+ (mt/with-dynamic-fn-redefs [sso/ldap-enabled (constantly true)+ sso/find-user (fn [username] (when (= username email) {:dn "uid=x"}))+ ;; simulate a directory that accepts anonymous (empty-password) binds+ sso/verify-password (fn [_user-info password]+ (or (= password "directory-pw") (empty? password)))]+ (is (true? (#'mfa.management/verify-user-password user-id "directory-pw")))+ (is (false? (#'mfa.management/verify-user-password user-id "wrong")))+ (testing "blank passwords never reach the bind — an empty bind is an anonymous bind"+ (is (false? (#'mfa.management/verify-user-password user-id "")))+ (is (false? (#'mfa.management/verify-user-password user-id " ")))+ (is (false? (#'mfa.management/verify-user-password user-id nil))))))))++(deftest status-requires-session-test+ (testing "GET /status without a session → 401 (the management block is behind +auth)"+ (is (= "Unauthenticated" (mt/client :get 401 "ee/mfa/status")))))++(deftest pending-re-enroll-overwrites-secret-test+ (testing "re-enrolling while pending generates a new secret; the OLD pending secret no longer confirms"+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key _email password]+ (let [{:keys [secret]} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})+ {secret2 :secret} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})]+ (is (not= secret secret2) "a fresh secret is issued on each re-enroll")+ (testing "a code from the FIRST (discarded) secret is rejected at confirm"+ (mt/client session-key :post 400 "ee/mfa/enroll/confirm" {:code (totp/generate-code secret)}))+ (testing "confirming with the SECOND secret succeeds"+ (is (= 10 (count (:recovery_codes (mt/client session-key :post 200 "ee/mfa/enroll/confirm"+ {:code (totp/generate-code secret2)}))))))))))))++(deftest confirm-code-cannot-replay-to-disable-test+ (testing "the code consumed by confirm-enrollment cannot then be used to disable (cross-operation replay)"+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key _email password]+ (let [{:keys [secret]} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})+ code (totp/generate-code secret)]+ ;; confirm consumes `code`'s time step+ (mt/client session-key :post 200 "ee/mfa/enroll/confirm" {:code code})+ (testing "the same code is rejected at disable — the time step was already consumed"+ (is (= "Invalid authentication code."+ (mt/client session-key :post 400 "ee/mfa/disable" {:code code}))))))))))++(deftest disable-throttled-test+ (testing "repeated wrong codes on /disable are throttled — 6-digit codes need brute-force limits"+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-fresh-user-session! [session-key _email password]+ (let [{:keys [secret]} (mt/client session-key :post 200 "ee/mfa/enroll" {:password password})]+ (mt/client session-key :post 200 "ee/mfa/enroll/confirm" {:code (totp/generate-code secret)})+ (dotimes [_ 5]+ (mt/client session-key :post 400 "ee/mfa/disable" {:code (wrong-code secret)}))+ (let [resp (mt/client session-key :post 400 "ee/mfa/disable" {:code (wrong-code secret)})]+ (is (re-find #"Too many attempts!" (str resp))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/enrollment_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_test.cljnew file mode 100644index 00000000000..0cf0d1182f0--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_test.clj@@ -0,0 +1,22 @@+(ns metabase-enterprise.mfa.enrollment-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.test :as mt]))++(deftest enrolled-method-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {confirmed-id :id} {}+ :model/AuthIdentity _ {:user_id confirmed-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}+ :model/User {pending-id :id} {}+ :model/AuthIdentity _ {:user_id pending-id+ :provider "totp"+ :credentials {:secret secret}}]+ (is (= :totp (enrollment/enrolled-method confirmed-id)))+ (testing "a pending (unconfirmed) enrollment is not a usable second factor"+ (is (nil? (enrollment/enrolled-method pending-id)))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.cljnew file mode 100644index 00000000000..9022d422011--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj@@ -0,0 +1,89 @@+(ns metabase-enterprise.mfa.gate-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.settings :as mfa.settings]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.auth-identity.provider :as auth-identity.provider]+ [metabase.test :as mt]))++(defn- with-enrolled-user! [f]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret (totp/generate-secret)}}]+ (f user-id)))++(deftest gate-is-no-op-when-disabled-test+ (testing "with mfa-enforcement :off (the default on a fresh instance) every result passes through untouched"+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (with-enrolled-user!+ (fn [user-id]+ (doseq [result [{:success? true :user {:id user-id}}+ {:success? false :error :invalid-credentials}]]+ (is (= result (auth-identity.provider/apply-mfa-gate :provider/password result)))))))))++(deftest gate-challenges-enrolled-users-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-enrolled-user!+ (fn [user-id]+ (testing "password and LDAP first factors get a challenge instead of a session"+ (doseq [provider [:provider/password :provider/ldap]]+ (let [gated (auth-identity.provider/apply-mfa-gate provider {:success? true :user {:id user-id}})]+ (is (= :mfa-required (:success? gated)))+ (is (true? (:mfa/pending? gated)))+ (is (some #{"totp"} (:mfa/methods gated)))+ (is (= provider (:mfa/first-factor gated))))))+ (testing "an unenrolled user is untouched"+ (mt/with-temp [:model/User {other-id :id} {}]+ (let [result {:success? true :user {:id other-id}}]+ (is (= result (auth-identity.provider/apply-mfa-gate :provider/password result)))))))))))++(deftest gate-enforces-after-license-lapse-test+ (testing "fail-closed: an enrolled user is still challenged when the token reports no features at all"+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-enrolled-user!+ (fn [user-id]+ (mt/with-premium-features #{}+ (let [gated (auth-identity.provider/apply-mfa-gate :provider/password {:success? true :user {:id user-id}})]+ (is (= :mfa-required (:success? gated)))+ (is (= :provider/password (:mfa/first-factor gated)))))))))))++(deftest gate-provider-coverage-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (with-enrolled-user!+ (fn [user-id]+ (let [result {:success? true :user {:id user-id}}]+ (testing "SSO providers are never gated — their IdP owns MFA"+ (is (= result (auth-identity.provider/apply-mfa-gate :provider/google result))))+ (testing "support-access-grant is deliberately exempt (admin-granted, time-boxed, audited)"+ (is (= result (auth-identity.provider/apply-mfa-gate :provider/support-access-grant result))))+ (testing "password reset completes but is marked pending so no session is issued"+ (let [gated (auth-identity.provider/apply-mfa-gate :provider/emailed-secret-password-reset result)]+ (is (true? (:success? gated)))+ (is (true? (:mfa/pending? gated)))+ (is (nil? (:mfa/first-factor gated)))))))))))++(deftest mfa-enforcement-write-path-test+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (testing "enabling (:optional) requires the :multi-factor-auth feature (setup is gated; enforcement is not)"+ (mt/with-premium-features #{}+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"[Mm]ulti-factor"+ (mfa.settings/mfa-enforcement! :optional)))+ (is (= :off (mfa.settings/mfa-enforcement)))))+ (testing "enabling works with the feature"+ (mt/with-premium-features #{:multi-factor-auth}+ (mfa.settings/mfa-enforcement! :optional)+ (is (= :optional (mfa.settings/mfa-enforcement)))))+ (testing "setting :off never requires the feature — the lapsed-license escape hatch"+ (mt/with-premium-features #{}+ (mfa.settings/mfa-enforcement! :off)+ (is (= :off (mfa.settings/mfa-enforcement)))))+ (testing "setting :required is rejected even with the feature — reserved for a future release"+ (mt/with-premium-features #{:multi-factor-auth}+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"reserved"+ (mfa.settings/mfa-enforcement! :required)))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.cljnew file mode 100644index 00000000000..788043caa40--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/ldap_flow_test.clj@@ -0,0 +1,95 @@+(ns metabase-enterprise.mfa.ldap-flow-test+ "MFA against a real (in-memory UnboundID) LDAP directory: the gate challenges LDAP first factors,+ and LDAP-only users enroll by re-authenticating with their *directory* password. Fixtures live in+ test_resources/ldap.ldif (Sally Brown: mail [email protected] / password 1234)."+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.management :as mfa.management]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.session.api :as api.session]+ [metabase.sso.ldap-test-util :as ldap.test]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(defn- reset-throttlers []+ (doseq [throttler (concat (vals @#'api.session/verify-throttlers)+ (vals @#'api.session/login-throttlers))]+ (reset! (:attempts throttler) nil)))++(use-fixtures :each (fn [f] (reset-throttlers) (f)))++(def ^:private sally-email "[email protected]")+(def ^:private sally-directory-password "1234")++(deftest ldap-login-is-challenged-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (ldap.test/with-ldap-server!+ ;; provision Sally by logging in once, then enroll her+ (let [_ (mt/client :post 200 "session" {:username sally-email+ :password sally-directory-password})+ user-id (t2/select-one-fn :id :model/User :email sally-email)+ secret (totp/generate-secret)]+ (try+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}})+ (testing "an enrolled user's LDAP login gets a challenge, not a session"+ (let [resp (mt/client :post 200 "session" {:username sally-email+ :password sally-directory-password})]+ (is (true? (:mfa_required resp)))+ (is (nil? (:id resp)) "no session until the second factor")+ (testing "the code completes the login"+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp)+ :code (totp/generate-code secret)}))))))+ (finally+ (t2/delete! :model/AuthIdentity :user_id user-id :provider "totp"))))))))++(deftest ldap-enroll-rejects-blank-password-test+ ;; An empty (or whitespace) password sent to ldap/bind? is an *anonymous* bind, which succeeds on+ ;; permissive directories — and the in-memory UnboundID server is one. verify-user-password must+ ;; reject blank passwords itself, before the bind, so this attack can never re-auth. Tested at two+ ;; layers: the endpoint schema, and the helper that owns the invariant (a future caller inherits+ ;; the guard only if it lives in the helper, not the schema).+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (ldap.test/with-ldap-server!+ (let [{session-key :id} (mt/client :post 200 "session" {:username sally-email+ :password sally-directory-password})+ user-id (t2/select-one-fn :id :model/User :email sally-email)]+ (testing "the helper rejects blank passwords rather than letting an anonymous bind pass"+ (is (false? (#'mfa.management/verify-user-password user-id "")))+ (is (false? (#'mfa.management/verify-user-password user-id " ")))+ (is (false? (#'mfa.management/verify-user-password user-id nil)))+ (is (true? (#'mfa.management/verify-user-password user-id sally-directory-password))+ "sanity: a real directory password still binds"))+ (testing "the enroll endpoint's schema also refuses a blank password"+ (mt/client session-key :post 400 "ee/mfa/enroll" {:password ""})))))))++(deftest ldap-only-user-enrolls-with-directory-password-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (ldap.test/with-ldap-server!+ (let [{session-key :id} (mt/client :post 200 "session" {:username sally-email+ :password sally-directory-password})+ user-id (t2/select-one-fn :id :model/User :email sally-email)]+ (try+ ;; provisioned users get a random local password they never know, so a successful+ ;; enroll with the directory password proves the LDAP-bind branch, not the local hash+ (testing "enroll re-auths by binding against the directory"+ (is (=? {:errors {:password some?}}+ (mt/client session-key :post 400 "ee/mfa/enroll" {:password "not-her-directory-pw"})))+ (let [{:keys [secret]} (mt/client session-key :post 200 "ee/mfa/enroll"+ {:password sally-directory-password})]+ (is (= 10 (count (:recovery_codes+ (mt/client session-key :post 200 "ee/mfa/enroll/confirm"+ {:code (totp/generate-code secret)})))))))+ (finally+ (t2/delete! :model/AuthIdentity :user_id user-id :provider "totp"))))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.cljnew file mode 100644index 00000000000..4a17d0bbef6--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj@@ -0,0 +1,237 @@+(ns metabase-enterprise.mfa.login-flow-test+ "End-to-end two-step login over the HTTP API."+ (:require+ [buddy.sign.jwt :as jwt]+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.management :as mfa.management]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.request.core :as request]+ [metabase.session.api :as api.session]+ [metabase.session.settings :as session.settings]+ [metabase.settings.models.setting.cache :as setting.cache]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(defn- reset-throttlers []+ (doseq [throttler (concat (vals @#'api.session/verify-throttlers)+ (vals @#'mfa.management/throttlers)+ (vals @#'api.session/login-throttlers)+ [@#'api.session/reset-password-throttler])]+ (reset! (:attempts throttler) nil)))++(use-fixtures :each (fn [f] (reset-throttlers) (f)))++(defn- wrong-code [secret]+ (let [current (totp/generate-code secret)]+ (if (= current "000000") "111111" "000000")))++(defmacro with-enrolled-rasta! [[secret-binding] & body]+ `(mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [~'mfa-enforcement :optional]+ (let [~secret-binding (totp/generate-secret)]+ (try+ (t2/insert! :model/AuthIdentity {:user_id (mt/user->id :rasta)+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret ~secret-binding}})+ ~@body+ (finally+ (t2/delete! :model/AuthIdentity :user_id (mt/user->id :rasta) :provider "totp")))))))++(deftest two-step-login-test+ (with-enrolled-rasta! [secret]+ (testing "step 1: password login returns an MFA challenge, not a session"+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (is (true? (:mfa_required resp)))+ (is (some #{"totp"} (:methods resp)))+ (is (string? (:challenge_token resp)))+ (is (nil? (:id resp)) "no session id is issued yet")+ (testing "step 2: verifying a valid code yields a real session"+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)}))))+ (testing "the consumed challenge token cannot mint a second session (jti + step replay)"+ (mt/client :post 401 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)}))))))++(deftest wrong-code-rejected-test+ (with-enrolled-rasta! [secret]+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (mt/client :post 401 "session/mfa/verify" {:challenge_token (:challenge_token resp) :code (wrong-code secret)})+ (testing "a failed code does not invalidate the challenge token — retry with the right one"+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)})))))))++(deftest bogus-token-rejected-test+ (mt/client :post 401 "session/mfa/verify" {:challenge_token "not-a-real-token" :code "000000"}))++(deftest expired-challenge-token-rejected-test+ (with-enrolled-rasta! [secret]+ (testing "a challenge token past its 5-minute TTL is rejected even with a valid code"+ ;; correctly signed, already expired — what a real token looks like 5+ minutes later+ (let [expired-token (jwt/sign {:user-id (mt/user->id :rasta)+ :provider "password"+ :purpose "mfa-challenge"+ :jti (str (random-uuid))+ :exp (- (quot (System/currentTimeMillis) 1000) 10)}+ (session.settings/mfa-challenge-signing-key)+ {:alg :hs256})]+ (mt/client :post 401 "session/mfa/verify"+ {:challenge_token expired-token :code (totp/generate-code secret)})))))++(deftest signing-key-survives-restart-test+ (with-enrolled-rasta! [secret]+ (testing "a challenge issued before a restart verifies after it (signing key is DB-backed, not in-memory)"+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ ;; restoring the settings cache from the DB is what a fresh node/restarted process does+ (setting.cache/restore-cache!)+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp)+ :code (totp/generate-code secret)})))))))++(deftest recovery-code-regeneration-survives-license-lapse-test+ ;; Rotating recovery codes for an EXISTING enrollment is management, not setup, so it is+ ;; deliberately not feature-gated — a lapsed license must never strand an enrolled user.+ (with-enrolled-rasta! [secret]+ (let [[c1 & _] (enrollment/reset-recovery-codes! (mt/user->id :rasta))+ login (mt/client :post 200 "session" (mt/user->credentials :rasta))+ {session-key :id} (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token login)+ :code (totp/generate-code secret)})]+ (mt/with-premium-features #{}+ (testing "regeneration still works with zero premium features"+ (is (= 10 (count (:recovery_codes+ (mt/client session-key :post 200 "ee/mfa/recovery-codes" {:code c1}))))))))))++(deftest failed-verification-is-audited-test+ (with-enrolled-rasta! [secret]+ ;; audit rows require the :audit-app feature at event time (premium-features/log-enabled?);+ ;; must nest inside with-enrolled-rasta!, whose with-premium-features replaces the set+ (mt/with-additional-premium-features #{:audit-app}+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (mt/client :post 401 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (wrong-code secret)})+ (testing "a failed second-factor attempt lands in the audit log"+ (is (=? {:topic :mfa-verification-failed+ :model_id (mt/user->id :rasta)}+ (mt/latest-audit-log-entry :mfa-verification-failed (mt/user->id :rasta)))))))))++(deftest remember-me-survives-mfa-test+ (with-enrolled-rasta! [secret]+ (testing "'remember me' from step 1 must ride the verify request — that's what creates the session"+ (let [challenge (mt/client :post 200 "session" (assoc (mt/user->credentials :rasta) :remember true))+ response (mt/client-real-response :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token challenge)+ :code (totp/generate-code secret)+ :remember true})]+ (is (get-in response [:cookies request/metabase-session-cookie :expires])+ "remember=true on /verify sets a permanent cookie")))+ (testing "without remember, the cookie is session-scoped"+ ;; the first verify consumed the current time step; use the +1 step (inside the ±1+ ;; validation window, strictly greater than the consumed step) so replay protection passes+ (let [challenge (mt/client :post 200 "session" (mt/user->credentials :rasta))+ code (totp/code-for-unix-time secret (+ (quot (System/currentTimeMillis) 1000) 30))+ response (mt/client-real-response :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token challenge)+ :code code})]+ (is (nil? (get-in response [:cookies request/metabase-session-cookie :expires])))))))++(deftest deactivated-user-cannot-verify-test+ (with-enrolled-rasta! [secret]+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (t2/update! :model/User (mt/user->id :rasta) {:is_active false})+ (try+ (testing "a challenge token does not outlive the account: deactivated mid-challenge gets the same 401 as a bad token"+ (mt/client :post 401 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)}))+ (finally+ (t2/update! :model/User (mt/user->id :rasta) {:is_active true}))))))++(deftest successful-verify-does-not-count-toward-throttle-test+ (with-enrolled-rasta! [secret]+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)})))+ (testing "only failures count — a busy legitimate user is never throttled by their own logins"+ (is (empty? @(:attempts (@#'api.session/verify-throttlers :user-id))))))))++(deftest verify-throttled-test+ (with-enrolled-rasta! [secret]+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (testing "6-digit codes need brute-force limits: repeated failures throttle the user"+ (dotimes [_ 5]+ (mt/client :post 401 "session/mfa/verify" {:challenge_token (:challenge_token resp) :code (wrong-code secret)}))+ (let [resp' (mt/client :post 400 "session/mfa/verify" {:challenge_token (:challenge_token resp) :code (wrong-code secret)})]+ (is (re-find #"Too many attempts!" (str resp'))))))))++(deftest enforcement-survives-license-lapse-test+ (with-enrolled-rasta! [secret]+ (mt/with-premium-features #{}+ (testing "an enrolled user is still challenged, and can still complete verification, with no token features"+ (let [resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (is (true? (:mfa_required resp)))+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify"+ {:challenge_token (:challenge_token resp) :code (totp/generate-code secret)}))))))))++(deftest recovery-code-login-test+ (with-enrolled-rasta! [_secret]+ (let [[code & _] (enrollment/reset-recovery-codes! (mt/user->id :rasta))+ resp (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (testing "a recovery code completes the two-step login in place of a TOTP code"+ (is (=? {:id string?}+ (mt/client :post 200 "session/mfa/verify" {:challenge_token (:challenge_token resp) :code code}))))+ (testing "single-use: the same recovery code is dead afterwards"+ (let [resp' (mt/client :post 200 "session" (mt/user->credentials :rasta))]+ (mt/client :post 401 "session/mfa/verify" {:challenge_token (:challenge_token resp') :code code}))))))++(deftest regenerate-recovery-codes-endpoint-test+ (with-enrolled-rasta! [secret]+ (let [user-id (mt/user->id :rasta)+ [c1 & _] (enrollment/reset-recovery-codes! user-id)+ login (mt/client :post 200 "session" (mt/user->credentials :rasta))+ {session-key :id} (mt/client :post 200 "session/mfa/verify" {:challenge_token (:challenge_token login)+ :code (totp/generate-code secret)})]+ (testing "requires a session"+ (mt/client :post 401 "ee/mfa/recovery-codes" {:code c1}))+ (testing "requires a fresh second factor, not just the session"+ (mt/client session-key :post 400 "ee/mfa/recovery-codes" {:code "000000"}))+ (testing "an unused recovery code re-auths; the whole old set is then invalid"+ (let [resp (mt/client session-key :post 200 "ee/mfa/recovery-codes" {:code c1})]+ (is (= 10 (count (:recovery_codes resp))))+ (is (false? (verification/verify-attempt! user-id c1 nil))+ "the re-auth code was consumed with the rest of the old set"))))))++(deftest password-reset-issues-no-session-test+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temporary-setting-values [mfa-enforcement :optional]+ (mt/with-temp [:model/User {user-id :id, email :email} {:password (str "Old-" (random-uuid))}]+ (try+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret (totp/generate-secret)}})+ (let [new-password (str "New-" (random-uuid))+ resp (mt/client :post 200 "session/reset_password"+ {:token (auth-identity/create-password-reset! user-id)+ :password new-password})]+ (testing "the password change succeeds but no session is issued — the user logs in through the gate"+ (is (true? (:success resp)))+ (is (nil? (:session_id resp))))+ (testing "the new password works through the normal, gated login"+ (let [login (mt/client :post 200 "session" {:username email :password new-password})]+ (is (true? (:mfa_required login))))))+ (finally+ (t2/delete! :model/AuthIdentity :user_id user-id :provider "totp")))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.cljnew file mode 100644index 00000000000..85bc036f34f--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.clj@@ -0,0 +1,84 @@+(ns metabase-enterprise.mfa.recovery-codes-test+ (:require+ [clojure.set :as set]+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.enrollment :as enrollment]+ [metabase-enterprise.mfa.recovery-codes :as recovery-codes]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- fresh-jti [] (str (random-uuid)))++(deftest ^:parallel generate-codes-test+ (let [codes (recovery-codes/generate-codes)]+ (is (= recovery-codes/num-codes (count codes)))+ (is (every? recovery-codes/recovery-code? codes))+ (is (= (count codes) (count (distinct codes))))+ (testing "a TOTP code never looks like a recovery code"+ (is (not (recovery-codes/recovery-code? "123456"))))))++(defmacro ^:private with-confirmed-enrollment! [[user-id-binding secret-binding] & body]+ `(let [~secret-binding (totp/generate-secret)]+ (mt/with-temp [:model/User {~user-id-binding :id} {}+ :model/AuthIdentity ~'_ {:user_id ~user-id-binding+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret ~secret-binding}}]+ ~@body)))++(deftest reset-recovery-codes-test+ (with-confirmed-enrollment! [user-id _secret]+ (let [codes (enrollment/reset-recovery-codes! user-id)]+ (is (= recovery-codes/num-codes (count codes)))+ (is (= recovery-codes/num-codes (enrollment/recovery-codes-remaining user-id)))+ (testing "only hashes are stored"+ (let [stored (get-in (t2/select-one :model/AuthIdentity :user_id user-id :provider "totp")+ [:credentials :recovery_codes])]+ (is (every? #(.startsWith ^String % "$2a$") stored))+ (is (empty? (set/intersection (set codes) (set stored)))))))))++(deftest reset-requires-confirmed-enrollment-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :credentials {:secret secret}}]+ (is (nil? (enrollment/reset-recovery-codes! user-id))))))++(deftest recovery-code-single-use-test+ (with-confirmed-enrollment! [user-id _secret]+ (let [[code & _] (enrollment/reset-recovery-codes! user-id)]+ (is (true? (verification/verify-attempt! user-id code (fresh-jti))))+ (is (= (dec recovery-codes/num-codes) (enrollment/recovery-codes-remaining user-id)))+ (testing "consumed — never accepted again"+ (is (false? (verification/verify-attempt! user-id code (fresh-jti))))))))++(deftest regenerate-invalidates-old-set-test+ (with-confirmed-enrollment! [user-id _secret]+ (let [[old-code & _] (enrollment/reset-recovery-codes! user-id)+ new-codes (enrollment/reset-recovery-codes! user-id)]+ (testing "old set is dead in its entirety"+ (is (false? (verification/verify-attempt! user-id old-code (fresh-jti)))))+ (testing "new set works"+ (is (true? (verification/verify-attempt! user-id (first new-codes) (fresh-jti))))))))++(deftest recovery-path-consumes-jti-test+ (with-confirmed-enrollment! [user-id secret]+ (let [[code-a code-b & _] (enrollment/reset-recovery-codes! user-id)+ jti (fresh-jti)]+ (is (true? (verification/verify-attempt! user-id code-a jti)))+ (testing "the jti is burned across factor kinds — a second unused recovery code can't reuse it"+ (is (false? (verification/verify-attempt! user-id code-b jti))))+ (testing "nor can a fresh TOTP code"+ (is (false? (verification/verify-attempt! user-id (totp/generate-code secret) jti)))))))++(deftest wrong-recovery-code-rejected-test+ (with-confirmed-enrollment! [user-id _secret]+ (enrollment/reset-recovery-codes! user-id)+ (is (false? (verification/verify-attempt! user-id "aaaaa-aaaaa" (fresh-jti))))+ (is (= recovery-codes/num-codes (enrollment/recovery-codes-remaining user-id)))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/totp_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/totp_test.cljnew file mode 100644index 00000000000..55f6a8a8587--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/totp_test.clj@@ -0,0 +1,47 @@+(ns metabase-enterprise.mfa.totp-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase.test :as mt]))++(def ^:private rfc-secret+ "RFC 6238 Appendix B seed (ASCII \"12345678901234567890\") encoded as Base32, for HMAC-SHA1."+ "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ")++(deftest ^:parallel rfc6238-vectors-test+ (testing "6-digit truncations of the RFC 6238 Appendix B SHA1 test vectors (proves interop with authenticator apps)"+ (are [unix expected] (= expected (totp/code-for-unix-time rfc-secret unix))+ 59 "287082"+ 1111111109 "081804"+ 1111111111 "050471"+ 1234567890 "005924"+ 2000000000 "279037"+ ;; T > 32 bits — proves 64-bit time-step handling (RFC 6238 Appendix A note)+ 20000000000 "353130")))++(deftest ^:parallel round-trip-test+ (let [secret (totp/generate-secret)]+ (testing "a generated secret is unpadded Base32"+ (is (re-matches #"[A-Z2-7]+" secret)))+ (testing "a freshly generated code validates"+ (is (totp/valid-code? secret (totp/generate-code secret))))+ (testing "malformed codes never validate"+ (is (not (totp/valid-code? secret "12")))+ (is (not (totp/valid-code? secret "abcdef")))+ (is (not (totp/valid-code? secret nil))))))++(deftest ^:parallel validation-window-test+ (let [secret (totp/generate-secret)+ now (totp/current-time-step)+ code-at (fn [^long step] (totp/code-for-unix-time secret (* step 30)))]+ ;; pin the clock so a step boundary mid-test can't move the window+ (mt/with-dynamic-fn-redefs [totp/current-time-step (constantly now)]+ (testing "the current step and one step either side validate, and report their step"+ (are [step] (= step (totp/matching-time-step secret (code-at step)))+ (dec now)+ now+ (inc now)))+ (testing "steps two or more away do not validate"+ (are [step] (nil? (totp/matching-time-step secret (code-at step)))+ (- now 2)+ (+ now 2))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/verification_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/verification_test.cljnew file mode 100644index 00000000000..993e2bc013b--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mfa/verification_test.clj@@ -0,0 +1,196 @@+(ns metabase-enterprise.mfa.verification-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.mfa.recovery-codes :as recovery-codes]+ [metabase-enterprise.mfa.totp :as totp]+ [metabase-enterprise.mfa.verification :as verification]+ [metabase.test :as mt]+ [metabase.test.util :as tu]+ [metabase.util.encryption :as encryption]+ [metabase.util.encryption-test :as encryption-test]+ [metabase.util.password :as u.password]+ [toucan2.connection :as t2.conn]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- fresh-jti [] (str (random-uuid)))++;;; -------------------------------------------------- verify-attempt! unit tests --------------------------------------------------++(deftest verify-consumes-time-step-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}]+ (let [code (totp/generate-code secret)]+ (is (true? (verification/verify-attempt! user-id code (fresh-jti))))+ (testing "the same code is rejected on replay, even with a fresh challenge token (RFC 6238 SS5.2)"+ (is (false? (verification/verify-attempt! user-id code (fresh-jti)))))))))++(deftest verify-rejects-used-jti-test+ (let [secret (totp/generate-secret)+ jti (fresh-jti)+ now (quot (System/currentTimeMillis) 1000)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret+ :used_jtis [{:jti jti :exp (+ now 600)}]}}]+ (testing "a consumed challenge token cannot mint a second session, even with a fresh valid code"+ (is (false? (verification/verify-attempt! user-id (totp/generate-code secret) jti)))))))++(deftest verify-rejects-stale-step-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret+ ;; pretend a code one step ahead was already accepted+ :last_used_step (inc (totp/current-time-step))}}]+ (testing "codes at or before the last accepted step are rejected"+ (is (false? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti))))))))++(deftest verify-rejects-unconfirmed-test+ (let [secret (totp/generate-secret)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity _ {:user_id user-id+ :provider "totp"+ :credentials {:secret secret}}]+ (is (false? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti)))))))++(deftest expired-jtis-are-pruned-test+ (let [secret (totp/generate-secret)+ now (quot (System/currentTimeMillis) 1000)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/AuthIdentity {ai-id :id} {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret+ :used_jtis [{:jti "stale" :exp (- now 10)}]}}]+ (is (true? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti))))+ (let [jtis (get-in (t2/select-one :model/AuthIdentity :id ai-id) [:credentials :used_jtis])]+ (testing "the expired jti is gone; the fresh one is recorded"+ (is (= 1 (count jtis)))+ (is (not= "stale" (:jti (first jtis)))))))))++;;; -------------------------------------------------- Concurrency tests --------------------------------------------------++;; These tests verify the security invariant: two concurrent requests with the same one-time+;; credential cannot both succeed. The invariant relies on SELECT FOR UPDATE inside+;; t2/with-transaction.+;;+;; Implementation note: we must use with-model-cleanup (committed data) rather than mt/with-temp+;; (rollback-only transaction) here, because each future gets its own fresh DB connection via+;; `binding [t2.conn/*current-connectable* nil]`. Fresh connections can only see committed rows;+;; rows in an uncommitted test transaction are invisible to them.++(deftest concurrent-recovery-code-single-use-test+ (testing "only one of N concurrent threads can consume the same recovery code"+ (let [secret (totp/generate-secret)+ all-codes (recovery-codes/generate-codes)+ code (first all-codes)]+ (tu/with-model-cleanup [:model/User :model/AuthIdentity]+ (let [{user-id :id} (t2/insert-returning-instance! :model/User {:first_name "Conc" :last_name "Test"+ :email (str (random-uuid) "@test.com")+ :password "unused"})]+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret+ :recovery_codes (mapv u.password/hash-bcrypt all-codes)}})+ (let [latch (java.util.concurrent.CountDownLatch. 1)+ threads 8+ ;; Each future binds *current-connectable* to nil to acquire a fresh independent+ ;; DB connection (not the test-transaction connection), so SELECT FOR UPDATE+ ;; actually serializes concurrent access.+ futures (doall+ (repeatedly threads+ (fn []+ (future+ (.await latch)+ (binding [t2.conn/*current-connectable* nil]+ (verification/verify-attempt! user-id code (fresh-jti)))))))]+ ;; release the gate -- all threads race+ (.countDown latch)+ (let [results (mapv #(deref % 10000 :timeout) futures)]+ (testing "no timeouts"+ (is (not-any? #{:timeout} results)))+ (testing "exactly one attempt succeeds"+ (is (= 1 (count (filter true? results)))))+ (testing "the code is fully consumed (0 of that code remain)"+ (binding [t2.conn/*current-connectable* nil]+ (is (= 0 (count (filter #(u.password/bcrypt-verify code %)+ (get-in (t2/select-one :model/AuthIdentity+ :user_id user-id :provider "totp")+ [:credentials :recovery_codes]))))))))))))))++(deftest concurrent-totp-code-single-use-test+ (testing "only one of N concurrent threads can consume the same TOTP time step"+ (let [secret (totp/generate-secret)]+ (tu/with-model-cleanup [:model/User :model/AuthIdentity]+ (let [{user-id :id} (t2/insert-returning-instance! :model/User {:first_name "Conc" :last_name "Totp"+ :email (str (random-uuid) "@test.com")+ :password "unused"})]+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}})+ (let [code (totp/generate-code secret)+ latch (java.util.concurrent.CountDownLatch. 1)+ threads 8+ futures (doall+ (repeatedly threads+ (fn []+ (future+ (.await latch)+ (binding [t2.conn/*current-connectable* nil]+ (verification/verify-attempt! user-id code (fresh-jti)))))))]+ (.countDown latch)+ (let [results (mapv #(deref % 10000 :timeout) futures)]+ (testing "no timeouts"+ (is (not-any? #{:timeout} results)))+ (testing "exactly one attempt succeeds"+ (is (= 1 (count (filter true? results))))))))))))++;;; -------------------------------------------------- Encryption-key rollover --------------------------------------------------++(deftest key-rollover-test+ (testing "an enrollment written under key A verifies after the column is rotated to key B"+ ;; The full `rotate-encryption-key` walk over `encrypted-json-columns` (which includes+ ;; [:auth_identity :credentials]) is exercised by metabase.cmd.rotate-encryption-key-test;+ ;; this covers the MFA-specific end of it: rotate this row the way the command does —+ ;; decrypt raw value with the old key, re-encrypt with the new — then verify a login code+ ;; under the new key.+ (let [secret (totp/generate-secret)+ k1 "0123456789abcdef-key-A"+ k2 "fedcba9876543210-key-B"]+ (mt/with-temp [:model/User {user-id :id} {}]+ (encryption-test/with-secret-key k1+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "totp"+ :confirmed_at (t/instant)+ :credentials {:secret secret}}))+ (let [ai-id (t2/select-one-fn :id :auth_identity :user_id user-id :provider "totp")+ raw (t2/select-one-fn :credentials :auth_identity :id ai-id)+ plaintext (encryption-test/with-secret-key k1+ (encryption/maybe-decrypt raw))+ rotated (encryption-test/with-secret-key k2+ (encryption/maybe-encrypt plaintext))]+ (is (encryption/possibly-encrypted-string? raw) "sanity: stored under key A as ciphertext")+ (t2/update! :auth_identity ai-id {:credentials rotated}))+ (encryption-test/with-secret-key k2+ (is (true? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti)))+ "the rotated enrollment verifies under the new key"))+ (encryption-test/with-secret-key k1+ ;; encrypted-json-out falls back to the raw ciphertext string, on which the+ ;; timestamp-parsing transform then blows up — either way the old key can't read the row+ (is (thrown? Exception+ (t2/select-one-fn :credentials :model/AuthIdentity+ :user_id user-id :provider "totp"))+ "sanity: the old key can no longer read the row"))))))diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.tsindex 15291099a2e..6639c50a7dd 100644--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts@@ -14,6 +14,7 @@ export * from "./erd";export * from "./gdrive";export * from "./library";export * from "./metabot";+export * from "./multi-factor-auth";export * from "./remote-sync";export * from "./oidc";export * from "./replacement";diff --git a/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.ts b/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.tsnew file mode 100644index 00000000000..b3614b36423--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.ts@@ -0,0 +1,95 @@+import type {+ MfaAdminOverview,+ MfaEnrollResponse,+ MfaStatus,+} from "metabase-types/api";++import { EnterpriseApi } from "./api";+import { invalidateTags, provideMfaStatusTags, tag } from "./tags";++export const multiFactorAuthApi = EnterpriseApi.injectEndpoints({+ endpoints: (builder) => ({+ getMfaAdminOverview: builder.query<MfaAdminOverview, void>({+ query: () => ({+ method: "GET",+ url: "/api/ee/mfa/admin/overview",+ }),+ providesTags: () => provideMfaStatusTags(),+ }),+ verifyMfa: builder.mutation<+ { id: string },+ { challenge_token: string; code: string; remember?: boolean }+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/session/mfa/verify",+ body,+ }),+ }),+ getMfaStatus: builder.query<MfaStatus, void>({+ query: () => ({+ method: "GET",+ url: "/api/ee/mfa/status",+ }),+ providesTags: () => provideMfaStatusTags(),+ }),+ enrollMfa: builder.mutation<MfaEnrollResponse, { password: string }>({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/mfa/enroll",+ body,+ }),+ }),+ confirmMfaEnrollment: builder.mutation<+ { recovery_codes: string[] },+ { code: string }+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/mfa/enroll/confirm",+ body,+ }),+ invalidatesTags: (_, error) => invalidateTags(error, [tag("mfa-status")]),+ }),+ disableMfa: builder.mutation<void, { code: string }>({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/mfa/disable",+ body,+ }),+ invalidatesTags: (_, error) => invalidateTags(error, [tag("mfa-status")]),+ }),+ sendEmailOtp: builder.mutation<+ { success: true },+ { challenge_token: string }+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/session/mfa/send-email-otp",+ body,+ }),+ }),+ regenerateRecoveryCodes: builder.mutation<+ { recovery_codes: string[] },+ { code: string }+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/mfa/recovery-codes",+ body,+ }),+ invalidatesTags: (_, error) => invalidateTags(error, [tag("mfa-status")]),+ }),+ }),+});++export const {+ useGetMfaAdminOverviewQuery,+ useVerifyMfaMutation,+ useGetMfaStatusQuery,+ useEnrollMfaMutation,+ useConfirmMfaEnrollmentMutation,+ useDisableMfaMutation,+ useSendEmailOtpMutation,+ useRegenerateRecoveryCodesMutation,+} = multiFactorAuthApi;diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.tsindex 1537165377c..32687d4bece 100644--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts@@ -82,6 +82,10 @@ export function invalidateTags(return !error ? tags : [];}+export function provideMfaStatusTags(): TagDescription<EnterpriseTagType>[] {+ return [tag("mfa-status")];+}+export function providePythonLibraryTags(library: PythonLibrary,): TagDescription<EnterpriseTagType>[] {diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsxindex f2eb5874915..031ee06660e 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx@@ -13,6 +13,7 @@ import {type AuthSettingsPageProps,PLUGIN_AUTH_PROVIDERS,} from "metabase/plugins";+import { AdminAuthCard } from "metabase-enterprise/multi_factor_auth/components/AdminAuthCard";import { JwtAuthCard } from "../containers/JwtAuthCard";import { OidcAuthCard } from "../containers/OidcAuthCard";@@ -45,6 +46,7 @@ function AuthenticationTab() {<SamlAuthCard /><JwtAuthCard /><OidcAuthCard />+ <AdminAuthCard /><SettingsSection><AdminSettingInputdiff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsxindex 85d5780aa01..befed208f01 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsx@@ -1,6 +1,9 @@import { useCallback } from "react";-import { AuthButton } from "metabase/auth/components/AuthButton";+import {+ AuthCardButton,+ AuthTextButton,+} from "metabase/auth/components/AuthButton";import type { AuthProvider } from "metabase/plugins/types";import type { OidcAuthProvider } from "metabase-types/api";@@ -23,11 +26,8 @@ export const OidcButton = ({window.location.href = url;}, [provider, redirectUrl]);- return (- <AuthButton isCard={isCard} onClick={handleLogin}>- {provider["login-prompt"]}- </AuthButton>- );+ const Button = isCard ? AuthCardButton : AuthTextButton;+ return <Button onClick={handleLogin}>{provider["login-prompt"]}</Button>;};/**diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SsoButton/SsoButton.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SsoButton/SsoButton.tsxindex 89180a289a7..355eae12dcb 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SsoButton/SsoButton.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SsoButton/SsoButton.tsx@@ -1,7 +1,10 @@import { useCallback, useEffect } from "react";import { t } from "ttag";-import { AuthButton } from "metabase/auth/components/AuthButton";+import {+ AuthCardButton,+ AuthTextButton,+} from "metabase/auth/components/AuthButton";import { useDispatch } from "metabase/redux";import { isWithinIframe } from "metabase/utils/iframe";@@ -29,9 +32,6 @@ export const SsoButton = ({}}, [isEmbedded, handleLogin]);- return (- <AuthButton isCard={isCard} onClick={handleLogin}>- {t`Sign in with SSO`}- </AuthButton>- );+ const Button = isCard ? AuthCardButton : AuthTextButton;+ return <Button onClick={handleLogin}>{t`Sign in with SSO`}</Button>;};diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.tsxnew file mode 100644index 00000000000..21bf8f193a8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.tsx@@ -0,0 +1,100 @@+import { useState } from "react";+import { t } from "ttag";++import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import { useHasTokenFeature } from "metabase/common/hooks";+import { useDispatch } from "metabase/redux";+import { push } from "metabase/router";+import { Box, Button, Group, Stack } from "metabase/ui";+import * as Urls from "metabase/urls";+import { useGetMfaStatusQuery } from "metabase-enterprise/api";+import type { MfaStatus } from "metabase-types/api";++import { DisableModal } from "./DisableModal";+import { RecoveryCodesModal } from "./RecoveryCodesModal";+import { SetupModal } from "./SetupModal";++type SecurityModal = "setup" | "disable" | "recovery-codes";++export function AccountSecurityPanel() {+ const { data: status, isLoading, error } = useGetMfaStatusQuery();+ const [openedModal, setOpenedModal] = useState<SecurityModal | null>(null);+ const hasFeature = useHasTokenFeature("multi-factor-auth");+ const dispatch = useDispatch();++ const handleCloseModal = () => setOpenedModal(null);++ const handleDisableSuccess = () => {+ setOpenedModal(null);+ if (!hasFeature) {+ dispatch(push(Urls.accountSettings()));+ }+ };++ if (isLoading || error != null || status == null) {+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ return (+ <>+ <MfaSection+ status={status}+ hasFeature={hasFeature}+ onOpenModal={setOpenedModal}+ />+ <SetupModal+ opened={openedModal === "setup"}+ onSuccess={handleCloseModal}+ onCancel={handleCloseModal}+ />+ <DisableModal+ opened={openedModal === "disable"}+ onSuccess={handleDisableSuccess}+ onCancel={handleCloseModal}+ />+ <RecoveryCodesModal+ opened={openedModal === "recovery-codes"}+ onSuccess={handleCloseModal}+ onCancel={handleCloseModal}+ />+ </>+ );+}++type MfaSectionProps = {+ status: MfaStatus;+ hasFeature: boolean;+ onOpenModal: (modal: SecurityModal) => void;+};++function MfaSection({ status, hasFeature, onOpenModal }: MfaSectionProps) {+ return (+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <Stack gap="xs">+ <Box fw="bold" lh="1.25rem">{t`Two-factor authentication`}</Box>+ <Box c="text-secondary" lh="1.25rem">+ {status.enrolled+ ? t`Authenticator apps are enabled.`+ : t`Protect your account with a code from an authenticator app.`}+ </Box>+ </Stack>+ <Box>+ {status.enrolled ? (+ <Group gap="sm" wrap="nowrap">+ <Button onClick={() => onOpenModal("disable")}>{t`Disable`}</Button>+ <Button onClick={() => onOpenModal("recovery-codes")}>+ {t`Generate recovery codes`}+ </Button>+ </Group>+ ) : (+ <Button+ disabled={!hasFeature || !status.mfa_enabled}+ onClick={() => onOpenModal("setup")}+ >+ {t`Set up two-factor authentication`}+ </Button>+ )}+ </Box>+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.unit.spec.tsxnew file mode 100644index 00000000000..91c8dfe444f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/AccountSecurityPanel.unit.spec.tsx@@ -0,0 +1,111 @@+import userEvent from "@testing-library/user-event";++import {+ setupMfaStatusEndpoint,+ setupMfaStatusEndpointError,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockState } from "metabase/redux/store/mocks";+import type { MfaStatus } from "metabase-types/api";+import {+ createMockMfaStatus,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { AccountSecurityPanel } from "./AccountSecurityPanel";++type SetupOpts = {+ status?: MfaStatus;+ hasStatusError?: boolean;+ hasFeature?: boolean;+};++function setup({+ status = createMockMfaStatus(),+ hasStatusError = false,+ hasFeature = true,+}: SetupOpts = {}) {+ if (hasStatusError) {+ setupMfaStatusEndpointError();+ } else {+ setupMfaStatusEndpoint(status);+ }++ renderWithProviders(<AccountSecurityPanel />, {+ storeInitialState: createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({+ "multi-factor-auth": hasFeature,+ }),+ }),+ }),+ });+}++describe("AccountSecurityPanel", () => {+ it("should open the setup modal when the user is not enrolled", async () => {+ setup({ status: createMockMfaStatus({ enrolled: false }) });++ const setupButton = await screen.findByRole("button", {+ name: "Set up two-factor authentication",+ });+ expect(setupButton).toBeEnabled();++ await userEvent.click(setupButton);+ expect(+ await screen.findByRole("dialog", {+ name: "Set up two-factor authentication",+ }),+ ).toBeInTheDocument();+ });++ it("should disable the setup button without the token feature", async () => {+ setup({+ status: createMockMfaStatus({ enrolled: false }),+ hasFeature: false,+ });++ expect(+ await screen.findByRole("button", {+ name: "Set up two-factor authentication",+ }),+ ).toBeDisabled();+ });++ it("should open the disable modal when the user is enrolled", async () => {+ setup({ status: createMockMfaStatus({ enrolled: true }) });++ await userEvent.click(+ await screen.findByRole("button", { name: "Disable" }),+ );++ expect(+ await screen.findByRole("dialog", {+ name: "Disable two-factor authentication",+ }),+ ).toBeInTheDocument();+ });++ it("should open the recovery codes modal when the user is enrolled", async () => {+ setup({ status: createMockMfaStatus({ enrolled: true }) });++ await userEvent.click(+ await screen.findByRole("button", {+ name: "Generate recovery codes",+ }),+ );++ expect(+ await screen.findByRole("dialog", {+ name: "Generate recovery codes",+ }),+ ).toBeInTheDocument();+ });++ it("should show an error message when the status cannot be loaded", async () => {+ setup({ hasStatusError: true });++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/ConfirmCodeForm.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/ConfirmCodeForm.tsxnew file mode 100644index 00000000000..2d8e50e51d5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/ConfirmCodeForm.tsx@@ -0,0 +1,75 @@+import { t } from "ttag";+import * as Yup from "yup";++import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import { Button, type ButtonProps, Group, Stack, Text } from "metabase/ui";+import * as Errors from "metabase/utils/errors";++const CONFIRM_CODE_SCHEMA = Yup.object({+ code: Yup.string().required(Errors.required),+});++type ConfirmCodeValues = {+ code: string;+};++const INITIAL_CODE_VALUES: ConfirmCodeValues = {+ code: "",+};++type ConfirmCodeFormProps = {+ message: string;+ submitLabel: string;+ submitColor?: ButtonProps["color"];+ onSubmit: (code: string) => Promise<void>;+ onCancel: () => void;+};++export function ConfirmCodeForm({+ message,+ submitLabel,+ submitColor,+ onSubmit,+ onCancel,+}: ConfirmCodeFormProps) {+ const handleSubmit = ({ code }: ConfirmCodeValues) =>+ onSubmit(code.trim().toLowerCase());++ return (+ <FormProvider+ initialValues={INITIAL_CODE_VALUES}+ validationSchema={CONFIRM_CODE_SCHEMA}+ onSubmit={handleSubmit}+ >+ <Form>+ <Stack gap="md">+ <Text c="text-secondary">{message}</Text>+ <FormTextInput+ name="code"+ label={t`Confirm with an authenticator code or a recovery code`}+ placeholder="123456"+ autoCapitalize="none"+ autoCorrect="off"+ spellCheck={false}+ data-autofocus+ />+ <FormErrorMessage />+ <Group justify="flex-end">+ <Button onClick={onCancel}>{t`Cancel`}</Button>+ <FormSubmitButton+ label={submitLabel}+ variant="filled"+ color={submitColor}+ />+ </Group>+ </Stack>+ </Form>+ </FormProvider>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/index.tsnew file mode 100644index 00000000000..f5be844ca0f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/index.ts@@ -0,0 +1 @@+export * from "./ConfirmCodeForm";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/CopyableCodeBlock.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/CopyableCodeBlock.tsxnew file mode 100644index 00000000000..b4cdf767a56--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/CopyableCodeBlock.tsx@@ -0,0 +1,45 @@+import { t } from "ttag";++import {+ ActionIcon,+ Box,+ CopyButton,+ FixedSizeIcon,+ Group,+ Stack,+ Tooltip,+} from "metabase/ui";++type CopyableCodeBlockProps = {+ codes: string[];+};++export function CopyableCodeBlock({ codes }: CopyableCodeBlockProps) {+ return (+ <Group+ px="md"+ py="0.75rem"+ justify="space-between"+ align="flex-start"+ bg="background-secondary"+ bdrs="md"+ >+ <Stack gap="sm">+ {codes.map((code, index) => (+ <Box key={index} ff="mono" fz="sm" lh="1rem">+ {code}+ </Box>+ ))}+ </Stack>+ <CopyButton value={codes.join("\n")}>+ {({ copy, copied }) => (+ <Tooltip label={copied ? t`Copied!` : t`Copy`}>+ <ActionIcon size="xs" m={-1} aria-label={t`Copy`} onClick={copy}>+ <FixedSizeIcon name="copy" />+ </ActionIcon>+ </Tooltip>+ )}+ </CopyButton>+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/index.tsnew file mode 100644index 00000000000..ba8b3a68994--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/index.ts@@ -0,0 +1 @@+export { CopyableCodeBlock } from "./CopyableCodeBlock";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.tsxnew file mode 100644index 00000000000..c344bb69cce--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.tsx@@ -0,0 +1,52 @@+import { t } from "ttag";++import { Modal } from "metabase/ui";+import { useDisableMfaMutation } from "metabase-enterprise/api";++import { ConfirmCodeForm } from "../ConfirmCodeForm";++type DisableModalProps = {+ opened: boolean;+ onSuccess: () => void;+ onCancel: () => void;+};++export function DisableModal({+ opened,+ onSuccess,+ onCancel,+}: DisableModalProps) {+ return (+ <Modal+ title={t`Disable two-factor authentication`}+ opened={opened}+ onClose={onCancel}+ >+ <DisableForm onSuccess={onSuccess} onCancel={onCancel} />+ </Modal>+ );+}++type DisableFormProps = {+ onSuccess: () => void;+ onCancel: () => void;+};++function DisableForm({ onSuccess, onCancel }: DisableFormProps) {+ const [disableMfa] = useDisableMfaMutation();++ const handleSubmit = async (code: string) => {+ await disableMfa({ code }).unwrap();+ onSuccess();+ };++ return (+ <ConfirmCodeForm+ message={t`Are you sure you want to disable two-factor authentication? Your account will be protected by your password only, and your recovery codes will stop working.`}+ submitLabel={t`Disable`}+ submitColor="error"+ onSubmit={handleSubmit}+ onCancel={onCancel}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.unit.spec.tsxnew file mode 100644index 00000000000..9b7a4093d70--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/DisableModal.unit.spec.tsx@@ -0,0 +1,59 @@+import userEvent from "@testing-library/user-event";++import {+ setupMfaDisableEndpoint,+ setupMfaDisableEndpointError,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";++import { DisableModal } from "./DisableModal";++type SetupOpts = {+ hasDisableError?: boolean;+};++function setup({ hasDisableError = false }: SetupOpts = {}) {+ if (hasDisableError) {+ setupMfaDisableEndpointError();+ } else {+ setupMfaDisableEndpoint();+ }++ const onSuccess = jest.fn();+ const onCancel = jest.fn();++ renderWithProviders(+ <DisableModal opened onSuccess={onSuccess} onCancel={onCancel} />,+ );++ return { onSuccess, onCancel };+}++async function submitCode() {+ await userEvent.type(+ screen.getByLabelText(+ "Confirm with an authenticator code or a recovery code",+ ),+ "123456",+ );+ await userEvent.click(screen.getByRole("button", { name: "Disable" }));+}++describe("DisableModal", () => {+ it("should call onSuccess after disabling with a valid code", async () => {+ const { onSuccess } = setup();++ await submitCode();++ await waitFor(() => expect(onSuccess).toHaveBeenCalled());+ });++ it("should show an error message when the code is rejected", async () => {+ const { onSuccess } = setup({ hasDisableError: true });++ await submitCode();++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ expect(onSuccess).not.toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/index.tsnew file mode 100644index 00000000000..d9577c96337--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/DisableModal/index.ts@@ -0,0 +1 @@+export * from "./DisableModal";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.tsxnew file mode 100644index 00000000000..30f917e4398--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.tsx@@ -0,0 +1,34 @@+import type { ReactNode } from "react";+import { t } from "ttag";++import { Box, Button, Group, Input, Stack, Text } from "metabase/ui";++import { CopyableCodeBlock } from "../CopyableCodeBlock";++type RecoveryCodesFormProps = {+ recoveryCodes: string[];+ message: ReactNode;+ onDone: () => void;+};++export function RecoveryCodesForm({+ recoveryCodes,+ message,+ onDone,+}: RecoveryCodesFormProps) {+ return (+ <Stack gap="md">+ <Text c="text-secondary">{message}</Text>+ <Input.Wrapper label={t`Your recovery codes`}>+ <Box mt="xs">+ <CopyableCodeBlock codes={recoveryCodes} />+ </Box>+ </Input.Wrapper>+ <Group justify="flex-end">+ <Button variant="filled" onClick={onDone}>+ {t`Done`}+ </Button>+ </Group>+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsxnew file mode 100644index 00000000000..892021050ef--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsx@@ -0,0 +1,40 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";++import { RecoveryCodesForm } from "./RecoveryCodesForm";++const RECOVERY_CODES = ["aaaaa-bbbbb", "ccccc-ddddd"];+const MESSAGE = "Save these codes somewhere safe.";++function setup() {+ const onDone = jest.fn();++ renderWithProviders(+ <RecoveryCodesForm+ recoveryCodes={RECOVERY_CODES}+ message={MESSAGE}+ onDone={onDone}+ />,+ );++ return { onDone };+}++describe("RecoveryCodesForm", () => {+ it("should show the message and the codes", () => {+ setup();++ expect(screen.getByText(MESSAGE)).toBeInTheDocument();+ expect(screen.getByText(new RegExp(RECOVERY_CODES[0]))).toBeInTheDocument();+ expect(screen.getByText(new RegExp(RECOVERY_CODES[1]))).toBeInTheDocument();+ });++ it("should call onDone when the codes are acknowledged", async () => {+ const { onDone } = setup();++ await userEvent.click(screen.getByRole("button", { name: "Done" }));++ expect(onDone).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/index.tsnew file mode 100644index 00000000000..2d2063f3f49--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/index.ts@@ -0,0 +1 @@+export * from "./RecoveryCodesForm";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.tsxnew file mode 100644index 00000000000..f091fb57641--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.tsx@@ -0,0 +1,76 @@+import { useState } from "react";+import { jt, t } from "ttag";++import { Box, Modal } from "metabase/ui";+import { useRegenerateRecoveryCodesMutation } from "metabase-enterprise/api";++import { ConfirmCodeForm } from "../ConfirmCodeForm";+import { RecoveryCodesForm } from "../RecoveryCodesForm";++type RecoveryCodesModalProps = {+ opened: boolean;+ onSuccess: () => void;+ onCancel: () => void;+};++export function RecoveryCodesModal({+ opened,+ onSuccess,+ onCancel,+}: RecoveryCodesModalProps) {+ return (+ <Modal+ title={t`Generate recovery codes`}+ opened={opened}+ onClose={onCancel}+ >+ <RecoveryCodesModalBody onSuccess={onSuccess} onCancel={onCancel} />+ </Modal>+ );+}++type RecoveryCodesModalBodyProps = {+ onSuccess: () => void;+ onCancel: () => void;+};++function RecoveryCodesModalBody({+ onSuccess,+ onCancel,+}: RecoveryCodesModalBodyProps) {+ const [regenerateRecoveryCodes] = useRegenerateRecoveryCodesMutation();+ const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);++ const handleGenerate = async (code: string) => {+ const { recovery_codes } = await regenerateRecoveryCodes({+ code,+ }).unwrap();+ setRecoveryCodes(recovery_codes);+ };++ if (recoveryCodes != null) {+ return (+ <RecoveryCodesForm+ recoveryCodes={recoveryCodes}+ message={jt`Your old recovery codes no longer work. Each new code signs you in once if you lose your authenticator — ${(+ <Box+ component="span"+ key="warning"+ c="text-primary"+ fw="bold"+ >{t`this is the only time they'll be shown.`}</Box>+ )}`}+ onDone={onSuccess}+ />+ );+ }++ return (+ <ConfirmCodeForm+ message={t`This will generate a new set of recovery codes and invalidate all of your old ones.`}+ submitLabel={t`Generate new codes`}+ onSubmit={handleGenerate}+ onCancel={onCancel}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.unit.spec.tsxnew file mode 100644index 00000000000..13a58e1fe03--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/RecoveryCodesModal.unit.spec.tsx@@ -0,0 +1,65 @@+import userEvent from "@testing-library/user-event";++import {+ setupMfaRecoveryCodesEndpoint,+ setupMfaRecoveryCodesEndpointError,+} from "__support__/server-mocks";+import { renderWithProviders, screen } from "__support__/ui";++import { RecoveryCodesModal } from "./RecoveryCodesModal";++const RECOVERY_CODES = ["aaaaa-bbbbb", "ccccc-ddddd"];++type SetupOpts = {+ hasRegenerateError?: boolean;+};++function setup({ hasRegenerateError = false }: SetupOpts = {}) {+ if (hasRegenerateError) {+ setupMfaRecoveryCodesEndpointError();+ } else {+ setupMfaRecoveryCodesEndpoint(RECOVERY_CODES);+ }++ const onSuccess = jest.fn();+ const onCancel = jest.fn();++ renderWithProviders(+ <RecoveryCodesModal opened onSuccess={onSuccess} onCancel={onCancel} />,+ );++ return { onSuccess, onCancel };+}++async function submitCode() {+ await userEvent.type(+ screen.getByLabelText(+ "Confirm with an authenticator code or a recovery code",+ ),+ "123456",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Generate new codes" }),+ );+}++describe("RecoveryCodesModal", () => {+ it("should show the new codes after confirming with a valid code", async () => {+ setup();++ await submitCode();++ expect(+ await screen.findByText(new RegExp(RECOVERY_CODES[0])),+ ).toBeInTheDocument();+ expect(screen.getByText(new RegExp(RECOVERY_CODES[1]))).toBeInTheDocument();+ });++ it("should show an error message when the code is rejected", async () => {+ setup({ hasRegenerateError: true });++ await submitCode();++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/index.tsnew file mode 100644index 00000000000..963f632800b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesModal/index.ts@@ -0,0 +1 @@+export * from "./RecoveryCodesModal";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.tsxnew file mode 100644index 00000000000..62b0caeafff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.tsx@@ -0,0 +1,205 @@+import { useState } from "react";+import QRCode from "react-qr-code";+import { jt, t } from "ttag";+import * as Yup from "yup";++import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import { Box, Button, Center, Group, Modal, Stack, Text } from "metabase/ui";+import * as Errors from "metabase/utils/errors";+import {+ useConfirmMfaEnrollmentMutation,+ useEnrollMfaMutation,+} from "metabase-enterprise/api";+import type { MfaEnrollResponse } from "metabase-types/api";++import { TOTP_CODE_LENGTH } from "../../../constants";+import { withTotpCodeRules } from "../../../schemas";+import { CopyableCodeBlock } from "../CopyableCodeBlock";+import { RecoveryCodesForm } from "../RecoveryCodesForm";++const QR_CODE_SIZE = 180;++type SetupModalProps = {+ opened: boolean;+ onSuccess: () => void;+ onCancel: () => void;+};++export function SetupModal({ opened, onSuccess, onCancel }: SetupModalProps) {+ return (+ <Modal+ title={t`Set up two-factor authentication`}+ opened={opened}+ onClose={onCancel}+ >+ <SetupModalBody onSuccess={onSuccess} onCancel={onCancel} />+ </Modal>+ );+}++type SetupModalBodyProps = {+ onSuccess: () => void;+ onCancel: () => void;+};++function SetupModalBody({ onSuccess, onCancel }: SetupModalBodyProps) {+ const [enrollment, setEnrollment] = useState<MfaEnrollResponse | null>(null);+ const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);++ if (recoveryCodes != null) {+ return (+ <RecoveryCodesForm+ recoveryCodes={recoveryCodes}+ message={jt`Each code signs you in once if you lose your authenticator. Save them somewhere safe — ${(+ <Box+ component="span"+ key="warning"+ c="text-primary"+ fw="bold"+ >{t`this is the only time they'll be shown.`}</Box>+ )}`}+ onDone={onSuccess}+ />+ );+ }++ if (enrollment == null) {+ return <ConfirmPasswordForm onEnroll={setEnrollment} onCancel={onCancel} />;+ }++ return (+ <EnrollForm+ enrollment={enrollment}+ onSuccess={setRecoveryCodes}+ onCancel={onCancel}+ />+ );+}++const PASSWORD_SCHEMA = Yup.object({+ password: Yup.string().required(Errors.required),+});++type ConfirmPasswordValues = {+ password: string;+};++const INITIAL_PASSWORD_VALUES: ConfirmPasswordValues = {+ password: "",+};++type ConfirmPasswordFormProps = {+ onEnroll: (enrollment: MfaEnrollResponse) => void;+ onCancel: () => void;+};++function ConfirmPasswordForm({ onEnroll, onCancel }: ConfirmPasswordFormProps) {+ const [enrollMfa] = useEnrollMfaMutation();++ const handleSubmit = async ({ password }: ConfirmPasswordValues) => {+ onEnroll(await enrollMfa({ password }).unwrap());+ };++ return (+ <FormProvider+ initialValues={INITIAL_PASSWORD_VALUES}+ validationSchema={PASSWORD_SCHEMA}+ onSubmit={handleSubmit}+ >+ <Form>+ <Stack gap="md">+ <Text c="text-secondary">+ {t`Protect your account by requiring a code from an authenticator app when you sign in.`}+ </Text>+ <FormTextInput+ name="password"+ type="password"+ label={t`Confirm your password to begin`}+ data-autofocus+ />+ <FormErrorMessage />+ <Group justify="flex-end">+ <Button onClick={onCancel}>{t`Cancel`}</Button>+ <FormSubmitButton label={t`Continue`} variant="filled" />+ </Group>+ </Stack>+ </Form>+ </FormProvider>+ );+}++const CODE_SCHEMA = Yup.object({+ code: withTotpCodeRules(Yup.string().required(Errors.required)),+});++type EnrollFormValues = {+ code: string;+};++const INITIAL_CODE_VALUES: EnrollFormValues = {+ code: "",+};++type EnrollFormProps = {+ enrollment: MfaEnrollResponse;+ onSuccess: (recoveryCodes: string[]) => void;+ onCancel: () => void;+};++function EnrollForm({ enrollment, onSuccess, onCancel }: EnrollFormProps) {+ const [confirmEnrollment] = useConfirmMfaEnrollmentMutation();++ const handleSubmit = async ({ code }: EnrollFormValues) => {+ const { recovery_codes } = await confirmEnrollment({+ code: code.trim(),+ }).unwrap();+ onSuccess(recovery_codes);+ };++ return (+ <FormProvider+ initialValues={INITIAL_CODE_VALUES}+ validationSchema={CODE_SCHEMA}+ onSubmit={handleSubmit}+ >+ <Form>+ <Stack gap="md">+ <Stack gap="sm">+ <Box>{t`Scan this QR code with an authenticator app:`}</Box>+ <Center>+ <Box bg="white" p="md">+ <QRCode value={enrollment.otpauth_uri} size={QR_CODE_SIZE} />+ </Box>+ </Center>+ </Stack>+ <Stack gap="sm">+ <Box>{t`Or enter this key in the app manually:`}</Box>+ <CopyableCodeBlock codes={[enrollment.secret]} />+ </Stack>+ <FormTextInput+ name="code"+ label={t`Enter the 6-digit code from the authenticator app`}+ placeholder="123456"+ maxLength={TOTP_CODE_LENGTH}+ inputMode="numeric"+ autoFocus+ />+ <FormErrorMessage />+ <Group justify="flex-end">+ <Button onClick={onCancel}>{t`Cancel`}</Button>+ <FormSubmitButton+ label={t`Set up authentication`}+ variant="filled"+ />+ </Group>+ </Stack>+ </Form>+ </FormProvider>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.unit.spec.tsxnew file mode 100644index 00000000000..42954e2f24c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.unit.spec.tsx@@ -0,0 +1,67 @@+import userEvent from "@testing-library/user-event";++import {+ setupMfaEnrollEndpoint,+ setupMfaEnrollEndpointError,+} from "__support__/server-mocks";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockMfaEnrollResponse } from "metabase-types/api/mocks";++import { SetupModal } from "./SetupModal";++const SECRET = "ABCDE23456";++type SetupOpts = {+ hasEnrollError?: boolean;+};++function setup({ hasEnrollError = false }: SetupOpts = {}) {+ if (hasEnrollError) {+ setupMfaEnrollEndpointError();+ } else {+ setupMfaEnrollEndpoint(+ createMockMfaEnrollResponse({+ secret: SECRET,+ otpauth_uri: `otpauth://totp/test?secret=${SECRET}`,+ }),+ );+ }++ const onSuccess = jest.fn();+ const onCancel = jest.fn();++ renderWithProviders(+ <SetupModal opened onSuccess={onSuccess} onCancel={onCancel} />,+ );++ return { onSuccess, onCancel };+}++async function submitPassword() {+ await userEvent.type(+ screen.getByLabelText("Confirm your password to begin"),+ "password",+ );+ await userEvent.click(screen.getByRole("button", { name: "Continue" }));+}++describe("SetupModal", () => {+ it("should show the enrollment step after confirming the password", async () => {+ setup();++ await submitPassword();++ expect(+ await screen.findByText("Scan this QR code with an authenticator app:"),+ ).toBeInTheDocument();+ expect(screen.getByText(SECRET)).toBeInTheDocument();+ });++ it("should show an error message when enrollment fails", async () => {+ setup({ hasEnrollError: true });++ await submitPassword();++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/index.tsnew file mode 100644index 00000000000..302a95d312b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/index.ts@@ -0,0 +1 @@+export * from "./SetupModal";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/index.tsnew file mode 100644index 00000000000..c5909dee7e6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/index.ts@@ -0,0 +1 @@+export * from "./AccountSecurityPanel";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.tsxnew file mode 100644index 00000000000..bb08550f6dc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.tsx@@ -0,0 +1,86 @@+import { msgid, ngettext, t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";+import { useAdminSetting } from "metabase/api/utils";+import { useHasTokenFeature } from "metabase/common/hooks";+import { Alert, Group, Switch, Text } from "metabase/ui";+import { useGetMfaAdminOverviewQuery } from "metabase-enterprise/api";+import type { MfaAdminOverview } from "metabase-types/api";++export function AdminAuthCard() {+ const hasFeature = useHasTokenFeature("multi-factor-auth");+ const { value: enforcement, updateSetting } =+ useAdminSetting("mfa-enforcement");++ const enabled = enforcement != null && enforcement !== "off";++ const { data: overview } = useGetMfaAdminOverviewQuery(undefined, {+ skip: !enabled,+ });++ if (!hasFeature && !enabled) {+ return null;+ }++ const handleChange = (checked: boolean) => {+ updateSetting({+ key: "mfa-enforcement",+ value: checked ? "optional" : "off",+ });+ };++ return (+ <SettingsSection>+ <SettingHeader+ id="mfa-enforcement"+ title={t`Two-factor authentication`}+ description={t`Let users secure their account with an authenticator app.`}+ />+ <Switch+ id="mfa-enforcement"+ checked={enabled}+ onChange={(e) => handleChange(e.target.checked)}+ label={enabled ? t`Enabled` : t`Disabled`}+ disabled={!enabled && !hasFeature}+ w="auto"+ size="sm"+ />+ {enabled && overview && !overview.encryption_key_set && (+ <Alert color="warning">+ {t`Make sure to set the MB_ENCRYPTION_SECRET_KEY environment variable to encrypt authenticator secrets.`}+ </Alert>+ )}+ {enabled && overview && <EnrollmentCounts overview={overview} />}+ </SettingsSection>+ );+}++type EnrollmentCountsProps = {+ overview: MfaAdminOverview;+};++function EnrollmentCounts({ overview }: EnrollmentCountsProps) {+ const enrolledCount = overview.enrolled_count;+ const unenrolledCount = overview.unenrolled_count;++ return (+ <Group gap="sm">+ <Text c="text-secondary">+ {ngettext(+ msgid`${enrolledCount} enrolled user`,+ `${enrolledCount} enrolled users`,+ enrolledCount,+ )}+ </Text>+ <Text c="text-secondary">•</Text>+ <Text c="text-secondary">+ {ngettext(+ msgid`${unenrolledCount} user without 2FA`,+ `${unenrolledCount} users without 2FA`,+ unenrolledCount,+ )}+ </Text>+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.unit.spec.tsxnew file mode 100644index 00000000000..855cea94c30--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/AdminAuthCard.unit.spec.tsx@@ -0,0 +1,73 @@+import {+ setupMfaAdminOverviewEndpoint,+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockState } from "metabase/redux/store/mocks";+import type { MfaAdminOverview } from "metabase-types/api";+import {+ createMockMfaAdminOverview,+ createMockSettingDefinition,+ createMockSettings,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { AdminAuthCard } from "./AdminAuthCard";++type SetupOpts = {+ mfaEnabled?: boolean;+ hasFeature?: boolean;+ overview?: MfaAdminOverview;+};++function setup({+ mfaEnabled = true,+ hasFeature = true,+ overview = createMockMfaAdminOverview(),+}: SetupOpts = {}) {+ const enforcement = mfaEnabled ? ("optional" as const) : ("off" as const);+ const settings = createMockSettings({+ "mfa-enforcement": enforcement,+ "token-features": createMockTokenFeatures({+ "multi-factor-auth": hasFeature,+ }),+ });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([+ createMockSettingDefinition({ key: "mfa-enforcement", value: enforcement }),+ ]);+ setupMfaAdminOverviewEndpoint(overview);++ renderWithProviders(<AdminAuthCard />, {+ storeInitialState: createMockState({+ settings: mockSettings(settings),+ }),+ });+}++describe("AdminAuthCard", () => {+ it("should show the enrollment counts when the setting is enabled", async () => {+ setup({+ overview: createMockMfaAdminOverview({+ enrolled_count: 1,+ unenrolled_count: 3,+ }),+ });++ expect(await screen.findByText("1 enrolled user")).toBeInTheDocument();+ expect(screen.getByText("3 users without 2FA")).toBeInTheDocument();+ });++ it("should warn when the encryption key is not set", async () => {+ setup({+ overview: createMockMfaAdminOverview({ encryption_key_set: false }),+ });++ expect(+ await screen.findByText(/MB_ENCRYPTION_SECRET_KEY/),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/index.tsnew file mode 100644index 00000000000..a3dae96a3b2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AdminAuthCard/index.ts@@ -0,0 +1 @@+export * from "./AdminAuthCard";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.tsxnew file mode 100644index 00000000000..fe8c9d7d191--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.tsx@@ -0,0 +1,164 @@+import { t } from "ttag";+import * as Yup from "yup";++import { AuthTextButton } from "metabase/auth/components/AuthButton";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import type { AuthChallengeFormProps } from "metabase/plugins";+import { useDispatch } from "metabase/redux";+import { completeLogin } from "metabase/redux/auth";+import { Box, Stack, Text } from "metabase/ui";+import * as Errors from "metabase/utils/errors";+import {+ useSendEmailOtpMutation,+ useVerifyMfaMutation,+} from "metabase-enterprise/api";++import { TOTP_CODE_LENGTH } from "../../constants";+import { withTotpCodeRules } from "../../schemas";++const CHALLENGE_SCHEMA = Yup.object({+ code: Yup.string().required(Errors.required).when("useRecoveryCode", {+ is: false,+ then: withTotpCodeRules,+ }),+ useRecoveryCode: Yup.boolean(),+});++type ChallengeCodeValues = {+ code: string;+ useRecoveryCode: boolean;+};++type ChallengeCodeFormProps = {+ challengeToken: string;+ remember?: boolean;+};++function ChallengeCodeForm({+ challengeToken,+ remember,+}: ChallengeCodeFormProps) {+ const dispatch = useDispatch();+ const [verifyMfa] = useVerifyMfaMutation();++ const handleSubmit = async ({ code }: ChallengeCodeValues) => {+ await verifyMfa({+ challenge_token: challengeToken,+ code: code.trim().toLowerCase(),+ remember,+ }).unwrap();+ await dispatch(completeLogin()).unwrap();+ };++ return (+ <FormProvider<ChallengeCodeValues>+ initialValues={{ code: "", useRecoveryCode: false }}+ validationSchema={CHALLENGE_SCHEMA}+ onSubmit={handleSubmit}+ >+ {({+ values: { useRecoveryCode },+ isSubmitting,+ setFieldValue,+ setFieldTouched,+ }) => (+ <Form>+ <Stack gap="md">+ <Text c="text-secondary" ta="center">+ {useRecoveryCode+ ? t`Enter one of your recovery codes.`+ : t`Enter the 6-digit code from your authenticator app.`}+ </Text>+ <FormTextInput+ name="code"+ aria-label={+ useRecoveryCode ? t`Recovery code` : t`Authenticator code`+ }+ placeholder={useRecoveryCode ? "xxxxx-xxxxx" : "123456"}+ maxLength={useRecoveryCode ? undefined : TOTP_CODE_LENGTH}+ inputMode={useRecoveryCode ? "text" : "numeric"}+ autoCapitalize="none"+ autoCorrect="off"+ spellCheck={false}+ autoFocus+ />+ <FormSubmitButton label={t`Verify`} variant="filled" w="100%" />+ <FormErrorMessage ta="center" />+ <Box ta="center">+ <AuthTextButton+ disabled={isSubmitting}+ onClick={() => {+ setFieldValue("useRecoveryCode", !useRecoveryCode);+ setFieldValue("code", "");+ setFieldTouched("code", false);+ }}+ >+ {useRecoveryCode+ ? t`Use an authenticator code instead`+ : t`Use a recovery code instead`}+ </AuthTextButton>+ </Box>+ </Stack>+ </Form>+ )}+ </FormProvider>+ );+}++type EmailOtpFormProps = {+ challengeToken: string;+};++function EmailOtpForm({ challengeToken }: EmailOtpFormProps) {+ const [sendEmailOtp, { isSuccess: emailSent }] = useSendEmailOtpMutation();++ const handleSubmit = async () => {+ await sendEmailOtp({ challenge_token: challengeToken }).unwrap();+ };++ return (+ <FormProvider initialValues={{}} onSubmit={handleSubmit}>+ {({ isSubmitting, submitForm }) => (+ <Form>+ <Stack gap="md" ta="center">+ {emailSent && (+ <Text c="text-secondary">{t`Code sent — check your email`}</Text>+ )}+ <AuthTextButton+ disabled={isSubmitting}+ onClick={() => submitForm()}+ >+ {emailSent ? t`Resend code` : t`Email me a code`}+ </AuthTextButton>+ <FormErrorMessage ta="center" />+ </Stack>+ </Form>+ )}+ </FormProvider>+ );+}++export function AuthChallengeForm({+ challengeToken,+ methods,+ remember,+ onCancel,+}: AuthChallengeFormProps) {+ return (+ <Stack mt="2.5rem" gap="md">+ <ChallengeCodeForm challengeToken={challengeToken} remember={remember} />+ {methods?.includes("email") && (+ <EmailOtpForm challengeToken={challengeToken} />+ )}+ <Box ta="center">+ <AuthTextButton onClick={onCancel}>{t`Back to log in`}</AuthTextButton>+ </Box>+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.unit.spec.tsxnew file mode 100644index 00000000000..66726de0f28--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.unit.spec.tsx@@ -0,0 +1,82 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCurrentUserEndpoint,+ setupMfaSendEmailOtpEndpoint,+ setupMfaVerifyEndpoint,+ setupMfaVerifyEndpointError,+ setupPropertiesEndpoints,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { MfaMethod } from "metabase-types/api";+import { createMockSettings, createMockUser } from "metabase-types/api/mocks";++import { AuthChallengeForm } from "./AuthChallengeForm";++type SetupOpts = {+ methods?: MfaMethod[];+ hasVerifyError?: boolean;+};++function setup({ methods = ["totp"], hasVerifyError = false }: SetupOpts = {}) {+ if (hasVerifyError) {+ setupMfaVerifyEndpointError();+ } else {+ setupMfaVerifyEndpoint();+ }+ setupMfaSendEmailOtpEndpoint();+ setupCurrentUserEndpoint(createMockUser());+ setupPropertiesEndpoints(createMockSettings());++ const onCancel = jest.fn();++ renderWithProviders(+ <AuthChallengeForm+ challengeToken="challenge-token"+ methods={methods}+ onCancel={onCancel}+ />,+ );++ return { onCancel };+}++async function submitCode() {+ await userEvent.type(screen.getByLabelText("Authenticator code"), "123456");+ await userEvent.click(screen.getByRole("button", { name: "Verify" }));+}++describe("AuthChallengeForm", () => {+ it("should verify the code and refresh the session", async () => {+ setup();++ await submitCode();++ await waitFor(() => {+ expect(+ fetchMock.callHistory.calls("path:/api/session/mfa/verify"),+ ).toHaveLength(1);+ });+ });++ it("should show an error message when the code is rejected", async () => {+ setup({ hasVerifyError: true });++ await submitCode();++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ });++ it("should send an email code when the email method is available", async () => {+ setup({ methods: ["totp", "email"] });++ await userEvent.click(+ screen.getByRole("button", { name: "Email me a code" }),+ );++ expect(+ await screen.findByText("Code sent — check your email"),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/index.tsnew file mode 100644index 00000000000..87f4e11dbd3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/index.ts@@ -0,0 +1 @@+export * from "./AuthChallengeForm";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.tsnew file mode 100644index 00000000000..7f3d4ea3b03--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.ts@@ -0,0 +1,2 @@+export const TOTP_CODE_LENGTH = 6;+export const RECOVERY_CODE_LENGTH = 11;diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.tsnew file mode 100644index 00000000000..0fcd563afdb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.ts@@ -0,0 +1,11 @@+import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";++import { AccountSecurityPanel } from "./components/AccountSecurityPanel";+import { AdminAuthCard } from "./components/AdminAuthCard";+import { AuthChallengeForm } from "./components/AuthChallengeForm";++export function initializePlugin() {+ PLUGIN_MULTI_FACTOR_AUTH.AuthChallengeForm = AuthChallengeForm;+ PLUGIN_MULTI_FACTOR_AUTH.AccountSecurityPanel = AccountSecurityPanel;+ PLUGIN_MULTI_FACTOR_AUTH.AdminAuthCard = AdminAuthCard;+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/schemas.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/schemas.tsnew file mode 100644index 00000000000..5860b9f5665--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/schemas.ts@@ -0,0 +1,12 @@+import { t } from "ttag";+import type * as Yup from "yup";++import * as Errors from "metabase/utils/errors";++import { TOTP_CODE_LENGTH } from "./constants";++export function withTotpCodeRules(schema: Yup.StringSchema) {+ return schema+ .matches(/^\d*$/, () => t`must contain only digits`)+ .length(TOTP_CODE_LENGTH, Errors.exactLength);+}diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.tsindex fd59f63a995..9ee0c7b54f6 100644--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts@@ -34,6 +34,7 @@ import { initializePlugin as initializeMetabot } from "./metabot";import { initializePlugin as initializeModelPersistence } from "./model_persistence";import { initializePlugin as initializeModeration } from "./moderation";import { initializePlugin as initializeTools } from "./monitor/tools";+import { initializePlugin as initializeMultiFactorAuth } from "./multi_factor_auth";import { initializePlugin as initializeRemoteSync } from "./remote_sync";import { initializePlugin as initializeReplacement } from "./replacement";import { initializePlugin as initializeResourceDownloads } from "./resource_downloads";@@ -85,6 +86,7 @@ export function initializePlugins() {initializeAuditApp();initializeMetabot();initializeModelPersistence();+ initializeMultiFactorAuth();initializeFeatureLevelPermissions();initializeApplicationPermissions();initializeGroupManagers();diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex 50cd3ed1fb7..00fd4a90955 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -40,6 +40,7 @@ export * from "./metric";export * from "./modelIndexes";export * from "./models";export * from "./moderation";+export * from "./multi-factor-auth";export * from "./notification";export * from "./notification-channels";export * from "./oauth";diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex 38e46e1b320..24d6842dcb8 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -22,6 +22,7 @@ export * from "./metric";export * from "./metabot";export * from "./modelIndexes";export * from "./models";+export * from "./multi-factor-auth";export * from "./notification";export * from "./oauth";export * from "./parameters";diff --git a/frontend/src/metabase-types/api/mocks/multi-factor-auth.ts b/frontend/src/metabase-types/api/mocks/multi-factor-auth.tsnew file mode 100644index 00000000000..fb8515b5f51--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/multi-factor-auth.ts@@ -0,0 +1,31 @@+import type {+ MfaAdminOverview,+ MfaEnrollResponse,+ MfaStatus,+} from "metabase-types/api";++export const createMockMfaStatus = (opts?: Partial<MfaStatus>): MfaStatus => ({+ mfa_enabled: true,+ enrolled: false,+ pending: false,+ method: null,+ recovery_codes_remaining: 0,+ ...opts,+});++export const createMockMfaEnrollResponse = (+ opts?: Partial<MfaEnrollResponse>,+): MfaEnrollResponse => ({+ secret: "",+ otpauth_uri: "",+ ...opts,+});++export const createMockMfaAdminOverview = (+ opts?: Partial<MfaAdminOverview>,+): MfaAdminOverview => ({+ encryption_key_set: true,+ enrolled_count: 0,+ unenrolled_count: 0,+ ...opts,+});diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 3000cb6adb7..c7cac017a44 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -118,6 +118,7 @@ export const createMockTokenFeatures = (hosting: false,"metabase-ai-managed": false,"metabot-v3": false,+ "multi-factor-auth": false,"offer-metabase-ai-managed": false,official_collections: false,sandboxes: false,@@ -444,5 +445,6 @@ export const createMockSettings = ("mcp-apps-cors-enabled-clients": [],"mcp-apps-cors-custom-origins": "","transforms-meter-locked": null,+ "mfa-enforcement": "off",...opts,});diff --git a/frontend/src/metabase-types/api/multi-factor-auth.ts b/frontend/src/metabase-types/api/multi-factor-auth.tsnew file mode 100644index 00000000000..f61513d6fe1--- /dev/null+++ b/frontend/src/metabase-types/api/multi-factor-auth.ts@@ -0,0 +1,20 @@+export type MfaMethod = "totp" | "email";++export interface MfaStatus {+ mfa_enabled: boolean;+ enrolled: boolean;+ pending: boolean;+ method: MfaMethod | null;+ recovery_codes_remaining: number;+}++export interface MfaEnrollResponse {+ secret: string;+ otpauth_uri: string;+}++export interface MfaAdminOverview {+ encryption_key_set: boolean;+ enrolled_count: number;+ unenrolled_count: number;+}diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 703ec7b60cc..b494e4b49dd 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -345,6 +345,7 @@ export const tokenFeatures = ["offer-metabase-ai-managed","metabase-ai-managed","metabot-v3",+ "multi-factor-auth","official_collections","sandboxes","scim",@@ -582,6 +583,7 @@ interface PublicSettings {"llm-metabot-configured?"?: boolean | null;"email-configured?": boolean;"embedding-app-origin": string | null;+ "mfa-enforcement"?: "off" | "optional";"embedding-app-origins-sdk": string | null;"embedding-app-origins-interactive": string | null;"enable-password-login": boolean;diff --git a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsxindex 97a7e7d9b74..18afd68ee9b 100644--- a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx+++ b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx@@ -3,6 +3,7 @@ import { useMemo } from "react";import { t } from "ttag";import { UserAvatar } from "metabase/common/components/UserAvatar";+import { useSetting } from "metabase/common/hooks";import { PLUGIN_IS_PASSWORD_USER } from "metabase/plugins";import { Box, Flex, Tabs, Title, rem } from "metabase/ui";import { getFullName } from "metabase/utils/user";@@ -25,6 +26,10 @@ export const AccountHeader = ({() => PLUGIN_IS_PASSWORD_USER.every((predicate) => predicate(user)),[user],);+ const mfaEnforcement = useSetting("mfa-enforcement");+ const isMfaEnabled = mfaEnforcement != null && mfaEnforcement !== "off";+ const hasSecurityTab =+ isMfaEnabled && (hasPasswordChange || user.sso_source === "ldap");const tabs = useMemo(() => [@@ -32,10 +37,13 @@ export const AccountHeader = ({...(hasPasswordChange? [{ name: t`Password`, value: "/account/password" }]: []),+ ...(hasSecurityTab+ ? [{ name: t`Security`, value: "/account/security" }]+ : []),{ name: t`Login History`, value: "/account/login-history" },{ name: t`Notifications`, value: "/account/notifications" },],- [hasPasswordChange],+ [hasPasswordChange, hasSecurityTab],);const userFullName = getFullName(user);diff --git a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsxindex 971e71799e0..ac1183d4484 100644--- a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx+++ b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx@@ -1,5 +1,8 @@-import { fireEvent, render, screen } from "__support__/ui";+import { mockSettings } from "__support__/settings";+import { fireEvent, renderWithProviders, screen } from "__support__/ui";import { PLUGIN_IS_PASSWORD_USER } from "metabase/plugins";+import { createMockState } from "metabase/redux/store/mocks";+import type { User } from "metabase-types/api";import { createMockUser } from "metabase-types/api/mocks";import { AccountHeader } from "./AccountHeader";@@ -13,6 +16,28 @@ const getUser = () =>sso_source: "google",});+type SetupOpts = {+ user?: User;+ isMfaEnabled?: boolean;+};++function setup({ user = getUser(), isMfaEnabled = false }: SetupOpts = {}) {+ const onChangeLocation = jest.fn();++ renderWithProviders(+ <AccountHeader user={user} onChangeLocation={onChangeLocation} />,+ {+ storeInitialState: createMockState({+ settings: mockSettings({+ "mfa-enforcement": isMfaEnabled ? "optional" : "off",+ }),+ }),+ },+ );++ return { onChangeLocation };+}+describe("AccountHeader", () => {const ORIGINAL_PLUGIN_IS_PASSWORD_USER = [...PLUGIN_IS_PASSWORD_USER];@@ -29,9 +54,7 @@ describe("AccountHeader", () => {});it("should show all tabs for a regular user", () => {- const user = getUser();-- render(<AccountHeader user={user} />);+ setup();expect(screen.getByText("Profile")).toBeInTheDocument();expect(screen.getByText("Password")).toBeInTheDocument();@@ -40,28 +63,37 @@ describe("AccountHeader", () => {});it("should show the password tab if it is enabled by a plugin", () => {- const user = getUser();PLUGIN_IS_PASSWORD_USER.push((user) => user.sso_source === "google");- render(<AccountHeader user={user} />);+ setup();expect(screen.getByText("Password")).toBeInTheDocument();});it("should hide the password tab if it is disabled by a plugin", () => {- const user = getUser();PLUGIN_IS_PASSWORD_USER.push((user) => user.sso_source !== "google");- render(<AccountHeader user={user} />);+ setup();expect(screen.queryByText("Password")).not.toBeInTheDocument();});- it("should change location when a tab is selected", () => {- const user = getUser();- const onChangeLocation = jest.fn();+ describe("security tab", () => {+ it("should show the tab when two-factor authentication is enabled for the instance", () => {+ setup({ isMfaEnabled: true });- render(<AccountHeader user={user} onChangeLocation={onChangeLocation} />);+ expect(screen.getByText("Security")).toBeInTheDocument();+ });++ it("should hide the tab when two-factor authentication is disabled for the instance", () => {+ setup({ isMfaEnabled: false });++ expect(screen.queryByText("Security")).not.toBeInTheDocument();+ });+ });++ it("should change location when a tab is selected", () => {+ const { onChangeLocation } = setup();fireEvent.click(screen.getByText("Profile"));expect(onChangeLocation).toHaveBeenCalledWith("/account/profile");diff --git a/frontend/src/metabase/account/app/components/AccountLayout/AccountLayout.unit.spec.tsx b/frontend/src/metabase/account/app/components/AccountLayout/AccountLayout.unit.spec.tsxindex 7dc7af2975f..fd8d0e07667 100644--- a/frontend/src/metabase/account/app/components/AccountLayout/AccountLayout.unit.spec.tsx+++ b/frontend/src/metabase/account/app/components/AccountLayout/AccountLayout.unit.spec.tsx@@ -1,23 +1,32 @@-import { render, screen } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";+import type { User } from "metabase-types/api";import { createMockUser } from "metabase-types/api/mocks";import AccountLayout from "./AccountLayout";+type SetupOpts = {+ user?: User;+};++function setup({ user = createMockUser() }: SetupOpts = {}) {+ renderWithProviders(+ <AccountLayout user={user} onChangeLocation={() => {}}>+ Content+ </AccountLayout>,+ );+}+describe("AccountLayout", () => {it("should render header and content", () => {- const user = createMockUser({- id: 1,- first_name: "John",- last_name: "Doe",- email: "[email protected]",+ setup({+ user: createMockUser({+ id: 1,+ first_name: "John",+ last_name: "Doe",+ email: "[email protected]",+ }),});- render(- <AccountLayout user={user} onChangeLocation={() => {}}>- Content- </AccountLayout>,- );-expect(screen.getByText("Profile")).toBeInTheDocument();expect(screen.getByText("Content")).toBeInTheDocument();});diff --git a/frontend/src/metabase/account/routes.tsx b/frontend/src/metabase/account/routes.tsxindex 519501a5a99..d62a2f1ca9d 100644--- a/frontend/src/metabase/account/routes.tsx+++ b/frontend/src/metabase/account/routes.tsx@@ -1,5 +1,6 @@import type { Store } from "@reduxjs/toolkit";+import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";import type { State } from "metabase/redux/store";import { IndexRedirect, Route, type RouteComponent } from "metabase/router";@@ -19,6 +20,10 @@ export const getAccountRoutes = (<IndexRedirect to="profile" /><Route path="profile" component={UserProfileApp} /><Route path="password" component={UserPasswordApp} />+ <Route+ path="security"+ component={PLUGIN_MULTI_FACTOR_AUTH.AccountSecurityPanel}+ /><Route path="login-history" component={LoginHistoryApp} />{getNotificationRoutes()}</Route>diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/AuthenticationSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/AuthenticationSettingsPage.tsxindex ccd296036f0..796734a8a17 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/AuthenticationSettingsPage.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/AuthenticationSettingsPage.tsx@@ -7,6 +7,7 @@ import { hasAnySsoFeature } from "metabase/common/utils/plan";import {type AuthSettingsPageTab,PLUGIN_AUTH_PROVIDERS,+ PLUGIN_MULTI_FACTOR_AUTH,} from "metabase/plugins";import { Box, Flex, Stack } from "metabase/ui";@@ -37,6 +38,7 @@ export function AuthenticationSettingsPage({<GoogleAuthCard /><LdapAuthCard /><ApiKeysAuthCard />+ <PLUGIN_MULTI_FACTOR_AUTH.AdminAuthCard /></Stack><Box style={{ flexShrink: 0 }}><UpsellSSO location="authentication-sidebar" />diff --git a/frontend/src/metabase/api/session.ts b/frontend/src/metabase/api/session.tsindex e9e0d711933..9c11c32ff39 100644--- a/frontend/src/metabase/api/session.ts+++ b/frontend/src/metabase/api/session.ts@@ -7,6 +7,7 @@ import {import MetabaseSettings from "metabase/utils/settings";import type {EnterpriseSettings,+ MfaMethod,PasswordResetTokenStatus,} from "metabase-types/api";@@ -19,6 +20,19 @@ export interface SessionResponse {id: string;}+export interface MfaChallengeResponse {+ mfa_required: true;+ methods: MfaMethod[];+ challenge_token: string;+}++export type CreateSessionResponse = SessionResponse | MfaChallengeResponse;++export const isMfaChallenge = (+ response: CreateSessionResponse,+): response is MfaChallengeResponse =>+ "mfa_required" in response && response.mfa_required === true;+export interface GoogleAuthData {token: string;remember?: boolean;@@ -35,7 +49,7 @@ export interface SsoLogoutResponse {export const sessionApi = Api.injectEndpoints({endpoints: (builder) => ({- createSession: builder.mutation<SessionResponse, LoginData>({+ createSession: builder.mutation<CreateSessionResponse, LoginData>({query: (body) => ({method: "POST",url: "/api/session",diff --git a/frontend/src/metabase/api/settings.ts b/frontend/src/metabase/api/settings.tsindex 7d4cb88601c..61b0c441500 100644--- a/frontend/src/metabase/api/settings.ts+++ b/frontend/src/metabase/api/settings.ts@@ -58,6 +58,7 @@ export const settingsApi = Api.injectEndpoints({tag("session-properties"),...(key === "uploads-settings" ? [listTag("database")] : []),...(key === "llm-anthropic-api-key" ? [listTag("llm-models")] : []),+ ...(key === "mfa-enforcement" ? [tag("mfa-status")] : []),// Enabling tenants creates the "all-external-users" permission group...(key === "use-tenants" ? [listTag("permissions-group")] : []),diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex 5cddab76023..9e96d0d4838 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -32,6 +32,7 @@ export const TAG_TYPES = ["llm-models","logger-preset","measure",+ "mfa-status","model-index","notification","oauth-authorization",diff --git a/frontend/src/metabase/auth/components/AuthButton/AuthButton.styled.tsx b/frontend/src/metabase/auth/components/AuthButton/AuthButton.module.csssimilarity index 56%rename from frontend/src/metabase/auth/components/AuthButton/AuthButton.styled.tsxrename to frontend/src/metabase/auth/components/AuthButton/AuthButton.module.cssindex 42b8b878bd7..8519b18d9a0 100644--- a/frontend/src/metabase/auth/components/AuthButton/AuthButton.styled.tsx+++ b/frontend/src/metabase/auth/components/AuthButton/AuthButton.module.css@@ -1,28 +1,27 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--import { Link } from "metabase/common/components/Link";--export const TextLink = styled(Link)`+.link {cursor: pointer;color: var(--mb-color-text-primary);- &:hover {+ &:hover,+ &:focus {color: var(--mb-color-core-brand);}-`;-export const CardLink = styled(TextLink)`+ &:disabled {+ cursor: default;+ color: var(--mb-color-text-disabled);+ }+}++.card {+ width: 100%;display: flex;- justify-content: center;align-items: center;+ justify-content: center;padding: 1.25rem;+ font-weight: 700;+ line-height: 1rem;background-color: var(--mb-color-background_page-primary);box-shadow: 0 3px 10px var(--mb-color-shadow-default);border-radius: 6px;-`;--export const CardText = styled.span`- font-weight: 700;- line-height: 1rem;-`;+}diff --git a/frontend/src/metabase/auth/components/AuthButton/AuthButton.tsx b/frontend/src/metabase/auth/components/AuthButton/AuthButton.tsxindex 5a2fd19ccfb..19c1d8ed85d 100644--- a/frontend/src/metabase/auth/components/AuthButton/AuthButton.tsx+++ b/frontend/src/metabase/auth/components/AuthButton/AuthButton.tsx@@ -1,27 +1,46 @@-import type { ReactNode } from "react";+import cx from "classnames";+import type { ComponentPropsWithoutRef, FunctionComponent } from "react";-import { CardLink, CardText, TextLink } from "./AuthButton.styled";+import type { LinkProps } from "metabase/router";+import { Link } from "metabase/router";+import type { AnchorProps, CardProps, UnstyledButtonProps } from "metabase/ui";+import { Anchor, Card, UnstyledButton } from "metabase/ui";-interface AuthButtonProps {- link?: string;- isCard?: boolean;- children?: ReactNode;- onClick?: () => void;+import S from "./AuthButton.module.css";++type AuthButtonProps = UnstyledButtonProps & ComponentPropsWithoutRef<"button">;++export function AuthTextButton({ className, ...props }: AuthButtonProps) {+ return <UnstyledButton className={cx(S.link, className)} {...props} />;+}++export function AuthCardButton({ className, ...props }: AuthButtonProps) {+ return (+ <UnstyledButton className={cx(S.link, S.card, className)} {...props} />+ );}-export const AuthButton = ({- link = "",- isCard,- children,- onClick,-}: AuthButtonProps): JSX.Element => {- return isCard ? (- <CardLink to={link} onClick={onClick}>- <CardText>{children}</CardText>- </CardLink>- ) : (- <TextLink to={link} onClick={onClick}>- {children}- </TextLink>+type AuthTextLinkProps = AnchorProps & Omit<LinkProps, "ref">;++export function AuthTextLink({ className, ...props }: AuthTextLinkProps) {+ return (+ <Anchor<FunctionComponent<LinkProps>>+ component={Link}+ className={cx(S.link, className)}+ underline="never"+ {...props}+ />);-};+}++type AuthCardLinkProps = CardProps & Omit<LinkProps, "ref">;++export function AuthCardLink({ className, ...props }: AuthCardLinkProps) {+ return (+ <Card<FunctionComponent<LinkProps>>+ component={Link}+ className={cx(S.link, S.card, className)}+ {...props}+ />+ );+}diff --git a/frontend/src/metabase/auth/components/AuthButton/AuthButton.unit.spec.tsx b/frontend/src/metabase/auth/components/AuthButton/AuthButton.unit.spec.tsxindex d785ad384b8..4dc5d0a0ffb 100644--- a/frontend/src/metabase/auth/components/AuthButton/AuthButton.unit.spec.tsx+++ b/frontend/src/metabase/auth/components/AuthButton/AuthButton.unit.spec.tsx@@ -1,25 +1,53 @@import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";-import { AuthButton } from "./AuthButton";+import {+ AuthCardButton,+ AuthCardLink,+ AuthTextButton,+ AuthTextLink,+} from "./AuthButton";-interface SetupOpts {- isCard?: boolean;-}+describe("AuthTextButton", () => {+ it("should render a button", () => {+ renderWithProviders(<AuthTextButton>Sign in</AuthTextButton>);-const setup = ({ isCard }: SetupOpts = {}) => {- renderWithProviders(<AuthButton isCard={isCard}>Sign in</AuthButton>);-};+ expect(screen.getByRole("button", { name: "Sign in" })).toBeInTheDocument();+ });+});-describe("AuthButton", () => {- it("should render a card", () => {- setup({ isCard: true });+describe("AuthCardButton", () => {+ it("should render a card button", () => {+ renderWithProviders(<AuthCardButton>Sign in</AuthCardButton>);- expect(screen.getByText("Sign in")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Sign in" })).toBeInTheDocument();});+});+describe("AuthTextLink", () => {it("should render a link", () => {- setup();+ renderWithProviders(+ <Route+ path="/"+ component={() => <AuthTextLink to="/auth/login">Sign in</AuthTextLink>}+ />,+ { withRouter: true },+ );++ expect(screen.getByRole("link", { name: "Sign in" })).toBeInTheDocument();+ });+});++describe("AuthCardLink", () => {+ it("should render a card link", () => {+ renderWithProviders(+ <Route+ path="/"+ component={() => <AuthCardLink to="/auth/login">Sign in</AuthCardLink>}+ />,+ { withRouter: true },+ );- expect(screen.getByText("Sign in")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Sign in" })).toBeInTheDocument();});});diff --git a/frontend/src/metabase/auth/components/PasswordButton/PasswordButton.tsx b/frontend/src/metabase/auth/components/PasswordButton/PasswordButton.tsxindex 27306548a73..137921f0351 100644--- a/frontend/src/metabase/auth/components/PasswordButton/PasswordButton.tsx+++ b/frontend/src/metabase/auth/components/PasswordButton/PasswordButton.tsx@@ -4,7 +4,7 @@ import { useSelector } from "metabase/redux";import * as Urls from "metabase/urls";import { getIsLdapEnabled } from "../../selectors";-import { AuthButton } from "../AuthButton";+import { AuthTextLink } from "../AuthButton";interface PasswordButtonProps {redirectUrl?: string;@@ -14,10 +14,10 @@ export const PasswordButton = ({ redirectUrl }: PasswordButtonProps) => {const isLdapEnabled = useSelector(getIsLdapEnabled);return (- <AuthButton link={Urls.password(redirectUrl)}>+ <AuthTextLink to={Urls.password(redirectUrl)}>{isLdapEnabled? t`Sign in with username or email`: t`Sign in with email`}- </AuthButton>+ </AuthTextLink>);};diff --git a/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx b/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsxindex 9906a4f9625..3a7377be186 100644--- a/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx+++ b/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx@@ -1,6 +1,8 @@-import { useCallback } from "react";+import { useCallback, useState } from "react";import { t } from "ttag";+import type { MfaChallengeResponse } from "metabase/api/session";+import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";import type { LoginData } from "metabase/redux/auth";import { login } from "metabase/redux/auth";@@ -10,7 +12,7 @@ import {getHasSessionCookies,getIsLdapEnabled,} from "../../selectors";-import { AuthButton } from "../AuthButton";+import { AuthTextLink } from "../AuthButton";import { LoginForm } from "../LoginForm";import { ActionList, ActionListItem } from "./PasswordPanel.styled";@@ -25,13 +27,35 @@ export const PasswordPanel = ({ redirectUrl }: PasswordPanelProps) => {const hasSessionCookies = useSelector(getHasSessionCookies);const dispatch = useDispatch();+ const [mfaChallenge, setMfaChallenge] = useState<MfaChallengeResponse | null>(+ null,+ );+ const [remember, setRemember] = useState(false);+const handleSubmit = useCallback(async (data: LoginData) => {- await dispatch(login({ data, redirectUrl })).unwrap();+ const { mfaChallenge: challenge } = await dispatch(+ login({ data, redirectUrl }),+ ).unwrap();+ if (challenge) {+ setRemember(Boolean(data.remember));+ setMfaChallenge(challenge);+ }},[dispatch, redirectUrl],);+ if (mfaChallenge) {+ return (+ <PLUGIN_MULTI_FACTOR_AUTH.AuthChallengeForm+ challengeToken={mfaChallenge.challenge_token}+ methods={mfaChallenge.methods}+ remember={remember}+ onCancel={() => setMfaChallenge(null)}+ />+ );+ }+return (<div><LoginForm@@ -41,9 +65,9 @@ export const PasswordPanel = ({ redirectUrl }: PasswordPanelProps) => {/><ActionList><ActionListItem>- <AuthButton link="/auth/forgot_password">+ <AuthTextLink to="/auth/forgot_password">{t`I seem to have forgotten my password`}- </AuthButton>+ </AuthTextLink></ActionListItem>{providers.map((provider) => (<ActionListItem key={provider.name}>diff --git a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsxindex 2fe5834e02b..71bff3e1c14 100644--- a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx+++ b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx@@ -10,6 +10,7 @@ import { useDispatch } from "metabase/redux";import { resetPassword } from "metabase/redux/auth";import { replace } from "metabase/router";import { Button } from "metabase/ui";+import * as Urls from "metabase/urls";import type { ResetPasswordData } from "../../types";import { AuthLayout } from "../AuthLayout";@@ -42,8 +43,12 @@ export const ResetPassword = ({const handlePasswordSubmit = useCallback(async ({ password }: ResetPasswordData) => {- await dispatch(resetPassword({ token, password })).unwrap();- dispatch(replace(redirectUrl || "/"));+ const { sessionCreated } = await dispatch(+ resetPassword({ token, password }),+ ).unwrap();+ dispatch(+ replace(sessionCreated ? redirectUrl || "/" : Urls.login(redirectUrl)),+ );sendToast({ message: t`You've updated your password.` });},[token, dispatch, redirectUrl, sendToast],diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 613011b1967..7c5a123d5d4 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -99,6 +99,10 @@ export {type MetabaseAIProviderSetupProps,} from "./oss/metabot";export { PLUGIN_MODEL_PERSISTENCE } from "./oss/model-persistence";+export {+ PLUGIN_MULTI_FACTOR_AUTH,+ type AuthChallengeFormProps,+} from "./oss/multi-factor-auth";export {PLUGIN_MODERATION,type RevisionOrModerationEvent,@@ -205,6 +209,7 @@ import { reinitialize as reinitializeLibrary } from "./oss/library";import { reinitialize as reinitializeMetabot } from "./oss/metabot";import { reinitialize as reinitializeModelPersistence } from "./oss/model-persistence";import { reinitialize as reinitializeModeration } from "./oss/moderation";+import { reinitialize as reinitializeMultiFactorAuth } from "./oss/multi-factor-auth";import { reinitialize as reinitializeNotificationsSdk } from "./oss/notifications-sdk";import { reinitialize as reinitializePermissions } from "./oss/permissions";import { reinitialize as reinitializeRemoteSync } from "./oss/remote-sync";@@ -250,6 +255,7 @@ export function reinitialize() {reinitializeMetabot();reinitializeModelPersistence();reinitializeModeration();+ reinitializeMultiFactorAuth();reinitializePermissions();reinitializeRemoteSync();reinitializeReplacement();diff --git a/frontend/src/metabase/plugins/oss/multi-factor-auth.ts b/frontend/src/metabase/plugins/oss/multi-factor-auth.tsnew file mode 100644index 00000000000..595c7d01106--- /dev/null+++ b/frontend/src/metabase/plugins/oss/multi-factor-auth.ts@@ -0,0 +1,27 @@+import {+ NotFoundPlaceholder,+ PluginPlaceholder,+} from "metabase/plugins/components/PluginPlaceholder";+import type { MfaMethod } from "metabase-types/api";++export type AuthChallengeFormProps = {+ challengeToken: string;+ methods: MfaMethod[];+ remember?: boolean;+ onCancel: () => void;+};++const getDefaultPluginMultiFactorAuth = () => ({+ AuthChallengeForm: PluginPlaceholder<AuthChallengeFormProps>,+ AccountSecurityPanel: NotFoundPlaceholder,+ AdminAuthCard: PluginPlaceholder,+});++export const PLUGIN_MULTI_FACTOR_AUTH = getDefaultPluginMultiFactorAuth();++/**+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.+ */+export function reinitialize() {+ Object.assign(PLUGIN_MULTI_FACTOR_AUTH, getDefaultPluginMultiFactorAuth());+}diff --git a/frontend/src/metabase/redux/auth.ts b/frontend/src/metabase/redux/auth.tsindex f5f5125ab9a..adcd761ae7c 100644--- a/frontend/src/metabase/redux/auth.ts+++ b/frontend/src/metabase/redux/auth.ts@@ -6,7 +6,11 @@ import {} from "@reduxjs/toolkit";import { loadLocalization } from "metabase/api/localization";-import { sessionApi } from "metabase/api/session";+import {+ type MfaChallengeResponse,+ isMfaChallenge,+ sessionApi,+} from "metabase/api/session";import { openNavbar } from "metabase/redux/app";import { refreshSiteSettings } from "metabase/redux/settings";import { clearCurrentUser, refreshCurrentUser } from "metabase/redux/user";@@ -55,23 +59,43 @@ export const refreshSession = createAsyncThunk(},);+export const COMPLETE_LOGIN = "metabase/auth/COMPLETE_LOGIN";+export const completeLogin = createAsyncThunk(+ COMPLETE_LOGIN,+ async (_, { dispatch }) => {+ await dispatch(refreshSession()).unwrap();+ if (!isSmallScreen()) {+ dispatch(openNavbar());+ }+ },+);+interface LoginPayload {data: LoginData;redirectUrl?: string;}+export interface LoginResult {+ mfaChallenge?: MfaChallengeResponse;+}+export const LOGIN = "metabase/auth/LOGIN";export const login = createAsyncThunk(LOGIN,async ({ data }: LoginPayload, { dispatch, rejectWithValue }) => {try {- await dispatch(+ const result = await dispatch(sessionApi.endpoints.createSession.initiate(data),).unwrap();- await dispatch(refreshSession()).unwrap();- if (!isSmallScreen()) {- dispatch(openNavbar());++ if (isMfaChallenge(result)) {+ const challenge: LoginResult = { mfaChallenge: result };+ return challenge;}++ await dispatch(completeLogin()).unwrap();+ const success: LoginResult = {};+ return success;} catch (error) {return rejectWithValue(error);}@@ -98,10 +122,7 @@ export const loginGoogle = createAsyncThunk(remember,}),).unwrap();- await dispatch(refreshSession()).unwrap();- if (!isSmallScreen()) {- dispatch(openNavbar());- }+ await dispatch(completeLogin()).unwrap();} catch (error) {return rejectWithValue(error);}@@ -169,13 +190,14 @@ export const resetPassword = createAsyncThunk(RESET_PASSWORD,async ({ token, password }: ResetPasswordPayload,- { dispatch, rejectWithValue },+ { dispatch, getState, rejectWithValue },) => {try {await dispatch(sessionApi.endpoints.resetPassword.initiate({ token, password }),).unwrap();await dispatch(refreshSession()).unwrap();+ return { sessionCreated: getUser(getState()) != null };} catch (error) {return rejectWithValue(error);}@@ -221,6 +243,16 @@ export const reducer = createReducer(initialState, (builder) => {builder.addCase(loginGoogle.fulfilled, (state) => {state.loginPending = false;});++ builder.addCase(completeLogin.pending, (state) => {+ state.loginPending = true;+ });+ builder.addCase(completeLogin.fulfilled, (state) => {+ state.loginPending = false;+ });+ builder.addCase(completeLogin.rejected, (state) => {+ state.loginPending = false;+ });builder.addCase(pauseRedirect.toString(), (state) => {state.redirect = false;});diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex 56a808bc001..10267597e66 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -35,6 +35,7 @@ export * from "./measure";export * from "./metabot";export * from "./metric";export * from "./model-indexes";+export * from "./multi-factor-auth";export * from "./native-query-snippet";export * from "./oauth";export * from "./performance";diff --git a/frontend/test/__support__/server-mocks/multi-factor-auth.ts b/frontend/test/__support__/server-mocks/multi-factor-auth.tsnew file mode 100644index 00000000000..9bee49cecd5--- /dev/null+++ b/frontend/test/__support__/server-mocks/multi-factor-auth.ts@@ -0,0 +1,57 @@+import fetchMock from "fetch-mock";++import type {+ MfaAdminOverview,+ MfaEnrollResponse,+ MfaStatus,+} from "metabase-types/api";++export function setupMfaStatusEndpoint(status: MfaStatus) {+ fetchMock.get("path:/api/ee/mfa/status", status);+}++export function setupMfaStatusEndpointError() {+ fetchMock.get("path:/api/ee/mfa/status", 500);+}++export function setupMfaEnrollEndpoint(response: MfaEnrollResponse) {+ fetchMock.post("path:/api/ee/mfa/enroll", response);+}++export function setupMfaEnrollEndpointError() {+ fetchMock.post("path:/api/ee/mfa/enroll", 500);+}++export function setupMfaDisableEndpoint() {+ fetchMock.post("path:/api/ee/mfa/disable", 204);+}++export function setupMfaDisableEndpointError() {+ fetchMock.post("path:/api/ee/mfa/disable", 500);+}++export function setupMfaRecoveryCodesEndpoint(recoveryCodes: string[]) {+ fetchMock.post("path:/api/ee/mfa/recovery-codes", {+ recovery_codes: recoveryCodes,+ });+}++export function setupMfaRecoveryCodesEndpointError() {+ fetchMock.post("path:/api/ee/mfa/recovery-codes", 500);+}++export function setupMfaAdminOverviewEndpoint(overview: MfaAdminOverview) {+ fetchMock.get("path:/api/ee/mfa/admin/overview", overview);+}++export function setupMfaVerifyEndpoint() {+ fetchMock.post("path:/api/session/mfa/verify", { id: "session-id" });+}++export function setupMfaVerifyEndpointError() {+ fetchMock.post("path:/api/session/mfa/verify", 500);+}++export function setupMfaSendEmailOtpEndpoint() {+ fetchMock.post("path:/api/session/mfa/send-email-otp", { success: true });+}diff --git a/package.json b/package.jsonindex f9f241c509d..0509ec78997 100644--- a/package.json+++ b/package.json@@ -152,6 +152,7 @@"react-innertext": "^1.1.5","react-is": "^18.2.0","react-markdown": "^9.0.0",+ "react-qr-code": "^2.0.15","react-redux": "^9.1.2","react-resizable": "^3.1.3","react-router": "3",diff --git a/resources/migrations/059_update_migrations.yaml b/resources/migrations/059_update_migrations.yamlindex 18f88acf6bc..f97cb8ad913 100644--- a/resources/migrations/059_update_migrations.yaml+++ b/resources/migrations/059_update_migrations.yaml@@ -3482,6 +3482,29 @@ databaseChangeLog:- customChange:class: "metabase.app_db.custom_migrations.DropMedallionNamesForDataLayer"+ - changeSet:+ id: v59.2026-07-10T22:29:16+ author: escherize+ comment: Add confirmed_at to auth_identity so MFA enrollment state is queryable in SQL+ changes:+ - addColumn:+ tableName: auth_identity+ columns:+ - column:+ name: confirmed_at+ type: ${timestamp_type}+ remarks: When this identity was confirmed (e.g. MFA enrollment completed). Null = unconfirmed.+ constraints:+ nullable: true++ - changeSet:+ id: v59.2026-07-10T22:29:17+ author: escherize+ comment: Backfill auth_identity.confirmed_at from the (possibly encrypted) credentials JSON+ changes:+ - customChange:+ class: "metabase.app_db.custom_migrations.BackfillMfaConfirmedAt"+# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<########################################################################################################################diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.cljindex 30b6030ff91..898ac86ba49 100644--- a/src/metabase/analytics/stats.clj+++ b/src/metabase/analytics/stats.clj@@ -795,7 +795,7 @@(defn- ee-snowplow-features-data'[]- (let [features [:sso-jwt :sso-saml :scim :sandboxes :email-allow-list :semantic-search :workspaces]]+ (let [features [:sso-jwt :sso-saml :scim :multi-factor-auth :sandboxes :email-allow-list :semantic-search :workspaces]](map(fn [feature]{:name featurediff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.cljindex 545524031e0..1ca8956e058 100644--- a/src/metabase/app_db/custom_migrations.clj+++ b/src/metabase/app_db/custom_migrations.clj@@ -2215,3 +2215,25 @@:where [:and[:not= :embed_url nil][:= :embedding_hostname nil]]})))++(define-migration BackfillMfaConfirmedAt+ ;; MFA enrollment confirmation used to live only inside the credentials JSON — encrypted at+ ;; rest when MB_ENCRYPTION_SECRET_KEY is set, and therefore invisible to SQL. Lift it into the+ ;; new auth_identity.confirmed_at column so enrollment state is queryable (admin visibility of+ ;; users without 2FA; Phase 2 mfa-required). The JSON keeps working as the source for rows+ ;; written by older code; new code writes only the column.+ (run! (fn [{:keys [id credentials]}]+ (let [creds (encrypted-json-out credentials)+ confirmed-at (when (map? creds)+ (try+ (some-> ^String (:confirmed_at creds) java.time.OffsetDateTime/parse)+ (catch Exception _ nil)))]+ (when confirmed-at+ (t2/query {:update :auth_identity+ :set {:confirmed_at confirmed-at}+ :where [:= :id id]}))))+ (t2/reducible-query {:select [:id :credentials]+ :from [:auth_identity]+ :where [:and+ [:= :provider "totp"]+ [:= :confirmed_at nil]]})))diff --git a/src/metabase/app_db/encryption.clj b/src/metabase/app_db/encryption.cljindex bc9870dd2ca..8d530810f5b 100644--- a/src/metabase/app_db/encryption.clj+++ b/src/metabase/app_db/encryption.clj@@ -18,7 +18,8 @@[:metabase_database :admin_details][:core_user :settings][:channel :details]- [:workspace_database :database_details]])+ [:workspace_database :database_details]+ [:auth_identity :credentials]])(defn- reencrypt-encrypted-json-column!"Re-encrypt `column` for every row in `table` using `encrypt-str-fn`. See `encrypted-json-columns`."diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.cljindex 6e8990e01de..1c251ea134d 100644--- a/src/metabase/audit_app/events/audit_log.clj+++ b/src/metabase/audit_app/events/audit_log.clj@@ -182,6 +182,9 @@(derive :event/user-reactivated ::user-event)(derive :event/password-reset-initiated ::user-event)(derive :event/password-reset-successful ::user-event)+(derive :event/mfa-verification-failed ::user-event)+(derive :event/mfa-enrolled ::user-event)+(derive :event/mfa-disabled ::user-event)(methodical/defmethod events/publish-event! ::user-event[topic event]diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.cljindex 607a2b35473..85222354724 100644--- a/src/metabase/auth_identity/models/auth_identity.clj+++ b/src/metabase/auth_identity/models/auth_identity.clj@@ -35,9 +35,14 @@(update 1 t/instant))))credentials))+;; `credentials` is encrypted at rest (whole column) so secrets stored in it — e.g. the TOTP+;; shared secret — survive `rotate-encryption-key`, which re-encrypts whole columns and cannot+;; reach fields nested inside JSON. The column is listed in+;; `metabase.app-db.encryption/encrypted-json-columns`. Rows written before encryption was+;; introduced are plaintext JSON; `maybe-decrypt` passes them through unchanged.(t2/deftransforms :model/AuthIdentity- {:credentials {:in mi/json-in- :out (comp parse-credentials-timestamps-out mi/json-out-with-keywordization)}+ {:credentials {:in mi/encrypted-json-in+ :out (comp parse-credentials-timestamps-out mi/encrypted-json-out)}:metadata mi/transform-json})(defmethod serdes/hash-fields :model/AuthIdentitydiff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.cljindex 1b4272a0695..dc47391e106 100644--- a/src/metabase/auth_identity/provider.clj+++ b/src/metabase/auth_identity/provider.clj@@ -284,6 +284,13 @@:success? true:redirect-url redirect-url))))+(defenterprise apply-mfa-gate+ "Decide whether a successful first-factor login must complete a second factor before a session is+ created. OSS has no native MFA, so the login result passes through unchanged."+ metabase-enterprise.mfa.core+ [_provider login-result]+ login-result)+(methodical/defmethod login! :around ::provider[provider request](as-> (merge request (authenticate provider request)) $@@ -296,9 +303,11 @@(and (:provider-id $) (:user-data $))(assoc-in [:user-data :provider-id] (:provider-id $)))(next-method provider $)+ (apply-mfa-gate provider $)(cond-> $- (:user $) (create-session! provider))- (select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data :claims :oidc-provider-key])))+ (and (:user $) (not (:mfa/pending? $))) (create-session! provider))+ (select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data :claims :oidc-provider-key+ :mfa/pending? :mfa/methods :mfa/first-factor])))(defenterprise sso-user-fields"Return the list of User model fields that should be populated from SSO user data.diff --git a/src/metabase/channel/email/messages.clj b/src/metabase/channel/email/messages.cljindex 6cbdee632cc..f86216f0530 100644--- a/src/metabase/channel/email/messages.clj+++ b/src/metabase/channel/email/messages.clj@@ -107,6 +107,55 @@;;; ### Public Interface+;;; ---- MFA notification emails ----++(defn send-mfa-enabled-email!+ "Send an email notifying `email` that two-factor authentication was enabled on their account."+ [email]+ {:pre [(u/email? email)]}+ (send-email-with-logo!+ {:subject (trs "[{0}] Two-factor authentication was enabled on your account" (app-name-trs))+ :recipients [email]+ :message-type :html+ :message (channel.template/render "mfa_enabled" (assoc (common-context) :logoHeader true))}))++(defn send-mfa-disabled-email!+ "Send an email notifying `email` that two-factor authentication was disabled on their account.+ The phrase 'using a verification code' is deliberate — the server can assert only what+ credential authorized the action, not who acted."+ [email]+ {:pre [(u/email? email)]}+ (send-email-with-logo!+ {:subject (trs "[{0}] Two-factor authentication was disabled on your account" (app-name-trs))+ :recipients [email]+ :message-type :html+ :message (channel.template/render "mfa_disabled" (assoc (common-context) :logoHeader true))}))++(defn send-mfa-removed-by-admin-email!+ "Send an email notifying `email` that an administrator removed their two-factor authentication."+ [email]+ {:pre [(u/email? email)]}+ (send-email-with-logo!+ {:subject (trs "[{0}] Two-factor authentication was removed from your account" (app-name-trs))+ :recipients [email]+ :message-type :html+ :message (channel.template/render "mfa_removed_by_admin" (assoc (common-context) :logoHeader true))}))++(defn send-mfa-login-code-email!+ "Send an email containing a one-time sign-in `code` to `email`.+ Uses [[metabase.channel.email/send-message-or-throw!]] directly so that SMTP delivery failures+ propagate to the caller — the /send-email-otp endpoint returns 500 on failure. Because of this,+ the data-URI logo-attachment handling in [[send-email-with-logo!]] is skipped."+ [email code]+ {:pre [(u/email? email) (string? code)]}+ (email/send-message-or-throw!+ {:subject (trs "[{0}] Your sign-in code" (app-name-trs))+ :recipients [email]+ :message-type :html+ :message (channel.template/render "mfa_login_code" (assoc (common-context) :logoHeader true :code code))}))++;;; ---- end MFA notification emails ----+(defn all-admin-recipients"Return a sequence of email addresses for all Admin users who have accepted their invitation (i.e. have logged in atleast once). Admins who have been invited but not yet accepted are excluded — they shouldn't receive notificationsdiff --git a/src/metabase/channel/email/mfa_disabled.hbs b/src/metabase/channel/email/mfa_disabled.hbsnew file mode 100644index 00000000000..946e5fac2bd--- /dev/null+++ b/src/metabase/channel/email/mfa_disabled.hbs@@ -0,0 +1,6 @@+{{> _header }}+ <div>+ <p>Two-factor authentication was turned off for your {{applicationName}} account using a verification code.</p>+ <p style="padding-top: 1em; font-size: small; color: {{colorTextMedium}};">If you did not do this, contact your administrator immediately.</p>+ </div>+{{> _footer }}diff --git a/src/metabase/channel/email/mfa_enabled.hbs b/src/metabase/channel/email/mfa_enabled.hbsnew file mode 100644index 00000000000..a7ee2f8b0bd--- /dev/null+++ b/src/metabase/channel/email/mfa_enabled.hbs@@ -0,0 +1,6 @@+{{> _header }}+ <div>+ <p>Two-factor authentication is now required when you sign in to {{applicationName}}.</p>+ <p style="padding-top: 1em; font-size: small; color: {{colorTextMedium}};">If you did not do this, reset your password and contact your administrator immediately.</p>+ </div>+{{> _footer }}diff --git a/src/metabase/channel/email/mfa_login_code.hbs b/src/metabase/channel/email/mfa_login_code.hbsnew file mode 100644index 00000000000..3e6024c14e7--- /dev/null+++ b/src/metabase/channel/email/mfa_login_code.hbs@@ -0,0 +1,7 @@+{{> _header }}+ <div style="text-align: center;">+ <p>Your one-time sign-in code is:</p>+ <div style="display: inline-block; font-size: 32px; font-weight: 700; letter-spacing: 8px; padding: 12px 16px 12px 24px; border: 1px solid #dddddd; border-radius: 8px;">{{code}}</div>+ <p style="padding-top: 2em; font-size: small; color: {{colorTextMedium}};">It expires in 10 minutes. If you didn't try to sign in, contact your administrator.</p>+ </div>+{{> _footer }}diff --git a/src/metabase/channel/email/mfa_removed_by_admin.hbs b/src/metabase/channel/email/mfa_removed_by_admin.hbsnew file mode 100644index 00000000000..771295c8cd4--- /dev/null+++ b/src/metabase/channel/email/mfa_removed_by_admin.hbs@@ -0,0 +1,9 @@+{{> _header }}+ <div>+ <p>An administrator removed two-factor authentication from your {{applicationName}} account. You can set it up again from your account settings.</p>+ <div style="text-align: center; padding: 1.5em 0 0.5em 0;">+ <a style="{{buttonStyle}}" href="{{{siteUrl}}}/account/security">Set up two-factor authentication</a>+ </div>+ <p style="padding-top: 1em; font-size: small; color: {{colorTextMedium}};">If you did not request this, contact your administrators — this action is recorded in the audit log.</p>+ </div>+{{> _footer }}diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.cljindex 33e5fdb0109..8f7bfceda65 100644--- a/src/metabase/premium_features/core.clj+++ b/src/metabase/premium_features/core.clj@@ -71,6 +71,7 @@enable-email-restrict-recipients?enable-embedding-sdk-origins?enable-embedding-simple-feature?+ enable-multi-factor-auth?enable-official-collections?enable-preemptive-caching?enable-query-reference-validation?diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.cljindex b8c891f1161..78de3dc67a5 100644--- a/src/metabase/premium_features/settings.clj+++ b/src/metabase/premium_features/settings.clj@@ -174,6 +174,10 @@"Should we enable user/group provisioning via SCIM?":scim)+(define-premium-feature enable-multi-factor-auth?+ "Should we enable native multi-factor authentication for interactive logins?"+ :multi-factor-auth)+(defn enable-any-sso?"Should we enable any SSO-based authentication?"[]@@ -410,6 +414,7 @@:hosting (is-hosted?):metabot-v3 (enable-metabot-v3?):metabase-ai-managed (enable-metabase-ai-managed?)+ :multi-factor-auth (enable-multi-factor-auth?):offer-metabase-ai-managed (enable-offer-metabase-ai-managed?):official_collections (enable-official-collections?):query_reference_validation (enable-query-reference-validation?)diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex cd5fbc0a91a..091ba17e4a2 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -7,9 +7,12 @@[metabase.api.open-api :as open-api][metabase.auth-identity.core :as auth-identity][metabase.channel.email.messages :as messages]+ [metabase.channel.settings :as channel.settings][metabase.config.core :as config][metabase.events.core :as events]+ [metabase.premium-features.core :refer [defenterprise]][metabase.request.core :as request]+ [metabase.session.challenge :as session.challenge][metabase.session.models.session :as session][metabase.session.schema :as session.schema][metabase.settings.core :as setting]@@ -28,17 +31,51 @@;;; ## API Endpoints+(def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle))+(def ^:private login-throttlers{:username (throttle/make-throttler :username);; IP Address doesn't have an actual UI field so just show error by username:ip-address (throttle/make-throttler :username, :attempts-threshold 50)})+(def ^:private verify-throttlers+ ;; Codes are 6 digits, so brute-force limits are load-bearing. Only failures count (see+ ;; `call-with-failure-throttling` below), so 5 wrong codes per user per hour, not 5 logins.+ {:user-id (throttle/make-throttler :user-id, :attempts-threshold 5)+ :ip-address (throttle/make-throttler :ip-address, :attempts-threshold 50)})++(def ^:private email-otp-send-throttlers+ ;; sending is expensive and spammable — every send counts, much tighter than verification+ {:user-id (throttle/make-throttler :user-id, :attempts-threshold 3)+ :ip-address (throttle/make-throttler :ip-address, :attempts-threshold 20)})++(defn- call-with-failure-throttling+ "Run `f` guarded by `pairs` of `[throttler throttle-key]`. Only a thrown exception counts as an+ attempt; successful calls are free. No-op when `MB_DISABLE_SESSION_THROTTLE` is set.+ The MFA management endpoints have their own throttling helpers (`mfa.throttling`); the two are+ kept separate deliberately — this one lives in OSS session code, that one in the EE module."+ [pairs f]+ (if throttling-disabled?+ (f)+ (try+ ((reduce (fn [g [thr key]]+ (fn [] (throttle/do-with-throttling thr key g)))+ f+ pairs))+ (catch clojure.lang.ExceptionInfo e+ ;; `throttle/do-with-throttling`'s over-the-limit exception carries `:errors` but no+ ;; `:status-code` (unlike `throttle/check`'s), which would surface as a 500+ (let [data (ex-data e)]+ (if (and (:errors data) (nil? (:status-code data)))+ (throw (ex-info (ex-message e) (assoc data :status-code 400) e))+ (throw e)))))))+(def ^:private password-fail-message (deferred-tru "Password did not match stored password."))(def ^:private password-fail-snippet (deferred-tru "did not match stored password"))-(mu/defn- ldap-login :- [:maybe [:map [:key ms/UUIDString]]]- "If LDAP is enabled and a matching user exists return a new Session for them, or `nil` if they couldn't be- authenticated."+(mu/defn- ldap-login :- [:maybe [:or session.schema/SessionSchema [:map [:mfa/pending? [:= true]]]]]+ "If LDAP is enabled and a matching user exists return a new Session for them (or an MFA-pending+ result map when a second factor is required), or `nil` if they couldn't be authenticated."[username password device-info :- request/DeviceInfo](when (sso/ldap-enabled)(let [result (auth-identity/login! :provider/ldap@@ -56,14 +93,15 @@:errors {:password password-fail-snippet}}))(:success? result)- (:session result)+ (if (:mfa/pending? result) result (:session result)):else(throw (ex-info (str (:message result)) {:errors {:_error (:error result)}:status-code 401}))))))-(mu/defn- email-login :- [:maybe [:map [:key ms/UUIDString]]]- "Find a matching `User` if one exists and return a new Session for them, or `nil` if they couldn't be authenticated."+(mu/defn- email-login :- [:maybe [:or session.schema/SessionSchema [:map [:mfa/pending? [:= true]]]]]+ "Find a matching `User` if one exists and return a new Session for them (or an MFA-pending result+ map when a second factor is required), or `nil` if they couldn't be authenticated."[username :- ms/NonBlankStringpassword :- [:maybe ms/NonBlankString]device-info :- request/DeviceInfo]@@ -73,21 +111,19 @@:device-info device-info})](cond(contains? #{:invalid-credentials :server-error :authentication-expired} (:error result)) nil- (:success? result) (:session result)+ (:success? result) (if (:mfa/pending? result) result (:session result)):else (throw (ex-info (str (:message result)) {:errors {:_error (:error result)}:status-code 401})))))-(def ^:private throttling-disabled? (config/config-bool :mb-disable-session-throttle))-(defn- throttle-check"Pass through to `throttle/check` but will not check if `throttling-disabled?` is true"[throttler throttle-key](when-not throttling-disabled?(throttle/check throttler throttle-key)))-(mu/defn- login :- session.schema/SessionSchema- "Attempt to login with different available methods with `username` and `password`, returning new Session ID or- throwing an Exception if login could not be completed."+(mu/defn- login :- [:or session.schema/SessionSchema [:map [:mfa/pending? [:= true]]]]+ "Attempt to login with different available methods with `username` and `password`, returning a new Session (or an+ MFA-pending result map when a second factor is required) or throwing an Exception if login could not be completed."[username :- ms/NonBlankStringpassword :- ms/NonBlankStringdevice-info :- request/DeviceInfo]@@ -101,6 +137,32 @@{:status-code 401:errors {:password password-fail-snippet}}))))+(defn- session-response+ "Ring response that sets the session cookies for a freshly created `session`.+ Body shape: `{:id <session-key>}`. The body is the same as the `POST /api/session` success path."+ [session request]+ (let [response (vary-meta {:id (str (:key session))} assoc :metabase-user-id (:user_id session))]+ (request/set-session-cookies request response session (t/zoned-date-time (t/zone-id "GMT")))))++(defenterprise verify-second-factor!+ "Verify a second-factor code (TOTP, recovery, or emailed one-time code) for user-id, atomically+ consuming it plus the challenge jti. Returns boolean.++ OSS fallback returns false — OSS can never have issued a challenge token (the MFA gate lives in+ EE), so this is unreachable in practice."+ metabase-enterprise.mfa.core+ [_user-id _code _jti]+ false)++(defenterprise send-mfa-email-otp!+ "Generate + email a one-time fallback code for user-id's confirmed enrollment; rejects a jti that+ already minted a session.++ OSS fallback throws (unreachable, as above)."+ metabase-enterprise.mfa.core+ [_user-id _jti]+ (throw (ex-info (tru "Multi-factor authentication is not available.") {:status-code 400})))+(defn- do-http-401-on-error [f](try(f)@@ -127,13 +189,20 @@[:username ms/NonBlankString][:password ms/NonBlankString]]request]- (let [ip-address (request/ip-address request)- request-time (t/zoned-date-time (t/zone-id "GMT"))- do-login (fn []- (let [{session-key :key, :as session} (login username password (request/device-info request))- response (vary-meta {:id (str session-key)}- assoc :metabase-user-id (:user_id session))]- (request/set-session-cookies request response session request-time)))]+ (let [ip-address (request/ip-address request)+ do-login (fn []+ (let [result (login username password (request/device-info request))]+ (if (:mfa/pending? result)+ ;; First factor OK, but a second factor is required: build and sign a+ ;; challenge token here (OSS session machinery) and return it instead of+ ;; a session. No cookies are set yet.+ {:status 200+ :body {:mfa_required true+ :methods (:mfa/methods result)+ :challenge_token (session.challenge/issue-challenge-token+ (get-in result [:user :id])+ (:mfa/first-factor result))}}+ (session-response result request))))](if throttling-disabled?(do-login)(http-401-on-error@@ -267,13 +336,22 @@[:provider/support-access-grant:provider/emailed-secret-password-reset]request-body)]- (if (:success? auth-result)+ (cond+ (not (:success? auth-result))+ (api/throw-invalid-param-exception :password (tru "Invalid reset token"))++ ;; The password change succeeded, but the user is MFA-enrolled: issue no session, or anyone+ ;; who can trigger a reset email routes around the second factor. They log in normally (and+ ;; get challenged) with the new password.+ (:mfa/pending? auth-result)+ {:success true}++ :else(let [session (:session auth-result)response (vary-meta {:success true :session_id (str (:key session))}assoc :metabase-user-id (:user_id session))](request/set-session-cookies request response session- (t/zoned-date-time (t/zone-id "GMT"))))- (api/throw-invalid-param-exception :password (tru "Invalid reset token")))))+ (t/zoned-date-time (t/zone-id "GMT")))))));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;@@ -358,6 +436,79 @@;; if we pass the [[ms/ValidPassword]] test we're g2g{:valid true})+;; No response schema: the success path returns a full ring response (session cookies must be set),+;; which the response-schema machinery would validate as the body. Same constraint as+;; `POST /api/session`. Body shape: `{:id <session-key>}`.+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+(api.macros/defendpoint :post "/mfa/verify"+ "Complete a two-step login by verifying a one-time code. Takes the `challenge_token` returned by+ `POST /api/session` and either the 6-digit `code` from the user's authenticator app, one of+ their single-use recovery codes, or an emailed one-time code; on success sets the session cookie."+ [_route-params+ _query-params+ ;; `:remember` is not bound here but is part of the contract: `request/set-session-cookies`+ ;; reads it from the raw body to decide session-vs-permanent cookie, exactly as on+ ;; `POST /api/session` — for MFA users THIS request is the one that creates the session.+ {challenge-token :challenge_token, code :code} :- [:map+ [:challenge_token ms/NonBlankString]+ [:code ms/NonBlankString]+ [:remember {:optional true} :boolean]]+ request]+ (let [claims (or (session.challenge/verify-challenge-token challenge-token)+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ {:keys [jti]} claims+ _ (when-not jti+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ user-id (:user-id claims)+ first-factor (auth-identity/provider-string->keyword (:provider claims))]+ ;; Throttle only failed attempts — counting successes would lock out a legitimately busy user.+ ;; The inner fn throws on failure so call-with-failure-throttling records the attempt.+ (call-with-failure-throttling+ [[(verify-throttlers :ip-address) (request/ip-address request)]+ [(verify-throttlers :user-id) user-id]]+ (fn []+ (when-not (verify-second-factor! user-id code jti)+ (events/publish-event! :event/mfa-verification-failed+ {:object (t2/select-one :model/User :id user-id)})+ (throw (ex-info (tru "Invalid authentication code.") {:status-code 401})))))+ (let [user (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id)]+ ;; the account can be deactivated (or deleted) between the password step and here; a+ ;; challenge token must not outlive the account. Same 401 as a bad token — no oracle.+ (when-not (:is_active user)+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ (session-response (auth-identity/create-session-with-auth-tracking! user (request/device-info request) first-factor)+ request))))++(api.macros/defendpoint :post "/mfa/send-email-otp" :- [:map [:success [:= true]]]+ "Email a one-time code as a fallback second factor (for a user who lost their authenticator but+ still has recovery codes disabled or unavailable). Requires a valid challenge token from+ `POST /api/session`; the code is single-use with a 10-minute expiry and is accepted by+ `POST /mfa/verify` like any other code."+ [_route-params+ _query-params+ {challenge-token :challenge_token} :- [:map [:challenge_token ms/NonBlankString]]+ request]+ (let [claims (or (session.challenge/verify-challenge-token challenge-token)+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ {:keys [jti]} claims+ _ (when-not jti+ (throw (ex-info (tru "Authentication session expired. Please log in again.")+ {:status-code 401})))+ user-id (:user-id claims)+ ip (request/ip-address request)]+ ;; sending is expensive and spammable — every send counts, not failure-only+ (when-not throttling-disabled?+ (throttle/check (email-otp-send-throttlers :ip-address) ip)+ (throttle/check (email-otp-send-throttlers :user-id) user-id))+ (when-not (channel.settings/email-configured?)+ (throw (ex-info (tru "Email is not configured on this instance.") {:status-code 400})))+ (send-mfa-email-otp! user-id jti))+ {:success true})+(defn- +log-all-request-failures [handler](open-api/handler-with-open-api-spec(fn [request respond raise]diff --git a/src/metabase/session/challenge.clj b/src/metabase/session/challenge.cljnew file mode 100644index 00000000000..9b7fa9ce5c1--- /dev/null+++ b/src/metabase/session/challenge.clj@@ -0,0 +1,43 @@+(ns metabase.session.challenge+ "Short-lived signed challenge tokens bridging the two steps of an MFA login.++ A challenge token is NOT a session: nothing is written to the session table and no cookie is set+ until the second factor passes. The token is a 5-minute HS256 JWT carrying the user, the+ first-factor provider (so session auth-tracking records it correctly), and a `jti` that is+ consumed on successful verification so one token cannot mint two sessions."+ (:require+ [buddy.sign.jwt :as jwt]+ [metabase.session.settings :as session.settings]+ [metabase.util.log :as log]))++(set! *warn-on-reflection* true)++(def ttl-seconds+ "How long a challenge token stays valid. (Consumed `jti`s are retained longer — see+ `enrollment/consume-jti`'s conservative 2-hour window.)"+ (* 5 60))++(defn issue-challenge-token+ "Create a signed token authorizing a second-factor attempt for `user-id`, remembering the+ first-factor `provider`."+ [user-id provider]+ (jwt/sign {:user-id user-id+ :provider (name provider)+ :purpose "mfa-challenge"+ :jti (str (random-uuid))+ :exp (+ (quot (System/currentTimeMillis) 1000) ttl-seconds)}+ (session.settings/mfa-challenge-signing-key)+ {:alg :hs256}))++(defn verify-challenge-token+ "Verify a challenge token's signature and expiry. Returns its claims map, or nil if+ invalid/expired/tampered. Does NOT consume the `jti` — that happens only on successful+ second-factor verification, so a user can retry codes on the same token."+ [token]+ (try+ (let [claims (jwt/unsign token (session.settings/mfa-challenge-signing-key) {:alg :hs256})]+ (when (= (:purpose claims) "mfa-challenge")+ claims))+ (catch Exception e+ (log/debug e "Invalid MFA challenge token")+ nil)))diff --git a/src/metabase/session/settings.clj b/src/metabase/session/settings.cljindex 870211836cb..7d28fc1dbb3 100644--- a/src/metabase/session/settings.clj+++ b/src/metabase/session/settings.clj@@ -1,5 +1,7 @@(ns metabase.session.settings(:require+ [buddy.core.codecs :as codecs]+ [buddy.core.nonce :as nonce][metabase.settings.core :as setting :refer [defsetting]][metabase.sso.core :as sso][metabase.util.i18n :refer [deferred-tru]]@@ -43,3 +45,15 @@:type :integer:default 48:audit :getter)++(defsetting mfa-challenge-signing-key+ (deferred-tru "Key used to sign MFA challenge tokens. Generated automatically on first use.")+ :visibility :internal+ :type :string+ :export? false+ :audit :never+ :encryption :when-encryption-key-set+ ;; :init generates and persists on first access. Two nodes touching it simultaneously can still+ ;; race (last write wins; the loser's in-flight 5-min challenge tokens fail verification), but+ ;; the window is one first-ever MFA login. Generate eagerly at startup if this ever bites.+ :init (fn [] (codecs/bytes->hex (nonce/random-bytes 32))))diff --git a/src/metabase/sso/core.clj b/src/metabase/sso/core.cljindex f20e7977a09..e827bfb8fd5 100644--- a/src/metabase/sso/core.clj+++ b/src/metabase/sso/core.clj@@ -12,6 +12,9 @@(p/import-vars[metabase.sso.commonsync-group-memberships!]+ [metabase.sso.ldap+ find-user+ verify-password][metabase.sso.ldap.default-implementationLDAPSettingsldap-search-result->user-info]diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.cljindex 56062d4608a..e5701f6eb68 100644--- a/test/metabase/app_db/custom_migrations_test.clj+++ b/test/metabase/app_db/custom_migrations_test.clj@@ -2909,6 +2909,34 @@(testing "Native transform strategy is stripped (can't resolve source table)"(is (not (contains? (get-source native-id) :source-incremental-strategy))))))))+(deftest backfill-mfa-confirmed-at-test+ (testing "v59.2026-07-10T22:29:17: confirmed_at is lifted out of the credentials JSON into the column"+ (encryption-test/with-secret-key "backfill-mfa-test-key-1234"+ (impl/test-migrations ["v59.2026-07-10T22:29:17"] [migrate!]+ (let [confirmed-at "2026-07-01T12:00:00Z"+ insert-identity!+ (fn [user-id credentials-str]+ (t2/insert-returning-pk! :auth_identity {:user_id user-id+ :provider "totp"+ :credentials credentials-str+ :created_at :%now+ :updated_at :%now}))+ enc-confirmed (insert-identity! (:id (new-instance-with-default :core_user))+ (encryption/maybe-encrypt+ (json/encode {:secret "s1" :confirmed_at confirmed-at})))+ plain-confirmed (insert-identity! (:id (new-instance-with-default :core_user))+ (json/encode {:secret "s2" :confirmed_at confirmed-at}))+ pending (insert-identity! (:id (new-instance-with-default :core_user))+ (encryption/maybe-encrypt+ (json/encode {:secret "s3"})))]+ (migrate!)+ (testing "encrypted confirmed row gets the column"+ (is (some? (t2/select-one-fn :confirmed_at :auth_identity :id enc-confirmed))))+ (testing "legacy plaintext confirmed row gets the column"+ (is (some? (t2/select-one-fn :confirmed_at :auth_identity :id plain-confirmed))))+ (testing "pending (unconfirmed) enrollment stays null"+ (is (nil? (t2/select-one-fn :confirmed_at :auth_identity :id pending)))))))))+(deftest backfill-transform-target-tables-test(testing "v60.2026-03-07T00:00:04 : backfill transform target tables"(impl/test-migrations ["v60.2026-03-07T00:00:04"] [migrate!]diff --git a/test/metabase/auth_identity/models/auth_identity_test.clj b/test/metabase/auth_identity/models/auth_identity_test.cljindex 0a19e8a1d0a..4eb047b0026 100644--- a/test/metabase/auth_identity/models/auth_identity_test.clj+++ b/test/metabase/auth_identity/models/auth_identity_test.clj@@ -2,6 +2,8 @@(:require[clojure.test :refer :all][metabase.test :as mt]+ [metabase.util.encryption :as encryption]+ [metabase.util.encryption-test :as encryption-test][metabase.util.password :as u.password][toucan2.core :as t2]))@@ -181,3 +183,33 @@"Password hash should match between AuthIdentity and User")(is (= (:password_salt auth-creds) (:password_salt user))"Password salt should match between AuthIdentity and User")))))++(deftest credentials-encrypted-at-rest-test+ (testing "with a secret key set, the raw credentials column is ciphertext, not JSON"+ (encryption-test/with-secret-key "key-for-auth-identity-test-1"+ (mt/with-temp [:model/User {user-id :id}]+ (t2/insert! :model/AuthIdentity {:user_id user-id+ :provider "google"+ :credentials {:secret "super-secret"}})+ (let [raw (t2/select-one-fn :credentials :auth_identity+ :user_id user-id :provider "google")]+ (is (encryption/possibly-encrypted-string? raw)+ "Raw column value should be encrypted")+ (is (not (re-find #"super-secret" (str raw)))+ "Plaintext must not appear in the stored value"))+ (testing "and the model transform round-trips the plaintext map"+ (is (= "super-secret"+ (get-in (t2/select-one :model/AuthIdentity :user_id user-id :provider "google")+ [:credentials :secret]))))))))++(deftest credentials-plaintext-rows-still-readable-test+ (testing "rows written before encryption (plain JSON in the column) still read as maps"+ (encryption-test/with-secret-key "key-for-auth-identity-test-2"+ (mt/with-temp [:model/User {user-id :id}]+ (t2/insert! :model/AuthIdentity {:user_id user-id :provider "google" :credentials {}})+ ;; simulate a legacy plaintext row by writing raw JSON straight to the table+ (t2/update! :auth_identity {:user_id user-id :provider "google"}+ {:credentials "{\"secret\":\"legacy-plain\"}"})+ (is (= "legacy-plain"+ (get-in (t2/select-one :model/AuthIdentity :user_id user-id :provider "google")+ [:credentials :secret])))))))diff --git a/test/metabase/session/challenge_test.clj b/test/metabase/session/challenge_test.cljnew file mode 100644index 00000000000..96e49a4824d--- /dev/null+++ b/test/metabase/session/challenge_test.clj@@ -0,0 +1,27 @@+(ns metabase.session.challenge-test+ "Round-trip tests for the MFA challenge token (JWT sign/verify)."+ (:require+ [clojure.test :refer :all]+ [metabase.session.challenge :as session.challenge]+ [metabase.test.fixtures :as fixtures]))++(use-fixtures :once (fixtures/initialize :db))++(deftest round-trip-test+ (testing "a signed token verifies and returns the expected claims"+ (let [token (session.challenge/issue-challenge-token 42 :provider/password)+ claims (session.challenge/verify-challenge-token token)]+ (is (map? claims))+ (is (= 42 (:user-id claims)))+ (is (= "password" (:provider claims)))+ (is (= "mfa-challenge" (:purpose claims)))+ (is (string? (:jti claims)))+ (is (pos? (:exp claims)))))+ (testing "a tampered token returns nil"+ (let [token (session.challenge/issue-challenge-token 1 :provider/ldap)+ bad (str token "tampered")]+ (is (nil? (session.challenge/verify-challenge-token bad)))))+ (testing "a garbage string returns nil"+ (is (nil? (session.challenge/verify-challenge-token "not-a-jwt"))))+ (testing "an empty string returns nil"+ (is (nil? (session.challenge/verify-challenge-token "")))))