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
Improve data app content checks (#85975)
Alexander Polyankinb6b05a509445
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 379b5a5bf10..d677e7d341f 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -333,6 +333,7 @@:ns-prefix "metabase.eid-translation":api #{metabase.eid-translation.api metabase.eid-translation.core metabase.eid-translation.init}:uses #{api+ api-scopebatch-processingsettingsutil}@@ -826,13 +827,11 @@:uses #{actionsanalyticsapi- api-scopeapi.eid-translationapp-dbchannelcollectionsdashboards- data-appsembeddingeventslib@@ -868,14 +867,13 @@data-apps{:team "Embedding"- :api #{metabase.data-apps.core}+ :api #{metabase.data-apps.core metabase.data-apps.schema}:uses #{actionsanalyticsapiapi-scopelib.belib.schema- parameters.schemapremium-featuresutil}}@@ -1848,7 +1846,6 @@{:team "Graphy":api #{metabase.native-query-snippets.api metabase.native-query-snippets.core metabase.native-query-snippets.schema}:uses #{api- api-scopecollectionseventslib@@ -2232,7 +2229,6 @@:model/NativeQuerySnippet:model/Notification:model/Revision- :model/Table:model/Timeline:model/User}}@@ -3000,7 +2996,6 @@:api #{metabase.timeline.api metabase.timeline.core metabase.timeline.schema}:uses #{analyticsapi- api-scopecollectionseventslib.schema@@ -3853,6 +3848,7 @@:uses #{actionsapiapi-scope+ audit-appcollectionsdata-appsevents@@ -3860,22 +3856,23 @@lib.belib.schemalib.types+ metabot+ metricsmodels- parameters- parameters.schemapermissionspremium-features- remote-sync+ queriessearchsettings+ systemutilutil.graphwarehouse-schema-overlay- enterprise/dependencies}+ enterprise/dependencies+ enterprise/serialization}:model-imports #{:model/Action:model/Card:model/Collection- :model/Dashboard:model/DataPermissions:model/Database:model/Fielddiff --git a/e2e/support/assets/data-apps/.gitignore b/e2e/support/assets/data-apps/.gitignoreindex 69917537918..e591f8bc222 100644--- a/e2e/support/assets/data-apps/.gitignore+++ b/e2e/support/assets/data-apps/.gitignore@@ -1,8 +1,3 @@-# Each test app under this directory commits its `src/` and its `data_app.yaml`-# manifest. Everything else — the SDK/template base pulled in at test setup and-# the built `dist/` bundle (Vite API) — is generated, so it's ignored here.-/*/*-!/*/src-!/*/data_app.yaml-# The app's typed schema, fetched from Metabase before each build.-/*/src/metabase.ts+# Built by the specs before each copy into the sync repository.+/data_apps/*/dist+/.builddiff --git a/e2e/support/assets/data-apps/collections/data_apps/data_app__sandbox.yaml b/e2e/support/assets/data-apps/collections/data_apps/data_app__sandbox.yamlnew file mode 100644index 00000000000..dce9c056f27--- /dev/null+++ b/e2e/support/assets/data-apps/collections/data_apps/data_app__sandbox.yaml@@ -0,0 +1,6 @@+name: 'Data App: sandbox'+entity_id: sandboxAppCollection1+slug: data_app__sandbox+namespace: data-apps+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/collections/data_apps/data_app__teams.yaml b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams.yamlnew file mode 100644index 00000000000..c1577882a58--- /dev/null+++ b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams.yaml@@ -0,0 +1,6 @@+name: 'Data App: teams'+entity_id: teamsAppCollection001+slug: data_app__teams+namespace: data-apps+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/addteam.yaml b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/addteam.yamlnew file mode 100644index 00000000000..eab5328843f--- /dev/null+++ b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/addteam.yaml@@ -0,0 +1,17 @@+collection_id: teamsAppCollection001+creator_id: [email protected]+entity_id: teamsAppAddTeam000001+implicit:+- kind: row/create+ table_id:+ - Writable Postgres12+ - public+ - scoreboard_actions+name: addTeam+parameter_mappings: []+parameters: []+query: []+type: implicit+visualization_settings: {}+serdes/meta:+- model: Actiondiff --git a/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/teamlist.yaml b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/teamlist.yamlnew file mode 100644index 00000000000..d8bc3e14e8a--- /dev/null+++ b/e2e/support/assets/data-apps/collections/data_apps/data_app__teams/teamlist.yaml@@ -0,0 +1,46 @@+name: teamList+entity_id: teamsAppTeamList00001+creator_id: [email protected]+display: table+collection_id: teamsAppCollection001+parameters: []+parameter_mappings: []+dataset_query:+ database: Writable Postgres12+ stages:+ - fields:+ - - field+ - base-type: type/Text+ effective-type: type/Text+ - - Writable Postgres12+ - public+ - scoreboard_actions+ - team_name+ - - field+ - base-type: type/Integer+ effective-type: type/Integer+ - - Writable Postgres12+ - public+ - scoreboard_actions+ - score+ order-by:+ - - asc+ - {}+ - - field+ - base-type: type/Text+ effective-type: type/Text+ - - Writable Postgres12+ - public+ - scoreboard_actions+ - team_name+ source-table:+ - Writable Postgres12+ - public+ - scoreboard_actions+ lib/type: mbql.stage/mbql+ lib/type: mbql/query+visualization_settings: {}+card_schema: 24+serdes/meta:+- model: Card+type: questiondiff --git a/e2e/support/assets/data-apps/collections/main/library.yaml b/e2e/support/assets/data-apps/collections/main/library.yamlnew file mode 100644index 00000000000..4750c1784fd--- /dev/null+++ b/e2e/support/assets/data-apps/collections/main/library.yaml@@ -0,0 +1,7 @@+name: Library+entity_id: librarylibrarylibrary+slug: library+type: library+is_remote_synced: true+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/collections/main/library/dashboards.yaml b/e2e/support/assets/data-apps/collections/main/library/dashboards.yamlnew file mode 100644index 00000000000..ab97d481014--- /dev/null+++ b/e2e/support/assets/data-apps/collections/main/library/dashboards.yaml@@ -0,0 +1,8 @@+name: Dashboards+entity_id: librarylibrarydashbrd+slug: dashboards+type: library-dashboards+parent_id: librarylibrarylibrary+is_remote_synced: true+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/collections/main/library/data.yaml b/e2e/support/assets/data-apps/collections/main/library/data.yamlnew file mode 100644index 00000000000..56eb578efe7--- /dev/null+++ b/e2e/support/assets/data-apps/collections/main/library/data.yaml@@ -0,0 +1,8 @@+name: Data+entity_id: librarylibrarydatadat+slug: data+type: library-data+parent_id: librarylibrarylibrary+is_remote_synced: true+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/collections/main/library/metrics.yaml b/e2e/support/assets/data-apps/collections/main/library/metrics.yamlnew file mode 100644index 00000000000..e91f8ca99e0--- /dev/null+++ b/e2e/support/assets/data-apps/collections/main/library/metrics.yaml@@ -0,0 +1,8 @@+name: Metrics+entity_id: librarylibrarymetrics+slug: metrics+type: library-metrics+parent_id: librarylibrarylibrary+is_remote_synced: true+serdes/meta:+- model: Collectiondiff --git a/e2e/support/assets/data-apps/custom-error-component/data_app.yaml b/e2e/support/assets/data-apps/custom-error-component/data_app.yamldeleted file mode 100644index 6e534facce0..00000000000--- a/e2e/support/assets/data-apps/custom-error-component/data_app.yaml+++ /dev/null@@ -1,9 +0,0 @@-version: 1-name: Custom Error Component-slug: custom-error-component-path: ./dist/index.js-entity_id: uWb09GFf1aqUzlNsbhPyF-serdes/meta:-- model: DataApp- id: uWb09GFf1aqUzlNsbhPyF- label: custom-error-componentdiff --git a/e2e/support/assets/data-apps/custom-error-component/src/index.tsx b/e2e/support/assets/data-apps/custom-error-component/src/index.tsxdeleted file mode 100644index db5ed23c0a3..00000000000--- a/e2e/support/assets/data-apps/custom-error-component/src/index.tsx+++ /dev/null@@ -1,34 +0,0 @@-import {- type SdkErrorComponentProps,- StaticQuestion,-} from "@metabase/embedding-sdk-react";-import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";--// A question id that does not exist, so the SDK takes its error path — which this-// app overrides with its own `errorComponent`, asserting an app-supplied component-// wins over the host's default neutral error state.-const MISSING_QUESTION_ID = 999999999;--function CustomError({ message }: SdkErrorComponentProps) {- return (- <div data-testid="custom-error-component">Custom app error: {message}</div>- );-}--function App() {- return (- <div data-testid="custom-error-app" style={{ padding: 24 }}>- <h1>Custom error app</h1>- <div style={{ height: 300 }}>- <StaticQuestion questionId={MISSING_QUESTION_ID} />- </div>- </div>- );-}--const factory: DataAppFactory = () => ({- component: App,- providerProps: { errorComponent: CustomError },-});--export default factory;diff --git a/e2e/support/assets/data-apps/data_apps/sandbox/data_app.yaml b/e2e/support/assets/data-apps/data_apps/sandbox/data_app.yamlnew file mode 100644index 00000000000..bbfad507f2f--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/sandbox/data_app.yaml@@ -0,0 +1,12 @@+allowed_hosts:+- https://allowed.data-app.test+- http://localhost:4444+collection: sandboxAppCollection1+description: null+entity_id: sandboxDataApp0000001+name: Sandbox+path: dist/index.js+slug: sandbox+version: 1+serdes/meta:+- model: DataAppdiff --git a/e2e/support/assets/data-apps/data_apps/sandbox/src/App.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/App.tsxnew file mode 100644index 00000000000..982d2a0ed4a--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/sandbox/src/App.tsx@@ -0,0 +1,39 @@+import {+ DataAppLink,+ DataAppRouter,+ useDataAppLocation,+} from "@metabase/embedding-sdk-react/data-app";+import type { ComponentType } from "react";++import { Isolation } from "./Isolation";+import { ProbesPage } from "./ProbesPage";+import { Sandbox } from "./Sandbox";++const ROUTES: Record<string, ComponentType> = {+ "/sandboxing": Sandbox,+ "/isolation": Isolation,+};++function Shell() {+ const { pathname } = useDataAppLocation();+ const Page = ROUTES[pathname] ?? ProbesPage;++ return (+ <div style={{ fontFamily: "sans-serif" }}>+ <nav style={{ padding: 16, display: "flex", gap: 16 }}>+ <DataAppLink to="/">Probes</DataAppLink>+ <DataAppLink to="/sandboxing">Sandbox</DataAppLink>+ <DataAppLink to="/isolation">Isolation</DataAppLink>+ </nav>+ <Page />+ </div>+ );+}++export default function App() {+ return (+ <DataAppRouter>+ <Shell />+ </DataAppRouter>+ );+}diff --git a/e2e/support/assets/data-apps/isolation/src/BoundaryReporter.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/BoundaryReporter.tsxsimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/BoundaryReporter.tsxrename to e2e/support/assets/data-apps/data_apps/sandbox/src/BoundaryReporter.tsxdiff --git a/e2e/support/assets/data-apps/data_apps/sandbox/src/Isolation.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/Isolation.tsxnew file mode 100644index 00000000000..f30d15f50b7--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/sandbox/src/Isolation.tsx@@ -0,0 +1,42 @@+import { useEffect, useState } from "react";++import { describeError } from "./utils";++const PROBE_COLOR = "rgb(0, 128, 0)";++export function Isolation() {+ const [cssInjected, setCssInjected] = useState("pending");+ const [jsMarker, setJsMarker] = useState("pending");++ useEffect(() => {+ // `createElement("style")` is the one tag the data-app sandbox permits, so+ // apps can style their own sandboxed document.+ try {+ const style = document.createElement("style");+ style.textContent = `.isolation-css-probe { color: ${PROBE_COLOR}; } body { background-color: ${PROBE_COLOR}; }`;+ document.head.appendChild(style);+ setCssInjected("ok");+ } catch (err) {+ setCssInjected(`failed: ${describeError(err)}`);+ }++ try {+ const globals = globalThis as Record<string, unknown>;+ globals.__DATA_APP_ISOLATION_MARKER__ = "in-app";+ setJsMarker(String(globals.__DATA_APP_ISOLATION_MARKER__));+ } catch (err) {+ setJsMarker(`failed: ${describeError(err)}`);+ }+ }, []);++ return (+ <div data-testid="data-app-isolation" style={{ padding: 24 }}>+ <h1 style={{ margin: "0 0 16px" }}>Isolation</h1>+ <div data-testid="css-injected">{cssInjected}</div>+ <div data-testid="isolation-css-probe" className="isolation-css-probe">+ css probe+ </div>+ <div data-testid="js-marker">{jsMarker}</div>+ </div>+ );+}diff --git a/e2e/support/assets/data-apps/isolation/src/App.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/ProbesPage.tsxsimilarity index 98%rename from e2e/support/assets/data-apps/isolation/src/App.tsxrename to e2e/support/assets/data-apps/data_apps/sandbox/src/ProbesPage.tsxindex 0358c9d86c9..543a36b03b3 100644--- a/e2e/support/assets/data-apps/isolation/src/App.tsx+++ b/e2e/support/assets/data-apps/data_apps/sandbox/src/ProbesPage.tsx@@ -13,7 +13,7 @@ import { describeError, getEnv } from "./utils";// across the isolation boundary and reports the first sign of the outcome:// `isolated:` (held) or `reached:` (crossed). The spec asserts every probe// reports `isolated:`.-export default function App() {+export function ProbesPage() {const env = getEnv();const [result, setResult] = useState("pending");const [probeId, setProbeId] = useState<string | null>(null);diff --git a/e2e/support/assets/data-apps/isolation/src/ReactProbes.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/ReactProbes.tsxsimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/ReactProbes.tsxrename to e2e/support/assets/data-apps/data_apps/sandbox/src/ReactProbes.tsxdiff --git a/e2e/support/assets/data-apps/data_apps/sandbox/src/Sandbox.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/Sandbox.tsxnew file mode 100644index 00000000000..56347ee6b02--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/sandbox/src/Sandbox.tsx@@ -0,0 +1,97 @@+import { useEffect, useState } from "react";++import { describeError } from "./utils";++const SANDBOX_ALLOWED_URL = "https://allowed.data-app.test/ping";+const SANDBOX_BLOCKED_URL = "https://blocked.data-app.test/ping";++type Probe = { id: string; run: () => void };++const BLOCKED_PROBES: Probe[] = [+ { id: "script", run: () => document.createElement("script") },+ { id: "window-open", run: () => window.open("https://blocked.test") },+ { id: "alert", run: () => window.alert("x") },+ { id: "history", run: () => window.history.pushState({}, "", "/x") },+ {+ id: "keydown-listener",+ run: () => document.addEventListener("keydown", () => {}),+ },+ { id: "websocket", run: () => new WebSocket("wss://blocked.test") },+ {+ id: "sendbeacon",+ run: () => navigator.sendBeacon("https://blocked.test"),+ },+];++export function Sandbox() {+ const [probeResults, setProbeResults] = useState<Record<string, string>>({});+ const [innerHtml, setInnerHtml] = useState("pending");+ const [blockedFetch, setBlockedFetch] = useState("pending");+ const [allowedFetch, setAllowedFetch] = useState("pending");+ const [blockedXhr, setBlockedXhr] = useState("pending");+ const [allowedXhr, setAllowedXhr] = useState("pending");++ useEffect(() => {+ const results: Record<string, string> = {};+ for (const probe of BLOCKED_PROBES) {+ try {+ probe.run();+ results[probe.id] = "not blocked";+ } catch {+ results[probe.id] = "blocked";+ }+ }+ setProbeResults(results);++ // `innerHTML` is distorted through DOMPurify, which strips <script>.+ try {+ const el = document.createElement("div");+ el.innerHTML = "<script>window.x=1</script><b>ok</b>";+ setInnerHtml(el.querySelector("script") ? "not stripped" : "stripped");+ } catch (err) {+ setInnerHtml(`threw: ${describeError(err)}`);+ }++ fetch(SANDBOX_BLOCKED_URL)+ .then((res) => setBlockedFetch(`ok: ${res.status}`))+ .catch((err) => setBlockedFetch(`blocked: ${describeError(err)}`));++ fetch(SANDBOX_ALLOWED_URL)+ .then((res) => setAllowedFetch(`ok: ${res.status}`))+ .catch((err) => setAllowedFetch(`blocked: ${describeError(err)}`));++ try {+ const xhr = new XMLHttpRequest();+ xhr.open("GET", SANDBOX_BLOCKED_URL);+ setBlockedXhr("not blocked");+ } catch (err) {+ setBlockedXhr(`blocked: ${describeError(err)}`);+ }++ const xhr = new XMLHttpRequest();+ xhr.addEventListener("load", () => setAllowedXhr(`ok: ${xhr.status}`));+ xhr.addEventListener("error", () => setAllowedXhr("blocked: error"));+ try {+ xhr.open("GET", SANDBOX_ALLOWED_URL);+ xhr.send();+ } catch (err) {+ setAllowedXhr(`blocked: ${describeError(err)}`);+ }+ }, []);++ return (+ <div data-testid="data-app-sandbox" style={{ padding: 24 }}>+ <h1 style={{ margin: "0 0 16px" }}>Sandbox</h1>+ {BLOCKED_PROBES.map((probe) => (+ <div key={probe.id} data-testid={`probe-${probe.id}`}>+ {probeResults[probe.id] ?? "pending"}+ </div>+ ))}+ <div data-testid="probe-innerhtml">{innerHtml}</div>+ <div data-testid="blocked-fetch-result">{blockedFetch}</div>+ <div data-testid="allowed-fetch-result">{allowedFetch}</div>+ <div data-testid="blocked-xhr-result">{blockedXhr}</div>+ <div data-testid="allowed-xhr-result">{allowedXhr}</div>+ </div>+ );+}diff --git a/e2e/support/assets/data-apps/isolation/src/index.tsx b/e2e/support/assets/data-apps/data_apps/sandbox/src/index.tsxsimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/index.tsxrename to e2e/support/assets/data-apps/data_apps/sandbox/src/index.tsxdiff --git a/e2e/support/assets/data-apps/isolation/src/probes.ts b/e2e/support/assets/data-apps/data_apps/sandbox/src/probes.tssimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/probes.tsrename to e2e/support/assets/data-apps/data_apps/sandbox/src/probes.tsdiff --git a/e2e/support/assets/data-apps/isolation/src/types.ts b/e2e/support/assets/data-apps/data_apps/sandbox/src/types.tssimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/types.tsrename to e2e/support/assets/data-apps/data_apps/sandbox/src/types.tsdiff --git a/e2e/support/assets/data-apps/isolation/src/utils.ts b/e2e/support/assets/data-apps/data_apps/sandbox/src/utils.tssimilarity index 100%rename from e2e/support/assets/data-apps/isolation/src/utils.tsrename to e2e/support/assets/data-apps/data_apps/sandbox/src/utils.tsdiff --git a/e2e/support/assets/data-apps/data_apps/teams/data_app.yaml b/e2e/support/assets/data-apps/data_apps/teams/data_app.yamlnew file mode 100644index 00000000000..68d7992ffa9--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/teams/data_app.yaml@@ -0,0 +1,10 @@+allowed_hosts: []+collection: teamsAppCollection001+description: The teams of the scoreboard, and a form to add one.+entity_id: teamsDataApp000000001+name: Teams+path: dist/index.js+slug: teams+version: 1+serdes/meta:+- model: DataAppdiff --git a/e2e/support/assets/data-apps/data_apps/teams/src/App.tsx b/e2e/support/assets/data-apps/data_apps/teams/src/App.tsxnew file mode 100644index 00000000000..7da74c6d3c5--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/teams/src/App.tsx@@ -0,0 +1,44 @@+import {+ useAction,+ useMetabaseQuery,+} from "@metabase/embedding-sdk-react/data-app";+import { useState } from "react";++import { addTeam } from "./metabase.actions";+import { teamList } from "./metabase.queries";++export default function App() {+ const teams = useMetabaseQuery(teamList);+ const { execute, isExecuting, error } = useAction(addTeam);+ const [teamName, setTeamName] = useState("");++ const onAdd = async () => {+ await execute({ team_name: teamName });+ setTeamName("");+ await teams.refetch();+ };++ return (+ <main style={{ fontFamily: "sans-serif", padding: 24 }}>+ <h1>Teams</h1>+ <ul aria-label="Teams">+ {(teams.data?.rows ?? []).map((team) => (+ <li key={team.team_name}>+ {team.team_name}: {team.score}+ </li>+ ))}+ </ul>+ <label>+ Team name+ <input+ value={teamName}+ onChange={(event) => setTeamName(event.target.value)}+ />+ </label>+ <button type="button" disabled={isExecuting} onClick={onAdd}>+ Add team+ </button>+ {error ? <p role="alert">{String(error)}</p> : null}+ </main>+ );+}diff --git a/e2e/support/assets/data-apps/synced-actions-app/src/index.tsx b/e2e/support/assets/data-apps/data_apps/teams/src/index.tsxsimilarity index 100%rename from e2e/support/assets/data-apps/synced-actions-app/src/index.tsxrename to e2e/support/assets/data-apps/data_apps/teams/src/index.tsxdiff --git a/e2e/support/assets/data-apps/data_apps/teams/src/metabase.actions.ts b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.actions.tsnew file mode 100644index 00000000000..d9cfa9dd289--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.actions.ts@@ -0,0 +1,9 @@+import { defineAction } from "@metabase/embedding-sdk-react/data-app";++import { schema } from "./metabase.schema";++export const addTeam = defineAction({+ entityId: "teamsAppAddTeam000001",+ kind: "row/create",+ table: schema.tables.scoreboardActions,+});diff --git a/e2e/support/assets/data-apps/data_apps/teams/src/metabase.queries.ts b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.queries.tsnew file mode 100644index 00000000000..f4835b6cf1e--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.queries.ts@@ -0,0 +1,12 @@+import { defineQuery, orderBy } from "@metabase/embedding-sdk-react/data-app";++import { schema } from "./metabase.schema";++const teams = schema.tables.scoreboardActions;++export const teamList = defineQuery({+ entityId: "teamsAppTeamList00001",+ source: teams,+ fields: [teams.fields.teamName, teams.fields.score],+ orderBys: [orderBy(teams.fields.teamName, "asc")],+});diff --git a/e2e/support/assets/data-apps/data_apps/teams/src/metabase.schema.ts b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.schema.tsnew file mode 100644index 00000000000..7714c6e7b4d--- /dev/null+++ b/e2e/support/assets/data-apps/data_apps/teams/src/metabase.schema.ts@@ -0,0 +1,84 @@+const tables = {+ scoreboardActions: {+ /* metadata: { "databaseName": "Writable Postgres12", "schemaName": "public", "tableName": "scoreboard_actions" } */+ type: "table",+ id: 215,+ name: "Scoreboard Actions",+ fields: {+ createdAt: {+ /* metadata: { "displayName": "Created At" } */+ type: "column",+ name: "created_at",+ sourceName: "scoreboard_actions",+ jsType: "Date",+ fieldId: 2167,+ tableId: 215,+ baseType: "type/DateTimeWithLocalTZ",+ },+ id: {+ /* metadata: { "displayName": "ID", "semanticType": "type/PK" } */+ type: "column",+ name: "id",+ sourceName: "scoreboard_actions",+ jsType: "number",+ fieldId: 2163,+ tableId: 215,+ baseType: "type/Integer",+ },+ score: {+ /* metadata: { "displayName": "Score" } */+ type: "column",+ name: "score",+ sourceName: "scoreboard_actions",+ jsType: "number",+ fieldId: 2165,+ tableId: 215,+ baseType: "type/Integer",+ },+ status: {+ /* metadata: { "displayName": "Status" } */+ type: "column",+ name: "status",+ sourceName: "scoreboard_actions",+ jsType: "string",+ fieldId: 2166,+ tableId: 215,+ baseType: "type/Text",+ },+ teamName: {+ /* metadata: { "displayName": "Team Name" } */+ type: "column",+ name: "team_name",+ sourceName: "scoreboard_actions",+ jsType: "string",+ fieldId: 2164,+ tableId: 215,+ baseType: "type/Text",+ },+ updatedAt: {+ /* metadata: { "displayName": "Updated At" } */+ type: "column",+ name: "updated_at",+ sourceName: "scoreboard_actions",+ jsType: "Date",+ fieldId: 2168,+ tableId: 215,+ baseType: "type/DateTimeWithLocalTZ",+ },+ },+ },+} as const;++const metrics = {} as const;++const schema = {+ schemaVersion: 3,+ generatedAt: "2026-10-30T00:00:00Z",+ metabase: {+ instanceUrl: "http://localhost:4000",+ },+ tables: tables,+ metrics: metrics,+} as const;++export { schema };diff --git a/e2e/support/assets/data-apps/databases/writable_postgres12/schemas/public/tables/scoreboard_actions/scoreboard_actions___tableusersettings.yaml b/e2e/support/assets/data-apps/databases/writable_postgres12/schemas/public/tables/scoreboard_actions/scoreboard_actions___tableusersettings.yamlnew file mode 100644index 00000000000..42d8120ba2b--- /dev/null+++ b/e2e/support/assets/data-apps/databases/writable_postgres12/schemas/public/tables/scoreboard_actions/scoreboard_actions___tableusersettings.yaml@@ -0,0 +1,8 @@+collection_id: librarylibrarydatadat+is_published: true+table_id:+- Writable Postgres12+- public+- scoreboard_actions+serdes/meta:+- model: TableUserSettingsdiff --git a/e2e/support/assets/data-apps/group-access-test/data_app.yaml b/e2e/support/assets/data-apps/group-access-test/data_app.yamldeleted file mode 100644index fb3cde24bc6..00000000000--- a/e2e/support/assets/data-apps/group-access-test/data_app.yaml+++ /dev/null@@ -1,10 +0,0 @@-name: Group Access Test-slug: group-access-test-version: 1-path: ./dist/index.js-collection: groupAccessAppColl001-entity_id: tQ8R4p2Y7mN6aX9cV3kL5-serdes/meta:-- model: DataApp- id: tQ8R4p2Y7mN6aX9cV3kL5- label: group-access-testdiff --git a/e2e/support/assets/data-apps/group-access-test/src/index.tsx b/e2e/support/assets/data-apps/group-access-test/src/index.tsxdeleted file mode 100644index 0980e129501..00000000000--- a/e2e/support/assets/data-apps/group-access-test/src/index.tsx+++ /dev/null@@ -1,9 +0,0 @@-import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";--function App() {- return <h1>Group access app</h1>;-}--const factory: DataAppFactory = () => ({ component: App });--export default factory;diff --git a/e2e/support/assets/data-apps/isolation/data_app.yaml b/e2e/support/assets/data-apps/isolation/data_app.yamldeleted file mode 100644index 3ff1fd0cd67..00000000000--- a/e2e/support/assets/data-apps/isolation/data_app.yaml+++ /dev/null@@ -1,9 +0,0 @@-version: 1-name: Isolation-slug: isolation-path: ./dist/index.js-entity_id: nu2o-JSPcsIfu3FM0ek24-serdes/meta:-- model: DataApp- id: nu2o-JSPcsIfu3FM0ek24- label: isolationdiff --git a/e2e/support/assets/data-apps/kitchen-sink/data_app.yaml b/e2e/support/assets/data-apps/kitchen-sink/data_app.yamldeleted file mode 100644index b63b7271490..00000000000--- a/e2e/support/assets/data-apps/kitchen-sink/data_app.yaml+++ /dev/null@@ -1,9 +0,0 @@-version: 1-name: Kitchen Sink-slug: kitchen-sink-path: ./dist/index.js-entity_id: JyvrOkPvwWQAQCwUEd1bb-serdes/meta:-- model: DataApp- id: JyvrOkPvwWQAQCwUEd1bb- label: kitchen-sinkdiff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsxdeleted file mode 100644index 65835fb4b61..00000000000--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx+++ /dev/null@@ -1,449 +0,0 @@-import {- InteractiveQuestion,- StaticQuestion,-} from "@metabase/embedding-sdk-react";-import {- copy,- DataAppLink,- DataAppRouter,- defineQuery,- useAction,- useDataAppLocation,- useMetabaseQuery,- useMetabaseQueryObject,-} from "@metabase/embedding-sdk-react/data-app";-import { type ComponentType, useEffect, useState } from "react";--import { actions, queries } from "./metabase";--// The sandbox throws host-realm errors, whose `instanceof Error` can be false in-// the guest; read `.message` defensively.-const describeError = (err: unknown): string =>- (err as { message?: string })?.message ?? String(err);--const PROBE_COLOR = "rgb(0, 128, 0)";--const MISSING_QUERY = defineQuery({- source: { type: "card", entityId: "missingQuestionEntity" },-});--const SANDBOX_ALLOWED_URL = "https://allowed.data-app.test/ping";-const SANDBOX_BLOCKED_URL = "https://blocked.data-app.test/ping";--function Overview() {- const ordersCount = useMetabaseQuery(queries.ordersCount);- const totalOrders = ordersCount.data?.rawRows?.[0]?.[0];- const ordersQuery = useMetabaseQueryObject(queries.orders);-- return (- <div data-testid="data-app-content" style={{ padding: 24 }}>- <h1 style={{ margin: "0 0 16px" }}>Orders overview</h1>-- <section- style={{- padding: 16,- border: "1px solid #e0e0e0",- borderRadius: 8,- marginBottom: 24,- maxWidth: 240,- }}- >- <div- style={{- color: "#6b7280",- fontSize: 12,- textTransform: "uppercase",- letterSpacing: 0.5,- }}- >- Total orders- </div>- <div- data-testid="orders-count"- style={{ fontSize: 32, fontWeight: 700 }}- >- {ordersCount.isLoading ? "…" : String(totalOrders ?? "—")}- </div>- </section>-- <h2 style={{ margin: "0 0 8px" }}>All orders</h2>- <div style={{ height: 400 }}>- {ordersQuery.query ? (- <InteractiveQuestion- card={{ query: ordersQuery.query }}- withDownloads- />- ) : (- <div>…</div>- )}- </div>- </div>- );-}--function Details() {- return (- <div data-testid="data-app-details" style={{ padding: 24 }}>- <h1 style={{ margin: "0 0 16px" }}>Order details</h1>- <p>A nested page reached through the data-app router.</p>- </div>- );-}--function QueryStates() {- const broken = useMetabaseQuery(MISSING_QUERY);- const working = useMetabaseQuery(queries.ordersCount);- const count = working.data?.rawRows?.[0]?.[0];-- return (- <div data-testid="data-app-query-states" style={{ padding: 24 }}>- <h1>Query states</h1>- <div data-testid="query-error">{broken.error ? "error" : "no-error"}</div>- <div data-testid="query-loading">- {working.isLoading ? "loading" : "done"}- </div>- <div data-testid="query-value">- {working.isLoading ? "…" : String(count ?? "—")}- </div>- <button- type="button"- data-testid="query-refetch"- onClick={() => {- working.refetch();- }}- >- refetch- </button>- </div>- );-}--function DownloadQuestionPage() {- return (- <div data-testid="data-app-download-question" style={{ padding: 24 }}>- <h1>Download question</h1>- <div style={{ height: 360 }}>- <StaticQuestion- questionId={queries.ordersByYear.source.entityId}- withDownloads- />- </div>- </div>- );-}--// An InteractiveQuestion on a single-column (count) query, so a spec can switch it-// to a custom viz — the example `demo-viz` requires exactly one result column.-function CustomVizPage() {- const q = useMetabaseQueryObject(queries.ordersCount);-- return (- <div data-testid="data-app-custom-viz" style={{ padding: 24 }}>- <h1>Custom viz</h1>- <div style={{ height: 360 }}>- {q.query ? (- <InteractiveQuestion card={{ query: q.query }} />- ) : (- <div data-testid="custom-viz-loading">…</div>- )}- </div>- </div>- );-}--function StaticQuestionPage() {- const q = useMetabaseQueryObject(queries.orders);-- return (- <div data-testid="data-app-static-question" style={{ padding: 24 }}>- <h1>Static question</h1>- <div style={{ height: 360 }}>- {q.query ? (- <StaticQuestion card={{ query: q.query }} />- ) : (- <div data-testid="static-question-loading">…</div>- )}- </div>- </div>- );-}--type AddTeamParams = { team_name: string; score: number };--function Actions({ params }: { params: AddTeamParams }) {- const action = useAction(actions.addTeam);- const [output, setOutput] = useState("idle");-- const onExecute = async () => {- try {- const res = await action.execute(params);- setOutput(res ? "returned-result" : "returned-null");- } catch {- setOutput("threw");- }- };-- return (- <div data-testid="data-app-actions" style={{ padding: 24 }}>- <h1>Actions</h1>- <button type="button" data-testid="action-execute" onClick={onExecute}>- execute- </button>- <button- type="button"- data-testid="action-reset"- onClick={() => action.reset()}- >- reset- </button>- <div data-testid="action-executing">- {action.isExecuting ? "executing" : "idle"}- </div>- <div data-testid="action-result">- {action.result ? "has-result" : "no-result"}- </div>- <div data-testid="action-error">- {action.error ? "has-error" : "no-error"}- </div>- <div data-testid="action-output">{output}</div>- </div>- );-}--function NewTeamActions() {- return <Actions params={{ team_name: "Data App FC", score: 7 }} />;-}--function ExistingTeamActions() {- return <Actions params={{ team_name: "Amorous Aardvarks", score: 1 }} />;-}--function Clipboard() {- const [status, setStatus] = useState("idle");-- const onCopy = async () => {- try {- await copy("data-app-clipboard-payload");- setStatus("copied");- } catch (err) {- setStatus(`failed: ${describeError(err)}`);- }- };-- return (- <div data-testid="data-app-clipboard" style={{ padding: 24 }}>- <h1>Clipboard</h1>- <button type="button" data-testid="clipboard-copy" onClick={onCopy}>- copy- </button>- <div data-testid="clipboard-status">{status}</div>- </div>- );-}--// With no app-supplied `errorComponent`, the host's default neutral error state-// renders here.-function MissingQuestion() {- return (- <div- data-testid="data-app-missing-question"- style={{ padding: 24, height: 300 }}- >- <StaticQuestion questionId={999999999} />- </div>- );-}--// Throws during render so the host's BundleErrorBoundary reports the failure to-// the parent, which renders its themed error screen.-function ThrowingPage(): JSX.Element {- throw new Error("intentional data-app bundle render error");-}--type Probe = { id: string; run: () => void };--const BLOCKED_PROBES: Probe[] = [- { id: "script", run: () => document.createElement("script") },- { id: "window-open", run: () => window.open("https://blocked.test") },- { id: "alert", run: () => window.alert("x") },- { id: "history", run: () => window.history.pushState({}, "", "/x") },- {- id: "keydown-listener",- run: () => document.addEventListener("keydown", () => {}),- },- { id: "websocket", run: () => new WebSocket("wss://blocked.test") },- {- id: "sendbeacon",- run: () => navigator.sendBeacon("https://blocked.test"),- },-];--function Sandbox() {- const [probeResults, setProbeResults] = useState<Record<string, string>>({});- const [innerHtml, setInnerHtml] = useState("pending");- const [blockedFetch, setBlockedFetch] = useState("pending");- const [allowedFetch, setAllowedFetch] = useState("pending");- const [blockedXhr, setBlockedXhr] = useState("pending");- const [allowedXhr, setAllowedXhr] = useState("pending");-- useEffect(() => {- const results: Record<string, string> = {};- for (const probe of BLOCKED_PROBES) {- try {- probe.run();- results[probe.id] = "not blocked";- } catch {- results[probe.id] = "blocked";- }- }- setProbeResults(results);-- // `innerHTML` is distorted through DOMPurify, which strips <script>.- try {- const el = document.createElement("div");- el.innerHTML = "<script>window.x=1</script><b>ok</b>";- setInnerHtml(el.querySelector("script") ? "not stripped" : "stripped");- } catch (err) {- setInnerHtml(`threw: ${describeError(err)}`);- }-- fetch(SANDBOX_BLOCKED_URL)- .then((res) => setBlockedFetch(`ok: ${res.status}`))- .catch((err) => setBlockedFetch(`blocked: ${describeError(err)}`));-- fetch(SANDBOX_ALLOWED_URL)- .then((res) => setAllowedFetch(`ok: ${res.status}`))- .catch((err) => setAllowedFetch(`blocked: ${describeError(err)}`));-- try {- const xhr = new XMLHttpRequest();- xhr.open("GET", SANDBOX_BLOCKED_URL);- setBlockedXhr("not blocked");- } catch (err) {- setBlockedXhr(`blocked: ${describeError(err)}`);- }-- const xhr = new XMLHttpRequest();- xhr.addEventListener("load", () => setAllowedXhr(`ok: ${xhr.status}`));- xhr.addEventListener("error", () => setAllowedXhr("blocked: error"));- try {- xhr.open("GET", SANDBOX_ALLOWED_URL);- xhr.send();- } catch (err) {- setAllowedXhr(`blocked: ${describeError(err)}`);- }- }, []);-- return (- <div data-testid="data-app-sandbox" style={{ padding: 24 }}>- <h1 style={{ margin: "0 0 16px" }}>Sandbox</h1>- {BLOCKED_PROBES.map((probe) => (- <div key={probe.id} data-testid={`probe-${probe.id}`}>- {probeResults[probe.id] ?? "pending"}- </div>- ))}- <div data-testid="probe-innerhtml">{innerHtml}</div>- <div data-testid="blocked-fetch-result">{blockedFetch}</div>- <div data-testid="allowed-fetch-result">{allowedFetch}</div>- <div data-testid="blocked-xhr-result">{blockedXhr}</div>- <div data-testid="allowed-xhr-result">{allowedXhr}</div>- </div>- );-}--function Isolation() {- const [cssInjected, setCssInjected] = useState("pending");- const [jsMarker, setJsMarker] = useState("pending");-- useEffect(() => {- // `createElement("style")` is the one tag the data-app sandbox permits, so- // apps can style their own sandboxed document.- try {- const style = document.createElement("style");- style.textContent = `.isolation-css-probe { color: ${PROBE_COLOR}; } body { background-color: ${PROBE_COLOR}; }`;- document.head.appendChild(style);- setCssInjected("ok");- } catch (err) {- setCssInjected(`failed: ${describeError(err)}`);- }-- try {- const globals = globalThis as Record<string, unknown>;- globals.__DATA_APP_ISOLATION_MARKER__ = "in-app";- setJsMarker(String(globals.__DATA_APP_ISOLATION_MARKER__));- } catch (err) {- setJsMarker(`failed: ${describeError(err)}`);- }- }, []);-- return (- <div data-testid="data-app-isolation" style={{ padding: 24 }}>- <h1 style={{ margin: "0 0 16px" }}>Isolation</h1>- <div data-testid="css-injected">{cssInjected}</div>- <div data-testid="isolation-css-probe" className="isolation-css-probe">- css probe- </div>- <div data-testid="js-marker">{jsMarker}</div>- </div>- );-}--const ROUTES: Record<string, ComponentType> = {- "/details": Details,- "/sandboxing": Sandbox,- "/isolation": Isolation,- "/query-states": QueryStates,- "/static-question": StaticQuestionPage,- "/download-question": DownloadQuestionPage,- "/custom-viz": CustomVizPage,- "/actions": NewTeamActions,- "/actions-existing-team": ExistingTeamActions,- "/clipboard": Clipboard,- "/missing-question": MissingQuestion,- "/throw": ThrowingPage,-};--function Shell() {- const { pathname, navigate } = useDataAppLocation();- const Page = ROUTES[pathname] ?? Overview;-- return (- <div style={{ fontFamily: "sans-serif" }}>- <nav- style={{- padding: 16,- borderBottom: "1px solid #e0e0e0",- display: "flex",- gap: 16,- flexWrap: "wrap",- }}- >- <DataAppLink to="/">Overview</DataAppLink>- <DataAppLink to="/details">Details</DataAppLink>- <DataAppLink to="/sandboxing">Sandbox</DataAppLink>- <DataAppLink to="/isolation">Isolation</DataAppLink>- <button- type="button"- data-testid="navigate-to-details"- onClick={() => navigate("/details")}- >- navigate to details- </button>- </nav>-- <div data-testid="current-pathname" style={{ padding: "0 16px" }}>- {pathname}- </div>-- <Page />- </div>- );-}--export default function App() {- return (- <DataAppRouter>- <Shell />- </DataAppRouter>- );-}diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/index.tsxdeleted file mode 100644index e59be79c863..00000000000--- a/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx+++ /dev/null@@ -1,13 +0,0 @@-import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";--import App from "./App";--const factory: DataAppFactory = () => ({- component: App,- providerProps: {- // The SDK loads no custom viz outside this allowlist; data-apps/custom-viz.cy.spec.ts uses demo-viz.- allowedCustomVisualizations: ["custom:demo-viz"],- },-});--export default factory;diff --git a/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml b/e2e/support/assets/data-apps/synced-actions-app/data_app.yamldeleted file mode 100644index 6e85142fbf4..00000000000--- a/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml+++ /dev/null@@ -1,10 +0,0 @@-version: 1-name: Synced Actions App-slug: synced-actions-app-path: ./dist/index.js-collection: syncedActionsAppColl1-entity_id: syncedActionsAppEnt01-serdes/meta:-- model: DataApp- id: syncedActionsAppEnt01- label: synced-actions-appdiff --git a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsxdeleted file mode 100644index af2904f0438..00000000000--- a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { useAction } from "@metabase/embedding-sdk-react/data-app";-import { useState } from "react";--import { actions } from "./metabase";--/**- * Executes the action that the app's typed schema defines as `addTeam`.- */-export default function App() {- const action = useAction(actions.addTeam);- const [output, setOutput] = useState("idle");-- const onExecute = async () => {- try {- await action.execute({ team_name: "Data App FC", score: 7 });- setOutput("executed");- } catch (error) {- setOutput(`threw: ${String(error)}`);- }- };-- return (- <div data-testid="synced-actions-content" style={{ padding: 24 }}>- <h1>Synced actions app</h1>-- <button type="button" data-testid="action-execute" onClick={onExecute}>- execute- </button>-- <div data-testid="action-output">{output}</div>- <div data-testid="action-error">- {action.error ? "has-error" : "no-error"}- </div>- </div>- );-}diff --git a/e2e/support/assets/data-apps/synced-app/data_app.yaml b/e2e/support/assets/data-apps/synced-app/data_app.yamldeleted file mode 100644index d9f8fd7e08c..00000000000--- a/e2e/support/assets/data-apps/synced-app/data_app.yaml+++ /dev/null@@ -1,10 +0,0 @@-version: 1-name: Synced App-slug: synced-app-path: ./dist/index.js-collection: syncedAppCollection01-entity_id: syncedAppEntityId0001-serdes/meta:-- model: DataApp- id: syncedAppEntityId0001- label: synced-appdiff --git a/e2e/support/assets/data-apps/synced-app/src/App.tsx b/e2e/support/assets/data-apps/synced-app/src/App.tsxdeleted file mode 100644index 09c5a7eb94e..00000000000--- a/e2e/support/assets/data-apps/synced-app/src/App.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { useMetabaseQuery } from "@metabase/embedding-sdk-react/data-app";--import { queries } from "./metabase";--/**- * Runs the saved question that the app's typed schema defines as `ordersCount`.- */-export default function App() {- const orders = useMetabaseQuery(queries.ordersCount);- const rows = orders.data?.rawRows;-- const total = rows?.[0]?.[1];-- return (- <div data-testid="synced-app-content" style={{ padding: 24 }}>- <h1>Synced app</h1>-- {orders.error ? (- <div data-testid="synced-app-error">{String(orders.error)}</div>- ) : (- <div data-testid="synced-app-total">- {total === undefined ? "" : String(total)}- </div>- )}- </div>- );-}diff --git a/e2e/support/assets/data-apps/synced-app/src/index.tsx b/e2e/support/assets/data-apps/synced-app/src/index.tsxdeleted file mode 100644index 97a94779d6c..00000000000--- a/e2e/support/assets/data-apps/synced-app/src/index.tsx+++ /dev/null@@ -1,7 +0,0 @@-import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";--import App from "./App";--const factory: DataAppFactory = () => ({ component: App });--export default factory;diff --git a/e2e/support/assets/data-apps/tsconfig.json b/e2e/support/assets/data-apps/tsconfig.jsonindex 39c50b3367f..e044daa68a6 100644--- a/e2e/support/assets/data-apps/tsconfig.json+++ b/e2e/support/assets/data-apps/tsconfig.json@@ -9,8 +9,8 @@"../../../../frontend/src/types/**/*.d.ts","../../../../frontend/src/embedding-sdk-shared/types/*.d.ts","../../../../frontend/src/metabase/dayjs/index.ts",- "*/src/**/*.ts",- "*/src/**/*.tsx"+ "data_apps/*/src/**/*.ts",+ "data_apps/*/src/**/*.tsx"],"exclude": [".build"]}diff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yamldeleted file mode 100644index 2c851a85b49..00000000000--- a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app.yaml+++ /dev/null@@ -1,7 +0,0 @@-name: 'Data App: Good App'-namespace: data-apps-entity_id: goodAppCollection0000-serdes/meta:-- id: goodAppCollection0000- label: data_app__good_app- model: Collectiondiff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yamldeleted file mode 100644index bf1dcb45781..00000000000--- a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__good_app/orders_goodAppOrdersQuestion.yaml+++ /dev/null@@ -1,20 +0,0 @@-name: Orders-entity_id: goodAppOrdersQuestion-type: question-display: table-collection_id: goodAppCollection0000-creator_id: [email protected]-dataset_query:- lib/type: mbql/query- database: Sample Database- stages:- - lib/type: mbql.stage/mbql- source-table:- - Sample Database- - PUBLIC- - ORDERS-visualization_settings: {}-serdes/meta:-- id: goodAppOrdersQuestion- label: orders- model: Carddiff --git a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yaml b/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yamldeleted file mode 100644index 021da477763..00000000000--- a/e2e/support/assets/example_synced_data_apps/collections/data_apps/data_app__second_app.yaml+++ /dev/null@@ -1,7 +0,0 @@-name: 'Data App: Second App'-namespace: data-apps-entity_id: secondAppCollection00-serdes/meta:-- id: secondAppCollection00- label: data_app__second_app- model: Collectiondiff --git a/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yamldeleted file mode 100644index 35501aabdb2..00000000000--- a/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml+++ /dev/null@@ -1,11 +0,0 @@-version: 1-name: Good App-slug: good-description: A well-formed app that syncs cleanly-path: ./index.js-collection: goodAppCollection0000-entity_id: Ioxf30LzIQCGwbCNtaG62-serdes/meta:-- model: DataApp- id: Ioxf30LzIQCGwbCNtaG62- label: gooddiff --git a/e2e/support/assets/example_synced_data_apps/data_apps/good/index.js b/e2e/support/assets/example_synced_data_apps/data_apps/good/index.jsdeleted file mode 100644index e68ee3ca4c4..00000000000--- a/e2e/support/assets/example_synced_data_apps/data_apps/good/index.js+++ /dev/null@@ -1,3 +0,0 @@-// A placeholder bundle — this fixture exercises sync/materialization + the admin-// listing + the bundle endpoint, not rendering, so the bytes are served opaquely.-export default () => ({ component: null });diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yamldeleted file mode 100644index 13dc4a3b727..00000000000--- a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/data_app.yaml+++ /dev/null@@ -1,10 +0,0 @@-version: 1-name: Second App-slug: second-app-path: ./index.js-collection: secondAppCollection00-entity_id: A-0Jd9Jt80EIbt1hOavWS-serdes/meta:-- model: DataApp- id: A-0Jd9Jt80EIbt1hOavWS- label: second-appdiff --git a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/index.js b/e2e/support/assets/example_synced_data_apps/data_apps/second-app/index.jsdeleted file mode 100644index e68ee3ca4c4..00000000000--- a/e2e/support/assets/example_synced_data_apps/data_apps/second-app/index.js+++ /dev/null@@ -1,3 +0,0 @@-// A placeholder bundle — this fixture exercises sync/materialization + the admin-// listing + the bundle endpoint, not rendering, so the bytes are served opaquely.-export default () => ({ component: null });diff --git a/e2e/support/config.js b/e2e/support/config.jsindex 9751ed3560b..88b4295c373 100644--- a/e2e/support/config.js+++ b/e2e/support/config.js@@ -31,7 +31,7 @@ import {stopCustomVizDevServer,} from "./helpers/e2e-custom-viz-dev-server-tasks";import {- buildDataApp,+ copyDataAppsFixture,removeDataAppPaths,writeDataAppFiles,} from "./helpers/e2e-data-app-tasks";@@ -311,7 +311,7 @@ const defaultConfig = {stopMockOidcServer,startCustomVizDevServer,stopCustomVizDevServer,- buildDataApp,+ copyDataAppsFixture,writeDataAppFiles,removeDataAppPaths,...perTestCaptureTasks,diff --git a/e2e/support/helpers/build-data-app-fixture.mjs b/e2e/support/helpers/build-data-app-fixture.mjsindex 1d18213b3fe..8d7e76db479 100644--- a/e2e/support/helpers/build-data-app-fixture.mjs+++ b/e2e/support/helpers/build-data-app-fixture.mjs@@ -11,22 +11,22 @@ import {SDK_DATA_APP_DEV_CONFIG_SOURCE,} from "./data-app-fixture-paths.mjs";-const appName = process.argv[2];-if (!appName) {- console.error("usage: build-data-app-fixture.mjs <appName>");+const slug = process.argv[2];+if (!slug) {+ console.error("usage: build-data-app-fixture.mjs <slug>");process.exit(2);}-const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);+const appDir = path.join(DATA_APP_FIXTURES_DIR, "data_apps", slug);if (!fs.existsSync(path.join(appDir, "src"))) {- console.error(`data-app fixture "${appName}" has no src/ at ${appDir}`);+ console.error(`data-app fixture "${slug}" has no src/ at ${appDir}`);process.exit(2);}const scratchDir = path.join(DATA_APP_FIXTURES_DIR, ".build");fs.mkdirSync(scratchDir, { recursive: true });-const dataAppDevEntry = path.join(scratchDir, `${appName}.data-app-dev.mjs`);+const dataAppDevEntry = path.join(scratchDir, `${slug}.data-app-dev.mjs`);await bundle({entryPoints: [SDK_DATA_APP_DEV_CONFIG_SOURCE],diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.tsindex 61add151e13..3b8640dd3fd 100644--- a/e2e/support/helpers/e2e-data-app-helpers.ts+++ b/e2e/support/helpers/e2e-data-app-helpers.ts@@ -1,80 +1,21 @@-import yaml from "js-yaml";--import { USERS, USER_GROUPS } from "e2e/support/cypress_data";+import { USER_GROUPS } from "e2e/support/cypress_data";import * as Urls from "metabase/urls/data-apps";-import type {- CreateDataAppRequest,- DataApp,- DataAppGroup,- GroupId,- GroupInfo,- TableId,-} from "metabase-types/api";+import type { TableId } from "metabase-types/api";-import { createLibrary, publishTables, updateSetting } from "./api";+import { createLibrary, publishTables } from "./api";import { getIframeBody } from "./e2e-embedding-helpers";-import {- LOCAL_GIT_PATH,- commitToRepo,- configureGitAndPullChanges,- copySyncedCollectionFixture,- setupGitSync,-} from "./e2e-remote-sync-helpers";--const DATA_APP_FIXTURES_PATH = "e2e/support/assets/data-apps";--export const DATA_APP_NAME = "kitchen-sink";-export const DATA_APP_DISPLAY_NAME = "Kitchen Sink";--export const visitDataAppRoute = (route: string) => {- installDataAppScopeGuard();- return cy.visit(`/apps/${DATA_APP_NAME}/${route}`);-};--export function createDataApp(- details: CreateDataAppRequest,-): Cypress.Chainable<DataApp> {- return cy- .request<DataApp>("POST", "/api/ee/apps", details)- .then(({ body }) => body);-}--export function addDataAppGroups(- app: Pick<DataApp, "name">,- groupIds: GroupId[],-): Cypress.Chainable<DataAppGroup[]> {- return cy- .request<DataAppGroup[]>("POST", `/api/ee/apps/${app.name}/groups`, {- group_ids: groupIds,- })- .then(({ body }) => body);-}+import { LOCAL_GIT_PATH } from "./e2e-remote-sync-helpers";/**- * Writes `app`'s typed schema to `src/metabase.ts` of the fixture directory named- * `app.name`, builds that fixture, and uploads the build as the app's bundle.+ * Builds the apps of `e2e/support/assets/data-apps` and copies that repository,+ * with the Library and the tables it publishes, into the sync repository.*/-export function uploadDataAppBundle(- app: Pick<DataApp, "name">,-): Cypress.Chainable<DataApp> {- return cy- .request<string>(`/api/ee/apps/${app.name}/typed-schema`)- .then(({ body: typedSchema }) =>- cy.task("writeDataAppFiles", {- files: {- [`${DATA_APP_FIXTURES_PATH}/${app.name}/src/metabase.ts`]:- typedSchema,- },- }),- )- .then(() => cy.task<string>("buildDataApp", { appName: app.name }))- .then((bundle) =>- cy.request<DataApp>("PUT", `/api/ee/apps/${app.name}/bundle`, {- bundle,- }),- )- .then(({ body }) => body);-}+export const copyDataAppsFixture = () =>+ cy.task(+ "copyDataAppsFixture",+ { destination: LOCAL_GIT_PATH },+ { timeout: 300000 },+ );/*** The two rejections endpoint scope enforcement can emit. `scope_not_permitted` comes from@@ -148,246 +89,6 @@ export function dataAppIframe(displayName: string) {return getIframeBody(`iframe[title="${displayName}"]`);}-/**- * A table as serialized YAML references it: database, schema, and table name.- * The schema is null for a database without schemas.- */-export type PortableTable = [- database: string,- schema: string | null,- table: string,-];--type ResourceEntity = Record<string, unknown>;--/** The slug serialization labels an entity with, from its name: lowercase, every other character an underscore. */-const slugOf = (name: string) =>- name.toLowerCase().replace(/[^\p{L}\p{N}_.]/gu, "_");--const serdesMeta = (model: string, entityId: string, name: string) => [- { id: entityId, label: slugOf(name), model },-];--/** The app's collection: a root collection of the `data-apps` namespace. */-const resourceCollection = (- entityId: string,- name: string,-): ResourceEntity => ({- name,- namespace: "data-apps",- entity_id: entityId,- "serdes/meta": serdesMeta("Collection", entityId, name),-});--/**- * A card in the app's collection, as an author writes it: a saved question from a- * query definition, or a copy of a metric from the repository. `stage`- * holds the clauses besides the source table.- */-const resourceCard = ({- entityId,- name,- type,- collection,- table,- stage = {},-}: {- entityId: string;- name: string;- type: "question" | "metric";- collection: string;- table: PortableTable;- stage?: ResourceEntity;-}): ResourceEntity => ({- name,- type,- display: type === "metric" ? "scalar" : "table",- entity_id: entityId,- collection_id: collection,- creator_id: USERS.admin.email,- dataset_query: {- "lib/type": "mbql/query",- database: table[0],- stages: [- { "lib/type": "mbql.stage/mbql", "source-table": table, ...stage },- ],- },- visualization_settings: {},- "serdes/meta": serdesMeta("Card", entityId, name),-});--/**- * The YAML an author writes for an app's collection, in the Metabase- * representation format: plain data for `writeDataAppResources`, read from- * nothing and written nowhere by itself.- */-export const dataAppRepresentations = {- collection: resourceCollection,- card: resourceCard,-};--const fileName = (entity: ResourceEntity) =>- `${slugOf(String(entity.name))}_${String(entity.entity_id)}.yaml`;--/**- * Writes the files of an app's collection as YAML under `collections/data_apps/`- * of `root`, as serialization lays them out: the collection's own file beside- * a directory of its name that holds the cards and actions. `root` is the- * repository the app lives in, or the app itself when it stands alone, as the- * CLI reads them. Replaces what was there for that collection.- */-export function writeDataAppResources(- root: string,- {- collection,- cards = [],- actions = [],- }: {- collection: ResourceEntity;- cards?: ResourceEntity[];- actions?: ResourceEntity[];- },-) {- const collectionsDir = `${root}/collections/data_apps`;- const stem = slugOf(String(collection.name));- const collectionDir = `${collectionsDir}/${stem}`;-- cy.task("removeDataAppPaths", {- paths: [`${collectionsDir}/${stem}.yaml`, collectionDir],- });-- return cy.task("writeDataAppFiles", {- files: {- [`${collectionsDir}/${stem}.yaml`]: yaml.dump(collection),- ...Object.fromEntries(- [...cards, ...actions].map((entity) => [- `${collectionDir}/${fileName(entity)}`,- yaml.dump(entity),- ]),- ),- },- });-}--export const copySyncedDataAppsFixture = () =>- cy.task("copyDirectory", {- source: `${Cypress.config("projectRoot")}/e2e/support/assets/example_synced_data_apps`,- destination: LOCAL_GIT_PATH,- });--/**- * Pulls `example_synced_data_apps` through a real remote-sync import, so a spec- * gets real app rows, each with its resource collection and permission group.- * Both `good` and `second-app` are served. `goodAppCards` replaces the- * `good` app's saved questions, so a spec decides which tables it reads.- */-export function pullExampleDataApps({- goodAppCards,-}: { goodAppCards?: ResourceEntity[] } = {}) {- setupGitSync();- copySyncedCollectionFixture();- updateSetting("remote-sync-custom-collections-enabled", true);- copySyncedDataAppsFixture();- if (goodAppCards) {- writeDataAppResources(LOCAL_GIT_PATH, {- collection: resourceCollection(- "goodAppCollection0000",- "Data App: Good App",- ),- cards: goodAppCards,- });- }- commitToRepo("Add data apps");- configureGitAndPullChanges("read-write");-}--/** A data app whose resources loaded into its collection. */-export type SyncedDataApp = DataApp & {- resource_collection_id: number;-};--const isSyncedDataApp = (app: DataApp): app is SyncedDataApp =>- typeof app.resource_collection_id === "number";--/**- * Writes the app's manifest into the sync repository as `data_apps/<slug>`, makes- * the repository's `collections/data_apps/` what the host app holds, and- * commits them, as an author does. The bundle is a placeholder that every pull- * loads again, so a spec uploads the built one with `uploadDataAppBundle` after- * its last pull. Pass `initializeRepo: false` to write into the repository an- * earlier call set up.- */-function commitDataApp(- appRoot: string,- slug: string,- { initializeRepo = true }: { initializeRepo?: boolean } = {},-) {- const appDir = `${LOCAL_GIT_PATH}/data_apps/${slug}`;- const collectionsDir = `${LOCAL_GIT_PATH}/collections/data_apps`;-- if (initializeRepo) {- setupGitSync();- copySyncedCollectionFixture();- updateSetting("remote-sync-custom-collections-enabled", true);- }- // A copy only adds, so a file the author deleted would stay in the repository.- cy.task("removeDataAppPaths", { paths: [collectionsDir] });- cy.task("copyDirectory", {- source: `${appRoot}/collections/data_apps`,- destination: collectionsDir,- });- cy.readFile(`${appRoot}/data_app.yaml`).then((manifest: string) =>- cy.task("writeDataAppFiles", {- files: {- [`${appDir}/data_app.yaml`]: manifest,- [`${appDir}/dist/index.js`]: "// uploaded by the spec",- },- }),- );- commitToRepo(`Publish ${slug}`);-}--/**- * Publishes the app with a pull and yields it once its resources loaded: with- * its collection and its permission group, which the admin list carries.- */-export function publishDataApp(- appRoot: string,- slug: string,- options?: { initializeRepo?: boolean },-) {- commitDataApp(appRoot, slug, options);- configureGitAndPullChanges("read-write");-- return cy.request<DataApp[]>("/api/ee/apps").then(({ body: apps }) => {- const app = apps.find(({ name }) => name === slug);-- if (!app) {- throw new Error(`The pull loaded no data app named ${slug}.`);- }- if (!isSyncedDataApp(app)) {- throw new Error(- `Data app ${slug} loaded without its resource collection or group.`,- );- }-- return cy.wrap(app, { log: false });- });-}--/** Creates a group and adds it to `app`'s groups, yielding the group's ID. */-export function assignTestGroupToDataApp(- app: Pick<DataApp, "name">,-): Cypress.Chainable<GroupId> {- return cy- .request<GroupInfo>("POST", "/api/permissions/group", {- name: `Data app test group: ${app.name}`,- })- .then(({ body: group }) =>- addDataAppGroups(app, [group.id]).then(() => group.id),- );-}-const DATA_APP_DEV_HOST_APP_DIR ="e2e/embedding-sdk-host-apps/vite-6-data-app-host-app";@@ -406,8 +107,6 @@ export function visitDataAppDevApp(clientHost: string) {}).should("exist");}-const DATA_APP_DEV_SLUG = "vite-6-data-app-host-app";-type DataAppDevServerOpts = {clientHost: string;tableId: TableId;@@ -424,11 +123,6 @@ export function setUpDataAppDevServer({createLibrary();publishTables({ table_ids: [tableId] });- createDataApp({- name: DATA_APP_DEV_SLUG,- allowed_hosts: ["https://allowed.data-app.test"],- });-cy.task("removeDataAppPaths", { paths: [DATA_APP_DEV_ENV_PATH] });waitForDataAppDevServerEnv(clientHost, mbUrl, { expectPresent: false });diff --git a/e2e/support/helpers/e2e-data-app-tasks.ts b/e2e/support/helpers/e2e-data-app-tasks.tsindex af56e9e5417..9af6367fdad 100644--- a/e2e/support/helpers/e2e-data-app-tasks.ts+++ b/e2e/support/helpers/e2e-data-app-tasks.ts@@ -39,28 +39,45 @@ function run(script: string, args: string[], env: NodeJS.ProcessEnv = {}) {});}-export async function buildDataApp({- appName,-}: {- appName: string;-}): Promise<string> {- const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);+const REPOSITORY_DIRS = ["collections", "databases", "data_apps"];- if (!fs.existsSync(path.join(appDir, "src"))) {- throw new Error(`data-app fixture "${appName}" has no src/ at ${appDir}`);- }+let buildingApps: Promise<void> | undefined;- await run(DATA_APP_BUILD_SCRIPT, [appName]);+/** Builds every fixture app once per Cypress process, into its own `dist/`. */+function buildDataApps() {+ buildingApps ??= (async () => {+ const appsDir = path.join(DATA_APP_FIXTURES_DIR, "data_apps");- const bundlePath = path.join(DATA_APP_FIXTURES_DIR, appName, "dist/index.js");+ for (const slug of fs.readdirSync(appsDir)) {+ await run(DATA_APP_BUILD_SCRIPT, [slug]);+ }+ })();- if (!fs.existsSync(bundlePath)) {- throw new Error(- `data-app build for "${appName}" produced no bundle at ${bundlePath}`,+ return buildingApps;+}++/**+ * Builds the fixture apps and copies the fixture repository, with the built+ * bundles, into `destination`, as an author's repository holds them.+ */+export async function copyDataAppsFixture({+ destination,+}: {+ destination: string;+}): Promise<null> {+ await buildDataApps();++ for (const dir of REPOSITORY_DIRS) {+ fs.cpSync(+ path.join(DATA_APP_FIXTURES_DIR, dir),+ path.join(destination, dir),+ {+ recursive: true,+ },);}- return fs.readFileSync(bundlePath, "utf8");+ return null;}/** Cypress resolves a relative path against the project root; match that. */diff --git a/e2e/test-host-app/data-apps/data-app-dev.cy.spec.ts b/e2e/test-host-app/data-apps/data-app-dev.cy.spec.tsdeleted file mode 100644index 2a991c87e3b..00000000000--- a/e2e/test-host-app/data-apps/data-app-dev.cy.spec.ts+++ /dev/null@@ -1,54 +0,0 @@-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import {- setUpDataAppDevServer,- tearDownDataAppDevServer,-} from "e2e/support/helpers/e2e-data-app-helpers";-import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";--const TIMEOUT_MS = 40000;--const CLIENT_PORT = Cypress.expose("CLIENT_PORT");-const CLIENT_HOST = `http://localhost:${CLIENT_PORT}`;--const { ORDERS_ID } = SAMPLE_DATABASE;--describe("Embedding SDK: data-app dev server", () => {- before(() => {- signInAsAdminAndEnableEmbeddingSdk();- setUpDataAppDevServer({ clientHost: CLIENT_HOST, tableId: ORDERS_ID });- });-- after(() => {- tearDownDataAppDevServer();- });-- it("serves and renders the sandboxed data app", () => {- cy.visit(CLIENT_HOST);-- cy.findByTestId("dev-app-content", { timeout: TIMEOUT_MS }).should("exist");- cy.findByTestId("dev-app-question").should("exist");- });-- it("renders a StaticQuestion fed a query from useMetabaseQueryObject", () => {- cy.visit(CLIENT_HOST);-- cy.findByTestId("table-body", { timeout: TIMEOUT_MS })- .findAllByTestId("cell-data")- .should("have.length.greaterThan", 0);- });-- it("sandboxes network requests but permits allowed_hosts", () => {- cy.intercept("https://allowed.data-app.test/**").as("allowedRequest");- cy.intercept("https://blocked.data-app.test/**").as("blockedRequest");-- cy.visit(CLIENT_HOST);-- // The allowed host (in data_app.yaml) reaches the network; the other never- // does — the sandbox rejects it before a request is made.- cy.get("@allowedRequest.all", { timeout: TIMEOUT_MS }).should(- "have.length.at.least",- 1,- );- cy.get("@blockedRequest.all").should("have.length", 0);- });-});diff --git a/e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.ts b/e2e/test-host-app/data-apps/data-apps-preview.cy.spec.tssimilarity index 93%rename from e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.tsrename to e2e/test-host-app/data-apps/data-apps-preview.cy.spec.tsindex a911c79c02a..a5eefda823d 100644--- a/e2e/test-host-app/data-apps/data-app-dev-diagnostics.cy.spec.ts+++ b/e2e/test-host-app/data-apps/data-apps-preview.cy.spec.ts@@ -24,7 +24,7 @@ const { ORDERS_ID } = SAMPLE_DATABASE;const DIAGNOSTICS_URL = `${CLIENT_HOST}${DATA_APP_DEV_DIAGNOSTICS_PATH}`;-describe("Embedding SDK: data-app dev diagnostics", () => {+describe("Embedding SDK: data-app dev preview", () => {before(() => {signInAsAdminAndEnableEmbeddingSdk();setUpDataAppDevServer({ clientHost: CLIENT_HOST, tableId: ORDERS_ID });@@ -34,6 +34,36 @@ describe("Embedding SDK: data-app dev diagnostics", () => {tearDownDataAppDevServer();});+ it("serves and renders the sandboxed data app", () => {+ cy.visit(CLIENT_HOST);++ cy.findByTestId("dev-app-content", { timeout: TIMEOUT_MS }).should("exist");+ cy.findByTestId("dev-app-question").should("exist");+ });++ it("renders a StaticQuestion fed a query from useMetabaseQueryObject", () => {+ cy.visit(CLIENT_HOST);++ cy.findByTestId("table-body", { timeout: TIMEOUT_MS })+ .findAllByTestId("cell-data")+ .should("have.length.greaterThan", 0);+ });++ it("sandboxes network requests but permits allowed_hosts", () => {+ cy.intercept("https://allowed.data-app.test/**").as("allowedRequest");+ cy.intercept("https://blocked.data-app.test/**").as("blockedRequest");++ cy.visit(CLIENT_HOST);++ // The allowed host (in data_app.yaml) reaches the network; the other never+ // does — the sandbox rejects it before a request is made.+ cy.get("@allowedRequest.all", { timeout: TIMEOUT_MS }).should(+ "have.length.at.least",+ 1,+ );+ cy.get("@blockedRequest.all").should("have.length", 0);+ });+describe("dev diagnostics", () => {beforeEach(() => {// The dev server's buffer outlives page loads by design; start each testdiff --git a/e2e/test/scenarios/data-apps/actions.cy.spec.ts b/e2e/test/scenarios/data-apps/actions.cy.spec.tsdeleted file mode 100644index 6ef2cef343e..00000000000--- a/e2e/test/scenarios/data-apps/actions.cy.spec.ts+++ /dev/null@@ -1,111 +0,0 @@-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- visitDataAppRoute as visitAppRoute,-} from "e2e/support/helpers";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--const TEST_TABLE = "scoreboard_actions";-const EXISTING_TEAM = "Amorous Aardvarks";--describe(- "scenarios > data apps > actions (useAction)",- { tags: ["@external", "@actions"] },- () => {- beforeEach(() => {- H.restore("postgres-writable");- cy.signInAsAdmin();- H.activateToken("bleeding-edge");-- H.resetTestTable({ type: "postgres", table: TEST_TABLE });- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });- H.setActionsEnabledForDB(WRITABLE_DB_ID);- });-- it("executes the action, exposing isExecuting and result, and resets", () => {- cy.intercept("POST", "/api/action/*/execute", (req) => {- req.on("response", (res) => {- res.setDelay(300);- });- });-- createKitchenSinkDataApp({}, { withAddTeamAction: true });-- visitAppRoute("actions");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("action-execute").click();- cy.findByTestId("action-executing").should("have.text", "executing");-- cy.findByTestId("action-result", { timeout: 30000 }).should(- "have.text",- "has-result",- );- cy.findByTestId("action-output").should("have.text", "returned-result");- cy.findByTestId("action-error").should("have.text", "no-error");-- cy.findByTestId("action-reset").click();- cy.findByTestId("action-result").should("have.text", "no-result");- });-- H.queryWritableDB(- `SELECT team_name, score FROM ${TEST_TABLE} WHERE team_name = 'Data App FC'`,- ).then(({ rows }) => {- expect(rows).to.have.length(1);- expect(rows[0].score).to.eq(7);- });- });-- it("surfaces an error when the action fails", () => {- // `team_name` is unique, so creating a team that already exists fails in the- // database — a real rejection, not a stubbed one.- createKitchenSinkDataApp({}, { withAddTeamAction: true });-- visitAppRoute("actions-existing-team");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("action-execute").click();-- cy.findByTestId("action-error", { timeout: 30000 }).should(- "have.text",- "has-error",- );- cy.findByTestId("action-result").should("have.text", "no-result");- cy.findByTestId("action-executing").should("have.text", "idle");- });-- H.queryWritableDB(- `SELECT team_name FROM ${TEST_TABLE} WHERE team_name = '${EXISTING_TEAM}'`,- ).then(({ rows }) => {- // Nothing was written - the existing team is still the only one.- expect(rows).to.have.length(1);- });- });-- describe("non-admin access", () => {- it("executes action for non-admin member of app's group", () => {- createKitchenSinkDataApp({}, { withAddTeamAction: true });- cy.signInAsNormalUser();-- visitAppRoute("actions");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("action-execute").click();-- cy.findByTestId("action-result", { timeout: 30000 }).should(- "have.text",- "has-result",- );- cy.findByTestId("action-error").should("have.text", "no-error");- });-- H.queryWritableDB(- `SELECT team_name, score FROM ${TEST_TABLE} WHERE team_name = 'Data App FC'`,- ).then(({ rows }) => {- expect(rows).to.have.length(1);- expect(rows[0].score).to.eq(7);- });- });- });- },-);diff --git a/e2e/test/scenarios/data-apps/backend_scope.cy.spec.ts b/e2e/test/scenarios/data-apps/backend_scope.cy.spec.tsdeleted file mode 100644index 41fa2e1f472..00000000000--- a/e2e/test/scenarios/data-apps/backend_scope.cy.spec.ts+++ /dev/null@@ -1,107 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- DATA_APP_NAME as APP_NAME,-} from "e2e/support/helpers";--import { createKitchenSinkDataApp } 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", () => {- createKitchenSinkDataApp();- 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/custom-viz.cy.spec.ts b/e2e/test/scenarios/data-apps/custom-viz.cy.spec.tsdeleted file mode 100644index 073bd3735bd..00000000000--- a/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts+++ /dev/null@@ -1,38 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- visitDataAppRoute as visitAppRoute,-} from "e2e/support/helpers";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--describe("scenarios > data apps > custom visualizations", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- // Enabling custom viz requires CSP image loading on, then the feature toggle.- H.updateSetting("csp-img-enabled", true);- H.updateSetting("custom-viz-enabled", true);- // Install the example plugin (identifier "demo-viz") straight through the API.- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);- });-- it("renders a custom visualization inside a data app", () => {- createKitchenSinkDataApp();-- visitAppRoute("custom-viz");-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- // Switch the visualization to the custom viz through the chart-type selector.- cy.findByTestId("chart-type-selector-button", { timeout: 30000 }).click();- cy.findByText("demo-viz").click();-- // The custom viz's own DOM proves it loaded + rendered inside the data app.- cy.findByTestId("demo-viz-click-target", { timeout: 30000 }).should(- "be.visible",- );- });- });-});diff --git a/e2e/test/scenarios/data-apps/data-apps-monitor.cy.spec.ts b/e2e/test/scenarios/data-apps/data-apps-monitor.cy.spec.tsnew file mode 100644index 00000000000..8b065f87e7e--- /dev/null+++ b/e2e/test/scenarios/data-apps/data-apps-monitor.cy.spec.ts@@ -0,0 +1,86 @@+import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";++const { H } = cy;++const TEAMS_TABLE = "scoreboard_actions";+const APP_SLUG = "teams";+const APP_NAME = "Teams";+const ADMIN_NAME = `${USERS.admin.first_name} ${USERS.admin.last_name}`;++// The first query against the audit view can take a while to settle, and the page's other+// queries share `/api/dataset`, so this waits for the table to stop loading rather than on an alias.+function logRows() {+ cy.findByTestId("data-app-log-table", { timeout: 20000 }).should(+ "have.attr",+ "aria-busy",+ "false",+ );+ return cy+ .findByTestId("data-app-log-table")+ .findAllByTestId("data-app-log-row");+}++function selectFilterOption(label: string, option: string) {+ H.main().findByLabelText(label).click();+ H.popover().findByRole("option", { name: option }).click();+}++// The log has more columns than the default viewport fits.+describe(+ "scenarios > data apps > monitor",+ { tags: ["@external", "@actions"], viewportWidth: 1600 },+ () => {+ beforeEach(() => {+ H.restore("postgres-writable");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.resetTestTable({ type: "postgres", table: TEAMS_TABLE });+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEAMS_TABLE });+ H.setActionsEnabledForDB(WRITABLE_DB_ID);++ H.createLibrary();+ H.setupGitSync();+ H.copyDataAppsFixture();+ H.commitToRepo("Add data apps");+ H.configureGitAndPullChanges("read-only");+ });++ it("lists the questions and actions an app runs, and narrows the log by entity type and app", () => {+ cy.intercept("POST", "/api/action/*/execute").as("execute");+ H.openDataApp(APP_SLUG);+ H.dataAppIframe(APP_NAME).within(() => {+ cy.findByText("Amorous Aardvarks: 0", { timeout: 30000 }).should(+ "be.visible",+ );+ cy.findByLabelText("Team name").type("Data App FC");+ cy.findByRole("button", { name: "Add team" }).click();+ });+ cy.wait("@execute");++ cy.visit("/monitor/ai-auditing/data-apps");+ cy.findByTestId("monitor-nav")+ .findByRole("link", { name: "Data app analytics" })+ .should("be.visible");++ cy.log("the app's records, by app and user");+ logRows()+ .should("contain", APP_NAME)+ .and("contain", APP_SLUG)+ .and("contain", "Question")+ .and("contain", "teamList")+ .and("contain", "Action")+ .and("contain", ADMIN_NAME);++ cy.log("only the action runs");+ selectFilterOption("Entity type", "Action");+ cy.location("search").should("contain", "type=action");+ logRows().should("contain", APP_SLUG).and("not.contain", "teamList");++ cy.log("only the app's records");+ selectFilterOption("Entity type", "All entity types");+ selectFilterOption("Data app", APP_NAME);+ cy.location("search").should("contain", `app=${APP_SLUG}`);+ logRows().should("contain", "teamList");+ });+ },+);diff --git a/e2e/test/scenarios/data-apps/data-apps-sandbox.cy.spec.ts b/e2e/test/scenarios/data-apps/data-apps-sandbox.cy.spec.tsnew file mode 100644index 00000000000..03f35d17e33--- /dev/null+++ b/e2e/test/scenarios/data-apps/data-apps-sandbox.cy.spec.ts@@ -0,0 +1,368 @@+import { WRITABLE_DB_ID } from "e2e/support/cypress_data";++const { H } = cy;++const TEAMS_TABLE = "scoreboard_actions";+const APP_NAME = "sandbox";+const APP_DISPLAY_NAME = "Sandbox";++describe("scenarios > data apps > sandbox", { tags: ["@external"] }, () => {+ beforeEach(() => {+ H.restore("postgres-writable");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.resetTestTable({ type: "postgres", table: TEAMS_TABLE });+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEAMS_TABLE });++ H.createLibrary();+ H.setupGitSync();+ H.copyDataAppsFixture();+ H.commitToRepo("Add data apps");+ H.configureGitAndPullChanges("read-only");+ });++ describe("sandboxing", () => {+ const ALLOWED_ORIGIN = "https://allowed.data-app.test";+ const ALLOWED_URL = `${ALLOWED_ORIGIN}/ping`;++ // Method/constructor calls the sandbox distortion replaces with a throwing+ // shim. (Getter-only reads like `localStorage` aren't intercepted, so they+ // aren't asserted here.)+ const BLOCKED_PROBE_IDS = [+ "script",+ "window-open",+ "alert",+ "history",+ "keydown-listener",+ "websocket",+ "sendbeacon",+ ];++ it("blocks dangerous globals, strips innerHTML, gates XHR, and blocks cross-origin fetch but permits allowed_hosts", () => {+ // The allowed host is stubbed with a CORS header so the sandbox's real+ // network call resolves; the blocked host is never intercepted because the+ // sandbox rejects it before it reaches the network.+ cy.intercept("GET", ALLOWED_URL, {+ statusCode: 200,+ headers: { "access-control-allow-origin": "*" },+ body: "pong",+ });++ H.openDataApp(APP_NAME);+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByRole("link", { name: "Sandbox" }).click();+ BLOCKED_PROBE_IDS.forEach((id) => {+ cy.findByTestId(`probe-${id}`, { timeout: 30000 }).should(+ "have.text",+ "blocked",+ );+ });++ cy.findByTestId("probe-innerhtml").should("have.text", "stripped");++ // A fetch to a host not in allowed_hosts is rejected by the sandbox.+ cy.findByTestId("blocked-fetch-result", { timeout: 30000 }).should(+ "contain",+ "not in allowed_hosts",+ );++ // A fetch to a host in allowed_hosts reaches the (stubbed) network.+ cy.findByTestId("allowed-fetch-result", { timeout: 30000 }).should(+ "have.text",+ "ok: 200",+ );++ // XHR is hard-blocked entirely — data apps are fetch-only. It can't opt out+ // of following a redirect back to the instance, so it's never allowlisted+ // like fetch: both blocked and allowed hosts are refused.+ cy.findByTestId("blocked-xhr-result").should("contain", "blocked");+ cy.findByTestId("allowed-xhr-result", { timeout: 30000 }).should(+ "contain",+ "blocked",+ );+ });+ });+ });++ describe("isolation", () => {+ it("serves the embed document with locked-down headers, renders the app in a sandboxed iframe, and keeps the app's CSS and JS globals inside it", () => {+ cy.request({+ url: `/embed/apps/${APP_NAME}`,+ followRedirect: false,+ }).then((res) => {+ expect(res.status).to.eq(200);+ expect(String(res.body)).to.contain("app-data-app");+ const csp = String(res.headers["content-security-policy"] ?? "");+ expect(csp).to.contain("frame-ancestors 'self'");+ expect(csp).to.contain("default-src 'none'");+ expect(csp).to.contain(+ "form-action https://allowed.data-app.test http://localhost:4444;",+ );+ // The data-app document deliberately does NOT grant 'unsafe-eval' — it's+ // confined to the sandbox-host realm doc (see the BE sandbox-host-endpoint-test).+ expect(csp).to.not.contain("'unsafe-eval'");+ expect(String(res.headers["x-frame-options"] ?? "")).to.match(+ /sameorigin/i,+ );+ });++ H.openDataApp(APP_NAME);++ cy.get(`iframe[title="${APP_DISPLAY_NAME}"]`)+ .should("have.attr", "sandbox")+ .and("contain", "allow-scripts")+ .and("not.contain", "allow-top-navigation")+ .and("not.contain", "allow-popups-to-escape-sandbox");++ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByRole("heading", { name: "Isolation probe" }).should(+ "be.visible",+ );+ cy.findByRole("link", { name: "Isolation" }).click();++ // The injected <style> applies to the app's own document.+ cy.findByTestId("css-injected").should("have.text", "ok");+ cy.findByTestId("isolation-css-probe").should(+ "have.css",+ "color",+ "rgb(0, 128, 0)",+ );++ // The app set the global in its own realm and read it back.+ cy.findByTestId("js-marker").should("have.text", "in-app");+ });++ // The aggressive `body` rule injected in the iframe does not reach the+ // parent document.+ cy.get("body").should(+ "not.have.css",+ "background-color",+ "rgb(0, 128, 0)",+ );++ // The parent window never sees the app's global.+ cy.window().should("not.have.property", "__DATA_APP_ISOLATION_MARKER__");+ });+ });++ describe("isolation probes", () => {+ const setup = () => {+ H.openDataApp(APP_NAME);+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("isolation-result", { timeout: 30000 }).should(+ "have.text",+ "pending",+ );+ });+ };++ /**+ * Click each probe in turn and record what it reported, then assert that the+ * boundary held for all of them at once, so every failing probe shows. Every+ * probe stops at the first sign it reached across the boundary: `isolated:`+ * means it did not, `reached:` means it did. `no-probe-observed` means the+ * probe never fired, which is also a failure. The fixture resets the result to+ * `pending` and tags it with the probe's id on each click, so a result is only+ * read once it belongs to the probe just clicked.+ */+ const runProbes = (probeIds: string[]) => {+ const results: Record<string, string> = {};++ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ probeIds.forEach((probeId) => {+ cy.findByTestId(`isolation-${probeId}`).scrollIntoView().click();++ cy.findByTestId("isolation-result", { timeout: 30000 })+ .should(($result) => {+ expect($result.attr("data-probe-id")).to.eq(probeId);+ expect($result.text()).not.to.eq("pending");+ })+ .invoke("text")+ .then((text) => {+ cy.log(`${probeId}: ${text}`);+ results[probeId] = text;+ });+ });+ });++ cy.then(() => {+ expect(Object.keys(results), "every probe reported").to.deep.eq(+ probeIds,+ );+ expect(+ probeIds+ .filter((probeId) => !results[probeId].includes("isolated:"))+ .map((probeId) => `${probeId}: ${results[probeId]}`),+ "probes that crossed the boundary",+ ).to.deep.eq([]);+ });+ };++ const guardMessage = () =>+ cy.contains("blocked host createElement", { timeout: 30000 });++ it("keeps the realms the app creates within the gated realm", () => {+ setup();++ runProbes([+ "window-frames",+ "create-element",+ "dom-parser",+ "adopt-html-doc-iframe",+ "import-html-doc-iframe",+ "xml-doc-iframe",+ "template-doc-iframe",+ "range-fragment-iframe",+ "inner-html",+ "custom-element",+ "window-open",+ ]);+ });++ // 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("keeps the host window, its storage and a host iframe's realm gated, and marks the SDK's requests 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();++ // `/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.wrap(markedPaths, { timeout: 30000 }).should((paths) => {+ expect([...paths], "requests marked as data-app").to.include(+ "/api/user/current",+ );+ });++ // 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+ // clone iframe has. Create it in the PARENT (whose createElement the host+ // guard never patched) and adopt it into the data-app document, mimicking a+ // host-created child frame the guest then reaches for.+ H.dataAppIframe(APP_DISPLAY_NAME).then(($body) => {+ const doc = $body[0].ownerDocument;+ const parentDoc = doc.defaultView!.parent.document;+ const iframe = parentDoc.createElement("iframe");+ iframe.style.display = "none";+ doc.body.appendChild(doc.adoptNode(iframe));++ expect(iframe.contentWindow !== null, "adopted iframe realm").to.equal(+ true,+ );+ });++ runProbes([+ "child-frame-grab",+ "window-parent",+ "window-top",+ "frame-element",+ "parent-chain",+ "window-opener",+ "parent-cookie",+ "parent-local-storage",+ "parent-session-storage",+ "parent-indexeddb",+ "parent-caches",+ ]);+ });++ it("gates the APIs that run code, read host data or reach a host realm", () => {+ setup();++ runProbes([+ "perf-resource-timing",+ "function-constructor",+ "worker",+ "shared-worker",+ "service-worker",+ "dynamic-import",+ "font-face",+ "cookie-store",+ "endowment-api",+ "stack-trace-realm",+ ]);+ });++ /**+ * For the probes whose element is refused during React's own render pass.+ *+ * The guard throws from `createElement` inside the reconciler, and the app's+ * `BoundaryReporter` never catches it: that boundary is declared in the GUEST+ * realm while HOST React renders the tree, and React's error-boundary detection+ * does not survive the membrane. The throw therefore reaches the host boundary+ * and takes the data app down — which is the correct outcome, but it also+ * destroys the probe, so there is no `isolation-result` left to read. Assert on+ * the guard's own message instead, and open the app again for each probe.+ */+ it("gates host-React iframes: about:blank, Metabase itself and srcdoc", () => {+ ["react-about-blank", "react-src", "react-srcdoc"].forEach((probeId) => {+ cy.log(probeId);+ H.openDataApp(APP_NAME);++ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("isolation-result", { timeout: 30000 }).should(+ "have.text",+ "pending",+ );+ });+ guardMessage().should("not.exist");++ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId(`isolation-${probeId}`).scrollIntoView().click();+ });+ guardMessage().should("exist");+ });+ });++ it("gates an allowed_host redirect to the instance", () => {+ const instanceUrl = Cypress.config("baseUrl") ?? "";+ const cors = {+ "Access-Control-Allow-Origin": instanceUrl,+ "Access-Control-Allow-Credentials": "true",+ };++ // An allowed host that answers the CORS preflight for a credentialed GET,+ // then 307-redirects it to the instance origin. The sandbox fetch checks only+ // the initial (allowed) URL; it must not follow the redirect across origins.+ cy.intercept("OPTIONS", "http://localhost:4444/**", {+ statusCode: 204,+ headers: {+ ...cors,+ "Access-Control-Allow-Methods": "GET",+ "Access-Control-Allow-Headers": "content-type",+ },+ });+ cy.intercept("GET", "http://localhost:4444/**", (req) => {+ req.reply({+ statusCode: 307,+ headers: {+ ...cors,+ Location: `${instanceUrl}/api/session/properties`,+ },+ });+ }).as("allowedHostRedirect");++ H.openDataApp(APP_NAME);+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("isolation-result", { timeout: 30000 }).should(+ "have.text",+ "pending",+ );+ });++ runProbes(["allowed-host-redirect"]);+ cy.wait("@allowedHostRedirect");+ });+ });+});diff --git a/e2e/test/scenarios/data-apps/data-apps.cy.spec.ts b/e2e/test/scenarios/data-apps/data-apps.cy.spec.tsnew file mode 100644index 00000000000..869dbb484d5--- /dev/null+++ b/e2e/test/scenarios/data-apps/data-apps.cy.spec.ts@@ -0,0 +1,151 @@+import { USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";++const { H } = cy;++const TEAMS_TABLE = "scoreboard_actions";+const APP_SLUG = "teams";+const APP_NAME = "Teams";+const NEW_TEAM = "Data App FC";++describe("scenarios > data apps", { tags: ["@external", "@actions"] }, () => {+ beforeEach(() => {+ H.restore("postgres-writable");+ H.resetSnowplow();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.resetTestTable({ type: "postgres", table: TEAMS_TABLE });+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEAMS_TABLE });+ H.setActionsEnabledForDB(WRITABLE_DB_ID);++ H.createLibrary();+ H.setupGitSync();+ H.copyDataAppsFixture();+ H.commitToRepo("Add data apps");+ H.configureGitAndPullChanges("read-only");+ });++ afterEach(() => {+ H.expectNoBadSnowplowEvents();+ });++ it("runs an imported app's question and action", () => {+ H.openDataApp(APP_SLUG);+ H.dataAppIframe(APP_NAME).within(() => {+ cy.findByRole("list", { name: "Teams" })+ .findByText("Amorous Aardvarks: 0", { timeout: 30000 })+ .should("be.visible");++ addTeam(NEW_TEAM);+ cy.findByRole("list", { name: "Teams" })+ .findByText(`${NEW_TEAM}: 0`)+ .should("be.visible");+ });++ H.queryWritableDB(+ `SELECT score FROM ${TEAMS_TABLE} WHERE team_name = '${NEW_TEAM}'`,+ ).then(({ rows }) => {+ expect(rows).to.have.length(1);+ });+ });++ it("lists an imported app with its questions and actions, and makes it a draft and live again", () => {+ cy.intercept("PUT", `/api/ee/apps/${APP_SLUG}`).as("updateApp");++ cy.visit("/data-studio/apps");+ H.main().findByText(APP_NAME).click();+ cy.location("pathname").should("eq", `/data-studio/apps/${APP_SLUG}`);+ H.dataAppIframe(APP_NAME)+ .findByText("Amorous Aardvarks: 0", { timeout: 30000 })+ .should("be.visible");++ cy.log("make the app a draft and live again");+ cy.findByTestId("data-app-about-sidebar")+ .findByText("Live")+ .should("be.visible");+ cy.findByRole("button", { name: "Data app options" }).click();+ H.popover()+ .findByRole("menuitem", { name: /Make draft/ })+ .click();+ H.modal().findByRole("button", { name: "Make draft" }).click();+ cy.wait("@updateApp");+ H.expectUnstructuredSnowplowEvent({ event: "data_app_made_draft" });+ cy.findByTestId("data-app-about-sidebar")+ .findByText("Draft")+ .should("be.visible");++ cy.findByRole("button", { name: "Data app options" }).click();+ H.popover()+ .findByRole("menuitem", { name: /Make live/ })+ .click();+ H.modal().findByRole("button", { name: "Make live" }).click();+ cy.wait("@updateApp");+ H.expectUnstructuredSnowplowEvent({ event: "data_app_made_live" });+ cy.findByTestId("data-app-about-sidebar")+ .findByText("Live")+ .should("be.visible");++ cy.log("open the app's question");+ H.main().findByRole("link", { name: "Questions" }).click();+ H.main().findByText("teamList").click();+ cy.location("pathname").should(+ "match",+ new RegExp(`^/data-studio/apps/${APP_SLUG}/questions/\\d+$`),+ );++ cy.log("open the app's action");+ cy.visit(`/data-studio/apps/${APP_SLUG}`);+ H.main().findByRole("link", { name: "Actions" }).click();+ H.main().findByText("addTeam").click();+ cy.location("pathname").should(+ "match",+ new RegExp(`^/data-studio/apps/${APP_SLUG}/actions/\\d+$`),+ );+ cy.findByTestId("data-app-action-definition").should("be.visible");+ });++ it("lets the members of a group the app is shared with use it", () => {+ cy.request("GET", `/api/permissions/group/${USER_GROUPS.DATA_GROUP}`)+ .its("body.name")+ .as("groupName");++ cy.log("people outside the app's groups cannot open it");+ cy.signInAsNormalUser();+ H.openDataApp(APP_SLUG);+ H.main()+ .findByText("You don’t have access to this data app")+ .should("be.visible");++ cy.log("share the app with a group");+ cy.signInAsAdmin();+ cy.intercept("POST", `/api/ee/apps/${APP_SLUG}/groups`).as("addGroups");+ cy.visit(`/data-studio/apps/${APP_SLUG}/permissions`);+ H.main().findByRole("button", { name: "Add groups" }).click();+ H.modal().findByRole("textbox", { name: "Groups" }).click();+ cy.get<string>("@groupName").then((name) =>+ cy.findByRole("option", { name }).click(),+ );+ H.modal().findByRole("button", { name: "Add" }).click();+ cy.wait("@addGroups");+ H.expectUnstructuredSnowplowEvent({ event: "data_app_group_added" });++ cy.log("a member of the group opens the app and uses it");+ cy.signInAsNormalUser();+ cy.visit("/");+ H.navigationSidebar()+ .findByRole("link", { name: new RegExp(`${APP_NAME}$`) })+ .invoke("removeAttr", "target")+ .click();+ H.dataAppIframe(APP_NAME).within(() => {+ cy.findByText("Amorous Aardvarks: 0", { timeout: 30000 }).should(+ "be.visible",+ );+ addTeam(NEW_TEAM);+ cy.findByText(`${NEW_TEAM}: 0`).should("be.visible");+ });+ });+});++function addTeam(name: string) {+ cy.findByLabelText("Team name").type(name);+ cy.findByRole("button", { name: "Add team" }).click();+}diff --git a/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.ts b/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.tsdeleted file mode 100644index 4521f9c2d4a..00000000000--- a/e2e/test/scenarios/data-apps/data-studio-permissions.cy.spec.ts+++ /dev/null@@ -1,236 +0,0 @@-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import {- ALL_USERS_GROUP_ID,- COLLECTION_GROUP_ID,-} from "e2e/support/cypress_sample_instance_data";-import type { GroupInfo } from "metabase-types/api";--const { H } = cy;-const { ORDERS_ID } = SAMPLE_DATABASE;--const EMPTY_STATE_TEXT =- "Only admins can open this app. Add groups to give people in them access.";--describe("scenarios > data apps > data studio permissions", () => {- beforeEach(() => {- H.restore();- H.resetSnowplow();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- });-- afterEach(() => {- H.expectNoBadSnowplowEvents();- });-- describe("group access", () => {- const APP_NAME = "group-access-test";- const APP_DISPLAY_NAME = "Group Access Test";- const APP_LINK_REGEX = new RegExp(`${APP_DISPLAY_NAME}$`);-- beforeEach(() => {- H.setupGitSync();- H.copySyncedCollectionFixture();- H.updateSetting("remote-sync-custom-collections-enabled", true);-- H.writeDataAppResources(H.LOCAL_GIT_PATH, {- collection: H.dataAppRepresentations.collection(- "groupAccessAppColl001",- `Data App: ${APP_DISPLAY_NAME}`,- ),- });-- // A built bundle and manifest let remote sync publish a real app, so- // access goes through the real permission checks.- cy.task<string>("buildDataApp", { appName: APP_NAME }).then((bundle) =>- cy.writeFile(- `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/dist/index.js`,- bundle,- ),- );- cy.readFile(- `e2e/support/assets/data-apps/${APP_NAME}/data_app.yaml`,- ).then((manifest) =>- cy.writeFile(- `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/data_app.yaml`,- manifest,- ),- );-- H.commitToRepo("Add a data app for testing group access");- H.configureGitAndPullChanges("read-write");-- cy.request("GET", `/api/permissions/group/${COLLECTION_GROUP_ID}`)- .its("body.name")- .as("groupName");- });-- it("grants and revokes access to an app when adding and removing a group", () => {- cy.log("the app is hidden and access is denied by default");- cy.signIn("nodata");- assertAppIsHidden();- assertAppAccessDenied();-- cy.signInAsAdmin();- cy.intercept("POST", `/api/ee/apps/${APP_NAME}/groups`).as("addGroups");- cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);- H.main().findByText(EMPTY_STATE_TEXT).should("be.visible");-- cy.log("add a group to the app");- H.main().findByRole("button", { name: "Add groups" }).click();- H.modal().findByRole("textbox", { name: "Groups" }).click();- cy.get<string>("@groupName").then((name) =>- cy.findByRole("option", { name }).click(),- );- H.modal().findByRole("button", { name: "Add" }).click();- cy.wait("@addGroups");- H.expectUnstructuredSnowplowEvent({ event: "data_app_group_added" });-- cy.get<string>("@groupName").then((name) =>- H.main().findByText(name).should("be.visible"),- );-- cy.log("members of the group can open the app");- cy.signIn("nodata");- visitHome();- H.navigationSidebar()- .findByRole("link", { name: APP_LINK_REGEX })- .should("be.visible")- .invoke("removeAttr", "target")- .click();- assertAppIsRendered();-- cy.log("remove the group after confirming");- cy.signInAsAdmin();- cy.intercept("DELETE", `/api/ee/apps/${APP_NAME}/groups/*`).as(- "removeGroup",- );- cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);- cy.get<string>("@groupName").then((name) =>- H.main()- .findByRole("button", { name: `${name} options` })- .click(),- );- H.popover()- .findByRole("menuitem", { name: /Remove access/ })- .click();- H.modal().findByRole("button", { name: "Remove access" }).click();- cy.wait("@removeGroup");- H.expectUnstructuredSnowplowEvent({ event: "data_app_group_removed" });- H.main().findByText(EMPTY_STATE_TEXT).should("be.visible");-- cy.log("admins can still open the app");- H.openDataApp(APP_NAME);- assertAppIsRendered();-- cy.log("members of the removed group lose access");- cy.signIn("nodata");- assertAppIsHidden();- assertAppAccessDenied();- });-- function visitHome() {- cy.intercept("GET", "/api/ee/apps").as("dataApps");- cy.visit("/");- cy.wait("@dataApps");- H.navigationSidebar()- .findByRole("listitem", { name: "Home" })- .should("be.visible");- }-- function assertAppIsHidden() {- visitHome();- H.navigationSidebar()- .findByRole("link", { name: APP_LINK_REGEX })- .should("not.exist");- }-- function assertAppAccessDenied() {- H.openDataApp(APP_NAME);- H.main()- .findByText("You don’t have access to this data app")- .should("be.visible");- }-- function assertAppIsRendered() {- H.dataAppIframe(APP_DISPLAY_NAME)- .findByRole("heading", { name: "Group access app" })- .should("be.visible");- }- });-- describe("missing data access", () => {- const APP_NAME = "good";- const GROUP_NAME = "Finches";- const DATA_ACCESS_PERMISSION_INDEX = 0;-- beforeEach(() => {- H.pullExampleDataApps({- goodAppCards: [- H.dataAppRepresentations.card({- entityId: "warningsOrdersCard000",- name: "Orders",- type: "question",- collection: "goodAppCollection0000",- table: ["Sample Database", "PUBLIC", "ORDERS"],- }),- ],- });- H.waitForBackfillComplete();-- cy.request<GroupInfo>("POST", "/api/permissions/group", {- name: GROUP_NAME,- }).then(({ body: group }) => {- H.blockUserGroupPermissions(ALL_USERS_GROUP_ID);- H.blockUserGroupPermissions(group.id);- cy.request("POST", `/api/ee/apps/${APP_NAME}/groups`, {- group_ids: [group.id],- });- });- });-- it("shows the tables a group can't view, links to their permissions, and clears once access is granted", () => {- cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);-- H.main()- .findByRole("row", { name: new RegExp(GROUP_NAME) })- .findByText("Missing 1 table")- .should("be.visible")- .click();-- cy.findByTestId("data-app-group-sidebar").within(() => {- cy.findByRole("heading", { name: GROUP_NAME }).should("be.visible");- cy.findByRole("region", { name: "Missing tables" }).within(() => {- cy.findByText("Sample Database").should("be.visible");- cy.findByText("PUBLIC").should("be.visible");- cy.findByText("Orders").click();- });- });-- H.popover()- .findByRole("menuitem", { name: /Change permissions/ })- .should("have.attr", "href")- .and("include", `/admin/permissions/data/database/${SAMPLE_DB_ID}/`)- .and("include", `/table/${ORDERS_ID}`);-- cy.log("grant access to the table");- cy.visit(- `/admin/permissions/data/database/${SAMPLE_DB_ID}/schema/PUBLIC/table/${ORDERS_ID}`,- );- H.assertPermissionForItem(- GROUP_NAME,- DATA_ACCESS_PERMISSION_INDEX,- "Blocked",- );- H.modifyPermission(GROUP_NAME, DATA_ACCESS_PERMISSION_INDEX, "Can view");- H.savePermissions();-- cy.visit(`/data-studio/apps/${APP_NAME}/permissions`);- H.main()- .findByRole("row", { name: new RegExp(GROUP_NAME) })- .findByText("All tables")- .should("be.visible");- });- });-});diff --git a/e2e/test/scenarios/data-apps/data-studio.cy.spec.ts b/e2e/test/scenarios/data-apps/data-studio.cy.spec.tsdeleted file mode 100644index 4aa24ccfe4e..00000000000--- a/e2e/test/scenarios/data-apps/data-studio.cy.spec.ts+++ /dev/null@@ -1,157 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- DATA_APP_NAME as APP_NAME,-} from "e2e/support/helpers";-import type { DataApp } from "metabase-types/api";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--const SYNCED_APP_NAME = "good";-const SYNCED_APP_DISPLAY_NAME = "Good App";--describe("scenarios > data apps > data studio", () => {- beforeEach(() => {- H.restore();- H.resetSnowplow();- cy.signInAsAdmin();- // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.- H.activateToken("bleeding-edge");- });-- afterEach(() => {- H.expectNoBadSnowplowEvents();- });-- it("lists a data app and previews it on the app's overview", () => {- createKitchenSinkDataApp();-- cy.intercept("POST", "/api/dataset").as("dataAppQuery");-- cy.visit("/data-studio/apps");- H.main().findByText(APP_DISPLAY_NAME).click();-- cy.location("pathname").should("eq", `/data-studio/apps/${APP_NAME}`);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- cy.findByTestId("orders-count", { timeout: 30000 })- .invoke("text")- .should("match", /^\d+$/);- });-- // The iframe's query requests must be attributed to the data app, so- // query_execution analytics record which app ran them (EMB-2088).- cy.wait("@dataAppQuery").then(({ request }) => {- expect(request.headers["x-metabase-client"]).to.equal("data-app");- expect(request.headers["x-metabase-client-identifier"]).to.equal(- APP_NAME,- );- });- });-- it("makes an app a draft and live again", () => {- H.pullExampleDataApps();- cy.intercept("PUT", `/api/ee/apps/${SYNCED_APP_NAME}`).as("updateGoodApp");-- cy.visit(`/data-studio/apps/${SYNCED_APP_NAME}`);- cy.findByTestId("data-app-about-sidebar")- .findByText("Live")- .should("be.visible");-- cy.findByRole("button", { name: "Data app options" }).click();- H.popover()- .findByRole("menuitem", { name: /Make draft/ })- .click();- H.modal()- .findByText(`Make ${SYNCED_APP_DISPLAY_NAME} a draft?`)- .should("be.visible");- H.modal().findByRole("button", { name: "Make draft" }).click();- cy.wait("@updateGoodApp");- H.expectUnstructuredSnowplowEvent({ event: "data_app_made_draft" });-- cy.findByTestId("data-app-about-sidebar")- .findByText("Draft")- .should("be.visible");-- cy.findByRole("button", { name: "Data app options" }).click();- H.popover()- .findByRole("menuitem", { name: /Make live/ })- .click();- H.modal().findByRole("button", { name: "Make live" }).click();- cy.wait("@updateGoodApp");- H.expectUnstructuredSnowplowEvent({ event: "data_app_made_live" });-- cy.findByTestId("data-app-about-sidebar")- .findByText("Live")- .should("be.visible");- });-- it("lists the app's questions and opens one", () => {- H.pullExampleDataApps();-- cy.visit(`/data-studio/apps/${SYNCED_APP_NAME}`);- H.main().findByRole("link", { name: "Questions" }).click();- H.main().findByText("Orders").click();-- cy.location("pathname").should(- "match",- new RegExp(`^/data-studio/apps/${SYNCED_APP_NAME}/questions/\\d+$`),- );- cy.findByTestId("data-app-question-overview")- .findByRole("link", { name: "Questions" })- .should(- "have.attr",- "href",- `/data-studio/apps/${SYNCED_APP_NAME}/questions`,- );- });-- describe("outdated apps", () => {- // Only a bump of the supported version makes a real app outdated, so the flag- // the API computes is patched onto a real app's responses instead.- function markAppOutdated() {- H.pullExampleDataApps();-- cy.intercept("GET", "/api/ee/apps", (req) => {- req.continue((res) => {- res.body = res.body.map((app: DataApp) =>- app.name === SYNCED_APP_NAME- ? { ...app, version: 1, outdated: true }- : app,- );- });- });- cy.intercept(- { method: "GET", pathname: `/api/ee/apps/${SYNCED_APP_NAME}` },- (req) => {- req.continue((res) => {- res.body = { ...res.body, version: 1, outdated: true };- });- },- );- }-- it("marks an outdated app in the list, offers no way to open it there, and refuses to open it", () => {- markAppOutdated();-- cy.visit("/data-studio/apps");- H.main()- .findByRole("row", { name: new RegExp(SYNCED_APP_DISPLAY_NAME) })- .within(() => {- cy.findByText("Live, outdated").should("be.visible");- cy.findByRole("button", { name: "Data app options" }).click();- });- H.popover().within(() => {- cy.findByRole("menuitem", { name: /Make draft/ }).should("be.visible");- cy.findByRole("menuitem", { name: /Open app/ }).should("not.exist");- });-- H.openDataApp(SYNCED_APP_NAME);- H.main().findByText("This data app is outdated").should("be.visible");- cy.get("iframe").should("not.exist");- });- });-});diff --git a/e2e/test/scenarios/data-apps/helpers/index.ts b/e2e/test/scenarios/data-apps/helpers/index.tsdeleted file mode 100644index 6b0b9ca39e2..00000000000--- a/e2e/test/scenarios/data-apps/helpers/index.ts+++ /dev/null@@ -1,128 +0,0 @@-import {- SAMPLE_DB_ID,- USER_GROUPS,- WRITABLE_DB_ID,-} from "e2e/support/cypress_data";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import type {- Card,- CollectionId,- DataApp,- TestStageSpec,- VisualizationDisplay,- WritebackAction,-} from "metabase-types/api";--const { H } = cy;--const { ORDERS_ID } = SAMPLE_DATABASE;--const COUNT = { type: "operator", operator: "count" } as const;--function createOrdersCard(- collectionId: CollectionId,- name: string,- display: VisualizationDisplay,- stage: TestStageSpec = {},-): Cypress.Chainable<Card> {- return H.createTestQuery({- database: SAMPLE_DB_ID,- stages: [{ source: { type: "table", id: ORDERS_ID }, ...stage }],- }).then((dataset_query) =>- H.createCard({- name,- display,- dataset_query,- collection_id: collectionId,- }),- );-}--/** Creates the questions the kitchen-sink app reads, in `app`'s collection. */-function createKitchenSinkQuestions(app: DataApp) {- createOrdersCard(app.resource_collection_id, "Orders", "table");- createOrdersCard(app.resource_collection_id, "Orders count", "scalar", {- aggregations: [COUNT],- });- createOrdersCard(app.resource_collection_id, "Orders by year", "line", {- aggregations: [COUNT],- breakouts: [{ type: "column", name: "CREATED_AT", unit: "year" }],- });-}--type KitchenSinkDataAppDetails = {- display_name?: string;- description?: string | null;- allowed_hosts?: string[];- enabled?: boolean;-};--type KitchenSinkDataAppOpts = {- withAddTeamAction?: boolean;-};--/**- * Creates the Library, publishes ORDERS to it, and creates the kitchen-sink app,- * readable by All Users, with its questions, the "Add team" action when asked,- * and its bundle built against them.- */-export function createKitchenSinkDataApp(- details: KitchenSinkDataAppDetails = {},- { withAddTeamAction = false }: KitchenSinkDataAppOpts = {},-): Cypress.Chainable<DataApp> {- H.createLibrary();- H.publishTables({ table_ids: [ORDERS_ID] });-- return H.createDataApp({- name: H.DATA_APP_NAME,- display_name: H.DATA_APP_DISPLAY_NAME,- ...details,- }).then((app) => {- H.addDataAppGroups(app, [USER_GROUPS.ALL_USERS_GROUP]);- createKitchenSinkQuestions(app);- if (withAddTeamAction) {- createAddTeamAction(app.resource_collection_id);- }- return H.uploadDataAppBundle(app);- });-}--/** Creates the model-less "Add team" action, which inserts a team into `scoreboard_actions`. */-export function createAddTeamAction(- collectionId: CollectionId,-): Cypress.Chainable<WritebackAction> {- return H.createTestNativeQuery({- database: WRITABLE_DB_ID,- query:- "INSERT INTO scoreboard_actions (team_name, score) VALUES ({{team_name}}, {{score}})",- templateTags: {- team_name: { type: "text", "display-name": "Team name", required: true },- score: { type: "number", "display-name": "Score", required: true },- },- }).then((dataset_query) =>- H.createAction({- name: "Add team",- type: "query",- collection_id: collectionId,- dataset_query,- parameters: [- {- id: "team_name",- slug: "team_name",- name: "Team name",- type: "string/=",- target: ["variable", ["template-tag", "team_name"]],- required: true,- },- {- id: "score",- slug: "score",- name: "Score",- type: "number/=",- target: ["variable", ["template-tag", "score"]],- required: true,- },- ],- }),- );-}diff --git a/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.tsdeleted file mode 100644index ed1367a43b4..00000000000--- a/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts+++ /dev/null@@ -1,85 +0,0 @@-import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";--import { createAddTeamAction } from "./helpers";--const { H } = cy;--const TEST_TABLE = "scoreboard_actions";--const APP_SLUG = "synced-actions-app";-const APP_DISPLAY_NAME = "Synced Actions App";--/** The fixture's `data_app.yaml` names this collection. */-const COLLECTION = "syncedActionsAppColl1";--const APP_ROOT = () =>- `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;--describe(- "scenarios > data apps > resources from a repository (actions)",- { tags: ["@external", "@actions"] },- () => {- const removeTestFiles = () =>- cy.task("removeDataAppPaths", {- paths: [`${APP_ROOT()}/collections`],- });-- beforeEach(() => {- H.restore("postgres-writable");- cy.signInAsAdmin();- H.activateToken("bleeding-edge");-- H.resetTestTable({ type: "postgres", table: TEST_TABLE });- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });- H.setActionsEnabledForDB(WRITABLE_DB_ID);-- removeTestFiles();- });-- after(() => {- removeTestFiles();- });-- /**- * Publishes the app, creates an action in its collection, and uploads the- * app's bundle built against its typed schema.- */- const publishApp = () => {- H.writeDataAppResources(APP_ROOT(), {- collection: H.dataAppRepresentations.collection(- COLLECTION,- "Data App: Synced Actions App",- ),- });-- return H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) =>- createAddTeamAction(app.resource_collection_id).then((action) =>- H.uploadDataAppBundle(app).then(() =>- cy.wrap({ app, action }, { log: false }),- ),- ),- );- };-- it("executes the action in the app's collection for a member of the app's group", () => {- publishApp().then(({ app, action }) => {- H.assignTestGroupToDataApp(app).then((groupId) => {- H.addUserToGroup(groupId, USERS.normal.email);- });-- cy.signInAsNormalUser();- cy.intercept("POST", "/api/action/*/execute").as("execute");- cy.visit(`/apps/${APP_SLUG}`);-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("action-execute", { timeout: 30000 }).click();- cy.findByTestId("action-output").should("have.text", "executed");- });-- cy.wait("@execute")- .its("request.url")- .should("contain", `/api/action/${action.entity_id}/execute`);- });- });- },-);diff --git a/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production.cy.spec.tsdeleted file mode 100644index aaabb742338..00000000000--- a/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts+++ /dev/null@@ -1,120 +0,0 @@-import { USERS } from "e2e/support/cypress_data";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import type { PortableTable } from "e2e/support/helpers";-import type { Card } from "metabase-types/api";--const { H } = cy;--const APP_SLUG = "synced-app";-const APP_DISPLAY_NAME = "Synced App";--/** The fixture's `data_app.yaml` names this collection. */-const COLLECTION = "syncedAppCollection01";-const QUESTION_ENTITY_ID = "syncedAppOrdersCount1";--const ORDERS_TABLE: PortableTable = ["Sample Database", "PUBLIC", "ORDERS"];--const APP_ROOT = () =>- `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;--/** The saved question an author writes, which the app's typed schema defines as `ordersCount`. */-const ORDERS_COUNT_QUESTION = H.dataAppRepresentations.card({- entityId: QUESTION_ENTITY_ID,- name: "OrdersCount",- type: "question",- collection: COLLECTION,- table: ORDERS_TABLE,- stage: {- aggregation: [["count", { "lib/uuid": crypto.randomUUID() }]],- breakout: [- [- "field",- { "lib/uuid": crypto.randomUUID() },- [...ORDERS_TABLE, "USER_ID"],- ],- ],- },-});--/**- * An app imported from a repository runs the saved question its typed schema- * defines, which the pull loaded into the app's collection.- */-describe("scenarios > data apps > resources from a repository", () => {- const removeTestFiles = () =>- cy.task("removeDataAppPaths", {- paths: [`${APP_ROOT()}/collections`],- });-- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- H.createLibrary();- H.publishTables({ table_ids: [SAMPLE_DATABASE.ORDERS_ID] });-- removeTestFiles();- H.writeDataAppResources(APP_ROOT(), {- collection: H.dataAppRepresentations.collection(- COLLECTION,- "Data App: Synced App",- ),- cards: [ORDERS_COUNT_QUESTION],- });- });-- after(() => {- removeTestFiles();- });-- /** Publishes the fixture, uploads its bundle, and yields the app with the ID of the card it must now run. */- const publishApp = () =>- H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) =>- H.uploadDataAppBundle(app).then(() =>- cy- .request<Card>(`/api/card/${QUESTION_ENTITY_ID}`)- .then(({ body: card }) =>- cy.wrap({ app, cardId: card.id }, { log: false }),- ),- ),- );-- it("runs the saved question its definition names", () => {- publishApp().then(({ cardId }) => {- cy.intercept("POST", "/api/dataset").as("dataset");- cy.visit(`/apps/${APP_SLUG}`);-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("synced-app-total", { timeout: 30000 }).should(- ($total) => {- expect(Number($total.text())).to.be.greaterThan(0);- },- );- });-- cy.wait("@dataset").then(({ request }) => {- const [stage] = request.body.stages ?? [];- expect(stage?.["source-card"], "runs the saved question").to.eq(cardId);- });- });- });-- it("serves the app to a member of its permission group", () => {- publishApp().then(({ app }) => {- H.assignTestGroupToDataApp(app).then((groupId) => {- H.addUserToGroup(groupId, USERS.normal.email);- });-- cy.signInAsNormalUser();- cy.visit(`/apps/${APP_SLUG}`);-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("synced-app-total", { timeout: 30000 }).should(- ($total) => {- expect(Number($total.text())).to.be.greaterThan(0);- },- );- });- });- });-});diff --git a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts b/e2e/test/scenarios/data-apps/sandbox.cy.spec.tsdeleted file mode 100644index 9a785ca50e5..00000000000--- a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts+++ /dev/null@@ -1,143 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- DATA_APP_NAME as APP_NAME,- visitDataAppRoute as visitAppRoute,-} from "e2e/support/helpers";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--describe("scenarios > data apps > sandbox & isolation", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.- H.activateToken("bleeding-edge");- });-- describe("sandboxing", () => {- const ALLOWED_ORIGIN = "https://allowed.data-app.test";- const ALLOWED_URL = `${ALLOWED_ORIGIN}/ping`;-- // Method/constructor calls the sandbox distortion replaces with a throwing- // shim. (Getter-only reads like `localStorage` aren't intercepted, so they- // aren't asserted here.)- const BLOCKED_PROBE_IDS = [- "script",- "window-open",- "alert",- "history",- "keydown-listener",- "websocket",- "sendbeacon",- ];-- it("blocks dangerous globals, strips innerHTML, gates XHR, and blocks cross-origin fetch but permits allowed_hosts", () => {- // The allowed host is stubbed with a CORS header so the sandbox's real- // network call resolves; the blocked host is never intercepted because the- // sandbox rejects it before it reaches the network.- cy.intercept("GET", ALLOWED_URL, {- statusCode: 200,- headers: { "access-control-allow-origin": "*" },- body: "pong",- });-- createKitchenSinkDataApp({ allowed_hosts: [ALLOWED_ORIGIN] });-- visitAppRoute("sandboxing");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- BLOCKED_PROBE_IDS.forEach((id) => {- cy.findByTestId(`probe-${id}`, { timeout: 30000 }).should(- "have.text",- "blocked",- );- });-- cy.findByTestId("probe-innerhtml").should("have.text", "stripped");-- // A fetch to a host not in allowed_hosts is rejected by the sandbox.- cy.findByTestId("blocked-fetch-result", { timeout: 30000 }).should(- "contain",- "not in allowed_hosts",- );-- // A fetch to a host in allowed_hosts reaches the (stubbed) network.- cy.findByTestId("allowed-fetch-result", { timeout: 30000 }).should(- "have.text",- "ok: 200",- );-- // XHR is hard-blocked entirely — data apps are fetch-only. It can't opt out- // of following a redirect back to the instance, so it's never allowlisted- // like fetch: both blocked and allowed hosts are refused.- cy.findByTestId("blocked-xhr-result").should("contain", "blocked");- cy.findByTestId("allowed-xhr-result", { timeout: 30000 }).should(- "contain",- "blocked",- );- });- });- });-- describe("isolation", () => {- it("serves the embed document with locked-down headers, renders the app in a sandboxed iframe, and keeps the app's CSS and JS globals inside it", () => {- createKitchenSinkDataApp();-- cy.request({- url: `/embed/apps/${APP_NAME}`,- followRedirect: false,- }).then((res) => {- expect(res.status).to.eq(200);- expect(String(res.body)).to.contain("app-data-app");- const csp = String(res.headers["content-security-policy"] ?? "");- expect(csp).to.contain("frame-ancestors 'self'");- expect(csp).to.contain("default-src 'none'");- expect(csp).to.contain("form-action 'none'");- // The data-app document deliberately does NOT grant 'unsafe-eval' — it's- // confined to the sandbox-host realm doc (see the BE sandbox-host-endpoint-test).- expect(csp).to.not.contain("'unsafe-eval'");- expect(String(res.headers["x-frame-options"] ?? "")).to.match(- /sameorigin/i,- );- });-- H.openDataApp(APP_NAME);-- cy.get(`iframe[title="${APP_DISPLAY_NAME}"]`)- .should("have.attr", "sandbox")- .and("contain", "allow-scripts")- .and("not.contain", "allow-top-navigation")- .and("not.contain", "allow-popups-to-escape-sandbox");-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- cy.findByRole("link", { name: "Isolation" }).click();-- // The injected <style> applies to the app's own document.- cy.findByTestId("css-injected").should("have.text", "ok");- cy.findByTestId("isolation-css-probe").should(- "have.css",- "color",- "rgb(0, 128, 0)",- );-- // The app set the global in its own realm and read it back.- cy.findByTestId("js-marker").should("have.text", "in-app");- });-- // The aggressive `body` rule injected in the iframe does not reach the- // parent document.- cy.get("body").should(- "not.have.css",- "background-color",- "rgb(0, 128, 0)",- );-- // The parent window never sees the app's global.- cy.window().should("not.have.property", "__DATA_APP_ISOLATION_MARKER__");- });- });-});diff --git a/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts b/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.tsdeleted file mode 100644index 2683bfa579e..00000000000--- a/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts+++ /dev/null@@ -1,237 +0,0 @@-const { H } = cy;--const APP_NAME = "isolation";-const APP_DISPLAY_NAME = "Isolation";--describe("scenarios > data apps > sandbox isolation", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- });-- const createIsolationDataApp = (allowedHosts: string[] = []) =>- H.createDataApp({- name: APP_NAME,- display_name: APP_DISPLAY_NAME,- allowed_hosts: allowedHosts,- }).then(H.uploadDataAppBundle);-- const setup = () => {- createIsolationDataApp();- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("isolation-result", { timeout: 30000 }).should(- "have.text",- "pending",- );- });- };-- /**- * Click each probe in turn and record what it reported, then assert that the- * boundary held for all of them at once, so every failing probe shows. Every- * probe stops at the first sign it reached across the boundary: `isolated:`- * means it did not, `reached:` means it did. `no-probe-observed` means the- * probe never fired, which is also a failure. The fixture resets the result to- * `pending` and tags it with the probe's id on each click, so a result is only- * read once it belongs to the probe just clicked.- */- const runProbes = (probeIds: string[]) => {- const results: Record<string, string> = {};-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- probeIds.forEach((probeId) => {- cy.findByTestId(`isolation-${probeId}`).scrollIntoView().click();-- cy.findByTestId("isolation-result", { timeout: 30000 })- .should(($result) => {- expect($result.attr("data-probe-id")).to.eq(probeId);- expect($result.text()).not.to.eq("pending");- })- .invoke("text")- .then((text) => {- cy.log(`${probeId}: ${text}`);- results[probeId] = text;- });- });- });-- cy.then(() => {- expect(Object.keys(results), "every probe reported").to.deep.eq(probeIds);- expect(- probeIds- .filter((probeId) => !results[probeId].includes("isolated:"))- .map((probeId) => `${probeId}: ${results[probeId]}`),- "probes that crossed the boundary",- ).to.deep.eq([]);- });- };-- const guardMessage = () =>- cy.contains("blocked host createElement", { timeout: 30000 });-- it("keeps the realms the app creates within the gated realm", () => {- setup();-- runProbes([- "window-frames",- "create-element",- "dom-parser",- "adopt-html-doc-iframe",- "import-html-doc-iframe",- "xml-doc-iframe",- "template-doc-iframe",- "range-fragment-iframe",- "inner-html",- "custom-element",- "window-open",- ]);- });-- // 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("keeps the host window, its storage and a host iframe's realm gated, and marks the SDK's requests 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();-- // `/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.wrap(markedPaths, { timeout: 30000 }).should((paths) => {- expect([...paths], "requests marked as data-app").to.include(- "/api/user/current",- );- });-- // 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- // clone iframe has. Create it in the PARENT (whose createElement the host- // guard never patched) and adopt it into the data-app document, mimicking a- // host-created child frame the guest then reaches for.- H.dataAppIframe(APP_DISPLAY_NAME).then(($body) => {- const doc = $body[0].ownerDocument;- const parentDoc = doc.defaultView!.parent.document;- const iframe = parentDoc.createElement("iframe");- iframe.style.display = "none";- doc.body.appendChild(doc.adoptNode(iframe));-- expect(iframe.contentWindow !== null, "adopted iframe realm").to.equal(- true,- );- });-- runProbes([- "child-frame-grab",- "window-parent",- "window-top",- "frame-element",- "parent-chain",- "window-opener",- "parent-cookie",- "parent-local-storage",- "parent-session-storage",- "parent-indexeddb",- "parent-caches",- ]);- });-- it("gates the APIs that run code, read host data or reach a host realm", () => {- setup();-- runProbes([- "perf-resource-timing",- "function-constructor",- "worker",- "shared-worker",- "service-worker",- "dynamic-import",- "font-face",- "cookie-store",- "endowment-api",- "stack-trace-realm",- ]);- });-- /**- * For the probes whose element is refused during React's own render pass.- *- * The guard throws from `createElement` inside the reconciler, and the app's- * `BoundaryReporter` never catches it: that boundary is declared in the GUEST- * realm while HOST React renders the tree, and React's error-boundary detection- * does not survive the membrane. The throw therefore reaches the host boundary- * and takes the data app down — which is the correct outcome, but it also- * destroys the probe, so there is no `isolation-result` left to read. Assert on- * the guard's own message instead, and open the app again for each probe.- */- it("gates host-React iframes: about:blank, Metabase itself and srcdoc", () => {- createIsolationDataApp();-- ["react-about-blank", "react-src", "react-srcdoc"].forEach((probeId) => {- cy.log(probeId);- H.openDataApp(APP_NAME);-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("isolation-result", { timeout: 30000 }).should(- "have.text",- "pending",- );- });- guardMessage().should("not.exist");-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId(`isolation-${probeId}`).scrollIntoView().click();- });- guardMessage().should("exist");- });- });-- it("gates an allowed_host redirect to the instance", () => {- const instanceUrl = Cypress.config("baseUrl") ?? "";- const cors = {- "Access-Control-Allow-Origin": instanceUrl,- "Access-Control-Allow-Credentials": "true",- };-- // An allowed host that answers the CORS preflight for a credentialed GET,- // then 307-redirects it to the instance origin. The sandbox fetch checks only- // the initial (allowed) URL; it must not follow the redirect across origins.- cy.intercept("OPTIONS", "http://localhost:4444/**", {- statusCode: 204,- headers: {- ...cors,- "Access-Control-Allow-Methods": "GET",- "Access-Control-Allow-Headers": "content-type",- },- });- cy.intercept("GET", "http://localhost:4444/**", (req) => {- req.reply({- statusCode: 307,- headers: { ...cors, Location: `${instanceUrl}/api/session/properties` },- });- }).as("allowedHostRedirect");-- createIsolationDataApp(["http://localhost:4444"]);- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("isolation-result", { timeout: 30000 }).should(- "have.text",- "pending",- );- });-- runProbes(["allowed-host-redirect"]);- cy.wait("@allowedHostRedirect");- });-});diff --git a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts b/e2e/test/scenarios/data-apps/sdk.cy.spec.tsdeleted file mode 100644index 202d67966e3..00000000000--- a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts+++ /dev/null@@ -1,169 +0,0 @@-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- visitDataAppRoute as visitAppRoute,-} from "e2e/support/helpers";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--describe("scenarios > data apps > SDK runtime", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.- H.activateToken("bleeding-edge");- });-- describe("query hooks & question components", () => {- it("surfaces the useMetabaseQuery error state, and re-runs the query when the app calls refetch", () => {- cy.intercept("POST", "/api/dataset").as("datasetQuery");- createKitchenSinkDataApp();-- visitAppRoute("query-states");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("query-error", { timeout: 30000 }).should(- "have.text",- "error",- );-- // The query has to have resolved before refetching means anything.- cy.findByTestId("query-value", { timeout: 30000 })- .invoke("text")- .should("match", /^\d+$/);- });-- // A refetch of a query that already succeeded renders the same value, so the- // request going out again is the only thing that proves refetch did anything.- cy.get("@datasetQuery.all").then((queriesBefore) => {- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("query-refetch").click();- });-- cy.get("@datasetQuery.all").should(- "have.length",- queriesBefore.length + 1,- );- });- });-- it("renders a StaticQuestion from useMetabaseQueryObject", () => {- createKitchenSinkDataApp();-- visitAppRoute("static-question");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- // A rendered value, not just the header: the hook's query object has to- // have actually run.- cy.findAllByTestId("header-cell", { timeout: 30000 }).then(- ($headers) => {- const subtotalIndex = [...$headers].findIndex(- (header) => header.textContent?.trim() === "Subtotal",- );- expect(subtotalIndex, "Subtotal column").to.be.at.least(0);-- // Cells are row-major, so the first row's Subtotal sits at the- // column's own index.- cy.findByTestId("table-body")- .findAllByTestId("cell-data")- .should("have.length.greaterThan", subtotalIndex)- .then(($cells) => {- const subtotal = $cells.eq(subtotalIndex).text();- expect(parseFloat(subtotal.replace(/[^\d.]/g, ""))).to.be.above(- 0,- );- });- },- );- });- });- });-- describe("clipboard (copy)", () => {- it("writes text to the clipboard from a user click", () => {- createKitchenSinkDataApp();-- visitAppRoute("clipboard");-- // Headless Chrome reports the iframe document as unfocused, so the real- // `navigator.clipboard.writeText` rejects ("Document is not focused").- // Stub it: the test still verifies the app reaches the sanctioned `copy`- // (not blocked by the sandbox) with the right text — the OS write itself- // is browser behavior, not ours.- H.dataAppIframe(APP_DISPLAY_NAME).then(($body) => {- const win = $body[0].ownerDocument.defaultView;- if (win) {- const writeText = cy.stub(win.navigator.clipboard, "writeText");- writeText.resolves();- writeText.as("writeText");- }- });-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("clipboard-copy").click();- cy.findByTestId("clipboard-status", { timeout: 30000 }).should(- "have.text",- "copied",- );- });-- cy.get("@writeText").should(- "have.been.calledOnceWith",- "data-app-clipboard-payload",- );- });- });-- describe("error component", () => {- it("shows the default neutral error state for a missing question", () => {- createKitchenSinkDataApp();-- visitAppRoute("missing-question");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByText(/not found/i, { timeout: 30000 }).should("be.visible");- });- });-- it("lets an app override the default with its own errorComponent", () => {- const CUSTOM_APP = "custom-error-component";- const CUSTOM_DISPLAY = "Custom Error App";-- H.createDataApp({ name: CUSTOM_APP, display_name: CUSTOM_DISPLAY }).then(- H.uploadDataAppBundle,- );-- H.openDataApp(CUSTOM_APP);- H.dataAppIframe(CUSTOM_DISPLAY).within(() => {- cy.findByTestId("custom-error-component", { timeout: 30000 })- .should("be.visible")- .and("contain", "Custom app error");- });- });- });-- describe("question downloads", () => {- beforeEach(() => {- cy.deleteDownloadsFolder();- });-- it("downloads a chart question as PNG", () => {- createKitchenSinkDataApp();-- visitAppRoute("download-question");-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- // The chart must render before its toolbar (and the download button) exist.- cy.findByTestId("data-app-download-question", {- timeout: 30000,- }).should("exist");- cy.findByTestId("question-download-widget-button", { timeout: 30000 })- .should("be.visible")- .click();-- cy.findByText(".png").click();- cy.findByTestId("download-results-button").click();- });-- cy.verifyDownload(".png", { contains: true });- });- });-});diff --git a/e2e/test/scenarios/data-apps/sync.cy.spec.ts b/e2e/test/scenarios/data-apps/sync.cy.spec.tsdeleted file mode 100644index 8de82aee11a..00000000000--- a/e2e/test/scenarios/data-apps/sync.cy.spec.ts+++ /dev/null@@ -1,84 +0,0 @@-import type { DataApp } from "metabase-types/api";--const { H } = cy;--/**- * Drives a real remote-sync pull of a repo whose `data_apps/` holds two apps, each a `data_app.yaml` with its bundle- * next to it, and asserts that pulls materialize and remove them.- */-describe("scenarios > data apps > repo sync", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- H.setupGitSync();- });-- it("materializes each app with its bundle, then removes an app whose files are removed from the repo on the next sync", () => {- H.copySyncedCollectionFixture();- H.updateSetting("remote-sync-custom-collections-enabled", true);- H.copySyncedDataAppsFixture();- H.commitToRepo("Add data apps");- H.configureGitAndPullChanges("read-write");-- cy.visit("/data-studio/apps");- H.main().within(() => {- cy.findByRole("row", { name: /Good App/ }).should("be.visible");- cy.findByRole("row", { name: /Second App/ }).should("be.visible");- });-- cy.request("GET", "/api/ee/apps").then(({ body: apps }) => {- expect(apps.map((app: { name: string }) => app.name).sort()).to.deep.eq([- "good",- "second-app",- ]);- });-- cy.request("/api/ee/apps/good/bundle").its("status").should("eq", 200);-- // The good app's collection files were loaded with it: its collection, and- // the saved question in it, addressed by the entity IDs the files carry.- cy.request<DataApp>("/api/ee/apps/good").then(({ body: app }) => {- cy.request("/api/collection/goodAppCollection0000")- .its("body.id")- .should("eq", app.resource_collection_id);- cy.request("/api/card/goodAppOrdersQuestion")- .its("body.collection_id")- .should("eq", app.resource_collection_id);- });-- // An author deletes an app by deleting its directory and its collection's- // files in one commit; the pull deletes the app, and the app deletes its- // collection with what it holds.- cy.task("removeDataAppPaths", {- paths: [- `${H.LOCAL_GIT_PATH}/data_apps/good`,- `${H.LOCAL_GIT_PATH}/collections/data_apps/data_app__good_app.yaml`,- `${H.LOCAL_GIT_PATH}/collections/data_apps/data_app__good_app`,- ],- });- H.commitToRepo("Remove the good app from the repo");- H.configureGitAndPullChanges("read-write");-- cy.request("GET", "/api/ee/apps").then(({ body: apps }) => {- expect(apps.map((app: { name: string }) => app.name)).to.deep.eq([- "second-app",- ]);- });- cy.request({ url: "/api/ee/apps/good", failOnStatusCode: false })- .its("status")- .should("eq", 404);- cy.request({- url: "/api/card/goodAppOrdersQuestion",- failOnStatusCode: false,- })- .its("status")- .should("eq", 404);- cy.request({- url: "/api/collection/goodAppCollection0000",- failOnStatusCode: false,- })- .its("status")- .should("eq", 404);- });-});diff --git a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts b/e2e/test/scenarios/data-apps/user-access.cy.spec.tsdeleted file mode 100644index 8203a63c4e0..00000000000--- a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts+++ /dev/null@@ -1,120 +0,0 @@-const { H } = cy;--const SYNCED_APP_SLUG = "good";-const ALLOWED_HOST = "https://secret-api.data-app.test";--describe("scenarios > data apps > authentication", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- });-- describe("signed-out visitors", () => {- beforeEach(() => {- H.setupGitSync();- H.copySyncedCollectionFixture();- H.updateSetting("remote-sync-custom-collections-enabled", true);- H.copySyncedDataAppsFixture();- cy.task("writeDataAppFiles", {- files: {- [`${H.LOCAL_GIT_PATH}/data_apps/${SYNCED_APP_SLUG}/data_app.yaml`]: [- "version: 1",- "name: Good App",- `slug: ${SYNCED_APP_SLUG}`,- "path: ./index.js",- "collection: goodAppCollection0000",- "allowed_hosts:",- ` - ${ALLOWED_HOST}`,- "entity_id: Ioxf30LzIQCGwbCNtaG62",- "serdes/meta:",- "- model: DataApp",- " id: Ioxf30LzIQCGwbCNtaG62",- ` label: ${SYNCED_APP_SLUG}`,- "",- ].join("\n"),- },- });- H.commitToRepo("Add a data app with an allowed host");- H.configureGitAndPullChanges("read-write");-- cy.request(`/embed/apps/${SYNCED_APP_SLUG}`).then((res) => {- expect(String(res.headers["content-security-policy"])).to.contain(- ALLOWED_HOST,- );- });- cy.request(`/api/ee/apps/${SYNCED_APP_SLUG}/bundle`).then((res) => {- expect(- String(res.headers["x-metabase-data-app-allowed-hosts"]),- ).to.contain(ALLOWED_HOST);- });-- cy.signOut();- });-- it("does not serve the app, its bundle, its metadata or its allowed hosts", () => {- cy.request({- url: `/embed/apps/${SYNCED_APP_SLUG}`,- failOnStatusCode: false,- followRedirect: false,- }).as("iframeDocument");- cy.request({- url: `/apps/${SYNCED_APP_SLUG}`,- failOnStatusCode: false,- followRedirect: false,- }).as("appPage");- cy.request({- url: `/api/ee/apps/${SYNCED_APP_SLUG}/bundle`,- failOnStatusCode: false,- }).as("bundle");- cy.request({- url: `/api/ee/apps/${SYNCED_APP_SLUG}`,- failOnStatusCode: false,- }).as("metadata");-- cy.then(function () {- const iframeDocument: Cypress.Response<unknown> = this.iframeDocument;- const appPage: Cypress.Response<unknown> = this.appPage;- const bundle: Cypress.Response<unknown> = this.bundle;- const metadata: Cypress.Response<unknown> = this.metadata;- const appPageCsp = appPage.headers["content-security-policy"];-- // The SPA shell is still served for the app page; the React app sends- // the visitor to login. Anchor on it so a 404 or an empty response can't- // pass the negative checks.- expect({- iframeDocumentStatus: iframeDocument.status,- iframeDocumentRedirectsToLogin: String(- iframeDocument.headers["location"],- ).includes("/auth/login"),- iframeDocumentCspHasAllowedHost: String(- iframeDocument.headers["content-security-policy"] ?? "",- ).includes(ALLOWED_HOST),- appPageStatus: appPage.status,- appPageIsHtml: String(appPage.headers["content-type"]).includes(- "text/html",- ),- appPageHasCsp: typeof appPageCsp === "string",- appPageCspHasAllowedHost: String(appPageCsp ?? "").includes(- ALLOWED_HOST,- ),- bundleStatus: bundle.status,- bundleHasAllowedHostsHeader:- "x-metabase-data-app-allowed-hosts" in bundle.headers,- metadataStatus: metadata.status,- }).to.deep.equal({- iframeDocumentStatus: 302,- iframeDocumentRedirectsToLogin: true,- iframeDocumentCspHasAllowedHost: false,- appPageStatus: 200,- appPageIsHtml: true,- appPageHasCsp: true,- appPageCspHasAllowedHost: false,- bundleStatus: 401,- bundleHasAllowedHostsHeader: false,- metadataStatus: 401,- });- });- });- });-});diff --git a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts b/e2e/test/scenarios/data-apps/viewing.cy.spec.tsdeleted file mode 100644index b8ea9bb6192..00000000000--- a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts+++ /dev/null@@ -1,170 +0,0 @@-import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";-import {- DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,- DATA_APP_NAME as APP_NAME,- visitDataAppRoute as visitAppRoute,-} from "e2e/support/helpers";-import {- DataPermission,- DataPermissionValue,- type GroupPermissions,-} from "metabase-types/api";--import { createKitchenSinkDataApp } from "./helpers";--const { H } = cy;--const BLOCKED_PERMISSION: GroupPermissions = {- [SAMPLE_DB_ID]: {- [DataPermission.VIEW_DATA]: DataPermissionValue.BLOCKED,- [DataPermission.CREATE_QUERIES]: DataPermissionValue.NO,- },-};--describe("scenarios > data apps > viewing & routing", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.- H.activateToken("bleeding-edge");- });-- describe("viewing permissions", () => {- it("lets a non-admin open a data app by direct URL", () => {- createKitchenSinkDataApp();-- // A normal (non-admin) user has data access, so the app opens and renders- // its data — the admin gate is only on *managing* apps, not viewing them.- cy.signInAsNormalUser();- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- cy.findByTestId("orders-count", { timeout: 30000 })- .invoke("text")- .should("match", /^\d+$/);- });- });-- it("opens the app shell for a user without data access, but shows no data", () => {- cy.updatePermissionsGraph({- [USER_GROUPS.ALL_USERS_GROUP]: BLOCKED_PERMISSION,- [USER_GROUPS.COLLECTION_GROUP]: BLOCKED_PERMISSION,- });-- createKitchenSinkDataApp();-- cy.signIn("nodata");- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- // Group access lets users view the app shell.- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );-- // The user's incomplete data permissions still blocks its query,- // so the orders-count renders "—".- cy.findByTestId("orders-count", { timeout: 30000 }).should(- "have.text",- "—",- );- });- });-- it("shows a not-found state for a disabled or missing app", () => {- // No app with this slug exists, so the metadata endpoint 404s and the host- // renders a not-found state rather than a broken iframe.- H.openDataApp("does-not-exist");- H.main().findByText("Data app not found").should("be.visible");- });- });-- describe("loading state", () => {- it("keeps the loader up until the app's bundle has actually rendered", () => {- createKitchenSinkDataApp();- cy.intercept(- { method: "GET", pathname: `/api/ee/apps/${APP_NAME}/bundle` },- (req) => {- req.on("response", (res) => {- res.setDelay(2000);- });- },- );-- H.openDataApp(APP_NAME);-- cy.findByTestId("data-app-loading").should("be.visible");-- cy.findByTestId("data-app-loading", { timeout: 30000 }).should(- "not.exist",- );- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- });- });- });-- describe("internal routing", () => {- it("starts on a deep-linked sub-route, and mirrors link and imperative route changes into the parent URL", () => {- createKitchenSinkDataApp();-- cy.log("deep-link directly to a sub-route");- visitAppRoute("details");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Order details" }).should(- "be.visible",- );- cy.findByTestId("current-pathname").should("have.text", "/details");- });-- cy.log("navigate with a DataAppLink");- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- // Navigate to a nested page using the exposed `DataAppLink`.- cy.findByRole("link", { name: "Details" }).click();- cy.findByRole("heading", { name: "Order details" }).should(- "be.visible",- );- // The app's own router moved, too — not just the page that rendered.- cy.findByTestId("current-pathname").should("have.text", "/details");- });-- // The iframe's client-side navigation is mirrored to the parent's URL bar- // (via replaceState), so the top-level path reflects the nested route.- cy.location("pathname").should("eq", `/apps/${APP_NAME}/details`);-- cy.log("navigate imperatively via useDataAppLocation().navigate");- H.openDataApp(APP_NAME);- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByRole("heading", { name: "Orders overview" }).should(- "be.visible",- );- cy.findByTestId("navigate-to-details").click();- cy.findByRole("heading", { name: "Order details" }).should(- "be.visible",- );- cy.findByTestId("current-pathname").should("have.text", "/details");- });- cy.location("pathname").should("eq", `/apps/${APP_NAME}/details`);- });- });-- describe("host error / not-ready screens", () => {- it("shows a themed host error screen when the bundle throws while rendering", () => {- createKitchenSinkDataApp();-- visitAppRoute("throw");- // The throw is caught in the iframe and reported to the parent, which- // renders its themed failure screen in the host realm.- H.main()- .findByText(/couldn.t be loaded/i, { timeout: 30000 })- .should("be.visible");- });- });-});diff --git a/e2e/test/scenarios/monitor/ai-auditing/data-apps-analytics.cy.spec.ts b/e2e/test/scenarios/monitor/ai-auditing/data-apps-analytics.cy.spec.tsdeleted file mode 100644index 17447337a73..00000000000--- a/e2e/test/scenarios/monitor/ai-auditing/data-apps-analytics.cy.spec.ts+++ /dev/null@@ -1,194 +0,0 @@-import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import type { PortableTable } from "e2e/support/helpers";-import { createAddTeamAction } from "e2e/test/scenarios/data-apps/helpers";--const { H } = cy;--const DATA_APPS_ANALYTICS_PATH = "/monitor/ai-auditing/data-apps";--const SCOREBOARD_TABLE = "scoreboard_actions";-const ORDERS_TABLE: PortableTable = ["Sample Database", "PUBLIC", "ORDERS"];--const appRoot = (slug: string) =>- `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${slug}`;--/** Reads a saved question when it opens. */-const QUESTION_APP = {- slug: "synced-app",- displayName: "Synced App",- collection: "syncedAppCollection01",- question: "syncedAppOrdersCount1",-};--/** Runs an action on a click. */-const ACTIONS_APP = {- slug: "synced-actions-app",- displayName: "Synced Actions App",- collection: "syncedActionsAppColl1",-};--const ADMIN_NAME = `${USERS.admin.first_name} ${USERS.admin.last_name}`;--function removeTestFiles() {- cy.task("removeDataAppPaths", {- paths: [- `${appRoot(QUESTION_APP.slug)}/collections`,- `${appRoot(ACTIONS_APP.slug)}/collections`,- ],- });-}--function writeQuestionAppResources(root: string) {- return H.writeDataAppResources(root, {- collection: H.dataAppRepresentations.collection(- QUESTION_APP.collection,- `Data App: ${QUESTION_APP.displayName}`,- ),- cards: [- H.dataAppRepresentations.card({- entityId: QUESTION_APP.question,- name: "OrdersCount",- type: "question",- collection: QUESTION_APP.collection,- table: ORDERS_TABLE,- }),- ],- });-}--function publishQuestionApp() {- const root = appRoot(QUESTION_APP.slug);-- writeQuestionAppResources(root);- return H.publishDataApp(root, QUESTION_APP.slug);-}--// A publish makes the repository's collections what the app's root holds, so this root carries the-// question app's collection too; otherwise the pull would remove its saved question.-function publishActionsApp() {- const root = appRoot(ACTIONS_APP.slug);-- H.writeDataAppResources(root, {- collection: H.dataAppRepresentations.collection(- ACTIONS_APP.collection,- `Data App: ${ACTIONS_APP.displayName}`,- ),- });- writeQuestionAppResources(root);-- return H.publishDataApp(root, ACTIONS_APP.slug, {- initializeRepo: false,- }).then((app) =>- createAddTeamAction(app.resource_collection_id).then(() => app),- );-}--// The first query against the audit view can take a while to settle, and the page's other-// queries share `/api/dataset`, so this waits for the table to stop loading rather than on an alias.-function logTable() {- cy.findByTestId("data-app-log-table", { timeout: 20000 }).should(- "have.attr",- "aria-busy",- "false",- );- return cy.findByTestId("data-app-log-table");-}--const logRows = () => logTable().findAllByTestId("data-app-log-row");--function selectFilterOption(label: string, option: string) {- H.main().findByLabelText(label).click();- H.popover().findByRole("option", { name: option }).click();-}--// The log has more columns than the default viewport fits.-describe(- "scenarios > monitor > ai auditing > data app analytics",- { tags: ["@external", "@actions"], viewportWidth: 1600 },- () => {- beforeEach(() => {- H.restore("postgres-writable");- cy.signInAsAdmin();- H.activateToken("bleeding-edge");- H.createLibrary();- H.publishTables({ table_ids: [SAMPLE_DATABASE.ORDERS_ID] });-- H.resetTestTable({ type: "postgres", table: SCOREBOARD_TABLE });- H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: SCOREBOARD_TABLE });- H.setActionsEnabledForDB(WRITABLE_DB_ID);-- removeTestFiles();- });-- after(() => {- removeTestFiles();- });-- it("lists the questions and actions published data apps run, and narrows the log by entity type and app", () => {- cy.log(- "Publish both apps, then upload their bundles, since each pull reloads every app's placeholder bundle",- );- publishQuestionApp().then((questionApp) =>- publishActionsApp().then((actionsApp) => {- H.uploadDataAppBundle(questionApp);- H.uploadDataAppBundle(actionsApp);- }),- );-- cy.log("Read the question in one app");- cy.intercept("POST", "/api/dataset").as("appQuery");- cy.visit(`/apps/${QUESTION_APP.slug}`);- H.dataAppIframe(QUESTION_APP.displayName)- .findByTestId("synced-app-total", { timeout: 30000 })- .should(($total) => {- expect(Number($total.text())).to.be.greaterThan(0);- });- cy.wait("@appQuery");-- cy.log("Run the action in the other");- cy.intercept("POST", "/api/action/*/execute").as("execute");- cy.visit(`/apps/${ACTIONS_APP.slug}`);- H.dataAppIframe(ACTIONS_APP.displayName).within(() => {- cy.findByTestId("action-execute", { timeout: 30000 }).click();- cy.findByTestId("action-output").should("have.text", "executed");- });- cy.wait("@execute");-- cy.visit(DATA_APPS_ANALYTICS_PATH);- cy.findByTestId("monitor-nav")- .findByRole("link", { name: "Data app analytics" })- .should("be.visible");- H.main()- .findByRole("heading", { name: "Data app analytics" })- .should("be.visible");-- cy.log("Both apps' records, by app and user");- logRows()- .should("contain", QUESTION_APP.displayName)- .and("contain", QUESTION_APP.slug)- .and("contain", ACTIONS_APP.displayName)- .and("contain", ACTIONS_APP.slug)- .and("contain", "Question")- .and("contain", "OrdersCount")- .and("contain", ADMIN_NAME);-- cy.log("Only the action runs");- selectFilterOption("Entity type", "Action");- cy.location("search").should("contain", "type=action");- logRows()- .should("contain", ACTIONS_APP.slug)- .and("not.contain", QUESTION_APP.slug)- .and("not.contain", "Question");-- cy.log("Only the question app's records");- selectFilterOption("Entity type", "All entity types");- selectFilterOption("Data app", QUESTION_APP.displayName);- cy.location("search").should("contain", `app=${QUESTION_APP.slug}`);- logRows()- .should("contain", QUESTION_APP.slug)- .and("contain", "Question")- .and("not.contain", ACTIONS_APP.slug);- });- },-);diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex 2f97992f794..9e249569b72 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -1,21 +1,22 @@(ns metabase-enterprise.data-apps.api- "Data-app endpoints, mounted at `/api/ee/apps`: manage data apps and the groups that can read their collections, serve- their bundles, and generate their typed schema."+ "Data-app endpoints, mounted at `/api/ee/apps`: list data apps, enable or disable them, manage the groups that can read+ their collections, serve their bundles, and generate the files of their repository."(:require[clojure.string :as str]+ [clojure.walk :as walk][metabase-enterprise.data-apps.apps :as data-apps.apps][metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.generate.actions :as generate.actions]+ [metabase-enterprise.data-apps.generate.queries :as generate.queries]+ [metabase-enterprise.data-apps.generate.schema :as generate.schema][metabase-enterprise.data-apps.group-access :as data-app.group-access]- [metabase-enterprise.data-apps.models.data-app :as data-app]- [metabase-enterprise.data-apps.typed-schema :as data-apps.typed-schema][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]]- [metabase.data-apps.schema :as data-apps.schema]- [metabase.events.core :as events]- [metabase.remote-sync.core :as remote-sync]+ [metabase.lib.schema.test-spec]+ [metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.malli.schema :as ms])@@ -26,8 +27,8 @@;;; ------------------------------------------------ Constants -------------------------------------------------;; Slug must not collide with the literal `repo-status`/`sandbox-host` sub-routes.-(def ^:private slug-regex #"(?!repo-status$|sandbox-host$)[^/]+")+;; Slug must not collide with the literal `repo-status`/`sandbox-host`/`generate` sub-routes.+(def ^:private slug-regex #"(?!repo-status$|sandbox-host$|generate$)[^/]+")(def ^:private bundle-response-headers;; `no-cache` so the browser may cache but must revalidate via@@ -71,30 +72,9 @@[:created_at :any][:updated_at :any]])-(def ^:private CreateDataAppRequest- [:map {:closed true}- [:name ::data-apps.schema/slug]- [:display_name {:optional true} ::data-apps.schema/display-name]- [:description {:optional true} ::data-apps.schema/description]- [:version {:optional true} ::data-apps.schema/version]- [:bundle_path {:optional true} ::data-apps.schema/bundle-path]- [:allowed_hosts {:optional true} ::data-apps.schema/allowed-hosts]- [:enabled {:optional true} :boolean]])--(def ^:private create-defaults- "What a new app starts with: an empty bundle, and unless its request says otherwise, the bundle path the app- template builds to; it is enabled, like an app an import creates."- {:bundle_path "dist/index.js"- :bundle ""})-(def ^:private UpdateDataAppRequest[:map {:closed true}- [:enabled {:optional true} :boolean]- [:display_name {:optional true} ::data-apps.schema/display-name]- [:description {:optional true} ::data-apps.schema/description]- [:version {:optional true} ::data-apps.schema/version]- [:bundle_path {:optional true} ::data-apps.schema/bundle-path]- [:allowed_hosts {:optional true} ::data-apps.schema/allowed-hosts]])+ [:enabled :boolean]])(def ^:private PublicDataAppResponse[:map {:closed true}@@ -109,6 +89,32 @@[:configured :boolean][:url [:maybe :string]]])+(def ^:private GeneratedFiles+ [:sequential [:map {:closed true}+ [:path ms/NonBlankString]+ [:contents :string]]])++(defn- kebab-case-keys+ "`x` with the keys of every map in it kebab-cased, as the SDK's camelCase keys are in Lib's test query spec."+ [x]+ (walk/postwalk #(cond-> % (map? %) (update-keys (comp keyword u/->kebab-case-en name))) x))++(def ^:private QueryDefinitions+ "The `defineQuery` exports of a data app's `metabase.queries.ts`, by export name: each one's entity ID, and its+ definition as a one-stage test query."+ [:map-of :string [:map {:closed true}+ [:entityId ms/NanoIdString]+ [:query [:and {:decode/api kebab-case-keys} :metabase.lib.schema.test-spec/test-query-spec]]]])++(def ^:private ActionDefinitions+ "The `defineAction` exports of a data app's `metabase.actions.ts`, by export name: implicit actions of `kind` on a+ table."+ [:map-of :string [:map {:closed true}+ [:entityId ms/NanoIdString]+ [:kind [:enum "row/create" "row/update" "row/delete"]]+ [:table [:map {:closed true}+ [:id ms/PositiveInt]]]]])+(def ^:private AddGroupsRequest[:map {:closed true}[:group_ids [:sequential {:min 1 :max 100} ms/PositiveInt]]])@@ -188,90 +194,48 @@(remove #(and (not api/*is-superuser?*) (data-app.config/outdated? %)))(mapv data-app-response)))-(defn- with-bundle- "The DataApp `changes` with their `bundle` text as the bytes the app is served."- [changes]- (cond-> changes- (contains? changes :bundle) (update :bundle data-app/file->bundle)))--(defn- write-check-data-app- "The DataApp named `slug` without its bundle, checked for existence and write permissions."- [slug]- (api/write-check (api/check-404 (data-apps.db/data-app-by-slug slug))))--(defn- check-editable!- "Throws a 403 when `app` is read-only under remote sync."- [app]- (api/check-403 (remote-sync/model-editable? :model/DataApp app)))--(api.macros/defendpoint :post "/" :- DataAppResponse- "Create a data app with its resource collection and an empty bundle. It is enabled unless the request says- otherwise."- [_route-params- _query-params- body :- CreateDataAppRequest]- (api/create-check :model/DataApp body)- (check-editable! body)- (let [row (merge create-defaults {:display_name (:name body)} body)- app (data-apps.db/data-app (data-apps.apps/create-app! (with-bundle row)))]- (events/publish-event! :event/data-app-create {:object app :user-id api/*current-user-id*})- (data-app-response app)))--(defn- update-app!- "Apply `changes` to the data app named `slug` and return the updated app."- [slug changes]- (let [app (write-check-data-app slug)- synced-changes (dissoc changes :enabled)]- (when (seq synced-changes)- (check-editable! app))- (when (seq changes)- (data-apps.db/update-data-app! (:id app) (with-bundle changes)))- (let [app (data-apps.db/data-app (:id app))]- (when (seq synced-changes)- (events/publish-event! :event/data-app-update {:object app :user-id api/*current-user-id*}))- (data-app-response app))))-;; NOTE on the `slug-regex` constraint: the default path-param matcher allows slashes inside a segment, so `/:slug`-;; would otherwise swallow `/x/bundle`. The regex also excludes the literal `repo-status` and `sandbox-host` routes.+;; would otherwise swallow `/x/bundle`. The regex also excludes the literal `repo-status`, `sandbox-host` and+;; `generate` routes.(api.macros/defendpoint :put ["/:slug" :slug slug-regex] :- DataAppResponse- "Update a data app's manifest fields, or enable or disable it. A disabled app is served to superusers only."+ "Enable or disable a data app. A disabled app is served to superusers only. Superusers only; anything else about an+ app changes only through a repository import."[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]_query-params- changes :- UpdateDataAppRequest]- (update-app! slug changes))+ {:keys [enabled]} :- UpdateDataAppRequest]+ (api/check-superuser)+ (let [app (api/check-404 (data-apps.db/data-app-by-slug slug))]+ (data-apps.db/update-data-app! (:id app) {:enabled enabled})+ (data-app-response (data-apps.db/data-app (:id app)))))-(api.macros/defendpoint :put ["/:slug/bundle" :slug slug-regex] :- DataAppResponse- "Replace a data app's bundle."- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]- _query-params- {:keys [bundle]} :- [:map {:closed true} [:bundle ::data-apps.schema/bundle-text]]]- (update-app! slug {:bundle bundle}))+(api.macros/defendpoint :get "/generate/schema" :- GeneratedFiles+ "The `src/metabase.schema.ts` file of a data app: the Library's published tables, with their fields, segments and+ measures, and its metrics. Superusers only."+ []+ (api/check-superuser)+ (generate.schema/generate))-(api.macros/defendpoint :delete ["/:slug" :slug slug-regex] :- :nil- "Delete a data app, its bundle, and its collection with the grants on it."- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]- (let [app (write-check-data-app slug)]- (check-editable! app)- (data-apps.db/delete-data-app! (:id app))- (events/publish-event! :event/data-app-delete {:object app :user-id api/*current-user-id*}))- ;; a `nil` body is rendered as a 204; matches the `:- :nil` response schema- ;; above (returning `generic-204-no-content` would fail that validation).- nil)--(def ^:private typescript-response-headers- {"Content-Type" "text/typescript; charset=utf-8"- "X-Content-Type-Options" "nosniff"- "Cross-Origin-Resource-Policy" "same-origin"- "Referrer-Policy" "no-referrer"- "Cache-Control" "no-store"})+(api.macros/defendpoint :post "/generate/queries" :- GeneratedFiles+ "The YAML files of the questions a data app defines, one per `defineQuery` export in `queries`, in its collection with+ the entity ID `collection`. Nothing is saved. Superusers only."+ [_route-params+ _query-params+ {:keys [collection queries]} :- [:map {:closed true}+ [:collection ms/NanoIdString]+ [:queries QueryDefinitions]]]+ (api/check-superuser)+ (generate.queries/generate collection queries))-(api.macros/defendpoint :get ["/:slug/typed-schema" :slug slug-regex] :- :any- "Return the TypeScript module of the data app's queries and actions: a `defineQuery` call for each question and metric- and a `defineAction` call for each action in the app's collection, addressed by entity ID. Superusers only."- [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]- {:status 200- :headers typescript-response-headers- :body (data-apps.typed-schema/generate (write-check-data-app slug))})+(api.macros/defendpoint :post "/generate/actions" :- GeneratedFiles+ "The YAML files of the implicit actions a data app defines, one per `defineAction` export in `actions`, in its+ collection with the entity ID `collection`. Nothing is saved. Superusers only."+ [_route-params+ _query-params+ {:keys [collection actions]} :- [:map {:closed true}+ [:collection ms/NanoIdString]+ [:actions ActionDefinitions]]]+ (api/check-superuser)+ (generate.actions/generate collection actions))(def ^:private GroupPermissionWarning[:mapdiff --git a/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj b/enterprise/backend/src/metabase_enterprise/data_apps/apps.cljindex 59e8851dc91..394b53de742 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/apps.clj@@ -1,13 +1,8 @@(ns metabase-enterprise.data-apps.apps- "Creating data apps, and the connected repository's URL."+ "The connected repository's URL."(:require[clojure.string :as str]- [metabase-enterprise.data-apps.db :as data-apps.db]- [metabase.api.common :as api]- [metabase.collections.core :as collections]- [metabase.settings.core :as setting]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2]))+ [metabase.settings.core :as setting]))(set! *warn-on-reflection* true)@@ -20,19 +15,3 @@(let [url (try (setting/get :remote-sync-url) (catch Throwable _ nil))](when-not (str/blank? url)url)))--(defn collection-name- "The name of the resource collection the API creates for the data app with `slug`."- [slug]- (format "Data App: %s" slug))--(defn create-app!- "Create the data app `row` with a new root collection of the `data-apps` namespace as its resource collection, and- return the app's ID; throws a 409 when a data app already has the slug."- [{slug :name :as row}]- (t2/with-transaction [_conn]- (api/check (not (data-apps.db/data-app-exists? slug))- [409 (tru "A data app with this slug already exists.")])- (let [collection (collections/create-collection! {:name (collection-name slug)- :namespace (name collections/data-apps-ns)})]- (data-apps.db/insert-data-app-returning-pk! (assoc row :resource_collection_id (:id collection))))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/checks.clj b/enterprise/backend/src/metabase_enterprise/data_apps/checks.cljindex 417adbb36f7..adc16acd850 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/checks.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/checks.clj@@ -1,7 +1,7 @@(ns metabase-enterprise.data-apps.checks- "The checks that hold a data app's ad-hoc queries and card runs to its own cards and the Library, and its action runs- to the actions in its collection: no native or internal queries, cards from the app's collection, tables published to- the Library, Library metrics, segments and measures of published tables, and actions from the app's collection."+ "The checks that hold a data app's requests to the Library and its own collection. A dev preview, which has no app on+ the instance, reads the Library alone and runs ad-hoc implicit actions; an app may also use the cards and run the+ actions in its collection."(:require[clojure.set :as set][clojure.string :as str]@@ -14,12 +14,8 @@[metabase.lib-be.schema :as lib-be.schema][metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id]- [metabase.lib.schema.parameter :as lib.schema.parameter]- [metabase.parameters.params :as params]- [metabase.parameters.schema :as parameters.schema][metabase.premium-features.core :refer [defenterprise defenterprise-schema]]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [tru]]))(set! *warn-on-reflection* true)@@ -29,12 +25,26 @@(ex-info message {:status-code 400}))(defenterprise request-data-app- "The data app whose slug a data-app `request` names by [[data-apps/data-app-slug]], read-checked, so a missing app is- a 404 and an unreadable one a 403; nil for a request that is not a data app's."+ "What a data-app `request` is checked as: the app its slug names by [[data-apps/data-app-slug]], read-checked, so a+ missing app is a 404 and an unreadable one a 403, or, for a dev preview's request, a preview of the app its slug+ names, whether the app exists or not; nil for a request that is not a data app's.":feature :data-apps[request](when (data-apps/data-app-request? request)- (api/read-check (some-> (data-apps/data-app-slug request) data-apps.db/data-app-by-slug))))+ (let [slug (data-apps/data-app-slug request)]+ (if (data-apps/data-app-dev-request? request)+ {:slug (api/check-404 slug)}+ (api/read-check (some-> slug data-apps.db/data-app-by-slug))))))++(defn- app-collection-id+ "The ID of the collection of the app `data-app`, or nil for a dev preview or an app without one."+ [data-app]+ (:resource_collection_id data-app))++(defn- preview?+ "Whether `data-app` is a dev preview, which has no ID."+ [data-app]+ (not (contains? data-app :id)))(defn- format-ids"`ids` in order, for an error message."@@ -44,30 +54,38 @@(defn- in-app-collection?"Whether `entity` is in `data-app`'s collection."[data-app entity]- (let [collection-id (:resource_collection_id data-app)]+ (let [collection-id (app-collection-id data-app)](and (some? collection-id) (= collection-id (:collection_id entity)))))-(defenterprise-schema check-query :- :nil- "Throws a 400 unless `query`, as the `/api/dataset` endpoints normalize it, is neither internal nor native and uses only- cards in `data-app`'s collection, tables published to the Library (joins included), Library metrics, and segments and- measures of published tables."+(defenterprise-schema check-adhoc-query :- :nil+ "Throws a 400 unless `query`, as the `/api/dataset` endpoints normalize it, is an MBQL query without explicit joins or+ custom columns that reads only tables published to the Library, through foreign keys too, Library metrics, and+ segments and measures of published tables; an app's query may also build on the cards in its collection.":feature :data-apps- [data-app :- ::data-apps.schema/data-app+ [data-app :- ::data-apps.schema/data-app-infoquery :- ::lib-be.schema/maybe-legacy-or-internal-query](when (= :internal (keyword (:type query)))(throw (data-app-error (tru "A data app cannot run internal queries."))))+ (when (lib/any-native-stage? query)+ (throw (data-app-error (tru "A data app cannot run native queries."))))+ (when (some #(seq (lib/joins query %)) (range (lib/stage-count query)))+ (throw (data-app-error (tru "A data app cannot run queries that join tables explicitly."))))+ (when (some #(seq (lib/expressions query %)) (range (lib/stage-count query)))+ (throw (data-app-error (tru "A data app cannot run queries with custom columns."))))(let [metric-ids (lib/all-metric-ids query)card-ids (set/difference (set (lib/all-source-card-ids query)) metric-ids)]- (when (lib/any-native-stage? query)- (throw (data-app-error (tru "A data app cannot run native queries."))))- (when-let [external (some->> (not-empty card-ids)- (data-apps.db/external-card-ids (:resource_collection_id data-app))- not-empty)]- (throw (data-app-error (tru "A data app can use only the cards in its own collection, not the cards {0}."- (format-ids external)))))+ (when (seq card-ids)+ (when (preview? data-app)+ (throw (data-app-error (tru "A data app''s dev preview cannot build on cards, not the cards {0}." (format-ids card-ids)))))+ (when-let [external (not-empty (data-apps.db/external-card-ids (app-collection-id data-app) card-ids))]+ (throw (data-app-error (tru "A data app can use only the cards in its own collection, not the cards {0}."+ (format-ids external))))))(when-let [external (some-> metric-ids data-apps.db/external-metric-ids not-empty)](throw (data-app-error (tru "A data app can use only metrics from the Library, not the metrics {0}." (format-ids external)))))- (when-let [external (some-> (lib/all-source-table-ids query) data-apps.db/external-table-ids not-empty)]+ (when-let [external (some-> (not-empty (set/union (set (lib/all-source-table-ids query))+ (set (lib/all-implicitly-joined-table-ids query))))+ data-apps.db/external-table-ids+ not-empty)](throw (data-app-error (tru "A data app can read only tables published to the Library, not the tables {0}."(format-ids external)))))(when-let [external (some-> (lib/all-segment-ids query) data-apps.db/external-segment-ids not-empty)]@@ -78,34 +96,20 @@(format-ids external))))))nil)-(defn- in-library?- "Whether `entity` is in the Library or one of its collections."- [entity]- (contains? collections/library-collection-types (-> entity (t2/hydrate :collection) :collection :type)))--(defn- read-checked-app-card- "The card with `card-id`, after a read check; throws a 400 unless it is in `data-app`'s collection or in the Library."- [data-app card-id]- (let [card (api/read-check :model/Card card-id)]- (when-not (or (in-app-collection? data-app card) (in-library? card))- (throw (data-app-error (tru "A data app can use only the cards in its own collection and in the Library, not the card {0}."- (str card-id)))))- card))--(defn- check-values-source-card- "Throws a 400 unless the card with `card-id` is one `data-app` may use and not a dashboard question, after a read- check of the card."- [data-app card-id]- (when (:dashboard_id (read-checked-app-card data-app card-id))- (throw (data-app-error (tru "A data app cannot take parameter values from the dashboard question {0}." (str card-id))))))-(defenterprise-schema check-card :- :nil- "Throws a 400 unless the card with `card-id` is in `data-app`'s collection or in the Library, after a read check of- the card."+ "Throws a 400 unless the card with `card-id` is a Library metric, or `data-app` is an app and the card is in its+ collection, after a read check of the card; a dev preview uses no saved card but Library metrics.":feature :data-apps- [data-app :- ::data-apps.schema/data-app+ [data-app :- ::data-apps.schema/data-app-infocard-id :- ::lib.schema.id/card]- (read-checked-app-card data-app card-id)+ (let [card (api/read-check :model/Card card-id)]+ (when (seq (data-apps.db/external-metric-ids #{card-id}))+ (when (preview? data-app)+ (throw (data-app-error (tru "A data app''s dev preview cannot use saved cards but Library metrics, not the card {0}."+ (str card-id)))))+ (when-not (in-app-collection? data-app card)+ (throw (data-app-error (tru "A data app can use only the cards in its own collection and Library metrics, not the card {0}."+ (str card-id)))))))nil)(defn- published-table?@@ -121,57 +125,47 @@(throw (data-app-error (tru "A data app can read only fields of tables published to the Library, not the field {0}."(str field-id))))))-(defenterprise-schema check-card-parameter :- :nil- "Throws a 400 unless the card with `card-id` is in `data-app`'s collection or the Library and its parameter- `param-key` takes its values from a static list, such a card other than a dashboard question, or a field of a table- published to the Library, after read checks of each."- :feature :data-apps- [data-app :- ::data-apps.schema/data-app- card-id :- ::lib.schema.id/card- param-key :- ::lib.schema.parameter/id]- (let [card (read-checked-app-card data-app card-id)- parameter (some #(when (= param-key (:id %)) %) (:parameters card))]- (case (some-> (:values_source_type parameter) keyword)- :static-list nil- :card (some->> (get-in parameter [:values_source_config :card_id]) (check-values-source-card data-app))- (some-> (params/param-target->field-id (:target parameter) card) check-published-field)))- nil)--(defenterprise-schema check-parameter :- :nil- "Throws a 400 unless the ad-hoc `parameter` takes its values from a static list, a card `data-app` may use other than- a dashboard question, or the fields with `field-ids`, each of a table published to the Library, after read checks- of each."- :feature :data-apps- [data-app :- ::data-apps.schema/data-app- parameter :- ::parameters.schema/parameter- field-ids :- [:maybe [:sequential ::lib.schema.id/field]]]- (case (some-> (:values_source_type parameter) keyword)- :static-list nil- :card (some->> (get-in parameter [:values_source_config :card_id]) (check-values-source-card data-app))- (run! check-published-field field-ids))- nil)-(defenterprise-schema check-action :- :nil- "Throws a 400 unless the action with `action-id` is in `data-app`'s collection, after a read check of the action."+ "Throws a 400 unless `data-app` is an app and the action with `action-id` is in its collection, after a read check of+ the action; a dev preview runs ad-hoc actions alone.":feature :data-apps- [data-app :- ::data-apps.schema/data-app+ [data-app :- ::data-apps.schema/data-app-infoaction-id :- ::lib.schema.id/action]+ (when (preview? data-app)+ (throw (data-app-error (tru "A data app''s dev preview can run only ad-hoc actions, not the action {0}." (str action-id)))))(when-not (in-app-collection? data-app (api/read-check :model/Action action-id))(throw (data-app-error (tru "A data app can run only the actions in its own collection, not the action {0}."(str action-id)))))nil)+(defenterprise-schema check-adhoc-action :- :nil+ "Throws a 400 unless `data-app` is a dev preview and the ad-hoc `action` is an implicit action of no model on a table+ published to the Library, after a read check of the table."+ :feature :data-apps+ [data-app :- ::data-apps.schema/data-app-info+ action :- ::actions.schema/action.adhoc]+ (when-not (preview? data-app)+ (throw (data-app-error (tru "A data app can run only the actions in its own collection, not ad-hoc ones."))))+ (let [table-id (:table_id action)]+ (when-not (and (= :implicit (keyword (:type action))) (nil? (:model_id action)) table-id)+ (throw (data-app-error (tru "A data app''s dev preview can run only implicit actions on a table."))))+ (api/read-check :model/Table table-id)+ (when-not (published-table? table-id)+ (throw (data-app-error (tru "A data app can write only to tables published to the Library, not the table {0}."+ (str table-id))))))+ nil)+(defenterprise-schema data-app-actions :- [:sequential ::actions.schema/action]"The `actions` in `data-app`'s collection.":feature :data-apps- [data-app :- ::data-apps.schema/data-app+ [data-app :- ::data-apps.schema/data-app-infoactions :- [:sequential ::actions.schema/action]](filterv (partial in-app-collection? data-app) actions))(defenterprise-schema check-table :- :nil"Throws a 400 unless the table with `table-id` is published to the Library, after a read check of the table.":feature :data-apps- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-infotable-id :- ::lib.schema.id/table](api/read-check :model/Table table-id)(when-not (published-table? table-id)@@ -182,7 +176,7 @@"Throws a 400 unless the field with `field-id` belongs to a table published to the Library, after a read check ofthe field.":feature :data-apps- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-infofield-id :- ::lib.schema.id/field](check-published-field field-id)nil)@@ -191,7 +185,7 @@"Throws a 400 unless the database with `database-id` has a table published to the Library, after a read check of thedatabase.":feature :data-apps- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-infodatabase-id :- ::lib.schema.id/database](api/read-check :model/Database database-id)(when-not (some #(= database-id (:db_id %)) (data-apps.db/published-tables))@@ -206,7 +200,7 @@(defenterprise-schema check-user-key-value :- :nil"Throws a 400 unless the user key-value `k` in `nmspace` is one the SDK uses inside a data app.":feature :data-apps- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-infonmspace :- :stringk :- :string](when-not (contains? sdk-user-key-values [nmspace k])@@ -217,26 +211,16 @@(defenterprise-schema data-app-collection-types :- [:maybe [:set :string]]"The types of the Library and of its collections, which their subcollections inherit.":feature :data-apps- [_data-app :- ::data-apps.schema/data-app]+ [_data-app :- ::data-apps.schema/data-app-info]collections/library-collection-types)(defenterprise-schema check-collection :- :nil"Throws a 400 unless the collection with `collection-id` is of a type in [[data-app-collection-types]], after a readcheck of the collection.":feature :data-apps- [data-app :- ::data-apps.schema/data-app+ [data-app :- ::data-apps.schema/data-app-infocollection-id :- ::lib.schema.id/collection](when-not (contains? (data-app-collection-types data-app) (:type (api/read-check :model/Collection collection-id)))(throw (data-app-error (tru "A data app can see only the Library and its collections, not the collection {0}."(str collection-id)))))nil)--(defenterprise-schema check-dashboard :- :nil- "Throws a 400 unless the dashboard with `dashboard-id` is in the Library, after a read check of the dashboard."- :feature :data-apps- [_data-app :- ::data-apps.schema/data-app- dashboard-id :- ::lib.schema.id/dashboard]- (when-not (in-library? (api/read-check :model/Dashboard dashboard-id))- (throw (data-app-error (tru "A data app can use only the dashboards in the Library, not the dashboard {0}."- (str dashboard-id)))))- nil)diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.cljindex 4a66546d67d..c985b32bf0a 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj@@ -6,6 +6,7 @@[metabase.collections.models.collection :as collection][metabase.data-apps.schema :as data-apps.schema][metabase.lib.schema.id :as lib.schema.id]+ [metabase.queries.core :as queries][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][metabase.warehouse-schema-overlay.core :as warehouse-schema-overlay]@@ -66,10 +67,16 @@[collection-id :- pos-int?](t2/exists? :model/Collection :id collection-id :namespace "data-apps"))-(mu/defn insert-data-app-returning-pk! :- ms/PositiveInt- "Insert the DataApp `row`, returning its ID."- [row :- ::data-apps.schema/data-app.update]- (t2/insert-returning-pk! :model/DataApp row))+(mu/defn resource-collection-name :- :string+ "The name of the resource collection of the data app named `slug`."+ [slug :- :string]+ (format "Data App: %s" slug))++(mu/defn insert-resource-collection! :- ms/PositiveInt+ "Insert the resource collection of the data app named `slug`, a top-level collection of data apps, returning its ID."+ [slug :- :string]+ (t2/insert-returning-pk! :model/Collection {:name (resource-collection-name slug)+ :namespace "data-apps"}))(mu/defn update-data-app!"Apply `changes` to the DataApp with `data-app-id`."@@ -77,11 +84,6 @@changes :- ::data-apps.schema/data-app.update](t2/update! :model/DataApp :id data-app-id changes))-(mu/defn delete-data-app!- "Delete the DataApp with `data-app-id`."- [data-app-id :- ms/PositiveInt]- (t2/delete! :model/DataApp :id data-app-id))-(defn resource-collection-ids"The IDs of the resource collections owned by data apps."[]@@ -157,6 +159,11 @@:order-by [[:name :asc] [:id :asc]]})[]))+(mu/defn table+ "The Table with `table-id`, or nil."+ [table-id :- ::lib.schema.id/table]+ (t2/select-one :model/Table {:from [(warehouse-schema-overlay/table-query)] :where [:= :id table-id]}))+(mu/defn resource-cards"The unarchived Cards in the collection with `collection-id`, in name then id order."[collection-id :- ::lib.schema.id/collection]@@ -214,3 +221,74 @@{:join [(warehouse-schema-overlay/table-query {:alias :table})[:= :table.id :measure.table_id]]:where [:and [:in :measure.id measure-ids] [:= :table.is_published true]]})))++(defn destination-database-ids+ "The IDs among `database-ids` of the databases that are routing destinations."+ [database-ids]+ (if (seq database-ids)+ (t2/select-fn-set :id :model/Database :id [:in database-ids] :router_database_id [:not= nil])+ #{}))++(mu/defn metric-cards-in-collections+ "The non-archived metric Cards in `collection-ids`, in name then id order."+ [collection-ids :- [:set ::lib.schema.id/collection]]+ (if (seq collection-ids)+ (t2/select :model/Card {:where [:and+ [:= :type "metric"]+ [:= :archived false]+ [:in :collection_id collection-ids]]+ :order-by [[:name :asc] [:id :asc]]})+ []))++(mu/defn field-ids-and-table-ids+ "The id and Table id of the Fields with `field-ids`."+ [field-ids :- [:set ::lib.schema.id/field]]+ (t2/select [:model/Field :id :table_id] :id [:in field-ids] {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]}))++(mu/defn card-dimensions+ "The query-relevant columns (`:dimensions` and `:dimension_mappings` among them) of the Card with `card-id`,+ or nil."+ [card-id :- ::lib.schema.id/card]+ (queries/card-query-info card-id))++(mu/defn table-names+ "The id, database id, name, and display name of the Tables with `table-ids`."+ [table-ids :- [:sequential ::lib.schema.id/table]]+ (t2/select [:model/Table :id :db_id :name :display_name] :id [:in table-ids] {:from [(warehouse-schema-overlay/table-query)]}))++(mu/defn field-table-id+ "The Table id of the Field with `field-id`, or nil."+ [field-id :- ::lib.schema.id/field]+ (t2/select-one-fn :table_id :model/Field :id field-id {:from [(warehouse-schema-overlay/field-query {:user-settings? false})]}))++(mu/defn published-tables-in-collections+ "The active, published Tables in `collection-ids`, in name then id order."+ [collection-ids :- [:set ::lib.schema.id/collection]]+ (if (seq collection-ids)+ (t2/select :model/Table+ {:from [(warehouse-schema-overlay/table-query)]+ :where [:and+ [:= :active true]+ [:= :is_published true]+ [:in :collection_id collection-ids]]+ :order-by [[:name :asc] [:id :asc]]})+ []))++(mu/defn measure-definition+ "The definition of the Measure with `measure-id`, or nil."+ [measure-id :- ::lib.schema.id/measure]+ (t2/select-one-fn :definition :model/Measure :id measure-id))++(mu/defn measure-definitions+ "The id and definition of the Measures with `measure-ids`."+ [measure-ids :- [:sequential ::lib.schema.id/measure]]+ (t2/select [:model/Measure :id :definition] :id [:in measure-ids]))++(mu/defn unarchived-collections+ "The unarchived Collections among `collection-ids`, with their Library types."+ [collection-ids :- [:set ::lib.schema.id/collection]]+ (if (seq collection-ids)+ (t2/select [:model/Collection :id :type]+ :id [:in collection-ids]+ :archived false)+ []))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/actions.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/actions.cljnew file mode 100644index 00000000000..5f79b5e3438--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/actions.clj@@ -0,0 +1,35 @@+(ns metabase-enterprise.data-apps.generate.actions+ "The YAML files of the implicit actions a data app defines with `defineAction` in its `metabase.actions.ts`, each+ named after its export."+ (:require+ [metabase-enterprise.data-apps.generate.util :as generate.util]+ [metabase-enterprise.serialization.core :as serialization]+ [metabase.api.common :as api]+ [metabase.models.serialization :as serdes]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(defn- action+ "The implicit action named `action-name` with entity ID `entity-id` in the collection with `collection-entity-id`,+ doing `kind` on the table with `table-id`, as an export extracts it."+ [action-name entity-id collection-entity-id kind table-id]+ {:serdes/meta [{:model "Action" :id entity-id :label (serialization/slugify-name action-name)}]+ :entity_id entity-id+ :name action-name+ :type "implicit"+ :collection_id collection-entity-id+ :creator_id (serdes/*export-user* api/*current-user-id*)+ :implicit [{:kind kind :table_id (serdes/*export-table-fk* table-id)}]+ :parameters []+ :parameter_mappings []+ :query []+ :visualization_settings {}})++(defn generate+ "The files of the implicit actions in `definitions`, a map of export name to `{:entityId .. :kind .. :table {:id ..}}`,+ in the data app's collection with entity ID `collection-entity-id`, each at its path in the collection's directory."+ [collection-entity-id definitions]+ (vec (for [[export-name {:keys [entityId kind] {table-id :id} :table}] definitions+ :let [export-name (u/qualified-name export-name)]]+ (generate.util/resource-file export-name (action export-name entityId collection-entity-id kind table-id)))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/queries.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/queries.cljnew file mode 100644index 00000000000..f9559ee8af2--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/queries.clj@@ -0,0 +1,47 @@+(ns metabase-enterprise.data-apps.generate.queries+ "The YAML files of the questions a data app defines with `defineQuery` in its `metabase.queries.ts`, each named after+ its export, built as the dev preview runs it."+ (:require+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.generate.util :as generate.util]+ [metabase.api.common :as api]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.models.serialization :as serdes]+ [metabase.queries.core :as queries]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(defn- build-query+ "The query Lib builds from the query definition `query`."+ [query]+ (let [table-id (get-in query [:stages 0 :source :id])+ mp (lib-be/application-database-metadata-provider (:db_id (api/check-404 (data-apps.db/table table-id))))]+ (lib/test-query mp query)))++(defn- card+ "The question named `card-name` with entity ID `entity-id` in the collection with `collection-entity-id`, holding the+ query `query` builds, as an export extracts it."+ [card-name entity-id collection-entity-id query]+ (let [query (build-query query)]+ (-> (serdes/extract-one "Card" {} {:entity_id entity-id+ :name card-name+ :card_schema queries/current-card-schema-version+ :type :question+ :display :table+ :creator_id api/*current-user-id*+ :database_id (:database query)+ :dataset_query (lib/prepare-for-serialization query)+ :visualization_settings {}+ :parameters []+ :parameter_mappings []})+ (assoc :collection_id collection-entity-id))))++(defn generate+ "The files of the questions in `definitions`, a map of export name to `{:entityId .. :query ..}`, in the data app's+ collection with entity ID `collection-entity-id`, each at its path in the collection's directory."+ [collection-entity-id definitions]+ (vec (for [[export-name {:keys [entityId query]}] definitions+ :let [export-name (u/qualified-name export-name)]]+ (generate.util/resource-file export-name (card export-name entityId collection-entity-id query)))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema.cljnew file mode 100644index 00000000000..ea02199b949--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema.clj@@ -0,0 +1,67 @@+(ns metabase-enterprise.data-apps.generate.schema+ "The `src/metabase.schema.ts` file of a data app: the TypeScript module describing the Library's published tables,+ with their fields, segments and measures, and its metrics, for the `Lib.createTestQuery` DSL; each entry's+ `/* metadata: {...} */` block carries context for humans and agents.++ (-> (fetch-items) create-schema render-typescript)++ [[fetch-items]] is the only impure stage, and reads through+ [[metabase-enterprise.data-apps.generate.schema.source/SchemaSource]]. Which keys render as runtime data vs metadata+ is policy in `metabase-enterprise.data-apps.generate.schema.render`; TypeScript syntax lives only in the+ `metabase-enterprise.data-apps.generate.schema.javascript` printer. The table and metric details lookups read-check+ the current user, so callers outside a request must bind a current-user context first."+ (:require+ [clojure.set :as set]+ [metabase-enterprise.data-apps.generate.schema.common :as schemas.common]+ [metabase-enterprise.data-apps.generate.schema.javascript :as schemas.javascript]+ [metabase-enterprise.data-apps.generate.schema.render :as schemas.render]+ [metabase-enterprise.data-apps.generate.schema.source :as schemas.source]+ [metabase.system.core :as system])+ (:import+ (java.time Instant)))++(set! *warn-on-reflection* true)++(def Items+ "Fetched schema entities, ready for pure assembly by [[create-schema]]."+ [:map {:closed true}+ [:tables [:sequential :map]]+ [:metrics [:sequential :map]]])++(defn fetch-items+ "Fetches Library metrics, and published tables and the tables metrics are backed by."+ ([]+ (fetch-items schemas.source/app-db-source))+ ([source]+ (let [{:keys [data-collection-ids metric-collection-ids]} (schemas.source/library-scope source)+ metrics (schemas.source/metrics source metric-collection-ids)+ table-ids (set/union (into #{} (map :id) (schemas.source/library-tables source data-collection-ids))+ (into #{} (mapcat :mappedTableIds) metrics))]+ {:tables (vec (schemas.source/tables source table-ids))+ :metrics (vec metrics)})))++(defn create-schema+ "Assembles fetched [[Items]] into the schema value; `info` optionally pins `:generated-at` and `:instance-url`,+ which default to the current time and the configured site URL."+ ([items]+ (create-schema items nil))+ ([{:keys [tables metrics]} {:keys [generated-at instance-url]}]+ (array-map+ :schemaVersion 3+ :generatedAt (str (or generated-at (Instant/now)))+ :metabase {:instanceUrl (or instance-url (system/site-url))}+ :tables (schemas.common/keyed-map tables)+ :metrics (schemas.common/keyed-map metrics))))++(defn render-typescript+ "Renders a schema value as an ES module of `as const` TypeScript constants."+ [schema]+ (-> schema+ schemas.render/schema->ast+ schemas.javascript/render-js))++(defn generate+ "The `src/metabase.schema.ts` file of a data app, at its path in the app's directory."+ []+ [{:path "src/metabase.schema.ts"+ :contents (-> (fetch-items) create-schema render-typescript)}])diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/common.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/common.cljnew file mode 100644index 00000000000..ee4ad275f7e--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/common.clj@@ -0,0 +1,159 @@+(ns metabase-enterprise.data-apps.generate.schema.common+ "Shared helpers for generating a data app's schema."+ (:require+ [clojure.string :as str]+ [medley.core :as m]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase.audit-app.core :as audit]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.metabot.core :as metabot]+ [metabase.premium-features.core :as premium-features]+ [metabase.types.core]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(comment metabase.types.core/keep-me)++;; Action parameters in generated schemas use these primitive types.+(def ^:private primitive-type->js-type+ {:number "number"+ :boolean "boolean"+ :string "string"+ :date "Date"+ :datetime "Date"+ :time "Date"})++(defn- type-keyword+ [schema-type]+ (cond+ (keyword? schema-type) schema-type+ (string? schema-type) (let [schema-type (str/replace schema-type #"^:" "")]+ (if (str/includes? schema-type "/")+ (keyword schema-type)+ (keyword "type" schema-type)))))++;; Result columns and fields use Metabase base/effective types. For example,+;; `:type/Integer` maps to "number", and `:type/UUID` maps to "string".+(defn- schema-type->js-type+ [schema-type]+ (let [schema-type (type-keyword schema-type)]+ (cond+ (nil? schema-type) "unknown"+ (isa? schema-type :type/Boolean) "boolean"+ (isa? schema-type :type/Number) "number"+ (isa? schema-type :type/Temporal) "Date"+ (isa? schema-type :type/Text) "string"+ (isa? schema-type :type/TextLike) "string"+ :else "unknown")))++(defn- js-type+ [{:keys [type base_type effective_type] :as _column}]+ (or (get primitive-type->js-type type)+ (schema-type->js-type (or effective_type base_type))))++(defn column-schema+ "Returns the schema representation for a result column or field-like map."+ [{:keys [name display_name base_type effective_type semantic_type description unit] :as column}]+ (let [effective-type (or effective_type base_type)]+ (m/assoc-some+ {:type "column"+ :name name+ :displayName (or display_name name)+ :jsType (js-type column)}+ :baseType base_type+ :effectiveType (when (not= effective-type base_type) effective-type)+ :semanticType semantic_type+ :description description+ :unit unit)))++(defn generated-key+ "Returns a stable JavaScript object key for an entity name and id."+ [entity-name id]+ (let [generated-key (some-> entity-name u/->camelCaseEn)]+ (if (str/blank? generated-key)+ (str "entity" id)+ generated-key)))++(defn pascal-case+ "Capitalizes the first character of string without changing the rest."+ [string]+ (when-not (str/blank? string)+ (str (u/upper-case-en (subs string 0 1))+ (subs string 1))))++(defn- duplicate-key?+ [key->count key]+ (> (get key->count key 0) 1))++(defn- keyed-map-candidate-key+ [key->count {:keys [key id]+ key-disambiguator :keyDisambiguator+ table-id :tableId}]+ (cond-> key+ (duplicate-key? key->count key) (str (or key-disambiguator table-id id))))++(defn- unique-keys+ "Returns `ks` with every key that is still shared by several `entities` suffixed with its entity id until all are+ unique, so no entity overwrites another."+ [entities ks]+ (let [key->count (frequencies ks)]+ (if (every? #(= 1 %) (vals key->count))+ ks+ (recur entities (mapv (fn [entity k]+ (cond-> k (duplicate-key? key->count k) (str "_" (:id entity))))+ entities ks)))))++(defn keyed-map+ "Returns a sorted map keyed by each entity key, disambiguating duplicate keys."+ [entities]+ (let [entities (vec entities)+ base-key->count (frequencies (map :key entities))+ candidate-keys (mapv (partial keyed-map-candidate-key base-key->count) entities)+ candidate->count (frequencies candidate-keys)+ ks (unique-keys entities+ (mapv (fn [entity candidate-key]+ (cond-> candidate-key+ (duplicate-key? candidate->count candidate-key) (str (:id entity))))+ entities candidate-keys))]+ (into (sorted-map)+ (map (fn [entity key]+ [key (-> entity+ (dissoc :keyDisambiguator)+ (assoc :key key))])+ entities ks))))++(defn without-unavailable-cards+ "`cards` without any backed by a routing destination database, and, while the audit feature is off, without the+ audit database's and the audit collection's: the card details lookup refuses one in the audit collection, and one+ on the audit database would be listed without its table."+ [cards]+ (let [destination-ids (data-apps.db/destination-database-ids (into #{} (keep :database_id) cards))+ audit-off? (not (premium-features/enable-audit-app?))]+ (cond->> cards+ (seq destination-ids) (remove #(contains? destination-ids (:database_id %)))+ audit-off? (remove #(or (= audit/audit-db-id (:database_id %))+ (some-> (:collection_id %) audit/is-collection-id-audit?))))))++(defn aggregation-result-column-with-metadata-provider+ "Returns an aggregation result column using an existing metadata provider."+ [metadata-provider query-definition]+ (try+ (let [query (lib/query metadata-provider query-definition)+ aggregation-column (m/find-first #(= (:lib/source %) :source/aggregations)+ (lib/returned-columns query))]+ (when aggregation-column+ (metabot/->result-column query aggregation-column)))+ (catch Exception _+ nil)))++(defn aggregation-result-column+ "Returns the first aggregation result column for a saved query definition, for metrics and measures."+ [database-id query-definition]+ (try+ (aggregation-result-column-with-metadata-provider+ (lib-be/application-database-metadata-provider database-id)+ query-definition)+ (catch Exception _+ nil)))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/javascript.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/javascript.cljnew file mode 100644index 00000000000..112457391e3--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/javascript.clj@@ -0,0 +1,258 @@+(ns metabase-enterprise.data-apps.generate.schema.javascript+ "A small TypeScript AST encoded as tagged vectors, and a printer for it.++ The AST covers exactly the subset of TypeScript that generated schema modules+ emit. Expressions:++ [:lit 42] ; any JSON-encodable literal+ [:ref \"tables\" \"orders\" :fields] ; property path => tables.orders.fields+ [:call \"pickFields\" expr ...] ; call expression, args printed inline+ [:arr expr-or-item ...] ; array literal+ [:obj entry ...] ; object literal++ Object entries are `[key expr]` or `[key {:metadata {...}} obj]`; array+ items are bare expressions or `[:item {:metadata {...}} obj]`, where `obj`+ is an `[:obj ...]`. Metadata is a JSON-encodable map, printed as a+ `/* metadata: {...} */` block first inside the entry's object, before its+ properties, so a reader meets it before the data it describes and it never+ reaches runtime code. Statements:++ [:const \"tables\" expr] ; const tables = <expr> as const;+ [:raw \"function helper() {...}\"] ; verbatim TypeScript+ [:export \"tables\"] ; export { tables };+ [:module statement ...] ; one printed file++ For example:++ [:module+ [:const \"tables\"+ [:obj [\"orders\" {:metadata {\"entityId\" \"abc123\"}}+ [:obj [\"type\" [:lit \"table\"]]+ [\"ids\" [:arr [:lit 1] [:lit 2]]]]]]]+ [:export \"tables\"]]++ prints as:++ const tables = {+ orders: {+ /* metadata: { \"entityId\": \"abc123\" } */+ type: \"table\",+ ids: [ 1, 2 ]+ }+ } as const;++ export { tables };++ Rendering rules: arrays whose items are all literals print on one line;+ `:call` arguments always print inline; object keys print bare when they are+ valid JavaScript identifiers and quoted otherwise. A metadata block whose+ values are all scalars prints on one line, so a field costs a reader one line+ of the file; one with a nested array or object prints as+ `JSON.stringify(x, null, 2)` would, one array item per line. [[render-js]]+ prints a `:module`; [[Module]] is the Malli schema for the whole grammar.++ The printer is deliberately option-free and policy-free: decisions about+ *what* to emit (runtime keys, metadata, compaction) belong in+ `metabase-enterprise.data-apps.generate.schema.render`, which builds this AST. If the output needs+ new syntax, add a node type and its printer here rather than concatenating+ TypeScript strings elsewhere."+ (:require+ [clojure.string :as str]+ [metabase.util :as u]+ [metabase.util.json :as json]))++(set! *warn-on-reflection* true)++(def ^:private expression-tags+ #{:lit :ref :call :arr :obj})++(def ^:private key-schema+ [:or :string :keyword])++(def Module+ "Malli schema for the TypeScript AST accepted by [[render-js]]."+ [:schema {:registry+ {::entry-options [:map {:closed true}+ [:metadata {:optional true} [:map-of key-schema :any]]]+ ;; Metadata prints as a block inside the entry's object, so only an object can carry it.+ ::entry [:or+ [:tuple key-schema [:ref ::expr]]+ [:tuple key-schema [:ref ::entry-options] [:ref ::obj]]]+ ::item [:tuple [:= :item] [:ref ::entry-options] [:ref ::obj]]+ ::obj [:cat [:= :obj] [:* [:schema [:ref ::entry]]]]+ ::expr [:multi {:dispatch first}+ [:lit [:tuple [:= :lit] :any]]+ [:ref [:cat [:= :ref] [:+ key-schema]]]+ [:call [:cat [:= :call] :string [:* [:schema [:ref ::expr]]]]]+ [:arr [:cat [:= :arr] [:* [:or+ [:schema [:ref ::item]]+ [:schema [:ref ::expr]]]]]]+ [:obj [:ref ::obj]]]+ ::statement [:multi {:dispatch first}+ [:const [:tuple [:= :const] key-schema [:ref ::expr]]]+ [:raw [:tuple [:= :raw] :string]]+ [:export [:tuple [:= :export] key-schema]]]}}+ [:cat [:= :module] [:* [:schema [:ref ::statement]]]]])++(defn expression?+ "Returns true when `value` is an AST expression node."+ [value]+ (and (vector? value)+ (contains? expression-tags (first value))))++(defn call?+ "Returns true when `value` is a `[:call ...]` expression node."+ [value]+ (and (vector? value)+ (= :call (first value))))++(def ^:private js-identifier-pattern+ #"[A-Za-z_$][A-Za-z0-9_$]*")++(defn- spaces+ [indent]+ (apply str (repeat indent " ")))++(defn- javascript-key+ "Renders a value as a JavaScript object key.++ Valid identifiers render bare e.g. orders; everything else renders as a quoted+ property name e.g. \"orders-by-month\"."+ [entry-key]+ (let [key-name (u/qualified-name entry-key)]+ (if (re-matches js-identifier-pattern key-name)+ key-name+ (json/encode key-name))))++(defn- reference-path+ "Renders `[:ref ...]` segments as a JavaScript property path."+ [path-segments]+ (str (u/qualified-name (first path-segments))+ (apply str (for [path-segment (rest path-segments)]+ (let [segment-name (u/qualified-name path-segment)]+ (if (re-matches js-identifier-pattern segment-name)+ (str "." segment-name)+ (str "[" (json/encode segment-name) "]")))))))++(defn- entry-parts+ "Returns `[key entry-options expr]` for either entry form."+ [entry]+ (if (= 3 (count entry))+ entry+ [(first entry) nil (second entry)]))++(defn- item-parts+ "Returns `[entry-options expr]` for either array item form."+ [item]+ (if (and (vector? item) (= :item (first item)))+ [(second item) (nth item 2)]+ [nil item]))++(defn- metadata-json+ "Renders `metadata` as JSON: on one line when every value is a scalar, otherwise as `JSON.stringify(x, null, 2)`+ would, with each line after the first indented by `indent`."+ [metadata indent]+ (if (not-any? coll? (vals metadata))+ (str "{ "+ (str/join ", " (for [[k v] metadata]+ (str (json/encode (u/qualified-name k)) ": " (json/encode v))))+ " }")+ (str/replace (json/encode metadata {:pretty {:indent-arrays? true :object-field-value-separator ": "}})+ "\n" (str "\n" (spaces indent)))))++(defn- metadata-block+ "Returns a `/* metadata: {...} */` block. A `*/` can only occur inside a JSON string, where it is written as the+ equivalent `*\\/`, so the block always ends where it should."+ [indent metadata]+ (str (spaces indent) "/* metadata: "+ (str/replace (metadata-json metadata indent) "*/" "*\\/")+ " */"))++(declare render-expression)++(defn- render-inline+ "Renders an expression on a single line, for `:call` arguments."+ [node]+ (case (first node)+ :lit (json/encode (second node))+ :ref (reference-path (rest node))+ :call (let [[_ function-name & args] node]+ (str function-name "(" (str/join ", " (map render-inline args)) ")"))+ :arr (str "[ " (str/join ", " (map render-inline (rest node))) " ]")+ :obj (str "{ "+ (str/join ", " (for [entry (rest node)+ :let [[entry-key options expr] (entry-parts entry)]]+ (do+ ;; An inline object has no room for a block, so refuse rather than drop it.+ (when (seq (:metadata options))+ (throw (ex-info "Metadata can only be attached to an object on its own lines."+ {:node node})))+ (str (javascript-key entry-key) ": " (render-inline expr)))))+ " }")))++(defn- literal-node?+ [node]+ (and (vector? node) (= :lit (first node))))++(defn- render-object+ [entries indent metadata]+ (let [inner-indent (+ indent 2)+ lines (for [entry entries+ :let [[entry-key options expr] (entry-parts entry)]]+ (str (spaces inner-indent)+ (javascript-key entry-key)+ ": "+ (render-expression expr inner-indent (:metadata options))))+ ;; the block comes first, so a reader meets it before the properties it describes+ body (str/join "\n" (remove str/blank? [(when (seq metadata) (metadata-block inner-indent metadata))+ (str/join ",\n" lines)]))]+ (if (str/blank? body)+ "{ }"+ (str "{\n" body "\n" (spaces indent) "}"))))++(defn- render-array+ [items indent]+ (cond+ (empty? items)+ "[ ]"++ (every? literal-node? items)+ (str "[ " (str/join ", " (map #(json/encode (second %)) items)) " ]")++ :else+ (str "[\n"+ (str/join ",\n"+ (for [item items+ :let [[options expr] (item-parts item)+ item-indent (+ indent 2)]]+ (str (spaces item-indent)+ (render-expression expr item-indent (:metadata options)))))+ "\n" (spaces indent) "]")))++(defn- render-expression+ "Renders `node` at `indent`. `metadata`, when present, prints inside `node`, which must then be an object."+ ([node indent]+ (render-expression node indent nil))+ ([node indent metadata]+ (when (and (seq metadata) (not= :obj (first node)))+ (throw (ex-info "Metadata can only be attached to an object." {:node node})))+ (case (first node)+ :lit (json/encode (second node))+ :ref (reference-path (rest node))+ :call (render-inline node)+ :obj (render-object (rest node) indent metadata)+ :arr (render-array (rest node) indent))))++(defn- render-statement+ [statement]+ (case (first statement)+ :raw (second statement)+ :const (let [[_ const-name expr] statement]+ (str "const " (u/qualified-name const-name) " = "+ (render-expression expr 0) " as const;"))+ :export (str "export { " (u/qualified-name (second statement)) " };")))++(defn render-js+ "Renders a `[:module ...]` AST as TypeScript source."+ [[_ & statements]]+ (str (str/join "\n\n" (map render-statement statements)) "\n"))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/metric.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/metric.cljnew file mode 100644index 00000000000..d3a9e354b1c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/metric.clj@@ -0,0 +1,288 @@+(ns metabase-enterprise.data-apps.generate.schema.metric+ "The schema of metrics, with their dimensions."+ (:require+ [medley.core :as m]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.generate.schema.common :as schemas.common]+ [metabase-enterprise.data-apps.generate.schema.table :as schemas.table]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.metabot.core :as metabot]+ [metabase.metrics.core :as metrics]+ [metabase.util :as u]+ [metabase.util.log :as log]))++(set! *warn-on-reflection* true)++(defn- metric-result-column+ "Returns the metric aggregation result column inferred by Lib."+ [card]+ (schemas.common/aggregation-result-column (:database_id card) (:dataset_query card)))++(defn- metric-filters+ "Returns the display names of the filters `card`'s query applies. The schema exposes a metric only as an+ aggregation, so they are the only hint that it counts a subset of the rows."+ [card]+ (when-let [query-definition (not-empty (:dataset_query card))]+ (try+ (let [query (lib/query (lib-be/application-database-metadata-provider (:database_id card))+ query-definition)]+ (not-empty (vec (for [stage-number (range (lib/stage-count query))+ filter-clause (lib/filters query stage-number)]+ (lib/display-name query stage-number filter-clause)))))+ (catch Exception e+ (log/warnf e "Could not describe the filters of metric %s" (:id card))+ nil))))++(defn- metric-details-error-message+ [card error-message]+ (format "Failed to build schema details for metric \"%s\" (card %s): %s"+ (or (:name card) "Untitled")+ (:id card)+ (or error-message "unknown error")))++(defn- metric-details-error-data+ [card error-data]+ (m/assoc-some+ {:card-id (:id card)+ :card-name (:name card)+ :card-type (:type card)}+ :status-code (:status-code error-data)))++(defn- metric-details+ "Returns metric details with queryable dimensions for schema generation."+ [card]+ (let [response (metabot/get-metric-details {:metric-id (:id card)+ ;; The generated schema does not use the default temporal dimension.+ :with-default-temporal-breakout? false+ :with-field-values? false+ :with-queryable-dimensions? true+ :with-segments? false})]+ (or (:structured-output response)+ (let [error-message (:output response)]+ (throw (ex-info (metric-details-error-message card error-message)+ (assoc (metric-details-error-data card response)+ :error-message error-message)))))))++(defn- persisted-dimension->column+ "Converts persisted metric dimensions to column-shaped maps.++ Persisted metric dimensions use kebab-case field/type keys, while [[schemas.common/column-schema]] expects+ result-column-style snake_case keys."+ [dimension]+ (let [field-id (some-> dimension :sources first :field-id)]+ {:name (:name dimension)+ :display_name (:display-name dimension)+ :base_type (some-> (:effective-type dimension) u/qualified-name)+ :effective_type (some-> (:effective-type dimension) u/qualified-name)+ :semantic_type (some-> (:semantic-type dimension) u/qualified-name)+ :field_id field-id}))++(defn- dimension-field-id+ "Returns the field id backing a metric dimension, including persisted dimension sources."+ [{:keys [field_id] :as dimension}]+ (or field_id (some-> dimension :sources first :field-id)))++(defn- dimension-table-id+ "Returns the table id that backs a metric dimension, when known."+ ([dimension]+ (dimension-table-id dimension nil))+ ([dimension field-table-ids]+ (or (:table_id dimension)+ (:table-id dimension)+ (if field-table-ids+ (get field-table-ids (dimension-field-id dimension))+ (schemas.table/table-by-field-id (dimension-field-id dimension))))))++(defn- field-table-ids+ "Returns backing table ids for dimensions that need field-based resolution."+ [dimensions]+ (let [field-ids (into #{}+ (comp (remove #(or (:table_id %) (:table-id %)))+ (keep dimension-field-id))+ dimensions)]+ (when (seq field-ids)+ (into {}+ (map (juxt :id :table_id))+ (data-apps.db/field-ids-and-table-ids field-ids)))))++(defn- dimension-schema+ "Returns the schema for a metric dimension."+ ([dimension metric-id]+ (dimension-schema dimension metric-id (dimension-table-id dimension) {} {}))+ ([dimension+ metric-id+ table-id+ table-key-by-id+ table-source-name-by-id]+ (let [field-id (dimension-field-id dimension)+ dimension-id (or (:id dimension) field-id)+ column (if (:sources dimension)+ (persisted-dimension->column dimension)+ dimension)]+ (m/assoc-some+ (assoc (schemas.common/column-schema column)+ :type "column"+ :key (schemas.common/generated-key (:name column) dimension-id)+ :id (str dimension-id))+ :sourceName (when (integer? table-id)+ (get table-source-name-by-id table-id))+ :fieldId (when (integer? field-id) field-id)+ :tableId (when (integer? table-id) table-id)+ :sourceFieldId (when (integer? (:source-field-id dimension))+ (:source-field-id dimension))+ :metricId metric-id+ :keyDisambiguator (when (integer? table-id)+ (get table-key-by-id table-id))))))++(defn- mapping-source-field-id+ "Returns the mapped source field id for a metric dimension mapping."+ [{:keys [target]}]+ (when (and (vector? target)+ (= :field (first target))+ (map? (second target)))+ (let [source-field-id (:source-field (second target))]+ (when (integer? source-field-id)+ source-field-id))))++(defn- enrich-dimensions-with-mappings+ "Adds mapped source field ids to persisted metric dimensions."+ [dimensions dimension-mappings]+ (let [mapping-by-dimension-id (into {} (map (juxt :dimension-id identity)) dimension-mappings)]+ (mapv (fn [{:keys [id] :as dimension}]+ (m/assoc-some dimension+ :source-field-id (some-> (get mapping-by-dimension-id id)+ mapping-source-field-id)))+ dimensions)))++(defn- sync-and-fetch-metric-dimensions!+ "Syncs and returns persisted metric dimensions with mapping metadata."+ [{:keys [id]}]+ (metrics/sync-dimensions! :metadata/metric id)+ (let [{:keys [dimensions dimension_mappings]} (data-apps.db/card-dimensions id)]+ (enrich-dimensions-with-mappings dimensions dimension_mappings)))++(defn- table-source-rows+ "Returns table rows for table-backed metric dimensions."+ [table-ids]+ (when (seq table-ids)+ (data-apps.db/table-names table-ids)))++(defn- table-key-disambiguators+ "Returns table display keys used to disambiguate compacted metric dimensions."+ [table-rows]+ (when (seq table-rows)+ (->> table-rows+ (map (fn [{:keys [id name display_name]}]+ [id (schemas.common/pascal-case (schemas.common/generated-key (or display_name name) id))]))+ (into {}))))++(defn- table-source-names+ "Returns table names emitted as metric dimension source names."+ [table-rows]+ (when (seq table-rows)+ (->> table-rows+ (map (juxt :id :name))+ (into {}))))++(defn- source-table-schema+ "Returns the metric source table identity from portable table metadata."+ [[database-name schema-name table-name]]+ (when (and database-name table-name)+ {:databaseName database-name+ :schemaName schema-name+ :tableName table-name}))++(defn- source-table-id+ "Returns the source table id for table-backed metrics."+ [card]+ (lib/primary-source-table-id (:dataset_query card)))++(defn- source-card-id+ "Return the source card ID from the first stage of a metric's definition.++ This identifies the card the definition reads from. The source needed to use the metric is returned by+ [[metabase.metabot.tools.util/metric-required-source]]; a multi-stage definition can require its base table."+ [card]+ (lib/primary-source-card-id (:dataset_query card)))++(defn- fallback-metric-column+ "Returns a stable fallback column when metric result-column inference fails."+ [{:keys [name]}]+ {:type "column"+ :name name+ :displayName name+ :jsType "unknown"})++(defn- metric-dimensions-with-table-ids+ "Returns metric dimensions paired with their backing table ids, filtering mapped dimensions for card metrics."+ [details source-card-id-value]+ (let [dimensions (or (seq (sync-and-fetch-metric-dimensions! details))+ (:queryable-dimensions details))+ field-table-ids (field-table-ids dimensions)]+ (cond->> (mapv (fn [dimension]+ [dimension (dimension-table-id dimension field-table-ids)])+ dimensions)+ source-card-id-value (remove (fn [[_dimension table-id]]+ (integer? table-id))))))++(defn- metric-dimension-schemas+ "Returns dimension schemas and mapped table ids for a metric."+ [metric-id details source-card-id-value]+ (let [dimension-table-id-pairs (metric-dimensions-with-table-ids details source-card-id-value)+ table-ids (->> dimension-table-id-pairs (keep second) (filter integer?) distinct)+ table-rows (table-source-rows table-ids)+ table-key-by-id (table-key-disambiguators table-rows)+ table-source-name-by-id (table-source-names table-rows)+ dimension-schemas (mapv (fn [[dimension table-id]]+ (dimension-schema dimension+ metric-id+ table-id+ table-key-by-id+ table-source-name-by-id))+ dimension-table-id-pairs)]+ {:dimension-schemas dimension-schemas+ :mapped-table-ids (->> dimension-schemas (keep :tableId) distinct sort vec)}))++(defn- metric-schema+ "Returns the schema for a metric and its queryable dimensions."+ [{:keys [id name description verified portable_entity_id base_table_portable_fk] :as details}+ card]+ (let [result-column (or (some-> (metric-result-column card) schemas.common/column-schema)+ (fallback-metric-column details))+ source-card-id-value (source-card-id card)+ {:keys [dimension-schemas mapped-table-ids]} (metric-dimension-schemas id details source-card-id-value)]+ (m/assoc-some+ {:type "metric"+ :key (schemas.common/generated-key name id)+ :id id+ :name name+ :columns [result-column]}+ :databaseId (:database_id card)+ :sourceTableId (source-table-id card)+ :sourceCardId source-card-id-value+ :entityId portable_entity_id+ :description description+ :filters (metric-filters card)+ :verified (when verified true)+ :sourceTable (source-table-schema base_table_portable_fk)+ :mappedTableIds (not-empty mapped-table-ids)+ :dimensions (not-empty (schemas.common/keyed-map dimension-schemas)))))++(defn- references-saved-card?+ "Whether `metric`'s query depends on a saved card anywhere, not only as its stage-0 source."+ [metric]+ (boolean (seq (lib/all-source-card-ids (:dataset_query metric)))))++(defn metric-schemas+ "Returns the schemas of the metrics in the collections with `collection-ids`."+ [collection-ids]+ (for [metric (remove source-card-id+ (schemas.common/without-unavailable-cards (data-apps.db/metric-cards-in-collections collection-ids)))+ ;; A data app's questions can use only metrics that resolve entirely from tables, as they+ ;; read no saved question. `source-card-id` sees only stage 0, so a table-sourced metric+ ;; joining a saved question would get through; check the whole query instead.+ :when (not (references-saved-card? metric))+ :let [details (metric-details metric)]+ :when details]+ (metric-schema details metric)))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/render.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/render.cljnew file mode 100644index 00000000000..687ba776865--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/render.clj@@ -0,0 +1,363 @@+(ns metabase-enterprise.data-apps.generate.schema.render+ "Converts semantic schema values into the TypeScript AST.++ This is the pure policy stage of the schema pipeline: it decides which+ schema keys become runtime data, which become `/* metadata */` blocks, and how+ metric dimensions compact into `pickFields(...)` calls. The output is the+ tagged-vector AST described in [[metabase-enterprise.data-apps.generate.schema.javascript]];+ [[schema->ast]] produces it, and the public+ [[metabase-enterprise.data-apps.generate.schemas/render-typescript]] composes it with the+ printer.++ Nothing here touches the database or builds strings: new rendering behavior+ should be expressed as schema -> AST transformation (extend+ [[schema-render-policy]] or emit different nodes), keeping it assertable+ structurally in tests."+ (:require+ [clojure.string :as str]+ [metabase-enterprise.data-apps.generate.schema.javascript :as schemas.javascript]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++;; The rendered schema serves two audiences:+;; - `:runtime` keys are executable data consumed by the Lib.createTestQuery DSL.+;; - `:metadata` keys are emitted as a `/* metadata: {...} */` block inside the+;; entity for coding agents and humans, preserving useful context without+;; making the runtime object larger or more ambiguous than the DSL needs.+(def ^:private schema-render-policy+ {:table {:runtime [:type :id :name :fields :segments :measures]+ :metadata [:entityId :description :databaseName :schemaName :tableName]}+ :field {:runtime [:type :name :sourceName :jsType :fieldId :tableId+ :baseType :effectiveType :defaultTemporalBucket]+ :metadata [:displayName :description :semanticType :unit]}+ :segment {:runtime [:type :id :tableId :name]+ :metadata [:entityId :description]}+ :measure {:runtime [:type :id :tableId :name :columns]+ :metadata [:entityId :description]}+ :metric {:runtime [:type :id :name :databaseId :sourceTableId :sourceCardId+ :mappedTableIds :columns :dimensions]+ :metadata [:entityId :description :filters :verified :sourceTable]}+ :metric-dimension {:runtime [:type :id :fieldId :metricId :tableId :sourceName :sourceFieldId+ :name :jsType :baseType :effectiveType :defaultTemporalBucket]+ :metadata [:displayName :description :semanticType :unit]}+ :column {:runtime [:type :name :jsType]+ :metadata [:displayName :description :baseType :effectiveType :semanticType :unit]}})++;; Nested entity kinds by parent kind and entry key. Map values hold keyed+;; entity maps; sequential values hold entity vectors. Metric `:dimensions` are+;; special-cased in [[entity->node]] because compaction mixes call expressions+;; with nested dimension maps.+(def ^:private entity-children+ {:table {:fields :field, :segments :segment, :measures :measure}+ :measure {:columns :column}+ :metric {:columns :column}})++(defn- policy-runtime-keys+ "Returns the keys that should be emitted as runtime data for a schema node."+ [kind value]+ (filter #(contains? value %)+ (get-in schema-render-policy [kind :runtime])))++(defn- redundant-table-name?+ "Returns true when a table's name would duplicate its object key."+ [entry-key table-name]+ (and (some? entry-key)+ (some? table-name)+ (= (name entry-key) (str table-name))))++(defn- metadata-value+ "Returns `value` as written in a metadata block, or nil when there is nothing to write: a nil or blank value says+ nothing, so a map loses such keys at any depth (a table without a schema has no `schemaName`)."+ [value]+ (cond+ (string? value) (when-not (str/blank? value) value)+ (map? value) (not-empty (into {} (keep (fn [[k v]] (when-some [v (metadata-value v)] [k v]))) value))+ (coll? value) (not-empty (into [] (keep metadata-value) value))+ :else value))++(defn- entity-metadata+ "Returns the metadata-only keys of an entity, in policy order, or nil when it has none."+ [kind value entry-key]+ (not-empty+ (apply array-map+ (mapcat (fn [metadata-key]+ (when-some [metadata (metadata-value (get value metadata-key))]+ (when-not (and (= kind :table)+ (= metadata-key :tableName)+ (redundant-table-name? entry-key metadata))+ [(name metadata-key) metadata])))+ (get-in schema-render-policy [kind :metadata])))))++(defn- generic->node+ "Converts a schema value without render policy into an AST expression.++ Values outside the policy table (instance metadata) emit every key and no+ metadata block."+ [value]+ (cond+ (schemas.javascript/expression? value) value+ (map? value) (into [:obj] (for [[entry-key entry-value] value]+ [entry-key (generic->node entry-value)]))+ (sequential? value) (into [:arr] (map generic->node) value)+ :else [:lit value]))++(declare entity->node)++(defn- keyed-entities->obj+ "Converts a map of entity key -> entity of `kind` into an object expression."+ [entities kind]+ (into [:obj]+ (for [[entry-key entity] entities]+ (if-let [metadata (entity-metadata kind entity entry-key)]+ [entry-key {:metadata metadata} (entity->node entity kind)]+ [entry-key (entity->node entity kind)]))))++(defn- entities->arr+ "Converts a sequence of entities of `kind` into an array expression."+ [entities kind]+ (into [:arr]+ (for [entity entities]+ (if-let [metadata (entity-metadata kind entity nil)]+ [:item {:metadata metadata} (entity->node entity kind)]+ (entity->node entity kind)))))++(defn- dimensions->obj+ "Converts compacted metric dimensions into an object expression.++ Compaction leaves a mix of `pickFields(...)` call expressions and grouped raw+ dimension maps under `:dimensions`."+ [dimensions]+ (into [:obj]+ (for [[entry-key group] dimensions]+ [entry-key (if (schemas.javascript/expression? group)+ group+ (keyed-entities->obj group :metric-dimension))])))++(defn- entity->node+ "Converts one schema entity of `kind` into an object expression, emitting the+ runtime keys chosen by [[schema-render-policy]]."+ [entity kind]+ (into [:obj]+ (for [entry-key (policy-runtime-keys kind entity)+ :let [value (get entity entry-key)+ child-kind (get-in entity-children [kind entry-key])]]+ [entry-key+ (cond+ (and (= kind :metric)+ (= entry-key :dimensions)) (dimensions->obj value)+ (and child-kind (map? value)) (keyed-entities->obj value child-kind)+ (and child-kind+ (sequential? value)) (entities->arr value child-kind)+ :else (generic->node value))])))++(defn- table-fields-reference-lookup+ "Returns table-id -> field-map reference expression for tables in `schema`."+ [schema]+ (into {}+ (for [[table-key {:keys [id]}] (:tables schema)+ :when (integer? id)]+ [id {:key table-key+ :reference [:ref "tables" table-key "fields"]}])))++(defn- field-lookup-keys+ "Returns the table-scoped lookup keys that can identify a field."+ [table-id {:keys [fieldId name]}]+ (cond-> []+ (integer? fieldId) (conj [table-id fieldId])+ (string? name) (conj [table-id name])))++(defn- table-field-key-entries+ "Returns lookup entries that map table/field identity to rendered field keys."+ [table-id table-key fields]+ (for [[field-key field] fields+ lookup-key (field-lookup-keys table-id field)]+ [lookup-key {:table-key table-key+ :field-key field-key}]))++(defn- table-field-key-lookup+ "Returns [table-id field-id-or-name] -> rendered table/field keys for `schema`."+ [schema]+ (into {}+ (mapcat (fn [[table-key {:keys [id fields]}]]+ (when (integer? id)+ (table-field-key-entries id table-key fields))))+ (:tables schema)))++(defn- pick-fields-call+ "Returns a `pickFields(...)` call expression for compacted metric dimensions."+ ([fields-reference field-keys]+ (pick-fields-call fields-reference field-keys nil))+ ([fields-reference field-keys source-field-id]+ (cond-> [:call "pickFields"+ fields-reference+ (into [:arr] (map (fn [field-key] [:lit field-key])) field-keys)]+ (integer? source-field-id)+ (conj [:obj ["sourceFieldId" [:lit source-field-id]]]))))++(defn- dimension-group-output-key+ "Returns the output key for a compacted dimension group, suffixed by its foreign key's field key when several joins+ reach the same table."+ [table-key source-field-id table-key-count field-key-by-field-id]+ (if (= 1 (get table-key-count table-key))+ table-key+ (str table-key "Via" (if-let [field-key (get field-key-by-field-id source-field-id)]+ (u/capitalize-first-char field-key)+ source-field-id))))++(defn- metric-dimension-table-field+ "Returns table field metadata when a metric dimension can be represented by `pickFields(...)`."+ [fields-reference-by-table field-key-by-table-and-field {:keys [tableId fieldId name sourceFieldId]}]+ (when-let [{table-key :key, :keys [reference]} (get fields-reference-by-table tableId)]+ (when-let [{:keys [field-key]} (or (get field-key-by-table-and-field [tableId fieldId])+ (get field-key-by-table-and-field [tableId name]))]+ {:field-key field-key+ :reference reference+ :source-field-id sourceFieldId+ :table-key table-key})))++(defn- add-compact-metric-dimension-field+ "Adds one matched metric dimension to its table/source-field compaction group."+ [groups {:keys [field-key reference source-field-id table-key]}]+ (update groups+ [table-key source-field-id]+ (fnil (fn [group]+ (update group :field-keys conj field-key))+ {:field-keys []+ :reference reference+ :source-field-id source-field-id+ :table-key table-key})))++(defn- compact-metric-dimension-fields+ "Compacts table-backed metric dimensions into grouped call expressions.++ Returns both the compacted `:fields` map and the original dimension keys that+ were compacted, so raw dimensions can be preserved without another lookup pass."+ [fields-reference-by-table field-key-by-table-and-field dimensions]+ (let [{:keys [fields-by-group dimension-keys]}+ (reduce (fn [acc [dimension-key dimension]]+ (if-let [field (metric-dimension-table-field fields-reference-by-table+ field-key-by-table-and-field+ dimension)]+ (-> acc+ (update :fields-by-group add-compact-metric-dimension-field field)+ (update :dimension-keys conj dimension-key))+ acc))+ {:dimension-keys #{}+ :fields-by-group (array-map)}+ dimensions)+ table-key-count (frequencies (map (comp :table-key val) fields-by-group))+ field-key-by-field-id (into {}+ (keep (fn [[[_table-id field-id-or-name] {:keys [field-key]}]]+ (when (integer? field-id-or-name)+ [field-id-or-name field-key])))+ field-key-by-table-and-field)]+ {:dimension-keys dimension-keys+ :fields (not-empty+ (reduce-kv (fn [acc _ {:keys [table-key reference field-keys source-field-id]}]+ (assoc acc+ (dimension-group-output-key table-key source-field-id table-key-count+ field-key-by-field-id)+ (pick-fields-call reference+ (distinct field-keys)+ source-field-id)))+ (array-map)+ fields-by-group))}))++(defn- compact-metric-dimension-keys+ "Returns original metric dimension keys represented by compacted fields."+ [compact-fields]+ (:dimension-keys compact-fields))++(defn- raw-metric-dimension-fields+ "Returns non-compacted metric dimensions as raw runtime fields.++ Raw dimensions are kept under `\"fields\"`, or `\"metricFields\"` if compacted+ fields already use `\"fields\"` as their output key."+ [dimensions compact-keys compact-fields]+ (when-let [raw-fields (not-empty (update-vals (apply dissoc dimensions compact-keys)+ #(dissoc % :metricId)))]+ (let [group-key (if (contains? compact-fields "fields")+ "metricFields"+ "fields")]+ {group-key raw-fields})))++(defn- compact-metric-dimensions+ "Rewrites metric dimensions into compact field references where possible."+ [schema]+ (let [fields-reference-by-table (table-fields-reference-lookup schema)+ field-key-by-table-and-field (table-field-key-lookup schema)]+ (update schema :metrics+ (fn [metrics]+ (update-vals metrics+ (fn [metric]+ (let [dimensions (:dimensions metric)+ compact-fields (compact-metric-dimension-fields fields-reference-by-table+ field-key-by-table-and-field+ dimensions)+ fields (:fields compact-fields)+ compact-keys (compact-metric-dimension-keys compact-fields)+ raw-fields (raw-metric-dimension-fields dimensions compact-keys fields)+ compact-dimensions (not-empty (merge raw-fields fields))]+ (cond-> (dissoc metric :dimensions)+ compact-dimensions (assoc :dimensions compact-dimensions)))))))))++(def ^:private pick-fields-helper+ "The TypeScript helper used by compacted metric dimensions."+ [:raw (str/join "\n"+ ["function pickFields<TFields extends object, TKey extends keyof TFields>("+ " fields: TFields,"+ " keys: readonly TKey[],"+ " options?: { sourceFieldId?: number },"+ "): Pick<TFields, TKey> {"+ " return Object.fromEntries(keys.map((key) => {"+ " const field = fields[key] as { tableId?: number };"+ " if (options?.sourceFieldId == null) {"+ " return [key, field];"+ " }"+ " const { tableId, ...joinedField } = field;"+ ""+ " return [key, { ...joinedField, sourceFieldId: options.sourceFieldId }];"+ " })) as Pick<TFields, TKey>;"+ "}"])])++(defn- uses-pick-fields-helper?+ "Returns true when compacted metrics contain `pickFields(...)` expressions."+ [schema]+ (boolean+ (some (fn [metric]+ (some schemas.javascript/call? (vals (:dimensions metric))))+ (vals (:metrics schema)))))++(def ^:private top-level-keys+ [:tables :metrics])++(defn- section->node+ "Converts one top-level schema section into an object expression."+ [section-key section]+ (case section-key+ :tables (keyed-entities->obj section :table)+ :metrics (keyed-entities->obj section :metric)))++(defn schema->ast+ "Converts a semantic schema value into a TypeScript module AST.++ Each present top-level section becomes its own `const`; the `schema` const+ ties them together with the remaining schema metadata and is the module's+ export."+ [schema]+ (let [schema (compact-metric-dimensions schema)+ present-keys (filter #(contains? schema %) top-level-keys)+ schema-metadata (apply dissoc schema top-level-keys)+ schema-entries (concat (for [[entry-key value] schema-metadata]+ [entry-key (generic->node value)])+ (for [section-key present-keys]+ [section-key [:ref (name section-key)]]))]+ (into [:module]+ (concat+ (when (uses-pick-fields-helper? schema)+ [pick-fields-helper])+ (for [section-key present-keys]+ [:const (name section-key) (section->node section-key (get schema section-key))])+ [[:const "schema" (into [:obj] schema-entries)]+ [:export "schema"]]))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/source.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/source.cljnew file mode 100644index 00000000000..0396f1bbadb--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/source.clj@@ -0,0 +1,65 @@+(ns metabase-enterprise.data-apps.generate.schema.source+ "Data access for a data app's schema, reified as a protocol.++ [[SchemaSource]] names every read that [[metabase-enterprise.data-apps.generate.schemas/fetch-items]] performs, so+ the data-access surface is one definition. [[app-db-source]] is the production implementation; tests reify the+ protocol with literal values. All methods return the shaped schema entities of the+ `metabase-enterprise.data-apps.generate.schema.*` builders, except [[library-tables]], which returns raw table rows+ (only `:id` is consumed)."+ (:require+ [clojure.set :as set]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.generate.schema.metric :as schemas.metric]+ [metabase-enterprise.data-apps.generate.schema.table :as schemas.table]+ [metabase.collections.core :as collections]+ [metabase.collections.models.collection :as collection]))++(set! *warn-on-reflection* true)++(def LibraryScope+ "The library collection tree, classified by collection type: `:data-collection-ids` hold the published tables,+ `:metric-collection-ids` the metrics."+ [:map {:closed true}+ [:data-collection-ids [:set :int]]+ [:metric-collection-ids [:set :int]]])++(defn- app-db-library-scope+ "The [[LibraryScope]] of the root libraries and their descendants, empty where the instance has no library."+ []+ (let [library (collections/library-collection)+ descendants (when (and library (not (:archived library)))+ (collection/descendants-flat-for [library]))+ collections (data-apps.db/unarchived-collections (into #{} (map :id) descendants))+ ids-of-type (fn [collection-type]+ (into #{} (comp (filter #(= (:type %) collection-type)) (map :id)) collections))]+ {:data-collection-ids (ids-of-type collection/library-data-collection-type)+ :metric-collection-ids (ids-of-type collection/library-metrics-collection-type)}))++(defprotocol SchemaSource+ "The data-access patterns behind schema generation."+ (library-scope [source]+ "The [[LibraryScope]] of the root libraries.")+ (metrics [source collection-ids]+ "Schema entities for the metrics in `collection-ids`.")+ (tables [source table-ids]+ "Schema entities for the tables with `table-ids`.")+ (library-tables [source collection-ids]+ "Published table rows in `collection-ids`."))++(defn- curated-library-ids+ [scope-key requested-ids]+ (set/intersection (scope-key (app-db-library-scope)) requested-ids))++(def app-db-source+ "The production [[SchemaSource]], backed by the application database."+ (reify SchemaSource+ (library-scope [_]+ (app-db-library-scope))+ (metrics [_ collection-ids]+ (vec (schemas.metric/metric-schemas+ (curated-library-ids :metric-collection-ids collection-ids))))+ (tables [_ table-ids]+ (vec (schemas.table/table-schemas (schemas.table/select-tables table-ids))))+ (library-tables [_ collection-ids]+ (vec (schemas.table/select-library-tables+ (curated-library-ids :data-collection-ids collection-ids))))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/table.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/table.cljnew file mode 100644index 00000000000..ddac68ac7e2--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/schema/table.clj@@ -0,0 +1,187 @@+(ns metabase-enterprise.data-apps.generate.schema.table+ "The schema of tables, with their fields, segments and measures."+ (:require+ [medley.core :as m]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.generate.schema.common :as schemas.common]+ [metabase.audit-app.core :as audit]+ [metabase.lib-be.core :as lib-be]+ [metabase.metabot.core :as metabot]+ [metabase.premium-features.core :as premium-features]))++(set! *warn-on-reflection* true)++(defn table-by-field-id+ "Returns the table for a given field id."+ [field-id]+ (when (integer? field-id)+ (data-apps.db/field-table-id field-id)))++(defn field-schema+ "Returns the schema for a table field."+ ([field]+ (field-schema field nil nil))+ ([field source-name]+ (field-schema field source-name nil))+ ([{:keys [id field_id] :as field} source-name table-id]+ (let [field-id (or id field_id)+ table-id (or table-id (:table_id field) (:table-id field) (table-by-field-id field-id))]+ (m/assoc-some+ (assoc (schemas.common/column-schema field)+ :type "column"+ :key (schemas.common/generated-key (:name field) field-id)+ :id field-id)+ :sourceName source-name+ :fieldId (when (integer? field-id) field-id)+ :tableId (when (integer? table-id) table-id)+ :defaultTemporalBucket (:unit field)))))++(defn- without-unavailable-tables+ "`tables` without any backed by a routing destination database, and without the audit database's while the audit+ feature is off, since the table details lookup refuses those."+ [tables]+ (let [destination-ids (data-apps.db/destination-database-ids (into #{} (keep :db_id) tables))+ audit-off? (not (premium-features/enable-audit-app?))]+ (cond->> tables+ (seq destination-ids) (remove #(contains? destination-ids (:db_id %)))+ audit-off? (remove #(= audit/audit-db-id (:db_id %))))))++(defn select-tables+ "Returns the active tables with `table-ids`."+ [table-ids]+ (without-unavailable-tables (data-apps.db/active-tables table-ids)))++(defn select-library-tables+ "Returns the published tables in the library collections with `collection-ids`."+ [collection-ids]+ (->> (data-apps.db/published-tables-in-collections collection-ids)+ (without-unavailable-tables)))++(defn segment-schema+ "Returns the schema for a segment."+ [table-id {:keys [id name description display-name portable-entity-id portable_entity_id]}]+ (m/assoc-some+ {:type "segment"+ :key (schemas.common/generated-key (or display-name name) id)+ :id id+ :tableId table-id+ :name name}+ :entityId (or portable_entity_id portable-entity-id)+ :description description))++(defn- fallback-measure-column+ [{:keys [name]}]+ {:type "column"+ :name name+ :displayName name+ :jsType "unknown"})++(defn measure-result-column+ "Returns the result column for a measure definition, or nil when it cannot be inferred.++ Measures render as aggregate fields. When Lib can infer the+ aggregation column, the schema exposes the real result type. Otherwise, the+ measure remains usable with a fallback column."+ [database-id measure-id]+ (try+ (when-let [definition (data-apps.db/measure-definition measure-id)]+ (schemas.common/aggregation-result-column database-id definition))+ (catch Exception _+ nil)))++(defn- measure-result-columns+ "Returns result columns for table measures with one definition query and metadata provider."+ [database-id measures]+ (let [measure-ids (into [] (keep :id) measures)]+ (when (seq measure-ids)+ (let [definition-by-measure-id (into {}+ (map (juxt :id :definition))+ (data-apps.db/measure-definitions measure-ids))]+ (try+ (let [metadata-provider (lib-be/application-database-metadata-provider database-id)]+ (into {}+ (keep (fn [{:keys [id]}]+ (when-let [definition (get definition-by-measure-id id)]+ [id (schemas.common/aggregation-result-column-with-metadata-provider metadata-provider definition)])))+ measures))+ ;; Result-column inference is best effort; callers fall back to an unknown column.+ (catch Exception _+ {}))))))++(defn measure-schema+ "Returns the schema for a measure."+ ([table-id database-id measure]+ (measure-schema table-id database-id (measure-result-column database-id (:id measure)) measure))+ ([table-id _database-id result-column {:keys [id name description display-name portable-entity-id portable_entity_id]}]+ (m/assoc-some+ {:type "measure"+ :key (schemas.common/generated-key (or display-name name) id)+ :id id+ :tableId table-id+ :name name+ :columns [(or (some-> result-column schemas.common/column-schema)+ (fallback-measure-column {:name (or display-name name)}))]}+ :entityId (or portable_entity_id portable-entity-id)+ :description description)))++(defn table-schema+ "Returns the schema for a table."+ [{:keys [id name description display_name database_id database_name database_schema portable_entity_id fields segments measures]}]+ (let [segments-map (schemas.common/keyed-map (map #(segment-schema id %) segments))+ measure-result-column-by-id (measure-result-columns database_id measures)+ measures-map (schemas.common/keyed-map (map #(measure-schema id database_id+ (get measure-result-column-by-id (:id %))+ %)+ measures))]+ (m/assoc-some+ {:type "table"+ :key (schemas.common/generated-key (or display_name name) id)+ :id id+ :name (or display_name name)+ :databaseName database_name+ :tableName name+ :fields (schemas.common/keyed-map (map #(field-schema % name id) fields))}+ :entityId portable_entity_id+ :description description+ :schemaName database_schema+ :segments (not-empty segments-map)+ :measures (not-empty measures-map))))++(defn- table-details-error-message+ [table error-message]+ (format "Failed to build schema details for table \"%s\" (table %s): %s"+ (or (:name table) "Untitled")+ (:id table)+ (or error-message "unknown error")))++(defn- table-details-error-data+ [table error-data]+ (m/assoc-some+ {:table-id (:id table)+ :table-name (:name table)}+ :status-code (:status-code error-data)))++(defn- table-details+ [table]+ (let [response (metabot/get-table-details+ {:entity-type :table+ :entity-id (:id table)+ :with-fields? true+ :with-field-values? false+ :with-related-tables? false+ :with-metrics? false+ :with-measures? true+ :with-segments? true})]+ (or (:structured-output response)+ (let [error-message (:output response)]+ (throw (ex-info (table-details-error-message table error-message)+ (assoc (table-details-error-data table response)+ :error-message error-message)))))))++(defn table-schemas+ "Returns table schemas for selected table rows."+ [tables]+ (for [table tables+ :let [details (table-details table)]+ :when details]+ (table-schema details)))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/generate/util.clj b/enterprise/backend/src/metabase_enterprise/data_apps/generate/util.cljnew file mode 100644index 00000000000..d9f21ea39ca--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/generate/util.clj@@ -0,0 +1,12 @@+(ns metabase-enterprise.data-apps.generate.util+ "The files Metabase generates for a data app."+ (:require+ [metabase-enterprise.serialization.core :as serialization]))++(set! *warn-on-reflection* true)++(defn resource-file+ "The file of the extracted `entity` named `export-name`, at its path in the app's collection directory."+ [export-name entity]+ {:path (str (serialization/slugify-name export-name) ".yaml")+ :contents (serialization/entity-yaml entity)})diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.cljindex d51e0723eec..061f4cc1e61 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj@@ -92,11 +92,10 @@(t2/define-before-insert :model/DataApp[data-app](let [row (prepare ::data-apps.schema/data-app.insert data-app)]- (when-not (:resource_collection_id row)- (throw (ex-info (tru "A data app needs a collection of its own.")- {:status-code 400})))- (check-resource-collection (:resource_collection_id row) nil)- row))+ (if-let [collection-id (:resource_collection_id row)]+ (do (check-resource-collection collection-id nil)+ row)+ (assoc row :resource_collection_id (data-apps.db/insert-resource-collection! (:name row))))))(t2/define-before-update :model/DataApp[data-app]@@ -224,16 +223,6 @@(defmethod serdes/resource-paths "DataApp" [ingested][(ingested-bundle-path ingested)])-(defmethod serdes/load-one! "DataApp"- [ingested maybe-local]- ;; an app made on the instance keeps its slug: the unique index would refuse the insert anyway, but with an error- ;; that doesn't say what to do- (when (and (nil? maybe-local) (data-apps.db/data-app-exists? (:slug ingested)))- (throw (ex-info (tru "A data app named \"{0}\" already exists on this instance. Delete it, or give the app in the repository another slug."- (:slug ingested))- {:status-code 400})))- (serdes/default-load-one! ingested maybe-local))-(defenterprise data-app-collection-ids"The resource collections of the data apps, which hold the copies an app runs.":feature :nonediff --git a/enterprise/backend/src/metabase_enterprise/data_apps/typed_schema.clj b/enterprise/backend/src/metabase_enterprise/data_apps/typed_schema.cljdeleted file mode 100644index 8ff1e9601c6..00000000000--- a/enterprise/backend/src/metabase_enterprise/data_apps/typed_schema.clj+++ /dev/null@@ -1,178 +0,0 @@-(ns metabase-enterprise.data-apps.typed-schema- "The TypeScript module of a data app's queries and actions: a `defineQuery` call for each question in the app's- resource collection, typed by its result columns, and a `defineAction` call for each action, typed by its- parameters, each addressed by its entity ID."- (:require- [clojure.string :as str]- [medley.core :as m]- [metabase-enterprise.data-apps.db :as data-apps.db]- [metabase.actions.core :as actions]- [metabase.lib.core :as lib]- [metabase.lib.schema.common :as lib.schema.common]- [metabase.types.core]- [metabase.util :as u]- [metabase.util.json :as json]))--(set! *warn-on-reflection* true)--(comment metabase.types.core/keep-me)--(defn- column-js-type- "The JavaScript type of a value of a column with `base-type`."- [base-type]- (let [base-type (some-> base-type keyword)]- (cond- (nil? base-type) "unknown"- (isa? base-type :type/Boolean) "boolean"- (isa? base-type :type/Number) "number"- (isa? base-type :type/Temporal) "Date"- (isa? base-type :type/TextLike) "string"- (isa? base-type :type/Text) "string"- :else "unknown")))--(defn- column-schema- "The schema of a card's result `column`."- [{:keys [name display_name base_type effective_type semantic_type]}]- (let [effective-type (or effective_type base_type)]- (m/assoc-some- {:type "column"- :name name- :displayName (or display_name name)- :jsType (column-js-type effective-type)}- :baseType base_type- :effectiveType effective-type- :semanticType semantic_type)))--(defn- query-definition- "The `defineQuery` argument of `card`: a card source with its result columns."- [{:keys [name entity_id result_metadata]}]- {:source (m/assoc-some {:type "card"- :entityId entity_id- :name name}- :columns (some->> result_metadata (mapv column-schema)))})--(defn- param-type->js-type- "The JavaScript type of a value of an action parameter of `param-type`."- [param-type]- (when ((some-fn keyword? string?) param-type)- (let [param-type (lib.schema.common/normalize-keyword param-type)]- (case (or (namespace param-type) (name param-type))- ("number" "numeric") "number"- ("text" "string") "string"- "date" "Date"- "boolean" "boolean"- nil))))--(defn- template-tag-types- "The value types of the template tags of `action`'s query, keyed by tag name. A field filter's `:type` is always- `:dimension`, so its `:widget-type` is what tells the value type."- [{:keys [dataset_query]}]- (some-> dataset_query- not-empty- lib/all-template-tags-map- (update-vals (fn [{:keys [type widget-type]}]- (if (= type :dimension) widget-type type)))))--(defn- parameter-schema- "The schema of an action's execute parameter."- [tag-types {:keys [id slug name display-name type target required]}]- (let [slug (or slug (some-> id clojure.core/name) (some-> name u/slugify))]- (m/assoc-some- {:slug slug- :displayName (or display-name name slug)- :jsType (or (param-type->js-type type)- (param-type->js-type (get tag-types (some-> target lib/parameter-target-template-tag-name)))- "unknown")}- :required (when required true))))--(defn- hidden-parameter-ids- "The IDs of the parameters `action`'s form hides, which execution refuses a value for."- [{:keys [visualization_settings]}]- (into #{} (keep #(when (:hidden %) (:id %))) (vals (:fields visualization_settings))))--(defn- action-definition- "The `defineAction` argument of the query `action`: its entity ID and parameters."- [{:keys [entity_id name description type parameters] :as action}]- (let [tag-types (template-tag-types action)- hidden? (hidden-parameter-ids action)]- {:action (m/assoc-some- {:kind "action"- :id entity_id- :name name- :type type- :parameters (into [] (comp (remove (comp hidden? :id))- (map #(parameter-schema tag-types %)))- parameters)}- :description description)}))--(defn- identifier-part- "`s` with the characters a JavaScript identifier can't hold removed."- [s]- (str/replace s #"[^\p{L}\p{N}_$]" ""))--(defn- export-key- "A JavaScript identifier for an entity named `entity-name` with `entity-id`, the same on every instance."- [entity-name entity-id]- (let [k (some-> entity-name u/->camelCaseEn identifier-part)]- (cond- (str/blank? k) (str "entity_" (identifier-part entity-id))- (re-find #"^\p{N}" k) (str "_" k)- :else k)))--(defn- keyed- "`entities` keyed by a unique JavaScript identifier made from each one's name, in their order."- [entities]- (let [ks (map #(export-key (:name %) (:entity_id %)) entities)- n (frequencies ks)]- (map (fn [entity k]- [(cond-> k (> (n k) 1) (str "_" (identifier-part (:entity_id entity)))) entity])- entities ks)))--(defn- identifier? [k]- (re-matches #"[A-Za-z_$][A-Za-z0-9_$]*" k))--(defn- render- "`value` as a TypeScript literal indented by `indent`."- [value indent]- (let [inner (str indent " ")]- (cond- (map? value) (if (empty? value)- "{}"- (str "{\n"- (str/join (for [[k v] value- :let [k (u/qualified-name k)]]- (str inner (if (identifier? k) k (json/encode k)) ": "- (render v inner) ",\n")))- indent "}"))- (sequential? value) (if (empty? value)- "[]"- (str "[\n"- (str/join (for [v value] (str inner (render v inner) ",\n")))- indent "]"))- :else (json/encode value))))--(defn- render-entries- "The `export const` of `export-name`: an object of `entities` keyed by name, each its `define-fn` call on its- `definition`."- [export-name define-fn definition entities]- (str "export const " export-name " = {\n"- (str/join (for [[k entity] (keyed entities)]- (str " " k ": " define-fn "(" (render (definition entity) " ") "),\n")))- "};\n"))--(defn generate- "The TypeScript module of the queries and actions of the data app `app`."- [{slug :name, collection-id :resource_collection_id}]- (let [cards (data-apps.db/resource-cards collection-id)- action-ids (data-apps.db/resource-action-ids collection-id)- actions (when (seq action-ids)- (let [by-id (u/index-by :id (actions/select-actions-for-ids action-ids))]- (keep by-id action-ids)))]- (str "// The queries and actions of the data app \"" slug "\", generated by Metabase from the questions and\n"- "// actions in the app's collection. Do not edit: after changing them, fetch it again with\n"- "// mb data-app typed-schema " slug " --out src/metabase.ts\n"- "import { defineAction, defineQuery } from \"@metabase/embedding-sdk-react/data-app\";\n"- "\n"- (render-entries "queries" "defineQuery" query-definition cards)- "\n"- (render-entries "actions" "defineAction" action-definition actions))))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.cljindex 565faf77ece..3b37483a65e 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj@@ -463,10 +463,6 @@(remote-sync.db/collections sync-on)))(update :sync-off #(when-let [sync-off (seq %)](remote-sync.db/collections sync-off))))]- ;; a data app's collection is synced with its app, and a pull refuses its file once it says remote-synced- (when (some spec/data-apps-namespace-collection? sync-on)- (throw (ex-info (tru "A data app''s collection is synced with its app and can''t be marked as synced.")- {:status-code 400})))(doseq [collection sync-on:when (not (:is_remote_synced collection))](collections/assert-remote-syncable (assoc collection :is_remote_synced true)))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/events.cljindex df3550bcc76..2372426ba2c 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj@@ -109,23 +109,6 @@(remote-sync.db/insert-rsos! rows))(count rows)))-(defn backfill-data-app-tracking!- "Insert a 'create' ledger row for every published DataApp that has none, returning the number of rows inserted."- []- (let [data-app-spec (spec/spec-for-model-key :model/DataApp)- tracked (remote-sync.db/tracked-model-ids "DataApp")- timestamp (t/offset-date-time)- rows (for [app (remote-sync.db/instances-where :model/DataApp (:conditions data-app-spec))- :when (not (contains? tracked (:id app)))]- (merge {:model_type "DataApp"- :model_id (:id app)- :status "create"- :status_changed_at timestamp}- (spec/build-sync-object-fields data-app-spec app)))]- (when (seq rows)- (remote-sync.db/insert-rsos! rows))- (count rows)))-(defn disable-library-tracking!"Remove all snippet, data action, their namespaces' collection, and glossary tracking entries."[]diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/init.cljindex 55bf9e64ba1..9f83f239adf 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj@@ -69,10 +69,7 @@(when (= :read-write (settings/remote-sync-type))(let [n (events/backfill-action-tracking!)](when (pos? n)- (log/infof "Tracking %d existing actions for remote sync" n)))- (let [n (events/backfill-data-app-tracking!)]- (when (pos? n)- (log/infof "Tracking %d existing data apps for remote sync" n))))+ (log/infof "Tracking %d existing actions for remote sync" n))))(when-not (collection/has-remote-synced-collection?)(if (nil? (settings/remote-sync-branch))(log/warn "Remote sync is enabled but no remote-sync branch is set. Cannot do initial import.")diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.cljindex 58b059ebc08..edbdff01c18 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -6,7 +6,6 @@[metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.data-apps.test-util :as data-apps.tu]- [metabase.events.core :as events][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.permissions.core :as perms]@@ -22,12 +21,14 @@"The bundle of the apps these tests serve."(.getBytes "BUNDLE" "UTF-8"))-(def ^:private app-request+(def ^:private demo-app+ "The attributes of the app the endpoint tests serve."{:name "demo":display_name "Demo app":bundle_path "dist/index.js":allowed_hosts ["https://api.example.com"]- :enabled true})+ :enabled true+ :bundle (.getBytes "DEMOBUNDLE" "UTF-8")});;; ---------------------------------------------- Permissions ----------------------------------------------@@ -66,76 +67,55 @@(is (str/includes? (str (mt/user-real-request :crowberto :get 200 (data-apps.tu/app-url app "bundle")))"BUNDLE")))))))-(deftest read-only-remote-sync-blocks-data-app-changes-test+(deftest read-only-remote-sync-allows-enabling-test(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/RemoteSyncObject]- (mt/with-temp [:model/DataApp app {}]- (let [url (data-apps.tu/app-url app)]- (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"- remote-sync-type :read-only]- (testing "a read-only instance refuses to create, change, or delete an app"- (mt/user-http-request :crowberto :post 403 "ee/apps" (assoc app-request :name "other"))- (is (not (t2/exists? :model/DataApp :name "other")))- (mt/user-http-request :crowberto :put 403 url {:display_name "Renamed"})- (mt/user-http-request :crowberto :put 403 url {:enabled false :display_name "Renamed"})- (mt/user-http-request :crowberto :delete 403 url)- (is (=? {:display_name (:display_name app) :enabled true} (t2/select-one :model/DataApp :name (:name app)))))- (testing "enabling and disabling stays allowed"- (is (=? {:enabled false}- (mt/user-http-request :crowberto :put 200 url {:enabled false})))))- (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"- remote-sync-type :read-write]- (testing "a read-write instance allows changes"- (is (=? {:display_name "Renamed"}- (mt/user-http-request :crowberto :put 200 url {:display_name "Renamed"}))))))))))+ (mt/with-temp [:model/DataApp app {}]+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-type :read-only]+ (testing "enabling and disabling an app is allowed on a read-only instance"+ (is (=? {:enabled false}+ (mt/user-http-request :crowberto :put 200 (data-apps.tu/app-url app) {:enabled false}))))))))(deftest enabling-a-data-app-is-not-a-synced-change-test(mt/with-premium-features #{:data-apps}(mt/with-model-cleanup [:model/RemoteSyncObject](mt/with-temp [:model/DataApp app {}](mt/user-http-request :crowberto :put 200 (data-apps.tu/app-url app) {:enabled false})- (is (not (t2/exists? :model/RemoteSyncObject :model_type "DataApp" :model_id (:id app))))- (mt/user-http-request :crowberto :put 200 (data-apps.tu/app-url app) {:display_name "Renamed"})- (is (=? {:model_name (:name app) :status "update"}- (t2/select-one :model/RemoteSyncObject :model_type "DataApp" :model_id (:id app))))))))+ (is (not (t2/exists? :model/RemoteSyncObject :model_type "DataApp" :model_id (:id app))))))))(deftest data-app-write-endpoints-require-feature-token-test(mt/with-premium-features #{}- (mt/user-http-request :crowberto :post 402 "ee/apps" {:name "demo"})))--(defn- update-venues-query- "A native query that renames every venue."- []- (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'"))+ (mt/user-http-request :crowberto :put 402 "ee/apps/demo" {:enabled false})))(deftest group-with-access-reaches-only-copied-actions-test(testing "an action is reachable exactly when it lives in the data app collection"(mt/with-premium-features #{:data-apps}- (mt/with-non-admin-groups-no-root-collection-perms- (mt/with-temp [:model/DataApp {app-collection-id :resource_collection_id :as app} {}- :model/PermissionsGroup {group-id :id} {}- :model/Collection {source-collection-id :id} {:namespace :data-actions}- :model/Action {source-id :id} {:type :query- :collection_id source-collection-id}- :model/QueryAction _ {:action_id source-id- :database_id (mt/id)- :dataset_query (update-venues-query)}- :model/Action {copied-id :id} {:type :query- :collection_id app-collection-id}- :model/QueryAction _ {:action_id copied-id- :database_id (mt/id)- :dataset_query (update-venues-query)}]- (group-access/add-groups! app [group-id])- (perms/add-user-to-group! (mt/user->id :rasta) group-id)- (testing "the group with access reads the action copied into the app collection"- (is (=? {:id copied-id}- (mt/user-http-request :rasta :get 200 (str "action/" copied-id)))))- (testing "the same group cannot read the source action it was copied from"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :get 403 (str "action/" source-id)))))- (testing "a superuser still reads both"- (is (=? {:id source-id}- (mt/user-http-request :crowberto :get 200 (str "action/" source-id))))))))))+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/DataApp {app-collection-id :resource_collection_id :as app} {}+ :model/PermissionsGroup {group-id :id} {}+ :model/Collection {source-collection-id :id} {:namespace :data-actions}+ :model/Action {source-id :id} {:type :implicit+ :collection_id source-collection-id}+ :model/ImplicitAction _ {:action_id source-id+ :kind "row/update"+ :table_id (mt/id :venues)}+ :model/Action {copied-id :id} {:type :implicit+ :collection_id app-collection-id}+ :model/ImplicitAction _ {:action_id copied-id+ :kind "row/update"+ :table_id (mt/id :venues)}]+ (group-access/add-groups! app [group-id])+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (testing "the group with access reads the action copied into the app collection"+ (is (=? {:id copied-id}+ (mt/user-http-request :rasta :get 200 (str "action/" copied-id)))))+ (testing "the same group cannot read the source action it was copied from"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 (str "action/" source-id)))))+ (testing "a superuser still reads both"+ (is (=? {:id source-id}+ (mt/user-http-request :crowberto :get 200 (str "action/" source-id)))))))))))(deftest outdated-apps-are-hidden-from-users-and-badged-for-admins-test(mt/test-helpers-set-global-values!@@ -192,123 +172,31 @@(is (= ["https://api.example.com"] (get-in by-name [(:name with-hosts) :allowed_hosts])))(is (= [] (get-in by-name [(:name without-hosts) :allowed_hosts]))))))))-;;; ------------------------------------------------- Create & update ---------------------------------------------------(deftest create-endpoint-test- (mt/test-helpers-set-global-values!- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (testing "a non-superuser cannot create an app"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "ee/apps" app-request))))- (testing "a superuser creates an app with its manifest fields"- (is (=? {:name "demo"- :display_name "Demo app"- :bundle_path "dist/index.js"- :allowed_hosts ["https://api.example.com"]- :version 1- :enabled true- :resource_collection_id pos-int?}- (mt/user-http-request :crowberto :post 200 "ee/apps"- (assoc app-request :bundle_path "./dist/index.js" :bundle "BUNDLE"))))- (testing "with an empty bundle, whatever the request carries"- (is (= 0 (alength ^bytes (t2/select-one-fn :bundle :model/DataApp :name "demo")))))- (testing "with its own collection in the data-apps namespace, which no group but Administrators reads"- (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "demo")]- (is (=? {:name "Data App: demo" :namespace :data-apps :location "/"}- (t2/select-one :model/Collection :id collection-id)))- (is (= #{} (perms/collection-read-access-group-ids collection-id))))))- (testing "a taken slug is refused"- (is (= "A data app with this slug already exists."- (mt/user-http-request :crowberto :post 409 "ee/apps" app-request))))- (testing "invalid manifest fields are refused"- (doseq [bad [{:name "Not A Slug"}- {:name "repo-status"}- {:bundle_path "../escape.js"}- {:allowed_hosts ["ftp://example.com"]}- {:version 0}]]- (mt/user-http-request :crowberto :post 400 "ee/apps" (merge app-request {:name "other"} bad))- (is (not (t2/exists? :model/DataApp :name "other")) (str "should refuse: " (pr-str bad)))))))))--(deftest create-endpoint-publishes-collection-creation-test- (testing "the app's collection is created the way any collection is, so what listens to collection events (remote- sync, the activity log) sees it"- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (let [created (atom [])]- (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic {:keys [object]}]- (when (= :event/collection-create topic)- (swap! created conj (:id object))))]- (mt/user-http-request :crowberto :post 200 "ee/apps" app-request))- (is (= [(t2/select-one-fn :resource_collection_id :model/DataApp :name "demo")] @created)))))))+;;; ---------------------------------------------------- Update ----------------------------------------------------(deftest update-endpoint-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (mt/user-http-request :crowberto :post 200 "ee/apps" app-request)- (let [bundle-hash #(t2/select-one-fn :bundle_hash :model/DataApp :name "demo")]+ (mt/with-temp [:model/DataApp app {:display_name "Demo app"}]+ (let [url (data-apps.tu/app-url app)](testing "a non-superuser cannot update an app"(is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :put 403 "ee/apps/demo" {:display_name "Mine"}))))- (testing "a superuser updates manifest fields"- (is (=? {:display_name "Renamed" :description "What it does" :allowed_hosts []}- (mt/user-http-request :crowberto :put 200 "ee/apps/demo"- {:display_name "Renamed"- :description " What it does "- :allowed_hosts []}))))- (testing "invalid manifest fields are refused"- (mt/user-http-request :crowberto :put 400 "ee/apps/demo" {:bundle_path "/abs.js"})- (is (= "dist/index.js" (t2/select-one-fn :bundle_path :model/DataApp :name "demo"))))- (testing "the bundle is ignored, since only PUT /:slug/bundle replaces it"- (let [before (bundle-hash)]- (mt/user-http-request :crowberto :put 200 "ee/apps/demo" {:bundle "NEWBUNDLE"})- (is (= before (bundle-hash)))))+ (mt/user-http-request :rasta :put 403 url {:enabled false}))))+ (testing "a superuser enables and disables an app"+ (is (=? {:enabled false} (mt/user-http-request :crowberto :put 200 url {:enabled false})))+ (is (=? {:enabled true} (mt/user-http-request :crowberto :put 200 url {:enabled true}))))+ (testing "anything else about an app changes only through an import"+ (mt/user-http-request :crowberto :put 400 url {:display_name "Renamed"})+ (is (= "Demo app" (t2/select-one-fn :display_name :model/DataApp :id (:id app)))))(testing "updating a missing app 404s"(mt/user-http-request :crowberto :put 404 "ee/apps/missing" {:enabled false})))))))-(deftest delete-endpoint-requires-a-superuser-test- (mt/with-premium-features #{:data-apps}- (mt/with-temp [:model/DataApp app {}- :model/PermissionsGroup {group-id :id} {}- :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)- :group_id group-id}]- (group-access/add-groups! app [group-id])- (testing "a user with access can open the app"- (mt/user-http-request :rasta :get 200 (data-apps.tu/app-url app)))- (testing "a user with access cannot delete the app"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :delete 403 (data-apps.tu/app-url app))))- (is (t2/exists? :model/DataApp :id (:id app)))))))--(deftest delete-endpoint-404s-for-a-missing-app-test- (mt/with-premium-features #{:data-apps}- (mt/user-http-request :crowberto :delete 404 "ee/apps/missing")))--(deftest delete-endpoint-preserves-groups-test- (mt/with-premium-features #{:data-apps}- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/DataApp app {}- :model/PermissionsGroup {group-id :id} {}- :model/Card {card-id :id} {:collection_id (:resource_collection_id app)- :dataset_query (data-apps.tu/venues-query)}]- (group-access/add-groups! app [group-id])- (mt/user-http-request :crowberto :delete 204 (data-apps.tu/app-url app))- (is (not (t2/exists? :model/DataApp :id (:id app))))- (is (not (t2/exists? :model/Collection :id (:resource_collection_id app))))- (is (not (t2/exists? :model/Card :id card-id)))- (is (not (t2/exists? :model/Permissions :group_id group-id- :object (perms/collection-read-path (:resource_collection_id app)))))- (is (t2/exists? :model/PermissionsGroup :id group-id))))))-;;; ----------------------------------------------------- API -----------------------------------------------------(deftest list-and-bundle-endpoints-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (mt/user-http-request :crowberto :post 200 "ee/apps" app-request)- (mt/user-http-request :crowberto :put 200 "ee/apps/demo/bundle" {:bundle "DEMOBUNDLE"})+ (mt/with-temp [:model/DataApp _ demo-app](testing "GET / lists the apps"(is (=? [{:name "demo" :display_name "Demo app":bundle_path "dist/index.js" :enabled true}]@@ -332,9 +220,7 @@(deftest enable-disable-endpoint-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (mt/user-http-request :crowberto :post 200 "ee/apps" app-request)- (mt/user-http-request :crowberto :put 200 "ee/apps/demo/bundle" {:bundle "DEMOBUNDLE"})+ (mt/with-temp [:model/DataApp _ demo-app](testing "PUT /:slug can disable an app"(is (=? {:name "demo" :enabled false}(mt/user-http-request :crowberto :put 200 "ee/apps/demo" {:enabled false}))))@@ -384,160 +270,52 @@(is (= 200 (:status (mt/user-http-request-full-response:crowberto :get 200 "ee/apps/sandbox-host"))))))))-(deftest create-defaults-test- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (testing "app created from its slug alone is enabled, with an empty bundle and its collection"- (is (=? {:name "demo"- :display_name "demo"- :bundle_path "dist/index.js"- :enabled true- :resource_collection_id pos-int?}- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})))- (is (= 0 (alength ^bytes (t2/select-one-fn :bundle :model/DataApp :name "demo"))))- (is (=? {:name "demo" :enabled true} (mt/user-http-request :crowberto :get 200 "ee/apps/demo")))))))--(deftest replace-bundle-endpoint-test- (mt/test-helpers-set-global-values!- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo" :enabled true})- (testing "a non-superuser cannot replace the bundle"- (mt/user-http-request :rasta :put 403 "ee/apps/demo/bundle" {:bundle "MINE"}))- (testing "the new bundle is what the app serves"- (let [{:keys [bundle_hash]} (mt/user-http-request :crowberto :put 200 "ee/apps/demo/bundle" {:bundle "V1"})]- (is (str/includes? (str (mt/user-real-request :crowberto :get 200 "ee/apps/demo/bundle")) "V1"))- (is (not= bundle_hash- (:bundle_hash (mt/user-http-request :crowberto :put 200 "ee/apps/demo/bundle" {:bundle "V2"}))))- (is (str/includes? (str (mt/user-real-request :crowberto :get 200 "ee/apps/demo/bundle")) "V2"))))- (testing "a missing app 404s"- (mt/user-http-request :crowberto :put 404 "ee/apps/missing/bundle" {:bundle "V1"}))))))-(deftest admins-write-the-resource-collection-through-the-api-test(mt/with-premium-features #{:data-apps}(data-apps.tu/with-published-tables! [(mt/id :venues)](mt/with-actions-enabled- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/Card :model/Action]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- query (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))]- (testing "an admin creates a question in the app's collection"- (is (=? {:collection_id collection-id}- (mt/user-http-request :crowberto :post 200 "card" {:name "Venues"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query}))))- (testing "an admin creates an action in the app's collection"- (is (=? {:collection_id collection-id}- (mt/user-http-request :crowberto :post 200 "action"- {:name "Rename venues"- :type "query"- :database_id (mt/id)- :collection_id collection-id- :dataset_query (lib/native-query (mt/metadata-provider)- "UPDATE venues SET name = {{name}}")- :parameters [{:id "name" :slug "name" :type "string/="- :target [:variable [:template-tag "name"]]}]}))))- (testing "nobody else writes it"- (mt/user-http-request :rasta :post 403 "card" {:name "Mine"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query}))))))))--(deftest typed-schema-endpoint-test- (mt/with-premium-features #{:data-apps}- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-actions-enabled- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/Card :model/Action]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- mp (mt/metadata-provider)- query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))- (lib/aggregate (lib/count))- (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))- card (mt/user-http-request :crowberto :post 200 "card" {:name "Venues by category"- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query})- action-id (:id (mt/user-http-request :crowberto :post 200 "action"- {:name "Rename venue"- :type "query"- :database_id (mt/id)- :collection_id collection-id- :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}} WHERE id = {{id}}")- :parameters [{:id "name" :slug "name" :type "string/="- :target [:variable [:template-tag "name"]]- :required true}- {:id "id" :slug "id" :type "number/="- :target [:variable [:template-tag "id"]]}]}))- action-entity-id (t2/select-one-fn :entity_id :model/Action :id action-id)]- (testing "a non-superuser cannot read it"- (mt/user-http-request :rasta :get 403 "ee/apps/demo/typed-schema"))- (let [{:keys [body headers]} (mt/user-http-request-full-response :crowberto :get 200 "ee/apps/demo/typed-schema")]- (is (str/starts-with? (get headers "Content-Type") "text/typescript"))- (testing "the module says how to fetch it again"- (is (str/includes? body "// mb data-app typed-schema demo --out src/metabase.ts\n")))- (testing "the module imports the define functions"- (is (str/includes? body "import { defineAction, defineQuery } from \"@metabase/embedding-sdk-react/data-app\";")))- (testing "a question is a card source addressed by its entity ID and typed by its result columns"- (is (str/includes? body "export const queries = {\n venuesByCategory: defineQuery({"))- (is (str/includes? body (str "entityId: \"" (:entity_id card) "\"")))- (is (str/includes? body "name: \"count\""))- (is (str/includes? body "jsType: \"number\"")))- (testing "an action is addressed by its entity ID and typed by its parameters"- (is (str/includes? body "export const actions = {\n renameVenue: defineAction({"))- (is (str/includes? body (str "id: \"" action-entity-id "\"")))- (is (str/includes? body "slug: \"name\",\n displayName: \"name\",\n jsType: \"string\",\n required: true,"))- (is (str/includes? body "slug: \"id\",\n displayName: \"id\",\n jsType: \"number\","))))))))))--(defn- create-question!- "A table question named `card-name` in the collection with `collection-id`, reading `query`, created by an admin."- [collection-id card-name query]- (mt/user-http-request :crowberto :post 200 "card" {:name card-name- :collection_id collection-id- :display "table"- :visualization_settings {}- :dataset_query query}))+ (mt/with-model-cleanup [:model/Card :model/Action]+ (mt/with-temp [:model/DataApp {collection-id :resource_collection_id} {}]+ (let [query (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))]+ (testing "an admin creates a question in the app's collection"+ (is (=? {:collection_id collection-id}+ (mt/user-http-request :crowberto :post 200 "card" {:name "Venues"+ :collection_id collection-id+ :display "table"+ :visualization_settings {}+ :dataset_query query}))))+ (testing "an admin creates an action in the app's collection"+ (is (=? {:collection_id collection-id}+ (mt/user-http-request :crowberto :post 200 "action"+ {:name "Rename venues"+ :type "implicit"+ :kind "row/update"+ :table_id (mt/id :venues)+ :collection_id collection-id}))))+ (testing "nobody else writes it"+ (mt/user-http-request :rasta :post 403 "card" {:name "Mine"+ :collection_id collection-id+ :display "table"+ :visualization_settings {}+ :dataset_query query})))))))))(deftest disabled-apps-are-listed-only-to-superusers-test(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (let [{:keys [id]} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo" :enabled false})]- (group-access/add-groups! (t2/select-one :model/DataApp :id id) [(:id (perms/all-users-group))])- (testing "a user with access doesn't see the disabled app"- (is (not-any? #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps"))))- (testing "a superuser does"- (is (some #(= "demo" (:name %)) (mt/user-http-request :crowberto :get 200 "ee/apps"))))- (testing "a user with access sees it once it's enabled"- (mt/user-http-request :crowberto :put 200 "ee/apps/demo" {:enabled true})- (is (some #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps"))))))))+ (mt/with-temp [:model/DataApp app {:name "demo" :enabled false}]+ (group-access/add-groups! app [(:id (perms/all-users-group))])+ (testing "a user with access doesn't see the disabled app"+ (is (not-any? #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps"))))+ (testing "a superuser does"+ (is (some #(= "demo" (:name %)) (mt/user-http-request :crowberto :get 200 "ee/apps"))))+ (testing "a user with access sees it once it's enabled"+ (mt/user-http-request :crowberto :put 200 "ee/apps/demo" {:enabled true})+ (is (some #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps")))))))(deftest apps-are-listed-only-to-users-who-can-read-their-collection-test(mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection]- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})+ (mt/with-temp [:model/DataApp _ {:name "demo"}](testing "a user without a grant on the app's collection doesn't see the app"(is (not-any? #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps"))))(testing "a user sees it once their group can read the collection"(group-access/add-groups! (t2/select-one :model/DataApp :name "demo") [(:id (perms/all-users-group))])(is (some #(= "demo" (:name %)) (mt/user-http-request :rasta :get 200 "ee/apps")))))))--(deftest typed-schema-keys-are-the-same-on-every-instance-test- (mt/with-premium-features #{:data-apps}- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/Card]- (let [{collection-id :resource_collection_id} (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "demo"})- mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp (mt/id :venues)))- _ (create-question! collection-id "Café crème" query)- twins [(create-question! collection-id "Twin" query) (create-question! collection-id "Twin" query)]- symbols (create-question! collection-id "???" query)- body (mt/user-http-request :crowberto :get 200 "ee/apps/demo/typed-schema")- eid-part #(str/replace (:entity_id %) "-" "")]- (testing "a name keeps its letters, whatever their script"- (is (str/includes? body " caféCrème: defineQuery({")))- (testing "names that collide, or that have no letters, are told apart by entity ID"- (doseq [twin twins]- (is (str/includes? body (str " twin_" (eid-part twin) ": defineQuery({"))))- (is (str/includes? body (str " entity_" (eid-part symbols) ": defineQuery({")))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.cljdeleted file mode 100644index 31f269c2fc6..00000000000--- a/enterprise/backend/test/metabase_enterprise/data_apps/apps_test.clj+++ /dev/null@@ -1,16 +0,0 @@-(ns metabase-enterprise.data-apps.apps-test- (:require- [clojure.test :refer :all]- [metabase-enterprise.data-apps.apps :as data-apps.apps]- [metabase.test :as mt]- [toucan2.core :as t2]))--(set! *warn-on-reflection* true)--(deftest create-app-refuses-a-taken-slug-test- (mt/with-temp [:model/DataApp {app-name :name} {}]- (let [collection-count (t2/count :model/Collection)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"already exists"- (data-apps.apps/create-app! {:name app-name :display_name "Sales" :bundle_path "dist/index.js"})))- (testing "and creates no collection for it"- (is (= collection-count (t2/count :model/Collection)))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/checks_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/checks_test.cljindex 946e516d094..2d498dec0d4 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/checks_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/checks_test.clj@@ -26,6 +26,10 @@"Request options that mark a request as from the data app of [[do-with-app-collection]]."(as-app "birds"))+(def ^:private as-preview+ "Request options that mark a request as from a data app's dev preview."+ (assoc-in as-data-app [:request-options :headers "x-metabase-data-app-dev"] "true"))+(def ^:private error-formats"The format of the error message for each kind of entity a data app may not use."{:cards "A data app can use only the cards in its own collection, not the cards %s."@@ -42,7 +46,7 @@(defn- card-error"The error message for a data app's run of the card with `card-id`."[card-id]- (format "A data app can use only the cards in its own collection and in the Library, not the card %d." card-id))+ (format "A data app can use only the cards in its own collection and Library metrics, not the card %d." card-id))(defn- action-error"The error message for a data app's run of the action with `action-id`."@@ -68,10 +72,10 @@(let [mp (mt/metadata-provider)](lib/query mp (lib.metadata/card mp card-id))))-(defn- join- "`query` joined to `joinable`, on the conditions the foreign keys suggest."- [query joinable]- (lib/join query (lib/join-clause joinable)))+(defn- category-name+ "The CATEGORIES.NAME column `query` on VENUES reaches through its foreign key."+ [query]+ (some #(when (= (mt/id :categories :name) (:id %)) %) (lib/breakoutable-columns query)))(defn- do-with-app-card!"Call `f` with the ID of a card on the published VENUES table in the collection of the data app of@@ -108,6 +112,12 @@(testing "a data app's request that names no app, or an app that doesn't exist, is not found"(doseq [options [(as-app nil) (as-app "no-such-app")]](is (= "Not found." (run-query 404 (card-query card-id) options)))))+ (testing "a dev preview's request reads the Library alone, whether its app exists or not"+ (doseq [app-name ["no-such-app" "birds"]+ :let [options (assoc-in (as-app app-name) [:request-options :headers "x-metabase-data-app-dev"] "true")]]+ (is (= "completed" (:status (run-query 202 (-> (table-query :venues) (lib/limit 1)) options))))+ (is (= (format "A data app's dev preview cannot build on cards, not the cards %d." card-id)+ (run-query 400 (card-query card-id) options)))))(testing "an app the user can't read is refused"(is (= "You don't have permissions to do that."(mt/user-http-request :rasta :post 403 "dataset" as-data-app (card-query card-id))))))))@@ -123,25 +133,38 @@endpoint))(is (= (error-message :tables (mt/id :categories)) (mt/user-http-request :crowberto :post 400 "dataset/csv" as-data-app{:query (table-query :categories)}))))- (testing "a join of an unpublished table is refused, from a published table or the app's card"- (doseq [query [(table-query :venues) (card-query card-id)]]- (is (= (error-message :tables (mt/id :categories))- (run-query 400 (join query (lib.metadata/table (mt/metadata-provider) (mt/id :categories))))))))- (testing "the join runs once its table is published"+ (testing "a table reached through a foreign key is refused, from a published table or the app's card"+ (doseq [[label query] [["in a preview" (table-query :venues)] ["in the app" (card-query card-id)]]]+ (let [query (lib/breakout query (category-name query))]+ (is (= (error-message :tables (mt/id :categories))+ (run-query 400 query (if (= label "in a preview") as-preview as-data-app)))+ label))))+ (testing "it is read once it is published"(data-apps.tu/with-published-tables! [(mt/id :categories)]- (is (= "completed" (:status (run-query 202 (-> (table-query :venues)- (join (lib.metadata/table (mt/metadata-provider)- (mt/id :categories)))- (lib/limit 1)))))))))))+ (let [query (table-query :venues)]+ (is (= "completed" (:status (run-query 202 (-> query (lib/breakout (category-name query)) (lib/limit 1))))))))))))-(deftest other-cards-are-refused-test+(deftest explicit-joins-and-custom-columns-are-refused-test(do-with-app-card!(fn [card-id _collection-id]+ (data-apps.tu/with-published-tables! [(mt/id :categories)]+ (let [mp (mt/metadata-provider)]+ (doseq [query [(table-query :venues) (card-query card-id)]]+ (testing "an explicit join, even of a published table"+ (is (= "A data app cannot run queries that join tables explicitly."+ (run-query 400 (lib/join query (lib/join-clause (lib.metadata/table mp (mt/id :categories))))))))+ (testing "a custom column"+ (is (= "A data app cannot run queries with custom columns."+ (run-query 400 (lib/expression query "Double price"+ (lib/* (lib.metadata/field mp (mt/id :venues :price)) 2))))))))))))++(deftest other-cards-are-refused-test+ (do-with-app-card!+ (fn [_card-id _collection-id](mt/with-temp [:model/DataApp {other-collection-id :resource_collection_id} {:name "bees":display_name "Bees":bundle_path "bees.js"}:model/Card {elsewhere-id :id} {:name "Venues elsewhere" :dataset_query (data-apps.tu/venues-query)}- :model/Card {categories-id :id} {:name "Categories elsewhere" :dataset_query (table-query :categories)}:model/Card {other-app-id :id} {:name "Venues of bees":collection_id other-collection-id:dataset_query (data-apps.tu/venues-query)}]@@ -149,10 +172,6 @@(doseq [other-id [elsewhere-id other-app-id]](is (= (error-message :cards other-id)(run-query 400 (card-query other-id))))))- (testing "a join of a card outside the app's collection is refused"- (is (= (error-message :cards categories-id)- (run-query 400 (join (card-query card-id)- (lib.metadata/card (mt/metadata-provider) categories-id))))))(testing "the other app runs its own card"(is (= "completed" (:status (run-query 202 (lib/limit (card-query other-app-id) 1) (as-app "bees"))))))))))@@ -274,6 +293,9 @@(t2/delete! :model/Collection :id (:resource_collection_id app))(is (= (card-error elsewhere-id)(mt/user-http-request :crowberto :post 400 (format "card/%d/query" elsewhere-id) (as-app "wasps"))))))+ (testing "a dev preview runs no saved card"+ (is (= (format "A data app's dev preview cannot use saved cards but Library metrics, not the card %d." elsewhere-id)+ (mt/user-http-request :crowberto :post 400 (format "card/%d/query" elsewhere-id) as-preview))))(testing "an ID of no card is not found, as for any request"(is (= "Not found." (mt/user-http-request :crowberto :post 404 "card/999999999/query" as-data-app))))(testing "a request that is not a data app's still runs the card"@@ -297,206 +319,70 @@(testing "a request that is not a data app's still reads it"(is (=? {:id elsewhere-id} (mt/user-http-request :crowberto :get 200 (format "card/%d" elsewhere-id)))))))))-(def ^:private static-parameter- "A parameter whose values are a static list, so loading them runs no query."- {:id "kind"- :slug "kind"- :name "Kind"- :type :string/=- :values_source_type :static-list- :values_source_config {:values ["bar" "cafe"]}})--(deftest card-parameter-endpoints-check-card-test- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {app-card-id :id} {:collection_id collection-id- :parameters [static-parameter]- :dataset_query (data-apps.tu/venues-query)}- :model/Card {elsewhere-id :id} {:parameters [static-parameter]- :dataset_query (data-apps.tu/venues-query)}]- (testing "the app's card loads its parameter values"- (is (=? {:values [["bar"] ["cafe"]]}- (mt/user-http-request :crowberto :get 200 (format "card/%d/params/kind/values" app-card-id) as-data-app)))- (is (=? {:values [["cafe"]]}- (mt/user-http-request :crowberto :get 200 (format "card/%d/params/kind/search/caf" app-card-id)- as-data-app))))- (testing "a card outside the app's collection is refused"- (is (= (card-error elsewhere-id)- (mt/user-http-request :crowberto :get 400 (format "card/%d/params/kind/values" elsewhere-id) as-data-app)))- (is (= (card-error elsewhere-id)- (mt/user-http-request :crowberto :get 400 (format "card/%d/params/kind/search/caf" elsewhere-id)- as-data-app)))- (is (= (card-error elsewhere-id)- (mt/user-http-request :crowberto :get 400 (format "card/%d/params/kind/remapping?value=bar" elsewhere-id)- as-data-app))))- (testing "a request that is not a data app's still loads the card's parameter values"- (is (=? {:values [["bar"] ["cafe"]]}- (mt/user-http-request :crowberto :get 200 (format "card/%d/params/kind/values" elsewhere-id))))))))))--(defn- legacy-field-ref- "The legacy ref of the field with `field-id`, as parameters store it."- [field-id]- (let [mp (mt/metadata-provider)]- (lib/->legacy-MBQL (lib/ref (lib.metadata/field mp field-id)))))--(defn- card-source-parameter- "A parameter whose values come from the names of the venues card with `card-id`."- [card-id]- {:id "venue"- :slug "venue"- :name "Venue"- :type :string/=- :values_source_type :card- :values_source_config {:card_id card-id :value_field (legacy-field-ref (mt/id :venues :name))}})-(deftest card-endpoints-allow-library-metrics-test(do-with-app-collection(fn [_collection-id](data-apps.tu/do-with-sources!(fn [{:keys [metric-id]}]- (testing "a Library metric, its metadata and its run are open to a data app"- (is (=? {:id metric-id} (mt/user-http-request :crowberto :get 200 (format "card/%d" metric-id) as-data-app)))- (is (map? (mt/user-http-request :crowberto :get 200 (format "card/%d/query_metadata" metric-id) as-data-app)))- (is (=? {:id (str "card__" metric-id)}- (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" metric-id) as-data-app)))- (is (= "completed" (:status (mt/user-http-request :crowberto :post 202 (format "card/%d/query" metric-id)- as-data-app)))))+ (testing "a Library metric and its metadata are open to an app and its dev preview, as the SDK reads them"+ (doseq [options [as-data-app as-preview]+ url ["card/%d" "card/%d/query_metadata" "table/card__%d/query_metadata"]]+ (is (map? (mt/user-http-request :crowberto :get 200 (format url metric-id) options)) url)))(mt/with-temp [:model/Card {outside-id :id} {:name "Venue count elsewhere":type :metric:database_id (mt/id):dataset_query (lib/aggregate (data-apps.tu/venues-query) (lib/count))}](testing "a metric outside the Library is refused"- (doseq [url ["card/%d" "card/%d/query_metadata" "table/card__%d/query_metadata"]]- (is (= (card-error outside-id)- (mt/user-http-request :crowberto :get 400 (format url outside-id) as-data-app))- url))))- (let [library-id (:id (collections/library-collection))- dashboards-id (t2/select-one-pk :model/Collection- :location (str "/" library-id "/")- :type collections/library-dashboards-collection-type)]- (mt/with-temp [:model/Dashboard dashboard {:collection_id dashboards-id}- :model/Card {question-id :id} {:collection_id dashboards-id- :dashboard_id (:id dashboard)- :dataset_query (data-apps.tu/venues-query)}]- (testing "a dashboard question in the Library is open to the card endpoints"- (is (=? {:id question-id} (mt/user-http-request :crowberto :get 200 (format "card/%d" question-id) as-data-app)))- (is (=? {:id (str "card__" question-id)}- (mt/user-http-request :crowberto :get 200 (format "table/card__%d/query_metadata" question-id)- as-data-app))))- (testing "but not as a source of parameter values"- (is (= (format "A data app cannot take parameter values from the dashboard question %d." question-id)- (mt/user-http-request :crowberto :post 400 "dataset/parameter/values" as-data-app- {:parameter (card-source-parameter question-id)}))))- (testing "nor as a source card of a query"- (is (= (error-message :cards question-id)- (run-query 400 (card-query question-id))))))))))))--(deftest adhoc-parameter-endpoints-check-values-source-test- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {source-id :id} {:collection_id collection-id- :dataset_query (data-apps.tu/venues-query)}- :model/Card {elsewhere-id :id} {:dataset_query (data-apps.tu/venues-query)}]- (testing "a static list loads as is"- (is (=? {:values [["bar"] ["cafe"]]}- (mt/user-http-request :crowberto :post 200 "dataset/parameter/values" as-data-app- {:parameter static-parameter}))))- (testing "values from a card of the app load, from any other card are refused"- (is (seq (:values (mt/user-http-request :crowberto :post 200 "dataset/parameter/values" as-data-app- {:parameter (card-source-parameter source-id)}))))- (doseq [[url body] [["dataset/parameter/values" {}]- ["dataset/parameter/search/Red" {}]- ["dataset/parameter/remapping" {:value "Red"}]]]- (is (= (card-error elsewhere-id)- (mt/user-http-request :crowberto :post 400 url as-data-app- (assoc body :parameter (card-source-parameter elsewhere-id))))- url)))- (let [parameter {:id "name" :type :string/=}]- (testing "values from a field of a published table load, from any other field are refused"- (is (seq (:values (mt/user-http-request :crowberto :post 200 "dataset/parameter/values" as-data-app- {:parameter parameter :field_ids [(mt/id :venues :name)]}))))- (doseq [[url body] [["dataset/parameter/values" {}]- ["dataset/parameter/search/Red" {}]- ["dataset/parameter/remapping" {:value "Red"}]]]- (is (= (format "A data app can read only fields of tables published to the Library, not the field %d."- (mt/id :categories :name))- (mt/user-http-request :crowberto :post 400 url as-data-app- (assoc body :parameter parameter :field_ids [(mt/id :categories :name)])))- url)))- (testing "a request that is not a data app's still loads the values of any field"- (is (seq (:values (mt/user-http-request :crowberto :post 200 "dataset/parameter/values"- {:parameter parameter :field_ids [(mt/id :categories :name)]})))))))))))--(deftest card-parameter-endpoints-check-values-source-card-test- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {source-id :id} {:collection_id collection-id- :dataset_query (data-apps.tu/venues-query)}- :model/Card {card-id :id} {:collection_id collection-id- :parameters [(card-source-parameter source-id)]- :dataset_query (data-apps.tu/venues-query)}]- (testing "a parameter whose values come from a card of the app loads them"- (is (seq (:values (mt/user-http-request :crowberto :get 200 (format "card/%d/params/venue/values" card-id)- as-data-app)))))- (testing "a parameter whose values come from a card outside the app's collection is refused"- (t2/update! :model/Card :id source-id {:collection_id nil})- (doseq [url ["card/%d/params/venue/values" "card/%d/params/venue/search/Red" "card/%d/params/venue/remapping?value=Red"]]- (is (= (card-error source-id)- (mt/user-http-request :crowberto :get 400 (format url card-id) as-data-app))- url))))))))--(defn- field-parameter- "A parameter whose values come from the field with `field-id`."- [field-id]- {:id "field"- :slug "field"- :name "Field"- :type :string/=- :target [:dimension (legacy-field-ref field-id)]})--(deftest card-parameter-endpoints-check-values-source-field-test- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {published-id :id} {:collection_id collection-id- :parameters [(field-parameter (mt/id :venues :name))]- :dataset_query (data-apps.tu/venues-query)}- :model/Card {unpublished-id :id} {:collection_id collection-id- :parameters [(field-parameter (mt/id :checkins :date))]- :dataset_query (data-apps.tu/venues-query)}]- (testing "a parameter whose values come from a field of a published table loads them"- (is (seq (:values (mt/user-http-request :crowberto :get 200 (format "card/%d/params/field/values" published-id)- as-data-app)))))- (testing "a parameter whose values come from a field of an unpublished table is refused"- (is (= (format "A data app can read only fields of tables published to the Library, not the field %d."- (mt/id :checkins :date))- (mt/user-http-request :crowberto :get 400 (format "card/%d/params/field/values" unpublished-id)- as-data-app)))))))))+ (is (= (card-error outside-id)+ (mt/user-http-request :crowberto :get 400 (format "card/%d" outside-id) as-data-app))))))))))++(deftest out-of-scope-endpoints-test+ (testing "parameter values, dashboards, the native editor's snippets and autocompletion, and timelines are no part of a+ data app's surface"+ (do-with-app-card!+ (fn [card-id _collection-id]+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}]+ (doseq [[method url body] [[:get (format "card/%d/params/kind/values" card-id)]+ [:get (format "card/%d/params/kind/search/caf" card-id)]+ [:get (format "card/%d/params/kind/remapping?value=bar" card-id)]+ [:post "dataset/parameter/values" {:parameter {:id "kind" :type :string/=}}]+ [:post "dataset/parameter/search/caf" {:parameter {:id "kind" :type :string/=}}]+ [:post "dataset/parameter/remapping" {:parameter {:id "kind" :type :string/=} :value "bar"}]+ [:get (format "dashboard/%d" dashboard-id)]+ [:get (format "dashboard/%d/query_metadata" dashboard-id)]+ [:get "native-query-snippet"]+ [:get (format "database/%d/autocomplete_suggestions?prefix=ven" (mt/id))]+ [:get (format "database/%d/card_autocomplete_suggestions?query=ven" (mt/id))]+ [:get "timeline"]]]+ (is (= "scope_not_permitted"+ (:error (if body+ (mt/user-http-request :crowberto method 403 url as-data-app body)+ (mt/user-http-request :crowberto method 403 url as-data-app))))+ url)))))))(deftest refusal-names-large-id-without-grouping-test(do-with-app-card!(fn [_card-id _collection-id](mt/with-temp [:model/Card {elsewhere-id :id} {:id 1234567 :dataset_query (data-apps.tu/venues-query)}](testing "an ID of a thousand or more appears as it is, not as 1,234,567"- (is (= "A data app can use only the cards in its own collection and in the Library, not the card 1234567."+ (is (= "A data app can use only the cards in its own collection and Library metrics, not the card 1234567."(mt/user-http-request :crowberto :post 400 (format "card/%d/query" elsewhere-id) as-data-app))))))))(defn- do-with-rename-action!- "Call `f` with the ID of a temp query action, on no model, that renames a category to itself, in the collection with- `collection-id`."+ "Call `f` with the ID of a temp implicit action, on no model, that updates a category, in the collection with+ `collection-id`, with the category Table published to the Library."[collection-id f]- (mt/with-temp [:model/Action {action-id :id} {:name "Rename category"- :type :query- :collection_id collection-id}- :model/QueryAction _ {:action_id action-id- :database_id (mt/id)- :dataset_query (lib/native-query- (mt/metadata-provider)- "UPDATE categories SET name = name WHERE id = 1")}]- (f action-id)))+ (data-apps.tu/with-published-tables! [(mt/id :categories)]+ (mt/with-temp [:model/Action {action-id :id} {:name "Update category"+ :type :implicit+ :collection_id collection-id}+ :model/ImplicitAction _ {:action_id action-id+ :kind "row/update"+ :table_id (mt/id :categories)}]+ (f action-id))))++(def ^:private category-parameters+ {:id 1 :name "African"})(deftest action-endpoints-run-app-action-test(mt/with-actions-test-data-and-actions-enabled@@ -506,19 +392,19 @@collection-id(fn [action-id](testing "the app's action runs, and its values endpoint answers"- (is (= {:rows-affected 1}+ (is (= {:rows-updated 1}(mt/user-http-request :crowberto :post 200 (format "action/%d/execute" action-id) as-data-app- {:parameters {}})))- (is (= {}+ {:parameters category-parameters})))+ (is (= category-parameters(mt/user-http-request :crowberto :post 200 (format "action/%d/execute/values" action-id)- as-data-app {:parameters {}}))))+ as-data-app {:parameters category-parameters}))))(testing "by its entity ID too"- (is (= {:rows-affected 1}+ (is (= {:rows-updated 1}(mt/user-http-request :crowberto :post 200(format "action/%s/execute"(t2/select-one-fn :entity_id :model/Action :id action-id))as-data-app- {:parameters {}}))))))))))+ {:parameters category-parameters}))))))))))(deftest action-endpoints-refuse-other-actions-test(mt/with-actions-test-data-and-actions-enabled@@ -531,17 +417,42 @@(testing "an action outside the app's collection is refused"(is (= (action-error elsewhere-id)(mt/user-http-request :crowberto :post 400 (format "action/%d/execute" elsewhere-id) as-data-app- {:parameters {}})))+ {:parameters category-parameters})))(is (= (action-error elsewhere-id)(mt/user-http-request :crowberto :post 400 (format "action/%d/execute/values" elsewhere-id)- as-data-app {:parameters {}}))))+ as-data-app {:parameters category-parameters}))))(testing "an ID of no action is not found, as for any request"(is (= "Not found." (mt/user-http-request :crowberto :post 404 "action/999999999/execute" as-data-app- {:parameters {}}))))+ {:parameters category-parameters}))))(testing "a request that is not a data app's still runs the action"- (is (= {:rows-affected 1}+ (is (= {:rows-updated 1}(mt/user-http-request :crowberto :post 200 (format "action/%d/execute" elsewhere-id)- {:parameters {}})))))))))))+ {:parameters category-parameters})))))))))))++(deftest preview-runs-only-adhoc-implicit-actions-on-published-tables-test+ (mt/with-actions-test-data-and-actions-enabled+ (do-with-app-collection+ (fn [collection-id]+ (let [adhoc {:name "Rename" :type "implicit" :kind "row/update" :table_id (mt/id :categories)}]+ (testing "a dev preview runs no ad-hoc action on an unpublished table"+ (is (= (format "A data app can write only to tables published to the Library, not the table %d." (mt/id :categories))+ (mt/user-http-request :crowberto :post 400 "action/execute" as-preview+ {:action adhoc :parameters category-parameters}))))+ (do-with-rename-action!+ collection-id+ (fn [action-id]+ (testing "a dev preview runs an ad-hoc implicit action on a published table"+ (is (=? {:rows-updated some?}+ (mt/user-http-request :crowberto :post 200 "action/execute" as-preview+ {:action adhoc :parameters category-parameters}))))+ (testing "nor a saved one, even the app's"+ (is (= (format "A data app's dev preview can run only ad-hoc actions, not the action %d." action-id)+ (mt/user-http-request :crowberto :post 400 (format "action/%d/execute" action-id) as-preview+ {:parameters category-parameters}))))+ (testing "an app runs no ad-hoc action"+ (is (= "A data app can run only the actions in its own collection, not ad-hoc ones."+ (mt/user-http-request :crowberto :post 400 "action/execute" as-data-app+ {:action adhoc :parameters category-parameters})))))))))))(deftest action-read-endpoints-hold-to-app-actions-test(mt/with-actions-test-data-and-actions-enabled@@ -583,7 +494,7 @@(mt/user-http-request :crowberto :get 400 (format "action/%d" elsewhere-id) (as-app "wasps"))))(is (= (action-error elsewhere-id)(mt/user-http-request :crowberto :post 400 (format "action/%d/execute" elsewhere-id) (as-app "wasps")- {:parameters {}})))))))))))+ {:parameters category-parameters})))))))))))(deftest table-and-field-endpoints-check-published-tables-test(do-with-app-collection@@ -672,31 +583,6 @@(is (= (format "A data app can read only databases with tables published to the Library, not the database %d." (:id db))(mt/user-http-request :crowberto :get 400 (format "database/%d" (:id db)) as-data-app))))))))-(deftest database-autocomplete-endpoints-suggest-only-published-tables-test- (do-with-app-collection- (fn [_collection-id]- (mt/with-temp [:model/Database db {:engine :h2 :details {}}- :model/Table published {:db_id (:id db) :name "ZEBRA_PUBLISHED"}- :model/Table unpublished {:db_id (:id db) :name "ZEBRA_UNPUBLISHED"}- :model/Field _published-field {:table_id (:id published) :name "ZEBRA_SEEN"}- :model/Field _unpublished-field {:table_id (:id unpublished) :name "ZEBRA_HIDDEN"}- :model/Card card {:name "Zebra autocomplete card"}]- (data-apps.tu/with-published-tables! [(:id published)]- (let [url (format "database/%d/autocomplete_suggestions" (:id db))]- (testing "table and field suggestions hold only published tables and their fields"- (is (= #{"ZEBRA_PUBLISHED" "ZEBRA_SEEN"}- (set (map first (mt/user-http-request :crowberto :get 200 url as-data-app :prefix "zebra")))))- (is (= #{"ZEBRA_PUBLISHED" "ZEBRA_SEEN"}- (set (map first (mt/user-http-request :crowberto :get 200 url as-data-app :substring "ebra"))))))- (testing "a request that is not a data app's still suggests unpublished tables and their fields"- (is (= #{"ZEBRA_PUBLISHED" "ZEBRA_UNPUBLISHED" "ZEBRA_SEEN" "ZEBRA_HIDDEN"}- (set (map first (mt/user-http-request :crowberto :get 200 url :prefix "zebra"))))))))- (let [url (format "database/%d/card_autocomplete_suggestions" (mt/id))]- (testing "card suggestions are empty"- (is (= [] (mt/user-http-request :crowberto :get 200 url as-data-app :query "zebra autocomplete"))))- (testing "a request that is not a data app's still suggests cards"- (is (some #(= (:id card) (:id %)) (mt/user-http-request :crowberto :get 200 url :query "zebra autocomplete")))))))))-(defn- do-with-zebras!"Call `f` with a temp table published to the Library, one unpublished, a metric in the Library and one outside it, allnamed Zebra, as `{:published :unpublished :metric :outside-metric}`."@@ -859,54 +745,6 @@(is (contains? found ["card" (:id root-card)])))(is (contains? (set (map :id (mt/user-http-request :crowberto :get 200 "collection"))) (:id outside))))))))))))-(deftest dashboard-endpoints-allow-only-library-dashboards-test- (do-with-app-collection- (fn [_collection-id]- (data-apps.tu/do-with-library!- (fn [_library]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (let [library-id (:id (collections/library-collection))- dashboards-id (t2/select-one-pk :model/Collection- :location (str "/" library-id "/")- :type collections/library-dashboards-collection-type)]- (mt/with-temp [:model/Dashboard library {:collection_id dashboards-id :parameters [static-parameter]}- :model/Card question {:collection_id dashboards-id- :dashboard_id (:id library)- :dataset_query (data-apps.tu/venues-query)}- :model/DashboardCard dashcard {:dashboard_id (:id library) :card_id (:id question)}- :model/Dashboard outside {:parameters [static-parameter]}- :model/Card card {:dataset_query (data-apps.tu/venues-query)}- :model/DashboardCard outside-dashcard {:dashboard_id (:id outside) :card_id (:id card)}]- (testing "a dashboard in the Library, its metadata, parameter values and dashcard runs are open to a data app"- (is (=? {:id (:id library)} (mt/user-http-request :crowberto :get 200 (format "dashboard/%d" (:id library)) as-data-app)))- (is (map? (mt/user-http-request :crowberto :get 200 (format "dashboard/%d/query_metadata" (:id library)) as-data-app)))- (is (=? {:values [["bar"] ["cafe"]]}- (mt/user-http-request :crowberto :get 200 (format "dashboard/%d/params/kind/values" (:id library))- as-data-app)))- (is (= "completed" (:status (mt/user-http-request :crowberto :post 202- (format "dashboard/%d/dashcard/%d/card/%d/query"- (:id library) (:id dashcard) (:id question))- as-data-app)))))- (testing "a dashboard outside the Library is refused"- (doseq [[method url] [[:get (format "dashboard/%d" (:id outside))]- [:get (format "dashboard/%d/query_metadata" (:id outside))]- [:get (format "dashboard/%d/params/kind/values" (:id outside))]- [:get (format "dashboard/%d/params/kind/search/caf" (:id outside))]- [:post (format "dashboard/%d/dashcard/%d/card/%d/query"- (:id outside) (:id outside-dashcard) (:id card))]]]- (is (= (format "A data app can use only the dashboards in the Library, not the dashboard %d." (:id outside))- (mt/user-http-request :crowberto method 400 url as-data-app))- url)))- (testing "valid filter fields are open only for fields of published tables"- (is (map? (mt/user-http-request :crowberto :get 200 "dashboard/params/valid-filter-fields" as-data-app- :filtered (mt/id :venues :name) :filtering (mt/id :venues :price))))- (is (= (format "A data app can read only fields of tables published to the Library, not the field %d."- (mt/id :categories :name))- (mt/user-http-request :crowberto :get 400 "dashboard/params/valid-filter-fields" as-data-app- :filtered (mt/id :categories :name) :filtering (mt/id :venues :price)))))- (testing "a request that is not a data app's still reads the other dashboard"- (is (=? {:id (:id outside)} (mt/user-http-request :crowberto :get 200 (format "dashboard/%d" (:id outside))))))))))))))-(deftest without-data-apps-feature-test(testing "without the data-apps feature a data app's queries are not checked"(mt/with-premium-features #{}diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/generate_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/generate_test.cljnew file mode 100644index 00000000000..8df0d8e6ed1--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/generate_test.clj@@ -0,0 +1,69 @@+(ns metabase-enterprise.data-apps.generate-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase-enterprise.data-apps.test-util :as data-apps.tu]+ [metabase.test :as mt]))++(set! *warn-on-reflection* true)++(def ^:private collection-entity-id "AppCollection12345678")++(deftest generate-schema-test+ (mt/with-premium-features #{:data-apps}+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (testing "a non-superuser cannot generate an app's files"+ (mt/user-http-request :rasta :get 403 "ee/apps/generate/schema"))+ (let [[{:keys [path contents]} :as files] (mt/user-http-request :crowberto :get 200 "ee/apps/generate/schema")]+ (is (= 1 (count files)))+ (is (= "src/metabase.schema.ts" path))+ (testing "the schema holds the published tables with their fields, and the Library's metrics"+ (is (str/includes? contents "const tables = {"))+ (is (str/includes? contents (str "id: " (mt/id :venues))))+ (is (str/includes? contents (str "fieldId: " (mt/id :venues :name))))+ (is (str/includes? contents "const metrics = {")))+ (testing "and no actions"+ (is (not (str/includes? contents "actions"))))))))++(deftest generate-queries-test+ (mt/with-premium-features #{:data-apps}+ (data-apps.tu/with-published-tables! [(mt/id :venues)]+ (let [definition {:entityId "VenuesByCategory12345"+ :query {:stages [{:source {:type "table" :id (mt/id :venues) :name "Venues"}+ :aggregations [{:type "operator" :operator "count" :args []}]+ :breakouts [{:type "column"+ :name "CATEGORY_ID"+ :fieldId (mt/id :venues :category_id)+ :displayName "Category ID"+ :jsType "number"}]}]}}+ [{:keys [path contents]} :as files]+ (mt/user-http-request :crowberto :post 200 "ee/apps/generate/queries"+ {:collection collection-entity-id+ :queries {:venuesByCategory definition}})]+ (is (= 1 (count files)))+ (testing "a question is named after its export and filed in the app's collection by its entity ID"+ (is (= "venuesbycategory.yaml" path))+ (is (str/includes? contents "name: venuesByCategory\n"))+ (is (str/includes? contents "entity_id: VenuesByCategory12345\n"))+ (is (str/includes? contents (str "collection_id: " collection-entity-id "\n"))))+ (testing "its query is the definition's, with portable references"+ (is (str/includes? contents "- count"))+ (is (str/includes? contents "- CATEGORY_ID")))))))++(deftest generate-actions-test+ (mt/with-premium-features #{:data-apps}+ (let [[{:keys [path contents]} :as files]+ (mt/user-http-request :crowberto :post 200 "ee/apps/generate/actions"+ {:collection collection-entity-id+ :actions {:updateVenue {:entityId "UpdateVenue1234567890"+ :kind "row/update"+ :table {:id (mt/id :venues) :name "Venues"}}}})]+ (is (= 1 (count files)))+ (testing "an implicit action is named after its export and filed in the app's collection by its entity ID"+ (is (= "updatevenue.yaml" path))+ (is (str/includes? contents "name: updateVenue\n"))+ (is (str/includes? contents "entity_id: UpdateVenue1234567890\n"))+ (is (str/includes? contents (str "collection_id: " collection-entity-id "\n")))+ (is (str/includes? contents "type: implicit\n"))+ (is (str/includes? contents "kind: row/update"))+ (is (str/includes? contents "- VENUES"))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.cljindex b70956d439b..d30fb94af2f 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj@@ -33,22 +33,21 @@[[app-sym table-ids] & body]`(do-with-app-reading! ~table-ids (fn [~app-sym] ~@body)))-(defn- do-with-query-action!- "Call `f` with a query action running `sql` in the collection with `collection-id`."- [collection-id sql f]- (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Run" :collection_id collection-id}- :model/QueryAction _ {:action_id action-id- :database_id (mt/id)- :dataset_query (lib/native-query (mt/metadata-provider) sql)}]+(defn- do-with-implicit-action!+ "Call `f` with an implicit action of no model that deletes from the Table with `table-id`, in the collection with+ `collection-id`."+ [collection-id table-id f]+ (mt/with-temp [:model/Action {action-id :id} {:type :implicit :name "Delete" :collection_id collection-id}+ :model/ImplicitAction _ {:action_id action-id :kind "row/delete" :table_id table-id}](f)))(deftest group-permission-warnings-walk-the-dependency-graph-test(testing "the warnings list the tables a question reads, the tables only a Library metric it aggregates reads, and the- tables a query action writes"+ table an implicit action writes"(mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}(mt/with-no-data-perms-for-all-users!(mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]- (data-apps.tu/with-published-tables! [(mt/id :orders) (mt/id :venues)]+ (data-apps.tu/with-published-tables! [(mt/id :orders) (mt/id :venues) (mt/id :checkins)](data-apps.tu/do-with-library!(fn [{:keys [metrics-id]}](let [mp (mt/metadata-provider)]@@ -68,8 +67,8 @@(mt/with-temp [:model/Card _ {:collection_id collection-id:dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))(lib/aggregate (lib.metadata/metric mp metric-id)))}]- (do-with-query-action!- collection-id "DELETE FROM CHECKINS WHERE ID = 1"+ (do-with-implicit-action!+ collection-id (mt/id :checkins)(fn [](deps.test/synchronously-run-dependency-job!)(perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)@@ -79,47 +78,6 @@{:id (mt/id :orders)} {:id (mt/id :venues)}]}](group-access/permission-warnings app)))))))))))))))))-(deftest group-permission-warnings-include-tables-in-optional-clauses-test- (testing "the tables an optional clause of a query action names count, whether or not its parameter is set"- (mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}- (mt/with-no-data-perms-for-all-users!- (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]- (doseq [sql ["UPDATE VENUES SET NAME = 'x' [[WHERE ID IN (SELECT VENUE_ID FROM CHECKINS WHERE ID = {{id}})]]"- "UPDATE VENUES v SET NAME = 'x' WHERE v.ID IN (SELECT v2.ID FROM VENUES v2 [[JOIN CHECKINS c ON c.VENUE_ID = v2.ID AND c.ID = {{id}}]])"]]- (testing sql- (mt/with-temp [:model/DataApp {collection-id :resource_collection_id :as app}- {}- :model/PermissionsGroup group {}]- (do-with-query-action!- collection-id sql- (fn []- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (deps.test/synchronously-run-dependency-job!)- (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)} {:id (mt/id :venues)}]}]- (group-access/permission-warnings app)))))))))))))--(deftest group-permission-warnings-follow-snippet-edit-test- (testing "after a snippet edit and the jobs, the warnings list the tables of the snippet's new SQL in a query action"- (mt/test-helpers-set-global-values!- (mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}- (mt/with-no-data-perms-for-all-users!- (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus :model/AnalysisFinding]- (mt/with-temp [:model/NativeQuerySnippet snippet {:name "birds source" :content "VENUES"}- :model/DataApp {collection-id :resource_collection_id :as app}- {}- :model/PermissionsGroup group {}]- (do-with-query-action!- collection-id "DELETE FROM {{snippet: birds source}} WHERE ID = 1"- (fn []- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (deps.test/synchronously-run-dependency-job!)- (t2/update! :model/NativeQuerySnippet :id (:id snippet) {:content "CHECKINS"})- (deps.test/synchronously-run-dependency-job!)- (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)}]}]- (group-access/permission-warnings app))))))))))))-(deftest group-permission-warnings-exclude-inactive-tables-test(mt/with-premium-features #{:data-apps :advanced-permissions}(mt/with-no-data-perms-for-all-users!diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.cljdeleted file mode 100644index 446cab3da6e..00000000000--- a/enterprise/backend/test/metabase_enterprise/data_apps/invariants_test.clj+++ /dev/null@@ -1,365 +0,0 @@-(ns metabase-enterprise.data-apps.invariants-test- "What a data app's collection may hold, enforced by the model hooks, so a write through Toucan, which is what a- remote-sync pull does, is refused like an API call."- (:require- [clojure.string :as str]- [clojure.test :refer :all]- [metabase-enterprise.data-apps.test-util :as data-apps.tu :refer [do-with-app-collection]]- [metabase.collections.models.collection :as collection]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.test :as mt]- [toucan2.core :as t2]))--(set! *warn-on-reflection* true)--(defn- reading-card- "A native query of the action kind that reads the card with `card-id` through a card template tag."- [card-id]- (let [tag (str "#" card-id)]- (lib/query (mt/metadata-provider)- {:database (mt/id)- :type :native- :native {:query (str "SELECT * FROM {{" tag "}}")- :template-tags {tag {:type :card- :card-id card-id- :name tag- :display-name tag- :id (str (random-uuid))}}}})))--(defn- insert-query-action!- "Insert a query action named `action-name` running `query` in the collection with `collection-id`, as a load does,- with `action-columns` merged into its Action row."- [collection-id action-name query & [action-columns]]- (let [action-id (t2/insert-returning-pk! :model/Action (merge {:name action-name- :type :query- :collection_id collection-id- :creator_id (mt/user->id :crowberto)}- action-columns))]- (t2/insert! :model/QueryAction {:action_id action-id :database_id (mt/id) :dataset_query query})- action-id))--(deftest card-in-apps-collection-holds-query-test- (testing "a card in an app's collection holds a query on a database"- (do-with-app-collection- (fn [collection-id]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must hold a query on a database"- (t2/insert! :model/Card {:name "Empty"- :display "table"- :visualization_settings {}- :creator_id (mt/user->id :crowberto)- :collection_id collection-id- :dataset_query {}})))))))--(deftest action-in-apps-collection-is-neither-archived-nor-public-test- (testing "an action is refused archived or public on insert, not only on update"- (do-with-app-collection- (fn [collection-id]- (let [query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be archived"- (insert-query-action! collection-id "Archived" query {:archived true})))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be made public"- (insert-query-action! collection-id "Public" query- {:public_uuid (str (random-uuid))- :made_public_by_id (mt/user->id :crowberto)})))- (testing "elsewhere both are fine"- (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}]- (is (pos-int? (insert-query-action! other-id "Archived elsewhere" query {:archived true})))- (is (pos-int? (insert-query-action! other-id "Public elsewhere" query- {:public_uuid (str (random-uuid))- :made_public_by_id (mt/user->id :crowberto)}))))))))))--(deftest action-in-apps-collection-takes-no-values-from-card-test- (testing "a parameter of an action in an app's collection takes no values from a card"- (do-with-app-collection- (fn [collection-id]- (mt/with-temp [:model/Card {card-id :id} {:name "Elsewhere"}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't take a parameter's values from a card"- (insert-query-action!- collection-id "Rename" (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = {{name}}")- {:parameters [{:id "name"- :slug "name"- :type :string/=- :values_source_type "card"- :values_source_config {:card_id card-id}}]}))))))))--(deftest action-in-apps-collection-reads-only-apps-cards-test- (testing "a query action in an app's collection reads no card outside it, when it is written as a load writes it"- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {outside-id :id} {:name "Elsewhere"}- :model/Card {own-id :id} {:name "Own"- :collection_id collection-id- :dataset_query (data-apps.tu/venues-query)}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (insert-query-action! collection-id "Reads outside" (reading-card outside-id))))- (let [action-id (insert-query-action! collection-id "Reads own" (reading-card own-id))]- (testing "changing its query to read a card outside is refused"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (t2/update! :model/QueryAction :action_id action-id {:dataset_query (reading-card outside-id)})))))- (testing "moving an action that reads a card outside into the collection is refused"- (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}]- (let [action-id (insert-query-action! other-id "Moved in" (reading-card outside-id))]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (t2/update! :model/Action :id action-id {:collection_id collection-id})))- (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))))))--(defn- insert-implicit-action!- "Insert an implicit action of no model named `action-name` that inserts into the Table with `table-id`, in the- collection with `collection-id`, as a load does."- [collection-id action-name table-id]- (let [action-id (t2/insert-returning-pk! :model/Action {:name action-name- :type :implicit- :collection_id collection-id- :creator_id (mt/user->id :crowberto)})]- (t2/insert! :model/ImplicitAction {:action_id action-id :kind "row/create" :table_id table-id})- action-id))--(deftest implicit-action-in-apps-collection-writes-to-published-table-test- (testing "an implicit action of no model in an app's collection writes only to a table published to the Library"- (do-with-app-collection- (fn [collection-id]- (testing "an unpublished table is refused"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"published to the Library"- (t2/with-transaction [_conn]- (insert-implicit-action! collection-id "Unpublished" (mt/id :venues)))))- (is (not (t2/exists? :model/Action :collection_id collection-id :name "Unpublished"))))- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (testing "a published table goes in"- (let [action-id (insert-implicit-action! collection-id "Published" (mt/id :venues))]- (is (= (mt/id :venues) (t2/select-one-fn :table_id :model/ImplicitAction :action_id action-id)))- (testing "and the action can't move to an unpublished table"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"published to the Library"- (t2/update! :model/ImplicitAction {:action_id action-id} {:table_id (mt/id :categories)})))- (is (= (mt/id :venues) (t2/select-one-fn :table_id :model/ImplicitAction :action_id action-id)))))))))))--(deftest create-implicit-action-in-apps-collection-api-test- (testing "POST /api/action creates an implicit action of no model in an app's collection on a published table"- (mt/with-actions-enabled- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (let [{action-id :id} (mt/user-http-request :crowberto :post 200 "action"- {:name "Add venue"- :type "implicit"- :kind "row/create"- :table_id (mt/id :venues)- :collection_id collection-id})]- (is (=? {:type :implicit- :model_id nil- :collection_id collection-id}- (t2/select-one :model/Action :id action-id)))- (is (= (mt/id :venues) (t2/select-one-fn :table_id :model/ImplicitAction :action_id action-id))))))))))--(deftest moving-implicit-action-into-apps-collection-is-checked-test- (testing "an implicit action moved into an app's collection, as a pull may move one, needs a published table too"- (do-with-app-collection- (fn [collection-id]- (mt/with-model-cleanup [:model/Action]- (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}]- (let [action-id (insert-implicit-action! other-id "Elsewhere" (mt/id :venues))]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"published to the Library"- (t2/update! :model/Action :id action-id {:collection_id collection-id})))- (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id)))- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (t2/update! :model/Action :id action-id {:collection_id collection-id})- (is (= collection-id (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))))--(deftest two-data-apps-cannot-share-collection-test- (testing "the database refuses a second app on a collection another app already owns"- (mt/with-model-cleanup [:model/DataApp]- (do-with-app-collection- (fn [collection-id]- (let [insert! (fn [slug collection-id]- (t2/query-one {:insert-into :data_app- :values [{:name slug- :display_name slug- :bundle_path "index.js"- :entity_id (data-apps.tu/app-entity-id slug)- :resource_collection_id collection-id- :created_at :%now- :updated_at :%now}]}))]- (mt/with-temp [:model/Collection {free-id :id} {:namespace :data-apps}]- (testing "the same row on a collection no app owns goes in"- (insert! "sparrows" free-id)- (is (t2/exists? :model/DataApp :name "sparrows")))- (is (thrown? Exception (t2/with-transaction [_conn]- (insert! "finches" collection-id))))- (is (not (t2/exists? :model/DataApp :name "finches"))))))))))--(deftest data-apps-collection-is-root-collection-of-its-namespace-test- (testing "an app given an existing collection gets it only when it is a plain top-level collection of data apps that- no other app has"- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp]- (mt/with-temp [:model/Collection {default-id :id} {:name "Finance"}- :model/Collection {root-id :id} {:name "Root" :namespace :data-apps}- :model/Collection {archived-id :id} {:name "Archived" :namespace :data-apps :archived true}- :model/Collection {official-id :id} {:name "Official" :namespace :data-apps :authority_level "official"}- :model/Collection {synced-id :id} {:name "Synced" :namespace :data-apps :is_remote_synced true}]- (let [app! (fn [slug collection-id]- (t2/insert-returning-pk! :model/DataApp {:name slug- :display_name slug- :bundle_path "index.js"- :resource_collection_id collection-id}))]- (doseq [[label collection-id] [["a default-namespace collection" default-id]- ["an archived collection" archived-id]- ["an official collection" official-id]]]- (testing label- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a top-level collection of data apps"- (app! "refused" collection-id)))))- (testing "a remote-synced one is fine, as remote sync marks an app's collection"- (is (pos-int? (app! "synced" synced-id))))- (testing "a top-level collection of data apps is fine"- (is (pos-int? (app! "accepted" root-id)))- (testing "but not for a second app"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"already belongs to another data app"- (app! "second" root-id)))))))))))--(deftest app-collection-stays-at-namespace-root-test- (testing "an app's collection lives in the data-apps namespace, so it can't be filed under a regular collection,- where trashing the ancestor would take the app's copies with it"- (mt/with-temp [:model/Collection {ancestor-id :id} {}- :model/DataApp {collection-id :resource_collection_id} {}]- (mt/with-test-user :crowberto- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"cannot move a data app's collection"- (collection/move-collection!- (t2/select-one :model/Collection :id collection-id)- (collection/children-location (t2/select-one :model/Collection :id ancestor-id))))))- (is (= "/" (t2/select-one-fn :location :model/Collection :id collection-id))))))--(deftest content-of-data-apps-namespace-is-checked-before-its-app-loads-test- (testing "a load may write a collection's content before the app that owns it, so the namespace decides"- (mt/with-premium-features #{:data-apps}- (mt/with-temp [:model/Collection {collection-id :id} {:name "Not yet an app's" :namespace :data-apps}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be built with the query builder"- (mt/with-temp [:model/Card _ {:collection_id collection-id- :dataset_query (lib/native-query (mt/metadata-provider) "SELECT 1")}])))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be archived"- (insert-query-action! collection-id "Archived" (lib/native-query (mt/metadata-provider) "SELECT 1")- {:archived true})))))))--(deftest apps-collection-stays-what-it-was-given-as-test- (testing "an app's collection can't later be moved, typed or made a sample, but remote sync may sync it and a restore may clear its- archive marker"- (do-with-app-collection- (fn [collection-id]- (mt/with-temp [:model/Collection {other-id :id} {:name "Other" :namespace :data-apps}]- (doseq [changes [{:type "library-metrics"} {:is_sample true}- {:location (str "/" other-id "/")}]]- (testing (pr-str changes)- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"- (t2/update! :model/Collection :id collection-id changes)))))- (t2/update! :model/Collection :id collection-id {:archive_operation_id nil :is_remote_synced true :description "Birds"})- (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :id collection-id)))- (is (= "Birds" (t2/select-one-fn :description :model/Collection :id collection-id))))))))--(deftest moving-action-into-apps-collection-is-checked-test- (testing "an action moved into an app's collection, as a pull may move one, meets the same rules as one created there"- (do-with-app-collection- (fn [collection-id]- (mt/with-temp [:model/Collection {other-id :id} {:namespace :data-actions}- :model/Card {card-id :id} {:name "Elsewhere"}]- (let [query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = {{name}}")]- (doseq [[label columns message] [["archived" {:archived true} #"can't be archived"]- ["public" {:public_uuid (str (random-uuid)) :made_public_by_id (mt/user->id :crowberto)}- #"can't be made public"]- ["taking parameter values from a card"- {:parameters [{:id "name" :slug "name" :type :string/=- :values_source_type "card"- :values_source_config {:card_id card-id}}]}- #"can't take a parameter's values from a card"]]]- (testing label- (let [action-id (insert-query-action! other-id (str "Moved " label) query columns)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo message- (t2/update! :model/Action :id action-id {:collection_id collection-id})))- (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))- (testing "an action of a model"- (mt/with-actions-enabled- (mt/with-temp [:model/Collection {model-coll :id} {:name "Models"}- :model/Card {model-id :id} {:type :model :collection_id model-coll- :dataset_query (data-apps.tu/venues-query)}]- (let [action-id (t2/insert-returning-pk! :model/Action {:name "Of a model" :type :query :model_id model-id- :creator_id (mt/user->id :crowberto)})]- (t2/insert! :model/QueryAction {:action_id action-id :database_id (mt/id)- :dataset_query (lib/native-query (mt/metadata-provider) "SELECT 1")})- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"goes in the model's collection"- (t2/update! :model/Action :id action-id {:collection_id collection-id})))- (is (= model-coll (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))))--(deftest card-in-apps-collection-reads-only-published-tables-through-its-macros-test- (testing "segments, measures and remapped columns count as reads of the tables they reach"- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (let [mp (mt/metadata-provider)- venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))- category (some #(when (= (mt/id :categories :name) (:id %)) %) (lib/filterable-columns venues))- save! (fn [query]- (mt/with-temp [:model/Card _ {:name "Saved" :collection_id collection-id :dataset_query query}]))]- (mt/with-temp [:model/Segment {segment-id :id} {:name "Bars"- :table_id (mt/id :venues)- :definition (lib/filter venues (lib/= category "Bar"))}- :model/Measure {measure-id :id} {:name "Categories"- :table_id (mt/id :venues)- :definition (lib/aggregate venues (lib/distinct category))}]- (let [mp (mt/metadata-provider)]- (testing "a segment that filters on an unpublished table"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"- (save! (lib/filter venues (lib.metadata/segment mp segment-id))))))- (testing "a measure that aggregates one"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"- (save! (lib/aggregate venues (lib.metadata/measure mp measure-id))))))))- (testing "a column remapped to an unpublished table's column"- (mt/with-temp [:model/Dimension _ {:field_id (mt/id :venues :category_id)- :name "Category"- :type :external- :human_readable_field_id (mt/id :categories :name)}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not CATEGORIES"- (save! (lib/query (mt/metadata-provider)- (lib.metadata/table (mt/metadata-provider) (mt/id :venues))))))))))))))--(deftest card-in-apps-collection-stays-editable-after-its-table-is-unpublished-test- (testing "a later change that leaves the query alone keeps working; one that changes it is checked again"- (do-with-app-collection- (fn [collection-id]- (let [card-id (data-apps.tu/with-published-tables! [(mt/id :venues)]- (t2/insert-returning-pk! :model/Card {:name "Venues"- :display "table"- :visualization_settings {}- :creator_id (mt/user->id :crowberto)- :collection_id collection-id- :dataset_query (data-apps.tu/venues-query)}))]- (t2/update! :model/Card :id card-id {:name "Renamed" :description "Still venues"})- (is (= "Renamed" (t2/select-one-fn :name :model/Card :id card-id)))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not VENUES"- (t2/update! :model/Card :id card-id {:dataset_query (lib/limit (data-apps.tu/venues-query) 10)}))))))))--(deftest card-in-apps-collection-is-in-no-document-test- (testing "a card that belongs to a document elsewhere can't be in an app's collection"- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Document {document-id :id} {:name "Notes"}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"in no dashboard or document"- (t2/insert! :model/Card {:name "In a document"- :display "table"- :visualization_settings {}- :creator_id (mt/user->id :crowberto)- :collection_id collection-id- :document_id document-id- :dataset_query (data-apps.tu/venues-query)})))))))))--(deftest refusals-name-cards-test- (testing "a refusal names a card by its name, not only by its id on this instance"- (do-with-app-collection- (fn [collection-id]- (data-apps.tu/with-published-tables! [(mt/id :venues)]- (mt/with-temp [:model/Card {card-id :id} {:name "Venues elsewhere" :dataset_query (data-apps.tu/venues-query)}]- (let [message (try (mt/with-temp [:model/Card _ {:collection_id collection-id- :dataset_query (lib/query (mt/metadata-provider)- (lib.metadata/card (mt/metadata-provider) card-id))}])- nil- (catch clojure.lang.ExceptionInfo e (ex-message e)))]- (is (str/includes? message (format "\"Venues elsewhere\" (%d)" card-id))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.cljindex be803cf8d9d..bcbe5a9febe 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj@@ -34,11 +34,11 @@(is (thrown-with-msg? clojure.lang.ExceptionInfo #"bundle hash is computed from its bundle"(t2/update! :model/DataApp :id id {:bundle_hash "stale"})))))))-(deftest insert-requires-resource-collection-test- (testing "the API creates an app's collection, so an insert without one is refused"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"needs a collection of its own"- (mt/with-temp [:model/DataApp _ {:name "m" :resource_collection_id nil}])))- (is (not (t2/exists? :model/DataApp :name "m")))))+(deftest insert-creates-resource-collection-test+ (testing "an app inserted without a collection gets a top-level collection of data apps of its own"+ (mt/with-temp [:model/DataApp {collection-id :resource_collection_id} {:name "m"}]+ (is (=? {:name "Data App: m" :namespace :data-apps :location "/"}+ (t2/select-one :model/Collection :id collection-id))))))(deftest the-resource-collection-cannot-change-test(mt/with-temp [:model/Collection {other-id :id} {:name "Other" :namespace :data-apps}@@ -133,3 +133,53 @@(is (not (mi/can-read? :model/DataApp id)))(is (not (mi/can-write? :model/DataApp id)))(is (not (mi/can-create? :model/DataApp {})))))))++(deftest two-data-apps-cannot-share-collection-test+ (testing "the database refuses a second app on a collection another app already owns"+ (mt/with-model-cleanup [:model/DataApp]+ (mt/with-temp [:model/DataApp {collection-id :resource_collection_id} {}]+ (let [insert! (fn [slug collection-id]+ (t2/query-one {:insert-into :data_app+ :values [{:name slug+ :display_name slug+ :bundle_path "index.js"+ :entity_id (subs (str slug "-" (apply str (repeat 21 "a"))) 0 21)+ :resource_collection_id collection-id+ :created_at :%now+ :updated_at :%now}]}))]+ (mt/with-temp [:model/Collection {free-id :id} {:namespace :data-apps}]+ (testing "the same row on a collection no app owns goes in"+ (insert! "sparrows" free-id)+ (is (t2/exists? :model/DataApp :name "sparrows")))+ (is (thrown? Exception (t2/with-transaction [_conn]+ (insert! "finches" collection-id))))+ (is (not (t2/exists? :model/DataApp :name "finches")))))))))++(deftest data-apps-collection-is-root-collection-of-its-namespace-test+ (testing "an app given an existing collection gets it only when it is a plain top-level collection of data apps that+ no other app has"+ (mt/with-premium-features #{:data-apps}+ (mt/with-model-cleanup [:model/DataApp]+ (mt/with-temp [:model/Collection {default-id :id} {:name "Finance"}+ :model/Collection {root-id :id} {:name "Root" :namespace :data-apps}+ :model/Collection {archived-id :id} {:name "Archived" :namespace :data-apps :archived true}+ :model/Collection {official-id :id} {:name "Official" :namespace :data-apps :authority_level "official"}+ :model/Collection {synced-id :id} {:name "Synced" :namespace :data-apps :is_remote_synced true}]+ (let [app! (fn [slug collection-id]+ (t2/insert-returning-pk! :model/DataApp {:name slug+ :display_name slug+ :bundle_path "index.js"+ :resource_collection_id collection-id}))]+ (doseq [[label collection-id] [["a default-namespace collection" default-id]+ ["an archived collection" archived-id]+ ["an official collection" official-id]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a top-level collection of data apps"+ (app! "refused" collection-id)))))+ (testing "a remote-synced one is fine, as remote sync marks an app's collection"+ (is (pos-int? (app! "synced" synced-id))))+ (testing "a top-level collection of data apps is fine"+ (is (pos-int? (app! "accepted" root-id)))+ (testing "but not for a second app"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"already belongs to another data app"+ (app! "second" root-id)))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.cljindex f940300fe0f..9560442027a 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj@@ -180,18 +180,6 @@(import! dump-dir)(is (nil? (t2/select-one-fn :description :model/DataApp :id (:id app))))))))-(deftest import-does-not-take-over-an-app-made-on-the-instance-test- (mt/with-premium-features #{:data-apps}- (ts/with-random-dump-dir [dump-dir "data-app-takeover-"]- (mt/with-temp [:model/DataApp app {:name "sales-ops"}]- (write-app-files! dump-dir "sales-ops" (app-yaml "Ld3cXiYs9n8HP3q3FvC7R" "sales-ops") {"dist/index.js" "B"})- (let [e (try (import! dump-dir) nil (catch clojure.lang.ExceptionInfo e e))]- (is (re-find #"Failed to load" (ex-message e)))- (testing "the pull says what to do, rather than failing on the slug's unique index"- (is (re-find #"named \"sales-ops\" already exists on this instance"- (ex-message (ex-cause e))))))- (is (=? {:entity_id (:entity_id app)} (t2/select-one :model/DataApp :id (:id app))))))))-(deftest export-includes-data-apps-test(mt/with-temp [:model/DataApp {app-entity-id :entity_id} {}](is (some #(= [{:model "DataApp" :id app-entity-id}] (map (fn [m] (dissoc m :label)) (:serdes/meta %)))@@ -211,11 +199,9 @@:dataset_query (lib/query (mt/metadata-provider)(lib.metadata/table (mt/metadata-provider) (mt/id :venues)))}:model/Action {action-id :id action-eid :entity_id}- {:name "Rename venue" :type :query :collection_id collection-id}- :model/QueryAction _- {:action_id action-id- :database_id (mt/id)- :dataset_query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")}]+ {:name "Rename venue" :type :implicit :collection_id collection-id}+ :model/ImplicitAction _+ {:action_id action-id :kind "row/update" :table_id (mt/id :venues)}](export! dump-dir :with-collections? true)(testing "the files sit under the collection's directory of the data-apps namespace"(doseq [path ["data_app__sales_ops.yaml" "data_app__sales_ops/venues_list.yaml"diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.cljindex a21317362c9..1d05d9e5878 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/test_util.clj@@ -2,7 +2,7 @@(:require[clojure.set :as set][clojure.string :as str]- [metabase-enterprise.data-apps.apps :as data-apps.apps]+ [metabase-enterprise.data-apps.db :as data-apps.db][metabase-enterprise.data-studio.db :as data-studio.db][metabase-enterprise.serialization.core :as serialization][metabase-enterprise.serialization.dump :as serialization.dump]@@ -65,7 +65,7 @@:as options}](let [entity-id (or entity_id (app-entity-id dir))collection (if (contains? options :collection) collection (collection-entity-id dir))- collection-name (data-apps.apps/collection-name slug)+ collection-name (data-apps.db/resource-collection-name slug)resources (if (contains? options :resources)resources(when collection {(collection-path collection-name) (collection-file collection collection-name)}))]@@ -179,8 +179,8 @@(t2/delete! :model/Collection :id [:in (cons (:id library) (map :id children))]))))))(defn do-with-sources!- "Call `f` with what a data app uses from outside its collection, a venues metric in the Library and a query action- that belongs to no model, and with what it can't, a venues model and an action on it, as+ "Call `f` with what a data app uses from outside its collection, a venues metric in the Library and an implicit action+ on venues that belongs to no model, and with what it can't, a venues model and an action on it, as`{:metric-id :action-id :model-id :model-action-id}`."[f](do-with-library!@@ -197,11 +197,13 @@:database_id (mt/id):dataset_query query}](f {:metric-id metric-id- :action-id (actions/insert! {:name "Rename venue"- :type :query- :database_id (mt/id)- :dataset_query (lib/native-query mp "UPDATE venues SET name = {{name}}")- :parameters [{:id "name" :slug "name" :type :string/=}]})+ :action-id (let [action-id (t2/insert-returning-pk! :model/Action {:name "Update venue"+ :type :implicit+ :creator_id (mt/user->id :crowberto)})]+ (t2/insert! :model/ImplicitAction {:action_id action-id+ :kind "row/update"+ :table_id (mt/id :venues)})+ action-id):model-id model-id:model-action-id (actions/insert! {:name "Create venue" :type :implicit :kind :row/create:model_id model-id})}))))))diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/dependency_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/dependency_test.cljindex 1a2c1cd8093..0c883bf04f0 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/dependency_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/dependency_test.clj@@ -1214,10 +1214,8 @@{:name "birds" :display_name "Birds" :bundle_path "birds.js"}:model/Collection {other-collection-id :id} {}:model/Card {card-id :id} {:dataset_query venues-query :collection_id collection-id}- :model/Action {action-id :id} {:type :query :name "Delete venue" :collection_id collection-id}- :model/QueryAction _ {:action_id action-id- :database_id (mt/id)- :dataset_query (lib/native-query mp "DELETE FROM venues WHERE id = 1")}]+ :model/Action {action-id :id} {:type :implicit :name "Update venue" :collection_id collection-id}+ :model/ImplicitAction _ {:action_id action-id :kind "row/update" :table_id (mt/id :venues)}](testing "an app depends on the cards and actions in its resource collection"(assert-pending :data-app app-id)(deps.test/synchronously-run-dependency-job!)diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.cljindex ff401e75d40..9ce60fc5de3 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj@@ -5,18 +5,12 @@(:require[clojure.string :as str][clojure.test :refer :all]- [metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.data-apps.test-util :as data-apps.tu]- [metabase-enterprise.dependencies.test-util :as deps.test][metabase-enterprise.remote-sync.impl :as impl][metabase-enterprise.remote-sync.models.remote-sync-task :as remote-sync.task][metabase-enterprise.remote-sync.source.protocol :as source.p][metabase-enterprise.remote-sync.test-helpers :as test-helpers]- [metabase.actions.core :as actions]- [metabase.collections.models.collection :as collection][metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.permissions.core :as perms][metabase.remote-sync.test-util :as remote-sync.tu][metabase.search.test-util :as search.tu][metabase.test :as mt]@@ -38,11 +32,6 @@[eid slug bundle](data-apps.tu/app-files slug {:name "Sales" :path "dist/index.js" :bundle bundle :entity_id eid}))-(defn- app-files-in- "The files of `repo` that serialization writes for data apps: under `data_apps/` and `collections/data_apps/`."- [repo]- (into #{} (filter #(re-find #"^(data_apps|collections/data_apps)/" %)) (keys repo)))-(defn- new-task! [sync-task-type](t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type sync-task-type :initiated_by (mt/user->id :rasta)}))@@ -55,15 +44,6 @@(impl/handle-task-result! result task)result))-(defn- export!- "Export to `mock` under a fresh task, complete it, and return the result."- [mock]- (t2/delete! :model/RemoteSyncTask)- (let [task (new-task! "export")- result (impl/export! (source.p/snapshot mock) task "export")]- (impl/handle-task-result! result task)- result))-(defn- bundle-text [slug](when-let [^bytes bundle (t2/select-one-fn :bundle [:model/DataApp :bundle] :name slug)](String. bundle "UTF-8")))@@ -105,76 +85,6 @@(is (= "v1" (remote-sync.task/last-version)))(is (= "BUNDLE-V2" (bundle-text "sales")))))))-(deftest export-writes-and-removes-data-app-files-test- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" {}})- repo #(get @(:files-atom mock) "main")]- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "sales"- :display_name "Sales"- :bundle_path "dist/index.js"})- (mt/user-http-request :crowberto :put 200 "ee/apps/sales/bundle" {:bundle "BUNDLE"})- (testing "a created app is exported as its manifest, its bundle file, and its collection's file"- (is (= :success (:status (export! mock))))- (is (=? {:slug "sales" :name "Sales" :path "dist/index.js" :collection string?}- (yaml/parse-string (get (repo) "data_apps/sales/data_app.yaml"))))- (is (= "BUNDLE" (get (repo) "data_apps/sales/dist/index.js")))- (is (=? {:name "Data App: sales" :namespace "data-apps"}- (yaml/parse-string (get (repo) "collections/data_apps/data_app__sales.yaml")))))- (testing "an updated bundle is exported"- (mt/user-http-request :crowberto :put 200 "ee/apps/sales/bundle" {:bundle "BUNDLE-V2"})- (is (= :success (:status (export! mock))))- (is (= "BUNDLE-V2" (get (repo) "data_apps/sales/dist/index.js"))))- (testing "a deleted app's files are removed from the repo, and the other apps' files stay"- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "ops"- :display_name "Ops"- :bundle_path "app.js"})- (mt/user-http-request :crowberto :put 200 "ee/apps/ops/bundle" {:bundle "OPS"})- (mt/user-http-request :crowberto :delete 204 "ee/apps/sales")- (is (= :success (:status (export! mock))))- (is (= #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js" "collections/data_apps/data_app__ops.yaml"}- (app-files-in (repo))))))))--(deftest export-keeps-files-serialization-does-not-own-test- (testing "an export rewrites an app's manifest and bundle but leaves the app's source next to them alone"- (with-data-apps-sync- (let [source {"data_apps/sales/src/App.tsx" "export const App = () => null;"- "data_apps/sales/package.json" "{}"- "data_apps/sales/pnpm-lock.yaml" "lockfileVersion: '9.0'\n"- "data_apps/sales/deploy/k8s.yaml" "a: 1\n---\nb: [unterminated\n"}- mock (test-helpers/create-mock-source- :initial-files {"main" (merge (app-tree sales-eid "sales" "BUNDLE-V1") source)})- repo #(get @(:files-atom mock) "main")]- (is (= :success (:status (import-at! mock "main" :force? true))))- (mt/user-http-request :crowberto :put 200 "ee/apps/sales/bundle" {:bundle "BUNDLE-V2"})- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "ops"- :display_name "Ops"- :bundle_path "app.js"})- (mt/user-http-request :crowberto :put 200 "ee/apps/ops/bundle" {:bundle "OPS"})- (is (= :success (:status (export! mock))))- (is (= "BUNDLE-V2" (get (repo) "data_apps/sales/dist/index.js")))- (is (= source (select-keys (repo) (keys source))))- (testing "deleting the app removes only the files serialization owns"- (mt/user-http-request :crowberto :delete 204 "ee/apps/sales")- (is (= :success (:status (export! mock))))- (is (= (into #{"data_apps/ops/data_app.yaml" "data_apps/ops/app.js" "collections/data_apps/data_app__ops.yaml"}- (keys source))- (app-files-in (repo)))))))))--(deftest pull-refuses-to-delete-an-unpushed-app-test- (testing "a pull whose repo lacks an app created here but not pushed yet is a conflict, not a silent delete"- (with-data-apps-sync- (let [app (app-tree sales-eid "sales" "BUNDLE")- src (test-helpers/versioned-source :trees {"v0" app "v1" (assoc app "README.md" "x")} :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "ops"- :display_name "Ops"- :bundle_path "app.js"})- (mt/user-http-request :crowberto :put 200 "ee/apps/ops/bundle" {:bundle "OPS"})- (is (=? {:status :conflict} (import-at! src "v1")))- (is (t2/exists? :model/DataApp :name "ops"))))))--;;; ------------------------------------------------- Resources --------------------------------------------------(def ^:private shop-collection-eid (data-apps.tu/collection-entity-id "shop"))(def ^:private question-eid "shopQuestionListVenue")@@ -223,34 +133,11 @@(is (not= collection-id (t2/select-one-fn :collection_id :model/Card :id metric-id)))(is (not (t2/exists? :model/Card :collection_id collection-id :type :metric))))(testing "the action is copied into the collection, on no model"- (is (=? {:type :query :collection_id collection-id :model_id nil}+ (is (=? {:type :implicit :collection_id collection-id :model_id nil}(t2/select-one :model/Action :entity_id (copy-eid action-id)))))(testing "the source is untouched"(is (nil? (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))))-(deftest pull-updates-and-removes-resources-with-their-files-test- (with-data-apps-sync- (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}- {:entity_id "shopQuestionOther0001" :name "Other" :query (venues-stages)}]- [])- file-of (fn [eid] (some #(when (str/includes? % eid) %) (keys resources)))- renamed (update resources (file-of question-eid) #(yaml/generate-string (assoc (yaml/parse-string %) :name "Renamed")))- src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)- "v1" (shop-tree renamed)- "v2" (shop-tree (dissoc renamed (file-of "shopQuestionOther0001")))}- :current "v0")]- (let [result (import-at! src "v0" :force? true)]- (is (= :success (:status result)) (:message result)))- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]- (testing "a changed file updates the card in place"- (is (= :success (:status (import-at! src "v1"))))- (is (= "Renamed" (t2/select-one-fn :name :model/Card :id card-id))))- (testing "a card whose file is gone is removed"- (is (= :success (:status (import-at! src "v2"))))- (is (t2/exists? :model/Card :id card-id))- (is (not (t2/exists? :model/Card :entity_id "shopQuestionOther0001"))))))))-(deftest pull-refuses-resources-an-app-may-not-hold-test(testing "a resource the Card hook refuses fails the pull"(with-data-apps-sync@@ -265,336 +152,6 @@(is (str/includes? (:message result) "not archived"))(is (not (t2/exists? :model/Card :entity_id question-eid)))))))-(deftest export-writes-an-apps-resources-under-its-collection-test- (testing "what an app's collection holds is exported under collections/data_apps/, like any namespace's content"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" {}})- repo #(get @(:files-atom mock) "main")]- (mt/user-http-request :crowberto :post 200 "ee/apps" {:name "sales"- :display_name "Sales"- :bundle_path "dist/index.js"})- (mt/user-http-request :crowberto :put 200 "ee/apps/sales/bundle" {:bundle "BUNDLE"})- (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "sales")- mp (mt/metadata-provider)]- (mt/with-temp [:model/Card _ {:name "Venues list"- :type :question- :collection_id collection-id- :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}]- (actions/insert! {:name "Rename venue"- :type :query- :collection_id collection-id- :database_id (mt/id)- :dataset_query (lib/native-query mp "UPDATE venues SET name = 'x'")})- (is (= :success (:status (export! mock))))- (is (= #{"data_apps/sales/data_app.yaml"- "data_apps/sales/dist/index.js"- "collections/data_apps/data_app__sales.yaml"- "collections/data_apps/data_app__sales/venues_list.yaml"- "collections/data_apps/data_app__sales/rename_venue.yaml"}- (app-files-in (repo))))- (is (empty? (filter #(re-find #"^(collections/main|actions)/" %) (keys (repo))))- "nothing of the app's lands in the default namespace's directories")))))))--(defn- question-resources []- (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- []))--(defn- resource-files- "The files of data apps' collections in `mock`'s repository."- [mock]- (into #{} (filter #(re-find #"^collections/data_apps/" %)) (keys (get @(:files-atom mock) "main"))))--(defn- file-named- "Whether a file of `mock`'s repository under `collections/data_apps/` has a name starting with `stem`."- [mock stem]- (some #(str/starts-with? (last (str/split % #"/")) stem) (resource-files mock)))--(deftest pull-reaches-permission-warnings-test- (testing "once the jobs run after a pull, the warnings list the tables the app's question and action name"- (with-data-apps-sync- (mt/with-premium-features #{:data-apps :advanced-permissions :dependencies}- (mt/with-no-data-perms-for-all-users!- (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]- (let [action-id (actions/insert! {:name "Clear checkins"- :type :query- :database_id (mt/id)- :dataset_query (lib/native-query (mt/metadata-provider)- "DELETE FROM checkins WHERE id = {{id}}")- :parameters [{:id "id" :slug "id" :type :number/=}]})- resources (data-apps.tu/build-resources- shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- [action-id])- src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :success (:status result)) (:message result))- (mt/with-temp [:model/PermissionsGroup group {}]- (let [app (t2/select-one :model/DataApp :name "shop")]- (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)- (group-access/add-groups! app [(:id group)])- (deps.test/synchronously-run-dependency-job!)- (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :checkins)} {:id (mt/id :venues)}]}]- (group-access/permission-warnings app))))))))))))--(deftest an-apps-collection-is-written-by-admins-test- (testing "an admin can write an app's collection, its cards and its actions, unless the instance is read-only"- (with-data-apps-sync- (data-apps.tu/do-with-sources!- (fn [{:keys [action-id]}]- (let [resources (data-apps.tu/build-resources- shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- [action-id])- src (test-helpers/versioned-source :trees {"v0" (shop-tree resources)} :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (let [collection-id (shop-collection-id)- card-id (t2/select-one-pk :model/Card :entity_id question-eid)- copy-id (t2/select-one-pk :model/Action :collection_id collection-id)- writes! (fn [status can-write?]- (is (=? {:can_write can-write?}- (mt/user-http-request :crowberto :get 200 (str "collection/" collection-id))))- (is (=? {:can_write can-write?}- (mt/user-http-request :crowberto :get 200 (str "card/" card-id))))- (mt/user-http-request :crowberto :put status (str "card/" card-id) {:description "edited here"})- (mt/with-actions-enabled- (mt/user-http-request :crowberto :put status (str "action/" copy-id) {:name "Renamed"}))- (mt/user-http-request :rasta :put 403 (str "card/" card-id) {:description "mine"}))]- (testing "on a read-write instance"- (mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-url "https://example.com/repo.git"]- (writes! 200 true)))- (testing "without remote sync"- (mt/with-temporary-setting-values [remote-sync-url nil]- (writes! 200 true)))- (testing "on a read-only instance"- (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url "https://example.com/repo.git"]- (writes! 403 false))))))))))--(deftest a-copy-of-an-apps-card-elsewhere-is-a-card-like-any-other-test- (testing "copying a card out of an app's collection needs only read access to it"- (with-data-apps-sync- (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")- mp (mt/metadata-provider)]- (is (= :success (:status (import-at! src "v0" :force? true))))- (is (=? {:collection_id nil}- (mt/user-http-request :crowberto :post 200 "card"- {:name "Copy"- :display "table"- :visualization_settings {}- :dataset_query (lib/->legacy-MBQL- (lib/query mp (lib.metadata/table mp (mt/id :venues))))- :source_card_id (t2/select-one-pk :model/Card :entity_id question-eid)})))))))--(deftest a-pull-changes-a-card-in-an-apps-collection-test- (testing "the permissions that refuse every write to an app's collection don't stop a pull"- (with-data-apps-sync- (let [resources (fn [card-name]- (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name card-name :query (venues-stages)}]- []))- src (test-helpers/versioned-source :trees {"v0" (shop-tree (resources "VenuesList"))- "v1" (shop-tree (resources "Renamed on read-write"))- "v2" (shop-tree (resources "Renamed on read-only"))}- :current "v0")- card-name #(t2/select-one-fn :name :model/Card :entity_id question-eid)]- (is (= :success (:status (import-at! src "v0" :force? true))))- (testing "on a read-write instance"- (is (= :success (:status (import-at! src "v1"))))- (is (= "Renamed on read-write" (card-name))))- (testing "on a read-only instance"- (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url "https://example.com/repo.git"]- (is (= :success (:status (import-at! src "v2"))))- (is (= "Renamed on read-only" (card-name)))))))))--(deftest an-apps-collection-holds-only-what-a-pull-accepts-test- (testing "what the resource validator would refuse on a pull can't be saved into an app's collection, by a write the- permissions don't cover"- (with-data-apps-sync- (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (let [collection-id (shop-collection-id)- card! (fn [card-type]- (mt/with-temp [:model/Card {card-id :id} {:name "Saved here"- :type card-type- :collection_id collection-id- :dataset_query (data-apps.tu/venues-query)}]- (t2/select-one :model/Card :id card-id)))]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions, metrics, and query actions"- (mt/with-temp [:model/Dashboard _ {:name "Saved here" :collection_id collection-id}])))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions, metrics, and query actions"- (mt/with-temp [:model/Collection _ {:name "Inside"- :location (collection/children-location- (t2/select-one :model/Collection :id collection-id))- :namespace "data-apps"}])))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"data app's collection" (card! :model)))- (is (=? {:collection_id collection-id :type :question} (card! :question)))- (testing "a bookmark is not content"- (mt/user-http-request :crowberto :post 200 (str "bookmark/collection/" collection-id)))- (testing "with the library feature too, whose check runs in the same place"- (mt/with-additional-premium-features #{:library}- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"data app's collection" (card! :model)))))- (testing "a question a load checks as a possible dashboard question, before its dashboard is known, is a question here"- (is (= (collection/check-allowed-content :question collection-id)- (collection/check-allowed-content :dashboard-question collection-id))))- (mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Elsewhere"}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions, metrics, and query actions"- (t2/update! :model/Dashboard :id dashboard-id {:collection_id collection-id})))- (is (nil? (t2/select-one-fn :collection_id :model/Dashboard :id dashboard-id)))))))))--(deftest a-card-in-an-apps-collection-stays-what-a-pull-accepts-test- (testing "a card there can't become what the resource validator refuses, since the next export would write it"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})- mp (mt/metadata-provider)- q (lib/->legacy-MBQL (lib/query mp (lib.metadata/table mp (mt/id :venues))))]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)- collection-id (shop-collection-id)]- (testing "archived, public, or a model"- (mt/with-temporary-setting-values [enable-public-sharing true]- (mt/user-http-request :crowberto :post 400 (str "card/" card-id "/public_link")))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"- (t2/update! :model/Card :id card-id {:archived true})))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"- (t2/update! :model/Card :id card-id {:type :model})))- (is (=? {:archived false :public_uuid nil :type :question} (t2/select-one :model/Card :id card-id))))- (testing "a card that is already public can't be moved in"- (mt/with-temp [:model/Card {public-id :id} {:name "Already public"- :dataset_query q- :public_uuid (str (random-uuid))- :made_public_by_id (mt/user->id :crowberto)}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"- (t2/update! :model/Card :id public-id {:collection_id collection-id})))- (is (nil? (t2/select-one-fn :collection_id :model/Card :id public-id)))))- (testing "the export keeps its file"- (is (= :success (:status (export! mock))))- (is (file-named mock "venueslist"))- (is (= :success (:status (import-at! mock "main" :force? true)))))- (testing "a card anywhere else still can be archived"- (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}]- (mt/user-http-request :crowberto :put 200 (str "card/" other-id) {:archived true}))))))))--(deftest pull-moves-card-out-of-apps-collection-test- (testing "a pull whose commit moves a card out of an app's collection, into an ordinary synced collection, succeeds"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [synced-eid "shopCardsMovedOutColl"- synced-dir (str "collections/" synced-eid "_moved_out/")- ;; the commit an author pushes: the card's file in an ordinary synced collection- moved-out (reduce-kv (fn [tree path content]- (let [entity (yaml/parse-string content)]- (if (= question-eid (:entity_id entity))- (assoc tree- (str synced-dir "cards/" (last (str/split path #"/")))- (yaml/generate-string (assoc entity :collection_id synced-eid)))- (assoc tree path content))))- {(str synced-dir synced-eid "_moved_out.yaml")- (test-helpers/generate-collection-yaml synced-eid "Moved out" :is-remote-synced true)}- (get @(:files-atom mock) "main"))- src (test-helpers/versioned-source :trees {"v1" moved-out} :current "v1")]- (let [result (import-at! src "v1" :force? true)]- (is (= :success (:status result)) (:message result)))- (is (= (t2/select-one-pk :model/Collection :entity_id synced-eid)- (t2/select-one-fn :collection_id :model/Card :entity_id question-eid))))))))--(deftest pull-refuses-two-apps-that-name-one-collection-test- (with-data-apps-sync- (let [shared (data-apps.tu/collection-entity-id "shared")- app (fn [slug] (data-apps.tu/app-files slug {:name slug :path "index.js" :bundle "B" :collection shared}))- src (test-helpers/versioned-source :trees {"v0" (merge (app "first") (app "second"))} :current "v0")- result (import-at! src "v0" :force? true)]- (testing "the database refuses the second app on the collection the first owns"- (is (= :error (:status result)))- (is (str/includes? (:message result) "already belongs to another data app"))- (is (= 1 (t2/count :model/DataApp :name [:in ["first" "second"]])))))))--(deftest pull-refuses-a-manifest-that-names-a-collection-it-doesnt-define-test- (testing "a manifest with no resource files can't claim a collection that is already here"- (with-data-apps-sync- (mt/with-temp [:model/Collection {collection-id :id, collection-eid :entity_id} {:name "Finance"}- :model/Card {card-id :id} {:name "Finance card" :collection_id collection-id}]- (let [src (test-helpers/versioned-source- :trees {"v0" (data-apps.tu/app-files "shop" {:name "Shop" :path "index.js" :bundle "B"- :collection collection-eid :resources nil})}- :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) "must be a top-level collection of data apps"))- (is (not (t2/exists? :model/DataApp :name "shop")))- (is (t2/exists? :model/Collection :id collection-id))- (is (t2/exists? :model/Card :id card-id)))))))--(deftest pull-refuses-native-question-in-apps-collection-test- (testing "a question in an app's collection is built with the query builder, so a pull refuses one in SQL"- (with-data-apps-sync- (let [resources (question-resources)- path (some #(when (str/includes? % question-eid) %) (keys resources))- parsed (yaml/parse-string (get resources path))- native (assoc parsed :dataset_query {:database (:database (:dataset_query parsed))- :lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/native"- :native "SELECT * FROM venues"}]})- src (test-helpers/versioned-source- :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string native)))}- :current "v0")- result (import-at! src "v0" :force? true)]- (is (= :error (:status result)))- (is (str/includes? (:message result) "must be built with the query builder"))- (is (not (t2/exists? :model/Card :entity_id question-eid)))))))--(deftest pull-loads-a-resource-on-a-database-not-connected-yet-test- (testing "a resource whose database isn't connected yet loads as a card's does, against a stub database and an- inactive table that a later connection and sync fill in"- (with-data-apps-sync- (mt/with-model-cleanup [:model/Database]- (let [db-name "Data app warehouse not connected yet"- resources (question-resources)- path (some #(when (str/includes? % question-eid) %) (keys resources))- elsewhere (-> (yaml/parse-string (get resources path))- (assoc :database_id db-name)- (dissoc :result_metadata)- (assoc-in [:dataset_query :database] db-name)- (assoc-in [:dataset_query :stages 0 :source-table] [db-name "analytics" "accounts"]))- src (test-helpers/versioned-source- :trees {"v0" (shop-tree (assoc resources path (yaml/generate-string elsewhere)))}- :current "v0")- result (import-at! src "v0" :force? true)- db-id (t2/select-one-pk :model/Database :name db-name)- table-id (t2/select-one-pk :model/Table :db_id db-id :schema "analytics" :name "accounts")]- (is (= :success (:status result)) (:message result))- (is (=? {:is_stub true} (t2/select-one :model/Database :id db-id)))- (is (=? {:active false} (t2/select-one :model/Table :id table-id)))- (is (=? {:database_id db-id :collection_id (shop-collection-id)}- (t2/select-one :model/Card :entity_id question-eid))))))))--(deftest an-apps-collection-cant-be-moved-to-the-trash-test- (testing "trashing it would drop the app's resource files on the next export"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [before (resource-files mock)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"- (t2/update! :model/Collection :id (shop-collection-id) {:archived true})))- (is (= :success (:status (export! mock))))- (is (= before (resource-files mock)))- (testing "deleting the app still deletes its collection"- (let [collection-id (shop-collection-id)]- (mt/user-http-request :crowberto :delete 204 "ee/apps/shop")- (is (not (t2/exists? :model/Collection :id collection-id))))))))))--(deftest an-apps-own-yaml-is-left-alone-test- (testing "a YAML file in the app's directory that isn't its manifest is the app's own: not loaded, not removed"- (with-data-apps-sync- (let [own "data_apps/shop/i18n/en.yaml"- mock (test-helpers/create-mock-source- :initial-files {"main" (assoc (shop-tree (question-resources)) own "greeting: hello\n")})]- (let [result (import-at! mock "main" :force? true)]- (is (= :success (:status result)) (:message result)))- (mt/user-http-request :crowberto :put 200 "ee/apps/shop/bundle" {:bundle "B2"})- (is (= :success (:status (export! mock))))- (is (= "greeting: hello\n" (get-in @(:files-atom mock) ["main" own])))))))-(deftest deleting-an-apps-files-deletes-the-app-and-its-collection-test(testing "an author deletes an app by deleting its directory and its collection's files under collections/data_apps/"(with-data-apps-sync@@ -611,215 +168,3 @@(testing "the hook deletes the collection and what it held"(is (not (t2/exists? :model/Collection :id collection-id)))(is (not (t2/exists? :model/Card :entity_id question-eid)))))))))--(deftest deleting-an-apps-directory-without-its-collection-files-still-deletes-the-app-test- (testing "an author deletes an app's directory but leaves its collection's files: the pull doesn't fail, it deletes- the app, and with it its collection and what it held"- (with-data-apps-sync- (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- [])- v0 (shop-tree resources)- v1 (dissoc v0 "data_apps/shop/data_app.yaml" "data_apps/shop/index.js")- src (test-helpers/versioned-source :trees {"v0" v0 "v1" v1} :current "v0")]- (is (= :success (:status (import-at! src "v0" :force? true))))- (let [collection-id (shop-collection-id)]- (is (t2/exists? :model/Card :entity_id question-eid :collection_id collection-id))- (let [result (import-at! src "v1")]- (is (= :success (:status result)) (:message result)))- (is (not (t2/exists? :model/DataApp :name "shop")))- (is (not (t2/exists? :model/Collection :id collection-id)))- (is (not (t2/exists? :model/Card :entity_id question-eid))))))))--(deftest a-read-only-instance-still-serves-the-root-collection-test- (testing "with remote sync read-only, a card in no collection is read and edited as before: nothing there is synced"- (with-data-apps-sync- (mt/with-temp [:model/Card {card-id :id} {:name "In the root" :collection_id nil}]- (mt/with-temporary-setting-values [remote-sync-type :read-only remote-sync-url "https://example.com/repo.git"]- (mt/user-http-request :crowberto :get 200 (str "card/" card-id))- (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:description "edited in the root"}))))))--(deftest card-in-apps-collection-reads-only-library-test- (testing "a card there is a query builder question on tables published to the Library, aggregating only Library- metrics, and based on no other card, whether it is saved or changed"- (with-data-apps-sync- (data-apps.tu/do-with-sources!- (fn [{library-metric-id :metric-id}]- (let [src (test-helpers/versioned-source :trees {"v0" (shop-tree (question-resources))} :current "v0")- mp (mt/metadata-provider)]- (is (= :success (:status (import-at! src "v0" :force? true))))- (mt/with-temp [:model/Card {other-metric-id :id} {:name "Venue count elsewhere"- :type :metric- :dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))- (lib/aggregate (lib/count)))}]- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)- collection-id (shop-collection-id)- mp (mt/metadata-provider)- venues (lib/query mp (lib.metadata/table mp (mt/id :venues)))- save! (fn [query]- (mt/with-temp [:model/Card _ {:name "Saved" :collection_id collection-id :dataset_query query}]))- refused? (fn [message query]- (let [query-before (t2/select-one-fn :dataset_query :model/Card :id card-id)]- (and (is (thrown-with-msg? clojure.lang.ExceptionInfo message (save! query)))- (is (thrown-with-msg? clojure.lang.ExceptionInfo message- (t2/update! :model/Card :id card-id {:dataset_query query})))- (is (= query-before (t2/select-one-fn :dataset_query :model/Card :id card-id))))))]- (testing "a table published to the Library, and a Library metric, are fine"- (save! venues)- (save! (lib/aggregate venues (lib.metadata/metric mp library-metric-id)))- (t2/update! :model/Card :id card-id {:dataset_query (lib/aggregate venues (lib/count))}))- (testing "a table that isn't published is refused"- (refused? #"can read only tables published to the Library, not USERS"- (lib/query mp (lib.metadata/table mp (mt/id :users)))))- (testing "so is one joined explicitly"- (refused? #"can read only tables published to the Library, not CATEGORIES"- (lib/join venues (lib.metadata/table mp (mt/id :categories)))))- (testing "or through a foreign key"- (refused? #"can read only tables published to the Library, not CATEGORIES"- (lib/breakout venues (some #(when (= (mt/id :categories :name) (:id %)) %)- (lib/breakoutable-columns venues)))))- (testing "as is SQL"- (refused? #"must be built with the query builder"- (lib/native-query mp "SELECT * FROM venues")))- (testing "a card as the source, even the app's own"- (refused? #"not the card"- (lib/query mp (lib.metadata/card mp card-id))))- (testing "and a metric outside the Library"- (refused? #"can use only metrics from the Library"- (lib/aggregate venues (lib.metadata/metric mp other-metric-id))))- (testing "a card elsewhere can still read the app's card"- (mt/user-http-request :crowberto :post 200 "card"- {:name "Saved" :type "question" :display "table" :visualization_settings {}- :dataset_query (lib/->legacy-MBQL (lib/query mp (lib.metadata/card mp card-id)))}))))))))))--(deftest a-card-in-an-apps-collection-cant-take-embedding-settings-test- (testing "embedding parameters would make the export write a file every pull refuses, with embedding itself left off"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [card-id (t2/select-one-pk :model/Card :entity_id question-eid)]- (mt/with-temporary-setting-values [enable-embedding-modular true]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question or metric"- (t2/update! :model/Card :id card-id {:embedding_params {}})))- (testing "a card elsewhere takes them"- (mt/with-temp [:model/Card {other-id :id} {:name "Elsewhere"}]- (mt/user-http-request :crowberto :put 200 (str "card/" other-id) {:embedding_params {}}))))- (is (= :success (:status (export! mock))))- (is (= :success (:status (import-at! mock "main" :force? true)))))))))--(deftest an-apps-collection-cant-be-made-official-or-moved-test- (testing "either would make the export write a file every pull refuses"- (with-data-apps-sync- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [collection-id (shop-collection-id)- before (resource-files mock)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"- (t2/update! :model/Collection :id collection-id {:authority_level "official"})))- (mt/with-temp [:model/Collection other {:name "Other root" :namespace :data-apps}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You cannot move a data app's collection"- (collection/move-collection! (t2/select-one :model/Collection :id collection-id)- (collection/children-location other)))))- (is (=? {:authority_level nil :location "/"} (t2/select-one :model/Collection :id collection-id)))- (is (= :success (:status (export! mock))))- (testing "and the export keeps the collection's files"- (is (= before (resource-files mock))))- (is (= :success (:status (import-at! mock "main" :force? true)))))))))--(deftest an-action-in-an-apps-collection-cant-be-archived-test- (testing "an export leaves out an archived action, and the next pull would then delete it from every instance"- (with-data-apps-sync- (data-apps.tu/do-with-sources!- (fn [{:keys [action-id]}]- (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- [action-id])- mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [copy-id (t2/select-one-pk :model/Action :collection_id (shop-collection-id))- before (resource-files mock)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't be archived"- (t2/update! :model/Action :id copy-id {:archived true})))- (testing "the source can still be archived"- (mt/with-actions-enabled- (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived true})))- (is (false? (t2/select-one-fn :archived :model/Action :id copy-id)))- (is (= :success (:status (export! mock))))- (testing "and the export keeps the action's file"- (is (= before (resource-files mock)))))))))))--(deftest an-apps-collection-cant-be-marked-remote-synced-test- (testing "an app's collection is synced with its app, and a pull refuses its file once it says remote-synced"- (with-data-apps-sync- (mt/with-additional-premium-features #{:remote-sync}- (let [mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree (question-resources))})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [collection-id (shop-collection-id)]- (mt/with-dynamic-fn-redefs [impl/finish-remote-config! (constantly nil)]- (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings" {:collections {collection-id true}})- (is (false? (t2/select-one-fn :is_remote_synced :model/Collection :id collection-id)))- (testing "an ordinary collection still can be"- (mt/with-temp [:model/Collection {other-id :id} {:name "Ordinary"}]- (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings" {:collections {other-id true}})- (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :id other-id))))))))))))--(deftest an-action-in-an-apps-collection-stays-what-a-pull-accepts-test- (testing "an action there can't be made public or read a card outside the collection: the next export would write it- into a file every pull refuses"- (with-data-apps-sync- (data-apps.tu/do-with-sources!- (fn [{:keys [action-id]}]- (let [resources (data-apps.tu/build-resources shop-collection-name shop-collection-eid- [{:entity_id question-eid :name "VenuesList" :query (venues-stages)}]- [action-id])- mock (test-helpers/create-mock-source :initial-files {"main" (shop-tree resources)})]- (is (= :success (:status (import-at! mock "main" :force? true))))- (let [copy-id (t2/select-one-pk :model/Action :collection_id (shop-collection-id))- card-id (t2/select-one-pk :model/Card :entity_id question-eid)- reads (fn [id]- (let [tag (str "#" id)]- (lib/query (mt/metadata-provider)- {:database (mt/id)- :type :native- :native {:query (str "SELECT * FROM {{" tag "}}")- :template-tags {tag {:type :card- :card-id id- :name tag- :display-name tag- :id (str (random-uuid))}}}})))]- (mt/with-actions-enabled- (mt/with-temporary-setting-values [enable-public-sharing true]- (mt/user-http-request :crowberto :post 400 (str "action/" copy-id "/public_link"))- (is (nil? (t2/select-one-fn :public_uuid :model/Action :id copy-id)))- (testing "the source action still can be"- (mt/user-http-request :crowberto :post 200 (str "action/" action-id "/public_link"))))- (mt/with-temp [:model/Card {outside-id :id} {:name "Outside"}]- (let [query-before (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can read only the app's own cards"- (actions/update! {:id copy-id :dataset_query (reads outside-id)}- (actions/select-action :id copy-id))))- (is (= query-before (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id)))))- (testing "it can read the app's own card"- (actions/update! {:id copy-id :dataset_query (reads card-id)} (actions/select-action :id copy-id))- (is (= #{card-id}- (into #{} (keep :card-id)- (filter map? (tree-seq coll? seq (t2/select-one-fn :dataset_query :model/QueryAction :action_id copy-id))))))))- (is (= :success (:status (export! mock))))- (is (= :success (:status (import-at! mock "main" :force? true)))))))))))--(deftest pull-loads-app-whose-collection-is-remote-synced-test- (testing "an app's collection may be remote-synced, as remote sync marks it once it syncs the collection, so a pull- that says so loads the app, and the next pull too"- (with-data-apps-sync- (let [tree (shop-tree (question-resources))- coll-file (data-apps.tu/collection-path shop-collection-name)- synced (update tree coll-file #(yaml/generate-string (assoc (yaml/parse-string %) :is_remote_synced true)))- src (test-helpers/versioned-source :trees {"v0" synced "v1" (assoc synced "README.md" "x")} :current "v0")]- (is (contains? tree coll-file) "the fixture writes the collection's file where the test changes it")- (let [result (import-at! src "v0" :force? true)]- (is (= :success (:status result)) (:message result)))- (is (= (shop-collection-id) (t2/select-one-pk :model/Collection :entity_id shop-collection-eid)))- (is (true? (t2/select-one-fn :is_remote_synced :model/Collection :entity_id shop-collection-eid)))- (is (t2/exists? :model/Card :entity_id question-eid :collection_id (shop-collection-id)))- (let [result (import-at! src "v1" :force? true)]- (is (= :success (:status result)) (:message result)))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.cljindex 1a7332e7a36..aea5bf588e1 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/init_test.clj@@ -305,43 +305,3 @@(is (zero? (glossary-rso-count))))))));;; ------------------------------------------- Data app ledger backfill ---------------------------------------------(defn- do-with-untracked-data-apps!- "Runs `f` with the ids of a `:published` and a `:tracked` data app, and the `:published-name` of the first, under- `remote-sync-type` `sync-type`, where only `:tracked` has a DataApp ledger row."- [sync-type f]- (mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"- :remote-sync-type sync-type- :remote-sync-branch "main"]- (mt/with-model-cleanup [:model/RemoteSyncObject]- (mt/with-temp [:model/DataApp {published :id published-name :name} {}- :model/DataApp {tracked :id tracked-name :name} {}]- (t2/delete! :model/RemoteSyncObject :model_type "DataApp")- (t2/insert! :model/RemoteSyncObject {:model_type "DataApp" :model_id tracked :model_name tracked-name- :status "synced" :status_changed_at (t/offset-date-time)})- (mt/with-dynamic-fn-redefs [impl/async-import! (constantly nil)- remote-sync.object/dirty? (constantly false)]- (f {:published published :published-name published-name :tracked tracked}))))))--(defn- data-app-rso-statuses []- (t2/select-fn->fn :model_id :status :model/RemoteSyncObject :model_type "DataApp"))--(deftest remote-sync-init-backfills-data-app-tracking-test- (testing "read-write init tracks every untracked published data app as 'create', once, so the next push writes it"- (do-with-untracked-data-apps!- :read-write- (fn [{:keys [published published-name tracked]}]- (#'init/remote-sync-init)- (is (= {published "create" tracked "synced"} (data-app-rso-statuses)))- (is (=? {:model_name published-name}- (t2/select-one :model/RemoteSyncObject :model_type "DataApp" :model_id published)))- (testing "a second run inserts nothing"- (is (= 0 (rs-events/backfill-data-app-tracking!))))))))--(deftest remote-sync-init-data-app-backfill-skips-read-only-test- (testing "a read-only instance is not backfilled"- (do-with-untracked-data-apps!- :read-only- (fn [{:keys [tracked]}]- (#'init/remote-sync-init)- (is (= {tracked "synced"} (data-app-rso-statuses)))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.cljindex 12942b98179..ee2cc9f653c 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj@@ -375,12 +375,14 @@"Runs `f` with `{:folder :root-action :folder-action :app-action}`: actions without a model in the data actions root,a data actions folder, and a data app collection."[f]- (mt/with-temp [:model/Collection {folder :id} {:name "Billing" :namespace "data-actions" :location "/"}- :model/Collection {app-coll :id} {:name "App" :namespace "data-apps" :location "/"}- :model/Action {root-action :id} {:type :query :name "At root"}- :model/Action {folder-action :id} {:type :query :name "In folder" :collection_id folder}- :model/Action {app-action :id} {:type :query :name "App copy" :collection_id app-coll}]- (f {:folder folder :root-action root-action :folder-action folder-action :app-action app-action})))+ (binding [mi/*deserializing?* true]+ (mt/with-temp [:model/Collection {folder :id} {:name "Billing" :namespace "data-actions" :location "/"}+ :model/Collection {app-coll :id} {:name "App" :namespace "data-apps" :location "/"}+ :model/Action {root-action :id} {:type :query :name "At root"}+ :model/Action {folder-action :id} {:type :query :name "In folder" :collection_id folder}+ :model/Action {app-action :id} {:type :implicit :name "App copy" :collection_id app-coll}+ :model/ImplicitAction _ {:action_id app-action :kind "row/update" :table_id (mt/id :venues)}]+ (f {:folder folder :root-action root-action :folder-action folder-action :app-action app-action}))))(deftest data-action-eligibility-follows-library-test(testing "actions without a model are synced with the Library from the data actions root and namespace"diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsxindex 39ad46b4c42..d8b3645c7fc 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx@@ -99,9 +99,9 @@ describe("DevToolbar closed", () => {);});- it("shows no count when there are no alerts", async () => {+ it("shows no warning or count when there are no alerts", async () => {await setup();- expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);+ expect(getToggle()).toHaveTextContent(/^Diagnostics$/);});});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsxindex 68deea0716c..a088a2d79d9 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DiagnosticsToggle/DiagnosticsToggle.tsx@@ -1,4 +1,3 @@-/* eslint-disable i18next/no-literal-string */import cx from "classnames";import S from "../DevToolbar.module.css";@@ -15,6 +14,6 @@ export const DiagnosticsToggle = ({ count, onOpen }: Props) => (onClick={onOpen}title="Data app diagnostics">- ⚠ Diagnostics{count > 0 ? ` (${count})` : ""}+ {count > 0 ? `⚠ Diagnostics (${count})` : "Diagnostics"}</button>);diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.tsindex a1fd9b46847..03fc89278ab 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts@@ -54,6 +54,7 @@ export {} from "./hooks/public/use-metabase-query";export type {DefinedQuery,+ LegacyQuestionSource,MetabaseLocalFieldReference,MetabaseBreakout,MetabaseDynamicColumn,@@ -66,9 +67,11 @@ export type {UseMetabaseQueryResult,} from "./hooks/public/use-metabase-query";export type {- ActionKindFromDataAppSchema,- ActionParametersFromDataAppSchema,+ ActionDefinition,+ ActionKindFromDefinition,+ ActionParametersFromDefinition,DefinedAction,+ ImplicitActionDefinition,} from "./hooks/public/use-action";export type {DataAppFactory,diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.tsindex afe4e49b926..85a6bc76599 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts@@ -35,7 +35,7 @@ export type SchemaValue<TColumn extends SchemaColumn> =: TColumn["jsType"] extends "boolean"? boolean | null: TColumn["jsType"] extends "Date"- ? string | Date | null+ ? string | null: RowValue | null;/** @notExported SchemaValue */diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.tsindex 981d10488fc..4b893d737f2 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts@@ -1,15 +1,13 @@-import type { DefinedAction } from "./types";+import type { ActionDefinition, DefinedAction } from "./types";/**- * Defines a data app action. `action.id` is the action's entity ID or its- * numeric id. The typed schema Metabase generates for an app holds one- * definition per action in the app's collection.+ * Defines a data app action: an implicit action of `kind` on a table from the+ * app's schema, which the dev preview runs without saving it. A production+ * build runs the action `entityId` names.*/-export function defineAction<- const TDefinition extends {- action: { id: number | string; parameters: readonly unknown[] };- },->(definition: TDefinition): TDefinition & DefinedAction {+export function defineAction<const TDefinition extends ActionDefinition>(+ definition: TDefinition,+): TDefinition & DefinedAction {// `DefinedAction` has no runtime member, so the object is returned as is; the// cast only adds the mark that a data app's `useAction` requires.return definition as TDefinition & DefinedAction;diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.tsindex 871e9b1d48b..8d459d5aacf 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts@@ -2,17 +2,19 @@ export { useAction, useDataAppAction } from "./use-action";export type {ActionExecuteError,ActionKind,- ActionKindFromDataAppSchema,- ActionParameterSchema,- ActionParametersFromDataAppSchema,+ ActionDefinition,+ ActionKindFromDefinition,+ ActionParametersFromDefinition,ActionResultForBulk,ActionResultForCreate,ActionResultForDelete,ActionResultForKind,ActionResultForSql,ActionResultForUpdate,- ActionSchema,AnyActionResult,DefinedAction,+ ImplicitActionDefinition,+ ImplicitActionKind,+ TableActionParameters,UseActionResult,} from "./types";diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.tsindex 3854e0cfe19..9d63d8d3215 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts@@ -5,13 +5,18 @@* discriminated `ActionResultForKind` shape it drives describe just the* kind / response surface. The `…FromDataAppSchema` helpers below layer on* top, deriving the hook's `TParameters` / `TKind` generics from a- * data app typed schema entry; the hook never sees the+ * data app's action definition; the hook never sees the* schema directly.*/import type { SdkActionId } from "embedding-sdk-bundle/types/action";-import type { RowValue, SchemaJavaScriptType } from "../data-schema";+import type {+ FieldSchema,+ RowValue,+ SchemaJavaScriptType,+ TableSchema,+} from "../data-schema";/*** Flat public kind union. Maps onto the backend's namespaced@@ -135,43 +140,40 @@ export type ActionResultForKind<TKind extends ActionKind | undefined> =// ============================================================================// Data App schema-derived helpers// -----------------------------------------------------------------------------// These read a single action entry in a data app typed schema+// These read a single action definition of a data app// and derive the hook's `TParameters` / `TKind`. `useAction` applies them to a// `defineAction(...)` export, so a Data App writes neither generic.// ============================================================================/**- * Shape of a single action parameter as it appears in a generated- * typed schema entry. An action parameter is not a column, so it- * carries no `name`.+ * The implicit actions a data app defines on a table.** @category useAction*/-export type ActionParameterSchema = {- slug: string;- displayName?: string;- jsType?: SchemaJavaScriptType;- required?: boolean;-};+export type ImplicitActionKind = "row/create" | "row/update" | "row/delete";/**- * Shape of a single action entry in a data app typed schema.- * The entry is what `defineAction` wraps; `parameters` drives- * `ActionParametersFromDataAppSchema`, and `type` drives- * `ActionKindFromDataAppSchema`.+ * A data app action that writes a row of a table from the app's schema: the+ * dev preview runs it without saving it, and a production build runs the+ * action `entityId` names.** @category useAction*/-export type ActionSchema = {- kind?: "action";- id: number | string;- name?: string;- type?: "query";- parameters: readonly ActionParameterSchema[];- description?: string;- entityId?: string;+export type ImplicitActionDefinition = {+ entityId: string;+ kind: ImplicitActionKind;+ table: TableSchema;};+/**+ * What `defineAction` wraps. Its table's fields drive+ * `ActionParametersFromDefinition`, and its `kind` drives+ * `ActionKindFromDefinition`.+ *+ * @category useAction+ */+export type ActionDefinition = ImplicitActionDefinition;+/** TS value type for a single action parameter, derived from its `jsType`. */type ActionParamValue<TParam extends { jsType?: SchemaJavaScriptType }> =TParam["jsType"] extends "string"@@ -185,43 +187,46 @@ type ActionParamValue<TParam extends { jsType?: SchemaJavaScriptType }> =: RowValue | null;/**- * Walks a schema entry's `parameters` tuple and produces an object keyed by- * slug. Parameters with `required: true` become required keys; everything- * else is optional. Feeds the hook's `TParameters` generic so a Data App- * author gets compile-time errors on missing required keys, wrong value- * types, and unknown slugs. Falls back to `Record<string, unknown>` if- * `TAction` is not a schema entry (e.g. a bare numeric id).+ * An implicit action's parameters: its table's columns, by name, each typed+ * by its `jsType` and optional, since the database decides what a row needs.** @category useAction* @notExported ActionParamValue*/-export type ActionParametersFromDataAppSchema<TAction> = TAction extends {- parameters: readonly ActionParameterSchema[];+export type TableActionParameters<TTable> = TTable extends {+ fields: infer TFields extends Record<string, FieldSchema>;}? {- [P in TAction["parameters"][number] as P extends { required: true }- ? P["slug"]- : never]: ActionParamValue<P>;- } & {- [P in TAction["parameters"][number] as P extends { required: true }- ? never- : P["slug"]]?: ActionParamValue<P>;+ [TKey in keyof TFields as Lowercase<+ TFields[TKey]["name"]+ >]?: ActionParamValue<TFields[TKey]>;}: Record<string, unknown>;/**- * Maps a schema entry to the flat `ActionKind` union: a data app's actions- * are query actions, so `type: "query"` gives `"sql"`. Feeds the hook's+ * The parameters of an action definition, which type the hook's `execute`.+ * Falls back to `Record<string, unknown>` if `TDefinition` is not a+ * definition (e.g. a bare numeric id).+ *+ * @category useAction+ */+export type ActionParametersFromDefinition<TDefinition> = TDefinition extends {+ table: infer TTable;+}+ ? TableActionParameters<TTable>+ : Record<string, unknown>;++/**+ * Maps an action definition to the flat `ActionKind` union: `row/create`+ * gives `"create"`, and so on. Feeds the hook's* `TKind` generic so `result` is typed via `ActionResultForKind<TKind>`.- * Falls back to the full `ActionKind` union if `TAction` is not a schema- * entry (e.g. a bare numeric id).** @category useAction*/-export type ActionKindFromDataAppSchema<TAction> = TAction extends {- type: "query";+export type ActionKindFromDefinition<TDefinition> = TDefinition extends {+ kind: `row/${infer TKind extends "create" | "update" | "delete"}`;}- ? "sql"+ ? TKind: ActionKind;/**@@ -270,11 +275,11 @@ export declare class DefinedAction {/** The SDK's `useAction`: a definition object, or an id. */export interface UseAction {/** A definition, which types `execute` and `result` itself. */- <TDefinition extends { action: ActionSchema }>(+ <TDefinition extends ActionDefinition>(action: TDefinition | null,): UseActionResult<- ActionParametersFromDataAppSchema<TDefinition["action"]>,- ActionKindFromDataAppSchema<TDefinition["action"]>+ ActionParametersFromDefinition<TDefinition>,+ ActionKindFromDefinition<TDefinition>>;/** An id, which describes nothing: `useAction<Parameters, "create">(42)`. */@@ -287,13 +292,13 @@ export interface UseAction {}/**- * A data app's `useAction`: only a `defineAction(...)` definition from its typed schema.+ * A data app's `useAction`: only a `defineAction(...)` definition.*/export interface UseDataAppAction {- <TDefinition extends DefinedAction & { action: ActionSchema }>(+ <TDefinition extends DefinedAction & ActionDefinition>(action: TDefinition | null,): UseActionResult<- ActionParametersFromDataAppSchema<TDefinition["action"]>,- ActionKindFromDataAppSchema<TDefinition["action"]>+ ActionParametersFromDefinition<TDefinition>,+ ActionKindFromDefinition<TDefinition>>;}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.tsindex 99adbead219..fb599298116 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts@@ -8,8 +8,9 @@ import type {} from "./types";/**- * Defines a data app query. A data app's typed schema, generated by Metabase,- * defines each question in the app's collection with it.+ * Defines a data app query: a question over a table of the app's schema, which+ * the dev preview runs from its definition. A production build runs the+ * question its `entityId` names.*/export function defineQuery<TEntity extends TableSchema | undefined = undefined,diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.tsindex 4dd356a1c5d..a29b6286d6c 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts@@ -15,6 +15,7 @@ export { useMetabaseQuery } from "./use-metabase-query";export { useMetabaseQueryObject } from "./use-metabase-query-object";export type {DefinedQuery,+ LegacyQuestionSource,MetabaseLocalFieldReference,MetabaseBreakout,MetabaseDynamicColumn,diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.tsindex 087649100f6..7be38bba9fc 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts@@ -160,35 +160,6 @@ export const TEST_SCHEMA = {sourceCardId: 41,},},- actions: {- createOrder: {- kind: "action" as const,- id: 51,- name: "Create Order",- type: "query" as const,- parameters: [- {- slug: "status",- displayName: "Status",- jsType: "string" as const,- },- ],- },- updateOrder: {- kind: "action" as const,- id: 52,- name: "Update Order",- type: "query" as const,- parameters: [- {- slug: "id",- displayName: "ID",- jsType: "number" as const,- required: true,- },- ],- },- },questions: {// Generated question columns carry only `type`, `name`, and `jsType`; the// display name is rendered as a comment, not as runtime metadata.diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsxindex f0594b27cd2..2214a554f60 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx@@ -1,6 +1,7 @@// Register mocks before loading the modules under test.// oxfmt-ignoreimport {+ PUBLISHED_QUESTION_ENTITY_ID,createMockStore,mockFetchTableMetadataAndForeignKeys,mockRunRtkEndpoint,@@ -11,7 +12,9 @@ import {import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";import { cardApi } from "metabase/api";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import * as Lib from "metabase-lib";+import { isObject } from "metabase-types/guards";import {aggregations,@@ -968,3 +971,58 @@ describe("resolveDatasetQuery named breakouts", () => {]);});});++describe("resolveDatasetQuery in a data app", () => {+ const ordersCountQuery = {+ entityId: PUBLISHED_QUESTION_ENTITY_ID,+ source: TEST_SCHEMA.tables.orders,+ aggregations: [count()],+ };++ beforeEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ mockRunRtkEndpoint.mockImplementation(async (request) => {+ if (isObject(request) && "card" in request) {+ return {+ [PUBLISHED_QUESTION_ENTITY_ID]: {+ id: 41,+ type: "card",+ status: "ok",+ },+ };+ }+ return isObject(request) && request.id === 41+ ? TEST_METADATA.questions[41]+ : undefined;+ });+ });++ afterEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = false;+ EMBEDDING_SDK_CONFIG.isDataAppDev = false;+ });++ it("runs the question its entity ID names, which holds the query's clauses", async () => {+ const datasetQuery =+ await resolveDatasetQueryInBundle(createMockStore())(ordersCountQuery);++ expect(stagesOf(datasetQuery)).toEqual([+ expect.objectContaining({ "source-card": 41 }),+ ]);+ expect(stagesOf(datasetQuery)[0]).not.toHaveProperty("aggregation");+ });++ it("runs the table query itself in the dev preview", async () => {+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ const datasetQuery =+ await resolveDatasetQueryInBundle(createMockStore())(ordersCountQuery);++ expect(stagesOf(datasetQuery)).toEqual([+ expect.objectContaining({+ "source-table": 1,+ aggregation: [expect.anything()],+ }),+ ]);+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.tsindex 5ee2961ce5b..d661feae9a5 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts@@ -43,22 +43,32 @@ defineQuery({breakouts: [breakout(TEST_SCHEMA.tables.orders.fields.createdAt)],});-const actionWithInvalidId = {- action: { ...TEST_SCHEMA.actions.createOrder, id: true },+const actionWithInvalidEntityId = {+ entityId: true,+ kind: "row/create",+ table: TEST_SCHEMA.tables.orders,} as const;-// @ts-expect-error action ids are numbers or entity IDs-defineAction(actionWithInvalidId);+// @ts-expect-error an action's entity ID is a string+defineAction(actionWithInvalidEntityId);-// @ts-expect-error action definitions must reference a generated action-defineAction({ action: TEST_SCHEMA.tables.orders });+// @ts-expect-error action definitions name a table from the app's schema+defineAction({ entityId: "ordersEntity", kind: "row/create", table: 1 });-const CreateOrder = defineAction({- action: TEST_SCHEMA.actions.createOrder,+// @ts-expect-error action definitions need the entity ID of the action a production build runs+defineAction({ kind: "row/create", table: TEST_SCHEMA.tables.orders });++defineAction({+ entityId: "ordersEntity",+ // @ts-expect-error an implicit action creates, updates or deletes a row+ kind: "row/upsert",+ table: TEST_SCHEMA.tables.orders,});-const UpdateOrder = defineAction({- action: TEST_SCHEMA.actions.updateOrder,+const CreateOrder = defineAction({+ entityId: "createOrderEntity",+ kind: "row/create",+ table: TEST_SCHEMA.tables.orders,});// --------@@ -237,7 +247,11 @@ function InvalidTypeFixtures() {useMetabaseQueryObject({ ...staticQuery, limit: 10 });// @ts-expect-error a data app's action is a `defineAction` definition, never an inline object- useDataAppAction({ action: TEST_SCHEMA.actions.createOrder });+ useDataAppAction({+ entityId: "createOrderEntity",+ kind: "row/create",+ table: TEST_SCHEMA.tables.orders,+ });// @ts-expect-error a copy of a definition is not the definitionuseDataAppAction({ ...CreateOrder });@@ -245,11 +259,11 @@ function InvalidTypeFixtures() {// @ts-expect-error a data app never names an action by iduseDataAppAction(51);- // @ts-expect-error pass the `defineAction` export, not the schema entry- useDataAppAction(TEST_SCHEMA.actions.createOrder);+ // @ts-expect-error pass the `defineAction` export, not a table+ useDataAppAction(TEST_SCHEMA.tables.orders);- // @ts-expect-error the SDK hook takes a definition object or an id, not the schema entry- useAction(TEST_SCHEMA.actions.createOrder);+ // @ts-expect-error the SDK hook takes a definition object or an id, not a table+ useAction(TEST_SCHEMA.tables.orders);// @ts-expect-error the definition's parameter slugs are the only keysuseAction(CreateOrder).execute({ stauts: "shipped" });@@ -257,9 +271,6 @@ function InvalidTypeFixtures() {// @ts-expect-error a parameter value is typed by its `jsType`useAction(CreateOrder).execute({ status: 1 });- // @ts-expect-error required parameters cannot be omitted- useAction(UpdateOrder).execute({});-// @ts-expect-error `result` is discriminated by the action's kindvoid useAction(CreateOrder).result?.["rows-updated"];diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.tsindex c0919782db1..461870f7af3 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts@@ -38,13 +38,17 @@ const _questionEntityId: "ordersQuestionEntity1" =ordersQuestionQuery.source.entityId;const CreateOrder = defineAction({- action: { ...TEST_SCHEMA.actions.createOrder, id: "createOrderEntity" },+ entityId: "createOrderEntity",+ kind: "row/create",+ table: TEST_SCHEMA.tables.orders,});-const _actionEntityId: "createOrderEntity" = CreateOrder.action.id;+const _actionEntityId: "createOrderEntity" = CreateOrder.entityId;const UpdateOrder = defineAction({- action: TEST_SCHEMA.actions.updateOrder,+ entityId: "updateOrderEntity",+ kind: "row/update",+ table: TEST_SCHEMA.tables.orders,});function CardQueryFixtures() {@@ -169,10 +173,9 @@ function ValidTypeFixtures() {void createOrder.execute({ status: "shipped" });- const createdCount: number | undefined =- createOrder.result?.["rows-affected"];+ const createdRow = createOrder.result?.["created-row"];- void createdCount;+ void createdRow;const updateOrder = useDataAppAction(UpdateOrder);@@ -180,16 +183,17 @@ function ValidTypeFixtures() {// The SDK hook takes a plain definition object, and a `defineAction` export too.const sdkCreateOrder = useAction({- action: TEST_SCHEMA.actions.createOrder,+ entityId: "createOrderEntity",+ kind: "row/create",+ table: TEST_SCHEMA.tables.orders,});void sdkCreateOrder.execute({ status: "shipped" });void useAction(CreateOrder).execute({ status: "shipped" });- const updatedCount: number | undefined =- updateOrder.result?.["rows-affected"];+ const updatedRows = updateOrder.result?.["rows-updated"];- void updatedCount;+ void updatedRows;// A raw id types nothing, so the generics still stand in for a definition.const rawAction = useAction<{ status: string }, "create">(51);diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.tsindex 21a97bc7e95..edcd0e9a814 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts@@ -16,7 +16,6 @@ import type {InferSchema,MetricSchema,QueryData,- QuestionSchema,SchemaColumn,SchemaJavaScriptType,SchemaValue,@@ -447,6 +446,12 @@ type StageClauses<TDimension, TAggregation, TFilter> = {type TableQueryBase<TTable> = {source: TTable extends TableSchema ? SourceQuerySpec<TTable> : TableSchema;fields?: readonly FieldReference<TTable>[];+ /**+ * The entity ID of this query's question in the app's collection. A+ * production build runs that question, which holds the query's clauses; the+ * dev preview runs the table query itself.+ */+ entityId?: string;} & StageClauses<FieldReference<TTable>,AnyAggregation<TTable>,@@ -532,12 +537,21 @@ type RequireDynamicOrderByNames<TEntity, TQuery, TDynamic> =>;/**- * A saved question run as is, typed by its result columns. A data app's typed- * schema defines each of its questions this way. Its static clauses are the- * question's own.+ * The saved question a data app built against an older SDK runs, by its+ * entity ID.+ *+ * @deprecated A data app defines a query on a table of its schema, with `entityId`.+ */+export type LegacyQuestionSource = { type: "card"; entityId: string };++/**+ * A query of a data app built against an older SDK, which runs the saved+ * question its `source` names.+ *+ * @deprecated A data app defines a query on a table of its schema, with `entityId`.*/-type QuestionQuery = {- source: QuestionSchema;+type LegacyQuestionQuery = {+ source: LegacyQuestionSource;enabled?: boolean;fields?: never;filters?: never;@@ -549,7 +563,7 @@ type QuestionQuery = {export type MetabaseQueryOptions<TEntity = unknown, _TSchema = unknown> =| TableQuery<TEntity>- | QuestionQuery;+ | LegacyQuestionQuery;type EmptyRow = Record<never, never>;diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex bf678db4ce9..37be1a5f137 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -181,6 +181,7 @@ export type {SdkActionId,SdkActionDefinition,SdkActionInput,+ SdkLegacyActionDefinition,} from "embedding-sdk-bundle/types";export type {FieldSchema,diff --git a/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.unit.spec.tsnew file mode 100644index 00000000000..5eef68efe08--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.unit.spec.ts@@ -0,0 +1,37 @@+import { copy } from "./copy";++describe("copy", () => {+ const originalClipboard = navigator.clipboard;++ afterEach(() => {+ Object.defineProperty(navigator, "clipboard", {+ value: originalClipboard,+ configurable: true,+ });+ });++ function setClipboard(clipboard: Pick<Clipboard, "writeText"> | undefined) {+ Object.defineProperty(navigator, "clipboard", {+ value: clipboard,+ configurable: true,+ });+ }++ it("writes the text to the clipboard", async () => {+ const writeText = jest.fn<Promise<void>, [string]>(() => Promise.resolve());+ setClipboard({ writeText });++ await copy("data-app-clipboard-payload");++ expect(writeText).toHaveBeenCalledTimes(1);+ expect(writeText).toHaveBeenCalledWith("data-app-clipboard-payload");+ });++ it("rejects when the clipboard is unavailable", async () => {+ setClipboard(undefined);++ await expect(copy("text")).rejects.toThrow(+ "Clipboard write is unavailable",+ );+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/package.template.json b/enterprise/frontend/src/embedding-sdk-package/package.template.jsonindex 11726712667..62c7606540a 100644--- a/enterprise/frontend/src/embedding-sdk-package/package.template.json+++ b/enterprise/frontend/src/embedding-sdk-package/package.template.json@@ -34,7 +34,7 @@},"./data-app-dev/config": {"types": "./dist/data-app-dev.config.d.ts",- "import": "./dist/data-app-dev.config.js"+ "import": "./dist/data-app-dev.config.mjs"},"./package.json": "./package.json"},diff --git a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts b/enterprise/frontend/src/metabase-enterprise/api/data-app.tsindex 21cff44ca5d..4d07b7e9374 100644--- a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts@@ -121,14 +121,6 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({invalidatesTags: (_, error, { name }) =>invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),}),- deleteDataApp: builder.mutation<void, string>({- query: (name) => ({- method: "DELETE",- url: `/api/ee/apps/${encodeURIComponent(name)}`,- }),- invalidatesTags: (_, error, name) =>- invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),- }),}),});@@ -141,5 +133,4 @@ export const {useAddDataAppGroupsMutation,useRemoveDataAppGroupMutation,useSetDataAppEnabledMutation,- useDeleteDataAppMutation,} = dataAppApi;diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsxindex a5138da0a92..bd9749b9cea 100644--- a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/components/DataAppActionHeader/DataAppActionHeader.tsx@@ -4,13 +4,17 @@ import type { PillTab } from "metabase/common/components/PillTabNavigation";import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import type { StackProps } from "metabase/ui";import * as Urls from "metabase/urls";-import type { DataApp, WritebackQueryAction } from "metabase-types/api";+import type {+ DataApp,+ WritebackImplicitQueryAction,+ WritebackQueryAction,+} from "metabase-types/api";import { DataAppItemHeader } from "../DataAppItemHeader";type DataAppActionHeaderProps = {app: DataApp;- action: WritebackQueryAction;+ action: WritebackQueryAction | WritebackImplicitQueryAction;} & Omit<StackProps, "title">;export function DataAppActionHeader({diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.ts b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.tsindex acc1c3b0c50..e5c5188b156 100644--- a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/hooks/use-route-data-app-action/use-route-data-app-action.ts@@ -26,7 +26,10 @@ export function useRouteDataAppAction() {error: databasesError,} = useActionDatabases();- const action = currentData?.type === "query" ? currentData : undefined;+ const action =+ currentData?.type === "query" || currentData?.type === "implicit"+ ? currentData+ : undefined;const isLoadingAction = currentData === undefined && isFetchingAction;const isActionNotFound =!isLoadingAction && actionFetchError === undefined && action === undefined;diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsxindex 68933358be2..66414ac1445 100644--- a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.tsx@@ -1,5 +1,8 @@+import _ from "underscore";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { ImplicitActionDefinitionContent } from "metabase/data-studio/actions/components/ImplicitActionDefinitionContent";import { QueryActionDefinitionContent } from "metabase/data-studio/actions/components/QueryActionDefinitionContent";import { Center } from "metabase/ui";@@ -20,7 +23,17 @@ export function DataAppActionDefinitionPage() {return (<PageContainer data-testid="data-app-action-definition"><DataAppActionHeader app={app} action={action} />- <QueryActionDefinitionContent action={action} databases={databases} />+ {action.type === "implicit" ? (+ <ImplicitActionDefinitionContent+ tableId={action.table_id}+ kind={action.kind}+ readOnly+ onChangeTable={_.noop}+ onChangeKind={_.noop}+ />+ ) : (+ <QueryActionDefinitionContent action={action} databases={databases} />+ )}</PageContainer>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.unit.spec.tsxnew file mode 100644index 00000000000..0fcd9275f31--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionDefinitionPage/DataAppActionDefinitionPage.unit.spec.tsx@@ -0,0 +1,92 @@+import {+ setupActionEndpoints,+ setupDataAppEndpoint,+ setupDatabaseListEndpoint,+ setupTableQueryMetadataEndpoint,+} from "__support__/server-mocks";+import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";+import type { WritebackImplicitQueryAction } from "metabase-types/api";+import {+ createMockDataApp,+ createMockDatabase,+ createMockField,+ createMockImplicitQueryAction,+ createMockTable,+} from "metabase-types/api/mocks";++import { DataAppActionDefinitionPage } from "./DataAppActionDefinitionPage";++const APP = createMockDataApp({ name: "teams" });++const DATABASE = createMockDatabase({+ id: 1,+ name: "Shop",+ settings: { "database-enable-actions": true },+});++const TABLE = createMockTable({+ id: 10,+ db_id: 1,+ db: DATABASE,+ schema: "public",+ display_name: "Teams",+ fields: [+ createMockField({+ id: 100,+ table_id: 10,+ name: "ID",+ semantic_type: "type/PK",+ }),+ ],+});++type SetupOpts = {+ action: WritebackImplicitQueryAction;+};++function setup({ action }: SetupOpts) {+ setupDataAppEndpoint(APP);+ setupActionEndpoints(action);+ setupTableQueryMetadataEndpoint(TABLE);+ setupDatabaseListEndpoint([DATABASE]);++ renderWithProviders(+ <Route+ path="/data-studio/apps/:name/actions/:actionId"+ element={<DataAppActionDefinitionPage />}+ />,+ {+ withRouter: true,+ initialRoute: `/data-studio/apps/${APP.name}/actions/${action.id}`,+ },+ );+}++describe("DataAppActionDefinitionPage", () => {+ it("shows the table and the operation of an app's table action, read-only", async () => {+ setup({+ action: createMockImplicitQueryAction({+ id: 2,+ name: "addTeam",+ model_id: null,+ table_id: TABLE.id,+ kind: "row/create",+ can_write: false,+ }),+ });++ expect(await screen.findByText("Teams")).toBeInTheDocument();+ expect(screen.getByTestId("data-app-action-header")).toHaveTextContent(+ "addTeam",+ );+ expect(+ screen.getByText(+ "Adds a new row. The form asks for every column the database does not fill in.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Change table" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsxindex 86ac1d22a99..ae253a5eb4e 100644--- a/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-apps/data-studio/pages/DataAppActionFieldsPage/DataAppActionFieldsPage.tsx@@ -1,6 +1,9 @@import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { PageContainer } from "metabase/common/data-studio/components/PageContainer";-import { QueryActionFieldsContent } from "metabase/data-studio/actions/components/ActionFieldsContent";+import {+ ImplicitActionFieldsContent,+ QueryActionFieldsContent,+} from "metabase/data-studio/actions/components/ActionFieldsContent";import { canEditActionQuery } from "metabase/data-studio/actions/utils";import { useParams } from "metabase/router";import { Center } from "metabase/ui";@@ -24,14 +27,24 @@ export function DataAppActionFieldsPage() {return (<PageContainer data-testid="data-app-action-fields" gap="lg" px={0} pb={0}><DataAppActionHeader app={app} action={action} px="3.5rem" />- <QueryActionFieldsContent- action={action}- fieldId={fieldId}- canChangeFieldType={canEditActionQuery(action, databases)}- getFieldsUrl={(fieldId) =>- Urls.dataStudioDataAppActionFields(app.name, action.id, fieldId)- }- />+ {action.type === "implicit" ? (+ <ImplicitActionFieldsContent+ action={action}+ fieldId={fieldId}+ getFieldsUrl={(fieldId) =>+ Urls.dataStudioDataAppActionFields(app.name, action.id, fieldId)+ }+ />+ ) : (+ <QueryActionFieldsContent+ action={action}+ fieldId={fieldId}+ canChangeFieldType={canEditActionQuery(action, databases)}+ getFieldsUrl={(fieldId) =>+ Urls.dataStudioDataAppActionFields(app.name, action.id, fieldId)+ }+ />+ )}</PageContainer>);}diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.tsindex 3a9ee2ae0aa..e52bd2c2198 100644--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts@@ -1,7 +1,9 @@+import { translateEntityId } from "embedding-sdk-bundle/lib/translate-entity-id";import type { SdkStore } from "embedding-sdk-bundle/store/types";import {type DynamicQueryInput,type QueryInput,+ type TableQueryInput,isQueryInput,isQuestionInput,isTableInput,@@ -9,6 +11,7 @@ import {import type { QuestionSchema } from "embedding-sdk-shared/lib/create-metabase-query/schema";import { cardApi, selectCard, selectTableQueryMetadata } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { isDataApp, isDataAppDev } from "metabase/embedding-sdk/config";import { selectMetadataProviderUnfiltered } from "metabase/metadata-store";import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";import * as Lib from "metabase-lib";@@ -74,12 +77,18 @@ type ResolvedSource = {/*** A card source given by its entity ID, with the card's numeric id: query- * metadata and the query itself address cards by numeric id.+ * metadata and the query itself address cards by numeric id. Outside the dev+ * preview, a data app's table query runs the question its `entityId` names,+ * which holds its static clauses.*/async function resolveSourceCard(store: SdkStore,input: QueryInput,): Promise<ResolvedSource> {+ if (isTableInput(input) && isDataApp() && !isDataAppDev()) {+ return resolveDataAppQuestion(store, input);+ }+if (!isQuestionInput(input) || input.source.id !== undefined) {return { input };}@@ -92,6 +101,27 @@ async function resolveSourceCard(};}+async function resolveDataAppQuestion(+ store: SdkStore,+ { entityId }: TableQueryInput,+): Promise<ResolvedSource> {+ if (entityId === undefined) {+ throw new Error(+ "A data app's query needs an `entityId` in `defineQuery(...)`: the question it names is what the app runs.",+ );+ }++ const cardId = await translateEntityId(store, "card", entityId);+ const card: Card = await runRtkEndpoint(+ { id: cardId },+ store.dispatch,+ cardApi.endpoints.getCard,+ { forceRefetch: false },+ );++ return { input: { source: { type: "card", id: card.id } }, card };+}+async function fetchCardByEntityId(store: SdkStore,entityId: string,@@ -106,7 +136,7 @@ async function fetchCardByEntityId(} catch (error) {if (isObject(error) && error.status === 404) {throw new Error(- `Saved question ${entityId} does not exist. Fetch the app's typed schema again to pick up its current questions.`,+ `Saved question ${entityId} does not exist. Generate the app's questions and import the repository again.`,);}@@ -172,7 +202,8 @@ function withoutOrderBys<TStage extends TestStageSpec>({function toStageSpec(input: QueryInput): TestStageWithSourceSpec {if (!isQuestionInput(input)) {- return input;+ const { entityId: _entityId, ...stage } = input;+ return stage;}return {diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.tsindex 876155cc0d7..1762f4cb938 100644--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts@@ -1,11 +1,16 @@+import { translateEntityId } from "embedding-sdk-bundle/lib/translate-entity-id";import type { SdkStore } from "embedding-sdk-bundle/store/types";import type {SdkActionDefinition,SdkActionId,SdkActionInput,+ SdkLegacyActionDefinition,} from "embedding-sdk-bundle/types/action";-import { executeAction as executeActionMutation } from "metabase/api/action";-import { isDataApp } from "metabase/embedding-sdk/config";+import {+ executeAction as executeActionMutation,+ executeUnsavedAction as executeUnsavedActionMutation,+} from "metabase/api/action";+import { isDataApp, isDataAppDev } from "metabase/embedding-sdk/config";import type {BaseEntityId,ParametersForActionExecution,@@ -48,22 +53,71 @@ const parseActionId = (const isActionDefinition = (input: SdkActionInput,-): input is SdkActionDefinition => isObject(input) && "action" in input;+): input is SdkActionDefinition => isObject(input) && "entityId" in input;-function toExecutableActionId(input: SdkActionInput): SdkActionId {- if (isActionDefinition(input)) {- return input.action.id;- }+const isLegacyActionDefinition = (+ input: SdkActionInput,+): input is SdkLegacyActionDefinition =>+ isObject(input) && "action" in input && isObject(input.action);+function toRawActionId(input: SdkActionId): SdkActionId {if (isDataApp()) {throw new Error(- `Action ${input} was passed to \`useAction\` as a raw id. A data app must pass a \`defineAction(...)\` definition from its typed schema.`,+ `Action ${input} was passed to \`useAction\` as a raw id. A data app must pass a \`defineAction(...)\` definition.`,);}return input;}+async function executeDefinedAction(+ reduxStore: SdkStore,+ definition: SdkActionDefinition,+ parameters: ActionParametersPayload,+): Promise<ExecuteActionResult> {+ if (isDataAppDev()) {+ return reduxStore+ .dispatch(+ executeUnsavedActionMutation.initiate({+ action: {+ name: definition.kind,+ type: "implicit",+ kind: definition.kind,+ table_id: definition.table.id,+ },+ // Forwarded unchanged: the SDK keeps the parameter bag loose, and the+ // endpoint validates the values server-side.+ parameters: parameters as ParametersForActionExecution,+ }),+ )+ .unwrap();+ }++ return executeSavedAction(reduxStore, definition.entityId, parameters);+}++async function executeSavedAction(+ reduxStore: SdkStore,+ actionId: SdkActionId,+ parameters: ActionParametersPayload,+): Promise<ExecuteActionResult> {+ const id =+ typeof actionId === "number"+ ? actionId+ : await translateEntityId(reduxStore, "action", actionId);++ return reduxStore+ .dispatch(+ executeActionMutation.initiate({+ id,+ // Forwarded unchanged: the SDK keeps the parameter bag loose, and the+ // endpoint validates the values server-side.+ parameters: parameters as ParametersForActionExecution,+ }),+ )+ .unwrap();+}+/*** Triggers a pre-existing Metabase action. The curried `(store) => fn` shape* mirrors `createDashboard` / `queryQuestion` so the package@@ -77,10 +131,18 @@ export const executeAction =actionId,parameters = {},}: ExecuteActionParams): Promise<ExecuteActionResult> => {+ if (isActionDefinition(actionId)) {+ return executeDefinedAction(reduxStore, actionId, parameters);+ }++ if (isLegacyActionDefinition(actionId)) {+ return executeSavedAction(reduxStore, actionId.action.id, parameters);+ }+return reduxStore.dispatch(executeActionMutation.initiate({- id: parseActionId(toExecutableActionId(actionId)),+ id: parseActionId(toRawActionId(actionId)),// Forwarded unchanged: the SDK keeps the parameter bag loose, and the// endpoint validates the values server-side.parameters: parameters as ParametersForActionExecution,diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.tsindex 38f49bc8af2..4be7b1d3ed3 100644--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts@@ -31,25 +31,94 @@ describe("executeAction", () => {activeStore = undefined;fetchMock.removeRoutes().clearHistory();EMBEDDING_SDK_CONFIG.isDataApp = false;+ EMBEDDING_SDK_CONFIG.isDataAppDev = false;});describe("an action definition", () => {const ACTION_ENTITY_ID = "appActionEntity000091";- const definition = { action: { id: ACTION_ENTITY_ID } };+ const ACTION_ID = 91;+ const definition = {+ entityId: ACTION_ENTITY_ID,+ kind: "row/update" as const,+ table: { id: 3 },+ };++ it("runs the saved action its entity ID names in a data app", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ fetchMock.post("path:/api/eid-translation/translate", {+ entity_ids: {+ [ACTION_ENTITY_ID]: { id: ACTION_ID, type: "action", status: "ok" },+ },+ });+ fetchMock.post(`path:/api/action/${ACTION_ID}/execute`, {+ status: 200,+ body: { "rows-updated": [1] },+ });++ const result = await executeAction(setup())({+ actionId: definition,+ parameters: { id: 1 },+ });++ expect(result).toEqual({ "rows-updated": [1] });+ const calls = fetchMock.callHistory.calls(+ `path:/api/action/${ACTION_ID}/execute`,+ );+ expect(calls).toHaveLength(1);+ expect(JSON.parse(String(calls[0].options.body))).toEqual({+ parameters: { id: 1 },+ });+ });++ it("runs the action itself, without saving it, in the dev preview", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;+ fetchMock.post("path:/api/action/execute", {+ status: 200,+ body: { "rows-updated": [1] },+ });- it("runs the action its definition names in a data app", async () => {+ await executeAction(setup())({+ actionId: definition,+ parameters: { id: 1 },+ });++ const calls = fetchMock.callHistory.calls("path:/api/action/execute");+ expect(calls).toHaveLength(1);+ expect(JSON.parse(String(calls[0].options.body))).toEqual({+ action: {+ name: "row/update",+ type: "implicit",+ kind: "row/update",+ table_id: 3,+ },+ parameters: { id: 1 },+ });+ expect(+ fetchMock.callHistory.calls("path:/api/eid-translation/translate"),+ ).toHaveLength(0);+ });++ it("runs the saved action an older app's definition names by `action.id`", async () => {EMBEDDING_SDK_CONFIG.isDataApp = true;- fetchMock.post(`path:/api/action/${ACTION_ENTITY_ID}/execute`, {+ fetchMock.post("path:/api/eid-translation/translate", {+ entity_ids: {+ [ACTION_ENTITY_ID]: { id: ACTION_ID, type: "action", status: "ok" },+ },+ });+ fetchMock.post(`path:/api/action/${ACTION_ID}/execute`, {status: 200,- body: { "rows-affected": 1 },+ body: { "rows-updated": [1] },});- await executeAction(setup())({ actionId: definition });+ const result = await executeAction(setup())({+ actionId: { action: { id: ACTION_ENTITY_ID } },+ parameters: { id: 1 },+ });+ expect(result).toEqual({ "rows-updated": [1] });expect(- fetchMock.callHistory.calls(- `path:/api/action/${ACTION_ENTITY_ID}/execute`,- ),+ fetchMock.callHistory.calls(`path:/api/action/${ACTION_ID}/execute`),).toHaveLength(1);});diff --git a/frontend/src/embedding-sdk-bundle/lib/translate-entity-id.ts b/frontend/src/embedding-sdk-bundle/lib/translate-entity-id.tsnew file mode 100644index 00000000000..54608ea5813--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/translate-entity-id.ts@@ -0,0 +1,39 @@+import type { SdkStore } from "embedding-sdk-bundle/store/types";+import {+ type EntityType,+ type TranslateEntityIdResponse,+ entityIdApi,+} from "metabase/api/entity-id";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { isBaseEntityID } from "metabase-types/api";++/**+ * The numeric id of the `type` entity with `entityId`. Throws when the+ * instance has no such entity, as a data app's questions and actions are+ * missing until its repository is imported.+ */+export async function translateEntityId(+ store: SdkStore,+ type: EntityType,+ entityId: string,+): Promise<number> {+ if (!isBaseEntityID(entityId)) {+ throw new Error(`${entityId} is not an entity ID.`);+ }++ const response: TranslateEntityIdResponse = await runRtkEndpoint(+ { [type]: [entityId] },+ store.dispatch,+ entityIdApi.endpoints.translateEntityId,+ { forceRefetch: false },+ );+ const translation = response[entityId];++ if (translation?.status !== "ok" || typeof translation.id !== "number") {+ throw new Error(+ `The ${type} ${entityId} does not exist. Import the app's repository to create it.`,+ );+ }++ return translation.id;+}diff --git a/frontend/src/embedding-sdk-bundle/types/action.ts b/frontend/src/embedding-sdk-bundle/types/action.tsindex f3eef8aec4f..f9bb62c4da0 100644--- a/frontend/src/embedding-sdk-bundle/types/action.ts+++ b/frontend/src/embedding-sdk-bundle/types/action.ts@@ -4,12 +4,27 @@ import type { SdkEntityId } from "embedding-sdk-bundle/types/entity";export type SdkActionId = number | SdkEntityId;/**- * How a data app names an action: a `defineAction` definition from the app's- * typed schema, whose `action.id` is the entity ID of an action in the app's- * collection.+ * How a data app names an action: a `defineAction` definition of an implicit+ * action on a table. The dev preview runs it without saving it, and a+ * production build runs the action `entityId` names.*/export type SdkActionDefinition = {+ entityId: SdkEntityId;+ kind: "row/create" | "row/update" | "row/delete";+ table: { id: number };+};++/**+ * How a data app built against an older SDK names an action: the saved action+ * `action.id` names, by its entity ID or numeric id.+ *+ * @deprecated A data app passes a `defineAction` definition with `entityId`.+ */+export type SdkLegacyActionDefinition = {action: { id: SdkActionId };};-export type SdkActionInput = SdkActionId | SdkActionDefinition;+export type SdkActionInput =+ | SdkActionId+ | SdkActionDefinition+ | SdkLegacyActionDefinition;diff --git a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.tsindex 9a16790c30a..459756d2116 100644--- a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts+++ b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts@@ -20,6 +20,8 @@ export type TableQueryInput = Omit<TestStageWithSourceSpec, "source"> & {source: TableSchema;limit?: number;enabled?: boolean;+ /** The entity ID of the question a data app runs in production. */+ entityId?: string;};/**diff --git a/frontend/src/metabase-types/api/actions.ts b/frontend/src/metabase-types/api/actions.tsindex 20261793d48..d129f46eb23 100644--- a/frontend/src/metabase-types/api/actions.ts+++ b/frontend/src/metabase-types/api/actions.ts@@ -223,6 +223,11 @@ export interface ExecuteActionRequest {parameters: ParametersForActionExecution;}+export interface ExecuteUnsavedActionRequest {+ action: CreateActionRequest;+ parameters: ParametersForActionExecution;+}+export interface PrefetchActionValuesRequest {id: WritebackActionId;parameters: ParametersForActionExecution;diff --git a/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.tsindex 87a8d8f4cdb..02c5a615e94 100644--- a/frontend/src/metabase-types/api/data-app.ts+++ b/frontend/src/metabase-types/api/data-app.ts@@ -38,16 +38,6 @@ export interface DataApp {updated_at: string;}-export interface CreateDataAppRequest {- name: string;- display_name?: string;- description?: string | null;- version?: number;- bundle_path?: string;- allowed_hosts?: string[];- enabled?: boolean;-}-/*** Status of the connected repository as it relates to data apps. The connection* itself (URL / branch / token) is configured on the remote-sync settings page.diff --git a/frontend/src/metabase/api/action.ts b/frontend/src/metabase/api/action.tsindex 280d51ac2d6..af17fd37e18 100644--- a/frontend/src/metabase/api/action.ts+++ b/frontend/src/metabase/api/action.ts@@ -5,6 +5,7 @@ import type {CreateActionRequest,ExecuteActionRequest,ExecuteDashcardActionRequest,+ ExecuteUnsavedActionRequest,GetActionRequest,ListActionsRequest,ParametersForActionExecution,@@ -149,6 +150,16 @@ export const actionApi = Api.injectEndpoints({body: { parameters },}),}),+ executeUnsavedAction: builder.mutation<+ ActionExecutionResult,+ ExecuteUnsavedActionRequest+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/action/execute",+ body,+ }),+ }),prefetchActionValues: builder.query<ParametersForActionExecution,PrefetchActionValuesRequest@@ -203,6 +214,7 @@ export const {deleteActionPublicLink,createActionPublicLink,executeAction,+ executeUnsavedAction,prefetchActionValues,executeDashcardAction,prefetchDashcardValues,diff --git a/frontend/src/metabase/api/client/middleware.ts b/frontend/src/metabase/api/client/middleware.tsindex 6fae207e904..d52f3f39977 100644--- a/frontend/src/metabase/api/client/middleware.ts+++ b/frontend/src/metabase/api/client/middleware.ts@@ -37,6 +37,7 @@ function getOnBeforeRequestHandlers(): OnBeforeRequestHandler[] {PLUGIN_API.onBeforeRequestHandlers.reactSdkEmbedReferrer,PLUGIN_API.onBeforeRequestHandlers.reactSdkReactVersion,PLUGIN_API.onBeforeRequestHandlers.embedReferrer,+ PLUGIN_API.onBeforeRequestHandlers.setDataAppDevHeader,];}diff --git a/frontend/src/metabase/api/client/request-handlers.ts b/frontend/src/metabase/api/client/request-handlers.tsindex dfbcc6ae7c5..405a0e01540 100644--- a/frontend/src/metabase/api/client/request-handlers.ts+++ b/frontend/src/metabase/api/client/request-handlers.ts@@ -75,6 +75,9 @@ const getDefaultPluginApi = () => ({// Send the host page URL as the embed referrer header. Installed by the// iframe SDK's embed route, which receives the URL via postMessage.embedReferrer: noop,+ // Mark requests from a data app's dev preview. Installed by the data app+ // runtime.+ setDataAppDevHeader: noop,},});diff --git a/frontend/src/metabase/embedding/config.ts b/frontend/src/metabase/embedding/config.tsindex 2f552768abf..a06d3e2c7b6 100644--- a/frontend/src/metabase/embedding/config.ts+++ b/frontend/src/metabase/embedding/config.ts@@ -7,6 +7,7 @@ import {} from "metabase/embedding-sdk/config";import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";+import { setDataAppDevHeader } from "./lib/auth/set-data-app-dev-header";import { setEmbedPreviewHeader } from "./lib/auth/set-embed-preview-header";import { setReactSdkEmbedReferrerHeader } from "./lib/auth/set-react-sdk-embed-referrer-header";import { setRequestClientHeaders } from "./lib/auth/set-request-client-headers";@@ -68,6 +69,8 @@ export function setDataApp(PLUGIN_API.onBeforeRequestHandlers.reactSdkEmbedReferrer =setReactSdkEmbedReferrerHeader;++ PLUGIN_API.onBeforeRequestHandlers.setDataAppDevHeader = setDataAppDevHeader;}export function isPublicEmbedding() {diff --git a/frontend/src/metabase/embedding/lib/auth/set-data-app-dev-header.ts b/frontend/src/metabase/embedding/lib/auth/set-data-app-dev-header.tsnew file mode 100644index 00000000000..294d42f613c--- /dev/null+++ b/frontend/src/metabase/embedding/lib/auth/set-data-app-dev-header.ts@@ -0,0 +1,13 @@+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */+import type { OnBeforeRequestHandler } from "metabase/api/client";+import { isDataAppDev } from "metabase/embedding-sdk/config";++/**+ * Tag requests from a data app's dev preview, which runs the app's queries and+ * actions without them existing on the instance.+ */+export const setDataAppDevHeader: OnBeforeRequestHandler = async () => {+ if (isDataAppDev()) {+ return { headers: { "X-Metabase-Data-App-Dev": "true" } };+ }+};diff --git a/frontend/test/__support__/server-mocks/data-app.ts b/frontend/test/__support__/server-mocks/data-app.tsindex 20925fe1bd8..4a14f172c2f 100644--- a/frontend/test/__support__/server-mocks/data-app.ts+++ b/frontend/test/__support__/server-mocks/data-app.ts@@ -16,6 +16,10 @@ export function setupListDataAppsEndpointWithError(error: string) {fetchMock.get("path:/api/ee/apps", { status: 500, body: error });}+export function setupDataAppEndpoint(app: DataApp) {+ fetchMock.get(`path:/api/ee/apps/${app.name}`, app);+}+export function setupDataAppRepoStatusEndpoint(status: DataAppRepoStatus) {fetchMock.get("path:/api/ee/apps/repo-status", status);}@@ -28,10 +32,6 @@ export function setupUpdateDataAppEndpoint(app: DataApp) {fetchMock.put(`path:/api/ee/apps/${app.name}`, app);}-export function setupDeleteDataAppEndpoint(name: string) {- fetchMock.delete(`path:/api/ee/apps/${name}`, 204);-}-export function setupDataAppGroupsEndpoint(name: string,groups: DataAppGroup[],diff --git a/rspack.embedding-sdk-node.config.js b/rspack.embedding-sdk-node.config.jsindex 0eb0bcf3d37..5083b3813ae 100644--- a/rspack.embedding-sdk-node.config.js+++ b/rspack.embedding-sdk-node.config.js@@ -110,7 +110,7 @@ const dataAppDevConfig = {externalsType: "module",output: {path: SDK_DIST_PATH,- filename: "data-app-dev.config.js",+ filename: "data-app-dev.config.mjs",library: { type: "module" },},experiments: { outputModule: true },diff --git a/src/metabase/actions/actions.clj b/src/metabase/actions/actions.cljindex 793446c4b1a..98f1aaca700 100644--- a/src/metabase/actions/actions.clj+++ b/src/metabase/actions/actions.clj@@ -152,8 +152,12 @@nil)-(defn- database-for-action [action-or-id]- (actions.db/database-for-action (u/the-id action-or-id)))+(defn- database-for-action+ "The Database `action-or-id` runs against; an ad-hoc action, which has no ID, names it as its `:database_id`."+ [action-or-id]+ (if (and (map? action-or-id) (nil? (:id action-or-id)))+ (some-> (:database_id action-or-id) actions.db/database)+ (actions.db/database-for-action (u/the-id action-or-id))))(defn check-actions-enabled"Throws an appropriate error if actions are unsupported or disabled for the database the action runs against,diff --git a/src/metabase/actions/core.clj b/src/metabase/actions/core.cljindex d73339a2514..d7910059621 100644--- a/src/metabase/actions/core.clj+++ b/src/metabase/actions/core.clj@@ -53,6 +53,7 @@execute-dashcard!fetch-values][metabase.actions.models+ adhoc-actioncheck-action-databases-enabledcheck-implicit-action-table-pkcheck-implicit-actions-supporteddiff --git a/src/metabase/actions/db.clj b/src/metabase/actions/db.cljindex d2b873d33a6..cb137f9c45c 100644--- a/src/metabase/actions/db.clj+++ b/src/metabase/actions/db.clj@@ -63,14 +63,6 @@[card-id :- ::lib.schema.id/card](t2/select-one-fn :collection_id [:model/Card :collection_id] :id card-id))-(mu/defn card-ids-outside-collection- "Among `card-ids`, the IDs of the Cards that are not in the Collection with `collection-id`."- [card-ids :- [:set ::lib.schema.id/card]- collection-id :- ::lib.schema.id/collection]- (t2/select-pks-set :model/Card {:where [:and- [:in :id card-ids]- [:or [:= :collection_id nil] [:not= :collection_id collection-id]]]}))-(mu/defn collection-exists?"Whether the Collection with `collection-id` exists."[collection-id :- ::lib.schema.id/collection]@@ -200,12 +192,6 @@[action-id :- ::lib.schema.id/action](t2/select-one-fn :table_id [:model/ImplicitAction :table_id] :action_id action-id))-(mu/defn table-published? :- :boolean- "Whether the Table with `table-id` is published to the Library."- [table-id :- ::lib.schema.id/table]- (some? (t2/select-one-fn :id [:model/Table :id] :id table-id :is_published true- {:from [(warehouse-schema-overlay/table-query)]})))-(mu/defn tables-with-fields"The Tables with `table-ids`, with their Fields hydrated."[table-ids :- [:sequential ::lib.schema.id/table]]diff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex e59065797a1..8abd2f1116b 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -50,7 +50,7 @@endpoint of shape `{<parameter-id> <value>}`.`action` should already be hydrated with its `:card`. `opts` carries the audit attribution from the endpoint."- [{query :dataset_query, action-id :id, :as action} :- ::actions.schema/action+ [{query :dataset_query, action-id :id, :as action} :- ::actions.schema/action.executablerequest-parameters :- RequestParametersopts :- [:maybe ExecuteActionOpts]](log/tracef "Executing action %d" action-id)@@ -92,7 +92,7 @@(mu/defn- implicit-action-table"The Table, with its Fields, that the implicit `action` writes to: its model's source Table when it has a model."- [{model-id :model_id, table-id :table_id} :- ::actions.schema/action]+ [{model-id :model_id, table-id :table_id} :- ::actions.schema/action.executable](let [table-id (if model-id(:table-id (query/query->database-and-table-ids (actions.db/card-query model-id)))table-id)]@@ -146,7 +146,7 @@[:row-parameters ::actions.args/row][:pk-column :string][:prefetch-parameters {:optional true} [:maybe ::parameters.schema/parameters]]]- [{:keys [parameters] :as action} :- ::actions.schema/action+ [{:keys [parameters] :as action} :- ::actions.schema/action.executableimplicit-action :- ImplicitActionKindrequest-parameters :- RequestParameters](let [{database-id :db_id@@ -236,10 +236,10 @@(mu/defn execute-action!"Execute the given action with the given parameters of shape `{<parameter-id> <value>}."- ([action :- ::actions.schema/action+ ([action :- ::actions.schema/action.executablerequest-parameters :- RequestParameters](execute-action! action request-parameters nil))- ([action :- ::actions.schema/action+ ([action :- ::actions.schema/action.executablerequest-parameters :- RequestParametersopts :- [:maybe ExecuteActionOpts]](let [;; if a value is supplied for a hidden parameter, it should raise an errordiff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex d66dbcf5bba..d93347354c6 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -1,6 +1,5 @@(ns metabase.actions.models(:require- [clojure.string :as str][medley.core :as m][metabase.actions.actions :as actions][metabase.actions.db :as actions.db]@@ -156,41 +155,18 @@(throw (model-collection-error)))(assoc action :collection_id model-collection-id)))-(defn- query-card-ids- "The IDs of the Cards the native `query` reads through card template tags."- [query]- (into #{}- (keep (fn [path]- (let [{:keys [model id]} (last path)]- (when (= "Card" model) id))))- (serdes/mbql-deps true query)))-(defn- data-app-action-error"A 400 error for an action in a data app's collection, with `message`."[message](ex-info message {:status-code 400}))-(defn- check-data-app-action-query- "Throws when `query`, of an action in the Collection with `collection-id`, reads a card outside that collection- while the collection is a data app's."- [collection-id query]- (when (and (some? collection-id)- (perms/data-app-collection? collection-id))- (let [card-ids (query-card-ids query)- outside (when (seq card-ids)- (actions.db/card-ids-outside-collection card-ids collection-id))]- (when (seq outside)- (throw (data-app-action-error- (tru "An action in a data app''s collection can read only the app''s own cards, not card {0}."- (str/join ", " (sort outside)))))))))-(defn- check-data-app-action- "Throws unless `action`, when it is in a data app's collection, is a query or implicit action of no model that is+ "Throws unless `action`, when it is in a data app's collection, is an implicit action on a table, of no model, that isneither archived nor public and whose parameters take no values from a card."[{collection-id :collection_id, :as action}](when (and (some? collection-id) (perms/data-app-collection? collection-id))- (when (or (not (#{:query :implicit} (keyword (:type action)))) (:model_id action))- (throw (data-app-action-error (tru "An action in a data app''s collection must be a query or implicit action of no model."))))+ (when (or (not= :implicit (keyword (:type action))) (:model_id action))+ (throw (data-app-action-error (tru "An action in a data app''s collection must be an implicit action on a table."))))(when (:archived action)(throw (data-app-action-error (tru "An action in a data app''s collection can''t be archived."))))(when (:public_uuid action)@@ -198,17 +174,6 @@(when (some #(= "card" (some-> (:values_source_type %) name)) (:parameters action))(throw (data-app-action-error (tru "An action in a data app''s collection can''t take a parameter''s values from a card."))))))-(defn- check-data-app-action-table- "Throws when an implicit action in the Collection with `collection-id`, a data app's, writes to the Table with- `table-id` while that table is not published to the Library; a load skips this, as it may publish the table later."- [collection-id table-id]- (when (and (some? collection-id)- (some? table-id)- (not mi/*deserializing?*)- (perms/data-app-collection? collection-id)- (not (actions.db/table-published? table-id)))- (throw (data-app-action-error (tru "An implicit action in a data app''s collection can write only to a table published to the Library.")))))-(t2/define-before-insert :model/Action[{model-id :model_id, :as action}](u/prog1 (cond-> (public-sharing/add-public-uuid-prefix action)@@ -233,12 +198,8 @@(check-implicit-actions-supported action))(when (contains? (t2/changes <>) :collection_id)(check-collection-content <>))- (when (some #(contains? (t2/changes <>) %) [:collection_id :type :archived :public_uuid :parameters])- (check-data-app-action <>))- (when (contains? (t2/changes <>) :collection_id)- (check-data-app-action-query (:collection_id <>) (:dataset_query (actions.db/query-action (:id <>))))- (when (implicit? <>)- (check-data-app-action-table (:collection_id <>) (actions.db/implicit-action-table-id (:id <>))))))))+ (when (some #(contains? (t2/changes <>) %) [:collection_id :type :model_id :archived :public_uuid :parameters])+ (check-data-app-action <>)))))(defn- set-query-database"`query-action` with the `:database_id` of its query, when it has one, as a row copied whole may hold its query@@ -250,14 +211,11 @@(t2/define-before-insert :model/QueryAction[query-action]- (u/prog1 (set-query-database query-action)- (check-data-app-action-query (actions.db/action-collection-id (:action_id <>)) (:dataset_query <>))))+ (set-query-database query-action))(t2/define-before-update :model/QueryAction[query-action]- (u/prog1 (set-query-database query-action)- (when (contains? (t2/changes query-action) :dataset_query)- (check-data-app-action-query (actions.db/action-collection-id (:action_id <>)) (:dataset_query <>)))))+ (set-query-database query-action))(defn- check-implicit-action-table"Throws a 400 unless `implicit-action` has a Table exactly when its Action has no model, as an action of a model writes@@ -285,25 +243,16 @@(when-not (= 1 (count (filter #(isa? (:semantic_type %) :type/PK) fields)))(throw (ex-info (tru "An implicit action needs a table with exactly one primary key.") {:status-code 400}))))))-(defn- check-model-less-implicit-action-table- "Throws a 400 when the Table of `implicit-action`, an action without a model, is not published to the Library while- the action is in a data app's collection."- [{table-id :table_id, action-id :action_id}]- (when table-id- (check-data-app-action-table (actions.db/action-collection-id action-id) table-id)))-(t2/define-before-update :model/ImplicitAction[implicit-action](u/prog1 implicit-action(when (contains? (t2/changes implicit-action) :table_id)- (check-implicit-action-table implicit-action)- (check-model-less-implicit-action-table implicit-action))))+ (check-implicit-action-table implicit-action))))(t2/define-before-insert :model/ImplicitAction[implicit-action](u/prog1 implicit-action- (check-implicit-action-table implicit-action)- (check-model-less-implicit-action-table implicit-action)))+ (check-implicit-action-table implicit-action)))(defn- action-database-ids"The ids of the Databases `action` runs against: its query's, or for an implicit action its model's or its table's."@@ -652,6 +601,16 @@(enrich-implicit-action action (table-id->db-id table-id) (table-id->params table-id) field-id->viz))action))))+(mu/defn adhoc-action :- ::actions.schema/action.for-insert+ "The ad-hoc `action`, built without saving it: an implicit one with its parameters derived from its Table, and a query+ one writing to the database of its query."+ [action :- ::actions.schema/action.adhoc]+ (t2/instance :model/Action+ (if (= :implicit (keyword (:type action)))+ (first (enrich-actions-with-implicit-params+ [(merge {:visualization_settings {}} action)]))+ (assoc action :database_id (get-in action [:dataset_query :database])))))+(mu/defn select-actions :- [:maybe [:sequential ::actions.schema/action]]"Find actions with given options and generate implicit parameters for execution. Also adds the `:database_id` of thetable for implicit actions."diff --git a/src/metabase/actions/schema.clj b/src/metabase/actions/schema.cljindex 0ee561b067f..060c470c139 100644--- a/src/metabase/actions/schema.clj+++ b/src/metabase/actions/schema.clj@@ -184,6 +184,10 @@"Schema for inserting a new Action internally."(action-schema :insert false))+(mr/def ::action.executable+ "An Action that can be executed: one selected from the app DB, or an ad-hoc one built without saving it."+ [:or ::action ::action.for-insert])+(mr/def ::action.for-update"Schema for updating an Action internally."(action-schema :update false))@@ -192,6 +196,10 @@"Schema for the REST API body that creates an Action, without the columns the server populates."(action-schema :insert true))+(mr/def ::action.adhoc+ "Schema for an ad-hoc Action, which runs without being saved, as its create request would describe it."+ ::action.create-request)+(mr/def ::action.update-request"Schema for the REST API body that updates an Action, without the columns the server populates."(action-schema :update true))diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.cljindex 2b30e2f2307..ae8778acb93 100644--- a/src/metabase/actions_rest/api.clj+++ b/src/metabase/actions_rest/api.clj@@ -218,6 +218,20 @@(contains? slug->id k) (get slug->id k):else k)))))+(api.macros/defendpoint :post "/execute" :- :map+ "Execute the ad-hoc `action`, without saving it. Superusers only."+ {:scope api-scope/data-app}+ [_route-params+ _query-params+ {:keys [action parameters]} :- [:map {:closed true}+ [:action ::actions.schema/action.adhoc]+ [:parameters {:optional true} [:maybe ::actions.schema/execute-parameter-values]]]+ request]+ (api/check-superuser)+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-action action))+ (let [action (actions/adhoc-action action)]+ (actions/execute-action! action (remap-parameter-keys action (update-keys parameters name)))))+;; 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;;diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex bb2314ca001..df3b8bd8823 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -627,9 +627,9 @@(when (and collection-id(some? model-type)(not= :model/CollectionBookmark model-type)- (not (contains? #{:question :dashboard-question :metric :action} (keyword model-type)))+ (not (contains? #{:question :dashboard-question :action} (keyword model-type)))(perms/data-app-collection? collection-id))- (throw (ex-info "A data app's collection can hold only questions, metrics, and query actions" {:status-code 400})))+ (throw (ex-info (tru "A data app''s collection can hold only questions and implicit actions.") {:status-code 400})))(check-library-content model-type collection-id))(defenterprise check-library-updatediff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex dd95d92f5ee..7ae19f8ba10 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -8,7 +8,6 @@[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]@@ -22,7 +21,6 @@[metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.dashboards.models.dashboard-tab :as dashboard-tab][metabase.dashboards.settings :as dashboards.settings]- [metabase.data-apps.core :as data-apps][metabase.eid-translation.core :as eid-translation][metabase.embedding.validation :as embedding.validation][metabase.events.core :as events]@@ -689,16 +687,13 @@: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}[:dashboard_load_id {:optional true} [:maybe ms/NonBlankString]]]- _body- request]+ _body](with-dashboard-load-id dashboard-load-id(let [resolved-id (eid-translation/->id-or-404 :dashboard id)- _ (some-> (data-apps/request-data-app request) (data-apps/check-dashboard resolved-id))dashboard (get-dashboard resolved-id)](u/prog1 (first (revisions/with-last-edit-info [dashboard] :dashboard))(events/publish-event! :event/dashboard-read {:object-id (:id dashboard) :user-id api/*current-user-id*})))))@@ -1193,17 +1188,14 @@: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}[:dashboard_load_id {:optional true} [:maybe ms/NonBlankString]]]- _body- request]+ _body](with-dashboard-load-id dashboard-load-id(perms/with-relevant-permissions-for-user api/*current-user-id*(let [resolved-id (eid-translation/->id-or-404 :dashboard id)- _ (some-> (data-apps/request-data-app request) (data-apps/check-dashboard resolved-id))dashboard (get-dashboard resolved-id)](queries/batch-fetch-dashboard-metadata [dashboard])))))@@ -1351,14 +1343,11 @@;; 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]]constraint-param-key->value :- (ms/string-keyed-map [:ref ::lib.schema.parameter/parameter.value])- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard id))+ _body](let [dashboard (api/read-check :model/Dashboard id)];; If a user can read the dashboard, then they can lookup filters. This also works with sandboxing.(binding [qp.perms/*param-values-query* true]@@ -1377,15 +1366,12 @@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][:query ms/NonBlankString]]constraint-param-key->value :- (ms/string-keyed-map [:ref ::lib.schema.parameter/parameter.value])- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard id))+ _body](let [dashboard (api/read-check :model/Dashboard id)];; If a user can read the dashboard, then they can lookup filters. This also works with sandboxing.(binding [qp.perms/*param-values-query* true@@ -1401,14 +1387,11 @@;; 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]]{:keys [value]} :- [:map {:closed true} [:value :string]]- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard id))+ _body](let [dashboard (api/read-check :model/Dashboard id)](binding [qp.perms/*param-values-query* true](parameters.dashboard/dashboard-param-remapped-value dashboard param-key (codec/url-decode value)))))@@ -1438,20 +1421,15 @@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)][:filtering {:optional true} [:maybe (ms/QueryVectorOf ::lib.schema.id/field)]]]- _body- request]+ _body](let [filtered-field-ids (if (sequential? filtered) (set filtered) #{filtered})- filtering-field-ids (if (sequential? filtering) (set filtering) #{filtering})- data-app (data-apps/request-data-app request)]+ filtering-field-ids (if (sequential? filtering) (set filtering) #{filtering})](doseq [field-id (set/union filtered-field-ids filtering-field-ids)]- (if data-app- (data-apps/check-field data-app field-id)- (api/read-check :model/Field field-id)))+ (api/read-check :model/Field field-id))(into {} (for [field-id filtered-field-ids][field-id (sort (chain-filter/filterable-field-ids field-id filtering-field-ids))]))))@@ -1461,15 +1439,12 @@"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]]_query-params{:keys [parameters]} :- [:map {:closed true}- [:parameters {:optional true} ::actions.schema/prefetch-parameter-values]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard dashboard-id))+ [:parameters {:optional true} ::actions.schema/prefetch-parameter-values]]](api/read-check :model/Dashboard dashboard-id)(let [dashcard (api/check-404 (dashboards-rest.db/dashcard-in-dashboard dashcard-id dashboard-id))](actions/fetch-values@@ -1485,16 +1460,13 @@`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]]_query-params{:keys [parameters]} :- [:map {:closed true}[:parameters {:optional true}- [:maybe ::actions.schema/execute-parameter-values.string-keys]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard dashboard-id))+ [:maybe ::actions.schema/execute-parameter-values.string-keys]]]](api/read-check :model/Dashboard dashboard-id)(actions/execute-dashcard! dashboard-id dashcard-id parameters))@@ -1506,7 +1478,6 @@#_{: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]@@ -1514,9 +1485,7 @@_query-params{:keys [dashboard_load_id], :as body} :- [:map {:closed true}[:dashboard_load_id {:optional true} [:maybe ms/NonBlankString]]- [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard dashboard-id))+ [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]](with-dashboard-load-id dashboard_load_id(m/mapply qp.dashboard/process-query-for-dashcard(merge@@ -1535,7 +1504,6 @@`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]@@ -1548,9 +1516,7 @@:- [:map {:closed true}[:parameters {:optional true} [:maybe ::parameters.schema/api.parameter-values]][:format_rows {:default false} ms/BooleanValue]- [:pivot_results {:default false} ms/BooleanValue]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard dashboard-id))+ [:pivot_results {:default false} ms/BooleanValue]]](m/mapply qp.dashboard/process-query-for-dashcard{:dashboard (api/check-404 (dashboards-rest.db/dashboard dashboard-id)):card (api/check-404 (dashboards-rest.db/card card-id))@@ -1575,16 +1541,13 @@#_{: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][:card-id ms/PositiveInt]]_query-paramsbody :- [:map {:closed true}- [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-dashboard dashboard-id))+ [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]](m/mapply qp.dashboard/process-query-for-dashcard(mergebodydiff --git a/src/metabase/data_apps/core.clj b/src/metabase/data_apps/core.cljindex 5747b7a3e22..c7f5c7d5fe7 100644--- a/src/metabase/data_apps/core.clj+++ b/src/metabase/data_apps/core.clj@@ -7,8 +7,6 @@[metabase.data-apps.schema :as data-apps.schema][metabase.lib-be.schema :as lib-be.schema][metabase.lib.schema.id :as lib.schema.id]- [metabase.lib.schema.parameter :as lib.schema.parameter]- [metabase.parameters.schema :as parameters.schema][metabase.premium-features.core :refer [defenterprise defenterprise-schema]]))(defenterprise visible-data-app-filter-select@@ -37,6 +35,12 @@(contains? token-scopes ::scope/unrestricted)(contains? token-scopes "*")))+(defn data-app-dev-request?+ "Whether `request` comes from a data app's dev preview, which runs the app's queries and actions without them existing+ on the instance; it says so with the `X-Metabase-Data-App-Dev: true` header."+ [request]+ (= "true" (get-in request [:headers "x-metabase-data-app-dev"])))+(defn data-app-request?"Whether `request` is confined to the data-app scope: marked by the data-app scope middleware, or authorized by a tokenwhose scopes, short of full access, grant it."@@ -47,17 +51,17 @@(scope/scope-satisfied? (into #{} (filter string?) token-scopes) api-scope/data-app)))))(defenterprise request-data-app- "The data app whose slug a data-app `request` names by [[data-app-slug]], read-checked; nil for a request that is not- a data app's, or without the data-apps feature."+ "What a data-app `request` is checked as: the app its slug names by [[data-app-slug]], read-checked, or a dev preview+ of it; nil for a request that is not a data app's, or without the data-apps feature."metabase-enterprise.data-apps.checks[_request]nil)-(defenterprise-schema check-query :- :nil+(defenterprise-schema check-adhoc-query :- :nil"Throws a 400 unless `data-app` may run `query`, an MBQL or internal query as the `/api/dataset` endpoints take it;does nothing without the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_query :- ::lib-be.schema/maybe-legacy-or-internal-query]nil)@@ -65,40 +69,29 @@"Throws a 400 unless `data-app` may use the card with `card-id`, after a read check of the card; does nothing withoutthe data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_card-id :- ::lib.schema.id/card]nil)-(defenterprise-schema check-card-parameter :- :nil- "Throws a 400 unless `data-app` may use the card with `card-id` and the card its parameter `param-key` takes its- values from, after read checks of both; does nothing without the data-apps feature."- metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app- _card-id :- ::lib.schema.id/card- _param-key :- ::lib.schema.parameter/id]- nil)--(defenterprise-schema check-parameter :- :nil- "Throws a 400 unless `data-app` may load values for the ad-hoc `parameter` from its source or the fields with- `field-ids`; does nothing without the data-apps feature."- metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app- _parameter :- ::parameters.schema/parameter- _field-ids :- [:maybe [:sequential ::lib.schema.id/field]]]- nil)-(defenterprise-schema check-action :- :nil"Throws a 400 unless `data-app` may run the action with `action-id`, after a read check of the action; does nothingwithout the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_action-id :- ::lib.schema.id/action]nil)+(defenterprise-schema check-adhoc-action :- :nil+ "Throws a 400 unless `data-app` may run the ad-hoc `action`; does nothing without the data-apps feature."+ metabase-enterprise.data-apps.checks+ [_data-app :- ::data-apps.schema/data-app-info+ _action :- ::actions.schema/action.adhoc]+ nil)+(defenterprise-schema data-app-actions :- [:sequential ::actions.schema/action]"The `actions` that `data-app` may use; all of them without the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-infoactions :- [:sequential ::actions.schema/action]]actions)@@ -106,7 +99,7 @@"Throws a 400 unless `data-app` may read the table with `table-id`, after a read check of the table; does nothingwithout the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_table-id :- ::lib.schema.id/table]nil)@@ -114,7 +107,7 @@"Throws a 400 unless `data-app` may read the field with `field-id`, after a read check of the field; does nothingwithout the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_field-id :- ::lib.schema.id/field]nil)@@ -122,7 +115,7 @@"Throws a 400 unless `data-app` may read the database with `database-id`, after a read check of the database; doesnothing without the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_database-id :- ::lib.schema.id/database]nil)@@ -130,7 +123,7 @@"Throws a 400 unless `data-app` may use the user key-value `k` in `nmspace`; does nothing without the data-appsfeature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_nmspace :- :string_k :- :string]nil)@@ -138,21 +131,13 @@(defenterprise-schema data-app-collection-types :- [:maybe [:set :string]]"The types of the collections that `data-app` may see, or nil, meaning any, without the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app]+ [_data-app :- ::data-apps.schema/data-app-info]nil)(defenterprise-schema check-collection :- :nil"Throws a 400 unless `data-app` may see the collection with `collection-id`, after a read check of the collection;does nothing without the data-apps feature."metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app+ [_data-app :- ::data-apps.schema/data-app-info_collection-id :- ::lib.schema.id/collection]nil)--(defenterprise-schema check-dashboard :- :nil- "Throws a 400 unless `data-app` may use the dashboard with `dashboard-id`, after a read check of the dashboard; does- nothing without the data-apps feature."- metabase-enterprise.data-apps.checks- [_data-app :- ::data-apps.schema/data-app- _dashboard-id :- ::lib.schema.id/dashboard]- nil)diff --git a/src/metabase/data_apps/schema.clj b/src/metabase/data_apps/schema.cljindex f903de7e461..05f8d857b5b 100644--- a/src/metabase/data_apps/schema.clj+++ b/src/metabase/data_apps/schema.clj@@ -12,7 +12,7 @@(def ^:private reserved-slugs"Slugs that collide with literal `/api/ee/apps/*` sub-routes, so an app with one would be unreachable."- #{"repo-status" "sandbox-host"})+ #{"repo-status" "sandbox-host" "generate"})(defn- decoders"Schema properties decoding a value with `f` both in [[metabase.lib.core/normalize]] and at the API boundary."@@ -86,10 +86,6 @@bytes?[:fn {:error/message "must be less than 10 MiB"} #(<= (alength ^bytes %) max-bundle-bytes)]])-(mr/def ::bundle-text- "The text of a data app's bundle file."- [:string {:max max-bundle-bytes}])-(mr/def ::data-app"A DataApp as selected from the app DB: every column of `:data_app`."[:merge@@ -98,6 +94,17 @@[:id ms/PositiveInt][:bundle_hash {:optional true} [:maybe :string]]]])+(mr/def ::data-app-preview+ "A data app's dev preview: the slug its manifest declares, whether or not the app exists on the instance."+ [:map {:closed true}+ [:slug :string]])++(mr/def ::data-app-info+ "What a data app's request is checked as: the app it names, or a dev preview of one, which has no ID."+ [:multi {:dispatch #(if (contains? % :id) :app :preview)}+ [:app ::data-app]+ [:preview ::data-app-preview]])+(mr/def ::data-app.update"What an update (or insert) of a DataApp accepts: every column of `:data_app` except `id` and the `bundle_hash` themodel computes, all optional."diff --git a/src/metabase/eid_translation/api.clj b/src/metabase/eid_translation/api.cljindex 48661d9f4b1..e08bbce8308 100644--- a/src/metabase/eid_translation/api.clj+++ b/src/metabase/eid_translation/api.clj@@ -1,6 +1,7 @@(ns metabase.eid-translation.api"`/api/eid-translation` routes."(:require+ [metabase.api-scope.data-app :as api-scope][metabase.api.macros :as api.macros][metabase.eid-translation.schema :as eid-translation.schema][metabase.eid-translation.util :as eid-translation]))@@ -11,6 +12,7 @@#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/translate""Translate entity IDs to model IDs."+ {:scope api-scope/data-app}[_route-params_query-params{:keys [entity_ids]} :- [:map {:closed true}diff --git a/src/metabase/native_query_snippets/api.clj b/src/metabase/native_query_snippets/api.cljindex 6f792f3aeb4..53e09d263ef 100644--- a/src/metabase/native_query_snippets/api.clj+++ b/src/metabase/native_query_snippets/api.clj@@ -2,7 +2,6 @@"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]@@ -31,7 +30,6 @@#_{: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]]]]diff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.cljindex 81adb9d8c5d..074aac76219 100644--- a/src/metabase/queries/db.clj+++ b/src/metabase/queries/db.clj@@ -4,7 +4,6 @@methods."(:require[metabase.app-db.core :as mdb]- [metabase.collections.core :as collections][metabase.dashboards.schema :as dashboards.schema][metabase.lib-be.schema :as lib-be.schema][metabase.lib.schema.id :as lib.schema.id]@@ -567,27 +566,3 @@:id [:in ^:allow-subquery {:select [:stored_result_id]:from [:stored_result_use]:where [:= :card_id card-id]}]))--(mu/defn unpublished-table-names :- [:set :string]- "Among the Tables with `table-ids`, the names of those not published to the Library."- [table-ids :- [:set {:min 1} ::lib.schema.id/table]]- (or (t2/select-fn-set :name [:model/Table :name] :id [:in table-ids] :is_published false- {:from [(warehouse-schema-overlay/table-query)]})- #{}))--(mu/defn library-metric-ids :- [:set ::lib.schema.id/card]- "Among `card-ids`, the IDs of the metrics in the Library's Metrics collection or one of its subcollections."- [card-ids :- [:set {:min 1} ::lib.schema.id/card]]- (or (t2/select-fn-set :id [:model/Card :report_card.id] {:join [:collection [:= :collection.id :report_card.collection_id]]- :where [:and- [:in :report_card.id card-ids]- [:= :report_card.type "metric"]- [:= :collection.type collections/library-metrics-collection-type]]})- #{}))--(defn card-ids-outside-collection- "Among `card-ids`, the IDs of the cards that are not in the collection with `collection-id`."- [card-ids collection-id]- (t2/select-pks-set :model/Card {:where [:and- [:in :id card-ids]- [:or [:= :collection_id nil] [:not= :collection_id collection-id]]]}))diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 64ff60280c8..d2c0c329bf7 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -4,7 +4,6 @@(:require[better-cond.core :as b][clojure.set :as set]- [clojure.string :as str][honey.sql.helpers :as sql.helpers][medley.core :as m][metabase.analytics-interface.core :as analytics]@@ -22,7 +21,6 @@[metabase.lib-be.core :as lib-be][metabase.lib-be.schema :as lib-be.schema][metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata]@@ -997,76 +995,32 @@[message](ex-info message {:status-code 400}))-(defn- card-labels- "The cards with `card-ids` as they appear in an error, by name and ID."- [metadata-providerable card-ids]- (str/join ", " (for [{card-name :name, card-id :id} (sort-by :id (lib.metadata/bulk-metadata metadata-providerable :metadata/card card-ids))]- (format "\"%s\" (%d)" card-name card-id))))--(defn- tables-read- "The IDs of the tables `query` reads: its source tables, explicit joins included, and the tables it reaches through a- foreign key."- [query]- (set/union (set (lib/all-source-table-ids query))- (set (lib/all-implicitly-joined-table-ids query))))--(defn- macro-tables-read- "The IDs of the tables that the definitions of the segments and measures `query` uses read."- [query]- (into #{}- (comp (keep :definition)- (filter (comp seq :stages))- (mapcat #(tables-read (lib/query query %))))- (concat (some->> (lib/all-segment-ids query) (lib.metadata/bulk-metadata query :metadata/segment))- (some->> (lib/all-measure-ids query) (lib.metadata/bulk-metadata query :metadata/measure)))))--(defn- remapped-tables-read- "The IDs of the tables whose columns replace a column `query` returns, through a foreign key remapping."- [query]- (into #{}- (keep :table-id)- (some->> (lib/returned-columns query)- (keep (comp :field-id :lib/external-remap))- not-empty- (lib.metadata/bulk-metadata query :metadata/column))))-(defn- check-data-app-card-query- "Returns the IDs of the Library metrics `dataset_query` aggregates, and throws unless it is an MBQL query on a- database, based on no card, that reads only tables published to the Library, through its segments, measures and- remapped columns too; a load skips the published check, since it may load a table's published state later."+ "Throws unless `dataset_query` is an MBQL query on a database of a single stage that reads a table, with no explicit+ joins or custom columns; the metrics, segments and measures it names may be any."[{:keys [dataset_query]}](when-not (:database dataset_query)(throw (data-app-card-error (tru "A card in a data app''s collection must hold a query on a database."))))- (let [query (lib/query (lib-be/application-database-metadata-provider (:database dataset_query)) dataset_query)- metric-ids (set (lib/all-metric-ids query))- card-ids (set/difference (set (lib/all-source-card-ids query)) metric-ids)]+ (let [query (lib-be/normalize-query dataset_query)](when (lib/any-native-stage? query)(throw (data-app-card-error (tru "A card in a data app''s collection must be built with the query builder, not SQL."))))- (when (seq card-ids)- (throw (data-app-card-error (tru "A card in a data app''s collection can read only tables published to the Library, not the card {0}."- (card-labels query card-ids)))))- (when-let [outside (seq (when (seq metric-ids)- (set/difference metric-ids (queries.db/library-metric-ids metric-ids))))]- (throw (data-app-card-error (tru "A card in a data app''s collection can use only metrics from the Library, not the metric {0}."- (card-labels query outside)))))- (when-not mi/*deserializing?*- (when-let [unpublished (seq (some-> (not-empty (set/union (tables-read query)- (macro-tables-read query)- (remapped-tables-read query)))- queries.db/unpublished-table-names))]- (throw (data-app-card-error (tru "A card in a data app''s collection can read only tables published to the Library, not {0}. Publish them, or read other tables."- (str/join ", " (sort unpublished)))))))- metric-ids))+ (when (not= 1 (lib/stage-count query))+ (throw (data-app-card-error (tru "A card in a data app''s collection must be a query of a single stage."))))+ (when (or (lib/primary-source-card-id query) (nil? (lib/primary-source-table-id query)))+ (throw (data-app-card-error (tru "A card in a data app''s collection must read a table, not a card."))))+ (when (seq (lib/joins query))+ (throw (data-app-card-error (tru "A card in a data app''s collection can''t join tables explicitly."))))+ (when (seq (lib/expressions query))+ (throw (data-app-card-error (tru "A card in a data app''s collection can''t have custom columns."))))))(defn- check-data-app-card- "Throws unless `card`, when it is in a data app's collection, is a question or metric in no dashboard or document, not- archived, public or embedded, whose query reads only the Library, and whose other references, such as parameter- values, name only cards in the collection."+ "Throws unless `card`, when it is in a data app's collection, is a question in no dashboard or document, not archived,+ public or embedded, with no parameters, whose query reads a table in a single stage."[{:keys [collection_id] :as card}](when (and (some? collection_id)(perms/data-app-collection? collection_id));; a new card without a type is a question, the column's default- (when (or (not (contains? #{:question :metric} (keyword (or (:type card) :question))))+ (when (or (not= :question (keyword (or (:type card) :question)))(:dashboard_id card)(:document_id card)(:archived card)@@ -1074,23 +1028,15 @@(:enable_embedding card)(:embedding_params card)(:embedding_type card))- (throw (data-app-card-error (tru "A card in a data app''s collection must be a question or metric, in no dashboard or document, that is not archived, public or embedded."))))- (let [metric-ids (check-data-app-card-query card)- card-ids (into #{}- (keep (fn [path]- (let [{:keys [model id]} (last path)]- (when (and (= "Card" model) (not (metric-ids id))) id))))- (serdes/serialization-dependencies "Card" card))- outside (when (seq card-ids)- (queries.db/card-ids-outside-collection card-ids collection_id))]- (when (seq outside)- (throw (data-app-card-error (tru "A card in a data app''s collection can reference only the app''s own cards and Library metrics, not card {0}."- (str/join ", " (sort outside)))))))))+ (throw (data-app-card-error (tru "A card in a data app''s collection must be a question, in no dashboard or document, that is not archived, public or embedded."))))+ (when (seq (:parameters card))+ (throw (data-app-card-error (tru "A card in a data app''s collection can''t have parameters."))))+ (check-data-app-card-query card)))(def ^:private data-app-card-columns"The columns [[check-data-app-card]] reads; an update that changes none of them leaves a card as it was checked."#{:collection_id :dashboard_id :document_id :type :archived :public_uuid :enable_embedding :embedding_params- :embedding_type :dataset_query :parameters :parameter_mappings :visualization_settings})+ :embedding_type :dataset_query :parameters})(t2/define-before-insert :model/Card[card]@@ -1183,7 +1129,6 @@;; populate-query-fields must run before pre-update in case source_card_id should be nilled.;; Only allow it to nil out a stale table_id when the query itself is changing.(populate-query-fields (contains? changes :dataset_query))- ;; after the query's columns are set again: `source_card_id` is one of the references it reads(cond-> (some data-app-card-columns (keys changes)) (doto check-data-app-card))(clear-metabot-origin changes)(pre-update changes)diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex 5644fe2fac4..03509ff2205 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -984,14 +984,11 @@;; 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]]_query-params- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-card-parameter card-id param-key))+ _body](binding [qp.perms/*param-values-query* true](queries/card-param-values (api/read-check :model/Card card-id) param-key)))@@ -1006,15 +1003,12 @@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][:query ms/NonBlankString]]_query-params- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-card-parameter card-id param-key))+ _body](binding [qp.perms/*param-values-query* true](queries/card-param-values (api/read-check :model/Card card-id) param-key query)))@@ -1027,14 +1021,11 @@;; 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]]{:keys [value]} :- [:map {:closed true} [:value :string]]- _body- request]- (some-> (data-apps/request-data-app request) (data-apps/check-card-parameter id param-key))+ _body](binding [qp.perms/*param-values-query* true](-> (api/read-check :model/Card id)(queries/card-param-remapped-value param-key (codec/url-decode value)))))diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.cljindex f5379ed021c..cf07be21831 100644--- a/src/metabase/query_processor/api.clj+++ b/src/metabase/query_processor/api.clj@@ -109,7 +109,7 @@_query-paramsquery :- ::lib-be.schema/maybe-legacy-or-internal-queryrequest]- (some-> (data-apps/request-data-app request) (data-apps/check-query query))+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-query query))(run-streaming-query(-> query(dissoc :cache-strategy)@@ -164,7 +164,7 @@[:pivot_results {:default false} ms/BooleanValue][:csv_include_bom {:default false} ms/BooleanValue]]request]- (some-> (data-apps/request-data-app request) (data-apps/check-query query))+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-query query))(let [viz-settings (-> visualization-settingsmi/normalize-visualization-settingsmb.viz/norm->db)@@ -203,7 +203,7 @@_query-paramsquery :- ::lib-be.schema/maybe-legacy-queryrequest]- (some-> (data-apps/request-data-app request) (data-apps/check-query query))+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-query query))(queries/batch-fetch-query-metadata[query](when-some [include-sensitive-fields (get-in query [:settings :include-sensitive-fields])]@@ -222,7 +222,7 @@[:pretty {:default true} [:maybe :boolean]][::mc/default ::lib-be.schema/maybe-legacy-query]]request]- (some-> (data-apps/request-data-app request) (data-apps/check-query (dissoc query :pretty)))+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-query (dissoc query :pretty)))(model-persistence/with-persisted-substituion-disabled(let [query (-> (lib-be/normalize-query (dissoc query :pretty))(dissoc :constraints :middleware)@@ -257,7 +257,7 @@_query-params{:keys [database] :as query} :- ::lib-be.schema/maybe-legacy-queryrequest]- (some-> (data-apps/request-data-app request) (data-apps/check-query query))+ (some-> (data-apps/request-data-app request) (data-apps/check-adhoc-query query))(api/read-check :model/Database database)(let [info {:executed-by api/*current-user-id*:context :ad-hoc}]@@ -299,15 +299,12 @@#_{: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]field-ids :field_ids} :- [:map {:closed true}[:parameter ::parameters.schema/parameter]- [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-parameter parameter field-ids))+ [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]](parameter-values parameter field-ids nil));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -316,16 +313,13 @@#_{: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{:keys [parameter]field-ids :field_ids} :- [:map {:closed true}[:parameter ::parameters.schema/parameter]- [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-parameter parameter field-ids))+ [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]](parameter-values parameter field-ids query))(defn param-remapped-value@@ -348,13 +342,10 @@#_{: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}[:parameter ::parameters.schema/parameter][:value [:ref ::lib.schema.parameter/parameter.value]]- [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]- request]- (some-> (data-apps/request-data-app request) (data-apps/check-parameter parameter field_ids))+ [:field_ids {:optional true} [:maybe [:sequential ::lib.schema.id/field]]]]](param-remapped-value field_ids parameter value))diff --git a/src/metabase/search/api.clj b/src/metabase/search/api.cljindex ecadf2c67f4..208281a2df5 100644--- a/src/metabase/search/api.clj+++ b/src/metabase/search/api.clj@@ -301,15 +301,18 @@:display-type (set display-type)}))(defn- data-app-search-params- "`query-params` narrowed, for a data-app `request`, to the Library's content; without a Library, the search looks for- tables in the Trash, which holds none."+ "`query-params` narrowed, for a data-app `request`, to the Library's tables and metrics among the models it asks for;+ without a Library or such a model, the search looks for tables in the Trash, which holds none."[request query-params](if (data-apps/request-data-app request)- (if-let [library (collections/library-collection)]- (assoc query-params :collection (:id library))- (-> query-params- (dissoc :ids)- (assoc :models ["table"] :collection (collections/trash-collection-id))))+ (let [models (cond->> ["table" "metric"]+ (seq (:models query-params)) (filterv (set (:models query-params))))+ library (when (seq models) (collections/library-collection))]+ (if library+ (assoc query-params :models models :collection (:id library))+ (-> query-params+ (dissoc :ids)+ (assoc :models ["table"] :collection (collections/trash-collection-id)))))query-params))#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-casediff --git a/src/metabase/timeline/api/timeline.clj b/src/metabase/timeline/api/timeline.cljindex 26b4e594ba6..aa68f9e8092 100644--- a/src/metabase/timeline/api/timeline.clj+++ b/src/metabase/timeline/api/timeline.clj@@ -1,7 +1,6 @@(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]@@ -60,7 +59,6 @@(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/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex cdb6ddc978d..75e2f2768c6 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -622,8 +622,8 @@;;; --------------------------------- GET /api/database/:id/autocomplete_suggestions ----------------------------------(defn- autocomplete-tables [db-id like-pattern limit published-only?]- (warehouses-rest.db/autocomplete-tables db-id like-pattern limit published-only?))+(defn- autocomplete-tables [db-id like-pattern limit]+ (warehouses-rest.db/autocomplete-tables db-id like-pattern limit))(defn- autocomplete-cards"Returns cards that match the search string in the given database, ordered by id.@@ -636,8 +636,8 @@[database-id search-card-slug include-dashboard-questions?](warehouses-rest.db/autocomplete-cards database-id search-card-slug include-dashboard-questions?))-(defn- autocomplete-fields [db-id like-pattern limit published-only?]- (warehouses-rest.db/autocomplete-fields db-id like-pattern limit published-only?))+(defn- autocomplete-fields [db-id like-pattern limit]+ (warehouses-rest.db/autocomplete-fields db-id like-pattern limit))(defn- autocomplete-results [tables fields limit](let [tbl-count (count tables)@@ -655,11 +655,11 @@(defn- autocomplete-suggestions"`like-pattern` is a `LIKE` right-hand side (see [[h2x/like-substring]] and [[h2x/like-prefix]]) matched against- lowercased table and field names; only published tables and their fields when `published-only?`."- [db-id like-pattern published-only?]+ lowercased table and field names."+ [db-id like-pattern](let [limit 50- tables (filter mi/can-read? (autocomplete-tables db-id like-pattern limit published-only?))- fields (readable-fields-only (autocomplete-fields db-id like-pattern limit published-only?))]+ tables (filter mi/can-read? (autocomplete-tables db-id like-pattern limit))+ fields (readable-fields-only (autocomplete-fields db-id like-pattern limit))](autocomplete-results tables fields limit)));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API@@ -679,31 +679,27 @@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}[:prefix {:optional true} [:maybe ms/NonBlankString]]- [:substring {:optional true} [:maybe ms/NonBlankString]]]- _body- request]+ [:substring {:optional true} [:maybe ms/NonBlankString]]]](api/read-check (warehouses/get-database id))(when (and (str/blank? prefix) (str/blank? substring))(throw (ex-info (tru "Must include prefix or search") {:status-code 400})))- (let [published-only? (some? (data-apps/request-data-app request))]- (try- {:status 200- ;; Presumably user will repeat same prefixes many times writing the query,- ;; so let them cache response to make autocomplete feel fast. 60 seconds- ;; is not enough to be a nuisance when schema or permissions change. Cache- ;; is user-specific since we're checking for permissions.- :headers {"Cache-Control" "public, max-age=60"- "Vary" "Cookie, X-Metabase-Client"}- :body (cond- substring (autocomplete-suggestions id (h2x/like-substring substring) published-only?)- prefix (autocomplete-suggestions id (h2x/like-prefix prefix) published-only?))}- (catch Throwable e- (log/warnf "Error with autocomplete: %s" (ex-message e))))))+ (try+ {:status 200+ ;; Presumably user will repeat same prefixes many times writing the query,+ ;; so let them cache response to make autocomplete feel fast. 60 seconds+ ;; is not enough to be a nuisance when schema or permissions change. Cache+ ;; is user-specific since we're checking for permissions.+ :headers {"Cache-Control" "public, max-age=60"+ "Vary" "Cookie"}+ :body (cond+ substring (autocomplete-suggestions id (h2x/like-substring substring))+ prefix (autocomplete-suggestions id (h2x/like-prefix prefix)))}+ (catch Throwable e+ (log/warnf "Error with autocomplete: %s" (ex-message e)))));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;@@ -719,23 +715,18 @@"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}[:query ms/NonBlankString]- [:include_dashboard_questions {:optional true} ms/BooleanValue]]- _body- request]+ [:include_dashboard_questions {:optional true} ms/BooleanValue]]](api/read-check (warehouses/get-database id))- (if (some? (data-apps/request-data-app request))- []- (try- (->> (autocomplete-cards id query include_dashboard_questions)- (filter mi/can-read?)- (map #(select-keys % [:id :name :type :collection_name])))- (catch Throwable e- (log/warnf "Error with autocomplete: %s" (ex-message e))))))+ (try+ (->> (autocomplete-cards id query include_dashboard_questions)+ (filter mi/can-read?)+ (map #(select-keys % [:id :name :type :collection_name])))+ (catch Throwable e+ (log/warnf "Error with autocomplete: %s" (ex-message e)))));;; ------------------------------------------ GET /api/database/:id/fields ------------------------------------------diff --git a/src/metabase/warehouses_rest/db.clj b/src/metabase/warehouses_rest/db.cljindex 52969f60d17..35a66c16271 100644--- a/src/metabase/warehouses_rest/db.clj+++ b/src/metabase/warehouses_rest/db.clj@@ -125,20 +125,16 @@(mu/defn autocomplete-tables"Up to `limit` id, Database id, schema, and name rows of the active, visible Tables of the Database with`database-id` whose lower-cased name matches the SQL LIKE `like-pattern` (a Honey SQL LIKE right-hand side, see- `metabase.util.honey-sql-2/like-substring`/`like-prefix`), in name order; only published Tables when- `published-only?`."- [database-id :- ::lib.schema.id/database- like-pattern :- [:or :string vector?]- limit :- ms/PositiveInt- published-only? :- :boolean]+ `metabase.util.honey-sql-2/like-substring`/`like-prefix`), in name order."+ [database-id :- ::lib.schema.id/database+ like-pattern :- [:or :string vector?]+ limit :- ms/PositiveInt](t2/select [:model/Table :id :db_id :schema :name]{:from [(warehouse-schema-overlay/table-query)]:where [:and [:= :db_id database-id][:= :active true][:like :%lower.name like-pattern]- [:= :visibility_type nil]- (when published-only?- [:= :is_published true])]+ [:= :visibility_type nil]]:order-by [[:%lower.name :asc]]:limit limit}))@@ -201,12 +197,10 @@(mu/defn autocomplete-fields"Up to `limit` name, type, id, and Table of the active, non-sensitive Fields of active Tables of the Database with`database-id` whose lower-cased name matches the SQL LIKE `like-pattern` (a Honey SQL LIKE right-hand side, see- `metabase.util.honey-sql-2/like-substring`/`like-prefix`), in field then table name order; only Fields of- published Tables when `published-only?`."- [database-id :- ::lib.schema.id/database- like-pattern :- [:or :string vector?]- limit :- ms/PositiveInt- published-only? :- :boolean]+ `metabase.util.honey-sql-2/like-substring`/`like-prefix`), in field then table name order."+ [database-id :- ::lib.schema.id/database+ like-pattern :- [:or :string vector?]+ limit :- ms/PositiveInt];; NOTE: measuring showed that this query performance is improved ~4x when adding trgm index in pgsql and ~10x when;; adding a index on `lower(metabase_field.name)` for ordering (trgm index having on impact on queries with index).;; Pgsql now has an index on that (see migration `v49.2023-01-24T12:00:00`) as other dbms do not support indexes on@@ -221,9 +215,7 @@[[:lower :table.name] :asc]];; checking for table.active in join makes query faster when there are a lot of inactive tables:inner-join [(warehouse-schema-overlay/table-query {:alias :table}) [:and :table.active- [:= :table.id :metabase_field.table_id]- (when published-only?- :table.is_published)]]+ [:= :table.id :metabase_field.table_id]]]:limit limit}))(mu/defn table-ids-for-databasediff --git a/test/metabase/actions/models_test.clj b/test/metabase/actions/models_test.cljindex eb755be2051..57834525910 100644--- a/test/metabase/actions/models_test.clj+++ b/test/metabase/actions/models_test.clj@@ -6,7 +6,7 @@[clojure.test :refer :all][metabase.actions.models :as action][metabase.actions.schema :as actions.schema]- [metabase.api.common :as api]+ [metabase.config.core :as config][metabase.driver :as driver][metabase.driver.mysql :as mysql][metabase.lib.core :as lib]@@ -233,8 +233,7 @@(deftest query-action-without-model-test(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)(testing "a query action can be inserted and updated without a model, and keeps its own collection"- (mt/with-temp [:model/Collection {coll-id :id} {:namespace "data-actions"}- :model/Collection {app-id :id} {:namespace "data-apps"}]+ (mt/with-temp [:model/Collection {coll-id :id} {:namespace "data-actions"}](mt/with-model-cleanup [:model/Action](let [insert! (fn [collection-id](action/insert! (lib/normalize ::actions.schema/action.for-insert@@ -248,10 +247,7 @@(action/select-action :id action-id)))(action/update! {:id action-id :name "Renamed"} (action/select-action :id action-id))(is (=? {:name "Renamed" :model_id nil :collection_id coll-id}- (action/select-action :id action-id)))- (testing "a data app collection takes one too"- (is (=? {:model_id nil :collection_id app-id}- (action/select-action :id (insert! app-id)))))))))))+ (action/select-action :id action-id)))))))))(deftest action-in-a-data-apps-collection-is-admin-only-test(testing "Only administrators write an action in a collection of the data apps namespace"@@ -260,23 +256,78 @@(mt/with-model-cleanup [:model/Action](let [action-in (fn [collection-id](lib/normalize ::actions.schema/action.for-insert- {:type :query+ {:type :implicit+ :kind :row/create:name "No model":collection_id collection-id- :database_id (mt/id)- :dataset_query (mt/native-query {:query "update categories set name = 'x' where id = 1"})}))- action (action/select-action :id (action/insert! (action-in app-id)))+ :table_id (mt/id :categories)}))elsewhere (action/select-action :id (action/insert! (action-in coll-id)))](mt/with-test-user :crowberto- (is (true? (mi/can-write? action)))- (is (true? (:can_write (t2/hydrate action :can_write))))+ (is (true? (mi/can-write? elsewhere)))(is (true? (mi/can-create? :model/Action (action-in app-id))))(is (true? (mi/can-update? elsewhere {:collection_id app-id}))))(mt/with-test-user :rasta- (is (false? (mi/can-write? action)))- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions to do that."- (api/write-check :model/Action (:id action))))- (is (false? (mi/can-create? :model/Action (action-in app-id))))))))))+ (is (false? (mi/can-write? elsewhere)))+ (is (false? (mi/can-create? :model/Action (action-in app-id))))+ (is (false? (mi/can-update? elsewhere {:collection_id app-id})))))))))++(defn- insert-data-app-action!+ "Insert an action named `action-name` of `action-type` in the collection with `collection-id`, as a load does, with+ `action-columns` merged into its Action row: an implicit one of no model inserting into the venues table, or a query+ one running SQL."+ [collection-id action-type action-name & [action-columns]]+ (let [action-id (t2/insert-returning-pk! :model/Action (merge {:name action-name+ :type action-type+ :collection_id collection-id+ :creator_id (mt/user->id :crowberto)}+ action-columns))]+ (if (= :implicit action-type)+ (t2/insert! :model/ImplicitAction {:action_id action-id :kind "row/create" :table_id (mt/id :venues)})+ (t2/insert! :model/QueryAction {:action_id action-id+ :database_id (mt/id)+ :dataset_query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")}))+ action-id))++(def ^:private card-values-parameters+ "Action parameters, one taking its values from a card that doesn't exist."+ [{:id "name" :slug "name" :type :string/= :values_source_type "card" :values_source_config {:card_id Integer/MAX_VALUE}}])++(deftest action-in-a-data-apps-collection-is-plain-implicit-action-test+ (testing "an action in a collection of the data apps namespace is an implicit action of no model, neither archived nor+ public, whose parameters take no values from a card, however it gets there"+ (when config/ee-available?+ (mt/with-temp [:model/Collection {app-id :id} {:namespace "data-apps"}+ :model/Collection {other-id :id} {:namespace "data-actions"}]+ (mt/with-model-cleanup [:model/Action]+ (doseq [[label action-type columns message]+ [["a query action" :query nil #"must be an implicit action on a table"]+ ["archived" :implicit {:archived true} #"can't be archived"]+ ["public" :implicit {:public_uuid (str (random-uuid)) :made_public_by_id (mt/user->id :crowberto)}+ #"can't be made public"]+ ["taking parameter values from a card" :implicit {:parameters card-values-parameters}+ #"can't take a parameter's values from a card"]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (insert-data-app-action! app-id action-type label columns)))+ (testing "moved in from elsewhere, where it is fine"+ (let [action-id (insert-data-app-action! other-id action-type (str label " elsewhere") columns)]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (t2/update! :model/Action :id action-id {:collection_id app-id})))+ (is (= other-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))))))++(deftest action-in-a-data-apps-collection-writes-to-any-table-test+ (testing "the hook reads only the action's rows, so an implicit action of no model there writes to any table"+ (when config/ee-available?+ (mt/with-temp [:model/Collection {app-id :id} {:namespace "data-apps"}+ :model/Collection {other-id :id} {:namespace "data-actions"}]+ (mt/with-model-cleanup [:model/Action]+ (let [action-id (insert-data-app-action! app-id :implicit "Add venue")]+ (t2/update! :model/ImplicitAction {:action_id action-id} {:table_id (mt/id :categories)})+ (is (= (mt/id :categories) (t2/select-one-fn :table_id :model/ImplicitAction :action_id action-id))))+ (testing "and one moves in"+ (let [action-id (insert-data-app-action! other-id :implicit "Moved in")]+ (t2/update! :model/Action :id action-id {:collection_id app-id})+ (is (= app-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))))(deftest implicit-action-requires-table-test(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.cljindex d3187236a1a..b79b2b16021 100644--- a/test/metabase/actions_rest/api_test.clj+++ b/test/metabase/actions_rest/api_test.clj@@ -1140,6 +1140,32 @@"AAAAAAAAAAAAAAAAAAAAA"){:parameters {:id 1 :name "European"}}))))))))+(deftest execute-adhoc-action-test+ (mt/with-actions-test-data-and-actions-enabled+ (let [action-count (t2/count :model/Action)+ implicit {:name "Rename" :type "implicit" :kind "row/update" :table_id (mt/id :categories)}+ query {:name "Rename"+ :type "query"+ :dataset_query (mt/native-query {:query "UPDATE categories SET name = {{name}} WHERE id = 1"+ :template-tags {"name" {:id "name"+ :name "name"+ :display-name "Name"+ :type "text"}}})+ :parameters [{:id "name" :slug "name" :type "string/="+ :target [:variable [:template-tag "name"]]}]}]+ (testing "a superuser runs an ad-hoc implicit action"+ (is (=? {:rows-updated some?}+ (mt/user-http-request :crowberto :post 200 "action/execute"+ {:action implicit :parameters {:id 1 :name "European"}}))))+ (testing "a superuser runs an ad-hoc query action"+ (is (=? {:rows-affected 1}+ (mt/user-http-request :crowberto :post 200 "action/execute"+ {:action query :parameters {:name "European"}}))))+ (testing "nobody else does"+ (mt/user-http-request :rasta :post 403 "action/execute" {:action implicit :parameters {:id 1 :name "European"}}))+ (testing "nothing is saved"+ (is (= action-count (t2/count :model/Action)))))))+(deftest execute-action-test-3(mt/with-actions-test-data-and-actions-enabled(mt/with-actions [{:keys [action-id]} unshared-action-opts]diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex af5f8105199..02c8e2b7022 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -3451,3 +3451,40 @@(let [descendants (serdes/descendants "Collection" (:id coll) {:skip-archived false})](is (contains? descendants ["Table" (:id active-table)]))(is (contains? descendants ["Table" (:id archived-table)])))))))++(deftest data-apps-collection-holds-only-questions-and-implicit-actions-test+ (testing "a collection of the data apps namespace holds questions and implicit actions, nothing else"+ (when config/ee-available?+ (mt/with-temp [:model/Collection {collection-id :id :as collection} {:namespace "data-apps"}+ :model/Dashboard {dashboard-id :id} {:name "Elsewhere"}]+ (doseq [[label insert!] [["a dashboard" #(mt/with-temp [:model/Dashboard _ {:collection_id collection-id}])]+ ["a collection" #(mt/with-temp [:model/Collection _ {:namespace "data-apps"+ :location (collection/children-location collection)}])]+ ["a model" #(mt/with-temp [:model/Card _ {:type :model :collection_id collection-id}])]+ ["a metric" #(mt/with-temp [:model/Card _ {:type :metric :collection_id collection-id}])]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions and implicit actions" (insert!)))))+ (testing "a dashboard moved in"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can hold only questions and implicit actions"+ (t2/update! :model/Dashboard :id dashboard-id {:collection_id collection-id})))+ (is (nil? (t2/select-one-fn :collection_id :model/Dashboard :id dashboard-id))))+ (testing "a bookmark is not content"+ (mt/with-temp [:model/CollectionBookmark _ {:collection_id collection-id :user_id (mt/user->id :crowberto)}]+ (is (t2/exists? :model/CollectionBookmark :collection_id collection-id))))))))++(deftest data-apps-collection-stays-top-level-collection-test+ (testing "a collection of the data apps namespace can't be moved, typed or made a sample, but can be described, synced+ and cleared of an archive marker"+ (when config/ee-available?+ (mt/with-temp [:model/Collection {collection-id :id :as collection} {:namespace "data-apps"}+ :model/Collection {other-id :id :as other} {:namespace "data-apps"}]+ (doseq [changes [{:type "library-metrics"} {:is_sample true} {:location (str "/" other-id "/")}]]+ (testing (pr-str changes)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"stays a top-level collection of data apps"+ (t2/update! :model/Collection :id collection-id changes)))))+ (testing "move-collection!"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"cannot move a data app's collection"+ (collection/move-collection! collection (collection/children-location other)))))+ (t2/update! :model/Collection :id collection-id {:archive_operation_id nil :is_remote_synced true :description "Birds"})+ (is (=? {:location "/" :is_remote_synced true :description "Birds"}+ (t2/select-one :model/Collection :id collection-id)))))))diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 00094ac1f58..8cf502a1384 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -1931,30 +1931,26 @@(deftest data-app-collection-items-test(testing "GET /api/collection/:id/items lists the actions and questions of a data app collection"- (mt/with-temp [:model/Collection {app-coll-id :id} {:namespace "data-apps", :name "Data app collection"}- :model/Collection {actions-coll-id :id} {:namespace "data-actions", :name "Data actions folder"}- :model/Action {in-app :id} {:type :query, :name "In app", :collection_id app-coll-id}- :model/QueryAction _ {:action_id in-app- :database_id (mt/id)- :dataset_query (mt/native-query {:query "DELETE FROM venues"})}- :model/Action {in-folder :id} {:type :query, :name "In folder", :collection_id actions-coll-id}- :model/QueryAction _ {:action_id in-folder- :database_id (mt/id)- :dataset_query (mt/native-query {:query "DELETE FROM venues"})}]- (binding [mi/*deserializing?* true]- (mt/with-temp [:model/Card _ {:name "App question"- :collection_id app-coll-id- :dataset_query (mt/mbql-query venues)}]- (let [items (fn [coll-id model]- (->> (mt/user-http-request :crowberto :get 200 (str "collection/" coll-id "/items") :models model)- :data- (map #(select-keys % [:name :model :collection_namespace]))))]- (is (= [{:name "In app", :model "action", :collection_namespace "data-apps"}]- (items app-coll-id "action")))- (is (= [{:name "App question", :model "card"}]- (map #(dissoc % :collection_namespace) (items app-coll-id "card"))))- (is (= [{:name "In folder", :model "action", :collection_namespace "data-actions"}]- (items actions-coll-id "action")))))))))+ (binding [mi/*deserializing?* true]+ (mt/with-temp [:model/Collection {app-coll-id :id} {:namespace "data-apps", :name "Data app collection"}+ :model/Collection {actions-coll-id :id} {:namespace "data-actions", :name "Data actions folder"}+ :model/Action {in-app :id} {:type :implicit, :name "In app", :collection_id app-coll-id}+ :model/ImplicitAction _ {:action_id in-app, :kind "row/update", :table_id (mt/id :venues)}+ :model/Action {in-folder :id} {:type :implicit, :name "In folder", :collection_id actions-coll-id}+ :model/ImplicitAction _ {:action_id in-folder, :kind "row/update", :table_id (mt/id :venues)}+ :model/Card _ {:name "App question"+ :collection_id app-coll-id+ :dataset_query (mt/mbql-query venues)}]+ (let [items (fn [coll-id model]+ (->> (mt/user-http-request :crowberto :get 200 (str "collection/" coll-id "/items") :models model)+ :data+ (map #(select-keys % [:name :model :collection_namespace]))))]+ (is (= [{:name "In app", :model "action", :collection_namespace "data-apps"}]+ (items app-coll-id "action")))+ (is (= [{:name "App question", :model "card"}]+ (map #(dissoc % :collection_namespace) (items app-coll-id "card"))))+ (is (= [{:name "In folder", :model "action", :collection_namespace "data-actions"}]+ (items actions-coll-id "action"))))))))(deftest snippet-collection-items-count-only-test(testing "The snippets namespace is unpaginated, but a count-only request still keeps its LIMIT"diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 8be23fdcb1c..b202d542ec1 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -1181,19 +1181,126 @@(deftest card-in-a-data-apps-collection-is-admin-only-test(testing "Only administrators write a card in a collection of the data apps namespace"- ;; created as a load creates it, which doesn't check that the table is published- (binding [mi/*deserializing?* true]- (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}- :model/Card card {:collection_id collection-id- :dataset_query (mt/mbql-query venues)}]- (mt/with-test-user :crowberto- (is (true? (mi/can-write? card)))- (is (true? (mi/can-write? :model/Card (:id card))))- (is (true? (:can_write (t2/hydrate card :can_write))))- (is (true? (mi/can-create? :model/Card {:collection_id collection-id}))))- (mt/with-test-user :rasta- (is (false? (mi/can-write? card)))- (is (false? (mi/can-create? :model/Card {:collection_id collection-id}))))))))+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card card {:collection_id collection-id+ :dataset_query (mt/mbql-query venues)}]+ (mt/with-test-user :crowberto+ (is (true? (mi/can-write? card)))+ (is (true? (mi/can-write? :model/Card (:id card))))+ (is (true? (:can_write (t2/hydrate card :can_write))))+ (is (true? (mi/can-create? :model/Card {:collection_id collection-id}))))+ (mt/with-test-user :rasta+ (is (false? (mi/can-write? card)))+ (is (false? (mi/can-create? :model/Card {:collection_id collection-id})))))))++(defn- venues-query+ "A query of all venues."+ []+ (let [mp (mt/metadata-provider)]+ (lib/query mp (lib.metadata/table mp (mt/id :venues)))))++(deftest card-in-a-data-apps-collection-holds-query-on-database-test+ (when config/ee-available?+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must hold a query on a database"+ (t2/insert! :model/Card {:name "Empty"+ :display "table"+ :visualization_settings {}+ :creator_id (mt/user->id :crowberto)+ :collection_id collection-id+ :dataset_query {}}))))))++(deftest card-in-a-data-apps-collection-is-plain-question-test+ (testing "a card in a collection of the data apps namespace is a question in no dashboard or document, not archived,+ public or embedded, however it gets there"+ (when config/ee-available?+ (mt/with-temporary-setting-values [enable-public-sharing true+ enable-embedding-static true]+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card {card-id :id} {:collection_id collection-id :dataset_query (venues-query)}+ :model/Document {document-id :id} {:name "Notes"}]+ (doseq [[label changes] [["archived" {:archived true}]+ ["a model" {:type :model}]+ ["public" {:public_uuid (str (random-uuid)) :made_public_by_id (mt/user->id :crowberto)}]+ ["embedded" {:enable_embedding true}]+ ["with embedding parameters" {:embedding_params {}}]+ ["in a document" {:document_id document-id}]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question, in no dashboard or document"+ (t2/update! :model/Card :id card-id changes)))+ (testing "moved in from elsewhere"+ (mt/with-temp [:model/Card {other-id :id} (merge {:dataset_query (venues-query)} changes)]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must be a question|can hold only questions"+ (t2/update! :model/Card :id other-id {:collection_id collection-id})))+ (is (nil? (t2/select-one-fn :collection_id :model/Card :id other-id)))))))+ (is (=? {:archived false :public_uuid nil :type :question :document_id nil}+ (t2/select-one :model/Card :id card-id))))))))++(deftest card-in-a-data-apps-collection-has-no-parameters-test+ (when config/ee-available?+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card {card-id :id} {:collection_id collection-id :dataset_query (venues-query)}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"can't have parameters"+ (t2/update! :model/Card :id card-id {:parameters [{:id "venue"+ :slug "venue"+ :name "Venue"+ :type :string/=}]})))+ (testing "an empty list is no parameters"+ (mt/with-temp [:model/Card {other-id :id} {:collection_id collection-id :dataset_query (venues-query) :parameters []}]+ (is (= [] (t2/select-one-fn :parameters :model/Card :id other-id))))))))++(deftest card-in-a-data-apps-collection-reads-table-in-single-stage-test+ (testing "a card in a collection of the data apps namespace reads a table in a single MBQL stage, without explicit+ joins or custom columns, whether it is saved or changed"+ (when config/ee-available?+ (let [mp (mt/metadata-provider)+ venues (venues-query)+ categories (lib.metadata/table mp (mt/id :categories))]+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card {card-id :id} {:collection_id collection-id :dataset_query venues}+ :model/Card {other-id :id} {:dataset_query venues}]+ (doseq [[label query message]+ [["SQL" (lib/native-query mp "SELECT * FROM venues") #"must be built with the query builder"]+ ["two stages" (lib/append-stage (lib/aggregate venues (lib/count))) #"single stage"]+ ["a card as the source, even one in the same collection"+ (lib/query mp (lib.metadata/card mp card-id)) #"must read a table, not a card"]+ ["another card as the source" (lib/query mp (lib.metadata/card mp other-id)) #"must read a table, not a card"]+ ["an explicit join"+ (lib/join venues (lib/join-clause categories [(lib/= (lib.metadata/field mp (mt/id :venues :category_id))+ (lib.metadata/field mp (mt/id :categories :id)))]))+ #"can't join tables explicitly"]+ ["a custom column"+ (lib/expression venues "Double price" (lib/* (lib.metadata/field mp (mt/id :venues :price)) 2))+ #"can't have custom columns"]]]+ (testing label+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (mt/with-temp [:model/Card _ {:collection_id collection-id :dataset_query query}])))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (t2/update! :model/Card :id card-id {:dataset_query query})))+ (is (= (mt/id :venues) (t2/select-one-fn :table_id :model/Card :id card-id))))))))))++(deftest card-in-a-data-apps-collection-reads-any-table-test+ (testing "the hook reads only the card, so the tables, metrics, segments and measures its query names may be any"+ (when config/ee-available?+ (let [venues (venues-query)+ category (some #(when (= (mt/id :categories :name) (:id %)) %) (lib/filterable-columns venues))]+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace "data-apps"}+ :model/Card {card-id :id} {:collection_id collection-id :dataset_query venues}+ :model/Card {metric-id :id} {:type :metric :dataset_query (lib/aggregate venues (lib/count))}+ :model/Segment {segment-id :id} {:name "Bars"+ :table_id (mt/id :venues)+ :definition (lib/filter venues (lib/= category "Bar"))}+ :model/Measure {measure-id :id} {:name "Categories"+ :table_id (mt/id :venues)+ :definition (lib/aggregate venues (lib/distinct category))}]+ (let [mp (mt/metadata-provider)]+ (doseq [[label query] [["another table" (lib/query mp (lib.metadata/table mp (mt/id :users)))]+ ["an implicit join" (lib/breakout venues category)]+ ["a metric" (lib/aggregate venues (lib.metadata/metric mp metric-id))]+ ["a segment" (lib/filter venues (lib.metadata/segment mp segment-id))]+ ["a measure" (lib/aggregate venues (lib.metadata/measure mp measure-id))]]]+ (testing label+ (is (= 1 (t2/update! :model/Card :id card-id {:dataset_query query})))))))))))(deftest ^:parallel breakouts->identifier->action-fn-test(are [b1 b2 expected-identifier->action] (=? expected-identifier->actiondiff --git a/test/metabase/server/routes/index_test.clj b/test/metabase/server/routes/index_test.cljindex 4b108b3ab93..281d304eb96 100644--- a/test/metabase/server/routes/index_test.clj+++ b/test/metabase/server/routes/index_test.clj@@ -1,6 +1,8 @@(ns metabase.server.routes.index-test(:require+ [clojure.string :as str][clojure.test :refer :all]+ [metabase.config.core :as config][metabase.server.routes.index :as index][metabase.test :as mt][metabase.util.i18n :as i18n]))@@ -49,3 +51,21 @@;; but we can override with the user locale(binding [i18n/*user-locale* "fr"](is (= "fr" (:language (#'index/template-parameters false {})))))))++(defn- data-app-response+ "What the `/embed/apps` entrypoint responds to `request`."+ [request]+ (let [response (promise)]+ (index/data-app request #(deliver response %) #(throw %))+ @response))++(deftest data-app-entrypoint-test+ (when config/ee-available?+ (testing "a signed-out visitor is sent to log in, then back to the app's page"+ (mt/with-premium-features #{:data-apps}+ (let [{:keys [status headers]} (data-app-response {:uri "/embed/apps/sales/sub" :query-string "x=1"})]+ (is (= 302 status))+ (is (str/ends-with? (get headers "Location") "/auth/login?redirect=%2Fapps%2Fsales%2Fsub%3Fx%3D1"))))))+ (testing "without the feature the request falls through to the generic embed handler"+ (mt/with-premium-features #{}+ (is (nil? (data-app-response {:uri "/embed/apps/sales" :metabase-user-id (mt/user->id :crowberto)}))))))diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.cljindex 55bb01deca2..38a4a239ea8 100644--- a/test/metabase/test/util.clj+++ b/test/metabase/test/util.clj@@ -494,17 +494,6 @@(locking dimension-lock(next-method model explicit-attributes f)))-(methodical/defmethod t2.with-temp/do-with-temp* :around :model/DataApp- "Give a temp data app a temp collection named like the one the API creates, unless the attributes set- `resource_collection_id`, even to nil."- [model explicit-attributes f]- (let [attributes (merge (t2.with-temp/with-temp-defaults model) explicit-attributes)]- (if (contains? attributes :resource_collection_id)- (next-method model attributes f)- (t2.with-temp/with-temp [:model/Collection {collection-id :id} {:name (str "Data App: " (:name attributes))- :namespace "data-apps"}]- (next-method model (assoc attributes :resource_collection_id collection-id) f)))))-(defn- set-with-temp-defaults! [](doseq [[model defaults-fn] with-temp-defaults-fns](methodical/add-primary-method! #'t2.with-temp/with-temp-defaultsdiff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex 693a8d11b8c..65096b7df4b 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -1134,7 +1134,7 @@(testing "GET /api/database/:id/autocomplete_suggestions"(testing " returns sane Cache-Control headers"(is (=? {"Cache-Control" "public, max-age=60"- "Vary" "Cookie, X-Metabase-Client"}+ "Vary" "Cookie"}(-> (client/client-full-response (test.users/username->token :rasta) :get 200(format "database/%s/autocomplete_suggestions" (mt/id)):prefix "u")