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
Per-scope checkboxes on the OAuth consent page (GHY-4555) (#82527)
Eric Normand5701125c3410
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 131fffd17a8..e8d41411065 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1378,6 +1378,7 @@mcpmodelsrequest+ serversettingssystemtaskdiff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.mdindex bf1a2d5439c..88d27f30b00 100644--- a/src/metabase/mcp/README.md+++ b/src/metabase/mcp/README.md@@ -75,9 +75,11 @@ chart never embeds.A tool call or data resource read the token lacks a scope for is refused with HTTP 403 and a`WWW-Authenticate: Bearer error="insufficient_scope"` challenge whose `scope` lists the v2 scopes the token already-holds plus the one required, so a client can step up. Each tool also declares its scope in `securitySchemes`. Inside-a JSON-RPC batch the refusal is an in-band `-32600` error instead. UI shell reads are never challenged: see-[Resources](#resources).+holds plus the one required, so a client can step up. Each tool also declares its scope in `securitySchemes`, which is+draft [SEP-1488](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1488), supported by ChatGPT. It is+not part of MCP 2025-03-26 (the version this server reports) or the final 2026-07-28 tools spec, so other clients+discover the missing scope from the 403 instead. Inside a JSON-RPC batch the refusal is an in-band `-32600` error+instead. UI shell reads are never challenged: see [Resources](#resources).OAuth protected resource metadata is available at:@@ -85,7 +87,18 @@ OAuth protected resource metadata is available at:/.well-known/oauth-protected-resource/api/metabase-mcp```-The consent screen grants every scope the client requested, without the opportunity to customize.+On the consent screen, the baseline scopes are ticked and locked, and every other scope the client requested starts+unticked. Only the scopes the user ticks are granted, and only for the token this authorization mints: an untick never+touches a token the app already has. A scope left unticked is not remembered by Metabase. A later 403 can trigger+another step-up in clients that support it. Other clients may require manual reauthorization. Each challenge's+`error_description` ends with a note that the user must tick the permission on the consent screen.++Several clients replace the 403's `error_description` with their own text, so the `initialize` result's+`instructions` explain scope failures to the model too: an auth error usually means a missing permission rather than an+expired login, the model should name the failed tool or resource and the permission it requires, and the user grants it+by reconnecting and ticking permissions on the consent screen. Because every optional permission starts unticked, the+instructions tell the model to have the user tick every permission they want, not only the new one. The instructions+are one static string, the same for every caller: there is no per-connection permission list.## Available toolsdiff --git a/src/metabase/mcp/v2/api.clj b/src/metabase/mcp/v2/api.cljindex bbc330dc908..ab7c715e728 100644--- a/src/metabase/mcp/v2/api.clj+++ b/src/metabase/mcp/v2/api.clj@@ -57,13 +57,21 @@(cond-> (filterv #(or (= required %) (mcp.scope/matches? held %)) surface-scopes)(not (some #{required} surface-scopes)) (conj required))))+(defn- step-up-description+ "The `insufficient_scope` challenge's `error_description`: `description`, which names the missing permission, then a+ note telling the user to tick it on the consent screen."+ [description]+ ;; The note covers a permission never granted and one a later authorization left unticked, so it doesn't say the+ ;; permission starts unticked. Printable ASCII without `\"` or `\\`: what RFC 6750 allows in `error_description`.+ (str description ". The user must tick this permission on the consent screen."))+(defn- with-step-up-challenge"`error-response` marked with [[transport/insufficient-scope]] for the scope an `insufficient-scope` detail names,- asking for [[step-up-scopes]] over `token-scopes`."+ asking for [[step-up-scopes]] over `token-scopes`, with [[step-up-description]] as the `error_description`."[error-response token-scopes {:keys [required-scope description]}](transport/insufficient-scope error-response(step-up-scopes mcp.paths/v2-surface-scopes token-scopes required-scope)- description))+ (step-up-description description)))(defn- handle-tools-call [id params session-id token-scopes request-context](let [tool-name (:name params)@@ -164,27 +172,34 @@"When visualize_query is available, use it for any request to show, chart, plot, or visualize data (pass a ""query_handle from execute_query or execute_sql when you have one); don't draw the chart yourself.\n""Teaching errors embed the relevant contract, so a failed call always names its fix.\n"- ;; Must match what the consent screen shows: one Authorize button, no per-permission choices. Given less, the- ;; model invents a step asking the user to tick the permission.- "A permission failure may reach you rewritten by your client. If a Metabase tool call or resource read fails "- "with a message about re-authorization, an expired token, \"insufficient scope\", \"Unauthorized\", or just "- "\"tool execution failed\", the usual cause is a missing permission on this connection, not an expired login. "- "Tell the user which tool or resource failed and which permission it needs: for a tool, use the name in the "- "\"Requires the ... permission\" sentence that starts the tool's description, which is how Metabase's consent "- "screen names it. To grant it, the user reconnects Metabase in their client and clicks Authorize on the "- "consent screen, e.g. in Claude Code: /mcp, select this server, Re-authenticate; in Codex: "- "`codex mcp login <server>`, then start a new session. The consent screen has no per-permission choices, so "- "don't ask the user to check or select anything. Don't retry the tool until the user says they have "- "reconnected."))+ ;; Must match what the consent screen shows: a tick box per permission, every optional one unticked, so the+ ;; user has to re-tick what the connection already had. Naming this connection's permissions here backfired:+ ;; with that list in context the model sometimes refused a write without calling the tool, and a call that+ ;; never 403s leaves the client no step-up scope to ask for. The unfiltered tool list needs saying because+ ;; a scope-filtered list is the conventional design and the protocol has no field to signal ours: asked what+ ;; this connection could do, a model read the roster as a grant and answered with scopes it did not hold.+ "Every tool is listed whatever this connection holds, so the list says nothing about its permissions; only a "+ "failed call reveals a missing one.\n"+ "An auth error (\"re-authorization\", \"expired token\", \"insufficient scope\", \"Unauthorized\", \"tool "+ "execution failed\") usually means a missing permission, not an expired login. When a tool call or resource "+ "read needs a permission this connection lacks, tell the user which tool or resource failed, which permission "+ "it needs (each tool's description starts with the permission it requires), and why, and ask whether to grant "+ "it. Some clients open the consent screen themselves; otherwise the user reconnects (Claude Code: /mcp, "+ "select this server, Re-authenticate; "+ "Codex: `codex mcp login <server>`, then a new session). The permission is unticked on the consent screen; "+ "tell them to tick it. Every other permission also starts unticked, so tell them to re-tick the ones they "+ "want to keep. Retry once they have reconnected."))(def ^:private default-ask-scopes"The `scope` of the 401 challenge, which an uninstructed client requests on first connect. Every scope here must beinside the OAuth server's default grant ceiling.";; Every tool is listed whatever the token holds. A call needing a scope the token lacks is answered with a 403- ;; `insufficient_scope` naming the union of held and required scopes, and each tool declares its scope in- ;; `securitySchemes`, so a client steps up to the rest of the surface rather than being granted it up front. The- ;; surface still accepts all of [[metabase.mcp.paths/v2-surface-scopes]]. A scope outside the ceiling is answered- ;; "Invalid scope" for a client that follows the challenge.+ ;; `insufficient_scope` naming the union of held and required scopes, so a client steps up to the rest of the surface+ ;; rather than being granted it up front. Each tool also declares its scope in `securitySchemes`, which is draft+ ;; SEP-1488 (modelcontextprotocol issue 1488) and supported by ChatGPT; it is not in MCP 2025-03-26, the version this+ ;; server reports, so other clients learn the missing scope from the 403. The surface still accepts all of+ ;; [[metabase.mcp.paths/v2-surface-scopes]]. A scope outside the ceiling is answered "Invalid scope" for a client that+ ;; follows the challenge.mcp.paths/v2-baseline-scopes)(def ^{:arglists '([request respond raise])} handlerdiff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.cljindex 55494e1edda..260aef019e4 100644--- a/src/metabase/metabot/scope.clj+++ b/src/metabase/metabot/scope.clj@@ -158,7 +158,7 @@;; Resource(api-scope/defscope agent-resource-read "agent:resource:read"- (deferred-tru "View resources"))+ (deferred-tru "Read MCP resources"));; Todo(api-scope/defscope agent-todo-read "agent:todo:read"diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljindex e0fc6db26b9..e758d27e311 100644--- a/src/metabase/oauth_server/api/oauth.clj+++ b/src/metabase/oauth_server/api/oauth.clj@@ -7,11 +7,13 @@[clojure.string :as str][metabase.api-scope.core :as api-scope][metabase.api.macros :as api.macros]+ [metabase.mcp.core :as mcp][metabase.oauth-server.consent-page :as consent-page][metabase.oauth-server.core :as oauth-server][metabase.oauth-server.models.oauth-client-event :as client-event][metabase.oauth-server.settings :as oauth-settings][metabase.request.core :as request]+ [metabase.server.middleware.security :as mw.security][metabase.system.core :as system][metabase.util.log :as log][metabase.util.malli.schema :as ms]@@ -99,22 +101,60 @@(str (subs s 0 (- max-len 3)) "...")s))+(def ^:private consent-scope-order+ "The MCP v2 scopes in the order the consent page lists them, least to most harmful."+ ["agent:resource:read"+ "agent:content:read"+ "agent:query:run"+ "agent:content:write"+ "agent:sql:run"+ "agent:delivery:write"])++(defn- scope-tokens+ "Split a space-separated OAuth `scope` value into its distinct scope strings, in first-seen order. Returns nil when+ blank.++ Deduplicating here is what keeps a repeated scope out of the granted token: the decision filters the grant from this+ list, so a duplicate left in it would be stored twice."+ [scope-param]+ (some-> scope-param str str/trim not-empty (str/split #"\s+") distinct vec))+(defn- requested-scope-descriptions- "Turn the space-separated OAuth `scope` value into a vector of `{:scope :description}` maps for the- consent page, so the user sees exactly what the client is asking for. Falls back to the raw scope- string when a scope has no registered human-readable description. Returns nil when no scope was- requested."+ "Turn the space-separated OAuth `scope` value into a vector of `{:scope :description :full-access? :locked?}` maps for+ the consent page, so the user sees exactly what the client is asking for. Scopes in [[consent-scope-order]] come+ first in that order, then the rest in request order. `:locked?` marks an MCP baseline scope, which is always granted;+ every other scope starts unticked. Falls back to the raw scope string when a scope has no registered human-readable+ description. Returns nil when no scope was requested."[scope-param]- (when-let [scope-str (some-> scope-param str not-empty)]- (->> (str/split scope-str #"\s+")- (remove str/blank?)- distinct- (mapv (fn [s]- {:scope s- :description (or (some-> (api-scope/scope-description s) str) s)- ;; Flag the broad first-party grant so the consent page can warn about it without- ;; hardcoding the scope string in the view.- :full-access? (= s oauth-server/full-access-scope)})))))+ (when-let [scopes (scope-tokens scope-param)]+ (let [rank (zipmap consent-scope-order (range))+ baseline (set (mcp/v2-baseline-scopes))]+ (->> scopes+ ;; `sort-by` is stable, so unranked scopes keep their request order+ (sort-by #(rank % (count rank)))+ (mapv (fn [s]+ {:scope s+ :description (or (some-> (api-scope/scope-description s) str) s)+ ;; Flag the broad first-party grant so the consent page can warn about it without+ ;; hardcoding the scope string in the view.+ :full-access? (= s oauth-server/full-access-scope)+ :locked? (contains? baseline s)}))))))++(defn- form-values+ "A form field that may repeat, as a vector: Ring decodes one value to a string and several to a vector."+ [v]+ (cond+ (nil? v) []+ (sequential? v) (vec v)+ :else [v]))++(defn- granted-scopes+ "The scopes an approved decision grants, in offered order: every `offered` scope the user `chosen`, plus every+ offered MCP baseline scope, which the consent page shows as always granted. Returns nil when `chosen` names a scope+ that was not offered."+ [offered chosen]+ (when (every? (set offered) chosen)+ (filterv (some-fn (set chosen) (set (mcp/v2-baseline-scopes))) offered)));;; ------------------------------------------- Error descriptions ------------------------------------------------@@ -386,8 +426,13 @@Applied by both the consent page and the decision endpoint. The consent form's signature proves only that theform 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."+ can re-sign anything. The endpoint that issues the code has to apply these rules itself.++ Never returns a blank scope. The decision endpoint leans on that: it answers a nil grant with 403+ `params_tampered`, which is only the right status while the sole way to reach it is a choice naming an unoffered+ scope. A blank offer would make an honest approval look like tampering."[parsed]+ {:post [(not (str/blank? %))]}(let [;; A scope-less request would otherwise mint a token with no scopes._ (when (str/blank? (:scope parsed))(throw (ex-info "no scope was requested"@@ -431,15 +476,17 @@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})}+ (-> {:status 200+ :headers {"Content-Type" "text/html; charset=utf-8"}+ ;; the page's inline script is nonce'd, so it needs the nonce in `script-src`+ mw.security/script-nonce-response-key true+ :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]}@@ -493,6 +540,7 @@[:response_type {:optional true} [:maybe :string]][:redirect_uri {:optional true} [:maybe :string]][:scope {:optional true} [:maybe :string]]+ [:granted_scope {:optional true} [:maybe [:or :string [:sequential :string]]]][:state {:optional true} [:maybe :string]][:code_challenge {:optional true} [:maybe :string]][:code_challenge_method {:optional true} [:maybe :string]]@@ -521,21 +569,42 @@(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 (re-matches #"[a-fA-F0-9]+" params-sig))- (odd? (count params-sig))- (not (verify-oauth-params-signature cookie-token parsed-params params-sig)))+ parsed-params (select-keys parsed oauth-param-keys)+ signature-ok? (and (not (str/blank? params-sig))+ (some? (re-matches #"[a-fA-F0-9]+" params-sig))+ (even? (count params-sig))+ (verify-oauth-params-signature cookie-token parsed-params params-sig))+ ;; 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. Evaluated only+ ;; once the signature holds, so a forged form is still answered `params_tampered`.+ offered (when (and signature-ok? approved)+ (scope-tokens (scope-to-grant parsed)))+ ;; The offered scope is what the consent page showed; the user's ticked boxes are+ ;; unsigned, so they may only narrow the offer.+ granted (when (and signature-ok? approved)+ (granted-scopes offered (form-values (:granted_scope body))))]+ (cond+ (or (not signature-ok?)+ ;; A choice naming a scope the consent page never offered.+ (and approved (nil? granted))){:status 403:headers {"Content-Type" "application/json"}:body {:error "params_tampered"}}- ;; 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.++ ;; Nothing granted would mint a token that can do nothing.+ (and approved (empty? granted))+ {:status 400+ :headers {"Content-Type" "application/json"}+ :body {:error "invalid_request"+ :error_description "No scope was selected."}}++ :else(redirect-authorization-decision provider(cond-> parsed- approved (assoc :scope (scope-to-grant parsed)))+ approved+ (assoc :scope (str/join " " granted)))approvedrequest)))(catch ExceptionInfo ediff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.cljindex c1e7fe3ec2e..7856316d9eb 100644--- a/src/metabase/oauth_server/consent_page.clj+++ b/src/metabase/oauth_server/consent_page.clj@@ -77,29 +77,115 @@:default-logo? (= logo-url default-logo-url):brand-color (sanitize-css-color (get colors "brand"))}))+(defn- full-access-warning+ [client-name]+ [:div.warning+ [:span.mark "!"]+ [:span "This grants " [:strong "complete access to your account"] " — anything you can do, "+ (or client-name "this application") " can do, including reading and changing all data you "+ "can reach. Only approve it for a tool you trust and control."]])+(defn- render-scope-list- "Render the requested OAuth scopes as a hiccup list so the user sees exactly what they're granting.- `scopes` is a vector of `{:scope <string> :description <localized-string-or-raw-scope>}` maps.+ "Render the requested OAuth scopes as a hiccup list of checkboxes named `granted_scope`, so the user sees exactly+ what they're granting and picks which of it to grant. `scopes` is a vector of+ `{:scope <string> :description <localized-string-or-raw-scope> :full-access? <bool> :locked? <bool>}` maps, rendered+ in order.++ A `:locked?` scope is ticked, disabled, and labelled as always granted; every other scope starts unticked and can be+ ticked. A `:full-access?` scope carries the full-access warning in its own row.Shows the human description and the raw scope string: the description is readable, the raw stringis the precise, unambiguous grant the token will carry — both matter when approving a broad scope.When a scope has no registered description (it falls back to the raw string) the raw span isomitted to avoid showing the same value twice."- [scopes]+ [scopes client-name](when (seq scopes)[:ul.scopes- (for [{:keys [scope description full-access?]} scopes]- [:li (when full-access? {:class "full"})- [:span {:class (if full-access? "dot full" "dot")}]- (if full-access? [:strong description] [:span description])- (when (not= description scope)- [:span.raw scope])])]))+ (for [{:keys [scope description full-access? locked?]} scopes]+ [:li {:class (not-empty (str/join " " (cond-> [] full-access? (conj "full") locked? (conj "locked"))))}+ [:label+ [:input (cond-> {:type "checkbox" :name "granted_scope" :value scope}+ locked? (assoc :checked true :disabled true))]+ [:span.text+ (if full-access? [:strong description] [:span description])+ (when (not= description scope)+ [:span.raw scope])]+ (when locked?+ [:span.always "Always granted"])]+ (when full-access?+ (full-access-warning client-name))])]))++(def ^:private consent-form-script+ "Progressive enhancement for the consent form; the server enforces everything it does. Keeps Authorize disabled while+ no scope checkbox is ticked (a locked, always-granted one counts), and debounces the decision: on submit it shows a+ spinner on the clicked button and disables both, re-enabling them if the page is restored from the bfcache."+ "(function () {+ var form = document.getElementById('consent-form');+ if (!form) { return; }+ var buttons = form.querySelectorAll('button[name=\"approved\"]');+ var allow = form.querySelector('button.allow');+ var boxes = form.querySelectorAll('input[type=\"checkbox\"]');+ var submitting = false;+ var lastClicked = null;++ function syncAllow() {+ if (submitting || !allow || boxes.length === 0) { return; }+ var anyTicked = false;+ for (var i = 0; i < boxes.length; i++) {+ if (boxes[i].checked) { anyTicked = true; }+ }+ allow.disabled = !anyTicked;+ }++ function removeDecisionInput() {+ var input = form.querySelector('input[type=\"hidden\"][name=\"approved\"]');+ if (input) { input.parentNode.removeChild(input); }+ }++ for (var i = 0; i < buttons.length; i++) {+ buttons[i].addEventListener('click', function () { lastClicked = this; });+ }++ form.addEventListener('change', syncAllow);++ form.addEventListener('submit', function (event) {+ if (submitting) { event.preventDefault(); return; }+ var submitter = event.submitter || lastClicked;+ if (!submitter || submitter.name !== 'approved') { return; }+ submitting = true;+ // A disabled button is left out of the submitted form, so carry its decision in a hidden input.+ removeDecisionInput();+ var decision = document.createElement('input');+ decision.type = 'hidden';+ decision.name = 'approved';+ decision.value = submitter.value;+ form.appendChild(decision);+ submitter.classList.add('loading');+ submitter.setAttribute('aria-busy', 'true');+ for (var i = 0; i < buttons.length; i++) { buttons[i].disabled = true; }+ });++ window.addEventListener('pageshow', function (event) {+ if (!event.persisted) { return; }+ submitting = false;+ removeDecisionInput();+ for (var i = 0; i < buttons.length; i++) {+ buttons[i].disabled = false;+ buttons[i].classList.remove('loading');+ buttons[i].removeAttribute('aria-busy');+ }+ syncAllow();+ });++ syncAllow();+})();")(defn render-consent-page"Render a server-side HTML consent page for the OAuth authorization flow.- `scopes` is a vector of `{:scope :description}` maps describing what the client is requesting; it is- shown to the user so a broad grant (e.g. full account access) is never approved blindly."+ `scopes` is a vector of `{:scope :description :full-access? :locked?}` maps describing what the client is+ requesting, in display order; each is shown as a `granted_scope` checkbox (see [[render-scope-list]]) so a broad+ grant (e.g. full account access) is never approved blindly."[{:keys [client-name oauth-params nonce csrf-token params-sig scopes]}](let [{:keys [font-family logo-url default-logo? brand-color]} (appearance-settings)css-font-family (css-escape-font-name font-family)]@@ -128,14 +214,18 @@.subtitle { text-align: center; font-size: 0.875rem; line-height: 1.5; color: #696e7b; margin-bottom: 1.5rem; }.scopes { list-style: none; margin: 0 0 1.5rem; padding: 0;border: 1px solid #f0f0f0; border-radius: 8px; }- .scopes li { display: flex; align-items: baseline; gap: 0.5rem;- padding: 0.75rem 1rem; font-size: 0.875rem; color: #4c5773; }+ .scopes li { padding: 0.75rem 1rem; font-size: 0.875rem; color: #4c5773; }.scopes li + li { border-top: 1px solid #f0f0f0; }- .scopes .dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%;- background: " brand-color "; transform: translateY(-1px); }+ .scopes label { display: flex; align-items: baseline; gap: 0.5rem; cursor: pointer; }+ .scopes input { flex: 0 0 auto; margin: 0; accent-color: " brand-color ";+ transform: translateY(2px); cursor: pointer; }+ .scopes .text { flex: 1 1 auto; display: flex; flex-wrap: wrap; column-gap: 0.5rem; }.scopes .raw { font-family: monospace; font-size: 0.75rem; color: #949aab; }+ .scopes li.locked label, .scopes li.locked input { cursor: default; }+ .scopes .always { flex: 0 0 auto; font-size: 0.75rem; color: #949aab; white-space: nowrap; }.scopes li.full strong { color: #2e353b; }- .scopes .dot.full { background: #e35a4c; width: 8px; height: 8px; }+ .scopes li.full input { accent-color: #e35a4c; }+ .scopes li .warning { margin: 0.625rem 0 0; }.warning { display: flex; gap: 0.5rem; align-items: flex-start;background: #fdf3f2; border: 1px solid #f7d3cf; border-radius: 8px;padding: 0.75rem 1rem; margin-bottom: 1.5rem;@@ -148,9 +238,16 @@font-family: inherit; cursor: pointer;transition: background-color 0.15s ease, border-color 0.15s ease, filter 0.15s ease; }.allow { background: " brand-color "; color: #fff; border: 1px solid " brand-color "; }- .allow:hover { filter: brightness(0.9); }+ .allow:hover:not(:disabled) { filter: brightness(0.9); }.deny { background: #fff; color: #4c5773; border: 1px solid #ddd; }- .deny:hover { background: #f9fbfc; border-color: #ccc; }"))]]+ .deny:hover:not(:disabled) { background: #f9fbfc; border-color: #ccc; }+ button:disabled { cursor: default; opacity: 0.55; }+ button.loading:disabled { opacity: 1; }+ button.loading::before { content: ''; display: inline-block; width: 0.875em; height: 0.875em;+ margin-right: 0.5em; vertical-align: -0.125em; border-radius: 50%;+ border: 2px solid; border-right-color: transparent;+ animation: consent-spin 0.7s linear infinite; }+ @keyframes consent-spin { to { transform: rotate(360deg); } }"))]][:body[:div.consent[:div.logo@@ -160,18 +257,12 @@[:h1 "Authorize " (or client-name "Unknown Application") "?"][:p.subtitle (or client-name "This application") " is requesting access to "[:strong (appearance/application-name)] " on your behalf:"]- (when (some :full-access? scopes)- [:div.warning- [:span.mark "!"]- [:span "This grants " [:strong "complete access to your account"] " — anything you can do, "- (or client-name "this application") " can do, including reading and changing all data you "- "can reach. Only approve it for a tool you trust and control."]])- (render-scope-list scopes)- (when-let [redirect-host (some-> (:redirect_uri oauth-params) not-empty (java.net.URI.) (.getHost))]- [:p.destination "Redirects to " [:strong redirect-host]]);; Absolute action: a root-relative path would drop the subpath when Metabase is hosted;; under one (site-url like https://example.com/metabase).- [:form {:method "POST" :action (absolute-url "/oauth/authorize/decision")}+ [:form {:id "consent-form" :method "POST" :action (absolute-url "/oauth/authorize/decision")}+ (render-scope-list scopes client-name)+ (when-let [redirect-host (some-> (:redirect_uri oauth-params) not-empty (java.net.URI.) (.getHost))]+ [:p.destination "Redirects to " [:strong redirect-host]])[:input {:type "hidden" :name "csrf_token" :value csrf-token}][:input {:type "hidden" :name "params_sig" :value params-sig}](for [[k v] oauth-params@@ -180,4 +271,5 @@[:input {:type "hidden" :name (name k) :value v}])[:div.actions[:button.deny {:type "submit" :name "approved" :value "false"} "Cancel"]- [:button.allow {:type "submit" :name "approved" :value "true"} "Authorize"]]]]]]))))+ [:button.allow {:type "submit" :name "approved" :value "true"} "Authorize"]]]]+ [:script {:nonce nonce} (h/raw consent-form-script)]]]))))diff --git a/test/metabase/mcp/v2/api_test.clj b/test/metabase/mcp/v2/api_test.cljindex c11ed1967d4..df147a3a9d6 100644--- a/test/metabase/mcp/v2/api_test.clj+++ b/test/metabase/mcp/v2/api_test.clj@@ -127,23 +127,39 @@(testing "the cause is a missing permission, not an expired login"(is (re-find #"(?i)missing permission" instructions))(is (re-find #"(?i)not an expired login" instructions)))+ (testing "GHY-4555: the roster is not a grant. Every tool is listed whatever the token holds, but a scope-filtered+ list is the conventional design and nothing on the wire signals ours, so a model asked what the+ connection could do read the roster as a grant and named scopes it did not hold"+ (is (re-find #"(?i)every tool is listed whatever this connection holds" instructions))+ (is (re-find #"(?i)says nothing about its permissions" instructions))+ (is (re-find #"(?i)only a failed call reveals a missing one" instructions)))(testing "a resource read is refused the same way as a tool call, so the guidance covers both"(is (re-find #"(?i)tool call or resource read" instructions)))(testing "the model names the tool and the permission, as the consent screen names it"(is (re-find #"(?i)which tool" instructions))(is (re-find #"(?i)which permission" instructions))+ (is (re-find #"(?i)and why" instructions))(is (re-find #"(?i)consent screen" instructions))(testing "and finds that name where the description puts it: first, ahead of any client truncation"- (is (re-find #"(?i)sentence that starts the tool's description" instructions))+ (is (re-find #"(?i)each tool's description starts with the permission it requires" instructions))(is (not (re-find #"(?i)ends the tool's description" instructions)))))(testing "the user reconnects, with steps for common clients"(is (re-find #"(?i)re-?authenticate|reconnect" instructions))(is (str/includes? instructions "/mcp"))(is (str/includes? instructions "codex mcp login")))- (testing "no retry until the user has reconnected"- (is (re-find #"(?i)(don't|do not) retry" instructions)))- (testing "the consent screen is all-or-nothing, so the model must not invent a step to tick a permission"- (is (re-find #"(?i)no per-permission" instructions)))+ (testing "the retry waits until the user has reconnected"+ (is (re-find #"(?i)retry once they have reconnected" instructions))+ (is (not (re-find #"(?i)(don't|do not) retry" instructions))))+ (testing "GHY-4555: the consent screen shows a newly requested permission unticked, so the model tells the user+ to tick it, and asks rather than sending them through consent unprompted"+ (is (not (re-find #"(?i)no per-permission" instructions)))+ (is (re-find #"(?i)unticked" instructions))+ (is (re-find #"(?i)tell them to tick it" instructions))+ (is (re-find #"(?i)ask whether to grant it" instructions))+ (testing "and that every other permission starts unticked too, so a step-up doesn't silently drop one the+ connection already had"+ (is (re-find #"(?i)every other permission also starts unticked" instructions))+ (is (re-find #"(?i)re-tick the ones they want to keep" instructions))))(testing "the skills guidance is kept"(is (re-find #"learn\(\)" instructions))))))@@ -815,6 +831,23 @@(def ^:private metadata-url"http://localhost:3000/.well-known/oauth-protected-resource")+(def ^:private unticked-note+ "What every `insufficient_scope` `error_description` ends with."+ ". The user must tick this permission on the consent screen.")++(deftest ^:parallel step-up-description-test+ (testing "GHY-4555: a step-up opens a consent screen where the missing permission is unticked, so a client that shows+ the error_description tells the user to tick it; the note covers a permission that was never granted and one+ that was unticked and removed, so it does not claim the permission starts unticked; the text stays inside+ RFC 6750's error_description characters (printable ASCII without quote or backslash)"+ (is (= (str "execute_sql requires agent:sql:run (Write and run its own raw SQL on your connected databases)"+ unticked-note)+ (#'v2.api/step-up-description+ "execute_sql requires agent:sql:run (Write and run its own raw SQL on your connected databases)")))+ (is (not (str/includes? unticked-note "starts unticked"))+ "a removed permission does not start unticked, it was ticked and then cleared")+ (is (re-matches #"[\x20\x21\x23-\x5B\x5D-\x7E]+" unticked-note))))+(deftest scope-denial-is-a-403-insufficient-scope-challenge-test(testing "GHY-4543: a scope denial must be a real HTTP 403 carrying an `insufficient_scope` WWW-Authenticatechallenge (MCP authorization spec, runtime insufficient scope). Claude Code only records a step-up@@ -832,7 +865,7 @@"scope=\"agent:content:read agent:sql:run\", ""resource_metadata=\"" metadata-url "/api/metabase-mcp\", ""error_description=\"execute_sql requires agent:sql:run "- "(" (registry/english-scope-label "agent:sql:run") ")\"")+ "(" (registry/english-scope-label "agent:sql:run") ")" unticked-note "\"")(get-in response [:headers "WWW-Authenticate"]))"scope is the held v2 scopes plus the required one; the legacy non-v2 scope is not echoed")(testing "the body is still the JSON-RPC error, for clients that read it"@@ -889,7 +922,7 @@"scope=\"agent:content:read agent:query:run agent:delivery:write\", ""resource_metadata=\"" metadata-url "/api/metabase-mcp\", ""error_description=\"alert_write requires agent:query:run "- "(" (registry/english-scope-label "agent:query:run") ")\"")+ "(" (registry/english-scope-label "agent:query:run") ")" unticked-note "\"")(get-in response [:headers "WWW-Authenticate"])))(is (= -32600 (get-in response [:body :error :code])))(is (re-find #"requires the agent:query:run scope" (get-in response [:body :error :message])))@@ -954,7 +987,7 @@"scope=\"agent:content:read agent:query:run agent:sql:run agent:resource:read\", ""resource_metadata=\"" metadata-url "/api/metabase-mcp\", ""error_description=\"execute_sql requires agent:sql:run "- "(" (registry/english-scope-label "agent:sql:run") ")\"")+ "(" (registry/english-scope-label "agent:sql:run") ")" unticked-note "\"")(get-in response [:headers "WWW-Authenticate"])))))))))))(deftest data-resource-read-without-its-scope-is-a-403-insufficient-scope-challenge-test@@ -975,7 +1008,7 @@"scope=\"agent:content:read agent:resource:read\", ""resource_metadata=\"" metadata-url "/api/metabase-mcp\", ""error_description=\"catalog://metabase/fields requires agent:resource:read "- "(" (registry/english-scope-label "agent:resource:read") ")\"")+ "(" (registry/english-scope-label "agent:resource:read") ")" unticked-note "\"")(get-in response [:headers "WWW-Authenticate"])))(testing "the body is the JSON-RPC error, with no transport-internal marker"(is (= #{:jsonrpc :id :error} (set (keys (:body response)))))@@ -1139,6 +1172,35 @@(is (nil? (get-in response [:headers "WWW-Authenticate"])))(is (= "served" (-> response :body :result :content first :text))))))))+(def ^:private scope-failure-paragraph+ (str "An auth error (\"re-authorization\", \"expired token\", \"insufficient scope\", \"Unauthorized\", \"tool "+ "execution failed\") usually means a missing permission, not an expired login. When a tool call or resource "+ "read needs a permission this connection lacks, tell the user which tool or resource failed, which permission "+ "it needs (each tool's description starts with the permission it requires), and why, and ask whether to grant "+ "it. Some clients open the consent screen themselves; otherwise the user reconnects (Claude Code: /mcp, "+ "select this server, Re-authenticate; "+ "Codex: `codex mcp login <server>`, then a new session). The permission is unticked on the consent screen; "+ "tell them to tick it. Every other permission also starts unticked, so tell them to re-tick the ones they "+ "want to keep. Retry once they have reconnected."))++(deftest initialize-instructions-say-each-thing-once-test+ (testing "GHY-4555: every connection pays for the instructions in tokens, so the scope-failure guidance is one+ paragraph, the same for every caller, saying each thing once"+ (let [[_ response] (initialize!)+ instructions (get-in response [:body :result :instructions])]+ (is (str/ends-with? instructions (str "\n" scope-failure-paragraph)) instructions)+ (doseq [[phrase most] [["ask whether to grant it" 1] ["retry" 1] ["the usual cause is" 0] ["e.g." 0]]]+ (testing phrase+ (is (>= most (count (re-seq (re-pattern (str "(?i)" (java.util.regex.Pattern/quote phrase)))+ instructions)))))))))++(deftest initialize-instructions-fit-claude-code-truncation-test+ (testing "GHY-4555: Claude Code truncates server instructions at 2048 characters, which cut off the end of the+ scope-failure guidance, so the whole string has to fit"+ (let [[_ response] (initialize!)+ instructions (get-in response [:body :result :instructions])]+ (is (<= (count instructions) 2048) (str (count instructions) " characters")))))+;;; ------------------------------------- Native saves and the SQL scope -------------------------------------------(def ^:private content-write-scopes@@ -1152,7 +1214,7 @@"scope=\"agent:content:read agent:content:write agent:query:run agent:sql:run\", ""resource_metadata=\"" metadata-url "/api/metabase-mcp\", ""error_description=\"" tool-name " requires agent:sql:run "- "(" (registry/english-scope-label "agent:sql:run") ")\""))+ "(" (registry/english-scope-label "agent:sql:run") ")" unticked-note "\""))(deftest native-source-scope-denial-is-a-403-insufficient-scope-challenge-test(testing "GHY-4543: question_write and transform_write check agent:sql:run inside the handler, once the sourcediff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljindex 434c02dc481..1b06b9034a7 100644--- a/test/metabase/oauth_server/api_test.clj+++ b/test/metabase/oauth_server/api_test.clj@@ -2,6 +2,7 @@(:require[clojure.string :as str][clojure.test :refer [deftest is testing use-fixtures]]+ [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]@@ -554,6 +555,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -650,6 +652,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -688,6 +691,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state "test-state"}302:csrf-cookie (extract-csrf-cookie consent-resp))))@@ -865,6 +869,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state "test-state"}302:csrf-cookie csrf-cookie)@@ -1075,6 +1080,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state "test-state"}extra-params)302@@ -1323,6 +1329,7 @@:redirect_uri "https://example.com/callback":response_type "code":scope "agent:content:read"+ :granted_scope "agent:content:read":state state}302:csrf-cookie csrf-cookie)@@ -1887,52 +1894,86 @@#{"agent:content:read" "agent:content:write" "agent:query:run""agent:sql:run" "agent:delivery:write" "agent:resource:read"})+(defn- mcp-resource-uri []+ (str "http://localhost:3000" (mcp/mcp-canonical-path)))++(defn- register-mcp-client!+ "Register a confidential DCR client with `registration` merged into the body. Returns the registration response."+ [registration]+ (register-client! (merge {:redirect_uris ["https://example.com/callback"]+ :client_name "Step-up Client"+ :token_endpoint_auth_method "client_secret_basic"}+ registration)))++(defn- get-mcp-consent-page!+ "GET `/oauth/authorize` as crowberto for `scope` against the canonical MCP resource. Returns the full response,+ whatever its status."+ [client-id scope]+ ;; `/oauth/authorize` answers a stale session with a login 302, which the test client does not+ ;; retry the way it retries a 401. A session cached from an earlier rolled-back transaction would+ ;; turn every authorize below into that redirect, so revalidate it here first.+ (mt/user-http-request :crowberto :get 200 "api/user/current")+ (mt/user-http-request-full-response+ :crowberto :get "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope scope+ :resource (mcp-resource-uri)+ :state "test-state"))++(defn- offered-scopes+ "The offered scopes signed into the consent page in `consent-resp`, in order."+ [consent-resp]+ (some-> (extract-hidden-field "scope" (:body consent-resp)) (str/split #" ")))++(defn- post-mcp-decision!+ "Approve the MCP consent page in `consent-resp`, echoing its signed fields back with `granted` (a seq of scope+ strings, or nil to send no choice) as the user's choice. Returns the full decision response."+ [client-id consent-resp granted expected-status]+ (let [body (:body consent-resp)]+ (form-post-decision!+ :crowberto+ (cond-> {: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 (extract-hidden-field "scope" body)+ :resource (mcp-resource-uri)+ :state "test-state"}+ (seq granted) (assoc :granted_scope (vec granted)))+ expected-status+ :csrf-cookie (extract-csrf-cookie consent-resp))))++(defn- exchange-code!+ "Exchange the authorization code in `decision`'s redirect for tokens. Returns the token response body."+ [{:keys [client_id client_secret]} decision]+ (token-request! {:grant_type "authorization_code"+ :code (extract-query-param (get-in decision [:headers "Location"]) "code")+ :redirect_uri "https://example.com/callback"+ :resource (mcp-resource-uri)}+ :authorization (basic-auth-header client_id client_secret)))+(defn- register-then-authorize-mcp!"Register a confidential DCR client with `registration` merged into the body, then run the whole- authorization-code flow as crowberto for `scope` against the canonical MCP resource. Returns- `{:authorize <consent-page response>, :token <token response or nil>}`; `:token` is nil when the+ authorization-code flow as crowberto for `scope` against the canonical MCP resource, ticking every offered scope.+ Returns `{:authorize <consent-page response>, :token <token response or nil>}`; `:token` is nil when theauthorize request did not reach the consent page."[registration scope]- (let [mcp-uri (str "http://localhost:3000" (mcp/mcp-canonical-path))- {:keys [client_id client_secret]}- (register-client! (merge {:redirect_uris ["https://example.com/callback"]- :client_name "Step-up Client"- :token_endpoint_auth_method "client_secret_basic"}- registration))- ;; `/oauth/authorize` answers a stale session with a login 302, which the test client does not- ;; retry the way it retries a 401. A session cached from an earlier rolled-back transaction would- ;; turn every authorize below into that redirect, so revalidate it here first.- _ (mt/user-http-request :crowberto :get 200 "api/user/current")- consent-resp (mt/user-http-request-full-response- :crowberto :get "oauth/authorize"- :client_id client_id- :redirect_uri "https://example.com/callback"- :response_type "code"- :scope scope- :resource mcp-uri- :state "test-state")- body (:body consent-resp)]+ (let [client (register-mcp-client! registration)+ consent-resp (get-mcp-consent-page! (:client_id client) scope)]{:authorize consent-resp:token (when (= 200 (:status consent-resp))- (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 (extract-hidden-field "scope" body)- :resource mcp-uri- :state "test-state"}- 302- :csrf-cookie (extract-csrf-cookie consent-resp))- code (extract-query-param (get-in decision [:headers "Location"]) "code")]- (token-request! {:grant_type "authorization_code"- :code code- :redirect_uri "https://example.com/callback"- :resource mcp-uri}- :authorization (basic-auth-header client_id client_secret))))}))+ (exchange-code! client (post-mcp-decision! (:client_id client) consent-resp+ (offered-scopes consent-resp) 302)))}))++(defn- token-scope-set [token-response]+ (some-> (:scope token-response) (str/split #" ") set))++(def ^:private v2-baseline-scope-set+ #{"agent:content:read" "agent:query:run" "agent:resource:read"})(deftest registration-scope-does-not-narrow-step-up-test(testing (str "GHY-4543: Claude Code registers with the scope it read from the protected-resource metadata, then "@@ -2033,6 +2074,346 @@(str oauth-server/full-access-scope " agent:content:read"))](is (= 200 (:status response)) (pr-str (:body response))))))))+;;; ---------------------------------------------- Per-scope consent -----------------------------------------------++(def ^:private all-v2-scopes+ (str/join " " (sort v2-scope-set)))++(deftest decision-mints-only-chosen-scopes-test+ (testing (str "GHY-4555: a client requests all six v2 scopes and the user ticks only `agent:content:write`. The "+ "token carries that plus the always-granted baseline, and neither the token response nor the stored "+ "token holds the scopes the user left unticked.")+ (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 [client (register-mcp-client! {})+ consent-resp (get-mcp-consent-page! (:client_id client) all-v2-scopes)+ expected (conj v2-baseline-scope-set "agent:content:write")]+ (is (= v2-scope-set (set (offered-scopes consent-resp))) "the page offers all six")+ (let [token (exchange-code! client (post-mcp-decision! (:client_id client) consent-resp+ ["agent:content:write"] 302))+ stored (:scopes (oauth-server/resolve-access-token (:access_token token)))]+ (testing "the token response `scope` names exactly the granted scopes (RFC 6749 section 3.3)"+ (is (= expected (token-scope-set token))))+ (testing "the stored token carries the same scopes"+ (is (= expected stored))+ (is (not-any? #{"agent:sql:run" "agent:delivery:write"} stored)))))))))++(deftest decision-rejects-choice-outside-offered-scopes-test+ (testing (str "GHY-4555: the signed `scope` is what was offered and the user's choice travels in an unsigned field, "+ "so a choice naming anything outside the offered set is rejected as tampering instead of widening "+ "the grant.")+ (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 [client (register-mcp-client! {})+ consent-resp (get-mcp-consent-page!+ (:client_id client)+ "agent:content:read agent:query:run agent:resource:read agent:content:write")]+ (doseq [granted [["agent:sql:run"]+ ["agent:content:write" "agent:delivery:write"]+ [oauth-server/full-access-scope]+ ["agent:content:write agent:sql:run"]+ [""]]]+ (testing (pr-str granted)+ (let [response (post-mcp-decision! (:client_id client) consent-resp granted 403)]+ (is (= "params_tampered" (get-in response [:body :error])))+ (is (nil? (get-in response [:headers "Location"])) "no code is issued")))))))))++(deftest decision-rejects-empty-grant-test+ (testing (str "GHY-4555: approving with nothing chosen when no baseline scope was offered would mint a token with "+ "no scope. The page disables Authorize in that case, and the server refuses it too.")+ (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 "a non-baseline scope requested without a resource indicator"+ (let [client-id (:client_id (create-test-client! {:scopes ["agent:content:write"]}))+ consent-resp (mt/user-http-request-full-response+ :crowberto :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "agent:content:write"+ :state "test-state")+ consent-body (:body consent-resp)+ 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:write"+ :state "test-state"}+ 400+ :csrf-cookie (extract-csrf-cookie consent-resp))]+ (is (= "invalid_request" (get-in response [:body :error])))+ (is (nil? (get-in response [:headers "Location"])) "no code is issued")))+ (testing "MCP scopes outside the baseline"+ (let [client (register-mcp-client! {})+ consent-resp (get-mcp-consent-page! (:client_id client) "agent:content:write agent:sql:run")+ response (post-mcp-decision! (:client_id client) consent-resp nil 400)]+ (is (= "invalid_request" (get-in response [:body :error])))))))))++(deftest decision-always-grants-offered-baseline-test+ (testing (str "GHY-4555: the baseline scopes are ticked and locked on the page, and a disabled checkbox is not "+ "submitted, so the server grants every offered baseline scope whatever the form sends.")+ (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 "all six offered, nothing chosen: the token carries the baseline"+ (let [client (register-mcp-client! {})+ consent-resp (get-mcp-consent-page! (:client_id client) all-v2-scopes)+ token (exchange-code! client (post-mcp-decision! (:client_id client) consent-resp nil 302))]+ (is (= v2-baseline-scope-set (token-scope-set token)))))+ (testing "only the baseline scopes that were offered are granted"+ (let [client (register-mcp-client! {})+ consent-resp (get-mcp-consent-page! (:client_id client) "agent:query:run agent:content:write")+ token (exchange-code! client (post-mcp-decision! (:client_id client) consent-resp nil 302))]+ (is (= #{"agent:query:run"} (token-scope-set token)))))))))++(deftest reauthorize-offers-declined-scope-again-test+ (testing (str "GHY-4555: a declined scope is not remembered. Re-authorizing the same client offers it again, and "+ "ticking it this time grants it.")+ (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 [client (register-mcp-client! {})+ initial (get-mcp-consent-page! (:client_id client) all-v2-scopes)+ token (exchange-code! client (post-mcp-decision! (:client_id client) initial+ ["agent:content:write"] 302))]+ (is (not (contains? (token-scope-set token) "agent:sql:run")))+ (let [again (get-mcp-consent-page! (:client_id client) all-v2-scopes)]+ (is (= v2-scope-set (set (offered-scopes again))) "the declined scopes are offered again")+ (let [token (exchange-code! client (post-mcp-decision! (:client_id client) again+ ["agent:sql:run"] 302))]+ (is (= (conj v2-baseline-scope-set "agent:sql:run") (token-scope-set token))))))))))++(defn- consent-checkboxes+ "The `{:scope <value> :checked? :disabled?}` of each scope checkbox on the consent page `body`, in page order."+ [body]+ (for [tag (re-seq #"<input[^>]*type=\"checkbox\"[^>]*>" body)]+ {:scope (second (re-find #"value=\"([^\"]*)\"" tag))+ :checked? (boolean (re-find #"\schecked[\s=/>]" tag))+ :disabled? (boolean (re-find #"\sdisabled[\s=/>]" tag))}))++(deftest consent-page-scope-order-test+ (testing (str "GHY-4555: the six v2 scopes are listed least to most harmful whatever order they were requested in, "+ "and any other requested scope follows in request order")+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ ;; a registered non-v2 scope: GHY-4542 drops unregistered scopes before the page is rendered+ (let [not-v2 (first-non-mcp-default-scope)+ requested [not-v2 "agent:delivery:write" "agent:sql:run" oauth-server/full-access-scope+ "agent:content:write" "agent:query:run" "agent:content:read" "agent:resource:read"]+ client-id (:client_id (create-test-client! {:scopes requested}))+ body (:body (mt/user-http-request-full-response+ :crowberto :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope (str/join " " requested)+ :state "test-state"))]+ (is (= ["agent:resource:read" "agent:content:read" "agent:query:run"+ "agent:content:write" "agent:sql:run" "agent:delivery:write"+ not-v2 oauth-server/full-access-scope]+ (map :scope (consent-checkboxes body))))+ (testing "the baseline is ticked and locked; everything else, `mb:full` included, starts unticked"+ (is (= {"agent:resource:read" [true true]+ "agent:content:read" [true true]+ "agent:query:run" [true true]+ "agent:content:write" [false false]+ "agent:sql:run" [false false]+ "agent:delivery:write" [false false]+ not-v2 [false false]+ oauth-server/full-access-scope [false false]}+ (into {} (map (juxt :scope (juxt :checked? :disabled?))) (consent-checkboxes body))))))))))++(deftest consent-scope-order-covers-v2-scopes-test+ (testing "GHY-4555: the consent order ranks exactly the v2 scopes, so a new v2 scope is not silently listed last"+ (is (= (set (mcp/v2-scopes)) (set @#'api.oauth/consent-scope-order)))+ (is (= (count (mcp/v2-scopes)) (count @#'api.oauth/consent-scope-order)))))++(deftest consent-page-opts-into-script-nonce-test+ (testing (str "GHY-4568: the consent page's inline script needs a `script-src` nonce. Dev mode allows "+ "'unsafe-inline' and adds no nonce, so a response that forgot to opt in would work locally and have "+ "its script blocked in production. Outside dev mode, the CSP header's nonce must be the one on the "+ "page's script tag.")+ (with-redefs [config/is-dev? false]+ (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!))+ response (get-consent-page! :crowberto client-id)+ header-nonce (some->> (get-in response [:headers "Content-Security-Policy"])+ (re-find #"script-src[^;]*'nonce-([^']+)'")+ second)+ body-nonce (some->> (:body response)+ (re-find #"<script nonce=\"([^\"]+)\">")+ second)]+ (is (seq header-nonce) "the CSP header's script-src carries a nonce")+ (is (seq body-nonce) "the page has a nonce'd script tag")+ (is (= header-nonce body-nonce))))))))++;;; ------------------------------------------ Unticking a held scope --------------------------------------------++(defn- register-app-client!+ "Register a confidential DCR client named `client-name` whose only redirect is `redirect-uri` and which may use+ refresh tokens. Returns the registration response."+ [client-name redirect-uri]+ (register-client! {:redirect_uris [redirect-uri]+ :client_name client-name+ :grant_types ["authorization_code" "refresh_token"]+ :response_types ["code"]+ :token_endpoint_auth_method "client_secret_basic"}))++(defn- consent-page-at!+ "GET `/oauth/authorize` as `user` for `client-id` redirecting to `redirect-uri`, requesting `scope` (every v2 scope by+ default) against the canonical MCP resource. Returns the full 200 response."+ ([user client-id redirect-uri]+ (consent-page-at! user client-id redirect-uri all-v2-scopes))+ ([user client-id redirect-uri scope]+ ;; see [[get-mcp-consent-page!]] for why the session is revalidated first+ (mt/user-http-request user :get 200 "api/user/current")+ (mt/user-http-request-full-response+ user :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri redirect-uri+ :response_type "code"+ :scope scope+ :resource (mcp-resource-uri)+ :state "test-state")))++(defn- insert-token!+ "Insert a `model` (`:model/OAuthAccessToken` or `:model/OAuthRefreshToken`) row for `user` on `client-id` holding+ `scopes`, live for an hour unless `overrides` say otherwise."+ [model user client-id scopes & {:as overrides}]+ (t2/insert! model (merge {:token (str (random-uuid))+ :user_id (mt/user->id user)+ :client_id client-id+ :scope (vec scopes)+ :expiry (+ (System/currentTimeMillis) (* 60 60 1000))}+ overrides)))++(defn- checkbox-states+ "`scope` -> `[checked? disabled?]` for each scope checkbox on the consent page in `response`."+ [response]+ (into {} (map (juxt :scope (juxt :checked? :disabled?))) (consent-checkboxes (:body response))))++(def ^:private baseline-locked+ {"agent:resource:read" [true true]+ "agent:content:read" [true true]+ "agent:query:run" [true true]})++(deftest consent-page-does-not-pre-tick-held-scopes-test+ (testing (str "GHY-4555: a step-up asks for held plus required scopes, and every non-baseline scope is offered "+ "unticked even when the user already holds it on a live token of the same client. Pre-ticking a held "+ "scope needs to know which connection is stepping up, which the consent page cannot tell (GHY-4627). "+ "The baseline stays ticked and locked.")+ (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"+ held (conj v2-baseline-scope-set "agent:content:write")+ {:keys [client_id]} (register-app-client! "Step-up Client" redirect)]+ (insert-token! :model/OAuthAccessToken :crowberto client_id held)+ (insert-token! :model/OAuthRefreshToken :crowberto client_id held :expiry nil)+ (is (= (merge baseline-locked+ {"agent:content:write" [false false]+ "agent:sql:run" [false false]+ "agent:delivery:write" [false false]})+ (checkbox-states (consent-page-at! :crowberto client_id redirect)))))))))++(defn- authorize-at!+ "Run the consent flow as crowberto for the registered `client` at `redirect-uri`, requesting `scope` and ticking+ exactly `granted`, then exchange the code. Returns the token response."+ [client redirect-uri scope granted]+ (let [consent (consent-page-at! :crowberto (:client_id client) redirect-uri scope)+ body (:body consent)+ decision (form-post-decision!+ :crowberto+ (cond-> {:approved "true"+ :csrf_token (extract-csrf-token-from-consent body)+ :params_sig (extract-params-sig-from-consent body)+ :client_id (:client_id client)+ :redirect_uri redirect-uri+ :response_type "code"+ :scope (extract-hidden-field "scope" body)+ :resource (mcp-resource-uri)+ :state "test-state"}+ (seq granted) (assoc :granted_scope (vec granted)))+ 302+ :csrf-cookie (extract-csrf-cookie consent))]+ (token-request! {:grant_type "authorization_code"+ :code (extract-query-param (get-in decision [:headers "Location"]) "code")+ :redirect_uri redirect-uri+ :resource (mcp-resource-uri)}+ :authorization (basic-auth-header (:client_id client) (:client_secret client)))))++(defn- access-token-scopes+ "The scope set the bearer `token-response`'s access token resolves to, or nil when it no longer resolves."+ [token-response]+ (:scopes (oauth-server/resolve-access-token (:access_token token-response))))++(defn- live-refresh-scopes+ "The scope sets of the unrevoked refresh tokens of `client`."+ [client]+ (set (map (comp set :scope) (t2/select :model/OAuthRefreshToken :client_id (:client_id client) :revoked_at nil))))++(defn- refresh!+ "Refresh `token-response` for `client`. Returns the response body."+ [client token-response]+ (token-request! {:grant_type "refresh_token" :refresh_token (:refresh_token token-response)}+ :authorization (basic-auth-header (:client_id client) (:client_secret client))))++(def ^:private claude-redirect "https://claude.ai/api/mcp/auth_callback")++(deftest untick-leaves-other-live-tokens-alone-test+ (testing (str "GHY-4555: a consent decision governs only the token this authorization mints. Unticking a scope the "+ "same app already holds must not narrow or revoke that app's other live tokens: the authorization code "+ "and the approved event are already persisted when the decision returns, dynamic registration lets "+ "anyone register a client carrying another app's redirect, and a code issued before the untick would "+ "mint the scope back anyway. Taking a granted permission away is a separate flow.")+ (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 [held (conj v2-baseline-scope-set "agent:content:write")+ window-a (register-app-client! "Claude" claude-redirect)+ token-a (authorize-at! window-a claude-redirect all-v2-scopes ["agent:content:write"])+ ;; the Claude connector registers a new client for the step-up, which leaves out content:write+ window-b (register-app-client! "Claude" claude-redirect)+ step-up (str/join " " (conj (sort v2-baseline-scope-set) "agent:content:write" "agent:sql:run"))]+ (is (= held (access-token-scopes token-a)))+ (is (= [false false] (get (checkbox-states (consent-page-at! :crowberto (:client_id window-b)+ claude-redirect step-up))+ "agent:content:write"))+ "content:write is offered, unticked and tickable, so leaving it out narrows this authorization")+ (let [token-b (authorize-at! window-b claude-redirect step-up ["agent:sql:run"])]+ (is (= (conj v2-baseline-scope-set "agent:sql:run") (token-scope-set token-b))+ "the new token carries only what was ticked")+ (testing "the other window's access and refresh tokens keep the unticked scope"+ (is (= held (access-token-scopes token-a)))+ (is (= #{held} (live-refresh-scopes window-a))))+ (testing "and its refresh token still mints it"+ (is (= held (token-scope-set (refresh! window-a token-a)))))))))))++(deftest decision-stores-a-repeated-scope-once-test+ (testing (str "GHY-4555: a client may repeat a scope in its `scope` parameter. The consent page lists it once, and "+ "the grant is filtered from the offered list, so a duplicate left there would be stored twice.")+ (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 [client (register-app-client! "Claude" claude-redirect)+ scope "agent:content:write agent:query:run agent:content:write"+ consent (consent-page-at! :crowberto (:client_id client) claude-redirect scope)+ _ (authorize-at! client claude-redirect scope ["agent:content:write"])+ row (t2/select-one :model/OAuthAccessToken :client_id (:client_id client))]+ (is (= ["agent:query:run" "agent:content:write"]+ (map :scope (consent-checkboxes (:body consent))))+ "the page lists the repeated scope once")+ (is (= ["agent:content:write" "agent:query:run"] (vec (:scope row)))+ "the stored token holds it once"))))))+(deftest registration-disabled-baseline-client-can-step-up-test(testing (str "GHY-4543: Claude Code registers with the baseline scopes and steps up on the same client_id. Turning ""dynamic registration off blocks new clients, but must not turn that step-up into a raw 400 for a "diff --git a/test/metabase/oauth_server/consent_page_test.clj b/test/metabase/oauth_server/consent_page_test.cljindex cb65ad1bac7..77485df4579 100644--- a/test/metabase/oauth_server/consent_page_test.clj+++ b/test/metabase/oauth_server/consent_page_test.clj@@ -154,3 +154,70 @@:full-access? false}])](is (not (re-find #"class=\"warning\"" html)))(is (not (re-find #"complete access to your account" html))))))++(defn- checkbox-tags+ "The `<input type=\"checkbox\">` tags in `html`, in document order."+ [html]+ (re-seq #"<input[^>]*type=\"checkbox\"[^>]*>" html))++(defn- tag-value [tag]+ (second (re-find #"value=\"([^\"]*)\"" tag)))++(defn- tag-has-attribute? [tag attribute]+ (boolean (re-find (re-pattern (str "\\s" attribute "[\\s=/>]")) tag)))++(def ^:private checkbox-scopes+ [{:scope "agent:content:read" :description "Read content" :locked? true}+ {:scope "agent:sql:run" :description "Run SQL"}+ {:scope "mb:full"+ :description "Full access to Metabase as your user account"+ :full-access? true}])++(deftest consent-page-scope-checkboxes-test+ (testing "GHY-4555: every offered scope gets a checkbox named `granted_scope` whose value is the raw scope, in the given order"+ (let [tags (checkbox-tags (render-with-scopes! checkbox-scopes))]+ (is (= ["agent:content:read" "agent:sql:run" "mb:full"] (map tag-value tags)))+ (is (every? #(re-find #"name=\"granted_scope\"" %) tags))))+ (testing "the checkboxes are inside the form, so ticking one is what gets submitted"+ (let [html (render-with-scopes! checkbox-scopes)]+ (is (< (.indexOf ^String html "<form")+ (.indexOf ^String html "type=\"checkbox\"")+ (.indexOf ^String html "</form>"))))))++(deftest consent-page-locked-baseline-checkbox-test+ (testing "GHY-4555: a locked scope is ticked and disabled, and the page says it is always granted"+ (let [html (render-with-scopes! checkbox-scopes)+ [locked] (checkbox-tags html)]+ (is (tag-has-attribute? locked "checked"))+ (is (tag-has-attribute? locked "disabled"))+ (is (re-find #"(?s)value=\"agent:content:read\"(?:(?!</li>).)*Always granted" html)+ "the note sits in the locked scope's row")))+ (testing "every other scope, including a full-access one, starts unticked and can be ticked"+ (let [[_ sql full] (checkbox-tags (render-with-scopes! checkbox-scopes))]+ (doseq [tag [sql full]]+ (is (not (tag-has-attribute? tag "checked")) tag)+ (is (not (tag-has-attribute? tag "disabled")) tag))))+ (testing "no always-granted note when nothing is locked"+ (is (not (re-find #"Always granted" (render-with-scopes! (rest checkbox-scopes)))))))++(deftest consent-page-full-access-warning-placement-test+ (testing "GHY-4555: the full-access warning sits in the full-access scope's own row, next to its checkbox"+ (let [html (render-with-scopes! checkbox-scopes)]+ (is (re-find #"(?s)value=\"mb:full\"(?:(?!</li>).)*class=\"warning\"" html))+ (is (not (re-find #"(?s)class=\"warning\".*type=\"checkbox\" value=\"mb:full\"" html))+ "the warning does not precede the checkbox it is about"))))++(deftest consent-page-script-test+ (let [html (render-with-scopes! checkbox-scopes)]+ (testing "GHY-4568: the page's inline script carries the CSP nonce, without which a production CSP blocks it"+ (is (re-find #"<script nonce=\"test-nonce\">" html)))+ (testing "GHY-4568: the script debounces the decision and restores the buttons when the page comes back from the bfcache"+ (let [script (second (re-find #"(?s)<script nonce=\"test-nonce\">(.*?)</script>" html))]+ (is (re-find #"addEventListener\('submit'" script))+ (is (re-find #"addEventListener\('pageshow'" script))+ (testing (str "a disabled button is left out of the submitted form, so the clicked button's `approved` value "+ "is copied into a hidden input before the buttons are disabled")+ (is (re-find #"(?s)name = 'approved'.*disabled = true" script)))))+ (testing "without the script the buttons still submit their own `approved` value, and Authorize is not disabled"+ (is (re-find #"<button class=\"deny\" name=\"approved\" type=\"submit\" value=\"false\">" html))+ (is (re-find #"<button class=\"allow\" name=\"approved\" type=\"submit\" value=\"true\">" html)))))