Skip to content

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

Separate MCP and REST OAuth tokens by scope (GHY-4969) (#84811)

Eric Normand7cac28c9ca9b
diff --git a/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts
index a83c04449ea..64b2af6b60d 100644
--- a/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts
+++ b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts
@@ -73,7 +73,8 @@ describe("scenarios > admin > metabot > oauth authorizations", () => {
const authorizeUrl =
`/oauth/authorize?client_id=${client.client_id}` +
`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` +
- `&response_type=code&scope=${encodeURIComponent(SCOPE)}&state=test-state`;
+ `&response_type=code&scope=${encodeURIComponent(SCOPE)}&state=test-state` +
+ `&resource=${encodeURIComponent(mcpResource())}`;
// Stub a same-origin HTML response so the browser navigates to it (firing a `load` event
// Cypress can wait on) instead of following the real 302 to the external redirect_uri, which
@@ -153,7 +154,8 @@ function decideClient(client: RegisteredClient, approved: boolean) {
const authorizeUrl =
`/oauth/authorize?client_id=${clientId}` +
`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` +
- `&response_type=code&scope=${encodeURIComponent(SCOPE)}&state=test-state`;
+ `&response_type=code&scope=${encodeURIComponent(SCOPE)}&state=test-state` +
+ `&resource=${encodeURIComponent(mcpResource())}`;
return cy.request("GET", authorizeUrl).then(({ body }) => {
cy.request({
@@ -170,6 +172,7 @@ function decideClient(client: RegisteredClient, approved: boolean) {
response_type: "code",
scope: SCOPE,
state: "test-state",
+ resource: mcpResource(),
},
})
.its("status")
@@ -177,6 +180,10 @@ function decideClient(client: RegisteredClient, approved: boolean) {
});
}
+function mcpResource() {
+ return `${Cypress.config("baseUrl")}/api/metabase-mcp`;
+}
+
/**
* Assert exactly one table row contains all of the given texts together — ties a specific event
* (and the deciding user) to the expected client's row rather than checking page-wide counts.
diff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.clj
index 827e957170c..200525e0256 100644
--- a/src/metabase/app_db/custom_migrations.clj
+++ b/src/metabase/app_db/custom_migrations.clj
@@ -2265,9 +2265,9 @@
;;; 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.
+;;; instead, and no legacy scope satisfies any v2 scope. The MCP endpoint refuses a token with no v2 scope
+;;; with a 401 `invalid_token`, 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.scope/v2-surface-scopes`: a
;;; migration's behaviour must be frozen against later edits to that vector.
@@ -2309,9 +2309,9 @@
:where [:= :registration_type "dynamic"]})))
(define-migration RevokeLegacyMcpOAuthTokens
- ;; 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.
+ ;; Kept as a no-op. The MCP endpoint refuses legacy-scoped tokens with a 401 `invalid_token`, so the
+ ;; client re-authorizes and revoking the tokens adds nothing. The changeset stays so that instances
+ ;; which already ran it can still roll back past it.
nil)
(define-migration MoveDataAppResourceCollectionsToTheirNamespace
diff --git a/src/metabase/mcp/http_handler.clj b/src/metabase/mcp/http_handler.clj
index 0c2d57b227b..38452ba7130 100644
--- a/src/metabase/mcp/http_handler.clj
+++ b/src/metabase/mcp/http_handler.clj
@@ -15,6 +15,7 @@
:oauth-bearer {:extract-token #'oauth-server/extract-bearer-token
:resolve-token #'oauth-server/resolve-access-token
:full-access-scope oauth-server/full-access-scope
+ :mcp-scopes (set (mcp/v2-scopes))
:bearer-only-paths mcp.paths/endpoint-paths}
:mcp-ui-credentials {:on-surface? #'mcp/ui-credential-on-surface?
:resolve-credential #'mcp/resolve-ui-credential
diff --git a/src/metabase/mcp/paths.clj b/src/metabase/mcp/paths.clj
index 9a9a80f52ce..3cb3c9bbf2f 100644
--- a/src/metabase/mcp/paths.clj
+++ b/src/metabase/mcp/paths.clj
@@ -19,11 +19,10 @@
The following are derived from this set and must not drift from it:
1. the route table mounts exactly these paths
2. `metabase.oauth-server.api.metadata` publishes one RFC 9728 document per path
- 3. `metabase.oauth-server.core/narrow-scope-to-resources` recognises an RFC 8707 `resource` indicator
+ 3. `metabase.oauth-server.api.oauth/narrow-scope-to-resource` recognises an RFC 8707 `resource` indicator
only if it names one.
4. the session middleware uses these to determine bearer-only paths
- A path that still serves traffic but has dropped out of this set fails OPEN — the indicator matches nothing, so the
- grant is never narrowed to the MCP surface."
+ A path that still serves traffic but is missing from this set fails CLOSED, so the grant loses every MCP scope."
#{canonical-path
"/api/mcp"})
diff --git a/src/metabase/mcp/transport.clj b/src/metabase/mcp/transport.clj
index 97eed6e9e7a..92aa992e5d4 100644
--- a/src/metabase/mcp/transport.clj
+++ b/src/metabase/mcp/transport.clj
@@ -715,8 +715,11 @@
`:endpoint-paths`.
- `:default-ask-scopes` — optional scopes emitted as the `scope` parameter of the 401
`WWW-Authenticate` challenge, i.e. what a client that has not been told otherwise asks for.
- Omit to let clients ask for everything the resource metadata advertises."
- [{:keys [tools-hash-fn endpoint-paths default-path default-ask-scopes] :as opts}]
+ Omit to let clients ask for everything the resource metadata advertises.
+ - `:accepted-scopes` — the set of scope strings that mark an OAuth token as issued for this surface. An
+ OAuth-authenticated request whose token holds none of them gets the 401 `invalid_token` challenge.
+ Other auth methods are not checked."
+ [{:keys [tools-hash-fn endpoint-paths default-path default-ask-scopes accepted-scopes] :as opts}]
(open-api/handler-with-open-api-spec
(fn [request respond raise]
(let [origin-error (validate-origin request)
@@ -758,16 +761,15 @@
(some? origin-error)
(respond origin-error)
- ;; The session middleware never authenticates an OAuth token without scopes. Should one arrive, refuse it
- ;; as an invalid token.
- (and (:authenticated-via-oauth? request) (empty? token-scopes))
+ ;; An OAuth token holding none of this surface's scopes was not issued for this server, e.g. a REST token,
+ ;; so the MCP auth spec requires `invalid_token`. A token without scopes falls here too.
+ (and (:authenticated-via-oauth? request) (not-any? accepted-scopes token-scopes))
(respond @invalid-token)
;; MCP authenticates only with an OAuth bearer token. The session middleware already ignores sessions and
;; API keys on the MCP paths; this check keeps a request with a current user but no OAuth marker from
- ;; dispatching should one arrive anyway. It gets the 401 discovery challenge below. An `mb:full` token
- ;; carries the unrestricted sentinel next to its other granted scopes; the sentinel is not an MCP scope, so
- ;; only those strings reach MCP.
+ ;; dispatching should one arrive anyway. It gets the 401 discovery challenge below. A token that reaches
+ ;; here holds an MCP scope, so the session middleware kept only MCP scopes; the filter keeps only strings.
(and current-user-id (:authenticated-via-oauth? request))
(dispatch current-user-id (into #{} (filter string?) token-scopes))
diff --git a/src/metabase/mcp/v2/api.clj b/src/metabase/mcp/v2/api.clj
index 4e2861a01c1..1cfeba3894c 100644
--- a/src/metabase/mcp/v2/api.clj
+++ b/src/metabase/mcp/v2/api.clj
@@ -230,4 +230,5 @@
:tools-hash-fn registry/tools-hash
:endpoint-paths mcp.paths/endpoint-paths
:default-path mcp.paths/canonical-path
- :default-ask-scopes default-ask-scopes}))
+ :default-ask-scopes default-ask-scopes
+ :accepted-scopes (set mcp.scope/v2-surface-scopes)}))
diff --git a/src/metabase/oauth_server/api/metadata.clj b/src/metabase/oauth_server/api/metadata.clj
index e0a1ef017df..5180a2cf758 100644
--- a/src/metabase/oauth_server/api/metadata.clj
+++ b/src/metabase/oauth_server/api/metadata.clj
@@ -51,23 +51,20 @@
[:bearer_methods_supported [:sequential :string]]]]])
(defn- protected-resource-metadata
- "OAuth Protected Resource Metadata (RFC 9728) advertising `resource-path` as the protected resource, with the
- scopes that [[metabase.oauth-server.core/mcp-resource-advertised-scopes]] returns for `resource-path` as
- `:scopes_supported`."
+ "OAuth Protected Resource Metadata (RFC 9728) advertising `resource-path` as the protected resource, with every
+ [[metabase.mcp.core/v2-scopes]] as `:scopes_supported`."
[resource-path]
- ;; The scopes are derived from `resource-path` rather than passed in, so the resource and its advertised scopes
- ;; cannot disagree.
(let [site-url (system/site-url)]
{:status 200
:headers {"Content-Type" "application/json"}
:body {:resource (str site-url resource-path)
:authorization_servers [site-url]
- :scopes_supported (oauth-server/mcp-resource-advertised-scopes resource-path)
+ :scopes_supported (vec (mcp/v2-scopes)) ;; all mcp scopes; this is what clients will request
:bearer_methods_supported ["header"]}}))
;; One endpoint per MCP path, kept in sync with [[metabase.mcp.paths/endpoint-paths]]. Each advertises its own
;; path as `:resource`, so a strict RFC 9728 client connecting via an alias still sees a resource value matching
-;; the URL it hit — and [[metabase.oauth-server.core/narrow-scope-to-resource]] recognizes all of them, so the
+;; the URL it hit — and [[metabase.oauth-server.api.oauth/narrow-scope-to-resource]] recognizes all of them, so the
;; scope narrowing applies whichever path the client came in on.
(api.macros/defendpoint :get "/oauth-protected-resource/api/metabase-mcp"
:- resource-metadata-response-schema
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index a27720328d6..f3efbe69899 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -17,6 +17,7 @@
[metabase.request.core :as request]
[metabase.server.middleware.security :as mw.security]
[metabase.system.core :as system]
+ [metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli.schema :as ms]
[metabase.util.throttle :as u.throttle]
@@ -106,11 +107,9 @@
(defn- scope-tokens
"Split a space-separated OAuth `scope` value into its distinct scope strings, in first-seen order. Returns nil when
- blank.
-
- Deduplicating here is what keeps a repeated scope out of the granted token: the decision filters the grant from this
- list, so a duplicate left in it would be stored twice."
+ blank."
[scope-param]
+ ;; deduplicate to keep repeated scope out of granted token
(some-> scope-param str str/trim not-empty (str/split #"\s+") distinct vec))
(defn- requested-scope-descriptions
@@ -160,8 +159,16 @@
(def ^:private invalid-target-description
"The resource parameter must be an absolute URI without a fragment.")
-(def ^:private narrowed-away-scope-description
- "The requested scopes are not accepted by the requested resource.")
+(defn- narrowed-away-scope-description
+ "The `error_description` for an authorization request in which no requested scope is accepted by `resources`."
+ [resources]
+ ;; Names only the server's own MCP resource URL: the client's `resource` may hold characters RFC 6749 forbids here.
+ (let [mcp-resource (str (system/site-url) (mcp/mcp-canonical-path))]
+ (if (empty? resources)
+ (str "No resource was requested, so no MCP scopes can be granted. "
+ "Send the MCP server's resource URL, which is " mcp-resource ".")
+ (str "The requested scopes are not accepted by the requested resource. "
+ "The MCP server's resource URL is " mcp-resource "."))))
(defn- authorization-server-metadata-url
"Absolute URL of the RFC 8414 authorization server metadata document, which lists `scopes_supported`."
@@ -383,14 +390,13 @@
;; - application_type defaults to "native" (not the RFC default "web") so
;; CLI tools and desktop apps can use HTTP loopback redirects.
;; - scope defaults to every scope any surface advertises. That is a ceiling on
- ;; what the client may later request, not a grant (see
- ;; [[metabase.oauth-server.core/default-grant-scopes]]), and clients derive what
- ;; to request from discovery metadata rather than from this value.
+ ;; what the client may later request, not a grant (RFC 7591), and clients derive
+ ;; what to request from discovery metadata rather than from this value.
(let [body (cond-> body
(not (contains? body :application_type))
(assoc :application_type "native")
(not (contains? body :scope))
- (assoc :scope (str/join " " (oauth-server/default-grant-scopes)))
+ (assoc :scope (str/join " " (oauth-server/supported-scopes)))
;; Remove client_credentials grant type — tokens issued without a
;; user context are unusable for MCP (validate-bearer-token requires
;; a valid user-id).
@@ -465,6 +471,73 @@
(:error_description data)
fallback))
+(def ^:private scheme-default-port
+ {"http" 80, "https" 443})
+
+(defn- canonical-resource-uri
+ "Canonical form of a resource identifier, for comparing indicators that clients spell differently.
+
+ Lowercases scheme and host, elides the scheme's default port, and trims a trailing slash. Query and fragment are
+ dropped: the canonical form has neither, and ignoring them can only cause narrowing, never widening. Returns nil for
+ anything that is not an absolute URI, which then matches nothing.
+
+ Per RFC 3986 the scheme and host are case-insensitive and the default port is elidable; the path is neither, so
+ `/API/v2` deliberately does not canonicalize to `/api/v2`."
+ [s]
+ (when s
+ (try
+ (let [^java.net.URI uri (java.net.URI. (str s))
+ scheme (some-> (.getScheme uri) u/lower-case-en)
+ ;; `.getHost` is nil for a host java.net.URI considers non-conformant -- notably one with an
+ ;; underscore, which is routine for Docker Compose / k8s service names and which Metabase's own
+ ;; `u/url?` accepts. Reading the authority instead keeps those canonicalizing; a nil host here
+ ;; would return nil, match nothing, and disable narrowing instance-wide and silently.
+ authority (some-> (.getAuthority uri) u/lower-case-en)
+ [host port] (when authority
+ (if-let [[_ h p] (re-matches #"(?:[^@]*@)?(.*?)(?::(\d+))?" authority)]
+ [h (some-> p parse-long)]
+ [authority nil]))
+ path (or (.getPath uri) "")]
+ (when (and scheme (not-empty host))
+ (str scheme "://" host
+ (when-not (or (nil? port) (= port (scheme-default-port scheme)))
+ (str ":" port))
+ (cond-> path
+ (and (> (count path) 1) (str/ends-with? path "/"))
+ (subs 0 (dec (count path)))))))
+ (catch java.net.URISyntaxException _ nil))))
+
+(defn narrow-scope-to-resource
+ "Narrow an OAuth `scope` string to what the requested `resources` accept.
+
+ An MCP token has one or more MCP `resources` listed and only MCP `resources`. Anything else (including missing
+ `resources`) is a REST token. An MCP `resource` matches the current site URL and an MCP path.
+
+ Narrows MCP tokens to only MCP scopes, and REST tokens to anything but MCP scopes. Narrowing is the way we deal with
+ mutually exclusive scopes and surfaces. Mixed resources throw invalid_scope. Returns `nil` if there are no scopes
+ valid to the resource."
+ [resources scope]
+ (let [mcp-endpoints (into #{}
+ (map #(canonical-resource-uri (str (system/site-url) %)))
+ (mcp/mcp-endpoint-paths))
+ resources-by-type (group-by #(if (mcp-endpoints %) :resource/mcp :resource/rest)
+ (into #{}
+ (keep canonical-resource-uri)
+ (cond-> resources (string? resources) vector)))]
+ (cond
+ (and (seq (:resource/mcp resources-by-type))
+ (seq (:resource/rest resources-by-type)))
+ (throw (ex-info "cannot mix mcp and rest resources in one token"
+ {:oauth-error "invalid_scope"
+ :error-description "Request a token for MCP resources or for other resources, not both."
+ :resource resources}))
+
+ (seq (:resource/mcp resources-by-type))
+ (not-empty (str/join " " (filter (set (mcp/v2-scopes)) (scope-tokens scope))))
+
+ :else
+ (not-empty (str/join " " (remove (set (mcp/v2-scopes)) (scope-tokens scope)))))))
+
(defn- token-error-response
"The token endpoint's response to an exception `e` thrown while handling a token request."
[e]
@@ -480,45 +553,38 @@
(defn- scope-to-grant
"The scope a parsed authorization request may be granted: its requested scopes filtered to the registered ones,
- then narrowed to the `resource` indicator it names. Throws `ex-info` carrying `:oauth-error` and
- `:error-description` when the request names no scope, when none of its scopes are registered, or when none of
- them survive narrowing.
+ then narrowed to the `resource` indicator it names (none means REST). Throws `ex-info` carrying `:oauth-error` and
+ `:error-description` when the request names no scope, when none of its scopes are registered, when none of them
+ survive narrowing, or when incompatible resources are requested.
- Applied by both the consent page and the decision endpoint. The consent form's signature proves only that the
- form was not tampered with by a third party: it is keyed by the CSRF token the page shows the user, so the user
- can re-sign anything. The endpoint that issues the code has to apply these rules itself.
+ Applied by both the consent page and the decision endpoint. The consent form's signature proves only that the form
+ was not tampered with by a third party: it is keyed by the CSRF token the page shows the user, so the user can
+ re-sign anything. The endpoint that issues the code has to apply these rules itself.
- Never returns a blank scope. The decision endpoint leans on that: it answers a nil grant with 403
- `params_tampered`, which is only the right status while the sole way to reach it is a choice naming an unoffered
- scope. A blank offer would make an honest approval look like tampering."
+ Never returns a blank scope. The decision endpoint leans on that: it answers a nil grant with 403 `params_tampered`,
+ which is only the right status while the sole way to reach it is a choice naming an unoffered scope. A blank offer
+ would make an honest approval look like tampering."
[parsed]
{:post [(not (str/blank? %))]}
- (let [;; A scope-less request would otherwise mint a token with no scopes.
- _ (when (str/blank? (:scope parsed))
- (throw (ex-info "no scope was requested"
- {:oauth-error "invalid_scope"
- :error-description (missing-scope-description)})))
- ;; A client can hold an unregistered scope from before registration validated them, and `scope-matches?`
- ;; would honor `*` or `agent:*` as a wildcard grant, so one must never survive. Dropping rather than
- ;; refusing (RFC 6749 section 3.3) keeps a client that still holds a since-deprecated scope able to
- ;; re-authorize, and the refusal would reach a browser tab rather than the client program. Filtered
- ;; before narrowing, so a request is treated the same with and without `resource`.
- registered (oauth-server/registered-scopes-only (:scope parsed))
- _ (when-not registered
- (throw (ex-info "no requested scope is a registered scope"
- {:oauth-error "invalid_scope"
- :error-description (no-supported-scopes-description)})))
- narrowed (oauth-server/narrow-scope-to-resource (:resource parsed) registered)]
- ;; Nothing surviving means the client asked exclusively for scopes this resource does not
- ;; accept: dropping the parameter there renders a consent screen listing nothing and mints a
- ;; zero-scope token, which looks like success while authorizing nothing on the resource the
- ;; client named. RFC 6749 section 4.1.2.1 has an error for it.
- (when-not narrowed
- (throw (ex-info "no requested scope is accepted by the named resource"
- {:oauth-error "invalid_scope"
- :error-description narrowed-away-scope-description
- :resource (:resource parsed)})))
- narrowed))
+ ;; A scope-less request would otherwise mint a token with no scopes.
+ (when (str/blank? (:scope parsed))
+ (throw (ex-info "no scope was requested"
+ {:oauth-error "invalid_scope"
+ :error-description (missing-scope-description)})))
+ (let [;; A client can hold an unregistered scope from before registration validated them, and `scope-matches?` would
+ ;; honor `*` or `agent:*` as a wildcard grant, so one must never survive. Dropping rather than refusing (RFC
+ ;; 6749 section 3.3) keeps a client that still holds a since-deprecated scope able to re-authorize, and the
+ ;; refusal would reach a browser tab rather than the client program. Filtered before narrowing, so this filter
+ ;; does not depend on `resource`.
+ registered (or (oauth-server/registered-scopes-only (:scope parsed))
+ (throw (ex-info "no requested scope is a registered scope"
+ {:oauth-error "invalid_scope"
+ :error-description (no-supported-scopes-description)})))]
+ (or (narrow-scope-to-resource (:resource parsed) registered)
+ (throw (ex-info "no requested scope is accepted by the named resource"
+ {:oauth-error "invalid_scope"
+ :error-description (narrowed-away-scope-description (:resource parsed))
+ :resource (:resource parsed)})))))
(defn- authorization-consent-response
"Validate the authorization request `query-params` and return the consent page response, which sets the CSRF
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 75d562ae602..86cf59da881 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -54,45 +54,6 @@
seq
(str/join " ")))
-(defn mcp-resource-scopes
- "The scopes the MCP resource at `path` accepts, which [[narrow-scope-to-resource]] trims a grant to. Every path in
- [[metabase.mcp.paths/endpoint-paths]] now reaches the same v2 surface, so they all accept the same set: the scopes
- the v2 tool registry gates on plus the resource scopes its UI tools render through. What the resource *advertises*
- is [[mcp-resource-advertised-scopes]].
-
- This branched while v1 was still served. v1's tools gated on the per-entity agent-API scopes
- (`agent:question:create`, `agent:sql:execute`, …), so the aliases that reached v1 had to advertise those or
- a client following the metadata would land with an empty `tools/list`. With v1 retired (#81708) the branch
- inverted: the canonical `/api/metabase-mcp` served v2 tools while advertising fourteen scopes no tool gates
- on any more, putting them on a consent screen for capabilities that no longer exist. `path` is kept in the
- signature because RFC 9728 metadata is per-resource and a future surface may diverge again."
- [_path]
- (vec (into (sorted-set) (mcp/v2-scopes))))
-
-(defn mcp-resource-advertised-scopes
- "The RFC 9728 `scopes_supported` for the MCP resource at `path`: every v2 scope, in surface order, which Claude Code
- and the Claude connectors request on first connect."
- ;; The whole surface, not the baseline (ENG-11089): a manual reconnect asks for exactly this, so a narrower list left
- ;; the write scopes unreachable for clients whose step-up is lossy.
- [_path]
- (vec (mcp/v2-scopes)))
-
-(defn default-grant-scopes
- "The scope set a dynamically-registered client is registered with when it sends no `scope` of its own (RFC 7591 makes
- the parameter optional, and the major MCP clients omit it).
-
- This is a *ceiling*, not a grant, according to the RFC: a client may later request any subset of it, and the token
- carries only what was requested and consented to. Because it is a ceiling it must cover everything any surface
- advertises — a client derives what to ask for from discovery metadata, never from what it registered with, so a
- scope we advertise but do not register is one the authorization request is rejected outright. Hence the union of
- every advertised set rather than a hand-maintained list.
-
- Narrowing this does not produce least privilege, it produces failed authorizations. The levers that shrink an issued
- token are what each resource advertises, [[narrow-scope-to-resource]], and the consent screen."
- []
- ;; sorted so the `scope` echoed back in the registration response is stable across restarts
- (into (sorted-set) (supported-scopes)))
-
(defn- widen-to-grant-ceiling
"`client` with the scopes it lacks from `mcp-scopes` appended to its `:scopes` when it is dynamically registered,
and those it lacks from `ceiling` too while `registration-enabled?`. Any other `client`, nil included, is returned
@@ -107,7 +68,7 @@
(defn- with-default-grant-ceiling
"Wrap `client-store` so that reading a client applies [[widen-to-grant-ceiling]] with the MCP surface's scopes,
- [[default-grant-scopes]], and the dynamic-registration setting. Writes pass through unchanged."
+ [[supported-scopes]], and the dynamic-registration setting. Writes pass through unchanged."
[client-store]
;; A registration `scope` can only widen what a client may later request, never narrow it: MCP clients register with
;; the narrow scope they start from and then step up on the same `client_id`, which a per-client snapshot would
@@ -125,7 +86,7 @@
(widen-to-grant-ceiling (oidc.proto/get-client client-store client-id)
(oauth-settings/oauth-server-dynamic-registration-enabled)
(when (mcp/mcp-enabled?) (mcp/v2-scopes))
- (default-grant-scopes)))
+ (supported-scopes)))
(register-client [_ client-config]
(oidc.proto/register-client client-store client-config))
(update-client [_ client-id updated-config]
@@ -173,47 +134,6 @@
(into {} (keep (fn [path] (some-> (canonical-resource-uri (str (system/site-url) path)) (vector path))))
(mcp/mcp-endpoint-paths)))
-(defn narrow-scope-to-resource
- "Narrow an OAuth `scope` string to what the requested `resources` accept.
-
- `resources` are RFC 8707 resource indicators from the authorization request. When one names the MCP resource —
- compared as [[canonical-resource-uri]], since clients disagree on trailing slashes, case, and default ports — scopes
- no named surface accepts are dropped, so the consent screen asks for what the token can actually be used for
- rather than everything the client registered. Several indicators may be sent, and the token has to work against
- each, so what survives is the union of what they accept. Returns the scope unchanged when no indicator names a
- resource we narrow for, and nil when no requested scope survives.
-
- Every alias in [[metabase.mcp.core/mcp-endpoint-paths]] counts, not just the canonical one: a client that connected
- through an alias was handed that path as its resource identifier, and narrowing has to recognize what it was told to
- send back.
-
- Only ever removes scopes: a request in which none survive is refused by the caller rather than granted an empty
- scope.
-
- `mb:full` does not survive. The MCP resource metadata never advertised it, and a client naming the MCP resource is
- asking for a token to use against that surface — which accepts none of the REST API that scope unlocks.
-
- This shapes the consent screen and the stored grant; it is not audience enforcement. `resolve-access-token` does
- not read `:resource` from the token row, so a token narrowed against one MCP path is still accepted at another,
- and a client that omits the indicator is not narrowed at all. Both gaps are inherited rather than introduced
- here; closing them is BOT-2124."
- [resources scope]
- (let [scope (some-> scope str str/trim not-empty)
- ;; A lone indicator may arrive as a bare string (the endpoint schema allows one). `keep` over a String
- ;; iterates characters, none of which canonicalize, which would silently skip narrowing entirely --
- ;; so normalize before the scan rather than relying on the caller having vectorized.
- named (into #{} (keep canonical-resource-uri)
- (cond-> resources (string? resources) vector))
- ;; Every MCP path the request actually named. A client may send several RFC 8707 indicators, and the
- ;; token has to work against each -- so the accepted set is the UNION of what they accept, not the set
- ;; of whichever one is checked first. Taking a single winner would drop the v1-only scopes when a v1
- ;; alias is named alongside v2, silently shrinking a grant the client asked for and the user approved.
- matched (keep (mcp-endpoint-paths-by-url) named)]
- (if (or (not scope) (empty? matched))
- scope
- (let [accepted (into #{} (mapcat mcp-resource-scopes) matched)]
- (not-empty (str/join " " (filter accepted (str/split scope #"\s+"))))))))
-
(defn mcp-resource-url
"Return the canonical MCP endpoint's RFC 8707 resource indicator under the Site URL.
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index 3c4689c914e..465ef5328d0 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -14,6 +14,7 @@
The second main path to authentication is an API key. For this, we look at the `X-Api-Key` header. If that matches
an ApiKey in our database, you'll be authenticated as that ApiKey's associated User."
(:require
+ [clojure.set :as set]
[clojure.string :as str]
[java-time.api :as t]
[malli.error :as me]
@@ -173,13 +174,14 @@
(assoc :embedding/auth-method "api-key")))))))
(mr/def ::oauth-bearer
- "Fns that authenticate a request by its OAuth bearer token, the scope that grants full access, and the request
- paths where a bearer token is the only credential accepted."
+ "Fns that authenticate a request by its OAuth bearer token, the scope that grants full access, the scopes that make
+ a token an MCP token, and the request paths where a bearer token is the only credential accepted."
[:map
{:closed true}
[:extract-token ifn?]
[:resolve-token ifn?]
[:full-access-scope ms/NonBlankString]
+ [:mcp-scopes [:set ms/NonBlankString]]
[:bearer-only-paths [:set [:re #"^/"]]]])
(defn- bearer-only-path?
@@ -206,19 +208,22 @@
#{::scope/unrestricted})
(defn- oauth-token->token-scopes
- "Map the OAuth scopes granted to a bearer access token onto the `:token-scopes` value the API
- scope middleware understands. A token carrying the full-access scope (`mb:full`) gets the
- unrestricted sentinel — reachable across the whole REST API as the user — next to the other
- scopes it was granted, which MCP gates on because it ignores the sentinel. Any narrower scope
- set is passed through verbatim, so the token can reach only the agent endpoints that opt into
- those scopes and is rejected elsewhere by `ensure-scopes-checked`.
-
- This mapping is the single trust hinge for OAuth bearer auth on the general API; keep it here
- and unit-test the two directions (full ⇒ unrestricted, narrow ⇒ passed through) so the
- security invariant can't silently regress."
- [full-access-scope granted-scopes]
- (if (contains? granted-scopes full-access-scope)
+ "Map the OAuth scopes granted to a bearer access token onto the `:token-scopes` value the API scope middleware
+ understands.
+
+ Rules, in this order:
+ 1. A token holding any of `mcp-scopes` is an MCP token and keeps only those.
+ 2. A full-access scope is replaced by the unrestricted sentinel.
+ 3. Anything else is unchanged."
+ [full-access-scope mcp-scopes granted-scopes]
+ (cond
+ (some mcp-scopes granted-scopes)
+ (set/intersection granted-scopes mcp-scopes)
+
+ (contains? granted-scopes full-access-scope)
(into full-access-token-scopes (disj granted-scopes full-access-scope))
+
+ :else
granted-scopes))
(mu/defn- current-user-info-for-oauth-token :- [:maybe ::request.schema/current-user-info]
@@ -227,8 +232,8 @@
merged request carries both the user identity and the access the token was granted, and marks it
`:authenticated-via-oauth?`. A token with no scopes does not authenticate. This is the only place an
OAuth access token authenticates a request to the general (`/api/*`) API."
- [{:keys [extract-token resolve-token full-access-scope]} :- [:maybe ::oauth-bearer]
- request :- ::request.schema/request]
+ [{:keys [extract-token resolve-token full-access-scope mcp-scopes]} :- [:maybe ::oauth-bearer]
+ request :- ::request.schema/request]
(when (and extract-token (init-status/complete?))
(when-let [token (extract-token request)]
(when-let [{:keys [user-id scopes]} (resolve-token token)]
@@ -236,7 +241,7 @@
(when (seq scopes)
(some-> (server.db/oauth-user-info user-id (premium-features/enable-advanced-permissions?))
(m/update-existing :is-group-manager? boolean)
- (assoc :token-scopes (oauth-token->token-scopes full-access-scope scopes)
+ (assoc :token-scopes (oauth-token->token-scopes full-access-scope mcp-scopes scopes)
:authenticated-via-oauth? true
:embedding/auth-method "oauth")))))))
diff --git a/test/metabase/mcp/transport_test.clj b/test/metabase/mcp/transport_test.clj
index f42b05029ad..82af18ca137 100644
--- a/test/metabase/mcp/transport_test.clj
+++ b/test/metabase/mcp/transport_test.clj
@@ -602,7 +602,8 @@
:capabilities {:tools {}}
:tools-hash-fn (constantly "hash")
:endpoint-paths #{"/api/metabase-mcp"}
- :default-path "/api/metabase-mcp"})
+ :default-path "/api/metabase-mcp"
+ :accepted-scopes #{"agent:test"}})
result (promise)]
(mt/with-current-user user-id
(handler (merge {:request-method :post
@@ -628,7 +629,7 @@
(is (str/includes? (get-in response [:headers "WWW-Authenticate"] "") "invalid_token")))))
(testing "an OAuth-authenticated request with token scopes is served"
(is (= 200 (:status (invoke-transport (mt/user->id :rasta)
- {:authenticated-via-oauth? true :token-scopes #{"agent:content:read"}}
+ {:authenticated-via-oauth? true :token-scopes #{"agent:test"}}
initialize)))))))))
(deftest only-oauth-authenticated-requests-are-dispatched-test
@@ -646,6 +647,27 @@
(is (str/includes? challenge "resource_metadata="))
(is (not (str/includes? challenge "invalid_token"))))))))))
+(deftest oauth-request-without-an-accepted-scope-is-refused-test
+ (testing "GHY-4969: an OAuth token that holds none of the surface's accepted scopes was not issued for this server,
+ so the MCP authorization spec requires a 401 `invalid_token`. A token holding one accepted scope is
+ served."
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [initialize {"jsonrpc" "2.0" "id" 1 "method" "initialize" "params" {"capabilities" {}}}]
+ (doseq [token-scopes [#{:metabase.api.macros.scope/unrestricted}
+ #{"agent:content:read"}
+ #{:metabase.api.macros.scope/unrestricted "agent:content:read"}]]
+ (testing (str "OAuth-authenticated with token-scopes " (pr-str token-scopes))
+ (let [response (invoke-transport (mt/user->id :rasta)
+ {:authenticated-via-oauth? true :token-scopes token-scopes}
+ initialize)]
+ (is (= 401 (:status response)))
+ (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "") "error=\"invalid_token\"")))))
+ (testing "an OAuth token holding an accepted scope is served"
+ (is (= 200 (:status (invoke-transport (mt/user->id :rasta)
+ {:authenticated-via-oauth? true
+ :token-scopes #{"agent:test" "other"}}
+ initialize)))))))))
+
;;; -------------------------------------------------- Throttling --------------------------------------------------
(deftest per-user-throttle-returns-429-test
@@ -960,42 +982,20 @@
(is (= (str "Bearer error=\"insufficient_scope\", scope=\"a b\", resource_metadata=\"" url "\"")
(challenge url ["a" "b"] nil))))))
-(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 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.")
+(deftest legacy-scoped-bearer-token-must-reauthorize-test
+ (testing (str "GHY-4343, GHY-4491, GHY-4969: MCP clients connected to a v0.60-v0.63 release hold tokens with the "
+ "pre-v2 agent scopes, and the upgrade leaves those tokens alive. They hold no v2 MCP scope, so the "
+ "endpoint refuses them as not issued for this server: a 401 `invalid_token` on `initialize`, which "
+ "makes the client re-authorize.")
(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 [;; Two agent-API scopes the v2 surface never gates on.
- 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: ")))))))))
+ (let [token (issue-bearer! (mt/user->id :rasta) client-id
+ ["agent:question:create" "agent:resource:read"])
+ response (client/client-full-response :post 401 endpoint
+ {:request-options
+ {:headers {"authorization" (str "Bearer " token)}}}
+ (jsonrpc-request "initialize" {:capabilities {}}))]
+ (is (= 401 (:status response)))
+ (is (nil? (get-in response [:headers "Mcp-Session-Id"])))
+ (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "") "error=\"invalid_token\""))))))))
diff --git a/test/metabase/mcp/v2/api_test.clj b/test/metabase/mcp/v2/api_test.clj
index 84cfa2dc2eb..eedd0aabff7 100644
--- a/test/metabase/mcp/v2/api_test.clj
+++ b/test/metabase/mcp/v2/api_test.clj
@@ -20,7 +20,6 @@
[metabase.mcp.v2.skills :as skills]
[metabase.mcp.v2.test-util :as v2.tu]
[metabase.metabot.scope :as metabot.scope]
- [metabase.oauth-server.core :as oauth-server]
[metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions-group :as perms-group]
@@ -331,8 +330,8 @@
(is (re-find #"learn\(\)" instructions))))))
(defn- do-with-tools-listed-by-grant!
- "Call `f` with `{grant tools}`: the `tools/list` result for Bearer tokens holding various scope grants, including
- none of the MCP scopes (`\"no MCP scope\"`)."
+ "Call `f` with `{grant tools}`: the `tools/list` result for Bearer tokens holding various scope grants, from one MCP
+ scope (`\"content:read\"`) to all of them."
[f]
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(oauth-server.tu/with-oauth-client [client-id]
@@ -356,26 +355,26 @@
{:request-options {:headers (assoc headers "mcp-session-id" session-id)}}
(jsonrpc-request "tools/list"))
(get-in [:body :result :tools])))))]
- (f {"no MCP scope" (bearer-tools [oauth-server/full-access-scope])
- "content:read" (bearer-tools ["agent:content:read"])
+ (f {"content:read" (bearer-tools ["agent:content:read"])
"query:run" (bearer-tools ["agent:query:run"])
"all v2 scopes" (bearer-tools (vec mcp.scope/v2-surface-scopes))}))))))
(deftest tools-list-is-identical-whatever-the-token-holds-test
(testing "GHY-4543: Claude Code keeps the first descriptors it loads for the whole session, and ChatGPT reads
`securitySchemes` to decide what to step up for. So `tools/list` must send the same tools, the same
- descriptions and the same schemes to a token holding no MCP scope and to tokens holding different scopes: text that
- varied with the grant (\"not available on this connection\") would outlive a successful re-auth, and a
- listing filtered by scope would leave a client with no tool to step up from."
+ descriptions and the same schemes to tokens holding different scopes: text that varied with the grant
+ (\"not available on this connection\") would outlive a successful re-auth, and a listing filtered by scope
+ would leave a client with no tool to step up from. GHY-4969: a token holding no MCP scope is refused
+ before the handshake, so the narrowest grant, one MCP scope, is the baseline."
(do-with-tools-listed-by-grant!
(fn [by-grant]
- (let [payloads (update-vals by-grant json/encode)
- no-scope (by-grant "no MCP scope")]
- (doseq [[grant payload] (dissoc payloads "no MCP scope")]
+ (let [payloads (update-vals by-grant json/encode)
+ baseline (by-grant "content:read")]
+ (doseq [[grant payload] (dissoc payloads "content:read")]
(testing grant
- (is (= (payloads "no MCP scope") payload))))
+ (is (= (payloads "content:read") payload))))
(testing "and the payload really carries what those clients read, so the comparison is not of two blanks"
- (let [by-name (into {} (map (juxt :name identity)) no-scope)]
+ (let [by-name (into {} (map (juxt :name identity)) baseline)]
(is (re-find #"\ARequires the \"[^\"]+\" permission \(agent:query:run\)\.\n\n"
(get-in by-name ["execute_query" :description])))
(is (= [{:type "oauth2" :scopes ["agent:content:read"]}]
@@ -589,7 +588,7 @@
against. A challenge naming scopes that set does not contain is not merely over-broad — a fresh client
asks for exactly what it was told, is answered \"Invalid scope\", and the connect fails outright. The
surface becomes unreachable over OAuth."
- (let [grantable (set ((requiring-resolve 'metabase.oauth-server.core/default-grant-scopes)))]
+ (let [grantable (set ((requiring-resolve 'metabase.oauth-server.core/supported-scopes)))]
(doseq [scope @#'v2.api/default-ask-scopes]
(testing scope
(is (contains? grantable scope)
@@ -1347,8 +1346,11 @@
(deftest rest-scopes-reach-no-mcp-tool-or-resource-test
(testing "GHY-4940: REST scopes gate REST endpoints only. A token holding every scope that is not an MCP scope (every
- registered scope and every scope a REST endpoint declares) is refused by every MCP tool and every MCP data
- resource. UI shells carry no data and are read by any token, so they are not checked."
+ registered scope and every scope a REST endpoint declares) reaches no MCP tool and no MCP resource.
+
+ GHY-4969: `mb:full` is in the set too. It gives the whole REST API, but it still gives nothing on MCP. A
+ token that holds no MCP scope was not issued for this server, so the MCP authorization spec requires the
+ endpoint to refuse it with a 401 `invalid_token`, before the handshake."
(require 'metabase.api-routes.routes)
(when config/ee-available?
(require 'metabase-enterprise.api-routes.routes))
@@ -1357,38 +1359,24 @@
:let [scope (get-in form [:metadata :scope])]
:when (string? scope)]
scope)
- ;; mb:full is left out: the session middleware expands it to the named MCP scopes.
non-mcp-scopes (into (sorted-set)
- (remove (conj v2.tu/all-scopes "mb:full"))
+ (remove v2.tu/all-scopes)
(concat endpoint-scopes (map :scope (api-scope/all-scopes))))]
(is (seq non-mcp-scopes))
- (v2.tu/do-with-bearer-token!
- non-mcp-scopes
- (fn [headers]
- (let [session-id (-> (client/client-full-response :post 200 endpoint
- {:request-options {:headers headers}}
- (jsonrpc-request "initialize" mcp-app-ui-capabilities))
- (get-in [:headers "Mcp-Session-Id"]))
- post! (fn [body]
- (client/client-full-response :post endpoint
- {:request-options {:headers (assoc headers "mcp-session-id"
- session-id)}}
- body))
- tools (get-in (post! (jsonrpc-request "tools/list")) [:body :result :tools])
- resources (get-in (post! (jsonrpc-request "resources/list")) [:body :result :resources])]
- (is (seq tools))
- (doseq [{tool-name :name} tools]
- (testing (str "tools/call " tool-name)
- (let [response (post! (jsonrpc-request "tools/call" {:name tool-name :arguments {}}))]
- (is (= 403 (:status response)))
- (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "") "error=\"insufficient_scope\"")))))
- (doseq [{:keys [uri mimeType]} resources
- :when (not= "text/html;profile=mcp-app" mimeType)]
- (testing (str "resources/read " uri)
- (let [response (post! (jsonrpc-request "resources/read" {:uri uri}))]
- (is (= 403 (:status response)))
- (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "")
- "error=\"insufficient_scope\"")))))))))))
+ (is (contains? non-mcp-scopes "mb:full"))
+ (doseq [[label scopes] [["every non-MCP scope, mb:full included" non-mcp-scopes]
+ ["only mb:full" #{"mb:full"}]
+ ["only non-MCP REST scopes" (disj non-mcp-scopes "mb:full")]]]
+ (testing label
+ (v2.tu/do-with-bearer-token!
+ scopes
+ (fn [headers]
+ (let [response (client/client-full-response :post 401 endpoint
+ {:request-options {:headers headers}}
+ (jsonrpc-request "initialize" mcp-app-ui-capabilities))]
+ (is (nil? (get-in response [:headers "Mcp-Session-Id"])))
+ (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "")
+ "error=\"invalid_token\""))))))))))
(deftest baseline-token-reads-the-fields-catalog-test
(testing "GHY-4543, GHY-4939: the locked baseline carries agent:content:read, so a client that unticked everything
@@ -1513,7 +1501,8 @@
(deftest sessions-without-mcp-scopes-reach-no-mcp-tool-test
(testing "GHY-4942: MCP tools match only the named scopes a token holds. An `mb:full` bearer token holds only
- the unrestricted sentinel, so it reaches no scoped tool. (A cookie session cannot reach MCP at all; see
+ the unrestricted sentinel, so it reaches no scoped tool. GHY-4969: it is refused before the handshake,
+ with a 401 `invalid_token`. (A cookie session cannot reach MCP at all; see
`session-and-api-key-cannot-authenticate-mcp-test`.)"
(v2.tu/do-with-temp-tool!
{:name "scope_probe_sql"
@@ -1524,15 +1513,15 @@
:args [:map]
:handler (fn [_ _] {:content [{:type "text" :text "served"}]})}
(fn []
- (let [call (jsonrpc-request "tools/call" {:name "scope_probe_sql" :arguments {}})]
- (testing "mb:full bearer token"
- (v2.tu/do-with-bearer-token!
- #{"mb:full"}
- (fn [headers]
- (let [response ((bearer-session-post! headers) 403 call)]
- (is (= 403 (:status response)))
- (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "")
- "error_description=\"scope_probe_sql requires agent:sql:run")))))))))))
+ (testing "mb:full bearer token"
+ (v2.tu/do-with-bearer-token!
+ #{"mb:full"}
+ (fn [headers]
+ (let [response (client/client-full-response :post 401 endpoint
+ {:request-options {:headers headers}}
+ (jsonrpc-request "initialize" {:capabilities {}}))]
+ (is (str/includes? (get-in response [:headers "WWW-Authenticate"] "")
+ "error=\"invalid_token\""))))))))))
(deftest mb-full-token-keeps-its-named-mcp-scopes-test
(testing "GHY-4942: mb:full grants nothing in MCP, but a token granted mb:full next to named MCP scopes still holds
@@ -1578,19 +1567,14 @@
:post status "dataset"
{:request-options {:headers {"x-metabase-mcp-ui-auth" credential}}}
query))]
- (testing "an mb:full session cannot mint a credential"
+ (testing "GHY-4969: an mb:full token cannot open a session, so it cannot mint a credential"
(v2.tu/do-with-bearer-token!
#{"mb:full"}
(fn [headers]
- (let [session-id (-> (client/client-full-response :post 200 endpoint
- {:request-options {:headers headers}}
- (jsonrpc-request "initialize" mcp-app-ui-capabilities))
- (get-in [:headers "Mcp-Session-Id"]))
- response (client/client-full-response
- :post 403 endpoint
- {:request-options {:headers (assoc headers "mcp-session-id" session-id)}}
- (jsonrpc-request "tools/call" {:name "refresh_ui_credential" :arguments {}}))]
- (is (nil? (get-in response [:body :result :_meta :com.metabase/mcp-apps :credential])))))))
+ (let [response (client/client-full-response :post 401 endpoint
+ {:request-options {:headers headers}}
+ (jsonrpc-request "initialize" mcp-app-ui-capabilities))]
+ (is (nil? (get-in response [:headers "Mcp-Session-Id"])))))))
(testing "agent:sql:execute is not an MCP scope, so it does not stand in for agent:sql:run"
(v2.tu/do-with-bearer-token!
v2.tu/all-scopes
diff --git a/test/metabase/oauth_server/api/oauth_test.clj b/test/metabase/oauth_server/api/oauth_test.clj
new file mode 100644
index 00000000000..8962ac7a258
--- /dev/null
+++ b/test/metabase/oauth_server/api/oauth_test.clj
@@ -0,0 +1,167 @@
+(ns metabase.oauth-server.api.oauth-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer [deftest is testing]]
+ [metabase.mcp.core :as mcp]
+ [metabase.oauth-server.api.oauth :as api.oauth]
+ [metabase.test :as mt]))
+
+(defn- scopes [s]
+ (set (some-> s (str/split #"\s+"))))
+
+(deftest narrow-scope-to-resource-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [mcp-uri "http://localhost:3000/api/metabase-mcp"
+ v1-uri "http://localhost:3000/api/mcp"]
+ (testing "an alias narrows to the same surface — every MCP path reaches it now, so a
+ per-entity scope no tool gates on is dropped rather than carried into the grant"
+ (let [narrowed (scopes (api.oauth/narrow-scope-to-resource
+ [v1-uri]
+ "agent:content:read agent:question:create agent:sql:execute agent:query:run"))]
+ (is (= #{"agent:content:read" "agent:query:run"} narrowed))))
+ (testing "an indicator naming the MCP resource drops scopes that surface does not accept"
+ (let [narrowed (scopes (api.oauth/narrow-scope-to-resource
+ [mcp-uri]
+ "agent:content:read agent:question:create agent:sql:execute agent:query:run"))]
+ (is (= #{"agent:content:read" "agent:query:run"} narrowed))))
+ (testing "GHY-4543: every v2 scope survives narrowing on every alias — otherwise a first connect or a
+ step-up for a write scope is stripped at consent"
+ (doseq [path (mcp/mcp-endpoint-paths)]
+ (testing path
+ (is (= (set (mcp/v2-scopes))
+ (scopes (api.oauth/narrow-scope-to-resource
+ [(str "http://localhost:3000" path)] (str/join " " (mcp/v2-scopes)))))))))
+ (testing "GHY-4226: `mb:full` is dropped like any other scope the MCP surface does not accept. A
+ client naming the MCP resource wants a token for that surface, which accepts none of
+ the REST API that scope unlocks."
+ (is (= #{"agent:content:read"}
+ (scopes (api.oauth/narrow-scope-to-resource
+ [mcp-uri] "mb:full agent:content:read agent:question:create"))))
+ (testing "and it is the only thing requested, nothing survives"
+ (is (nil? (api.oauth/narrow-scope-to-resource [mcp-uri] "mb:full")))))
+ (testing "nil rather than an empty scope when nothing survives, so the caller can refuse the request"
+ (is (nil? (api.oauth/narrow-scope-to-resource [mcp-uri] "agent:question:create")))
+ (is (nil? (api.oauth/narrow-scope-to-resource nil "agent:content:read"))))
+ (testing "blank and missing scopes stay absent rather than becoming an empty parameter"
+ (doseq [blank [nil "" " "]]
+ (testing (pr-str blank)
+ (is (nil? (api.oauth/narrow-scope-to-resource [mcp-uri] blank)))
+ (is (nil? (api.oauth/narrow-scope-to-resource nil blank))))))
+ (testing "narrowing only ever removes — a client cannot gain a scope it did not request"
+ (let [requested "agent:content:read agent:question:create mb:full"]
+ (doseq [resources [[mcp-uri] nil]]
+ (testing (pr-str resources)
+ (is (every? (scopes requested)
+ (scopes (api.oauth/narrow-scope-to-resource resources requested)))))))))))
+
+(deftest narrow-scope-to-non-mcp-resource-test
+ (testing "GHY-4969: a token for anything but the MCP resource is narrowed to everything but the MCP scopes, so a
+ REST token can never be used against MCP"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [requested "mb:full agent:content:read agent:question:create agent:sql:run"]
+ (doseq [resources [nil
+ []
+ ["http://localhost:3000/api/agent"]
+ "http://localhost:3000/api/agent"
+ ["not-a-uri"]]]
+ (testing (pr-str resources)
+ (is (= #{"mb:full" "agent:question:create"}
+ (scopes (api.oauth/narrow-scope-to-resource resources requested))))))
+ (testing "nothing survives when only MCP scopes are requested"
+ (is (nil? (api.oauth/narrow-scope-to-resource nil (str/join " " (mcp/v2-scopes))))))))))
+
+(deftest narrow-scope-to-mixed-resources-test
+ (testing "GHY-4969: a token is either for MCP or for the rest of Metabase, so naming both kinds of resource is
+ refused rather than silently narrowed to one of them"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (doseq [resources [["http://localhost:3000/api/metabase-mcp" "http://localhost:3000/api/agent"]
+ ["http://localhost:3000/api/agent" "http://localhost:3000/api/mcp"]]]
+ (testing (pr-str resources)
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo #"cannot mix"
+ (api.oauth/narrow-scope-to-resource resources "agent:content:read mb:full")))
+ (is (= "invalid_scope"
+ (try
+ (api.oauth/narrow-scope-to-resource resources "agent:content:read mb:full")
+ (catch clojure.lang.ExceptionInfo e
+ (:oauth-error (ex-data e)))))))))))
+
+(deftest narrow-scope-to-resource-canonicalization-test
+ (testing "resource indicators are compared canonically, not byte-for-byte. Clients disagree on
+ trailing slashes, case, and default ports -- a live Claude Code bug appends a trailing
+ slash via WHATWG URL -- and a mismatch silently treats the MCP resource as a REST one.
+ RFC 3986 makes scheme and host case-insensitive and the default port elidable; the path is
+ neither."
+ (let [requested "agent:content:read agent:question:create"
+ as-mcp "agent:content:read"
+ as-rest "agent:question:create"]
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (doseq [indicator ["http://localhost:3000/api/metabase-mcp"
+ "http://localhost:3000/api/metabase-mcp/"
+ "HTTP://LOCALHOST:3000/api/metabase-mcp"
+ "http://LocalHost:3000/api/metabase-mcp/"]]
+ (testing (str "matches " (pr-str indicator))
+ (is (= as-mcp (api.oauth/narrow-scope-to-resource [indicator] requested))))))
+ (testing "the default port is elidable in both directions"
+ (mt/with-temporary-setting-values [site-url "https://example.com"]
+ (doseq [indicator ["https://example.com/api/metabase-mcp"
+ "https://example.com:443/api/metabase-mcp"]]
+ (testing (str "matches " (pr-str indicator))
+ (is (= as-mcp (api.oauth/narrow-scope-to-resource [indicator] requested))))))
+ (mt/with-temporary-setting-values [site-url "http://example.com"]
+ (is (= as-mcp (api.oauth/narrow-scope-to-resource
+ ["http://example.com:80/api/metabase-mcp"] requested)))))
+ (testing "canonicalization does not make unrelated resources match"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (doseq [indicator ["http://localhost:3000/api/metabase-mcp/extra"
+ "http://localhost:3000/API/METABASE-MCP/V2"
+ "http://localhost:3001/api/metabase-mcp"
+ "https://localhost:3000/api/metabase-mcp"
+ "http://evil.example.com/api/metabase-mcp"
+ "not-a-uri"]]
+ (testing (str "treated as non-MCP: " (pr-str indicator))
+ (is (= as-rest (api.oauth/narrow-scope-to-resource [indicator] requested))))))))))
+
+(deftest narrow-scope-to-resource-multiple-indicators-test
+ (testing "RFC 8707 allows several `resource` indicators. Every MCP path reaches the same v2 surface, so naming
+ several of them narrows to that one surface's set, in any order"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [canonical "http://localhost:3000/api/metabase-mcp"
+ alias1 "http://localhost:3000/api/mcp"
+ requested "mb:full agent:content:read agent:question:create agent:sql:execute"]
+ (doseq [indicators [[canonical] [alias1] [canonical alias1] [alias1 canonical]]]
+ (testing (pr-str indicators)
+ (is (= #{"agent:content:read"}
+ (scopes (api.oauth/narrow-scope-to-resource indicators requested))))))))))
+
+(deftest narrow-scope-to-resource-bare-string-test
+ (testing "a lone indicator may arrive as a bare string -- the endpoint schema allows one. `keep` over a
+ String iterates characters, none of which canonicalize, so an un-normalized argument would treat
+ the MCP resource as a REST one. Narrowing must not depend on the caller having vectorized."
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [uri "http://localhost:3000/api/metabase-mcp"
+ requested "mb:full agent:content:read agent:question:create"]
+ (is (= (api.oauth/narrow-scope-to-resource [uri] requested)
+ (api.oauth/narrow-scope-to-resource uri requested)))
+ (is (= "agent:content:read" (api.oauth/narrow-scope-to-resource uri requested)))))))
+
+(deftest narrow-scope-to-resource-underscore-host-test
+ (testing "`java.net.URI/getHost` is nil for a host it considers non-conformant -- notably one containing an
+ underscore, which is routine for Docker Compose and internal k8s service names, and which
+ Metabase's own `u/url?` accepts as a Site URL. Reading the host alone made canonicalization
+ return nil on such an instance, so no indicator ever matched the MCP resource."
+ (mt/with-temporary-setting-values [site-url "http://metabase_internal:3000"]
+ (let [v2 "http://metabase_internal:3000/api/metabase-mcp"
+ requested "mb:full agent:content:read agent:question:create"]
+ (is (= "agent:content:read" (api.oauth/narrow-scope-to-resource [v2] requested))
+ "MCP narrowing still applies when the Site URL host contains an underscore")))
+ (testing "canonicalization keeps the properties it had for conformant hosts"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [requested "agent:content:read agent:question:create"
+ as-mcp "agent:content:read"]
+ (testing "userinfo is still stripped rather than compared"
+ (is (= as-mcp (api.oauth/narrow-scope-to-resource
+ ["http://user:pass@localhost:3000/api/metabase-mcp"] requested))))
+ (testing "host case is still folded and the default port still elided"
+ (is (= as-mcp (api.oauth/narrow-scope-to-resource
+ ["HTTP://LocalHost:3000/api/metabase-mcp"] requested)))))))))
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index dc3e79ef8eb..2b755d09c82 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -73,13 +73,10 @@
".well-known/oauth-protected-resource/api/metabase-mcp"
".well-known/oauth-protected-resource/api/mcp"]]
(testing url
- (let [response (mt/user-http-request :crowberto :get 200 url)
- resource-path (str/replace (:resource response) "http://localhost:3000" "")]
+ (let [response (mt/user-http-request :crowberto :get 200 url)]
(is (= #{"agent:content:read" "agent:content:write" "agent:query:run"
"agent:sql:run" "agent:delivery:write"}
- (set (:scopes_supported response))))
- (is (empty? (remove (set (oauth-server/mcp-resource-scopes resource-path))
- (:scopes_supported response))))))))))
+ (set (:scopes_supported response))))))))))
(deftest authorization-server-metadata-stays-wide-test
(testing "GHY-4543: the RFC 8414 document keeps advertising every v2 scope, alongside the rest of the default grant.
@@ -327,7 +324,7 @@
(set (:scopes (t2/select-one :model/OAuthClient :client_id (:client_id response))))))))
(testing "omitting `scope` still registers the client with the default ceiling"
(let [response (register-client! {:redirect_uris ["https://example.com/callback"]})]
- (is (= (set (oauth-server/default-grant-scopes))
+ (is (= (set (oauth-server/supported-scopes))
(set (:scopes (t2/select-one :model/OAuthClient :client_id (:client_id response))))))))))))
(deftest discovery-registration-endpoint-disabled-test
@@ -362,7 +359,7 @@
:client_name "Test Auth Client"
:grant_types ["authorization_code" "refresh_token"]
:response_types ["code"]
- :scopes ["agent:content:read"]
+ :scopes ["mb:full"]
:application_type "web"
:registration_type "static"}
[inserted] (t2/insert-returning-instances! :model/OAuthClient (merge defaults overrides))]
@@ -379,12 +376,12 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state")
body (:body response)]
(is (str/includes? (get-in response [:headers "Content-Type"]) "text/html"))
(is (str/includes? body "Test Auth Client"))
- (is (str/includes? body "agent:content:read"))
+ (is (str/includes? body "mb:full"))
(is (str/includes? body client-id))
(is (str/includes? body "test-state"))
(is (str/includes? body "/oauth/authorize/decision")))))))
@@ -453,25 +450,25 @@
(doseq [[description error params]
[["an unsupported response_type"
"unsupported_response_type" [:client_id client-id :response_type "token"
- :scope "agent:content:read"]]
+ :scope "mb:full"]]
["a missing response_type"
- "invalid_request" [:client_id client-id :scope "agent:content:read"]]
+ "invalid_request" [:client_id client-id :scope "mb:full"]]
["a scope the client did not register"
"invalid_scope" [:client_id client-id :response_type "code" :scope "agent:sql:execute"]]
["a public client without PKCE"
"invalid_request" [:client_id public-client-id :response_type "code"
- :scope "agent:content:read"]]
+ :scope "mb:full"]]
["code_challenge_method without code_challenge"
- "invalid_request" [:client_id client-id :response_type "code" :scope "agent:content:read"
+ "invalid_request" [:client_id client-id :response_type "code" :scope "mb:full"
:code_challenge_method "S256"]]
["an unsupported code_challenge_method"
- "invalid_request" [:client_id client-id :response_type "code" :scope "agent:content:read"
+ "invalid_request" [:client_id client-id :response_type "code" :scope "mb:full"
:code_challenge "abc" :code_challenge_method "plain"]]
["a relative resource indicator"
- "invalid_target" [:client_id client-id :response_type "code" :scope "agent:content:read"
+ "invalid_target" [:client_id client-id :response_type "code" :scope "mb:full"
:resource "not-absolute"]]
["a resource indicator with a fragment"
- "invalid_target" [:client_id client-id :response_type "code" :scope "agent:content:read"
+ "invalid_target" [:client_id client-id :response_type "code" :scope "mb:full"
:resource "http://localhost:3000/api/mcp#fragment"]]]]
(testing description
(let [response (apply authorize-request! 400
@@ -509,7 +506,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"
(mapcat identity extra-params))))
@@ -567,8 +564,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state "test-state"}
302
:csrf-cookie csrf-cookie)
@@ -600,7 +597,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"}
302
:csrf-cookie csrf-cookie)
@@ -664,8 +661,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state "test-state"}
302
:csrf-cookie csrf-cookie)
@@ -703,8 +700,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state "test-state"}
302
:csrf-cookie (extract-csrf-cookie consent-resp))))
@@ -743,7 +740,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"}
403)]
(is (= "csrf_validation_failed" (:error (:body response)))))))))
@@ -763,7 +760,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"}
403
:csrf-cookie csrf-cookie)]
@@ -788,7 +785,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "tampered-state"} ;; tampered state
403
:csrf-cookie csrf-cookie)]
@@ -812,7 +809,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"}
403
:csrf-cookie csrf-cookie)]
@@ -836,7 +833,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"}
403
:csrf-cookie csrf-cookie)]
@@ -881,8 +878,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state "test-state"}
302
:csrf-cookie csrf-cookie)
@@ -1183,7 +1180,7 @@
:client_name "Other Client"
:grant_types ["authorization_code"]
:response_types ["code"]
- :scopes ["agent:content:read"]})
+ :scopes ["mb:full"]})
code (authorize-and-get-code! (:client_id client-a))
response (token-request!
{:grant_type "authorization_code"
@@ -1349,8 +1346,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state "test-state"}
extra-params)
302
@@ -1443,7 +1440,7 @@
this endpoint's own resource check knows the URI was malformed."
(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!)
+ (let [{:keys [client_id client_secret]} (create-test-client! {:scopes ["agent:content:read"]})
granted-resource (str "http://localhost:3000" (mcp/mcp-canonical-path))
consent-resp (authorize-request! 200
:client_id client_id
@@ -1616,7 +1613,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state state)
consent-body (:body consent-resp)
csrf-token (extract-csrf-token-from-consent consent-body)
@@ -1631,8 +1628,8 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
- :granted_scope "agent:content:read"
+ :scope "mb:full"
+ :granted_scope "mb:full"
:state state}
302
:csrf-cookie csrf-cookie)
@@ -1654,7 +1651,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state")
body (:body response)]
(is (not (str/includes? body "<script>alert('xss')</script>"))
@@ -1669,6 +1666,9 @@
[field-name body]
(second (re-find (re-pattern (str "name=\"" field-name "\"[^>]*value=\"([^\"]*)\"")) body)))
+(defn- mcp-resource-uri []
+ (str "http://localhost:3000" (mcp/mcp-canonical-path)))
+
(deftest authorize-narrows-scope-to-mcp-resource-test
(testing "an RFC 8707 `resource` indicator naming the MCP surface narrows the grant to the
scopes that surface accepts, so the consent screen asks for what the token can actually
@@ -1752,6 +1752,7 @@
:redirect_uri "https://example.com/callback"
:response_type "code"
:scope (str/join " " v2-scopes)
+ :resource (mcp-resource-uri)
:state "test-state"))
consent! (fn [response]
(is (str/includes? (get-in response [:headers "Content-Type"]) "text/html")
@@ -1777,7 +1778,7 @@
(defn- first-non-mcp-default-scope
"A scope in the default grant ceiling that the MCP surface does not accept."
[]
- (first (remove (set (mcp/v2-scopes)) (oauth-server/default-grant-scopes))))
+ (first (remove (set (mcp/v2-scopes)) (oauth-server/supported-scopes))))
(deftest grant-ceiling-widens-only-dynamic-clients-test
(testing (str "GHY-4543: only a dynamically registered client is widened. It always gains the MCP scopes, and the "
@@ -1794,13 +1795,16 @@
(let [client-id (:client_id (create-test-client!
{:scopes ["agent:content:read"]
:registration_type registration-type}))]
- (mt/user-http-request-full-response
- :crowberto :get "oauth/authorize"
- :client_id client-id
- :redirect_uri "https://example.com/callback"
- :response_type "code"
- :scope scope
- :state "test-state")))))
+ (apply mt/user-http-request-full-response
+ :crowberto :get "oauth/authorize"
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope scope
+ :state "test-state"
+ ;; GHY-4969: an MCP scope survives only a request naming the MCP resource
+ (when (some #{scope} (mcp/v2-scopes))
+ [:resource (mcp-resource-uri)]))))))
consent? (fn [response] (is (= 200 (:status response)) (pr-str (:body response))))
refused? (fn [response]
(is (= 400 (:status response)))
@@ -1839,6 +1843,7 @@
:redirect_uri "https://example.com/callback"
:response_type "code"
:scope "agent:query:run"
+ :resource (mcp-resource-uri)
:state "test-state")))))]
(testing "with MCP enabled a dynamic client is widened onto the MCP scopes and reaches consent"
(let [response (authorize true)]
@@ -1863,8 +1868,8 @@
[["an unregistered scope" [:response_type "code" :scope "*"]]
["no scope at all" [:response_type "code"]]
["a scope the client did not register" [:response_type "code" :scope "agent:sql:execute"]]
- ["an unsupported response_type" [:response_type "token" :scope "agent:content:read"]]
- ["a malformed resource indicator" [:response_type "code" :scope "agent:content:read"
+ ["an unsupported response_type" [:response_type "token" :scope "mb:full"]]
+ ["a malformed resource indicator" [:response_type "code" :scope "mb:full"
:resource "http://bad uri"]]]]
(testing label
(let [response (apply authorize-request! 400
@@ -1894,8 +1899,26 @@
:resource (str "http://localhost:3000" (mcp/mcp-canonical-path))
:state "test-state")]
(is (= {:error "invalid_scope"
- :error_description "The requested scopes are not accepted by the requested resource."}
- (:body response))))))))
+ :error_description (str "The requested scopes are not accepted by the requested resource. "
+ "The MCP server's resource URL is http://localhost:3000"
+ (mcp/mcp-canonical-path) ".")}
+ (:body response))))
+ (testing "GHY-4969: the error_description never echoes the client's resource, which may hold characters
+ RFC 6749 forbids there (it allows only printable ASCII)"
+ (let [resource "https://example.com/‮evilé"
+ client-id (:client_id (create-test-client! {:scopes ["agent:content:read"]}))
+ response (authorize-request! 400
+ :client_id client-id
+ :scope "agent:content:read"
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :resource resource
+ :state "test-state")
+ desc (get-in response [:body :error_description])]
+ (is (= "invalid_scope" (get-in response [:body :error])))
+ (is (string? desc))
+ (is (not (str/includes? desc "evil")))
+ (is (re-matches #"[\x20-\x21\x23-\x5B\x5D-\x7E]*" desc))))))))
(deftest authorize-drops-unregistered-scopes-test
(testing "GHY-4542: a scope that is not registered via `defscope` is dropped from the request rather than
@@ -1909,16 +1932,16 @@
(t2/with-transaction [_conn nil {:rollback-only true}]
(doseq [[label registered requested resource expected absent]
[["a wildcard alongside a registered scope"
- ["agent:content:read" "*"] "agent:content:read *" nil "agent:content:read" []]
+ ["mb:full" "*"] "mb:full *" nil "mb:full" []]
["a hierarchical wildcard alongside a registered scope"
- ["agent:content:read" "agent:*"] "agent:* agent:content:read" nil "agent:content:read" []]
+ ["mb:full" "agent:*"] "agent:* mb:full" nil "mb:full" []]
["a scope deprecated since the client registered"
- ["agent:content:read" "agent:table:read"] "agent:table:read agent:content:read" nil
- "agent:content:read" ["agent:table:read"]]
+ ["mb:full" "agent:table:read"] "agent:table:read mb:full" nil
+ "mb:full" ["agent:table:read"]]
["several survivors, keeping the requested order"
- ["agent:content:read" "agent:question:create" "agent:table:read"]
- "agent:table:read agent:content:read agent:question:create" nil
- "agent:content:read agent:question:create" ["agent:table:read"]]
+ ["mb:full" "agent:question:create" "agent:table:read"]
+ "agent:table:read mb:full agent:question:create" nil
+ "mb:full agent:question:create" ["agent:table:read"]]
["a resource indicator narrowing the survivors further"
["agent:content:read" "agent:question:create" "agent:table:read"]
"agent:table:read agent:content:read agent:question:create"
@@ -1946,16 +1969,16 @@
endpoint that declares a scope. Followed through consent, the decision, and the token exchange."
(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! {:scopes ["*" "agent:content:read"]})
+ (let [{:keys [client_id client_secret]} (create-test-client! {:scopes ["*" "mb:full"]})
consent-resp (authorize-request! 200
:client_id client_id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "* agent:content:read"
+ :scope "* mb:full"
:state "test-state")
body (:body consent-resp)
granted (extract-hidden-field "scope" body)]
- (is (= "agent:content:read" granted))
+ (is (= "mb:full" granted))
(let [decision (form-post-decision!
:crowberto
{:approved "true"
@@ -1965,6 +1988,7 @@
:redirect_uri "https://example.com/callback"
:response_type "code"
:scope granted
+ :granted_scope granted
:state "test-state"}
302
:csrf-cookie (extract-csrf-cookie consent-resp))
@@ -1973,7 +1997,7 @@
:code code
:redirect_uri "https://example.com/callback"}
:authorization (basic-auth-header client_id client_secret))]
- (is (= "agent:content:read" (:scope token))
+ (is (= "mb:full" (:scope token))
"the minted token carries only the registered scope")))))))
(defn- sign-decision-params
@@ -1993,11 +2017,11 @@
;; as :rasta, so this test's decisions don't share :crowberto's per-user decision throttle with the rest of
;; the namespace
(let [{:keys [client_id client_secret]} (create-test-client!
- {:scopes ["*" "agent:content:read" "agent:table:read"]})
+ {:scopes ["*" "mb:full" "agent:table:read"]})
consent-resp (get-consent-page! :rasta client_id)
csrf-token (extract-csrf-token-from-consent (:body consent-resp))
csrf-cookie (extract-csrf-cookie consent-resp)
- approve! (fn [scope expected-status]
+ approve! (fn [scope expected-status & [granted]]
(let [params (cond-> {:client_id client_id
:redirect_uri "https://example.com/callback"
:response_type "code"
@@ -2005,26 +2029,27 @@
scope (assoc :scope scope))]
(form-post-decision!
:rasta
- (assoc params
- :approved "true"
- :csrf_token csrf-token
- :params_sig (sign-decision-params csrf-token params))
+ (cond-> (assoc params
+ :approved "true"
+ :csrf_token csrf-token
+ :params_sig (sign-decision-params csrf-token params))
+ granted (assoc :granted_scope granted))
expected-status
:csrf-cookie csrf-cookie)))
refused {:error "invalid_request"
:error_description "The authorization request is invalid."}]
(testing "a correctly signed approval of a registered scope still issues a code"
- (let [response (approve! "agent:content:read" 302)]
+ (let [response (approve! "mb:full" 302 "mb:full")]
(is (some? (extract-query-param (get-in response [:headers "Location"]) "code")))))
(testing "a re-signed wildcard is dropped, so the code is issued for the registered scope alone and the
token it buys carries no wildcard"
- (let [response (approve! "* agent:content:read" 302)
+ (let [response (approve! "* mb:full" 302 "mb:full")
code (extract-query-param (get-in response [:headers "Location"]) "code")
token (token-request! {:grant_type "authorization_code"
:code code
:redirect_uri "https://example.com/callback"}
:authorization (basic-auth-header client_id client_secret))]
- (is (= "agent:content:read" (:scope token)))))
+ (is (= "mb:full" (:scope token)))))
(testing "a re-signed request whose scopes are all unregistered is refused, since dropping leaves nothing"
(is (= refused (:body (approve! "*" 400))))
(is (= refused (:body (approve! "agent:table:read" 400)))))
@@ -2106,8 +2131,7 @@
(t2/with-transaction [_conn nil {:rollback-only true}]
(let [client-id (:client_id (create-test-client! {:scopes [oauth-server/full-access-scope]}))]
(testing "the scope is advertised nowhere"
- (is (not (contains? (set (oauth-server/supported-scopes)) oauth-server/full-access-scope)))
- (is (not (contains? (set (oauth-server/default-grant-scopes)) oauth-server/full-access-scope))))
+ (is (not (contains? (set (oauth-server/supported-scopes)) oauth-server/full-access-scope))))
(testing "yet the consent screen still renders for a client registered with it"
(is (mt/user-http-request :crowberto :get 200 "oauth/authorize"
:client_id client-id
@@ -2137,7 +2161,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"
:resource resource)]
(is (= {:error "invalid_target"
@@ -2163,7 +2187,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"
:resource resource}
400
@@ -2195,9 +2219,6 @@
#{"agent:content:read" "agent:content:write" "agent:query:run"
"agent:sql:run" "agent:delivery:write"})
-(defn- mcp-resource-uri []
- (str "http://localhost:3000" (mcp/mcp-canonical-path)))
-
(defn- register-mcp-client!
"Register a confidential DCR client with `registration` merged into the body. Returns the registration response."
[registration]
@@ -2320,7 +2341,7 @@
(mt/with-temporary-setting-values [site-url "http://localhost:3000"
oauth-server-dynamic-registration-enabled true]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [not-mcp (first (remove v2-scope-set (oauth-server/default-grant-scopes)))
+ (let [not-mcp (first (remove v2-scope-set (oauth-server/supported-scopes)))
{:keys [authorize token]} (register-then-authorize-mcp!
{:scope "agent:content:read agent:query:run"}
(str/join " " (conj (sort v2-scope-set) not-mcp)))]
@@ -2346,16 +2367,26 @@
:state "test-state")))
(deftest dynamic-client-ceiling-still-bounds-requests-test
- (testing (str "GHY-4543: a narrow registration is widened to the default ceiling, not beyond it. A client that "
- "omits the resource indicator is not narrowed, so the ceiling is what refuses these.")
+ (testing (str "GHY-4543: a narrow registration is widened to the default ceiling, not beyond it. GHY-4969: a client "
+ "that omits the resource indicator asks for a REST token, so only the MCP scopes are dropped, and the "
+ "ceiling is what refuses these.")
(mt/with-temporary-setting-values [site-url "http://localhost:3000"
oauth-server-dynamic-registration-enabled true]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (testing "control: the same flow reaches consent for a scope inside the default ceiling"
+ (testing "control: the same flow reaches consent for a non-MCP scope inside the default ceiling"
(let [response (register-then-authorize-without-resource!
{:scope "agent:content:read agent:query:run"}
- "agent:content:write")]
+ (first-non-mcp-default-scope))]
(is (= 200 (:status response)) (pr-str (:body response)))))
+ (testing "GHY-4969: an MCP scope inside the ceiling is dropped without the MCP resource, which leaves nothing"
+ (let [response (register-then-authorize-without-resource!
+ {:scope "agent:content:read agent:query:run"}
+ "agent:content:write")]
+ (is (= {:error "invalid_scope"
+ :error_description (str "No resource was requested, so no MCP scopes can be granted. "
+ "Send the MCP server's resource URL, which is http://localhost:3000"
+ (mcp/mcp-canonical-path) ".")}
+ (:body response)))))
(doseq [scope [oauth-server/full-access-scope "*" "agent:*" "bogus:nonsense"]]
(testing scope
(let [response (register-then-authorize-without-resource!
@@ -2366,14 +2397,17 @@
(deftest dynamic-client-registered-with-extra-scope-keeps-it-test
(testing (str "GHY-4543: the ceiling is the registration `scope` *plus* the default, so a first-party client that "
- "registers for `mb:full`, which the default deliberately omits, can still authorize for it.")
+ "registers for `mb:full`, which the default deliberately omits, can still authorize for it. "
+ "GHY-4969: with no resource indicator the token is a REST token, so the MCP scope asked for "
+ "alongside it is dropped.")
(mt/with-temporary-setting-values [site-url "http://localhost:3000"
oauth-server-dynamic-registration-enabled true]
(t2/with-transaction [_conn nil {:rollback-only true}]
(let [response (register-then-authorize-without-resource!
{:scope oauth-server/full-access-scope}
(str oauth-server/full-access-scope " agent:content:read"))]
- (is (= 200 (:status response)) (pr-str (:body response))))))))
+ (is (= 200 (:status response)) (pr-str (:body response)))
+ (is (= [oauth-server/full-access-scope] (offered-scopes response))))))))
;;; ---------------------------------------------- Per-scope consent -----------------------------------------------
@@ -2428,13 +2462,13 @@
oauth-server-dynamic-registration-enabled true]
(t2/with-transaction [_conn nil {:rollback-only true}]
(testing "a non-baseline scope requested without a resource indicator"
- (let [client-id (:client_id (create-test-client! {:scopes ["agent:content:write"]}))
+ (let [client-id (:client_id (create-test-client! {:scopes ["mb:full"]}))
consent-resp (mt/user-http-request-full-response
:crowberto :get 200 "oauth/authorize"
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:write"
+ :scope "mb:full"
:state "test-state")
consent-body (:body consent-resp)
response (form-post-decision!
@@ -2445,7 +2479,7 @@
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:write"
+ :scope "mb:full"
:state "test-state"}
400
:csrf-cookie (extract-csrf-cookie consent-resp))]
@@ -2501,34 +2535,49 @@
(deftest consent-page-scope-order-test
(testing (str "GHY-4555: the five v2 scopes are listed least to most harmful whatever order they were requested in, "
- "and any other requested scope follows in request order")
+ "and any other requested scope follows in request order. GHY-4969: v2 scopes and other scopes can no "
+ "longer share a consent page, so each order is checked on its own page.")
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
;; a registered non-v2 scope: GHY-4542 drops unregistered scopes before the page is rendered
- (let [not-v2 (first-non-mcp-default-scope)
- requested [not-v2 "agent:delivery:write" "agent:sql:run" oauth-server/full-access-scope
- "agent:content:write" "agent:query:run" "agent:content:read"]
- client-id (:client_id (create-test-client! {:scopes requested}))
- body (:body (mt/user-http-request-full-response
- :crowberto :get 200 "oauth/authorize"
- :client_id client-id
- :redirect_uri "https://example.com/callback"
- :response_type "code"
- :scope (str/join " " requested)
- :state "test-state"))]
- (is (= ["agent:content:read" "agent:query:run"
- "agent:content:write" "agent:sql:run" "agent:delivery:write"
- not-v2 oauth-server/full-access-scope]
- (map :scope (consent-checkboxes body))))
- (testing "the baseline is ticked and locked; everything else, `mb:full` included, starts ticked (GHY-4826)"
- (is (= {"agent:content:read" [true true]
- "agent:query:run" [true true]
- "agent:content:write" [true false]
- "agent:sql:run" [true false]
- "agent:delivery:write" [true false]
- not-v2 [true false]
- oauth-server/full-access-scope [true false]}
- (into {} (map (juxt :scope (juxt :checked? :disabled?))) (consent-checkboxes body))))))))))
+ (let [not-v2 (first-non-mcp-default-scope)
+ consent! (fn [requested & resource]
+ (let [client-id (:client_id (create-test-client! {:scopes requested}))]
+ (:body (apply mt/user-http-request-full-response
+ :crowberto :get 200 "oauth/authorize"
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope (str/join " " requested)
+ :state "test-state"
+ resource))))
+ checkboxes (fn [body]
+ (into {} (map (juxt :scope (juxt :checked? :disabled?))) (consent-checkboxes body)))]
+ (testing "the v2 scopes, against the MCP resource"
+ (let [body (consent! ["agent:delivery:write" "agent:sql:run" "agent:content:write" "agent:query:run"
+ "agent:content:read"]
+ :resource (mcp-resource-uri))]
+ (is (= ["agent:content:read" "agent:query:run"
+ "agent:content:write" "agent:sql:run" "agent:delivery:write"]
+ (map :scope (consent-checkboxes body))))
+ (testing "the baseline is ticked and locked; everything else starts ticked (GHY-4826)"
+ (is (= {"agent:content:read" [true true]
+ "agent:query:run" [true true]
+ "agent:content:write" [true false]
+ "agent:sql:run" [true false]
+ "agent:delivery:write" [true false]}
+ (checkboxes body))))))
+ (testing "other scopes, without a resource indicator"
+ (let [body (consent! [not-v2 oauth-server/full-access-scope])]
+ (is (= [not-v2 oauth-server/full-access-scope]
+ (map :scope (consent-checkboxes body))))
+ (testing "every one, `mb:full` included, starts ticked and unlocked (GHY-4826)"
+ (is (= {not-v2 [true false]
+ oauth-server/full-access-scope [true false]}
+ (checkboxes body)))))
+ (testing "in request order"
+ (is (= [oauth-server/full-access-scope not-v2]
+ (map :scope (consent-checkboxes (consent! [oauth-server/full-access-scope not-v2]))))))))))))
(deftest consent-page-opts-into-script-nonce-test
(testing (str "GHY-4568: the consent page's inline script needs a `script-src` nonce. Dev mode allows "
@@ -2750,7 +2799,7 @@
(let [response (authorize (str/join " " (sort v2-scope-set)) :resource mcp-uri)]
(is (= 200 (:status response)) (pr-str (:body response)))
(is (= v2-scope-set (some-> (extract-hidden-field "scope" (:body response)) (str/split #" ") set)))))
- ;; No resource indicator, so nothing is narrowed and the ceiling alone decides.
+ ;; No resource indicator, so only MCP scopes are dropped and the ceiling alone decides on this one.
(testing "the client cannot request an agent-API scope outside its registration"
(let [response (authorize not-mcp)]
(is (= 400 (:status response)))
@@ -2761,7 +2810,7 @@
(def ^:private consent-request-params
{:redirect_uri "https://example.com/callback"
:response_type "code"
- :scope "agent:content:read"
+ :scope "mb:full"
:state "test-state"})
(defn- consent-get!
@@ -2787,7 +2836,7 @@
extra-cookies))})}}
(assoc params
:approved "true"
- :granted_scope "agent:content:read"
+ :granted_scope "mb:full"
:csrf_token csrf-token
:params_sig (sign-decision-params csrf-token params)))))
diff --git a/test/metabase/oauth_server/core_test.clj b/test/metabase/oauth_server/core_test.clj
index db0b3b18e60..eb1ed51cec2 100644
--- a/test/metabase/oauth_server/core_test.clj
+++ b/test/metabase/oauth_server/core_test.clj
@@ -1,9 +1,9 @@
(ns metabase.oauth-server.core-test
(:require
- [clojure.string :as str]
[clojure.test :refer [deftest is testing use-fixtures]]
[metabase.mcp.core :as mcp]
[metabase.mcp.v2.api :as v2.api]
+ [metabase.oauth-server.api.metadata :as metadata]
[metabase.oauth-server.core :as oauth-server]
[metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.test :as mt]
@@ -15,32 +15,29 @@
(thunk)
(oauth-server/reset-provider!)))
+(defn- advertised-scopes
+ "The `scopes_supported` the RFC 9728 metadata publishes for the MCP resource at `path`."
+ [path]
+ (-> (#'metadata/protected-resource-metadata path) :body :scopes_supported))
+
(deftest mb-full-is-advertised-nowhere-test
(testing "GHY-4226: `mb:full` grants full user-equivalent REST access, and advertising it put that
in front of every client reading discovery metadata. It is now absent from both advertised
- sets, from the set the MCP resource accepts, and from the default DCR grant, so no client is
- led toward it and none can request it without having registered for it explicitly."
+ sets and from the default DCR grant, so no client is led toward it and none can request it
+ without having registered for it explicitly."
(is (not (contains? (set (oauth-server/supported-scopes)) "mb:full")))
- (is (not (contains? (set (oauth-server/mcp-resource-scopes (mcp/mcp-canonical-path))) "mb:full")))
- (is (not (contains? (set (oauth-server/mcp-resource-advertised-scopes (mcp/mcp-canonical-path))) "mb:full")))
- (is (not (contains? (set (oauth-server/default-grant-scopes)) "mb:full")))))
+ (is (not (contains? (set (advertised-scopes (mcp/mcp-canonical-path))) "mb:full")))))
(deftest default-grant-covers-everything-advertised-test
(testing "GHY-4226: the DCR default is a ceiling, and clients derive what to request from
discovery metadata rather than from what they registered with. A scope we advertise but
do not register for is therefore not a narrower grant — it is an `invalid_scope`
rejection at /authorize for any client that asks for everything advertised, which is
- what Claude and ChatGPT both do.
-
- Iterated over every endpoint path rather than over the sets `default-grant-scopes` is
- built from: asserting a set covers the sets it is defined as the union of cannot fail."
- (let [ceiling (set (oauth-server/default-grant-scopes))]
+ what Claude and ChatGPT both do."
+ (let [ceiling (set (oauth-server/supported-scopes))]
(doseq [path (mcp/mcp-endpoint-paths)]
(testing path
- (is (empty? (remove ceiling (oauth-server/mcp-resource-scopes path))))
- (is (empty? (remove ceiling (oauth-server/mcp-resource-advertised-scopes path))))))
- (testing "and the authorization-server metadata set"
- (is (empty? (remove ceiling (oauth-server/supported-scopes))))))))
+ (is (empty? (remove ceiling (advertised-scopes path)))))))))
(deftest v2-default-ask-is-the-whole-surface-and-is-requestable-test
(testing "ENG-11089: the v2 401 challenge asks an uninstructed client for every v2 scope. A manual reconnect from
@@ -49,11 +46,8 @@
(is (= #{"agent:content:read" "agent:content:write" "agent:query:run"
"agent:sql:run" "agent:delivery:write"}
(set @#'v2.api/default-ask-scopes)))
- (testing "the surface still accepts every scope asked for, or narrowing strips the ask at consent"
- (is (empty? (remove (set (oauth-server/mcp-resource-scopes (mcp/mcp-canonical-path)))
- @#'v2.api/default-ask-scopes))))
(testing "every asked scope is inside the ceiling, or the ask itself would be rejected"
- (let [ceiling (set (oauth-server/default-grant-scopes))]
+ (let [ceiling (set (oauth-server/supported-scopes))]
(doseq [scope @#'v2.api/default-ask-scopes]
(testing scope
(is (contains? ceiling scope))))))
@@ -64,56 +58,24 @@
(deftest advertised-scopes-are-distinct-test
(testing "GHY-4151: `scopes_supported` is a set of scope strings (RFC 8414, RFC 9728), so no scope may be
- advertised twice.
-
- GHY-4543: the protected-resource metadata advertises `mcp-resource-advertised-scopes`, a vector copied
- from the `v2-surface-scopes` literal, so a scope repeated there is repeated on the wire. The accepted
- set, `mcp-resource-scopes`, is built through a `sorted-set` and cannot repeat by construction; it is
- checked too, alongside the literals both are built from, where a duplicate would be silently swallowed."
+ advertised twice. The protected-resource metadata copies the v2 surface literal, so a scope repeated
+ there is repeated on the wire."
(let [duplicates (fn [scopes] (->> scopes frequencies (filter (fn [[_ n]] (> n 1))) (map key) sort vec))]
(doseq [path (mcp/mcp-endpoint-paths)]
(testing path
- (doseq [[label scopes] {"advertised" (oauth-server/mcp-resource-advertised-scopes path)
- "accepted" (oauth-server/mcp-resource-scopes path)}]
- (testing label
- (is (empty? (duplicates scopes)))))))
+ (is (empty? (duplicates (advertised-scopes path))))))
(testing "the v2 surface literal has no duplicates of its own"
(is (empty? (duplicates (mcp/v2-scopes))))))))
(deftest rationalized-scopes-are-in-the-default-grant-test
(testing "GHY-4225: the five v2 scopes must all reach the default grant a dynamically-registered
- client receives, or the tool surface advertises capabilities no such client can use.
- (This replaces a check on `agent:document:create`, which duplicate_content required
- until GHY-4225 collapsed the per-type create scopes into `agent:content:write`.)"
- (let [granted (set (oauth-server/default-grant-scopes))]
+ client receives, or the tool surface advertises capabilities no such client can use."
+ (let [granted (set (oauth-server/supported-scopes))]
(doseq [scope ["agent:content:read" "agent:content:write" "agent:query:run"
"agent:sql:run" "agent:delivery:write"]]
(testing scope
(is (contains? granted scope)))))))
-(deftest mcp-resource-accepts-only-the-mcp-surface-test
- (testing "Every MCP endpoint path now reaches the same v2 surface, so each accepts the rationalized scopes
- its tool registry gates on and none of the agent-API per-entity scopes. While v1 was still served
- the aliases that reached it had to accept the wider set; with v1 retired that would list per-entity
- scopes on a consent screen for tools that no longer exist."
- (doseq [path (mcp/mcp-endpoint-paths)]
- (testing path
- (let [mcp (set (oauth-server/mcp-resource-scopes path))]
- (testing "the rationalized scopes are accepted"
- (doseq [scope ["agent:content:read" "agent:content:write" "agent:query:run"
- "agent:sql:run" "agent:delivery:write"]]
- (testing scope
- (is (contains? mcp scope)))))
- (testing "agent-API per-entity scopes are not"
- (doseq [scope ["agent:collection:create" "agent:dashboard:create" "agent:dashboard:update"
- "agent:metric:create" "agent:metric:update" "agent:question:create"
- "agent:query:construct" "agent:query:execute" "agent:sql:construct"]]
- (testing scope
- (is (not (contains? mcp scope)))))))))
- (testing "every path answers the same set, since every path reaches the same surface"
- (is (= 1 (count (set (map (comp set oauth-server/mcp-resource-scopes)
- (mcp/mcp-endpoint-paths)))))))))
-
(deftest ^:parallel widen-to-grant-ceiling-test
(let [widen #'oauth-server/widen-to-grant-ceiling
mcp ["agent:content:read" "agent:sql:run"]
@@ -168,173 +130,3 @@
(testing "returns nil once the client row is gone — token must not outlive its client"
(t2/delete! :model/OAuthClient :client_id client-id)
(is (nil? (oauth-server/resolve-access-token token))))))))))
-
-;;; ----------------------------------- RFC 8707 resource narrowing -----------------------------------
-
-(deftest narrow-scope-to-resource-test
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (let [mcp-uri "http://localhost:3000/api/metabase-mcp"
- v1-uri "http://localhost:3000/api/mcp"
- scopes #(set (some-> % (str/split #"\s+")))]
- (testing "an alias narrows to the same surface — every MCP path reaches it now, so a
- per-entity scope no tool gates on is dropped rather than carried into the grant"
- (let [narrowed (scopes (oauth-server/narrow-scope-to-resource
- [v1-uri]
- "agent:content:read agent:question:create agent:sql:execute agent:query:run"))]
- (is (not (contains? narrowed "agent:question:create")))
- (is (not (contains? narrowed "agent:sql:execute")))
- (is (contains? narrowed "agent:content:read"))
- (is (contains? narrowed "agent:query:run"))))
- (testing "an indicator naming the MCP resource drops scopes that surface does not accept"
- (let [narrowed (scopes (oauth-server/narrow-scope-to-resource
- [mcp-uri]
- "agent:content:read agent:question:create agent:sql:execute agent:query:run"))]
- (is (= #{"agent:content:read" "agent:query:run"} narrowed))))
- (testing "GHY-4543: every v2 scope survives narrowing on every alias — otherwise a first connect or a
- step-up for a write scope is stripped at consent"
- (let [v2-scopes ["agent:content:read" "agent:content:write" "agent:query:run"
- "agent:sql:run" "agent:delivery:write"]]
- (doseq [path (mcp/mcp-endpoint-paths)]
- (testing path
- (is (= (set v2-scopes)
- (scopes (oauth-server/narrow-scope-to-resource
- [(str "http://localhost:3000" path)] (str/join " " v2-scopes)))))))))
- (testing "GHY-4226: `mb:full` is dropped like any other scope the surface does not accept. A
- client naming the MCP resource wants a token for that surface, which accepts none of
- the REST API that scope unlocks."
- (is (= #{"agent:content:read"}
- (scopes (oauth-server/narrow-scope-to-resource
- [mcp-uri] "mb:full agent:content:read agent:question:create"))))
- (testing "and it is the only thing requested, nothing survives"
- (is (nil? (oauth-server/narrow-scope-to-resource [mcp-uri] "mb:full")))))
- (testing "GHY-4250: every alias narrows, not just the canonical path — a client that connected
- through an alias was handed that path as its resource identifier, so recognizing
- only the canonical one would silently hand it the wide consent screen. Each narrows to
- what its OWN surface accepts: the v2 path to the v2 set, the aliases (still v1 until the
- switchover) to v1's, which is why `mb:full` goes everywhere but `agent:question:create`
- survives only where a v1 tool can still use it."
- (doseq [path ["/api/metabase-mcp" "/api/mcp"]]
- (testing path
- (let [narrowed (oauth-server/narrow-scope-to-resource
- [(str "http://localhost:3000" path)]
- "mb:full agent:content:read agent:question:create")]
- (is (not (str/includes? narrowed "mb:full")))
- (is (str/includes? narrowed "agent:content:read"))
- ;; Every path reaches v2, so none of them accept the agent-API per-entity scopes.
- (is (not (str/includes? narrowed "agent:question:create")))))))
- (testing "no indicator, or one naming a different resource, leaves the scope alone"
- (let [wide "agent:content:read agent:question:create"]
- (is (= wide (oauth-server/narrow-scope-to-resource nil wide)))
- (is (= wide (oauth-server/narrow-scope-to-resource [] wide)))
- (is (= wide (oauth-server/narrow-scope-to-resource
- ["http://localhost:3000/api/agent"] wide)))))
- (testing "nil rather than an empty scope when nothing survives, so the caller drops the
- parameter instead of sending a blank one"
- (is (nil? (oauth-server/narrow-scope-to-resource [mcp-uri] "agent:question:create"))))
- (testing "blank and missing scopes stay absent rather than becoming an empty parameter"
- (doseq [blank [nil "" " "]]
- (testing (pr-str blank)
- (is (nil? (oauth-server/narrow-scope-to-resource [mcp-uri] blank)))
- (is (nil? (oauth-server/narrow-scope-to-resource nil blank))))))
- (testing "narrowing only ever removes — a client cannot gain a scope it did not request"
- (let [requested "agent:content:read agent:question:create mb:full"]
- (is (every? (scopes requested)
- (scopes (oauth-server/narrow-scope-to-resource [mcp-uri] requested)))))))))
-
-(deftest narrow-scope-to-resource-canonicalization-test
- (testing "resource indicators are compared canonically, not byte-for-byte. Clients disagree on
- trailing slashes, case, and default ports -- a live Claude Code bug appends a trailing
- slash via WHATWG URL -- and a mismatch silently skips narrowing, handing the caller the
- wide consent screen. RFC 3986 makes scheme and host case-insensitive and the default
- port elidable; the path is neither."
- (let [wide "agent:content:read agent:question:create"
- narrowed "agent:content:read"]
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (doseq [indicator ["http://localhost:3000/api/metabase-mcp"
- "http://localhost:3000/api/metabase-mcp/"
- "HTTP://LOCALHOST:3000/api/metabase-mcp"
- "http://LocalHost:3000/api/metabase-mcp/"]]
- (testing (str "matches " (pr-str indicator))
- (is (= narrowed (oauth-server/narrow-scope-to-resource [indicator] wide))))))
- (testing "the default port is elidable in both directions"
- (mt/with-temporary-setting-values [site-url "https://example.com"]
- (doseq [indicator ["https://example.com/api/metabase-mcp"
- "https://example.com:443/api/metabase-mcp"]]
- (testing (str "matches " (pr-str indicator))
- (is (= narrowed (oauth-server/narrow-scope-to-resource [indicator] wide))))))
- (mt/with-temporary-setting-values [site-url "http://example.com"]
- (is (= narrowed (oauth-server/narrow-scope-to-resource
- ["http://example.com:80/api/metabase-mcp"] wide)))))
- (testing "canonicalization does not make unrelated resources match"
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (doseq [indicator ["http://localhost:3000/api/metabase-mcp/extra"
- "http://localhost:3000/API/METABASE-MCP/V2"
- "http://localhost:3001/api/metabase-mcp"
- "https://localhost:3000/api/metabase-mcp"
- "http://evil.example.com/api/metabase-mcp"
- "not-a-uri"]]
- (testing (str "leaves scope alone for " (pr-str indicator))
- (is (= wide (oauth-server/narrow-scope-to-resource [indicator] wide))))))))))
-
-(deftest narrow-scope-to-resource-multiple-indicators-test
- (testing "RFC 8707 allows several `resource` indicators, and a token has to work against each, so the
- accepted set is the UNION of what the named resources accept. Every MCP path now reaches the
- same v2 surface, so the union is that one surface's set however many paths are named -- and a
- per-entity scope no surface accepts is never re-admitted by naming more of them."
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (let [canonical "http://localhost:3000/api/metabase-mcp"
- alias1 "http://localhost:3000/api/mcp"
- wide "mb:full agent:content:read agent:question:create agent:sql:execute"
- scopes #(set (some-> % (str/split #"\s+")))]
- (testing "one indicator each: every path narrows to the v2 surface"
- (doseq [indicator [canonical alias1]]
- (testing indicator
- (let [narrowed (scopes (oauth-server/narrow-scope-to-resource [indicator] wide))]
- (is (contains? narrowed "agent:content:read"))
- (is (not (contains? narrowed "agent:question:create")))
- (is (not (contains? narrowed "agent:sql:execute")))))))
- (testing "naming several paths together is the same union, in either order"
- (doseq [indicators [[canonical alias1] [alias1 canonical]]]
- (testing (pr-str indicators)
- (let [narrowed (scopes (oauth-server/narrow-scope-to-resource indicators wide))]
- (is (contains? narrowed "agent:content:read"))
- (is (not (contains? narrowed "agent:question:create")))))))
- (testing "the union never re-admits a scope no named surface accepts"
- (doseq [indicators [[canonical] [alias1] [canonical alias1] [alias1 canonical]]]
- (testing (pr-str indicators)
- (is (not (contains? (scopes (oauth-server/narrow-scope-to-resource indicators wide))
- "mb:full"))))))))))
-
-(deftest narrow-scope-to-resource-bare-string-test
- (testing "a lone indicator may arrive as a bare string -- the endpoint schema allows one. `keep` over a
- String iterates characters, none of which canonicalize, so an un-normalized argument would skip
- narrowing entirely and hand back the wide scope. Narrowing must not depend on the caller having
- vectorized."
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (let [uri "http://localhost:3000/api/metabase-mcp"
- wide "mb:full agent:content:read agent:question:create"]
- (is (= (oauth-server/narrow-scope-to-resource [uri] wide)
- (oauth-server/narrow-scope-to-resource uri wide)))
- (is (= "agent:content:read" (oauth-server/narrow-scope-to-resource uri wide)))))))
-
-(deftest narrow-scope-to-resource-underscore-host-test
- (testing "`java.net.URI/getHost` is nil for a host it considers non-conformant -- notably one containing an
- underscore, which is routine for Docker Compose and internal k8s service names, and which
- Metabase's own `u/url?` accepts as a Site URL. Reading the host alone made canonicalization
- return nil on such an instance, so no indicator ever matched and narrowing was disabled
- instance-wide, silently."
- (mt/with-temporary-setting-values [site-url "http://metabase_internal:3000"]
- (let [v2 "http://metabase_internal:3000/api/metabase-mcp"
- wide "mb:full agent:content:read agent:question:create"]
- (is (= "agent:content:read" (oauth-server/narrow-scope-to-resource [v2] wide))
- "narrowing still applies when the Site URL host contains an underscore")))
- (testing "canonicalization keeps the properties it had for conformant hosts"
- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
- (let [wide "agent:content:read agent:question:create"
- narrowed "agent:content:read"]
- (testing "userinfo is still stripped rather than compared"
- (is (= narrowed (oauth-server/narrow-scope-to-resource
- ["http://user:pass@localhost:3000/api/metabase-mcp"] wide))))
- (testing "host case is still folded and the default port still elided"
- (is (= narrowed (oauth-server/narrow-scope-to-resource
- ["HTTP://LocalHost:3000/api/metabase-mcp"] wide)))))))))
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index 05fdbab9996..3d674871cda 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -26,7 +26,8 @@
(partial #'mw.session/merge-current-user-info mcp.http-handler/options))
(def ^:private oauth-token->token-scopes
- (partial #'mw.session/oauth-token->token-scopes oauth-server/full-access-scope))
+ (let [{:keys [full-access-scope mcp-scopes]} (:oauth-bearer mcp.http-handler/options)]
+ (partial #'mw.session/oauth-token->token-scopes full-access-scope mcp-scopes)))
(defn- bearer-request [token]
{:headers {"authorization" (str "Bearer " token)}})
@@ -56,13 +57,19 @@
(testing "a token carrying the full-access scope maps to the unrestricted sentinel (general REST reachable)"
(is (= #{::scope/unrestricted}
(oauth-token->token-scopes #{oauth-server/full-access-scope}))))
- (testing "GHY-4942: the other scopes it was granted ride along, since MCP ignores the sentinel and gates on them"
- (is (= #{::scope/unrestricted "agent:sql:run"}
- (oauth-token->token-scopes #{oauth-server/full-access-scope "agent:sql:run"}))))
- (testing "any narrower scope set is passed through verbatim (only opted-in agent endpoints reachable)"
+ (testing "the other REST scopes it was granted ride along"
+ (is (= #{::scope/unrestricted "agent:query:execute"}
+ (oauth-token->token-scopes #{oauth-server/full-access-scope "agent:query:execute"}))))
+ (testing "any narrower REST scope set is passed through verbatim (only opted-in agent endpoints reachable)"
(is (= #{"agent:query:execute"}
(oauth-token->token-scopes #{"agent:query:execute"})))
- (is (= #{} (oauth-token->token-scopes #{})))))
+ (is (= #{} (oauth-token->token-scopes #{}))))
+ (testing "GHY-4969: a token holding any MCP scope is an MCP token, so it keeps only its MCP scopes"
+ (is (= #{"agent:sql:run" "agent:content:read"}
+ (oauth-token->token-scopes #{"agent:sql:run" "agent:content:read" "agent:query:execute"})))
+ (testing "and `mb:full` next to an MCP scope never becomes the unrestricted sentinel"
+ (is (= #{"agent:sql:run"}
+ (oauth-token->token-scopes #{oauth-server/full-access-scope "agent:sql:run"}))))))
(deftest token-scopes-satisfy-scope-middleware-test
(testing "the full-access mapping passes endpoints that declare no :scope; a narrow one is rejected"
@@ -75,7 +82,9 @@
(fn [e] (deliver p e)))
@p))]
(is (= 200 (reached (oauth-token->token-scopes #{oauth-server/full-access-scope}))))
- (is (= 403 (reached (oauth-token->token-scopes #{"agent:query:execute"})))))))
+ (is (= 403 (reached (oauth-token->token-scopes #{"agent:query:execute"}))))
+ (testing "GHY-4969: an MCP token holding `mb:full` cannot reach the general REST API"
+ (is (= 403 (reached (oauth-token->token-scopes #{oauth-server/full-access-scope "agent:sql:run"}))))))))
;;; -------------------------------------------- end-to-end bridge (DB-backed) ----------------------------------------