Skip to content

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

Count refused OAuth token requests toward throttling (#84920)

Andrei Simionescu32ede3056a17
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj
index 0d174f0e130..a26eed39a00 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj
@@ -1,4 +1,4 @@
-(ns metabase-enterprise.sso.integrations.jwt-bearer-grant-test
+(ns ^:synchronized metabase-enterprise.sso.integrations.jwt-bearer-grant-test
(:require
[buddy.sign.jwt :as jwt]
[buddy.sign.util :as buddy-util]
@@ -6,9 +6,12 @@
[clojure.test :refer :all]
[metabase-enterprise.mcp.test-util :as mcp.tu]
[metabase-enterprise.sso.test-setup :as sso.test-setup]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.config.core :as config]
[metabase.mcp.core :as mcp]
[metabase.mcp.v2.test-util]
+ [metabase.oauth-server.api.oauth :as api.oauth]
+ [metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.system.core :as system]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -18,6 +21,13 @@
(use-fixtures :once (fixtures/initialize :test-users))
+(use-fixtures :each (fn [thunk]
+ (oauth-server.tu/reset-token-throttlers!)
+ (try
+ (thunk)
+ (finally
+ (oauth-server.tu/reset-token-throttlers!)))))
+
(defmacro ^:private with-jwt-bearer-setup!
"Run `body` with JWT authentication set up, deleting the tokens and audit rows it creates."
[& body]
@@ -289,6 +299,59 @@
:groups ["agents"]})}))]
(is (some? (mcp-session access_token)))))))))))
+(deftest exchange-refusal-throttling-test
+ (testing "a verified JWT's refusals don't count toward the token limits, unlike an unverified JWT's"
+ (with-jwt-bearer-setup!
+ (mcp.tu/with-group-level-mode
+ (let [verified [["unsupported_grant_type" #(assertion {:email "[email protected]"})]
+ ["invalid_grant" #(assertion {:first_name "Jay"})]]
+ unverified [["invalid_grant" #(jwt/sign {:email "[email protected]"} "not-the-secret")]
+ ["invalid_grant" #(assertion {:email "[email protected]"
+ :exp (- (buddy-util/now) 60)})]]]
+ (doseq [[client-id limit] [[nil 50] ["jwt-bearer-backend" 10]]]
+ (testing (if client-id "with a client ID" "without a client ID")
+ (oauth-server.tu/reset-token-throttlers!)
+ (letfn [(check []
+ (let [error (fn [status sign]
+ (get-in (token-response status (cond-> {:assertion (sign)}
+ client-id (assoc :client_id client-id)))
+ [:body :error]))]
+ (doseq [[expected sign] (take (inc limit) (cycle verified))]
+ (is (= expected (error 400 sign))))
+ (doseq [[expected sign] (take limit (cycle unverified))]
+ (is (= expected (error 400 sign))))
+ (is (= "too_many_requests" (error 429 (second (first unverified)))))))]
+ ;; The client limit keys on a registered client, so the client-ID case needs one.
+ (if client-id
+ (mt/with-temp [:model/OAuthClient _ {:client_id client-id
+ :redirect_uris ["https://example.com/callback"]
+ :grant_types ["authorization_code"]
+ :response_types ["code"]
+ :scopes ["openid"]
+ :registration_type "static"}]
+ (check))
+ (check))))))))))
+
+(deftest exchange-unverified-login-error-counts-test
+ (testing "a login that throws without a known post-verification error counts toward the throttles"
+ (with-jwt-bearer-setup!
+ (oauth-server.tu/reset-token-throttlers!)
+ (with-redefs [auth-identity/login! (fn [& _] (throw (ex-info "boom" {})))]
+ (is (= "invalid_grant"
+ (get-in (token-response 400 {:assertion (assertion {:email "[email protected]"})})
+ [:body :error])))
+ (is (= 1 (count @(:attempts @#'api.oauth/token-ip-throttler))))))))
+
+(deftest exchange-provisioning-refusal-throttling-test
+ (testing "a verified JWT refused because user provisioning is off doesn't count toward the token limits"
+ (with-jwt-bearer-setup!
+ (mt/with-temporary-setting-values [jwt-user-provisioning-enabled? false]
+ (dotimes [_ (:attempts-threshold @#'api.oauth/token-ip-throttler)]
+ (is (= "invalid_grant"
+ (get-in (token-response 400 {:assertion (assertion {:email "[email protected]"})})
+ [:body :error])))))
+ (is (=? {:access_token string?} (token! "[email protected]"))))))
+
(deftest token-drives-mcp-test
(testing "MCP calls run as the user named in the JWT, and usage and audit rows belong to that user"
(with-jwt-bearer-setup!
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index 9fe85d84a05..a27720328d6 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -23,6 +23,7 @@
[oidc-provider.core :as oidc]
[oidc-provider.protocol :as proto]
[oidc-provider.registration :as reg]
+ [oidc-provider.token-endpoint :as oidc.token-endpoint]
[oidc-provider.util :as oidc-util]
[ring.util.response :as response]
[throttle.core :as throttle])
@@ -265,6 +266,7 @@
(def ^:private one-minute-ms (* 60 1000))
(def ^:private one-hour-ms (* 60 one-minute-ms))
+(def ^:private max-client-id-length 255)
;; /oauth/token is the highest-risk endpoint: unauthenticated, accepts client credentials,
;; and is the primary target for brute-forcing client secrets or replaying authorization codes.
@@ -302,6 +304,36 @@
:error_description (ex-message e#)})
(throw e#)))))
+(defn- retry-after-seconds
+ "Return how many seconds `throttle-key` must wait before another attempt."
+ [{:keys [attempts attempts-threshold attempt-ttl-ms]} throttle-key]
+ (if-let [[_ blocking-attempt-ms] (nth (filter (fn [[attempt-key]] (= throttle-key attempt-key)) @attempts)
+ (dec attempts-threshold) nil)]
+ (quot (+ 999 (max 0 (- (+ blocking-attempt-ms attempt-ttl-ms) (System/currentTimeMillis)))) 1000)
+ 0))
+
+(defn- do-with-token-throttling
+ "Apply the token throttles to `f`.
+ The client limit keys on the stored `client_id` of the client the given ID resolves to, found the same way
+ the token request finds it, so the two agree on which client an ID names however the app DB compares strings.
+ Requests use only the IP limit when the client ID is missing or names no client."
+ [ip-address client-id f]
+ (let [client-id (when (seq client-id)
+ (:client_id (oauth-server.db/oauth-client client-id)))
+ response (with-throttling-429 [token-ip-throttler ip-address]
+ (if client-id
+ (with-throttling-429 [token-client-throttler client-id]
+ (f))
+ (f)))]
+ (if (= 429 (:status response))
+ (let [retry-after (max (retry-after-seconds token-ip-throttler ip-address)
+ (if client-id (retry-after-seconds token-client-throttler client-id) 0))]
+ (-> response
+ (assoc-in [:headers "Retry-After"] (str retry-after))
+ (assoc-in [:body :error_description]
+ (format "Too many attempts! You must wait %d seconds before trying again." retry-after))))
+ response)))
+
;;; ------------------------------------------------ Endpoints ----------------------------------------------------
(api.macros/defendpoint :post "/register"
@@ -433,6 +465,19 @@
(:error_description data)
fallback))
+(defn- token-error-response
+ "The token endpoint's response to an exception `e` thrown while handling a token request."
+ [e]
+ (log/warnf "OAuth token request failed: %s" (ex-message e))
+ (let [data (ex-data e)
+ error (token-error-code data)]
+ {:status (if (= error "invalid_client") 401 400)
+ :headers {"Content-Type" "application/json"
+ "Cache-Control" "no-store"
+ "Pragma" "no-cache"}
+ :body {:error error
+ :error_description (error-description data invalid-token-request-description)}}))
+
(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
@@ -641,45 +686,43 @@
[:code {:optional true} [:maybe :string]]
[:redirect_uri {:optional true} [:maybe :string]]
[:refresh_token {:optional true} [:maybe :string]]
- [:client_id {:optional true} [:maybe :string]]
+ [:client_id {:optional true} [:maybe [:string {:max max-client-id-length}]]]
[:client_secret {:optional true} [:maybe :string]]
[:scope {:optional true} [:maybe :string]]
[:code_verifier {:optional true} [:maybe :string]]
[:resource {:optional true} [:maybe [:or :string [:sequential :string]]]]]
request]
- (let [ip-address (request/ip-address request)
- ;; Fall back to IP when client_id isn't in the body (e.g. confidential clients using
- ;; HTTP Basic auth) to avoid pooling unrelated clients into a shared throttle bucket.
- client-id (or (:client_id body) ip-address)]
- (with-throttling-429 [token-client-throttler client-id
- token-ip-throttler ip-address]
- (or (when-let [provider (oauth-server/get-provider)]
- (let [authorization-header (get-in request [:headers "authorization"])]
- (try
- (check-resource-indicators! (:resource body))
- (let [response (if (= jwt-bearer/grant-type (:grant_type body))
- (jwt-bearer/exchange-jwt-for-token! provider request
- {:assertion (:assertion body)
- :scopes (when (some? (:scope body))
- (or (scope-tokens (:scope body)) []))
- :resource (:resource body)})
- (oidc/token-request provider body authorization-header))]
- {:status 200
- :headers {"Content-Type" "application/json"
- "Cache-Control" "no-store"
- "Pragma" "no-cache"}
- :body response})
- (catch ExceptionInfo e
- (log/warnf "OAuth token request failed: %s" (ex-message e))
- (let [data (ex-data e)
- error (token-error-code data)]
- {:status (if (= error "invalid_client") 401 400)
- :headers {"Content-Type" "application/json"
- "Cache-Control" "no-store"
- "Pragma" "no-cache"}
- :body {:error error
- :error_description (error-description data invalid-token-request-description)}})))))
- {:status 404 :body {:error "not_found"}}))))
+ (let [ip-address (request/ip-address request)
+ authorization-header (get-in request [:headers "authorization"])
+ client-id (or (:client-id (oidc.token-endpoint/parse-basic-auth authorization-header))
+ (:client_id body))]
+ (try
+ (do-with-token-throttling ip-address client-id
+ (fn []
+ (try
+ (or (when-let [provider (oauth-server/get-provider)]
+ (check-resource-indicators! (:resource body))
+ (let [response (if (= jwt-bearer/grant-type (:grant_type body))
+ (jwt-bearer/exchange-jwt-for-token!
+ provider request
+ {:assertion (:assertion body)
+ :scopes (when (some? (:scope body))
+ (or (scope-tokens (:scope body)) []))
+ :resource (:resource body)})
+ (oidc/token-request provider body authorization-header))]
+ {:status 200
+ :headers {"Content-Type" "application/json"
+ "Cache-Control" "no-store"
+ "Pragma" "no-cache"}
+ :body response}))
+ {:status 404 :body {:error "not_found"}})
+ (catch ExceptionInfo e
+ ;; A refused JWT that passed verification is no guess, so it returns uncounted
+ (if (jwt-bearer/verified-refusal? e)
+ (token-error-response e)
+ (throw e))))))
+ (catch ExceptionInfo e
+ (token-error-response e)))))
(api.macros/defendpoint :post "/revoke"
:- [:map [:status [:enum 200 404]]]
diff --git a/src/metabase/oauth_server/jwt_bearer.clj b/src/metabase/oauth_server/jwt_bearer.clj
index 5b56363cdd0..1c60ac8d637 100644
--- a/src/metabase/oauth_server/jwt_bearer.clj
+++ b/src/metabase/oauth_server/jwt_bearer.clj
@@ -64,18 +64,30 @@
"These `:error` values identify refused JWT logins whose `:message` was written by Metabase for the caller."
#{:non-personal-user :missing-email :missing-exp-or-iat :future-iat :invalid-tenant})
+(defn- verified-login-refusal?
+ "Whether a refused JWT login `result` comes from an assertion that passed verification.
+
+ An allowlist, so an unrecognised failure counts toward the throttles rather than skipping them. Verified refusals
+ are the ones Metabase raises itself after the JWT library accepts the assertion: a returned failure in
+ [[own-reason-errors]], or an exception it throws with a 4xx status, such as user provisioning being off. A failed
+ verification returns `:invalid-jwt`, and anything else, including a caught exception with no `:error` or status,
+ is treated as unverified."
+ [{:keys [error status-code]}]
+ (and (not= :invalid-jwt error)
+ (boolean (or (own-reason-errors error)
+ (<= 400 (or status-code 0) 499)))))
+
(defn- refusal-description
"Return `error_description` for a refused JWT login, or nil to use the token endpoint's generic one.
- The login's `message` goes back only when Metabase wrote it for the caller: the login returned one of
- [[own-reason-errors]], or threw with a 4xx `status-code`. A JWT that fails verification gets a fixed description,
- since the verifier's message is library text."
- [{:keys [error status-code message]}]
+ The login's `message` goes back only for a [[verified-login-refusal?]], whose message Metabase wrote for the caller.
+ A JWT that fails verification gets a fixed description, since the verifier's message is library text."
+ [{:keys [error message] :as result}]
(cond
(= :invalid-jwt error)
"The JWT could not be verified."
- (or (own-reason-errors error) (<= 400 (or status-code 0) 499))
+ (verified-login-refusal? result)
(str message)))
(defn- log-in!
@@ -96,7 +108,9 @@
:status-code (:status-code (ex-data e))}))]
(if success?
user
- (throw (ex-info (str message) {:error "invalid_grant", :error-description (refusal-description result)})))))
+ (throw (ex-info (str message) {:error "invalid_grant"
+ :error-description (refusal-description result)
+ ::verified? (verified-login-refusal? result)})))))
(defn- check-mcp-access!
"Throws `ex-info` carrying `unsupported_grant_type` unless the groups of the User with `user-id` allow MCP."
@@ -105,14 +119,23 @@
(mcp.perms/enabled? (mcp.perms/policy-for-current-user)))
(throw (ex-info (str "MCP access is not enabled for the groups of user " user-id)
{:error "unsupported_grant_type"
- :error-description "MCP access is not enabled for this user's groups."}))))
+ :error-description "MCP access is not enabled for this user's groups."
+ ::verified? true}))))
+
+(defn verified-refusal?
+ "Return whether `e` refuses a JWT bearer grant whose assertion passed verification.
+
+ These are the JWT login refusals that [[verified-login-refusal?]] accepts, and refusals of users whose groups don't
+ allow MCP."
+ [e]
+ (boolean (::verified? (ex-data e))))
(defn exchange-jwt-for-token!
"Issue an MCP access token to the user named in the JWT `assertion`.
Return the RFC 6749 token response. The token carries `scopes`, or every MCP scope when `scopes` is nil,
and is bound to the MCP endpoint, which `resource` must name when it is given.
- Throw `ex-info` carrying the RFC 6749 `:error` when the request is refused."
+ Throw `ex-info` carrying the RFC 6749 `:error` when the request is refused; see [[verified-refusal?]]."
[provider request {:keys [assertion scopes resource]}]
(let [scopes (or scopes (mcp/v2-scopes))
_ (check-request! assertion scopes resource)
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index 578907d527f..dc3e79ef8eb 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -1,13 +1,15 @@
-(ns metabase.oauth-server.api-test
+(ns ^:synchronized metabase.oauth-server.api-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is testing use-fixtures]]
[metabase.api-keys.core :as api-key]
+ [metabase.app-db.core :as mdb]
[metabase.auth-identity.core :as auth-identity]
[metabase.config.core :as config]
[metabase.mcp.core :as mcp]
[metabase.oauth-server.api.oauth :as api.oauth]
[metabase.oauth-server.core :as oauth-server]
+ [metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.test :as mt]
[metabase.test.http-client :as client]
[metabase.util.secret :as u.secret]
@@ -22,9 +24,13 @@
;; reset-provider! is safe here — it resets a local atom, no global side effects.
(use-fixtures :each (fn [thunk]
(oauth-server/reset-provider!)
- (binding [client/*url-prefix* ""]
- (thunk))
- (oauth-server/reset-provider!)))
+ (oauth-server.tu/reset-token-throttlers!)
+ (try
+ (binding [client/*url-prefix* ""]
+ (thunk))
+ (finally
+ (oauth-server.tu/reset-token-throttlers!)
+ (oauth-server/reset-provider!)))))
(deftest discovery-endpoint-test
(testing "Discovery endpoint returns valid OAuth metadata"
@@ -885,13 +891,15 @@
(defn- token-request!
"POST to /oauth/token with form-encoded params."
- [params & {:keys [expected-status authorization]
+ [params & {:keys [expected-status authorization ip-address full-response?]
:or {expected-status 200}}]
(let [request-options (cond-> {:headers {"content-type" "application/x-www-form-urlencoded"}}
- authorization (assoc-in [:headers "authorization"] authorization))]
- (client/client :post expected-status "oauth/token"
- {:request-options request-options}
- params)))
+ authorization (assoc-in [:headers "authorization"] authorization)
+ ip-address (assoc-in [:headers "x-forwarded-for"] ip-address))
+ request (if full-response? client/client-full-response client/client)]
+ (request :post expected-status "oauth/token"
+ {:request-options request-options}
+ params)))
(set! *warn-on-reflection* true)
@@ -937,6 +945,235 @@
:authorization (basic-auth-header client-id client-secret))]
(is (=? {:error "invalid_grant"} response)))))))
+(deftest token-refusals-throttled-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)
+ params {:grant_type "authorization_code"
+ :code "bogus-code"
+ :redirect_uri "https://example.com/callback"}
+ authorization (basic-auth-header client-id client-secret)]
+ (dotimes [_ 10]
+ (is (= "invalid_grant"
+ (:error (token-request! params :expected-status 400 :authorization authorization)))))
+ (let [response (token-request! params :expected-status 429 :authorization authorization :full-response? true)]
+ (is (= "too_many_requests" (get-in response [:body :error])))
+ (is (= (str "Too many attempts! You must wait " (get-in response [:headers "Retry-After"])
+ " seconds before trying again.")
+ (get-in response [:body :error_description])))
+ (is (some-> (get-in response [:headers "Retry-After"]) parse-long pos-int?))
+ (is (= 10 (count @(:attempts @#'api.oauth/token-ip-throttler)))))))))
+
+(deftest token-ip-refusals-throttled-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (dotimes [_ 50]
+ (is (= "invalid_request" (:error (token-request! {:grant_type "authorization_code"
+ :client_id (str (random-uuid))
+ :code "bogus-code"}
+ :expected-status 400)))))
+ (is (= "too_many_requests"
+ (:error (token-request! {:grant_type "authorization_code"
+ :client_id (str (random-uuid))
+ :code "bogus-code"}
+ :expected-status 429))))))
+
+(deftest token-rotating-unknown-client-ids-get-only-the-ip-limit-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (dotimes [i 100]
+ (is (= (if (< i 50) "invalid_request" "too_many_requests")
+ (:error (token-request! {:grant_type "authorization_code"
+ :client_id (str (random-uuid))
+ :code "bogus-code"}
+ :expected-status (if (< i 50) 400 429))))))
+ (is (empty? @(:attempts @#'api.oauth/token-client-throttler)))))
+
+(deftest token-ip-throttles-do-not-extend-client-lockout-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (doseq [client-attempt-count [0 8 9]]
+ (testing (str client-attempt-count " previous client refusals")
+ (oauth-server.tu/reset-token-throttlers!)
+ (mt/user-http-request :crowberto :get 200 "api/user/current")
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)
+ ip-address "198.51.100.6"
+ authorization (basic-auth-header client-id client-secret)
+ params {:grant_type "authorization_code"
+ :code (authorize-and-get-code! client-id)
+ :redirect_uri "https://example.com/callback"}
+ client-throttler @#'api.oauth/token-client-throttler
+ ip-throttler @#'api.oauth/token-ip-throttler
+ now (System/currentTimeMillis)]
+ (reset! (:attempts client-throttler)
+ (repeat client-attempt-count [client-id (- now (* 10 60 1000))]))
+ (reset! (:attempts ip-throttler) (repeat 50 [ip-address (- now (* 59 60 1000))]))
+ (let [responses (repeatedly 10 #(token-request! params :authorization authorization :ip-address ip-address
+ :expected-status 429 :full-response? true))]
+ (is (= (repeat 10 "too_many_requests") (map #(get-in % [:body :error]) responses)))
+ (is (every? #(some-> (get-in % [:headers "Retry-After"]) parse-long (<= 60)) responses)))
+ (is (= client-attempt-count (count @(:attempts client-throttler))))
+ (swap! (:attempts ip-throttler)
+ (fn [attempts]
+ (doall (for [[throttle-key timestamp] attempts]
+ [throttle-key (- timestamp (* 60 1000))]))))
+ (is (string? (:access_token (token-request! params :authorization authorization
+ :ip-address ip-address))))))))))
+
+(deftest token-overlong-body-client-id-rejected-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [response (token-request! {:grant_type "authorization_code"
+ :client_id (apply str (repeat 256 "a"))
+ :code "bogus-code"}
+ :expected-status 400 :full-response? true)]
+ (is (some? (get-in response [:body :errors :client_id])))
+ (is (empty? @(:attempts @#'api.oauth/token-client-throttler)))
+ (is (empty? @(:attempts @#'api.oauth/token-ip-throttler))))))
+
+(deftest token-requests-that-name-no-client-use-only-ip-throttle-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ ;; Revalidated before the transaction, as a session created inside it would be rolled back but stay cached
+ (mt/user-http-request :crowberto :get 200 "api/user/current")
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)
+ ip-address "198.51.100.1"
+ long-name (apply str (repeat 256 "a"))]
+ (doseq [[description params authorization]
+ [["no client ID" {} nil]
+ ["an empty client ID" {:client_id ""} nil]
+ ["an unknown client ID" {:client_id "no-such-client"} nil]
+ ;; A Basic username, even an empty one, names the client ahead of the body's `client_id`
+ ["an empty Basic username" {:client_id client-id} (basic-auth-header "" "secret")]
+ ["an overlong Basic username" {:client_id client-id} (basic-auth-header long-name "secret")]]]
+ (testing description
+ (oauth-server.tu/reset-token-throttlers!)
+ (dotimes [_ 11]
+ (is (= "invalid_request"
+ (:error (token-request! (merge {:grant_type "authorization_code" :code "bogus-code"} params)
+ :authorization authorization :ip-address ip-address
+ :expected-status 400)))))
+ (is (empty? @(:attempts @#'api.oauth/token-client-throttler)))
+ (is (= 11 (count @(:attempts @#'api.oauth/token-ip-throttler))))
+ (is (string? (:access_token
+ (token-request! {:grant_type "authorization_code"
+ :code (authorize-and-get-code! client-id)
+ :redirect_uri "https://example.com/callback"}
+ :ip-address ip-address
+ :authorization (basic-auth-header client-id client-secret)))))))))))
+
+(deftest token-client-throttle-is-shared-across-ips-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (mt/user-http-request :crowberto :get 200 "api/user/current")
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)]
+ (dotimes [i 10]
+ (is (= "invalid_request"
+ (:error (token-request! {:grant_type "refresh_token"
+ :client_id client-id
+ :refresh_token "bogus-token"}
+ :ip-address (str "198.51.100." (+ 10 i)) :expected-status 400)))))
+ (is (= "too_many_requests"
+ (:error (token-request! {:grant_type "authorization_code"
+ :client_id client-id
+ :code (authorize-and-get-code! client-id)
+ :redirect_uri "https://example.com/callback"}
+ :ip-address "198.51.100.3"
+ :authorization (basic-auth-header client-id client-secret)
+ :expected-status 429))))))))
+
+(deftest token-client-throttle-keys-on-the-stored-client-id-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (create-test-client! {:client_id "mixed-case-client"})
+ ;; MySQL and MariaDB match these spellings to the client, while H2 and Postgres match none
+ (let [spellings ["MIXED-CASE-CLIENT" "míxed-case-client" "mixed-case-client "
+ (str "mixed-case-client" (apply str (repeat 250 " ")))]]
+ (dotimes [i 10]
+ (is (= "invalid_request"
+ (:error (token-request! {:grant_type "refresh_token" :refresh_token "bogus-token"}
+ :authorization (basic-auth-header (nth spellings (mod i (count spellings)))
+ "wrong-secret")
+ :ip-address (str "198.51.100." (+ 20 i)) :expected-status 400)))))
+ (is (= (if (= :mysql (mdb/db-type)) {"mixed-case-client" 10} {})
+ (frequencies (map first @(:attempts @#'api.oauth/token-client-throttler)))))))))
+
+(deftest token-basic-auth-determines-client-throttle-key-test
+ (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!)
+ authorization (basic-auth-header client-id "wrong-secret")
+ params (fn [] {:grant_type "authorization_code"
+ :client_id (str (random-uuid))
+ :code "bogus-code"})]
+ (dotimes [_ 10]
+ (is (= "invalid_request"
+ (:error (token-request! (params) :authorization authorization :expected-status 400)))))
+ (is (= "too_many_requests"
+ (:error (token-request! (params) :authorization authorization :expected-status 429))))))))
+
+(deftest token-retry-after-covers-the-blocking-windows-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (doseq [[client-age-minutes ip-age-minutes expected-wait]
+ [[40 nil 1200] [nil 40 1200] [40 20 2400] [20 40 2400]]]
+ (testing (str "client attempts aged " client-age-minutes ", IP attempts aged " ip-age-minutes)
+ (mt/user-http-request :crowberto :get 200 "api/user/current")
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)
+ ip-address "198.51.100.4"
+ params {:grant_type "authorization_code"
+ :code (authorize-and-get-code! client-id)
+ :redirect_uri "https://example.com/callback"}
+ authorization (basic-auth-header client-id client-secret)
+ client-throttler @#'api.oauth/token-client-throttler
+ ip-throttler @#'api.oauth/token-ip-throttler
+ now (System/currentTimeMillis)
+ attempts (fn [throttler throttle-key age-minutes]
+ (when age-minutes
+ (concat (repeat (- (:attempts-threshold throttler) 2)
+ [throttle-key (- now (* 10 60 1000))])
+ (repeat 4 [throttle-key (- now (* age-minutes 60 1000))]))))]
+ (reset! (:attempts client-throttler)
+ (attempts client-throttler client-id client-age-minutes))
+ (reset! (:attempts ip-throttler) (attempts ip-throttler ip-address ip-age-minutes))
+ (let [response (token-request! params :authorization authorization :ip-address ip-address
+ :expected-status 429 :full-response? true)
+ wait (some-> (get-in response [:headers "Retry-After"]) parse-long)]
+ (is (pos-int? wait))
+ (when (pos-int? wait)
+ (is (= (str "Too many attempts! You must wait " wait " seconds before trying again.")
+ (get-in response [:body :error_description])))
+ (is (<= (- expected-wait 60) wait expected-wait))
+ (let [second-response (token-request! params :authorization authorization :ip-address ip-address
+ :expected-status 429 :full-response? true)
+ second-wait (some-> (get-in second-response [:headers "Retry-After"]) parse-long)]
+ (is (pos-int? second-wait))
+ (when (pos-int? second-wait)
+ (is (= (str "Too many attempts! You must wait " second-wait " seconds before trying again.")
+ (get-in second-response [:body :error_description])))
+ (doseq [throttler [client-throttler ip-throttler]]
+ (swap! (:attempts throttler)
+ (fn [recorded]
+ (doall (for [[throttle-key timestamp] recorded]
+ [throttle-key (- timestamp (* 1000 second-wait))])))))
+ (is (string? (:access_token (token-request! params :authorization authorization
+ :ip-address ip-address))))))))))))))
+
+(deftest successful-token-requests-do-not-count-toward-throttle-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [{client-id :client_id, client-secret :client_secret} (create-test-client!)
+ authorization (basic-auth-header client-id client-secret)
+ code (authorize-and-get-code! client-id)
+ tokens (token-request! {:grant_type "authorization_code"
+ :code code
+ :redirect_uri "https://example.com/callback"}
+ :authorization authorization)]
+ (loop [refresh-token (:refresh_token tokens), remaining 51]
+ (when (pos? remaining)
+ (let [response (token-request! {:grant_type "refresh_token"
+ :refresh_token refresh-token}
+ :authorization authorization)]
+ (is (string? (:access_token response)))
+ (recur (:refresh_token response) (dec remaining)))))))))
+
(deftest token-auth-code-wrong-client-test
(testing "GHY-4491: Authorization code grant -- a code issued to another client is an invalid grant"
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
diff --git a/test/metabase/oauth_server/test_util.clj b/test/metabase/oauth_server/test_util.clj
index 1f8712fd40d..a02c39343eb 100644
--- a/test/metabase/oauth_server/test_util.clj
+++ b/test/metabase/oauth_server/test_util.clj
@@ -1,8 +1,15 @@
(ns metabase.oauth-server.test-util
"Helpers for tests that exercise the OAuth server."
(:require
+ [metabase.oauth-server.api.oauth :as api.oauth]
[metabase.test :as mt]))
+(defn reset-token-throttlers!
+ "Clear failed attempts counted by the OAuth token endpoint."
+ []
+ (doseq [throttler [@#'api.oauth/token-client-throttler @#'api.oauth/token-ip-throttler]]
+ (reset! (:attempts throttler) '())))
+
(defmacro with-oauth-client
"Execute `body` with a freshly registered `oauth_client` row, binding `client-id-binding` to its
`client_id`, and delete the row when `body` exits. Save test tokens against this client id —