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
Add data-apps scope to BE endpoints to prevent calling unmarked endpoints from inside a data app (#79382)
Timofey Kachalov7994ad35d8a3
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 670b4009929..66a6a0514ab 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -137,6 +137,7 @@:uses #{actionsanalyticsapi+ api-scopeapi.eid-translationcollectionslib@@ -317,7 +318,9 @@api-scope{:team "Metabot":api #{metabase.api-scope.core- metabase.api-scope.init}}+ metabase.api-scope.data-app+ metabase.api-scope.init}+ :uses #{util}}api.eid-translation{:team "UX West"@@ -640,6 +643,7 @@:ns-prefix "metabase.collections-rest":api #{metabase.collections-rest.api}:uses #{api+ api-scopeapi.eid-translationcollectionsdocuments@@ -795,6 +799,7 @@:uses #{actionsanalyticsapi+ api-scopeapi.eid-translationapp-dbchannel@@ -1735,6 +1740,7 @@{:team "Graphy":api #{metabase.native-query-snippets.api metabase.native-query-snippets.core metabase.native-query-snippets.schema}:uses #{api+ api-scopecollectionseventslib@@ -2109,6 +2115,7 @@:ns-prefix "metabase.queries-rest":api #{metabase.queries-rest.api}:uses #{api+ api-scopeapi.eid-translationcollectionsembedding@@ -2194,6 +2201,7 @@:uses #{analyticsanalytics.interfaceapi+ api-scopeapp-dbappearanceaudit-app@@ -2388,6 +2396,7 @@:uses #{analyticsanalytics.interfaceapi+ api-scopeapp-dbappearanceaudit-app@@ -2469,6 +2478,7 @@analytics.interfaceapiapi-keys+ api-scopeapp-dbappearancecore.initialization-status@@ -2503,6 +2513,7 @@metabase.session.schemametabase.session.settings} ; TODO -- shouldn't be exposed as an API namespace:uses #{api+ api-scopeapp-dbchannelevents@@ -2809,6 +2820,7 @@metabase.timeline.core}:uses #{analyticsapi+ api-scopecollectionseventslib.schema@@ -3045,6 +3057,7 @@:api #{metabase.user-key-value.apimetabase.user-key-value.init}:uses #{api+ api-scopelib.schemautilutil.config}}@@ -3088,6 +3101,7 @@:ns-prefix "metabase.users-rest":api #{metabase.users-rest.api}:uses #{api+ api-scopeappearancecollectionsevents@@ -3188,6 +3202,7 @@:api #{metabase.warehouses-rest.api}:uses #{analyticsapi+ api-scopeapp-dbcollectionsdatabase-routing@@ -3276,6 +3291,7 @@:api #{metabase.warehouse-schema-rest.api}:uses #{analyticsapi+ api-scopeapp-dbcollectionsdatabase-routing@@ -3578,6 +3594,7 @@{:team "UX West":api #{metabase-enterprise.content-translation.routes}:uses #{api+ api-scopecontent-translationembeddingpremium-features@@ -3607,6 +3624,7 @@metabase-enterprise.custom-viz-plugin.initmetabase-enterprise.custom-viz-plugin.settings}:uses #{api+ api-scopeeventsmodelspremium-features@@ -3620,6 +3638,7 @@{:team "Embedding":api #{metabase-enterprise.data-apps.api metabase-enterprise.data-apps.init metabase-enterprise.data-apps.sync}:uses #{api+ api-scopecollectionsliblib.be@@ -4010,6 +4029,7 @@:ns-prefix "metabase-enterprise.sandbox":api #{metabase-enterprise.sandbox.api.routes metabase-enterprise.sandbox.api.util metabase-enterprise.sandbox.schema}:uses #{api+ api-scopeapp-dbaudit-appdriverdiff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsxindex 9818e3577eb..ea1de5ae100 100644--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx@@ -64,7 +64,10 @@ function Overview() {<h2 style={{ margin: "0 0 8px" }}>All orders</h2><div style={{ height: 400 }}>{ordersQuery.query ? (- <InteractiveQuestion card={{ query: ordersQuery.query }} />+ <InteractiveQuestion+ card={{ query: ordersQuery.query }}+ withDownloads+ />) : (<div>…</div>)}diff --git a/e2e/support/cypress.js b/e2e/support/cypress.jsindex 727e74e704e..43e561aaf76 100644--- a/e2e/support/cypress.js+++ b/e2e/support/cypress.js@@ -7,6 +7,12 @@ import "@testing-library/cypress/add-commands";import { configure } from "@testing-library/cypress";import "cypress-real-events/support";import addContext from "mochawesome/addContext";++import {+ assertNoDataAppScopeDenials,+ resetDataAppScopeGuard,+} from "e2e/support/helpers/e2e-data-app-helpers";+import "./commands";// Must stay imported after "@cypress/code-coverage/support": its afterEach// zeroes the window coverage counters after collecting each test's fires,@@ -196,3 +202,8 @@ beforeEach(function () {}).as("globalIntercept");}});++// A data app's scope rejections are recorded by the intercept H.openDataApp installs; see+// e2e/support/helpers/e2e-data-app-helpers.ts.+beforeEach(resetDataAppScopeGuard);+afterEach(assertNoDataAppScopeDenials);diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.tsindex 1be88140d29..f212c0f8819 100644--- a/e2e/support/helpers/e2e-data-app-helpers.ts+++ b/e2e/support/helpers/e2e-data-app-helpers.ts@@ -16,8 +16,10 @@ import { LOCAL_GIT_PATH } from "./e2e-remote-sync-helpers";export const DATA_APP_NAME = "kitchen-sink";export const DATA_APP_DISPLAY_NAME = "Kitchen Sink";-export const visitDataAppRoute = (route: string) =>- cy.visit(`/apps/${DATA_APP_NAME}/${route}`);+export const visitDataAppRoute = (route: string) => {+ installDataAppScopeGuard();+ return cy.visit(`/apps/${DATA_APP_NAME}/${route}`);+};export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({id: 1,@@ -104,7 +106,71 @@ export const mockDataApp = <TestEnv = DataAppTestEnv>(});};+/**+ * The two rejections endpoint scope enforcement can emit. `scope_not_permitted` comes from+ * `ensure-scopes-checked` — the endpoint declares no `:scope` at all, so a narrowed request+ * may not reach it. `unsupported_scope` comes from `enforce-scope` — the endpoint is scoped,+ * but not for the scope the request carries. Either one inside a data app means a route the+ * SDK really uses was never tagged `data-apps:base`.+ */+const SCOPE_ERRORS = ["scope_not_permitted", "unsupported_scope"];++let scopeDenials: string[] = [];+let scopeGuardInstalled = false;++/**+ * Records every scope rejection the backend returns while a data app is open. Every request a+ * sandboxed app makes is marked `X-Metabase-Client: data-app` and confined to `data-apps:base`,+ * so a rejection here is a route missing its `{:scope api-scope/data-app}` tag, not a+ * permission problem. `assertNoDataAppScopeDenials` (a root `afterEach`) fails the test on any.+ */+function installDataAppScopeGuard() {+ if (scopeGuardInstalled) {+ return;+ }+ scopeGuardInstalled = true;++ cy.intercept("/api/**", (req) => {+ // `after:response` rather than a `req.continue` callback: the latter buffers the body,+ // which would sit in front of the streamed `/api/dataset` responses.+ req.on("after:response", (res) => {+ // `res.body` is whatever the endpoint returned; the scope middleware answers with a+ // JSON `{error, message}` body.+ const error = (res.body as { error?: string } | undefined)?.error;+ if (+ res.statusCode === 403 &&+ error !== undefined &&+ SCOPE_ERRORS.includes(error)+ ) {+ scopeDenials.push(+ `${req.method} ${new URL(req.url).pathname} -> ${error}`,+ );+ }+ });+ });+}++/** Root `beforeEach` in `e2e/support/cypress.js`: intercepts reset between tests, so must this record. */+export function resetDataAppScopeGuard() {+ scopeDenials = [];+ scopeGuardInstalled = false;+}++/** Root `afterEach` in `e2e/support/cypress.js`. Only a test that opened a data app pays for it. */+export function assertNoDataAppScopeDenials() {+ if (!scopeGuardInstalled) {+ return;+ }+ cy.then(() => {+ expect(+ scopeDenials,+ `data-app scope rejections:\n${scopeDenials.join("\n")}`,+ ).to.be.empty;+ });+}+export function openDataApp(slug: string) {+ installDataAppScopeGuard();return cy.visit(Urls.dataApp(slug));}diff --git a/e2e/test/scenarios/data-apps/backend_scope.cy.spec.ts b/e2e/test/scenarios/data-apps/backend_scope.cy.spec.tsnew file mode 100644index 00000000000..1ae11773849--- /dev/null+++ b/e2e/test/scenarios/data-apps/backend_scope.cy.spec.ts@@ -0,0 +1,110 @@+import {+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,+ DATA_APP_NAME as APP_NAME,+} from "e2e/support/helpers";++import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";++const { H } = cy;++const TIMEOUT = 30000;++describe("scenarios > data apps > backend scope", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ /**+ * The unit and middleware tests can only assert the endpoints we already thought to list.+ * This one works the other way round: drive the SDK surface a data app actually exposes and+ * let the backend tell us what it refuses. The scope guard `H.openDataApp` installs records+ * every rejection and the root `afterEach` fails the test on any, so this spec only has to+ * exercise the surface.+ */+ it("serves the whole InteractiveQuestion surface without refusing a request for scope", () => {+ H.mockDataApp(APP_NAME, {+ displayName: APP_DISPLAY_NAME,+ testEnv: TEST_ENV,+ });+ H.openDataApp(APP_NAME);++ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("data-app-content", { timeout: TIMEOUT }).should("exist");++ // The toolbar only mounts once the first query has come back, so this doubles as the+ // wait for `/api/dataset`.+ cy.findByTestId("interactive-question-result-toolbar", {+ timeout: TIMEOUT,+ }).should("exist");++ cy.log("Chart type picker — loads visualization metadata");+ cy.findByTestId("chart-type-selector-button").click();+ cy.findByText("More charts").should("be.visible");+ // Toggle the trigger to close: key events would land on the parent document, not the+ // iframe, and Mantine treats a stray Escape as a modal dismiss.+ cy.findByTestId("chart-type-selector-button").click();++ cy.log("Visualization settings");+ cy.findByTestId("viz-settings-button").click();+ cy.findByTestId("viz-settings-button").click();++ cy.log("Filter picker — loads table metadata and field values");+ cy.findByTestId("filter-dropdown-button").click();+ // This `within` is the whole iframe, so a column name also matches the table+ // rendered behind the picker. Pick from the popover the button just opened.+ cy.get('[data-element-id="mantine-popover"]')+ .should("have.length.above", 0)+ .last()+ .within(() => {+ cy.findByText("Total").click();+ });+ cy.findByText("Add filter").click();++ cy.log("Summarize picker — loads the aggregation/column pickers");+ // The button is labelled by how many summaries the question has, and with+ // none it opens the aggregation picker directly — the badge list, with its+ // "Add another summary", is what a question that already aggregates opens.+ cy.findByText("Summarize").click();+ cy.findByTestId("aggregation-picker").should("be.visible");+ cy.findByText("Summarize").click();++ cy.log("Group-by picker");+ cy.findByText("Group").click();+ cy.findByText("Group").click();++ cy.log(+ "Download menu — loads the export formats and downloads preference",+ );+ cy.findByTestId("question-download-widget-button").click();+ cy.findByTestId("question-download-widget-button").click();++ cy.log("Notebook editor — loads databases, schemas, tables and fields");+ cy.findByTestId("notebook-button").click();+ cy.findByText("Back to visualization", { timeout: TIMEOUT }).should(+ "be.visible",+ );++ cy.log("Add a notebook filter step");+ cy.findByTestId("action-buttons").findByText("Filter").click();+ cy.get('[data-element-id="mantine-popover"]')+ .should("have.length.above", 0)+ .last()+ .within(() => {+ // A sparse float has no cached field values, so the picker defaults to+ // Between and offers Min/Max. A low-cardinality column like Quantity+ // defaults to `=` and offers a value list instead.+ cy.findByText("Discount").click();+ });+ cy.findByPlaceholderText("Min").type("2");+ cy.findByText("Add filter").click();++ cy.log("Re-run the edited query");+ cy.findByText("Visualize").click();+ cy.findByText("Back to visualization", { timeout: TIMEOUT }).should(+ "not.exist",+ );+ });+ });+});diff --git a/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts b/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.tsindex 515ae37b075..dd51946489e 100644--- a/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts@@ -12,7 +12,7 @@ describe("scenarios > data apps > sandbox isolation", () => {H.activateToken("bleeding-edge");});- const setUp = () => {+ const setup = () => {const instanceUrl = Cypress.config("baseUrl") ?? "";const testEnv: IsolationTestEnv = { instanceUrl };@@ -63,177 +63,177 @@ describe("scenarios > data apps > sandbox isolation", () => {};it("keeps a document.createElement about:blank iframe within the gated realm", () => {- setUp();+ setup();runProbe("isolation-create-element");});it("gates a host-React about:blank iframe", () => {- setUp();+ setup();runProbeExpectingGuard("isolation-react-about-blank");});it("gates an iframe pointing at Metabase itself", () => {- setUp();+ setup();runProbeExpectingGuard("isolation-react-src");});it("gates a srcdoc iframe", () => {- setUp();+ setup();runProbeExpectingGuard("isolation-react-srcdoc");});it("keeps a window.open realm within the gated realm", () => {- setUp();+ setup();runProbe("isolation-window-open");});it("gates the Worker constructor", () => {- setUp();+ setup();runProbe("isolation-worker");});it("gates the SharedWorker constructor", () => {- setUp();+ setup();runProbe("isolation-shared-worker");});it("gates the service worker registration API", () => {- setUp();+ setup();runProbe("isolation-service-worker");});it("gates dynamic import", () => {- setUp();+ setup();runProbe("isolation-dynamic-import");});it("keeps a dangerouslySetInnerHTML iframe within the gated realm", () => {- setUp();+ setup();runProbe("isolation-inner-html");});it("keeps a Function-constructor fetch gated", () => {- setUp();+ setup();runProbe("isolation-function-constructor");});it("keeps a DOMParser iframe within the gated realm", () => {- setUp();+ setup();runProbe("isolation-dom-parser");});it("keeps a createHTMLDocument iframe adopted into the realm gated", () => {- setUp();+ setup();runProbe("isolation-adopt-html-doc-iframe");});it("keeps a createHTMLDocument iframe imported into the realm gated", () => {- setUp();+ setup();runProbe("isolation-import-html-doc-iframe");});it("keeps a createDocument iframe adopted into the realm gated", () => {- setUp();+ setup();runProbe("isolation-xml-doc-iframe");});it("keeps a template owner-document iframe adopted into the realm gated", () => {- setUp();+ setup();runProbe("isolation-template-doc-iframe");});it("keeps a raw API out of the SDK endowments", () => {- setUp();+ setup();runProbe("isolation-endowment-api");});it("keeps an Error.prepareStackTrace realm reference gated", () => {- setUp();+ setup();runProbe("isolation-stack-trace-realm");});it("keeps window.parent within the gated realm", () => {- setUp();+ setup();runProbe("isolation-window-parent");});it("keeps window.top within the gated realm", () => {- setUp();+ setup();runProbe("isolation-window-top");});it("keeps window.frameElement's owner realm gated", () => {- setUp();+ setup();runProbe("isolation-frame-element");});it("keeps window.parent.parent within the gated realm", () => {- setUp();+ setup();runProbe("isolation-parent-chain");});it("gates document.cookie on the parent realm", () => {- setUp();+ setup();runProbe("isolation-parent-cookie");});it("gates localStorage on the parent realm", () => {- setUp();+ setup();runProbe("isolation-parent-local-storage");});it("gates sessionStorage on the parent realm", () => {- setUp();+ setup();runProbe("isolation-parent-session-storage");});it("gates indexedDB on the parent realm", () => {- setUp();+ setup();runProbe("isolation-parent-indexeddb");});it("gates caches on the parent realm", () => {- setUp();+ setup();runProbe("isolation-parent-caches");});it("keeps indexed window.frames access gated", () => {- setUp();+ setup();runProbe("isolation-window-frames");});it("keeps window.opener's realm gated", () => {- setUp();+ setup();runProbe("isolation-window-opener");});it("gates FontFace.load", () => {- setUp();+ setup();runProbe("isolation-font-face");});it("gates cookieStore", () => {- setUp();+ setup();runProbe("isolation-cookie-store");});it("gates performance resource timing", () => {- setUp();+ setup();runProbe("isolation-perf-resource-timing");});it("keeps a Range.createContextualFragment iframe within the gated realm", () => {- setUp();+ setup();runProbe("isolation-range-fragment-iframe");});it("keeps a custom element's upgrade callback in the gated realm", () => {- setUp();+ setup();runProbe("isolation-custom-element");});it("keeps a host iframe's realm gated", () => {- setUp();+ setup();// A srcless (about:blank) iframe is same-origin, so its `contentWindow` is a// live realm with an un-gated `fetch` — the same capability html2canvas's@@ -289,4 +289,37 @@ describe("scenarios > data apps > sandbox isolation", () => {runProbe("isolation-allowed-host-redirect");});++ // The 403s the marker produces are backend behaviour, covered by+ // `data_app_scope_test.clj`. What only e2e can prove is the premise those 403s rest+ // on: that the real transport stamps `X-Metabase-Client: data-app` on the requests the+ // SDK makes from inside the sandbox. The header cannot be spoofed to gain access —+ // host-realm code the membraned guest can't reach sets it, and it only ever narrows —+ // but if it ever stopped being sent, the confinement would silently stop applying.+ it("marks the requests the SDK makes from inside the sandbox as data-app", () => {+ const markedPaths = new Set<string>();++ cy.intercept("/api/**", (req) => {+ if (req.headers["x-metabase-client"] === "data-app") {+ markedPaths.add(new URL(req.url).pathname);+ }+ });++ setup();++ // Wait for the guest bundle to have rendered — the SDK's bootstrap requests are+ // still in flight while it loads, so asserting earlier races them.+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("isolation-result", { timeout: 30000 }).should("exist");+ });++ // `/api/user/current` is the whole marked surface this fixture produces — it renders+ // isolation probes, not questions, and the SDK's bootstrap takes site settings from+ // the auth prefetch rather than refetching `/api/session/properties`.+ cy.then(() => {+ expect([...markedPaths], "requests marked as data-app").to.include(+ "/api/user/current",+ );+ });+ });});diff --git a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj b/enterprise/backend/src/metabase_enterprise/content_translation/routes.cljindex 26bc56ffa24..80124e4cab0 100644--- a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj@@ -5,6 +5,7 @@[clojure.string :as str][metabase-enterprise.api.core :as ee.api][metabase-enterprise.content-translation.dictionary :as dictionary]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.content-translation.models :as ct]@@ -101,6 +102,7 @@(api.macros/defendpoint :get "/dictionary" :- DictionaryResponse"Fetch the content translation dictionary for authenticated users (auth-based embedding flows)."+ {:scope api-scope/data-app}[_route-params{:keys [locale]} :- [:map {:closed true} [:locale :string]]](api/check api/*current-user-id* 401 "Unauthenticated")diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.cljindex 7979ff4be7e..d4a71ebde7c 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj@@ -7,6 +7,7 @@[metabase-enterprise.custom-viz-plugin.db :as custom-viz-plugin.db][metabase-enterprise.custom-viz-plugin.manifest :as manifest][metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -209,6 +210,7 @@"List active and enabled custom visualization plugins. Available to any authenticated user.Plugins with version mismatches are included, with soft `warnings` attached.Dev-only plugins are excluded when dev mode is disabled."+ {:scope api-scope/data-app}[](let [dev-mode? (custom-viz.settings/custom-viz-plugin-dev-mode-enabled)plugins (custom-viz-plugin.db/active-enabled-non-blob-plugins)]@@ -281,6 +283,7 @@"Serve the JS bundle for a plugin from the on-disk cache.Returns application/javascript with ETag and Cache-Control headers.In dev mode, proxies from `dev_bundle_url` if set."+ {:scope api-scope/data-app}[{:keys [id], :as _route-params} :- [:map {:closed true} [:id ms/PositiveInt]]_query-params_body@@ -313,6 +316,7 @@and must match the manifest `icon`. Only the icon is served — plugins do notship arbitrary assets.In dev mode, proxies from the dev base URL if set."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]{:keys [path]} :- [:map {:closed true} [:path ms/NonBlankString]]_bodydiff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex dcf79e47ac2..54c3ddb94d1 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -13,6 +13,7 @@[metabase-enterprise.data-apps.query-definition :as query-definition][metabase-enterprise.data-apps.sync :as data-app.sync][metabase-enterprise.data-apps.user-access :as data-app.user-access]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -404,6 +405,10 @@(data-app.sync/ensure-draft! slug)(data-app-response (data-apps.db/non-blob-data-app-by-slug slug)))+;; Not tagged `data-apps:base`, though the bundle route below is — which looks backwards until+;; you place the two callers. `DataAppView` fetches this metadata on the *host* page to decide+;; what iframe to render, before any data-app realm exists, so the request never carries the+;; marker. The bundle is fetched from inside that iframe, where it does.(api.macros/defendpoint :get ["/:slug" :slug slug-regex] :- [:or DataAppResponse PublicDataAppResponse]"Fetch metadata for a single enabled data app by its slug."[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]@@ -413,6 +418,7 @@(api.macros/defendpoint :get ["/:slug/bundle" :slug slug-regex] :- :any"Serve the cached JS bundle for a single enabled data app by slug. Honors`If-None-Match` against the content-hash ETag with a 304."+ {:scope api-scope/data-app}[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]_query-params_bodydiff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.cljindex 6a65ca89e76..779a7273c28 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj@@ -3,6 +3,7 @@[metabase-enterprise.sandbox.api.column-filter :as col-filter][metabase-enterprise.sandbox.api.util :as sandbox.api.util][metabase-enterprise.sandbox.db :as sandbox.db]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.permissions.core :as perms]@@ -76,6 +77,7 @@excluded from what is show in the query builder. When the user has full permissions (or no permissions) this routedoesn't add/change anything from the OSS version. See the docs on the OSS version of the endpoint for moreinformation."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include_sensitive_fields include_hidden_fields include_editable_data_model]}diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/table_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/table_test.cljindex 3e0d9683831..e8d2009395f 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/table_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/table_test.clj@@ -35,6 +35,18 @@(is (= all-columns(field-names :crowberto)))))))+(deftest query-metadata-data-app-scope-test+ (testing "GET /api/table/:id/query_metadata carries the data-app scope even under sandboxing"+ ;; Regression: the EE sandbox *replaces* the OSS query_metadata endpoint when sandboxing is active,+ ;; so it must be tagged `{:scope api-scope/data-app}` too — otherwise a sandboxed data app gets+ ;; scope_not_permitted (403) on tables it can otherwise read.+ (met/with-gtaps! {:gtaps {:venues {:query (mt.tu/restricted-column-query (mt/id))}}+ :attributes {:cat 50}}+ (let [as-data-app {:request-options {:headers {"x-metabase-client" "data-app"}}}]+ (testing "a data-app-marked request passes scope enforcement (not scope_not_permitted)"+ (is (mt/user-http-request :rasta :get 200+ (format "table/%d/query_metadata" (mt/id :venues)) as-data-app)))))))+(deftest query-metadata-not-sandboxed-for-admins-test(testing "GET /api/table/:id/query_metadata";; checks that admins are exempt from normal perms checking.diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsxindex 7941aae475a..6a9f0532271 100644--- a/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx@@ -4,6 +4,7 @@ import { ToolbarButton } from "metabase/common/components/ToolbarButton";import { useHasEmailSetup } from "metabase/common/hooks";import { toggleSharing } from "metabase/dashboard/actions";import { useDashboardContext } from "metabase/dashboard/context";+import { isDataApp } from "metabase/embedding-sdk/config";import type { DashboardSubscriptionsButtonProps } from "metabase/plugins";import { useDispatch } from "metabase/redux";@@ -25,9 +26,15 @@ export const DashboardSubscriptionsButton = (const hasDataCards = dashboard?.dashcards?.some((dashCard) => !["text", "heading"].includes(dashCard.card.display),);+ // A data app renders a UI; a subscription is scheduled email delivered later, out of band.+ // It is deliberately not part of the data-app surface, so the affordance never appears+ // rather than appearing and failing on the (unscoped) /api/pulse routes behind it.+ const isDataAppEmbed = isDataApp();+// We decided not to show the subscriptions button if email is not set up- const hasEmailSetup = useHasEmailSetup();- if (!hasEmailSetup || !hasDataCards) {+ const hasEmailSetup = useHasEmailSetup({ skip: isDataAppEmbed });++ if (!hasEmailSetup || !hasDataCards || isDataAppEmbed) {return null;}diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsxindex f5814533692..b91b9517737 100644--- a/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsx@@ -10,6 +10,7 @@ import { setupDashcardQueryEndpoints } from "__support__/server-mocks/dashcard";import { mockSettings } from "__support__/settings";import { renderWithProviders } from "__support__/ui";import { DashboardContextProvider } from "metabase/dashboard/context";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import type { DashboardCard } from "metabase-types/api";import {createMockCard,@@ -42,11 +43,15 @@ const tableDashcard = createMockDashboardCard({interface SetupOpts {dashcards?: DashboardCard[];emailConfigured?: boolean;+ isDataApp?: boolean;}const setup = ({emailConfigured,dashcards = [tableDashcard],+ isDataApp = false,}: SetupOpts = {}) => {+ EMBEDDING_SDK_CONFIG.isDataApp = isDataApp;+setupNotificationChannelsEndpoints({email: {configured: emailConfigured,@@ -71,6 +76,10 @@ const setup = ({};describe("DashboardSubscriptionsButton", () => {+ afterEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = false;+ });+it("should render the subscriptions button when email is configured", async () => {setup({ emailConfigured: true });@@ -107,6 +116,22 @@ describe("DashboardSubscriptionsButton", () => {screen.queryByRole("button", { name: "Subscriptions" }),).not.toBeInTheDocument();});++ it("should not render the subscriptions button and should not call pulse/form_input inside a data app", async () => {+ // A subscription is scheduled email delivered out of band, so it is not part of the+ // data-app surface. `/api/pulse` is unscoped for data apps, so a subscriptions button+ // offered here would 403 as soon as it was clicked.+ setup({ emailConfigured: true, isDataApp: true });++ await waitFor(async () => {+ expect(await getDashboardRequests()).toHaveLength(1);+ });++ expect(+ screen.queryByRole("button", { name: "Subscriptions" }),+ ).not.toBeInTheDocument();+ expect(await getSubscriptionChannelInfoRequests()).toHaveLength(0);+ });});function setupDashboardRelatedEndpoints(diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsxindex 0d40d1def74..074a5f69c18 100644--- a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx@@ -8,6 +8,7 @@ import { useSdkSelector } from "embedding-sdk-bundle/store";import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import { useHasEmailSetup } from "metabase/common/hooks";import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/current-user";+import { isDataApp } from "metabase/embedding-sdk/config";import type { QuestionAlertsButtonProps } from "metabase/plugins";import { isInstanceAnalyticsCollection } from "metabase-enterprise/collections/utils";@@ -25,13 +26,21 @@ export const QuestionAlertsButton = (props: QuestionAlertsButtonProps) => {const isModel = question?.type() === "model";const isAnalytics = isInstanceAnalyticsCollection(question?.collection());+ // A data app renders a UI; an alert is scheduled email delivered later, out of band. It is+ // deliberately not part of the data-app surface, so the affordance never appears rather+ // than appearing and failing on the (unscoped) /api/notification routes behind it.+ const isDataAppEmbed = isDataApp();+// Skip the pulse/form_input request in guest embed mode (EMB-1525),// as the endpoint does not exist for guest embeds.- const hasEmailSetup = useHasEmailSetup({ skip: isGuestEmbed });+ const hasEmailSetup = useHasEmailSetup({+ skip: isGuestEmbed || isDataAppEmbed,+ });const shouldRenderAlertsButton =hasEmailSetup &&!isGuestEmbed &&+ !isDataAppEmbed &&withAlerts &&isSaved &&canManageSubscriptions &&diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsxindex e6f997ee147..65389a4275b 100644--- a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.unit.spec.tsx@@ -12,6 +12,7 @@ import {createMockLoginStatusState,createMockSdkState,} from "embedding-sdk-bundle/test/mocks/state";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import {createMockTokenFeatures,createMockUser,@@ -44,7 +45,12 @@ jest.mock(}),);-function setup({ isGuestEmbed }: { isGuestEmbed: boolean }) {+function setup({+ isGuestEmbed = false,+ isDataApp = false,+}: { isGuestEmbed?: boolean; isDataApp?: boolean } = {}) {+ EMBEDDING_SDK_CONFIG.isDataApp = isDataApp;+setupNotificationChannelsEndpoints({email: { configured: true },});@@ -81,6 +87,10 @@ async function getFormInputRequests() {}describe("QuestionAlertsButton", () => {+ afterEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = false;+ });+it("should render the alerts button and call pulse/form_input when not in guest embed mode", async () => {setup({ isGuestEmbed: false });@@ -102,4 +112,24 @@ describe("QuestionAlertsButton", () => {expect(await getFormInputRequests()).toHaveLength(0);});++ it("should not render the alerts button and should not call pulse/form_input inside a data app", async () => {+ // An alert is scheduled email delivered out of band, so it is not part of the data-app+ // surface. `/api/notification` is unscoped for data apps, so an alerts button offered here+ // would 403 as soon as it was clicked.+ setup({ isDataApp: true });++ // Give the probe the same window the first test needs to make it, and assert it never+ // arrives. Asserting straight after render would pass either way, since nothing has+ // resolved yet at that point.+ await expect(+ waitFor(async () => {+ expect(await getFormInputRequests()).toHaveLength(1);+ }),+ ).rejects.toThrow();++ expect(+ screen.queryByRole("button", { name: "Alerts" }),+ ).not.toBeInTheDocument();+ });});diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.cljindex dca582e9b5b..5e3c40ab410 100644--- a/src/metabase/actions_rest/api.clj+++ b/src/metabase/actions_rest/api.clj@@ -5,6 +5,7 @@[metabase.actions.core :as actions][metabase.actions.schema :as actions.schema][metabase.analytics.core :as analytics]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.eid-translation.core :as eid-translation]@@ -32,6 +33,7 @@(api.macros/defendpoint :get "/" :- [:sequential ::actions.schema/action]"Returns actions that can be used for QueryActions. By default lists all viewable actions. Pass optional`?model-id=<model-id>` to limit to actions on a particular model."+ {:scope api-scope/data-app}[_route-params{:keys [model-id]} :- [:map {:closed true}[:model-id {:optional true} [:maybe ::lib.schema.id/card]]]]@@ -55,6 +57,7 @@(api.macros/defendpoint :get "/:action-id" :- ::actions.schema/action"Fetch an Action."+ {:scope api-scope/data-app}[{:keys [action-id]} :- [:map {:closed true}[:action-id ms/PositiveInt]]](-> (actions/select-action :id action-id :archived false)@@ -193,6 +196,7 @@"Fetches the values for filling in execution parameters. Pass PK parameters and values to select.Parameters are sent in the request body rather than the query string so their values stay out of URLs and logs."+ {:scope api-scope/data-app}[{:keys [action-id]} :- [:map {:closed true}[:action-id ms/PositiveInt]]_query-params@@ -235,6 +239,7 @@"Execute the Action.`parameters` should be the mapped dashboard parameters with values."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ::actions.schema/id ms/NanoIdString]]]_query-paramsdiff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 90b1ad42e84..28039648505 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -1718,12 +1718,15 @@request without `:token-scopes` is not defaulted, so scope enforcement rejects it.- For **JWT-authenticated** requests, derives `:token-scopes` from the JWT when a`\"scope\"` claim is present, falls back to any pre-existing `:token-scopes` on the- request, and finally defaults to `#{::scope/unrestricted}` for unscoped JWTs.+ request, and finally defaults to `#{::scope/unrestricted}` for unscoped JWTs. A request+ [[metabase.server.middleware.data-app-scope]] already confined is the exception: its+ narrowing is a server-side decision and a caller-supplied `\"scope\"` claim may not+ widen it back out.This ensures downstream scope enforcement never has to special-case nil within theagent API."[handler]- (fn [{:keys [headers metabase-user-id token-scopes] :as request} respond raise]+ (fn [{:keys [headers metabase-user-id token-scopes data-app-scoped?] :as request} respond raise](cond;; Already authenticated via X-Metabase-Session or synthetic request (e.g. MCP dispatch).;; Preserve existing :token-scopes when present (MCP sets them on the synthetic request).@@ -1761,9 +1764,11 @@(log/warn "JWT scopes" (:scopes result)"differ from pre-existing token-scopes" token-scopes))(request/with-current-user (:id user)- (handler (assoc request :token-scopes (or (:scopes result)- token-scopes- #{::scope/unrestricted}))+ (handler (assoc request :token-scopes (if data-app-scoped?+ token-scopes+ (or (:scopes result)+ token-scopes+ #{::scope/unrestricted})))respond raise)))(respond (error-response (:error result) (:message result) "Bearer error=\"invalid_token\"")))))))))diff --git a/src/metabase/api_scope/data_app.clj b/src/metabase/api_scope/data_app.cljnew file mode 100644index 00000000000..bac39c62913--- /dev/null+++ b/src/metabase/api_scope/data_app.clj@@ -0,0 +1,36 @@+(ns metabase.api-scope.data-app+ "Scope declaration for sandboxed data-app requests.++ A data-app iframe runs untrusted, admin-uploaded code. Its SDK client stamps every request+ with `X-Metabase-Client: data-app` (from trusted host-realm code the guest can't reach); the+ [[metabase.server.middleware.data-app-scope]] middleware maps that onto this scope,+ confining the request to endpoints tagged `{:scope api-scope/data-app}` — the read/query+ surface a data app needs to render. Everything else fails closed via+ [[metabase.api.macros.scope/ensure-scopes-checked]].++ `data-apps:base` is the read/query tier. It is namespaced so a later tier (say a+ `data-apps:write` covering card/dashboard saves) can be added without another rename, and+ so `data-apps:*` stays available as the wildcard that covers both — see+ [[metabase.api-scope.core/scope-matches?]].++ Endpoints tag with the var rather than the string: the scope name is a wire contract that+ has already been renamed once, and a var keeps the next rename to this one line.++ What gets tagged: a route is tagged when the SDK actually calls it from inside a data app.+ Untagged is the default and is not a judgement that a route is dangerous — most untagged+ routes are writes, admin or auth surfaces, and the rest simply have no SDK caller. Where the+ omission is genuinely surprising — a read route sitting next to a tagged sibling, such as+ `GET /api/action/:action-id` beside the tagged execute routes — the reason is written at the+ endpoint itself, so \"why isn't this one tagged?\" is answered where the question is asked.++ Declared here (loaded early by [[metabase.api-scope.init]]) so the scope is registered before+ any endpoint namespace resolves the tag, mirroring how metabot declares its `agent:*` scopes+ in `metabase.metabot.scope`."+ (:require+ [metabase.api-scope.core :as api-scope]+ [metabase.util.i18n :refer [deferred-tru]]))++(set! *warn-on-reflection* true)++(api-scope/defscope data-app "data-apps:base"+ (deferred-tru "Read and query access for a sandboxed data app."))diff --git a/src/metabase/api_scope/init.clj b/src/metabase/api_scope/init.cljindex 7d936abe1bf..3f5e0020589 100644--- a/src/metabase/api_scope/init.clj+++ b/src/metabase/api_scope/init.clj@@ -1,3 +1,4 @@(ns metabase.api-scope.init(:require- [metabase.api-scope.core]))+ [metabase.api-scope.core]+ [metabase.api-scope.data-app]))diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex ce6f0bb83fb..4d2d4a482c4 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -6,6 +6,7 @@(:require[malli.core :as mc][malli.transform :as mtx]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.collections-rest.db :as collections-rest.db]@@ -70,6 +71,7 @@`?exclude-other-user-collections=true`.If personal-only is `true`, then return only personal collections where `personal_owner_id` is not `nil`."+ {:scope api-scope/data-app}[_route-params{:keys [archived exclude-other-user-collections namespace personal-only]} :- [:map {:closed true}[:archived {:default false} [:maybe ms/BooleanValue]]@@ -135,6 +137,7 @@When `shallow` is true, takes an optional `collection-id` and returns only the requested collection (orthe root, if `collection-id` is `nil`)."+ {:scope api-scope/data-app}[_route-params{:keys [exclude-archived exclude-other-user-collections include-librarynamespace namespaces shallow collection-id]}@@ -356,6 +359,7 @@(api.macros/defendpoint :get "/root" :- ::Collection"Return the 'Root' Collection object with standard details added"+ {:scope api-scope/data-app}[_route-params{:keys [namespace]} :- [:map {:closed true}[:namespace {:optional true} [:maybe ms/NonBlankString]]]]@@ -385,6 +389,7 @@Note that this endpoint should return results in a similar shape to `/api/dashboard/:id/items`, so if this ischanged, that should too."+ {:scope api-scope/data-app}[_route-params{:keys [models archived namespace pinned-state sort-column sort-direction official-collections-firstinclude-library collection-type show-dashboard-questions@@ -587,6 +592,7 @@(api.macros/defendpoint :get "/:id" :- ::Collection"Fetch a specific Collection with standard details added"+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]](let [resolved-id (eid-translation/->id-or-404 :collection id)]@@ -641,6 +647,7 @@Note that this endpoint should return results in a similar shape to `/api/dashboard/:id/items`, so if this ischanged, that should too."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]{:keys [models archived pinned-state sort-column sort-direction official-collections-firstdiff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex 43186d72682..94ba7db3132 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -8,6 +8,7 @@[metabase.actions.core :as actions][metabase.actions.schema :as actions.schema][metabase.analytics.core :as analytics]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.channel.email.messages :as messages]@@ -661,6 +662,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id""Get Dashboard with ID."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]{dashboard-load-id :dashboard_load_id} :- [:map {:closed true}@@ -1159,6 +1161,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/query_metadata""Get all of the required query metadata for the cards on dashboard."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]{dashboard-load-id :dashboard_load_id} :- [:map {:closed true}@@ -1308,6 +1311,7 @@;; fetch values for Dashboard 1 parameter 'abc' that are possible when parameter 'def' is set to 100GET /api/dashboard/1/params/abc/values?def=100"+ {:scope api-scope/data-app}[{:keys [id param-key]} :- [:map {:closed true}[:id ms/PositiveInt][:param-key ms/NonBlankString]]@@ -1330,6 +1334,7 @@GET /api/dashboard/1/params/abc/search/Cam?def=100Currently limited to first 1000 results."+ {:scope api-scope/data-app}[{:keys [id param-key query]} :- [:map {:closed true}[:id ms/PositiveInt][:param-key ms/NonBlankString]@@ -1350,6 +1355,7 @@;; fetch the remapped value for Dashboard 1 parameter 'abc' for value 100GET /api/dashboard/1/params/abc/remapping?value=100"+ {:scope api-scope/data-app}[{:keys [id param-key]} :- [:map {:closed true}[:id ms/PositiveInt][:param-key ms/NonBlankString]]@@ -1383,6 +1389,7 @@Results are returned as a map of`filtered` Field ID -> subset of `filtering` Field IDs that would be used in chain filter query"+ {:scope api-scope/data-app}[_route-params{:keys [filtered filtering]} :- [:map {:closed true}[:filtered (ms/QueryVectorOf ::lib.schema.id/field)]@@ -1400,6 +1407,7 @@"Fetches the values for filling in execution parameters. Pass PK parameters and values to select.Parameters are sent in the request body rather than the query string so their values stay out of URLs and logs."+ {:scope api-scope/data-app}[{:keys [dashboard-id dashcard-id]} :- [:map {:closed true}[:dashboard-id ms/PositiveInt][:dashcard-id ms/PositiveInt]]@@ -1421,6 +1429,7 @@`parameters` should be the mapped dashboard parameters with values.`extra_parameters` should be the extra, user entered parameter values."+ {:scope api-scope/data-app}[{:keys [dashboard-id dashcard-id]} :- [:map {:closed true}[:dashboard-id ms/PositiveInt][:dashcard-id ms/PositiveInt]]@@ -1439,6 +1448,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/:dashboard-id/dashcard/:dashcard-id/card/:card-id/query""Run the query associated with a Saved Question (`Card`) in the context of a `Dashboard` that includes it."+ {:scope api-scope/data-app}[{:keys [dashboard-id dashcard-id card-id]} :- [:map {:closed true}[:dashboard-id ms/PositiveInt][:dashcard-id ms/PositiveInt]@@ -1465,6 +1475,7 @@`parameters` should be passed as query parameter encoded as a serialized JSON string (this is because this endpointis normally used to power 'Download Results' buttons that use HTML `form` actions)."+ {:scope api-scope/data-app}[{:keys [dashboard-id dashcard-id card-id export-format]} :- [:map {:closed true}[:dashboard-id ms/PositiveInt][:dashcard-id ms/PositiveInt]@@ -1502,6 +1513,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/pivot/:dashboard-id/dashcard/:dashcard-id/card/:card-id/query""Run a pivot table query for a specific DashCard."+ {:scope api-scope/data-app}[{:keys [dashboard-id dashcard-id card-id]} :- [:map {:closed true}[:dashboard-id ms/PositiveInt][:dashcard-id ms/PositiveInt]diff --git a/src/metabase/embedding/util.clj b/src/metabase/embedding/util.cljindex a6bd4dd6a4c..8d80db62b43 100644--- a/src/metabase/embedding/util.clj+++ b/src/metabase/embedding/util.clj@@ -3,12 +3,23 @@(def ^:private embedding-sdk-client "embedding-sdk-react")(def ^:private embedded-analytics-js-client "embedding-simple")+(def ^:private data-app-client "data-app")(defn has-react-sdk-header?"Check if the client has indicated it is from the Embedding SDK for React."[request](= (get-in request [:headers "x-metabase-client"]) embedding-sdk-client))+(defn has-data-app-header?+ "Check if the client has indicated it is a sandboxed data app.++ Unlike its siblings here this one gates authorization, not behaviour:+ [[metabase.server.middleware.data-app-scope]] confines a request to the `data-app` scope+ on the strength of it, so the client name must stay in sync with+ `EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader` on the FE."+ [request]+ (= (get-in request [:headers "x-metabase-client"]) data-app-client))+(defn has-embedded-analytics-js-header?"Check if the client has indicated it is from modular embedding."[request]diff --git a/src/metabase/native_query_snippets/api.clj b/src/metabase/native_query_snippets/api.cljindex cdce29f9eb0..ea544bf54c3 100644--- a/src/metabase/native_query_snippets/api.clj+++ b/src/metabase/native_query_snippets/api.clj@@ -2,6 +2,7 @@"Native query snippet (/api/native-query-snippet) endpoints."(:require[clojure.data :as data]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.collections.core :as collections]@@ -30,6 +31,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/""Fetch all snippets"+ {:scope api-scope/data-app}[_route-params{:keys [archived]} :- [:map {:closed true}[:archived {:default false} [:maybe ms/BooleanValue]]]]@@ -45,6 +47,9 @@;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+;; Not tagged `data-apps:base`, though the list route above is: a data app needs the list to+;; resolve snippet names while rendering a native question, whereas fetching one by id is the+;; Data Studio snippet editor (`useGetSnippetQuery`), which a data app does not render.(api.macros/defendpoint :get "/:id""Fetch native query snippet with ID."[{:keys [id]} :- [:map {:closed true}diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex 5aca2c0c59a..82b1aff5f1c 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -1,6 +1,7 @@(ns metabase.queries-rest.api.card"/api/card endpoints."(:require+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.collections.models.collection :as collection]@@ -226,6 +227,7 @@As of v57, returns the MBQL query (`dataset_query`) as MBQL 5; to return the query as MBQL 4 (aka legacy MBQL)instead, you can specify `?legacy-mbql=true`."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]{legacy-mbql? :legacy-mbql@@ -647,6 +649,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/query_metadata""Get all of the required query metadata for a card."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id [:or ms/PositiveInt ms/NanoIdString]]]](let [resolved-id (eid-translation/->id-or-404 :card id)]@@ -782,6 +785,7 @@(api.macros/defendpoint :post "/:card-id/query""Run the query associated with a Card. When `stored_result_id` is supplied, serve the cached snapshot instead of re-running the queryand optionally re-sorts the rows via the `sort` body param."+ {:scope api-scope/data-app}[{:keys [card-id]} :- [:map {:closed true}[:card-id [:or ms/PositiveInt ms/NanoIdString]]]_query-params@@ -829,6 +833,7 @@`csv_include_bom`, `parameters`, `pivot-results?` and `format-rows?` should be passed as application/x-www-form-urlencoded form contentor json in the body. This is because this endpoint is normally used to power 'Download Results' buttons that useHTML `form` actions)."+ {:scope api-scope/data-app}[{:keys [card-id export-format]} :- [:map {:closed true}[:card-id ms/PositiveInt][:export-format ::qp.schema/export-format]]@@ -915,6 +920,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/pivot/:card-id/query""Run the query associated with a Card."+ {:scope api-scope/data-app}[{:keys [card-id]} :- [:map {:closed true}[:card-id ms/PositiveInt]]_query-params@@ -943,6 +949,7 @@;; fetch values for Card 1 parameter 'abc' that are possibleGET /api/queries/1/params/abc/values"+ {:scope api-scope/data-app}[{:keys [card-id param-key]} :- [:map {:closed true}[:card-id ms/PositiveInt][:param-key ::lib.schema.parameter/id]]]@@ -960,6 +967,7 @@GET /api/queries/1/params/abc/search/OrangeCurrently limited to first 1000 results."+ {:scope api-scope/data-app}[{:keys [card-id param-key query]} :- [:map {:closed true}[:card-id ms/PositiveInt][:param-key ::lib.schema.parameter/id]@@ -976,6 +984,7 @@;; fetch the remapped value for Card 1 parameter 'abc' for value 100GET /api/queries/1/params/abc/remapping?value=100"+ {:scope api-scope/data-app}[{:keys [id param-key]} :- [:map {:closed true}[:id ::lib.schema.id/card][:param-key ::lib.schema.parameter/id]]diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.cljindex d1cbd501bf4..b1c81c78bc4 100644--- a/src/metabase/query_processor/api.clj+++ b/src/metabase/query_processor/api.clj@@ -3,6 +3,7 @@(:refer-clojure :exclude [get-in select-keys])(:require[malli.core :as mc]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.driver :as driver]@@ -102,6 +103,7 @@(api.macros/defendpoint :post "/":- (server/streaming-response-schema ::qp.schema/query-result)"Execute a query and retrieve the results in the usual format. The query will not use the cache."+ {:scope api-scope/data-app}[_route-params_query-paramsquery :- ::lib-be.schema/maybe-legacy-or-internal-query]@@ -134,6 +136,7 @@(api.macros/defendpoint :post ["/:export-format", :export-format qp.schema/export-formats-regex]:- (server/streaming-response-schema ::qp.schema/query-result)"Execute a query and download the result data as a file in the specified format."+ {:scope api-scope/data-app}[{:keys [export-format]} :- [:map {:closed true}[:export-format ::qp.schema/export-format]]_query-params@@ -190,6 +193,7 @@You can pass `{:settings {:include-sensitive-fields true}}` in the query to include fields withvisibility_type :sensitive in the response."+ {:scope api-scope/data-app}[_route-params_query-paramsquery :- ::lib-be.schema/maybe-legacy-query]@@ -204,6 +208,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/native""Fetch a native version of an MBQL query."+ {:scope api-scope/data-app}[_route-params_query-params{:keys [database pretty] :as query} :- [:map {:closed true}@@ -238,6 +243,7 @@(api.macros/defendpoint :post "/pivot":- (server/streaming-response-schema ::qp.schema/query-result)"Generate a pivoted dataset for an ad-hoc query"+ {:scope api-scope/data-app}[_route-params_query-params{:keys [database] :as query} :- ::lib-be.schema/maybe-legacy-query]@@ -283,6 +289,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/parameter/values""Return parameter values for cards or dashboards that are being edited."+ {:scope api-scope/data-app}[_route-params_query-params{:keys [parameter]@@ -297,6 +304,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/parameter/search/:query""Return parameter values for cards or dashboards that are being edited. Expects a query string at `?query=foo`."+ {:scope api-scope/data-app}[{:keys [query]} :- [:map {:closed true}[:query ms/NonBlankString]]_query-params@@ -326,6 +334,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/parameter/remapping""Return the remapped parameter values for cards or dashboards that are being edited."+ {:scope api-scope/data-app}[_route-params_query-params{:keys [parameter value field_ids]} :- [:map {:closed true}diff --git a/src/metabase/request/schema.clj b/src/metabase/request/schema.cljindex 514e5ec40ef..f7a3758ccaf 100644--- a/src/metabase/request/schema.clj+++ b/src/metabase/request/schema.clj@@ -22,6 +22,7 @@[:settings {:optional true} [:maybe [:or ms/UserSettings :string]]][:token-scopes {:optional true} [:maybe [:set [:or :keyword :string]]]][:token-scopes-checked {:optional true} :boolean]+ [:data-app-scoped? {:optional true} :boolean][:authenticated-via-oauth? {:optional true} :boolean]])(mr/def ::json-value@@ -109,6 +110,7 @@[:token-scopes {:optional true} [:maybe [:set [:or :keyword :string]]]][:token-scopes-checked {:optional true} :boolean][:authenticated-via-oauth? {:optional true} :boolean]+ [:data-app-scoped? {:optional true} :boolean][:mcp-ui-session-id {:optional true} [:maybe :string]][:mcp-ui-credential {:optional true} [:maybe[:map {:closed true}diff --git a/src/metabase/search/api.clj b/src/metabase/search/api.cljindex 4edfa5320c2..e03f354926f 100644--- a/src/metabase/search/api.clj+++ b/src/metabase/search/api.clj@@ -3,6 +3,7 @@[clojure.string :as str][java-time.api :as t][metabase.analytics-interface.core :as analytics]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.open-api :as open-api]@@ -332,6 +333,7 @@- The `verified` filter supports models and cards.A search query that has both filters applied will only return models and cards."+ {:scope api-scope/data-app}[_route-paramsquery-params :- search-request-schema](api/check-valid-page-params (request/limit) (request/offset))diff --git a/src/metabase/server/handler.clj b/src/metabase/server/handler.cljindex 813c0608688..9f2ff29a77a 100644--- a/src/metabase/server/handler.clj+++ b/src/metabase/server/handler.clj@@ -7,6 +7,7 @@[metabase.config.core :as config][metabase.server.middleware.auth :as mw.auth][metabase.server.middleware.browser-cookie :as mw.browser-cookie]+ [metabase.server.middleware.data-app-scope :as mw.data-app-scope][metabase.server.middleware.exceptions :as mw.exceptions][metabase.server.middleware.json :as mw.json][metabase.server.middleware.log :as mw.log]@@ -97,6 +98,7 @@#'mw.misc/maybe-set-site-url ; set the value of `site-url` if it hasn't been set yet#'mw.session/reset-session-timeout ; Resets the timeout cookie for user activity to [[metabase.request.cookies/session-timeout]]#'mw.session/bind-current-user ; Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil+ #'mw.data-app-scope/wrap-data-app-scope ; narrows a data-app request (X-Metabase-Client: data-app) to the `data-app` scope (runs after current-user-info so it sees any resolved token scopes)#'mw.session/wrap-current-user-info ; looks for :metabase-session-key and sets :metabase-user-id and other info if Session ID is valid#'mw.pf-cache/wrap-premium-features-cache-check ; check cookie to refresh premium features cache if needed#'mw.settings-cache/wrap-settings-cache-check ; check cookie to refresh settings cache if neededdiff --git a/src/metabase/server/middleware/data_app_scope.clj b/src/metabase/server/middleware/data_app_scope.cljnew file mode 100644index 00000000000..a05f0fc9d68--- /dev/null+++ b/src/metabase/server/middleware/data_app_scope.clj@@ -0,0 +1,72 @@+(ns metabase.server.middleware.data-app-scope+ "Ring middleware that confines a data-app-originated request to the `data-apps:base` scope.++ A sandboxed data app's SDK client already stamps every instance request with+ `X-Metabase-Client: data-app` (set by `setDataApp` on the FE and re-applied by the SDK's+ `useInitData` on every component mount, so it can't be dropped). Trusted host-realm code+ adds it; the membraned guest can't reach that code, and — critically — the header only ever+ *narrows* access, so it needs no cryptographic protection: forging it can only restrict the+ caller.++ When that header is present on an otherwise full-access request, this middleware sets+ `:token-scopes #{\"data-apps:base\"}`, so the endpoint scope middleware+ ([[metabase.api.macros.scope]]) lets the request reach only endpoints tagged+ `{:scope api-scope/data-app}` and fails closed everywhere else.++ It never *broadens* access: a request already carrying a restricted `:token-scopes` (an+ OAuth or agent token) is left untouched, so the header can't turn a narrow token into a+ card-query-capable one. That's why it must run after `wrap-current-user-info`, which is+ what resolves those token scopes. The scope itself is declared in+ [[metabase.api-scope.data-app]].++ Narrowed requests also carry `:data-app-scoped?`, so downstream auth middleware that+ rewrites `:token-scopes` — the agent API's, on a JWT `scope` claim — can tell a confinement+ decision made here from an absent one and refuse to widen it back out."+ (:require+ [metabase.api-scope.data-app :as api-scope]+ [metabase.api.macros.scope :as scope]+ [metabase.embedding.util :as embedding.util]))++(set! *warn-on-reflection* true)++(def ^:private data-app-token-scopes+ "The scope set a data-app request is confined to — the scope declared in+ [[metabase.api-scope.data-app]] and carried by the `{:scope api-scope/data-app}` endpoint+ tags."+ #{api-scope/data-app})++(defn- full-access?+ "True when `token-scopes` represents an unrestricted credential — a normal session, or a+ bearer token granted access to the whole REST API. Only such requests may be narrowed by+ the marker; an already-scoped credential (an OAuth or agent token) must not be broadened,+ so it stays untouched.++ `\"*\"` counts as full access because [[metabase.api-scope.core/scope-matches?]] treats a+ granted `\"*\"` as satisfying every required scope."+ [token-scopes]+ (or (nil? token-scopes)+ (contains? token-scopes ::scope/unrestricted)+ (contains? token-scopes "*")))++(defn- narrow-to-data-app?+ "True when `request` carries the data-app client marker on a credential this may confine.++ MCP visualization iframes are excluded even though they look full-access here:+ `wrap-current-user-info` hands them `#{::scope/unrestricted}` deliberately, because their+ authorization boundary is the route allowlist in [[metabase.server.middleware.session]]+ rather than the scope set. Narrowing one would cost it the `/api/embed-mcp` routes, which+ carry no `data-app` tag, and it is already confined by that allowlist either way."+ [request]+ (and (embedding.util/has-data-app-header? request)+ (not (:mcp-ui-credential request))+ (full-access? (:token-scopes request))))++(defn wrap-data-app-scope+ "When a request comes from a sandboxed data app (`X-Metabase-Client: data-app`) AND is+ otherwise full-access, confine it to the `data-apps:base` scope."+ [handler]+ (fn [request respond raise]+ (handler (cond-> request+ (narrow-to-data-app? request) (assoc :token-scopes data-app-token-scopes+ :data-app-scoped? true))+ respond raise)))diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex 59d602e28d9..a6601ed242a 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -2,6 +2,7 @@"/api/session endpoints"(:require[java-time.api :as t]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.open-api :as open-api]@@ -459,6 +460,7 @@(api.macros/defendpoint :get "/properties""Get all properties and their values. These are the specific `Settings` that are readable by the current user, or arepublic if no user is logged in."+ {:scope api-scope/data-app}[](setting/user-readable-values-map (setting/current-user-readable-visibilities)))diff --git a/src/metabase/timeline/api/timeline.clj b/src/metabase/timeline/api/timeline.cljindex 0bcef4a3a0e..b035ab8a61b 100644--- a/src/metabase/timeline/api/timeline.clj+++ b/src/metabase/timeline/api/timeline.clj@@ -1,6 +1,7 @@(ns metabase.timeline.api.timeline"/api/timeline endpoints."(:require+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.collections.models.collection :as collection]@@ -59,6 +60,7 @@(api.macros/defendpoint :get "/" :- [:sequential ::Timeline]"Fetch a list of `Timeline`s. Can include `archived=true` to return archived timelines."+ {:scope api-scope/data-app}[_route-params{:keys [include], archived? :archived} :- [:map {:closed true}[:include {:optional true} ::include]diff --git a/src/metabase/user_key_value/api.clj b/src/metabase/user_key_value/api.cljindex 275aa8da497..f37c218160a 100644--- a/src/metabase/user_key_value/api.clj+++ b/src/metabase/user_key_value/api.clj@@ -3,6 +3,7 @@[malli.core :as mc][malli.experimental.time.transform :as mett][malli.transform :as mtx]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.lib.schema.literal]@@ -16,6 +17,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :put "/namespace/:namespace/key/:key""Upsert a KV-pair for the user"+ {:scope api-scope/data-app}[{nmspace :namespace, k :key} :- [:map {:closed true}[:key ms/NonBlankString][:namespace ms/NonBlankString]]@@ -46,6 +48,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/namespace/:namespace/key/:key""Get a value for the user"+ {:scope api-scope/data-app}[{nmspace :namespace, k :key} :- [:map {:closed true}[:key ms/NonBlankString][:namespace ms/NonBlankString]]]@@ -55,6 +58,9 @@;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+;; Not tagged `data-apps:base`, though the three per-key routes around it are: `useUserKeyValue`+;; only ever reads, writes or clears one key at a time, so nothing a data app renders enumerates+;; a whole namespace.(api.macros/defendpoint :get "/namespace/:namespace""Returns all KV pairs in a given namespace for the current user"[{nmspace :namespace} :- [:map {:closed true}@@ -67,6 +73,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :delete "/namespace/:namespace/key/:key""Deletes a KV-pair for the user"+ {:scope api-scope/data-app}[{nmspace :namespace, k :key} :- [:map {:closed true}[:key ms/NonBlankString][:namespace ms/NonBlankString]]]diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.cljindex dd28122deeb..2c7cf081c87 100644--- a/src/metabase/users_rest/api.clj+++ b/src/metabase/users_rest/api.clj@@ -3,6 +3,7 @@(:require[clojure.set :as set][java-time.api :as t]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.appearance.core :as appearance]@@ -395,6 +396,7 @@(api.macros/defendpoint :get "/current" :- ::current-user-response"Fetch the current `User`."+ {:scope api-scope/data-app}[](-> (api/check-404 @api/*current-user*);; `:type` is selected for the current user so attribute resolution can check it, but isn't part of thisdiff --git a/src/metabase/warehouse_schema_rest/api/field.clj b/src/metabase/warehouse_schema_rest/api/field.cljindex 19927cf4341..6a0bcb79e1a 100644--- a/src/metabase/warehouse_schema_rest/api/field.clj+++ b/src/metabase/warehouse_schema_rest/api/field.clj@@ -1,6 +1,7 @@(ns metabase.warehouse-schema-rest.api.field(:require[metabase.analytics.core :as analytics]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.events.core :as events]@@ -52,6 +53,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id""Get `Field` with ID."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{include-editable-data-model? :include_editable_data_model} :- [:map {:closed true}@@ -223,6 +225,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/summary""Get the count and distinct count of `Field` with ID."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]](let [field (api/read-check :model/Field id)]@@ -286,6 +289,7 @@"If a Field's value of `has_field_values` is `:list`, return a list of all the distinct values of the Field (orremapped Field), and (if defined by a User) a map of human-readable remapped values. If `has_field_values` is not`:list`, checks whether we should create FieldValues for this Field; if so, creates and returns them."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]](let [field (api/query-check (warehouse-schema-rest.db/field id))]@@ -376,6 +380,7 @@(api.macros/defendpoint :get "/:id/search/:search-id""Search for values of a Field with `search-id` that start with `value`. See docstring for[[metabase.parameters.field/search-values]] for a more detailed explanation."+ {:scope api-scope/data-app}[{:keys [id search-id]} :- [:map {:closed true}[:id ms/PositiveInt][:search-id ms/PositiveInt]]@@ -395,6 +400,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/remapping/:remapped-id""Fetch remapped Field values."+ {:scope api-scope/data-app}[{:keys [id remapped-id]} :- [:map {:closed true}[:id ms/PositiveInt][:remapped-id ms/PositiveInt]]@@ -411,6 +417,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/related""Return related entities."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]](-> (warehouse-schema-rest.db/field id) api/read-check xrays/related))diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.cljindex e004514e73e..0b9e1c23d79 100644--- a/src/metabase/warehouse_schema_rest/api/table.clj+++ b/src/metabase/warehouse_schema_rest/api/table.clj@@ -2,6 +2,7 @@"/api/table endpoints."(:require[clojure.java.io :as io]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.collections.core :as collections]@@ -128,6 +129,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id""Get `Table` with ID."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include_editable_data_model]}@@ -322,6 +324,7 @@data model, while `false` checks that they have data access perms for the table. Defaults to `false`.These options are provided for use in the Admin Edit Metadata page."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include_sensitive_fields include_hidden_fields include_editable_data_model]}@@ -342,6 +345,7 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/card__:id/query_metadata""Return metadata for the 'virtual' table for a Card."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]](first (schema.table/batch-fetch-card-query-metadatas [id] {:include-database? true})))@@ -366,6 +370,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/fks""Get all foreign keys whose destination is a `Field` that belongs to this `Table`."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]](api/read-check :model/Table id)diff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex 63a42ade5f8..9f842986830 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -4,6 +4,7 @@[clojure.string :as str][medley.core :as m][metabase.analytics.core :as analytics]+ [metabase.api-scope.data-app :as api-scope][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.config.core :as config]@@ -354,6 +355,7 @@[[metabase.warehouses.models.database]] uses the implementation of [[metabase.models.interface/can-write?]] for`:model/Database` in [[metabase.warehouses.models.database]] to exclude the `details` field, if the requesting userlacks permission to change the database details."+ {:scope api-scope/data-app}[_route-params{:keys [include saved include_editable_data_model exclude_uneditable_details include_only_uploadable include_analyticsrouter_database_id can-query can-write-metadata]}@@ -481,6 +483,7 @@[[metabase.warehouses.models.database]] uses the implementation of [[metabase.models.interface/can-write?]] for `:model/Database`in [[metabase.warehouses.models.database]] to exclude the `details` field, if the requesting user lacks permission to change thedatabase details."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include include_editable_data_model exclude_uneditable_details]}@@ -658,6 +661,7 @@Tables are returned in the format `[table_name \"Table\"]`;When Fields have a semantic_type, they are returned in the format `[field_name \"table_name base_type semantic_type\"]`When Fields lack a semantic_type, they are returned in the format `[field_name \"table_name base_type\"]`"+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [prefix substring]} :- [:map {:closed true}@@ -694,6 +698,7 @@"Return a list of `Card` autocomplete suggestions for a given `query` in a given `Database`.This is intended for use with the ACE Editor when the User is typing in a template tag for a `Card`, e.g. {{#...}}."+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [query include_dashboard_questions]} :- [:map {:closed true}@@ -1235,6 +1240,7 @@Optional filters:- `can-query=true` - filter to only schemas containing tables the user can query- `can-write-metadata=true` - filter to only schemas containing tables the user can edit metadata for"+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include_editable_data_model@@ -1298,6 +1304,7 @@Optional filters:- `can-query=true` - filter to only tables the user can query- `can-write-metadata=true` - filter to only tables the user can edit metadata for"+ {:scope api-scope/data-app}[{:keys [id schema]} :- [:map {:closed true}[:id ms/PositiveInt][:schema ms/NonBlankString]]@@ -1333,6 +1340,10 @@Optional filters:- `can-query=true` - filter to only tables the user can query- `can-write-metadata=true` - filter to only tables the user can edit metadata for"+ ;; Tagged for the same reason as the `/:id/schema/:schema` sibling, and it is this route the SDK+ ;; usually reaches: `GET /:id/schemas` reports a nil schema as "", and the sibling's `NonBlankString`+ ;; route regex cannot match an empty segment, so every schemaless warehouse lands here.+ {:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [schema include_hidden include_editable_data_model can-query can-write-metadata include_measures]} :- [:map {:closed true}diff --git a/test/metabase/server/middleware/data_app_scope_test.clj b/test/metabase/server/middleware/data_app_scope_test.cljnew file mode 100644index 00000000000..ea99366b06d--- /dev/null+++ b/test/metabase/server/middleware/data_app_scope_test.clj@@ -0,0 +1,131 @@+(ns metabase.server.middleware.data-app-scope-test+ (:require+ [clojure.test :refer :all]+ [metabase.api-scope.core :as api-scope]+ [metabase.api-scope.data-app :as api-scope.data-app]+ [metabase.api.macros.scope :as scope]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.server.middleware.data-app-scope :as mw.data-app-scope]+ [metabase.test :as mt]))++(def ^:private marker+ {:headers {"x-metabase-client" "data-app"}})++(defn- run-middleware+ "Run `wrap-data-app-scope` over `request` and return the request its inner handler saw."+ [request]+ (let [seen (promise)+ handler (mw.data-app-scope/wrap-data-app-scope+ (fn [req respond _raise] (respond req)))]+ ;; A Clojure promise implements IFn via `deliver`, so it works directly as the `respond` callback.+ (handler request seen identity)+ (deref seen 1000 ::timeout)))++(defn- token-scopes-seen+ "The `:token-scopes` `wrap-data-app-scope`'s inner handler saw for `request`."+ [request]+ (:token-scopes (run-middleware request)))++(deftest ^:parallel wrap-data-app-scope-test+ (testing "an X-Metabase-Client: data-app request from a normal session narrows to the data-app scope"+ (is (= #{api-scope.data-app/data-app} (token-scopes-seen marker))))+ (testing "it narrows a full-access (::unrestricted) token down to the data-app scope"+ (is (= #{api-scope.data-app/data-app}+ (token-scopes-seen (assoc marker :token-scopes #{::scope/unrestricted})))))+ (testing "it narrows a `*` grant too — `scope-matches?` treats it as satisfying every scope"+ (is (= #{api-scope.data-app/data-app}+ (token-scopes-seen (assoc marker :token-scopes api-scope/unrestricted)))))+ (testing "a dev/preview data app is confined too — the X-Metabase-Client header is still \"data-app\"+ (the \"-preview\" suffix lives only on the analytics *client* var, not the header)"+ (is (= #{api-scope.data-app/data-app}+ (token-scopes-seen {:headers {"x-metabase-client" "data-app"+ "x-metabase-embedded-preview" "true"}}))))+ (testing "a narrowed request is flagged, so downstream auth middleware can refuse to widen it"+ (is (true? (:data-app-scoped? (run-middleware marker)))))+ (testing "every request this middleware does not narrow reaches the handler byte-for-byte unchanged"+ (doseq [[what request] {"no client header at all" {:headers {}}+ "a non-data-app SDK client" {:headers {"x-metabase-client" "embedding-sdk-react"}}+ ;; Narrowing an already-scoped OAuth/agent token would broaden it.+ "a marked but scoped token" (assoc marker :token-scopes #{"agent:search"})+ ;; An MCP-UI credential's route allowlist, not its scope set, confines it.+ "a marked MCP-UI credential" (assoc marker+ :token-scopes #{::scope/unrestricted}+ :mcp-ui-credential {:uid 1})}]+ (is (identical? request (run-middleware request)) what))))++(deftest ^:parallel data-app-scope-registered-test+ (testing "the data-app scope is registered so tagged endpoints don't warn about an unknown scope"+ (is (api-scope/registered-scope? api-scope.data-app/data-app)))+ (testing "the scope string is a wire contract — a JWT may carry it, so renaming is breaking"+ (is (= "data-apps:base" api-scope.data-app/data-app)))+ (testing "the `data-apps:*` wildcard covers it, leaving room for a later tier"+ (is (api-scope/scope-matches? #{"data-apps:*"} api-scope.data-app/data-app))))++(deftest data-app-marker-enforces-endpoint-scope-test+ ;; Mirrors the endpoints probed by the e2e spec+ ;; (e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts) so both layers stay in sync.+ (let [as-data-app {:request-options {:headers {"x-metabase-client" "data-app"}}}+ privileged ["permissions/graph" "setting"]]+ (testing "an admin session reaches the privileged endpoints without the data-app client header"+ (doseq [endpoint privileged]+ (is (mt/user-http-request :crowberto :get 200 endpoint) endpoint)))+ (testing "the write/admin endpoints still fail closed once the request is marked as a data app"+ (doseq [endpoint privileged]+ (is (= "scope_not_permitted"+ (:error (mt/user-http-request :crowberto :get 403 endpoint as-data-app)))+ endpoint)))+ (testing "the SDK bootstrap surface (current user + settings) is reachable when marked"+ (is (mt/user-http-request :crowberto :get 200 "user/current" as-data-app))+ (is (mt/user-http-request :crowberto :get 200 "session/properties" as-data-app)))+ (testing "the data-app read/query surface still passes scope enforcement when marked"+ (is (mt/user-http-request :crowberto :get 200 "collection/root" as-data-app)))+ (testing "the feature-surface reads (downloads pref) are reachable when marked"+ ;; POST /api/action/:id/execute (write-back for `useAction`) is tagged too, but needs an+ ;; action fixture — actions.cy.spec.ts is its functional guard under enforcement.+ ;;+ ;; 204 (not scope_not_permitted) proves the marked request reached the handler; the key is unset.+ (is (nil? (mt/user-http-request :crowberto :get 204+ "user-key-value/namespace/data-app-test/key/format" as-data-app))))+ (testing "alerts and subscriptions are not part of the data-app surface"+ ;; Scheduled email delivered out of band is not something a data app renders, so neither+ ;; the probe the SDK buttons gate on nor the CRUD behind them is reachable. The buttons are+ ;; gated off in a data app too (`embedding-sdk-ee/notifications`), so nothing offers a+ ;; control that would 403 here.+ (doseq [endpoint ["pulse/form_input" "pulse" "notification"]]+ (is (= "scope_not_permitted"+ (:error (mt/user-http-request :crowberto :get 403 endpoint as-data-app)))+ endpoint)))+ (testing "the user-key-value key a marked request writes is one it can also clear"+ ;; The delete body is irrelevant — reaching the handler at all is what the tag buys.+ (is (not= "scope_not_permitted"+ (:error (mt/user-http-request :crowberto :delete+ "user-key-value/namespace/data-app-test/key/format"+ as-data-app)))))+ (testing "the InteractiveQuestion.Editor data-source surface is reachable when marked"+ (is (mt/user-http-request :crowberto :get 200 "database" as-data-app)))+ (testing "a pre-built-def route (table-routes, mounted by value not ns-symbol) enforces the tag"+ (is (mt/user-http-request :crowberto :get 200+ (format "table/%d/query_metadata" (mt/id :venues)) as-data-app)))))++(deftest data-app-marker-reaches-object-detail-action-reads-test+ ;; The SDK's "Detail" visualization renders `ObjectDetailPanel`, which lists a writable model's+ ;; actions, and its `ActionExecuteModal` fetches the one clicked. Both are reads, and both must+ ;; carry the tag or the menu silently disappears for an admin inside a data app.+ ;; Built with plain `with-temp` rather than `mt/with-actions`: that helper's cleanup reindexes search, which+ ;; drops orphan index tables, and that DDL commits the rollback-only `with-temp` transaction on H2 whenever the+ ;; `metabase.search.*` namespaces ran earlier in the same JVM.+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-temp [:model/Card {model-id :id} {:type :model+ :dataset_query (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider)+ (mt/id :categories)))}+ :model/Action {action-id :id} {:name "Update category" :model_id model-id :type :implicit}+ :model/ImplicitAction _ {:action_id action-id :kind "row/update"}]+ (let [as-data-app {:request-options {:headers {"x-metabase-client" "data-app"}}}]+ (testing "GET /api/action?model-id= -- the object-detail action menu"+ (is (=? [{:id action-id}]+ (mt/user-http-request :crowberto :get 200 "action" as-data-app :model-id model-id))))+ (testing "GET /api/action/:id -- the execute modal's definition fetch"+ (is (=? {:id action-id}+ (mt/user-http-request :crowberto :get 200 (format "action/%d" action-id) as-data-app))))))))