Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Eagerly load tenant auth-provider; fail tenant SSO logins loudly (UXW-4898) (#78492)

John Swanson2c82f4332cfc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 08c75d27b46..531f560ef94 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3696,7 +3696,7 @@
enterprise/tenants
{:team "Admin Webapp"
- :api #{metabase-enterprise.tenants.api}
+ :api #{metabase-enterprise.tenants.api metabase-enterprise.tenants.init}
:uses #{api
audit-app
auth-identity
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index 1abe35a39d1..544f0820079 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -28,5 +28,6 @@
[metabase-enterprise.sso.init]
[metabase-enterprise.stale.init]
[metabase-enterprise.support-access-grants.init]
+ [metabase-enterprise.tenants.init]
[metabase-enterprise.transforms-python.init]
[metabase-enterprise.workspaces.init]))
diff --git a/enterprise/backend/src/metabase_enterprise/tenants/init.clj b/enterprise/backend/src/metabase_enterprise/tenants/init.clj
new file mode 100644
index 00000000000..911c6698443
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/tenants/init.clj
@@ -0,0 +1,9 @@
+(ns metabase-enterprise.tenants.init
+ "Loads tenants namespaces that need to be loaded for side effects on system launch. See [[metabase-enterprise.core.init]].
+
+ [[metabase-enterprise.tenants.auth-provider]] registers the `login!` method that validates a login's tenant claim
+ and stamps `:tenant_id` onto the user data. The SSO providers only `derive` from its keyword, which does not load
+ the namespace — without this eager require, a freshly started instance silently skips the tenant step for JWT/SAML
+ logins until something else loads the namespace, provisioning tenant users as internal users (UXW-4898)."
+ (:require
+ [metabase-enterprise.tenants.auth-provider]))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
index 300d26cb9f8..4d89895497f 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
@@ -10,11 +10,13 @@
[metabase-enterprise.sso.test-setup :as sso.test-setup]
[metabase-enterprise.tenants.auth-provider] ;; make sure the auth provider is actually registered
[metabase.appearance.settings :as appearance.settings]
+ [metabase.auth-identity.provider :as auth-identity.provider]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.http-client :as client]
[metabase.util :as u]
[metabase.util.malli.schema :as ms]
+ [methodical.core :as methodical]
[toucan2.core :as t2]))
(use-fixtures :once (fixtures/initialize :test-users))
@@ -1168,6 +1170,75 @@
(testing "user is assigned to All tenant users (magic group for tenant users)"
(is (contains? (group-memberships (u/the-id user)) "All tenant users")))))))))))))
+(deftest jwt-with-valid-tenant-claim-must-never-create-wedged-internal-user-test
+ (testing (str "UXW-4898: if the tenant login step is missing from the login! method chain (as happens when "
+ "metabase-enterprise.tenants.auth-provider was never loaded — see metabase-enterprise.tenants.init), "
+ "a JWT carrying a valid @tenant plus a mapped tenant group must NOT succeed and silently create an "
+ "internal user, which would permanently wedge the account. It must fail loudly and leave no user row.")
+ (with-jwt-default-setup!
+ (mt/with-additional-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant _ {:slug "tenant-mctenantson"
+ :name "Tenant McTenantson"}
+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Administrators"
+ :is_tenant_group true}]
+ (mt/with-temporary-setting-values
+ [jwt-group-sync true
+ jwt-group-mappings {"Tenant Administrators" [tenant-group-id]}
+ jwt-attribute-groups "groups"]
+ (mt/with-model-cleanup [:model/User]
+ (let [dispatch-val :metabase-enterprise.tenants.auth-provider/create-tenant-if-not-exists
+ method (methodical/primary-method auth-identity.provider/login! dispatch-val)]
+ (is (some? method)
+ "tenant login method should be registered at startup (see metabase-enterprise.tenants.init)")
+ (try
+ (alter-var-root #'auth-identity.provider/login! methodical/remove-primary-method dispatch-val)
+ (let [response (client/client-real-response :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :return_to default-redirect-uri
+ :jwt
+ (jwt/sign
+ {:email "[email protected]"
+ :first_name "Wedged"
+ :last_name "User"
+ "@tenant" "tenant-mctenantson"
+ :groups ["Tenant Administrators"]}
+ default-jwt-secret))]
+ (is (not (sso.test-setup/successful-login? response)))
+ (testing "no half-provisioned user row is left behind"
+ (is (nil? (t2/select-one :model/User :email "[email protected]")))))
+ (finally
+ (alter-var-root #'auth-identity.provider/login!
+ methodical/add-primary-method dispatch-val method))))))))))))
+
+(deftest jwt-without-tenant-claim-mapped-to-tenant-group-fails-loudly-test
+ (testing (str "EMB-2118/#78009: a JWT with no @tenant claim whose groups map to a tenant group must not succeed "
+ "and silently create an internal user with a swallowed group-sync failure. The tenant-group "
+ "mismatch must fail the login and roll back user creation.")
+ (with-jwt-default-setup!
+ (mt/with-additional-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Administrators"
+ :is_tenant_group true}]
+ (mt/with-temporary-setting-values
+ [jwt-group-sync true
+ jwt-group-mappings {"Tenant Administrators" [tenant-group-id]}
+ jwt-attribute-groups "groups"]
+ (mt/with-model-cleanup [:model/User]
+ (let [response (client/client-real-response :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :return_to default-redirect-uri
+ :jwt
+ (jwt/sign
+ {:email "[email protected]"
+ :first_name "Tenantless"
+ :last_name "User"
+ :groups ["Tenant Administrators"]}
+ default-jwt-secret))]
+ (is (not (sso.test-setup/successful-login? response)))
+ (testing "user creation is rolled back"
+ (is (nil? (t2/select-one :model/User :email "[email protected]")))))))))))))
+
(deftest tenant-user-assigned-to-tenant-group-via-name-matching-test
(testing "JWT user with tenant claim can be assigned to tenant user groups via group name matching (no explicit mappings)"
(with-jwt-default-setup!
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/init_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/init_test.clj
new file mode 100644
index 00000000000..dee54cd8cf6
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/tenants/init_test.clj
@@ -0,0 +1,14 @@
+(ns metabase-enterprise.tenants.init-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.core.init]
+ [metabase.auth-identity.provider :as auth-identity.provider]
+ [methodical.core :as methodical]))
+
+(deftest tenant-auth-provider-registered-on-init-test
+ (testing (str "UXW-4898: the enterprise init chain must load metabase-enterprise.tenants.auth-provider. "
+ "The SSO providers only `derive` from its dispatch keyword, which does not load the namespace — "
+ "if this method is missing, JWT/SAML logins silently skip tenant validation and provision tenant "
+ "users as internal users.")
+ (is (some? (methodical/primary-method auth-identity.provider/login!
+ :metabase-enterprise.tenants.auth-provider/create-tenant-if-not-exists)))))
diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.clj
index dc47391e106..23f2131dff4 100644
--- a/src/metabase/auth_identity/provider.clj
+++ b/src/metabase/auth_identity/provider.clj
@@ -302,7 +302,11 @@
(cond-> $
(and (:provider-id $) (:user-data $))
(assoc-in [:user-data :provider-id] (:provider-id $)))
- (next-method provider $)
+ ;; run the whole provisioning chain (tenant creation, user create/update, group sync) in one
+ ;; transaction: a failure partway through (e.g. a tenant-group assignment rejected because the
+ ;; user's tenant assignment was lost) must not leave a half-provisioned account behind (UXW-4898)
+ (t2/with-transaction [_]
+ (next-method provider $))
(apply-mfa-gate provider $)
(cond-> $
(and (:user $) (not (:mfa/pending? $))) (create-session! provider))
@@ -348,15 +352,24 @@
[:provider-id {:optional true} [:maybe :string]]
[:tenant_id {:optional true} [:maybe ms/PositiveInt]]]
provider :- :keyword]
- (t2/with-transaction [_]
- (u/prog1
- (t2/insert-returning-instance! [:model/User :id :last_login :is_active :tenant_id]
- (select-keys user-data (sso-user-fields)))
- (t2/insert! :model/AuthIdentity (cond-> {:user_id (:id <>) :provider (name provider)}
- (:provider-id user-data) (assoc :provider_id (:provider-id user-data))))
- (notification/with-skip-sending-notification true
- (events/publish-event! :event/user-invited {:object (assoc (t2/select-one :model/User (:id <>))
- :sso_source (name provider))})))))
+ (let [insert-fields (sso-user-fields)]
+ ;; The tenant flow upstream validated the tenant claim and stamped :tenant_id into user-data. If
+ ;; the field list would strip it here (e.g. a premium-feature check flapped mid-request, or the
+ ;; enterprise implementation isn't registered yet), inserting anyway would create a non-tenant
+ ;; user that can never log in with its tenant claim again (UXW-4898) — refuse instead
+ (when (and (:tenant_id user-data)
+ (not (some #{:tenant_id} insert-fields)))
+ (throw (ex-info "Unable to provision SSO user: tenant assignment could not be applied"
+ {:status-code 500})))
+ (t2/with-transaction [_]
+ (u/prog1
+ (t2/insert-returning-instance! [:model/User :id :last_login :is_active :tenant_id]
+ (select-keys user-data insert-fields))
+ (t2/insert! :model/AuthIdentity (cond-> {:user_id (:id <>) :provider (name provider)}
+ (:provider-id user-data) (assoc :provider_id (:provider-id user-data))))
+ (notification/with-skip-sending-notification true
+ (events/publish-event! :event/user-invited {:object (assoc (t2/select-one :model/User (:id <>))
+ :sso_source (name provider))}))))))
(methodical/defmethod login! ::create-user-if-not-exists
[provider request]
diff --git a/src/metabase/sso/common.clj b/src/metabase/sso/common.clj
index 17b1176d9e4..d549248f30b 100644
--- a/src/metabase/sso/common.clj
+++ b/src/metabase/sso/common.clj
@@ -35,7 +35,13 @@
(try
(perms/add-user-to-group! user-or-id group-or-id)
(catch Throwable e
- (log/errorf e "Error adding user %s to group %s" (u/the-id user-or-id) (u/the-id group-or-id))))))
+ ;; A tenant/group mismatch means the user landed in the wrong space (e.g. an SSO login whose
+ ;; tenant assignment was lost); swallowing it would silently wedge the account (UXW-4898),
+ ;; so fail the login loudly instead. A nil :group-is-tenant? means the group doesn't exist —
+ ;; that stays on the log-and-continue path like any other bogus group id.
+ (if (some (comp some? :group-is-tenant?) (:bad-user-group-pairs (ex-data e)))
+ (throw e)
+ (log/errorf e "Error adding user %s to group %s" (u/the-id user-or-id) (u/the-id group-or-id)))))))
(defn sync-group-memberships!
"Update the PermissionsGroups a User belongs to, adding or deleting membership entries as needed so that Users is
diff --git a/test/metabase/auth_identity/provider_test.clj b/test/metabase/auth_identity/provider_test.clj
index d88a73109f2..861f4613684 100644
--- a/test/metabase/auth_identity/provider_test.clj
+++ b/test/metabase/auth_identity/provider_test.clj
@@ -3,6 +3,7 @@
[clojure.test :refer :all]
[java-time.api :as t]
[metabase.auth-identity.provider :as provider]
+ [metabase.test :as mt]
[methodical.core :as methodical]))
;; Set up test providers for testing the hierarchy
@@ -92,6 +93,19 @@
(is (nil? (:session result)))
(is (nil? (:user result)))))))
+(deftest create-user!-refuses-to-strip-tenant-id-test
+ (testing (str "UXW-4898: when user-data carries :tenant_id but the sso-user-fields field list would strip it "
+ "(e.g. a premium-feature check disagrees with the upstream tenant flow that stamped it), "
+ "create-user! must throw rather than silently create a non-tenant user — such a user could "
+ "never log in with its tenant claim again")
+ (mt/with-premium-features #{:sso-jwt}
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"tenant assignment could not be applied"
+ (#'provider/create-user! {:email "[email protected]"
+ :sso_source :jwt
+ :tenant_id 1}
+ :jwt))))))
+
(deftest ^:parallel ^:parallel three-valued-success-state-test
(testing "Success states work correctly"
(testing "Success state: true"