The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GHY-4542: Reject unregistered and empty OAuth scopes; fail closed on scope-less bearer tokens (#82498)
Eric Normand0700179dad6d
diff --git a/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.tsindex ffdb4e3edd3..36913f4508c 100644--- a/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts+++ b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts@@ -4,6 +4,7 @@ const { H } = cy;const PATH = "/admin/metabot/mcp/authorizations";const REDIRECT_URI = "https://example.com/callback";+const SCOPE = "agent:content:read";/*** End-to-end coverage for the OAuth Authorizations admin page.@@ -110,8 +111,8 @@ function denyClient(client: RegisteredClient) {/*** Drive the consent flow to a decision for a registered client, recording an `approved` or `denied`- * event stamped with the signed-in user. `scope` is omitted (it's optional, and the DCR client's- * agent scopes don't include `profile`); the client must be confidential so the public-client PKCE+ * event stamped with the signed-in user. `/oauth/authorize` requires a scope, and the DCR client's+ * default scopes include `SCOPE`; the client must be confidential so the public-client PKCE* requirement doesn't apply. Mirrors the real browser flow: GET the consent page, lift the CSRF* token + params signature from its hidden fields, then POST the decision (Cypress carries the* CSRF cookie). Both approve and deny redirect (302).@@ -121,7 +122,7 @@ function decideClient(client: RegisteredClient, approved: boolean) {const authorizeUrl =`/oauth/authorize?client_id=${clientId}` +`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` +- "&response_type=code&state=test-state";+ `&response_type=code&scope=${encodeURIComponent(SCOPE)}&state=test-state`;return cy.request("GET", authorizeUrl).then(({ body }) => {cy.request({@@ -136,6 +137,7 @@ function decideClient(client: RegisteredClient, approved: boolean) {client_id: clientId,redirect_uri: REDIRECT_URI,response_type: "code",+ scope: SCOPE,state: "test-state",},})diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 68ef06b478f..90b1ad42e84 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -1651,15 +1651,25 @@(str/trim (subs auth-header 7))))(defn- error-response- "Create a 401 error response with structured JSON body."- [error-type message]+ "Create a 401 error response with a structured JSON body and `challenge` as its RFC 6750 `WWW-Authenticate` value."+ [error-type message challenge]{:status 401- :headers {"Content-Type" "application/json"}+ :headers {"Content-Type" "application/json"+ "WWW-Authenticate" challenge}:body {:error error-type:message message}});;; -------------------------------------------- Stateless JWT Authentication --------------------------------------------+(def ^:private jwt-not-configured+ {:error "jwt_not_configured"+ :message "JWT authentication is not configured. Set the JWT shared secret in admin settings."})++(defn- jwt-provider-available?+ "Whether a `:provider/jwt` implementation is registered with [[auth-identity/authenticate]]."+ []+ (auth-identity/isa? :provider/jwt :metabase.auth-identity.provider/provider))+(defn- authenticate-with-jwt"Authenticate a request using a stateless JWT. Returns `{:user <user>}` on success, or`{:error <type> :message <msg>}` on failure. Does NOT create a session.@@ -1670,26 +1680,30 @@When the JWT contains a `\"scope\"` claim, the result includes `:scopes` — a parsed set of scope strings — so that[[enforce-authentication]] can attach it to the request for downstream scope enforcement."[token]- (let [result (auth-identity/authenticate :provider/jwt {:token token})]- (if (:success? result)- ;; JWT is valid - look up user from the email extracted by the JWT provider- ;; The provider uses jwt-attribute-email setting to extract the email from claims- (if-let [user (when-let [email (get-in result [:user-data :email])]- (agent-api.db/active-user-by-email email))]- (let [scope-entry (-> result :jwt-data (find :scope))]- (cond-> {:user user}- scope-entry- (assoc :scopes (or (scope/parse-scopes (val scope-entry)) #{}))))- ;; Don't reveal whether the user exists or not - use same error as invalid JWT- {:error "invalid_jwt"- :message "Invalid or expired JWT token."})- ;; Authentication failed - map error to agent API format- (case (:error result)- :jwt-not-enabled {:error "jwt_not_configured"- :message "JWT authentication is not configured. Set the JWT shared secret in admin settings."}- ;; Default: use generic invalid JWT message (don't leak details)- {:error "invalid_jwt"- :message "Invalid or expired JWT token."}))))+ ;; The JWT provider ships only in EE, so on OSS nothing registers `:provider/jwt` and `authenticate` has no method+ ;; to dispatch to. Answer the way a disabled provider does rather than let it throw: this is the last stop for a+ ;; bearer token the OAuth bridge already declined, and it owes that request a 401 challenge, not a 500.+ (if-not (jwt-provider-available?)+ jwt-not-configured+ (let [result (auth-identity/authenticate :provider/jwt {:token token})]+ (if (:success? result)+ ;; JWT is valid - look up user from the email extracted by the JWT provider+ ;; The provider uses jwt-attribute-email setting to extract the email from claims+ (if-let [user (when-let [email (get-in result [:user-data :email])]+ (agent-api.db/active-user-by-email email))]+ (let [scope-entry (-> result :jwt-data (find :scope))]+ (cond-> {:user user}+ scope-entry+ (assoc :scopes (or (scope/parse-scopes (val scope-entry)) #{}))))+ ;; Don't reveal whether the user exists or not - use same error as invalid JWT+ {:error "invalid_jwt"+ :message "Invalid or expired JWT token."})+ ;; Authentication failed - map error to agent API format+ (case (:error result)+ :jwt-not-enabled jwt-not-configured+ ;; Default: use generic invalid JWT message (don't leak details)+ {:error "invalid_jwt"+ :message "Invalid or expired JWT token."})))));;; -------------------------------------------------- Middleware ----------------------------------------------------@@ -1700,7 +1714,8 @@- For **session-authenticated** requests (where `:metabase-user-id` is already set byupstream middleware), preserves any pre-existing `:token-scopes` value if present,- otherwise defaults to `#{::scope/unrestricted}` for unrestricted access.+ otherwise defaults to `#{::scope/unrestricted}` for unrestricted access. An OAuth-authenticated+ request without `:token-scopes` is not defaulted, so scope enforcement rejects it.- For **JWT-authenticated** requests, derives `:token-scopes` from the JWT when a`\"scope\"` claim is present, falls back to any pre-existing `:token-scopes` on therequest, and finally defaults to `#{::scope/unrestricted}` for unscoped JWTs.@@ -1714,7 +1729,8 @@;; Preserve existing :token-scopes when present (MCP sets them on the synthetic request).metabase-user-id(handler (cond-> request- (not token-scopes) (assoc :token-scopes #{::scope/unrestricted}))+ (and (not token-scopes) (not (:authenticated-via-oauth? request)))+ (assoc :token-scopes #{::scope/unrestricted}))respond raise);; Not authenticated via session - check for Bearer JWT@@ -1722,15 +1738,19 @@(let [auth-header (get headers "authorization")bearer-token (extract-bearer-token auth-header)](cond- ;; No authorization header and no session+ ;; No authorization header and no session.+ ;; RFC 6750 section 3.1: a challenge to a request with no bearer token carries no error code.(nil? auth-header)(respond (error-response "missing_authorization"- "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."))+ (str "Authentication required. Use X-Metabase-Session header or "+ "Authorization: Bearer <jwt>.")+ "Bearer"));; Authorization header present but not Bearer format(nil? bearer-token)(respond (error-response "invalid_authorization_format"- "Authorization header must use Bearer scheme: Authorization: Bearer <jwt>"))+ "Authorization header must use Bearer scheme: Authorization: Bearer <jwt>"+ "Bearer"));; Validate JWT:else@@ -1745,7 +1765,7 @@token-scopes#{::scope/unrestricted}))respond raise)))- (respond (error-response (:error result) (:message result))))))))))+ (respond (error-response (:error result) (:message result) "Bearer error=\"invalid_token\"")))))))))(def +auth"Agent API authentication middleware. Supports both session-based and stateless JWT authentication."diff --git a/src/metabase/api/macros/scope.clj b/src/metabase/api/macros/scope.cljindex 0a224c07483..35c41f6197b 100644--- a/src/metabase/api/macros/scope.clj+++ b/src/metabase/api/macros/scope.clj@@ -22,6 +22,7 @@request is rejected rather than served. Being a keyword, it can never be requested, granted, or named ona consent screen."(:require+ [clojure.string :as str][metabase.api-scope.core :as api-scope][metabase.config.core :as config][metabase.util.log :as log]))@@ -38,10 +39,45 @@[token-scopes required-scope](api-scope/scope-matches? token-scopes required-scope))+(defn- quoted-string+ "`s` as a double-quoted auth-param value: `\"` becomes `'`, `\\` becomes `/`, and every character outside+ printable ASCII becomes `?`."+ [s]+ ;; Replaced rather than backslash-escaped: RFC 6750 section 3 excludes `\"` and `\\` from `scope` and+ ;; `error_description` values outright, so an escaped quote is still invalid there.+ (str "\""+ (-> (str s)+ (str/replace #"[^\x20-\x7E]" "?")+ (str/replace "\"" "'")+ (str/replace "\\" "/"))+ "\""))++(defn- insufficient-scope-response+ "A 403 JSON response with `error` and `message`, carrying an RFC 6750 `insufficient_scope` `WWW-Authenticate`+ challenge that names `required-scope` as `scope` when non-nil and uses `message` as `error_description`."+ [error message required-scope]+ {:status 403+ ;; Comma-separated per RFC 7235's `#auth-param`.+ :headers {"Content-Type" "application/json"+ "WWW-Authenticate" (str "Bearer error=\"insufficient_scope\""+ (when required-scope+ (str ", scope=" (quoted-string required-scope)))+ ", error_description=" (quoted-string message))}+ :body {:error error+ :message message}})++(defn- oauth-without-token-scopes?+ "True for a request the session middleware authenticated with an OAuth access token that carries no+ `:token-scopes`."+ [request]+ ;; Nil scopes mean scope-unaware auth only for sessions and API keys; for OAuth they must fail closed.+ (and (:authenticated-via-oauth? request)+ (empty? (:token-scopes request))))+(defn enforce-scope"Returns a Ring middleware that checks `:token-scopes` on the request against `required-scope` (a string).Passes through when `:token-scopes` is nil (normal session auth) or contains `::unrestricted`- (session auth or unscoped JWT).+ (session auth or unscoped JWT). Rejects an OAuth-authenticated request with no `:token-scopes`.On success, sets `:token-scopes-checked` on the request so that downstream [[ensure-scopes-checked]]middleware knows scope enforcement already happened. This allows `enforce-scope` to be applied at the@@ -66,19 +102,19 @@(fn [handler](fn [request respond raise](let [token-scopes (:token-scopes request)]- (if (or (nil? token-scopes)- (contains? token-scopes ::unrestricted)- (and (contains? token-scopes ::mcp-ui)- (:token-scopes-checked request))- (scope-satisfied? token-scopes required-scope))+ (if (and (not (oauth-without-token-scopes? request))+ (or (nil? token-scopes)+ (contains? token-scopes ::unrestricted)+ (and (contains? token-scopes ::mcp-ui)+ (:token-scopes-checked request))+ (scope-satisfied? token-scopes required-scope)))(handler (cond-> requesttoken-scopes (assoc :token-scopes-checked true))respond raise)(do (log/warnf "Scope check failed — required: %s, granted: %s" required-scope token-scopes)- (respond {:status 403- :headers {"Content-Type" "application/json"}- :body {:error "unsupported_scope"- :message "Insufficient scope for this operation."}})))))))+ (respond (insufficient-scope-response "unsupported_scope"+ "Insufficient scope for this operation."+ required-scope))))))))(defn ensure-scopes-checked"Security middleware that prevents scoped authorization tokens from accessing endpoints that have not@@ -90,15 +126,17 @@Passes through when:- `:token-scopes` is nil (request did not go through scope-aware auth)- `:token-scopes` contains `::unrestricted` (session auth or unscoped JWT)- - `:token-scopes-checked` is true ([[enforce-scope]] already ran, e.g. at the namespace level)"+ - `:token-scopes-checked` is true ([[enforce-scope]] already ran, e.g. at the namespace level)++ None of these apply to an OAuth-authenticated request with no `:token-scopes`, which is always rejected."[handler](fn [request respond raise](let [token-scopes (:token-scopes request)]- (if (or (nil? token-scopes)- (contains? token-scopes ::unrestricted)- (:token-scopes-checked request))+ (if (and (not (oauth-without-token-scopes? request))+ (or (nil? token-scopes)+ (contains? token-scopes ::unrestricted)+ (:token-scopes-checked request)))(handler request respond raise)- (respond {:status 403- :headers {"Content-Type" "application/json"}- :body {:error "scope_not_permitted"- :message "Scoped tokens cannot access this endpoint."}})))))+ (respond (insufficient-scope-response "scope_not_permitted"+ "Scoped tokens cannot access this endpoint."+ nil))))))diff --git a/src/metabase/mcp/transport.clj b/src/metabase/mcp/transport.cljindex 2460015b222..21fc524fe2d 100644--- a/src/metabase/mcp/transport.clj+++ b/src/metabase/mcp/transport.clj@@ -693,10 +693,17 @@[{:keys [tools-hash-fn endpoint-paths default-path default-ask-scopes] :as opts}](open-api/handler-with-open-api-spec(fn [request respond raise]- (let [origin-error (validate-origin request)- bearer-token (oauth-server/extract-bearer-token request)- session-auth api/*current-user-id*- token-scopes (:token-scopes request)]+ (let [origin-error (validate-origin request)+ bearer-token (oauth-server/extract-bearer-token request)+ session-auth api/*current-user-id*+ token-scopes (:token-scopes request)+ ;; RFC 6750 `invalid_token`, still carrying the RFC 9728 discovery parameters: a client whose token+ ;; expired re-discovers the protected-resource metadata from this 401 (MCP auth spec MUST).+ invalid-token (delay (json-response 401 (jsonrpc-error nil -32603 (message/msg ["Invalid bearer token"]))+ {"WWW-Authenticate"+ (str (www-authenticate-discovery endpoint-paths default-path+ default-ask-scopes request)+ ", error=\"invalid_token\"")}))](letfn [(dispatch [user-id token-scopes](request/with-current-user user-id;; Charge the throttle per JSON-RPC message, not per HTTP request, so a batch can't smuggle many@@ -725,6 +732,11 @@(some? origin-error)(respond origin-error)+ ;; The session middleware never authenticates an OAuth token without scopes. Should one arrive, the+ ;; `session-auth` branch below would dispatch nil scopes as unrestricted, so refuse it as an invalid token.+ (and (:authenticated-via-oauth? request) (empty? token-scopes))+ (respond @invalid-token)+;; Respect the scope set attached to an authenticated request. Sessions without one;; retain unrestricted access.session-auth@@ -741,12 +753,7 @@;; active-user check (a disabled user's token still authenticated) and the scope trust hinge (raw token;; scopes dispatched verbatim). Return the RFC 6750 `invalid_token` 401 and dispatch nothing.bearer-token- ;; RFC 6750 `invalid_token`, still carrying the RFC 9728 discovery parameters: a client whose- ;; token expired re-discovers the protected-resource metadata from this 401 (MCP auth spec MUST).- (respond (json-response 401 (jsonrpc-error nil -32603 (message/msg ["Invalid bearer token"]))- {"WWW-Authenticate" (str (www-authenticate-discovery endpoint-paths default-path- default-ask-scopes request)- ", error=\"invalid_token\"")}))+ (respond @invalid-token);; No auth at all — return 401 with discovery:elsediff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljindex 634be1545f2..e0fc6db26b9 100644--- a/src/metabase/oauth_server/api/oauth.clj+++ b/src/metabase/oauth_server/api/oauth.clj@@ -24,7 +24,7 @@[throttle.core :as throttle])(:import(clojure.lang ExceptionInfo)- (java.net URI URLEncoder)))+ (java.net URI URISyntaxException URLEncoder)))(set! *warn-on-reflection* true)@@ -116,6 +116,83 @@;; hardcoding the scope string in the view.:full-access? (= s oauth-server/full-access-scope)})))))+;;; ------------------------------------------- Error descriptions ------------------------------------------------++;;; Fixed strings, never echoing what the request sent, and within the RFC 6749 section 5.2 character set.++(def ^:private invalid-authorization-request-description "The authorization request is invalid.")++(def ^:private invalid-token-request-description "The token request is invalid.")++(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- authorization-server-metadata-url+ "Absolute URL of the RFC 8414 authorization server metadata document, which lists `scopes_supported`."+ []+ (str (system/site-url) "/.well-known/oauth-authorization-server"))++(defn- unsupported-scopes-description+ "The `error_description` for a registration naming a scope that is not registered."+ []+ (str "The request contained unsupported scopes. Request only scopes listed in scopes_supported at "+ (authorization-server-metadata-url)))++(defn- no-supported-scopes-description+ "The `error_description` for an authorization request in which no requested scope is registered."+ []+ (str "None of the requested scopes are supported. Request only scopes listed in scopes_supported at "+ (authorization-server-metadata-url)))++(defn- missing-scope-description+ "The `error_description` for an authorization request with no scope."+ []+ (str "The request must include a scope. Request only scopes listed in scopes_supported at "+ (authorization-server-metadata-url)))++(defn- empty-scope-description+ "The `error_description` for a client registration whose `scope` is present but empty."+ []+ (str "The scope must not be empty. Omit scope, or include only scopes listed in scopes_supported at "+ (authorization-server-metadata-url)))++(defn- invalid-client-metadata-response+ "The RFC 7591 `invalid_client_metadata` 400 for a registration this endpoint refuses before the library sees it."+ [description]+ {:status 400+ :headers {"Content-Type" "application/json"}+ :body {"error" "invalid_client_metadata"+ "error_description" description}})++;;; -------------------------------------------- Resource indicators ----------------------------------------------++(defn- malformed-resource?+ "True when any `resource` indicator (a string, or a sequence of strings) is not an absolute URI without a fragment,+ as RFC 8707 section 2 requires."+ [resource]+ ;; oidc-provider validates resource indicators by constructing a `java.net.URI`, so an unparseable one reaches the+ ;; endpoints as a URISyntaxException rather than the ex-info they catch. Checked here before the library sees it,+ ;; which also lets every malformed indicator be answered with the description saying what a valid one looks like.+ (boolean+ (some (fn [r]+ (try+ (let [uri (URI. (str r))]+ (or (not (.isAbsolute uri))+ (some? (.getFragment uri))))+ (catch URISyntaxException _+ true)))+ (if (string? resource) [resource] resource))))++(defn- check-resource-indicators!+ "Throw the RFC 8707 `invalid_target` error when any `resource` indicator is malformed."+ [resource]+ (when (malformed-resource? resource)+ (throw (ex-info "resource is not a valid indicator" {:error "invalid_target"+ :error-description invalid-target-description}))))+(defn- redirect-authorization-decision"Issue a 302 redirect for an approved or denied authorization decision, clearing the CSRF cookie."[provider parsed approved request]@@ -211,11 +288,21 @@:body {"error" "registration_not_supported"}}(with-throttling-429 [registration-throttler (request/ip-address request)](or (when-let [provider (oauth-server/get-provider)]- (if (nil? body)- {:status 400- :headers {"Content-Type" "application/json"}- :body {"error" "invalid_client_metadata"- "error_description" "Invalid or missing JSON body"}}+ (cond+ (nil? body)+ (invalid-client-metadata-response "Invalid or missing JSON body")++ ;; Only an omitted `scope` gets the default below; an empty one would register a client that+ ;; can never authorize.+ (and (contains? body :scope) (str/blank? (:scope body)))+ (invalid-client-metadata-response (empty-scope-description))++ ;; A client's registered scopes are the ceiling /authorize checks requests against, so a+ ;; self-nominated wildcard such as `*` would later be granted as one.+ (not (oauth-server/all-scopes-registered? (:scope body)))+ (invalid-client-metadata-response (unsupported-scopes-description))++ :else(try;; MCP clients frequently omit application_type, scope, and may request;; unsupported grant types. We are required to support poorly-configured@@ -271,6 +358,90 @@:body body})))){:status 404 :body {:error "not_found"}}))+(defn- authorization-error-code+ "The RFC 6749 section 4.1.2.1 (or RFC 8707) `error` code for the ex-data of an exception thrown while validating an+ authorization request."+ [{:keys [oauth-error error] :as data}]+ (or oauth-error+ ;; oidc-provider names a code only for its PKCE and resource-indicator errors; its response_type and scope+ ;; errors are told apart by the data they carry, and malformed parameters carry neither.+ error+ (cond+ (contains? data :response-type) "unsupported_response_type"+ (contains? data :requested) "invalid_scope"+ :else "invalid_request")))++(defn- error-description+ "The `error_description` for an exception's ex-data: the one it carries, else `fallback`."+ [data fallback]+ (or (:error-description data)+ (:error_description data)+ fallback))++(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.++ 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."+ [parsed]+ (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))++(defn- authorization-consent-response+ "Validate the authorization request `query-params` and return the consent page response, which sets the CSRF+ cookie. Throws `ex-info` when the request is invalid; its data may carry `:oauth-error` and `:error-description`."+ [provider query-params request]+ (let [_ (check-resource-indicators! (:resource query-params))+ ;; A blank scope is dropped so the provider validates the rest of the request first; the missing scope is+ ;; then reported as `invalid_scope` by [[scope-to-grant]].+ parsed (oidc/parse-authorization-request provider+ (cond-> query-params+ (str/blank? (:scope query-params)) (dissoc :scope)))+ ;; Narrowed before signing, so the signature binds the granted scope through the consent form round-trip.+ parsed (assoc parsed :scope (scope-to-grant parsed))+ client (proto/get-client (:client-store provider) (:client_id parsed))+ csrf-token (generate-csrf-token)+ oauth-params (select-keys parsed oauth-param-keys)+ params-sig (sign-oauth-params csrf-token oauth-params)]+ (-> {:status 200+ :headers {"Content-Type" "text/html; charset=utf-8"}+ :body (consent-page/render-consent-page+ {:client-name (some-> (:client-name client) (truncate 64))+ :nonce (:nonce request)+ :csrf-token csrf-token+ :params-sig params-sig+ :scopes (requested-scope-descriptions (:scope oauth-params))+ :oauth-params oauth-params})}+ (response/set-cookie csrf-cookie-name csrf-token (csrf-cookie-opts 600)))))+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case]}(api.macros/defendpoint :get "/authorize":- [:map [:status [:enum 200 302 400 404]] [:body [:or :string :map]]]@@ -294,48 +465,19 @@:body ""}(or (when-let [provider (oauth-server/get-provider)](try- (let [parsed (oidc/parse-authorization-request provider query-params)- ;; Narrow before signing: the signature then binds the narrowed scope through the- ;; consent form round-trip, so the decision endpoint grants exactly what was shown.- requested (some-> (:scope parsed) str str/trim not-empty)- narrowed (oauth-server/narrow-scope-to-resource (:resource parsed) (:scope parsed))- ;; `narrow-scope-to-resource` answers nil both for "no scope was requested" and for- ;; "a scope was requested and nothing survived". Only the first may drop the parameter.- ;; The second means the client asked exclusively for scopes this resource does not- ;; accept: dropping it 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 (and requested (not narrowed))- (throw (ex-info "no requested scope is accepted by the named resource"- {:oauth-error "invalid_scope"- :error-description (str "The requested scopes are not accepted by "- "the requested resource.")- :resource (:resource parsed)})))- parsed (if narrowed- (assoc parsed :scope narrowed)- (dissoc parsed :scope))- client (proto/get-client (:client-store provider) (:client_id parsed))- csrf-token (generate-csrf-token)- oauth-params (select-keys parsed oauth-param-keys)- params-sig (sign-oauth-params csrf-token oauth-params)]- (-> {:status 200- :headers {"Content-Type" "text/html; charset=utf-8"}- :body (consent-page/render-consent-page- {:client-name (some-> (:client-name client) (truncate 64))- :nonce (:nonce request)- :csrf-token csrf-token- :params-sig params-sig- :scopes (requested-scope-descriptions (:scope oauth-params))- :oauth-params oauth-params})}- (response/set-cookie csrf-cookie-name csrf-token (csrf-cookie-opts 600))))+ (authorization-consent-response provider query-params request)(catch ExceptionInfo e(log/warnf "OAuth authorize request failed: %s" (ex-message e))- (let [{:keys [oauth-error error-description]} (ex-data e)]+ ;; Reported to the user in their own browser, never by redirecting to the client's redirect URI.+ ;; Dynamic registration is unauthenticated, so a client can register any redirect URI it likes, and+ ;; redirecting errors there would turn a link on this host into a zero-click open redirector+ ;; (RFC 9700 section 4.11).+ (let [data (ex-data e)+ error (authorization-error-code data)]{:status 400:headers {"Content-Type" "application/json"}- :body {:error (or oauth-error "invalid_request")- :error_description (or error-description- "The authorization request is invalid.")}}))))+ :body {:error error+ :error_description (error-description data invalid-authorization-request-description)}})))){:status 404 :body {:error "not_found"}})))(api.macros/defendpoint :post "/authorize/decision"@@ -375,6 +517,7 @@:body {:error "csrf_validation_failed"}}(let [approved (= "true" (str (:approved body)))](try+ (check-resource-indicators! (:resource auth-params))(let [parsed (oidc/parse-authorization-request provider auth-params);; Verify the HMAC against the *parsed* params (same normalized form as the consent page).;; This must happen after parsing to ensure form-encoding round-trips don't cause mismatches.@@ -386,13 +529,21 @@{:status 403:headers {"Content-Type" "application/json"}:body {:error "params_tampered"}}- (redirect-authorization-decision provider parsed approved request)))+ ;; The signature says the form was not tampered with by a third party, not that its scope+ ;; was ever validated: it is keyed by the CSRF token printed on the consent page, so the+ ;; user can re-sign anything. This is where the code is issued, so the scope rules apply+ ;; here too. A denial grants nothing and needs none of them.+ (redirect-authorization-decision provider+ (cond-> parsed+ approved (assoc :scope (scope-to-grant parsed)))+ approved+ request)))(catch ExceptionInfo e(log/warnf "OAuth authorization decision failed: %s" (ex-message e)){:status 400:headers {"Content-Type" "application/json"}:body {:error "invalid_request"- :error_description "The authorization request is invalid."}}))))))+ :error_description invalid-authorization-request-description}})))))){:status 404 :body {:error "not_found"}}))))(api.macros/defendpoint :post "/token"@@ -420,6 +571,7 @@(or (when-let [provider (oauth-server/get-provider)](let [authorization-header (get-in request [:headers "authorization"])](try+ (check-resource-indicators! (:resource body))(let [response (oidc/token-request provider body authorization-header)]{:status 200:headers {"Content-Type" "application/json"@@ -435,7 +587,7 @@"Cache-Control" "no-store""Pragma" "no-cache"}:body {:error error- :error_description (or (:error_description data) "The token request is invalid.")}})))))+ :error_description (error-description data invalid-token-request-description)}}))))){:status 404 :body {:error "not_found"}}))))(api.macros/defendpoint :post "/revoke"diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.cljindex 430534c0ed2..97e1e915e29 100644--- a/src/metabase/oauth_server/core.clj+++ b/src/metabase/oauth_server/core.clj@@ -2,6 +2,7 @@(:require[clojure.string :as str][java-time.api :as t]+ [metabase.api-scope.core :as api-scope][metabase.mcp.core :as mcp][metabase.oauth-server.db :as oauth-server.db][metabase.oauth-server.scopes :as scopes]@@ -32,11 +33,26 @@`mb:full` is deliberately absent. Advertising it here puts a full-access grant in front of every client that readsdiscovery metadata, so keeping it out means no client is led toward it. Note this is not a gate: dynamic- registration is unauthenticated and passes a client-supplied `scope` through unchecked, so a client that names- `mb:full` itself still registers with it. Keeping it off this list narrows who finds it, not who may ask."+ registration is unauthenticated and accepts any registered scope, so a client that names `mb:full` itself still+ registers with it. Keeping it off this list narrows who finds it, not who may ask."[](vec (into (sorted-set) (mcp/all-scopes))))+(defn all-scopes-registered?+ "True when every scope in the space-delimited `scope` string is registered via+ [[metabase.api-scope.core/defscope]]. A nil or blank `scope` names none, so it is true."+ [scope]+ (every? api-scope/registered-scope? (api-scope/parse-scopes scope)))++(defn registered-scopes-only+ "The space-delimited `scope` string with every scope that is not registered via+ [[metabase.api-scope.core/defscope]] removed, keeping the requested order, or nil when none remain."+ [scope]+ (some->> (str/split (str scope) #"\s+")+ (filter api-scope/registered-scope?)+ 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@@ -159,17 +175,14 @@no named surface accepts are dropped, so the consent screen asks for what the token can actually be used forrather than everything the client registered. Several indicators may be sent, and the token has to work againsteach, 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 nothing survives.-- Note nil is the answer for both \"nothing was requested\" and \"nothing survived\"; the caller has the requested- scope and must tell them apart, since only the first may drop the parameter (see the authorize handler).+ 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 connectedthrough an alias was handed that path as its resource identifier, and narrowing has to recognize what it was told tosend back.- Only ever removes scopes, and runs after the provider has validated the request, so it can never turn a valid- authorization into a rejected one.+ 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 isasking for a token to use against that surface — which accepts none of the REST API that scope unlocks.diff --git a/src/metabase/request/schema.clj b/src/metabase/request/schema.cljindex aa38c81ff48..514e5ec40ef 100644--- a/src/metabase/request/schema.clj+++ b/src/metabase/request/schema.clj@@ -21,7 +21,8 @@[:auth-provider {:optional true} [:maybe :string]][:settings {:optional true} [:maybe [:or ms/UserSettings :string]]][:token-scopes {:optional true} [:maybe [:set [:or :keyword :string]]]]- [:token-scopes-checked {:optional true} :boolean]])+ [:token-scopes-checked {:optional true} :boolean]+ [:authenticated-via-oauth? {:optional true} :boolean]])(mr/def ::json-value"A JSON-shaped value: a scalar, a sequence of JSON values, or a string-keyed JSON object."@@ -107,6 +108,7 @@[:slack/validated? {:optional true} :boolean][:token-scopes {:optional true} [:maybe [:set [:or :keyword :string]]]][:token-scopes-checked {:optional true} :boolean]+ [:authenticated-via-oauth? {:optional true} :boolean][:mcp-ui-session-id {:optional true} [:maybe :string]][:mcp-ui-credential {:optional true} [:maybe[:map {:closed true}diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 3d259e3d9a1..83261b6a4ab 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -187,15 +187,19 @@(mu/defn- current-user-info-for-oauth-token :- [:maybe ::request.schema/current-user-info]"Return current-user-info for a valid OAuth bearer access token on `request`, or nil. Mirrors theshape returned by the session/api-key resolvers and additionally attaches `:token-scopes`, so the- merged request carries both the user identity and the access the token was granted. This is the- only place an OAuth access token authenticates a request to the general (`/api/*`) API."+ 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."[request :- ::request.schema/request](when (init-status/complete?)(when-let [token (oauth-server/extract-bearer-token request)](when-let [{:keys [user-id scopes]} (oauth-server/resolve-access-token token)]- (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 scopes)))))))+ ;; Downstream, nil `:token-scopes` passes as scope-unaware auth, so a scope-less token is refused here.+ (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 scopes)+ :authenticated-via-oauth? true)))))))(defn- current-user-info-for-mcp-ui-credential"Resolve the short-lived credential from an MCP App tool result.diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex 2221d3c778a..99c5d59f4a9 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -10,6 +10,7 @@[metabase.agent-api.settings :as agent-api.settings][metabase.ai-tracing.log :as ait.log][metabase.ai-tracing.settings :as ai-tracing.settings]+ [metabase.api.macros.scope :as api.scope][metabase.collections.models.collection :as collection][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -82,6 +83,68 @@(client/client :get 401 "agent/v1/ping"{:request-options {:headers {"x-metabase-session" session-key}}})))))))))+(deftest agent-api-401-for-an-unusable-bearer-token-carries-invalid-token-test+ (testing "GHY-4542: RFC 6750 section 3 requires a 401 for a bearer token that does not authenticate to carry an+ `invalid_token` challenge. The session middleware declines such a token silently, leaving the agent API+ to answer the request, so the challenge has to come from there."+ ;; site-url: resolving the bearer token builds the OAuth provider, whose config derives its issuer from it+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (client/client-full-response+ :get 401 "agent/v1/ping"+ {:request-options {:headers {"authorization" (str "Bearer " (random-uuid))}}})]+ (is (= "Bearer error=\"invalid_token\"" (get-in response [:headers "WWW-Authenticate"])))+ ;; which of the JWT failures the body names depends on whether a shared secret is configured; the challenge+ ;; is the same either way+ (is (string? (get-in response [:body :message])))))))++(deftest agent-api-401-when-no-jwt-provider-is-registered-test+ (testing "GHY-4542: the JWT provider ships only in EE, so on OSS nothing registers `:provider/jwt` and+ `auth-identity/authenticate` has no method to dispatch to. A bearer token the OAuth bridge declined+ reaches that dispatch, and the agent API has to answer it with the 401 `invalid_token` challenge rather+ than let the dispatch throw and serve a 500 carrying a stack trace."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (with-redefs-fn {#'agent-api.api/jwt-provider-available? (constantly false)}+ (fn []+ (let [response (client/client-full-response+ :get 401 "agent/v1/ping"+ {:request-options {:headers {"authorization" (str "Bearer " (random-uuid))}}})]+ (is (= "Bearer error=\"invalid_token\"" (get-in response [:headers "WWW-Authenticate"])))+ (is (= "jwt_not_configured" (get-in response [:body :error])))))))))++(deftest agent-api-401-without-bearer-token-carries-plain-challenge-test+ (testing "GHY-4542: RFC 7235 requires every 401 to carry a `WWW-Authenticate` challenge, and RFC 6750 section 3.1+ says one answering a request with no bearer token SHOULD NOT include an error code. So both 401s the+ agent API gives before it has a token to judge carry a plain `Bearer` challenge, with unchanged bodies."+ (testing "no credentials at all"+ (let [response (client/client-full-response :get 401 "agent/v1/ping")]+ (is (= "Bearer" (get-in response [:headers "WWW-Authenticate"])))+ (is (= {:error "missing_authorization"+ :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}+ (:body response)))))+ (testing "an Authorization header that does not use the Bearer scheme"+ (let [response (client/client-full-response :get 401 "agent/v1/ping"+ {:request-options {:headers {"authorization" "Basic dXNlcjpwYXNz"}}})]+ (is (= "Bearer" (get-in response [:headers "WWW-Authenticate"])))+ (is (= {:error "invalid_authorization_format"+ :message "Authorization header must use Bearer scheme: Authorization: Bearer <jwt>"}+ (:body response)))))))++(deftest enforce-authentication-does-not-widen-oauth-request-without-scopes-test+ (testing "GHY-4542: the agent API defaults nil `:token-scopes` on an authenticated request to unrestricted, which+ is right for a session but would hand an OAuth-authenticated request with no scopes full access and+ defeat the scope middleware's own fail-closed check. That request keeps nil and is refused by the+ endpoint's scope check."+ (let [enforce-authentication #'agent-api.api/enforce-authentication+ handler (enforce-authentication+ ((api.scope/enforce-scope "agent:search") (fn [_ respond _] (respond {:status 200}))))+ status (fn [request]+ (let [p (promise)]+ (handler request #(deliver p (:status %)) #(deliver p %))+ (deref p 10000 ::timeout)))]+ (is (= 403 (status {:metabase-user-id (mt/user->id :rasta) :authenticated-via-oauth? true})))+ (testing "a session request with nil token-scopes is still unrestricted"+ (is (= 200 (status {:metabase-user-id (mt/user->id :rasta)})))))))+(deftest agent-api-enabled-setting-test(testing "External Agent API routes return 403 when disabled"(mt/with-temporary-setting-values [agent-api.settings/agent-api-enabled? false]diff --git a/test/metabase/api/macros/scope_test.clj b/test/metabase/api/macros/scope_test.cljindex b857486f0b2..73c242cb911 100644--- a/test/metabase/api/macros/scope_test.clj+++ b/test/metabase/api/macros/scope_test.clj@@ -102,6 +102,86 @@(is (= 403 (:status (invoke {:token-scopes #{"agent:queries"} :token-scopes-checked true}))))(is (= 403 (:status (invoke {:token-scopes #{} :token-scopes-checked true})))))))+(deftest ^:parallel oauth-request-without-token-scopes-fails-closed-test+ (testing "GHY-4542: nil `:token-scopes` means scope-unaware auth (a session or API key), so both middlewares+ let it through. An OAuth-authenticated request always carries its granted scopes; one that arrives+ without any must be refused, not treated as unrestricted. The auth method the session middleware+ records decides which case it is, not the presence of a bearer header."+ (let [ok-handler (fn [_request respond _raise]+ (respond {:status 200 :body "ok"}))+ middleware (scope/enforce-scope "agent:reports")]+ (doseq [[label wrapped] {"enforce-scope" (middleware ok-handler)+ "ensure-scopes-checked" (scope/ensure-scopes-checked ok-handler)}]+ (testing label+ (doseq [token-scopes [nil #{}]]+ (testing (str "OAuth-authenticated with token-scopes " (pr-str token-scopes) " is refused")+ (let [response (invoke-handler wrapped {:authenticated-via-oauth? true+ :token-scopes token-scopes})]+ (is (= 403 (:status response)))+ (is (= (if (= label "enforce-scope") "unsupported_scope" "scope_not_permitted")+ (get-in response [:body :error])))))+ (testing (str "even when already stamped :token-scopes-checked, with token-scopes " (pr-str token-scopes))+ (is (= 403 (:status (invoke-handler wrapped {:authenticated-via-oauth? true+ :token-scopes token-scopes+ :token-scopes-checked true}))))))+ (testing "the same request without the OAuth marker is session or API-key auth and passes"+ (is (= {:status 200 :body "ok"}+ (invoke-handler wrapped {:token-scopes nil}))))+ (testing "an OAuth request carrying a full-access grant still passes"+ (is (= {:status 200 :body "ok"}+ (invoke-handler wrapped {:authenticated-via-oauth? true+ :token-scopes #{::scope/unrestricted}})))))))))++(deftest ^:parallel quoted-string-test+ (testing "GHY-4542: RFC 6750 section 3 excludes `\"` and `\\` from an auth-param value outright, so neither can be+ escaped into one, and limits the rest to printable ASCII. A value carrying any of them would produce a+ challenge header a client cannot parse, so they are replaced rather than emitted."+ (let [quoted-string #'scope/quoted-string]+ (is (= "\"plain value\"" (quoted-string "plain value")))+ (is (= "\"it's 'quoted'\"" (quoted-string "it's \"quoted\"")))+ (is (= "\"back/slash\"" (quoted-string "back\\slash")))+ (is (= "\"caf?\"" (quoted-string "café")))+ (is (= "\"tab?here\"" (quoted-string "tab\there")))+ (is (= "\"\"" (quoted-string nil)))+ (testing "so every value it produces stays inside the character set"+ (doseq [s ["plain value" "it's \"quoted\"" "back\\slash" "café" "tab\there"]]+ (is (re-matches #"\"[\x20-\x21\x23-\x5B\x5D-\x7E]*\"" (quoted-string s))))))))++(deftest ^:parallel scope-denial-carries-insufficient-scope-challenge-test+ (testing "GHY-4542: RFC 6750 section 3 requires a resource server to answer a bearer token that does not grant+ access with a `WWW-Authenticate` challenge. `insufficient_scope` tells an OAuth client to re-authorize+ for more scope instead of treating the 403 as final; `scope` names what `enforce-scope` requires, and+ is omitted where the endpoint declares no scope to ask for."+ (let [ok-handler (fn [_request respond _raise]+ (respond {:status 200 :body "ok"}))+ enforced ((scope/enforce-scope "agent:reports") ok-handler)+ unchecked (scope/ensure-scopes-checked ok-handler)]+ (doseq [[label wrapped request expected]+ [["enforce-scope, insufficient scope"+ enforced {:token-scopes #{"agent:queries"}}+ (str "Bearer error=\"insufficient_scope\", scope=\"agent:reports\", "+ "error_description=\"Insufficient scope for this operation.\"")]+ ["enforce-scope, OAuth request without token-scopes"+ enforced {:authenticated-via-oauth? true}+ (str "Bearer error=\"insufficient_scope\", scope=\"agent:reports\", "+ "error_description=\"Insufficient scope for this operation.\"")]+ ["ensure-scopes-checked, scoped token on an endpoint without a scope"+ unchecked {:token-scopes #{"agent:reports"}}+ (str "Bearer error=\"insufficient_scope\", "+ "error_description=\"Scoped tokens cannot access this endpoint.\"")]+ ["ensure-scopes-checked, OAuth request without token-scopes"+ unchecked {:authenticated-via-oauth? true :token-scopes-checked true}+ (str "Bearer error=\"insufficient_scope\", "+ "error_description=\"Scoped tokens cannot access this endpoint.\"")]]]+ (testing label+ (let [response (invoke-handler wrapped request)]+ (is (= 403 (:status response)))+ (is (= expected (get-in response [:headers "WWW-Authenticate"])))+ (testing "the JSON body is unchanged"+ (is (= "application/json" (get-in response [:headers "Content-Type"])))+ (is (= (if (= wrapped enforced) "unsupported_scope" "scope_not_permitted")+ (get-in response [:body :error]))))))))))+(deftest ^:parallel ensure-scopes-checked-test(let [ok-handler (fn [_request respond _raise](respond {:status 200 :body "ok"}))]diff --git a/test/metabase/mcp/transport_test.clj b/test/metabase/mcp/transport_test.cljindex d9b9ed6b7b5..cbce5cba63f 100644--- a/test/metabase/mcp/transport_test.clj+++ b/test/metabase/mcp/transport_test.clj@@ -549,6 +549,43 @@(is (str/includes? (get-in response [:headers "WWW-Authenticate"] "") "resource_metadata=")"the invalid_token challenge still carries RFC 9728 discovery")))))))))+(defn- invoke-transport+ "Invoke an MCP transport handler directly, bypassing the session middleware, as `user-id` with the given extra+ request keys, and return the response."+ [user-id request-keys body]+ (let [handler (mcp.transport/make-handler {:dispatch-method-fn (fn [id & _] (mcp.transport/jsonrpc-response id {}))+ :capabilities {:tools {}}+ :tools-hash-fn (constantly "hash")+ :endpoint-paths #{"/api/metabase-mcp"}+ :default-path "/api/metabase-mcp"})+ result (promise)]+ (mt/with-current-user user-id+ (handler (merge {:request-method :post+ :uri "/api/metabase-mcp"+ :headers {}+ :body body}+ request-keys)+ #(deliver result %)+ #(deliver result %)))+ (deref result 10000 ::timeout)))++(deftest oauth-request-without-token-scopes-is-refused-by-the-transport-test+ (testing "GHY-4542: defense in depth behind the session middleware. A request authenticated via OAuth but carrying+ no `:token-scopes` is refused with the invalid_token 401 rather than dispatched as unrestricted. The+ marker the session middleware records decides it, so a cookie session (nil token-scopes, no marker)+ keeps unrestricted access."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [initialize {"jsonrpc" "2.0" "id" 1 "method" "initialize" "params" {"capabilities" {}}}]+ (doseq [token-scopes [nil #{}]]+ (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"] "") "invalid_token")))))+ (testing "a session request with nil token-scopes is served"+ (is (= 200 (:status (invoke-transport (mt/user->id :rasta) {} initialize)))))))))+;;; -------------------------------------------------- Throttling --------------------------------------------------(deftest per-user-throttle-returns-429-testdiff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljindex 69e957d5705..434c02dc481 100644--- a/test/metabase/oauth_server/api_test.clj+++ b/test/metabase/oauth_server/api_test.clj@@ -240,6 +240,82 @@:expected-status 403)](is (= "registration_not_supported" (:error response)))))))+(deftest dynamic-register-rejects-unregistered-scopes-test+ (testing "GHY-4542: registration is unauthenticated, and a client's registered scopes are the ceiling+ `/oauth/authorize` checks requests against. Storing a self-nominated `*` or `agent:*` lets the+ client request it later and receive a token `scope-matches?` treats as a wildcard grant, so+ any scope that is not a registered scope is rejected before anything is stored. The error+ points the client at the metadata document listing the supported scopes and does not echo+ what it sent."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (doseq [scope ["*" "agent:*" "bogus" "agent:content:read *" "agent:ü\"x\\"]]+ (testing (pr-str scope)+ (let [before (t2/count :model/OAuthClient)+ response (register-client! {:redirect_uris ["https://example.com/callback"]+ :scope scope}+ :expected-status 400)]+ (is (= {:error "invalid_client_metadata"+ :error_description (str "The request contained unsupported scopes. Request only scopes listed "+ "in scopes_supported at "+ "http://localhost:3000/.well-known/oauth-authorization-server")}+ response)+ "the description tells the client where the supported scopes are listed, without echoing what it+ sent, and stays within the RFC 6749 section 5.2 character set")+ (is (= before (t2/count :model/OAuthClient))+ "no client is stored"))))))))++(deftest dynamic-register-rejects-empty-scope-test+ (testing "GHY-4542: a client that sends `scope` but leaves it empty would register with no scopes and could+ never authorize, since /oauth/authorize requires a scope. That is rejected rather than silently+ replaced with the default ceiling, which is reserved for a client that omits `scope` entirely+ (pinned in `dynamic-register-accepts-registered-scopes-test`)."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ ;; `nil` is encoded as JSON null. Were the key dropped in decoding, the client would get the default+ ;; ceiling and a 201.+ (doseq [body [{:redirect_uris ["https://example.com/callback"] :scope nil}+ {:redirect_uris ["https://example.com/callback"] :scope ""}+ {:redirect_uris ["https://example.com/callback"] :scope " "}]]+ (testing (pr-str body)+ (let [before (t2/count :model/OAuthClient)+ response (register-client! body :expected-status 400)]+ (is (= {:error "invalid_client_metadata"+ :error_description (str "The scope must not be empty. Omit scope, or include only scopes "+ "listed in scopes_supported at "+ "http://localhost:3000/.well-known/oauth-authorization-server")}+ response))+ (is (= before (t2/count :model/OAuthClient))+ "no client is stored"))))+ (testing "`scope` is a space-delimited string, so an empty JSON array fails the body schema"+ (let [before (t2/count :model/OAuthClient)]+ (register-client! {:redirect_uris ["https://example.com/callback"] :scope []}+ :expected-status 400)+ (is (= before (t2/count :model/OAuthClient))+ "no client is stored")))))))++(deftest dynamic-register-accepts-registered-scopes-test+ (testing "GHY-4542: rejecting unregistered scopes must not reject registered ones"+ (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 "an explicit set of registered scopes is stored as sent"+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]+ :scope "agent:content:read agent:query:run"})]+ (is (= #{"agent:content:read" "agent:query:run"}+ (set (:scopes (t2/select-one :model/OAuthClient :client_id (:client_id response))))))))+ (testing "`mb:full` is registered, and the Metabase CLI registers with it explicitly"+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]+ :scope oauth-server/full-access-scope})]+ (is (= #{oauth-server/full-access-scope}+ (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))+ (set (:scopes (t2/select-one :model/OAuthClient :client_id (:client_id response))))))))))))+(deftest discovery-registration-endpoint-disabled-test(testing "Discovery document omits registration_endpoint when DCR is disabled"(mt/with-temporary-setting-values [site-url "http://localhost:3000"@@ -272,7 +348,7 @@:client_name "Test Auth Client":grant_types ["authorization_code" "refresh_token"]:response_types ["code"]- :scopes ["profile"]+ :scopes ["agent:content:read"]:application_type "web":registration_type "static"}[inserted] (t2/insert-returning-instances! :model/OAuthClient (merge defaults overrides))]@@ -289,38 +365,112 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":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 "profile"))+ (is (str/includes? body "agent:content:read"))(is (str/includes? body client-id))(is (str/includes? body "test-state"))(is (str/includes? body "/oauth/authorize/decision")))))))+(defn- authorize-request!+ "GET /oauth/authorize as crowberto with the query `params` key-value pairs, expecting `expected-status`. Returns the+ full response."+ [expected-status & params]+ (apply mt/user-http-request-full-response :crowberto :get expected-status "oauth/authorize" params))++(def ^:private invalid-request-description "The authorization request is invalid.")++(def ^:private invalid-target-description+ "The resource parameter must be an absolute URI without a fragment.")++(def ^:private invalid-token-request-description "The token request is invalid.")+(deftest authorize-invalid-client-id-test- (testing "GET /oauth/authorize with missing/invalid client_id returns 400"+ (testing "GHY-4542: a missing or unknown client identifier is answered with a 400 in the user's browser, with no+ redirect anywhere, even when the request also carries a second error."(mt/with-temporary-setting-values [site-url "http://localhost:3000"]- (let [response (mt/user-http-request :crowberto :get 400- "oauth/authorize"- :client_id "nonexistent-client"- :redirect_uri "https://example.com/callback"- :response_type "code")]- (is (= "invalid_request" (:error response)))))))+ (doseq [client-params [[:client_id "nonexistent-client"] [:client_id ""] []]]+ (testing (pr-str client-params)+ (let [response (apply authorize-request! 400+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "*"+ :state "test-state"+ client-params)]+ (is (= "invalid_request" (get-in response [:body :error])))+ (is (nil? (get-in response [:headers "Location"])))))))))(deftest authorize-mismatched-redirect-uri-test- (testing "GET /oauth/authorize with mismatched redirect_uri returns 400"+ (testing "GHY-4542: a redirect_uri that is missing, or is not registered for the requesting client (matched+ exactly, so a trailing slash, an added query, or another client's registration all count as+ unregistered), is answered with a 400 in the user's browser and no Location header."(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}]- (let [client (create-test-client!)- client-id (:client_id client)- response (mt/user-http-request :crowberto :get 400- "oauth/authorize"- :client_id client-id- :redirect_uri "https://evil.com/callback"- :response_type "code")]- (is (= "invalid_request" (:error response))))))))+ (let [client-id (:client_id (create-test-client!))]+ (create-test-client! {:redirect_uris ["https://other.example.com/callback"]})+ (doseq [redirect-params [[:redirect_uri "https://evil.com/callback"]+ [:redirect_uri "https://example.com/callback/"]+ [:redirect_uri "https://example.com/callback?next=https://evil.com"]+ ;; registered, but for a different client+ [:redirect_uri "https://other.example.com/callback"]+ [:redirect_uri ""]+ []]]+ (testing (pr-str redirect-params)+ (let [response (apply authorize-request! 400+ :client_id client-id+ :response_type "code"+ :scope "*"+ :state "test-state"+ redirect-params)]+ (is (= "invalid_request" (get-in response [:body :error])))+ (is (nil? (get-in response [:headers "Location"])))))))))))++(deftest authorize-request-errors-name-their-rfc-error-code-test+ (testing "GHY-4542: every authorize error is a 400 JSON body in the user's browser, and each names the RFC 6749+ section 4.1.2.1 (or RFC 8707) code for what was wrong. oidc-provider labels its response_type and scope+ failures only in the data it throws, which is what these codes are derived from."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client-id (:client_id (create-test-client!))+ public-client-id (:client_id (create-test-client! {:client_type "public"}))]+ (doseq [[description error params]+ [["an unsupported response_type"+ "unsupported_response_type" [:client_id client-id :response_type "token"+ :scope "agent:content:read"]]+ ["a missing response_type"+ "invalid_request" [:client_id client-id :scope "agent:content:read"]]+ ["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"]]+ ["code_challenge_method without code_challenge"+ "invalid_request" [:client_id client-id :response_type "code" :scope "agent:content:read"+ :code_challenge_method "S256"]]+ ["an unsupported code_challenge_method"+ "invalid_request" [:client_id client-id :response_type "code" :scope "agent:content:read"+ :code_challenge "abc" :code_challenge_method "plain"]]+ ["a relative resource indicator"+ "invalid_target" [:client_id client-id :response_type "code" :scope "agent:content:read"+ :resource "not-absolute"]]+ ["a resource indicator with a fragment"+ "invalid_target" [:client_id client-id :response_type "code" :scope "agent:content:read"+ :resource "http://localhost:3000/api/mcp#fragment"]]]]+ (testing description+ (let [response (apply authorize-request! 400+ :redirect_uri "https://example.com/callback"+ :state "test-state"+ params)]+ (is (= {:error error+ ;; every `invalid_target`, however the indicator is wrong, says what a valid one looks like+ :error_description (if (= error "invalid_target")+ invalid-target-description+ invalid-request-description)}+ (:body response)))+ (is (nil? (get-in response [:headers "Location"])))))))))))(deftest authorize-unauthenticated-test(testing "GET /oauth/authorize without session redirects to login page"@@ -345,7 +495,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"(mapcat identity extra-params))))@@ -403,7 +553,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -435,7 +585,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -499,7 +649,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -537,7 +687,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}302:csrf-cookie (extract-csrf-cookie consent-resp))))@@ -576,7 +726,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}403)](is (= "csrf_validation_failed" (:error (:body response)))))))))@@ -596,7 +746,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}403:csrf-cookie csrf-cookie)]@@ -621,7 +771,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "tampered-state"} ;; tampered state403:csrf-cookie csrf-cookie)]@@ -645,7 +795,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}403:csrf-cookie csrf-cookie)]@@ -669,7 +819,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}403:csrf-cookie csrf-cookie)]@@ -714,7 +864,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -784,7 +934,7 @@:client_name "Other Client":grant_types ["authorization_code"]:response_types ["code"]- :scopes ["profile"]})+ :scopes ["agent:content:read"]})code (authorize-and-get-code! (:client_id client-a))response (token-request!{:grant_type "authorization_code"@@ -924,7 +1074,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state"}extra-params)302@@ -1010,6 +1160,51 @@{:request-options request-options}params)))+(deftest token-refresh-resource-outside-the-grant-keeps-the-generic-description-test+ (testing "GHY-4542: oidc-provider raises `invalid_target` for a refresh whose `resource` is not in the original+ grant, carrying no description of its own. That is a well-formed absolute URI, so answering it with the+ description for an unparseable one would send the client chasing a syntax problem it does not have: only+ 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!)+ granted-resource (str "http://localhost:3000" (mcp/mcp-canonical-path))+ consent-resp (authorize-request! 200+ :client_id client_id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "agent:content:read"+ :resource granted-resource+ :state "test-state")+ body (:body consent-resp)+ decision (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token (extract-csrf-token-from-consent body)+ :params_sig (extract-params-sig-from-consent body)+ :client_id client_id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ ;; the MCP resource accepts it, so narrowing leaves it as requested+ :scope "agent:content:read"+ :resource granted-resource+ :state "test-state"}+ 302+ :csrf-cookie (extract-csrf-cookie consent-resp))+ tokens (token-request! {:grant_type "authorization_code"+ :code (extract-query-param+ (get-in decision [:headers "Location"]) "code")+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client_id client_secret))]+ (is (some? (:refresh_token tokens)) "the original grant carries the resource it was issued for")+ (is (= {:error "invalid_target"+ :error_description invalid-token-request-description}+ (token-request! {:grant_type "refresh_token"+ :refresh_token (:refresh_token tokens)+ :resource "https://other.example.com/api/mcp"}+ :expected-status 400+ :authorization (basic-auth-header client_id client_secret)))))))))+(deftest token-refresh-revoked-token-test(testing "Refresh token grant with revoked refresh token returns error"(mt/with-temporary-setting-values [site-url "http://localhost:3000"]@@ -1112,7 +1307,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state state)consent-body (:body consent-resp)csrf-token (extract-csrf-token-from-consent consent-body)@@ -1127,7 +1322,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state state}302:csrf-cookie csrf-cookie)@@ -1149,7 +1344,7 @@:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :scope "profile"+ :scope "agent:content:read":state "test-state")body (:body response)](is (not (str/includes? body "<script>alert('xss')</script>"))@@ -1226,10 +1421,10 @@(deftest authorize-legacy-mcp-client-can-request-v2-scopes-test(testing (str "GHY-4343: a client that registered against a shipped v0.60-v0.63 release snapshotted only the ""pre-v2 per-entity agent scopes, and `validate-scope` rejects any requested scope absent from that "- "snapshot. Because `/oauth/authorize` validates before narrowing, a user forced to re-authorize was "- "answered a 400 `invalid_request` JSON body rendered raw in their browser tab - the manual recovery "- "path was broken too. `WidenDynamicOAuthClientScopesForMcpV2` unions the six v2 scopes into every "- "dynamically registered client's snapshot so the request validates and reaches consent.")+ "snapshot, so a user forced to re-authorize is answered with a 400 `invalid_scope` JSON body "+ "rendered raw in their browser tab and has no in-product recovery path. "+ "`WidenDynamicOAuthClientScopesForMcpV2` unions the six v2 scopes into every dynamically registered "+ "client's snapshot so the request validates and reaches consent.");; GHY-4543: reading a dynamic client now adds the six v2 scopes whatever the registration setting says, so the;; request reaches consent with or without the migration applied. Registration is disabled so only that MCP part;; of the ceiling applies. A static client carrying the same legacy snapshot is the control: it is never widened,@@ -1257,7 +1452,9 @@dynamic-id (:client_id (create-test-client! {:scopes legacy-scopes:registration_type "dynamic"}))](testing "control: the six v2 scopes are refused against the legacy snapshot alone"- (is (= "invalid_request" (:error (:body (authorize! static-id 400))))))+ (is (= {:error "invalid_scope"+ :error_description invalid-request-description}+ (:body (authorize! static-id 400)))))(testing "before the migration, the dynamic client reaches consent because reading it widens it"(consent! (authorize! dynamic-id 200)));; Apply what the migration applies. The change class itself is exercised against the changelog in@@ -1297,7 +1494,7 @@consent? (fn [response] (is (= 200 (:status response)) (pr-str (:body response))))refused? (fn [response](is (= 400 (:status response)))- (is (= "invalid_request" (get-in response [:body :error]))))]+ (is (= "invalid_scope" (get-in response [:body :error]))))](is (some? not-mcp) "the default ceiling holds a scope the MCP surface does not accept")(testing "control: a static client reaches consent for the scope it registered for"(consent? (authorize "static" true "agent:content:read")))@@ -1341,7 +1538,35 @@(testing "with MCP disabled it is not widened, so the scope is refused"(let [response (authorize false)](is (= 400 (:status response)))- (is (= "invalid_request" (get-in response [:body :error]))))))))+ (is (= "invalid_scope" (get-in response [:body :error]))))))))++(deftest authorize-error-never-redirects-to-a-client-registered-uri-test+ (testing "GHY-4542: dynamic client registration is unauthenticated, so anyone can register a client whose+ redirect_uri points at their own site. If /oauth/authorize delivered its errors by redirecting there,+ a single link on the trusted Metabase host would send any logged-in user straight off-site with no+ consent step: a zero-click open redirector. RFC 9700 section 4.11 says to answer with an error rather+ than redirect when the redirect URI is not trusted, so every authorize error is a 400 rendered in the+ user's own browser and never carries a Location header."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [off-site "https://evil.example/callback"+ client-id (:client_id (create-test-client! {:redirect_uris [off-site]}))]+ (doseq [[label params]+ [["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"+ :resource "http://bad uri"]]]]+ (testing label+ (let [response (apply authorize-request! 400+ :client_id client-id+ :redirect_uri off-site+ :state "test-state"+ params)]+ (is (nil? (get-in response [:headers "Location"])))+ (is (not (str/includes? (pr-str (:headers response)) off-site))+ "no response header names the client's off-site redirect URI")))))))))(deftest authorize-rejects-fully-narrowed-scope-test(testing "when every requested scope is one the named resource does not accept, answer RFC 6749@@ -1352,30 +1577,215 @@(t2/with-transaction [_conn nil {:rollback-only true}](let [client-id (:client_id (create-test-client!{:scopes ["agent:question:create" "agent:sql:execute"]}))- response (mt/user-http-request-full-response- :crowberto :get 400 "oauth/authorize"- :client_id client-id- ;; both are v1-only: the v2 resource accepts neither- :scope "agent:question:create agent:sql:execute"- :redirect_uri "https://example.com/callback"- :response_type "code"- :resource (str "http://localhost:3000" (mcp/mcp-canonical-path))- :state "test-state")]- (is (= "invalid_scope" (get-in response [:body :error]))))))))--(deftest authorize-without-scope-still-renders-consent-test- (testing "a client that sends no `scope` at all is not the same case as one whose scopes were all- narrowed away -- narrowing answers nil for both, and only the first may drop the parameter.- This pins that the `invalid_scope` branch above did not swallow the no-scope request."+ response (authorize-request! 400+ :client_id client-id+ ;; both are v1-only: the v2 resource accepts neither+ :scope "agent:question:create agent:sql:execute"+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :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))))))))++(deftest authorize-drops-unregistered-scopes-test+ (testing "GHY-4542: a scope that is not registered via `defscope` is dropped from the request rather than+ refusing it. A client that registered a wildcard such as `*` before registration validated scopes can+ still request it, and `scope-matches?` would honor it as a wildcard grant, so it must not survive; but+ refusing outright strands the user on a JSON error in a browser tab while the client waits, and breaks+ step-up for a client legitimately holding a scope we have since deprecated (`agent:table:read` and+ friends shipped in v0.60-v0.61). RFC 6749 section 3.3 allows issuing a narrower scope than was asked+ for. Filtering happens before resource narrowing, so the two compose."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (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" []]+ ["a hierarchical wildcard alongside a registered scope"+ ["agent:content:read" "agent:*"] "agent:* agent:content:read" nil "agent:content:read" []]+ ["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"]]+ ["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"]]+ ["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"+ (str "http://localhost:3000" (mcp/mcp-canonical-path))+ "agent:content:read" ["agent:table:read" "agent:question:create"]]]]+ (testing label+ (let [client-id (:client_id (create-test-client! {:scopes registered}))+ response (apply authorize-request! 200+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope requested+ :state "test-state"+ (when resource [:resource resource]))+ body (:body response)]+ (is (= expected (extract-hidden-field "scope" body))+ "the signed scope carries exactly the surviving scopes")+ (doseq [scope absent]+ (is (not (str/includes? body scope))+ "a dropped scope is nowhere on the consent page")))))))))++(deftest authorize-dropping-unregistered-scopes-never-widens-test+ (testing "GHY-4542: dropping an unregistered scope must narrow the grant, never widen it. `*` is honored as a+ wildcard on the granted side by `scope-matches?`, so a token that still carried it would pass every+ 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"]})+ consent-resp (authorize-request! 200+ :client_id client_id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "* agent:content:read"+ :state "test-state")+ body (:body consent-resp)+ granted (extract-hidden-field "scope" body)]+ (is (= "agent:content:read" granted))+ (let [decision (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token (extract-csrf-token-from-consent body)+ :params_sig (extract-params-sig-from-consent body)+ :client_id client_id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope granted+ :state "test-state"}+ 302+ :csrf-cookie (extract-csrf-cookie consent-resp))+ code (extract-query-param (get-in decision [: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))+ "the minted token carries only the registered scope")))))))++(defn- sign-decision-params+ "Sign `oauth-params` with `csrf-token` exactly as the consent page does, so a hand-built form carries a signature+ the decision endpoint accepts."+ [csrf-token oauth-params]+ (#'api.oauth/sign-oauth-params csrf-token oauth-params))++(deftest authorize-decision-enforces-scope-rules-test+ (testing "GHY-4542: the HMAC over the consent form is keyed by the CSRF token, which is printed on the page the+ user is looking at, so the user can recompute it over whatever scope they like. The signature proves no+ third party tampered with the form; it does not prove the scope was ever validated. /authorize/decision+ is the endpoint that issues the code, so it applies the scope rules itself: drop unregistered scopes,+ refuse when none survive, and grant exactly what is left."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ ;; 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"]})+ 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]+ (let [params (cond-> {:client_id client_id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :state "test-state"}+ scope (assoc :scope scope))]+ (form-post-decision!+ :rasta+ (assoc params+ :approved "true"+ :csrf_token csrf-token+ :params_sig (sign-decision-params csrf-token params))+ 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)]+ (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)+ 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)))))+ (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)))))+ (testing "a re-signed request with no usable scope at all is refused"+ (doseq [scope [nil "" " "]]+ (testing (pr-str scope)+ (let [response (approve! scope 400)]+ (is (= refused (:body response)))+ (is (nil? (get-in response [:headers "Location"]))))))))))))++(deftest authorize-rejects-a-request-whose-scopes-are-all-unregistered-test+ (testing "GHY-4542: dropping unregistered scopes cannot leave a request with none, because a scope-less token is+ indistinguishable downstream from scope-unaware auth. When nothing survives the filter the request is+ refused with `invalid_scope` and a description distinct from the resource-narrowing one, so the two are+ diagnosable, pointing at the metadata document without echoing what the client sent."+ (doseq [site-url ["http://localhost:3000" "http://localhost:3000/metabase"]]+ (testing (str "site-url " site-url)+ (mt/with-temporary-setting-values [site-url site-url]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (doseq [[registered requested] [[["*"] "*"]+ [["agent:*"] "agent:*"]+ ;; shipped in v0.60-v0.61 and since removed, so older DCR clients hold it+ [["agent:table:read"] "agent:table:read"]]+ resource [nil (str site-url (mcp/mcp-canonical-path))]]+ (testing (pr-str {:requested requested :resource resource})+ (let [client-id (:client_id (create-test-client! {:scopes registered}))+ response (apply authorize-request! 400+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope requested+ :state "test-state"+ (when resource [:resource resource]))+ description (str (get-in response [:body :error_description]))]+ (is (= {:error "invalid_scope"+ :error_description (str "None of the requested scopes are supported. Request only scopes "+ "listed in scopes_supported at " site-url+ "/.well-known/oauth-authorization-server")}+ (:body response))+ "the description points at the metadata document, including the site-url subpath")+ (is (not (str/includes? description requested))+ "the description does not echo the rejected scopes")+ (is (re-matches #"[\x20-\x21\x23-\x5B\x5D-\x7E]*" description)+ "the description stays within the RFC 6749 section 5.2 error_description character set")+ (is (nil? (get-in response [:headers "Location"]))))))))))))++(deftest authorize-rejects-missing-scope-test+ (testing "GHY-4542: a request with no scope used to render a consent screen listing no permissions and+ mint a token with no scopes. Nothing downstream should have to tell a scope-less OAuth token+ apart from scope-unaware auth, so /authorize answers `invalid_scope` instead, whether `scope`+ is absent, empty, or whitespace, and with or without a `resource` indicator."(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}](let [client-id (:client_id (create-test-client! {:scopes ["agent:content:read"]}))]- (is (mt/user-http-request :crowberto :get 200 "oauth/authorize"+ (doseq [scope-params [[] [:scope ""] [:scope " "]]+ resource [nil (str "http://localhost:3000" (mcp/mcp-canonical-path))]]+ (testing (pr-str {:scope-params scope-params :resource resource})+ (let [response (apply authorize-request! 400:client_id client-id:redirect_uri "https://example.com/callback":response_type "code"- :resource (str "http://localhost:3000" (mcp/mcp-canonical-path))- :state "test-state")))))))+ :state "test-state"+ (concat scope-params+ (when resource [:resource resource])))]+ (is (= {:error "invalid_scope"+ :error_description (str "The request must include a scope. Request only scopes listed in "+ "scopes_supported at "+ "http://localhost:3000/.well-known/oauth-authorization-server")}+ (:body response)))))))))))(deftest mb-full-client-can-still-authorize-test(testing "removing `mb:full` from the advertised sets must not break a first-party client that@@ -1398,6 +1808,79 @@:scope oauth-server/full-access-scope:state "test-state"))))))))+;;; ------------------------------------- Malformed resource indicators -------------------------------------++(def ^:private malformed-resources+ "`resource` values containing an entry that is not a parseable URI at all, as opposed to one that parses but is+ relative or has a fragment."+ ["http://bad uri"+ ["http://localhost:3000/api/mcp" "http://bad uri"]])++(deftest authorize-malformed-resource-is-invalid-target-test+ (testing "GHY-4542: an unparseable `resource` indicator made oidc-provider throw a URISyntaxException that nothing+ caught, answering a client input error with a 500. It is now a 400 naming the RFC 8707 section 2+ `invalid_target` code, like any other invalid resource indicator."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client-id (:client_id (create-test-client!))]+ (doseq [resource malformed-resources]+ (testing (pr-str resource)+ (let [response (authorize-request! 400+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "agent:content:read"+ :state "test-state"+ :resource resource)]+ (is (= {:error "invalid_target"+ :error_description invalid-target-description}+ (:body response)))+ (is (nil? (get-in response [:headers "Location"])))))))))))++(deftest authorize-decision-malformed-resource-is-invalid-request-test+ (testing "GHY-4542: the decision endpoint's parameters are untrusted until their signature verifies, so an+ unparseable `resource` there is a 400 `invalid_request` rather than a 500, and never a redirect"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client-id (:client_id (create-test-client!))+ consent-resp (get-consent-page! :crowberto client-id)+ consent-body (:body consent-resp)]+ (doseq [resource malformed-resources]+ (testing (pr-str resource)+ (let [response (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token (extract-csrf-token-from-consent consent-body)+ :params_sig (extract-params-sig-from-consent consent-body)+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "agent:content:read"+ :state "test-state"+ :resource resource}+ 400+ :csrf-cookie (extract-csrf-cookie consent-resp))]+ (is (= {:error "invalid_request"+ :error_description "The authorization request is invalid."}+ (:body response)))+ (is (nil? (get-in response [:headers "Location"])))))))))))++(deftest token-malformed-resource-is-invalid-target-test+ (testing "GHY-4542: an unparseable `resource` indicator at the token endpoint is an RFC 8707 `invalid_target` 400+ in the RFC 6749 section 5.2 error shape, not a 500"+ (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!)]+ (doseq [resource malformed-resources]+ (testing (pr-str resource)+ (is (= {:error "invalid_target"+ :error_description invalid-target-description}+ (token-request! {:grant_type "authorization_code"+ :code "some-code"+ :redirect_uri "https://example.com/callback"+ :resource resource}+ :expected-status 400+ :authorization (basic-auth-header client_id client_secret)))))))))));;; ------------------------------- Registration scope vs. the authorization ceiling -------------------------------(def ^:private v2-scope-set@@ -1537,7 +2020,7 @@{:scope "agent:content:read agent:query:run agent:resource:read"}scope)](is (= 400 (:status response)))- (is (= "invalid_request" (get-in response [:body :error]))))))))))+ (is (= "invalid_scope" (get-in response [:body :error]))))))))))(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 "@@ -1582,4 +2065,4 @@(testing "the client cannot request an agent-API scope outside its registration"(let [response (authorize not-mcp)](is (= 400 (:status response)))- (is (= "invalid_request" (get-in response [:body :error]))))))))))+ (is (= "invalid_scope" (get-in response [:body :error]))))))))))diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.cljindex c7f2f2eb080..300a2f1cde6 100644--- a/test/metabase/server/middleware/session_oauth_test.clj+++ b/test/metabase/server/middleware/session_oauth_test.clj@@ -16,6 +16,7 @@[metabase.oauth-server.test-util :as oauth-server.tu][metabase.server.middleware.session :as mw.session][metabase.test :as mt]+ [metabase.test.http-client :as client][oidc-provider.store :as oidc.store][toucan2.core :as t2]))@@ -109,6 +110,111 @@(is (= user-id (:metabase-user-id req)))(is (= #{"agent:query:execute"} (:token-scopes req))))))))))+(deftest bearer-bridge-marks-oauth-authentication-test+ (testing "GHY-4542: a request the bearer bridge authenticated is marked as OAuth-authenticated, which is what the+ scope middleware and the MCP transport key their fail-closed checks on"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (oauth-server.tu/with-oauth-client [client-id]+ (let [token (str (random-uuid))]+ (save-access-token! token (mt/user->id :rasta) client-id ["agent:query:execute"] (in-one-hour))+ (is (true? (:authenticated-via-oauth? (merge-current-user-info (bearer-request token)))))))))))++(defn- passes-scope-middleware?+ "Whether `request` gets through both [[scope/enforce-scope]] and [[scope/ensure-scopes-checked]]."+ [request]+ (let [status (fn [wrapped]+ (let [p (promise)]+ (wrapped request #(deliver p (:status %)) #(deliver p %))+ (deref p 10000 ::timeout)))+ ok (fn [_ respond _] (respond {:status 200}))]+ (= [200 200] [(status ((scope/enforce-scope "agent:query:execute") ok))+ (status (scope/ensure-scopes-checked ok))])))++(deftest bearer-bridge-refuses-token-without-scopes-test+ (testing "GHY-4542: an access token with no scopes must not authenticate. Downstream, nil `:token-scopes` means+ scope-unaware auth and passes as unrestricted, so the only thing keeping such a token from becoming+ unrestricted would otherwise be an empty set surviving every hop. /oauth/authorize no longer issues+ one, so these are minted straight into the store."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ ;; Commit the client row instead of holding `with-temp`'s rollback-only transaction open across the four HTTP+ ;; round-trips below. The request runs on a conveyed connectable, so anything in its path that commits+ ;; implicitly -- the app DB creates its search index tables lazily, and DDL commits implicitly on H2 and MySQL+ ;; -- invalidates the savepoint and the scope exit throws instead of rolling back.+ (mt/test-helpers-set-global-values!+ (oauth-server.tu/with-oauth-client [client-id]+ (mt/with-model-cleanup [:model/OAuthAccessToken]+ (doseq [scopes [nil []]]+ (testing (str "scopes " (pr-str scopes))+ (let [token (str (random-uuid))]+ (oidc.store/save-access-token (:token-store (oauth-server/get-provider))+ token (str (mt/user->id :rasta)) client-id scopes (in-one-hour) nil)+ (testing "the bearer bridge does not authenticate the request"+ (let [req (merge-current-user-info (bearer-request token))]+ (is (nil? (:metabase-user-id req)))+ (is (nil? (:token-scopes req)))+ (is (nil? (:authenticated-via-oauth? req)))))+ (testing "a general API endpoint answers 401"+ (client/client :get 401 "user/current"+ {:request-options {:headers {"authorization" (str "Bearer " token)}}}))+ (testing "an agent API endpoint that declares a scope does not serve it"+ (client/client :post 401 "agent/v1/search"+ {:request-options {:headers {"authorization" (str "Bearer " token)}}}+ {:term_queries ["orders"]})))))))))))++(deftest non-oauth-auth-is-unaffected-by-oauth-fail-closed-test+ (testing "GHY-4542: session and API-key requests carry nil `:token-scopes` and must keep passing the scope+ middleware. A stray bearer header does not make a session request OAuth-authenticated: the session+ takes precedence and the bearer is never resolved."+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [user-info {:metabase-user-id (mt/user->id :rasta) :is-superuser? false}]+ (testing "a session request"+ (mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-session (fn [_ _] user-info)]+ (let [req (merge-current-user-info {:metabase-session-key "session-key"})]+ (is (= "session" (:embedding/auth-method req)))+ (is (nil? (:authenticated-via-oauth? req)))+ (is (passes-scope-middleware? req)))))+ (testing "an API-key request"+ (mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-api-key (fn [_] user-info)]+ (let [req (merge-current-user-info {:headers {"x-api-key" "mb_whatever"}})]+ (is (= "api-key" (:embedding/auth-method req)))+ (is (nil? (:authenticated-via-oauth? req)))+ (is (passes-scope-middleware? req)))))+ (testing "a session request carrying a stray bearer header"+ (oauth-server.tu/with-oauth-client [client-id]+ (mt/with-model-cleanup [:model/OAuthAccessToken]+ (let [token (str (random-uuid))]+ (save-access-token! token (mt/user->id :rasta) client-id [] (in-one-hour))+ (mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-session (fn [_ _] user-info)]+ (let [req (merge-current-user-info (assoc (bearer-request token) :metabase-session-key "session-key"))]+ (is (= (mt/user->id :rasta) (:metabase-user-id req)))+ (is (= "session" (:embedding/auth-method req)))+ (is (nil? (:authenticated-via-oauth? req)))+ (is (passes-scope-middleware? req))))+ (testing "and over HTTP"+ (let [options {:request-options {:headers {"authorization" (str "Bearer " token)}}}]+ (is (= (mt/user->id :rasta)+ (:id (mt/user-http-request :rasta :get 200 "user/current" options))))))))))))))++(deftest narrow-oauth-token-gets-insufficient-scope-challenge-test+ (testing "GHY-4542: a narrow OAuth token reaching an agent API endpoint that declares a scope it does not hold gets+ a 403 carrying the RFC 6750 section 3 `insufficient_scope` challenge, naming the scope that endpoint+ requires, so the client knows to re-authorize for it"+ (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 [token (str (random-uuid))+ _ (save-access-token! token (mt/user->id :rasta) client-id+ ["agent:query:execute"] (in-one-hour))+ response (client/client-full-response+ :post 403 "agent/v1/search"+ {:request-options {:headers {"authorization" (str "Bearer " token)}}}+ {:term_queries ["orders"]})]+ (is (= (str "Bearer error=\"insufficient_scope\", scope=\"agent:search\", "+ "error_description=\"Insufficient scope for this operation.\"")+ (get-in response [:headers "WWW-Authenticate"])))+ (is (= "unsupported_scope" (get-in response [:body :error])))))))))+(deftest bearer-bridge-expired-token-test(mt/with-temporary-setting-values [site-url "http://localhost:3000"](t2/with-transaction [_conn nil {:rollback-only true}]