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
GHY-4491: Keep legacy MCP OAuth tokens alive on upgrade; answer invalid_grant for bad grants (#82950)
Eric Normand6d78fff1a146
diff --git a/resources/migrations/064/20260909_retire_mcp_v1_oauth_scopes.yaml b/resources/migrations/064/20260909_retire_mcp_v1_oauth_scopes.yamlindex a297333c30c..471b70ed17b 100644--- a/resources/migrations/064/20260909_retire_mcp_v1_oauth_scopes.yaml+++ b/resources/migrations/064/20260909_retire_mcp_v1_oauth_scopes.yaml@@ -1,11 +1,11 @@-## MCP v1 retirement (GHY-4343). `/api/metabase-mcp` now serves the v2 tool surface, whose tools gate-## on six coarse scopes. Clients connected to v0.60–v0.63 hold tokens carrying the per-entity agent-## scopes instead; no legacy scope satisfies any v2 scope, so those clients get HTTP 200 with an empty-## tools list and no error. The refresh grant can only narrow, so it never self-heals.+## MCP v1 retirement. `/api/metabase-mcp` now serves the v2 tool surface, whose tools gate on six+## coarse scopes. Clients connected to v0.60–v0.63 hold tokens carrying the per-entity agent scopes+## instead; no legacy scope satisfies any v2 scope. A call short of scope gets a 403+## `insufficient_scope` step-up, so the client re-authorizes.##-## Two data-only changesets: widen every dynamically registered client's scope snapshot so a-## re-authorization validates, then revoke the legacy-shaped tokens so the client actually-## re-authenticates rather than refreshing. Both are idempotent.+## The first changeset widens every dynamically registered client's scope snapshot so that+## re-authorization validates. The second is a no-op: legacy tokens are left alive so clients recover+## through the step-up. Its id stays so that instances which already ran it can still roll back.databaseChangeLog:- changeSet:@@ -20,7 +20,7 @@ databaseChangeLog:- changeSet:id: v64.2026-09-09T12:00:01author: bryanmaass- comment: Revoke OAuth tokens carrying only pre-MCP-v2 scopes+ comment: No-op. Legacy-scoped OAuth tokens are left alive to recover through the 403 step-upchanges:- customChange:class: metabase.app_db.custom_migrations.RevokeLegacyMcpOAuthTokensdiff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.cljindex d3d6cce29f8..84360c94a71 100644--- a/src/metabase/app_db/custom_migrations.clj+++ b/src/metabase/app_db/custom_migrations.clj@@ -2261,12 +2261,11 @@:set {:value_with_aad (encryption/maybe-encrypt plain {:aad (mdb.setting/setting-aad "example-dashboard-id")})}:where [:= :key "example-dashboard-id"]}))))-;;; MCP v1 retirement (GHY-4343): `/api/metabase-mcp` now serves the v2 tool surface, which gates every-;;; tool on one of six coarse scopes. Clients connected to v0.60–v0.63 hold OAuth tokens carrying the-;;; per-entity agent scopes instead, and no legacy scope satisfies any v2 scope, so `list-tools` (which,-;;; when this migration was written, filtered by scope) filtered the whole surface away: HTTP 200, an-;;; empty tools list, nothing logged. It does not self-heal — the refresh grant copies the original scope-;;; forward and can only narrow — so a refreshing client stays in the zero-tools state indefinitely.+;;; MCP v1 retirement: `/api/metabase-mcp` serves the v2 tool surface, which gates every tool on one of six+;;; coarse scopes. Clients connected to v0.60–v0.63 hold OAuth tokens carrying the per-entity agent scopes+;;; instead, and no legacy scope satisfies any v2 scope. A call short of scope gets a 403 `insufficient_scope`+;;; challenge that names the v2 scopes, so the client re-authorizes; that re-authorization only validates if+;;; the client's registered scope snapshot includes the v2 scopes.;;;;;; The scope strings are literals rather than a read of `metabase.mcp.paths/v2-surface-scopes`: a;;; migration's behaviour must be frozen against later edits to that vector.@@ -2279,20 +2278,6 @@"agent:delivery:write""agent:resource:read"])-;; `agent:resource:read` is excluded: it gates only a resource, so a token holding it alone still-;; resolves zero *tools*, which is the state this migration exists to end.-(def ^:private ^:no-doc mcp-v2-tool-scopes- (set (remove #{"agent:resource:read"} mcp-v2-scopes)))--(defn- legacy-mcp-scopes?- "True when `scopes` looks like a token minted against the pre-v2 scope set: it satisfies no v2 tool- and carries at least one scope outside the six. The second half is what keeps this off tokens that- are already v2-shaped (or empty), so re-running the migration revokes nothing new."- [scopes]- (let [scopes (set (filter string? scopes))]- (and (not (some mcp-v2-tool-scopes scopes))- (boolean (some (complement (set mcp-v2-scopes)) scopes)))))-(defn- json-array-out"Parse a JSON-array column into a vector, tolerating a row that is already a collection. Returns nilfor anything that isn't an array — including unparseable JSON — so a malformed row is skipped@@ -2305,7 +2290,7 @@(vec parsed))))(define-migration WidenDynamicOAuthClientScopesForMcpV2- ;; Step 1 of 2 — raise the ceiling. Dynamically registered clients snapshot the scope set that+ ;; Raise the ceiling. Dynamically registered clients snapshot the scope set that;; existed when they registered, and `validate-scope` rejects any requested scope absent from that;; snapshot. Without this a user who re-authorizes is answered `400 invalid_request`, rendered raw;; in the browser tab, because `/oauth/authorize` validates before narrowing. Widening the snapshot@@ -2322,17 +2307,7 @@:where [:= :registration_type "dynamic"]})))(define-migration RevokeLegacyMcpOAuthTokens- ;; Step 2 of 2 — force one re-authentication. Both tables must be stamped: leaving the refresh token- ;; alive means the client silently refreshes into another legacy-scoped access token instead of- ;; re-authenticating. Once both are revoked the next request gets the existing `invalid_token` 401- ;; with the discovery challenge — the RFC 6750 path every MCP client already handles.- (doseq [table [:oauth_access_token :oauth_refresh_token]]- (run! (fn [{:keys [id scope]}]- (when (some-> (json-array-out scope) legacy-mcp-scopes?)- (t2/query {:update table- :set {:revoked_at :%now}- :where [:= :id id]})))- ;; Already-revoked rows are skipped, which is also what makes this safe to re-run.- (t2/reducible-query {:select [:id :scope]- :from [table]- :where [:= :revoked_at nil]}))))+ ;; Kept as a no-op. Legacy-scoped clients re-authorize on their own through the 403 step-up, and+ ;; revoking their tokens would instead force them through the refresh-failure path. The changeset+ ;; stays so that instances which already ran it can still roll back past it.+ nil)diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljindex e758d27e311..2a5e4cd287c 100644--- a/src/metabase/oauth_server/api/oauth.clj+++ b/src/metabase/oauth_server/api/oauth.clj@@ -411,6 +411,20 @@(contains? data :requested) "invalid_scope":else "invalid_request")))+(defn- token-error-code+ "The RFC 6749 section 5.2 `error` code for the ex-data of an exception thrown while handling a token request."+ [{:keys [error] :as data}]+ (or error+ ;; oidc-provider names a code only for its PKCE, expired refresh token, and resource-indicator errors. Its other+ ;; grant failures carry the code or refresh token that failed, or the client or redirect URI the grant is bound+ ;; to as `:expected`/`:actual`. Malformed requests carry none of these. A missing `redirect_uri` also carries+ ;; `:code`, and `invalid_grant` is right for it too: the code is consumed by then, so a retry cannot succeed.+ (if (or (contains? data :code)+ (contains? data :refresh-token)+ (and (contains? data :expected) (contains? data :actual)))+ "invalid_grant"+ "invalid_request")))+(defn- error-description"The `error_description` for an exception's ex-data: the one it carries, else `fallback`."[data fallback]@@ -650,7 +664,7 @@(catch ExceptionInfo e(log/warnf "OAuth token request failed: %s" (ex-message e))(let [data (ex-data e)- error (or (:error data) "invalid_request")]+ error (token-error-code data)]{:status (if (= error "invalid_client") 401 400):headers {"Content-Type" "application/json""Cache-Control" "no-store"diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.cljindex 2b47fecfc4a..d97a1098dc1 100644--- a/test/metabase/app_db/custom_migrations_test.clj+++ b/test/metabase/app_db/custom_migrations_test.clj@@ -3020,8 +3020,9 @@"registration snapshot and tokens scoped to it. The v2 surface gates on six coarse scopes that no ""legacy scope satisfies, so without this migration the client gets HTTP 200 with an empty tools list ""and never recovers — the refresh grant can only narrow. The migration widens the ceiling so a "- "re-authorization validates, then revokes the legacy-shaped tokens so the client actually "- "re-authenticates instead of refreshing.")+ "re-authorization validates. GHY-4491: the second changeset is a no-op. tools/list now lists every "+ "tool and a call short of scope gets a 403 insufficient_scope step-up, so a legacy client "+ "re-authorizes on its own; revoking its tokens would only force it through the refresh-failure path.")(impl/test-migrations ["v64.2026-09-09T12:00:00" "v64.2026-09-09T12:00:01"] [migrate!](let [;; The 17 scopes DCR snapshots on v0.63: 15 per-entity agent scopes + 2 mcp-ui resource scopes.legacy-scopes ["agent:sql:construct" "agent:sql:create" "agent:sql:edit" "agent:sql:read"@@ -3081,9 +3082,9 @@(is (every? scopes legacy-scopes)))))(testing "a statically registered client is left alone — it did not snapshot via DCR"(is (= (set legacy-scopes) (scopes-of :oauth_client static-id :scopes))))- (testing "legacy-scoped tokens are revoked — both tables, or the client refreshes instead of re-authing"- (is (revoked? :oauth_access_token legacy-access))- (is (revoked? :oauth_refresh_token legacy-refresh)))+ (testing "GHY-4491: legacy-scoped tokens are NOT revoked; the client self-heals through the 403 step-up"+ (is (not (revoked? :oauth_access_token legacy-access)))+ (is (not (revoked? :oauth_refresh_token legacy-refresh))))(testing "tokens already carrying a v2 tool scope keep working"(is (not (revoked? :oauth_access_token v2-access)))(is (not (revoked? :oauth_refresh_token v2-refresh))))))))diff --git a/test/metabase/mcp/transport_test.clj b/test/metabase/mcp/transport_test.cljindex cbce5cba63f..df7ac2249b6 100644--- a/test/metabase/mcp/transport_test.clj+++ b/test/metabase/mcp/transport_test.clj@@ -884,64 +884,43 @@(is (= (str "Bearer error=\"insufficient_scope\", scope=\"a b\", resource_metadata=\"" url "\"")(challenge url ["a" "b"] nil))))))-(deftest legacy-scoped-bearer-token-is-challenged-then-refused-test+(deftest legacy-scoped-bearer-token-is-stepped-up-test(testing (str "GHY-4343: `/api/metabase-mcp` now serves the v2 tool surface, but every MCP client connected to a ""shipped v0.60-v0.63 release holds a token carrying the pre-v2 per-entity agent scopes. No legacy "- "scope satisfies any v2 tool scope and `registry/list-tools` then filtered silently, so the pre-fix "- "failure mode was a successful handshake followed by HTTP 200 with an empty tools list - no error, "- "nothing logged, and no self-heal (the refresh grant copies scope forward and can only narrow). "- "`RevokeLegacyMcpOAuthTokens` stamps such tokens revoked so the client is refused outright and "- "re-authenticates. Whichever way it resolves, it must never be a 200 carrying zero tools.")+ "scope satisfies any v2 tool scope, and the pre-fix failure mode was a successful handshake followed "+ "by HTTP 200 with an empty tools list. GHY-4491: the upgrade leaves such tokens alive, so the client "+ "must recover on its own: it is listed every tool, and a call gets a 403 `insufficient_scope` "+ "challenge naming the v2 scope to re-authorize for.")(mt/with-temporary-setting-values [site-url "http://localhost:3000"](oauth-server.tu/with-oauth-client [client-id](mt/with-model-cleanup [:model/OAuthAccessToken]- (let [;; Exactly the review's token: one per-entity scope the v2 surface never gates on, plus- ;; `agent:resource:read`, which gates a resource rather than any tool.- token (issue-bearer! (mt/user->id :rasta) client-id- ["agent:question:create" "agent:resource:read"])- headers (fn [& {:as extra}]- {:request-options {:headers (merge {"authorization" (str "Bearer " token)} extra)}})- ;; The tool list is only reachable through a session, so the handshake runs first. Its status is- ;; not asserted: the point is what `tools/list` can be answered, and revoking the token moves the- ;; refusal to this call rather than removing it.- _ (testing (str "GHY-4543: before the migration this token handshakes and is listed every tool, "- "since tools/list no longer filters by scope, but can call none of them")- (let [sid (get-in (client/client-full-response- :post 200 "metabase-mcp" (headers)- (jsonrpc-request "initialize" {:capabilities {}}))- [:headers "Mcp-Session-Id"])- r (client/client-full-response :post 200 "metabase-mcp"- (headers "mcp-session-id" sid)- (jsonrpc-request "tools/list" {} 2))- tools (get-in r [:body :result :tools])- call (client/client-full-response :post 403 "metabase-mcp"- (headers "mcp-session-id" sid)- (jsonrpc-request- "tools/call"- {:name (:name (first tools))- :arguments {}}- 3))]- (is (= 200 (:status r)))- (is (seq tools))- (is (= 403 (:status call)))- (is (str/includes? (get-in call [:headers "WWW-Authenticate"] "")- "error=\"insufficient_scope\""))- (is (str/starts-with? (get-in call [:body :error :message] "")- "Insufficient scope to call tool: "))))- ;; Then put the token in the state `RevokeLegacyMcpOAuthTokens` leaves it in. The migration- ;; class itself is exercised in `metabase.app-db.custom-migrations-test`, against the changelog;- ;; what this test owns is the consequence at the transport, which is the revoked stamp.- _ (t2/update! :model/OAuthAccessToken- {:token (oidc.util/hash-token token)} {:revoked_at :%now})- init (client/client-full-response :post 401 "metabase-mcp" (headers)- (jsonrpc-request "initialize" {:capabilities {}}))]- (testing "after the migration the token is refused at the handshake, so it never holds a useless session"- (is (= 401 (:status init)))- (is (nil? (get-in init [:headers "Mcp-Session-Id"]))- "a revoked token must not be handed a working MCP session")- (let [challenge (get-in init [:headers "WWW-Authenticate"] "")]- (is (str/includes? challenge "invalid_token"))- (is (str/includes? challenge "resource_metadata=")- "the challenge carries RFC 9728 discovery, so the client knows where to re-authenticate")- (is (str/includes? challenge "agent:content:read")- "and names the v2 scopes to ask for, which the widened client snapshot now validates")))))))))+ (let [;; One per-entity scope the v2 surface never gates on, plus `agent:resource:read`, which gates a+ ;; resource rather than any tool.+ token (issue-bearer! (mt/user->id :rasta) client-id+ ["agent:question:create" "agent:resource:read"])+ headers (fn [& {:as extra}]+ {:request-options {:headers (merge {"authorization" (str "Bearer " token)} extra)}})+ sid (get-in (client/client-full-response+ :post 200 "metabase-mcp" (headers)+ (jsonrpc-request "initialize" {:capabilities {}}))+ [:headers "Mcp-Session-Id"])+ listed (client/client-full-response :post 200 "metabase-mcp"+ (headers "mcp-session-id" sid)+ (jsonrpc-request "tools/list" {} 2))+ tools (get-in listed [:body :result :tools])+ call (client/client-full-response :post 403 "metabase-mcp"+ (headers "mcp-session-id" sid)+ (jsonrpc-request "tools/call" {:name "search" :arguments {}} 3))+ challenge (get-in call [:headers "WWW-Authenticate"] "")]+ (testing "the handshake succeeds and every tool is listed, since tools/list does not filter by scope"+ (is (string? sid))+ (is (some #{"search"} (map :name tools))))+ (testing "a call is refused with a step-up challenge rather than a 200 or a 401"+ (is (= 403 (:status call)))+ (is (str/includes? challenge "error=\"insufficient_scope\""))+ (is (str/includes? challenge "agent:content:read")+ "the challenge names the v2 scope to ask for, which the widened client snapshot validates")+ (is (str/includes? challenge "resource_metadata=")+ "and carries RFC 9728 discovery, so the client knows where to re-authorize")+ (is (str/starts-with? (get-in call [:body :error :message] "")+ "Insufficient scope to call tool: ")))))))))diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljindex 1b06b9034a7..832149565cb 100644--- a/test/metabase/oauth_server/api_test.clj+++ b/test/metabase/oauth_server/api_test.clj@@ -916,7 +916,7 @@"Should return full token response"))))))(deftest token-auth-code-invalid-code-test- (testing "Authorization code grant -- invalid code returns error"+ (testing "GHY-4491: Authorization code grant -- an unknown code is an invalid grant (RFC 6749 section 5.2)"(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}](let [test-client (create-test-client!)@@ -928,10 +928,10 @@:redirect_uri "https://example.com/callback"}:expected-status 400:authorization (basic-auth-header client-id client-secret))]- (is (=? {:error string?} response)))))))+ (is (=? {:error "invalid_grant"} response)))))))(deftest token-auth-code-wrong-client-test- (testing "Authorization code grant -- wrong client gets error"+ (testing "GHY-4491: Authorization code grant -- a code issued to another client is an invalid grant"(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}](let [client-a (create-test-client!)@@ -947,7 +947,22 @@:redirect_uri "https://example.com/callback"}:expected-status 400:authorization (basic-auth-header (:client_id client-b) (:client_secret client-b)))]- (is (=? {:error string?} response)))))))+ (is (=? {:error "invalid_grant"} response)))))))++(deftest token-auth-code-redirect-uri-mismatch-test+ (testing "GHY-4491: Authorization code grant -- a redirect_uri that differs from the authorization request's is an+ invalid grant"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [{:keys [client_id client_secret]} (create-test-client!)+ code (authorize-and-get-code! client_id)]+ (is (=? {:error "invalid_grant"}+ (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/other-callback"}+ :expected-status 400+ :authorization (basic-auth-header client_id client_secret)))))))))(deftest token-refresh-grant-test(testing "Refresh token grant -- returns new access token"@@ -1026,7 +1041,7 @@(is (=? {:error string?} response)))))))(deftest token-missing-grant-type-test- (testing "Missing grant_type -- returns 400"+ (testing "Missing grant_type -- a malformed request stays invalid_request"(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}](let [test-client (create-test-client!)@@ -1034,7 +1049,18 @@{}:expected-status 400:authorization (basic-auth-header (:client_id test-client) (:client_secret test-client)))]- (is (=? {:error string?} response)))))))+ (is (=? {:error "invalid_request"} response)))))))++(deftest token-refresh-missing-refresh-token-test+ (testing "GHY-4491: a refresh_token grant with no refresh_token is a malformed request, not an invalid grant"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [{:keys [client_id client_secret]} (create-test-client!)]+ (is (=? {:error "invalid_request"}+ (token-request!+ {:grant_type "refresh_token"}+ :expected-status 400+ :authorization (basic-auth-header client_id client_secret)))))))))(deftest token-basic-auth-test(testing "Client auth via Basic header works"@@ -1131,12 +1157,12 @@:redirect_uri "https://example.com/callback"}:expected-status 400:authorization (basic-auth-header client-id client-secret))]- (is (=? {:error string?} response)))))))+ (is (=? {:error "invalid_grant"} response)))))));;; ----------------------------------------- Expired / Revoked Token Tests ------------------------------------(deftest token-auth-code-expired-code-test- (testing "Authorization code grant with expired code returns error"+ (testing "GHY-4491: Authorization code grant with an expired code is an invalid grant"(mt/with-temporary-setting-values [site-url "http://localhost:3000"oauth-server-authorization-code-ttl 1](t2/with-transaction [_conn nil {:rollback-only true}]@@ -1146,7 +1172,7 @@code (authorize-and-get-code! client-id)](is (string? code) "Should get an authorization code")(Thread/sleep 1500)- (is (=? {:error string?}+ (is (=? {:error "invalid_grant"}(token-request!{:grant_type "authorization_code":code code@@ -1212,7 +1238,9 @@:authorization (basic-auth-header client_id client_secret)))))))))(deftest token-refresh-revoked-token-test- (testing "Refresh token grant with revoked refresh token returns error"+ (testing (str "GHY-4491: a revoked refresh token is an invalid grant (RFC 6749 section 5.2). Claude Code drops its "+ "stored tokens and asks the user to sign in again on invalid_grant, but keeps retrying the dead "+ "tokens on invalid_request.")(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}](let [test-client (create-test-client!)@@ -1234,7 +1262,38 @@:refresh_token refresh-token}:expected-status 400:authorization (basic-auth-header client-id client-secret))]- (is (=? {:error string?} response))))))))+ (is (=? {:error "invalid_grant"} response))))))))++(deftest token-refresh-unknown-token-test+ (testing "GHY-4491: an unknown refresh token is an invalid grant"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [{:keys [client_id client_secret]} (create-test-client!)]+ (is (= {:error "invalid_grant"+ :error_description invalid-token-request-description}+ (token-request!+ {:grant_type "refresh_token"+ :refresh_token "not-a-refresh-token"}+ :expected-status 400+ :authorization (basic-auth-header client_id client_secret)))))))))++(deftest token-refresh-other-clients-token-test+ (testing "GHY-4491: a refresh token issued to another client is an invalid grant"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client-a (create-test-client!)+ client-b (create-test-client!)+ tokens (token-request!+ {:grant_type "authorization_code"+ :code (authorize-and-get-code! (:client_id client-a))+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header (:client_id client-a) (:client_secret client-a)))]+ (is (=? {:error "invalid_grant"}+ (token-request!+ {:grant_type "refresh_token"+ :refresh_token (:refresh_token tokens)}+ :expected-status 400+ :authorization (basic-auth-header (:client_id client-b) (:client_secret client-b))))))))))(deftest revocation-valid-token-test(testing "Revocation returns 200 for a valid access token"