Skip to content

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

mcp-v2.00 prep: extract query guards + pulse helpers; additive shared-ns changes v2 needs (#81244)

bryan79041e2487f5
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index c21d01d18a2..bb32f524720 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1619,7 +1619,8 @@
system
task
tracing
- util}}
+ util}
+ :model-imports #{:model/User}}
osi
{:team "Metabot"
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index adf7a610d29..6c9b2882e41 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -3,6 +3,7 @@
Endpoints are versioned (e.g., /v1/search) and use standard HTTP semantics."
(:require
[clojure.string :as str]
+ [metabase.agent-api.query-guards :as query-guards]
[metabase.agent-api.settings :as agent-api.settings]
[metabase.agent-api.validation :as agent-api.validation]
[metabase.ai-tracing.core :as ait]
@@ -485,55 +486,6 @@
[:handle [:map {:closed true} [:query ms/NonBlankString]]]
[:fresh ::construct-query-request]])
-(defn- reject-native-query!
- "Throw a 400 if `query-map` is a native query anywhere — top-level, nested, or in a join, in either the
- legacy or the MBQL 5 form. Normalizes the payload to MBQL 5 (best-effort) and checks for a native stage
- with [[lib/any-native-stage?]], so the check reads keyword `:lib/type`s regardless of how the JSON was
- decoded; a payload too malformed to normalize is left for the shape and validation checks that follow.
-
- `/v2/query` and `/v1/execute` are gated by the MBQL-execution scopes (`agent:query` /
- `agent:query:execute`), not `agent:sql:execute`. The opaque base64 payloads they accept (a
- query_handle, a continuation token) could carry a native query; allowing it would let a token
- without the SQL-execution scope run raw SQL, defeating the scope split and bypassing the
- execute-sql kill switch. Force native execution onto `/v1/execute-sql`, which is correctly scoped."
- [query-map]
- (when (some-> (u/ignore-exceptions (lib-be/normalize-query query-map))
- not-empty
- lib/any-native-stage?)
- (throw (ex-info "Native queries are not supported here; use execute_sql instead."
- {:status-code 400}))))
-
-(defn- validate-serialized-query!
- "Sanity-check a decoded MBQL query map from a client-reachable base64 payload (query_handle or token).
- Require `:stages` to be a non-empty sequence of maps, and the last-stage `:limit` (if present) an
- integer; otherwise `serialized-query-limit`, `clamp-total-limit`, and `apply-page-to-query` would
- throw on the malformed shape and surface a 500 instead of a clean 400.
- Deep MBQL validation still happens in the QP at execution."
- [query-map]
- (let [stages (:stages query-map)]
- (when-not (and (sequential? stages) (seq stages) (every? map? stages))
- (throw (ex-info "Invalid query: expected a serialized MBQL query with a non-empty :stages of maps."
- {:status-code 400 :query-map query-map})))
- ;; `contains?` (not `when-let`) so an explicit `false`/`nil` limit is caught, not skipped.
- (when (contains? (last stages) :limit)
- (let [limit (:limit (last stages))]
- (when-not (and (int? limit) (pos? limit))
- (throw (ex-info "Invalid query: last-stage :limit must be a positive integer."
- {:status-code 400 :query-map query-map})))))))
-
-(defn- check-token-query-permissions!
- "Re-validate query permissions on the continuation-token path.
-
- The token body is client-supplied and could in principle name a different source table than
- the one the fresh `/v2/query` call was authorized against (a user's data perms can also
- change between pages). The QP middleware would catch this at execution time, but running
- the explicit `api/query-check` first gives a cleaner 403 and avoids spinning up the
- streaming response just to abort."
- [query-map]
- (when-let [table-id (get-in query-map [:stages 0 :source-table])]
- (when (int? table-id)
- (api/query-check :model/Table table-id))))
-
(defn- initial-page-state
"Normalize the three /v2/query entry points into a single {:query :total-limit :page} shape.
@@ -549,16 +501,16 @@
(cond
(:continuation_token body)
(let [{:keys [query pagination]} (decode-continuation-token (:continuation_token body))]
- (reject-native-query! query)
- (validate-serialized-query! query)
+ (query-guards/reject-native-query! query)
+ (query-guards/validate-serialized-query! query)
(let [query (normalize-and-validate-query query)]
- (check-token-query-permissions! query)
+ (query-guards/check-token-query-permissions! query)
{:query query :total-limit (:limit pagination) :page (:page pagination)}))
(string? (:query body))
(let [query (decode-base64-json-map (:query body))]
- (reject-native-query! query)
- (validate-serialized-query! query)
+ (query-guards/reject-native-query! query)
+ (query-guards/validate-serialized-query! query)
(let [query (normalize-and-validate-query query)]
{:query query
:total-limit (clamp-total-limit (serialized-query-limit query))
@@ -670,7 +622,7 @@
_query-params
{encoded-query :query} :- ::execute-query-request]
(let [decoded (-> encoded-query u/decode-base64 json/decode)]
- (reject-native-query! decoded)
+ (query-guards/reject-native-query! decoded)
(let [query (normalize-and-validate-query decoded)]
(qp.streaming/streaming-response [rff :api]
(qp/process-query (prepare-combined-query query) rff)))))
diff --git a/src/metabase/agent_api/query_guards.clj b/src/metabase/agent_api/query_guards.clj
new file mode 100644
index 00000000000..40d2b905606
--- /dev/null
+++ b/src/metabase/agent_api/query_guards.clj
@@ -0,0 +1,221 @@
+(ns metabase.agent-api.query-guards
+ "Guards that every client-reachable serialized MBQL payload must pass before execution on an
+ MBQL-scoped path — whether it arrives as a fresh query, a continuation token, or a stored
+ query handle. Opaque payloads could otherwise smuggle native SQL past the MBQL-only scopes
+ (bypassing the execute-sql kill switch) or retain access the caller has since lost, so the
+ three `!` guards run together at every such entry point.
+
+ Consumers: the agent-api execution paths (`/v2/query`, the handle and continuation-token
+ paths) run these guards directly — their former private copies are deleted — and the v2 MCP
+ tool surface joins them as the stack lands. One deliberate tightening over the old private
+ copy: native detection raw-scans the payload instead of normalize-then-inspect, so a payload
+ too malformed to normalize now fails closed instead of falling through to shape validation.
+
+ [[check-mcp-ui-native-query!]] is the odd one out: it is written to guard the ordinary QP endpoints,
+ which the MCP Apps iframe reaches with a credential that the endpoint scope middleware cannot narrow.
+ It shares the native detection but refuses raw SQL on scope rather than banning it outright. It is
+ NOT yet wired into any endpoint — the `:mcp-ui-credential` it keys on, and the scopes claim it spends,
+ only exist once the v2 core's session rework lands (the next PR in this stack). It is extracted and
+ unit-tested here so that slice can wire it in without also authoring it; until then it is dormant."
+ (:require
+ [clojure.string :as str]
+ [metabase.agent-api.settings :as agent-api.settings]
+ [metabase.api.common :as api]
+ [metabase.api.macros.scope :as scope]
+ [metabase.metabot.scope :as metabot.scope]
+ [metabase.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(defn- token
+ "Normalized name of a keyword or string — namespace kept, lowercased, `_` folded to `-`. nil for anything
+ else, so junk keys and values fall out rather than throwing.
+
+ Everything this guard matches goes through here because the QP normalizer canonicalizes keys
+ case-insensitively and treats `_` and `-` alike: `:SOURCE_QUERY`, `:Source-Query` and `:source-query` all
+ reach the query processor as the same edge. Matching them case-exactly, as this did, let a caller walk
+ straight past the guard by changing the spelling of a key."
+ [x]
+ (when (or (keyword? x) (string? x))
+ (-> x u/qualified-name u/lower-case-en (str/replace \_ \-))))
+
+(defn- tokenized-entries
+ "`node`'s entries as `[token value]` pairs, dropping keys that are neither keyword nor string. A seq rather
+ than a map so a node carrying two spellings of one edge (`:source-query` AND `\"source_query\"`) has both
+ scanned instead of one silently shadowing the other."
+ [node]
+ (keep (fn [[k v]] (when-let [t (token k)] [t v])) node))
+
+(defn native-marker?
+ "True if `node` is a map carrying a native-SQL marker: a `native` query body (the universal signal across
+ legacy and MBQL 5 native forms), a legacy `type: native`, or an MBQL 5 `mbql.stage/native` `lib/type`.
+ A `native` key only counts when its value is non-nil, so an explicit-null key from a JSON round-trip is not
+ a marker.
+
+ Keys and values are matched through [[token]], so keyword and raw-JSON-string forms, casing, and `_`/`-`
+ spelling all collapse together — a payload decoded without keywordizing, or spelled `NATIVE`, trips the
+ guard exactly as `:native` does. A legitimate serialized MBQL query carries none of these."
+ [node]
+ (boolean
+ (and (map? node)
+ (let [entries (tokenized-entries node)]
+ (some (fn [[t v]]
+ (case t
+ "native" (some? v)
+ "type" (= "native" (token v))
+ "lib/type" (= "mbql.stage/native" (token v))
+ false))
+ entries)))))
+
+(def ^:private native-seq-edges
+ "Structural edges whose value is a *sequence* of stage/join maps, as [[token]]s. A native marker may hide in
+ any element, so each is scanned. One token covers every spelling the QP accepts — keyword or raw JSON
+ string, any casing."
+ #{"stages" "joins"})
+
+(def ^:private native-map-edges
+ "Structural edges whose value is a nested stage/query *map*, as [[token]]s. `source_query` and
+ `source-query` normalize to one token: legacy MBQL normalization canonicalizes both, so a snake_case
+ payload still reaches the query processor as a native stage and must trip the guard."
+ #{"query" "source-query"})
+
+(defn native-query?
+ "True if `query-map` (a decoded, client-reachable query) contains native SQL along its
+ query-nesting structure — legacy top-level `:type :native`, a legacy nested `:source-query`'s
+ `:native`, or an MBQL 5 `:mbql.stage/native` stage, including inside joins or nested joins.
+
+ Scans only the structural query-nesting edges ([[native-seq-edges]] and [[native-map-edges]]),
+ not the whole tree: `:expressions` and `:template-tags` are maps keyed by caller-chosen names, so
+ a whole-tree scan would reject a perfectly legitimate query that merely has a column/expression/tag
+ named `native`. The callers are MBQL-only by scope, so a native marker anywhere along the query
+ structure means the payload is smuggling raw SQL, regardless of how it's nested.
+
+ Deliberately does not normalize first. `lib-be/normalize-query` swallows its own failures and returns
+ `{}`, and it needs the referenced database's metadata to resolve, so a normalize-then-inspect check
+ silently reports \"not native\" for anything it cannot parse or look up. Matching raw markers keeps the
+ guard total, independent of app-DB state, and failing closed: a malformed value hanging off a
+ structural edge (e.g. a `:stages` that is a junk map rather than a sequence) is deep-scanned so a
+ buried `:native` marker still trips the guard."
+ [query-map]
+ (letfn [;; A stage/query map is walked only along the structural edges, never into caller-named
+ ;; sub-maps like `:expressions`/`:template-tags`.
+ (scan-map [node]
+ (if-not (map? node)
+ ;; A non-map where a stage/query map belongs (e.g. `{:stages [1]}`) is junk: deep-scan it
+ ;; rather than throw, so the caller's shape validation reports the 400.
+ (deep-scan node)
+ (or (native-marker? node)
+ (boolean (some (fn [[t v]]
+ (cond
+ (native-seq-edges t) (scan-seq-edge v)
+ (native-map-edges t) (scan-map-edge v)
+ :else false))
+ (tokenized-entries node))))))
+ ;; `:stages`/`:joins`: normally a sequence of stage/join maps. A malformed non-sequential
+ ;; value is deep-scanned so junk can't smuggle a marker past the guard.
+ (scan-seq-edge [node]
+ (cond
+ (nil? node) false
+ (sequential? node) (boolean (some scan-map node))
+ :else (deep-scan node)))
+ ;; `:query`/`:source-query`: normally a nested stage/query map. A malformed non-map value
+ ;; is deep-scanned.
+ (scan-map-edge [node]
+ (cond
+ (nil? node) false
+ (map? node) (scan-map node)
+ :else (deep-scan node)))
+ ;; Fail-closed fallback for a malformed sub-tree: match a marker anywhere within it.
+ (deep-scan [node]
+ (boolean (some native-marker? (tree-seq coll? seq node))))]
+ (scan-map query-map)))
+
+(defn reject-native-query!
+ "Throw a 400 if `query-map` is a native query.
+
+ The MBQL execution paths are gated by the MBQL-execution scopes (`agent:query` /
+ `agent:query:execute`), not `agent:sql:execute`. The opaque base64 payloads they accept (a
+ query_handle, a continuation token) could carry a native query — legacy top-level `:type :native`
+ or an MBQL 5 native stage; allowing either would let a token without the SQL-execution scope run
+ raw SQL, defeating the scope split and bypassing the execute-sql kill switch. Force native
+ execution onto the SQL-execution path, which is correctly scoped."
+ [query-map]
+ (when (native-query? query-map)
+ ;; No :query-map in ex-data: the rejection can surface to the client, and echoing the decoded
+ ;; payload back would bloat the response (and land it in error logs) for no diagnostic gain.
+ (throw (ex-info "Native queries are not supported here; use execute_sql instead."
+ {:status-code 400}))))
+
+(defn validate-serialized-query!
+ "Sanity-check a decoded MBQL query map from a client-reachable base64 payload (query_handle or token).
+ Require `:stages` to be a non-empty sequence of maps, and the last-stage `:limit` (if present) a
+ positive integer; otherwise downstream paging arithmetic would throw on the malformed shape and
+ surface a 500 instead of a clean 400.
+ Deep MBQL validation still happens in the QP at execution."
+ [query-map]
+ (let [stages (:stages query-map)]
+ (when-not (and (sequential? stages) (seq stages) (every? map? stages))
+ (throw (ex-info "Invalid query: expected a serialized MBQL query with a non-empty :stages of maps."
+ {:status-code 400 :query-map query-map})))
+ ;; `contains?` (not `when-let`) so an explicit `false`/`nil` limit is caught, not skipped.
+ (when (contains? (last stages) :limit)
+ (let [limit (:limit (last stages))]
+ (when-not (and (int? limit) (pos? limit))
+ (throw (ex-info "Invalid query: last-stage :limit must be a positive integer."
+ {:status-code 400 :query-map query-map})))))))
+
+(defn check-mcp-ui-native-query!
+ "Throw a 403 if `request` is authenticated by an MCP Apps UI credential that may not run `query` as raw SQL.
+
+ NOT yet wired into any endpoint. The `:mcp-ui-credential` request key it dispatches on is attached by
+ the v2 core's session rework (the next PR in this stack); until that lands no request carries it, so this
+ guard is a no-op wherever it might be called. It is authored and unit-tested here so the session-rework
+ slice can drop it into the QP endpoint path without also having to write it. When wiring it in, add it to
+ the QP-endpoint request flow for the routes on the MCP-UI credential's allowlist (the `/api/dataset*`
+ surface), and delete this paragraph.
+
+ The iframe's credential is stamped `::scope/unrestricted` on purpose — none of the routes on its allowlist declare
+ a `:scope`, so a narrower stamp would 403 the iframe at bootstrap. That makes the endpoint scope middleware unable
+ to stop a credential lifted out of the resource HTML from POSTing native SQL to the query endpoints. The minting
+ session's real scopes are meant to ride along on the credential and be spent here: raw SQL needs an SQL-execution
+ scope (`agent:sql:run`, or v1's concrete `agent:sql:execute`) and the `mcp-execute-sql-enabled` kill switch.
+
+ Sequencing: credentials only start carrying a scopes claim with the v2 core's session rework (the
+ next PR in this stack). Until then — and for any credential minted before that deploy — the claim
+ is absent and a native query over a UI credential fails closed, which the test suite codifies.
+
+ Native is refused rather than banned because `execute_sql` handles legitimately hold raw SQL and are visualizable
+ by design. Non-native queries, and requests authenticated any other way, pass straight through."
+ [request query]
+ ;; Keyed on the credential, not on its scopes claim, so a credential carrying no claim is refused rather than
+ ;; waved through — a rolling deploy can hand this node one minted before the claim existed.
+ (when-let [claims (:mcp-ui-credential request)]
+ (when (native-query? query)
+ ;; Scope check first, kill switch second: a client that lacks the SQL-execution scope is refused
+ ;; the same way whether or not the instance has raw SQL enabled. Testing the kill switch first
+ ;; would leak that config bit — an unauthorized caller could tell `mcp-execute-sql-enabled`'s
+ ;; state apart by which 403 message it got back.
+ (let [token-scopes (:token-scopes claims)]
+ (when-not (or (contains? token-scopes ::scope/unrestricted)
+ (scope/scope-satisfied? token-scopes metabot.scope/agent-sql-run)
+ (scope/scope-satisfied? token-scopes metabot.scope/agent-sql-execute))
+ (throw (ex-info (str "Running raw SQL requires the " metabot.scope/agent-sql-run
+ " scope, which this client was not granted.")
+ {:status-code 403}))))
+ (when-not (agent-api.settings/mcp-execute-sql-enabled)
+ (throw (ex-info (str "Running raw SQL is disabled on this instance — an admin can re-enable it "
+ "with the mcp-execute-sql-enabled setting.")
+ {:status-code 403}))))))
+
+(defn check-token-query-permissions!
+ "Re-validate the current user's permissions on a stored or client-supplied query.
+
+ A stage-0 fast path, not the enforcement point: only a numeric first-stage `:source-table` is
+ checked here, and the QP middleware remains the authoritative backstop at execution. The payload
+ could in principle name a different source table than the one the original call was authorized
+ against (a user's data perms can also change between calls); the explicit `api/query-check`
+ gives a cleaner 403 and avoids spinning up the streaming response just to abort."
+ [query-map]
+ (when-let [table-id (get-in query-map [:stages 0 :source-table])]
+ (when (int? table-id)
+ (api/query-check :model/Table table-id))))
diff --git a/src/metabase/channel/urls.clj b/src/metabase/channel/urls.clj
index 6803e592bee..a1f37750e88 100644
--- a/src/metabase/channel/urls.clj
+++ b/src/metabase/channel/urls.clj
@@ -33,6 +33,17 @@
[^Integer id]
(format "/question/%d" id))
+(defn metric-path
+ "Relative frontend path for a metric `Card` with ID, e.g. \"/metric/10\" — metrics have their own
+ page, not the question query builder."
+ [^Integer id]
+ (format "/metric/%d" id))
+
+(defn transform-path
+ "Relative frontend path for a `Transform` with ID, e.g. \"/data-studio/transforms/10\"."
+ [^Integer id]
+ (format "/data-studio/transforms/%d" id))
+
(defn dashboard-url
"Return an appropriate URL for a `Dashboard` with ID.
@@ -112,12 +123,17 @@
[]
(str (site-url) "/unsubscribe"))
+(defn collection-path
+ "Relative frontend path for a `Collection` with ID, or nil for root, e.g. \"/collection/10\"."
+ [collection-id-or-nil]
+ (format "/collection/%s" (or collection-id-or-nil "root")))
+
(defn collection-url
"Return an appropriate URL for a `Collection` with ID or nil for root.
(collection-url 10) -> \"http://localhost:3000/collection/10\"
(collection-url nil) -> \"http://localhost:3000/collection/root\""
[collection-id-or-nil]
- (format "%s/collection/%s" (site-url) (or collection-id-or-nil "root")))
+ (str (site-url) (collection-path collection-id-or-nil)))
(defn tools-caching-details-url
"Return an appropriate URL for linking to caching log details."
diff --git a/src/metabase/mcp/settings.clj b/src/metabase/mcp/settings.clj
index d0bda554492..18f62367f79 100644
--- a/src/metabase/mcp/settings.clj
+++ b/src/metabase/mcp/settings.clj
@@ -56,6 +56,44 @@
:export? true
:doc false)
+(defsetting mcp-v2-disabled-tools
+ (deferred-tru "v2 MCP tool names to disable, stored as CSV. Disabled tools are hidden from tools/list and rejected by tools/call.")
+ :type :csv
+ :default []
+ :visibility :admin
+ :export? false
+ :encryption :no
+ :audit :getter
+ :doc false)
+
+(def ^:private ^:const default-query-handle-ttl-hours
+ "Default for [[mcp-query-handle-ttl-hours]]. One source, referenced by both the setting's `:default`
+ and its getter's fallback, so the two can't drift."
+ 24)
+
+(defsetting mcp-query-handle-ttl-hours
+ (deferred-tru "Hours a stored MCP query handle is kept before the scheduled GC task deletes it.")
+ ;; `:positive-integer` rather than `:integer`: the GC deletes handles created before `now - ttl`,
+ ;; so 0 puts the cutoff at *now* and clears the whole table on the next run, and a negative takes
+ ;; handles minted seconds ago. The type guards the read path too, which a `:setter` cannot —
+ ;; env vars are read straight through `get-raw-value` and never pass through one.
+ :type :positive-integer
+ :default default-query-handle-ttl-hours
+ :visibility :internal
+ :export? false
+ :doc false
+ ;; The read predicate yields nil for a stored non-positive rather than falling back to the
+ ;; default, and the GC would then `(long nil)`. Fall back here, as `attachment-table-row-limit`
+ ;; does for the same reason.
+ :getter (fn []
+ ;; `get-raw-value` rethrows a parse failure (e.g. MB_MCP_QUERY_HANDLE_TTL_HOURS=forever),
+ ;; which would kill the GC task on every run — an unreadable value means the default,
+ ;; same as a non-positive one.
+ (or (try
+ (setting/get-value-of-type :positive-integer :mcp-query-handle-ttl-hours)
+ (catch Exception _ nil))
+ default-query-handle-ttl-hours)))
+
(defsetting mcp-apps-cors-enabled-clients
(deferred-tru "Popular MCP clients enabled for CORS, stored as CSV client keys (e.g. claude, vscode).")
:type :csv
diff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.clj
index 011c9a53f0c..1eb934d9c7f 100644
--- a/src/metabase/metabot/scope.clj
+++ b/src/metabase/metabot/scope.clj
@@ -36,6 +36,30 @@
(api-scope/defscope agent-query-execute "agent:query:execute"
(deferred-tru "Execute queries"))
+;;; ──────────────────────────────────────────────────────────────────
+;;; Rationalized MCP v2 scopes (GHY-4225)
+;;; ──────────────────────────────────────────────────────────────────
+;;
+;; Five scopes a human can actually read on a consent screen, replacing the per-entity leaves below
+;; across the MCP surface. Those leaves stay declared: the agent API and Metabot's own tools still
+;; gate on them, and a token carrying one satisfies no other name, so they can never be renamed
+;; away. (MCP v1's UI resources still register the `agent:viz:mcp-ui:*` leaves too; that surface
+;; goes with v1's retirement.)
+;;
+;; The `agent:` prefix is deliberate — these gate the agent API and Metabot too, not only MCP, so an
+;; `mcp:` prefix would both misdescribe them and strand two prefixes side by side forever.
+
+(api-scope/defscope agent-content-read "agent:content:read"
+ (deferred-tru "See your Metabase content and data structure"))
+(api-scope/defscope agent-content-write "agent:content:write"
+ (deferred-tru "Create, edit and trash Metabase content"))
+(api-scope/defscope agent-query-run "agent:query:run"
+ (deferred-tru "Run queries against your connected databases and see the results"))
+(api-scope/defscope agent-sql-run "agent:sql:run"
+ (deferred-tru "Write and run its own raw SQL on your connected databases"))
+(api-scope/defscope agent-delivery-write "agent:delivery:write"
+ (deferred-tru "Set up scheduled delivery of your data to email addresses and Slack channels it chooses"))
+
;; Question (saved cards via Agent API)
(api-scope/defscope agent-question-create "agent:question:create"
(deferred-tru "Create saved questions"))
@@ -79,6 +103,8 @@
(deferred-tru "Subscribe to dashboard alerts"))
;; Collection
+;; `create` still gates the v1 `create_collection` endpoint; tokens carry the literal string, so it
+;; can never be renamed away. The v2 surface gates on `agent:content:write` instead.
(api-scope/defscope agent-collection-create "agent:collection:create"
(deferred-tru "Create collections"))
@@ -101,12 +127,24 @@
(deferred-tru "Edit charts and visualizations"))
(api-scope/defscope agent-viz-navigate "agent:viz:navigate"
(deferred-tru "Navigate to visualizations"))
+;; Kept explicit (master re-added them after GHY-4225): the v1 MCP UI resources still register these
+;; literal strings and they carry their own consent-screen descriptions. The v2 surface does not gate
+;; on them — see the note below.
(api-scope/defscope agent-viz-mcp-ui-query "agent:viz:mcp-ui:query"
(deferred-tru "Render query visualizations in the MCP UI"))
(api-scope/defscope agent-viz-mcp-ui-drill-through "agent:viz:mcp-ui:drill-through"
(deferred-tru "Render drill-through visualizations in the MCP UI"))
+;; The v2 UI resources gate on `agent:query:run`, not a viz scope of their own: rendering a chart
+;; is what running a query looks like on screen, and `visualize_query`'s fresh-query path means a
+;; viz-only grant would run a query the user thought they had declined. Client capability is gated
+;; by the `:mcp-app-ui` extension, and the iframe executes under the user's own session, so a
+;; separate scope was not a data boundary. The `agent:viz:mcp-ui:*` leaves declared above stay
+;; exactly as they shipped in v0.62: this slice adds scopes and removes none, so every token minted
+;; against the old concrete strings keeps matching (grant-side matching is prefix-based, and the
+;; `agent:viz:*` wildcard covers them as well).
;; Alert
+;; Gates the agent-API create-alert endpoint; v2's alert_write gates on `agent:delivery:write`.
(api-scope/defscope agent-alert-create "agent:alert:create"
(deferred-tru "Create alerts"))
@@ -187,14 +225,32 @@
"Map from metabot permission type to the wildcard scope strings granted when
that permission is `:yes`."
{:permission/metabot-sql-generation #{"agent:sql:*" "agent:transforms:*" "agent:snippets:*"}
+ ;; NLQ grants `agent:content:read` (not the `agent:content:*` wildcard): an NLQ-only user reads
+ ;; content and data structure, but content *writes* are an other-tools capability. Granting the
+ ;; wildcard here would satisfy `agent:content:write` too, over-granting NLQ-only users.
+ ;;
;; `agent:timelines:*` and `agent:explorations:*` are granted under nlq: the
;; NLQ-gated :explorations profile offers the exploration + read-only timeline
;; tools (and its prompt instructs their use), so NLQ-only users must not have
;; them silently scope-filtered away.
- :permission/metabot-nlq #{"agent:notebook:*" "agent:query:*" "agent:metric:*"
- "agent:question:*" "agent:timelines:*" "agent:explorations:*"}
- :permission/metabot-other-tools #{"agent:viz:*" "agent:dashboard:*" "agent:document:*" "agent:alert:*"
- "agent:timelines:*" "agent:collection:*"}})
+ :permission/metabot-nlq #{"agent:notebook:*"
+ "agent:query:*"
+ "agent:question:*"
+ "agent:metric:*"
+ "agent:timelines:*"
+ "agent:explorations:*"
+ "agent:content:read"}
+ ;; `agent:content:*` (the full read+write wildcard) rides other-tools, which owns content writes.
+ ;; `agent:delivery:*` covers `agent:delivery:write`, the v2 scope that gates scheduled-delivery
+ ;; setup — no other bucket's wildcard reaches it, so without this the scope would be dead config.
+ :permission/metabot-other-tools #{"agent:viz:*"
+ "agent:dashboard:*"
+ "agent:document:*"
+ "agent:alert:*"
+ "agent:delivery:*"
+ "agent:timelines:*"
+ "agent:collection:*"
+ "agent:content:*"}})
(def always-granted-scopes
"Scopes granted to every user regardless of permissions."
diff --git a/src/metabase/models/serialization/resolve.clj b/src/metabase/models/serialization/resolve.clj
index 1ba769bfdc1..15a86f4d60e 100644
--- a/src/metabase/models/serialization/resolve.clj
+++ b/src/metabase/models/serialization/resolve.clj
@@ -46,6 +46,25 @@
"The current `SerdesImportResolver` instance. Bound during import."
nil)
+;;; ============================================================
+;;; Agent surface
+;;; ============================================================
+
+(def ^:dynamic *numeric-ids-allowed?*
+ "Whether bare numeric table/field/card ids are accepted alongside portable references inside
+ a query body being resolved.
+
+ False — the default and today's only live value: this PR lands the flag ahead of its readers,
+ so current behavior is unchanged. The agent-lib dialect rework (a later PR in this stack)
+ adds the schema predicate that consults it, and the v2 MCP query pipeline is the first binder
+ (it binds true for the duration of a resolve). False stays the safe direction: a numeric id
+ is rejected with a teaching error rather than resolved against whatever row happens to carry
+ that id.
+
+ It is ambient rather than a parameter because its eventual reader is a registered Malli
+ schema predicate, which has no call site to thread a value through."
+ false)
+
;;; ============================================================
;;; Pure predicates
;;; ============================================================
diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.clj
index ca728405281..447e161bc92 100644
--- a/src/metabase/models/serialization/resolve/mp.clj
+++ b/src/metabase/models/serialization/resolve/mp.clj
@@ -116,10 +116,9 @@
oracle, so both get this identical message.
The LLM can still self-correct in one turn by listing the parent database's tables with
- `read_resource`; the message points it at that path."
+ the calling surface's discovery tool; the message points it at that path."
[_metadata-provider [_path-db-name _path-schema _path-table-name :as path]]
- (ex-info (tru "No table found matching portable FK {0}. Call `read_resource` with `metabase://database/<numeric id>/tables` to list available tables and schemas, then retry with an exact portable FK from the response."
- (pr-str path))
+ (ex-info (tru "No table found matching portable FK {0}." (pr-str path))
{:status-code 400
:error :unknown-table
:agent-error? true
@@ -177,7 +176,7 @@
;; Deliberately do NOT enumerate the matching `[schema name id]` tuples — the metadata
;; provider is un-sandboxed, so a leaked candidate list could surface tables the caller
;; cannot otherwise see (parity with the `unknown-table-ex-info` strip above).
- (throw (ex-info (tru "Ambiguous portable table FK {0}: {1} candidates. Call `read_resource` with `metabase://database/<numeric id>/tables` to list available tables and retry with a more specific portable FK."
+ (throw (ex-info (tru "Ambiguous portable table FK {0}: {1} candidates."
(pr-str path) (count candidates))
{:status-code 400
:error :ambiguous-table
@@ -204,10 +203,10 @@
;; column name. The metadata provider is un-sandboxed, the `:agent-error?` flag
;; relays this message verbatim to the user, and a leaked FK-candidate path would
;; reveal table names the caller may not be permitted to see. The LLM can recover
- ;; by reading the parent table's fields with `read_resource`.
+ ;; by listing the parent table's fields with the calling surface's discovery tool.
unknown-field-ex
(fn [segment]
- (ex-info (tru "No column {0} on table {1}.{2}.{3}. Call `read_resource` with `metabase://table/<numeric id>/fields` to list this table''s columns."
+ (ex-info (tru "No column {0} on table {1}.{2}.{3}."
(pr-str segment) (pr-str db) (pr-str schema) (pr-str table-name))
{:status-code 400
:error :unknown-field
@@ -378,7 +377,7 @@
(if (= database-id (:id current-db))
(:name current-db)
(throw (ex-info (tru "Cannot export database id {0}: metadata provider is for database id {1}."
- database-id (:id current-db))
+ (str database-id) (str (:id current-db)))
{:status-code 400
:error :unknown-database-id
:database-id database-id
@@ -416,14 +415,14 @@
entity-id (when card (or (:entity-id card) (:entity_id card)))]
(cond
(nil? card)
- (throw (ex-info (tru "No saved question, model, or metric found with id {0}." card-id)
+ (throw (ex-info (tru "No saved question, model, or metric found with id {0}." (str card-id))
{:status-code 400
:error :unknown-card-id
:card-id card-id}))
(not= card-db-id current-db-id)
- (throw (ex-info (tru "Saved question / model / metric id {0} belongs to database {1}, but this resolver targets database {2}."
- card-id card-db-id current-db-id)
+ (throw (ex-info (tru "Saved question / model / metric id {0} belongs to database {1}, but this query targets database {2}. Cross-database queries are not supported."
+ (str card-id) (str card-db-id) (str current-db-id))
{:status-code 400
:error :cross-database-card
:card-id card-id
@@ -431,7 +430,8 @@
:expected-database current-db-id}))
(or (not (string? entity-id)) (str/blank? entity-id))
- (throw (ex-info (tru "Saved question, model, or metric id {0} does not have an entity_id, so it cannot be exported as a portable representation." card-id)
+ (throw (ex-info (tru "Saved question, model, or metric id {0} does not have an entity_id, so it cannot be exported as a portable representation."
+ (str card-id))
{:status-code 400
:error :missing-card-entity-id
:card-id card-id}))
@@ -454,8 +454,7 @@
card-db-id (when card (or (:database-id card) (:database_id card)))]
(cond
(nil? card)
- (throw (ex-info (tru "No saved question or model found with entity_id {0}. Do not invent or guess entity_ids: call `read_resource` with `metabase://question/<numeric id>` or `metabase://model/<numeric id>` first, then copy the exact `portable_entity_id` from the response into `source-card:`."
- (pr-str entity-id))
+ (throw (ex-info (tru "No saved question or model found with entity_id {0}." (pr-str entity-id))
{:agent-error? true
:status-code 400
:error :unknown-card
@@ -490,8 +489,7 @@
current-db-id (:id (lib.metadata/database metadata-provider))]
(cond
(nil? measure)
- (throw (ex-info (tru "No measure found with entity_id {0}. Do not invent or guess entity_ids: read the table that owns the measure with `read_resource` (`metabase://table/<numeric id>`) and copy the exact `portable_entity_id` from its `<measure>` tag."
- (pr-str entity-id))
+ (throw (ex-info (tru "No measure found with entity_id {0}." (pr-str entity-id))
{:agent-error? true
:status-code 400
:error :unknown-measure
@@ -522,21 +520,21 @@
entity-id (when measure (or (:entity-id measure) (:entity_id measure)))]
(cond
(nil? measure)
- (throw (ex-info (tru "No measure found with id {0}." measure-id)
+ (throw (ex-info (tru "No measure found with id {0}." (str measure-id))
{:status-code 400
:error :unknown-measure-id
:measure-id measure-id}))
(nil? measure-table)
- (throw (ex-info (tru "Measure id {0} belongs to a table outside this metadata provider''s database."
- measure-id)
+ (throw (ex-info (tru "Measure id {0} belongs to a table in a different database than this query. Cross-database queries are not supported."
+ (str measure-id))
{:status-code 400
:error :cross-database-measure
:measure-id measure-id}))
(not (and (string? entity-id) (seq entity-id)))
(throw (ex-info (tru "Measure id {0} does not have an entity_id, so it cannot be exported as a portable representation."
- measure-id)
+ (str measure-id))
{:status-code 400
:error :missing-measure-entity-id
:measure-id measure-id}))
@@ -556,21 +554,21 @@
entity-id (when segment (or (:entity-id segment) (:entity_id segment)))]
(cond
(nil? segment)
- (throw (ex-info (tru "No segment found with id {0}." segment-id)
+ (throw (ex-info (tru "No segment found with id {0}." (str segment-id))
{:status-code 400
:error :unknown-segment-id
:segment-id segment-id}))
(nil? segment-table)
- (throw (ex-info (tru "Segment id {0} belongs to a table outside this metadata provider''s database."
- segment-id)
+ (throw (ex-info (tru "Segment id {0} belongs to a table in a different database than this query. Cross-database queries are not supported."
+ (str segment-id))
{:status-code 400
:error :cross-database-segment
:segment-id segment-id}))
(not (and (string? entity-id) (seq entity-id)))
(throw (ex-info (tru "Segment id {0} does not have an entity_id, so it cannot be exported as a portable representation."
- segment-id)
+ (str segment-id))
{:status-code 400
:error :missing-segment-entity-id
:segment-id segment-id}))
@@ -589,8 +587,7 @@
current-db-id (:id (lib.metadata/database metadata-provider))]
(cond
(nil? segment)
- (throw (ex-info (tru "No segment found with entity_id {0}. Do not invent or guess entity_ids: read the table that owns the segment with `read_resource` (`metabase://table/<numeric id>`) and copy the exact `portable_entity_id` from its `<segment>` tag."
- (pr-str entity-id))
+ (throw (ex-info (tru "No segment found with entity_id {0}." (pr-str entity-id))
{:agent-error? true
:status-code 400
:error :unknown-segment
@@ -692,7 +689,7 @@
(when table-id
(let [t (lib.metadata.protocols/table metadata-provider table-id)]
(when-not t
- (throw (ex-info (tru "No table with id {0} in metadata provider." table-id)
+ (throw (ex-info (tru "No table found with id {0}." (str table-id))
{:status-code 400
:error :unknown-table-id
:table-id table-id})))
@@ -701,7 +698,7 @@
(when field-id
(let [f (lib.metadata.protocols/field metadata-provider field-id)]
(when-not f
- (throw (ex-info (tru "No field with id {0} in metadata provider." field-id)
+ (throw (ex-info (tru "No field found with id {0}." (str field-id))
{:status-code 400
:error :unknown-field-id
:field-id field-id})))
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 3fb9bb81c92..08648aeef6f 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -91,7 +91,16 @@
(defn resolve-access-token
"Validate an OAuth bearer access token string against the token store. Returns
`{:user-id <int> :scopes <set-of-strings>}` on success, or nil on failure (unknown,
- expired, or revoked token, or a token with no associated user).
+ expired, or revoked token, a token with no associated user, or a token whose user has since
+ been deactivated).
+
+ The `is_active` gate here is defense in depth, not the primary control: deactivating a user through
+ the model fires `:event/user-credentials-revoked`, and `metabase.oauth-server.events.revoke-on-deactivation`
+ stamps `revoked_at` on every token, which the store lookup above already filters on. This gate covers
+ the paths that don't go through the model hook — a direct SQL or migration update of `core_user`, a
+ restored backup — and keeps the invariant local to the one resolver every bearer caller shares (the
+ v1 MCP transport dispatches straight on the returned `:user-id` with no re-check of its own). It costs
+ one indexed primary-key lookup per bearer request.
This is the single token-resolution lookup shared by the MCP transport and the core
session middleware's bearer-token bridge — keep it the only place an access token is
@@ -106,5 +115,6 @@
;; Fail closed if the issuing client is gone (SEC-863).
(t2/exists? :model/OAuthClient :client_id (:client-id token-data)))
(when-let [user-id (some-> (:user-id token-data) parse-long)]
- {:user-id user-id
- :scopes (or (some->> (:scope token-data) (into #{})) #{})})))))))
+ (when (t2/exists? :model/User :id user-id :is_active true)
+ {:user-id user-id
+ :scopes (or (some->> (:scope token-data) (into #{})) #{})}))))))))
diff --git a/src/metabase/pulse/api.clj b/src/metabase/pulse/api.clj
index fe827b6498d..7e529db4194 100644
--- a/src/metabase/pulse/api.clj
+++ b/src/metabase/pulse/api.clj
@@ -20,7 +20,8 @@
(p/import-vars
[metabase.pulse.api.pulse
- create-pulse-with-perm-checks!])
+ create-pulse-with-perm-checks!
+ update-pulse-with-perm-checks!])
(def ^{:arglists '([request respond raise])} pulse-routes
"`/api/pulse` routes. `/api/pulse/unsubscribe/*` does not require authentication, so you can unsubscribe without being
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 95cadd4c7cc..91cc6fcfee5 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -25,6 +25,7 @@
[metabase.pulse.send :as pulse.send]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
+ [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -39,48 +40,6 @@
[alert]
(m/find-first #(= :email (keyword (:channel_type %))) (:channels alert)))
-(defn- maybe-filter-pulses-recipients
- "If the current user is sandboxed, remove all Metabase users from the `pulses` recipient lists that are not the user
- themselves. Recipients that are plain email addresses are preserved.
-
- If the current user is not a superuser, also filters the list of recipients to remove users from a different tenant."
- [pulses]
- (cond->> pulses
- (perms/sandboxed-or-impersonated-user?)
- (map (fn [pulse]
- (assoc pulse :channels
- (for [channel (:channels pulse)]
- (assoc channel :recipients
- (filter (fn [recipient]
- (or (not (:id recipient))
- (= (:id recipient) api/*current-user-id*)))
- (:recipients channel)))))))
-
- (not api/*is-superuser?*)
- (map (fn [pulse]
- (assoc pulse :channels
- (for [channel (:channels pulse)]
- (assoc channel :recipients
- (filter (fn [recipient]
- (or (not (:id recipient))
- (= (:tenant_id recipient) (:tenant_id api/*current-user*))))
- (:recipients channel)))))))))
-
-(defn- maybe-filter-pulse-recipients
- [pulse]
- (first (maybe-filter-pulses-recipients [pulse])))
-
-(defn- maybe-strip-sensitive-metadata
- "If the current user does not have collection read permissions for the pulse, but can still read the pulse due to
- being the creator or a recipient, we return it with some metadata removed."
- [pulse]
- (if (mi/current-user-has-full-permissions? :read pulse)
- pulse
- (-> (dissoc pulse :cards)
- (update :channels
- (fn [channels]
- (map #(dissoc % :recipients) channels))))))
-
;; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest
;; of the REST API
;;
@@ -114,9 +73,9 @@
:dashboard-id dashboard-id
:user-id (when creator-or-recipient api/*current-user-id*)})
(filter (if creator-or-recipient mi/can-read? mi/can-write?))
- maybe-filter-pulses-recipients)
+ models.pulse/maybe-filter-pulses-recipients)
pulses (if creator-or-recipient
- (map maybe-strip-sensitive-metadata pulses)
+ (map models.pulse/maybe-strip-sensitive-metadata pulses)
pulses)]
(mapv
(fn [pulse]
@@ -237,26 +196,43 @@
(api/let-404 [pulse (models.pulse/retrieve-pulse id)]
(api/check-403 (mi/can-read? pulse))
(-> pulse
- maybe-filter-pulse-recipients
- maybe-strip-sensitive-metadata
+ models.pulse/maybe-filter-pulse-recipients
+ models.pulse/maybe-strip-sensitive-metadata
(t2/hydrate :can_write))))
(defn- maybe-add-recipients
- "Sandboxed users and users using connection impersonation can't read the full recipient list for a pulse, so we need
- to merge in existing recipients before writing the pulse updates to avoid them being deleted unintentionally. We only
- merge in recipients that are Metabase users, not raw email addresses, which these users can still view and modify."
+ "Merge back the recipients the current user was not allowed to see before writing `pulse-updates`.
+
+ The `:channels` submitted to an update are authoritative — [[metabase.pulse.models.pulse/update-notification-channels!]]
+ deletes any recipient not present — so every recipient hidden on the read path must be restored on
+ the write path, or a caller who reads a pulse and submits it back silently deletes recipients it
+ never saw. Two read filters hide recipients, and each is compensated here:
+
+ * sandboxed and connection-impersonated users see only themselves
+ (see [[metabase.pulse.models.pulse/maybe-filter-pulses-recipients]]);
+ * tenant-scoped users see only same-tenant users
+ (see [[metabase.pulse.models.pulse/hidden-cross-tenant-recipients]]).
+
+ Only Metabase-user recipients are merged back. Raw email addresses stay visible to these users
+ under both filters, so they remain the caller's to add or remove."
[pulse-updates pulse-before-update]
- (if (perms/sandboxed-or-impersonated-user?)
- (let [recipients-to-add (filter
- (fn [{id :id}] (and id (not= id api/*current-user-id*)))
- (:recipients (email-channel pulse-before-update)))]
+ (let [existing-recipients (:recipients (email-channel pulse-before-update))
+ recipients-to-add (concat
+ (when (perms/sandboxed-or-impersonated-user?)
+ (filter (fn [{id :id}] (and id (not= id api/*current-user-id*)))
+ existing-recipients))
+ (models.pulse/hidden-cross-tenant-recipients existing-recipients))]
+ (if (seq recipients-to-add)
(assoc pulse-updates :channels
(for [channel (:channels pulse-updates)]
- (if (= "email" (:channel_type channel))
+ ;; normalize like [[email-channel]]: :channel_type is a string over REST but a
+ ;; keyword when this is called directly with a hydrated pulse
+ (if (= :email (keyword (:channel_type channel)))
(assoc channel :recipients
- (concat (:recipients channel) recipients-to-add))
- channel))))
- pulse-updates))
+ (m/distinct-by (some-fn :id :email)
+ (concat (:recipients channel) recipients-to-add)))
+ channel)))
+ pulse-updates)))
(defn check-card-read-permissions
"Users can only create a pulse for `cards` they have access to."
@@ -266,25 +242,20 @@
(assert (integer? card-id))
(api/read-check :model/Card card-id)))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :put "/:id"
- "Update a Pulse with `id`."
- [{:keys [id]} :- [:map
- [:id ms/PositiveInt]]
- _query-params
- {:keys [cards], :as pulse-updates} :- [:map
- [:name {:optional true} [:maybe ms/NonBlankString]]
- [:cards {:optional true} [:maybe [:+ models.pulse/CoercibleToCardRef]]]
- [:channels {:optional true} [:maybe [:+ PulseChannel]]]
- [:skip_if_empty {:default false} [:maybe :boolean]]
- [:collection_id {:optional true} [:maybe ms/PositiveInt]]
- [:collection_position {:optional true} [:maybe ms/PositiveInt]]
- [:archived {:default false} [:maybe :boolean]]
- [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter]]]]]
- ;; do various perms checks
+(defn update-pulse-with-perm-checks!
+ "Apply `pulse-updates` to the Pulse with `id`, running the same permission checks `PUT /api/pulse/:id`
+ runs: the subscription/monitoring application permission, a write check on the Pulse, read checks on
+ any `:cards`, the collection-change check, and the advanced-permissions gate on adding recipients.
+ Returns the updated Pulse."
+ [id {:keys [cards] :as pulse-updates}]
+ ;; Validate `:cards` up front so a bad card ref is a clean 400, not a 500. This fn is called
+ ;; directly (e.g. from the agent API), not only through the PUT endpoint whose schema already
+ ;; coerces `:cards` — without this, `check-card-read-permissions`'s `(assert (integer? card-id))`
+ ;; throws a bare AssertionError (no :status-code) on a string id and surfaces as a 500.
+ (when (some? cards)
+ (when-not (mr/validate [:sequential models.pulse/CoercibleToCardRef] cards)
+ (throw (ex-info (tru "Invalid :cards: each entry must be a card reference.")
+ {:status-code 400}))))
(try
(perms/check-has-application-permission :monitoring)
(catch clojure.lang.ExceptionInfo _e
@@ -320,9 +291,28 @@
(assoc (select-keys pulse-updates [:name :cards :channels :skip_if_empty :collection_id :collection_position
:archived :parameters])
:id id)))))
- ;; return updated Pulse
(models.pulse/retrieve-pulse id))
+;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
+;; use our API + we will need it when we make auto-TypeScript-signature generation happen
+;;
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :put "/:id"
+ "Update a Pulse with `id`."
+ [{:keys [id]} :- [:map
+ [:id ms/PositiveInt]]
+ _query-params
+ pulse-updates :- [:map
+ [:name {:optional true} [:maybe ms/NonBlankString]]
+ [:cards {:optional true} [:maybe [:+ models.pulse/CoercibleToCardRef]]]
+ [:channels {:optional true} [:maybe [:+ PulseChannel]]]
+ [:skip_if_empty {:default false} [:maybe :boolean]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:collection_position {:optional true} [:maybe ms/PositiveInt]]
+ [:archived {:default false} [:maybe :boolean]]
+ [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter]]]]]
+ (update-pulse-with-perm-checks! id pulse-updates))
+
;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
;;
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
diff --git a/src/metabase/pulse/core.clj b/src/metabase/pulse/core.clj
index 6b45f22ab14..bd205816c18 100644
--- a/src/metabase/pulse/core.clj
+++ b/src/metabase/pulse/core.clj
@@ -14,7 +14,10 @@
(p/import-vars
[metabase.pulse.models.pulse
card->ref
+ maybe-filter-pulse-recipients
+ maybe-strip-sensitive-metadata
retrieve-alerts-for-cards
+ retrieve-pulse
update-pulse!]
[metabase.pulse.update-alerts
delete-alerts-if-needed!])
diff --git a/src/metabase/pulse/models/pulse.clj b/src/metabase/pulse/models/pulse.clj
index 2be564c4142..734f3542f21 100644
--- a/src/metabase/pulse/models/pulse.clj
+++ b/src/metabase/pulse/models/pulse.clj
@@ -403,6 +403,101 @@
hydrate-notification
notification->pulse))))
+(defn- tenant-scoped-caller?
+ "True when the current user's recipient visibility is narrowed to their own tenant. Superusers and
+ users with no tenant see recipients unfiltered, as before tenants existed."
+ []
+ (and (not api/*is-superuser?*)
+ (some? (:tenant_id @api/*current-user*))))
+
+(defn- recipient-ids->tenant-ids
+ "Map of user id -> `:tenant_id` for the Metabase-user recipients in `recipient-ids`. Recipient maps
+ come from the `:recipients` batched-hydrate, which does not select `:tenant_id`, so tenant
+ membership is looked up here rather than read off the map — reading it off the map compares nil to
+ nil and filters nothing (or, once the caller has a tenant, drops every recipient)."
+ [recipient-ids]
+ (if (seq recipient-ids)
+ (t2/select-pk->fn :tenant_id :model/User :id [:in recipient-ids])
+ {}))
+
+(defn- recipient-visible-to-tenant-caller?
+ "Whether a tenant-scoped caller may see `recipient`. Plain-email recipients (no `:id`) are always
+ visible; Metabase-user recipients are visible only when they belong to the caller's tenant.
+
+ This predicate is the single definition of the tenant recipient filter: the read path uses it to
+ hide recipients ([[filter-cross-tenant-recipients]]) and the write path uses it to merge the same
+ hidden recipients back in, so a filtered read that is submitted back as a write cannot silently
+ delete them."
+ [id->tenant-id tenant-id recipient]
+ (or (not (:id recipient))
+ (= (id->tenant-id (:id recipient)) tenant-id)))
+
+(defn hidden-cross-tenant-recipients
+ "The Metabase-user recipients in `recipients` that [[filter-cross-tenant-recipients]] would hide from
+ the current user. Returns `nil` when the caller is not tenant-scoped, i.e. when nothing is hidden.
+
+ The write path uses this to restore recipients the caller was never shown; see
+ [[metabase.pulse.api.pulse/maybe-add-recipients]]."
+ [recipients]
+ (when (tenant-scoped-caller?)
+ (let [tenant-id (:tenant_id @api/*current-user*)
+ id->tenant-id (recipient-ids->tenant-ids (into #{} (keep :id) recipients))]
+ (remove #(recipient-visible-to-tenant-caller? id->tenant-id tenant-id %) recipients))))
+
+(defn- filter-cross-tenant-recipients
+ "Drop Metabase-user recipients that belong to a different tenant than the current (tenant-scoped)
+ user."
+ [pulses]
+ (let [tenant-id (:tenant_id @api/*current-user*)
+ recipient-ids (into #{}
+ (comp (mapcat :channels) (mapcat :recipients) (keep :id))
+ pulses)
+ id->tenant-id (recipient-ids->tenant-ids recipient-ids)]
+ (for [pulse pulses]
+ (assoc pulse :channels
+ (for [channel (:channels pulse)]
+ (assoc channel :recipients
+ (filter #(recipient-visible-to-tenant-caller? id->tenant-id tenant-id %)
+ (:recipients channel))))))))
+
+(defn maybe-filter-pulses-recipients
+ "If the current user is sandboxed, remove all Metabase users from the `pulses` recipient lists that are not the user
+ themselves. Recipients that are plain email addresses are preserved.
+
+ If the current user belongs to a tenant (and is not a superuser), also filters the recipient
+ lists down to users in the same tenant. A user with no tenant sees recipients unfiltered, as
+ before tenants existed."
+ [pulses]
+ (cond->> pulses
+ (perms/sandboxed-or-impersonated-user?)
+ (map (fn [pulse]
+ (assoc pulse :channels
+ (for [channel (:channels pulse)]
+ (assoc channel :recipients
+ (filter (fn [recipient]
+ (or (not (:id recipient))
+ (= (:id recipient) api/*current-user-id*)))
+ (:recipients channel)))))))
+
+ (tenant-scoped-caller?)
+ filter-cross-tenant-recipients))
+
+(defn maybe-filter-pulse-recipients
+ "[[maybe-filter-pulses-recipients]] for a single pulse."
+ [pulse]
+ (first (maybe-filter-pulses-recipients [pulse])))
+
+(defn maybe-strip-sensitive-metadata
+ "If the current user does not have collection read permissions for the pulse, but can still read the pulse due to
+ being the creator or a recipient, we return it with some metadata removed."
+ [pulse]
+ (if (mi/current-user-has-full-permissions? :read pulse)
+ pulse
+ (-> (dissoc pulse :cards)
+ (update :channels
+ (fn [channels]
+ (map #(dissoc % :recipients) channels))))))
+
(mu/defn retrieve-user-alerts-for-card
"Find all alerts for `card-id` that `user-id` is set to receive"
[{:keys [archived? card-id user-id]
diff --git a/src/metabase/server/streaming_response.clj b/src/metabase/server/streaming_response.clj
index 490d07ffec0..515ae95e73f 100644
--- a/src/metabase/server/streaming_response.clj
+++ b/src/metabase/server/streaming_response.clj
@@ -23,7 +23,7 @@
(java.nio ByteBuffer)
(java.nio.channels ClosedChannelException SocketChannel)
(java.nio.charset StandardCharsets)
- (java.util.concurrent Future)
+ (java.util.concurrent ExecutorService Future)
(java.util.concurrent.atomic AtomicBoolean)
(java.util.zip GZIPOutputStream)
(org.eclipse.jetty.ee9.nested HttpChannel Request)
@@ -231,10 +231,10 @@
(.cancel fut true)))))))
(defn- do-f-async
- "Runs `f` asynchronously on the streaming response `thread-pool`, returning immediately. When `f` finishes,
- completes (i.e., closes) Jetty `async-context`. `completed?` is an `AtomicBoolean` used to coordinate with
- Jetty's timeout/error callbacks so that only one path calls `.complete`."
- [^AsyncContext async-context response ^Request request f ^OutputStream os finished-chan canceled-chan ^AtomicBoolean completed?]
+ "Runs `f` asynchronously on `executor` (the shared streaming response `thread-pool` when nil), returning
+ immediately. When `f` finishes, completes (i.e., closes) Jetty `async-context`. `completed?` is an `AtomicBoolean`
+ used to coordinate with Jetty's timeout/error callbacks so that only one path calls `.complete`."
+ [^AsyncContext async-context response ^Request request f ^OutputStream os finished-chan canceled-chan ^AtomicBoolean completed? executor]
{:pre [(some? os)]}
(let [task (^:once fn* []
(binding [*response* response
@@ -257,7 +257,8 @@
(a/close! canceled-chan)
(when (.compareAndSet completed? false true)
(.complete async-context))))))
- fut (.submit (thread-pool/thread-pool) ^Runnable task)]
+ ^ExecutorService pool (or executor (thread-pool/thread-pool))
+ fut (.submit pool ^Runnable task)]
(start-interrupt-escalation! fut finished-chan canceled-chan)
nil))
@@ -375,7 +376,7 @@
(defn- respond
[{:keys [^HttpServletResponse response ^AsyncContext async-context request-map response-map request]}
- f {:keys [content-type status headers], :as _options} finished-chan]
+ f {:keys [content-type status headers executor], :as _options} finished-chan]
(let [canceled-chan (a/promise-chan)
completed? (AtomicBoolean. false)]
(.addListener async-context
@@ -414,7 +415,7 @@
(let [output-stream-delay (output-stream-delay gzip? response)
delay-os (delay-output-stream output-stream-delay)]
(start-async-cancel-loop! request finished-chan canceled-chan)
- (do-f-async async-context response request f delay-os finished-chan canceled-chan completed?)))
+ (do-f-async async-context response request f delay-os finished-chan canceled-chan completed? executor)))
(catch Throwable e
(log/errorf "Unexpected exception in do-f-async: %s" (ex-message e))
(try
@@ -491,7 +492,12 @@
Current options:
* `:content-type` -- string content type to return in the results. This is required!
- * `:headers` -- other headers to include in the API response."
+ * `:headers` -- other headers to include in the API response.
+ * `:executor` -- optional `ExecutorService` to run `f` on. Defaults to the shared streaming response thread pool,
+ which is a small fixed pool: responses that block for the life of a client connection (rather than for the life
+ of a query) must supply their own executor so they cannot exhaust it. The supplied executor's futures must
+ support real interruption (`Future.cancel(true)`) — the hung-request escalation interrupts the worker, and a
+ ForkJoinPool-backed executor silently ignores it."
{:style/indent 2, :arglists '([options [os-binding canceled-chan-binding] & body])}
[options [os-binding canceled-chan-binding :as bindings] & body]
{:pre [(= (count bindings) 2)]}
diff --git a/test/metabase/agent_api/query_guards_test.clj b/test/metabase/agent_api/query_guards_test.clj
new file mode 100644
index 00000000000..3534991f82f
--- /dev/null
+++ b/test/metabase/agent_api/query_guards_test.clj
@@ -0,0 +1,246 @@
+(ns metabase.agent-api.query-guards-test
+ "Tests for the MBQL-path guards (GHY-4136). The native-detection and shape-validation guards are
+ the security boundary that keeps opaque base64 payloads (query handles, continuation tokens) from
+ smuggling native SQL past the MBQL-only scopes, so they are exercised exhaustively here.
+ `check-token-query-permissions!`'s allow/deny cases need permission fixtures and are the
+ DB-backed deftests toward the end of this namespace; its no-op branches (which document that
+ only a stage-0 numeric source-table is checked) are covered by the pure tests."
+ (:require
+ [clojure.test :refer [are deftest is testing]]
+ [metabase.agent-api.query-guards :as query-guards]
+ [metabase.test :as mt]))
+
+(set! *warn-on-reflection* true)
+
+(defn- thrown-status
+ "Return the `:status-code` from the ex-data of the exception `thunk` throws. Returns `::no-throw`
+ when `thunk` does not throw and `::no-status` when it throws an `ExceptionInfo` without a
+ `:status-code` — two distinct sentinels so an assertion for \"does not throw\" can't be satisfied
+ by a throw that merely lacks a status (which would be a 500 to the client, not the clean pass the
+ test means to assert)."
+ [thunk]
+ (try (thunk) ::no-throw
+ (catch clojure.lang.ExceptionInfo e (:status-code (ex-data e) ::no-status))))
+
+(deftest ^:parallel native-marker?-test
+ (testing "every native-marker form is detected"
+ (are [node] (true? (query-guards/native-marker? node))
+ {:native "SELECT 1"} ; universal :native body
+ {:native {:query "SELECT 1"}}
+ {:type :native} ; legacy keyword
+ {:type "native"} ; legacy json-decoded string
+ {:lib/type :mbql.stage/native} ; MBQL 5 keyword
+ {:lib/type "mbql.stage/native"})) ; MBQL 5 json-decoded string
+ (testing "a payload decoded without keywordizing is detected too"
+ (are [node] (true? (query-guards/native-marker? node))
+ {"native" "SELECT 1"}
+ {"type" "native"}
+ {"lib/type" "mbql.stage/native"}))
+ (testing "clean MBQL nodes are not markers"
+ (are [node] (false? (query-guards/native-marker? node))
+ {:type :query}
+ {:type "query"}
+ {"type" "query"}
+ {:lib/type :mbql.stage/mbql}
+ {:lib/type "mbql.stage/mbql"}
+ {"lib/type" "mbql.stage/mbql"}
+ {:source-table 1}
+ {}))
+ (testing "non-map and junk values never throw and are never markers"
+ (are [node] (false? (query-guards/native-marker? node))
+ nil 42 "native" :native [:native] #{:native} '(:native))))
+
+(deftest ^:parallel native-query?-test
+ (testing "native SQL is detected at every depth of the tree"
+ (are [query-map] (true? (query-guards/native-query? query-map))
+ {:type :native :native {:query "SELECT 1"}} ; legacy top-level
+ {:database 1 :type :query :query {:source-query {:native "SELECT 1"}}} ; legacy nested source-query
+ {:stages [{:lib/type :mbql.stage/native :native "SELECT 1"}]} ; MBQL 5 native stage
+ {:stages [{:lib/type :mbql.stage/mbql
+ :joins [{:stages [{:lib/type :mbql.stage/native :native "x"}]}]}]} ; native inside a join
+ {:stages [{:lib/type :mbql.stage/mbql
+ :joins [{:stages [{:lib/type :mbql.stage/mbql
+ :joins [{:stages [{:lib/type :mbql.stage/native}]}]}]}]}]} ; nested join
+ {"database" 1 "type" "native" "native" {"query" "SELECT 1"}} ; decoded without keywordizing
+ {"stages" [{"lib/type" "mbql.stage/native" "native" "SELECT 1"}]}
+ ;; snake_case source_query: legacy normalization canonicalizes it too, so it reaches the QP
+ ;; as a native stage — missing this edge let an MBQL-only-scoped caller run raw SQL.
+ {"type" "query" "database" 1 "query" {"source_query" {"native" "SELECT 1"}}}
+ {:database 1 :type :query :query {:source_query {:native "SELECT 1"}}}))
+ (testing "a payload MBQL 5 normalization cannot make sense of still fails closed"
+ ;; The guard cannot delegate detection to `lib-be/normalize-query` + `lib/any-native-stage?`:
+ ;; normalization swallows its own failure and hands back `{}`, so a normalize-then-inspect check
+ ;; sees no stages and waves these through instead of rejecting them.
+ (are [query-map] (true? (query-guards/native-query? query-map))
+ {:stages [{:lib/type :mbql.stage/native :native "SELECT 1"} 42]}
+ {:stages {:garbage [{:native "SELECT 1"}]}}))
+ (testing "a non-map element where a stage belongs never throws: it is deep-scanned, and a marker after it still trips"
+ ;; `/v2/query` must answer a 400 from shape validation for `{:stages [1]}`, not a 500 from the guard.
+ (is (false? (query-guards/native-query? {:stages [1]})))
+ (is (false? (query-guards/native-query? {:stages [42 {:lib/type :mbql.stage/mbql :source-table 1}]})))
+ (is (true? (query-guards/native-query? {:stages [42 {:lib/type :mbql.stage/native :native "SELECT 1"}]}))))
+ (testing "the deep-scan fallbacks fail closed: a marker buried inside a malformed edge value still trips"
+ (are [query-map] (true? (query-guards/native-query? query-map))
+ {:stages [[{:native "SELECT 1"}]]} ; non-map stage element wrapping a marker
+ {:query [{:native "SELECT 1"}]} ; :query edge holding a vector, not a map
+ {:stages [{:source-query [[{:type "native"}]]}]})) ; nested non-map :source-query
+ (testing "clean MBQL queries are not native"
+ (are [query-map] (false? (query-guards/native-query? query-map))
+ {:stages [{:lib/type :mbql.stage/mbql :source-table 1}]}
+ {:stages [{:lib/type :mbql.stage/mbql :source-table 1
+ :joins [{:stages [{:lib/type :mbql.stage/mbql :source-table 2}]}]}]}
+ {:database 1 :type :query :query {:source-table 1}}
+ {}
+ {:stages []}))
+ (testing "GHY-4136 C1: a legit query whose caller-named sub-maps contain the key `native` is NOT native.
+ `:expressions` is keyed by expression name and `:template-tags` by tag name, so a column or tag
+ literally named `native` must not be mistaken for a native-SQL marker — the guard walks only the
+ structural query-nesting edges, never these caller-named maps."
+ (are [query-map] (false? (query-guards/native-query? query-map))
+ {:database 1 :type :query :query {:source-table 1 :expressions {"native" [:+ 1 2]}}} ; legacy expression named native
+ {:database 1 :type :query :query {:source-table 1} :template-tags {"native" {:type :text}}} ; legacy template tag named native
+ {:stages [{:lib/type :mbql.stage/mbql :source-table 1 :expressions {"native" [:+ 1 2]}}]} ; MBQL 5 expression named native
+ {"query" {"source-table" 1 "expressions" {"native" [:+ 1 2]}}}))) ; decoded without keywordizing
+
+(deftest ^:parallel native-query?-is-case-and-separator-insensitive-test
+ (testing "the QP normalizer canonicalizes keys case-insensitively and treats `_` and `-` alike, so a payload
+ spelled `:SOURCE_QUERY` still reaches the query processor as a native stage. Matching edge names and
+ markers case-exactly let a caller walk straight past the guard by changing the spelling — and once
+ `check-mcp-ui-native-query!` is wired onto /api/dataset (the next slice), this scan is the only gate
+ standing between an unrestricted-stamped MCP UI credential and raw SQL."
+ (testing "nested-query edges, however spelled"
+ (are [q] (true? (query-guards/native-query? q))
+ {:query {:source-query {:native "select 1"}}}
+ {:query {:source_query {:native "select 1"}}}
+ {:query {:SOURCE_QUERY {:native "select 1"}}}
+ {:query {:Source-Query {:native "select 1"}}}
+ {"QUERY" {"Source_Query" {"native" "select 1"}}}))
+ (testing "the markers themselves, however spelled"
+ (are [q] (true? (query-guards/native-query? q))
+ {:query {:source_query {:NATIVE "select 1"}}}
+ {:type "NATIVE"}
+ {:TYPE :Native}
+ {:lib/type "MBQL.STAGE/NATIVE"}
+ {:stages [{:LIB/TYPE "mbql.stage/native"}]}))
+ (testing "sequence edges, however spelled"
+ (are [q] (true? (query-guards/native-query? q))
+ {:STAGES [{:native "select 1"}]}
+ {:query {:JOINS [{:source-query {:native "select 1"}}]}}))
+ (testing "and a legitimate MBQL query is still not native, whatever its columns are called"
+ (are [q] (false? (query-guards/native-query? q))
+ {:query {:source-table 1}}
+ {:stages [{:lib/type "mbql.stage/mbql" :source-table 1}]}
+ ;; caller-named sub-maps are never scanned: an expression or tag called `native` is not a marker
+ {:stages [{:lib/type "mbql.stage/mbql" :expressions {:NATIVE [:+ 1 1]}}]}
+ {:query {:source-table 1 :template-tags {:Source_Query {:name "x"}}}}))))
+
+(deftest reject-native-query!-test
+ (testing "native queries throw a 400 with a steering message"
+ (let [query {:stages [{:lib/type :mbql.stage/native :native "SELECT 1"}]}]
+ (is (= 400 (thrown-status #(query-guards/reject-native-query! query))))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"execute_sql"
+ (query-guards/reject-native-query! query)))))
+ (testing "clean MBQL queries pass (return nil, do not throw)"
+ (is (nil? (query-guards/reject-native-query! {:stages [{:lib/type :mbql.stage/mbql :source-table 1}]})))))
+
+(deftest validate-serialized-query!-test
+ (testing "well-formed serialized MBQL passes"
+ (are [query-map] (nil? (query-guards/validate-serialized-query! query-map))
+ {:stages [{:source-table 1}]}
+ {:stages [{:source-table 1} {:filters []}]}
+ {:stages [{:source-table 1 :limit 50}]} ; positive int limit is fine
+ {:stages [{:source-table 1 :limit 1}]}))
+ (testing "a missing or malformed :stages is a 400, not a downstream 500"
+ (are [query-map] (= 400 (thrown-status #(query-guards/validate-serialized-query! query-map)))
+ {} ; no :stages
+ {:stages nil}
+ {:stages []} ; empty
+ {:stages {:source-table 1}} ; not sequential
+ {:stages [{:source-table 1} 42]})) ; a non-map stage
+ (testing "a present-but-invalid last-stage :limit is a 400 (contains?, so explicit false/nil is caught)"
+ (are [limit] (= 400 (thrown-status #(query-guards/validate-serialized-query! {:stages [{:limit limit}]})))
+ false
+ nil
+ 0
+ -1
+ "50"
+ 1.5)))
+
+(deftest check-token-query-permissions!-no-op-test
+ (testing "the guard is a no-op when there is no stage-0 numeric source-table"
+ ;; Documents the partial coverage: a source-card, a nil source-table, or a non-int value is not
+ ;; checked here — the QP is the authoritative backstop at execution; this guard is a stage-0
+ ;; fast path for a cleaner 403, never the enforcement point.
+ (are [query-map] (nil? (query-guards/check-token-query-permissions! query-map))
+ {:stages [{:source-card 10}]} ; card source, no source-table
+ {:stages [{}]} ; nothing to check
+ {:stages [{:source-table "card__10"}]} ; string (virtual) source, not an int
+ {:stages []}
+ {})))
+
+(deftest check-token-query-permissions!-allow-deny-test
+ (testing "passes (does not throw) when the current user can query the stage-0 source table"
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= ::no-throw (thrown-status #(query-guards/check-token-query-permissions!
+ {:stages [{:source-table (mt/id :orders)}]}))))))
+ (testing "throws 403 when the current user lacks data perms on the source table"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= 403 (thrown-status #(query-guards/check-token-query-permissions!
+ {:stages [{:source-table (mt/id :orders)}]}))))))))
+
+(defn- ui-request
+ "A request map shaped like one the MCP Apps iframe credential authenticated."
+ [token-scopes]
+ {:mcp-ui-credential {:uid 1 :sid "session" :token-scopes token-scopes}})
+
+(def ^:private legacy-native {:database 1 :type "native" :native {:query "SELECT 1"}})
+(def ^:private mbql-5-native {:lib/type "mbql/query" :database 1
+ :stages [{:lib/type "mbql.stage/native" :native "SELECT 1"}]})
+(def ^:private mbql-query {:lib/type "mbql/query" :database 1
+ :stages [{:lib/type "mbql.stage/mbql" :source-table 1}]})
+
+(deftest check-mcp-ui-native-query!-test
+ (testing "GHY-4318: both query shapes /api/dataset accepts are refused when the minting session lacked
+ agent:sql:run — a hand-rolled payload would most naturally use the legacy shape, while execute_sql
+ mints MBQL 5"
+ (are [query] (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!
+ (ui-request #{"agent:content:read" "agent:query:run"})
+ query)))
+ legacy-native
+ mbql-5-native))
+ (testing "the refusal names the scope the client would need"
+ (is (re-find #"agent:sql:run"
+ (try (query-guards/check-mcp-ui-native-query!
+ (ui-request #{"agent:query:run"}) legacy-native)
+ ""
+ (catch clojure.lang.ExceptionInfo e (ex-message e))))))
+ (testing "grants that cover agent:sql:run pass"
+ (are [scopes] (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query!
+ (ui-request scopes) legacy-native)))
+ #{"agent:sql:run"}
+ #{"agent:sql:execute"} ; v1's concrete scope keeps working
+ #{"agent:sql:*"} ; metabot permissions grant wildcards
+ #{:metabase.api.macros.scope/unrestricted})) ; browser-session MCP clients
+ (testing "non-native queries are never gated, whatever the grant"
+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! (ui-request #{}) mbql-query)))))
+ (testing "requests not authenticated by a UI credential pass through untouched"
+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! {} legacy-native)))))
+ (testing "a credential carrying no scopes claim fails closed — a rolling deploy can mint one"
+ (is (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!
+ {:mcp-ui-credential {:uid 1 :sid "session"}} legacy-native)))))
+ (testing "the kill switch outranks the grant"
+ (mt/with-temporary-setting-values [mcp-execute-sql-enabled false]
+ (is (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!
+ (ui-request #{"agent:sql:run"}) legacy-native))))))
+ (testing "M2: the scope check runs before the kill switch, so an unauthorized caller cannot tell the
+ mcp-execute-sql-enabled state apart from the 403 it gets — the message names the missing scope,
+ not the kill switch, whether the switch is on or off"
+ (doseq [enabled? [true false]]
+ (mt/with-temporary-setting-values [mcp-execute-sql-enabled enabled?]
+ (let [msg (try (query-guards/check-mcp-ui-native-query! (ui-request #{"agent:query:run"}) legacy-native)
+ ""
+ (catch clojure.lang.ExceptionInfo e (ex-message e)))]
+ (is (re-find #"agent:sql:run" msg))
+ (is (not (re-find #"mcp-execute-sql-enabled" msg))
+ "the scope refusal must not reveal the kill-switch setting to an unauthorized caller"))))))
diff --git a/test/metabase/mcp/settings_test.clj b/test/metabase/mcp/settings_test.clj
index 569a4475277..39b361b6e4d 100644
--- a/test/metabase/mcp/settings_test.clj
+++ b/test/metabase/mcp/settings_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer :all]
[metabase.mcp.settings :as mcp.settings]
+ [metabase.settings.core :as setting]
[metabase.test :as mt]))
(deftest mcp-apps-cors-custom-origins-path-validation-test
@@ -25,3 +26,37 @@
(mt/with-temporary-setting-values [mcp.settings/mcp-apps-cors-custom-origins ""]
(mcp.settings/mcp-apps-cors-custom-origins! "http://localhost:6274 electron://example.com")
(is (= "http://localhost:6274 electron://example.com" (mcp.settings/mcp-apps-cors-custom-origins))))))
+
+(deftest mcp-query-handle-ttl-hours-must-be-positive-test
+ (testing "a non-positive TTL is rejected on write. The GC deletes handles created before
+ `now - ttl`, so 0 makes the cutoff *now* and wipes every stored handle on the next run,
+ and a negative pushes the cutoff into the future and takes handles minted seconds ago."
+ (mt/with-temporary-setting-values [mcp.settings/mcp-query-handle-ttl-hours 24]
+ (doseq [bad [0 -1 "0"]]
+ (testing (str "rejects " (pr-str bad))
+ (is (thrown? Throwable (mcp.settings/mcp-query-handle-ttl-hours! bad)))))
+ (testing "the setting is left unchanged after a rejected save"
+ (is (= 24 (mcp.settings/mcp-query-handle-ttl-hours))))))
+ (testing "positive values are accepted, including a string one"
+ (mt/with-temporary-setting-values [mcp.settings/mcp-query-handle-ttl-hours 24]
+ (mcp.settings/mcp-query-handle-ttl-hours! 1)
+ (is (= 1 (mcp.settings/mcp-query-handle-ttl-hours)))
+ (mcp.settings/mcp-query-handle-ttl-hours! "48")
+ (is (= 48 (mcp.settings/mcp-query-handle-ttl-hours))))))
+
+(deftest mcp-query-handle-ttl-hours-ignores-a-non-positive-stored-value-test
+ (testing "a non-positive value that reached storage without passing through the setter — an env
+ var is read straight through `get-raw-value` and never sees one — is not returned. The
+ `:positive-integer` type's read predicate rejects it, yielding nil, and the getter falls
+ back to the default — so the GC is never handed a cutoff of *now*, nor a nil it would
+ `(long nil)` on."
+ (mt/with-temporary-setting-values [mcp.settings/mcp-query-handle-ttl-hours 24]
+ (doseq [bad ["0" "-5"]]
+ (testing (str "stored " (pr-str bad))
+ (setting/set-value-of-type! :string :mcp-query-handle-ttl-hours bad)
+ (is (= 24 (mcp.settings/mcp-query-handle-ttl-hours)))))
+ (testing "an unparseable stored value (e.g. MB_MCP_QUERY_HANDLE_TTL_HOURS=forever) takes the
+ throw path in the getter, not the nil path — it must fall back rather than kill the
+ GC task on every run"
+ (setting/set-value-of-type! :string :mcp-query-handle-ttl-hours "forever")
+ (is (= 24 (mcp.settings/mcp-query-handle-ttl-hours)))))))
diff --git a/test/metabase/metabot/scope_test.clj b/test/metabase/metabot/scope_test.clj
index 7923f1edfb1..9f8a8a8b006 100644
--- a/test/metabase/metabot/scope_test.clj
+++ b/test/metabase/metabot/scope_test.clj
@@ -45,13 +45,16 @@
(is (contains? scopes "agent:sql:*"))
(is (contains? scopes "agent:transforms:*"))
(is (contains? scopes "agent:snippets:*"))
- (is (contains? scopes "agent:search"))))
+ (is (contains? scopes "agent:search"))
+ (testing "metric is an MBQL macro gated by NLQ, not SQL generation"
+ (is (not (contains? scopes "agent:metric:*"))))))
(deftest ^:parallel perms->scopes-nql-test
(let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-nlq :yes})]
(is (contains? scopes "agent:notebook:*"))
(is (contains? scopes "agent:query:*"))
- (is (contains? scopes "agent:question:*"))))
+ (is (contains? scopes "agent:question:*"))
+ (is (contains? scopes "agent:metric:*"))))
(deftest ^:parallel perms->scopes-other-tools-test
(let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})]
@@ -60,6 +63,32 @@
(is (contains? scopes "agent:document:*"))
(is (contains? scopes "agent:alert:*"))))
+(deftest ^:parallel rationalized-mcp-v2-scopes-bucket-membership-test
+ (testing "GHY-4225: each of the five rationalized scopes is reachable from at least one permission bucket"
+ (let [nlq (scope/user-metabot-perms->scopes {:permission/metabot-nlq :yes})
+ other (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})
+ sql-gen (scope/user-metabot-perms->scopes {:permission/metabot-sql-generation :yes})]
+ (testing "agent:content:read via nlq (read-only)"
+ (is (api-scope/scope-matches? nlq "agent:content:read")))
+ (testing "agent:content:write via other-tools"
+ (is (api-scope/scope-matches? other "agent:content:write")))
+ (testing "agent:query:run via nlq"
+ (is (api-scope/scope-matches? nlq "agent:query:run")))
+ (testing "agent:sql:run via sql-generation"
+ (is (api-scope/scope-matches? sql-gen "agent:sql:run")))
+ (testing "I1: agent:delivery:write via other-tools — no other bucket's wildcard reaches it"
+ (is (api-scope/scope-matches? other "agent:delivery:write"))
+ (is (not (api-scope/scope-matches? nlq "agent:delivery:write")))
+ (is (not (api-scope/scope-matches? sql-gen "agent:delivery:write")))))))
+
+(deftest ^:parallel nlq-does-not-grant-content-write-test
+ (testing "I2: metabot-nlq grants content READ but NOT content write — an NLQ-only user must not be
+ able to create/edit/trash content via the agent:content:* wildcard"
+ (let [nlq (scope/user-metabot-perms->scopes {:permission/metabot-nlq :yes})]
+ (is (api-scope/scope-matches? nlq "agent:content:read"))
+ (is (not (contains? nlq "agent:content:*")))
+ (is (not (api-scope/scope-matches? nlq "agent:content:write"))))))
+
(deftest ^:parallel perms->scopes-no-does-not-grant-test
(let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-sql-generation :no
:permission/metabot-nlq :no})]
diff --git a/test/metabase/models/serialization/resolve/mp_test.clj b/test/metabase/models/serialization/resolve/mp_test.clj
index 69daf2c8e2a..5cc205bc175 100644
--- a/test/metabase/models/serialization/resolve/mp_test.clj
+++ b/test/metabase/models/serialization/resolve/mp_test.clj
@@ -176,7 +176,10 @@
(is (= :unknown-table (:error d)))
(is (= 400 (:status-code d)))
(is (true? (:agent-error? d)))
- (is (re-find #"read_resource" msg) "message points the LLM at read_resource to re-list")
+ (is (re-find #"No table found matching portable FK" msg)
+ "the resolver states the miss (positive check, so an empty/unrelated message can't pass)")
+ (is (not (re-find #"read_resource|browse_data" msg))
+ "the resolver states the miss; the calling surface owns the recovery sentence")
(testing "inactive-row miss is indistinguishable from a never-existed miss (no oracle)"
(let [never-existed (try (resolve/import-table-fk r [(:name db) "PUBLIC" "never_existed_xyz"])
(catch clojure.lang.ExceptionInfo e2 (.getMessage e2)))]
@@ -242,8 +245,10 @@
(testing "ex-data carries only the rejected path — no candidates / schemas"
(is (nil? (:candidates d)))
(is (nil? (:available-schemas d))))
- (testing "message points the LLM at read_resource for self-correction"
- (is (re-find #"read_resource" msg)))))))))
+ (testing "the resolver states the miss without naming any surface's discovery tool"
+ (is (re-find #"No table found matching portable FK" msg)
+ "positive check: the message actually states the miss")
+ (is (not (re-find #"read_resource|browse_data" msg))))))))))
(deftest ^:parallel import-table-fk-error-test-2
(testing "schema does not exist in DB → still :unknown-table, no schema enumeration"
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index ca21f554c19..ba26aa61bd7 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -12,9 +12,12 @@
[metabase.channel.settings :as channel.settings]
[metabase.driver :as driver]
[metabase.lib.core :as lib]
+ [metabase.models.interface :as mi]
[metabase.notification.test-util :as notification.tu]
[metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
+ [metabase.pulse.api :as pulse.api]
+ [metabase.pulse.models.pulse :as models.pulse]
[metabase.pulse.models.pulse-channel :as pulse-channel]
[metabase.pulse.models.pulse-test :as pulse-test]
[metabase.pulse.test-util :as pulse.test-util]
@@ -1436,3 +1439,65 @@
:model/Pulse {pulse-id :id} {:dashboard_id dash-id}]
(mt/user-http-request :crowberto :put 200 (str "dashboard/" dash-id) {:collection_id (:id coll)})
(is (true? (:archived (mt/user-http-request :crowberto :put 200 (str "pulse/" pulse-id) {:archived true})))))))
+
+(deftest update-pulse-with-perm-checks!-validates-cards-test
+ (testing "I3: a non-coercible :cards ref is a clean 400, not a 500. `update-pulse-with-perm-checks!` is
+ called directly (e.g. from the agent API), not only through the PUT endpoint whose schema coerces
+ :cards, so a bad ref must be rejected with a :status-code before check-card-read-permissions'
+ (assert (integer? card-id)) / u/the-id can throw a status-less error that surfaces as a 500."
+ (mt/with-current-user (mt/user->id :crowberto)
+ (doseq [bad [["not-a-card-ref"] [{:not "a card"}] [42.5]]]
+ (let [ex (try (pulse.api/update-pulse-with-perm-checks! Integer/MAX_VALUE {:cards bad})
+ nil
+ (catch clojure.lang.ExceptionInfo e e)
+ (catch Throwable e e))]
+ (is (instance? clojure.lang.ExceptionInfo ex)
+ (str "expected an ExceptionInfo (status-carrying), got " (some-> ex type) " for " (pr-str bad)))
+ (is (= 400 (:status-code (ex-data ex)))
+ (str "expected a 400 for a bad :cards ref " (pr-str bad))))))))
+
+(deftest tenant-hidden-recipients-survive-update-test
+ (mt/when-ee-evailable
+ (testing "a tenant-scoped caller that reads a pulse and submits it back must not delete the
+ recipients the read filter hid from it. The submitted :channels are authoritative
+ (update-notification-channels! deletes anything absent), so every recipient hidden on
+ read is merged back on write."
+ (mt/with-premium-features #{:tenants}
+ ;; Build the fixture as an admin: Pulse/PulseCard/PulseChannel writes run permission checks,
+ ;; and this test is about the update path, not about who may create a subscription.
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "PulseRT T1" :slug "pulse-rt-t1"}
+ :model/Tenant {other-tenant-id :id} {:name "PulseRT T2" :slug "pulse-rt-t2"}
+ :model/User {caller-id :id} {:tenant_id tenant-id}
+ :model/User {same-id :id} {:tenant_id tenant-id}
+ :model/User {other-id :id} {:tenant_id other-tenant-id}
+ :model/User {internal-id :id} {}
+ :model/Card {card-id :id} {}
+ :model/Pulse {pulse-id :id} {:name "Round trip"}
+ :model/PulseCard _ {:pulse_id pulse-id :card_id card-id}
+ :model/PulseChannel {chan-id :id} {:pulse_id pulse-id
+ :channel_type :email
+ :schedule_type :daily
+ :schedule_hour 12
+ :details {}}]
+ (doseq [uid [same-id other-id internal-id]]
+ (t2/insert! :model/PulseChannelRecipient {:pulse_channel_id chan-id :user_id uid}))
+ (let [recipient-ids #(t2/select-fn-set :user_id :model/PulseChannelRecipient
+ :pulse_channel_id chan-id)]
+ (is (= #{same-id other-id internal-id} (recipient-ids))
+ "all three user recipients exist before the round trip")
+ ;; The tenant caller must be able to write the pulse, otherwise the update 403s before
+ ;; it ever reaches the recipient merge this test is about. Collection permissions are
+ ;; orthogonal to the recipient filtering under test.
+ (with-redefs [mi/can-write? (constantly true)
+ mi/current-user-has-full-permissions? (constantly true)]
+ (mt/with-current-user caller-id
+ (let [read-back (-> (models.pulse/retrieve-pulse pulse-id)
+ models.pulse/maybe-filter-pulse-recipients)
+ visible (->> read-back :channels (mapcat :recipients) (keep :id) set)]
+ (testing "the read filter hides the other-tenant and tenantless recipients"
+ (is (= #{same-id} visible)))
+ (testing "submitting what was read back preserves the hidden recipients"
+ (pulse.api/update-pulse-with-perm-checks! pulse-id (select-keys read-back [:channels]))
+ (is (= #{same-id other-id internal-id} (recipient-ids))
+ "hidden recipients must survive; if they are gone the read filter silently deleted them"))))))))))))
diff --git a/test/metabase/pulse/models/pulse_test.clj b/test/metabase/pulse/models/pulse_test.clj
index a447b6c3fab..bd325823f93 100644
--- a/test/metabase/pulse/models/pulse_test.clj
+++ b/test/metabase/pulse/models/pulse_test.clj
@@ -561,3 +561,42 @@
{:cards [(assoc card :include_xls true)]
:dashboard_id nil
:collection_id nil}))))))))))
+
+(deftest maybe-filter-pulses-recipients-cross-tenant-test
+ ;; Tenants are enterprise-only: :model/Tenant is not on the OSS classpath, so guard the body out
+ ;; of OSS builds entirely (with-premium-features only flips the flag, it does not load EE code).
+ (mt/when-ee-evailable
+ (testing "GHY-4140: for a non-superuser, the recipient filter drops other-tenant users but
+ keeps same-tenant users. The comparison must deref *current-user* (an atom); reading
+ :tenant_id off the atom itself is always nil, which wrongly drops every tenant user."
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "GHY4140 T1" :slug "ghy4140-t1"}
+ :model/Tenant {other-tenant-id :id} {:name "GHY4140 T2" :slug "ghy4140-t2"}
+ :model/User {caller-id :id} {:tenant_id tenant-id}
+ :model/User {same-id :id} {:tenant_id tenant-id}
+ :model/User {other-id :id} {:tenant_id other-tenant-id}
+ :model/User {internal-id :id} {}]
+ ;; Production recipient maps come from the :recipients hydration, which selects only
+ ;; id/email/name fields — no :tenant_id — so the recipients here carry ids only. The
+ ;; filter must work on that shape, which is why it looks tenant membership up from the
+ ;; app DB instead of reading it off the map.
+ (let [pulses [{:channels [{:recipients [{:id same-id}
+ {:id other-id}
+ {:id internal-id}
+ {:email "[email protected]"}]}]}]]
+ (mt/with-current-user caller-id
+ (let [kept (-> (models.pulse/maybe-filter-pulses-recipients pulses)
+ first :channels first :recipients)]
+ (testing "same-tenant Metabase user survives"
+ (is (some #(= same-id (:id %)) kept)))
+ (testing "other-tenant Metabase user is redacted"
+ (is (not (some #(= other-id (:id %)) kept))))
+ (testing "an internal (tenantless) user is redacted too: a tenant caller sees only its own tenant"
+ (is (not (some #(= internal-id (:id %)) kept))))
+ (testing "raw email recipient is always preserved"
+ (is (some #(= "[email protected]" (:email %)) kept)))))
+ (testing "a caller with no tenant sees recipients unfiltered, as before tenants existed"
+ (mt/with-current-user internal-id
+ (is (= [{:id same-id} {:id other-id} {:id internal-id} {:email "[email protected]"}]
+ (-> (models.pulse/maybe-filter-pulses-recipients pulses)
+ first :channels first :recipients)))))))))))
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index c8afe7b4e6c..c67fd240109 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -159,6 +159,35 @@
(testing "after reactivation the same token STILL does not authenticate"
(is (nil? (:metabase-user-id (merge-current-user-info (bearer-request token))))))))))))
+(deftest resolve-access-token-deactivated-user-test
+ (testing "S1: a still-live token for a user who has since been deactivated does NOT resolve — the shared
+ resolver gates on is_active so the v1 MCP transport (which dispatches straight on :user-id,
+ with no is_active re-check of its own) can't authenticate a deactivated user's bearer token"
+ ;; Deactivates with a raw UPDATE, not `t2/update! :model/User`: the model's before-update hook fires
+ ;; `:event/user-credentials-revoked`, whose handler stamps `revoked_at` on the token and would make the
+ ;; store lookup fail first — the resolver's own is_active gate would never be what this test exercises.
+ ;; The raw UPDATE is exactly the path the gate exists for.
+ ;; Uses :rasta (a shared fixture user) but restores `is_active` and deletes the token in a `finally`,
+ ;; so the deactivation can't leak to sibling tests. A rollback-only transaction does NOT isolate the
+ ;; update from tests running on other connections; a `with-temp` user hits an FK on teardown because the
+ ;; token row still references it.
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :rasta)
+ token (str (random-uuid))]
+ (try
+ (save-access-token! token user-id client-id [oauth-server/full-access-scope] (in-one-hour))
+ (testing "resolves while the user is active"
+ (is (= user-id (:user-id (oauth-server/resolve-access-token token)))))
+ (t2/query {:update :core_user :set {:is_active false} :where [:= :id user-id]})
+ (testing "stops resolving once the user is deactivated"
+ (is (nil? (oauth-server/resolve-access-token token)))
+ (testing "and the token itself was not revoked — the resolver's gate did the refusing"
+ (is (nil? (t2/select-one-fn :revoked_at :model/OAuthAccessToken :token token)))))
+ (finally
+ (t2/query {:update :core_user :set {:is_active true} :where [:= :id user-id]})
+ (t2/delete! :model/OAuthAccessToken :token token))))))))
+
(deftest bearer-bridge-precedence-test
(testing "session/api-key auth takes precedence — bearer resolution is not even attempted"
(let [called? (atom false)]
diff --git a/test/metabase/server/streaming_response_test.clj b/test/metabase/server/streaming_response_test.clj
index 6490d3156ea..6b3d8782a96 100644
--- a/test/metabase/server/streaming_response_test.clj
+++ b/test/metabase/server/streaming_response_test.clj
@@ -575,7 +575,8 @@
os
finished-chan
canceled-chan
- (AtomicBoolean. false))
+ (AtomicBoolean. false)
+ nil)
(is (true? (deref task-started? 5000 ::timed-out)))
(a/>!! canceled-chan ::request-canceled)
(is (true? (deref interrupted? 5000 ::timed-out)))
@@ -639,7 +640,8 @@
os
finished-chan
canceled-chan
- completed?)
+ completed?
+ nil)
(is (true? (.await task-started 5 TimeUnit/SECONDS))
"Worker thread should start")
(.set completed? true)
@@ -649,3 +651,31 @@
(a/timeout 5000) ([_] ::timed-out)))))))
(is (false? (.await complete-called 100 TimeUnit/MILLISECONDS))
"Worker thread should not call .complete when timeout already completed the context"))))))
+
+(deftest do-f-async-custom-executor-test
+ (testing "the :executor option runs `f` on that executor instead of the shared streaming pool"
+ (let [executor (java.util.concurrent.Executors/newSingleThreadExecutor
+ (reify java.util.concurrent.ThreadFactory
+ (newThread [_ r]
+ (doto (Thread. ^Runnable r) (.setName "custom-streaming-executor")))))
+ ran-on (promise)
+ finished-chan (a/promise-chan)
+ canceled-chan (a/promise-chan)]
+ (try
+ (with-open [os (java.io.ByteArrayOutputStream.)]
+ (#'streaming-response/do-f-async
+ (reify AsyncContext
+ (complete [_] nil))
+ nil
+ nil
+ (fn [_os _canceled-chan]
+ (deliver ran-on (.getName (Thread/currentThread))))
+ os
+ finished-chan
+ canceled-chan
+ (AtomicBoolean. false)
+ executor)
+ (is (= "custom-streaming-executor" (deref ran-on 5000 ::timed-out)))
+ (is (= :completed (a/<!! finished-chan))))
+ (finally
+ (.shutdownNow executor))))))