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
UXW-4916: MFA mandatory enrollment flow on login (#79093)
Braden Shepherdson79546eb55f26
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex b412460a0de..7aca2f922eb 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1581,6 +1581,13 @@util}:model-imports #{:model/Card :model/Field :model/Measure}}+ mfa+ {:team "UX West"+ :api #{metabase.mfa.init metabase.mfa.settings}+ :uses #{premium-features+ settings+ util}}+model-persistence{:team "Graphy":api #{metabase.model-persistence.api@@ -2984,6 +2991,7 @@permissionspremium-featuresrequest+ sessionssosso.auth-identitysystem@@ -2996,6 +3004,7 @@:model/Collection:model/Dashboard:model/LoginHistory+ :model/Session:model/User}}users.tenants@@ -3782,13 +3791,14 @@:model/Table}}enterprise/mfa- {:team "Graphy"+ {:team "UX West":api #{metabase-enterprise.mfa.core metabase-enterprise.mfa.init metabase-enterprise.mfa.routes}:uses #{apiappearancechanneleventslib.schema+ mfapremium-featuresrequestsettingsdiff --git a/.github/actions/e2e-prepare-containers/action.yml b/.github/actions/e2e-prepare-containers/action.ymlindex 1c83fa8b0b8..0c641701127 100644--- a/.github/actions/e2e-prepare-containers/action.yml+++ b/.github/actions/e2e-prepare-containers/action.yml@@ -15,6 +15,10 @@ inputs:description: OpenLDAP containerrequired: truedefault: false+ mocksaml:+ description: Mock SAML container+ required: true+ default: falsepostgres:description: Postgres containerrequired: true@@ -73,6 +77,7 @@ runs:[ "${{ inputs.mongo }}" = true ] && SERVICES+=(mongo-sample)[ "${{ inputs.maildev }}" = true ] && SERVICES+=(maildev maildev-ssl)[ "${{ inputs.openldap }}" = true ] && SERVICES+=(ldap)+ [ "${{ inputs.mocksaml }}" = true ] && SERVICES+=(saml-idp)[ "${{ inputs.webhook }}" = true ] && SERVICES+=(webhook-tester)[ "${{ inputs.snowplow }}" = true ] && SERVICES+=(snowplow-micro)@@ -109,6 +114,12 @@ runs:echo -e "${G}Openldap is up and running!"fi+ if ${{ inputs.mocksaml }}; then+ echo -e "${Y}checking mock saml container..." &&+ while ! nc -z localhost 8090; do sleep 1; done &&+ echo -e "${G}Mock SAML is up and running!"+ fi+if ${{ inputs.postgres }}; thenecho -e "${Y}checking postgres container..." &&while ! nc -z localhost 5404; do sleep 1; done &&diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.ymlindex c84cd430759..57a1cb4d985 100644--- a/.github/workflows/e2e-test.yml+++ b/.github/workflows/e2e-test.yml@@ -102,6 +102,7 @@ jobs:postgres: truemysql: truemongo: true+ mocksaml: true- name: Retrieve uberjar artifact for ${{ inputs.edition }}uses: ./.github/actions/fetch-artifactdiff --git a/e2e/support/config.js b/e2e/support/config.jsindex 117af42f427..eefc280967c 100644--- a/e2e/support/config.js+++ b/e2e/support/config.js@@ -22,6 +22,7 @@ import {verifyDownloadTasks,} from "./commands/downloads/downloadUtils";import * as dbTasks from "./db_tasks";+import { requestAsAdmin } from "./helpers/e2e-admin-request-tasks";import {startCustomVizDevServer,stopCustomVizDevServer,@@ -298,6 +299,7 @@ const defaultConfig = {copyDirectory,removeDirectory,signJwt,+ requestAsAdmin,startMockLlmServer,stopMockLlmServer,startCustomVizDevServer,diff --git a/e2e/support/helpers/e2e-admin-request-tasks.ts b/e2e/support/helpers/e2e-admin-request-tasks.tsnew file mode 100644index 00000000000..6e3d13bc52c--- /dev/null+++ b/e2e/support/helpers/e2e-admin-request-tasks.ts@@ -0,0 +1,66 @@+import {+ BACKEND_HOST,+ BACKEND_PORT,+} from "../../runner/constants/backend-port";+import { USERS } from "../cypress_data";++const BASE_URL = `http://${BACKEND_HOST}:${BACKEND_PORT}`;++type AdminRequest = {+ method?: string;+ url: string;+ body?: unknown;+};++async function send(url: string, init: RequestInit) {+ const response = await fetch(`${BASE_URL}${url}`, {+ ...init,+ headers: { "Content-Type": "application/json", ...init.headers },+ });+ const text = await response.text();++ if (!response.ok) {+ throw new Error(`${init.method} ${url} → ${response.status}: ${text}`);+ }+ return text ? JSON.parse(text) : null;+}++function cachedAdminSession(): string | undefined {+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require for optional file+ const { loginCache } = require("../cypress_sample_instance_data.json");+ return loginCache?.admin?.sessionId;+ } catch {+ return undefined;+ }+}++async function freshAdminSession(): Promise<string | undefined> {+ const { email: username, password } = USERS.admin;+ const { id } = await send("/api/session", {+ method: "POST",+ body: JSON.stringify({ username, password }),+ });+ return id;+}++/**+ Acts as the admin without touching the browser's cookies+ */+export async function requestAsAdmin({+ method = "GET",+ url,+ body,+}: AdminRequest) {+ const sessionId = cachedAdminSession() ?? (await freshAdminSession());++ if (!sessionId) {+ throw new Error("Could not resolve an admin session");+ }++ return send(url, {+ method,+ headers: { "X-Metabase-Session": sessionId },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+}diff --git a/e2e/support/helpers/e2e-saml-helpers.ts b/e2e/support/helpers/e2e-saml-helpers.tsnew file mode 100644index 00000000000..20df3770b3b--- /dev/null+++ b/e2e/support/helpers/e2e-saml-helpers.ts@@ -0,0 +1,34 @@+/**+ Requires the mock SAML IdP from e2e/test/scenarios/docker-compose.yml, which the Cypress+ runner starts for you:+ docker compose -f e2e/test/scenarios/docker-compose.yml up -d saml-idp++ Tests that sign in through it need `{ tags: "@external" }`, and a token with `sso-saml`.+ */++/** Published port of the `saml-idp` service. */+export const MOCK_SAML_IDP_URL = "http://localhost:8090";++/** Matches ENTITY_ID on the `saml-idp` service. */+const MOCK_SAML_ENTITY_ID = "https://saml.example.com/entityid";++/** Test-only keypair the IdP signs with; see e2e/test/scenarios/saml-keys. */+const MOCK_SAML_CERT_PATH = "e2e/test/scenarios/saml-keys/public.crt";++export const setupSaml = () => {+ cy.log("Set up mock SAML IdP");++ cy.readFile<string>(MOCK_SAML_CERT_PATH, "utf8").then((certificate) => {+ cy.request("PUT", "/api/setting", {+ "saml-enabled": true,+ "saml-identity-provider-uri": `${MOCK_SAML_IDP_URL}/api/saml/sso`,+ "saml-identity-provider-issuer": MOCK_SAML_ENTITY_ID,+ "saml-identity-provider-certificate": certificate,+ // mock-saml names its attributes after the raw profile keys, not the WS-Federation claim+ // URIs these settings default to, so they have to be mapped explicitly.+ "saml-attribute-email": "email",+ "saml-attribute-firstname": "firstName",+ "saml-attribute-lastname": "lastName",+ });+ });+};diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.tsindex bfd78a56cf5..6ff53d5763b 100644--- a/e2e/support/helpers/index.ts+++ b/e2e/support/helpers/index.ts@@ -52,6 +52,7 @@ export * from "./e2e-qa-databases-helpers";export * from "./e2e-relative-date-picker-helpers";export * from "./e2e-remote-sync-helpers";export * from "./e2e-request-helpers";+export * from "./e2e-saml-helpers";export * from "./e2e-search-helpers";export * from "./e2e-setup-helpers";export * from "./e2e-sharing-helpers";diff --git a/e2e/test/scenarios/admin-2/multi-factor-auth.cy.spec.ts b/e2e/test/scenarios/admin-2/multi-factor-auth.cy.spec.tsindex 53d28cc3c68..c8716461b45 100644--- a/e2e/test/scenarios/admin-2/multi-factor-auth.cy.spec.ts+++ b/e2e/test/scenarios/admin-2/multi-factor-auth.cy.spec.ts@@ -2,11 +2,21 @@ const { H } = cy;import * as OTPAuth from "otpauth";import { USERS } from "e2e/support/cypress_data";+import { ORDERS_COUNT_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";+import { dayjs } from "metabase/dayjs";const { admin, nodata, normal } = USERS;const NEW_PASSWORD = "NewPassword2fa!123";+const GRACE_PERIOD_DAYS = 14;++const LDAP_USER = { username: "[email protected]", password: "123456" };++/** mock-saml accepts any username and password, but only example.com/example.org domains. */+const SAML_USER = { username: "samluser", domain: "example.com" };+const SAML_USER_EMAIL = `${SAML_USER.username}@${SAML_USER.domain}`;+type MaildevEmail = { subject: string; html: string };describe("scenarios > admin > settings > multi-factor authentication", () => {@@ -15,315 +25,633 @@ describe("scenarios > admin > settings > multi-factor authentication", () => {H.clearInbox();cy.signInAsAdmin();H.activateToken("bleeding-edge");- cy.intercept("PUT", "/api/setting/mfa-enforcement").as("updateEnforcement");+ // Every enforcement change writes the deadline alongside it, so it lands on the bulk route.+ cy.intercept("PUT", "/api/setting").as("updateSettings");cy.intercept("POST", "/api/ee/mfa/enroll").as("enroll");});- it("admin can enable and disable 2FA in authentication settings", () => {- cy.visit("/admin/settings/authentication");- mfaSetting().scrollIntoView();- mfaSetting().findByText("Two-factor authentication").should("be.visible");- mfaToggle().should("not.be.checked").click();- cy.wait("@updateEnforcement");- mfaSetting()- .should("contain", "0 enrolled users")- .and("contain", "users without 2FA");-- cy.log("Disable it again");- mfaToggle().should("be.checked").click();- cy.wait("@updateEnforcement");- mfaToggle().should("not.be.checked");- mfaSetting().should("not.contain", "enrolled");- });+ describe("optional", () => {+ describe("admin settings", () => {+ it("admin can enable and disable 2FA in authentication settings", () => {+ cy.visit("/admin/settings/authentication");+ mfaSetting().scrollIntoView();+ mfaSetting()+ .findByText("Two-factor authentication")+ .should("be.visible");+ mfaToggle().should("not.be.checked").click();+ cy.wait("@updateSettings");+ mfaSetting()+ .should("contain", "0 enrolled users")+ .and("contain", "users without 2FA");++ cy.log("Enabling it leaves enforcement optional");+ enforcementOption("Don't require").should("be.checked");++ cy.log("Disable it again");+ mfaToggle().should("be.checked").click();+ cy.wait("@updateSettings");+ mfaToggle().should("not.be.checked");+ mfaSetting().should("not.contain", "enrolled");+ });- it("user can set up 2FA in account settings and sign in with an authenticator code", () => {- let totpSecret = "";+ it("admin can remove a user's enrollment to unlock them", () => {+ enableMfa();+ enrollUser();- enableMfa();+ cy.log(+ "Admin drills into the enrolled list from the count on the card",+ );+ cy.signInAsAdmin();+ cy.visit("/admin/settings/authentication");+ mfaSetting().scrollIntoView().findByText("1 enrolled user").click();- cy.log("User enrolls from account authentication settings");- cy.signInAsNormalUser();+ enrolledUsersTable()+ .should("contain", normal.first_name)+ .and("contain", normal.email);- cy.log("The old security URL lands on the combined Authentication tab");- cy.visit("/account/security");- cy.url().should("contain", "/account/authentication");- cy.findByTestId("account-header")- .findByRole("tab", { name: "Authentication" })- .should("be.visible");+ cy.log("Admin removes the enrollment (the lockout escape hatch)");+ cy.findByLabelText(+ `Actions for ${normal.first_name} ${normal.last_name}`,+ ).click();+ H.menu().findByText("Remove two-factor authentication").click();+ H.modal().within(() => {+ cy.findByText(+ `Remove two-factor authentication for ${normal.first_name} ${normal.last_name}?`,+ ).should("be.visible");+ cy.button("Remove").click();+ });++ cy.log("They drop off the enrolled list and the count follows");+ enrolledUsersTable().should("not.contain", normal.email);+ cy.visit("/admin/settings/authentication");+ mfaSetting().scrollIntoView().should("contain", "0 enrolled users");++ cy.log("And they now show up as needing to set 2FA up again");+ mfaSetting()+ .findByText(/users? without 2FA/)+ .click();+ unenrolledUsersTable().should("contain", normal.email);- cy.log("Password and 2FA now share one tab");- cy.findByLabelText("Current password").should("be.visible");+ cy.log("After the removal the user signs in with just a password");+ signInWithPassword();+ cy.findByTestId("greeting-message").should("be.visible");+ cy.url().should("not.contain", "/auth/login");+ });- enrollViaUI().then((secret) => {- totpSecret = secret;- });- cy.findByRole("button", { name: "Disable" }).should("be.visible");- cy.findByRole("button", { name: "Generate recovery codes" }).should(- "be.visible",- );+ it("admin can search the users-without-2FA list", () => {+ enableMfa();+ enrollUser();- cy.log("Signing in now requires an authenticator code");- signInWithPassword();- cy.findByTestId("login-page")- .findByText("Enter the 6-digit code from your authenticator app.")- .should("be.visible");- // The backend rejects a reused TOTP time step, so take the code for the- // next 30-second window — validation accepts one step of clock skew.- cy.then(() => generateTotpCode(totpSecret, Date.now() / 1000 + 30)).then(- (code) => {- cy.findByLabelText("Authenticator code").type(code);- },- );- cy.button("Verify").click();- cy.findByTestId("greeting-message").should("be.visible");- });+ cy.signInAsAdmin();+ cy.visit("/admin/settings/authentication");+ mfaSetting()+ .scrollIntoView()+ .findByText(/users? without 2FA/)+ .click();- it("user can disable 2FA themselves and re-enroll", () => {- enableMfa();- enrollNormalUser().then(({ secret }) => {- cy.log("Disabling requires a fresh second factor, not just a password");- cy.visit("/account/password");- cy.findByRole("button", { name: "Disable" }).click();- H.modal().within(() => {- cy.findByText(- "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.",- ).should("be.visible");- cy.findByLabelText(- "Confirm with an authenticator code or a recovery code",- ).type(generateTotpCode(secret, Date.now() / 1000 + 30));- cy.button("Disable").click();+ cy.log(+ "The enrolled user is absent — they already have a second factor",+ );+ unenrolledUsersTable().should("not.contain", normal.email);++ cy.log("Searching narrows to a single person");+ unenrolledUsersTable().should("contain", nodata.email);+ cy.findByPlaceholderText("Search…").type(admin.first_name);+ unenrolledUsersTable()+ .should("contain", admin.email)+ .and("not.contain", nodata.email);});});- cy.findByRole("button", {- name: "Set up two-factor authentication",- }).should("be.enabled");- cy.log("Re-enroll from scratch with a new secret");- enrollViaUI();- cy.findByRole("button", { name: "Disable" }).should("be.visible");- });+ describe("enrollment", () => {+ it("user can set up 2FA in account settings and sign in with an authenticator code", () => {+ let totpSecret = "";++ enableMfa();++ cy.log("User enrolls from account security settings");+ cy.signInAsNormalUser();+ cy.visit("/account/security");+ cy.findByTestId("account-header")+ .findByRole("tab", { name: "Authentication" })+ .should("be.visible");+ enrollViaUI().then((secret) => {+ totpSecret = secret;+ });+ cy.findByRole("button", { name: "Disable" }).should("be.visible");+ cy.findByRole("button", { name: "Generate recovery codes" }).should(+ "be.visible",+ );- it("recovery codes sign the user in once and regeneration invalidates the old set", () => {- enableMfa();- cy.intercept("POST", "/api/ee/mfa/recovery-codes").as("regenerate");-- enrollNormalUser().then(({ secret, recoveryCodes }) => {- cy.log("Sign in with a recovery code instead of an authenticator code");- signInWithPassword();- cy.findByTestId("login-page")- .findByText("Use a recovery code instead")- .click();- cy.findByLabelText("Recovery code").type(recoveryCodes[0]);- cy.button("Verify").click();- cy.findByTestId("greeting-message").should("be.visible");-- cy.log("Regenerate the recovery codes");- cy.visit("/account/password");- cy.findByRole("button", { name: "Generate recovery codes" }).click();- H.modal().within(() => {- cy.findByText(- "This will generate a new set of recovery codes and invalidate all of your old ones.",- ).should("be.visible");- cy.findByLabelText(- "Confirm with an authenticator code or a recovery code",- ).type(generateTotpCode(secret, Date.now() / 1000 + 30));- cy.button("Generate new codes").click();- cy.findByText("Your recovery codes").should("be.visible");- cy.button("Done").click();+ cy.log("Signing in now requires an authenticator code");+ signInWithPassword();+ cy.findByTestId("login-page")+ .findByText("Enter the 6-digit code from your authenticator app.")+ .should("be.visible");+ // The backend rejects a reused TOTP time step, so take the code for the+ // next 30-second window — validation accepts one step of clock skew.+ cy.then(() =>+ generateTotpCode(totpSecret, Date.now() / 1000 + 30),+ ).then((code) => {+ cy.findByLabelText("Authenticator code").type(code);+ });+ cy.button("Verify").click();+ cy.findByTestId("greeting-message").should("be.visible");});- cy.log("Old codes no longer work; new ones do");- cy.wait("@regenerate").then(({ response }) => {- const newCodes = response?.body.recovery_codes;+ it("user can disable 2FA themselves and re-enroll", () => {+ enableMfa();+ enrollUser().then(({ secret }) => {+ cy.log(+ "Disabling requires a fresh second factor, not just a password",+ );+ cy.visit("/account/security");+ cy.findByRole("button", { name: "Disable" }).click();+ H.modal().within(() => {+ cy.findByText(+ "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.",+ ).should("be.visible");+ cy.findByLabelText(+ "Confirm with an authenticator code or a recovery code",+ ).type(generateTotpCode(secret, Date.now() / 1000 + 30));+ cy.button("Disable").click();+ });+ });+ cy.findByRole("button", {+ name: "Set up two-factor authentication",+ }).should("be.enabled");++ cy.log("Re-enroll from scratch with a new secret");+ enrollViaUI();+ cy.findByRole("button", { name: "Disable" }).should("be.visible");+ });+ });++ describe("login flows", () => {+ it("recovery codes sign the user in once and regeneration invalidates the old set", () => {+ enableMfa();+ cy.intercept("POST", "/api/ee/mfa/recovery-codes").as("regenerate");++ enrollUser().then(({ secret, recoveryCodes }) => {+ cy.log(+ "Sign in with a recovery code instead of an authenticator code",+ );+ signInWithPassword();+ cy.findByTestId("login-page")+ .findByText("Use a recovery code instead")+ .click();+ cy.findByLabelText("Recovery code").type(recoveryCodes[0]);+ cy.button("Verify").click();+ cy.findByTestId("greeting-message").should("be.visible");++ cy.log("Regenerate the recovery codes");+ cy.visit("/account/authentication");+ cy.findByRole("button", { name: "Generate recovery codes" }).click();+ H.modal().within(() => {+ cy.findByText(+ "This will generate a new set of recovery codes and invalidate all of your old ones.",+ ).should("be.visible");+ cy.findByLabelText(+ "Confirm with an authenticator code or a recovery code",+ ).type(generateTotpCode(secret, Date.now() / 1000 + 30));+ cy.button("Generate new codes").click();+ cy.findByText("Your recovery codes").should("be.visible");+ cy.button("Done").click();+ });++ cy.log("Old codes no longer work; new ones do");+ cy.wait("@regenerate").then(({ response }) => {+ const newCodes = response?.body.recovery_codes;+ signInWithPassword();+ cy.findByTestId("login-page")+ .findByText("Use a recovery code instead")+ .click();+ cy.findByLabelText("Recovery code").type(recoveryCodes[1]);+ cy.button("Verify").click();+ cy.findByTestId("login-page")+ .findByRole("alert")+ .should("contain", "Invalid authentication code.");+ cy.findByLabelText("Recovery code").clear().type(newCodes[0]);+ // the submit button transiently reads "Failed" after the rejected+ // attempt but stays clickable, so match either label+ cy.button(/Verify|Failed/).click();+ cy.findByTestId("greeting-message").should("be.visible");+ });+ });+ });++ it("an emailed one-time code works as a fallback second factor", () => {+ enableMfa();+ H.setupSMTP();+ enrollUser();+signInWithPassword();cy.findByTestId("login-page")- .findByText("Use a recovery code instead")- .click();- cy.findByLabelText("Recovery code").type(recoveryCodes[1]);- cy.button("Verify").click();+ .findByText("Enter the 6-digit code from your authenticator app.")+ .should("be.visible");++ cy.findByTestId("login-page").findByText("Email me a code").click();cy.findByTestId("login-page")- .findByRole("alert")- .should("contain", "Invalid authentication code.");- cy.findByLabelText("Recovery code").clear().type(newCodes[0]);- // the submit button transiently reads "Failed" after the rejected- // attempt but stays clickable, so match either label- cy.button(/Verify|Failed/).click();+ .findByText("Code sent — check your email")+ .should("be.visible");++ H.getInbox().then(({ body: emails }: { body: MaildevEmail[] }) => {+ const otpEmail = emails.find((email) =>+ email.subject.includes("Your sign-in code"),+ );+ expect(otpEmail, "sign-in code email").to.exist;+ const code = otpEmail?.html.match(/>\s*(\d{6})\s*</)?.[1];+ expect(code, "6-digit code in the email body").to.be.a("string");+ cy.findByLabelText("Authenticator code").type(String(code));+ });+ cy.button("Verify").click();cy.findByTestId("greeting-message").should("be.visible");});++ it("resetting a forgotten password does not bypass the second factor", () => {+ enableMfa();+ H.setupSMTP();+ enrollUser().then(({ secret }) => {+ cy.log("Request a reset link and set a new password");+ cy.signOut();+ cy.visit("/auth/forgot_password");+ cy.findByLabelText("Email address").type(normal.email);+ cy.button("Send password reset email").click();+ cy.findByTestId("login-page")+ .findByText(/If the email exists/)+ .should("be.visible");++ // the reset email is sent asynchronously and lands next to the "2FA+ // enabled" notification from enrollment — wait for both to be there+ H.getInbox(2).then(({ body: emails }: { body: MaildevEmail[] }) => {+ const resetEmail = emails.find((email) =>+ email.subject.includes("Password Reset"),+ );+ expect(resetEmail, "password reset email").to.exist;+ cy.visit(getResetLink(String(resetEmail?.html)));+ });+ cy.findByLabelText("Create a password").type(NEW_PASSWORD);+ cy.findByLabelText("Confirm your password").type(NEW_PASSWORD);+ cy.button("Save new password").click();++ cy.log("No session is minted — the new password still needs a code");+ cy.url().should("contain", "/auth/login");+ cy.findByLabelText("Email address").type(normal.email);+ cy.findByLabelText("Password").type(NEW_PASSWORD);+ cy.button("Sign in").click();+ cy.findByTestId("login-page")+ .findByText("Enter the 6-digit code from your authenticator app.")+ .should("be.visible");+ cy.then(() => generateTotpCode(secret, Date.now() / 1000 + 30)).then(+ (code) => {+ cy.findByLabelText("Authenticator code").type(code);+ },+ );+ cy.button("Verify").click();+ cy.findByTestId("greeting-message").should("be.visible");+ });+ });++ it("an enrolled user is still challenged and can disable 2FA after the license lapses", () => {+ enableMfa();+ enrollUser().then(({ secret, recoveryCodes }) => {+ cy.log("Drop the premium token — the gate must fail closed");+ cy.signInAsAdmin();+ H.deleteToken();++ signInWithPassword();+ cy.findByTestId("login-page")+ .findByText("Enter the 6-digit code from your authenticator app.")+ .should("be.visible");+ cy.then(() => generateTotpCode(secret, Date.now() / 1000 + 30)).then(+ (code) => {+ cy.findByLabelText("Authenticator code").type(code);+ },+ );+ cy.button("Verify").click();+ cy.findByTestId("greeting-message").should("be.visible");++ cy.log(+ "Managing the existing enrollment still works without a license",+ );+ cy.visit("/account/security");+ cy.findByRole("button", { name: "Disable" }).click();+ H.modal().within(() => {+ cy.findByLabelText(+ "Confirm with an authenticator code or a recovery code",+ ).type(recoveryCodes[0]);+ cy.button("Disable").click();+ });++ cy.log("Without the feature there is no way back into setup");+ cy.url().should("contain", "/account/authentication");+ cy.findByRole("button", {+ name: "Set up two-factor authentication",+ }).should("be.disabled");+ });+ });});});- it("an emailed one-time code works as a fallback second factor", () => {- enableMfa();- H.setupSMTP();- enrollNormalUser();+ describe("required", () => {+ describe("admin", () => {+ it("allows user to set mfa to required, sets default grace period", () => {+ const deadline = dayjs().add(GRACE_PERIOD_DAYS, "day");- signInWithPassword();- cy.findByTestId("login-page")- .findByText("Enter the 6-digit code from your authenticator app.")- .should("be.visible");+ cy.visit("/admin/settings/authentication");+ mfaSetting().scrollIntoView();- cy.findByTestId("login-page").findByText("Email me a code").click();- cy.findByTestId("login-page")- .findByText("Code sent — check your email")- .should("be.visible");+ cy.log("Enforcement and the deadline only exist once 2FA is allowed");+ mfaSetting().should("not.contain", "Require now");+ mfaDeadline().should("not.exist");- H.getInbox().then(({ body: emails }: { body: MaildevEmail[] }) => {- const otpEmail = emails.find((email) =>- email.subject.includes("Your sign-in code"),- );- expect(otpEmail, "sign-in code email").to.exist;- const code = otpEmail?.html.match(/>\s*(\d{6})\s*</)?.[1];- expect(code, "6-digit code in the email body").to.be.a("string");- cy.findByLabelText("Authenticator code").type(String(code));- });- cy.button("Verify").click();- cy.findByTestId("greeting-message").should("be.visible");- });+ mfaToggle().should("not.be.checked").click();+ cy.wait("@updateSettings");++ // Because the admin has not enrolled, they cannot set two factor to required+ enforcementOption("Require by a certain date").should("be.disabled");+ mfaSetting()+ .findByText(/account before requiring it/)+ .should("be.visible");- it("resetting a forgotten password does not bypass the second factor", () => {- enableMfa();- H.setupSMTP();- enrollNormalUser().then(({ secret }) => {- cy.log("Request a reset link and set a new password");- cy.signOut();- cy.visit("/auth/forgot_password");- cy.findByLabelText("Email address").type(normal.email);- cy.button("Send password reset email").click();- cy.findByTestId("login-page")- .findByText(/If the email exists/)- .should("be.visible");-- // the reset email is sent asynchronously and lands next to the "2FA- // enabled" notification from enrollment — wait for both to be there- H.getInbox(2).then(({ body: emails }: { body: MaildevEmail[] }) => {- const resetEmail = emails.find((email) =>- email.subject.includes("Password Reset"),+ enrollUser("admin");+ cy.reload();++ cy.log(+ "Enforcement and a default two-week grace period are saved together",);- expect(resetEmail, "password reset email").to.exist;- cy.visit(getResetLink(String(resetEmail?.html)));+ enforcementOption("Require by a certain date").click();+ cy.wait("@updateSettings");++ mfaDeadline().should("have.value", deadline.format("MMMM D, YYYY"));});- cy.findByLabelText("Create a password").type(NEW_PASSWORD);- cy.findByLabelText("Confirm your password").type(NEW_PASSWORD);- cy.button("Save new password").click();-- cy.log("No session is minted — the new password still needs a code");- cy.url().should("contain", "/auth/login");- cy.findByLabelText("Email address").type(normal.email);- cy.findByLabelText("Password").type(NEW_PASSWORD);- cy.button("Sign in").click();- cy.findByTestId("login-page")- .findByText("Enter the 6-digit code from your authenticator app.")- .should("be.visible");- cy.then(() => generateTotpCode(secret, Date.now() / 1000 + 30)).then(- (code) => {- cy.findByLabelText("Authenticator code").type(code);- },- );- cy.button("Verify").click();- cy.findByTestId("greeting-message").should("be.visible");- });- });- it("an enrolled user is still challenged and can disable 2FA after the license lapses", () => {- enableMfa();- enrollNormalUser().then(({ secret, recoveryCodes }) => {- cy.log("Drop the premium token — the gate must fail closed");- cy.signInAsAdmin();- H.deleteToken();-- signInWithPassword();- cy.findByTestId("login-page")- .findByText("Enter the 6-digit code from your authenticator app.")- .should("be.visible");- cy.then(() => generateTotpCode(secret, Date.now() / 1000 + 30)).then(- (code) => {- cy.findByLabelText("Authenticator code").type(code);- },- );- cy.button("Verify").click();- cy.findByTestId("greeting-message").should("be.visible");+ it("should immediately invalidate current username / password sessions when enforcement is required", () => {+ cy.signInAsNormalUser();- cy.log("Managing the existing enrollment still works without a license");- cy.visit("/account/authentication");- cy.findByRole("button", { name: "Disable" }).click();- H.modal().within(() => {- cy.findByLabelText(- "Confirm with an authenticator code or a recovery code",- ).type(recoveryCodes[0]);- cy.button("Disable").click();+ cy.visit("/");+ cy.findByTestId("greeting-message").should("be.visible");+ H.openNavigationSidebar();+ H.navigationSidebar().findByText("Our analytics").should("be.visible");++ cy.log("An admin turns enforcement on part-way through their session");+ cy.task("requestAsAdmin", {+ method: "PUT",+ url: "/api/setting",+ body: {+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": null,+ },+ });++ cy.log("next api request should return unauthenticated");+ H.navigationSidebar().findByText("Our analytics").click();++ cy.log("should be brought to login screen");+ cy.findByRole("heading", { name: "Sign in to Metabase" }).should(+ "be.visible",+ );});- cy.log("Without the feature there is no way back into setup");- cy.url().should("contain", "/account/authentication");- cy.findByRole("button", {- name: "Set up two-factor authentication",- }).should("be.disabled");- });- });+ it("should immediately invalidate current LDAP sessions when enforcement is required", () => {+ H.setupLdap();+ signInWithLdap();+ cy.findByTestId("greeting-message").should("be.visible");+ H.openNavigationSidebar();+ H.navigationSidebar()+ .findByText("Your personal collection")+ .should("be.visible");++ cy.log("An admin turns enforcement on part-way through their session");+ cy.task("requestAsAdmin", {+ method: "PUT",+ url: "/api/setting",+ body: {+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": null,+ },+ });++ cy.log("next api request should return unauthenticated");+ H.navigationSidebar().findByText("Your personal collection").click();++ cy.log("should be brought to login screen");+ cy.findByRole("heading", { name: "Sign in to Metabase" }).should(+ "be.visible",+ );+ });- it("admin can remove a user's enrollment to unlock them", () => {- enableMfa();- enrollNormalUser();+ it("should not invalidate sessions created via SAML, even when enforcement is required", () => {+ H.setupSaml();+ createSamlUser();- cy.log("Admin drills into the enrolled list from the count on the card");- cy.signInAsAdmin();- cy.visit("/admin/settings/authentication");- mfaSetting().scrollIntoView().findByText("1 enrolled user").click();-- enrolledUsersTable()- .should("contain", normal.first_name)- .and("contain", normal.email);-- cy.log("Admin removes the enrollment (the lockout escape hatch)");- cy.findByLabelText(- `Actions for ${normal.first_name} ${normal.last_name}`,- ).click();- H.menu().findByText("Remove two-factor authentication").click();- H.modal().within(() => {- cy.findByText(- `Remove two-factor authentication for ${normal.first_name} ${normal.last_name}?`,- ).should("be.visible");- cy.button("Remove").click();+ cy.signOut();+ cy.visit("/auth/login");+ cy.button("Sign in with SSO").click();++ cy.log("The IdP takes over — any password works, the domain is fixed");+ cy.get("#username").type(SAML_USER.username);+ cy.get("#domain").select(SAML_USER.domain);+ cy.get("#password").type("anything");+ cy.get("button").click();++ cy.log("Straight in: SSO providers are exempt from the MFA gate");+ cy.findByTestId("greeting-message").should("be.visible");++ cy.log("An admin turns enforcement on part-way through their session");+ cy.task("requestAsAdmin", {+ method: "PUT",+ url: "/api/setting",+ body: {+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": null,+ },+ });++ cy.log("The SAML session survives — the IdP owns MFA for those users");+ H.navigationSidebar().findByText("Our analytics").click();+ H.collectionTable().findByText("Orders, Count").click();+ cy.location("pathname").should(+ "contain",+ `/question/${ORDERS_COUNT_QUESTION_ID}`,+ );+ cy.findByTestId("login-page").should("not.exist");+ });});- cy.log("They drop off the enrolled list and the count follows");- enrolledUsersTable().should("not.contain", normal.email);- cy.visit("/admin/settings/authentication");- mfaSetting().scrollIntoView().should("contain", "0 enrolled users");-- cy.log("And they now show up as needing to set 2FA up again");- mfaSetting()- .findByText(/users? without 2FA/)- .click();- unenrolledUsersTable().should("contain", normal.email);-- cy.log("After the removal the user signs in with just a password");- signInWithPassword();- cy.findByTestId("greeting-message").should("be.visible");- cy.url().should("not.contain", "/auth/login");- });+ describe("login", () => {+ it("forces enrollment on login if grace period is past", () => {+ cy.intercept("POST", "/api/session").as("login");+ let secret = "";- it("admin can search the users-without-2FA list", () => {- enableMfa();- enrollNormalUser();+ cy.log("Enforcement started yesterday, so the grace period is over");+ requireMfa({ deadline: daysFromNow(-1) });- cy.signInAsAdmin();- cy.visit("/admin/settings/authentication");- mfaSetting()- .scrollIntoView()- .findByText(/users? without 2FA/)- .click();-- cy.log("The enrolled user is absent — they already have a second factor");- unenrolledUsersTable().should("not.contain", normal.email);-- cy.log("Searching narrows to a single person");- unenrolledUsersTable().should("contain", nodata.email);- cy.findByPlaceholderText("Search…").type(admin.first_name);- unenrolledUsersTable()- .should("contain", admin.email)- .and("not.contain", nodata.email);+ cy.log("A correct password on its own no longer yields a session");+ signInWithPassword();+ cy.wait("@login").then(({ response }) => {+ secret = response?.body.secret;+ });+ cy.findByTestId("login-page").within(() => {+ cy.findByText(+ "Two-factor authentication is required. Finish setting it up to sign in.",+ ).should("be.visible");+ cy.findByText("Or enter this key in the app manually:").should(+ "be.visible",+ );+ });++ cy.log("The key on screen is the one the login handed out");+ cy.then(() => {+ cy.findByTestId("login-page").should("contain", secret);+ cy.findByLabelText(+ "Enter the 6-digit code from the authenticator app",+ ).type(generateTotpCode(secret, Date.now() / 1000));+ });+ cy.button("Set up authentication").click();++ cy.log("Recovery codes are shown, and the user is still not signed in");+ cy.findByTestId("login-page")+ .findByText("Your recovery codes")+ .should("be.visible");+ cy.url().should("contain", "/auth/login");+ cy.findByTestId("greeting-message").should("not.exist");++ cy.log("Acknowledging the codes is what completes the login");+ cy.button("Done").click();+ cy.findByTestId("greeting-message").should("be.visible");+ cy.url().should("not.contain", "/auth/login");+ });+ it("does not require a challenge if within the grace period", () => {+ requireMfa({ deadline: daysFromNow(7) });++ signInWithPassword();+ cy.findByTestId("greeting-message").should("be.visible");+ cy.url().should("not.contain", "/auth/login");+ });++ it("resetting a forgotten password does not bypass enrollment", () => {+ cy.intercept("POST", "/api/session").as("login");+ H.setupSMTP();+ requireMfa();+ cy.log("Request a reset link and set a new password");+ cy.signOut();+ cy.visit("/auth/forgot_password");+ cy.findByLabelText("Email address").type(normal.email);+ cy.button("Send password reset email").click();+ cy.findByTestId("login-page")+ .findByText(/If the email exists/)+ .should("be.visible");++ H.getInbox(1).then(({ body: emails }: { body: MaildevEmail[] }) => {+ const resetEmail = emails.find((email) =>+ email.subject.includes("Password Reset"),+ );+ expect(resetEmail, "password reset email").to.exist;+ cy.visit(getResetLink(String(resetEmail?.html)));+ });+ cy.findByLabelText("Create a password").type(NEW_PASSWORD);+ cy.findByLabelText("Confirm your password").type(NEW_PASSWORD);+ cy.button("Save new password").click();++ cy.log("No session is minted — user must enroll in MFA");++ cy.url().should("contain", "/auth/login");+ cy.findByLabelText("Email address").type(normal.email);+ cy.findByLabelText("Password").type(NEW_PASSWORD);+ cy.button("Sign in").click();++ cy.wait("@login").then(({ response }) => {+ const secret = response?.body.secret;+ cy.findByTestId("login-page").should("contain", secret);+ cy.findByLabelText(+ "Enter the 6-digit code from the authenticator app",+ ).type(generateTotpCode(secret, Date.now() / 1000));+ });++ cy.button("Set up authentication").click();++ cy.findByTestId("login-page")+ .findByText("Your recovery codes")+ .should("be.visible");+ cy.url().should("contain", "/auth/login");+ cy.findByTestId("greeting-message").should("not.exist");++ cy.button("Done").click();+ cy.findByTestId("greeting-message").should("be.visible");+ });+ });++ describe("sso", () => {+ it(+ "requires a challenge when logging in via LDAP",+ { tags: "@external" },+ () => {+ cy.intercept("POST", "/api/session").as("login");+ let secret = "";++ H.setupLdap();+ requireMfa({ deadline: daysFromNow(-1) });++ cy.log(+ "LDAP provisions the user on first sign-in, then enrolls them",+ );+ signInWithLdap();+ cy.wait("@login").then(({ response }) => {+ secret = response?.body.secret;+ });+ cy.then(() => {+ cy.findByLabelText(+ "Enter the 6-digit code from the authenticator app",+ ).type(generateTotpCode(secret, Date.now() / 1000));+ });+ cy.button("Set up authentication").click();+ cy.button("Done").click();+ cy.findByTestId("greeting-message").should("be.visible");++ cy.log("Signing in again is challenged for the second factor");+ signInWithLdap();+ cy.findByTestId("login-page")+ .findByText("Enter the 6-digit code from your authenticator app.")+ .should("be.visible");+ // Enrollment consumed a time step, so take the next 30-second window+ cy.then(() => {+ cy.findByLabelText("Authenticator code").type(+ generateTotpCode(secret, Date.now() / 1000 + 30),+ );+ });+ cy.button("Verify").click();+ cy.findByTestId("greeting-message").should("be.visible");+ },+ );++ it(+ "does not require MFA challenge if logging in via SAML",+ { tags: "@external" },+ () => {+ H.setupSaml();++ requireMfa({ deadline: daysFromNow(-1) });++ cy.signOut();+ cy.visit("/auth/login");+ cy.button("Sign in with SSO").click();++ cy.log(+ "The IdP takes over — any password works, the domain is fixed",+ );+ cy.get("#username").type(SAML_USER.username);+ cy.get("#domain").select(SAML_USER.domain);+ cy.get("#password").type("anything");+ cy.get("button").click();++ cy.log("User is provisioned");+ cy.findByTestId("greeting-message").should("be.visible");+ cy.url().should("not.contain", "/auth/login");+ cy.findByTestId("login-page").should("not.exist");+ },+ );+ });});});@@ -340,7 +668,16 @@ function mfaSetting() {}function mfaToggle() {- return mfaSetting().findByLabelText(/Enabled|Disabled/);+ return mfaSetting().findByLabelText("Allow two-factor authentication");+}++/** One of "Don't require", "Require now", "Require by a certain date". */+function enforcementOption(label: string) {+ return mfaSetting().findByLabelText(label);+}++function mfaDeadline() {+ return mfaSetting().findByLabelText("Enrollment deadline");}function enableMfa() {@@ -349,10 +686,26 @@ function enableMfa() {});}-function enrollNormalUser() {- cy.signInAsNormalUser();+type RequireMfaOptions = {+ deadline?: Date | null;+};++// sets MFA to required, will also set deadline to match current UX+function requireMfa({ deadline = null }: RequireMfaOptions = {}) {+ return cy.request("PUT", "/api/setting", {+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": deadline?.toISOString() ?? null,+ });+}++function daysFromNow(days: number) {+ return dayjs().add(days, "day").startOf("day").toDate();+}++function enrollUser(user: keyof typeof USERS = "normal") {+ cy.signIn(user);return cy- .request("POST", "/api/ee/mfa/enroll", { password: normal.password })+ .request("POST", "/api/ee/mfa/enroll", { password: USERS[user].password }).then(({ body: { secret } }) =>cy.request("POST", "/api/ee/mfa/enroll/confirm", {@@ -395,6 +748,26 @@ function signInWithPassword() {cy.button("Sign in").click();}+function signInWithLdap() {+ cy.signOut();+ cy.visit("/auth/login");+ cy.findByLabelText("Username or email address").type(LDAP_USER.username);+ cy.findByLabelText("Password").type(LDAP_USER.password);+ cy.button("Sign in").click();+}++// Create a user to match what SAML server will respond with so they have+// have same permissions as a normal user+function createSamlUser() {+ // @ts-expect-error - this isn't typed yet+ return cy.createUserFromRawData({+ first_name: SAML_USER.username,+ last_name: SAML_USER.username,+ email: SAML_USER_EMAIL,+ user_group_memberships: normal.user_group_memberships,+ });+}+function getResetLink(html: string) {const [, anchor] = html.match(/<a (.*)>/) ?? [];const [, href] = String(anchor).match(/href="([^"]+)"/) ?? [];diff --git a/e2e/test/scenarios/docker-compose.yml b/e2e/test/scenarios/docker-compose.ymlindex 686fc8f09dc..ecb4463ff20 100644--- a/e2e/test/scenarios/docker-compose.yml+++ b/e2e/test/scenarios/docker-compose.yml@@ -55,6 +55,16 @@ services:volumes:- ./maildev-keys:/keys+ saml-idp:+ image: boxyhq/mock-saml:1.4.2+ ports:+ - "8090:4000"+ environment:+ APP_URL: http://localhost:8090+ ENTITY_ID: https://saml.example.com/entityid+ env_file:+ - ./saml-keys/mock-saml.env+ldap:image: bitnamilegacy/openldap:2.6.4ports:diff --git a/e2e/test/scenarios/saml-keys/mock-saml.env b/e2e/test/scenarios/saml-keys/mock-saml.envnew file mode 100644index 00000000000..96f691a9230--- /dev/null+++ b/e2e/test/scenarios/saml-keys/mock-saml.env@@ -0,0 +1,5 @@+# Test-only keypair for the mock-saml IdP. Generated with:+# openssl req -x509 -newkey rsa:2048 -keyout key.pem -out public.crt -sha256 -days 365000 -nodes+# mock-saml wants these base64-encoded rather than as file paths.+PUBLIC_KEY=LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURKVENDQWcyZ0F3SUJBZ0lVUTRlWlhnYnRRT25TeWxlSFFkbW51UE1rY3NNd0RRWUpLb1pJaHZjTkFRRUwKQlFBd0lURWZNQjBHQTFVRUF3d1diV1YwWVdKaGMyVXRaVEpsTFcxdlkyc3RjMkZ0YkRBZ0Z3MHlOakE0TURZeApPVEl4TVRWYUdBOHpNREkxTVRJd056RTVNakV4TlZvd0lURWZNQjBHQTFVRUF3d1diV1YwWVdKaGMyVXRaVEpsCkxXMXZZMnN0YzJGdGJEQ0NBU0l3RFFZSktvWklodmNOQVFFQkJRQURnZ0VQQURDQ0FRb0NnZ0VCQUpoV3NIR3EKaWxNOURnbk5tNXpUdnVtRFF3dGgrV2hIL1hqcUZTbmVnVE9WazZLR3dRaVkydjE1WGJaU1JaUnhVeGNzMnprNAp1OGZnRFBvL0FKNGs0UkxBejlSWmZ3VTliWVN1R05TOUlFWTUzTnRQOXZONElkM2Q3WGpxeXdoNjEvcjJKdUU2CkRNOFNSd0NVaUovQWZ4MzN4ZWpmTjl1R0gwTGFpN1lOVGRRZ3d6Z1dLbjJJMEJzMlBQcEVld251U2dwODN0OVIKT25QS3Nibmw3SXBmWTQyZHRCWFV3UGlxaFp5M0tFeElYdG5QNzlVU1hBM1dzTlRjYTFUS3lheGRCTzY3UGtPWQpzejJuL2xldUlJYWRQa3AyY0VTVXZ2cDNkQlg4bjRlb081em0rVndycFNGSXFpSjRwdmc4UkZuYzFGWEdxYTRNCkRVeUF1ZEs1UXJZaEZyc0NBd0VBQWFOVE1GRXdIUVlEVlIwT0JCWUVGSUIyaGFCd3dzNTBKNHJJSGVhRk9RVkYKZmRJbE1COEdBMVVkSXdRWU1CYUFGSUIyaGFCd3dzNTBKNHJJSGVhRk9RVkZmZElsTUE4R0ExVWRFd0VCL3dRRgpNQU1CQWY4d0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dFQkFBWnBYeXd6UURKVk9aZlNPbkJsL3RDU1ZwamRhNXhYCmQyRlVoR2hDd1ZCZUZVMC9jSnduMldpR3ppRDZ1QW1XNDFSaVYzWkxuMnZlSUtja001NFBnTjFPKzN6SlcvT1oKS2dONW5rdExyUitkODhFb3ppc00zOFRtT3UzeHNjdmxRTVRKeVRkZTBCemtqSEFlUUhaS0J3d01ja1JjQ0pFago3cjhRbU1lcG1kektYV1ZtcXEvZHRQNHZudmVYNjdPYUY0Y00zcXdJRFhabE9KUzVEblVVRWtTMUtaSXlrdnRkClF2VGE4RzdMU1lpekNJcVkyVm01VHhuY0pyUExvTHZVcG81aXRZQ1BnNXRpd3V0MjJ3NDRyQ3c4aFlDRzFsUysKWjBKaEd4Sm81ZlBTdHBZT0ZQd3NtN3k4bzF3MEtXd29jZ0N2UzZyaStVRlJHZ0hPdUtXN0tXMD0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=+PRIVATE_KEY=LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2UUlCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQktjd2dnU2pBZ0VBQW9JQkFRQ1lWckJ4cW9wVFBRNEoKelp1YzA3N3BnME1MWWZsb1IvMTQ2aFVwM29FemxaT2loc0VJbU5yOWVWMjJVa1dVY1ZNWExOczVPTHZINEF6NgpQd0NlSk9FU3dNL1VXWDhGUFcyRXJoalV2U0JHT2R6YlQvYnplQ0hkM2UxNDZzc0lldGY2OWliaE9nelBFa2NBCmxJaWZ3SDhkOThYbzN6ZmJoaDlDMm91MkRVM1VJTU00RmlwOWlOQWJOano2UkhzSjdrb0tmTjdmVVRwenlyRzUKNWV5S1gyT05uYlFWMU1ENHFvV2N0eWhNU0Y3WnorL1ZFbHdOMXJEVTNHdFV5c21zWFFUdXV6NURtTE05cC81WApyaUNHblQ1S2RuQkVsTDc2ZDNRVi9KK0hxRHVjNXZsY0s2VWhTS29pZUtiNFBFUlozTlJWeHFtdURBMU1nTG5TCnVVSzJJUmE3QWdNQkFBRUNnZ0VBSlFiRkFndWFiVnJrbzV0VzNFcFhGN2l3dmY2Rk9VUnVKa3AyOUdOQmNnRkUKRGZmRXlVc2x4d0FOdC9mTk02Ukx0dEZQUTF3M3dBQUVCM3J5c24xeU96V2tEZy9tb0tacWpSb25yT1YvQjdLZQpyS3VGOFcxY2hlbWdBNGpGNm55NUxDVlNFK0loSk45alpJKzFtV2FYUHZodklRZklNdElwblAwemdmOC8wSFA2Ckh6NHBmUjVOdFhtV0YzNWsvWnlLNXZIaHZobk5GRUVHUnJWZ3FYRGowc3BkZmFUU283S2JjQmNvRzdlNndhd2EKVXRhOTV0N1lNY21abDhQN3JlS2h5bVVEU1JJWWQ0c0F5UnE1NmIwWTFRNmRzUEgwT21JNE52ZnNtNWgxN3VVZwpPcVJtb3d2bndjVnFLZVJCazZ1bWtpdlphcjduUXpDc29Rb3Vob3c0YVFLQmdRREdaYWdMdWUvM2haNzNrV3d1CnRJT3o5N1lyK3FxemlBODEzQ2FlVFlXVXlIWXFzYWFJeklXazFZY1FkZERDMXB2NE8zY1NtL3RNZlA3YTBHVEwKa1hEUE50L2wyQXoxVkJGcms2QkxEWjVnWkovSnpneTA1U2xpUVdwR2JMUm5uTmtIaDJKdk5SQlhlSUE1cjMvWgpLcXd3T3JTOGVHakNuTi9ETmpaOVo1blhGd0tCZ1FERWthQkVXYkMvTWZua1JmSSszYVR5OFEvZ1pDOElyZ1JQCmYySFFGSzRDVlFGNXJHWm1jeEFVWHpKbmVTQ3NDNVFTMzcyaXJjNmRQZGx0bHAwd3YzenIwbVRLM05PU2JlVlIKUmdPNWlJRVZYNTZsVUJ4UGdZR0ZPQ25UdUpoTElaUUtybUdvbmRUY1ZnYjAxenZPK09uYjdKMytwMFhpbHpPTgpmbFQ1ZG1mRC9RS0JnSG9QMXprSHQ5VUExOUlYSFlrS3RMRUg2WVBiWUNTK3hDVHVBckNJbjNQdmRZeEU2bUhsCit4OXo0L3BEa2lJZHFhNHEzOUtLTnkxVEJmV1lHenVIaXZGaUlKU252U2svQk15NzhmWGJOaUsySmYwaUVYMUcKTkpUb0REdXg2N2lIcnB0TU4wcVdTaXlXemNVdjdhZXQ4bXhsNGdiR3lpVmFJTzFZc0dPdFZ1QVhBb0dBWTFhMQpCOVhMM05RRTFiZ0RsSUd1dXBmWXppM1RGeS9hUGRMQ084WTNxallMYU5JWGJlNzRVVk5LeGNBUkl1RTNFOUsrCm8xZnk4c1F1L1pNQUhZS29Qd1UwcXRDdW0zR3VVa1J2M1hOK3lLNXFIbUU5N1hBbFpJM2RsWUhVZFNPakRVTFQKVjhOcnIyNUtWYkh3SjhqalpxRk50MFFSclZGOFhDVmNERFlxZW9FQ2dZRUF2QTNBTS9BbHN1eFpCTTFPVnIzRQpvUW0rSC9ESkw3QUtrbkM2b2JkUkpaUGYyVmtpYmdHS1IwUW1JMU95dDF0MjI0MnBPT25JVWtEcmdvMXJpS0tCClY1WmVZalJQeUpJU01IcHFxZjlFakpIaUIxb3gxdnlFb3J4cVMrZFZyQlV3QW0wYVBQOEhCVkxhaXd5VVo3SS8KeHpxUHl5VUpncEozM1UrTzdlSXJOTW89Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0Kdiff --git a/e2e/test/scenarios/saml-keys/public.crt b/e2e/test/scenarios/saml-keys/public.crtnew file mode 100644index 00000000000..aeea776758d--- /dev/null+++ b/e2e/test/scenarios/saml-keys/public.crt@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDJTCCAg2gAwIBAgIUQ4eZXgbtQOnSyleHQdmnuPMkcsMwDQYJKoZIhvcNAQEL+BQAwITEfMB0GA1UEAwwWbWV0YWJhc2UtZTJlLW1vY2stc2FtbDAgFw0yNjA4MDYx+OTIxMTVaGA8zMDI1MTIwNzE5MjExNVowITEfMB0GA1UEAwwWbWV0YWJhc2UtZTJl+LW1vY2stc2FtbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJhWsHGq+ilM9DgnNm5zTvumDQwth+WhH/XjqFSnegTOVk6KGwQiY2v15XbZSRZRxUxcs2zk4+u8fgDPo/AJ4k4RLAz9RZfwU9bYSuGNS9IEY53NtP9vN4Id3d7Xjqywh61/r2JuE6+DM8SRwCUiJ/Afx33xejfN9uGH0Lai7YNTdQgwzgWKn2I0Bs2PPpEewnuSgp83t9R+OnPKsbnl7IpfY42dtBXUwPiqhZy3KExIXtnP79USXA3WsNTca1TKyaxdBO67PkOY+sz2n/leuIIadPkp2cESUvvp3dBX8n4eoO5zm+VwrpSFIqiJ4pvg8RFnc1FXGqa4M+DUyAudK5QrYhFrsCAwEAAaNTMFEwHQYDVR0OBBYEFIB2haBwws50J4rIHeaFOQVF+fdIlMB8GA1UdIwQYMBaAFIB2haBwws50J4rIHeaFOQVFfdIlMA8GA1UdEwEB/wQF+MAMBAf8wDQYJKoZIhvcNAQELBQADggEBAAZpXywzQDJVOZfSOnBl/tCSVpjda5xX+d2FUhGhCwVBeFU0/cJwn2WiGziD6uAmW41RiV3ZLn2veIKckM54PgN1O+3zJW/OZ+KgN5nktLrR+d88EozisM38TmOu3xscvlQMTJyTde0BzkjHAeQHZKBwwMckRcCJEj+7r8QmMepmdzKXWVmqq/dtP4vnveX67OaF4cM3qwIDXZlOJS5DnUUEkS1KZIykvtd+QvTa8G7LSYizCIqY2Vm5TxncJrPLoLvUpo5itYCPg5tiwut22w44rCw8hYCG1lS++Z0JhGxJo5fPStpYOFPwsm7y8o1w0KWwocgCvS6ri+UFRGgHOuKW7KW0=+-----END CERTIFICATE-----diff --git a/enterprise/backend/src/metabase_enterprise/mfa/core.clj b/enterprise/backend/src/metabase_enterprise/mfa/core.cljindex 5f0f040e8d3..a6d82efc4e6 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/core.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/core.clj@@ -5,10 +5,12 @@or mfa.settings directly."(:require[metabase-enterprise.mfa.db :as mfa.db]+ [metabase-enterprise.mfa.enrollment :as enrollment][metabase-enterprise.mfa.gate :as gate][metabase-enterprise.mfa.settings][metabase-enterprise.mfa.verification :as verification][metabase.channel.email.messages :as messages]+ [metabase.mfa.settings][metabase.premium-features.core :refer [defenterprise]][metabase.util.i18n :refer [tru]][metabase.util.log :as log]@@ -18,8 +20,9 @@(p/import-vars[metabase-enterprise.mfa.settings- mfa-enforcement- mfa-enabled?])+ mfa-enabled?]+ [metabase.mfa.settings+ mfa-enforcement])(defenterprise apply-mfa-gate"Decide whether a successful first-factor login must complete a second factor before a session is@@ -36,14 +39,46 @@(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.+ consuming it plus the challenge jti.- OSS fallback returns false — OSS can never have issued a challenge token (the MFA gate lives in+ Returns the AuthIdentity of the 2nd factor method verified, else nil.++ OSS fallback returns nil — OSS can never have issued a challenge token (the MFA gate lives inEE), so this is unreachable in practice.":feature :none[user-id code jti](verification/verify-attempt! user-id code jti))+(defenterprise start-enrollment!+ "Begin enrollment of a new authenticator for a user who is not currently enrolled, and attempting to log in.+ Only called when the instance is configured to *require* MFA, but this user is not enrolled.++ Precondition: caller must validate that the correct username and password for this `user-id` have been provided.++ Returns a map intended for the `:body` of a response, containing the plaintext `:secret` and the `:otpauth_uri`+ used for the QR code. Returns nil if any conditions fail (e.g. if the user is already enrolled).++ OSS always returns nil, since new enrollments are not allowed without the `:multi-factor-auth` feature."+ :feature :multi-factor-auth+ [user-id]+ (enrollment/start-enrollment! user-id))++(defenterprise confirm-enrollment!+ "Complete enrollment of a new authenticator for a currently pending enrollment. Requires the `user-id` and `code`,+ plus the single-use `jti` from a [[metabase.session.challenge/issue-enrollment-token]].++ On success, marks the enrollment as confirmed, consumes the OTP's time step (so it can't be reused), generates the+ recovery codes, and consumes the `jti` so it can't be reused either.++ Returns a map containing the plaintext recovery codes + the id of the AuthIdentity record which was confirmed,+ or nil if any conditions fail.++ Note that this actually requires the `:multi-factor-auth` feature. [[verify-second-factor!]] above will still verify+ existing OTPs after a downgrade, but we won't allow new enrollments. The OSS counterpart always returns nil."+ :feature :multi-factor-auth+ [user-id code jti]+ (enrollment/confirm-enrollment! 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 thatalready minted a session.@@ -67,3 +102,9 @@;; 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}))))))++(defenterprise mfa-required?+ "Whether MFA is currently required for all users on the instance"+ :feature :multi-factor-auth+ []+ (metabase-enterprise.mfa.settings/mfa-required?))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.cljindex dcb50fed76c..8ca8ab6dca4 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj@@ -17,6 +17,7 @@[metabase-enterprise.mfa.recovery-codes :as recovery-codes][metabase-enterprise.mfa.totp :as totp][metabase-enterprise.mfa.verification :as verification]+ [metabase.appearance.core :as appearance][metabase.util.password :as u.password][toucan2.core :as t2]))@@ -37,17 +38,24 @@(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)."+ pending confirmation (the model encrypts the credentials column at rest).++ Precondition: Caller is responsible for checking that the request legitimately comes from `user-id`. Either the+ user should already be logged in (and we should require and validate their password too), or they have just+ entered their password during login, and the instance requires MFA but they're not enrolled yet.++ Returns a map with the the plaintext `:secret` and `:otpauth_uri` for use as a QR code; or nil if the user+ already has a *confirmed* enrollment.++ Disable any existing enrollment first, if you want to re-enroll. Silently replacing a confirmed second factor with+ a new enrollment would let a 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- (mfa.db/lock-user user-id)- (let [auth-identity (mfa.db/lock-totp-identity user-id)]+ (let [user (mfa.db/lock-user user-id)+ auth-identity (mfa.db/lock-totp-identity user-id)](when-not (some-> auth-identity verification/confirmed?)(let [secret (totp/generate-secret)credentials {:secret secret}]@@ -56,26 +64,37 @@(mfa.db/insert-auth-identity! {:user_id user-id:provider "totp":credentials credentials}))- secret)))))+ {:secret secret+ :otpauth_uri (totp/otpauth-uri {:issuer (or (appearance/site-name) "Metabase")+ :account (:email user)+ :secret secret})})))))(defn confirm-enrollment!"Confirm a pending enrollment by verifying a live `code` against the pending secret. On successmarks the enrollment confirmed, consumes the code's time step (so it can't also complete alogin), 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 (mfa.db/lock-totp-identity user-id)]- (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)]- (mfa.db/update-auth-identity! (: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)))))))+ failure or when there is no pending enrollment.++ Accepts an optional `jti`. Ignored if nil, but if present the `jti` will be atomically checked and+ consumed in the same transaction **if** the enrollment is successful. That prevents using a single+ password entry for multiple enrollments. Failed enrollment does not consume the `jti`, which allows+ e.g. a typo'd OTP to be retried."+ ([user-id code] (confirm-enrollment! user-id code nil))+ ([user-id code jti]+ (t2/with-transaction [_conn]+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)]+ (when-not (verification/confirmed? auth-identity)+ (when-not (verification/jti-used? (:credentials auth-identity) jti)+ (when-let [secret (verification/stored-secret auth-identity)]+ (when-let [step (totp/matching-time-step secret code)]+ (let [codes (recovery-codes/generate-codes)]+ (mfa.db/update-auth-identity! (:id auth-identity)+ {:confirmed_at (t/instant)+ :credentials (assoc (:credentials auth-identity)+ :last_used_step step+ :recovery_codes (mapv u.password/hash-bcrypt codes))})+ {:recovery-codes codes+ :mfa-auth-identity-id (:id auth-identity)})))))))))(defn disable!"Remove `user-id`'s TOTP enrollment entirely (re-auth is the caller's responsibility). True whendiff --git a/enterprise/backend/src/metabase_enterprise/mfa/gate.clj b/enterprise/backend/src/metabase_enterprise/mfa/gate.cljindex 6295c35f0b9..c8c050f31bd 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/gate.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/gate.clj@@ -13,8 +13,10 @@audited, and Metabase staff cannot hold the user's second factor.- SSO providers — exempt: the identity provider owns MFA there."(:require+ [better-cond.core :as b][metabase-enterprise.mfa.enrollment :as enrollment][metabase-enterprise.mfa.settings :as mfa.settings]+ [metabase.auth-identity.core :as auth-identity][metabase.channel.settings :as channel.settings]))(set! *warn-on-reflection* true)@@ -26,38 +28,77 @@(cond-> ["totp"](channel.settings/email-configured?) (conj "email")))-(def ^:private challenged-providers- #{:provider/password :provider/ldap})+(defn- challenged-provider?+ [provider]+ (auth-identity/isa? provider :metabase.auth-identity.provider/supports-mfa))(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."+ "Decide whether a successful first-factor login must complete a second factor before a session is created.++ - If the login was not successful, return it directly.+ - Transparent if MFA is disabled (`:off`); just returns the initial login result.+ - If this user is enrolled in MFA, signals that MFA is required to complete log-in:+ - Sets `:mfa/pending?`, which suppresses creating a session in the `login!` pipeline.+ - Attaches `:mfa/first-factor` to the `:provider/*` keyword used for the initial login.+ - Attaches `:mfa/methods` giving a list of second factor approaches this user and instance can support.+ - If MFA is *required* but this user is not enrolled yet, signals that MFA must be enrolled immediately to log in:+ - Sets `:mfa/pending?` and `:mfa/first-factor` as above.+ - Sets `:mfa/enroll? true` as well.+ - `:mfa/methods` is hard-coded to `\"totp\"`, since that's the method we want to configure, and we don't want to+ fall back to email here."[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])+ (b/cond+ ;; Pass through the first factor's `login-result` in two cases:+ ;; 1. First factor login failed+ (not (and (true? (:success? login-result))+ (:user login-result))) login-result+ ;; 2. MFA is not enabled at all+ (not (mfa.settings/mfa-enabled?)) login-result+ ;; 3. First factor does not need MFA (e.g. SSO, Google)+ (and (not (challenged-provider? provider))+ (not (contains? session-suppressed-providers provider))) login-result++ ;; At this point, we could plausibly require an MFA challenge or enrollment.+ :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))))++ ;; MFA configured and the provider supports MFA challenges: issue a challenge.+ ;; This signals `login!` not to mint a session yet.+ (and method (challenged-provider? provider))+ (assoc login-result+ :success? :mfa-required+ :mfa/pending? true+ :mfa/methods (available-methods)+ :mfa/first-factor provider)++ ;; If MFA is not enrolled, but not required, pass through the first factor.+ (and (nil? method)+ (not (mfa.settings/mfa-required?))) login-result++ ;; If the first factor is a special case (e.g. :provider/emailed-secret-password-reset) we don't log them in+ ;; directly after the new password is accepted, when MFA is in play. Instead, they get redirected to the regular+ ;; login page to re-enter their password and then answer an MFA challenge (or enroll).+ ;; This signals the `login!` flow accordingly.+ (contains? session-suppressed-providers provider)+ (assoc login-result :mfa/pending? true)++ ;; At this point, we know:+ ;; - First factor is a [[challenged-provider?]]+ ;; - User does not have MFA enrolled+ ;; - MFA is enabled+ ;; That leaves two cases.++ ;; 1. If MFA is *required*, they must immediately enroll.+ (mfa.settings/mfa-required?)+ (assoc login-result+ :success? :mfa-required+ :mfa/pending? true+ :mfa/enroll? true+ :mfa/methods ["totp"]+ :mfa/first-factor provider)++ ;; 2. MFA is enabled, but neither enrolled nor required: regular login.+ :else login-result))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/management.clj b/enterprise/backend/src/metabase_enterprise/mfa/management.cljindex ba173209d76..2b31b4cc7bb 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/management.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/management.clj@@ -15,11 +15,9 @@[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]@@ -110,14 +108,11 @@(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 (mfa.db/user-email api/*current-user-id*)]- {:secret secret- :otpauth_uri (totp/otpauth-uri {:issuer (or (appearance/site-name) "Metabase")- :account user-email- :secret secret})}))))+ ;; Precondition for [[enrollment/start-enrollment!]] is met: this user is logged in and we just+ ;; re-validated their password.+ (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}))))))(api.macros/defendpoint :post "/enroll/confirm" :- [:map[:recovery_codes [:sequential ms/NonBlankString]]]@@ -127,14 +122,14 @@_query-params{:keys [code]} :- [:map {:closed true} [: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)))))+ (let [{:keys [recovery-codes]} (throttled :enroll+ (fn []+ (or (enrollment/confirm-enrollment! api/*current-user-id* code)+ (throw (invalid-code-ex)))))user (mfa.db/user api/*current-user-id*)](messages/send-mfa-enabled-email! (:email user))(events/publish-event! :event/mfa-enrolled {:object user})- {:recovery_codes codes}))+ {:recovery_codes recovery-codes}))(api.macros/defendpoint :post "/disable" :- nil"Disable two-factor authentication for the current user. Re-auth is a fresh second factor — adiff --git a/enterprise/backend/src/metabase_enterprise/mfa/settings.clj b/enterprise/backend/src/metabase_enterprise/mfa/settings.cljindex 73131f3cb0b..05c4546b5dd 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/settings.clj@@ -1,5 +1,5 @@(ns metabase-enterprise.mfa.settings- "Settings for native multi-factor authentication.+ "EE-only settings for native multi-factor authentication.`mfa-enforcement` is deliberately NOT `:feature`-gated on read: `defsetting`'s `:feature` optionreturns the default value when the feature is absent, which on license lapse would read as@@ -7,32 +7,40 @@turning the setting ON (any value other than `:off`), so an admin on a lapsed license can alwaysset enforcement back to `:off`."(:require+ [java-time.api :as t]+ [metabase.mfa.settings :as mfa.settings][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru tru]]))+ [metabase.util.i18n :refer [deferred-tru tru]]+ [metabase.util.time :as u.time]))(set! *warn-on-reflection* true)-(def ^:private valid-enforcement-values #{:off :optional})+(defn mfa-enabled?+ "True when MFA is available to users at all (enforcement is not :off)."+ []+ (not= (mfa.settings/mfa-enforcement) :off))-(defsetting mfa-enforcement- (deferred-tru "Controls whether two-factor authentication is available to users. :off disables it entirely; :optional allows users to enroll voluntarily.")+(defsetting mfa-requirement-deadline+ (deferred-tru "Time after which mfa-enforcement will take effect for all users"):visibility :public- :type :keyword- :default :off+ :type :timestamp+ :default nil:export? false- :audit :raw-value+ :audit :getter: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))))+ (when new-value+ (premium-features/assert-has-feature :multi-factor-auth (tru "Multi-factor authentication")))+ (setting/set-value-of-type! :timestamp :mfa-requirement-deadline new-value)))-(defn mfa-enabled?- "True when MFA is available to users at all (enforcement is not :off)."- []- (not= (mfa-enforcement) :off))+(defn mfa-required?+ "True when MFA is required for all users (enforcement is :required)."+ ([now]+ (and (= (mfa.settings/mfa-enforcement) :required)+ (let [deadline (mfa-requirement-deadline)]+ (or (nil? deadline)+ (t/after?+ (u.time/coerce-to-timestamp now)+ (u.time/coerce-to-timestamp deadline))))))+ ([]+ (mfa-required? (t/offset-date-time))))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/verification.clj b/enterprise/backend/src/metabase_enterprise/mfa/verification.cljindex 23b059f2d2e..f6758397ae6 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/verification.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/verification.clj@@ -47,7 +47,10 @@[auth-identity](get-in auth-identity [:credentials :secret]))-(defn- jti-used? [credentials jti]+(defn jti-used?+ "Given the `:credentials` and a candidate `jti`, return true if that `jti` has been previously used for these+ credentials. Prevents reuse of a single password entry for multiple challenges or enrollments."+ [credentials jti](boolean (some #(= (:jti %) jti) (:used_jtis credentials))))(defn jti-consumed?@@ -55,7 +58,7 @@[user-id jti](boolean (some-> (totp-identity user-id) :credentials (jti-used? jti))))-(defn- consume-jti+(defn consume-jti"Record `jti` as used (nil jti = session re-auth, nothing to record), pruning expired entries."[credentials jti](if-not jti@@ -119,18 +122,20 @@recovery code, or the emailed code, plus the challenge `jti` when one is given (pass nil forsession re-auth, where no challenge token exists).- True only for a confirmed enrollment with an unused jti and an unconsumed code. Runs in a+ Verification succeeds only for a confirmed enrollment with an unused jti and an unconsumed code. Runs in atransaction with the enrollment row locked so a concurrently replayed code, recovery code, or- token cannot pass twice."+ token cannot pass twice.++ On successful verification the AuthIdentity associated with the second factor is returned, else nil"[user-id code jti](t2/with-transaction [_conn]- (boolean- (when-let [auth-identity (mfa.db/lock-totp-identity user-id)]- (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)))))))+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)]+ (when (and (confirmed? auth-identity)+ (not (jti-used? (:credentials auth-identity) jti)))+ (when (or (totp-attempt! auth-identity code jti)+ (recovery-attempt! auth-identity code jti)+ (email-otp-attempt! auth-identity code jti))+ auth-identity)))))(defn set-email-otp!"Generate a 6-digit emailed one-time code for `user-id`'s confirmed enrollment, replacing anydiff --git a/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.cljindex 513b9b1a07a..c45f86a8995 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/email_otp_test.clj@@ -36,9 +36,9 @@: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))))+ (is (true? (boolean (verification/verify-attempt! user-id code (fresh-jti)))))(testing "single-use"- (is (false? (verification/verify-attempt! user-id code (fresh-jti)))))))))+ (is (false? (boolean (verification/verify-attempt! user-id code (fresh-jti))))))))))(deftest successful-verify-clears-pending-email-otp-test(let [secret (totp/generate-secret)]@@ -48,9 +48,9 @@: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))))+ (is (true? (boolean (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)))))))))+ (is (false? (boolean (verification/verify-attempt! user-id email-code (fresh-jti))))))))))(deftest email-otp-requires-confirmed-enrollment-test(mt/with-temp [:model/User {user-id :id} {}@@ -72,7 +72,7 @@(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))))))))+ (is (false? (boolean (verification/verify-attempt! user-id code (fresh-jti)))))))))(deftest send-email-otp-e2e-test(mt/with-premium-features #{:multi-factor-auth}diff --git a/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.cljindex 5e4e3124081..d6838d0d514 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj@@ -2,10 +2,11 @@(:require[clojure.test :refer :all][java-time.api :as t]- [metabase-enterprise.mfa.settings :as mfa.settings]+ [metabase-enterprise.mfa.settings :as mfa.settings.ee][metabase-enterprise.mfa.totp :as totp][metabase.auth-identity.core :as auth-identity][metabase.auth-identity.provider :as auth-identity.provider]+ [metabase.mfa.settings :as mfa.settings.oss][metabase.test :as mt]))(defn- with-enrolled-user! [f]@@ -139,7 +140,7 @@(:success? (auth-identity.provider/apply-mfa-gate :provider/password result)))"sanity: challenged before the override")(mt/with-temp-env-var-value! [mb-mfa-enforcement "off"]- (is (false? (mfa.settings/mfa-enabled?))+ (is (false? (mfa.settings.ee/mfa-enabled?))"the env var beats the DB value")(is (= result (auth-identity.provider/apply-mfa-gate :provider/password result))"the gate no-ops, so the locked-out admin can log in"))))))))@@ -149,17 +150,17 @@(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)))))+ (mfa.settings.oss/mfa-enforcement! :optional)))+ (is (= :off (mfa.settings.oss/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)))))+ (mfa.settings.oss/mfa-enforcement! :optional)+ (is (= :optional (mfa.settings.oss/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"+ (mfa.settings.oss/mfa-enforcement! :off)+ (is (= :off (mfa.settings.oss/mfa-enforcement)))))+ (testing "setting :required counts as enforcement"(mt/with-premium-features #{:multi-factor-auth}- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"reserved"- (mfa.settings/mfa-enforcement! :required)))))))+ (mfa.settings.oss/mfa-enforcement! :required)+ (is (= :required (mfa.settings.oss/mfa-enforcement)))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.cljindex a2acbdfc008..3373b030f17 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj@@ -211,27 +211,53 @@(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))+ (is (false? (boolean (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} {}]- (try- (t2/insert! :model/AuthIdentity {:user_id user-id- :provider "totp"- :confirmed_at (t/instant)- :credentials {:secret (totp/generate-secret)}})+ (doseq [[label enforcement deadline] [["enrolled and :optional" :optional nil]+ ["enrolled and :required, no deadline" :required nil]+ ["enrolled and :required, deadline past"+ :required (t/minus (t/offset-date-time) (t/days 12))]+ ["enrolled and :required, deadline in the future"+ :required (t/plus (t/offset-date-time) (t/days 12))]]]+ (mt/with-temporary-setting-values [mfa-enforcement enforcement+ mfa-requirement-deadline deadline]+ (mt/with-model-cleanup [:model/AuthIdentity]+ (mt/with-temp [:model/User {user-id :id, email :email} {}]+ (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 label+ (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)))))))))))))++(deftest password-reset-when-required-and-unenrolled-issues-no-session-test+ (mt/with-premium-features #{:multi-factor-auth}+ (doseq [[label enforcement deadline] [["unenrolled and :required, no deadline" :required nil]+ ["unenrolled and :required, deadline past"+ :required (t/minus (t/offset-date-time) (t/days 12))]]]+ (mt/with-temporary-setting-values [mfa-enforcement enforcement+ mfa-requirement-deadline deadline]+ (mt/with-temp [:model/User {user-id :id, email :email} {}](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")))))))+ (testing label+ (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_enrollment login))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.cljindex 85bc036f34f..3de007ab41a 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/recovery_codes_test.clj@@ -53,32 +53,32 @@(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 (true? (boolean (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))))))))+ (is (false? (boolean (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)))))+ (is (false? (boolean (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))))))))+ (is (true? (boolean (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)))+ (is (true? (boolean (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))))+ (is (false? (boolean (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)))))))+ (is (false? (boolean (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 (false? (boolean (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/verification_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/verification_test.cljindex e0a3c1bbac6..7b938ec323b 100644--- a/enterprise/backend/test/metabase_enterprise/mfa/verification_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mfa/verification_test.clj@@ -29,9 +29,9 @@:confirmed_at (t/instant):credentials {:secret secret}}](let [code (totp/generate-code secret)]- (is (true? (verification/verify-attempt! user-id code (fresh-jti))))+ (is (true? (boolean (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)))))))))+ (is (false? (boolean (verification/verify-attempt! user-id code (fresh-jti))))))))))(deftest verify-rejects-used-jti-test(let [secret (totp/generate-secret)@@ -44,7 +44,7 @@: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)))))))+ (is (false? (boolean (verification/verify-attempt! user-id (totp/generate-code secret) jti))))))))(deftest verify-rejects-stale-step-test(let [secret (totp/generate-secret)]@@ -56,7 +56,7 @@;; 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))))))))+ (is (false? (boolean (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti)))))))))(deftest verify-rejects-unconfirmed-test(let [secret (totp/generate-secret)]@@ -64,7 +64,7 @@:model/AuthIdentity _ {:user_id user-id:provider "totp":credentials {:secret secret}}]- (is (false? (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti)))))))+ (is (false? (boolean (verification/verify-attempt! user-id (totp/generate-code secret) (fresh-jti))))))))(deftest expired-jtis-are-pruned-test(let [secret (totp/generate-secret)@@ -75,7 +75,7 @@: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))))+ (is (true? (boolean (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)))@@ -117,7 +117,7 @@(future(.await latch)(binding [t2.conn/*current-connectable* nil]- (verification/verify-attempt! user-id code (fresh-jti)))))))]+ (boolean (verification/verify-attempt! user-id code (fresh-jti))))))))];; release the gate -- all threads race(.countDown latch)(let [results (mapv #(deref % 10000 :timeout) futures)]@@ -152,7 +152,7 @@(future(.await latch)(binding [t2.conn/*current-connectable* nil]- (verification/verify-attempt! user-id code (fresh-jti)))))))]+ (boolean (verification/verify-attempt! user-id code (fresh-jti))))))))](.countDown latch)(let [results (mapv #(deref % 10000 :timeout) futures)](testing "no timeouts"@@ -190,7 +190,7 @@(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)))+ (is (true? (boolean (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 thediff --git a/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.ts b/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.tsindex 51541e2e783..1bd065e16da 100644--- a/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/multi-factor-auth.ts@@ -65,6 +65,8 @@ export const multiFactorAuthApi = EnterpriseApi.injectEndpoints({idTag("user", user_id),]),}),+ // `/api/session/*` 401s mean "wrong code", not "session gone". `noEvent` stops app-main+ // redirecting to /auth/login, which would remount the page and lose the retry.verifyMfa: builder.mutation<{ id: string },{ challenge_token: string; code: string; remember?: boolean }@@ -73,6 +75,18 @@ export const multiFactorAuthApi = EnterpriseApi.injectEndpoints({method: "POST",url: "/api/session/mfa/verify",body,+ noEvent: true,+ }),+ }),+ enrollMfaOnLogin: builder.mutation<+ { id: string; recovery_codes: string[] },+ { enrollment_token: string; code: string; remember?: boolean }+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/session/mfa/enroll",+ body,+ noEvent: true,}),}),getMfaStatus: builder.query<MfaStatus, void>({@@ -116,6 +130,7 @@ export const multiFactorAuthApi = EnterpriseApi.injectEndpoints({method: "POST",url: "/api/session/mfa/send-email-otp",body,+ noEvent: true,}),}),regenerateRecoveryCodes: builder.mutation<@@ -138,6 +153,7 @@ export const {useListUnenrolledMfaUsersQuery,useRemoveUserMfaMutation,useVerifyMfaMutation,+ useEnrollMfaOnLoginMutation,useGetMfaStatusQuery,useEnrollMfaMutation,useConfirmMfaEnrollmentMutation,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.tsxindex 79ae376ea2c..3a6afd1508d 100644--- 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.tsx@@ -3,7 +3,8 @@ import { t } from "ttag";import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";import { useHasTokenFeature } from "metabase/common/hooks";-import { Box, Button, Group, Stack } from "metabase/ui";+import { useSetting } from "metabase/settings";+import { Box, Button, Group, Stack, Tooltip } from "metabase/ui";import { useGetMfaStatusQuery } from "metabase-enterprise/api";import type { MfaStatus } from "metabase-types/api";@@ -61,6 +62,9 @@ type MfaSectionProps = {};function MfaSection({ status, hasFeature, onOpenModal }: MfaSectionProps) {+ const mfaEnforcement = useSetting("mfa-enforcement");++ const isMfaRequired = mfaEnforcement === "required";return (<Group justify="space-between" align="flex-start" wrap="nowrap"><Stack gap="xxs">@@ -74,9 +78,15 @@ function MfaSection({ status, hasFeature, onOpenModal }: MfaSectionProps) {<Box>{status.enrolled ? (<Group gap="sm" wrap="nowrap">- <Button- onClick={() => onOpenModal("disable")}- >{t`Disable`}</Button>+ <Tooltip+ label={t`Two-factor authentication can not be disabled when it is required on your instance`}+ disabled={!isMfaRequired}+ >+ <Button+ onClick={() => onOpenModal("disable")}+ disabled={isMfaRequired}+ >{t`Disable`}</Button>+ </Tooltip><Button onClick={() => onOpenModal("recovery-codes")}>{t`Generate recovery codes`}</Button>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.tsxindex 20ea39fd141..7a6f95103a2 100644--- 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.tsx@@ -11,7 +11,7 @@ import {screen,waitForLoaderToBeRemoved,} from "__support__/ui";-import type { MfaStatus } from "metabase-types/api";+import type { MfaEnforcement, MfaStatus } from "metabase-types/api";import {createMockMfaStatus,createMockTokenFeatures,@@ -23,12 +23,14 @@ type SetupOpts = {status?: MfaStatus;hasStatusError?: boolean;hasFeature?: boolean;+ enforcement?: MfaEnforcement;};function setup({status = createMockMfaStatus(),hasStatusError = false,hasFeature = true,+ enforcement = "optional",}: SetupOpts = {}) {if (hasStatusError) {setupMfaStatusEndpointError();@@ -39,6 +41,7 @@ function setup({renderWithProviders(<AccountSecurityPanel />, {storeInitialState: createMockState({settings: mockSettings({+ "mfa-enforcement": enforcement,"token-features": createMockTokenFeatures({"multi-factor-auth": hasFeature,}),@@ -106,7 +109,6 @@ describe("AccountSecurityPanel", () => {}),).toBeInTheDocument();});-it("should render nothing when the instance has two-factor authentication off", async () => {setup({status: createMockMfaStatus({ mfa_enabled: false, enrolled: true }),@@ -120,6 +122,19 @@ describe("AccountSecurityPanel", () => {expect(screen.queryByRole("button")).not.toBeInTheDocument();});+ describe("when two-factor authentication is required", () => {+ it("should not let an enrolled user disable it", async () => {+ setup({+ status: createMockMfaStatus({ enrolled: true }),+ enforcement: "required",+ });++ expect(+ await screen.findByRole("button", { name: "Disable" }),+ ).toBeDisabled();+ });+ });+it("should show an error message when the status cannot be loaded", async () => {setup({ hasStatusError: true });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.tsxindex f091fb57641..a5e2468a363 100644--- 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.tsx@@ -4,8 +4,8 @@ import { jt, t } from "ttag";import { Box, Modal } from "metabase/ui";import { useRegenerateRecoveryCodesMutation } from "metabase-enterprise/api";+import { RecoveryCodesForm } from "../../common/RecoveryCodesForm";import { ConfirmCodeForm } from "../ConfirmCodeForm";-import { RecoveryCodesForm } from "../RecoveryCodesForm";type RecoveryCodesModalProps = {opened: boolean;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.tsxindex 2c54d4deb17..bc4fcea7758 100644--- 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.tsx@@ -1,5 +1,4 @@import { useState } from "react";-import QRCode from "react-qr-code";import { jt, t } from "ttag";import * as Yup from "yup";@@ -10,7 +9,7 @@ import {FormSubmitButton,FormTextInput,} from "metabase/forms";-import { Box, Button, Center, Group, Modal, Stack, Text } from "metabase/ui";+import { Box, Button, Group, Modal, Stack, Text } from "metabase/ui";import * as Errors from "metabase/utils/errors";import {useConfirmMfaEnrollmentMutation,@@ -20,10 +19,8 @@ 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;+import { RecoveryCodesForm } from "../../common/RecoveryCodesForm";+import { TotpEnrollInstructions } from "../../common/TotpEnrollInstructions";type SetupModalProps = {opened: boolean;@@ -170,18 +167,10 @@ function EnrollForm({ enrollment, onSuccess, onCancel }: EnrollFormProps) {><Form><Stack gap="lg">- <Stack gap="sm">- <Box>{t`Scan this QR code with an authenticator app:`}</Box>- <Center>- <Box bg="white" p="lg">- <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>+ <TotpEnrollInstructions+ otpauthUri={enrollment.otpauth_uri}+ secret={enrollment.secret}+ /><FormTextInputname="code"label={t`Enter the 6-digit code from the authenticator app`}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.tsxindex 6d40b7fb875..e9dd66daccd 100644--- 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.tsx@@ -1,59 +1,253 @@-import { msgid, ngettext, t } from "ttag";+import { useState } from "react";+import { jt, msgid, ngettext, t } from "ttag";import { SettingsSection } from "metabase/admin/components/SettingsSection";+import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { Link } from "metabase/common/components/Link";import { useHasTokenFeature } from "metabase/common/hooks";import { getUserIsAdmin } from "metabase/current-user";+import { dayjs } from "metabase/dayjs";import { useSelector } from "metabase/redux";import { useAdminSetting } from "metabase/settings";-import { Alert, Anchor, Group, Switch, Text } from "metabase/ui";-import { useGetMfaAdminOverviewQuery } from "metabase-enterprise/api";+import {+ Alert,+ Anchor,+ Box,+ DateInput,+ Group,+ Radio,+ Stack,+ Switch,+ Text,+ Tooltip,+} from "metabase/ui";+import {+ useGetMfaAdminOverviewQuery,+ useGetMfaStatusQuery,+} from "metabase-enterprise/api";import type { MfaAdminOverview } from "metabase-types/api";-import { ENROLLED_USERS_PATH, UNENROLLED_USERS_PATH } from "../../constants";+import {+ ACCOUNT_AUTHENTICATION_PATH,+ ENROLLED_USERS_PATH,+ UNENROLLED_USERS_PATH,+} from "../../constants";++const ENFORCEMENT_OPTIONS = ["optional", "required", "required-date"] as const;+type EnforcementOption = (typeof ENFORCEMENT_OPTIONS)[number];++const isEnforcementOption = (value: unknown): value is EnforcementOption =>+ typeof value === "string" &&+ ENFORCEMENT_OPTIONS.some((option) => option === value);++const getEnforcementOptions = (): {+ value: EnforcementOption;+ label: string;+}[] => [+ { value: "optional", label: t`Don't require` },+ { value: "required", label: t`Require now` },+ { value: "required-date", label: t`Require by a certain date` },+];++const DEADLINE_INPUT_FORMAT = "YYYY-MM-DD";++const toDeadlineSetting = (date: string | null) =>+ date ? dayjs(date).startOf("day").toISOString() : null;++const toDeadlineInput = (deadline: string | null | undefined) =>+ deadline ? dayjs(deadline).format(DEADLINE_INPUT_FORMAT) : null;++const DEFAULT_GRACE_PERIOD_DAYS = 14;++const getDefaultDeadline = () =>+ toDeadlineSetting(+ dayjs().add(DEFAULT_GRACE_PERIOD_DAYS, "day").format(DEADLINE_INPUT_FORMAT),+ );export function AdminAuthCard() {const hasFeature = useHasTokenFeature("multi-factor-auth");- const { value: enforcement, updateSetting } =- useAdminSetting("mfa-enforcement");+ const {+ value: enforcement,+ updateSetting,+ updateSettings,+ } = useAdminSetting("mfa-enforcement");+ const { value: deadline } = useAdminSetting("mfa-requirement-deadline");+ const { value: isPasswordLoginEnabled } = useAdminSetting(+ "enable-password-login",+ );+ const { value: isLdapEnabled } = useAdminSetting("ldap-enabled");+ const [isConfirmingRequireNow, setIsConfirmingRequireNow] = useState(false);const enabled = enforcement != null && enforcement !== "off";const { data: overview } = useGetMfaAdminOverviewQuery(undefined, {skip: !enabled,});+ const { data: mfaStatus } = useGetMfaStatusQuery(undefined, {+ skip: !enabled,+ });++ // Requiring 2FA invalidates every session lacking a second factor, this admin's included, so+ // they have to enrol before they can turn it on. Assume not enrolled until the status loads.+ const canRequire = hasFeature && mfaStatus?.enrolled === true;++ const hasNoPasswordLogin =+ isPasswordLoginEnabled === false && isLdapEnabled === false;if (!hasFeature && !enabled) {return null;}- const handleChange = (checked: boolean) => {+ const handleEnable = (value: boolean) => {+ updateSettings({+ "mfa-enforcement": value ? "optional" : "off",+ "mfa-requirement-deadline": null,+ });+ };++ const applyEnforcement = (value: EnforcementOption) => {+ if (value === "optional") {+ updateSettings({+ "mfa-enforcement": "optional",+ "mfa-requirement-deadline": null,+ });+ } else if (value === "required-date") {+ updateSettings({+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": getDefaultDeadline(),+ });+ } else if (value === "required") {+ updateSettings({+ "mfa-enforcement": "required",+ "mfa-requirement-deadline": null,+ });+ }+ };++ const handleRequire = (value: EnforcementOption) => {+ if (value === "required") {+ setIsConfirmingRequireNow(true);+ } else {+ applyEnforcement(value);+ }+ };++ const handleConfirmRequireNow = () => {+ applyEnforcement("required");+ setIsConfirmingRequireNow(false);+ };++ const getEnforcementValue = (): EnforcementOption => {+ if (enforcement === "optional") {+ return "optional";+ }+ if (enforcement === "required" && deadline !== null) {+ return "required-date";+ }+ return "required";+ };++ const handleDeadlineChange = (date: string | null) => {updateSetting({- key: "mfa-enforcement",- value: checked ? "optional" : "off",+ key: "mfa-requirement-deadline",+ value: toDeadlineSetting(date),});};+ const showEnforcementOptions =+ enforcement === "required" || enforcement === "optional";++ const isSwitchDisabled = enforcement === "off" && hasNoPasswordLogin;+ const isEnforcementDisabled = hasNoPasswordLogin;+return (<SettingsSectiondata-testid="mfa-setting"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"- />+ <Tooltip+ disabled={!isSwitchDisabled}+ label={t`Enable password or LDAP authentication to enable two-factor authentication`}+ >+ <Switch+ label={t`Allow two-factor authentication`}+ checked={enforcement !== "off"}+ onChange={(event) => handleEnable(event.currentTarget.checked)}+ disabled={isSwitchDisabled}+ w="fit-content"+ />+ </Tooltip>+ {showEnforcementOptions && (+ <Box>+ <Tooltip+ disabled={!isEnforcementDisabled}+ label={t`Enable password or LDAP authentication to adjust two-factor authentication enforcement`}+ >+ <Radio.Group+ label={t`Require two-factor authentication`}+ labelProps={{ fw: "bold", mb: "sm" }}+ value={getEnforcementValue()}+ onChange={(value) =>+ isEnforcementOption(value) && handleRequire(value)+ }+ // this disabled value will override the per option disabled values+ disabled={isEnforcementDisabled || undefined}+ w="fit-content"+ >+ <Stack gap="sm">+ {getEnforcementOptions().map(({ label, value }) => (+ <Radio+ key={value}+ value={value}+ label={label}+ disabled={value === "optional" ? !hasFeature : !canRequire}+ />+ ))}+ </Stack>+ </Radio.Group>+ </Tooltip>+ {hasFeature && !canRequire && !hasNoPasswordLogin && (+ <Text size="sm" c="text-secondary" mt="sm">+ {jt`${(+ <Anchor+ key="enroll"+ component={Link}+ to={ACCOUNT_AUTHENTICATION_PATH}+ >{t`Set up two-factor authentication`}</Anchor>+ )} for your own account before requiring it, so you don't log yourself out.`}+ </Text>+ )}+ </Box>+ )}+ {enforcement === "required" && deadline !== null && (+ <DateInput+ id="mfa-requirement-deadline"+ label={t`Enrollment deadline`}+ description={t`Users must enroll before this date`}+ value={toDeadlineInput(deadline)}+ onChange={handleDeadlineChange}+ minDate={dayjs().add(1, "day").format(DEADLINE_INPUT_FORMAT)}+ disabled={!hasFeature}+ maw="20rem"+ data-1p-ignore // 1Password will try to fill this in for some reason+ />+ )}{enabled && overview && !overview.encryption_key_set && (<Alert size="compact" color="warning">{t`Make sure to set the MB_ENCRYPTION_SECRET_KEY environment variable to encrypt authenticator secrets.`}</Alert>)}{enabled && overview && <EnrollmentCounts overview={overview} />}+ <ConfirmModal+ opened={isConfirmingRequireNow}+ title={t`Require 2FA right now?`}+ message={t`This will require everyone — including you — to log back in now if they haven't logged in with 2FA before. Users who haven't set up 2FA yet can do that from the log in screen.`}+ confirmButtonText={t`Require now`}+ confirmButtonProps={{ color: "brand" }}+ onConfirm={handleConfirmRequireNow}+ onClose={() => setIsConfirmingRequireNow(false)}+ /></SettingsSection>);}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.tsxindex f732b71cb33..a62ea874392 100644--- 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.tsx@@ -1,14 +1,22 @@+import userEvent from "@testing-library/user-event";+import {+ findRequests,setupMfaAdminOverviewEndpoint,+ setupMfaStatusEndpoint,setupPropertiesEndpoints,setupSettingsEndpoints,+ setupUpdateSettingEndpoint,+ setupUpdateSettingsEndpoint,} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";-import { renderWithProviders, screen } from "__support__/ui";-import type { MfaAdminOverview } from "metabase-types/api";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { dayjs } from "metabase/dayjs";+import type { MfaAdminOverview, MfaEnforcement } from "metabase-types/api";import {createMockMfaAdminOverview,+ createMockMfaStatus,createMockSettingDefinition,createMockSettings,createMockTokenFeatures,@@ -17,22 +25,34 @@ import {import { AdminAuthCard } from "./AdminAuthCard";+const DEADLINE_LABEL = "Enrollment deadline";+type SetupOpts = {- mfaEnabled?: boolean;+ enforcement?: MfaEnforcement;+ deadline?: string | null;hasFeature?: boolean;overview?: MfaAdminOverview;isAdmin?: boolean;+ isEnrolled?: boolean;+ isPasswordLoginEnabled?: boolean;+ isLdapEnabled?: boolean;};function setup({- mfaEnabled = true,+ enforcement = "optional",+ deadline = null,hasFeature = true,overview = createMockMfaAdminOverview(),isAdmin = false,+ isEnrolled = true,+ isPasswordLoginEnabled = true,+ isLdapEnabled = false,}: SetupOpts = {}) {- const enforcement = mfaEnabled ? ("optional" as const) : ("off" as const);const settings = createMockSettings({"mfa-enforcement": enforcement,+ "mfa-requirement-deadline": deadline,+ "enable-password-login": isPasswordLoginEnabled,+ "ldap-enabled": isLdapEnabled,"token-features": createMockTokenFeatures({"multi-factor-auth": hasFeature,}),@@ -41,8 +61,20 @@ function setup({setupPropertiesEndpoints(settings);setupSettingsEndpoints([createMockSettingDefinition({ key: "mfa-enforcement", value: enforcement }),+ createMockSettingDefinition({+ key: "mfa-requirement-deadline",+ value: deadline,+ }),+ createMockSettingDefinition({+ key: "enable-password-login",+ value: isPasswordLoginEnabled,+ }),+ createMockSettingDefinition({ key: "ldap-enabled", value: isLdapEnabled }),]);+ setupUpdateSettingEndpoint();+ setupUpdateSettingsEndpoint();setupMfaAdminOverviewEndpoint(overview);+ setupMfaStatusEndpoint(createMockMfaStatus({ enrolled: isEnrolled }));renderWithProviders(<AdminAuthCard />, {withRouter: true,@@ -53,6 +85,35 @@ function setup({});}+/** The combined write, which goes to `/api/setting` with no key in the path. */+async function findBulkSettingUpdate() {+ const puts = await findRequests("PUT");+ const put = puts.find(({ url }: { url: string }) =>+ url.endsWith("/api/setting"),+ );++ expect(put).toBeDefined();+ return put;+}++const ALLOW_LABEL = "Allow two-factor authentication";+const ENFORCEMENT_LABEL = "Require two-factor authentication";+const NO_PASSWORD_LOGIN_HINT =+ "Enable password or LDAP authentication to enable two-factor authentication";++async function selectEnforcement(label: string) {+ const option = await screen.findByLabelText(label);++ await waitFor(() => expect(option).toBeEnabled());+ await userEvent.click(option);+}++async function confirmRequireNow() {+ await userEvent.click(+ await screen.findByRole("button", { name: "Require now" }),+ );+}+describe("AdminAuthCard", () => {it("should show the enrollment counts when the setting is enabled", async () => {setup({@@ -93,6 +154,57 @@ describe("AdminAuthCard", () => {expect(screen.queryByRole("link")).not.toBeInTheDocument();});+ describe("password authentication", () => {+ const NO_PASSWORD_LOGIN = {+ isPasswordLoginEnabled: false,+ isLdapEnabled: false,+ };++ it("should not let 2FA be turned on when password login and LDAP are both off", async () => {+ setup({ ...NO_PASSWORD_LOGIN, enforcement: "off" });++ const enableSwitch = await screen.findByLabelText(ALLOW_LABEL);++ expect(enableSwitch).toBeDisabled();++ await userEvent.hover(enableSwitch);++ expect(+ await screen.findByRole("tooltip", { name: NO_PASSWORD_LOGIN_HINT }),+ ).toBeInTheDocument();+ });++ it("should still let an admin turn 2FA off once it is on", async () => {+ setup({ ...NO_PASSWORD_LOGIN, enforcement: "optional" });++ const enableSwitch = await screen.findByLabelText(ALLOW_LABEL);+ expect(await screen.findByLabelText("Don't require")).toBeDisabled();+ expect(screen.getByLabelText("Require now")).toBeDisabled();+ expect(screen.getByLabelText("Require by a certain date")).toBeDisabled();++ expect(enableSwitch).toBeEnabled();++ await userEvent.click(enableSwitch);++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("off");+ });+ });++ it("should keep the switch live when password login is off but LDAP is on", async () => {+ setup({ isPasswordLoginEnabled: false, isLdapEnabled: true });++ expect(await screen.findByLabelText(ALLOW_LABEL)).toBeEnabled();+ });++ it("should keep the switch live when password login is on", async () => {+ setup({ isPasswordLoginEnabled: true, isLdapEnabled: false });++ expect(await screen.findByLabelText(ALLOW_LABEL)).toBeEnabled();+ });+ });+it("should warn when the encryption key is not set", async () => {setup({overview: createMockMfaAdminOverview({ encryption_key_set: false }),@@ -102,4 +214,212 @@ describe("AdminAuthCard", () => {await screen.findByText(/MB_ENCRYPTION_SECRET_KEY/),).toBeInTheDocument();});++ describe("allowing two-factor authentication", () => {+ it("should turn it on as optional", async () => {+ setup({ enforcement: "off" });++ const enableSwitch = await screen.findByLabelText(ALLOW_LABEL);++ expect(enableSwitch).toBeInTheDocument();+ expect(screen.queryByRole("radiogroup")).not.toBeInTheDocument();++ await userEvent.click(enableSwitch);++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("optional");+ expect(put?.body["mfa-requirement-deadline"]).toBeNull();+ });+ });++ it("should turn it off and clear the deadline", async () => {+ const chosen = dayjs().add(30, "day").startOf("day").toISOString();++ setup({ enforcement: "required", deadline: chosen });++ expect(+ await screen.findByRole("radiogroup", { name: ENFORCEMENT_LABEL }),+ ).toBeInTheDocument();++ await userEvent.click(await screen.findByLabelText(ALLOW_LABEL));++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("off");+ expect(put?.body["mfa-requirement-deadline"]).toBeNull();+ });+ });+ });++ describe("default grace period", () => {+ it("should seed a two-week deadline when enforcement becomes required", async () => {+ setup({ enforcement: "optional", deadline: null });++ await selectEnforcement("Require by a certain date");++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("required");+ expect(+ dayjs(put?.body["mfa-requirement-deadline"]).format("YYYY-MM-DD"),+ ).toBe(dayjs().add(14, "day").format("YYYY-MM-DD"));+ });+ });++ it("should clear a stored deadline when enforcement is immediate", async () => {+ const chosen = dayjs().add(90, "day").startOf("day").toISOString();++ setup({ enforcement: "required", deadline: chosen });++ await selectEnforcement("Require now");+ await confirmRequireNow();++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("required");+ expect(put?.body["mfa-requirement-deadline"]).toBeNull();+ });+ });++ // An optional instance must not carry a deadline, or it would take effect the moment+ // enforcement came back on.+ it("should clear the deadline when enforcement goes back to optional", async () => {+ const chosen = dayjs().add(30, "day").startOf("day").toISOString();++ setup({ enforcement: "required", deadline: chosen });++ await selectEnforcement("Don't require");++ await waitFor(async () => {+ const put = await findBulkSettingUpdate();+ expect(put?.body["mfa-enforcement"]).toBe("optional");+ expect(put?.body["mfa-requirement-deadline"]).toBeNull();+ });+ });+ });++ describe("requiring immediately", () => {+ const CONFIRMATION_MODAL_TEXT = /This will require everyone/;+ it("should warn that signed-in users will be signed out", async () => {+ setup({ enforcement: "optional" });++ await selectEnforcement("Require now");++ expect(+ await screen.findByText(CONFIRMATION_MODAL_TEXT),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ /log back in now if they haven't logged in with 2FA before/,+ ),+ ).toBeInTheDocument();++ expect(await findRequests("PUT")).toHaveLength(0);++ await confirmRequireNow();++ expect(await findRequests("PUT")).toHaveLength(1);+ });++ it("should leave enforcement alone when the warning is dismissed", async () => {+ setup({ enforcement: "optional" });++ await selectEnforcement("Require now");+ expect(+ await screen.findByText(CONFIRMATION_MODAL_TEXT),+ ).toBeInTheDocument();++ await userEvent.click(+ await screen.findByRole("button", { name: "Cancel" }),+ );++ await waitFor(() => {+ expect(+ screen.queryByText(CONFIRMATION_MODAL_TEXT),+ ).not.toBeInTheDocument();+ });+ expect(await findRequests("PUT")).toHaveLength(0);+ expect(screen.getByLabelText("Don't require")).toBeChecked();+ });++ it("should not warn when a deadline is set instead", async () => {+ setup({ enforcement: "optional" });++ await selectEnforcement("Require by a certain date");++ await waitFor(async () => {+ await findBulkSettingUpdate();+ });+ expect(+ screen.queryByText(CONFIRMATION_MODAL_TEXT),+ ).not.toBeInTheDocument();+ });+ });++ describe("enrollment deadline", () => {+ it("should be hidden unless enforcement is required", () => {+ setup({ enforcement: "optional" });++ expect(screen.queryByLabelText(DEADLINE_LABEL)).not.toBeInTheDocument();+ });++ it("should show the stored deadline as a local date", () => {+ const stored = dayjs("2099-01-01").startOf("day").toISOString();++ setup({ enforcement: "required", deadline: stored });++ expect(screen.getByLabelText(DEADLINE_LABEL)).toHaveValue(+ "January 1, 2099",+ );+ });+ });++ describe("admin has not enrolled", () => {+ it("should only allow enforcement to stay optional", async () => {+ setup({ enforcement: "optional", isEnrolled: false });++ await screen.findByRole("link", {+ name: "Set up two-factor authentication",+ });++ expect(screen.getByLabelText("Don't require")).toBeEnabled();+ expect(screen.getByLabelText("Require now")).toBeDisabled();+ expect(screen.getByLabelText("Require by a certain date")).toBeDisabled();++ expect(+ await screen.findByRole("link", {+ name: "Set up two-factor authentication",+ }),+ ).toHaveAttribute("href", "/account/authentication");+ });++ it("should allow requiring once they have enrolled", async () => {+ setup({ enforcement: "optional", isEnrolled: true });++ await waitFor(() => {+ expect(screen.getByLabelText("Require now")).toBeEnabled();+ });+ expect(screen.getByLabelText("Require by a certain date")).toBeEnabled();+ expect(+ screen.queryByRole("link", {+ name: "Set up two-factor authentication",+ }),+ ).not.toBeInTheDocument();+ });+ });++ describe("lapsed license", () => {+ it("should let an admin turn 2FA off but not change enforcement", async () => {+ setup({ hasFeature: false, enforcement: "required" });++ expect(+ await screen.findByLabelText("Allow two-factor authentication"),+ ).toBeEnabled();++ expect(screen.getByLabelText("Don't require")).toBeDisabled();+ expect(screen.getByLabelText("Require now")).toBeDisabled();+ expect(screen.getByLabelText("Require by a certain date")).toBeDisabled();+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.tsxnew file mode 100644index 00000000000..bfea395c56f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.tsx@@ -0,0 +1,145 @@+import { useState } from "react";+import { jt, 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 { AuthEnrollmentFormProps } 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 { useEnrollMfaOnLoginMutation } from "metabase-enterprise/api";++import { TOTP_CODE_LENGTH } from "../../constants";+import { withTotpCodeRules } from "../../schemas";+import { RecoveryCodesForm } from "../common/RecoveryCodesForm";+import { TotpEnrollInstructions } from "../common/TotpEnrollInstructions";++const ENROLL_SCHEMA = Yup.object({+ code: withTotpCodeRules(Yup.string().required(Errors.required)),+});++type EnrollValues = { code: string };++const INITIAL_VALUES: EnrollValues = { code: "" };++export function AuthEnrollmentForm({+ enrollmentToken,+ secret,+ otpauthUri,+ remember,+ onCancel,+}: AuthEnrollmentFormProps) {+ const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);++ return (+ <Stack mt="2.5rem" gap="md">+ {recoveryCodes ? (+ <RecoveryCodesStep recoveryCodes={recoveryCodes} />+ ) : (+ <EnrollStep+ enrollmentToken={enrollmentToken}+ secret={secret}+ otpauthUri={otpauthUri}+ remember={remember}+ onEnrolled={setRecoveryCodes}+ onCancel={onCancel}+ />+ )}+ </Stack>+ );+}++type EnrollStepProps = Omit<AuthEnrollmentFormProps, "onCancel"> & {+ onEnrolled: (recoveryCodes: string[]) => void;+ onCancel: () => void;+};++function EnrollStep({+ enrollmentToken,+ secret,+ otpauthUri,+ remember,+ onEnrolled,+ onCancel,+}: EnrollStepProps) {+ const [enrollMfaOnLogin] = useEnrollMfaOnLoginMutation();++ const handleSubmit = async ({ code }: EnrollValues) => {+ const { recovery_codes } = await enrollMfaOnLogin({+ enrollment_token: enrollmentToken,+ code: code.trim(),+ remember,+ }).unwrap();++ onEnrolled(recovery_codes);+ };++ return (+ <FormProvider+ initialValues={INITIAL_VALUES}+ validationSchema={ENROLL_SCHEMA}+ onSubmit={handleSubmit}+ >+ {({ isSubmitting }) => (+ <Form>+ <Stack gap="md">+ <Text c="text-secondary" ta="center">+ {t`Two-factor authentication is required. Finish setting it up to sign in.`}+ </Text>+ <TotpEnrollInstructions otpauthUri={otpauthUri} secret={secret} />+ <FormTextInput+ name="code"+ label={t`Enter the 6-digit code from the authenticator app`}+ placeholder="123456"+ maxLength={TOTP_CODE_LENGTH}+ inputMode="numeric"+ autoFocus+ />+ <FormSubmitButton+ label={t`Set up authentication`}+ variant="filled"+ w="100%"+ />+ <FormErrorMessage ta="center" />+ <Box ta="center">+ <AuthTextButton disabled={isSubmitting} onClick={onCancel}>+ {t`Back to log in`}+ </AuthTextButton>+ </Box>+ </Stack>+ </Form>+ )}+ </FormProvider>+ );+}++type RecoveryCodesStepProps = {+ recoveryCodes: string[];+};++function RecoveryCodesStep({ recoveryCodes }: RecoveryCodesStepProps) {+ const dispatch = useDispatch();++ 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={() => dispatch(completeLogin())}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.unit.spec.tsxnew file mode 100644index 00000000000..1f8f4c29554--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.unit.spec.tsx@@ -0,0 +1,128 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupCurrentUserEndpoint,+ setupMfaEnrollOnLoginEndpoint,+ setupMfaEnrollOnLoginEndpointError,+ setupPropertiesEndpoints,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { createMockSettings, createMockUser } from "metabase-types/api/mocks";++import { AuthEnrollmentForm } from "./AuthEnrollmentForm";++const RECOVERY_CODES = ["aaaaa-11111", "bbbbb-22222"];++type SetupOpts = {+ hasEnrollError?: boolean;+};++function setup({ hasEnrollError = false }: SetupOpts = {}) {+ if (hasEnrollError) {+ setupMfaEnrollOnLoginEndpointError();+ } else {+ setupMfaEnrollOnLoginEndpoint(RECOVERY_CODES);+ }+ setupCurrentUserEndpoint(createMockUser());+ setupPropertiesEndpoints(createMockSettings());++ const onCancel = jest.fn();++ renderWithProviders(+ <AuthEnrollmentForm+ enrollmentToken="enrollment-token"+ secret="TOTPSECRET"+ otpauthUri="otpauth://totp/Metabase:[email protected]?secret=TOTPSECRET"+ onCancel={onCancel}+ />,+ );++ return { onCancel };+}++async function submitCode() {+ await userEvent.type(+ screen.getByLabelText("Enter the 6-digit code from the authenticator app"),+ "123456",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Set up authentication" }),+ );+}++const loginRequests = () =>+ fetchMock.callHistory.calls("path:/api/user/current");++describe("AuthEnrollmentForm", () => {+ it("should show the QR code and the manual secret", () => {+ setup();++ expect(screen.getByText("TOTPSECRET")).toBeInTheDocument();+ expect(+ screen.getByText("Scan this QR code with an authenticator app:"),+ ).toBeInTheDocument();+ });++ it("should enroll the second factor and then show the recovery codes", async () => {+ setup();++ await submitCode();++ expect(await screen.findByText(RECOVERY_CODES[0])).toBeInTheDocument();+ expect(screen.getByText(RECOVERY_CODES[1])).toBeInTheDocument();+ expect(+ fetchMock.callHistory.calls("path:/api/session/mfa/enroll"),+ ).toHaveLength(1);+ });++ it("should not complete the login until the recovery codes are acknowledged", async () => {+ setup();++ await submitCode();+ await screen.findByText(RECOVERY_CODES[0]);++ expect(loginRequests()).toHaveLength(0);++ await userEvent.click(screen.getByRole("button", { name: "Done" }));++ await waitFor(() => {+ expect(loginRequests().length).toBeGreaterThan(0);+ });+ });++ it("should not offer a way back to log in once enrolled", async () => {+ setup();++ expect(+ screen.getByRole("button", { name: "Back to log in" }),+ ).toBeInTheDocument();++ await submitCode();+ await screen.findByText(RECOVERY_CODES[0]);++ expect(+ screen.queryByRole("button", { name: "Back to log in" }),+ ).not.toBeInTheDocument();+ });++ it("should keep the user on the form when the code is rejected", async () => {+ setup({ hasEnrollError: true });++ await submitCode();++ expect(await screen.findByText("An error occurred")).toBeInTheDocument();+ expect(screen.queryByText(RECOVERY_CODES[0])).not.toBeInTheDocument();+ expect(loginRequests()).toHaveLength(0);+ });++ it("should cancel back to the login form", async () => {+ const { onCancel } = setup();++ await userEvent.click(+ screen.getByRole("button", { name: "Back to log in" }),+ );++ expect(onCancel).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/index.tsnew file mode 100644index 00000000000..fc85cf8bb9f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/index.ts@@ -0,0 +1 @@+export { AuthEnrollmentForm } from "./AuthEnrollmentForm";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/common/CopyableCodeBlock/CopyableCodeBlock.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/CopyableCodeBlock.tsxrename to enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/CopyableCodeBlock/CopyableCodeBlock.tsxdiff --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/common/CopyableCodeBlock/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/CopyableCodeBlock/index.tsrename to enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/CopyableCodeBlock/index.tsdiff --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/common/RecoveryCodesForm/RecoveryCodesForm.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.tsxrename to enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/RecoveryCodesForm/RecoveryCodesForm.tsxdiff --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/common/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsxrename to enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/RecoveryCodesForm/RecoveryCodesForm.unit.spec.tsxdiff --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/common/RecoveryCodesForm/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/RecoveryCodesForm/index.tsrename to enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/RecoveryCodesForm/index.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/TotpEnrollInstructions.tsx b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/TotpEnrollInstructions.tsxnew file mode 100644index 00000000000..0187144d852--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/TotpEnrollInstructions.tsx@@ -0,0 +1,35 @@+import QRCode from "react-qr-code";+import { t } from "ttag";++import { Box, Center, Stack } from "metabase/ui";++import { CopyableCodeBlock } from "../CopyableCodeBlock";++const QR_CODE_SIZE = 180;++type TotpEnrollInstructionsProps = {+ otpauthUri: string;+ secret: string;+};++export function TotpEnrollInstructions({+ otpauthUri,+ secret,+}: TotpEnrollInstructionsProps) {+ return (+ <>+ <Stack gap="sm">+ <Box>{t`Scan this QR code with an authenticator app:`}</Box>+ <Center>+ <Box bg="white" p="lg">+ <QRCode value={otpauthUri} size={QR_CODE_SIZE} />+ </Box>+ </Center>+ </Stack>+ <Stack gap="sm">+ <Box>{t`Or enter this key in the app manually:`}</Box>+ <CopyableCodeBlock codes={[secret]} />+ </Stack>+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/index.tsnew file mode 100644index 00000000000..94d02c54f86--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/TotpEnrollInstructions/index.ts@@ -0,0 +1 @@+export { TotpEnrollInstructions } from "./TotpEnrollInstructions";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/index.tsnew file mode 100644index 00000000000..794a510f269--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/common/index.ts@@ -0,0 +1,3 @@+export { CopyableCodeBlock } from "./CopyableCodeBlock";+export { RecoveryCodesForm } from "./RecoveryCodesForm";+export { TotpEnrollInstructions } from "./TotpEnrollInstructions";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.tsindex bfd5d6ee903..572052f3e83 100644--- a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/constants.ts@@ -4,3 +4,5 @@ export const RECOVERY_CODE_LENGTH = 11;export const AUTHENTICATION_PATH = "/admin/settings/authentication";export const ENROLLED_USERS_PATH = `${AUTHENTICATION_PATH}/2fa/enrolled`;export const UNENROLLED_USERS_PATH = `${AUTHENTICATION_PATH}/2fa/unenrolled`;++export const ACCOUNT_AUTHENTICATION_PATH = "/account/authentication";diff --git a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.ts b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.tsindex 6825a97eeed..0cfb0bedbd5 100644--- a/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/multi_factor_auth/index.ts@@ -3,6 +3,7 @@ import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";import { AccountSecurityPanel } from "./components/AccountSecurityPanel";import { AdminAuthCard } from "./components/AdminAuthCard";import { AuthChallengeForm } from "./components/AuthChallengeForm";+import { AuthEnrollmentForm } from "./components/AuthEnrollmentForm";const enrolledUsersPage = () =>import(@@ -18,6 +19,7 @@ const unenrolledUsersPage = () =>export function initializePlugin() {PLUGIN_MULTI_FACTOR_AUTH.AuthChallengeForm = AuthChallengeForm;+ PLUGIN_MULTI_FACTOR_AUTH.AuthEnrollmentForm = AuthEnrollmentForm;PLUGIN_MULTI_FACTOR_AUTH.AccountSecurityPanel = AccountSecurityPanel;PLUGIN_MULTI_FACTOR_AUTH.AdminAuthCard = AdminAuthCard;PLUGIN_MULTI_FACTOR_AUTH.enrolledUsersPage = enrolledUsersPage;diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonindex 6c1a23abf18..c9d42a31703 100644--- a/frontend/lint/side-effect-files.json+++ b/frontend/lint/side-effect-files.json@@ -60,6 +60,7 @@"enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/ConfirmCodeForm/ConfirmCodeForm.tsx": "self","enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AccountSecurityPanel/SetupModal/SetupModal.tsx": "self","enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthChallengeForm/AuthChallengeForm.tsx": "self",+ "enterprise/frontend/src/metabase-enterprise/multi_factor_auth/components/AuthEnrollmentForm/AuthEnrollmentForm.tsx": "self","enterprise/frontend/src/metabase-enterprise/overrides.ts": "entry","enterprise/frontend/src/metabase-enterprise/plugins.ts": "entry","enterprise/frontend/src/metabase-enterprise/redux.ts": "self",diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 8b8c78683ab..9bcf0773082 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -447,5 +447,6 @@ export const createMockSettings = ("mcp-apps-cors-custom-origins": "","transforms-meter-locked": null,"mfa-enforcement": "off",+ "mfa-requirement-deadline": null,...opts,});diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 1d2c4142ee4..1fbf56bce7b 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -391,6 +391,8 @@ export type PasswordComplexity = {export type SessionCookieSameSite = "lax" | "strict" | "none";+export type MfaEnforcement = "off" | "optional" | "required";+export interface SettingDefinition<Key extends EnterpriseSettingKey = EnterpriseSettingKey,> {@@ -588,7 +590,8 @@ interface PublicSettings {"llm-metabot-supports-reasoning?"?: boolean | null;"email-configured?": boolean;"embedding-app-origin": string | null;- "mfa-enforcement"?: "off" | "optional";+ "mfa-enforcement": MfaEnforcement;+ "mfa-requirement-deadline": string | null;"embedding-app-origins-sdk": string | null;"embedding-app-origins-interactive": string | null;"enable-password-login": boolean;diff --git a/frontend/src/metabase/api/session.ts b/frontend/src/metabase/api/session.tsindex 7a2ebca0b68..5ed5c87351b 100644--- a/frontend/src/metabase/api/session.ts+++ b/frontend/src/metabase/api/session.ts@@ -1,5 +1,6 @@import type {LoginData,+ MfaEnrollResponse,MfaMethod,PasswordResetTokenStatus,} from "metabase-types/api";@@ -16,13 +17,27 @@ export interface MfaChallengeResponse {challenge_token: string;}-export type CreateSessionResponse = SessionResponse | MfaChallengeResponse;+export interface MfaEnrollmentResponse extends MfaEnrollResponse {+ mfa_enrollment: true;+ methods: MfaMethod[];+ enrollment_token: string;+}++export type CreateSessionResponse =+ | SessionResponse+ | MfaChallengeResponse+ | MfaEnrollmentResponse;export const isMfaChallenge = (response: CreateSessionResponse,): response is MfaChallengeResponse =>"mfa_required" in response && response.mfa_required === true;+export const isMfaEnrollment = (+ response: CreateSessionResponse,+): response is MfaEnrollmentResponse =>+ "mfa_enrollment" in response && response.mfa_enrollment === true;+export interface GoogleAuthData {token: string;remember?: boolean;diff --git a/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx b/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsxindex 20017ccd448..788ad7a1ae2 100644--- a/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx+++ b/frontend/src/metabase/auth/components/PasswordPanel/PasswordPanel.tsx@@ -1,7 +1,10 @@import { useCallback, useState } from "react";import { t } from "ttag";-import type { MfaChallengeResponse } from "metabase/api/session";+import type {+ MfaChallengeResponse,+ MfaEnrollmentResponse,+} from "metabase/api/session";import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";import { login } from "metabase/redux/auth";@@ -27,16 +30,21 @@ export const PasswordPanel = ({ redirectUrl }: PasswordPanelProps) => {const [mfaChallenge, setMfaChallenge] = useState<MfaChallengeResponse | null>(null,);+ const [mfaEnrollment, setMfaEnrollment] =+ useState<MfaEnrollmentResponse | null>(null);const [remember, setRemember] = useState(false);const handleSubmit = useCallback(async (data: LoginData) => {- const { mfaChallenge: challenge } = await dispatch(- login({ data, redirectUrl }),- ).unwrap();+ const { mfaChallenge: challenge, mfaEnrollment: enrollment } =+ await dispatch(login({ data, redirectUrl })).unwrap();+if (challenge) {setRemember(Boolean(data.remember));setMfaChallenge(challenge);+ } else if (enrollment) {+ setRemember(Boolean(data.remember));+ setMfaEnrollment(enrollment);}},[dispatch, redirectUrl],@@ -53,6 +61,18 @@ export const PasswordPanel = ({ redirectUrl }: PasswordPanelProps) => {);}+ if (mfaEnrollment) {+ return (+ <PLUGIN_MULTI_FACTOR_AUTH.AuthEnrollmentForm+ enrollmentToken={mfaEnrollment.enrollment_token}+ secret={mfaEnrollment.secret}+ otpauthUri={mfaEnrollment.otpauth_uri}+ remember={remember}+ onCancel={() => setMfaEnrollment(null)}+ />+ );+ }+return (<div><LoginFormdiff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex a58691bd60d..9db9dd018cd 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -102,6 +102,7 @@ export { PLUGIN_MODEL_PERSISTENCE } from "./oss/model-persistence";export {PLUGIN_MULTI_FACTOR_AUTH,type AuthChallengeFormProps,+ type AuthEnrollmentFormProps,} from "./oss/multi-factor-auth";export {PLUGIN_MODERATION,diff --git a/frontend/src/metabase/plugins/oss/multi-factor-auth.ts b/frontend/src/metabase/plugins/oss/multi-factor-auth.tsindex 680ba136ea2..fd451e01b62 100644--- a/frontend/src/metabase/plugins/oss/multi-factor-auth.ts+++ b/frontend/src/metabase/plugins/oss/multi-factor-auth.ts@@ -13,8 +13,17 @@ export type AuthChallengeFormProps = {onCancel: () => void;};+export type AuthEnrollmentFormProps = {+ enrollmentToken: string;+ secret: string;+ otpauthUri: string;+ remember?: boolean;+ onCancel: () => void;+};+const getDefaultPluginMultiFactorAuth = () => ({AuthChallengeForm: PluginPlaceholder<AuthChallengeFormProps>,+ AuthEnrollmentForm: PluginPlaceholder<AuthEnrollmentFormProps>,AccountSecurityPanel: PluginPlaceholder,AdminAuthCard: PluginPlaceholder,enrolledUsersPage: pluginPlaceholderRoute,diff --git a/frontend/src/metabase/redux/auth.ts b/frontend/src/metabase/redux/auth.tsindex 436c6aab37f..c57930ef14b 100644--- a/frontend/src/metabase/redux/auth.ts+++ b/frontend/src/metabase/redux/auth.ts@@ -8,7 +8,9 @@ import { Api } from "metabase/api";import { loadLocalization } from "metabase/api/localization";import {type MfaChallengeResponse,+ type MfaEnrollmentResponse,isMfaChallenge,+ isMfaEnrollment,sessionApi,} from "metabase/api/session";import { getUser, refetchCurrentUser } from "metabase/current-user";@@ -70,6 +72,7 @@ interface LoginPayload {export interface LoginResult {mfaChallenge?: MfaChallengeResponse;+ mfaEnrollment?: MfaEnrollmentResponse;}export const LOGIN = "metabase/auth/LOGIN";@@ -86,6 +89,11 @@ export const login = createAsyncThunk(return challenge;}+ if (isMfaEnrollment(result)) {+ const enrollment: LoginResult = { mfaEnrollment: result };+ return enrollment;+ }+await dispatch(completeLogin()).unwrap();const success: LoginResult = {};return success;diff --git a/frontend/test/__support__/server-mocks/multi-factor-auth.ts b/frontend/test/__support__/server-mocks/multi-factor-auth.tsindex 7f8829efcbb..99974ef66df 100644--- a/frontend/test/__support__/server-mocks/multi-factor-auth.ts+++ b/frontend/test/__support__/server-mocks/multi-factor-auth.ts@@ -91,6 +91,17 @@ export function setupMfaVerifyEndpointError() {fetchMock.post("path:/api/session/mfa/verify", 500);}+export function setupMfaEnrollOnLoginEndpoint(recoveryCodes: string[]) {+ fetchMock.post("path:/api/session/mfa/enroll", {+ id: "session-id",+ recovery_codes: recoveryCodes,+ });+}++export function setupMfaEnrollOnLoginEndpointError() {+ fetchMock.post("path:/api/session/mfa/enroll", 401);+}+export function setupMfaSendEmailOtpEndpoint() {fetchMock.post("path:/api/session/mfa/send-email-otp", { success: true });}diff --git a/resources/migrations/064/20260805_track_mfa_in_sessions.yaml b/resources/migrations/064/20260805_track_mfa_in_sessions.yamlnew file mode 100644index 00000000000..36a3da7624c--- /dev/null+++ b/resources/migrations/064/20260805_track_mfa_in_sessions.yaml@@ -0,0 +1,22 @@+# In order for us to know whether a session is valid post MFA requirement,+# we need to be able to inspect which sessions were obtained using MFA.++databaseChangeLog:+ - changeSet:+ id: v64.2026-08-05T09:55:00+ author: Ethan McCue+ comment: Track MFA method used in session+ changes:+ - addColumn:+ tableName: core_session+ columns:+ - column:+ name: mfa_auth_identity_id+ type: int+ remarks: Foreign key to auth_identity method used for MFA+ constraints:+ nullable: true+ rollback:+ - dropColumn:+ tableName: core_session+ columnName: mfa_auth_identity_iddiff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.cljindex 10ae61f4e1a..f8060fbb8b5 100644--- a/src/metabase/audit_app/events/audit_log.clj+++ b/src/metabase/audit_app/events/audit_log.clj@@ -183,6 +183,7 @@(events/derive! :event/password-reset-initiated ::user-event)(events/derive! :event/password-reset-successful ::user-event)(events/derive! :event/mfa-verification-failed ::user-event)+(events/derive! :event/mfa-required-enrollment-failed ::user-event)(events/derive! :event/mfa-enrolled ::user-event)(events/derive! :event/mfa-disabled ::user-event)diff --git a/src/metabase/auth_identity/db.clj b/src/metabase/auth_identity/db.cljindex 92c7e4f64b1..eb87755ee93 100644--- a/src/metabase/auth_identity/db.clj+++ b/src/metabase/auth_identity/db.clj@@ -119,15 +119,17 @@(mu/defn insert-session!"Insert a Session and return the inserted instance."- [session-id :- :string- user-id :- ::lib.schema.id/user- auth-identity-id :- [:maybe ms/PositiveInt]- session-key :- :string- expires-at :- [:maybe ms/TemporalInstant]]+ [session-id :- :string+ user-id :- ::lib.schema.id/user+ auth-identity-id :- [:maybe ms/PositiveInt]+ session-key :- :string+ expires-at :- [:maybe ms/TemporalInstant]+ mfa-auth-identity-id :- [:maybe ms/PositiveInt]](t2/insert-returning-instance! :model/Session;; Without setting the ID here we can't return an instance on MySQL:id session-id:user_id user-id:auth_identity_id auth-identity-id:session_key session-key- :expires_at expires-at))+ :expires_at expires-at+ :mfa_auth_identity_id mfa-auth-identity-id))diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.cljindex 99a9786a283..551d1866985 100644--- a/src/metabase/auth_identity/provider.clj+++ b/src/metabase/auth_identity/provider.clj@@ -254,6 +254,22 @@provider):hierarchy #'auth-identity.hierarchy/hierarchy)+(mu/defn- apply-inactive-check+ "Checks if the provided `request` is an attempt to log in an active user, or an inactive one.++ If the user does not have `:is_active true`, the response is not successful and an error message is returned. A+ request that resolved no user at all is left alone: link-only flows legitimately finish without one."+ [request :- [:map+ [:user {:optional true} [:maybe [:map+ [:id ms/PositiveInt]+ [:is_active :boolean]]]]]]+ (cond-> request+ (and (nil? (:error request))+ (:user request)+ (not (get-in request [:user :is_active]))) (assoc :success? false+ :error disabled-account-snippet+ :message disabled-account-message)))+(mu/defn- create-session!"Create a new session for a user with the given provider.Updates the last_used_at timestamp on the corresponding AuthIdentity."@@ -299,9 +315,12 @@[_provider login-result]login-result)+;; TODO: (bshepherdson, 2026-09-04) Only a sharp-eyed code reviewer caught that `:mfa/enroll?` had been introduced+;; but not added to this blocklist. The consumers of [[authenticate-owned-keys]] should be switched to an allowlist+;; using `select-keys`, rather than `dissoc`ing all the bad fields.(def ^:private authenticate-owned-keys[:user-id :user_id :user :user-data :auth-identity :provider-id :success? :session- :error :message :mfa/pending? :mfa/methods :mfa/first-factor+ :error :message :mfa/enroll? :mfa/pending? :mfa/methods :mfa/first-factor:jwt-data :claims:tenant-slug :tenant-attributes :user-provisioning-enabled?])@@ -327,11 +346,14 @@;; user's tenant assignment was lost) must not leave a half-provisioned account behind (UXW-4898)(t2/with-transaction [_](next-method provider $))+ (apply-inactive-check $)(apply-mfa-gate provider $)(cond-> $- (and (true? (:success? $)) (: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])))+ (and (true? (:success? $))+ (: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/enroll? :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/auth_identity/providers/password.clj b/src/metabase/auth_identity/providers/password.cljindex 0b2df38a4c7..d61e1c26db3 100644--- a/src/metabase/auth_identity/providers/password.clj+++ b/src/metabase/auth_identity/providers/password.clj@@ -16,6 +16,7 @@;; Register password provider in the hierarchy(auth-identity.hierarchy/derive! :provider/password ::provider/provider)+(auth-identity.hierarchy/derive! :provider/password ::provider/supports-mfa);;; -------------------------------------------------- Multimethod Implementations --------------------------------------------------diff --git a/src/metabase/auth_identity/session.clj b/src/metabase/auth_identity/session.cljindex a91e08f8d2a..cfa0e98ebf3 100644--- a/src/metabase/auth_identity/session.clj+++ b/src/metabase/auth_identity/session.clj@@ -19,20 +19,23 @@The session row and its `login_history` row are written in one transaction: `login_history.session_id` has a foreignkey to `core_session`, so a concurrent session delete (e.g. a password change, which invalidates the user's sessions)must not be able to remove the freshly-created session between the two inserts and break that reference."- [user device-info provider]- (let [user-id (u/the-id user)- provider-str (name provider)- auth-identity (auth-identity.db/auth-identity-expiry user-id provider-str)- auth-identity-id (:id auth-identity)- session-key (str (random-uuid))- session-id (string/random-string 12)- session (t2/with-transaction [_]- (u/prog1 (auth-identity.db/insert-session! session-id user-id auth-identity-id session-key (:expires_at auth-identity))- (when provider-str- (log/debugf "Updating last_used_at for user %s with provider %s" user-id provider-str)- (auth-identity.db/touch-auth-identity! auth-identity-id))- (when device-info- (login-history/record-login-history! session-id user device-info))))]- (assoc session- :key session-key- :type (if (some-> (request/current-request) request/embedded?) :full-app-embed :normal))))+ ([user device-info provider mfa-auth-identity-id]+ (let [user-id (u/the-id user)+ provider-str (name provider)+ auth-identity (auth-identity.db/auth-identity-expiry user-id provider-str)+ auth-identity-id (:id auth-identity)+ session-key (str (random-uuid))+ session-id (string/random-string 12)+ session (t2/with-transaction [_]+ (u/prog1 (auth-identity.db/insert-session! session-id user-id auth-identity-id session-key+ (:expires_at auth-identity) mfa-auth-identity-id)+ (when provider-str+ (log/debugf "Updating last_used_at for user %s with provider %s" user-id provider-str)+ (auth-identity.db/touch-auth-identity! auth-identity-id))+ (when device-info+ (login-history/record-login-history! session-id user device-info))))]+ (assoc session+ :key session-key+ :type (if (some-> (request/current-request) request/embedded?) :full-app-embed :normal))))+ ([user device-info provider]+ (create-session-with-auth-tracking! user device-info provider nil)))diff --git a/src/metabase/core/init.clj b/src/metabase/core/init.cljindex a2adb8ca484..d9ca14f8cff 100644--- a/src/metabase/core/init.clj+++ b/src/metabase/core/init.clj@@ -44,6 +44,7 @@[metabase.login-history.init][metabase.mcp.init][metabase.metabot.init]+ [metabase.mfa.init][metabase.model-persistence.init][metabase.models.init][metabase.mq.init]diff --git a/src/metabase/mfa/init.clj b/src/metabase/mfa/init.cljnew file mode 100644index 00000000000..56d4f7171c2--- /dev/null+++ b/src/metabase/mfa/init.clj@@ -0,0 +1,3 @@+(ns metabase.mfa.init+ (:require+ [metabase.mfa.settings]))diff --git a/src/metabase/mfa/settings.clj b/src/metabase/mfa/settings.cljnew file mode 100644index 00000000000..3c17a17c4fc--- /dev/null+++ b/src/metabase/mfa/settings.clj@@ -0,0 +1,31 @@+(ns metabase.mfa.settings+ "OSS 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]]))++(def ^:private valid-enforcement-values #{:off :optional :required})++(defsetting mfa-enforcement+ (deferred-tru "Controls whether two-factor authentication is available to users. :off disables it entirely; :optional allows users to enroll voluntarily, :required mandates users enroll.")+ :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, :optional, and :required."+ 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))))diff --git a/src/metabase/server/db.clj b/src/metabase/server/db.cljindex f1fa7932ed4..de4305231d1 100644--- a/src/metabase/server/db.clj+++ b/src/metabase/server/db.clj@@ -25,9 +25,15 @@now]:mysql [:- now [::h2x/mysql-interval amount unit]])))-(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds])} session-with-id-query+;; Hard-coded rather than `(descendants :metabase.auth-identity.provider/supports-mfa)` so the session query below is+;; compiled once rather than depending on load order of the provider namespaces.+;; [[metabase.server.middleware.session-test/mfa-providers-list-test]] keeps this in sync with the hierarchy.+(def ^:private mfa-supported-methods+ #{:provider/password :provider/ldap})++(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds mfa-required])} session-with-id-query(mdb/memoize-for-application-db- (fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds]+ (fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds mfa-required](first(t2.pipeline/compile*(cond-> {:select [[:session.user_id :metabase-user-id]@@ -51,9 +57,19 @@[:= :session.anti_csrf_token (case session-type:normal nil:full-app-embed ^:allow-raw-sql [:raw "?"])]]- (when session-timeout-seconds- [[:> [:coalesce :session.last_active_at :session.created_at]- (oldest-allowed-expr db-type session-timeout-seconds :second)]]))+ cat+ [(when mfa-required+ [[:or+ [:not= :session.mfa_auth_identity_id nil]+ (into [:and]+ (map (fn [mfa-supporting-provider]+ [:not= :auth_identity.provider+ ^:allow-raw-sql+ [:raw (str "'" (name mfa-supporting-provider) "'")]])+ mfa-supported-methods))]])+ (when session-timeout-seconds+ [[:> [:coalesce :session.last_active_at :session.created_at]+ (oldest-allowed-expr db-type session-timeout-seconds :second)]])]):limit [:inline 1]}enable-advanced-permissions?(->@@ -122,13 +138,15 @@max-age-minutes :- [:maybe :int]enable-advanced-permissions? :- :booleanenable-tenants? :- :boolean- session-timeout-seconds :- [:maybe :int]]+ session-timeout-seconds :- [:maybe :int]+ mfa-required :- :boolean](let [sql (session-with-id-query (mdb/db-type)max-age-minutes(if (seq anti-csrf-token) :full-app-embed :normal)enable-advanced-permissions?enable-tenants?- session-timeout-seconds)+ session-timeout-seconds+ mfa-required)params (concat [session-key-hash] (when (seq anti-csrf-token) [anti-csrf-token]))](t2/query-one (cons sql params))))diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 3f0fd31997f..7e53966d486 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -112,7 +112,8 @@(premium-features/enable-advanced-permissions?)(and (premium-features/enable-tenants?)(setting/get :use-tenants))- (request/enabled-session-timeout-seconds))+ (request/enabled-session-timeout-seconds)+ (session/mfa-required?));; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false(update :is-group-manager? boolean))))diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex c5c19adad7d..88de91c452b 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -16,6 +16,7 @@[metabase.session.db :as session.db][metabase.session.models.session :as session][metabase.session.schema :as session.schema]+ [metabase.session.settings :as session.settings][metabase.settings.core :as setting][metabase.sso.core :as sso][metabase.system.core :as system]@@ -146,13 +147,38 @@(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.+ consuming it plus the challenge jti.- OSS fallback returns false — OSS can never have issued a challenge token (the MFA gate lives in+ Returns the AuthIdentity of the 2nd factor method verified, else nil.++ OSS fallback returns nil — OSS can never have issued a challenge token (the MFA gate lives inEE), so this is unreachable in practice."metabase-enterprise.mfa.core[_user-id _code _jti]- false)+ nil)++(defenterprise start-enrollment!+ "Begin enrollment of a new authenticator for a user who is not currently enrolled, and attempting to log in.+ Only called when the instance is configured to *require* MFA, but this user is not enrolled.++ Precondition: caller must validate that the correct username and password for this `user-id` have been provided.++ Returns a map intended for the `:body` of a response, containing the plaintext `:secret` and the `:otpauth_uri`+ used for the QR code. Returns nil if any conditions fail (e.g. if the user is already enrolled).++ OSS always returns nil, since new enrollments are not allowed without the `:multi-factor-auth` feature."+ metabase-enterprise.mfa.core+ [_user-id]+ nil)++(defenterprise confirm-enrollment!+ "Complete enrollment of a new authenticator for a currently pending enrollment. Requires the `user-id` and `code`,+ plus the single-use `jti` from a [[metabase.session.challenge/issue-enrollment-token]].++ OSS always returns nil, signaling that enrollment has failed."+ metabase-enterprise.mfa.core+ [_user-id _code _jti]+ nil)(defenterprise send-mfa-email-otp!"Generate + email a one-time fallback code for user-id's confirmed enrollment; rejects a jti that@@ -177,6 +203,32 @@[& body]`(do-http-401-on-error (fn [] ~@body)))+(defn- mandatory-mfa-enrollment!+ "Called by the login handler when MFA is required and the user is not enrolled.++ This process and the wire response can be seen as combo of two things:+ - Start the MFA enrollment process, creating a stub `:model/AuthIdentity` etc.+ - Response contains the plaintext `secret` and an `otpauth_uri` for the QR code, just like authenticated+ enrollment in [[metabase-enterprise.mfa.management]].+ - Include an opaque JWT `enrollment_token`, which securely identifies the bearer to later requests as the user who+ just correctly entered their password. The JWT can only be used for enrollment of a new MFA setup, and can only+ be (successfully) used once.++ These tokens and the current OTP should be turned in to `/api/session/mfa/enroll` to complete enrollment and log in."+ [{{user-id :id} :user+ :mfa/keys [methods first-factor]+ :as _login-result}]+ ;; Precondition for [[enrollment/start-enrollment!]] is met: this user just provided their username and password+ ;; to `POST /api/session` and they have been successfully validated.+ (let [enrollment-details (or (start-enrollment! user-id)+ (throw (ex-info (tru "Two-factor authentication is already set up. Disable it before re-enrolling.")+ {:status-code 400})))]+ {:status 200+ :body (assoc enrollment-details+ :mfa_enrollment true+ :methods methods+ :enrollment_token (session.challenge/issue-enrollment-token user-id first-factor))}))+;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;@@ -192,17 +244,29 @@(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.+ (cond+ ;; First factor OK, but this user does not have a second factor enrolled. However the+ ;; instance is configured to require MFA, so force this user to enroll a second factor.+ ;; Expects the user to send a POST /mfa/enroll.+ ;; No cookies are set here.+ (:mfa/enroll? result)+ (mandatory-mfa-enrollment! result)++ (:mfa/pending? result)++ ;; First factor OK, but the user has a second factor configured. Build and sign a+ ;; challenge token here (OSS session machinery) and return it instead of a session.+ ;; Expects the user to send a POST /mfa/verify.+ ;; 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))))]++ ;; Otherwise, a straightforward single factor login.+ :else (session-response result request))))](if throttling-disabled?(do-login)(http-401-on-error@@ -353,10 +417,12 @@(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)+ ;; The password change succeeded, but an MFA is required. Either the user is already enrolled with MFA or they+ ;; are unenrolled but `mfa-required?`. Issue no session, or anyone who can trigger a password reset can bypass+ ;; MFA! The user logs in normally with their new password, either providing their second factor or configuring+ ;; MFA since it's required.+ (or (session.settings/mfa-required?)+ (:mfa/pending? auth-result)){:success true}:else@@ -475,25 +541,98 @@(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 (session.db/user user-id)})- (throw (ex-info (tru "Invalid authentication code.") {:status-code 401})))))- (let [user (session.db/user-login-status 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))))+ 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.+ mfa-auth-identity (call-with-failure-throttling+ [[(verify-throttlers :ip-address) (request/ip-address request)]+ [(verify-throttlers :user-id) user-id]]+ (fn []+ (or+ (verify-second-factor! user-id code jti)+ (do+ (events/publish-event! :event/mfa-verification-failed+ {:object (session.db/user user-id)})+ (throw (ex-info (tru "Invalid authentication code.") {:status-code 401}))))))+ user (session.db/user-login-status 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 (:id mfa-auth-identity))+ request)))++;; The response here is a combo of a plain login (with two cookies and the `:id` in the body) and successful MFA+;; enrollment, which sends a seq of 10 `:recovery_codes` for display to the user.+(api.macros/defendpoint :post "/mfa/enroll" :- [:map {:closed true}+ [:status [:= 200]]+ [:cookies+ [:map-of+ [:enum "metabase.SESSION" "metabase.TIMEOUT"]+ [:map {:closed true}+ [:value ms/NonBlankString]+ [:path ms/NonBlankString]+ [:max-age :int]+ [:same-site {:optional true} [:enum :strict :lax :none]]+ [:http-only {:optional true} :boolean]]]]+ [:body+ [:map {:closed true}+ [:id ms/NonBlankString]+ [:recovery_codes [:sequential ms/NonBlankString]]]]]+ "Complete a two-step login by *enrolling* a second factor for the first time. This happens when a user without+ MFA enrolled logs in for the first time after the instance starts *requiring* MFA.++ After confirming their email and password, the user will see an MFA enrollment screen, served by `POST /session`+ after it accepts the password. That body includes a single-use, signed JWT similar to the one used by an MFA+ challenge (see `POST /mfa/verify` above) as well as the details needed to show the QR code for enrolling MFA.++ This request must include the JWT (`enrollment_token`) and the OTP itself (`code`). If enrollment succeeds, both+ the pending enrollment and the JWT's `jti` are consumed, preventing reuse of either.++ A successful response **sets the session cookie, logging the user in!** Its body contains the recovery codes+ in the same form as enrollment when already authenticated."+ [_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 a newly enrolled MFA user THIS request is the one that creates the session.+ {enrollment-token :enrollment_token+ code :code} :- [:map {:closed true}+ [:enrollment_token ms/NonBlankString]+ [:code ms/NonBlankString]+ [:remember {:optional true} :boolean]]+ request]+ (let [claims (or (session.challenge/verify-enrollment-token enrollment-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.+ {:keys [recovery-codes+ mfa-auth-identity-id]} (call-with-failure-throttling+ [[(verify-throttlers :ip-address) (request/ip-address request)]+ [(verify-throttlers :user-id) user-id]]+ (fn []+ (or+ (confirm-enrollment! user-id code jti)+ (do (events/publish-event! :event/mfa-required-enrollment-failed+ {:object (session.db/user user-id)})+ (throw (ex-info (tru "Invalid authentication code.") {:status-code 401}))))))+ user (session.db/user-login-status user-id)]+ ;; the account can be deactivated (or deleted) between the password step and here; an+ ;; enrollment 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})))+ (-> (auth-identity/create-session-with-auth-tracking! user (request/device-info request) first-factor mfa-auth-identity-id)+ (session-response request)+ (assoc-in [:body :recovery_codes] recovery-codes))))(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 butdiff --git a/src/metabase/session/challenge.clj b/src/metabase/session/challenge.cljindex 1fa71155a80..db17d3b9a6d 100644--- a/src/metabase/session/challenge.clj+++ b/src/metabase/session/challenge.clj@@ -1,7 +1,7 @@(ns metabase.session.challenge- "Short-lived signed challenge tokens bridging the two steps of an MFA login.+ "Short-lived signed challenge tokens bridging the two steps of an MFA login or enrollment.- A challenge token is NOT a session: nothing is written to the session table and no cookie is set+ A token is NOT a session: nothing is written to the session table and no cookie is setuntil the second factor passes. The token is a 5-minute HS256 JWT carrying the user, thefirst-factor provider (so session auth-tracking records it correctly), and a `jti` that isconsumed on successful verification so one token cannot mint two sessions."@@ -12,32 +12,65 @@(set! *warn-on-reflection* true)-(def ttl-seconds- "How long a challenge token stays valid. (Consumed `jti`s are retained longer — see+(def ^:private challenge-ttl-seconds+ "How long a challenge or enrollment 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]+(defn- create-token+ "Helper for creating signed, single-use JWTs with different `purpose` and TTLs."+ [user-id provider purpose ttl-seconds](jwt/sign {:user-id user-id:provider (name provider)- :purpose "mfa-challenge"+ :purpose purpose: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]+(defn issue-challenge-token+ "Create a signed token authorizing a second-factor attempt for `user-id`, remembering the+ first-factor `provider`."+ [user-id provider]+ (create-token user-id provider "mfa-challenge" challenge-ttl-seconds))++(defn issue-enrollment-token+ "Create a signed token authorizing second-factor enrollment for `user-id`.++ This is used for *unauthenticated* enrollment, when MFA is required and the user has entered their password but does+ not yet have MFA enrolled."+ [user-id provider]+ (create-token user-id provider "mfa-enrollment" challenge-ttl-seconds))++(defn- verify-token+ "Helper for verifying a token's signature, expiry and `purpose`. Returns nil if the token is invalid, expired or+ tampered with, or if the `:purpose` in its claims don't match what we expect.++ Returns the claims map if successful."+ [token expected-purpose](try(let [claims (jwt/unsign token (session.settings/mfa-challenge-signing-key) {:alg :hs256})]- (when (= (:purpose claims) "mfa-challenge")- claims))+ (if (= (:purpose claims) expected-purpose)+ claims+ (log/debugf "Invalid MFA token - unexpected :purpose %s (expected %s)"+ (:purpose claims) expected-purpose)))(catch Exception e- (log/debugf "Invalid MFA challenge token: %s" (ex-message e))+ (log/debug e "Invalid MFA token")nil)))++;; NOTE: The `:purpose` claim checked by these verifiers is a critical check! If a `mfa-challenge` token were+;; accepted by the enrollment API, an attacker with the password but not the MFA could bypass an existing MFA by+;; using the challenge token to instead enroll their own authenticator instead.+(defn verify-challenge-token+ "Verify an `mfa-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]+ (verify-token token "mfa-challenge"))++(defn verify-enrollment-token+ "Verify an `mfa-enrollment` 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]+ (verify-token token "mfa-enrollment"))diff --git a/src/metabase/session/core.clj b/src/metabase/session/core.cljindex 4252ffdc7e0..af4e0dd3124 100644--- a/src/metabase/session/core.clj+++ b/src/metabase/session/core.clj@@ -18,6 +18,7 @@(metabase.session.settingsenable-password-loginenable-password-login!+ mfa-required?password-complexitysession-cookies))diff --git a/src/metabase/session/settings.clj b/src/metabase/session/settings.cljindex 9b2f662e249..534227efcd9 100644--- a/src/metabase/session/settings.clj+++ b/src/metabase/session/settings.clj@@ -2,6 +2,7 @@(:require[buddy.core.codecs :as codecs][buddy.core.nonce :as nonce]+ [metabase.premium-features.core :as premium-features][metabase.settings.core :as setting :refer [defsetting]][metabase.sso.core :as sso][metabase.util.i18n :refer [deferred-tru]]@@ -58,3 +59,11 @@;; 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))))++(premium-features/defenterprise mfa-required?+ "Whether MFA is currently required for all users on the instance when using email or LDAP auth.++ Always false in OSS, since that enforcement is an EE feature."+ metabase-enterprise.mfa.core+ []+ false)diff --git a/src/metabase/settings/models/setting.clj b/src/metabase/settings/models/setting.cljindex 7f5ee026594..6a3b6cd95f1 100644--- a/src/metabase/settings/models/setting.clj+++ b/src/metabase/settings/models/setting.clj@@ -23,6 +23,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]+ [metabase.util.time :as u.time][methodical.core :as methodical][toucan2.core :as t2])(:import@@ -959,8 +960,13 @@(defmethod set-value-of-type! :timestamp[_setting-type setting-definition-or-name new-value](set-value-of-type!- :string setting-definition-or-name- (some-> new-value u.date/format)))+ :string+ setting-definition-or-name+ (when (some? new-value) ; nils are written through directly+ ;; But if there is a value, then it must be one we can coerce to a timestamp.+ (if-let [timestamp (u.time/coerce-to-timestamp new-value)]+ (u.date/format timestamp)+ (throw (ex-info "Malformed value for :timestamp setting" {:value new-value}))))))(defn- serialize-csv [value](conddiff --git a/src/metabase/sso/providers/ldap.clj b/src/metabase/sso/providers/ldap.cljindex eb6f58f357c..86295eef865 100644--- a/src/metabase/sso/providers/ldap.clj+++ b/src/metabase/sso/providers/ldap.clj@@ -17,6 +17,9 @@;; Register LDAP provider in the hierarchy(auth-identity/derive! :provider/ldap :metabase.auth-identity.provider/provider)+;; LDAP Authenticated users are eligible for our MFA flow+(auth-identity/derive! :provider/ldap :metabase.auth-identity.provider/supports-mfa)+;; LDAP is an SSO provider that auto-creates users(auth-identity/derive! :provider/ldap :metabase.auth-identity.provider/create-user-if-not-exists)diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.cljindex 33d6c30e966..f93aa156bcb 100644--- a/src/metabase/users_rest/api.clj+++ b/src/metabase/users_rest/api.clj@@ -14,6 +14,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][metabase.request.core :as request]+ [metabase.session.core :as session][metabase.sso.core :as sso][metabase.system.core :as system][metabase.tenants.core :as tenants]@@ -632,14 +633,25 @@:password old_password})))"old_password"(tru "Invalid password")))- ;; set-password! invalidates the user's existing sessions; a self-change gets a fresh one below- (auth-identity/set-password! id password)- ;; after a successful password update go ahead and offer the client a new session that they can use- (when (= id api/*current-user-id*)- (let [{session-key :key, :as session} (auth-identity/create-session-with-auth-tracking! user (request/device-info request) :provider/password)- response {:success true- :session_id (str session-key)}]- (request/set-session-cookies request response session (t/zoned-date-time (t/zone-id "GMT")))))))+ ;; We want to propagate MFA info from the old session so that users aren't auto-logged out.+ ;; This needs to be done before we delete the old session.+ (let [mfa-auth-identity-id (some-> request+ :metabase-session-key+ session/hash-session-key+ users-rest.db/mfa-auth-identity-id-from-hashed-key+ :mfa_auth_identity_id)]+ ;; set-password! invalidates the user's existing sessions; a self-change gets a fresh one below+ (auth-identity/set-password! id password)+ ;; after a successful password update go ahead and offer the client a new session that they can use+ (when (= id api/*current-user-id*)+ (let [{session-key :key, :as session} (auth-identity/create-session-with-auth-tracking!+ user+ (request/device-info request)+ :provider/password+ mfa-auth-identity-id)+ response {:success true+ :session_id (str session-key)}]+ (request/set-session-cookies request response session (t/zoned-date-time (t/zone-id "GMT"))))))));;; +----------------------------------------------------------------------------------------------------------------+;;; | Password Reset URL -- POST /api/user/:id/password-reset-url |diff --git a/src/metabase/users_rest/db.clj b/src/metabase/users_rest/db.cljindex e9b2f369cf1..3a6d5ae04da 100644--- a/src/metabase/users_rest/db.clj+++ b/src/metabase/users_rest/db.clj@@ -136,3 +136,9 @@[user-id :- ::lib.schema.id/userchanges :- PersonalUserChanges](t2/update! :model/User user-id {:type :personal} changes))++(mu/defn mfa-auth-identity-id-from-hashed-key+ "Fetches the `mfa_auth_identity_id` from the session with the given hashed key"+ [key-hashed :- string?]+ (t2/select-one [:model/Session :mfa_auth_identity_id]+ :key_hashed key-hashed))diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.cljindex f382aaa66af..f6c6cc83db4 100644--- a/test/metabase/server/middleware/session_test.clj+++ b/test/metabase/server/middleware/session_test.clj@@ -7,10 +7,12 @@[metabase.api-keys.core :as api-key][metabase.api.common :refer [*current-user* *current-user-id* *is-group-manager?* *is-superuser?*]][metabase.app-db.core :as mdb]+ [metabase.auth-identity.core :as auth-identity][metabase.config.core :as config][metabase.initialization-status.core :as init-status][metabase.premium-features.core :as premium-features][metabase.request.core :as request]+ [metabase.server.db :as server.db][metabase.server.middleware.session :as mw.session][metabase.session.core :as session][metabase.session.events.revoke-on-deactivation] ; for side effects: deletes sessions on deactivation@@ -58,22 +60,23 @@(deftest session-expired-test(init-status/set-complete!)(testing "Session expiration time = 1 minute"- (with-redefs [env/env (assoc env/env :max-session-age "1")]- (doseq [[created-at expected msg]- [[:%now false "brand-new session"]- [#t "1970-01-01T00:00:01Z" true "really old session"]- [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -61 :second) true "session that is 61 seconds old"]- [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -59 :second) false "session that is 59 seconds old"]]]- (testing (format "\n%s %s be expired." msg (if expected "SHOULD" "SHOULD NOT"))- (mt/with-temp [:model/User {user-id :id}]- (let [session-id (session/generate-session-id)- session-key (str (random-uuid))- session-key-hashed (session/hash-session-key session-key)]- (t2/insert! (t2/table-name :model/Session) {:id session-id :key_hashed session-key-hashed, :user_id user-id, :created_at created-at})- (let [session (#'mw.session/current-user-info-for-session session-key nil)]- (if expected- (is (nil? session))- (is (some? session)))))))))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (with-redefs [env/env (assoc env/env :max-session-age "1")]+ (doseq [[created-at expected msg]+ [[:%now false "brand-new session"]+ [#t "1970-01-01T00:00:01Z" true "really old session"]+ [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -61 :second) true "session that is 61 seconds old"]+ [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -59 :second) false "session that is 59 seconds old"]]]+ (testing (format "\n%s %s be expired." msg (if expected "SHOULD" "SHOULD NOT"))+ (mt/with-temp [:model/User {user-id :id}]+ (let [session-id (session/generate-session-id)+ session-key (str (random-uuid))+ session-key-hashed (session/hash-session-key session-key)]+ (t2/insert! (t2/table-name :model/Session) {:id session-id :key_hashed session-key-hashed, :user_id user-id, :created_at created-at})+ (let [session (#'mw.session/current-user-info-for-session session-key nil)]+ (if expected+ (is (nil? session))+ (is (some? session))))))))))))(defn- insert-test-session!"Insert a `core_session` row directly, bypassing the model hooks so that columns like `created_at` and `expires_at`@@ -424,96 +427,100 @@(testing "make sure the `current-user-info-for-session` logic is working correctly";; for some reason Toucan seems to be busted with models with non-integer IDs and `with-temp` doesn't seem to work;; the way we'd expect :/- (try- (t2/insert! :model/Session {:id test-session-id- :key_hashed test-session-key-hashed- :user_id (mt/user->id :lucky)})- (is (= {:metabase-user-id (mt/user->id :lucky),- :is-superuser? false,- :is-group-manager? false,- :user-locale nil- :is-data-analyst? false- :auth-provider nil}- (#'mw.session/current-user-info-for-session test-session-key nil)))- (finally- (t2/delete! :model/Session :id test-session-id)))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (t2/insert! :model/Session {:id test-session-id+ :key_hashed test-session-key-hashed+ :user_id (mt/user->id :lucky)})+ (is (= {:metabase-user-id (mt/user->id :lucky),+ :is-superuser? false,+ :is-group-manager? false,+ :user-locale nil+ :is-data-analyst? false+ :auth-provider nil}+ (#'mw.session/current-user-info-for-session test-session-key nil)))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))(deftest current-user-info-for-session-test-2(testing "superusers should come back as `:is-superuser?`"- (try- (t2/insert! :model/Session {:id test-session-id- :key_hashed test-session-key-hashed- :user_id (mt/user->id :crowberto)})- (is (= {:metabase-user-id (mt/user->id :crowberto),- :is-superuser? true,- :is-group-manager? false,- :user-locale nil- :is-data-analyst? false- :auth-provider nil}- (#'mw.session/current-user-info-for-session test-session-key nil)))- (finally- (t2/delete! :model/Session :id test-session-id)))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (t2/insert! :model/Session {:id test-session-id+ :key_hashed test-session-key-hashed+ :user_id (mt/user->id :crowberto)})+ (is (= {:metabase-user-id (mt/user->id :crowberto),+ :is-superuser? true,+ :is-group-manager? false,+ :user-locale nil+ :is-data-analyst? false+ :auth-provider nil}+ (#'mw.session/current-user-info-for-session test-session-key nil)))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))(deftest current-user-info-for-session-test-3(testing "If user is a group manager of at least one group, `:is-group-manager?` "- (try- (mt/with-user-in-groups [group-1 {:name "New Group 1"}- group-2 {:name "New Group 2"}- user [group-1 group-2]]- (t2/update! :model/PermissionsGroupMembership {:user_id (:id user), :group_id (:id group-2)}- {:is_group_manager true})- (t2/insert! :model/Session {:id test-session-id- :key_hashed test-session-key-hashed- :user_id (:id user)})- (testing "is `false` if advanced-permisison is disabled"- (mt/with-premium-features #{}- (is (= false- (:is-group-manager? (#'mw.session/current-user-info-for-session test-session-key nil))))))- (testing "is `true` if advanced-permisison is enabled"- ;; a trick to run this test in OSS because even if advanced-permisison is enabled but EE ns is not evailable- ;; `enable-advanced-permissions?` will still return false- (mt/with-dynamic-fn-redefs [premium-features/enable-advanced-permissions? (fn [& _args] true)]- (is (true?- (:is-group-manager? (#'mw.session/current-user-info-for-session test-session-key nil)))))))- (finally- (t2/delete! :model/Session :id test-session-id)))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (mt/with-user-in-groups [group-1 {:name "New Group 1"}+ group-2 {:name "New Group 2"}+ user [group-1 group-2]]+ (t2/update! :model/PermissionsGroupMembership {:user_id (:id user), :group_id (:id group-2)}+ {:is_group_manager true})+ (t2/insert! :model/Session {:id test-session-id+ :key_hashed test-session-key-hashed+ :user_id (:id user)})+ (testing "is `false` if advanced-permisison is disabled"+ (mt/with-premium-features #{}+ (is (= false+ (:is-group-manager? (#'mw.session/current-user-info-for-session test-session-key nil))))))+ (testing "is `true` if advanced-permisison is enabled"+ ;; a trick to run this test in OSS because even if advanced-permisison is enabled but EE ns is not evailable+ ;; `enable-advanced-permissions?` will still return false+ (mt/with-dynamic-fn-redefs [premium-features/enable-advanced-permissions? (fn [& _args] true)]+ (is (true?+ (:is-group-manager? (#'mw.session/current-user-info-for-session test-session-key nil)))))))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))(deftest current-user-info-for-session-test-4- (testing "full-app-embed sessions shouldn't come back if we don't explicitly specifiy the anti-csrf token"- (try- (t2/insert! :model/Session {:id test-session-id- :key_hashed test-session-key-hashed- :user_id (mt/user->id :lucky)- :anti_csrf_token test-anti-csrf-token})- (is (= nil- (#'mw.session/current-user-info-for-session test-session-key nil)))- (finally- (t2/delete! :model/Session :id test-session-id)))- (testing "...but if we do specifiy the token, they should come back"+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (testing "full-app-embed sessions shouldn't come back if we don't explicitly specifiy the anti-csrf token"(try(t2/insert! :model/Session {:id test-session-id:key_hashed test-session-key-hashed:user_id (mt/user->id :lucky):anti_csrf_token test-anti-csrf-token})- (is (= {:metabase-user-id (mt/user->id :lucky),- :is-superuser? false,- :is-group-manager? false,- :user-locale nil- :is-data-analyst? false- :auth-provider nil}- (#'mw.session/current-user-info-for-session test-session-key test-anti-csrf-token)))+ (is (= nil+ (#'mw.session/current-user-info-for-session test-session-key nil)))(finally(t2/delete! :model/Session :id test-session-id)))- (testing "(unless the token is wrong)"+ (testing "...but if we do specifiy the token, they should come back"(try(t2/insert! :model/Session {:id test-session-id:key_hashed test-session-key-hashed:user_id (mt/user->id :lucky):anti_csrf_token test-anti-csrf-token})- (is (= nil- (#'mw.session/current-user-info-for-session test-session-key (str/join (reverse test-anti-csrf-token)))))+ (is (= {:metabase-user-id (mt/user->id :lucky),+ :is-superuser? false,+ :is-group-manager? false,+ :user-locale nil+ :is-data-analyst? false+ :auth-provider nil}+ (#'mw.session/current-user-info-for-session test-session-key test-anti-csrf-token)))(finally- (t2/delete! :model/Session :id test-session-id)))))))+ (t2/delete! :model/Session :id test-session-id)))+ (testing "(unless the token is wrong)"+ (try+ (t2/insert! :model/Session {:id test-session-id+ :key_hashed test-session-key-hashed+ :user_id (mt/user->id :lucky)+ :anti_csrf_token test-anti-csrf-token})+ (is (= nil+ (#'mw.session/current-user-info-for-session test-session-key (str/join (reverse test-anti-csrf-token)))))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))))(deftest current-user-info-for-session-test-5(testing "if we specify an anti-csrf token we shouldn't get back a session without that token"@@ -528,55 +535,58 @@(deftest current-user-info-for-session-test-6(testing "shouldn't fetch expired sessions"- (try- (t2/insert! :model/Session {:id test-session-id- :key_hashed test-session-key-hashed- :user_id (mt/user->id :lucky)})- ;; use low-level `execute!` because updating is normally disallowed for Sessions- (t2/query-one {:update (t2/table-name :model/Session), :set {:created_at (t/instant 1000)}, :where [:= :id test-session-id]})- (is (= nil- (#'mw.session/current-user-info-for-session test-session-key nil)))- (finally- (t2/delete! :model/Session :id test-session-id)))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (t2/insert! :model/Session {:id test-session-id+ :key_hashed test-session-key-hashed+ :user_id (mt/user->id :lucky)})+ ;; use low-level `execute!` because updating is normally disallowed for Sessions+ (t2/query-one {:update (t2/table-name :model/Session), :set {:created_at (t/instant 1000)}, :where [:= :id test-session-id]})+ (is (= nil+ (#'mw.session/current-user-info-for-session test-session-key nil)))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))(deftest current-user-info-for-session-test-7(testing "shouldn't fetch sessions for inactive users"- (try- (t2/insert! :model/Session {:id test-session-id :key_hashed test-session-key-hashed, :user_id (mt/user->id :trashbird)})- (is (= nil- (#'mw.session/current-user-info-for-session test-session-key nil)))- (finally- (t2/delete! :model/Session :id test-session-id)))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (t2/insert! :model/Session {:id test-session-id :key_hashed test-session-key-hashed, :user_id (mt/user->id :trashbird)})+ (is (= nil+ (#'mw.session/current-user-info-for-session test-session-key nil)))+ (finally+ (t2/delete! :model/Session :id test-session-id))))))(deftest auth-provider-via-left-join-test(testing "session LEFT JOIN on auth_identity returns correct provider for each auth method"- (mt/with-temp [:model/User {user-id :id} {}]- ;; "password" is excluded - its before-insert hook requires credentials, and it's already- ;; tested via auth-method-test in view_log_test.clj. "api-key" is tested above in- ;; current-user-info-for-api-key-test (different code path, no auth_identity).- (doseq [provider ["jwt" "saml" "google" "ldap" "oidc"- "custom-oidc" "slack-connect" "support-access-grant"]]- (testing (str "provider: " provider)- (let [ai (first (t2/insert-returning-instances! (t2/table-name :model/AuthIdentity)- {:user_id user-id- :provider provider- :provider_id (str user-id "-" provider)- :created_at :%now- :updated_at :%now}))- session-key (session/generate-session-key)- session-id (session/generate-session-id)]- (try- (t2/insert! (t2/table-name :model/Session)- {:id session-id- :key_hashed (session/hash-session-key session-key)- :user_id user-id- :auth_identity_id (:id ai)- :created_at :%now})- (is (= provider- (:auth-provider (#'mw.session/current-user-info-for-session session-key nil))))- (finally- (t2/delete! :model/Session :id session-id)- (t2/delete! :model/AuthIdentity :id (:id ai))))))))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (mt/with-temp [:model/User {user-id :id} {}]+ ;; "password" is excluded - its before-insert hook requires credentials, and it's already+ ;; tested via auth-method-test in view_log_test.clj. "api-key" is tested above in+ ;; current-user-info-for-api-key-test (different code path, no auth_identity).+ (doseq [provider ["jwt" "saml" "google" "ldap" "oidc"+ "custom-oidc" "slack-connect" "support-access-grant"]]+ (testing (str "provider: " provider)+ (let [ai (first (t2/insert-returning-instances! (t2/table-name :model/AuthIdentity)+ {:user_id user-id+ :provider provider+ :provider_id (str user-id "-" provider)+ :created_at :%now+ :updated_at :%now}))+ session-key (session/generate-session-key)+ session-id (session/generate-session-id)]+ (try+ (t2/insert! (t2/table-name :model/Session)+ {:id session-id+ :key_hashed (session/hash-session-key session-key)+ :user_id user-id+ :auth_identity_id (:id ai)+ :created_at :%now})+ (is (= provider+ (:auth-provider (#'mw.session/current-user-info-for-session session-key nil))))+ (finally+ (t2/delete! :model/Session :id session-id)+ (t2/delete! :model/AuthIdentity :id (:id ai)))))))))));; create a simple example of our middleware wrapped around a handler that simply returns our bound variables for users(defn- user-bound-handler [request]@@ -613,41 +623,42 @@;;; ---------------------------------------------- with-current-user -------------------------------------------------(deftest bind-locale-test- (let [handler (-> (fn [_ respond _]- (respond i18n/*user-locale*))- mw.session/bind-current-user- mw.session/wrap-current-user-info)- session-locale (fn [session-key & {:as more}]- (handler- (merge {:metabase-session-key session-key} more)- identity- (fn [e] (throw e))))]- (testing "No Session"- (is (= nil- (session-locale nil))))- (testing "w/ Session"- (testing "for user with no `:locale`"- (mt/with-temp [:model/User {user-id :id}]- (let [session-id (session/generate-session-id)- session-key (str (random-uuid))- session-key-hashed (session/hash-session-key session-key)]- (t2/insert! :model/Session {:id session-id :key_hashed session-key-hashed, :user_id user-id})- (is (= nil- (session-locale session-key)))- (testing "w/ X-Metabase-Locale header"+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (let [handler (-> (fn [_ respond _]+ (respond i18n/*user-locale*))+ mw.session/bind-current-user+ mw.session/wrap-current-user-info)+ session-locale (fn [session-key & {:as more}]+ (handler+ (merge {:metabase-session-key session-key} more)+ identity+ (fn [e] (throw e))))]+ (testing "No Session"+ (is (= nil+ (session-locale nil))))+ (testing "w/ Session"+ (testing "for user with no `:locale`"+ (mt/with-temp [:model/User {user-id :id}]+ (let [session-id (session/generate-session-id)+ session-key (str (random-uuid))+ session-key-hashed (session/hash-session-key session-key)]+ (t2/insert! :model/Session {:id session-id :key_hashed session-key-hashed, :user_id user-id})+ (is (= nil+ (session-locale session-key)))+ (testing "w/ X-Metabase-Locale header"+ (is (= "es_MX"+ (session-locale session-key :headers {"x-metabase-locale" "es-mx"})))))))+ (testing "for user *with* `:locale`"+ (mt/with-temp [:model/User {user-id :id} {:locale "es-MX"}]+ (let [session-id (session/generate-session-id)+ session-key (str (random-uuid))+ session-key-hashed (session/hash-session-key session-key)]+ (t2/insert! :model/Session {:id session-id :key_hashed session-key-hashed, :user_id user-id, :created_at :%now})(is (= "es_MX"- (session-locale session-key :headers {"x-metabase-locale" "es-mx"})))))))- (testing "for user *with* `:locale`"- (mt/with-temp [:model/User {user-id :id} {:locale "es-MX"}]- (let [session-id (session/generate-session-id)- session-key (str (random-uuid))- session-key-hashed (session/hash-session-key session-key)]- (t2/insert! :model/Session {:id session-id :key_hashed session-key-hashed, :user_id user-id, :created_at :%now})- (is (= "es_MX"- (session-locale session-key)))- (testing "w/ X-Metabase-Locale header"- (is (= "en_GB"- (session-locale session-key :headers {"x-metabase-locale" "en-GB"}))))))))))+ (session-locale session-key)))+ (testing "w/ X-Metabase-Locale header"+ (is (= "en_GB"+ (session-locale session-key :headers {"x-metabase-locale" "en-GB"})))))))))))(deftest session-timeout-test(let [request-time (t/zoned-date-time "2022-01-01T00:00:00.000Z")@@ -656,7 +667,8 @@:cookies {}}](testing "non-nil `session-timeout-seconds` should set the expiry of the timeout cookie relative to the request time"(mt/with-temporary-setting-values [session-timeout {:amount 60- :unit "minutes"}]+ :unit "minutes"}+ mfa-enforcement :off](testing "with normal sessions"(let [request {:cookies {request/metabase-session-cookie {:value "8df268ab-00c0-4b40-9413-d66b966b696a"}request/metabase-session-timeout-cookie {:value "alive"}}@@ -685,7 +697,8 @@:cookies {}}](testing "If the request does not have session cookies (because they have expired), they should not be reset."(mt/with-temporary-setting-values [session-timeout {:amount 60- :unit "minutes"}]+ :unit "minutes"}+ mfa-enforcement :off](let [request {:cookies {}}](is (= response(mw.session/reset-session-timeout* request response request-time))))))))@@ -697,7 +710,8 @@(deftest session-timeout-requires-premium-feature-test(init-status/set-complete!)(mt/with-premium-features #{}- (mt/with-temporary-setting-values [session-timeout {:amount 5 :unit "minutes"}]+ (mt/with-temporary-setting-values [session-timeout {:amount 5 :unit "minutes"}+ mfa-enforcement :off](mt/with-temp [:model/User {user-id :id}](let [session-id (session/generate-session-id)session-key (str (random-uuid))@@ -732,3 +746,224 @@nil nil nil nil "agent-api" "agent-api";; fully anonymous, non-special routenil nil nil nil nil nil))))++(defn session-valid?+ [session-key]+ (boolean (#'mw.session/current-user-info-for-session session-key nil)))++(defn- generate-session!+ [user-id auth-identity-id & {:keys [mfa_auth_identity_id]}]+ (let [session-id (session/generate-session-id)+ session-key (str (random-uuid))+ session-key-hashed (session/hash-session-key session-key)]+ (t2/insert! :model/Session {:id session-id+ :key_hashed session-key-hashed+ :user_id user-id+ :auth_identity_id auth-identity-id+ :mfa_auth_identity_id mfa_auth_identity_id})+ session-key))++(defn generate-mfa-session!+ [user-id auth-identity-id]+ (let [totp-auth-identity-id (t2/insert-returning-pk! :model/AuthIdentity {:user_id user-id+ :provider "totp"})]+ (generate-session! user-id+ auth-identity-id+ :mfa_auth_identity_id totp-auth-identity-id)))++(defn- generate-session-and-get-user-info!+ [user-id auth-identity-id]+ (let [session-key (generate-session! user-id auth-identity-id)+ session (#'mw.session/current-user-info-for-session session-key nil)]+ session))++(deftest mfa-password-test+ (testing "password"+ (testing "With feature flag off, password works"+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session (generate-session-and-get-user-info! user-id (:id auth-identity))]+ (is (some? session))))))+ (testing "When you lose access to the feature, MFA doesn't apply anymore."+ (mt/when-ee-evailable+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session (generate-session-and-get-user-info! user-id (:id auth-identity))]+ (is (some? session)))))))))+ (mt/when-ee-evailable+ (testing "With feature flag on, password doesn't work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session (generate-session-and-get-user-info! user-id (:id auth-identity))]+ (is (nil? session)))))))+ (testing "With feature flag on before deadline, password doesn't work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline (t/plus (t/offset-date-time)+ (t/hours 16))]+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session (generate-session-and-get-user-info! user-id (:id auth-identity))]+ (is (some? session)))))))+ (testing "With feature flag on after deadline, password doesn't work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline (t/minus (t/offset-date-time)+ (t/hours 16))]+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session (generate-session-and-get-user-info! user-id (:id auth-identity))]+ (is (nil? session))))))))))++(deftest mfa-providers-test+ (init-status/set-complete!)+ (doseq [provider (->> (descendants :metabase.auth-identity.provider/provider)+ ;; We test password separately above because of toucan weirdnes+ (remove #{:provider/password})+ ;; This one doesn't let you get a session normally+ (remove #{:provider/emailed-secret-password-reset}))]+ (testing (name provider)+ (testing "With feature flag off, all providers work"+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}+ :model/AuthIdentity {auth-identity-id :id} {:user_id user-id+ :provider (name provider)}]+ (let [session (generate-session-and-get-user-info! user-id auth-identity-id)]+ (is (some? session))))))+ (testing "When you lose access to the feature, MFA doesn't apply anymore."+ (mt/when-ee-evailable+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}+ :model/AuthIdentity {auth-identity-id :id} {:user_id user-id+ :provider (name provider)}]+ (let [session (generate-session-and-get-user-info! user-id auth-identity-id)]+ (is (some? session)))))))))+ (mt/when-ee-evailable+ (let [supports-mfa (auth-identity/isa? provider :metabase.auth-identity.provider/supports-mfa)]+ (testing "With mfa is being enforced, methods that support mfa don't work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (mt/with-temp+ [:model/User {user-id :id} {}+ :model/AuthIdentity {auth-identity-id :id} {:user_id user-id+ :provider (name provider)}]+ (let [session (generate-session-and-get-user-info! user-id auth-identity-id)]+ (is ((if supports-mfa nil? some?) session)))))))+ (testing "With mfa is being enforced but the enrollment deadline has not passed, methods that support mfa still work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline (t/plus (t/offset-date-time)+ (t/hours 16))]+ (mt/with-temp+ [:model/User {user-id :id} {}+ :model/AuthIdentity {auth-identity-id :id} {:user_id user-id+ :provider (name provider)}]+ (let [session (generate-session-and-get-user-info! user-id auth-identity-id)]+ (is (some? session)))))))+ (testing "With mfa is being enforced but the enrollment deadline has not passed, methods that support mfa don't work"+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline (t/minus (t/offset-date-time)+ (t/hours 16))]+ (mt/with-temp+ [:model/User {user-id :id} {}+ :model/AuthIdentity {auth-identity-id :id} {:user_id user-id+ :provider (name provider)}]+ (let [session (generate-session-and-get-user-info! user-id auth-identity-id)]+ (is ((if supports-mfa nil? some?) session))))))))))))++(deftest mfa-providers-list-test+ (testing "Ldap and password are the only ones that support mfa"+ (is (= #{:provider/password :provider/ldap}+ (auth-identity/descendants :metabase.auth-identity.provider/supports-mfa))))+ (testing "and the hard-coded list the session query is compiled from says the same thing"+ (is (= #{:provider/password :provider/ldap}+ @#'server.db/mfa-supported-methods))))++(deftest mfa-session-preservation-test+ (init-status/set-complete!)+ (testing "If you had a session before MFA was required, it is not preserved"+ (mt/when-ee-evailable+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session-key (generate-session! user-id (:id auth-identity))]+ (is (session-valid? session-key))+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (is (not (session-valid? session-key))))))))))+ (testing "If you had a session before MFA was required, but it was MFA'd, it is still preserved"+ (mt/when-ee-evailable+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session-key (generate-mfa-session! user-id (:id auth-identity))]+ (is (session-valid? session-key))+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline nil]+ (is (session-valid? session-key)))))))))+ (testing "If you had a session before the MFA requirement deadline, but it was MFA'd, it is still preserved"+ (mt/when-ee-evailable+ (mt/with-premium-features+ #{}+ (mt/with-temp+ [:model/User {user-id :id} {}]+ (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ session-key (generate-mfa-session! user-id (:id auth-identity))]+ (is (session-valid? session-key))+ (mt/with-premium-features+ #{:multi-factor-auth}+ (mt/with-temporary-setting-values+ [mfa-enforcement :required+ mfa-requirement-deadline (t/minus (t/offset-date-time)+ (t/hours 16))]+ (is (session-valid? session-key))))))))))diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.cljindex 1abca67cf6d..e3e29724b90 100644--- a/test/metabase/session/api_test.clj+++ b/test/metabase/session/api_test.clj@@ -710,7 +710,8 @@(testing "LDAP login - no fallback when password login disabled"(ldap.test/with-ldap-server!(mt/with-premium-features #{:disable-password-login}- (mt/with-temporary-setting-values [enable-password-login false]+ (mt/with-temporary-setting-values [enable-password-login false+ mfa-enforcement :off](is (= "Password login is disabled for this instance."(mt/client :post 401 "session" (mt/user->credentials :crowberto)))))))))@@ -732,7 +733,8 @@(deftest ldap-login-fallback-for-broken-settings-test(testing "LDAP login - fallback to local for broken LDAP settings"(ldap.test/with-ldap-server!- (mt/with-temporary-setting-values [ldap-user-base "cn=wrong,cn=com"]+ (mt/with-temporary-setting-values [mfa-enforcement :off+ ldap-user-base "cn=wrong,cn=com"](mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}](auth-identity/set-password! user-id "1234")(is (malli= SessionResponse@@ -742,7 +744,8 @@(deftest ldap-login-fallback-for-slow-ldap-test(testing "LDAP login - fallback to local for slow LDAP"(ldap.test/with-ldap-server!- (mt/with-temporary-setting-values [ldap-timeout-seconds 0.01]+ (mt/with-temporary-setting-values [mfa-enforcement :off+ ldap-timeout-seconds 0.01](mt/with-dynamic-fn-redefs [metabase.sso.ldap.default-implementation/search (fn [& _args](Thread/sleep 500))](mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]@@ -754,31 +757,34 @@(deftest ldap-login-new-user-test(testing "LDAP login - can login with new user"(ldap.test/with-ldap-server!- (try- (is (malli= SessionResponse- (mt/client :post 200 "session" {:username "sbrown20", :password "1234"})))- (finally- (t2/delete! :model/User :email "[email protected]"))))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (is (malli= SessionResponse+ (mt/client :post 200 "session" {:username "sbrown20", :password "1234"})))+ (finally+ (t2/delete! :model/User :email "[email protected]")))))))(deftest ldap-login-uppercase-email-test(testing "LDAP login - can login multiple times with uppercase email (#13739)"(ldap.test/with-ldap-server!- (try- (is (malli=- SessionResponse- (mt/client :post 200 "session" {:username "[email protected]", :password "strongpassword"})))- (is (malli=- SessionResponse- (mt/client :post 200 "session" {:username "[email protected]", :password "strongpassword"})))- (finally- (t2/delete! :model/User :email "[email protected]"))))))+ (mt/with-temporary-setting-values [mfa-enforcement :off]+ (try+ (is (malli=+ SessionResponse+ (mt/client :post 200 "session" {:username "[email protected]", :password "strongpassword"})))+ (is (malli=+ SessionResponse+ (mt/client :post 200 "session" {:username "[email protected]", :password "strongpassword"})))+ (finally+ (t2/delete! :model/User :email "[email protected]")))))))(deftest ldap-login-group-sync-without-uid-test(testing "LDAP login - group sync works even if ldap doesn't return uid (#22014)"(ldap.test/with-ldap-server!(mt/with-temp [:model/PermissionsGroup group {:name "Accounting"}](mt/with-temporary-raw-setting-values- [ldap-group-mappings (json/encode {"cn=Accounting,ou=Groups,dc=metabase,dc=com" [(:id group)]})]+ [ldap-group-mappings (json/encode {"cn=Accounting,ou=Groups,dc=metabase,dc=com" [(:id group)]})+ mfa-enforcement "off"](is (malli= SessionResponse(mt/client :post 200 "session" {:username "[email protected]", :password "pa$$word"})))(let [user-id (t2/select-one-pk :model/User :email "[email protected]")]diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.cljindex f115757e663..f6d0cd250fa 100644--- a/test/metabase/users_rest/api_test.clj+++ b/test/metabase/users_rest/api_test.clj@@ -12,6 +12,7 @@[metabase.permissions.core :as perms][metabase.permissions.models.permissions-group :as perms-group][metabase.permissions.util :as perms-util]+ [metabase.session.models.session :as session][metabase.test :as mt][metabase.test.fixtures :as fixtures][metabase.test.http-client :as client]@@ -1710,6 +1711,59 @@(is (nil? (mt/user-http-request :crowberto :put 204 (format "user/%d/password" (:id user)) {:password "abc123!!DEF":old_password "def"})))))))+(defn- generate-session!+ [user-id auth-identity-id & {:keys [mfa_auth_identity_id]}]+ (let [session-id (session/generate-session-id)+ session-key (str (random-uuid))+ session-key-hashed (session/hash-session-key session-key)]+ (t2/insert! :model/Session {:id session-id+ :key_hashed session-key-hashed+ :user_id user-id+ :auth_identity_id auth-identity-id+ :mfa_auth_identity_id mfa_auth_identity_id})+ session-key))++(deftest reset-password-propagates-mfa-test+ (testing "PUT /api/user/:id/password"+ (testing "Test that the session returned has the same MFA method as the initial session"+ (mt/when-ee-evailable+ (mt/with-premium-features #{:multi-factor-auth}+ (mt/with-temp [:model/User user {:is_superuser false}]+ (auth-identity/set-password! (:id user) "def")+ (let [user-id (:id user)+ auth-identity (t2/select-one :model/AuthIdentity :user_id user-id)+ totp-auth-identity-id (t2/insert-returning-pk! :model/AuthIdentity {:user_id user-id+ :provider "totp"})+ original-session-key (generate-session! user-id+ (:id auth-identity)+ :mfa_auth_identity_id totp-auth-identity-id)+ original-session (t2/select-one+ :model/Session+ :key_hashed (session/hash-session-key original-session-key))+ resp (mt/client original-session-key+ :put 200 (format "user/%d/password" user-id)+ {:password "abc123!!DEF"+ :old_password "def"})]+ (is (=? {:session_id string/valid-uuid?+ :success true}+ resp))+ ;; Original session should be gone+ (is (not (t2/exists?+ :model/Session+ :key_hashed (session/hash-session-key original-session-key))))+ (let [new-session-key (:session_id resp)+ new-session (t2/select-one+ :model/Session+ :key_hashed (session/hash-session-key new-session-key))]+ ;; Both the new and the old session should have an mfa id+ (is (some? (:mfa_auth_identity_id original-session)))+ (is (some? (:mfa_auth_identity_id new-session)))+ ;; Which is the same+ (is (= (:mfa_auth_identity_id original-session)+ (:mfa_auth_identity_id new-session)))+ ;; But they should be distinct sessions+ (is (not= (:id original-session) (:id new-session)))))))))))+(deftest reset-password-invalidates-existing-sessions-test(testing "PUT /api/user/:id/password invalidates the user's existing sessions"(mt/with-temp [:model/User user {:is_superuser false}]