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
Fix OIDC credential check for Entra ID (#83619)
appleby022efeb638b3
diff --git a/e2e/test/scenarios/admin/sso/oidc.cy.spec.ts b/e2e/test/scenarios/admin/sso/oidc.cy.spec.tsindex 4bbdad4fb42..ad9e33fe996 100644--- a/e2e/test/scenarios/admin/sso/oidc.cy.spec.ts+++ b/e2e/test/scenarios/admin/sso/oidc.cy.spec.ts@@ -43,9 +43,8 @@ describe("scenarios > admin > settings > SSO > OIDC", () => {cy.wait("@checkConnection");H.undoToast().findByText("OIDC connection is valid").should("be.visible");- cy.log("Saving checks again and creates the provider with group sync off");+ cy.log("Saving creates the provider with group sync off");cy.button("Save and enable").click();- cy.wait("@checkConnection");cy.wait("@createProvider").its("request.body.key").should("equal", "okta");cy.log("The page switches to its configured state");diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.cljindex 1816faa0834..b1f47122358 100644--- a/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj@@ -147,7 +147,8 @@[:issuer-uri :string][:client-id :string][:client-secret {:optional true} [:maybe :string]]- [:key {:optional true} [:maybe :string]]])+ [:key {:optional true} [:maybe :string]]+ [:scopes {:optional true} [:maybe [:sequential :string]]]])(def ^:private oidc-check-step-schema[:map@@ -176,7 +177,7 @@(if (str/blank? s)(:client-secret stored)s))- scopes (or (:scopes stored) ["openid"])]+ scopes (or (:scopes body) (:scopes stored) ["openid"])](check-oidc-connection! issuer-uri client-id client-secret scopes)));; DELETE /api/ee/sso/oidc/:keydiff --git a/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.cljindex aa190043a60..7825c4b973c 100644--- a/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/api/oidc_test.clj@@ -60,6 +60,31 @@(is (mt/user-http-request :crowberto :post 400 "ee/sso/oidc"(assoc test-provider :key "INVALID SLUG!")))))))))+(def ^:private failed-check-result+ {:ok false+ :discovery {:step :discovery :success true :token-endpoint "https://test.okta.com/oauth2/token"}+ :credentials {:step :credentials :success false :verified true :error "Invalid client credentials"}})++(deftest create-provider-failed-check-test+ (testing "Creating an OIDC provider fails with a 400 and saves nothing when the connection check fails"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (constantly failed-check-result)]+ (mt/with-temporary-setting-values [oidc-providers []]+ (is (= "Invalid client credentials"+ (mt/user-http-request :crowberto :post 400 "ee/sso/oidc" test-provider)))+ (is (= [] (sso-settings/oidc-providers))))))))++(deftest update-provider-failed-check-test+ (testing "Updating an OIDC provider fails with a 400 and leaves the stored provider unchanged when the connection check fails"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (constantly failed-check-result)]+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (is (= "Invalid client credentials"+ (mt/user-http-request :crowberto :put 400 "ee/sso/oidc/test-okta"+ {:client-id "new-client-id"+ :client-secret "new-client-secret"})))+ (is (= [test-provider] (sso-settings/oidc-providers))))))))+(deftest read-providers-test(testing "Reading OIDC providers"(mt/with-additional-premium-features #{:sso-oidc}@@ -114,3 +139,57 @@(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))))))))++(defn- check-scopes+ "POST to the OIDC check endpoint with `body` and return the scopes it passed to the configuration check."+ [body]+ (let [scopes (atom nil)]+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (fn [_issuer-uri _client-id _client-secret s]+ (reset! scopes s)+ successful-check-result)]+ (mt/user-http-request :crowberto :post 200 "ee/sso/oidc/check" body))+ @scopes))++(deftest check-uses-request-scopes-test+ (testing "OIDC check uses the scopes sent in the request over the stored provider's scopes"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (is (= ["openid" "groups"]+ (check-scopes {:issuer-uri "https://test.okta.com"+ :client-id "test-client-id"+ :key "test-okta"+ :scopes ["openid" "groups"]})))))))++(deftest check-falls-back-to-stored-scopes-test+ (testing "OIDC check uses the stored provider's scopes when the request has none"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (is (= ["openid" "email" "profile"]+ (check-scopes {:issuer-uri "https://test.okta.com"+ :client-id "test-client-id"+ :key "test-okta"})))))))++(deftest check-falls-back-to-openid-scope-test+ (testing "OIDC check uses the openid scope when neither the request nor a stored provider has scopes"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers []]+ (is (= ["openid"]+ (check-scopes {:issuer-uri "https://test.okta.com"+ :client-id "test-client-id"+ :client-secret "test-client-secret"})))))))++(deftest check-requires-superuser-test+ (testing "OIDC check endpoint requires superuser and does not probe the provider"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values [oidc-providers [test-provider]]+ (let [called? (atom false)]+ (mt/with-dynamic-fn-redefs [oidc.check/check-oidc-configuration (fn [& _]+ (reset! called? true)+ successful-check-result)]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "ee/sso/oidc/check"+ {:issuer-uri "https://test.okta.com"+ :client-id "test-client-id"+ :key "test-okta"+ :scopes ["openid"]})))+ (is (false? @called?))))))))diff --git a/enterprise/frontend/src/metabase-enterprise/api/oidc.ts b/enterprise/frontend/src/metabase-enterprise/api/oidc.tsindex 9dea932cc9c..76a966975a1 100644--- a/enterprise/frontend/src/metabase-enterprise/api/oidc.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/oidc.ts@@ -8,6 +8,7 @@ export interface OidcCheckRequest {"client-id": string;"client-secret"?: string | null;key?: string | null;+ scopes?: string[];}export interface OidcCheckStepResult {diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsxindex ef347b35688..d8a866b92e1 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx@@ -138,16 +138,20 @@ function providerToFormValues(};}-function formValuesToProvider(- values: OIDCFormValues,- groupSync: Partial<OidcGroupSync> | undefined,-): Partial<CustomOidcConfig> {- const scopes = values.scopes- ? values.scopes+function parseScopes(scopes: string | null): string[] {+ return scopes+ ? scopes.split(",").map((s) => s.trim()).filter(Boolean): DEFAULT_SCOPES;+}++function formValuesToProvider(+ values: OIDCFormValues,+ groupSync: Partial<OidcGroupSync> | undefined,+): Partial<CustomOidcConfig> {+ const scopes = parseScopes(values.scopes);const attributeMap: Record<string, string> = {};if (values["attribute-firstname"]) {@@ -222,6 +226,7 @@ export function SettingsOIDCForm() {const req: OidcCheckRequest = {"issuer-uri": values["issuer-uri"],"client-id": values["client-id"],+ scopes: parseScopes(values.scopes),};if (values["client-secret"]) {req["client-secret"] = values["client-secret"];@@ -260,7 +265,7 @@ export function SettingsOIDCForm() {const handleSubmit = useCallback(async (values: OIDCFormValues, helpers: FormikHelpers<OIDCFormValues>) => {- await runCheck(values);+ // No need to runCheck separately here, the backend does it before saving the provider.// the card and the save button hold each other, so no card write can be in flight hereconst providerData = formValuesToProvider(@@ -281,7 +286,7 @@ export function SettingsOIDCForm() {// the saved values become the baseline, so the form is clean before the refetch landshelpers.resetForm({ values });},- [existingProvider, createProvider, updateProvider, runCheck],+ [existingProvider, createProvider, updateProvider],);if (isLoadingDetails || isLoadingValues || isLoadingProviders) {diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsxindex ceb88908272..d9a7eef22e7 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx@@ -481,7 +481,7 @@ describe("SettingsOIDCForm", () => {);await waitFor(async () => {- expect(await findRequests("POST")).toHaveLength(2);+ expect(await findRequests("POST")).toHaveLength(1);});const [{ body }] = (await findRequests("POST")).filter(({ url }) =>url.endsWith("/api/ee/sso/oidc"),@@ -511,7 +511,7 @@ describe("SettingsOIDCForm", () => {);await waitFor(async () => {- expect(await findRequests("POST")).toHaveLength(2);+ expect(await findRequests("POST")).toHaveLength(1);});const [{ body }] = (await findRequests("POST")).filter(({ url }) =>url.endsWith("/api/ee/sso/oidc"),@@ -520,6 +520,70 @@ describe("SettingsOIDCForm", () => {});});+ describe("saving", () => {+ it("does not run a separate connection check when saving a new provider", async () => {+ await setup();+ await fillRequiredFields();++ await userEvent.click(+ screen.getByRole("button", { name: "Save and enable" }),+ );++ await waitFor(async () => {+ expect(await findRequests("POST")).toHaveLength(1);+ });+ const [{ url }] = await findRequests("POST");+ expect(url).toMatch(/\/api\/ee\/sso\/oidc$/);+ });++ it("does not run a separate connection check when saving an existing provider", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });++ await expandAttributes();+ await userEvent.type(+ screen.getByLabelText("Last name attribute key"),+ "surname",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Save changes" }),+ );++ await waitFor(async () =>+ expect(await getOidcPutCalls()).toHaveLength(1),+ );+ expect(await findRequests("POST")).toHaveLength(0);+ });+ });++ describe("connection check", () => {+ it("sends the scopes from the form to the connection check", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });++ await expandAttributes();+ const scopesInput = screen.getByLabelText(/^Scopes/);+ await waitFor(() => expect(scopesInput).toBeVisible());+ await userEvent.clear(scopesInput);+ await userEvent.type(+ scopesInput,+ "openid, https://graph.microsoft.com/.default",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Check connection" }),+ );++ await waitFor(async () => {+ const checks = (await findRequests("POST")).filter(({ url }) =>+ url.includes("/api/ee/sso/oidc/check"),+ );+ expect(checks).toHaveLength(1);+ expect(checks[0].body.scopes).toEqual([+ "openid",+ "https://graph.microsoft.com/.default",+ ]);+ });+ });+ });+describe("user provisioning", () => {it("saves right away without touching the page form", async () => {await setup({ providers: [EXISTING_PROVIDER] });diff --git a/src/metabase/sso/oidc/check.clj b/src/metabase/sso/oidc/check.cljindex e0205af719c..790b79fd2ca 100644--- a/src/metabase/sso/oidc/check.clj+++ b/src/metabase/sso/oidc/check.clj@@ -7,6 +7,7 @@[clojure.string :as str][metabase.sso.oidc.discovery :as discovery][metabase.sso.oidc.http :as oidc.http]+ [metabase.util :as u][metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -34,6 +35,33 @@:success false:error "Discovery document is missing required endpoints (authorization, token, or JWKS)"})))))+(def ^:private entra-token-hosts+ "Well-known Entra ID token endpoints."+ #{"login.microsoftonline.com"+ "login.windows.net"+ "login.microsoft.com"+ "login-us.microsoftonline.com"+ "login.microsoftonline.us"+ "login.partner.microsoftonline.cn"+ "login.chinacloudapi.cn"})++(defn- entra-token-endpoint?+ [token-endpoint]+ (contains? entra-token-hosts (some-> token-endpoint java.net.URI. .getHost u/lower-case-en)))++(defn- client-credentials-scopes+ "Return the list of scopes to use for a client_credentials request for the given `token-endpoint`.++ For most endpoints, this just returns `scopes`, but some endpoints might need to modify the scopes. Entra ID, for+ example, requires a .default scope."+ [token-endpoint client-id scopes]+ (if (and (entra-token-endpoint? token-endpoint)+ (not-any? #(str/ends-with? % "/.default") scopes))+ ;; Entra ID only issues client_credentials tokens for a `{resource}/.default` scope (AADSTS1002012). When none is+ ;; configured, ask for a token for the app itself, which needs no API permissions and should work for most setups.+ (conj (vec scopes) (str client-id "/.default"))+ scopes))+(defn check-credentials"Validate client credentials by POSTing a client_credentials grant to the token endpoint.@@ -51,7 +79,7 @@{:form-params {:grant_type "client_credentials":client_id client-id:client_secret client-secret- :scope (str/join " " scopes)}+ :scope (str/join " " (client-credentials-scopes token-endpoint client-id scopes))}:coerce :always})status (:status response)body (:body response)diff --git a/test/metabase/sso/oidc/check_test.clj b/test/metabase/sso/oidc/check_test.cljindex e9a542c1826..df10514e238 100644--- a/test/metabase/sso/oidc/check_test.clj+++ b/test/metabase/sso/oidc/check_test.clj@@ -1,6 +1,5 @@(ns metabase.sso.oidc.check-test(:require- [clojure.string :as str][clojure.test :refer :all][metabase.sso.oidc.check :as check][metabase.sso.oidc.http :as oidc.http]@@ -8,6 +7,18 @@(def ^:private token-endpoint "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token")+(def ^:private non-entra-token-endpoint "https://test.okta.com/oauth2/default/v1/token")++(defn- sent-scope+ "Call `check-credentials` against `endpoint` with `scopes` and return the `scope` form param it POSTed."+ [endpoint scopes]+ (let [captured (atom nil)]+ (mt/with-dynamic-fn-redefs [oidc.http/oidc-post (fn [_url opts]+ (reset! captured (:form-params opts))+ {:status 200 :body {:access_token "tok"}})]+ (check/check-credentials endpoint "client-id" "client-secret" scopes))+ (:scope @captured)))+(deftest ^:parallel check-credentials-includes-scope-test(testing "scope param is always included in the token endpoint request"(let [captured (atom nil)]@@ -20,24 +31,50 @@(deftest ^:parallel check-credentials-uses-provided-scopes-test(testing "configured scopes are sent space-joined"- (let [captured (atom nil)]- (mt/with-dynamic-fn-redefs [oidc.http/oidc-post (fn [_url opts]- (reset! captured (:form-params opts))- {:status 200 :body {:access_token "tok"}})]- (check/check-credentials token-endpoint "client-id" "client-secret"- ["openid" "email" "profile"])- (is (= "openid email profile" (:scope @captured)))))))+ (is (= "openid email profile"+ (sent-scope non-entra-token-endpoint ["openid" "email" "profile"])))))++(deftest ^:parallel check-credentials-entra-adds-default-scope-test+ (testing "OIDC credential check adds the app's own .default scope for Entra ID token endpoints (AADSTS1002012)"+ (doseq [endpoint ["https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token"+ "https://login.windows.net/tenant-id/oauth2/v2.0/token"+ "https://login.microsoft.com/tenant-id/oauth2/v2.0/token"+ "https://login-us.microsoftonline.com/tenant-id/oauth2/v2.0/token"+ "https://login.microsoftonline.us/tenant-id/oauth2/v2.0/token"+ "https://login.partner.microsoftonline.cn/tenant-id/oauth2/v2.0/token"+ "https://login.chinacloudapi.cn/tenant-id/oauth2/v2.0/token"+ "https://LOGIN.MicrosoftOnline.com/tenant-id/oauth2/v2.0/token"]]+ (testing endpoint+ (is (= "openid email profile client-id/.default"+ (sent-scope endpoint ["openid" "email" "profile"])))))))++(deftest ^:parallel check-credentials-entra-keeps-configured-default-scope-test+ (testing "OIDC credential check leaves Entra ID scopes alone when a .default scope is already configured"+ (is (= "openid https://graph.microsoft.com/.default"+ (sent-scope token-endpoint ["openid" "https://graph.microsoft.com/.default"])))))-(deftest ^:parallel check-credentials-entra-missing-scope-error-test- (testing "Entra AADSTS90014 error is surfaced correctly when scope list is empty"+(deftest ^:parallel check-credentials-non-entra-default-scope-test+ (testing "OIDC credential check never adds a .default scope for non-Entra token endpoints"+ (is (= "openid"+ (sent-scope non-entra-token-endpoint ["openid"])))))++(deftest ^:parallel check-credentials-entra-empty-scopes-test+ (testing "OIDC credential check sends only the app's own .default scope for Entra ID when no scopes are configured"+ (is (= "client-id/.default"+ (sent-scope token-endpoint [])))))++(deftest ^:parallel check-credentials-entra-invalid-scope-error-test+ (testing "OIDC credential check surfaces the full Entra ID invalid_scope error description"(mt/with-dynamic-fn-redefs [oidc.http/oidc-post(fn [_url _opts]{:status 400- :body {:error "invalid_request"- :error_description "AADSTS90014: The required field 'scope' is missing from the credential."}})]- (let [result (check/check-credentials token-endpoint "client-id" "client-secret" [])]- (is (false? (:success result)))- (is (str/includes? (:error result) "AADSTS90014"))))))+ :body {:error "invalid_scope"+ :error_description "AADSTS1002012: The provided value for scope openid is not valid."}})]+ (is (= {:step :credentials+ :success false+ :verified true+ :error "Unexpected response from token endpoint (HTTP 400): AADSTS1002012: The provided value for scope openid is not valid."}+ (check/check-credentials token-endpoint "client-id" "client-secret" ["openid"]))))))(deftest ^:parallel check-credentials-success-test(testing "HTTP 200 → success"