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 MCP OAuth discovery behind a TLS-terminating proxy (#75110)
Chris Truter594f46f9ff8c
diff --git a/src/metabase/oauth_server/api/metadata.clj b/src/metabase/oauth_server/api/metadata.cljindex 85348467a2b..d40963434b5 100644--- a/src/metabase/oauth_server/api/metadata.clj+++ b/src/metabase/oauth_server/api/metadata.clj@@ -38,15 +38,8 @@(or (discovery-response){:status 404 :body {:error "not_found"}}))-(api.macros/defendpoint :get "/oauth-protected-resource/api/mcp"- :- [:map- [:status [:= 200]]- [:body [:map- [:resource :string]- [:authorization_servers [:sequential :string]]- [:scopes_supported [:sequential :string]]- [:bearer_methods_supported [:sequential :string]]]]]- "Returns OAuth Protected Resource Metadata (RFC 9728) for the MCP endpoint."+(defn- protected-resource-response+ "Build the OAuth Protected Resource Metadata (RFC 9728) response for the MCP endpoint."[](let [site-url (system/site-url)]{:status 200@@ -55,3 +48,26 @@:authorization_servers [site-url]:scopes_supported (vec (oauth-server/all-agent-scopes)):bearer_methods_supported ["header"]}}))++(def ^:private protected-resource-schema+ [:map+ [:status [:= 200]]+ [:body [:map+ [:resource :string]+ [:authorization_servers [:sequential :string]]+ [:scopes_supported [:sequential :string]]+ [:bearer_methods_supported [:sequential :string]]]]])++(api.macros/defendpoint :get "/oauth-protected-resource/api/mcp"+ :- protected-resource-schema+ "Returns OAuth Protected Resource Metadata (RFC 9728) for the MCP endpoint."+ []+ (protected-resource-response))++;; Some clients probe the bare resource path instead of the resource-specific one; serve the same metadata here so+;; the request doesn't fall through to the SPA's HTML catch-all and trip a `JSON.parse` error (BOT-1617).+(api.macros/defendpoint :get "/oauth-protected-resource"+ :- protected-resource-schema+ "Returns OAuth Protected Resource Metadata (RFC 9728) for the MCP endpoint."+ []+ (protected-resource-response))diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.cljindex 9bfcd4d0084..37c3377025e 100644--- a/src/metabase/oauth_server/core.clj+++ b/src/metabase/oauth_server/core.clj@@ -10,6 +10,10 @@(set! *warn-on-reflection* true)+;; Cache holds `{:site-url <string>, :provider <Provider>}`. Every endpoint baked into the provider config is+;; derived from the Site URL (see [[build-provider-config]]), so a changed Site URL must rebuild the provider --+;; otherwise discovery keeps advertising the stale issuer/endpoints (e.g. http:// behind a TLS-terminating proxy+;; after the operator corrects Site URL to https://).(defonce ^:private provider (atom nil))(defn all-agent-scopes@@ -43,13 +47,18 @@(oidc/create-provider (build-provider-config)))(defn get-provider- "Returns the current provider instance, creating it lazily if needed."+ "Returns the current provider instance, (re)creating it when absent or when the Site URL has changed."[]- (or @provider- (swap! provider (fn [p] (or p (create-provider))))))+ (let [site-url (system/site-url)]+ (:provider+ (swap! provider+ (fn [cached]+ (if (and cached (= (:site-url cached) site-url))+ cached+ {:site-url site-url, :provider (create-provider)}))))))(defn reset-provider!- "Reset the provider atom to nil. Useful for testing."+ "Reset the provider cache to nil. Useful for testing."[](reset! provider nil))diff --git a/src/metabase/server/middleware/misc.clj b/src/metabase/server/middleware/misc.cljindex 7900b105ca9..0848b2e5e85 100644--- a/src/metabase/server/middleware/misc.clj+++ b/src/metabase/server/middleware/misc.clj@@ -7,6 +7,7 @@[metabase.request.core :as request][metabase.server.streaming-response][metabase.system.core :as system]+ [metabase.util :as u][metabase.util.log :as log])(:import(clojure.core.async.impl.channels ManyToManyChannel)@@ -58,12 +59,28 @@;;;; Effectively the very first API request that gets sent to us (usually some sort of setup request) ends up setting;; the (initial) value of `site-url`-(defn- maybe-set-site-url* [{{:strs [origin x-forwarded-host host user-agent]} :headers, uri :uri}]+(defn- forwarded-scheme+ "The scheme a TLS-terminating proxy used to reach us, from `X-Forwarded-Proto`."+ [x-forwarded-proto]+ ;; first hop of a comma-separated chain (`https, http`), lower-cased: URL schemes are case-insensitive+ ;; (RFC 3986) but normalize-site-url's "http" prefix check is not, so `HTTPS` would be mangled as scheme-less.+ (some-> x-forwarded-proto (str/split #",") first str/trim not-empty u/lower-case-en))++(defn- maybe-set-site-url* [{{:strs [origin x-forwarded-host x-forwarded-proto host user-agent]} :headers, uri :uri}](when (and (mdb/db-is-set-up?)(not (system/site-url))(not (#{"/api/health" "/livez" "/readyz"} uri))(or (nil? user-agent) ((complement str/includes?) user-agent "HealthChecker")))- (when-let [site-url (or origin x-forwarded-host host)]+ ;; `origin` already carries a scheme; the `*-host` headers normally don't, so prepend the scheme the proxy+ ;; terminated TLS with -- otherwise `normalize-site-url` defaults to `http://` and a TLS-terminating proxy ends+ ;; up advertising `http://` auth/discovery URLs over an `https` origin, breaking MCP OAuth (BOT-1617). Only+ ;; prepend when the host is scheme-less; a scheme-bearing host passes through untouched.+ (when-let [site-url (or origin+ (when-let [host (or x-forwarded-host host)]+ (if-let [scheme (and (not (str/includes? host "://"))+ (forwarded-scheme x-forwarded-proto))]+ (str scheme "://" host)+ host)))](log/infof "Setting Metabase site URL to %s" site-url)(try(system/site-url! site-url)diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljindex c176a957c5c..7b3a60a1b0a 100644--- a/test/metabase/oauth_server/api_test.clj+++ b/test/metabase/oauth_server/api_test.clj@@ -46,6 +46,27 @@:bearer_methods_supported ["header"]}response))))))+(deftest protected-resource-metadata-bare-path-test+ (testing "GET /.well-known/oauth-protected-resource (no resource suffix) serves the same metadata as JSON (BOT-1617)"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-protected-resource")]+ (is (=? {:resource "http://localhost:3000/api/mcp"+ :authorization_servers ["http://localhost:3000"]+ :bearer_methods_supported ["header"]}+ response))))))++(deftest discovery-endpoint-rebuilds-on-site-url-change-test+ (testing "Discovery advertises endpoints for the *current* site-url, even after it changes (BOT-1617)"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (is (=? {:issuer "http://localhost:3000"}+ (mt/user-http-request :crowberto :get 200 ".well-known/oauth-authorization-server"))))+ (mt/with-temporary-setting-values [site-url "https://mb.example.com"]+ (is (=? {:issuer "https://mb.example.com"+ :authorization_endpoint "https://mb.example.com/oauth/authorize"+ :token_endpoint "https://mb.example.com/oauth/token"}+ (mt/user-http-request :crowberto :get 200 ".well-known/oauth-authorization-server"))))))+;;; ----------------------------------------- Dynamic Client Registration ----------------------------------------------(defn- register-client!diff --git a/test/metabase/server/middleware/misc_test.clj b/test/metabase/server/middleware/misc_test.cljindex c60be659e4e..394398a17a1 100644--- a/test/metabase/server/middleware/misc_test.clj+++ b/test/metabase/server/middleware/misc_test.clj@@ -51,6 +51,35 @@(maybe-set-site-url request)(is (= "https://mb1.example.com" (system/site-url))))))))+(deftest maybe-set-site-url-forwarded-proto-test+ (testing "scheme-less `*-host` headers get the scheme from `X-Forwarded-Proto` (BOT-1617)"+ (doseq [host-header ["X-Forwarded-Host" "Host"]]+ (testing host-header+ (mt/with-temporary-setting-values [site-url nil]+ (maybe-set-site-url (-> (m/dissoc-in (ring.mock/request :get "/") [:headers "host"])+ (ring.mock/header host-header "mb.example.com")+ (ring.mock/header "X-Forwarded-Proto" "https")))+ (is (= "https://mb.example.com" (system/site-url)))))))+ (testing "`X-Forwarded-Proto` is matched case-insensitively (RFC 3986)"+ (mt/with-temporary-setting-values [site-url nil]+ (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)+ (ring.mock/header "X-Forwarded-Proto" "HTTPS")))+ (is (= "https://mb.example.com" (system/site-url)))))+ (testing "the first hop wins when `X-Forwarded-Proto` is a comma-separated chain"+ (mt/with-temporary-setting-values [site-url nil]+ (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)+ (ring.mock/header "X-Forwarded-Proto" "https, http")))+ (is (= "https://mb.example.com" (system/site-url)))))+ (testing "without `X-Forwarded-Proto`, a scheme-less host falls back to http:// (unchanged behavior)"+ (mt/with-temporary-setting-values [site-url nil]+ (maybe-set-site-url (mock-request "/" nil "mb.example.com" nil))+ (is (= "http://mb.example.com" (system/site-url)))))+ (testing "a scheme-bearing host header is left untouched, even alongside `X-Forwarded-Proto` (no double scheme)"+ (mt/with-temporary-setting-values [site-url nil]+ (maybe-set-site-url (-> (mock-request "/" nil "https://mb.example.com" nil)+ (ring.mock/header "X-Forwarded-Proto" "https")))+ (is (= "https://mb.example.com" (system/site-url))))))+(deftest add-version-header-test(testing "x-metabase-version is only added on API calls"(with-redefs [config/mb-version-info {:tag "v42"}]diff --git a/test/metabase/transforms/jobs_test.clj b/test/metabase/transforms/jobs_test.cljindex 8f39fc79eed..c3d186dbd57 100644--- a/test/metabase/transforms/jobs_test.clj+++ b/test/metabase/transforms/jobs_test.clj@@ -627,14 +627,19 @@on-enter (fn [] (await-barrier barrier-enter))on-exit (fn [] (await-barrier barrier-exit) (.set tl-tripped true))original-insert transforms.u/try-start-unless-already-running]- (mt/with-dynamic-fn-redefs [transforms.u/try-start-unless-already-running- (fn [transform-id run-method user-id]- (on-enter)- (let [[ret ex] (try- [(original-insert transform-id run-method user-id)]- (catch Throwable t [nil t]))]- (on-exit)- (if ex (throw ex) ret)))]+ ;; with-redefs, not with-dynamic-fn-redefs: run-transforms! dispatches each transform on an+ ;; ExecutorService worker (transforms-sql-worker), which doesn't convey dynamic bindings, so a+ ;; proxy-based redef is invisible there and the barrier choreography silently no-ops. A global+ ;; root swap is seen by every thread.+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}+ (with-redefs [transforms.u/try-start-unless-already-running+ (fn [transform-id run-method user-id]+ (on-enter)+ (let [[ret ex] (try+ [(original-insert transform-id run-method user-id)]+ (catch Throwable t [nil t]))]+ (on-exit)+ (if ex (throw ex) ret)))](let [run1 (transforms.job-run/start-run! (:id job) :manual)run2 (transforms.job-run/start-run! (:id job) :manual)fut1 (future