Skip to content

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

MCP further nits (#71478)

Chris Truter77afdaafc077
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index 459bf3074bf..ab5aa3e51df 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -22,6 +22,7 @@
[metabase.server.streaming-response :as streaming-response]
[metabase.util :as u]
[metabase.util.json :as json]
+ [metabase.util.log :as log]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -799,16 +800,17 @@
(defn- enforce-authentication
"Middleware that ensures requests are authenticated.
- Always sets `:token-scopes` on authenticated requests — `#{::scope/unrestricted}` for unrestricted access
- (session auth or unscoped JWTs), or the parsed scope set for scoped JWTs. This ensures downstream scope
- enforcement never has to special-case nil within the agent API.
+ Ensures `:token-scopes` is present on authenticated requests.
- Supports two authentication modes:
- - **Session-based**: Uses `X-Metabase-Session` header, validated by standard Metabase
- session middleware (which runs before this). If `:metabase-user-id` is set on the
- request, the user is already authenticated.
- - **Stateless JWT**: Uses `Authorization: Bearer <jwt>` header. The JWT is validated
- using the same auth-identity system as the /auth/sso endpoint."
+ - For **session-authenticated** requests (where `:metabase-user-id` is already set by
+ upstream middleware), preserves any pre-existing `:token-scopes` value if present,
+ otherwise defaults to `#{::scope/unrestricted}` for unrestricted access.
+ - For **JWT-authenticated** requests, derives `:token-scopes` from the JWT when a
+ `\"scope\"` claim is present, falls back to any pre-existing `:token-scopes` on the
+ request, and finally defaults to `#{::scope/unrestricted}` for unscoped JWTs.
+
+ This ensures downstream scope enforcement never has to special-case nil within the
+ agent API."
[handler]
(fn [{:keys [headers metabase-user-id token-scopes] :as request} respond raise]
(cond
@@ -839,10 +841,17 @@
:else
(let [result (authenticate-with-jwt bearer-token)]
(if-let [user (:user result)]
- (request/with-current-user (:id user)
- (handler (assoc request :token-scopes (or (:scopes result) #{::scope/unrestricted}))
- respond raise))
+ (do
+ (when (and (:scopes result) token-scopes (not= (:scopes result) token-scopes))
+ (log/warn "JWT scopes" (:scopes result)
+ "differ from pre-existing token-scopes" token-scopes))
+ (request/with-current-user (:id user)
+ (handler (assoc request :token-scopes (or (:scopes result)
+ token-scopes
+ #{::scope/unrestricted}))
+ respond raise)))
(respond (error-response (:error result) (:message result))))))))))
+
(def +auth
"Agent API authentication middleware. Supports both session-based and stateless JWT authentication."
(api.routes.common/wrap-middleware-for-open-api-spec-generation enforce-authentication))
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index abac66aa746..60394bf2701 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -36,7 +36,7 @@
:same-site :strict
:path "/oauth/authorize"
:max-age max-age}
- (str/starts-with? (system/site-url) "https")
+ (some-> (system/site-url) (str/starts-with? "https"))
(assoc :secure true)))
(defn- canonical-params-string
@@ -217,7 +217,7 @@
:body {:error "unauthorized"}}
(or (when-let [provider (oauth-server/get-provider)]
(let [cookie-token (get-in request [:cookies csrf-cookie-name :value])
- form-token (str (:csrf_token body))
+ form-token (some-> (:csrf_token body) str)
auth-params (select-keys body oauth-param-keys)
params-sig (some-> (:params_sig body) str)]
(if (or (str/blank? cookie-token)
@@ -233,6 +233,8 @@
;; This must happen after parsing to ensure form-encoding round-trips don't cause mismatches.
parsed-params (select-keys parsed oauth-param-keys)]
(if (or (str/blank? params-sig)
+ (not (re-matches #"[a-fA-F0-9]+" params-sig))
+ (odd? (count params-sig))
(not (verify-oauth-params-signature cookie-token parsed-params params-sig)))
{:status 403
:headers {"Content-Type" "application/json"}
diff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.clj
index d97e5be794b..d38d7a26acc 100644
--- a/src/metabase/oauth_server/consent_page.clj
+++ b/src/metabase/oauth_server/consent_page.clj
@@ -51,7 +51,10 @@
"Return `color` if it looks like a safe CSS color value (hex or named color),
otherwise return the default brand color. Prevents CSS injection via `h/raw` interpolation."
[color]
- (if (and (string? color) (re-matches #"#[0-9a-fA-F]{3,8}|[a-zA-Z]+" color))
+ (if (and (string? color)
+ (or (re-matches #"[a-zA-Z]+" color)
+ ;; 3-8 hex chars is permissive (valid lengths are 3,4,6,8) but no injection risk
+ (re-matches #"#[0-9a-fA-F]{3,8}" color)))
color
default-brand-color))
@@ -82,7 +85,7 @@
[:head
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
- [:title "Authorize " client-name]
+ [:title "Authorize " (or client-name "Unknown Application")]
[:style {:nonce nonce} (h/raw
(str
(font-face-css font-family)
@@ -114,7 +117,7 @@
(h/raw svg)
[:img {:src logo-url :alt "Logo" :height "32"}])]
[:h1 "Authorize " (or client-name "Unknown Application") "?"]
- [:p.client-id client-id]
+ (when client-id [:p.client-id client-id])
[:p.subtitle "This MCP client is requesting to be authorized. If you approve, it will be able to access resources from "
[:strong (appearance/application-name)] " on your behalf."]
[:form {:method "POST" :action "/oauth/authorize/decision"}
diff --git a/test/metabase/mcp/tools_test.clj b/test/metabase/mcp/tools_test.clj
new file mode 100644
index 00000000000..fc32b8dca7a
--- /dev/null
+++ b/test/metabase/mcp/tools_test.clj
@@ -0,0 +1,27 @@
+(ns metabase.mcp.tools-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.macros.scope :as scope]
+ [metabase.mcp.tools :as mcp.tools]))
+
+(deftest scope-matches?-test
+ (let [scope-matches? #'mcp.tools/scope-matches?]
+ (testing "nil token-scopes (internal callers) → always matches"
+ (is (true? (scope-matches? nil "agent:read")))
+ (is (true? (scope-matches? nil nil))))
+ (testing "unrestricted token-scopes → always matches"
+ (is (true? (scope-matches? #{::scope/unrestricted} "agent:read")))
+ (is (true? (scope-matches? #{::scope/unrestricted} nil))))
+ (testing "nil tool-scope with scoped token → denied"
+ (is (nil? (scope-matches? #{"agent:read"} nil)))
+ (is (nil? (scope-matches? #{} nil))))
+ (testing "exact scope match"
+ (is (true? (scope-matches? #{"agent:read"} "agent:read")))
+ (is (nil? (scope-matches? #{"agent:write"} "agent:read"))))
+ (testing "wildcard scope match"
+ (is (true? (scope-matches? #{"agent:*"} "agent:read")))
+ (is (true? (scope-matches? #{"agent:*"} "agent:write")))
+ (is (nil? (scope-matches? #{"other:*"} "agent:read"))))
+ (testing "no match"
+ (is (nil? (scope-matches? #{"foo:bar"} "agent:read")))
+ (is (nil? (scope-matches? #{} "agent:read"))))))
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index 957e0331df9..c176a957c5c 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -410,6 +410,79 @@
:csrf-cookie csrf-cookie)]
(is (= "csrf_validation_failed" (:error (:body response)))))))))
+(deftest authorize-decision-params-tampered-test
+ (testing "POST /oauth/authorize/decision with tampered state returns 403 params_tampered"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [client (create-test-client!)
+ client-id (:client_id client)
+ consent-resp (get-consent-page! :crowberto client-id)
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
+ csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent consent-body)
+ response (form-post-decision!
+ :crowberto
+ {:approved "true"
+ :csrf_token csrf-token
+ :params_sig params-sig
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope "profile"
+ :state "tampered-state"} ;; tampered state
+ 403
+ :csrf-cookie csrf-cookie)]
+ (is (= "params_tampered" (:error (:body response)))))))))
+
+(deftest authorize-decision-missing-params-sig-test
+ (testing "POST /oauth/authorize/decision with missing params_sig returns 403 params_tampered"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [client (create-test-client!)
+ client-id (:client_id client)
+ consent-resp (get-consent-page! :crowberto client-id)
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
+ csrf-cookie (extract-csrf-cookie consent-resp)
+ response (form-post-decision!
+ :crowberto
+ {:approved "true"
+ :csrf_token csrf-token
+ ;; no params_sig
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope "profile"
+ :state "test-state"}
+ 403
+ :csrf-cookie csrf-cookie)]
+ (is (= "params_tampered" (:error (:body response)))))))))
+
+(deftest authorize-decision-non-hex-params-sig-test
+ (testing "POST /oauth/authorize/decision with non-hex params_sig returns 403 params_tampered"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [client (create-test-client!)
+ client-id (:client_id client)
+ consent-resp (get-consent-page! :crowberto client-id)
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
+ csrf-cookie (extract-csrf-cookie consent-resp)
+ response (form-post-decision!
+ :crowberto
+ {:approved "true"
+ :csrf_token csrf-token
+ :params_sig "zzzz-not-hex!"
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope "profile"
+ :state "test-state"}
+ 403
+ :csrf-cookie csrf-cookie)]
+ (is (= "params_tampered" (:error (:body response)))))))))
+
(deftest authorize-decision-unauthenticated-test
(testing "POST /oauth/authorize/decision without session returns 401"
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]