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
Add support for OpenID Connect (#69538)
Nathan Voxlandb4f717609e1d
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.cljnew file mode 100644index 00000000000..7377db655e8--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj@@ -0,0 +1,195 @@+(ns metabase-enterprise.sso.api.oidc+ "Admin-only CRUD endpoints for managing OIDC providers at `/api/ee/sso/oidc`."+ (:require+ [clojure.string :as str]+ [clojure.walk :as walk]+ [metabase-enterprise.sso.settings :as sso-settings]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.premium-features.core :as premium-features]+ [metabase.settings.core :as setting]+ [metabase.sso.core :as sso]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]))++(set! *warn-on-reflection* true)++;;; -------------------------------------------------- Schema --------------------------------------------------++(def ^:private oidc-provider-create-schema+ [:map {:closed true}+ [:key :string]+ [:login-prompt :string]+ [:issuer-uri :string]+ [:client-id :string]+ [:client-secret :string]+ [:scopes {:optional true} [:sequential :string]]+ [:enabled {:optional true} :boolean]+ [:attribute-map {:optional true} [:map-of :string :string]]+ [:group-sync {:optional true} [:map {:closed true}+ [:enabled {:optional true} :boolean]+ [:group-attribute {:optional true} :string]+ [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])++(def ^:private oidc-provider-update-schema+ [:map {:closed true}+ [:login-prompt {:optional true} :string]+ [:issuer-uri {:optional true} :string]+ [:client-id {:optional true} :string]+ [:client-secret {:optional true} :string]+ [:scopes {:optional true} [:sequential :string]]+ [:enabled {:optional true} :boolean]+ [:attribute-map {:optional true} [:map-of :string :string]]+ [:group-sync {:optional true} [:map {:closed true}+ [:enabled {:optional true} :boolean]+ [:group-attribute {:optional true} :string]+ [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])++(def ^:private oidc-provider-response-schema+ [:map {:closed true}+ [:key :string]+ [:login-prompt :string]+ [:issuer-uri :string]+ [:client-id :string]+ [:client-secret :string]+ [:scopes {:optional true} [:sequential :string]]+ [:enabled {:optional true} :boolean]+ [:attribute-map {:optional true} [:map-of :string :string]]+ [:group-sync {:optional true} [:map {:closed true}+ [:enabled {:optional true} :boolean]+ [:group-attribute {:optional true} :string]+ [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])++;;; -------------------------------------------------- Helpers --------------------------------------------------++(defn- sanitize-response+ "Ensures the API response is safe to return to the client.+ Obfuscates the client-secret and ensures keys are strings."+ [provider]+ (cond-> provider+ (:client-secret provider) (update :client-secret setting/obfuscate-value)+ (:attribute-map provider) (update :attribute-map walk/stringify-keys)))++(defn- check-oidc-connection!+ "Run OIDC configuration check and throw a 400 if it fails. Returns the check result on success."+ [issuer-uri client-id client-secret]+ (let [result (sso/check-oidc-configuration issuer-uri client-id client-secret)]+ (api/check-400 (:ok result)+ (or (get-in result [:credentials :error])+ (get-in result [:discovery :error])+ "OIDC configuration check failed"))+ result))++;;; -------------------------------------------------- Endpoints --------------------------------------------------++;; GET /api/ee/sso/oidc+(api.macros/defendpoint :get "/" :- [:sequential oidc-provider-response-schema]+ "List all OIDC providers (with client secrets masked)."+ []+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (mapv sanitize-response (sso-settings/oidc-providers)))++;; GET /api/ee/sso/oidc/:key+(api.macros/defendpoint :get "/:key" :- oidc-provider-response-schema+ "Get a single OIDC provider by key (with client secret masked)."+ [{provider-key :key} :- [:map [:key :string]]]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (let [provider (sso-settings/get-oidc-provider provider-key)]+ (api/check-404 provider)+ (sanitize-response provider)))++;; POST /api/ee/sso/oidc+(api.macros/defendpoint :post "/" :- oidc-provider-response-schema+ "Create a new OIDC provider."+ [_route-params+ _query-params+ body :- oidc-provider-create-schema]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (let [provider-key (:key body)]+ (api/check-400 (u/valid-slug? provider-key) "Provider key must be a URL-safe slug (lowercase letters, numbers, hyphens, must start with letter or number)")+ (api/check-400 (nil? (sso-settings/get-oidc-provider provider-key)) (format "An OIDC provider with key '%s' already exists" provider-key))+ (check-oidc-connection! (:issuer-uri body) (:client-id body) (:client-secret body))+ (let [providers (sso-settings/oidc-providers)+ new-provider (merge {:enabled false+ :scopes ["openid" "email" "profile"]}+ body)]+ (sso-settings/oidc-providers! (conj (vec providers) new-provider))+ (sanitize-response new-provider))))++;; PUT /api/ee/sso/oidc/:key+(api.macros/defendpoint :put "/:key" :- oidc-provider-response-schema+ "Update an existing OIDC provider."+ [{provider-key :key} :- [:map [:key :string]]+ _query-params+ body :- oidc-provider-update-schema]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (let [providers (sso-settings/oidc-providers)+ idx (some (fn [[i p]] (when (= (:key p) provider-key) i))+ (map-indexed vector providers))]+ (api/check-404 idx)+ (let [existing (nth providers idx)+ ;; If client-secret is the mask or not provided, keep the existing one+ body (if (or (not (:client-secret body))+ (= (:client-secret body) (setting/obfuscate-value (:client-secret body))))+ (dissoc body :client-secret)+ body)+ updated (merge existing body)]+ (check-oidc-connection! (:issuer-uri updated) (:client-id updated) (:client-secret updated))+ (let [providers (assoc (vec providers) idx updated)]+ (sso-settings/oidc-providers! providers)+ (sanitize-response updated)))))++;; POST /api/ee/sso/oidc/check+(def ^:private oidc-check-request-schema+ [:map {:closed true}+ [:issuer-uri :string]+ [:client-id :string]+ [:client-secret {:optional true} [:maybe :string]]+ [:key {:optional true} [:maybe :string]]])++(def ^:private oidc-check-step-schema+ [:map+ [:step :keyword]+ [:success :boolean]+ [:verified {:optional true} :boolean]+ [:error {:optional true} :string]+ [:token-endpoint {:optional true} :string]])++(def ^:private oidc-check-response-schema+ [:map+ [:ok :boolean]+ [:discovery oidc-check-step-schema]+ [:credentials {:optional true} oidc-check-step-schema]])++(api.macros/defendpoint :post "/check" :- oidc-check-response-schema+ "Check an OIDC provider configuration by probing its discovery document and testing client credentials."+ [_route-params+ _query-params+ body :- oidc-check-request-schema]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (let [issuer-uri (:issuer-uri body)+ client-id (:client-id body)+ client-secret (let [s (:client-secret body)]+ (if (str/blank? s)+ ;; If no secret provided, look up the stored one by provider key+ (when-let [provider-key (:key body)]+ (when-let [provider (sso-settings/get-oidc-provider provider-key)]+ (:client-secret provider)))+ s))]+ (check-oidc-connection! issuer-uri client-id client-secret)))++;; DELETE /api/ee/sso/oidc/:key+(api.macros/defendpoint :delete "/:key" :- :nil+ "Delete an OIDC provider."+ [{provider-key :key} :- [:map [:key :string]]]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))+ (let [providers (sso-settings/oidc-providers)+ filtered (vec (remove #(= (:key %) provider-key) providers))]+ (when (= (count providers) (count filtered))+ (api/check-404 nil))+ (sso-settings/oidc-providers! filtered)+ nil))++(def ^{:arglists '([request respond raise])} routes+ "`/api/ee/sso/oidc` routes."+ (api.macros/ns-handler *ns* api/+check-superuser))diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj b/enterprise/backend/src/metabase_enterprise/sso/api/routes.cljindex 28fd5b8ea24..9476222f488 100644--- a/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj@@ -1,11 +1,13 @@(ns metabase-enterprise.sso.api.routes(:require+ [metabase-enterprise.sso.api.oidc][metabase-enterprise.sso.api.saml][metabase-enterprise.sso.api.sso][metabase.api.util.handlers :as handlers]))(comment metabase-enterprise.sso.api.saml/keep-me- metabase-enterprise.sso.api.sso/keep-me)+ metabase-enterprise.sso.api.sso/keep-me+ metabase-enterprise.sso.api.oidc/keep-me);; This needs to be injected into [[metabase.server.routes/routes]] -- not [[metabase.api-routes.core/routes]] !!!;;@@ -20,4 +22,5 @@"Ring routes for auth (SAML) API endpoints."(handlers/route-map-handler{"/auth" {"/sso" 'metabase-enterprise.sso.api.sso}- "/api" {"/saml" 'metabase-enterprise.sso.api.saml}}))+ "/api" {"/saml" 'metabase-enterprise.sso.api.saml+ "/ee" {"/sso" {"/oidc" metabase-enterprise.sso.api.oidc/routes}}}}))diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.cljindex 4117e6b9443..3e46c382ce5 100644--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj@@ -6,6 +6,7 @@(:require[metabase-enterprise.sso.api.interface :as sso.i][metabase-enterprise.sso.integrations.jwt :as jwt]+ [metabase-enterprise.sso.integrations.oidc :as oidc-integration][metabase-enterprise.sso.integrations.saml][metabase-enterprise.sso.integrations.slack-connect][metabase-enterprise.sso.settings :as sso-settings]@@ -149,3 +150,33 @@(catch Throwable e(log/error e "Error handling SLO")(sso-error-page e :out))))++;; Key schema that excludes `/` so /:key does not greedily match /:key/callback+(def ^:private ProviderKey+ [:string {:api/regex #"[a-z0-9][a-z0-9-]*"}])++;; GET /auth/sso/:key+;;+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+(api.macros/defendpoint :get "/:key"+ "Initiate OIDC SSO for a specific provider."+ [{provider-key :key} :- [:map [:key ProviderKey]]+ _query-params _body request]+ (try+ (oidc-integration/sso-initiate provider-key request)+ (catch Throwable e+ (log/error e "Error initiating OIDC SSO")+ (throw e))))++;; GET /auth/sso/:key/callback+;;+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+(api.macros/defendpoint :get "/:key/callback"+ "OIDC callback for a specific provider."+ [{provider-key :key} :- [:map [:key ProviderKey]]+ _query-params _body request]+ (try+ (oidc-integration/sso-callback provider-key request)+ (catch Throwable e+ (log/error e "Error handling OIDC callback")+ (throw e))))diff --git a/enterprise/backend/src/metabase_enterprise/sso/init.clj b/enterprise/backend/src/metabase_enterprise/sso/init.cljindex d527cb0b026..9033444f74a 100644--- a/enterprise/backend/src/metabase_enterprise/sso/init.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/init.clj@@ -2,6 +2,7 @@(:require[metabase-enterprise.sso.integrations.google] ; has a `define-multi-setting` impl[metabase-enterprise.sso.providers.jwt]+ [metabase-enterprise.sso.providers.oidc][metabase-enterprise.sso.providers.saml][metabase-enterprise.sso.providers.slack-connect][metabase-enterprise.sso.settings]))diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/oidc.cljnew file mode 100644index 00000000000..dd518e02923--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/oidc.clj@@ -0,0 +1,97 @@+(ns metabase-enterprise.sso.integrations.oidc+ "Implementation of the generic OIDC SSO backend backed by settings.++ Each OIDC provider has its own pair of endpoints:+ - GET /auth/sso/:key - Initiate OIDC flow+ - GET /auth/sso/:key/callback - Handle OIDC callback++ Flow:+ 1. User accesses GET /auth/sso/:key+ 2. Metabase redirects to provider's authorization endpoint+ 3. User authenticates with the IdP+ 4. IdP redirects back to GET /auth/sso/:key/callback?code=...&state=...+ 5. Metabase exchanges code for tokens and creates session"+ (:require+ [java-time.api :as t]+ [metabase-enterprise.sso.integrations.sso-utils :as sso-utils]+ [metabase-enterprise.sso.settings :as sso-settings]+ [metabase.api.common :as api]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.premium-features.core :as premium-features]+ [metabase.request.core :as request]+ [metabase.sso.core :as sso]+ [metabase.system.core :as system]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log]+ [ring.util.response :as response]))++(set! *warn-on-reflection* true)++(defn- get-redirect-uri+ "Generate the redirect URI for an OIDC provider callback."+ [provider-key]+ (str (system/site-url) "/auth/sso/" provider-key "/callback"))++(defn sso-initiate+ "Initiate the OIDC SSO flow for the given provider key."+ [provider-key request]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))++ (api/check-400 (sso-settings/oidc-enabled?) "OIDC is not enabled")++ (let [provider-config (sso-settings/get-oidc-provider provider-key)]+ (when-not provider-config+ (throw (ex-info (tru "OIDC provider ''{0}'' not found" provider-key)+ {:status-code 404})))+ (when-not (:enabled provider-config)+ (throw (ex-info (tru "OIDC provider ''{0}'' is not enabled" provider-key)+ {:status-code 400}))))++ (let [redirect-url (let [redirect (get-in request [:params :redirect])]+ (if redirect+ (sso-utils/check-sso-redirect redirect)+ "/"))+ auth-result (auth-identity/authenticate+ :provider/custom-oidc+ (assoc request+ :oidc-provider-key provider-key+ :redirect-uri (get-redirect-uri provider-key)+ :final-redirect redirect-url))]+ (if (= :redirect (:success? auth-result))+ (sso/wrap-oidc-redirect auth-result+ request+ (keyword (str "oidc-" provider-key))+ redirect-url+ {:browser-id (:browser-id request)})+ (throw (ex-info (or (:message auth-result) (tru "Failed to initiate OIDC authentication"))+ {:status-code 500})))))++(defn sso-callback+ "Handle the OIDC callback for the given provider key."+ [provider-key {{:keys [code state]} :params, :as request}]+ (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))++ (let [login-result (auth-identity/login!+ :provider/custom-oidc+ (assoc request+ :oidc-provider-key provider-key+ :code code+ :state state+ :oidc-provider (keyword (str "oidc-" provider-key))+ :redirect-uri (get-redirect-uri provider-key)+ :device-info (request/device-info request)))]+ (if (:success? login-result)+ (let [final-redirect (or (:redirect-url login-result) "/")+ base-response (-> (response/redirect final-redirect)+ (sso/clear-oidc-state-cookie))]+ (log/infof "OIDC authentication successful for provider %s, user %s"+ provider-key (get-in login-result [:user :email]))+ (if-let [session (:session login-result)]+ (request/set-session-cookies request+ base-response+ session+ (t/zoned-date-time (t/zone-id "GMT")))+ base-response))+ (let [error-msg (or (:message login-result) (tru "OIDC authentication failed"))]+ (log/errorf "OIDC authentication failed for provider %s: %s" provider-key error-msg)+ (throw (ex-info error-msg {:status-code 401}))))))diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.cljindex 793d163f469..6879b712741 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj@@ -14,7 +14,8 @@(set! *warn-on-reflection* true)-(defn- maybe-throw-user-provisioning+(defn maybe-throw-user-provisioning+ "Throw an error if `user-provisioning-enabled?` is falsey, indicating new user creation is not allowed."[user-provisioning-type](when (not user-provisioning-type)(throw (ex-info (trs "Sorry, but you''ll need a {0} account to view this page. Please contact your administrator."@@ -41,6 +42,10 @@[_](maybe-throw-user-provisioning (sso-settings/slack-connect-user-provisioning-enabled)))+(defmethod check-user-provisioning :oidc+ [_]+ (maybe-throw-user-provisioning (sso-settings/oidc-user-provisioning-enabled?)))+(defn relative-uri?"Checks that given `uri` is not an absolute (so no scheme and no host)."[uri]@@ -70,6 +75,19 @@{:status-code 400:redirect-url redirect-url})))))+(defn group-names->ids+ "Translate a user's group names to a set of Metabase group IDs using the given group mappings."+ [group-names group-mappings]+ (->> (cond-> group-names (string? group-names) vector)+ (map keyword)+ (mapcat group-mappings)+ set))++(defn all-mapped-group-ids+ "Returns the set of all Metabase group IDs that have configured mappings."+ [group-mappings]+ (-> group-mappings vals flatten set))+(defn stringify-valid-attributes"Remove all invalid attributes from passed user attributes, make sure all the remaining keys and values are strings"[attrs]diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.cljindex 46b61ef5145..ec26f8d702b 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj@@ -160,19 +160,9 @@"Translate a user's group names to a set of MB group IDs using the configured mappings"[group-names](if-let [name-mappings (not-empty (sso-settings/jwt-group-mappings))]- (set- (mapcat name-mappings- (map keyword group-names)))+ (sso-utils/group-names->ids group-names name-mappings)(t2/select-pks-set :model/PermissionsGroup :name [:in group-names])))-(defn- all-mapped-group-ids- "Returns the set of all MB group IDs that have configured mappings"- []- (-> (sso-settings/jwt-group-mappings)- vals- flatten- set))-(methodical/defmethod auth-identity/login! :after :provider/jwt"Sync JWT group memberships after successful login.@@ -190,4 +180,4 @@(sso/sync-group-memberships! user (group-names->ids group-names))(sso/sync-group-memberships! user(group-names->ids group-names)- (all-mapped-group-ids)))))))))+ (sso-utils/all-mapped-group-ids (sso-settings/jwt-group-mappings))))))))))diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.cljnew file mode 100644index 00000000000..0ed8a060fc5--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj@@ -0,0 +1,110 @@+(ns metabase-enterprise.sso.providers.oidc+ "Generic OIDC authentication provider backed by the `oidc-providers` setting.+ Derives from the base OIDC provider and adds per-provider configuration and claim extraction."+ (:require+ [metabase-enterprise.sso.integrations.sso-utils :as sso-utils]+ [metabase-enterprise.sso.settings :as sso-settings]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.premium-features.core :as premium-features]+ [metabase.sso.core :as sso]+ [metabase.util.i18n :refer [tru]]+ [methodical.core :as methodical]))++(set! *warn-on-reflection* true)++;;; -------------------------------------------------- Provider Registration --------------------------------------------------++(derive :provider/custom-oidc :provider/oidc)++;;; -------------------------------------------------- Configuration --------------------------------------------------++(defn- build-oidc-config+ "Build OIDC configuration map from provider settings."+ [provider-config request]+ (when (and (:client-id provider-config)+ (:client-secret provider-config)+ (:issuer-uri provider-config))+ (let [attribute-map (:attribute-map provider-config)]+ (cond-> {:client-id (:client-id provider-config)+ :client-secret (:client-secret provider-config)+ :issuer-uri (:issuer-uri provider-config)+ :scopes (or (:scopes provider-config) ["openid" "email" "profile"])+ :redirect-uri (:redirect-uri request)}+ (get attribute-map "email")+ (assoc :attribute-email (get attribute-map "email"))++ (get attribute-map "first_name")+ (assoc :attribute-firstname (get attribute-map "first_name"))++ (get attribute-map "last_name")+ (assoc :attribute-lastname (get attribute-map "last_name"))))))++;;; -------------------------------------------------- Authentication Implementation --------------------------------------------------++(methodical/defmethod auth-identity/authenticate :provider/custom-oidc+ [_provider request]+ (let [provider-key (:oidc-provider-key request)]+ (cond+ (not (premium-features/enable-sso-oidc?))+ {:success? false+ :error :feature-not-available+ :message (tru "OIDC authentication is not available on your plan")}++ (not provider-key)+ {:success? false+ :error :missing-provider+ :message (tru "OIDC provider key is required")}++ :else+ (let [provider-config (sso-settings/get-oidc-provider provider-key)]+ (cond+ (not provider-config)+ {:success? false+ :error :provider-not-found+ :message (tru "OIDC provider ''{0}'' not found" provider-key)}++ (not (:enabled provider-config))+ {:success? false+ :error :provider-not-enabled+ :message (tru "OIDC provider ''{0}'' is not enabled" provider-key)}++ :else+ (let [oidc-config (build-oidc-config provider-config request)]+ (if-not oidc-config+ {:success? false+ :error :configuration-error+ :message (tru "Failed to build OIDC configuration for provider ''{0}''" provider-key)}++ (let [auth-result (next-method _provider (assoc request :oidc-config oidc-config))]+ (if (and (:success? auth-result)+ (:user-data auth-result))+ (assoc-in auth-result [:user-data :sso_source] :oidc)+ auth-result)))))))))++;;; -------------------------------------------------- Login Implementation --------------------------------------------------++(methodical/defmethod auth-identity/login! :provider/custom-oidc+ [provider {:keys [user] :as request}]+ (when-not user+ (sso-utils/check-user-provisioning :oidc))+ (next-method provider request))++(methodical/defmethod auth-identity/login! :after :provider/custom-oidc+ [_provider result]+ ;; Handle group sync if configured+ (when-let [provider-key (:oidc-provider-key result)]+ (when-let [provider-config (sso-settings/get-oidc-provider provider-key)]+ (when (get-in provider-config [:group-sync :enabled])+ (let [group-attribute (get-in provider-config [:group-sync :group-attribute])+ group-mappings (get-in provider-config [:group-sync :group-mappings])+ claims (:claims result)+ user-groups (when (and claims group-attribute)+ (get claims (keyword group-attribute)))]+ (when (and user-groups group-mappings (:user result))+ (let [groups-to-sync (if (sequential? user-groups) user-groups [user-groups])]+ (if (empty? group-mappings)+ (sso/sync-group-memberships! (:user result) (sso-utils/group-names->ids groups-to-sync group-mappings))+ (sso/sync-group-memberships! (:user result)+ (sso-utils/group-names->ids groups-to-sync group-mappings)+ (sso-utils/all-mapped-group-ids group-mappings)))))))))+ result)diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.cljindex 6be6b046b08..3690b0f0cea 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj@@ -172,22 +172,6 @@(assoc-in [:user-data :is_active] true)(assoc :user-provisioning-enabled? provisioning-enabled?))))))-(defn- group-names->ids- "Translate a user's group names to a set of MB group IDs using the configured mappings"- [group-names]- (->> (cond-> group-names (string? group-names) vector)- (map keyword)- (mapcat (sso-settings/saml-group-mappings))- set))--(defn- all-mapped-group-ids- "Returns the set of all MB group IDs that have configured mappings"- []- (-> (sso-settings/saml-group-mappings)- vals- flatten- set))-(methodical/defmethod auth-identity/login! :after :provider/saml"Sync SAML group memberships after successful login.@@ -201,5 +185,5 @@(when (sso-settings/saml-group-sync)(when-let [group-names (:group-names saml-data)](sso/sync-group-memberships! user- (group-names->ids group-names)- (all-mapped-group-ids)))))))+ (sso-utils/group-names->ids group-names (sso-settings/saml-group-mappings))+ (sso-utils/all-mapped-group-ids (sso-settings/saml-group-mappings))))))))diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.cljindex 0bfd2b794c3..3bd898de300 100644--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj@@ -7,6 +7,7 @@[metabase-enterprise.scim.core :as scim][metabase.appearance.core :as appearance][metabase.settings.core :as setting :refer [define-multi-setting-impl defsetting]]+ [metabase.system.core :as system][metabase.util.i18n :refer [deferred-tru tru]][metabase.util.log :as log][metabase.util.malli :as mu]@@ -429,8 +430,79 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e(setting/get-value-of-type :boolean :slack-connect-enabled)false)))+;;; ------------------------------------------------ OIDC (Custom) ------------------------------------------------++(defsetting oidc-providers+ (deferred-tru "JSON containing OIDC provider configurations.")+ :encryption :when-encryption-key-set+ :type :json+ :default []+ :feature :sso-oidc+ :visibility :settings-manager+ :export? false+ :audit :no-value+ :sensitive? true)++(defn get-oidc-provider+ "Look up an OIDC provider by key from the `oidc-providers` setting."+ [provider-key]+ (some (fn [provider]+ (when (= (:key provider) provider-key)+ provider))+ (oidc-providers)))++(defsetting oidc-configured?+ (deferred-tru "Are any OIDC providers configured with required fields?")+ :type :boolean+ :default false+ :feature :sso-oidc+ :setter :none+ :getter (fn [] (boolean+ (some (fn [p]+ (and (:issuer-uri p)+ (:client-id p)+ (:client-secret p)))+ (oidc-providers))))+ :export? false)++(defsetting oidc-enabled?+ (deferred-tru "Is any OIDC provider enabled?")+ :type :boolean+ :default false+ :feature :sso-oidc+ :setter :none+ :getter (fn [] (boolean (seq (filter :enabled (oidc-providers)))))+ :export? false)++(defsetting oidc-login-providers+ (deferred-tru "Public-facing list of enabled OIDC providers for the login page.")+ :type :json+ :default []+ :feature :sso-oidc+ :visibility :public+ :setter :none+ :getter (fn []+ (let [base-url (str (system/site-url) "/auth/sso/")]+ (into []+ (comp (filter :enabled)+ (map (fn [p]+ {:type "oidc"+ :key (:key p)+ :login-prompt (:login-prompt p)+ :sso-url (str base-url (:key p))})))+ (oidc-providers))))+ :export? false)++(defsetting oidc-user-provisioning-enabled?+ (deferred-tru "When a user logs in via OIDC, create a Metabase account for them automatically if they don''t have one.")+ :type :boolean+ :default true+ :feature :sso-oidc+ :export? false+ :audit :getter)+(defsetting other-sso-enabled?- "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for+ "Are we using an SSO integration other than LDAP or Google Auth or ODIC? These integrations use the `/auth/sso` endpoint forauthorization rather than the normal login form or Google Auth button.":visibility :public:setter :nonediff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.cljindex fad7387bae2..ac6a91e6b83 100644--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj@@ -46,6 +46,7 @@:sso-google:sso-jwt:sso-ldap+ :sso-oidc:sso-saml:sso-slack:support-users@@ -94,6 +95,7 @@:sso_google true:sso_jwt true:sso_ldap true+ :sso_oidc true:sso_saml true:sso_slack true:support-users truediff --git a/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.cljnew file mode 100644index 00000000000..3f3979127d8--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj@@ -0,0 +1,124 @@+(ns metabase-enterprise.sso.api.oidc-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.sso.settings :as sso-settings]+ [metabase.sso.oidc.check :as oidc.check]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :test-users))++(def ^:private test-provider+ {:key "test-okta"+ :login-prompt "Test Okta"+ :issuer-uri "https://test.okta.com"+ :client-id "test-client-id"+ :client-secret "test-client-secret"+ :scopes ["openid" "email" "profile"]+ :enabled false})++(def ^:private successful-check-result+ {:ok true+ :discovery {:step :discovery :success true :token-endpoint "https://test.okta.com/oauth2/token"}+ :credentials {:step :credentials :success true :verified false}})++(deftest crud-requires-superuser-test+ (testing "OIDC provider CRUD endpoints require superuser"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers []]+ (testing "GET / requires superuser"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "ee/sso/oidc"))))+ (testing "POST / requires superuser"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "ee/sso/oidc" test-provider))))+ (testing "PUT /:key requires superuser"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 "ee/sso/oidc/test-okta"+ {:login-prompt "Updated"}))))+ (testing "DELETE /:key requires superuser"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :delete 403 "ee/sso/oidc/test-okta"))))))))++(deftest create-provider-test+ (testing "Creating an OIDC provider"+ (mt/with-additional-premium-features #{:sso-oidc}+ (with-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]+ (mt/with-temporary-setting-values [oidc-providers []]+ (testing "successfully creates provider"+ (let [result (mt/user-http-request :crowberto :post 200 "ee/sso/oidc" test-provider)]+ (is (= "test-okta" (:key result)))+ (is (= "Test Okta" (:login-prompt result)))+ (is (= "**********et" (:client-secret result)))+ (is (= 1 (count (sso-settings/oidc-providers))))))++ (testing "rejects duplicate key"+ (is (= "An OIDC provider with key 'test-okta' already exists"+ (mt/user-http-request :crowberto :post 400 "ee/sso/oidc" test-provider))))++ (testing "rejects invalid key"+ (is (mt/user-http-request :crowberto :post 400 "ee/sso/oidc"+ (assoc test-provider :key "INVALID SLUG!")))))))))++(deftest read-providers-test+ (testing "Reading OIDC providers"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (testing "lists all providers with masked secrets"+ (let [result (mt/user-http-request :crowberto :get 200 "ee/sso/oidc")]+ (is (= 1 (count result)))+ (is (= "**********et" (:client-secret (first result))))))++ (testing "gets single provider with masked secret"+ (let [result (mt/user-http-request :crowberto :get 200 "ee/sso/oidc/test-okta")]+ (is (= "test-okta" (:key result)))+ (is (= "**********et" (:client-secret result)))))++ (testing "returns 404 for missing provider"+ (is (mt/user-http-request :crowberto :get 404 "ee/sso/oidc/nonexistent")))))))++(deftest update-provider-test+ (testing "Updating an OIDC provider"+ (mt/with-additional-premium-features #{:sso-oidc}+ (with-redefs [oidc.check/check-oidc-configuration (constantly successful-check-result)]+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (testing "successfully updates login prompt"+ (let [result (mt/user-http-request :crowberto :put 200 "ee/sso/oidc/test-okta"+ {:login-prompt "Updated Okta"})]+ (is (= "Updated Okta" (:login-prompt result)))))++ (testing "preserves client secret when masked value is sent"+ (let [result (mt/user-http-request :crowberto :put 200 "ee/sso/oidc/test-okta"+ {:client-secret "**********et"})+ stored (sso-settings/get-oidc-provider "test-okta")]+ (is (= "**********et" (:client-secret result)))+ (is (= "test-client-secret" (:client-secret stored)))))++ (testing "returns 404 for missing provider"+ (is (mt/user-http-request :crowberto :put 404 "ee/sso/oidc/nonexistent"+ {:login-prompt "Updated"}))))))))++(deftest delete-provider-test+ (testing "Deleting an OIDC provider"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (testing "successfully deletes provider"+ (mt/user-http-request :crowberto :delete 204 "ee/sso/oidc/test-okta")+ (is (= 0 (count (sso-settings/oidc-providers)))))))))++(deftest settings-test+ (testing "OIDC computed settings"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers []]+ (testing "oidc-enabled is false with no providers"+ (is (false? (sso-settings/oidc-enabled?)))))++ (mt/with-temporary-setting-values [oidc-providers [(assoc test-provider :enabled true)]]+ (testing "oidc-configured is true when provider has required fields"+ (is (true? (sso-settings/oidc-enabled?)))))++ (mt/with-temporary-setting-values [oidc-providers [(assoc test-provider :enabled false)]]+ (testing "oidc-enabled is false when no provider is enabled"+ (is (false? (sso-settings/oidc-enabled?))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.cljnew file mode 100644index 00000000000..b78a824a3e7--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj@@ -0,0 +1,185 @@+(ns metabase-enterprise.sso.integrations.oidc-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase-enterprise.sso.test-setup :as sso.test-setup]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.config.core :as config]+ [metabase.sso.oidc.state :as oidc.state]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [metabase.util.encryption :as encryption]+ [methodical.core :as methodical]+ [ring.util.codec :as codec]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :test-users))++(def ^:private test-encryption-key+ "Test encryption key for OIDC state encryption."+ "Orw0AAyzkO/kPTLJRxiyKoBHXa/d6ZcO+p+gpZO/wSQ=")++(def ^:private test-secret+ "Hashed test encryption key."+ (encryption/secret-key->hash test-encryption-key))++(defmacro ^:private with-ensure-encryption!+ "Ensures an encryption key is available for OIDC state operations.+ Uses the existing encryption key if one is configured, otherwise+ sets a test key. This avoids conflicts with encrypted settings+ in the DB that were written with the real key."+ [& body]+ `(if (encryption/default-encryption-enabled?)+ (do ~@body)+ (with-redefs [encryption/default-secret-key test-secret]+ ~@body)))++(defn- do-with-url-prefix-disabled+ "Test fixture that disables API URL prefix."+ [thunk]+ (binding [client/*url-prefix* ""]+ (thunk)))++(use-fixtures :each do-with-url-prefix-disabled)++(def ^:private test-provider+ {:key "test-idp"+ :login-prompt "Test IdP"+ :issuer-uri "https://test.idp.example.com"+ :client-id "test-client-id"+ :client-secret "test-client-secret"+ :scopes ["openid" "email" "profile"]+ :enabled true})++;; Mock OIDC authentication for tests+(methodical/defmethod auth-identity/authenticate :provider/test-oidc-successful+ [_provider request]+ (if (some #(contains? request %) [:code :error :state])+ {:success? true+ :claims {}+ :user-data {:email "[email protected]"}+ :provider-id "test-oidc-provider-id"}+ {:success? :redirect+ :redirect-url "https://test.idp.example.com/authorize"+ :state "test-state"+ :nonce "test-nonce"}))++(methodical/prefer-method! #'auth-identity/authenticate :provider/test-oidc-successful :provider/oidc)++(defmacro ^:private with-successful-oidc! [& body]+ `(do+ (derive :provider/custom-oidc :provider/test-oidc-successful)+ (try+ ~@body+ (finally+ (underive :provider/custom-oidc :provider/test-oidc-successful)))))++(defmacro ^:private with-oidc-default-setup! [& body]+ `(mt/test-helpers-set-global-values!+ (mt/with-premium-features #{:audit-app}+ (sso.test-setup/do-with-other-sso-types-disabled!+ (fn []+ (mt/with-additional-premium-features #{:sso-oidc}+ (sso.test-setup/call-with-login-attributes-cleared!+ (fn []+ (mt/with-temporary-setting-values+ [oidc-providers [test-provider]+ site-url (format "http://localhost:%s" (config/config-str :mb-jetty-port))]+ ~@body)))))))))++;;; -------------------------------------------------- Prerequisites Tests --------------------------------------------------++(deftest provider-not-found-test+ (testing "SSO requests fail if provider key doesn't exist"+ (with-oidc-default-setup!+ (with-ensure-encryption!+ (with-successful-oidc!+ (let [response (mt/client-full-response :get 404 "/auth/sso/nonexistent"+ {:request-options {:redirect-strategy :none}})]+ (is (= 404 (:status response)))))))))++(deftest provider-not-enabled-test+ (testing "SSO requests fail if provider is not enabled"+ (mt/test-helpers-set-global-values!+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values+ [oidc-providers [(assoc test-provider :enabled false)]+ site-url (format "http://localhost:%s" (config/config-str :mb-jetty-port))]+ (with-ensure-encryption!+ (with-successful-oidc!+ (let [response (mt/client-full-response :get 400 "/auth/sso/test-idp"+ {:request-options {:redirect-strategy :none}})]+ (is (= 400 (:status response)))))))))))++;;; -------------------------------------------------- Redirect Tests --------------------------------------------------++(deftest redirect-test+ (testing "with OIDC provider configured, GET /auth/sso/:key redirects to IdP"+ (with-oidc-default-setup!+ (with-ensure-encryption!+ (with-successful-oidc!+ (let [result (mt/client-full-response :get 302 "/auth/sso/test-idp"+ {:request-options {:redirect-strategy :none}}+ :redirect "/")+ redirect-url (get-in result [:headers "Location"])+ oidc-state-cookie (->> (get-in result [:headers "Set-Cookie"])+ (filter #(str/includes? % "metabase.OIDC_STATE"))+ first)]+ (is (str/starts-with? redirect-url "https://test.idp.example.com/authorize"))+ (testing "OIDC state is stored in encrypted cookie"+ (is (some? oidc-state-cookie))+ (let [cookie-value (second (re-find #"metabase\.OIDC_STATE=([^;]+)" oidc-state-cookie))]+ (is (some? cookie-value))+ (let [state-data (oidc.state/decrypt-state (codec/url-decode cookie-value))]+ (is (= "test-state" (:state state-data)))+ (is (= "test-nonce" (:nonce state-data)))+ (is (= "/" (:redirect state-data))))))))))))++;;; -------------------------------------------------- Callback Tests --------------------------------------------------++(deftest callback-missing-state-cookie-test+ (testing "callback fails if state cookie is missing"+ (with-oidc-default-setup!+ (with-ensure-encryption!+ (let [response (mt/client-full-response :get 401 "/auth/sso/test-idp/callback"+ {:request-options {:redirect-strategy :none}}+ :code "test-code"+ :state "some-state")]+ (is (str/includes? (:body response) "OIDC state cookie is invalid, expired, or missing")))))))++(deftest happy-path-callback-test+ (testing "successful callback with valid code and state creates session"+ (with-oidc-default-setup!+ (with-ensure-encryption!+ (with-successful-oidc!+ ;; Initiate auth to set state cookie+ (let [init-response (mt/client-full-response :get 302 "/auth/sso/test-idp"+ {:request-options {:redirect-strategy :none}}+ :redirect "/")+ set-cookies (get-in init-response [:headers "Set-Cookie"])+ cookie-header (->> set-cookies+ (map #(first (str/split % #";")))+ (str/join "; "))+ response (mt/client-real-response :get 302 "/auth/sso/test-idp/callback"+ {:request-options {:redirect-strategy :none+ :headers {"Cookie" cookie-header}}}+ :code "test-code"+ :state "test-state")]+ (is (sso.test-setup/successful-login? response))+ (is (= "/" (get-in response [:headers "Location"])))))))))++;;; -------------------------------------------------- Open Redirect Protection Tests --------------------------------------------------++(deftest no-open-redirect-test+ (testing "Check that we prevent open redirects to untrusted sites"+ (with-oidc-default-setup!+ (with-ensure-encryption!+ (with-successful-oidc!+ (doseq [redirect-uri ["https://badsite.com"+ "//badsite.com"]]+ (is (= 400+ (:status (mt/client-full-response :get 400 "/auth/sso/test-idp"+ {:request-options {:redirect-strategy :none}}+ :redirect redirect-uri))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj b/enterprise/backend/test/metabase_enterprise/sso/test_setup.cljindex 50610022cbc..72268bb6696 100644--- a/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj@@ -140,6 +140,42 @@(mt/with-premium-features current-features(f))))))+;;; -------------------------------------------------- OIDC (Generic) Setup --------------------------------------------------++(def ^:private default-oidc-provider+ {:key "test-idp"+ :login-prompt "Test IdP"+ :issuer-uri "https://test.idp.example.com"+ :client-id "test-client-id"+ :client-secret "test-client-secret"+ :scopes ["openid" "email" "profile"]+ :enabled true})++(defn call-with-default-oidc-config!+ "Execute `f` with default OIDC configuration set up."+ [f]+ (let [current-features (token-check/*token-features*)]+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values+ [oidc-providers [default-oidc-provider]+ site-url (format "http://localhost:%s" (config/config-str :mb-jetty-port))]+ (mt/with-premium-features current-features+ (f))))))++(defmacro with-oidc-default-setup!+ "Set up default OIDC configuration for tests."+ [& body]+ `(mt/test-helpers-set-global-values!+ (mt/with-premium-features #{:audit-app}+ (do-with-other-sso-types-disabled!+ (fn []+ (mt/with-additional-premium-features #{:sso-oidc}+ (call-with-login-attributes-cleared!+ (fn []+ (call-with-default-oidc-config!+ (fn []+ ~@body))))))))))+(defmacro with-slack-default-setup!"Set up default Slack Connect configuration for tests.Includes premium features, other SSO types disabled, login attributes cleanup, and default Slack config."diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.tsindex 6f8e0ce4579..f8bb044e0b2 100644--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts@@ -10,6 +10,7 @@ export * from "./gdrive";export * from "./library";export * from "./metabot";export * from "./remote-sync";+export * from "./oidc";export * from "./saml";export * from "./scim";export * from "./support-access-grants";diff --git a/enterprise/frontend/src/metabase-enterprise/api/oidc.ts b/enterprise/frontend/src/metabase-enterprise/api/oidc.tsnew file mode 100644index 00000000000..c859bf297f0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/api/oidc.ts@@ -0,0 +1,104 @@+import { invalidateTags, tag } from "metabase/api/tags";++import { EnterpriseApi } from "./api";++export interface OidcCheckRequest {+ "issuer-uri": string;+ "client-id": string;+ "client-secret"?: string | null;+ key?: string | null;+}++export interface OidcCheckStepResult {+ step: string;+ success: boolean;+ verified?: boolean;+ error?: string;+ "token-endpoint"?: string;+}++export interface OidcCheckResponse {+ ok: boolean;+ discovery: OidcCheckStepResult;+ credentials?: OidcCheckStepResult;+}++export interface CustomOidcConfig {+ key: string;+ "login-prompt": string;+ "issuer-uri": string;+ "client-id": string;+ "client-secret"?: string;+ scopes?: string[];+ enabled?: boolean;+ "attribute-map"?: Record<string, string>;+ "group-sync"?: {+ enabled?: boolean;+ "group-attribute"?: string;+ "group-mappings"?: Record<string, number[]>;+ };+}++export const customOidcApi = EnterpriseApi.injectEndpoints({+ endpoints: (builder) => ({+ getCustomOidcProviders: builder.query<CustomOidcConfig[], void>({+ query: () => ({+ method: "GET",+ url: "/api/ee/sso/oidc",+ }),+ providesTags: ["session-properties"],+ }),+ getCustomOidcProvider: builder.query<CustomOidcConfig, string>({+ query: (key) => ({+ method: "GET",+ url: `/api/ee/sso/oidc/${key}`,+ }),+ providesTags: ["session-properties"],+ }),+ createCustomOidc: builder.mutation<CustomOidcConfig, CustomOidcConfig>({+ query: (provider) => ({+ method: "POST",+ url: "/api/ee/sso/oidc",+ body: provider,+ }),+ invalidatesTags: (_, error) =>+ invalidateTags(error, [tag("session-properties")]),+ }),+ updateCustomOidc: builder.mutation<+ CustomOidcConfig,+ { key: string; provider: Partial<CustomOidcConfig> }+ >({+ query: ({ key, provider }) => ({+ method: "PUT",+ url: `/api/ee/sso/oidc/${key}`,+ body: provider,+ }),+ invalidatesTags: (_, error) =>+ invalidateTags(error, [tag("session-properties")]),+ }),+ deleteCustomOidc: builder.mutation<void, string>({+ query: (key) => ({+ method: "DELETE",+ url: `/api/ee/sso/oidc/${key}`,+ }),+ invalidatesTags: (_, error) =>+ invalidateTags(error, [tag("session-properties")]),+ }),+ checkOidcConnection: builder.mutation<OidcCheckResponse, OidcCheckRequest>({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/sso/oidc/check",+ body,+ }),+ }),+ }),+});++export const {+ useGetCustomOidcProvidersQuery,+ useGetCustomOidcProviderQuery,+ useCreateCustomOidcMutation,+ useUpdateCustomOidcMutation,+ useDeleteCustomOidcMutation,+ useCheckOidcConnectionMutation,+} = customOidcApi;diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsxindex 735e65c4794..f2eb5874915 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/AuthSettingsPage.tsx@@ -15,6 +15,7 @@ import {} from "metabase/plugins";import { JwtAuthCard } from "../containers/JwtAuthCard";+import { OidcAuthCard } from "../containers/OidcAuthCard";import { SamlAuthCard } from "../containers/SamlAuthCard";import { useHasSsoEnabled } from "../utils";@@ -43,6 +44,7 @@ function AuthenticationTab() {<LdapAuthCard /><SamlAuthCard /><JwtAuthCard />+ <OidcAuthCard /><SettingsSection><AdminSettingInputdiff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsxnew file mode 100644index 00000000000..85d5780aa01--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/OidcButton/OidcButton.tsx@@ -0,0 +1,50 @@+import { useCallback } from "react";++import { AuthButton } from "metabase/auth/components/AuthButton";+import type { AuthProvider } from "metabase/plugins/types";+import type { OidcAuthProvider } from "metabase-types/api";++interface OidcButtonProps {+ provider: OidcAuthProvider;+ isCard?: boolean;+ redirectUrl?: string;+}++export const OidcButton = ({+ provider,+ isCard,+ redirectUrl,+}: OidcButtonProps): JSX.Element => {+ const handleLogin = useCallback(() => {+ const ssoUrl = provider["sso-url"];+ const url = redirectUrl+ ? `${ssoUrl}?redirect=${encodeURIComponent(redirectUrl)}`+ : ssoUrl;+ window.location.href = url;+ }, [provider, redirectUrl]);++ return (+ <AuthButton isCard={isCard} onClick={handleLogin}>+ {provider["login-prompt"]}+ </AuthButton>+ );+};++/**+ * Create an AuthProvider entry for an OIDC provider.+ * This keeps JSX inside the .tsx file so it can be called from .ts modules.+ */+export function createOidcAuthProvider(+ oidcProvider: OidcAuthProvider,+): AuthProvider {+ return {+ name: `oidc-${oidcProvider.key}`,+ Button: ({ isCard, redirectUrl }) => (+ <OidcButton+ provider={oidcProvider}+ isCard={isCard}+ redirectUrl={redirectUrl}+ />+ ),+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsxnew file mode 100644index 00000000000..9eb655dceef--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx@@ -0,0 +1,418 @@+import { useDisclosure } from "@mantine/hooks";+import { useCallback, useMemo } from "react";+import { t } from "ttag";+import * as Yup from "yup";++import {+ SettingsPageWrapper,+ SettingsSection,+} from "metabase/admin/components/SettingsSection";+import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";+import { getErrorMessage } from "metabase/api/utils/errors";+import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSetting, useToast } from "metabase/common/hooks";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSection,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import { useSelector } from "metabase/lib/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import { Button, Flex, Stack, Text } from "metabase/ui";+import {+ type CustomOidcConfig,+ type OidcCheckRequest,+ useCheckOidcConnectionMutation,+ useCreateCustomOidcMutation,+ useDeleteCustomOidcMutation,+ useGetCustomOidcProvidersQuery,+ useUpdateCustomOidcMutation,+} from "metabase-enterprise/api";++function getOidcFormSchema() {+ return Yup.object({+ "login-prompt": Yup.string().required(t`Login prompt is required`),+ key: Yup.string()+ .required(t`Key is required`)+ .matches(+ /^[a-z0-9][a-z0-9-]*$/,+ t`Must be lowercase letters, numbers, and hyphens only`,+ ),+ "issuer-uri": Yup.string().required(t`Issuer URI is required`),+ "client-id": Yup.string().required(t`Client ID is required`),+ "client-secret": Yup.string().nullable().default(null),+ scopes: Yup.string().nullable().default("openid, email, profile"),+ "attribute-email": Yup.string().nullable().default("email"),+ "attribute-firstname": Yup.string().nullable().default("given_name"),+ "attribute-lastname": Yup.string().nullable().default("family_name"),+ });+}++interface OIDCFormValues {+ "login-prompt": string;+ key: string;+ "issuer-uri": string;+ "client-id": string;+ "client-secret": string | null;+ scopes: string | null;+ "attribute-email": string | null;+ "attribute-firstname": string | null;+ "attribute-lastname": string | null;+}++function providerToFormValues(+ provider: CustomOidcConfig | null,+): OIDCFormValues {+ if (!provider) {+ return {+ "login-prompt": "",+ key: "",+ "issuer-uri": "",+ "client-id": "",+ "client-secret": null,+ scopes: "openid, email, profile",+ "attribute-email": "email",+ "attribute-firstname": "given_name",+ "attribute-lastname": "family_name",+ };+ }++ const attributeMap = provider["attribute-map"] ?? {};++ return {+ "login-prompt": provider["login-prompt"] ?? "",+ key: provider.key ?? "",+ "issuer-uri": provider["issuer-uri"] ?? "",+ "client-id": provider["client-id"] ?? "",+ "client-secret": null,+ scopes: (provider.scopes ?? ["openid", "email", "profile"]).join(", "),+ "attribute-email": attributeMap["email"] ?? "email",+ "attribute-firstname": attributeMap["first_name"] ?? "given_name",+ "attribute-lastname": attributeMap["last_name"] ?? "family_name",+ };+}++function formValuesToProvider(+ values: OIDCFormValues,+): Partial<CustomOidcConfig> {+ const scopes = values.scopes+ ? values.scopes+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean)+ : ["openid", "email", "profile"];++ const attributeMap: Record<string, string> = {};+ if (values["attribute-email"]) {+ attributeMap["email"] = values["attribute-email"];+ }+ if (values["attribute-firstname"]) {+ attributeMap["first_name"] = values["attribute-firstname"];+ }+ if (values["attribute-lastname"]) {+ attributeMap["last_name"] = values["attribute-lastname"];+ }++ const provider: Partial<CustomOidcConfig> = {+ key: values.key,+ "login-prompt": values["login-prompt"],+ "issuer-uri": values["issuer-uri"],+ "client-id": values["client-id"],+ scopes,+ enabled: true,+ "attribute-map": attributeMap,+ };++ if (values["client-secret"]) {+ provider["client-secret"] = values["client-secret"];+ }++ return provider;+}++export function SettingsOIDCForm() {+ const applicationName = useSelector(getApplicationName);+ const siteUrl = useSetting("site-url");+ const { data: providers, isLoading } = useGetCustomOidcProvidersQuery();+ const [createProvider] = useCreateCustomOidcMutation();+ const [updateProvider] = useUpdateCustomOidcMutation();+ const [deleteProvider] = useDeleteCustomOidcMutation();+ const [checkConnection, { isLoading: isChecking }] =+ useCheckOidcConnectionMutation();+ const [sendToast] = useToast();++ const existingProvider =+ providers && providers.length > 0 ? providers[0] : null;+ const isExisting = existingProvider !== null;+ const isEnabled = existingProvider?.enabled ?? false;++ const initialValues = useMemo(+ () => providerToFormValues(existingProvider),+ [existingProvider],+ );++ const runCheck = useCallback(+ async (values: OIDCFormValues) => {+ const req: OidcCheckRequest = {+ "issuer-uri": values["issuer-uri"],+ "client-id": values["client-id"],+ };+ if (values["client-secret"]) {+ req["client-secret"] = values["client-secret"];+ } else if (isExisting && existingProvider) {+ req.key = existingProvider.key;+ }+ return await checkConnection(req).unwrap();+ },+ [checkConnection, isExisting, existingProvider],+ );++ const handleCheckConnection = useCallback(+ async (values: OIDCFormValues) => {+ try {+ const result = await runCheck(values);+ if (result.credentials?.verified === false) {+ sendToast({+ message: t`OIDC discovery succeeded, but credentials could not be verified. The identity provider does not support the grant type used for testing.`,+ icon: "warning",+ });+ } else {+ sendToast({+ message: t`OIDC connection is valid`,+ icon: "check",+ });+ }+ } catch (error) {+ sendToast({+ message: getErrorMessage(error, t`OIDC configuration check failed`),+ icon: "warning",+ });+ }+ },+ [runCheck, sendToast],+ );++ const handleSubmit = useCallback(+ async (values: OIDCFormValues) => {+ // Run the connection check before saving — will throw on failure+ await runCheck(values);++ const providerData = formValuesToProvider(values);++ if (isExisting && existingProvider) {+ const { key: _key, ...updateData } = providerData;+ await updateProvider({+ key: existingProvider.key,+ provider: updateData,+ }).unwrap();+ } else {+ await createProvider(providerData as CustomOidcConfig).unwrap();+ }+ },+ [isExisting, existingProvider, createProvider, updateProvider, runCheck],+ );++ const handleToggleEnabled = useCallback(async () => {+ if (!existingProvider) {+ return;+ }+ try {+ await updateProvider({+ key: existingProvider.key,+ provider: { enabled: !isEnabled },+ }).unwrap();+ sendToast({+ message: isEnabled+ ? t`OIDC provider disabled`+ : t`OIDC provider enabled`,+ icon: "check",+ });+ } catch {+ sendToast({+ message: t`Failed to update OIDC provider`,+ icon: "warning",+ });+ }+ }, [existingProvider, isEnabled, updateProvider, sendToast]);++ const [isDeleteModalOpen, deleteModal] = useDisclosure(false);++ const handleDelete = useCallback(async () => {+ if (!existingProvider) {+ return;+ }+ try {+ await deleteProvider(existingProvider.key).unwrap();+ sendToast({+ message: t`OIDC provider deleted`,+ icon: "check",+ });+ } catch (error) {+ sendToast({+ message: t`Failed to delete OIDC provider`,+ icon: "warning",+ });+ } finally {+ deleteModal.close();+ }+ }, [existingProvider, deleteProvider, sendToast, deleteModal]);++ if (isLoading) {+ return <LoadingAndErrorWrapper loading />;+ }++ return (+ <SettingsPageWrapper title={t`OpenID Connect`}>+ <Stack gap="lg">+ <SettingsSection>+ <AdminSettingInput+ name="oidc-user-provisioning-enabled?"+ title={t`User provisioning`}+ inputType="boolean"+ />+ </SettingsSection>++ <FormProvider+ initialValues={initialValues}+ onSubmit={handleSubmit}+ validationSchema={getOidcFormSchema()}+ enableReinitialize+ >+ {({ dirty, values }) => (+ <Form>+ <SettingsSection>+ <FormSection title={t`Server settings`}>+ <Stack gap="md">+ <FormTextInput+ name="key"+ label={t`Key`}+ description={t`Provider identifier. Your OIDC redirect URI will be "${siteUrl}/auth/sso/${values.key || "{key}"}/callback"`}+ placeholder={t`e.g. okta`}+ required+ disabled={isExisting}+ />+ <FormTextInput+ name="login-prompt"+ label={t`Login prompt`}+ description={t`Button text on the ${applicationName} sign-in screen`}+ placeholder={t`e.g. Sign in with Okta`}+ required+ />+ <FormTextInput+ name="issuer-uri"+ label={t`Issuer URI`}+ description={t`The OIDC issuer URI. The discovery endpoint "${(values["issuer-uri"] || "{url}").replace(/\/+$/, "")}/.well-known/openid-configuration" should be accessible.`}+ placeholder="https://your-idp.example.com"+ required+ />+ <FormTextInput+ name="client-id"+ label={t`Client ID`}+ description={t`The Client ID configured for ${applicationName} in your OIDC provider.`}+ required+ />+ <FormTextInput+ name="client-secret"+ label={t`Client Secret`}+ description={t`The Client secret configured in your OIDC provider.`}+ type="password"+ placeholder={+ isExisting ? t`Leave blank to keep current value` : ""+ }+ />+ </Stack>+ </FormSection>++ <FormSection title={t`Optional settings`} collapsible>+ <Stack gap="md">+ <FormTextInput+ name="scopes"+ label={t`Scopes`}+ description={t`Comma-separated list of OIDC scopes to request.`}+ nullable+ />+ </Stack>+ </FormSection>++ <FormSection title={t`Attribute mapping`} collapsible>+ <Text c="text-secondary" mb="md">+ {t`Map OIDC claims to user attributes. Use standard OIDC claim names or your provider's custom claims.`}+ </Text>+ <Stack gap="md">+ <FormTextInput+ name="attribute-email"+ label={t`Email attribute`}+ nullable+ />+ <FormTextInput+ name="attribute-firstname"+ label={t`First name attribute`}+ nullable+ />+ <FormTextInput+ name="attribute-lastname"+ label={t`Last name attribute`}+ nullable+ />+ </Stack>+ </FormSection>++ <FormErrorMessage />+ <Flex justify="space-between">+ {isExisting ? (+ <>+ <Flex gap="md">+ <Button variant="outline" onClick={handleToggleEnabled}>+ {isEnabled ? t`Disable` : t`Enable`}+ </Button>+ <Button+ variant="filled"+ color="danger"+ onClick={deleteModal.open}+ >+ {t`Delete configuration`}+ </Button>+ </Flex>+ <ConfirmModal+ opened={isDeleteModalOpen}+ title={t`Delete this OIDC provider?`}+ message={t`Users will no longer be able to sign in with this provider. This can't be undone.`}+ onClose={deleteModal.close}+ onConfirm={handleDelete}+ />+ </>+ ) : (+ <span />+ )}+ <Flex gap="md">+ <Button+ variant="outline"+ loading={isChecking}+ disabled={!values["issuer-uri"] || !values["client-id"]}+ onClick={() => handleCheckConnection(values)}+ >+ {t`Check connection`}+ </Button>+ <FormSubmitButton+ disabled={!dirty}+ label={+ isExisting && isEnabled+ ? t`Save changes`+ : t`Save and enable`+ }+ variant="filled"+ />+ </Flex>+ </Flex>+ </SettingsSection>+ </Form>+ )}+ </FormProvider>+ </Stack>+ </SettingsPageWrapper>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/index.tsnew file mode 100644index 00000000000..0d184e79894--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/index.ts@@ -0,0 +1 @@+export * from "./SettingsOIDCForm";diff --git a/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/OidcAuthCard.tsx b/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/OidcAuthCard.tsxnew file mode 100644index 00000000000..77e303f85aa--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/OidcAuthCard.tsx@@ -0,0 +1,81 @@+import { useCallback } from "react";+import { t } from "ttag";++import { AuthCard } from "metabase/admin/settings/auth/components/AuthCard";+import { useAdminSetting } from "metabase/api/utils";+import { getErrorMessage } from "metabase/api/utils/errors";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useHasTokenFeature, useToast } from "metabase/common/hooks";+import {+ useDeleteCustomOidcMutation,+ useGetCustomOidcProvidersQuery,+ useUpdateCustomOidcMutation,+} from "metabase-enterprise/api";++export function OidcAuthCard() {+ const {+ value: isConfigured,+ settingDetails,+ isLoading,+ } = useAdminSetting("oidc-configured");+ const { value: isEnabled } = useAdminSetting("oidc-enabled");+ const { data: providers } = useGetCustomOidcProvidersQuery();+ const [updateProvider] = useUpdateCustomOidcMutation();+ const [deleteProvider] = useDeleteCustomOidcMutation();++ const hasFeature = useHasTokenFeature("sso_oidc");+ const [sendToast] = useToast();++ const handleToggle = useCallback(+ async (enabled: boolean) => {+ try {+ if (providers && providers.length > 0) {+ await updateProvider({+ key: providers[0].key,+ provider: { enabled },+ }).unwrap();+ }+ } catch (error) {+ sendToast({+ message: getErrorMessage(error, t`Failed to update OIDC provider`),+ icon: "warning",+ });+ }+ },+ [providers, updateProvider, sendToast],+ );++ const handleDeactivate = useCallback(async () => {+ try {+ if (providers) {+ await Promise.all(providers.map((p) => deleteProvider(p.key).unwrap()));+ }+ } catch (error) {+ sendToast({+ message: getErrorMessage(error, t`Failed to deactivate OIDC provider`),+ icon: "warning",+ });+ }+ }, [providers, deleteProvider, sendToast]);++ if (!hasFeature) {+ return null;+ }++ if (isLoading) {+ return <LoadingAndErrorWrapper loading />;+ }++ return (+ <AuthCard+ type="oidc"+ name={t`OIDC`}+ description={t`Allows users to login via an OpenID Connect Identity Provider.`}+ isConfigured={!!isConfigured}+ isEnabled={!!isEnabled}+ onChange={handleToggle}+ onDeactivate={handleDeactivate}+ setting={settingDetails}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/index.tsnew file mode 100644index 00000000000..8de837288a3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/containers/OidcAuthCard/index.ts@@ -0,0 +1 @@+export * from "./OidcAuthCard";diff --git a/enterprise/frontend/src/metabase-enterprise/auth/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/index.tsindex 44e4b702dd3..642097e0e46 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/auth/index.ts@@ -8,7 +8,7 @@ import {} from "metabase/plugins";import type { AuthProvider } from "metabase/plugins/types";import { hasPremiumFeature } from "metabase-enterprise/settings";-import type { User } from "metabase-types/api";+import type { OidcAuthProvider, User } from "metabase-types/api";import { createSessionMiddleware } from "../auth/middleware/session-middleware";@@ -17,7 +17,9 @@ import {LdapGroupMembershipFilter,LdapUserProvisioning,} from "./components/Ldap";+import { createOidcAuthProvider } from "./components/OidcButton/OidcButton";import { SettingsJWTForm } from "./components/SettingsJWTForm";+import { SettingsOIDCForm } from "./components/SettingsOIDCForm";import { SettingsSAMLForm } from "./components/SettingsSAMLForm";import { SsoButton } from "./components/SsoButton";@@ -41,6 +43,10 @@ export function initializePlugin() {PLUGIN_AUTH_PROVIDERS.SettingsJWTForm = SettingsJWTForm;}+ if (hasPremiumFeature("sso_oidc")) {+ PLUGIN_AUTH_PROVIDERS.SettingsOIDCForm = SettingsOIDCForm;+ }+// Add provider function that handles SSO and password loginconst enhancedProviderFunction = (providers: AuthProvider[]) => {if (@@ -49,6 +55,16 @@ export function initializePlugin() {) {providers = [SSO_PROVIDER, ...providers];}++ // Add OIDC provider buttons+ if (hasPremiumFeature("sso_oidc")) {+ const oidcProviders: OidcAuthProvider[] =+ MetabaseSettings.get("oidc-login-providers") ?? [];+ for (const oidcProvider of oidcProviders) {+ providers = [createOidcAuthProvider(oidcProvider), ...providers];+ }+ }+if (hasPremiumFeature("disable_password_login") &&!MetabaseSettings.isPasswordLoginEnabled() &&@@ -66,6 +82,7 @@ export function initializePlugin() {Boolean(user.sso_source !== "google" &&user.sso_source !== "ldap" &&+ user.sso_source !== "oidc" &&MetabaseSettings.isPasswordLoginEnabled(),);diff --git a/enterprise/frontend/src/metabase-enterprise/auth/utils.ts b/enterprise/frontend/src/metabase-enterprise/auth/utils.tsindex 7f61829e1da..74e28df352b 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/auth/utils.ts@@ -15,7 +15,8 @@ export function useHasSsoEnabled() {settings?.["google-auth-enabled"] ||settings?.["ldap-enabled"] ||settings?.["saml-enabled"] ||- settings?.["jwt-enabled"];+ settings?.["jwt-enabled"] ||+ settings?.["oidc-enabled"];return hasAnySsoProviderEnabled;}diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex cc9af46e7ca..dfe502fd378 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -118,6 +118,7 @@ export const createMockTokenFeatures = (sso_google: false,sso_jwt: false,sso_ldap: false,+ sso_oidc: false,sso_saml: false,session_timeout_config: false,whitelabel: false,@@ -301,6 +302,7 @@ export const createMockSettings = ("ldap-user-base": null,"ldap-user-filter": null,"ldap-user-provisioning-enabled?": false,+ "oidc-user-provisioning-enabled?": true,"ldap-attribute-email": null,"ldap-attribute-firstname": null,"ldap-attribute-lastname": null,@@ -328,6 +330,9 @@ export const createMockSettings = ("report-timezone": "Europe/London","report-timezone-short": "UTC","report-timezone-long": "Europe/London",+ "oidc-configured": false,+ "oidc-enabled": false,+ "oidc-login-providers": [],"saml-configured": false,"saml-enabled": false,"saml-identity-provider-uri": null,diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex f34f9f999b6..4256e7fa372 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -9,6 +9,13 @@ import type { DatabaseId } from "./database";import type { GroupId } from "./group";import type { UserId } from "./user";+export interface OidcAuthProvider {+ type: "oidc";+ key: string;+ "login-prompt": string;+ "sso-url": string;+}+export interface FormattingSettings {"type/Temporal"?: DateFormattingSettings;"type/Number"?: NumberFormattingSettings;@@ -326,6 +333,7 @@ export const tokenFeatures = ["sso_google","sso_jwt","sso_ldap",+ "sso_oidc","sso_saml","session_timeout_config","whitelabel",@@ -477,6 +485,7 @@ interface AdminSettings {"google-auth-auto-create-accounts-domain": string | null;"google-auth-configured": boolean;"premium-embedding-token": string | null;+ "oidc-login-providers"?: OidcAuthProvider[];"other-sso-enabled?"?: boolean; // yes the question mark is in the variable name"show-database-syncing-modal": boolean;"token-status": TokenStatus | null;@@ -564,6 +573,7 @@ interface PublicSettings {"ldap-group-mappings": Record<string /*ldap group name */, GroupId[]> | null;"ldap-group-membership-filter"?: string;"ldap-user-provisioning-enabled?": boolean;+ "oidc-user-provisioning-enabled?": boolean;"loading-message": LoadingMessage;"map-tile-server-url": string;"native-query-autocomplete-match-style": AutocompleteMatchStyle;@@ -713,6 +723,8 @@ export interface EnterpriseSettings extends Settings {"jwt-attribute-groups": string | null;"jwt-attribute-tenant": string | null;"jwt-group-sync": boolean | null;+ "oidc-enabled": boolean;+ "oidc-configured": boolean;"saml-enabled": boolean;"saml-configured": boolean;"saml-user-provisioning-enabled?": boolean;diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.tsindex f794b576b59..c9c47478f4a 100644--- a/frontend/src/metabase-types/api/user.ts+++ b/frontend/src/metabase-types/api/user.ts@@ -71,7 +71,7 @@ export interface User extends BaseUser {can_write_any_collection: boolean;personal_collection_id: CollectionId;tenant_collection_id: CollectionId | null;- sso_source: "jwt" | "ldap" | "google" | "scim" | "saml" | null;+ sso_source: "jwt" | "ldap" | "google" | "scim" | "saml" | "oidc" | null;custom_homepage: {dashboard_id: DashboardId;} | null;diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsxindex 30159d9abd3..759d8ec334d 100644--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx@@ -23,6 +23,7 @@ export function SettingsNav() {const hasWhitelabel = useHasTokenFeature("whitelabel");const hasSaml = useHasTokenFeature("sso_saml");const hasJwt = useHasTokenFeature("sso_jwt");+ const hasOidc = useHasTokenFeature("sso_oidc");const hasScim = useHasTokenFeature("scim");const hasPythonTransforms = useHasTokenFeature("transforms-python");const isHosted = useSetting("is-hosted?");@@ -47,6 +48,7 @@ export function SettingsNav() {<SettingsNavItem path="authentication/ldap" label="LDAP" />{hasSaml && <SettingsNavItem path="authentication/saml" label="SAML" />}{hasJwt && <SettingsNavItem path="authentication/jwt" label="JWT" />}+ {hasOidc && <SettingsNavItem path="authentication/oidc" label="OIDC" />}</SettingsNavItem><PLUGIN_REMOTE_SYNC.LibraryNav /><NavDivider />diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.setup.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.setup.tsxindex d2408b70e64..0390d92557d 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.setup.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.setup.tsx@@ -1,3 +1,5 @@+import fetchMock from "fetch-mock";+import {setupApiKeyEndpoints,setupPropertiesEndpoints,@@ -83,6 +85,7 @@ export const setup = async (setupSettingsEndpoints([]);setupApiKeyEndpoints(testApiKeys);setupTokenStatusEndpoint({ valid: isEnterprise });+ fetchMock.get("path:/api/ee/sso/oidc", []);renderWithProviders(<div>diff --git a/frontend/src/metabase/admin/settings/tests/setup.tsx b/frontend/src/metabase/admin/settings/tests/setup.tsxindex ad858791892..20c92089be0 100644--- a/frontend/src/metabase/admin/settings/tests/setup.tsx+++ b/frontend/src/metabase/admin/settings/tests/setup.tsx@@ -145,6 +145,7 @@ export const setup = async ({});fetchMock.get("path:/api/cloud-migration", { status: 204 });+ fetchMock.get("path:/api/ee/sso/oidc", []);const user = createMockUser({is_superuser: isAdmin,diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsxindex 7d5ee184165..f827aa48790 100644--- a/frontend/src/metabase/admin/settingsRoutes.tsx+++ b/frontend/src/metabase/admin/settingsRoutes.tsx@@ -59,6 +59,10 @@ export const getSettingsRoutes = () => (path="authentication/jwt"component={() => <PLUGIN_AUTH_PROVIDERS.SettingsJWTForm />}/>+ <Route+ path="authentication/oidc"+ component={() => <PLUGIN_AUTH_PROVIDERS.SettingsOIDCForm />}+ /><Routepath="remote-sync"component={() => <PLUGIN_REMOTE_SYNC.RemoteSyncSettings />}diff --git a/frontend/src/metabase/plugins/oss/auth.ts b/frontend/src/metabase/plugins/oss/auth.tsindex 71fc7249de9..15bcd570146 100644--- a/frontend/src/metabase/plugins/oss/auth.ts+++ b/frontend/src/metabase/plugins/oss/auth.ts@@ -21,6 +21,7 @@ const getDefaultPluginAuthProviders = () => ({UserProvisioningSettings: NotFoundPlaceholder,SettingsSAMLForm: NotFoundPlaceholder,SettingsJWTForm: NotFoundPlaceholder,+ SettingsOIDCForm: NotFoundPlaceholder,providers: [] as GetAuthProviders[],});diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.cljindex e32a27ff6e3..2aafef16477 100644--- a/src/metabase/premium_features/core.clj+++ b/src/metabase/premium_features/core.clj@@ -76,9 +76,10 @@enable-sso-google?enable-sso-jwt?enable-sso-ldap?+ enable-sso-oidc?enable-sso-saml?- enable-support-users?enable-sso-slack?+ enable-support-users?enable-transforms?enable-python-transforms?enable-upload-management?diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.cljindex be7dbe74658..8672972595f 100644--- a/src/metabase/premium_features/settings.clj+++ b/src/metabase/premium_features/settings.clj@@ -150,6 +150,10 @@"Should we enable Slack Connect (OIDC) authentication?":sso-slack)+(define-premium-feature ^{:added "0.59.0"} enable-sso-oidc?+ "Should we enable OIDC-based authentication?"+ :sso-oidc)+(define-premium-feature enable-sso-ldap?"Should we enable advanced configuration for LDAP authentication?":sso-ldap)@@ -168,6 +172,7 @@(or (enable-sso-jwt?)(enable-sso-saml?)(enable-sso-slack?)+ (enable-sso-oidc?)(enable-sso-ldap?)(enable-sso-google?)))@@ -364,6 +369,7 @@:sso_jwt (enable-sso-jwt?):sso_ldap (enable-sso-ldap?):sso_saml (enable-sso-saml?)+ :sso_oidc (enable-sso-oidc?):sso_slack (enable-sso-slack?):support-users (enable-support-users?):table_data_editing (table-data-editing?)diff --git a/src/metabase/server/auth_wrapper.clj b/src/metabase/server/auth_wrapper.cljindex 63a974dbc7a..5f344d2aee9 100644--- a/src/metabase/server/auth_wrapper.clj+++ b/src/metabase/server/auth_wrapper.clj@@ -16,7 +16,8 @@;; them in sync.(handlers/route-map-handler{"/auth" {"/sso" not-enabled}- "/api" {"/saml" not-enabled}}))+ "/api" {"/saml" not-enabled+ "/ee" {"/sso" {"/oidc" not-enabled}}}}));; This needs to be injected into [[metabase.server.routes/routes]] -- not [[metabase.api-routes.core/routes]] !!!;;diff --git a/src/metabase/sso/core.clj b/src/metabase/sso/core.cljindex 4df0df08dc8..e415aaada81 100644--- a/src/metabase/sso/core.clj+++ b/src/metabase/sso/core.clj@@ -4,6 +4,7 @@[metabase.sso.google][metabase.sso.ldap][metabase.sso.ldap.default-implementation]+ [metabase.sso.oidc.check][metabase.sso.oidc.state][metabase.sso.settings][potemkin :as p]))@@ -14,6 +15,8 @@[metabase.sso.ldap.default-implementationLDAPSettingsldap-search-result->user-info]+ [metabase.sso.oidc.check+ check-oidc-configuration][metabase.sso.oidc.statewrap-oidc-redirectclear-oidc-state-cookie]diff --git a/src/metabase/sso/oidc/check.clj b/src/metabase/sso/oidc/check.cljnew file mode 100644index 00000000000..c24b9b5987a--- /dev/null+++ b/src/metabase/sso/oidc/check.clj@@ -0,0 +1,101 @@+(ns metabase.sso.oidc.check+ "OIDC configuration validation.++ Validates OIDC provider configuration by probing the discovery document+ and testing client credentials against the token endpoint."+ (:require+ [clj-http.client :as http]+ [metabase.sso.oidc.discovery :as discovery]+ [metabase.util.log :as log]))++(set! *warn-on-reflection* true)++(defn check-discovery+ "Validate that the issuer's discovery document is fetchable and contains required endpoints.++ Invalidates the cache first to ensure a fresh fetch, then checks for authorization,+ token, and JWKS endpoints.++ Returns `{:step :discovery, :success bool, :error str?, :token-endpoint str?}`."+ [issuer-uri]+ (discovery/invalidate-cache! issuer-uri)+ (let [doc (discovery/discover-oidc-configuration issuer-uri)]+ (if (nil? doc)+ {:step :discovery+ :success false+ :error (str "Could not fetch OIDC discovery document from " issuer-uri)}+ (let [config {:discovery-document doc}]+ (if (discovery/validate-configuration config)+ {:step :discovery+ :success true+ :token-endpoint (discovery/get-token-endpoint config)}+ {:step :discovery+ :success false+ :error "Discovery document is missing required endpoints (authorization, token, or JWKS)"})))))++(defn check-credentials+ "Validate client credentials by POSTing a client_credentials grant to the token endpoint.++ Interprets the response:+ - HTTP 200 → credentials confirmed valid+ - `unsupported_grant_type` / `unauthorized_client` → inconclusive (IdP may not have checked the secret)+ - `invalid_client` → invalid credentials+ - Other errors → reported as-is++ Returns `{:step :credentials, :success bool, :verified bool, :error str?}`.+ When `:verified` is false, the IdP did not confirm the credentials but didn't reject them either."+ [token-endpoint client-id client-secret]+ (try+ (let [response (http/post token-endpoint+ {:form-params {:grant_type "client_credentials"+ :client_id client-id+ :client_secret client-secret}+ :as :json+ :coerce :always+ :throw-exceptions false+ :conn-timeout 5000+ :socket-timeout 5000})+ status (:status response)+ body (:body response)+ error-code (or (:error body)+ (when (string? body) body))]+ (cond+ (= 200 status)+ {:step :credentials :success true :verified true}++ (contains? #{"unsupported_grant_type" "unauthorized_client"} error-code)+ {:step :credentials :success true :verified false}++ (= "invalid_client" error-code)+ {:step :credentials :success false :verified true :error "Invalid client ID or client secret"}++ :else+ {:step :credentials+ :success false+ :verified true+ :error (str "Unexpected response from token endpoint (HTTP " status "): "+ (or (:error_description body) error-code body))}))+ (catch Exception e+ (log/warnf e "OIDC credential check failed for %s" token-endpoint)+ {:step :credentials+ :success false+ :verified false+ :error (str "Could not connect to token endpoint: " (.getMessage e))})))++(defn check-oidc-configuration+ "Run full OIDC configuration validation: discovery then credentials.++ Parameters:+ - issuer-uri: The OIDC issuer URL+ - client-id: OAuth2 client ID+ - client-secret: OAuth2 client secret++ Returns `{:ok bool, :discovery {...}, :credentials {...}}`."+ [issuer-uri client-id client-secret]+ (let [disc (check-discovery issuer-uri)]+ (if-not (:success disc)+ {:ok false :discovery disc}+ (let [cred (check-credentials (:token-endpoint disc) client-id client-secret)]+ {:ok (:success cred)+ :discovery disc+ :credentials cred}))))diff --git a/src/metabase/sso/oidc/discovery.clj b/src/metabase/sso/oidc/discovery.cljindex 97ec48a24ab..a4452e5c239 100644--- a/src/metabase/sso/oidc/discovery.clj+++ b/src/metabase/sso/oidc/discovery.clj@@ -7,6 +7,7 @@[clj-http.client :as http][clojure.string :as str][java-time.api :as t]+ [metabase.sso.settings :as sso.settings][metabase.util.http :as u.http][metabase.util.log :as log]))@@ -44,8 +45,8 @@Returns the parsed JSON document or nil on error."[issuer](let [url (discovery-url issuer)]- (when-not (u.http/valid-host? :external-only url)- (throw (ex-info "Invalid issuer URL: internal addresses not allowed"+ (when-not (u.http/valid-host? (sso.settings/oidc-allowed-networks) url)+ (throw (ex-info "Invalid issuer URL: address not allowed by network restrictions"{:url url})))(try(log/infof "Fetching OIDC discovery document from %s" url)diff --git a/src/metabase/sso/oidc/tokens.clj b/src/metabase/sso/oidc/tokens.cljindex 140c06e3d5f..bcde59bb262 100644--- a/src/metabase/sso/oidc/tokens.clj+++ b/src/metabase/sso/oidc/tokens.clj@@ -5,6 +5,7 @@[buddy.sign.jwt :as jwt][clj-http.client :as http][java-time.api :as t]+ [metabase.sso.settings :as sso.settings][metabase.util :as u][metabase.util.http :as u.http][metabase.util.log :as log]))@@ -43,8 +44,8 @@(defn- fetch-jwks"Fetch JWKS from the given URI. Returns the parsed JWKS map or nil on error."[jwks-uri]- (when-not (u.http/valid-host? :external-only jwks-uri)- (throw (ex-info "Invalid JWKS URI: internal addresses not allowed"+ (when-not (u.http/valid-host? (sso.settings/oidc-allowed-networks) jwks-uri)+ (throw (ex-info "Invalid JWKS URI: address not allowed by network restrictions"{:url jwks-uri})))(try(log/infof "Fetching JWKS from %s" jwks-uri)diff --git a/src/metabase/sso/providers/ldap.clj b/src/metabase/sso/providers/ldap.cljindex 23801405be4..c43a29140ac 100644--- a/src/metabase/sso/providers/ldap.clj+++ b/src/metabase/sso/providers/ldap.clj@@ -3,7 +3,7 @@(:require[metabase.auth-identity.core :as auth-identity][metabase.premium-features.core :refer [defenterprise]]- [metabase.sso.common :as sso.common]+ [metabase.sso.core :as sso][metabase.sso.ldap :as ldap][metabase.sso.ldap.default-implementation :as ldap.impl][metabase.util :as u]@@ -130,6 +130,6 @@(try(let [group-ids (ldap.impl/ldap-groups->mb-group-ids groups settings)all-mapped-ids (ldap.impl/all-mapped-group-ids settings)]- (sso.common/sync-group-memberships! (:user result) group-ids all-mapped-ids))+ (sso/sync-group-memberships! (:user result) group-ids all-mapped-ids))(catch Exception e(log/error e "Error syncing LDAP group memberships"))))))))diff --git a/src/metabase/sso/settings.clj b/src/metabase/sso/settings.cljindex 1cf40b2d2b7..fade67b3591 100644--- a/src/metabase/sso/settings.clj+++ b/src/metabase/sso/settings.clj@@ -187,6 +187,16 @@(setting/set-value-of-type! :boolean :google-auth-enabled new-value))(setting/set-value-of-type! :boolean :google-auth-enabled new-value))))+(defsetting oidc-allowed-networks+ (deferred-tru "What networks are OIDC requests allowed to? Possible values: ''allow-all'' (default), ''allow-private'', or ''external-only''.")+ :type :keyword+ :default :allow-all+ :export? false+ :setter (fn [new-value]+ (when (some? new-value)+ (assert (#{:allow-all :allow-private :external-only} (keyword new-value))))+ (setting/set-value-of-type! :keyword :oidc-allowed-networks new-value)))+(defn- ee-sso-configured? [](when config/ee-available?(setting/get :other-sso-enabled?)))diff --git a/src/metabase/util.cljc b/src/metabase/util.cljcindex 0e45faedf3c..b8df688f1f3 100644--- a/src/metabase/util.cljc+++ b/src/metabase/util.cljc@@ -552,6 +552,13 @@"")true str/join))))+(defn valid-slug?+ "Check that a given string is a valid slug."+ [slug]+ (and (string? slug)+ (not (str/blank? slug))+ (re-matches #"^[a-z0-9][a-z0-9\-]*$" slug)))+(defn id"If passed an integer ID, returns it. If passed a map containing an `:id` key, returns the value if it is an integer.Otherwise returns `nil`.diff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.cljindex 35617df3522..0571cd29e82 100644--- a/test/metabase/analytics/stats_test.clj+++ b/test/metabase/analytics/stats_test.clj@@ -568,7 +568,8 @@:llm-autodescription:query-reference-validation:cloud-custom-smtp- :session-timeout-config})+ :session-timeout-config+ :sso-oidc})(deftest every-feature-is-accounted-for-test(testing "Is every premium feature either tracked under the :features key, or intentionally excluded?"diff --git a/test/metabase/sso/oidc/discovery_test.clj b/test/metabase/sso/oidc/discovery_test.cljindex 171c1087d29..3de055f9552 100644--- a/test/metabase/sso/oidc/discovery_test.clj+++ b/test/metabase/sso/oidc/discovery_test.clj@@ -3,7 +3,8 @@[clj-http.client :as http][clojure.test :refer :all][java-time.api :as t]- [metabase.sso.oidc.discovery :as oidc.discovery]))+ [metabase.sso.oidc.discovery :as oidc.discovery]+ [metabase.test :as mt]))(deftest ^:parallel get-authorization-endpoint-test(testing "Gets authorization endpoint from discovery document"@@ -205,32 +206,35 @@;;; ================================================== SSRF Protection Tests ==================================================(deftest discover-oidc-configuration-ssrf-protection-test- (testing "Rejects internal addresses (localhost)"+ (testing "Respects oidc-allowed-networks if set"(oidc.discovery/clear-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid issuer URL: internal addresses not allowed"- (oidc.discovery/discover-oidc-configuration "http://localhost/oidc"))))-- (testing "Rejects internal addresses (127.0.0.1)"- (oidc.discovery/clear-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid issuer URL: internal addresses not allowed"- (oidc.discovery/discover-oidc-configuration "http://127.0.0.1/oidc"))))-- (testing "Rejects cloud metadata endpoint"- (oidc.discovery/clear-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid issuer URL: internal addresses not allowed"- (oidc.discovery/discover-oidc-configuration "http://169.254.169.254/metadata"))))-- (testing "Rejects private network addresses (192.168.x.x)"- (oidc.discovery/clear-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid issuer URL: internal addresses not allowed"- (oidc.discovery/discover-oidc-configuration "http://192.168.1.1/oidc"))))-- (testing "Rejects private network addresses (10.x.x.x)"- (oidc.discovery/clear-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid issuer URL: internal addresses not allowed"- (oidc.discovery/discover-oidc-configuration "http://10.0.0.1/oidc")))))+ (mt/with-temporary-setting-values [oidc-allowed-networks :external-only]+ (testing "Rejects internal addresses (localhost)"+ (oidc.discovery/clear-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid issuer URL: address not allowed by network restrictions"+ (oidc.discovery/discover-oidc-configuration "http://localhost/oidc"))))++ (testing "Rejects internal addresses (127.0.0.1)"+ (oidc.discovery/clear-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid issuer URL: address not allowed by network restrictions"+ (oidc.discovery/discover-oidc-configuration "http://127.0.0.1/oidc"))))++ (testing "Rejects cloud metadata endpoint"+ (oidc.discovery/clear-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid issuer URL: address not allowed by network restrictions"+ (oidc.discovery/discover-oidc-configuration "http://169.254.169.254/metadata"))))++ (testing "Rejects private network addresses (192.168.x.x)"+ (oidc.discovery/clear-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid issuer URL: address not allowed by network restrictions"+ (oidc.discovery/discover-oidc-configuration "http://192.168.1.1/oidc"))))++ (testing "Rejects private network addresses (10.x.x.x)"+ (oidc.discovery/clear-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid issuer URL: address not allowed by network restrictions"+ (oidc.discovery/discover-oidc-configuration "http://10.0.0.1/oidc")))))))diff --git a/test/metabase/sso/oidc/tokens_test.clj b/test/metabase/sso/oidc/tokens_test.cljindex 2133dd47afe..72e0381f7af 100644--- a/test/metabase/sso/oidc/tokens_test.clj+++ b/test/metabase/sso/oidc/tokens_test.clj@@ -5,7 +5,8 @@[clj-http.client :as http][clojure.test :refer :all][java-time.api :as t]- [metabase.sso.oidc.tokens :as oidc.tokens]))+ [metabase.sso.oidc.tokens :as oidc.tokens]+ [metabase.test :as mt]))(set! *warn-on-reflection* true)@@ -342,35 +343,37 @@ h0ccjghRm1/Az8L/HL+gdQmtY0NdB4Ml2mZHCVsPYf5WzIirTpjY0EzKDA==;;; ================================================== SSRF Protection Tests ==================================================(deftest get-jwks-ssrf-protection-test- (testing "Rejects internal addresses (localhost)"- (oidc.tokens/clear-jwks-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid JWKS URI: internal addresses not allowed"- (oidc.tokens/get-jwks "http://localhost/jwks"))))-- (testing "Rejects internal addresses (127.0.0.1)"- (oidc.tokens/clear-jwks-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid JWKS URI: internal addresses not allowed"- (oidc.tokens/get-jwks "http://127.0.0.1/jwks"))))-- (testing "Rejects cloud metadata endpoint"- (oidc.tokens/clear-jwks-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid JWKS URI: internal addresses not allowed"- (oidc.tokens/get-jwks "http://169.254.169.254/jwks"))))-- (testing "Rejects private network addresses (192.168.x.x)"- (oidc.tokens/clear-jwks-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid JWKS URI: internal addresses not allowed"- (oidc.tokens/get-jwks "http://192.168.1.1/jwks"))))-- (testing "Rejects private network addresses (10.x.x.x)"- (oidc.tokens/clear-jwks-cache!)- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Invalid JWKS URI: internal addresses not allowed"- (oidc.tokens/get-jwks "http://10.0.0.1/jwks")))))+ (testing "Respects oidc-allowed-networks if set"+ (mt/with-temporary-setting-values [oidc-allowed-networks :external-only]+ (testing "Rejects internal addresses (localhost)"+ (oidc.tokens/clear-jwks-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid JWKS URI: address not allowed by network restrictions"+ (oidc.tokens/get-jwks "http://localhost/jwks"))))++ (testing "Rejects internal addresses (127.0.0.1)"+ (oidc.tokens/clear-jwks-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid JWKS URI: address not allowed by network restrictions"+ (oidc.tokens/get-jwks "http://127.0.0.1/jwks"))))++ (testing "Rejects cloud metadata endpoint"+ (oidc.tokens/clear-jwks-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid JWKS URI: address not allowed by network restrictions"+ (oidc.tokens/get-jwks "http://169.254.169.254/jwks"))))++ (testing "Rejects private network addresses (192.168.x.x)"+ (oidc.tokens/clear-jwks-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid JWKS URI: address not allowed by network restrictions"+ (oidc.tokens/get-jwks "http://192.168.1.1/jwks"))))++ (testing "Rejects private network addresses (10.x.x.x)"+ (oidc.tokens/clear-jwks-cache!)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid JWKS URI: address not allowed by network restrictions"+ (oidc.tokens/get-jwks "http://10.0.0.1/jwks")))))));;; ================================================== Algorithm Support Tests ==================================================