Skip to content

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

Minor improvements to MCP server (#71406)

Chris Truter87dc66019155
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index c01f29f11aa..ad79597f516 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -798,11 +798,15 @@
- **Stateless JWT**: Uses `Authorization: Bearer <jwt>` header. The JWT is validated
using the same auth-identity system as the /auth/sso endpoint."
[handler]
- (fn [{:keys [headers metabase-user-id] :as request} respond raise]
+ (fn [{:keys [headers metabase-user-id token-scopes] :as request} respond raise]
(cond
- ;; Already authenticated via X-Metabase-Session (standard middleware handled it)
+ ;; Already authenticated via X-Metabase-Session (standard middleware handled it).
+ ;; Preserve any pre-existing :token-scopes (e.g., forwarded from internal MCP calls);
+ ;; default to unrestricted for normal session-authenticated browser requests.
metabase-user-id
- (handler (assoc request :token-scopes #{::scope/unrestricted}) respond raise)
+ (handler (cond-> request
+ (not token-scopes) (assoc :token-scopes #{::scope/unrestricted}))
+ respond raise)
;; Not authenticated via session - check for Bearer JWT
:else
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index e6f1cc4371d..85710123284 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -68,20 +68,19 @@
"Does `token-scopes` grant access to a tool with the given `tool-scope`?
- nil token-scopes → always matches (internal callers)
- ::scope/unrestricted in token-scopes → always matches
- - nil tool-scope → always matches (tool has no scope restriction)
- - empty token-scopes #{} → only matches tools with nil tool-scope
+ - nil tool-scope → only matches nil or unrestricted token-scopes
- wildcard scopes like \"agent:*\" match any tool scope starting with \"agent:\""
[token-scopes tool-scope]
(or (nil? token-scopes)
(contains? token-scopes ::scope/unrestricted)
- (nil? tool-scope)
- (contains? token-scopes tool-scope)
- (some (fn [s]
- (when (string? s)
- (when-let [prefix (when (str/ends-with? s ":*")
- (subs s 0 (dec (count s))))]
- (str/starts-with? tool-scope prefix))))
- token-scopes)))
+ (when (some? tool-scope)
+ (or (contains? token-scopes tool-scope)
+ (some (fn [s]
+ (when (string? s)
+ (when-let [prefix (when (str/ends-with? s ":*")
+ (subs s 0 (dec (count s))))]
+ (str/starts-with? tool-scope prefix))))
+ token-scopes)))))
(defn list-tools
"Return the tool definitions suitable for MCP `tools/list` responses.
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index 596737bf305..abac66aa746 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -2,6 +2,7 @@
"OAuth protocol endpoints. Mounted under `/oauth/`."
(:require
[buddy.core.codecs :as codecs]
+ [buddy.core.mac :as mac]
[buddy.core.nonce :as nonce]
[clojure.string :as str]
[metabase.api.macros :as api.macros]
@@ -9,12 +10,14 @@
[metabase.oauth-server.core :as oauth-server]
[metabase.oauth-server.settings :as oauth-settings]
[metabase.system.core :as system]
+ [metabase.util.log :as log]
[oidc-provider.core :as oidc]
[oidc-provider.protocol :as proto]
[oidc-provider.registration :as reg]
[oidc-provider.util :as oidc-util]
[ring.util.response :as response])
(:import
+ (clojure.lang ExceptionInfo)
(java.net URLEncoder)))
(set! *warn-on-reflection* true)
@@ -26,6 +29,71 @@
[]
(codecs/bytes->hex (nonce/random-bytes 16)))
+(defn- csrf-cookie-opts
+ "Cookie options for the CSRF cookie. Sets `:secure` when site-url is HTTPS."
+ [max-age]
+ (cond-> {:http-only true
+ :same-site :strict
+ :path "/oauth/authorize"
+ :max-age max-age}
+ (str/starts-with? (system/site-url) "https")
+ (assoc :secure true)))
+
+(defn- canonical-params-string
+ "Deterministic serialization of oauth-params for HMAC signing.
+ Sorts by key name, uses pr-str for values to avoid ambiguity with special characters."
+ [oauth-params]
+ (->> oauth-params
+ (remove (comp nil? val))
+ (sort-by (comp name key))
+ (map (fn [[k v]] (str (name k) "=" (pr-str v))))
+ (str/join "\n")))
+
+(defn- sign-oauth-params
+ "HMAC-SHA256 the canonical oauth-params string using the CSRF token as key."
+ [csrf-token oauth-params]
+ (codecs/bytes->hex
+ (mac/hash (canonical-params-string oauth-params)
+ {:key csrf-token :alg :hmac+sha256})))
+
+(defn- verify-oauth-params-signature
+ "Verify that the HMAC signature matches the oauth-params."
+ [csrf-token oauth-params signature]
+ (mac/verify (canonical-params-string oauth-params)
+ (codecs/hex->bytes signature)
+ {:key csrf-token :alg :hmac+sha256}))
+
+(def ^:private oauth-param-keys
+ "The set of OAuth authorization parameters that are signed and verified."
+ [:client_id
+ :code_challenge
+ :code_challenge_method
+ :nonce
+ :redirect_uri
+ :resource
+ :response_type
+ :scope
+ :state])
+
+(defn- truncate
+ "Truncate a string to `max-len` characters, appending \"...\" if truncated."
+ [s max-len]
+ {:pre [(> max-len 3)]}
+ (if (> (count s) max-len)
+ (str (subs s 0 (- max-len 3)) "...")
+ s))
+
+(defn- redirect-authorization-decision
+ "Issue a 302 redirect for an approved or denied authorization decision, clearing the CSRF cookie."
+ [provider parsed approved request]
+ (let [url (if approved
+ (oidc/authorize provider parsed (str (:metabase-user-id request)))
+ (oidc/deny-authorization provider parsed "access_denied" "User denied the request"))]
+ (-> {:status 302
+ :headers {"Location" url}
+ :body ""}
+ (response/set-cookie csrf-cookie-name "" (csrf-cookie-opts 0)))))
+
(defn- login-redirect-url
"Build a redirect URL to the login page that will redirect back to the given path after login.
Only allows redirecting back to OAuth paths to prevent open-redirect attacks."
@@ -80,7 +148,7 @@
{:status 201
:headers {"Content-Type" "application/json"}
:body response})
- (catch clojure.lang.ExceptionInfo e
+ (catch ExceptionInfo e
(reg/registration-error-response
(ex-message e)
(:error_description (ex-data e)))))))
@@ -115,34 +183,27 @@
:body ""}
(or (when-let [provider (oauth-server/get-provider)]
(try
- (let [parsed (oidc/parse-authorization-request provider query-params)
- client (proto/get-client (:client-store provider) (:client_id parsed))
- csrf-token (generate-csrf-token)]
+ (let [parsed (oidc/parse-authorization-request provider query-params)
+ 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 (or (:client-name client) "Unknown Application")
+ {:client-name (some-> (:client-name client) (truncate 64))
+ :client-id (:client_id parsed)
:nonce (:nonce request)
:csrf-token csrf-token
- :oauth-params {:client_id (:client_id parsed)
- :redirect_uri (:redirect_uri parsed)
- :response_type (:response_type parsed)
- :scope (:scope parsed)
- :state (:state parsed)
- :nonce (:nonce parsed)
- :code_challenge (:code_challenge parsed)
- :code_challenge_method (:code_challenge_method parsed)
- :resource (:resource parsed)}})}
- (response/set-cookie csrf-cookie-name csrf-token
- {:http-only true
- :same-site :strict
- :path "/oauth/authorize"
- :max-age 600})))
- (catch clojure.lang.ExceptionInfo e
+ :params-sig params-sig
+ :oauth-params oauth-params})}
+ (response/set-cookie csrf-cookie-name csrf-token (csrf-cookie-opts 600))))
+ (catch ExceptionInfo e
+ (log/warn e "OAuth authorize request failed")
{:status 400
:headers {"Content-Type" "application/json"}
:body {:error "invalid_request"
- :error_description (ex-message e)}})))
+ :error_description "The authorization request is invalid."}})))
{:status 404 :body {:error "not_found"}})))
(api.macros/defendpoint :post "/authorize/decision"
@@ -155,41 +216,34 @@
:headers {"Content-Type" "application/json"}
:body {:error "unauthorized"}}
(or (when-let [provider (oauth-server/get-provider)]
- (let [cookie-token (get-in request [:cookies csrf-cookie-name :value])
- form-token (str (:csrf_token body))]
+ (let [cookie-token (get-in request [:cookies csrf-cookie-name :value])
+ form-token (str (:csrf_token body))
+ auth-params (select-keys body oauth-param-keys)
+ params-sig (some-> (:params_sig body) str)]
(if (or (str/blank? cookie-token)
(str/blank? form-token)
(not (oidc-util/constant-time-eq? cookie-token form-token)))
{:status 403
:headers {"Content-Type" "application/json"}
:body {:error "csrf_validation_failed"}}
- (let [approved (= "true" (str (:approved body)))
- auth-params (select-keys body [:client_id :redirect_uri :response_type :scope :state :nonce
- :code_challenge :code_challenge_method :resource])]
+ (let [approved (= "true" (str (:approved body)))]
(try
- (let [parsed (oidc/parse-authorization-request provider auth-params)]
- (if approved
- (let [url (oidc/authorize provider parsed (str (:metabase-user-id request)))]
- (-> {:status 302
- :headers {"Location" url}
- :body ""}
- (response/set-cookie csrf-cookie-name "" {:http-only true
- :same-site :strict
- :path "/oauth/authorize"
- :max-age 0})))
- (let [url (oidc/deny-authorization provider parsed "access_denied" "User denied the request")]
- (-> {:status 302
- :headers {"Location" url}
- :body ""}
- (response/set-cookie csrf-cookie-name "" {:http-only true
- :same-site :strict
- :path "/oauth/authorize"
- :max-age 0})))))
- (catch clojure.lang.ExceptionInfo e
+ (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.
+ parsed-params (select-keys parsed oauth-param-keys)]
+ (if (or (str/blank? params-sig)
+ (not (verify-oauth-params-signature cookie-token parsed-params params-sig)))
+ {:status 403
+ :headers {"Content-Type" "application/json"}
+ :body {:error "params_tampered"}}
+ (redirect-authorization-decision provider parsed approved request)))
+ (catch ExceptionInfo e
+ (log/warn e "OAuth authorization decision failed")
{:status 400
:headers {"Content-Type" "application/json"}
:body {:error "invalid_request"
- :error_description (ex-message e)}}))))))
+ :error_description "The authorization request is invalid."}}))))))
{:status 404 :body {:error "not_found"}})))
(api.macros/defendpoint :post "/token"
@@ -206,14 +260,16 @@
"Cache-Control" "no-store"
"Pragma" "no-cache"}
:body response})
- (catch clojure.lang.ExceptionInfo e
- (let [data (ex-data e)]
- {:status (if (= (:error data) "invalid_client") 401 400)
+ (catch ExceptionInfo e
+ (log/warn e "OAuth token request failed")
+ (let [data (ex-data e)
+ error (or (:error data) "invalid_request")]
+ {:status (if (= error "invalid_client") 401 400)
:headers {"Content-Type" "application/json"
"Cache-Control" "no-store"
"Pragma" "no-cache"}
- :body {:error (or (:error data) "invalid_request")
- :error_description (ex-message e)}})))))
+ :body {:error error
+ :error_description (or (:error_description data) "The token request is invalid.")}})))))
{:status 404 :body {:error "not_found"}}))
(api.macros/defendpoint :post "/revoke"
diff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.clj
index 6668de75124..d97e5be794b 100644
--- a/src/metabase/oauth_server/consent_page.clj
+++ b/src/metabase/oauth_server/consent_page.clj
@@ -45,6 +45,16 @@
(def ^:private default-logo-svg
(delay (some-> (io/resource "frontend_client/app/assets/img/logo.svg") slurp)))
+(def ^:private default-brand-color "#509ee3")
+
+(defn- sanitize-css-color
+ "Return `color` if it looks like a safe CSS color value (hex or named color),
+ otherwise return the default brand color. Prevents CSS injection via `h/raw` interpolation."
+ [color]
+ (if (and (string? color) (re-matches #"#[0-9a-fA-F]{3,8}|[a-zA-Z]+" color))
+ color
+ default-brand-color))
+
(defn- branded-logo-svg
"Return the default Metabase logo SVG with `currentColor` replaced by the brand color."
[brand-color]
@@ -58,11 +68,11 @@
{:font-family (appearance/application-font)
:logo-url (absolute-url logo-url)
:default-logo? (= logo-url default-logo-url)
- :brand-color (get colors "brand" "#509ee3")}))
+ :brand-color (sanitize-css-color (get colors "brand"))}))
(defn render-consent-page
"Render a server-side HTML consent page for the OAuth authorization flow."
- [{:keys [client-name oauth-params nonce csrf-token]}]
+ [{:keys [client-name client-id oauth-params nonce csrf-token params-sig]}]
(let [{:keys [font-family logo-url default-logo? brand-color]} (appearance-settings)
css-font-family (css-escape-font-name font-family)]
(str
@@ -85,7 +95,9 @@
box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 4px 12px rgba(0,0,0,0.05);
padding: 2.5rem; max-width: 440px; width: 100%; margin: 1rem; }
.logo { display: flex; justify-content: center; margin-bottom: 1.5rem; }
- h1 { font-size: 1.25rem; font-weight: 700; color: #2e353b; text-align: center; margin-bottom: 0.5rem; }
+ h1 { font-size: 1.25rem; font-weight: 700; color: #2e353b; text-align: center; margin-bottom: 0.25rem; }
+ .client-id { text-align: center; font-size: 0.75rem; color: #949aab; margin-bottom: 1rem;
+ font-family: monospace; word-break: break-all; }
.subtitle { text-align: center; font-size: 0.875rem; line-height: 1.5; color: #696e7b; margin-bottom: 1.5rem; }
.actions { display: flex; gap: 0.75rem; }
button { flex: 1; padding: 0.75rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 700;
@@ -101,11 +113,13 @@
(if-let [svg (when default-logo? (branded-logo-svg brand-color))]
(h/raw svg)
[:img {:src logo-url :alt "Logo" :height "32"}])]
- [:h1 "Authorize " client-name "?"]
+ [:h1 "Authorize " (or client-name "Unknown Application") "?"]
+ [:p.client-id client-id]
[:p.subtitle "This MCP client is requesting to be authorized. If you approve, it will be able to access resources from "
[:strong (appearance/application-name)] " on your behalf."]
[:form {:method "POST" :action "/oauth/authorize/decision"}
[:input {:type "hidden" :name "csrf_token" :value csrf-token}]
+ [:input {:type "hidden" :name "params_sig" :value params-sig}]
(for [[k v] oauth-params
:when (some? v)
v (if (sequential? v) v [v])]
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 8390c639bf4..7bc4ee9fd64 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -36,7 +36,8 @@
:client-store (store/create-client-store)
:code-store (store/create-authorization-code-store)
:token-store (store/create-token-store)
- :scopes-supported (all-agent-scopes)}))
+ :scopes-supported (all-agent-scopes)
+ :rotate-refresh-tokens true}))
(defn- create-provider
"Create a new OAuth provider instance."
diff --git a/src/metabase/oauth_server/settings.clj b/src/metabase/oauth_server/settings.clj
index 09a25811a76..767c097283e 100644
--- a/src/metabase/oauth_server/settings.clj
+++ b/src/metabase/oauth_server/settings.clj
@@ -25,7 +25,7 @@
(deferred-tru "Refresh token time-to-live in seconds for the embedded OAuth server.")
:type :integer
:visibility :internal
- :default 2592000
+ :default 2592000 ;; 30 days
:doc false
:export? false
:audit :never)
diff --git a/src/metabase/oauth_server/store.clj b/src/metabase/oauth_server/store.clj
index a10c8d116c4..3dbbaa3c34c 100644
--- a/src/metabase/oauth_server/store.clj
+++ b/src/metabase/oauth_server/store.clj
@@ -10,16 +10,23 @@
;;; ------------------------------------------------- Helpers ----------------------------------------------------------
(defn- parse-user-id
- "Parse a user-id string to an integer, returning nil if not a valid integer.
- The oidc-provider library passes user-id as a string. For authorization_code and
- refresh_token grants this is a stringified Metabase user ID. For client_credentials
- grants the library passes the client-id string, which is not a valid integer."
+ "Parse a user-id string to a long, returning nil if not a valid positive integer.
+ The oidc-provider library passes user-id as a string. For most grants this is a
+ stringified Metabase user ID. We don't support client_credentials yet, but when we
+ do the library will pass the client-id (a UUID) which is not a valid integer — the
+ lenient nil return keeps this path open."
[user-id]
- (when user-id
- (try
- (Integer/parseInt (str user-id))
- (catch NumberFormatException _
- nil))))
+ (let [s (str user-id)]
+ (when (re-matches #"[1-9]\d*" s)
+ (Long/parseLong s))))
+
+(defn- parse-user-id-or-throw
+ "Like [[parse-user-id]] but throws if the user-id is missing or not a valid positive integer.
+ Use this in flows (e.g. authorization_code) where a real user must be present."
+ [user-id]
+ (or (parse-user-id user-id)
+ (throw (ex-info "Expected a valid user ID, but it was not a positive integer"
+ {:user-id user-id}))))
(def ^:private client-db-columns
"DB columns to select/project for OAuthClient rows."
@@ -45,10 +52,10 @@
the oidc-provider library can find the hash where it expects it."
[row]
(when row
- (let [m (select-and-kebab-keys row client-db-columns)]
+ (let [m (select-and-kebab-keys row client-db-columns)
+ token-hash (:registration-access-token-hash m)]
(cond-> m
- (:registration-access-token-hash m)
- (assoc :registration-access-token (:registration-access-token-hash m))))))
+ token-hash (assoc :registration-access-token token-hash)))))
(defn- client-config->db-row
"Convert a protocol ClientConfig map to DB column format for insert/update."
@@ -68,10 +75,9 @@
Ensures :resource is a vector (JSON deserialization may return a list)."
[row]
(when row
- (let [m (-> (select-and-kebab-keys row auth-code-db-columns)
- (update :user-id #(some-> % str)))]
- (cond-> m
- (:resource m) (update :resource vec)))))
+ (-> (select-and-kebab-keys row auth-code-db-columns)
+ (update :user-id #(some-> % str))
+ (u/update-if-exists :resource vec))))
(def ^:private access-token-db-columns
[:user_id :client_id :scope :expiry :resource])
@@ -80,10 +86,9 @@
"Convert a DB row from :model/OAuthAccessToken to the protocol's map shape."
[row]
(when row
- (let [m (-> (select-and-kebab-keys row access-token-db-columns)
- (update :user-id #(some-> % str)))]
- (cond-> m
- (:resource m) (update :resource vec)))))
+ (-> (select-and-kebab-keys row access-token-db-columns)
+ (update :user-id #(some-> % str))
+ (u/update-if-exists :resource vec))))
(def ^:private refresh-token-db-columns
[:user_id :client_id :scope :expiry :resource])
@@ -92,10 +97,9 @@
"Convert a DB row from :model/OAuthRefreshToken to the protocol's map shape."
[row]
(when row
- (let [m (-> (select-and-kebab-keys row refresh-token-db-columns)
- (update :user-id #(some-> % str)))]
- (cond-> m
- (:resource m) (update :resource vec)))))
+ (-> (select-and-kebab-keys row refresh-token-db-columns)
+ (update :user-id #(some-> % str))
+ (u/update-if-exists :resource vec))))
;;; ------------------------------------------------ ClientStore -------------------------------------------------------
@@ -142,7 +146,7 @@
(save-authorization-code [_ code user-id client-id redirect-uri scope nonce expiry code-challenge code-challenge-method resource]
(t2/insert! :model/OAuthAuthorizationCode
(cond-> {:code code
- :user_id (parse-user-id user-id)
+ :user_id (parse-user-id-or-throw user-id)
:client_id client-id
:redirect_uri redirect-uri
:scope (vec scope)
@@ -200,9 +204,8 @@
db-row->refresh-token))
(revoke-token [_ token]
- (let [now (java.time.OffsetDateTime/now)]
- (t2/update! :model/OAuthAccessToken {:token token} {:revoked_at now})
- (t2/update! :model/OAuthRefreshToken {:token token} {:revoked_at now}))
+ (t2/update! :model/OAuthAccessToken {:token token} {:revoked_at :%now})
+ (t2/update! :model/OAuthRefreshToken {:token token} {:revoked_at :%now})
true))
;;; ------------------------------------------------ Constructors ------------------------------------------------------
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index c262bee376f..4bafdbf8992 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -481,3 +481,23 @@
(is (= "Insufficient scope to call tool: get_table"
(-> result :content first :text))
"Error must not leak the required scope name"))))
+
+(deftest agent-api-preserves-token-scopes-test
+ (testing "scoped token restrictions are enforced by the Agent API layer (defense-in-depth)"
+ (testing "restricted scopes that don't match the endpoint are rejected by Agent API"
+ (let [result (mt/with-current-user (mt/user->id :crowberto)
+ ;; Bypass the MCP scope check by calling invoke-agent-api directly
+ ;; with scopes that don't match the endpoint's required scope (agent:table:read)
+ (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{"agent:search"}))]
+ (is (=? {:isError true} result)
+ "Agent API should reject when token scopes don't include the required scope")))
+ (testing "matching scopes are accepted by Agent API"
+ (let [result (mt/with-current-user (mt/user->id :crowberto)
+ (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{"agent:table:read"}))]
+ (is (not (:isError result))
+ "Agent API should accept when token scopes include the required scope")))
+ (testing "unrestricted scopes are accepted by Agent API"
+ (let [result (mt/with-current-user (mt/user->id :crowberto)
+ (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{::scope/unrestricted}))]
+ (is (not (:isError result))
+ "Agent API should accept unrestricted scopes")))))
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index 2fcd944f535..957e0331df9 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -8,6 +8,7 @@
[oidc-provider.util :as oidc-util]
[toucan2.core :as t2])
(:import
+ (java.net URLEncoder)
(java.security MessageDigest)
(java.util Base64)))
@@ -261,20 +262,29 @@
;;; ----------------------------------------- Authorization Decision ------------------------------------------------
(defn- get-consent-page!
- "GET the consent page and return the full response (including CSRF cookie)."
- [user client-id]
- (mt/user-http-request-full-response
- user :get 200 "oauth/authorize"
- :client_id client-id
- :redirect_uri "https://example.com/callback"
- :response_type "code"
- :scope "profile"
- :state "test-state"))
-
-(defn- extract-csrf-token-from-consent
- "Extract the CSRF token from the consent page HTML body."
- [body]
- (second (re-find #"name=\"csrf_token\"[^>]*value=\"([a-f0-9]+)\"" body)))
+ "GET the consent page and return the full response (including CSRF cookie).
+ Accepts optional extra query params (e.g. PKCE code_challenge)."
+ ([user client-id]
+ (get-consent-page! user client-id nil))
+ ([user client-id extra-params]
+ (apply mt/user-http-request-full-response
+ user :get 200 "oauth/authorize"
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope "profile"
+ :state "test-state"
+ (mapcat identity extra-params))))
+
+(defn- hidden-field-extractor
+ "Returns a function that extracts a hidden form field's hex value from HTML."
+ [field-name]
+ (let [pattern (re-pattern (str "name=\"" field-name "\"[^>]*value=\"([a-f0-9]+)\""))]
+ (fn [body] (second (re-find pattern body)))))
+
+(def ^:private extract-csrf-token-from-consent (hidden-field-extractor "csrf_token"))
+
+(def ^:private extract-params-sig-from-consent (hidden-field-extractor "params_sig"))
(defn- extract-csrf-cookie
"Extract the CSRF cookie value from the response.
@@ -308,12 +318,15 @@
(let [client (create-test-client!)
client-id (:client_id client)
consent-resp (get-consent-page! :crowberto client-id)
- csrf-token (extract-csrf-token-from-consent (:body consent-resp))
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent consent-body)
response (form-post-decision!
:crowberto
{:approved "true"
:csrf_token csrf-token
+ :params_sig params-sig
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
@@ -337,12 +350,15 @@
(let [client (create-test-client!)
client-id (:client_id client)
consent-resp (get-consent-page! :crowberto client-id)
- csrf-token (extract-csrf-token-from-consent (:body consent-resp))
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent consent-body)
response (form-post-decision!
:crowberto
{:approved "false"
:csrf_token csrf-token
+ :params_sig params-sig
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
@@ -421,12 +437,15 @@
Creates a client, authorizes, and extracts the code from the redirect."
[client-id]
(let [consent-resp (get-consent-page! :crowberto client-id)
- csrf-token (extract-csrf-token-from-consent (:body consent-resp))
+ body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent body)
csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent body)
response (form-post-decision!
:crowberto
{:approved "true"
:csrf_token csrf-token
+ :params_sig params-sig
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
@@ -627,13 +646,16 @@
(defn- authorize-and-get-code-with-params!
"Complete the authorize flow with extra decision params and return the authorization code."
[client-id extra-params]
- (let [consent-resp (get-consent-page! :crowberto client-id)
- csrf-token (extract-csrf-token-from-consent (:body consent-resp))
+ (let [consent-resp (get-consent-page! :crowberto client-id extra-params)
+ body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent body)
csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent body)
response (form-post-decision!
:crowberto
(merge {:approved "true"
:csrf_token csrf-token
+ :params_sig params-sig
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
@@ -811,32 +833,42 @@
(testing "OAuth state with special characters survives the authorize round-trip"
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [state "abc+/=&foo=bar baz"
- client (create-test-client!)
- client-id (:client_id client)
- consent-resp (mt/user-http-request-full-response
- :crowberto :get 200 "oauth/authorize"
- :client_id client-id
- :redirect_uri "https://example.com/callback"
- :response_type "code"
- :scope "profile"
- :state state)
- csrf-token (extract-csrf-token-from-consent (:body consent-resp))
- csrf-cookie (extract-csrf-cookie consent-resp)
- response (form-post-decision!
- :crowberto
- {:approved "true"
- :csrf_token csrf-token
+ ;; Test that special characters in state survive the authorize → consent → decision
+ ;; round-trip. Includes `/`, `=`, `&`, and space. Literal `+` is excluded because
+ ;; codec/url-encode (RFC 3986) doesn't percent-encode it, so ring's query parser
+ ;; decodes it as space. We can't pre-encode it as `%2B` either — codec/url-encode
+ ;; double-escapes the `%` to `%252B`. In a real client flow, `+` is sent as `%2B`
+ ;; and round-trips correctly.
+ (let [state "abc/=&foo=bar baz"
+ client (create-test-client!)
+ client-id (:client_id client)
+ consent-resp (mt/user-http-request-full-response
+ :crowberto :get 200 "oauth/authorize"
:client_id client-id
:redirect_uri "https://example.com/callback"
:response_type "code"
:scope "profile"
- :state state}
- 302
- :csrf-cookie csrf-cookie)
- location (get-in response [:headers "Location"])]
- (is (str/includes? location "state="))
- (is (str/includes? location (java.net.URLEncoder/encode state "UTF-8"))))))))
+ :state state)
+ consent-body (:body consent-resp)
+ csrf-token (extract-csrf-token-from-consent consent-body)
+ csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent consent-body)]
+ (is (some? params-sig) "Should extract params_sig from consent page")
+ (let [response (form-post-decision!
+ :crowberto
+ {:approved "true"
+ :csrf_token csrf-token
+ :params_sig params-sig
+ :client_id client-id
+ :redirect_uri "https://example.com/callback"
+ :response_type "code"
+ :scope "profile"
+ :state state}
+ 302
+ :csrf-cookie csrf-cookie)
+ location (get-in response [:headers "Location"])]
+ (is (str/includes? location "state="))
+ (is (str/includes? location (URLEncoder/encode state "UTF-8")))))))))
;;; ----------------------------------------- Consent Page Security --------------------------------------------------