Skip to content

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

Narrow OAuth refresh scope like authorize; answer invalid_scope on rejection (#84704)

Oreon Lothamera8789461a1c5
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index ff1e0d4f983..b663c179e4a 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -24,13 +24,15 @@
[oidc-provider.core :as oidc]
[oidc-provider.protocol :as proto]
[oidc-provider.registration :as reg]
+ [oidc-provider.store :as oidc.store]
[oidc-provider.token-endpoint :as oidc.token-endpoint]
[oidc-provider.util :as oidc-util]
[ring.util.response :as response]
[throttle.core :as throttle])
(:import
(clojure.lang ExceptionInfo)
- (java.net URI URISyntaxException URLEncoder)))
+ (java.net URI URISyntaxException URLEncoder)
+ (java.time Clock)))
(set! *warn-on-reflection* true)
@@ -159,6 +161,9 @@
(def ^:private invalid-target-description
"The resource parameter must be an absolute URI without a fragment.")
+(def ^:private not-held-scope-description
+ "None of the requested scopes were granted to this refresh token. Omit scope to refresh with the original grant.")
+
(defn- narrowed-away-scope-description
"The `error_description` for an authorization request in which no requested scope is accepted by `resources`."
[resources]
@@ -452,16 +457,24 @@
(defn- token-error-code
"The RFC 6749 section 5.2 `error` code for the ex-data of an exception thrown while handling a token request."
- [{:keys [error] :as data}]
- (or error
+ [{:keys [oauth-error error] :as data}]
+ (or oauth-error
+ error
;; oidc-provider names a code only for its PKCE, expired refresh token, and resource-indicator errors. Its other
;; grant failures carry the code or refresh token that failed, or the client or redirect URI the grant is bound
;; to as `:expected`/`:actual`. Malformed requests carry none of these. A missing `redirect_uri` also carries
;; `:code`, and `invalid_grant` is right for it too: the code is consumed by then, so a retry cannot succeed.
- (if (or (contains? data :code)
- (contains? data :refresh-token)
- (and (contains? data :expected) (contains? data :actual)))
+ ;; Its scope rejections carry `:requested`, and `invalid_scope` tells the client the scope is at fault.
+ (cond
+ (or (contains? data :code)
+ (contains? data :refresh-token)
+ (and (contains? data :expected) (contains? data :actual)))
"invalid_grant"
+
+ (contains? data :requested)
+ "invalid_scope"
+
+ :else
"invalid_request")))
(defn- error-description
@@ -557,9 +570,10 @@
`:error-description` when the request names no scope, when none of its scopes are registered, when none of them
survive narrowing, or when incompatible resources are requested.
- Applied by both the consent page and the decision endpoint. The consent form's signature proves only that the form
- was not tampered with by a third party: it is keyed by the CSRF token the page shows the user, so the user can
- re-sign anything. The endpoint that issues the code has to apply these rules itself.
+ Applied by the consent page, the decision endpoint, and a refresh that names a `scope`. The consent form's
+ signature proves only that the form was not tampered with by a third party: it is keyed by the CSRF token the
+ page shows the user, so the user can re-sign anything. The endpoint that issues the code has to apply these
+ rules itself.
Never returns a blank scope. The decision endpoint leans on that: it answers a nil grant with 403 `params_tampered`,
which is only the right status while the sole way to reach it is a choice naming an unoffered scope. A blank offer
@@ -586,6 +600,57 @@
:error-description (narrowed-away-scope-description (:resource parsed))
:resource (:resource parsed)})))))
+(defn- refreshable-token
+ "The stored refresh token a refresh `body` names, when oidc-provider would get as far as checking its scope: the
+ client authenticates, may use the refresh grant, and owns the token, and the token is unexpired. Otherwise nil.
+
+ Authenticates with oidc-provider's own `authenticate-client`, so a client that fails it gets exactly the error the
+ library would give. Skipped when the token does not resolve, which the library rejects without needing this."
+ [provider authorization-header {:keys [refresh_token] :as body}]
+ (when-let [token-data (some->> (not-empty refresh_token)
+ (oidc.store/get-refresh-token (:token-store provider)))]
+ (let [client (oidc.token-endpoint/authenticate-client body authorization-header (:client-store provider))
+ now (.millis ^Clock (:clock (:provider-config provider)))]
+ (when (and (some #{"refresh_token"} (:grant-types client))
+ (= (:client-id token-data) (:client-id client))
+ ;; the token store filters out revoked tokens, not expired ones
+ (let [expiry (:expiry token-data)]
+ (or (nil? expiry) (<= now expiry))))
+ token-data))))
+
+(defn- with-refresh-scope-to-grant
+ "The token request `body` with the `scope` of a refresh trimmed the same way authorization trims one: unregistered
+ scopes are dropped and the rest narrowed by [[scope-to-grant]] to the request's `resource`, else the one the refresh
+ token was issued for, which is the resource oidc-provider issues the new token for. Scopes the refresh token does not
+ hold are then dropped too, as RFC 6749 section 3.3 allows, so a client that always refreshes with the same `scope`
+ keeps working after the user declines part of it at consent; the response's `scope` says what was granted. Throws
+ `ex-info` carrying `:oauth-error` `invalid_scope` when no requested scope survives.
+
+ Trimmed only once [[refreshable-token]] finds the request would reach oidc-provider's scope check, so a dead token,
+ another client's token, or bad client credentials still get the library's own answer. A blank `scope` is dropped,
+ which RFC 6749 section 6 treats as the original grant; oidc-provider would read it as asking for no scopes and mint
+ a token with none. Any other `body` is returned unchanged."
+ [provider authorization-header {:keys [grant_type scope resource] :as body}]
+ (cond
+ (not= grant_type "refresh_token")
+ body
+
+ (str/blank? scope)
+ (dissoc body :scope)
+
+ :else
+ (if-let [token-data (refreshable-token provider authorization-header body)]
+ (let [requested (scope-tokens (scope-to-grant {:scope scope
+ :resource (or resource (:resource token-data))}))
+ held (into #{} (:scope token-data))]
+ ;; oidc-provider splits `scope` on single spaces and stores what it gets, so pass it deduplicated and
+ ;; single-spaced.
+ (assoc body :scope (or (not-empty (str/join " " (filter held requested)))
+ (throw (ex-info "no requested scope is held by the refresh token"
+ {:oauth-error "invalid_scope"
+ :error-description not-held-scope-description})))))
+ body)))
+
(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`."
@@ -775,7 +840,9 @@
:scopes (when (some? (:scope body))
(or (scope-tokens (:scope body)) []))
:resource (:resource body)})
- (oidc/token-request provider body authorization-header))]
+ (oidc/token-request provider
+ (with-refresh-scope-to-grant provider authorization-header body)
+ authorization-header))]
{:status 200
:headers {"Content-Type" "application/json"
"Cache-Control" "no-store"
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index 2485e0f8fca..dc1f156d507 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -2964,3 +2964,163 @@
(testing "the session really authenticates, so the refusal is about who, not whether"
(client/client session-key :get 200 "api/user/current"))
(refused-like-anonymous! {"x-metabase-session" session-key} (:client_id (create-test-client!))))))))
+
+;;; ------------------------------------------ Refresh scope vs. the grant -------------------------------------------
+
+(defn- refresh-with-scope!
+ "Refresh `token-response` as `client`, sending `scope` and, when given, `resource`. Returns the response body."
+ [client token-response scope & {:keys [resource expected-status] :or {expected-status 200}}]
+ (token-request! (cond-> {:grant_type "refresh_token"
+ :refresh_token (:refresh_token token-response)
+ :scope scope}
+ resource (assoc :resource resource))
+ :expected-status expected-status
+ :authorization (basic-auth-header (:client_id client) (:client_secret client))))
+
+(deftest refresh-drops-unregistered-scopes-and-narrows-to-resource-test
+ (testing (str "A refresh that names a `scope` gets the same treatment as an authorization request: unregistered "
+ "scopes are dropped and the rest narrowed to the resource. A client may refresh with the `scope` it "
+ "registered with, which can be every supported scope, so a refresh that only checked the request "
+ "against the grant would refuse every scope the authorization request had narrowed away.")
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"
+ oauth-server-dynamic-registration-enabled true]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [redirect "https://example.com/callback"
+ client (register-app-client! "MCP Client" redirect)
+ tokens (atom (authorize-at! client redirect all-v2-scopes (vec v2-scope-set)))
+ wide (str/join " " (conj (oauth-server/supported-scopes) "mb:full"))]
+ (is (= v2-scope-set (token-scope-set @tokens)))
+ (doseq [[label scope resource]
+ [["unregistered scopes alongside the grant"
+ (str "offline_access " all-v2-scopes " *")
+ nil]
+ ["scopes the MCP resource does not accept, narrowed to the resource the refresh token was issued for"
+ wide
+ nil]
+ ["scopes the MCP resource does not accept, narrowed to the resource the request names"
+ wide
+ (mcp-resource-uri)]
+ ["a repeated scope"
+ (str all-v2-scopes " " all-v2-scopes)
+ nil]]]
+ (testing label
+ (let [response (refresh-with-scope! client @tokens scope :resource resource)]
+ (reset! tokens response)
+ (is (= (str/split all-v2-scopes #" ") (str/split (:scope response) #" "))
+ "the token carries each surviving scope once, in the requested order")
+ (is (= v2-scope-set (access-token-scopes response)))
+ (is (= #{v2-scope-set} (live-refresh-scopes client))
+ "the rotated refresh token holds no dropped scope")))))))))
+
+(deftest refresh-grants-the-held-part-of-the-requested-scope-test
+ (testing (str "RFC 6749 section 3.3: a refresh asking for scopes the refresh token does not hold is granted the ones "
+ "it does hold, and the response's `scope` says which. A client that always refreshes with the same "
+ "`scope` would otherwise stop working once the user declined part of it at consent.")
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"
+ oauth-server-dynamic-registration-enabled true]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [redirect "https://example.com/callback"
+ client (register-app-client! "MCP Client" redirect)
+ held (conj v2-baseline-scope-set "agent:content:write")
+ tokens (authorize-at! client redirect all-v2-scopes ["agent:content:write"])
+ response (refresh-with-scope! client tokens all-v2-scopes)]
+ (is (= held (token-scope-set tokens)))
+ (is (= (filter held (str/split all-v2-scopes #" ")) (str/split (:scope response) #" ")))
+ (is (= held (access-token-scopes response)))
+ (is (= #{held} (live-refresh-scopes client))))))))
+
+(deftest refresh-scope-rejection-is-invalid-scope-test
+ (testing (str "RFC 6749 section 5.2: a refresh whose `scope` cannot be granted at all is `invalid_scope`, not "
+ "`invalid_request`. That tells the client the scope is at fault, so it can retry without `scope`, "
+ "which RFC 6749 section 6 treats as the original grant, rather than discarding a refresh token that "
+ "still works.")
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"
+ oauth-server-dynamic-registration-enabled true]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [redirect "https://example.com/callback"
+ client (register-app-client! "MCP Client" redirect)
+ held (conj v2-baseline-scope-set "agent:content:write")
+ tokens (authorize-at! client redirect all-v2-scopes ["agent:content:write"])
+ not-mcp (first-non-mcp-default-scope)]
+ (is (some? not-mcp) "a supported scope the MCP surface does not accept")
+ (doseq [[label scope description]
+ [["only unregistered scopes"
+ "offline_access *"
+ (str "None of the requested scopes are supported. Request only scopes listed in "
+ "scopes_supported at http://localhost:3000/.well-known/oauth-authorization-server")]
+ ["only scopes the resource the refresh token was issued for does not accept"
+ (str not-mcp " mb:full")
+ (str "The requested scopes are not accepted by the requested resource. "
+ "The MCP server's resource URL is http://localhost:3000" (mcp/mcp-canonical-path) ".")]
+ ["only scopes the refresh token does not hold"
+ "agent:sql:run agent:delivery:write"
+ (str "None of the requested scopes were granted to this refresh token. "
+ "Omit scope to refresh with the original grant.")]]]
+ (testing label
+ (is (= {:error "invalid_scope"
+ :error_description description}
+ (refresh-with-scope! client tokens scope :expected-status 400)))))
+ (testing "a rejected refresh leaves the refresh token live, so retrying without `scope` gets the original grant"
+ (is (= held (token-scope-set (refresh! client tokens))))))))))
+
+(deftest refresh-blank-scope-keeps-the-original-grant-test
+ (testing (str "RFC 6749 section 6: a refresh with a blank `scope` gets the original grant. oidc-provider reads a "
+ "whitespace-only `scope` as asking for no scopes, and rotation revokes the old refresh token, so it "
+ "would mint a token that can do nothing and leave the user to sign in again.")
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"
+ oauth-server-dynamic-registration-enabled true]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [redirect "https://example.com/callback"
+ client (register-app-client! "MCP Client" redirect)
+ tokens (atom (authorize-at! client redirect all-v2-scopes (vec v2-scope-set)))]
+ (doseq [scope ["" " "]]
+ (testing (pr-str scope)
+ (let [response (refresh-with-scope! client @tokens scope)]
+ (reset! tokens response)
+ (is (= v2-scope-set (token-scope-set response)))
+ (is (= v2-scope-set (access-token-scopes response)))))))))))
+
+(deftest refresh-scope-keeps-the-answer-for-a-refresh-that-fails-anyway-test
+ (testing (str "A refresh that oidc-provider refuses before it looks at the scope gets the same answer whatever "
+ "`scope` it sends: a dead or misused refresh token is `invalid_grant`, which tells the client the user "
+ "must sign in again, and bad client credentials never get as far as a scope check against a live "
+ "token. Sent with a `scope` no refresh could be granted, so trimming it first would answer "
+ "`invalid_scope`.")
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"
+ oauth-server-dynamic-registration-enabled true]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [redirect "https://example.com/callback"
+ issue! (fn []
+ (let [client (register-app-client! "MCP Client" redirect)]
+ [client (authorize-at! client redirect all-v2-scopes (vec v2-scope-set))]))
+ refresh (fn [client tokens scope]
+ (token-request! (cond-> {:grant_type "refresh_token"
+ :refresh_token (:refresh_token tokens)}
+ scope (assoc :scope scope))
+ :expected-status 400
+ :authorization (basic-auth-header (:client_id client) (:client_secret client))))]
+ (doseq [[label error setup]
+ [["an unknown refresh token"
+ "invalid_grant"
+ (fn [] (let [[client] (issue!)] [client {:refresh_token "not-a-refresh-token"}]))]
+ ["an expired refresh token still stored"
+ "invalid_grant"
+ (fn [] (let [[client tokens] (issue!)]
+ (t2/update! :model/OAuthRefreshToken {:client_id (:client_id client) :revoked_at nil}
+ {:expiry 1})
+ [client tokens]))]
+ ["another client's refresh token"
+ "invalid_grant"
+ (fn [] (let [[_ tokens] (issue!)
+ [other] (issue!)]
+ [other tokens]))]
+ ["a wrong client secret"
+ "invalid_request"
+ (fn [] (let [[client tokens] (issue!)]
+ [(assoc client :client_secret "wrong-secret") tokens]))]]]
+ (testing label
+ (let [[client tokens] (setup)
+ response (refresh client tokens "offline_access *")]
+ (is (= error (:error response)))
+ (is (= (refresh client tokens nil) response)
+ "the same answer as the refresh without `scope`")))))))))