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
JWTs can set tenant attributes (#68562)
John Swanson2b027c0ed18e
diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.cljindex b33e8007639..46b61ef5145 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj@@ -39,6 +39,9 @@(def ^:private ^{:arglists '([])} jwt-attribute-tenant(comp keyword sso-settings/jwt-attribute-tenant))+(def ^:private ^{:arglists '([])} jwt-attribute-tenant-attributes+ (comp keyword sso-settings/jwt-attribute-tenant-attributes))+(def ^:private registered-claims"Registered claims in the JWT standard which we should not interpret as login attributes."[:iss :iat :sub :aud :exp :nbf :jti])@@ -52,9 +55,17 @@(jwt-attribute-lastname)(jwt-attribute-groups)](when (setting/get :use-tenants)- [(jwt-attribute-tenant)]))]+ [(jwt-attribute-tenant)+ (jwt-attribute-tenant-attributes)]))](sso-utils/stringify-valid-attributes (apply dissoc jwt-data excluded-keys))))+(defn- extract-tenant-attributes+ "Extract and stringify tenant attributes from JWT data. Returns nil if not a map."+ [jwt-data]+ (let [attrs (get jwt-data (jwt-attribute-tenant-attributes))]+ (when (map? attrs)+ (sso-utils/stringify-valid-attributes attrs))))+(defn- decode-and-verify-jwt"Decode and verify a JWT token. Returns the JWT data if valid, throws on error."[token]@@ -91,6 +102,7 @@(integer? <>))(throw (ex-info "Value of `@tenant` must be a string" {:status-code 400:error :invalid-tenant}))))+ tenant-attributes (extract-tenant-attributes jwt-data)user-attributes (jwt-data->user-attributes jwt-data)](when-not email(throw (ex-info (tru "JWT token missing email claim")@@ -99,6 +111,7 @@(log/infof "Successfully authenticated JWT token for: %s %s" first-name last-name){:success? true:tenant-slug (some-> tenant-slug str)+ :tenant-attributes tenant-attributes:user-data (->> {:email email:first_name first-name:last_name last-namediff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.cljindex 74e9f5ac6a6..0bfd2b794c3 100644--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj@@ -252,6 +252,14 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e:feature :sso-jwt:audit :getter)+(defsetting jwt-attribute-tenant-attributes+ (deferred-tru "Key to retrieve the JWT user''s tenant attributes")+ :export? false+ :encryption :when-encryption-key-set+ :default "@tenant.attributes"+ :feature :sso-jwt+ :audit :getter)+(defsetting jwt-attribute-groups(deferred-tru "Key to retrieve the JWT user''s groups"):default "groups"diff --git a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.cljindex 78e02d316d1..b1eb7c14307 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj@@ -61,23 +61,36 @@:tenant-slug/is-active (:is_active existing-tenant):status-code 403})))))+(defn- maybe-update-tenant-attributes!+ "If tenant exists and there are new attributes to add, update the tenant.+ Only adds attributes that don't already exist (preserves existing)."+ [existing-tenant tenant-attributes]+ (when (and existing-tenant tenant-attributes)+ ;; merge new attrs into existing, with existing taking precedence (existing wins)+ (let [merged (merge tenant-attributes (:attributes existing-tenant))]+ (when (not= merged (:attributes existing-tenant))+ (request/as-admin+ (api.tenants/update-tenant! (:id existing-tenant) {:attributes merged}))))))+(defn- create-tenant-if-not-exists!- [{:as request :keys [user tenant-slug user-provisioning-enabled?]} existing-tenant]+ [{:as request :keys [user tenant-slug tenant-attributes user-provisioning-enabled?]} existing-tenant](if-not (setting/get :use-tenants)(do (validate-with-tenants-disabled! request)request)(do (validate-user-and-tenant-slug! user existing-tenant (boolean tenant-slug))(maybe-reactivate-tenant! existing-tenant user-provisioning-enabled?)+ (maybe-update-tenant-attributes! existing-tenant tenant-attributes)(cond-> request(boolean tenant-slug)(assoc-in [:user-data :tenant_id](u/the-id (or existing-tenant(request/as-admin- (api.tenants/create-tenant! {:slug tenant-slug :name tenant-slug})))))))))+ (api.tenants/create-tenant!+ (cond-> {:slug tenant-slug :name tenant-slug}+ tenant-attributes (assoc :attributes tenant-attributes)))))))))))(methodical/defmethod auth-identity/login! ::create-tenant-if-not-exists- [provider {:keys [tenant-slug]- :as request}]+ [provider {:keys [tenant-slug] :as request}](let [existing-tenant (when tenant-slug (t2/select-one :model/Tenant :slug tenant-slug))](next-method provider (create-tenant-if-not-exists! request existing-tenant))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.cljindex 97dbde1d947..b461f0b1480 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj@@ -1210,3 +1210,79 @@(group-memberships (u/the-id user)))))(testing "user is no longer in Group A"(is (not (contains? (group-memberships (u/the-id user)) "Group A"))))))))))))))++(deftest tenant-attributes-from-jwt-test+ (testing "Tenant attributes can be set via JWT"+ (testing "New tenant gets attributes from JWT"+ (mt/with-model-cleanup [:model/Tenant]+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "new-tenant-with-attrs"+ "@tenant.attributes" {"plan" "enterprise"+ "region" "us-west"}+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (sso.test-setup/successful-login? response))+ (let [tenant (t2/select-one :model/Tenant :slug "new-tenant-with-attrs")]+ (is (some? tenant))+ (is (= {"plan" "enterprise" "region" "us-west"}+ (:attributes tenant)))))))))))++ (testing "Existing tenant - new attributes added, existing preserved"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "existing-tenant"+ :name "Existing Tenant"+ :attributes {"plan" "enterprise"}}]+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "existing-tenant"+ "@tenant.attributes" {"plan" "basic"+ "region" "us-east"}+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (sso.test-setup/successful-login? response))+ (let [tenant (t2/select-one :model/Tenant tenant-id)]+ (testing "existing 'plan' attribute is preserved, not overwritten"+ (is (= "enterprise" (get (:attributes tenant) "plan"))))+ (testing "new 'region' attribute is added"+ (is (= "us-east" (get (:attributes tenant) "region"))))))))))))++ (testing "Invalid @tenant.attributes is ignored"+ (mt/with-model-cleanup [:model/Tenant]+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-invalid-attrs"+ "@tenant.attributes" "not-a-map"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (sso.test-setup/successful-login? response))+ (let [tenant (t2/select-one :model/Tenant :slug "tenant-invalid-attrs")]+ (is (some? tenant))+ (testing "tenant created but with no attributes since the value wasn't a map"+ (is (nil? (:attributes tenant))))))))))))))