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
Data Apps Permissions (#79822)
Phoomparin Manoc8f77a0925c8
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex d9c3e1529e0..f5d4d6f31c8 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -3273,15 +3273,28 @@:uses #{premium-features}}enterprise/data-apps- {:team "Gadget"+ {:team "Embedding":api #{metabase-enterprise.data-apps.apimetabase-enterprise.data-apps.initmetabase-enterprise.data-apps.sync}:uses #{api+ collections+ lib+ lib-bemodels+ permissionspremium-features+ requestsettings- util}}+ util}+ :model-imports #{:model/Card+ :model/Collection+ :model/DataPermissions+ :model/Database+ :model/Permissions+ :model/PermissionsGroup+ :model/Table+ :model/User}}enterprise/data-complexity-score{:team "Metabot"diff --git a/.github/workflows/embedding-sdk-host-sample-apps-tests.yml b/.github/workflows/embedding-sdk-host-sample-apps-tests.ymlindex f21f10256a7..d189c10e5d6 100644--- a/.github/workflows/embedding-sdk-host-sample-apps-tests.yml+++ b/.github/workflows/embedding-sdk-host-sample-apps-tests.yml@@ -424,15 +424,38 @@ jobs:if: steps.prebuilt-cljs.outcome != 'success'run: bun run build-pure:cljs+ # The data-app suite synchronizes real actions, and Metabase only permits+ # those against a writable warehouse, which comes from the `qa-db`+ # snapshot below. That snapshot creator builds every QA database in one+ # pass — Mongo and MySQL included — so all three have to be up even though+ # only `postgres-writable` is restored. The other host apps read the sample+ # database, so they skip the pull entirely.+ - name: Prepare Docker containers+ if: ${{ matrix.test_suite == 'vite-6-data-app-host-app-e2e' }}+ uses: ./.github/actions/e2e-prepare-containers+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}+ postgres: true+ mysql: true+ mongo: true+- name: Run Metabaserun: node e2e/runner/run_cypress_ci.js start- uses: ./.github/actions/resolve-job-id+ # Without `--spec` the snapshot config picks up `qa-db.cy.snap.js` too,+ # which is what creates the `postgres-writable` snapshot the data-app+ # action tests restore.- name: Generate database snapshotsrun: |- node e2e/runner/run_cypress_ci.js snapshot \- --spec "e2e/snapshot-creators/default.cy.snap.js"+ if [ "${{ matrix.test_suite }}" = "vite-6-data-app-host-app-e2e" ]; then+ node e2e/runner/run_cypress_ci.js snapshot+ else+ node e2e/runner/run_cypress_ci.js snapshot \+ --spec "e2e/snapshot-creators/default.cy.snap.js"+ fi- name: Prepare and launch Host Apprun: npx tsx ./e2e/runner/embedding-sdk/host-apps/start-ci.ts ${{ matrix.test_suite }}diff --git a/.github/workflows/embedding-sdk-package-build.yml b/.github/workflows/embedding-sdk-package-build.ymlindex 08888009d9f..208e7f25e3e 100644--- a/.github/workflows/embedding-sdk-package-build.yml+++ b/.github/workflows/embedding-sdk-package-build.yml@@ -24,6 +24,8 @@ jobs:# unrelated to embedding (EMB-765)echo "::remove-matcher owner=tsc::"bun run build-embedding-sdk-package+ - name: Smoke test the packed SDK CLI+ run: node bin/embedding-sdk/test-sdk-package.mjs- name: Prepare Embedding SDK artifactuses: actions/upload-artifact@v7with:diff --git a/.github/workflows/release-embedding-sdk.yml b/.github/workflows/release-embedding-sdk.ymlindex 4d1afc58006..dacf36385fa 100644--- a/.github/workflows/release-embedding-sdk.yml+++ b/.github/workflows/release-embedding-sdk.yml@@ -382,6 +382,9 @@ jobs:- name: Generate SDK package.json in the build directoryrun: bun run embedding-sdk:generate-package+ - name: Smoke test the packed SDK CLI+ run: node bin/embedding-sdk/test-sdk-package.mjs+- name: Upload built SDK package as artifactuses: actions/upload-artifact@v7with:diff --git a/bin/embedding-sdk/generate-sdk-package-files.js b/bin/embedding-sdk/generate-sdk-package-files.jsindex bfdc69499c4..5ba42272b0e 100644--- a/bin/embedding-sdk/generate-sdk-package-files.js+++ b/bin/embedding-sdk/generate-sdk-package-files.js@@ -1,23 +1,8 @@#!/usr/bin/env node-/* eslint-env node */-/* eslint-disable import/no-commonjs, import/order, no-console */const fs = require("fs");const path = require("path");const SDK_DIST_DIR = path.resolve("./resources/embedding-sdk");-const DEPENDENCIES = [];--function filterOuDependencies(object) {- const result = {};-- Object.entries(object).forEach(([packageName, version]) => {- if (DEPENDENCIES.includes(packageName)) {- result[packageName] = version;- }- });-- return result;-}function generateSdkPackage() {let maybeCommitHash = process.argv[2];@@ -27,13 +12,10 @@ function generateSdkPackage() {maybeCommitHash = maybeCommitHash.slice(0, 7);}- const mainPackageJson = fs.readFileSync(- path.resolve("./package.json"),- "utf-8",+ const mainPackageJsonContent = JSON.parse(+ fs.readFileSync(path.resolve("./package.json"), "utf-8"),);- const mainPackageJsonContent = JSON.parse(mainPackageJson);-const sdkPackageTemplateJson = fs.readFileSync(path.resolve("./enterprise/frontend/src/embedding-sdk-package/package.template.json",@@ -52,10 +34,19 @@ function generateSdkPackage() {const mergedContent = {...publishableTemplateJsonContent,+version: maybeCommitHash? `${sdkPackageTemplateJsonContent.version}-${todayDate}-${maybeCommitHash}`: sdkPackageTemplateJsonContent.version,- dependencies: filterOuDependencies(mainPackageJsonContent.dependencies),++ // Runtime dependencies of the CLI for data apps, not pre-bundled.+ dependencies: {+ // Compiles app definitions and local imports for the CLI to evaluate.+ esbuild: mainPackageJsonContent.devDependencies.esbuild,++ // Parses and edits TypeScript source files during resource sync.+ typescript: mainPackageJsonContent.dependencies.typescript,+ },};const mergedContentString = JSON.stringify(mergedContent, null, 2);diff --git a/bin/embedding-sdk/test-sdk-package.mjs b/bin/embedding-sdk/test-sdk-package.mjsnew file mode 100644index 00000000000..562ff1425c4--- /dev/null+++ b/bin/embedding-sdk/test-sdk-package.mjs@@ -0,0 +1,93 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import console from "node:console";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import process from "node:process";++const PACKAGE_PATH = path.resolve("resources/embedding-sdk");++const SMOKE_TEST_PATH = fs.mkdtempSync(+ path.join(os.tmpdir(), "sdk-package-smoke-"),+);++const NPM_COMMAND_OPTIONS = {+ cwd: SMOKE_TEST_PATH,+ encoding: "utf8",+ timeout: 180_000,+ env: { ...process.env, NODE_PATH: "", NODE_OPTIONS: "" },+};++try {+ fs.writeFileSync(+ path.join(SMOKE_TEST_PATH, "package.json"),+ JSON.stringify({ name: "sdk-package-smoke-test", private: true }),+ );++ // Get tarball with the SDK package dependencies+ const [tarball] = JSON.parse(+ execFileSync(+ "npm",+ ["pack", PACKAGE_PATH, "--json", "--ignore-scripts"],+ NPM_COMMAND_OPTIONS,+ ),+ );++ // Install the packed sdk and runtime dependencies+ execFileSync(+ "npm",+ [+ "install",+ tarball.filename,+ "--legacy-peer-deps",+ "--no-audit",+ "--no-fund",+ ],+ NPM_COMMAND_OPTIONS,+ );++ const installedPackage = path.join(+ SMOKE_TEST_PATH,+ "node_modules/@metabase/embedding-sdk-react",+ );++ const manifest = JSON.parse(+ fs.readFileSync(path.join(installedPackage, "package.json"), "utf8"),+ );++ // Check that both esbuild and typescript modules are installed and can be used+ execFileSync(+ process.execPath,+ [+ "--eval",+ `+ const { createRequire } = require("node:module");+ const sdkRequire = createRequire(${JSON.stringify(path.join(installedPackage, "package.json"))});++ sdkRequire("esbuild").transformSync("const value: number = 1", { loader: "ts" });+ sdkRequire("typescript").transpileModule("const value: number = 1", {});+ `,+ ],+ NPM_COMMAND_OPTIONS,+ );++ // Check that the installed CLI has data apps sync command+ const output = execFileSync(+ process.execPath,+ [+ path.join(installedPackage, manifest.bin),+ "data-apps",+ "sync-resources",+ "--help",+ ],+ NPM_COMMAND_OPTIONS,+ );++ assert.match(output, /Usage: .*sync-resources/);+ assert.match(output, /--app-root/);++ console.log("SDK package smoke test passed.");+} finally {+ fs.rmSync(SMOKE_TEST_PATH, { recursive: true, force: true });+}diff --git a/e2e/embedding-sdk-host-apps/angular-20-host-app/package.json b/e2e/embedding-sdk-host-apps/angular-20-host-app/package.jsonindex 31a4311b58e..7a4abbd4845 100644--- a/e2e/embedding-sdk-host-apps/angular-20-host-app/package.json+++ b/e2e/embedding-sdk-host-apps/angular-20-host-app/package.json@@ -1,12 +1,12 @@{"name": "angular-20-host-app","version": "0.0.0",+ "private": true,"scripts": {"start": "./entrypoint.sh","preview": "ng serve --configuration production --watch false","watch": "ng serve --configuration development --watch true"},- "private": true,"dependencies": {"@angular/common": "^20.0.0","@angular/compiler": "^20.0.0",diff --git a/e2e/embedding-sdk-host-apps/angular-20-host-app/src/index.html b/e2e/embedding-sdk-host-apps/angular-20-host-app/src/index.htmlindex 19084cb18ba..12a3df6fa73 100644--- a/e2e/embedding-sdk-host-apps/angular-20-host-app/src/index.html+++ b/e2e/embedding-sdk-host-apps/angular-20-host-app/src/index.html@@ -1,12 +1,12 @@<!doctype html><html lang="en">-<head>- <meta charset="utf-8">- <title>Angular@20 Host App</title>- <base href="/">- <meta name="viewport" content="width=device-width, initial-scale=1">-</head>-<body>- <app-root></app-root>-</body>+ <head>+ <meta charset="utf-8" />+ <title>Angular@20 Host App</title>+ <base href="/" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ </head>+ <body>+ <app-root></app-root>+ </body></html>diff --git a/e2e/embedding-sdk-host-apps/angular-20-host-app/tsconfig.json b/e2e/embedding-sdk-host-apps/angular-20-host-app/tsconfig.jsonindex 761ac7e15c6..4d41a201a98 100644--- a/e2e/embedding-sdk-host-apps/angular-20-host-app/tsconfig.json+++ b/e2e/embedding-sdk-host-apps/angular-20-host-app/tsconfig.json@@ -1,33 +1,26 @@/* To learn more about this file see: https://angular.io/config/tsconfig. */{- "compileOnSave": false,- "compilerOptions": {- "baseUrl": "./",+ "compileOnSave": false,+ "compilerOptions": {+ "baseUrl": "./","outDir": "./out-tsc/app",- "allowSyntheticDefaultImports": true,- "downlevelIteration": true,- "experimentalDecorators": true,- "moduleResolution": "node",+ "allowSyntheticDefaultImports": true,+ "downlevelIteration": true,+ "experimentalDecorators": true,+ "moduleResolution": "node","skipLibCheck": true,"target": "ES2022",- "module": "ES2022",- "useDefineForClassFields": false,- "jsx": "react-jsx",- "lib": [- "ES2022",- "dom"- ]- },- "angularCompilerOptions": {- "enableI18nLegacyMessageIdFormat": false,- "strictInjectionParameters": true,- "strictInputAccessModifiers": true,- "strictTemplates": true- },- "files": [- "src/main.ts"- ],- "include": [- "src/**/*.d.ts"- ]+ "module": "ES2022",+ "useDefineForClassFields": false,+ "jsx": "react-jsx",+ "lib": ["ES2022", "dom"]+ },+ "angularCompilerOptions": {+ "enableI18nLegacyMessageIdFormat": false,+ "strictInjectionParameters": true,+ "strictInputAccessModifiers": true,+ "strictTemplates": true+ },+ "files": ["src/main.ts"],+ "include": ["src/**/*.d.ts"]}diff --git a/e2e/embedding-sdk-host-apps/next-15-app-router-host-app/tsconfig.json b/e2e/embedding-sdk-host-apps/next-15-app-router-host-app/tsconfig.jsonindex fe4b73b478d..a8ea73ab1f4 100644--- a/e2e/embedding-sdk-host-apps/next-15-app-router-host-app/tsconfig.json+++ b/e2e/embedding-sdk-host-apps/next-15-app-router-host-app/tsconfig.json@@ -1,10 +1,6 @@{"compilerOptions": {- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,@@ -22,22 +18,13 @@}],"paths": {- "@/*": [- "./src/*"- ],+ "@/*": ["./src/*"],"@metabase/embedding-sdk-react": ["./node_modules/@metabase/embedding-sdk-react"]},"target": "ES2017"},- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx",- ".next/types/**/*.ts"- ],- "exclude": [- "node_modules"- ]+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]}diff --git a/e2e/embedding-sdk-host-apps/next-15-pages-router-host-app/tsconfig.json b/e2e/embedding-sdk-host-apps/next-15-pages-router-host-app/tsconfig.jsonindex fe4b73b478d..a8ea73ab1f4 100644--- a/e2e/embedding-sdk-host-apps/next-15-pages-router-host-app/tsconfig.json+++ b/e2e/embedding-sdk-host-apps/next-15-pages-router-host-app/tsconfig.json@@ -1,10 +1,6 @@{"compilerOptions": {- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,@@ -22,22 +18,13 @@}],"paths": {- "@/*": [- "./src/*"- ],+ "@/*": ["./src/*"],"@metabase/embedding-sdk-react": ["./node_modules/@metabase/embedding-sdk-react"]},"target": "ES2017"},- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx",- ".next/types/**/*.ts"- ],- "exclude": [- "node_modules"- ]+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]}diff --git a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignoreindex 6787e2e9453..2414f775f65 100644--- a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore+++ b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/.gitignore@@ -10,3 +10,6 @@ build# debugnpm-debug.log*++# generated test action declarations+/actions/diff --git a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/package.json b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/package.jsonindex d4b02676df1..9364283a5ae 100644--- a/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/package.json+++ b/e2e/embedding-sdk-host-apps/vite-6-data-app-host-app/package.json@@ -1,7 +1,7 @@{"name": "vite-6-data-app-host-app",- "private": true,"version": "0.0.0",+ "private": true,"type": "module","scripts": {"start": "./entrypoint.sh",diff --git a/e2e/embedding-sdk-host-apps/vite-6-host-app/package.json b/e2e/embedding-sdk-host-apps/vite-6-host-app/package.jsonindex adf1dee4980..222ffa1e850 100644--- a/e2e/embedding-sdk-host-apps/vite-6-host-app/package.json+++ b/e2e/embedding-sdk-host-apps/vite-6-host-app/package.json@@ -1,7 +1,7 @@{"name": "vite-6-host-app",- "private": true,"version": "0.0.0",+ "private": true,"type": "module","scripts": {"start": "./entrypoint.sh",diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsxindex b8efefa0ad7..93c57b95508 100644--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx@@ -3,15 +3,10 @@ import {StaticQuestion,useAction,} from "@metabase/embedding-sdk-react";-import type { MetabaseQueryOptions } from "@metabase/embedding-sdk-react/data-app";import {- aggregations,- breakout,copy,DataAppLink,DataAppRouter,- filter,- orderBy,useDataAppLocation,useMetabaseQuery,useMetabaseQueryObject,@@ -197,161 +192,15 @@ function NativeQueryPage() {);}-function Combinators() {- const combinators = getTestEnv().combinators!;- const countAgg = aggregations.count();-- const q = useMetabaseQuery({- source: combinators.source,- filters: [filter(combinators.filterField, ">", combinators.filterValue)],- aggregations: [countAgg],- breakouts: [breakout(combinators.breakoutField)],- orderBys: [orderBy(countAgg, "desc")],- });-- return (- <div data-testid="data-app-combinators" style={{ padding: 24 }}>- <h1>Combinators</h1>- <div data-testid="combinators-loading">- {q.isLoading ? "loading" : "done"}- </div>- <div data-testid="combinators-error">- {q.error ? "error" : "no-error"}- </div>- <div data-testid="combinators-rowcount">- {String(q.data?.rows?.length ?? 0)}- </div>- </div>- );-}--/**- * A saved question used as a query source, with clauses applied on top of it.- * Each case runs the same clauses against the table and against a question that- * copies it; agreeing results are the assertion, so the spec never has to encode- * sample-database numbers.- */-function CardSource() {- const {- source,- tableSource,- filterField,- filterColumn,- filterValue,- breakoutField,- breakoutColumn,- } = getTestEnv().cardSource!;-- const countAgg = aggregations.count();-- return (- <div data-testid="data-app-card-source" style={{ padding: 24 }}>- <h1>Card source</h1>-- <CardSourceCase- caseKey="source"- tableQuery={{ source: tableSource, aggregations: [countAgg] }}- cardQuery={{ source, aggregations: [countAgg] }}- totalTestId="card-source-total"- />-- <CardSourceCase- caseKey="filters"- tableQuery={{- source: tableSource,- filters: [filter(filterField, ">", filterValue)],- aggregations: [countAgg],- }}- cardQuery={{- source,- filters: [filter(filterColumn, ">", filterValue)],- aggregations: [countAgg],- }}- />-- <CardSourceCase- caseKey="aggregations"- tableQuery={{- source: tableSource,- filters: [filter(filterField, ">", filterValue)],- aggregations: [countAgg, aggregations.sum(filterField)],- }}- cardQuery={{- source,- filters: [filter(filterColumn, ">", filterValue)],- aggregations: [countAgg, aggregations.sum(filterColumn)],- }}- />-- <CardSourceCase- caseKey="breakouts"- tableQuery={{- source: tableSource,- filters: [filter(filterField, ">", filterValue)],- aggregations: [countAgg],- breakouts: [breakout(breakoutField)],- orderBys: [orderBy(breakoutField, "asc")],- }}- cardQuery={{- source,- filters: [filter(filterColumn, ">", filterValue)],- aggregations: [countAgg],- breakouts: [breakout(breakoutColumn)],- orderBys: [orderBy(breakoutColumn, "asc")],- }}- />- </div>- );-}--function CardSourceCase({- caseKey,- tableQuery,- cardQuery,- totalTestId,-}: {- caseKey: string;- tableQuery: MetabaseQueryOptions<undefined>;- cardQuery: MetabaseQueryOptions<undefined>;- totalTestId?: string;-}) {- const fromTable = useMetabaseQuery(tableQuery);- const fromCard = useMetabaseQuery(cardQuery);-- const failure = fromTable.error ?? fromCard.error;- const tableResult = describeResult(fromTable.data);- const cardResult = describeResult(fromCard.data);-- const status = failure- ? `error: ${describeError(failure)}`- : tableResult === null || cardResult === null- ? "loading"- : tableResult === cardResult- ? "match"- : `mismatch: table=${tableResult} card=${cardResult}`;-- return (- <div>- <div data-testid={`card-source-case-${caseKey}`}>{status}</div>- {totalTestId && (- <div data-testid={totalTestId}>- {String(fromCard.data?.rawRows?.[0]?.[0] ?? "")}- </div>- )}- </div>- );-}--/** Column names plus every row value, by position — comparable across sources. */-const describeResult = (- data: { columns: { name: string }[]; rawRows: unknown[][] } | null,-): string | null =>- data &&- `[${data.columns.map((column) => column.name).join(",")}] ${JSON.stringify(data.rawRows)}`;-function Actions() {const { actionId, actionParams } = getTestEnv();- const action = useAction(actionId ?? null);+ // A data app names its actions by definition. Nothing synchronizes here, so+ // the copy the definition points at is the authored action itself.+ const action = useAction(+ actionId+ ? { action: { id: actionId, parameters: [] }, copiedActionId: actionId }+ : null,+ );const [output, setOutput] = useState("idle");const onExecute = async () => {@@ -576,8 +425,6 @@ const ROUTES: Record<string, ComponentType> = {"/native-query": NativeQueryPage,"/download-question": DownloadQuestionPage,"/custom-viz": CustomVizPage,- "/combinators": Combinators,- "/card-source": CardSource,"/actions": Actions,"/clipboard": Clipboard,"/missing-question": MissingQuestion,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.yamlnew file mode 100644index 00000000000..86b0733c401--- /dev/null+++ b/e2e/support/assets/data-apps/synced-actions-app/data_app.yaml@@ -0,0 +1,2 @@+name: Synced Actions App+path: ./dist/index.jsdiff --git a/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsxnew file mode 100644index 00000000000..83c64d6d1f1--- /dev/null+++ b/e2e/support/assets/data-apps/synced-actions-app/src/App.tsx@@ -0,0 +1,39 @@+import { useAction } from "@metabase/embedding-sdk-react";+import { useState } from "react";++import { CreateScore } from "../actions/orders.action";++/**+ * Passes a source-controlled definition to `useAction` rather than a bare ID, so+ * a production build executes whatever `sync-resources` wrote into it — the copy+ * the app's own group is permitted to run. The spec that drives this app writes+ * `actions/orders.action.ts` before synchronizing.+ */+export default function App() {+ const action = useAction(CreateScore);+ 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-actions-app/src/index.tsx b/e2e/support/assets/data-apps/synced-actions-app/src/index.tsxnew file mode 100644index 00000000000..97a94779d6c--- /dev/null+++ b/e2e/support/assets/data-apps/synced-actions-app/src/index.tsx@@ -0,0 +1,7 @@+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/synced-app/data_app.yaml b/e2e/support/assets/data-apps/synced-app/data_app.yamlnew file mode 100644index 00000000000..2d367561d2d--- /dev/null+++ b/e2e/support/assets/data-apps/synced-app/data_app.yaml@@ -0,0 +1,2 @@+name: Synced App+path: ./dist/index.jsdiff --git a/e2e/support/assets/data-apps/synced-app/src/App.tsx b/e2e/support/assets/data-apps/synced-app/src/App.tsxnew file mode 100644index 00000000000..efd45bb0685--- /dev/null+++ b/e2e/support/assets/data-apps/synced-app/src/App.tsx@@ -0,0 +1,29 @@+import { useMetabaseQuery } from "@metabase/embedding-sdk-react/data-app";++import { OrdersCount } from "../queries/orders.query";++/**+ * Consumes a source-controlled query rather than an inline one, so a production+ * build runs whatever `sync-resources` wrote into the declaration. The spec that+ * drives this app writes `queries/orders.query.ts` before synchronizing.+ */+export default function App() {+ const orders = useMetabaseQuery(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.tsxnew file mode 100644index 00000000000..97a94779d6c--- /dev/null+++ b/e2e/support/assets/data-apps/synced-app/src/index.tsx@@ -0,0 +1,7 @@+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/component-webpack.config.js b/e2e/support/component-webpack.config.jsindex cef19bfa5d2..8c80c4a74f5 100644--- a/e2e/support/component-webpack.config.js+++ b/e2e/support/component-webpack.config.js@@ -34,10 +34,16 @@ module.exports = {...RESOLVE_ALIASES,...(embeddingSdkDistPath? {+ // The package alias below points at a bundle file, so subpath+ // exports cannot resolve through it and each needs its own entry.[`${SDK_PACKAGE_NAME}/data-app-dev`]: path.join(embeddingSdkDistPath,"data-app-dev.js",),+ [`${SDK_PACKAGE_NAME}/data-app`]: path.join(+ embeddingSdkDistPath,+ "data-app.js",+ ),}: null),...(embeddingSdkPath ? { [SDK_PACKAGE_NAME]: embeddingSdkPath } : null),diff --git a/e2e/support/config.js b/e2e/support/config.jsindex c9b8db8cd72..117af42f427 100644--- a/e2e/support/config.js+++ b/e2e/support/config.js@@ -26,7 +26,14 @@ import {startCustomVizDevServer,stopCustomVizDevServer,} from "./helpers/e2e-custom-viz-dev-server-tasks";-import { buildDataApp } from "./helpers/e2e-data-app-tasks";+import {+ buildDataApp,+ removeDataAppDeclaration,+ removeDataAppPaths,+ scaffoldDataApp,+ syncDataApp,+ writeDataAppFiles,+} from "./helpers/e2e-data-app-tasks";import { signJwt } from "./helpers/e2e-jwt-tasks";import {startMockLlmServer,@@ -296,6 +303,11 @@ const defaultConfig = {startCustomVizDevServer,stopCustomVizDevServer,buildDataApp,+ syncDataApp,+ scaffoldDataApp,+ writeDataAppFiles,+ removeDataAppDeclaration,+ removeDataAppPaths,...perTestCaptureTasks,});diff --git a/e2e/support/helpers/api/groupPermissions.ts b/e2e/support/helpers/api/groupPermissions.tsnew file mode 100644index 00000000000..d4295f24589--- /dev/null+++ b/e2e/support/helpers/api/groupPermissions.ts@@ -0,0 +1,16 @@+export function addUserToGroup(groupId: number, email: string) {+ return cy+ .request<{ data: Array<{ id: number; email: string }> }>("/api/user")+ .then(({ body }) => {+ const user = body.data.find((candidate) => candidate.email === email);++ if (!user) {+ throw new Error(`No user with the email ${email}`);+ }++ return cy.request("POST", "/api/permissions/membership", {+ group_id: groupId,+ user_id: user.id,+ });+ });+}diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.tsindex 22fd863d7a6..714a81d813f 100644--- a/e2e/support/helpers/api/index.ts+++ b/e2e/support/helpers/api/index.ts@@ -39,6 +39,7 @@ export { createTransformTag } from "./createTransformTag";export * from "./customVizPlugin";export { deleteComment } from "./deleteComment";export { editDashboardCard } from "./editDashboardCard";+export { addUserToGroup } from "./groupPermissions";export { getCurrentUser } from "./getCurrentUser";export { publishTables } from "./publishTables";export { remapDisplayValueToFK } from "./remapDisplayValueToFK";diff --git a/e2e/support/helpers/data-app-fixture-paths.mjs b/e2e/support/helpers/data-app-fixture-paths.mjsindex fcdf0fd950c..d66d35de330 100644--- a/e2e/support/helpers/data-app-fixture-paths.mjs+++ b/e2e/support/helpers/data-app-fixture-paths.mjs@@ -15,6 +15,11 @@ export const DATA_APP_BUILD_SCRIPT = path.join("e2e/support/helpers/build-data-app-fixture.mjs",);+export const DATA_APP_SYNC_SCRIPT = path.join(+ REPO_ROOT,+ "e2e/support/helpers/sync-data-app-fixture.mjs",+);+export const SDK_DATA_APP_DEV_CONFIG_SOURCE = path.join(REPO_ROOT,"enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts",diff --git a/e2e/support/helpers/data-app-test-env.ts b/e2e/support/helpers/data-app-test-env.tsindex e427eab8600..ca7a9a95648 100644--- a/e2e/support/helpers/data-app-test-env.ts+++ b/e2e/support/helpers/data-app-test-env.ts@@ -1,8 +1,3 @@-import type {- LocalFieldReference,- QuestionColumnReference,-} from "@metabase/embedding-sdk-react/data-app";-/*** The config a spec injects into a data-app fixture (via `H.mockDataApp`'s* `testEnv`), so a fixture doesn't hard-code values that track the Cypress@@ -14,8 +9,17 @@ import type {* runtime through its own `getTestEnv()`.*/export type DataAppTestEnv = {- scalarQuery: { source: TableSource; aggregations: CountAggregation[] };- questionQuery: { source: TableSource };+ /**+ * A deployed app runs the card its query was published as, so every query the+ * fixture renders names one. The swap drops the static clauses the card+ * already contains, so each id must match its whole authored query.+ */+ scalarQuery: {+ source: TableSource;+ aggregations: CountAggregation[];+ savedQuestionSourceId: number;+ };+ questionQuery: { source: TableSource; savedQuestionSourceId: number };/*** `/download-question` page: the id of a saved CHART question (so a `.png`* export is offered). Passed in because the id tracks the Cypress snapshot.@@ -39,37 +43,11 @@ export type DataAppTestEnv = {xhrBlockedUrl?: string;};/**- * `/query-states` page: a deliberately invalid query (bad table id), so the hook- * resolves to an `error` state; the page also exercises `refetch`.- */- errorQuery?: { source: TableSource };- /**- * `/combinators` page: exercises `filter`/`breakout`/`orderBy`/`aggregations`.- * The page hardcodes a `>` filter and a count aggregation ordered desc, so- * `filterField` must be numeric; `breakoutField` groups the rows.- */- combinators?: {- source: TableSource;- filterField: LocalFieldReference;- filterValue: number;- breakoutField: LocalFieldReference;- };- /**- * `/card-source` page: exercises a saved-question source with filters,- * aggregations, and breakouts. Each clause set runs against both sources and- * the page reports whether they agree, so `source` must be an unfiltered copy- * of `tableSource`. `*Field` addresses the table, `*Column` the question's- * result columns.+ * `/query-states` page: a deliberately invalid query (a card that does not+ * exist), so the hook resolves to an `error` state rather than to the refusal+ * an unsynchronized query would raise; the page also exercises `refetch`.*/- cardSource?: {- source: CardSource;- tableSource: TableSource;- filterField: LocalFieldReference;- filterColumn: QuestionColumnReference;- filterValue: number;- breakoutField: LocalFieldReference;- breakoutColumn: QuestionColumnReference;- };+ errorQuery?: { source: TableSource; savedQuestionSourceId: number };/*** `/actions` page: the id of the action the spec creates and `useAction`* executes, so it can't be hard-coded in the app. Left out to exercise the "no@@ -90,5 +68,4 @@ export type DataAppTestEnv = {// The queries use the SDK's `source` API (`{ type: "table", id }`); the database// is resolved from the SDK's metadata store, so no databaseId is passed.type TableSource = { type: "table"; id: number };-type CardSource = { type: "card"; id: number };type CountAggregation = { type: "operator"; operator: "count"; args: [] };diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.tsindex 29fe63578b5..a4df9666b46 100644--- a/e2e/support/helpers/e2e-data-app-helpers.ts+++ b/e2e/support/helpers/e2e-data-app-helpers.ts@@ -1,49 +1,24 @@import { USER_GROUPS } from "e2e/support/cypress_data";import * as Urls from "metabase/urls/data-apps";-import type { DataApp } from "metabase-types/api";+import type {+ CardId,+ Collection,+ CollectionId,+ CollectionPermission,+ CollectionPermissionsGraph,+ DataApp,+} from "metabase-types/api";import type { DataAppTestEnv } from "./data-app-test-env";import { getIframeBody } from "./e2e-embedding-helpers";import { LOCAL_GIT_PATH } from "./e2e-remote-sync-helpers";-export const SYNCED_DATA_APPS_FIXTURE_PATH =- Cypress.config("projectRoot") +- "/e2e/support/assets/example_synced_data_apps";--/**- * Copy the example data-app repo into the working directory of the local git repo- * `setupGitSync` created, so a `commitToRepo` + a real pull materialize its apps.- * The repo holds one directory per materialization outcome (a good app, an app- * whose bundle is missing, a malformed config, and a directory with no config) —- * see the fixture and the sync spec that drives it.- */-export const copySyncedDataAppsFixture = () =>- cy.task("copyDirectory", {- source: SYNCED_DATA_APPS_FIXTURE_PATH,- destination: LOCAL_GIT_PATH,- });--/**- * The e2e data-app fixture that `mockDataApp` builds and serves — its directory- * name and its `/apps/<slug>` URL segment. One bundle with a page per surface it- * exercises (questions, query hooks, actions, clipboard, sandbox, isolation), so- * the specs share a single build.- */export const DATA_APP_NAME = "kitchen-sink";export const DATA_APP_DISPLAY_NAME = "Kitchen Sink";-/**- * Visit a nested route inside the fixture data app. `openDataApp` encodes the- * slug, so it can't carry a sub-path — deep-links go through a raw `cy.visit`.- */export const visitDataAppRoute = (route: string) =>cy.visit(`/apps/${DATA_APP_NAME}/${route}`);-/**- * A minimal `DataApp`-shaped row. Admin-list state tests use it directly (they- * only assert how the management UI renders the list, no real bundle needed);- * `mockDataApp` uses it for the intercepted metadata of the built fixture.- */export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({id: 1,name: DATA_APP_NAME,@@ -51,6 +26,8 @@ export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({description: null,bundle_path: `data_apps/${DATA_APP_NAME}/dist/index.js`,enabled: true,+ resource_collection_id: null,+ permission_group_id: null,allowed_hosts: [],bundle_hash: "e2e-bundle-hash",last_synced_sha: "e2e0000",@@ -67,25 +44,14 @@ type MockDataAppOptions<TestEnv> = {/** `allowed_hosts` served in the bundle response header. */allowedHosts?: string[];/**- * Config a fixture reads at runtime, so it doesn't hard-code values that track- * the Cypress snapshot (e.g. sample-DB ids). It's JSON-serialized and prepended- * to the served bundle as `globalThis.__METABASE_DATA_APP_TEST_ENV__`; since the- * bundle is evaluated as one script in the sandbox realm, the app reads it as a- * plain global. Typed by `DataAppTestEnv` by default; pass another fixture's- * type as `TestEnv` if it differs.+ * Config a fixture reads at runtime, rather than hard-coding ids that track the+ * Cypress snapshot.*/testEnv?: TestEnv;- /**- * Hold the bundle response for this many ms, so the app's loading window is- * long enough to assert on. Without it a small mocked bundle can render before- * the test ever queries, making any "still loading" assertion racy.- */- bundleDelay?: number;+ /** Delays the bundle response, so a loading assertion has a window to catch. */+ bundleDelayMs?: number;};-/**- * Set up a data app for the current test- */export const mockDataApp = <TestEnv = DataAppTestEnv>(appName: string,options: MockDataAppOptions<TestEnv> = {},@@ -127,7 +93,7 @@ export const mockDataApp = <TestEnv = DataAppTestEnv>("X-Metabase-Data-App-Allowed-Hosts": JSON.stringify(allowedHosts),},body: prelude + bundleCode,- ...(options.bundleDelay ? { delay: options.bundleDelay } : {}),+ ...(options.bundleDelayMs ? { delay: options.bundleDelayMs } : {}),},);@@ -143,23 +109,230 @@ export function dataAppIframe(displayName: string) {return getIframeBody(`iframe[title="${displayName}"]`);}+export function setDataAppCollectionAccess(+ collectionId: CollectionId,+ access: CollectionPermission,+) {+ return cy+ .request<CollectionPermissionsGraph>("GET", "/api/collection/graph")+ .then(({ body: graph }) => {+ const groups = Object.fromEntries(+ Object.entries(graph.groups).map(([groupId, collections]) => [+ groupId,+ Number(groupId) === USER_GROUPS.ADMIN_GROUP+ ? collections+ : { ...collections, [collectionId]: access },+ ]),+ );++ cy.request("PUT", "/api/collection/graph", { ...graph, groups });+ });+}++export function moveDataAppModelToCollection({+ modelId,+ name,+ access,+}: {+ modelId: CardId;+ name: string;+ access: CollectionPermission;+}) {+ return cy+ .request<Collection>("POST", "/api/collection", { name })+ .then(({ body: collection }) => {+ cy.request("PUT", `/api/card/${modelId}`, {+ collection_id: collection.id,+ });++ setDataAppCollectionAccess(collection.id, access);++ return cy.wrap(collection, { log: false });+ });+}++/**+ * The dev host app is a real vite data app with the published SDK installed, so+ * synchronizing it exercises the package an author actually consumes rather than+ * the stub the scratch fixture provides.+ */+export const dataAppHostAppRoot = () =>+ `${Cypress.config("projectRoot")}/${DATA_APP_DEV_HOST_APP_DIR}`;++const actionDeclarationsFile = (appRoot: string) =>+ `${appRoot}/actions/orders.action.ts`;++/**+ * Clears everything synchronization generates in the host app. Both sync specs+ * drive the same checked-in directory, so each has to start from a clean tree —+ * a stray `actions/` would otherwise be discovered by the query spec's sync.+ */+export function resetDataAppHostAppSources() {+ const appRoot = dataAppHostAppRoot();++ return cy.task("removeDataAppPaths", {+ paths: [+ `${appRoot}/queries`,+ `${appRoot}/actions`,+ `${appRoot}/resources_metadata.json`,+ ],+ });+}++export function declareDataAppActions(+ appRoot: string,+ sourceActionIds: number[],+) {+ return cy.task("writeDataAppFiles", {+ files: {+ [actionDeclarationsFile(appRoot)]: [+ 'import { defineAction } from "@metabase/embedding-sdk-react/data-app";',+ ...sourceActionIds.map(+ (id) =>+ `export const Action${id} = defineAction({ action: { id: ${id}, parameters: [] } });`,+ ),+ ].join("\n"),+ },+ });+}++const queryDeclarationsFile = (appRoot: string) =>+ `${appRoot}/queries/orders.query.ts`;++/** Declares one `defineQuery` per entry, as an app author would. */+export function declareDataAppQueries(+ appRoot: string,+ declarations: Array<{ name: string; tableId: number; limit?: number }>,+) {+ return cy.task("writeDataAppFiles", {+ files: {+ [queryDeclarationsFile(appRoot)]: [+ 'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',+ ...declarations.map(({ name, tableId, limit }) => {+ const clauses = limit === undefined ? "" : `, limit: ${limit}`;+ return `export const ${name} = defineQuery({ source: { type: "table", id: ${tableId} }${clauses} });`;+ }),+ ].join("\n"),+ },+ });+}++/**+ * Deletes one declaration in place, so the rest keep the generated IDs+ * synchronization injected — which is what an author removing one does.+ * Splits on the declaration keyword rather than on lines, because an injected+ * ID lands on its own line and makes a declaration span several.+ */+function removeDeclaration(filePath: string, exportName: string) {+ return cy.task("removeDataAppDeclaration", { filePath, exportName });+}++export function removeDataAppQueryDeclaration(appRoot: string, name: string) {+ return removeDeclaration(queryDeclarationsFile(appRoot), name);+}++export function removeDataAppActionDeclaration(+ appRoot: string,+ sourceActionId: number,+) {+ return removeDeclaration(+ actionDeclarationsFile(appRoot),+ `Action${sourceActionId}`,+ );+}++/** Runs the real `sync-resources` CLI against the instance under test. */+export function syncDataAppResources(apiKey: string, appRoot: string) {+ return cy.task<{ ok: boolean; error: string | null }>("syncDataApp", {+ appRoot,+ metabaseUrl: Cypress.config("baseUrl"),+ apiKey,+ });+}++export const copySyncedDataAppsFixture = () =>+ cy.task("copyDirectory", {+ source: `${Cypress.config("projectRoot")}/e2e/support/assets/example_synced_data_apps`,+ destination: LOCAL_GIT_PATH,+ });++/** The test repo is not an npm project, so `defineQuery` needs a stub to resolve. */+export function declareSyncedDataAppQuery(slug: string, tableId: number) {+ const appRoot = `${LOCAL_GIT_PATH}/data_apps/${slug}`;+ const packageRoot = `${appRoot}/node_modules/@metabase/embedding-sdk-react`;++ return cy.task("writeDataAppFiles", {+ files: {+ [`${packageRoot}/package.json`]: JSON.stringify({+ name: "@metabase/embedding-sdk-react",+ exports: { "./data-app": "./data-app.js" },+ }),+ [`${packageRoot}/data-app.js`]: "exports.defineQuery = (q) => q;",+ [`${appRoot}/queries/orders.query.ts`]: [+ 'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',+ `export const Orders = defineQuery({ source: { type: "table", id: ${tableId} } });`,+ "",+ ].join("\n"),+ },+ });+}++export function createDataAppApiKey() {+ return cy+ .request<{ unmasked_key: string }>("POST", "/api/api-key", {+ name: `data-app-sync-e2e-${Date.now()}`,+ group_id: USER_GROUPS.ADMIN_GROUP,+ })+ .then(({ body }) => body.unmasked_key);+}++/**+ * A second app beside the host app, for cases that need two of them. It reuses+ * the host app's `node_modules`, so `defineQuery` still resolves through the+ * published SDK, and its directory name becomes the app's slug.+ */+export function createSecondDataApp(slug: string) {+ cy.task("scaffoldDataApp", { appName: slug, sdkFrom: dataAppHostAppRoot() });++ return `${Cypress.config("projectRoot")}/e2e/tmp/${slug}`;+}++/**+ * Runs the host app's own production build. The SDK's `metabase-resource-sync-check`+ * plugin runs on `buildStart`, so this is what refuses to bundle a stale app.+ */+export function buildDataAppHostApp() {+ return cy.exec(`cd "${dataAppHostAppRoot()}" && npm run build`, {+ failOnNonZeroExit: false,+ timeout: 180_000,+ });+}++/** The app's own permission group — the one its viewers are given. */+export function dataAppPermissionGroupId(slug: string) {+ return cy.request<DataApp>(`/api/apps/${slug}`).then(({ body }) => {+ const groupId = body.permission_group_id;++ if (typeof groupId !== "number") {+ throw new Error(`Data app ${slug} has no permission group.`);+ }++ return cy.wrap(groupId, { log: false });+ });+}++/** Puts a user in the app's own permission group, as granting app access does. */const DATA_APP_DEV_HOST_APP_DIR ="e2e/embedding-sdk-host-apps/vite-6-data-app-host-app";const DATA_APP_DEV_ENV_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/.env.local`;-/** The dev host app's manifest — the live manifest-validation suite edits it. */export const DATA_APP_DEV_MANIFEST_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/data_app.yaml`;-/** The dev host app's source entry — the soft-reload suite edits it. */export const DATA_APP_DEV_APP_SRC_PATH = `${DATA_APP_DEV_HOST_APP_DIR}/src/App.tsx`;const DATA_APP_DEV_CONTENT_TIMEOUT_MS = 40000;-/**- * Visit the dev host app and wait for the sandboxed bundle to render — the- * point at which the dev entry has booted (toolbar mounted, probes fired).- */export function visitDataAppDevApp(clientHost: string) {cy.visit(clientHost);cy.findByTestId("dev-app-content", {@@ -167,35 +340,31 @@ export function visitDataAppDevApp(clientHost: string) {}).should("exist");}-/**- * Provision auth for the data-app dev-server host app: create an API key and- * write the `.env.local` the SDK dev entry reads at startup, then wait for Vite- * to restart onto it. `clientHost` is the dev server origin.- */export function setUpDataAppDevServer(clientHost: string) {const mbUrl = Cypress.config("baseUrl");if (!mbUrl) {throw new Error("baseUrl must be set for the data-app dev-server suite");}- cy.exec(`rm -f ${DATA_APP_DEV_ENV_PATH}`);+ cy.task("removeDataAppPaths", { paths: [DATA_APP_DEV_ENV_PATH] });waitForDataAppDevServerEnv(clientHost, mbUrl, { expectPresent: false });cy.request("POST", "/api/api-key", {name: `data-app-dev-e2e-${Date.now()}`,group_id: USER_GROUPS.ADMIN_GROUP,}).then(({ body }) => {- cy.writeFile(- DATA_APP_DEV_ENV_PATH,- `DATA_APP_MB_URL=${mbUrl}\nDATA_APP_MB_API_KEY=${body.unmasked_key}\n`,- );+ cy.task("writeDataAppFiles", {+ files: {+ [DATA_APP_DEV_ENV_PATH]: `DATA_APP_MB_URL=${mbUrl}\nDATA_APP_MB_API_KEY=${body.unmasked_key}\n`,+ },+ });});waitForDataAppDevServerEnv(clientHost, mbUrl, { expectPresent: true });}export function tearDownDataAppDevServer() {- cy.exec(`rm -f ${DATA_APP_DEV_ENV_PATH}`);+ return cy.task("removeDataAppPaths", { paths: [DATA_APP_DEV_ENV_PATH] });}// `DATA_APP_MB_URL` shows up in (or drops out of) the served CSP once Vite hasdiff --git a/e2e/support/helpers/e2e-data-app-tasks.ts b/e2e/support/helpers/e2e-data-app-tasks.tsindex 724e9e0f6e9..3e6ad76bec4 100644--- a/e2e/support/helpers/e2e-data-app-tasks.ts+++ b/e2e/support/helpers/e2e-data-app-tasks.ts@@ -5,27 +5,25 @@ import path from "node:path";import {DATA_APP_BUILD_SCRIPT,DATA_APP_FIXTURES_DIR,+ DATA_APP_SYNC_SCRIPT,REPO_ROOT,} from "./data-app-fixture-paths.mjs";-/**- * Cypress task: build a data-app fixture and return its bundle code.- */-export async function buildDataApp({- appName,-}: {- appName: string;-}): Promise<string> {- const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);-- if (!fs.existsSync(path.join(appDir, "src"))) {- throw new Error(`data-app fixture "${appName}" has no src/ at ${appDir}`);- }-- await new Promise<void>((resolve, reject) => {- const child = spawn(process.execPath, [DATA_APP_BUILD_SCRIPT, appName], {+function run(script: string, args: string[], env: NodeJS.ProcessEnv = {}) {+ return new Promise<void>((resolve, reject) => {+ const child = spawn(process.execPath, [script, ...args], {cwd: REPO_ROOT,- stdio: ["ignore", "inherit", "inherit"],+ env: { ...process.env, ...env },+ stdio: ["ignore", "inherit", "pipe"],+ });++ // Mirrored to the runner as it arrives, and kept so a rejection carries the+ // script's own message rather than a bare exit code.+ let stderr = "";+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (chunk: string) => {+ stderr += chunk;+ process.stderr.write(chunk);});child.on("error", reject);@@ -34,11 +32,49 @@ export async function buildDataApp({? resolve(): reject(new Error(- `data-app build for "${appName}" exited with code ${code}`,+ stderr.trim() ||+ `${path.basename(script)} ${args.join(" ")} exited with code ${code}`,),),);});+}++export async function syncDataApp({+ appRoot,+ metabaseUrl,+ apiKey,+}: {+ appRoot: string;+ metabaseUrl: string;+ apiKey: string;+}): Promise<{ ok: boolean; error: string | null }> {+ try {+ await run(DATA_APP_SYNC_SCRIPT, [appRoot], {+ DATA_APP_MB_URL: metabaseUrl,+ DATA_APP_MB_API_KEY: apiKey,+ });+ return { ok: true, error: null };+ } catch (error) {+ return {+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+}++export async function buildDataApp({+ appName,+}: {+ appName: string;+}): Promise<string> {+ const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);++ if (!fs.existsSync(path.join(appDir, "src"))) {+ throw new Error(`data-app fixture "${appName}" has no src/ at ${appDir}`);+ }++ await run(DATA_APP_BUILD_SCRIPT, [appName]);const bundlePath = path.join(DATA_APP_FIXTURES_DIR, appName, "dist/index.js");@@ -50,3 +86,93 @@ export async function buildDataApp({return fs.readFileSync(bundlePath, "utf8");}++/** Cypress resolves a relative path against the project root; match that. */+function inRepo(target: string) {+ return path.isAbsolute(target) ? target : path.join(REPO_ROOT, target);+}++/**+ * The fixture filesystem lives behind tasks rather than `cy.exec`/`cy.writeFile`+ * so a spec changes an app in one round trip, and so nothing is composed into a+ * shell string.+ */+export async function scaffoldDataApp({+ appName,+ sdkFrom,+}: {+ appName: string;+ sdkFrom: string;+}): Promise<string> {+ // The task owns the location so a caller cannot aim the `rmSync` below elsewhere.+ if (path.basename(appName) !== appName) {+ throw new Error(`A scaffolded app is named, not located: ${appName}`);+ }++ const root = path.join(REPO_ROOT, "e2e", "tmp", appName);++ fs.rmSync(root, { recursive: true, force: true });+ fs.mkdirSync(root, { recursive: true });+ // The SDK the app synchronizes against, without a second npm install.+ fs.symlinkSync(+ path.join(inRepo(sdkFrom), "node_modules"),+ path.join(root, "node_modules"),+ );+ fs.writeFileSync(+ path.join(root, "data_app.yaml"),+ `name: ${appName}\npath: ./dist/index.js\n`,+ );++ return root;+}++export async function writeDataAppFiles({+ files,+}: {+ files: Record<string, string>;+}): Promise<null> {+ for (const [filePath, contents] of Object.entries(files)) {+ const target = inRepo(filePath);++ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, contents);+ }++ return null;+}++export async function removeDataAppDeclaration({+ filePath,+ exportName,+}: {+ filePath: string;+ exportName: string;+}): Promise<null> {+ const target = inRepo(filePath);+ const [imports, ...declarations] = fs+ .readFileSync(target, "utf8")+ .split("export const ");++ fs.writeFileSync(+ target,+ imports ++ declarations+ .filter((declaration) => !declaration.startsWith(`${exportName} `))+ .map((declaration) => `export const ${declaration}`)+ .join(""),+ );++ return null;+}++export async function removeDataAppPaths({+ paths,+}: {+ paths: string[];+}): Promise<null> {+ for (const target of paths) {+ fs.rmSync(inRepo(target), { recursive: true, force: true });+ }++ return null;+}diff --git a/e2e/support/helpers/sync-data-app-fixture.mjs b/e2e/support/helpers/sync-data-app-fixture.mjsnew file mode 100644index 00000000000..517b446f725--- /dev/null+++ b/e2e/support/helpers/sync-data-app-fixture.mjs@@ -0,0 +1,50 @@+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";++import { build as bundle } from "esbuild";++import { DATA_APP_FIXTURES_DIR, REPO_ROOT } from "./data-app-fixture-paths.mjs";++const appRoot = process.argv[2];+if (!appRoot) {+ console.error("usage: sync-data-app-fixture.mjs <appRoot>");+ process.exit(2);+}++const { DATA_APP_MB_URL, DATA_APP_MB_API_KEY } = process.env;+if (!DATA_APP_MB_URL || !DATA_APP_MB_API_KEY) {+ console.error("DATA_APP_MB_URL and DATA_APP_MB_API_KEY must be set");+ process.exit(2);+}++const SDK_PACKAGE_DIR = path.join(+ REPO_ROOT,+ "enterprise/frontend/src/embedding-sdk-package",+);++const scratchDir = path.join(DATA_APP_FIXTURES_DIR, ".build");+fs.mkdirSync(scratchDir, { recursive: true });+const entry = path.join(scratchDir, "sync-resources.mjs");++// The synchronization sources are TypeScript and reach the SDK package by its+// build alias, so bundle them the way the fixture build does before importing.+await bundle({+ entryPoints: [path.join(SDK_PACKAGE_DIR, "data-app-query-sync/sync.ts")],+ outfile: entry,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ alias: { "embedding-sdk-package": SDK_PACKAGE_DIR },+ logLevel: "warning",+});++const { syncResources } = await import(pathToFileURL(entry).href);++await syncResources({+ appRoot,+ metabaseUrl: DATA_APP_MB_URL,+ apiKey: DATA_APP_MB_API_KEY,+ log: (message) => console.log(`[sync-resources] ${message}`),+});diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsxnew file mode 100644index 00000000000..ac65872d4b0--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-query-sources.cy.spec.tsx@@ -0,0 +1,197 @@+import { MetabaseProvider } from "@metabase/embedding-sdk-react";+import {+ type MetabaseQueryOptions,+ aggregations,+ breakout,+ filter,+ orderBy,+ useMetabaseQuery,+} from "@metabase/embedding-sdk-react/data-app";++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion } from "e2e/support/helpers";+import {+ DEFAULT_SDK_AUTH_PROVIDER_CONFIG,+ mountSdk,+} from "e2e/support/helpers/embedding-sdk-component-testing";+import {+ mockAuthProviderAndJwtSignIn,+ signInAsAdminAndEnableEmbeddingSdk,+} from "e2e/support/helpers/embedding-sdk-testing";++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++const tableSource = { type: "table" as const, id: ORDERS_ID };++/** The same dimension addressed on a table source and on a card's result columns. */+const totalField = {+ type: "column" as const,+ fieldId: ORDERS.TOTAL,+ tableId: ORDERS_ID,+ name: "TOTAL",+ jsType: "number" as const,+};+const totalColumn = {+ type: "column" as const,+ name: "TOTAL",+ jsType: "number" as const,+};+const productField = {+ type: "column" as const,+ fieldId: ORDERS.PRODUCT_ID,+ tableId: ORDERS_ID,+ name: "PRODUCT_ID",+ jsType: "number" as const,+};+const productColumn = {+ type: "column" as const,+ name: "PRODUCT_ID",+ jsType: "number" as const,+};++const describeResult = (+ data: { columns: { name: string }[]; rawRows: unknown[][] } | null,+) =>+ data &&+ `[${data.columns.map((column) => column.name).join(",")}] ${JSON.stringify(data.rawRows)}`;++/**+ * Runs the same clauses against a table source and against a card of that table,+ * and reports whether they agree — so an assertion never has to encode+ * sample-database numbers.+ */+function QueryComparison({+ tableQuery,+ cardQuery,+}: {+ tableQuery: MetabaseQueryOptions<undefined>;+ cardQuery: MetabaseQueryOptions<undefined>;+}) {+ const fromTable = useMetabaseQuery(tableQuery);+ const fromCard = useMetabaseQuery(cardQuery);++ const failure = fromTable.error ?? fromCard.error;+ const table = describeResult(fromTable.data);+ const card = describeResult(fromCard.data);++ const status = failure+ ? `error: ${String(failure)}`+ : table === null || card === null+ ? "loading"+ : table === card+ ? "match"+ : `mismatch: table=${table} card=${card}`;++ return (+ <>+ <div data-testid="comparison">{status}</div>+ <div data-testid="first-aggregate">+ {String(fromCard.data?.rawRows?.[0]?.at(-1) ?? "")}+ </div>+ </>+ );+}++/**+ * A table source and a saved-question source are interchangeable to the query+ * DSL. This lives outside a data app on purpose: there a query runs the card it+ * was published as, so an un-published table source is refused and the two+ * cannot be compared side by side.+ */+describe("scenarios > embedding-sdk > query sources", () => {+ beforeEach(() => {+ signInAsAdminAndEnableEmbeddingSdk();++ createQuestion({+ name: "Orders, for source comparison",+ query: { "source-table": ORDERS_ID },+ }).then(({ body: card }) => {+ cy.wrap({ type: "card" as const, id: card.id }).as("cardSource");+ });++ cy.signOut();+ mockAuthProviderAndJwtSignIn();+ });++ const compare = (+ build: (source: { type: "card"; id: number }) => {+ tableQuery: MetabaseQueryOptions<undefined>;+ cardQuery: MetabaseQueryOptions<undefined>;+ },+ ) =>+ cy.get<{ type: "card"; id: number }>("@cardSource").then((cardSource) => {+ const { tableQuery, cardQuery } = build(cardSource);++ mountSdk(+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>+ <QueryComparison tableQuery={tableQuery} cardQuery={cardQuery} />+ </MetabaseProvider>,+ );++ cy.findByTestId("comparison", { timeout: 30000 }).should(+ "have.text",+ "match",+ );+ // Every comparison ends in an aggregation, and breakout columns come first, so+ // the first row's last cell is an aggregate. An empty result renders "" and a+ // zero count renders 0 — both vacuous matches, and both fail here.+ cy.findByTestId("first-aggregate").should(($el) =>+ expect(Number($el.text())).to.be.greaterThan(0),+ );+ });++ it("returns the same rows from a table and from a card of that table", () => {+ compare((source) => ({+ tableQuery: { source: tableSource, aggregations: [aggregations.count()] },+ cardQuery: { source, aggregations: [aggregations.count()] },+ }));+ });++ it("applies filters the same way on either source", () => {+ compare((source) => ({+ tableQuery: {+ source: tableSource,+ filters: [filter(totalField, ">", 50)],+ aggregations: [aggregations.count()],+ },+ cardQuery: {+ source,+ filters: [filter(totalColumn, ">", 50)],+ aggregations: [aggregations.count()],+ },+ }));+ });++ it("applies aggregations the same way on either source", () => {+ compare((source) => ({+ tableQuery: {+ source: tableSource,+ aggregations: [aggregations.count(), aggregations.sum(totalField)],+ },+ cardQuery: {+ source,+ aggregations: [aggregations.count(), aggregations.sum(totalColumn)],+ },+ }));+ });++ // The combinators the query builder exposes, on both source kinds at once.+ it("applies breakouts and orderBys the same way on either source", () => {+ compare((source) => ({+ tableQuery: {+ source: tableSource,+ filters: [filter(totalField, ">", 50)],+ aggregations: [aggregations.count()],+ breakouts: [breakout(productField)],+ orderBys: [orderBy(productField, "asc")],+ },+ cardQuery: {+ source,+ filters: [filter(totalColumn, ">", 50)],+ aggregations: [aggregations.count()],+ breakouts: [breakout(productColumn)],+ orderBys: [orderBy(productColumn, "asc")],+ },+ }));+ });+});diff --git a/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts b/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.tsnew file mode 100644index 00000000000..a99c4df0500--- /dev/null+++ b/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts@@ -0,0 +1,607 @@+import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";+import {+ addUserToGroup,+ createDataAppApiKey,+ dataAppHostAppRoot,+ dataAppPermissionGroupId,+ declareDataAppActions,+ moveDataAppModelToCollection,+ removeDataAppActionDeclaration,+ resetDataAppHostAppSources,+ syncDataAppResources,+} from "e2e/support/helpers";+import type { Card } from "metabase-types/api";++const { H } = cy;++const TEST_TABLE = "scoreboard_actions";+const MODEL_NAME = "Scoreboard model";++/** `syncResources` takes the app's slug from its directory name. */+const APP_SLUG = "vite-6-data-app-host-app";++const APP_ROOT = () => dataAppHostAppRoot();++/**+ * Drives the real `sync-resources` CLI against a live instance, so the copies are+ * checked against Metabase rather than a fake of its API. The unit suite covers+ * the decision logic; this covers the contract.+ */+describe(+ "Embedding SDK: data-app sync-resources (actions)",+ { 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);+ H.createModelFromTableName({+ tableName: TEST_TABLE,+ modelName: MODEL_NAME,+ });++ resetDataAppHostAppSources();+ createDataAppApiKey().as("apiKey");+ });++ after(() => {+ resetDataAppHostAppSources();+ });++ const sync = () =>+ cy.get<string>("@apiKey").then((apiKey) => {+ syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {+ expect(error, "sync-resources failed").to.eq(null);+ expect(ok).to.eq(true);+ });+ });++ /** The models Metabase holds in the app's own collection. */+ const copiedModels = () =>+ cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {+ expect(app.resource_collection_id, "resource collection").to.be.a(+ "number",+ );+ return cy+ .request(+ `/api/collection/${app.resource_collection_id}/items?models=dataset`,+ )+ .then(({ body }) => body.data);+ });++ const actionsOnModel = (modelId: number) =>+ cy.request(`/api/action?model-id=${modelId}`).then(({ body }) => body);++ /** Runs a sync that must be refused, and returns the message it refused with. */+ const syncExpectingRefusal = (message: string) =>+ cy.get<string>("@apiKey").then((apiKey) => {+ syncDataAppResources(apiKey, APP_ROOT()).should(({ ok, error }) => {+ expect(ok, "sync-resources should have refused").to.eq(false);+ expect(error).to.contain(message);+ });+ });++ /** Declares one implicit action on the fixture model, without syncing yet. */+ const declareOneAction = () =>+ cy.get<number>("@modelId").then((modelId) =>+ H.createImplicitAction({ model_id: modelId, kind: "create" }).then(+ ({ body: action }) => {+ declareDataAppActions(APP_ROOT(), [action.id]);+ return cy.wrap({ modelId, action }, { log: false });+ },+ ),+ );++ /** Syncs one declared action and hands back the copies Metabase now holds. */+ const syncOneAction = () =>+ declareOneAction().then(({ modelId, action }) => {+ sync();+ return copiedModels().then(([copiedModel]) =>+ actionsOnModel(copiedModel.id).then(([copiedAction]) =>+ cy.wrap(+ { modelId, action, copiedModel, copiedAction },+ { log: false },+ ),+ ),+ );+ });++ it("copies the model once for two actions, then deletes each copy as its declaration is removed", () => {+ cy.get<number>("@modelId").then((modelId) => {+ H.createImplicitAction({ model_id: modelId, kind: "create" }).then(+ ({ body: create }) => {+ H.createImplicitAction({ model_id: modelId, kind: "update" }).then(+ ({ body: update }) => {+ declareDataAppActions(APP_ROOT(), [create.id, update.id]);++ sync();++ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ const copiedModelId = models[0].id;+ expect(copiedModelId).not.to.eq(modelId);++ actionsOnModel(copiedModelId).then((actions) => {+ expect(actions).to.have.length(2);+ });+ });++ // Injected back into source: the ID a production build runs.+ cy.readFile(`${APP_ROOT()}/actions/orders.action.ts`).should(+ "match",+ /copiedActionId: \d+/,+ );++ cy.readFile(`${APP_ROOT()}/resources_metadata.json`).then(+ (lockfile) => {+ expect(lockfile.models).to.have.length(1);+ expect(lockfile.models[0].actions).to.have.length(2);+ },+ );++ sync();+ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ actionsOnModel(models[0].id).then((actions) => {+ expect(actions).to.have.length(2);+ });+ });++ // The model survives: its sibling still needs it.+ removeDataAppActionDeclaration(APP_ROOT(), update.id);+ sync();++ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ actionsOnModel(models[0].id).then((actions) => {+ expect(actions).to.have.length(1);+ });+ });++ removeDataAppActionDeclaration(APP_ROOT(), create.id);+ sync();++ copiedModels().should("have.length", 0);+ cy.readFile(`${APP_ROOT()}/resources_metadata.json`).then(+ (lockfile) => {+ expect(lockfile.models).to.have.length(0);+ },+ );+ },+ );+ },+ );+ });+ });++ it("updates the copies in place when the source model or action changes", () => {+ cy.get<number>("@modelId").then((modelId) => {+ H.createImplicitAction({ model_id: modelId, kind: "create" }).then(+ ({ body: action }) => {+ declareDataAppActions(APP_ROOT(), [action.id]);+ sync();++ copiedModels().then(([copy]) => {+ cy.request("PUT", `/api/card/${modelId}`, {+ name: `${MODEL_NAME} renamed`,+ });+ cy.request("PUT", `/api/action/${action.id}`, {+ description: "now documented",+ });++ sync();++ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ expect(models[0].id).to.eq(copy.id);+ expect(models[0].name).to.eq(`${MODEL_NAME} renamed`);++ actionsOnModel(models[0].id).then((actions) => {+ expect(actions).to.have.length(1);+ expect(actions[0].description).to.eq("now documented");+ });+ });+ });+ },+ );+ });+ });++ it("leaves the copies untouched when nothing changed", () => {+ syncOneAction().then(({ copiedModel, copiedAction }) => {+ sync();++ copiedModels().then(([model]) => {+ expect(model.id).to.eq(copiedModel.id);+ expect(model.updated_at, "the model copy was not rewritten").to.eq(+ copiedModel.updated_at,+ );++ actionsOnModel(model.id).then(([action]) => {+ expect(action.id).to.eq(copiedAction.id);+ expect(+ action.updated_at,+ "the action copy was not rewritten",+ ).to.eq(copiedAction.updated_at);+ });+ });+ });+ });++ it("restores a copied model edited directly in Metabase", () => {+ syncOneAction().then(({ copiedModel }) => {+ cy.request("PUT", `/api/card/${copiedModel.id}`, {+ name: "Edited by hand",+ });++ sync();++ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ expect(models[0].id).to.eq(copiedModel.id);+ expect(models[0].name).to.eq(MODEL_NAME);+ });+ });+ });++ it("restores a copied action edited directly in Metabase", () => {+ syncOneAction().then(({ copiedModel, copiedAction }) => {+ cy.request("PUT", `/api/action/${copiedAction.id}`, {+ name: "Edited by hand",+ });++ sync();++ actionsOnModel(copiedModel.id).then((actions) => {+ expect(actions).to.have.length(1);+ expect(actions[0].id).to.eq(copiedAction.id);+ expect(actions[0].name).to.eq(copiedAction.name);+ });+ });+ });++ describe("permissions", () => {+ const joinAppGroup = () =>+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ addUserToGroup(groupId, USERS.normal.email);+ return cy.wrap(groupId, { log: false });+ });++ // The copy is the whole point of the model copy: an app's viewers hold+ // read on the app's collection, so only the copy is reachable to them.+ it("lets the app's group execute the copy but not the action it was copied from", () => {+ syncOneAction().then(({ modelId, action, copiedAction }) => {+ // An action is readable through its model, and the fixture model sits+ // in the root collection the normal user's groups can read.+ moveDataAppModelToCollection({+ modelId,+ name: "Source models",+ access: "none",+ });+ joinAppGroup();++ cy.signInAsNormalUser();+ cy.request({+ method: "POST",+ url: `/api/action/${copiedAction.id}/execute`,+ body: { parameters: { team_name: "Data App FC", score: 7 } },+ })+ .its("status")+ .should("be.oneOf", [200, 204]);++ // The same request against the source, so the two are like for like.+ cy.request({+ method: "POST",+ url: `/api/action/${action.id}/execute`,+ body: { parameters: { team_name: "Data App FC", score: 7 } },+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);++ cy.request({+ url: `/api/action/${action.id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ });+ });++ it("reports a copy that was deleted in Metabase without being re-synced", () => {+ syncOneAction().then(({ copiedAction }) => {+ joinAppGroup();++ // The source still names this copy, but a production bundle built+ // before the deletion keeps addressing it.+ cy.request("DELETE", `/api/action/${copiedAction.id}`);++ cy.signInAsNormalUser();+ cy.request({+ method: "POST",+ url: `/api/action/${copiedAction.id}/execute`,+ body: { parameters: { team_name: "Data App FC", score: 7 } },+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 404);+ });+ });++ it("does not widen access to the model the copy was made from", () => {+ syncOneAction().then(({ modelId, copiedModel }) => {+ // The fixture model is created in the root collection, which the+ // normal user's groups can read, so close it before asking whether+ // the app's group opened anything.+ moveDataAppModelToCollection({+ modelId,+ name: "Source models",+ access: "none",+ });+ joinAppGroup();++ cy.signInAsNormalUser();+ cy.request(`/api/card/${copiedModel.id}`)+ .its("body.id")+ .should("eq", copiedModel.id);+ cy.request({ url: `/api/card/${modelId}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 403);+ });+ });+ });++ describe("recovery", () => {+ it("reuses the existing copies when copiedActionId is missing from the source", () => {+ syncOneAction().then(({ action, copiedModel, copiedAction }) => {+ // Rewriting the declarations drops the injected ID, as a bad merge would.+ declareDataAppActions(APP_ROOT(), [action.id]);+ sync();++ actionsOnModel(copiedModel.id).then((actions) => {+ expect(actions).to.have.length(1);+ expect(actions[0].id, "the copy is reused, not replaced").to.eq(+ copiedAction.id,+ );+ });+ cy.readFile(`${APP_ROOT()}/actions/orders.action.ts`).should(+ "contain",+ `copiedActionId: ${copiedAction.id}`,+ );+ });+ });++ it("recreates the copied action but keeps its model when the action is deleted in Metabase", () => {+ syncOneAction().then(({ copiedModel, copiedAction }) => {+ cy.request("DELETE", `/api/action/${copiedAction.id}`);+ sync();++ copiedModels().then((models) => {+ expect(models, "the model survives").to.have.length(1);+ expect(models[0].id).to.eq(copiedModel.id);++ actionsOnModel(models[0].id).then((actions) => {+ expect(actions).to.have.length(1);+ expect(actions[0].id).not.to.eq(copiedAction.id);+ });+ });+ });+ });++ it("brings back a copied model that was trashed on its own", () => {+ syncOneAction().then(({ copiedModel }) => {+ cy.request("PUT", `/api/card/${copiedModel.id}`, { archived: true });++ sync();++ cy.request(`/api/card/${copiedModel.id}`).then(+ ({ body: restored }) => {+ expect(restored.archived, "the copy is out of the trash").to.eq(+ false,+ );+ expect(restored.collection_id).to.eq(copiedModel.collection_id);+ },+ );+ });+ });++ it("recreates the copied model after it is deleted in Metabase", () => {+ syncOneAction().then(({ copiedModel }) => {+ cy.request("DELETE", `/api/card/${copiedModel.id}`);+ sync();++ copiedModels().then((models) => {+ expect(models).to.have.length(1);+ expect(models[0].id).not.to.eq(copiedModel.id);+ });+ });+ });+ });++ describe("refusals", () => {+ // `GET /api/action/:id` filters archived actions out, so an archived source+ // is unreadable rather than readable-and-flagged.+ it("copies nothing when the action's model is in the trash", () => {+ declareOneAction().then(({ modelId }) => {+ cy.request("PUT", `/api/card/${modelId}`, { archived: true });++ syncExpectingRefusal(`references an action on model ${modelId}`);+ copiedModels().should("have.length", 0);+ });+ });++ it("copies nothing when a declared action is archived and cannot be read", () => {+ declareOneAction().then(({ action }) => {+ cy.request("PUT", `/api/action/${action.id}`, { archived: true });++ syncExpectingRefusal(`Could not read action ${action.id}`);+ copiedModels().should("have.length", 0);+ });+ });++ // Validation itself is unit-tested; what matters here is that a rejected+ // lockfile stops the CLI before it mutates anything.+ it("refuses to sync when resources_metadata.json is corrupt, leaving the copies alone", () => {+ syncOneAction().then(({ copiedModel, copiedAction }) => {+ cy.writeFile(`${APP_ROOT()}/resources_metadata.json`, "{ not json");++ syncExpectingRefusal("Could not read resources_metadata.json");++ copiedModels().then((models) => {+ expect(models, "the copies are left alone").to.have.length(1);+ expect(models[0].id).to.eq(copiedModel.id);++ actionsOnModel(models[0].id).then((actions) => {+ expect(actions).to.have.length(1);+ expect(actions[0].id).to.eq(copiedAction.id);+ });+ });+ });+ });++ it("refuses to sync when a copied model was moved out of the app collection", () => {+ syncOneAction().then(({ copiedModel }) => {+ cy.request("POST", "/api/collection", { name: "Elsewhere" }).then(+ ({ body: collection }) => {+ cy.request("PUT", `/api/card/${copiedModel.id}`, {+ collection_id: collection.id,+ });++ syncExpectingRefusal(`Move card ${copiedModel.id} back to`);+ // Refusing is only worth anything if the card is left alone.+ cy.request(`/api/card/${copiedModel.id}`)+ .its("body.collection_id")+ .should("eq", collection.id);+ },+ );+ });+ });++ it("refuses to sync when a copied model was converted to a question", () => {+ syncOneAction().then(({ copiedModel }) => {+ cy.request("PUT", `/api/card/${copiedModel.id}`, {+ type: "question",+ });++ syncExpectingRefusal("is no longer a model");+ });+ });++ // Converting the parent model to a question deletes its implicit actions+ // and archives the rest (see `card.clj`), so the source becomes unreadable+ // rather than readable-with-a-non-model-parent.+ it("copies nothing when the source model was converted to a question", () => {+ declareOneAction().then(({ modelId, action }) => {+ cy.request("PUT", `/api/card/${modelId}`, { type: "question" });++ syncExpectingRefusal(`Could not read action ${action.id}`);+ copiedModels().should("have.length", 0);+ });+ });++ it("refuses to update a copied action that now belongs to another model", () => {+ syncOneAction().then(({ modelId, copiedAction }) => {+ // Still declared, but repointed at a model the app does not own:+ // replacing it would abandon an action nothing tracks.+ cy.request("PUT", `/api/action/${copiedAction.id}`, {+ model_id: modelId,+ });++ syncExpectingRefusal(+ `Action ${copiedAction.id} is the copy of action`,+ );+ cy.request(`/api/action/${copiedAction.id}`)+ .its("body.model_id")+ .should("eq", modelId);+ });+ });++ it("refuses to delete a copied action that now belongs to another model", () => {+ cy.get<number>("@modelId").then((modelId) => {+ H.createImplicitAction({ model_id: modelId, kind: "create" }).then(+ ({ body: create }) => {+ H.createImplicitAction({+ model_id: modelId,+ kind: "update",+ }).then(({ body: update }) => {+ declareDataAppActions(APP_ROOT(), [create.id, update.id]);+ sync();++ copiedModels().then(([copiedModel]) => {+ actionsOnModel(copiedModel.id).then((actions) => {+ const copyOfUpdate = actions.find(+ (candidate: { name: string }) =>+ candidate.name === "Update",+ );++ // Repointed at the source model, which the app does not+ // own — deleting it would destroy someone else's action.+ cy.request("PUT", `/api/action/${copyOfUpdate.id}`, {+ model_id: modelId,+ });+ removeDataAppActionDeclaration(APP_ROOT(), update.id);++ syncExpectingRefusal(+ `no longer hangs off copied model ${copiedModel.id}`,+ );+ cy.request(`/api/action/${copyOfUpdate.id}`)+ .its("status")+ .should("eq", 200);+ });+ });+ });+ },+ );+ });+ });++ it("does not copy models that are based on saved questions", () => {+ declareOneAction();++ cy.log("create a saved question");+ cy.get<number>("@modelId")+ .then((modelId) => cy.request<Card>(`/api/card/${modelId}`))+ .then(({ body: model }) =>+ cy.request<Card>("POST", "/api/card", {+ name: "Scoreboard source question",+ display: "table",+ visualization_settings: {},+ dataset_query: model.dataset_query,+ }),+ )+ .its("body.id")+ .as("sourceQuestionId");++ cy.log("change the model to use that saved question as its source");+ cy.get<number>("@sourceQuestionId").then((sourceQuestionId) => {+ cy.get<number>("@modelId").then((modelId) => {+ cy.request("PUT", `/api/card/${modelId}`, {+ dataset_query: {+ database: WRITABLE_DB_ID,+ type: "query",+ query: { "source-table": `card__${sourceQuestionId}` },+ },+ });+ });+ });++ cy.request("/api/action").its("body").as("actionsBeforeSync");++ syncExpectingRefusal(+ "depends on saved questions and cannot be synchronized",+ );++ cy.log("sync should not copy models that are based on saved questions");+ copiedModels().should("have.length", 0);++ cy.get("@actionsBeforeSync").then((actions) => {+ cy.request("/api/action").its("body").should("deep.equal", actions);+ });+ });+ });+ },+);diff --git a/e2e/test-host-app/data-apps/sync-resources.cy.spec.ts b/e2e/test-host-app/data-apps/sync-resources.cy.spec.tsnew file mode 100644index 00000000000..c7cf5639ff8--- /dev/null+++ b/e2e/test-host-app/data-apps/sync-resources.cy.spec.ts@@ -0,0 +1,722 @@+import { USERS, USER_GROUPS } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ addUserToGroup,+ buildDataAppHostApp,+ createDataAppApiKey,+ createSecondDataApp,+ dataAppHostAppRoot,+ dataAppPermissionGroupId,+ declareDataAppQueries,+ removeDataAppQueryDeclaration,+ resetDataAppHostAppSources,+ setDataAppCollectionAccess,+ syncDataAppResources,+} from "e2e/support/helpers";+import type { Card, DataApp } from "metabase-types/api";++const { H } = cy;+const { ORDERS_ID } = SAMPLE_DATABASE;++/** `syncResources` takes the app's slug from its directory name. */+const APP_SLUG = "vite-6-data-app-host-app";++/** The fields these specs read off a card the app collection holds. */+type AppCard = { id: number; name: string; collection_id: number | null };++const APP_ROOT = () => dataAppHostAppRoot();+const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;+const QUERIES_FILE = () => `${APP_ROOT()}/queries/orders.query.ts`;+const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;++const AUTHORED_MANIFEST = `name: Vite 6 Data App+path: ./dist/index.js+allowed_hosts:+ - https://allowed.data-app.test+`;++/**+ * The query half of `sync-resources`, run against the dev host app: a real vite+ * data app with the published SDK installed, so `defineQuery` resolves through+ * the package an author actually consumes rather than a stub.+ */+describe("Embedding SDK: data-app sync-resources (queries)", () => {+ const resetHostAppSources = () => {+ resetDataAppHostAppSources();+ cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);+ };++ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ // The query and actions specs share a checked-in host app, so start clean.+ resetHostAppSources();+ createDataAppApiKey().as("apiKey");+ });++ after(() => {+ resetHostAppSources();+ });++ const sync = () =>+ cy.get<string>("@apiKey").then((apiKey) => {+ syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {+ expect(error, "sync-resources failed").to.eq(null);+ expect(ok).to.eq(true);+ });+ });++ const syncExpectingRefusal = (message: string) =>+ cy.get<string>("@apiKey").then((apiKey) => {+ syncDataAppResources(apiKey, APP_ROOT()).should(({ ok, error }) => {+ expect(ok, "sync-resources should have refused").to.eq(false);+ expect(error).to.contain(message);+ });+ });++ /** The saved questions Metabase holds in the app's own collection. */+ const savedQuestions = () =>+ cy.request<DataApp>(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {+ expect(app.resource_collection_id, "resource collection").to.be.a(+ "number",+ );+ return cy+ .request<{+ data: AppCard[];+ }>(`/api/collection/${app.resource_collection_id}/items?models=card`)+ .then(({ body }) => body.data);+ });++ /** Declares one query and syncs it, handing back the card Metabase created. */+ const syncOneQuery = () => {+ declareDataAppQueries(APP_ROOT(), [{ name: "Orders", tableId: ORDERS_ID }]);+ sync();+ return savedQuestions().then(([card]) => cy.wrap(card, { log: false }));+ };++ it("names the definition whose query Metabase could not resolve", () => {+ declareDataAppQueries(APP_ROOT(), [{ name: "Orders", tableId: 999999 }]);++ syncExpectingRefusal("Could not resolve queries/orders.query.ts:Orders");++ savedQuestions().should("have.length", 0);+ });++ it("creates the saved question, writes its ID back, and re-syncs without changes", () => {+ declareDataAppQueries(APP_ROOT(), [+ { name: "Orders", tableId: ORDERS_ID, limit: 5 },+ ]);++ sync();++ savedQuestions().then((cards) => {+ expect(cards).to.have.length(1);++ cy.readFile(QUERIES_FILE()).should(+ "contain",+ `savedQuestionSourceId: ${cards[0].id}`,+ );+ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.queries).to.have.length(1);+ expect(lockfile.queries[0].savedQuestionSourceId).to.eq(cards[0].id);+ });++ sync();+ savedQuestions().then((after) => {+ expect(after).to.have.length(1);+ expect(after[0].id).to.eq(cards[0].id);+ });+ });+ });++ it("deletes the saved question when its declaration is removed", () => {+ syncOneQuery().then(() => {+ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");+ sync();++ savedQuestions().should("have.length", 0);+ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.queries).to.have.length(0);+ });+ });+ });++ // Removing a declaration deletes the copy and its lockfile entry, but the ID the+ // sync wrote into the source stays in source control. Bringing the declaration+ // back has to make a fresh copy: there is no card left to adopt.+ it("re-creates the copy when a removed declaration comes back naming the deleted card", () => {+ syncOneQuery().then((card) => {+ cy.readFile(QUERIES_FILE()).then((authored: string) => {+ expect(+ authored,+ "the sync wrote the copy's ID into the source",+ ).to.contain(`savedQuestionSourceId: ${card.id}`);++ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");+ sync();+ savedQuestions().should("have.length", 0);++ // Exactly what restoring the file from source control brings back.+ cy.writeFile(QUERIES_FILE(), authored);+ sync();++ savedQuestions().then((recreated) => {+ expect(recreated).to.have.length(1);+ expect(+ recreated[0].id,+ "the deleted card is not resurrected",+ ).not.to.eq(card.id);+ cy.readFile(QUERIES_FILE())+ .should("contain", `savedQuestionSourceId: ${recreated[0].id}`)+ .should("not.contain", `savedQuestionSourceId: ${card.id}`);+ });+ });+ });+ });++ it("names the trash when a restored declaration points at a trashed copy", () => {+ syncOneQuery().then((card) => {+ cy.readFile(QUERIES_FILE()).then((authored: string) => {+ cy.request("PUT", `/api/card/${card.id}`, { archived: true });++ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");+ sync();+ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.queries, "the entry is dropped").to.have.length(0);+ });++ cy.writeFile(QUERIES_FILE(), authored);+ syncExpectingRefusal(`card ${card.id}, which is in the trash`);+ });+ });+ });++ it("restores a hand-edited card's name instead of replacing the card", () => {+ syncOneQuery().then((card) => {+ cy.request("PUT", `/api/card/${card.id}`, { name: "Renamed by hand" });++ sync();++ savedQuestions().then((cards) => {+ expect(cards, "the card is updated in place").to.have.length(1);+ expect(cards[0].id).to.eq(card.id);+ expect(cards[0].name).to.eq("Orders");+ });+ });+ });++ it("brings back a saved question that was trashed on its own", () => {+ syncOneQuery().then((card) => {+ cy.request("PUT", `/api/card/${card.id}`, { archived: true });++ sync();++ cy.request(`/api/card/${card.id}`).then(({ body: restored }) => {+ expect(restored.archived, "the copy is out of the trash").to.eq(false);+ expect(restored.collection_id).to.eq(card.collection_id);+ });+ });+ });++ describe("trashed metric copies", () => {+ beforeEach(() => {+ H.createQuestion({+ name: "Count of orders",+ type: "metric",+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },+ display: "scalar",+ })+ .its("body.id")+ .as("sourceMetricId");++ cy.log("define a query that uses metrics");+ cy.get<number>("@sourceMetricId").then((id) => {+ cy.writeFile(+ QUERIES_FILE(),+ [+ 'import { defineQuery } from "@metabase/embedding-sdk-react/data-app";',++ "export const OrdersCount = defineQuery({",+ ` source: { type: "table", id: ${ORDERS_ID} },`,+ ` aggregations: [{ type: "metric", id: ${id}, sourceTableId: ${ORDERS_ID} }],`,+ "});",+ ].join("\n"),+ );+ });++ sync();++ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.metrics).to.have.length(1);+ expect(lockfile.queries).to.have.length(1);++ cy.wrap(lockfile.metrics[0].copiedMetricId).as("copiedMetricId");+ cy.wrap(lockfile.queries[0].savedQuestionSourceId).as("questionId");+ });++ cy.log("archive the copied metric");+ cy.get<number>("@copiedMetricId").then((id) => {+ cy.request<Card>(`/api/card/${id}`).its("body").as("metricCopy");++ H.archiveQuestion(id);+ });++ cy.get<Card>("@metricCopy").then((copy) => {+ cy.log("the copied metric is archived");++ cy.request<Card>(`/api/card/${copy.id}`).should(({ body }) => {+ expect(body.archived).to.eq(true);+ expect(body.collection_id).not.to.eq(copy.collection_id);+ });+ });+ });++ it("restores a trashed metric copy after sync", () => {+ sync();++ cy.get<Card>("@metricCopy").then((copy) => {+ cy.log("the archived metric should no longer be archived after sync");++ cy.request<Card>(`/api/card/${copy.id}`).should(({ body }) => {+ expect(body.archived).to.eq(false);+ expect(body.collection_id).to.eq(copy.collection_id);+ });++ cy.log("the copied metric in the lockfile remains the same");+ cy.readFile(LOCKFILE())+ .its("metrics.0.copiedMetricId")+ .should("eq", copy.id);+ });++ cy.get<number>("@questionId").then((id) => H.visitQuestion(id));++ H.assertQueryBuilderRowCount(1);+ });++ it("leaves a trashed metric copy in trash after its source is removed", () => {+ H.removeDataAppQueryDeclaration(APP_ROOT(), "OrdersCount");++ sync();++ cy.get<number>("@copiedMetricId").then((id) => {+ cy.log("the copied metric should remain archived after sync");+ cy.request<Card>(`/api/card/${id}`)+ .its("body.archived")+ .should("eq", true);+ });++ cy.readFile(LOCKFILE()).should((lockfile) => {+ expect(lockfile.metrics).to.deep.eq([]);+ expect(lockfile.queries).to.deep.eq([]);+ });++ cy.get<number>("@sourceMetricId").then((id) => {+ cy.log("the source metric should not be archived");+ cy.request<Card>(`/api/card/${id}`)+ .its("body.archived")+ .should("eq", false);+ });+ });+ });++ it("recreates the saved question after it is deleted in Metabase", () => {+ syncOneQuery().then((card) => {+ cy.request("DELETE", `/api/card/${card.id}`);++ sync();++ savedQuestions().then((cards) => {+ expect(cards).to.have.length(1);+ expect(cards[0].id).not.to.eq(card.id);+ });+ cy.readFile(QUERIES_FILE()).should("not.contain", `Id: ${card.id}`);+ });+ });++ it("restores savedQuestionSourceId from the lockfile when the source loses it", () => {+ syncOneQuery().then((card) => {+ // Rewriting the declaration drops the injected ID, as a bad merge would.+ declareDataAppQueries(APP_ROOT(), [+ { name: "Orders", tableId: ORDERS_ID },+ ]);++ sync();++ savedQuestions().then((cards) => {+ expect(cards, "the card is reused, not replaced").to.have.length(1);+ expect(cards[0].id).to.eq(card.id);+ });+ cy.readFile(QUERIES_FILE()).should(+ "contain",+ `savedQuestionSourceId: ${card.id}`,+ );+ });+ });++ it("rebuilds a missing lockfile entry from the ID left in the source", () => {+ syncOneQuery().then((card) => {+ cy.writeFile(LOCKFILE(), { queries: [], models: [] });++ sync();++ // The inline ID proves ownership, so the entry is rebuilt.+ savedQuestions().then((cards) => {+ expect(cards).to.have.length(1);+ expect(cards[0].id).to.eq(card.id);+ });+ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.queries).to.have.length(1);+ expect(lockfile.queries[0].savedQuestionSourceId).to.eq(card.id);+ });+ });+ });++ // A card in the trash reports the Trash as its collection, so one moved out+ // and trashed afterwards is indistinguishable from the app's own. Deleting is+ // permanent, so neither is deleted.+ it("leaves a trashed card in the trash when its declaration is removed", () => {+ syncOneQuery().then((card) => {+ cy.request("PUT", `/api/card/${card.id}`, { archived: true });+ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");++ sync();++ cy.request(`/api/card/${card.id}`)+ .its("body.archived")+ .should("eq", true);+ cy.readFile(LOCKFILE()).then((lockfile) => {+ expect(lockfile.queries, "no longer tracked").to.have.length(0);+ });+ });+ });++ it("refuses to delete a card that was moved out of the app collection", () => {+ syncOneQuery().then((card) => {+ cy.request("POST", "/api/collection", { name: "Elsewhere" }).then(+ ({ body: collection }) => {+ cy.request("PUT", `/api/card/${card.id}`, {+ collection_id: collection.id,+ });+ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");++ syncExpectingRefusal(`Move card ${card.id} back to`);+ cy.request(`/api/card/${card.id}`)+ .its("body.collection_id")+ .should("eq", collection.id);+ },+ );+ });+ });++ // Trashing the collection archives everything in it, and the app is served+ // from those copies, so a sync that reports success has not actually recovered.+ it("brings the app collection and its copies back out of the trash", () => {+ syncOneQuery().then((card) => {+ cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {+ cy.request("PUT", `/api/collection/${app.resource_collection_id}`, {+ archived: true,+ });+ cy.request(`/api/card/${card.id}`)+ .its("body.archived")+ .should("eq", true);++ sync();++ cy.request(`/api/collection/${app.resource_collection_id}`)+ .its("body.archived")+ .should("eq", false);+ cy.request(`/api/card/${card.id}`)+ .its("body.archived")+ .should("eq", false);+ });+ });+ });++ describe("the app's lifecycle", () => {+ it("takes the collection and the group with it when the app is removed", () => {+ syncOneQuery().then((card) => {+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {+ cy.request("DELETE", `/api/apps/${APP_SLUG}`);++ // Nothing is left for a former viewer to reach.+ cy.request({+ url: `/api/collection/${app.resource_collection_id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 404);+ cy.request({+ url: `/api/permissions/group/${groupId}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 404);+ cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 404);+ });+ });+ });+ });++ // Everything the CLI drives is superuser-gated, starting with the draft it+ // asks for first, so a key that is not an admin's gets nowhere.+ it("refuses to synchronize at all for a key that is not an admin's", () => {+ declareDataAppQueries(APP_ROOT(), [+ { name: "Orders", tableId: ORDERS_ID },+ ]);++ cy.request("POST", "/api/api-key", {+ name: `data-app-sync-e2e-non-admin-${Date.now()}`,+ group_id: USER_GROUPS.COLLECTION_GROUP,+ }).then(({ body: key }) => {+ syncDataAppResources(key.unmasked_key, APP_ROOT()).should(+ ({ ok, error }) => {+ expect(ok, "sync-resources should have refused").to.eq(false);+ expect(error).to.contain("403");+ expect(error, "refused at the first call it makes").to.contain(+ `/api/apps/${APP_SLUG}/draft`,+ );+ },+ );++ // The draft call is the one that creates the app, so a refusal leaves+ // nothing behind at all — not even the app to hold copies.+ cy.request({ url: `/api/apps/${APP_SLUG}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 404);+ });+ });+ });++ describe("two apps on one instance", () => {+ const OTHER_SLUG = "sync-resources-second-app";++ it("keeps each app's copies in its own collection, reachable only by its own group", () => {+ const otherRoot = createSecondDataApp(OTHER_SLUG);++ syncOneQuery().then((card) => {+ declareDataAppQueries(otherRoot, [+ { name: "OtherOrders", tableId: ORDERS_ID },+ ]);+ cy.get<string>("@apiKey").then((apiKey) => {+ syncDataAppResources(apiKey, otherRoot).then(({ error }) => {+ expect(error, "second app sync failed").to.eq(null);+ });+ });++ cy.request(`/api/apps/${OTHER_SLUG}`).then(({ body: otherApp }) => {+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ expect(+ otherApp.resource_collection_id,+ "each app gets its own collection",+ ).not.to.eq(null);+ expect(otherApp.permission_group_id).not.to.eq(groupId);++ // Joining one app's group must not reach the other app's copy.+ addUserToGroup(groupId, USERS.normal.email);++ cy.request(+ `/api/collection/${otherApp.resource_collection_id}/items?models=card`,+ ).then(({ body }) => {+ const otherCard = body.data[0];+ expect(otherCard.id, "the apps hold different cards").not.to.eq(+ card.id,+ );++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`)+ .its("body.id")+ .should("eq", card.id);+ cy.request({+ url: `/api/card/${otherCard.id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ });+ });+ });+ });+ });+ });++ describe("the build guard", () => {+ /** `cy.exec` reports the command's output; vite prints this only on success. */+ const expectBuildToSucceed = () =>+ buildDataAppHostApp().should((result) => {+ expect(`${result.stdout}${result.stderr}`).to.contain("built in");+ });++ // `metabase-resource-sync-check` runs on buildStart, so a stale app is+ // refused before it can be bundled and served.+ it("refuses to build when the source and the lockfile disagree", () => {+ syncOneQuery().then(() => {+ expectBuildToSucceed();++ // A hand-edited declaration no longer matches its lockfile entry.+ declareDataAppQueries(APP_ROOT(), [+ { name: "Orders", tableId: ORDERS_ID, limit: 3 },+ ]);++ buildDataAppHostApp().should((result) => {+ const output = `${result.stdout}${result.stderr}`;+ expect(output, "the build is refused").to.contain(+ "is not synchronized",+ );+ expect(output).not.to.contain("built in");+ });++ // Synchronizing makes it buildable again.+ sync();+ expectBuildToSucceed();+ });+ });+ });++ describe("permissions", () => {+ /** Puts the normal user in the app's group, as granting app access does. */+ const joinAppGroup = () =>+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ addUserToGroup(groupId, USERS.normal.email);+ return cy.wrap(groupId, { log: false });+ });++ it("does not let a viewer modify the copy it can read", () => {+ syncOneQuery().then((card) => {+ joinAppGroup();++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`).its("body.id").should("eq", card.id);++ // The grant is collection read, never readwrite.+ cy.request({+ method: "PUT",+ url: `/api/card/${card.id}`,+ body: { name: "Renamed by a viewer" },+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ cy.request({+ method: "DELETE",+ url: `/api/card/${card.id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ });+ });++ // The app collection is server-owned, so each sync reasserts exclusive+ // access — including over a grant an admin made deliberately.+ it("takes back access an admin granted another group on the app collection", () => {+ syncOneQuery().then((card) => {+ cy.request(`/api/apps/${APP_SLUG}`).then(({ body: app }) => {+ setDataAppCollectionAccess(app.resource_collection_id, "read");++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`)+ .its("body.id")+ .should("eq", card.id);++ cy.signInAsAdmin();+ sync();++ cy.signInAsNormalUser();+ cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 403);+ });+ });+ });++ it("grants the group nothing beyond the app's own collection", () => {+ cy.request("POST", "/api/collection", { name: "Private" }).then(+ ({ body: collection }) => {+ // The normal user belongs to groups that can read new collections, so+ // close this one: the claim under test is that joining the app group+ // grants the app's collection and nothing else.+ setDataAppCollectionAccess(collection.id, "none");++ H.createQuestion({+ name: "Private question",+ query: { "source-table": ORDERS_ID },+ collection_id: collection.id,+ }).then(({ body: unrelated }) => {+ syncOneQuery().then((card) => {+ joinAppGroup();++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`)+ .its("body.id")+ .should("eq", card.id);+ cy.request({+ url: `/api/card/${unrelated.id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ });+ });+ },+ );+ });++ it("leaves the group with nothing once the declaration is removed", () => {+ syncOneQuery().then((card) => {+ joinAppGroup();++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`).its("body.id").should("eq", card.id);++ cy.signInAsAdmin();+ removeDataAppQueryDeclaration(APP_ROOT(), "Orders");+ sync();++ // The copy is deleted with its declaration, so there is nothing left to+ // read — the group's collection grant now covers an empty collection.+ cy.signInAsNormalUser();+ cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 404);+ });+ });++ // The copy exists so an app's viewers can read it: they are given the app's+ // own group, which holds read on the app's collection and nothing else.+ it("lets the app's group read the copy while the rest of the instance cannot", () => {+ syncOneQuery().then((card) => {+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ cy.signInAsNormalUser();+ cy.request({ url: `/api/card/${card.id}`, failOnStatusCode: false })+ .its("status")+ .should("eq", 403);++ cy.signInAsAdmin();+ addUserToGroup(groupId, USERS.normal.email);++ cy.signInAsNormalUser();+ cy.request(`/api/card/${card.id}`)+ .its("body.id")+ .should("eq", card.id);+ });+ });+ });++ // `read-check-data-app` 403s a non-member, and the app view turns that status+ // into its own empty state instead of loading the bundle.+ it("tells a viewer outside the group that the app is not theirs to open", () => {+ syncOneQuery().then(() => {+ cy.signInAsNormalUser();+ cy.visit(`/apps/${APP_SLUG}`);++ cy.findByText("You don’t have access to this data app").should("exist");+ cy.get("iframe").should("not.exist");+ });+ });+ });+});diff --git a/e2e/test/scenarios/admin-2/people.cy.spec.js b/e2e/test/scenarios/admin-2/people.cy.spec.jsindex 07ffd307d39..6f808644c8f 100644--- a/e2e/test/scenarios/admin-2/people.cy.spec.js+++ b/e2e/test/scenarios/admin-2/people.cy.spec.js@@ -27,7 +27,8 @@ const normalUserName = H.getFullName(normal);describe("scenarios > admin > people", () => {beforeEach(() => {- cy.intercept("GET", "/api/permissions/group").as("getGroups");+ // `*` matches the `?tenancy=…` variants (People tab, user modals), not just the param-less Groups-tab request.+ cy.intercept("GET", "/api/permissions/group*").as("getGroups");cy.intercept("GET", "/api/api-key").as("listApiKeys");H.restore();cy.signInAsAdmin();diff --git a/e2e/test/scenarios/data-apps/actions.cy.spec.ts b/e2e/test/scenarios/data-apps/actions.cy.spec.tsindex d7af613db87..802ce98225f 100644--- a/e2e/test/scenarios/data-apps/actions.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/actions.cy.spec.ts@@ -2,8 +2,10 @@ import { WRITABLE_DB_ID } from "e2e/support/cypress_data";import {DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,DATA_APP_NAME as APP_NAME,+ moveDataAppModelToCollection,visitDataAppRoute as visitAppRoute,} from "e2e/support/helpers";+import type { CollectionPermission } from "metabase-types/api";import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";@@ -12,6 +14,7 @@ const { H } = cy;const TEST_TABLE = "scoreboard_actions";const MODEL_NAME = "Scoreboard model";const EXISTING_TEAM = "Amorous Aardvarks";+const RESOURCE_COLLECTION = "Data App resources";describe("scenarios > data apps > actions (useAction)",@@ -32,7 +35,7 @@ describe(});const setupActionsApp = (actionParams: Record<string, string | number>) =>- cy.get("@modelId").then((modelId) => {+ cy.get<number>("@modelId").then((modelId) => {H.createImplicitAction({model_id: modelId,kind: "create",@@ -46,7 +49,9 @@ describe(it("executes the action, exposing isExecuting and result, and resets", () => {cy.intercept("POST", "/api/action/*/execute", (req) => {- req.on("response", (res) => res.setDelay(300));+ req.on("response", (res) => {+ res.setDelay(300);+ });});setupActionsApp({ team_name: "Data App FC", score: 7 });@@ -99,5 +104,78 @@ describe(expect(rows).to.have.length(1);});});++ describe("collection permissions", () => {+ const setupRestrictedApp = (access: CollectionPermission) =>+ cy.get<number>("@modelId").then((modelId) => {+ moveDataAppModelToCollection({+ modelId,+ name: RESOURCE_COLLECTION,+ access,+ });++ H.createImplicitAction({+ model_id: modelId,+ kind: "create",+ }).then(({ body: action }) => {+ H.mockDataApp(APP_NAME, {+ displayName: APP_DISPLAY_NAME,+ testEnv: {+ ...TEST_ENV,+ actionId: action.id,+ actionParams: { team_name: "Data App FC", score: 7 },+ },+ });+ });+ });++ const assertNothingWritten = () =>+ H.queryWritableDB(+ `SELECT team_name FROM ${TEST_TABLE} WHERE team_name = 'Data App FC'`,+ ).then(({ rows }) => {+ expect(rows).to.have.length(0);+ });++ it("refuses the action when the user cannot read its collection", () => {+ setupRestrictedApp("none");+ cy.signInAsNormalUser();++ visitAppRoute("actions");+ 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");+ });++ assertNothingWritten();+ });++ it("executes the action when the user has view access to its collection", () => {+ setupRestrictedApp("read");+ 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/admin.cy.spec.ts b/e2e/test/scenarios/data-apps/admin.cy.spec.tsindex 616263583c2..625f35c5447 100644--- a/e2e/test/scenarios/data-apps/admin.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/admin.cy.spec.ts@@ -51,6 +51,25 @@ describe("scenarios > data apps > admin management", () => {});});+ it("keeps a data app's permission group out of the admin Groups list", () => {+ // Provisioning a data app draft creates its permission group as a side effect.+ cy.request("POST", "/api/apps/orders-app/draft").then(({ body }) => {+ const dataAppGroupId = body.permission_group_id;++ // The groups API does not return data-app groups.+ cy.request("GET", "/api/permissions/group").then(({ body: groups }) => {+ const ids = groups.map((group: { id: number }) => group.id);+ expect(ids).not.to.include(dataAppGroupId);+ });++ cy.visit("/admin/people/groups");+ cy.findByTestId("admin-panel").within(() => {+ cy.findByText("All Users").should("be.visible");+ cy.findByText("Data App: orders-app").should("not.exist");+ });+ });+ });+it("dismisses the promo banner and keeps it hidden across a reload", () => {cy.intercept("GET", "/api/apps/repo-status", { configured: true });cy.intercept("GET", "/api/apps", []);diff --git a/e2e/test/scenarios/data-apps/helpers/index.ts b/e2e/test/scenarios/data-apps/helpers/index.tsindex 2bdafcf50ae..687ecbd6dad 100644--- a/e2e/test/scenarios/data-apps/helpers/index.ts+++ b/e2e/test/scenarios/data-apps/helpers/index.ts@@ -1,9 +1,8 @@-import type {- LocalFieldReference,- QuestionColumnReference,-} from "@metabase/embedding-sdk-react/data-app";-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ ORDERS_COUNT_QUESTION_ID,+ ORDERS_QUESTION_ID,+} from "e2e/support/cypress_sample_instance_data";import type { DataAppTestEnv } from "e2e/support/helpers";// These live here (co-located with the specs) rather than in@@ -14,41 +13,21 @@ import type { DataAppTestEnv } from "e2e/support/helpers";const { ORDERS_ID } = SAMPLE_DATABASE;-/**- * A numeric field dimension for the query-builder combinators, hand-built the way- * an app without a generated `metabase.data.ts` schema would build one.- */-export const dataAppNumericField = (- fieldId: number,- name: string,-): LocalFieldReference => ({- type: "column",- fieldId,- tableId: ORDERS_ID,- name,- jsType: "number",-});+const source = { type: "table" as const, id: ORDERS_ID };/**- * The same dimension as it is addressed on a saved-question source: a card stage- * exposes the question's result columns, which are matched by name and carry no- * table-scoped identity.+ * The `testEnv` the fixture's Overview page reads (Orders count + question).+ *+ * Both carry a `savedQuestionSourceId`, because a deployed app runs the card its+ * query was published as — a bare table source is refused. Each id names a+ * snapshot question equivalent to the authored query, since the swap drops the+ * static clauses the card already contains.*/-export const dataAppNumericResultColumn = (- name: string,-): QuestionColumnReference => ({- type: "column",- name,- jsType: "number",-});--const source = { type: "table" as const, id: ORDERS_ID };--/** The `testEnv` the fixture's Overview page reads (Orders count + question). */export const DATA_APP_TEST_ENV: DataAppTestEnv = {scalarQuery: {source,aggregations: [{ type: "operator", operator: "count", args: [] }],+ savedQuestionSourceId: ORDERS_COUNT_QUESTION_ID,},- questionQuery: { source },+ questionQuery: { source, savedQuestionSourceId: ORDERS_QUESTION_ID },};diff --git a/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts b/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.tsnew file mode 100644index 00000000000..6820200faef--- /dev/null+++ b/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts@@ -0,0 +1,155 @@+import { SAMPLE_DB_ID, USERS } 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 DataApp,+ DataPermission,+ DataPermissionValue,+ type FieldsPermissions,+ type SchemasPermissions,+ type Table,+} from "metabase-types/api";++const { H } = cy;+const { ORDERS_ID } = SAMPLE_DATABASE;++const APP_NAME = "legacy-permission-test";++// Exercise real queries: preserving the permission graph alone does not prove that data still loads.+describe("scenarios > data apps > legacy view data permissions", () => {+ describe("preserves 'no self-service' access level when a user is added to data app group", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ // TODO(GHY-4493) Direct saved questions currently reject legacy access after backend hardening+ // In the meantime, use a saved SQL source to test app membership separately from the regression.+ H.createNativeQuestion({+ name: "Orders SQL source",+ database: SAMPLE_DB_ID,+ native: { query: "SELECT COUNT(*) AS total FROM ORDERS" },+ collection_id: null,+ })+ .its("body.id")+ .as("sourceQuestionId");++ cy.get<number>("@sourceQuestionId")+ .then((sourceQuestionId) =>+ H.createQuestion({+ name: "Orders with legacy access",+ database: SAMPLE_DB_ID,+ query: { "source-table": `card__${sourceQuestionId}` },+ display: "scalar",+ collection_id: null,+ }),+ )+ .its("body.id")+ .as("questionId");++ setViewDataPermissions(DataPermissionValue.BLOCKED);++ cy.signIn("nodata");+ H.visitQuestion("@questionId");+ H.main()+ .findByText("Sorry, you don't have permission to run this query.")+ .should("be.visible");+ cy.findByTestId("scalar-value").should("not.exist");++ cy.signInAsAdmin();+ });++ it("with all tables using no self-service", () => {+ // every table is no self-service+ setViewDataPermissions(DataPermissionValue.LEGACY_NO_SELF_SERVICE);++ assertAccessSurvivesAppMembership();+ });++ it("with some tables being unrestricted", () => {+ // Clear the database block, including tables omitted from query metadata.+ setViewDataPermissions(DataPermissionValue.LEGACY_NO_SELF_SERVICE);++ cy.request<{ tables: Table[] }>(+ "GET",+ `/api/database/${SAMPLE_DB_ID}/metadata`,+ ).then(({ body: { tables } }) => {+ const permissions: Record<+ string,+ Record<number, FieldsPermissions>+ > = {};++ // orders table is no self-service, other tables are unrestricted+ for (const table of tables) {+ const schema = table.schema ?? "";+ permissions[schema] ??= {};++ permissions[schema][Number(table.id)] =+ table.id === ORDERS_ID+ ? DataPermissionValue.LEGACY_NO_SELF_SERVICE+ : DataPermissionValue.UNRESTRICTED;+ }++ setViewDataPermissions(permissions);+ });++ assertAccessSurvivesAppMembership();+ });+ });+});++function assertAccessSurvivesAppMembership() {+ cy.log("legacy access should let the no data user load the saved question");+ cy.signIn("nodata");+ H.visitQuestion("@questionId");++ cy.findByTestId("scalar-value", { timeout: 20_000 }).should(+ "have.text",+ "18,760",+ );++ cy.signInAsAdmin();+ cy.request<DataApp>("POST", `/api/apps/${APP_NAME}/draft`)+ .its("body")+ .as("app");++ cy.log("assign the no data user to the data app group");+ cy.get<DataApp>("@app").then(({ permission_group_id }) => {+ if (permission_group_id === null) {+ throw new Error("data app must have a permission group");+ }++ H.addUserToGroup(permission_group_id, USERS.nodata.email);+ });++ cy.log("the same saved question must still load after app membership");+ cy.signIn("nodata");+ H.visitQuestion("@questionId");++ cy.findByTestId("scalar-value", { timeout: 20_000 }).should(+ "have.text",+ "18,760",+ );+}++function setViewDataPermissions(viewData: SchemasPermissions) {+ // The no-data user belongs to both groups. Neither should override the legacy grant.+ cy.updatePermissionsGraph({+ [ALL_USERS_GROUP_ID]: {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: viewData,+ [DataPermission.CREATE_QUERIES]: DataPermissionValue.NO,+ },+ },++ [COLLECTION_GROUP_ID]: {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: viewData,+ [DataPermission.CREATE_QUERIES]: DataPermissionValue.NO,+ },+ },+ });+}diff --git a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts b/e2e/test/scenarios/data-apps/sdk.cy.spec.tsindex 66c20809f59..92ed89be735 100644--- a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts@@ -6,13 +6,9 @@ import {visitDataAppRoute as visitAppRoute,} from "e2e/support/helpers";-import {- DATA_APP_TEST_ENV as TEST_ENV,- dataAppNumericField as numericField,- dataAppNumericResultColumn as resultColumn,-} from "./helpers";+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";-const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;+const { ORDERS_ID } = SAMPLE_DATABASE;const { H } = cy;@@ -30,8 +26,12 @@ describe("scenarios > data apps > SDK runtime", () => {displayName: APP_DISPLAY_NAME,testEnv: {...TEST_ENV,- // A table id that doesn't exist → the query resolves to an error.- errorQuery: { source: { type: "table", id: 999999 } },+ // A card that doesn't exist → the query resolves to an error, rather+ // than to the refusal an unsynchronized table source would raise.+ errorQuery: {+ source: { type: "table", id: ORDERS_ID },+ savedQuestionSourceId: 999999,+ },},});@@ -105,90 +105,6 @@ describe("scenarios > data apps > SDK runtime", () => {);});});-- it("builds a query with filter/breakout/orderBy/aggregations helpers", () => {- H.mockDataApp(APP_NAME, {- displayName: APP_DISPLAY_NAME,- testEnv: {- ...TEST_ENV,- combinators: {- source: { type: "table", id: ORDERS_ID },- filterField: numericField(ORDERS.TOTAL, "TOTAL"),- filterValue: 50,- breakoutField: numericField(ORDERS.PRODUCT_ID, "PRODUCT_ID"),- },- },- });-- visitAppRoute("combinators");- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("combinators-loading", { timeout: 30000 }).should(- "have.text",- "done",- );- cy.findByTestId("combinators-error").should("have.text", "no-error");- // `.should(callback)` retries until the query resolves with rows.- cy.findByTestId("combinators-rowcount", { timeout: 30000 }).should(- ($el) => {- expect(Number($el.text())).to.be.greaterThan(0);- },- );- });- });- });-- describe("saved question sources", () => {- const setupCardSourceApp = () =>- H.createQuestion({- name: "Orders as a data-app query source",- query: { "source-table": ORDERS_ID },- }).then(({ body: card }) => {- H.mockDataApp(APP_NAME, {- displayName: APP_DISPLAY_NAME,- testEnv: {- ...TEST_ENV,- cardSource: {- source: { type: "card", id: card.id },- tableSource: { type: "table", id: ORDERS_ID },- filterField: numericField(ORDERS.TOTAL, "TOTAL"),- filterColumn: resultColumn("TOTAL"),- filterValue: 50,- breakoutField: numericField(ORDERS.PRODUCT_ID, "PRODUCT_ID"),- breakoutColumn: resultColumn("PRODUCT_ID"),- },- },- });-- visitAppRoute("card-source");- });-- it("queries a saved question as a source", () => {- setupCardSourceApp();-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- cy.findByTestId("card-source-case-source", {- timeout: 30000,- }).should("have.text", "match");-- // A match on two empty results would be vacuous, so the source has to- // have actually returned rows.- cy.findByTestId("card-source-total").should(($el) => {- expect(Number($el.text())).to.be.greaterThan(0);- });- });- });-- it("applies filters, aggregations, and breakouts on top of a saved question", () => {- setupCardSourceApp();-- H.dataAppIframe(APP_DISPLAY_NAME).within(() => {- ["filters", "aggregations", "breakouts"].forEach((clause) => {- cy.findByTestId(`card-source-case-${clause}`, {- timeout: 30000,- }).should("have.text", "match");- });- });- });});describe("clipboard (copy)", () => {diff --git a/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts b/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.tsnew file mode 100644index 00000000000..d538c8c5ee2--- /dev/null+++ b/e2e/test/scenarios/data-apps/sync-resources-production-actions.cy.spec.ts@@ -0,0 +1,153 @@+import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";+import {+ addUserToGroup,+ createDataAppApiKey,+ dataAppIframe,+ dataAppPermissionGroupId,+ mockDataApp,+ syncDataAppResources,+} from "e2e/support/helpers";++const { H } = cy;++const TEST_TABLE = "scoreboard_actions";+const MODEL_NAME = "Scoreboard model";++const APP_SLUG = "synced-actions-app";+const APP_DISPLAY_NAME = "Synced Actions App";++const APP_ROOT = () =>+ `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;+const ACTION_FILE = () => `${APP_ROOT()}/actions/orders.action.ts`;+const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;+const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;++/** The manifest as source control holds it. */+const AUTHORED_MANIFEST = `name: ${APP_DISPLAY_NAME}\npath: ./dist/index.js\n`;++/** The declaration as source control holds it, with no generated ID yet. */+const declaration = (sourceActionId: number) =>+ [+ 'import { defineAction } from "@metabase/embedding-sdk-react/data-app";',+ "",+ "export const CreateScore = defineAction({",+ ` action: { id: ${sourceActionId}, parameters: [] },`,+ "});",+ "",+ ].join("\n");++/**+ * The action half of the production path. Outside the dev preview+ * `toExecutableActionId` runs `copiedActionId` — the copy hanging off the copied+ * model — because that is the only action an app's viewers may execute.+ */+describe(+ "scenarios > data apps > sync-resources in production (actions)",+ { tags: ["@external", "@actions"] },+ () => {+ // Restore the source files and remove the lockfile before each synchronization.+ const restoreAuthoredFixture = () => {+ cy.writeFile(ACTION_FILE(), declaration(1));+ cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);+ cy.task("removeDataAppPaths", { paths: [LOCKFILE()] });+ };++ 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);+ H.createModelFromTableName({+ tableName: TEST_TABLE,+ modelName: MODEL_NAME,+ });++ restoreAuthoredFixture();+ createDataAppApiKey().as("apiKey");+ });++ after(() => {+ restoreAuthoredFixture();+ });++ /** Declares the model's action, synchronizes, and returns both action IDs. */+ const syncApp = () =>+ cy.get<number>("@modelId").then((modelId) =>+ H.createImplicitAction({ model_id: modelId, kind: "create" }).then(+ ({ body: action }) => {+ cy.writeFile(ACTION_FILE(), declaration(action.id));++ return cy.get<string>("@apiKey").then((apiKey) =>+ syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {+ expect(error, "sync-resources failed").to.eq(null);+ expect(ok).to.eq(true);++ return cy+ .readFile(`${APP_ROOT()}/resources_metadata.json`)+ .then((lockfile) => {+ const copiedActionId =+ lockfile.models?.[0]?.actions?.[0]?.copiedActionId;++ if (typeof copiedActionId !== "number") {+ throw new Error(+ "The sync wrote no action to the lockfile.",+ );+ }++ return cy.wrap(+ { sourceActionId: action.id, copiedActionId },+ { log: false },+ );+ });+ }),+ );+ },+ ),+ );++ it("executes the synchronized copy rather than the authored action", () => {+ syncApp().then(({ sourceActionId, copiedActionId }) => {+ expect(copiedActionId).not.to.eq(sourceActionId);++ cy.intercept("POST", "/api/action/*/execute").as("execute");+ mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });+ cy.visit(`/apps/${APP_SLUG}`);++ dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("action-execute", { timeout: 30000 }).click();+ cy.findByTestId("action-output").should("have.text", "executed");+ });++ // The proof that production took the synchronized path.+ cy.wait("@execute")+ .its("request.url")+ .should("contain", `/api/action/${copiedActionId}/execute`);+ });+ });++ it("lets a member of the app's group execute it", () => {+ syncApp().then(({ copiedActionId }) => {+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ addUserToGroup(groupId, USERS.normal.email);++ cy.signInAsNormalUser();+ cy.intercept("POST", "/api/action/*/execute").as("execute");+ mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });+ cy.visit(`/apps/${APP_SLUG}`);++ 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/${copiedActionId}/execute`);+ });+ });+ });+ },+);diff --git a/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.ts b/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.tsnew file mode 100644index 00000000000..fd1d0decb94--- /dev/null+++ b/e2e/test/scenarios/data-apps/sync-resources-production.cy.spec.ts@@ -0,0 +1,184 @@+import { SAMPLE_DB_ID, USERS } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ addUserToGroup,+ createDataAppApiKey,+ dataAppIframe,+ dataAppPermissionGroupId,+ mockDataApp,+ syncDataAppResources,+} from "e2e/support/helpers";++const { H } = cy;+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++const APP_SLUG = "synced-app";+const APP_DISPLAY_NAME = "Synced App";++const APP_ROOT = () =>+ `${Cypress.config("projectRoot")}/e2e/support/assets/data-apps/${APP_SLUG}`;+const QUERY_FILE = () => `${APP_ROOT()}/queries/orders.query.ts`;+const MANIFEST_FILE = () => `${APP_ROOT()}/data_app.yaml`;+const LOCKFILE = () => `${APP_ROOT()}/resources_metadata.json`;++/** The manifest as source control holds it. */+const AUTHORED_MANIFEST = `name: ${APP_DISPLAY_NAME}\npath: ./dist/index.js\n`;++/** The declaration as source control holds it, with no generated ID yet. */+const AUTHORED_DECLARATION = [+ "import {",+ " aggregations,",+ " breakout,",+ " defineQuery,",+ '} from "@metabase/embedding-sdk-react/data-app";',+ "",+ "/**",+ " * Authored state, as it sits in source control before a sync. `id` is the sample",+ " * database's ORDERS table (`SAMPLE_DATABASE.ORDERS_ID`); the spec writes this file",+ " * from the same constant, so a snapshot change fails loudly rather than silently.",+ " * Synchronization writes `savedQuestionSourceId` in here, and the spec restores",+ " * this file afterwards.",+ " */",+ "const OrdersUserId = {",+ ' type: "column" as const,',+ ` fieldId: ${ORDERS.USER_ID},`,+ ` tableId: ${ORDERS_ID},`,+ ' name: "USER_ID",',+ ' displayName: "User ID",',+ ' jsType: "number",',+ "};",+ "",+ "export const OrdersCount = defineQuery({",+ ` source: { type: "table", id: ${ORDERS_ID} },`,+ " aggregations: [aggregations.count()],",+ " breakouts: [breakout(OrdersUserId)],",+ "});",+].join("\n");++/**+ * What a shipped data app actually does: outside the dev preview `isDataAppDev()`+ * is false, so the SDK addresses the synchronized copy — the only resource an+ * app's viewers are permitted to read — rather than the authored source.+ */+describe("scenarios > data apps > sync-resources in production", () => {+ // Restore the source files and remove the lockfile before each synchronization.+ const restoreAuthoredFixture = () => {+ cy.writeFile(QUERY_FILE(), `${AUTHORED_DECLARATION}\n`);+ cy.writeFile(MANIFEST_FILE(), AUTHORED_MANIFEST);+ cy.task("removeDataAppPaths", { paths: [LOCKFILE()] });+ };++ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ restoreAuthoredFixture();+ createDataAppApiKey().as("apiKey");+ });++ after(() => {+ restoreAuthoredFixture();+ });++ /** Synchronizes the fixture and returns the card the app must now address. */+ const syncApp = () =>+ cy.get<string>("@apiKey").then((apiKey) =>+ syncDataAppResources(apiKey, APP_ROOT()).then(({ ok, error }) => {+ expect(error, "sync-resources failed").to.eq(null);+ expect(ok).to.eq(true);++ return cy+ .readFile(`${APP_ROOT()}/resources_metadata.json`)+ .then((lockfile) => {+ const cardId = lockfile.queries?.[0]?.savedQuestionSourceId;++ if (typeof cardId !== "number") {+ throw new Error("The sync wrote no query entry to the lockfile.");+ }++ return cy.wrap(cardId, { log: false });+ });+ }),+ );++ it("runs the synchronized card rather than the authored table query", () => {+ syncApp().then((cardId) => {+ cy.readFile(QUERY_FILE()).should(+ "contain",+ `savedQuestionSourceId: ${cardId}`,+ );++ cy.intercept("POST", "/api/dataset").as("dataset");+ mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });+ cy.visit(`/apps/${APP_SLUG}`);++ dataAppIframe(APP_DISPLAY_NAME).within(() => {+ cy.findByTestId("synced-app-total", { timeout: 30000 }).should(+ ($total) => {+ expect(Number($total.text())).to.be.greaterThan(0);+ },+ );+ });++ // The proof that production took the synchronized path: the query runs+ // against the copied card, not the table the declaration names.+ cy.wait("@dataset").then(({ request }) => {+ const [stage] = request.body.stages ?? [];+ expect(stage?.["source-card"], "runs the synchronized card").to.eq(+ cardId,+ );+ expect(stage?.["source-table"], "not the authored table").to.be+ .undefined;+ });+ });+ });++ // The swap is only safe if both sides return the same thing. The dev preview+ // runs the authored query unswapped; production runs the card it was published+ // as. A deployed app cannot run the authored query at all, so the two sides are+ // captured separately rather than side by side.+ it("returns the same rows from the published card as from the authored query", () => {+ syncApp().then((cardId) => {+ cy.request("POST", "/api/dataset", {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ breakout: [["field", ORDERS.USER_ID, null]],+ },+ }).then(({ body: authored }) => {+ cy.request("POST", `/api/card/${cardId}/query`).then(+ ({ body: published }) => {+ expect(published.data.rows).to.deep.eq(authored.data.rows);+ expect(+ published.data.rows[0][1],+ "a match on two empty results would be vacuous",+ ).to.be.greaterThan(0);+ },+ );+ });+ });+ });++ it("serves the app to a member of its permission group", () => {+ syncApp().then(() => {+ dataAppPermissionGroupId(APP_SLUG).then((groupId) => {+ addUserToGroup(groupId, USERS.normal.email);++ cy.signInAsNormalUser();+ mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });+ cy.visit(`/apps/${APP_SLUG}`);++ 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/user-access.cy.spec.ts b/e2e/test/scenarios/data-apps/user-access.cy.spec.tsnew file mode 100644index 00000000000..a5f3d0765b2--- /dev/null+++ b/e2e/test/scenarios/data-apps/user-access.cy.spec.ts@@ -0,0 +1,359 @@+import { SAMPLE_DB_ID, USERS } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ ALL_USERS_GROUP_ID,+ COLLECTION_GROUP_ID,+ DATA_GROUP_ID,+} from "e2e/support/cypress_sample_instance_data";+import {+ type DataApp,+ DataPermission,+ DataPermissionValue,+ type Table,+} from "metabase-types/api";++const { H } = cy;++const DATA_APP_NAME = "user-access-test";++const { ORDERS_ID, PRODUCTS_ID } = SAMPLE_DATABASE;++const NORMAL_USER_NAME = `${USERS.normal.first_name} ${USERS.normal.last_name}`;+const NODATA_USER_NAME = `${USERS.nodata.first_name} ${USERS.nodata.last_name}`;++describe("scenarios > data apps > user access (EMB-2328)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ cy.request<DataApp>("POST", `/api/apps/${DATA_APP_NAME}/draft`).then(+ ({ body: app }) => {+ expect(app.permission_group_id).not.to.be.null;++ cy.wrap(app.permission_group_id, { log: false }).as("dataAppGroupId");+ },+ );+ });++ it("adds and removes a data app user by pasting a single email", () => {+ cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {+ table_ids: [],+ });++ cy.visit("/admin/settings/apps");+ openManageUserAccessFromAppRow();++ cy.location("pathname").should(+ "eq",+ `/admin/settings/apps/${DATA_APP_NAME}/users`,+ );++ H.main().within(() => {+ cy.findByRole("link", { name: "Data apps" }).should("be.visible");+ cy.findByText(DATA_APP_NAME).should("be.visible");+ cy.findByText("No one has access yet").should("be.visible");++ cy.findByRole("heading", { name: "Manage access to this app" }).should(+ "be.visible",+ );+ });++ cy.findByRole("button", { name: "Add users" }).click();+ H.popover().findByText(NORMAL_USER_NAME).should("be.visible");++ cy.findByRole("textbox", { name: "Search for a user to add" })+ .paste(` ${USERS.normal.email.toUpperCase()} `)+ .should("have.value", "");++ cy.findByRole("button", { name: "Add" }).click();++ userRow(USERS.normal.email).should("be.visible");+ cy.reload();++ H.main().within(() => {+ cy.findByText(NORMAL_USER_NAME, { timeout: 20_000 }).should("be.visible");+ cy.findByText(USERS.normal.email).should("be.visible");+ cy.findByText("No one has access yet").should("not.be.visible");+ });++ cy.findByRole("button", { name: `Remove ${NORMAL_USER_NAME}` }).click();++ H.main().within(() => {+ cy.findByText("No one has access yet", { timeout: 20_000 }).should(+ "be.visible",+ );++ cy.findByText(NORMAL_USER_NAME).should("not.exist");+ });+ });++ it("adds users from comma-separated emails without duplicating existing members", () => {+ cy.get<number>("@dataAppGroupId").then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ });++ cy.visit(`/admin/settings/apps/${DATA_APP_NAME}/users`);+ userRow(USERS.normal.email).should("be.visible");++ cy.findByRole("button", { name: "Add users" }).click();+ H.popover().findByText(NODATA_USER_NAME).should("be.visible");++ cy.log("paste a comma-separated list of emails");+ cy.findByRole("textbox", { name: "Search for a user to add" })+ .paste(` ${USERS.normal.email}, ${USERS.nodata.email.toUpperCase()} `)+ .should("have.value", USERS.normal.email);++ cy.findByRole("button", { name: "Add" }).click();++ userRow(USERS.nodata.email).should("be.visible");+ cy.reload();++ cy.log("both users from the comma-separated list should be visible");+ userRow(USERS.normal.email).should("have.length", 1).and("be.visible");+ userRow(USERS.nodata.email).should("have.length", 1).and("be.visible");+ });++ // SQLite does not have a schema.+ // The visible hierarchy should be "[Database] > [Table]" in table warnings.+ it("links a missing-access warning to a table without a schema", () => {+ H.activateToken("pro-self-hosted");+ H.addSqliteDatabase();++ cy.get<number>("@sqliteID").then((databaseId) => {+ H.withDatabase(databaseId, ({ NUMBER_WITH_NULLS_ID }) => {+ cy.request<Table>("GET", `/api/table/${NUMBER_WITH_NULLS_ID}`)+ .its("body")+ .as("sqliteTable");+ });++ cy.updatePermissionsGraph({+ [ALL_USERS_GROUP_ID]: {+ [databaseId]: {+ [DataPermission.VIEW_DATA]: DataPermissionValue.BLOCKED,+ },+ },+ [COLLECTION_GROUP_ID]: {+ [databaseId]: {+ [DataPermission.VIEW_DATA]: DataPermissionValue.BLOCKED,+ },+ },+ });+ });++ H.activateToken("bleeding-edge");++ cy.get<Table>("@sqliteTable").then(({ id, schema }) => {+ expect(schema).to.equal("");++ cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {+ table_ids: [id],+ });+ });++ cy.get<number>("@dataAppGroupId").then((groupId) => {+ H.addUserToGroup(groupId, USERS.nodata.email);+ });++ cy.visit(`/admin/settings/apps/${DATA_APP_NAME}/users`);+ userRow(USERS.nodata.email)+ .findByRole("button", { name: "Missing data access" })+ .should("be.visible")+ .realHover();++ cy.get<Table>("@sqliteTable").then(({ id, db_id }) => {+ cy.findByTestId("missing-tables-list").within(() => {+ cy.findAllByRole("link").should("have.length", 2);++ cy.findByRole("link", { name: "sqlite" }).should(+ "have.attr",+ "href",+ `/admin/permissions/data/database/${db_id}`,+ );++ cy.findByRole("link", { name: "Number With Nulls" })+ .should(+ "have.attr",+ "href",+ `/admin/permissions/data/database/${db_id}/table/${id}`,+ )+ .and("have.attr", "target", "_blank")+ .and("have.attr", "rel", "noopener noreferrer")+ .invoke("removeAttr", "target")+ .click();+ });++ cy.location("pathname").should(+ "eq",+ `/admin/permissions/data/database/${db_id}/table/${id}`,+ );+ });++ cy.findByTestId("permissions-editor-breadcrumbs").should(+ "contain.text",+ "Number With Nulls",+ );++ H.assertPermissionForItem("All Users", 0, "Blocked");+ });++ it("shows warnings only for users missing access to used tables", () => {+ // The no-data snapshot user belongs to both of these groups.+ // Block the products table in both groups.+ cy.updatePermissionsGraph({+ [ALL_USERS_GROUP_ID]: {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: {+ PUBLIC: {+ [ORDERS_ID]: DataPermissionValue.UNRESTRICTED,+ [PRODUCTS_ID]: DataPermissionValue.BLOCKED,+ },+ },+ },+ },++ [COLLECTION_GROUP_ID]: {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: {+ PUBLIC: {+ [ORDERS_ID]: DataPermissionValue.UNRESTRICTED,+ [PRODUCTS_ID]: DataPermissionValue.BLOCKED,+ },+ },+ },+ },++ [DATA_GROUP_ID]: {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: {+ PUBLIC: {+ [ORDERS_ID]: DataPermissionValue.UNRESTRICTED,+ [PRODUCTS_ID]: DataPermissionValue.UNRESTRICTED,+ },+ },+ },+ },+ });++ cy.request("PUT", `/api/apps/${DATA_APP_NAME}/table-dependencies`, {+ table_ids: [ORDERS_ID, PRODUCTS_ID],+ });++ cy.get<number>("@dataAppGroupId").then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ H.addUserToGroup(groupId, USERS.nodata.email);+ });++ cy.visit("/admin/settings/apps");++ dataAppRow()+ .findByRole("link", {+ name: "Some users are missing data access.",+ })+ .should("be.visible")+ .click();++ cy.location("pathname").should(+ "eq",+ `/admin/settings/apps/${DATA_APP_NAME}/users`,+ );++ cy.findByRole("heading", { name: "Manage access to this app" }).should(+ "be.visible",+ );++ userRow(USERS.normal.email).within(() => {+ cy.findByText(NORMAL_USER_NAME).should("be.visible");++ cy.findByRole("button", { name: "Missing data access" }).should(+ "not.exist",+ );+ });++ userRow(USERS.nodata.email).within(() => {+ cy.findByText(NODATA_USER_NAME).should("be.visible");++ cy.findByRole("button", { name: "Missing data access" })+ .should("be.visible")+ .realHover();+ });++ cy.findByTestId("data-access-warning-popover").within(() => {+ cy.findByText(+ `${USERS.nodata.first_name} doesn’t have permission to view these tables used in this app:`,+ ).should("be.visible");++ cy.findByTestId("missing-tables-list").within(() => {+ cy.findAllByRole("link")+ .should("have.length", 3)+ .and("be.visible")+ .should(($links) => {+ expect(+ [...$links].map((link) => ({+ label: link.textContent,+ href: link.getAttribute("href"),+ target: link.getAttribute("target"),+ rel: link.getAttribute("rel"),+ })),+ ).to.deep.equal([+ {+ label: "Sample Database",+ href: `/admin/permissions/data/database/${SAMPLE_DB_ID}`,+ target: "_blank",+ rel: "noopener noreferrer",+ },+ {+ label: "PUBLIC",+ href: `/admin/permissions/data/database/${SAMPLE_DB_ID}/schema/PUBLIC`,+ target: "_blank",+ rel: "noopener noreferrer",+ },+ {+ label: "Products",+ href: `/admin/permissions/data/database/${SAMPLE_DB_ID}/schema/PUBLIC/table/${PRODUCTS_ID}`,+ target: "_blank",+ rel: "noopener noreferrer",+ },+ ]);+ });++ cy.findByRole("link", { name: "Orders" }).should("not.exist");+ });+ });++ cy.findByRole("button", { name: `Remove ${NODATA_USER_NAME}` }).click();++ H.main().within(() => {+ cy.findByText(USERS.normal.email).should("be.visible");++ cy.findByText(USERS.nodata.email, { timeout: 20_000 }).should(+ "not.exist",+ );+ });++ cy.visit("/admin/settings/apps");+ dataAppRow().within(() => {+ cy.findByText(DATA_APP_NAME).should("be.visible");++ cy.findByRole("link", {+ name: "Some users are missing data access.",+ }).should("not.exist");+ });+ });+});++const dataAppRow = () =>+ cy+ .findByTestId(`data-app-list-item-${DATA_APP_NAME}`)+ .scrollIntoView()+ .should("be.visible");++function openManageUserAccessFromAppRow() {+ dataAppRow()+ .findByRole("button", { name: `Actions for ${DATA_APP_NAME}` })+ .click();++ H.popover().findByText("Manage user access").click();+}++const userRow = (email: string) => H.main().findByText(email).closest("tr");diff --git a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts b/e2e/test/scenarios/data-apps/viewing.cy.spec.tsindex dcebe8f9114..236ea1dd4d1 100644--- a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/viewing.cy.spec.ts@@ -3,6 +3,7 @@ import {DATA_APP_NAME as APP_NAME,visitDataAppRoute as visitAppRoute,} from "e2e/support/helpers";+import type { DataApp } from "metabase-types/api";import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";@@ -59,6 +60,45 @@ describe("scenarios > data apps > viewing & routing", () => {});});+ it("shows unpublished app error when opening an app without a resource collection", () => {+ cy.request<DataApp>("POST", `/api/apps/${APP_NAME}/draft`)+ .its("body.resource_collection_id")+ .as("resourceCollectionId");++ cy.log("archive and delete the data app collection");+ cy.get<number>("@resourceCollectionId").then((collectionId) => {+ cy.request("PUT", `/api/collection/${collectionId}`, {+ archived: true,+ });++ cy.request("DELETE", `/api/collection/${collectionId}`);+ });++ cy.log("fetching bundle should return 409 error");+ cy.request({+ url: `/api/apps/${APP_NAME}/bundle`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 409);++ cy.intercept("GET", `/api/apps/${APP_NAME}`).as("getUnpublishedApp");+ H.openDataApp(APP_NAME);++ cy.log("fetching data app metadata should return 409 error");+ cy.wait("@getUnpublishedApp")+ .its("response.statusCode")+ .should("eq", 409);++ H.main().within(() => {+ cy.findByText("This data app isn’t published yet").should("be.visible");++ cy.findByText(+ "An administrator needs to publish this data app before it can be opened.",+ ).should("be.visible");+ });+ });+it("shows a not-found state for a disabled or missing app", () => {// No app with this slug exists, so the metadata endpoint really 404s and the// host renders a not-found state rather than a broken iframe — no mock needed.@@ -72,7 +112,7 @@ describe("scenarios > data apps > viewing & routing", () => {H.mockDataApp(APP_NAME, {displayName: APP_DISPLAY_NAME,testEnv: TEST_ENV,- bundleDelay: 2000,+ bundleDelayMs: 2000,});H.openDataApp(APP_NAME);diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.cljindex 708aaa78fe6..a4078988d73 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj@@ -189,8 +189,9 @@(let [blocked-group-ids (advanced-permissions.db/blocked-group-ids group-ids)impersonation-group-ids (advanced-permissions.db/impersonated-group-ids group-ids)sandbox-group-ids (advanced-permissions.db/sandboxed-group-ids group-ids)+ ;; New databases have no legacy grants to preserve. App groups must start blocked.blocked-groups (into (or blocked-group-ids #{})- (concat impersonation-group-ids sandbox-group-ids))]+ (concat impersonation-group-ids sandbox-group-ids (perms/data-app-group-ids)))](zipmap group-ids (map #(if (blocked-groups %) :blocked :unrestricted) group-ids)))))(defenterprise new-table-view-data-permission-levels@@ -205,6 +206,14 @@sandbox-group-ids (into #{}(map :group_id)(advanced-permissions.db/sandboxed-group-ids-for-database db-id group-ids))- blocked-groups (into (or blocked-group-ids #{})- sandbox-group-ids)]- (zipmap group-ids (map #(if (blocked-groups %) :blocked :unrestricted) group-ids)))))+ app-group-ids (set (perms/data-app-group-ids))+ app-view-data (when (some app-group-ids group-ids)+ (perms/data-app-view-data-permission-level db-id))+ blocked-groups (into (or blocked-group-ids #{}) sandbox-group-ids)]+ ;; A new table must not introduce a block into an app group's database-wide legacy permission.+ (into {} (map (fn [group-id]+ [group-id (cond+ (app-group-ids group-id) app-view-data+ (blocked-groups group-id) :blocked+ :else :unrestricted)]))+ group-ids))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/README.md b/enterprise/backend/src/metabase_enterprise/data_apps/README.mdindex 21ccaf95fcf..85f7afa99e9 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/README.md+++ b/enterprise/backend/src/metabase_enterprise/data_apps/README.md@@ -46,25 +46,29 @@ remote-sync import → snapshot → sync-from-snapshot! → discover confilayer and are counted separately in the pull summary (see `fold-data-app-changes` in`remote_sync/impl.clj` — without it, a pull whose only change is a data app reports "no changes").-One import = one transaction. Discovery, upserts, and pruning all commit together.+Apps are synced independently. Each app's row and its resource links commit together, and pruning+runs in its own transaction. A database or resource setup error rolls back that app's update, then+records `sync_error` separately.## The repository is the source of truthA sync **upserts every app it finds and deletes every row whose directory is gone.** Theconsequences are worth stating explicitly, because they're the questions that come up:-| Event | What happens to apps |-|---|---|-| App directory removed from the repo | Row and cached bundle deleted on the next sync |-| Repo switched to a different one | Previous repo's apps are absent from the new snapshot, so they're dropped |-| Repo unlinked | Nothing — unlinking runs no sync, so apps survive |-| Repo has no `data_apps/` at all | All apps removed |-| Failed clone/fetch | Nothing — that throws before a snapshot exists, so deletion never fires |+| Event | What happens to apps |+| ----------------------------------- | ------------------------------------------------------------------------- |+| App directory removed from the repo | Row and cached bundle deleted on the next sync |+| Repo switched to a different one | Previous repo's apps are absent from the new snapshot, so they're dropped |+| Repo unlinked | Nothing — unlinking runs no sync, so apps survive |+| Repo has no `data_apps/` at all | All apps removed |+| Failed clone/fetch | Nothing — that throws before a snapshot exists, so deletion never fires |Pruning is by **directory presence**, not by successful parse. An app whose directory is stillthere but whose `data_app.yaml` is momentarily broken keeps its row and its last-good bundle, and ismarked with a `sync_error` — see failure isolation below. Local `enabled` state does not protect a-row: an app disabled in the admin UI and then deleted from the repo is still removed.+row: an app disabled in the admin UI and then deleted from the repo is still removed. Draft rows —+created via `POST /api/apps/:slug/draft` ahead of an app's first import — are the one exemption:+pruning skips them until a sync materializes the app and clears the flag.## Failure isolation@@ -100,8 +104,14 @@ assets (`metabase.server.routes/static-files-handler`).- `GET /api/apps/:slug/bundle` — the cached bytes, with a content-hash ETag and `If-None-Match`→ 304. Carries `X-Metabase-Data-App-Allowed-Hosts`, which the iframe reads to configure itssandbox fetch allowlist.+- `GET /api/apps/sandbox-host` — the empty document loaded as the Near-Membrane realm iframe,+ carrying the CSP that confines `'unsafe-eval'` to that realm.- `PUT /api/apps/:slug` — toggle `enabled` (superuser).-- `DELETE /api/apps/:slug` — drop a row and its bundle (superuser).+- `DELETE /api/apps/:slug` — drop a row, its bundle, and its owned resources (superuser).+- `POST /api/apps/:slug/draft` — create or reuse a draft row with its resources before the app's+ first import (superuser).+- `POST /api/apps/:slug/query` — resolve an authored query definition into a serializable+ Metabase query plus the table IDs it touches (superuser).- `GET /api/apps/repo-status` — whether a repo is connected (superuser).Responses are field-filtered by role: superusers get full metadata, everyone else gets `name` and@@ -114,20 +124,36 @@ middleware's lookup doesn't pull in route code.## Permissions-**Viewing is not gated.** Any signed-in user may open any enabled app — `can-read?` is-unconditionally true, and the endpoints are `+auth`, so reaching a read check already implies-authentication. The data an app queries still runs through the QP under the viewing user's own-permissions, so a user without data access opens the app and sees no data.+Each app owns two server-managed resources (`resources.clj`), created on draft or first import and+reasserted on every sync: a **collection** holding the copies the app is served from (saved+questions, action models, table-sourced metrics) and a **permissions group** its users belong to.-**Managing is superuser-only** — enabling, disabling, deleting, and reading repo status.+The group is set database-level `view-data :blocked` on every database, so it grants **no data+access of its own** (which cascades `create-queries`/`download-results` to `:no`); every group but+admins is revoked from the collection before the app group gets read access. Deleting an app deletes+both resources and everything in the collection.++**Viewing an app** requires read access to its resource collection. You have to be a member in+the app's group or be an admin. An app without a linked resource collection is considered _unpublished_.+The app's metadata and bundle endpoint returns HTTP 409 for all signed-in users. The frontend+shows the error "This data app isn’t published yet".++**A viewer sees an app's data only through access they already hold.** The app group grants no+view-data of its own, so a viewer without access to an app's tables (e.g. a sandboxed user) sees no+data from it — their own groups' permissions and sandboxes apply unchanged. Because the group grants+nothing, it can never lift another group's sandbox, so sandboxing needs no data-app special-casing.++**Managing is superuser-only** — enabling, disabling, deleting, drafts, query resolution, and repo+status.## Namespace map-| Namespace | Responsibility |-|---|---|-| `sync.clj` | Discovery, materialization, pruning. The entry point remote-sync calls. |-| `config.clj` | `data_app.yaml` parsing and validation; the `data_apps/` layout constants. |-| `api.clj` | The `/api/apps` endpoints, bundle serving, ETag handling. |-| `models/data_app.clj` | The `:model/DataApp` Toucan model, permissions, blob coercion. |-| `csp.clj` | `allowed_hosts` lookup for the core CSP middleware. |-| `init.clj` | Loads the above so endpoints, models, and hooks register. |+| Namespace | Responsibility |+| --------------------- | --------------------------------------------------------------------------------------------------- |+| `sync.clj` | Discovery, materialization, pruning, drafts. The entry point remote-sync calls. |+| `config.clj` | `data_app.yaml` parsing and validation; the `data_apps/` layout constants. |+| `api.clj` | The `/api/apps` endpoints, bundle serving, ETag handling. |+| `resources.clj` | Lifecycle of the app-owned collection and permission group: creation, view-data blocking, deletion. |+| `models/data_app.clj` | The `:model/DataApp` Toucan model, permissions, blob coercion. |+| `csp.clj` | `allowed_hosts` lookup for the core CSP middleware. |+| `init.clj` | Loads the above so endpoints, models, and hooks register. |diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex bd22c89cd9e..7d1f197f8f8 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -8,11 +8,18 @@`metabase.server.routes/static-files-handler`)."(:require[clojure.string :as str]+ [metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.query-definition :as query-definition][metabase-enterprise.data-apps.sync :as data-app.sync]+ [metabase-enterprise.data-apps.user-access :as data-app.user-access][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib-be.schema :as lib-be.schema]+ [metabase.lib.core :as lib]+ [metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.malli.schema :as ms])(:import@@ -60,6 +67,10 @@[:bundle_path ms/NonBlankString][:enabled :boolean][:allowed_hosts [:sequential :string]]+ [:resource_collection_id [:maybe ms/PositiveInt]]+ [:permission_group_id [:maybe ms/PositiveInt]]+ [:table_ids [:sequential ms/PositiveInt]]+ [:has_user_permission_warnings {:optional true} :boolean][:bundle_hash [:maybe :string]][:last_synced_sha [:maybe :string]][:last_synced_at [:maybe :any]]@@ -77,6 +88,54 @@[:configured :boolean][:url [:maybe :string]]])+(def ^:private MetricResponse+ [:map {:closed true}+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:type [:enum :metric]]+ [:collection_id [:maybe ms/PositiveInt]]+ [:dataset_query ::lib-be.schema/maybe-legacy-query]+ [:database_id ms/PositiveInt]+ [:display [:maybe [:or :keyword :string]]]+ [:visualization_settings [:maybe ms/VisualizationSettings]]+ [:description [:maybe :string]]])++(def ^:private QueryResolutionResponse+ [:map+ [:database_id ms/PositiveInt]+ [:dataset_query ::lib-be.schema/maybe-legacy-query]+ [:table_ids [:sequential ms/PositiveInt]]+ [:metrics [:sequential MetricResponse]]])++(def ^:private TableDependenciesRequest+ [:map {:closed true}+ [:table_ids [:sequential {:distinct true} ms/PositiveInt]]])++(def ^:private QueryTableDependenciesRequest+ [:map {:closed true}+ [:dataset_queries [:sequential ::lib-be.schema/maybe-legacy-query]]])++(def ^:private QueryTableDependenciesResponse+ [:map {:closed true}+ [:table_ids [:sequential ms/PositiveInt]]])++(def ^:private PermissionWarningsRequest+ [:map {:closed true}+ [:user_ids [:sequential {:min 1 :max 100 :distinct true} ms/PositiveInt]]])++(def ^:private MissingTable+ [:map {:closed true}+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:schema [:maybe :string]]+ [:database_id ms/PositiveInt]+ [:database_name ms/NonBlankString]])++(def ^:private PermissionWarning+ [:map {:closed true}+ [:user_id ms/PositiveInt]+ [:missing_tables [:sequential MissingTable]]])+;;; --------------------------------------------- Repo status ---------------------------------------------(api.macros/defendpoint :get "/repo-status" :- RepoStatusResponse@@ -131,14 +190,37 @@app(select-keys app [:name :display_name])))+(defn- data-app-list-response+ [warning-group-ids app]+ (cond-> (data-app-response app)+ api/*is-superuser?*+ (assoc :has_user_permission_warnings+ (contains? warning-group-ids (:permission_group_id app)))))++(defn- read-check-data-app+ "Check whether the current user can access a data app. Viewing requires read access to the app's+ resource collection. An app with no linked resource collection has not been published yet: it is+ not viewable by anyone through this endpoint (an admin must publish it first), signalled with a+ 409 so the client can show a dedicated \"not published\" screen rather than leaking metadata or+ the bundle to every signed-in user."+ [app]+ (api/read-check app)+ (if-let [collection-id (:resource_collection_id app)]+ (api/read-check :model/Collection collection-id)+ (throw (ex-info (tru "This data app has not been published yet.")+ {:status-code 409})))+ app)+(api.macros/defendpoint :get "/" :- [:sequential [:or DataAppResponse PublicDataAppResponse]]"List the data apps provided by the connected repository. Pass `available=true`to return only enabled apps without sync errors."[_route-params{:keys [available]} :- [:map {:closed true} [:available {:optional true} [:maybe :boolean]]]]- (->> (data-apps.db/non-blob-data-apps available)- (map api/read-check)- (mapv data-app-response)))+ (let [apps (->> (data-apps.db/non-blob-data-apps available)+ (mapv api/read-check))+ warning-group-ids (when api/*is-superuser?*+ (data-app.user-access/groups-with-permission-warnings apps))]+ (mapv (partial data-app-list-response warning-group-ids) apps)));; NOTE on the `slug-regex` constraint: the default path-param matcher allows;; slashes inside a segment, so `/:slug` would otherwise swallow `/x/bundle`.@@ -160,16 +242,129 @@longer in it is pruned by that sync anyway."[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]](api/check-superuser)- ;; `t2/delete!` returns the row count; a 0 means the slug wasn't there → 404.+ ;; The delete returns the row count; a 0 means the slug wasn't there → 404.(api/check-404 (pos? (data-apps.db/delete-data-app-by-slug! slug)));; a `nil` body is rendered as a 204; matches the `:- :nil` response schema;; above (returning `generic-204-no-content` would fail that validation).nil)+(api.macros/defendpoint :put ["/:slug/table-dependencies" :slug slug-regex] :- DataAppResponse+ "Store the tables used by the resources from a successful data app resource synchronization."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]+ _query-params+ {table-ids :table_ids} :- TableDependenciesRequest]+ (api/check-superuser)+ (let [app (api/check-404 (data-apps.db/non-blob-data-app-by-slug slug))+ table-ids (vec (sort table-ids))]+ (api/check-400 (= (set table-ids)+ (data-apps.db/existing-table-ids table-ids))+ (tru "One or more tables do not exist."))+ (data-apps.db/update-data-app! (:id app) {:table_ids table-ids})+ (data-apps.db/non-blob-data-app (:id app))))++(api.macros/defendpoint :post ["/:slug/user-permission-warnings" :slug slug-regex]+ :- [:sequential PermissionWarning]+ "Return warnings for users who cannot access every table used by a data app."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]+ _query-params+ {user-ids :user_ids} :- PermissionWarningsRequest]+ (api/check-superuser)+ (let [app (api/check-404 (data-apps.db/non-blob-data-app-by-slug slug))+ users (data-apps.db/users-for-permission-warnings user-ids)]+ (api/check-404 (= (count users) (count user-ids)))+ (api/check-400 (every? :is_active users)+ (tru "Deactivated users cannot be added to data apps."))+ (api/check-400 (every? (comp nil? :tenant_id) users)+ (tru "Tenant users cannot be added to data apps."))+ (data-app.user-access/permission-warnings (:table_ids app) users)))++(defn- query-table-ids+ "The tables a query reads, including ones it reaches only through an implicit join."+ [query]+ (into (set (lib/all-source-table-ids query))+ (lib/all-implicitly-joined-table-ids query)))++(defn- referenced-card-ids+ "Ids of the cards -- metrics, source questions, template-tag questions -- that `metric`'s own+ definition reads."+ [metric]+ (-> (lib-be/application-database-metadata-provider (:database_id metric))+ (lib/query (:dataset_query metric))+ lib/all-source-card-ids))++(defn- referenced-metrics+ "Return direct metric references, rejecting any whose own definition reads another card.++ Sync copies a referenced metric but rewrites nothing inside the copy, and copies nothing the copy+ in turn reads, so those references still point at the originals. The app would publish successfully+ and then fail for every viewer without access to the originals' collections, so refuse it here.++ This runs on every sync rather than at codegen, so a metric edited into this shape after its schema+ was generated is caught too."+ [query]+ (let [metric-ids (lib/all-source-card-ids query)+ metrics (sort-by :id (data-apps.db/metrics-by-ids metric-ids))+ nested (filter (comp seq referenced-card-ids) metrics)]+ (api/check-400 (empty? nested)+ (tru "Data app queries cannot use metrics that reference other saved questions or metrics: {0}"+ (str/join ", " (map :name nested))))+ (mapv #(update (select-keys % [:id :name :type :collection_id :dataset_query+ :database_id :display :visualization_settings :description])+ :dataset_query+ lib/prepare-for-serialization)+ metrics)))++(api.macros/defendpoint :post ["/:slug/query" :slug slug-regex] :- QueryResolutionResponse+ "Resolve an authored data-app query definition into a serializable Metabase query."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]+ _query-params+ query-def :- ::query-definition/query-definition]+ (api/check-superuser)+ (api/check-404 (data-apps.db/non-blob-data-app-by-slug slug))+ (let [{source-type :type, table-id :id} (get-in query-def [:stages 0 :source])+ _ (api/check-400 (= (keyword source-type) :table)+ "Data app query definitions must use a table source.")+ database-id (api/check-404 (data-apps.db/table-database-id table-id))+ query (lib/test-query (lib-be/application-database-metadata-provider database-id) query-def)]+ {:database_id database-id+ :dataset_query (lib/prepare-for-serialization query)+ :table_ids (vec (sort (query-table-ids query)))+ :metrics (referenced-metrics query)}))++(api.macros/defendpoint :post ["/:slug/query-table-dependencies" :slug slug-regex]+ :- QueryTableDependenciesResponse+ "Return the tables read by already-saved queries, including ones reached only through an implicit join.++ Sync copies models, actions and metrics whose queries it never resolves through `/query`, and only+ this metadata-based lookup sees an implicit join: the id of a table reached through a foreign key+ appears nowhere in the query itself."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]+ _query-params+ {dataset-queries :dataset_queries} :- QueryTableDependenciesRequest]+ (api/check-superuser)+ (api/check-404 (data-apps.db/non-blob-data-app-by-slug slug))+ {:table_ids (->> dataset-queries+ (mapcat (fn [dataset-query]+ (-> (lib-be/application-database-metadata-provider (:database dataset-query))+ (lib/query dataset-query)+ query-table-ids)))+ set+ sort+ vec)})++(api.macros/defendpoint :post ["/:slug/draft" :slug slug-regex] :- DataAppResponse+ "Create or reuse a data app draft before its first repository import."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]+ (api/check-superuser)+ (api/check-400 (data-app.config/valid-slug? slug)+ "Data app draft slugs must use lowercase letters, numbers, and dashes.")+ (data-app.sync/ensure-draft! slug)+ (data-apps.db/non-blob-data-app-by-slug slug))+(api.macros/defendpoint :get ["/:slug" :slug slug-regex] :- [:or DataAppResponse PublicDataAppResponse]"Fetch metadata for a single enabled data app by its slug."[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]- (data-app-response (api/read-check (data-apps.db/enabled-non-blob-data-app-by-slug slug))))+ (data-app-response (read-check-data-app (data-apps.db/enabled-non-blob-data-app-by-slug slug))))(api.macros/defendpoint :get ["/:slug/bundle" :slug slug-regex] :- :any"Serve the cached JS bundle for a single enabled data app by slug. Honors@@ -181,7 +376,7 @@respondraise](try- (let [row (api/read-check (data-apps.db/enabled-non-blob-data-app-by-slug slug))+ (let [row (read-check-data-app (data-apps.db/enabled-non-blob-data-app-by-slug slug))hash (:bundle_hash row)etag (some->> hash (format "\"%s\""))](conddiff --git a/enterprise/backend/src/metabase_enterprise/data_apps/config.clj b/enterprise/backend/src/metabase_enterprise/data_apps/config.cljindex 9644b81f24c..73962b03351 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/config.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/config.clj@@ -38,7 +38,7 @@"Slugs that collide with literal `/api/apps/*` sub-routes (see the API's`slug-regex`). An app with one of these would sync but be unreachable, so wereject it during parsing."- #{"repo-status"})+ #{"repo-status" "sandbox-host"})(defn- normalize-path"Trim and drop a leading `./` so the path is relative to the app directory."@@ -131,6 +131,13 @@[^String dir](subs dir (inc (str/last-index-of dir "/"))))+(defn valid-slug?+ "Whether `slug` can name a data app directory and API route."+ [slug]+ (and (string? slug)+ (re-matches slug-pattern slug)+ (not (contains? reserved-slugs slug))))+(defn parse-app-config"Parse the bytes of one `data_app.yaml` from the app directory `dir` (e.g.`data_apps/sales`) into `{:slug ..., :display_name ..., :description ...,@@ -138,9 +145,8 @@relative to the directory; `:description` is an optional one-liner (nil whenabsent or blank, capped at [[max-description-chars]]); `:allowed_hosts` is a(possibly empty) vector of origins the sandboxed bundle may reach. Throws an- `ex-info` with `:status-code` 400 on- malformed or incomplete content — including a directory whose name isn't a- usable slug, since that app has no URL to be served at."+ `ex-info` with `:status-code` 400 on malformed or incomplete content — including+ a directory whose name isn't a usable slug, since that app has no URL to be served at."[^bytes bytes ^String dir](let [parsed (parse-yaml bytes dir)slug (dir-slug dir)diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.cljindex d1e7b51d99f..ad5c7a8e19f 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj@@ -3,6 +3,7 @@additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."(:require[metabase-enterprise.data-apps.schema :as data-apps.schema]+ [metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -10,6 +11,7 @@(def ^:private non-blob-columns"Columns to select for normal data-app metadata reads, excluding the raw bundle blob."[:model/DataApp :id :name :display_name :description :bundle_path :enabled :allowed_hosts+ :resource_collection_id :permission_group_id :table_ids :draft:bundle_hash :last_synced_sha :last_synced_at :sync_error:created_at :updated_at])@@ -47,6 +49,30 @@[](t2/select [:model/DataApp :name :display_name :description :allowed_hosts :bundle_path :bundle_hash :sync_error]))+(defn table-database-id+ "The database ID for the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table :id table-id))++(defn existing-table-ids+ "The IDs from `table-ids` that belong to existing Tables."+ [table-ids]+ (if (seq table-ids)+ (t2/select-pks-set :model/Table :id [:in table-ids])+ #{}))++(defn users-for-permission-warnings+ "The fields needed to calculate permission warnings for Users with `user-ids`."+ [user-ids]+ (t2/select [:model/User :id :is_superuser :is_active :tenant_id] :id [:in user-ids]))++(defn metrics-by-ids+ "The metric Cards with `metric-ids`."+ [metric-ids]+ (if (seq metric-ids)+ (t2/select :model/Card :id [:in metric-ids] :type "metric")+ []))+(mu/defn data-app-exists?"Whether a DataApp named `slug` exists."[slug :- :string]@@ -75,11 +101,148 @@(t2/delete! :model/DataApp :name slug))(mu/defn delete-data-apps-not-named!- "Delete the DataApps whose name is not one of `slugs`, returning the number deleted."+ "Delete non-draft DataApps whose name is not one of `slugs`, returning the number deleted."[slugs :- [:set :string]]- (t2/delete! :model/DataApp :name [:not-in slugs]))+ (t2/delete! :model/DataApp :name [:not-in slugs] :draft false))(mu/defn delete-all-data-apps!- "Delete every DataApp, returning the number deleted."+ "Delete every non-draft DataApp, returning the number deleted."+ []+ (t2/delete! :model/DataApp :draft false))++(defn publish-data-app-drafts!+ "Mark drafts named by `slugs` as published."+ [slugs]+ (t2/update! :model/DataApp :name [:in slugs] :draft true {:draft false}))++(defn permission-group+ "The permission group with `group-id`, or nil."+ [group-id]+ (t2/select-one :model/PermissionsGroup :id group-id))++(defn insert-permission-group!+ "Insert a permission group and return it."+ [row]+ (t2/insert-returning-instance! :model/PermissionsGroup row))++(defn update-permission-group!+ "Apply `changes` to the permission group with `group-id`."+ [group-id changes]+ (t2/update! :model/PermissionsGroup :id group-id changes))++(defn delete-permission-group!+ "Delete the permission group with `group-id`."+ [group-id]+ (t2/delete! :model/PermissionsGroup :id group-id))++(defn data-app-group-ids+ "The IDs of permission groups owned by data apps."[]- (t2/delete! :model/DataApp))+ (t2/select-pks-set :model/PermissionsGroup :is_data_app_group true))++(defn databases-with-legacy-permissions+ "Database IDs with legacy View Data permissions from groups not owned by apps."+ [database-ids]+ (if (seq database-ids)+ (t2/select-fn-set :db_id :model/DataPermissions+ {:select [:p.db_id]+ :from [[:data_permissions :p]]+ :join [[:permissions_group :g] [:= :g.id :p.group_id]]+ :where [:and+ [:in :p.db_id database-ids]+ [:= :p.perm_type "perms/view-data"]+ [:= :p.perm_value "legacy-no-self-service"]+ [:= :g.is_data_app_group false]]})+ #{}))++(defn resource-collection+ "The resource collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn insert-resource-collection!+ "Insert a resource collection and return it."+ [row]+ (t2/insert-returning-instance! :model/Collection row))++(defn update-resource-collection!+ "Apply `changes` to the resource collection with `collection-id`."+ [collection-id changes]+ (t2/update! :model/Collection :id collection-id changes))++(defn delete-resource-collection!+ "Delete the resource collection with `collection-id`."+ [collection-id]+ (t2/delete! :model/Collection :id collection-id))++(defn non-router-database-ids+ "The IDs of databases that are not routed through another database."+ []+ (t2/select-pks-set :model/Database :router_database_id nil))++(defn permissions-for-paths-excluding-group+ "Permission grants for `paths`, excluding `group-id`."+ [paths group-id]+ (t2/select [:model/Permissions :group_id :object]+ :object [:in paths]+ :group_id [:not= group-id]))++(defn table-details+ "Table names and database details for `table-ids`."+ [table-ids]+ (t2/select :model/Table+ {:select [:t.id+ [:t.display_name :name]+ :t.schema+ [:t.db_id :database_id]+ [:d.name :database_name]]+ :from [[:metabase_table :t]]+ :join [[:metabase_database :d] [:= :d.id :t.db_id]]+ :where [:in :t.id table-ids]+ :order-by [[:d.name :asc] [:t.schema :asc] [:t.display_name :asc]]}))++(defn sandboxed-user-table-access+ "Sandboxed table access from non-data-app groups for the requested users and tables."+ [user-ids table-ids]+ (t2/query {:select-distinct [[:pgm.user_id :user_id]+ [:s.table_id :table_id]]+ :from [[:permissions_group_membership :pgm]]+ :join [[:sandboxes :s] [:= :s.group_id :pgm.group_id]+ [:permissions_group :pg] [:= :pg.id :pgm.group_id]]+ :where [:and+ [:in :pgm.user_id user-ids]+ [:in :s.table_id table-ids]+ [:not :pg.is_data_app_group]]}))++(defn unrestricted-user-table-access+ "Unrestricted table access from non-data-app groups for the requested users and tables."+ [user-ids table-ids]+ (t2/query {:select-distinct [[:pgm.user_id :user_id]+ [:t.id :table_id]]+ :from [[:permissions_group_membership :pgm]]+ :join [[:data_permissions :dp] [:= :dp.group_id :pgm.group_id]+ [:permissions_group :pg] [:= :pg.id :pgm.group_id]+ [:metabase_table :t] [:and+ [:= :t.db_id :dp.db_id]+ [:or+ [:= :dp.table_id nil]+ [:= :dp.table_id :t.id]]]]+ :where [:and+ [:in :pgm.user_id user-ids]+ [:in :t.id table-ids]+ [:not :pg.is_data_app_group]+ [:= :dp.perm_type (u/qualified-name :perms/view-data)]+ [:= :dp.perm_value "unrestricted"]]}))++(defn active-group-members+ "Active user memberships for `group-ids`, including API-key users."+ [group-ids]+ (t2/query {:select [[:pgm.group_id :group_id]+ [:u.id :id]+ :u.is_superuser+ :u.email]+ :from [[:permissions_group_membership :pgm]]+ :join [[:core_user :u] [:= :u.id :pgm.user_id]]+ :where [:and+ [:in :pgm.group_id group-ids]+ [:= :u.is_active true]]}))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 0524fc834c9..d7b9017dd37 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@@ -1,7 +1,10 @@(ns metabase-enterprise.data-apps.models.data-app(:require+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.resources :as data-app.resources][metabase.api.common :as api][metabase.models.interface :as mi]+ [metabase.premium-features.core :refer [defenterprise]][methodical.core :as methodical][toucan2.core :as t2])(:import@@ -25,7 +28,8 @@(t2/deftransforms :model/DataApp{:bundle transform-bundle;; JSON array of origins the sandboxed bundle may fetch/XHR (see config.clj).- :allowed_hosts mi/transform-json})+ :allowed_hosts mi/transform-json+ :table_ids mi/transform-json})(doto :model/DataApp(derive :metabase/model)@@ -56,7 +60,8 @@(t2/define-after-select :model/DataApp[app](cond-> app- (contains? app :allowed_hosts) (update :allowed_hosts #(or % []))))+ (contains? app :allowed_hosts) (update :allowed_hosts #(or % []))+ (contains? app :table_ids) (update :table_ids #(or % []))));; Deliberately ungated: any signed-in user may view a data app, and the `+auth`;; endpoints mean reaching a read check already implies authentication. See the@@ -73,7 +78,18 @@[_model _instance]api/*is-superuser?*)+(t2/define-before-delete :model/DataApp+ [app]+ (data-app.resources/delete-resources! app))+(methodical/defmethod mi/to-json :model/DataApp"Never include the raw bundle bytes in JSON."[data-app json-generator](next-method (dissoc data-app :bundle) json-generator))++(defenterprise data-app-group-ids+ "The data-app permission groups (those flagged `is_data_app_group`). SSO group sync must never touch+ their membership."+ :feature :none+ []+ (data-apps.db/data-app-group-ids))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/permissions.clj b/enterprise/backend/src/metabase_enterprise/data_apps/permissions.cljnew file mode 100644index 00000000000..b71b640ff4c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/permissions.clj@@ -0,0 +1,55 @@+(ns metabase-enterprise.data-apps.permissions+ (:require+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase.permissions.core :as perms]+ [metabase.premium-features.core :refer [defenterprise]]))++(defenterprise data-app-view-data-permission-level+ "Use legacy across the database when an ordinary group needs it. A block on another table can deny legacy queries."+ :feature :none+ [database-id]+ (if (contains? (data-apps.db/databases-with-legacy-permissions [database-id]) database-id)+ :legacy-no-self-service+ :blocked))++(defn- database-level-permission?+ [rows value]+ (and (= 1 (count rows))+ (let [{:keys [table_id perm_value]} (first rows)]+ (and (nil? table_id) (= perm_value value)))))++(defn- reconcile-group-permissions!+ [permissions group-id database-id view-data]+ (let [permissions (if (database-level-permission? (get permissions [group-id database-id :perms/view-data]) view-data)+ permissions+ (do+ (perms/set-database-permission! group-id database-id :perms/view-data view-data)+ (perms/index-database-permissions [group-id] [database-id])))]+ ;; Joining a data app must not grant permissions other than "view data".+ (doseq [perm-type [:perms/create-queries :perms/download-results+ :perms/manage-table-metadata :perms/manage-database :perms/transforms]+ :when (not (database-level-permission? (get permissions [group-id database-id perm-type]) :no))]+ (perms/set-database-permission! group-id database-id perm-type :no))))++(defn- reconcile-permissions!+ [group-ids database-ids]+ (when-let [group-ids (seq group-ids)]+ (let [legacy-databases (data-apps.db/databases-with-legacy-permissions database-ids)+ permissions (perms/index-database-permissions group-ids database-ids)]+ (doseq [group-id group-ids+ database-id database-ids]+ (reconcile-group-permissions! permissions group-id database-id+ (if (contains? legacy-databases database-id)+ :legacy-no-self-service+ :blocked))))))++(defn reconcile-app-group-permissions!+ "Reconcile one app group's data permissions during resource setup."+ [group-id database-ids]+ (reconcile-permissions! [group-id] database-ids))++(defenterprise reconcile-data-app-permissions!+ "Update data app groups after a group's database permission changes."+ :feature :none+ [database-ids]+ (reconcile-permissions! (data-apps.db/data-app-group-ids) database-ids))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj b/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.cljnew file mode 100644index 00000000000..57163883f8a--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/query_definition.clj@@ -0,0 +1,176 @@+(ns metabase-enterprise.data-apps.query-definition+ "Closed schemas for the data apps subset of `metabase.lib.schema.test-spec`.++ Data apps queries support a single table-sourced stage without explicit joins or expressions."+ (:require+ [malli.core :as mc]+ [malli.error :as me]+ [malli.transform :as mtx]+ [metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema.literal :as literal]+ [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]+ [metabase.util :as u]+ [metabase.util.malli.registry :as mr]))++(defn- normalize-binning [column]+ (let [{:keys [strategy num-bins bin-width] :as binning} (:binning column)]+ ;; Keep invalid options for validation instead of silently dropping them.+ (if (and binning (mr/validate ::binning binning))+ (cond-> (dissoc column :binning)+ (not (or (:bins column) (:bin-width column)))+ (merge (case strategy+ :default {:bins :auto}+ :num-bins {:bins num-bins}+ :bin-width {:bin-width bin-width})))+ column)))++(defn- query-map-decoder [schema _options]+ (let [metadata-keys (::sdk-metadata (mc/properties schema))]+ {:enter (fn [value]+ (when (map? value)+ ;; drop data apps specific metadata fields such as `js-type`+ (apply dissoc (update-keys value (comp keyword u/->kebab-case-en)) metadata-keys)))+ :leave (when (::normalize-binning (mc/properties schema)) normalize-binning)}))++(mr/def ::table-source+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:name :columns :fields :segments :measures]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :table]]+ [:id [:ref ::lib.schema.id/table]]])++(mr/def ::column+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:description :js-type :field-id :base-type :effective-type :default-temporal-bucket :id :metric-id]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :column]]+ [:name string?]+ [:table-id {:optional true} [:maybe ::lib.schema.id/table]]+ [:source-name {:optional true} [:maybe string?]]+ [:source-field-id {:optional true} [:maybe ::lib.schema.id/field]]+ [:display-name {:optional true} [:maybe string?]]+ [:index {:optional true} [:maybe pos-int?]]])++(mr/def ::temporal-bucket+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}+ [:unit {:optional true} [:maybe ::lib.schema.temporal-bucketing/unit]]])++(mr/def ::auto-bin+ [:= {:decode/normalize lib.schema.common/normalize-keyword} :auto])++(mr/def ::bin-count-bucket+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}+ [:bins {:optional true} [:maybe [:or pos-int? ::auto-bin]]]])++(mr/def ::bin-width-bucket+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}+ [:bin-width {:optional true} [:maybe [:or ::lib.schema.common/positive-number ::auto-bin]]]])++(mr/def ::binning+ [:multi {:decode/normalize lib.schema.common/normalize-map+ :dispatch (comp keyword :strategy)}+ [:default [:map {:closed true}+ [:strategy [:= {:decode/normalize lib.schema.common/normalize-keyword} :default]]]]+ [:num-bins [:map {:closed true}+ [:strategy [:= {:decode/normalize lib.schema.common/normalize-keyword} :num-bins]]+ [:num-bins pos-int?]]]+ [:bin-width [:map {:closed true}+ [:strategy [:= {:decode/normalize lib.schema.common/normalize-keyword} :bin-width]]+ [:bin-width ::lib.schema.common/positive-number]]]])++(mr/def ::column-with-binning+ [:merge+ ::column+ ::temporal-bucket+ ::bin-count-bucket+ ::bin-width-bucket+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::normalize-binning true}+ [:binning {:optional true} ::binning]]])++(mr/def ::breakout+ [:ref ::column-with-binning])++(mr/def ::order-by+ [:merge+ ::column-with-binning+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}+ [:direction {:optional true} [:maybe [:enum {:decode/normalize lib.schema.common/normalize-keyword} :asc :desc]]]]])++(mr/def ::literal-expression+ [:map {:closed true :decode/normalize {:compile query-map-decoder}}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :literal]]+ [:value [:ref ::literal/literal]]])++(mr/def ::operator+ keyword?)++(mr/def ::operator-expression+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:columns]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :operator]]+ [:operator ::operator]+ [:args {:default []} [:sequential [:ref ::expression]]]])++(mr/def ::expression+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case+ :dispatch (comp keyword :type)}+ [:column [:ref ::column]]+ [:literal [:ref ::literal-expression]]+ [:operator [:ref ::operator-expression]]])++(mr/def ::segment+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:name :table-id]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :segment]]+ [:id [:ref ::lib.schema.id/segment]]])++(mr/def ::measure+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:name :table-id :columns]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :measure]]+ [:id [:ref ::lib.schema.id/measure]]])++(mr/def ::metric+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:name :database-id :source-table-id :source-card-id :mapped-table-ids :columns :dimensions]}+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :metric]]+ [:id [:ref ::lib.schema.id/metric]]])++(mr/def ::aggregation+ [:or+ [:ref ::expression]+ [:ref ::measure]+ [:ref ::metric]])++(mr/def ::stage+ [:map {:closed true :decode/normalize {:compile query-map-decoder}+ ::sdk-metadata [:enabled]}+ [:source ::table-source]+ [:fields {:optional true} [:maybe [:sequential ::column]]]+ [:filters {:optional true} [:maybe [:sequential [:or ::expression ::segment]]]]+ [:aggregations {:optional true} [:maybe [:sequential ::aggregation]]]+ [:breakouts {:optional true} [:maybe [:sequential ::breakout]]]+ [:order-bys {:optional true} [:maybe [:sequential ::order-by]]]+ [:limit {:optional true} [:maybe number?]]])++(defn- strict-query-decoder [schema _options]+ (let [decode (mc/decoder schema (mtx/transformer+ (mtx/string-transformer)+ (mtx/json-transformer)+ (mtx/default-value-transformer)+ {:name :normalize}))+ validate (mr/validator schema)]+ (fn [value]+ ;; validate before the middleware silently drops unsupported fields+ (let [query (decode value)]+ (when-not (validate query)+ (throw (ex-info "Invalid data app query"+ {:status-code 400+ :errors (me/humanize (mr/explain schema query))})))+ query))))++(mr/def ::query-definition+ [:map {:closed true+ :decode/api {:compile strict-query-decoder}+ :decode/normalize {:compile query-map-decoder}}+ [:stages [:sequential {:min 1 :max 1} ::stage]]])diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/resources.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resources.cljnew file mode 100644index 00000000000..43e10fb3656--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/resources.clj@@ -0,0 +1,97 @@+(ns metabase-enterprise.data-apps.resources+ "Lifecycle for the permission group and resource collection owned by a data app."+ (:require+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.permissions :as data-app.permissions]+ [metabase.collections.core :as collection]+ [metabase.permissions.core :as perms]+ [metabase.request.core :as request]))++(set! *warn-on-reflection* true)++(defn- resource-name [app]+ (format "Data App: %s" (:name app)))++(defn- create-permission-group! [app]+ (let [group (data-apps.db/insert-permission-group! {:name (resource-name app)+ :is_data_app_group true})]+ (data-apps.db/update-data-app! (:id app) {:permission_group_id (:id group)})+ group))++(defn- permission-group! [app]+ (or (some->> (:permission_group_id app)+ (data-apps.db/permission-group))+ (create-permission-group! app)))++(defn- restore-trashed-collection!+ "Bring `collection` back out of the trash, with everything archived alongside it.++ Trashing it archives every copy inside, and an app is served from those copies,+ so a sync that left it there would report success over an app whose viewers see+ nothing. It goes back to the root, where the app created it: restoring in place+ fails outright when an ancestor is still in the trash.++ The restore runs with full permissions because a repository import reaches this+ from a scheduled task, where no user is bound; the collection is the app's own,+ so there is no one else's decision to weigh."+ [collection]+ (when (:archived collection)+ (request/as-admin+ (collection/archive-or-unarchive-collection! collection+ {:archived false, :parent_id nil}))))++(defn- apply-collection-permissions!+ "Gives the group read access. Preserves permission grants that are already correct."+ [group collection]+ (let [read-path (perms/collection-read-path collection)+ write-path (perms/collection-readwrite-path collection)+ permissions-by-group (group-by :group_id+ (data-apps.db/permissions-for-paths-excluding-group+ ["/" read-path write-path] (:id (perms/admin-group))))+ app-read-only? (= #{read-path} (set (map :object (get permissions-by-group (:id group)))))]+ ;; Remove write grants and access from other groups+ (doseq [group-id (keys permissions-by-group)+ :when (not (and (= group-id (:id group)) app-read-only?))]+ (perms/revoke-collection-permissions! group-id collection))+ (when-not app-read-only?+ (perms/grant-collection-read-permissions! group collection))))++(defn- apply-resource-permissions!+ [group collection]+ (data-app.permissions/reconcile-app-group-permissions! (:id group) (data-apps.db/non-router-database-ids))+ (apply-collection-permissions! group collection))++(defn- create-resource-collection! [app]+ (let [collection (data-apps.db/insert-resource-collection! {:name (resource-name app)+ :location "/"})]+ (data-apps.db/update-data-app! (:id app) {:resource_collection_id (:id collection)})+ collection))++(defn- resource-collection! [app]+ (or (some->> (:resource_collection_id app)+ (data-apps.db/resource-collection))+ (create-resource-collection! app)))++(defn ensure-resources!+ "Create or restore the server-owned permission resources for `app` and return their IDs."+ [app]+ (perms/with-global-permissions-lock+ (let [app (data-apps.db/non-blob-data-app (:id app))+ group (permission-group! app)+ collection (resource-collection! app)]+ (data-apps.db/update-permission-group! (:id group)+ {:name (resource-name app)})+ (data-apps.db/update-resource-collection! (:id collection)+ {:name (resource-name app)})+ (restore-trashed-collection! collection)+ (apply-resource-permissions! group collection)+ {:permission_group_id (:id group)+ :resource_collection_id (:id collection)})))++(defn delete-resources!+ "Delete the generated collection and permission group referenced by `app`."+ [{:keys [permission_group_id resource_collection_id]}]+ (when resource_collection_id+ (data-apps.db/delete-resource-collection! resource_collection_id))+ (when permission_group_id+ (data-apps.db/delete-permission-group! permission_group_id)))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj b/enterprise/backend/src/metabase_enterprise/data_apps/schema.cljindex 2dcbb2249f0..e93e7341708 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj@@ -20,7 +20,11 @@[:enabled :boolean][:created_at ms/TemporalInstant][:updated_at ms/TemporalInstant]- [:description [:maybe :string]]])+ [:description [:maybe :string]]+ [:resource_collection_id [:maybe ms/PositiveInt]]+ [:permission_group_id [:maybe ms/PositiveInt]]+ [:table_ids [:sequential ms/PositiveInt]]+ [:draft :boolean]])(mr/def ::data-app.update"What an update (or insert) of a DataApp accepts: every column of `:data_app` except `id`, all optional."@@ -37,4 +41,8 @@[:enabled {:optional true} [:maybe :boolean]][:created_at {:optional true} [:maybe ms/TemporalInstant]][:updated_at {:optional true} [:maybe ms/TemporalInstant]]- [:description {:optional true} [:maybe :string]]])+ [:description {:optional true} [:maybe :string]]+ [:resource_collection_id {:optional true} [:maybe ms/PositiveInt]]+ [:permission_group_id {:optional true} [:maybe ms/PositiveInt]]+ [:table_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]+ [:draft {:optional true} [:maybe :boolean]]])diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj b/enterprise/backend/src/metabase_enterprise/data_apps/sync.cljindex d92d9263cbc..3cb027029d1 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj@@ -15,6 +15,8 @@[clojure.string :as str][metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.resources :as data-app.resources]+ [metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting][metabase.util.i18n :refer [tru]]@@ -47,6 +49,31 @@(when-not (str/blank? url)url)))+(defn- create-draft!+ [slug]+ (let [app (t2/with-transaction [_conn]+ (when-not (data-apps.db/data-app-exists? slug)+ (data-apps.db/insert-data-app!+ {:name slug+ :display_name slug+ :bundle_path (format "%s/%s/%s" data-app.config/apps-dir slug data-app.config/config-file-name)+ :sync_error (tru "Bundle not synced yet.")+ :draft true}))+ (data-apps.db/non-blob-data-app-by-slug slug))]+ (data-app.resources/ensure-resources! app)))++(defn ensure-draft!+ "Create a data app draft when needed and ensure its permission resources.+ A later repository import fills the same row with the authoritative manifest+ and bundle."+ [slug]+ (try+ (create-draft! slug)+ (catch Throwable e+ (if (data-apps.db/data-app-exists? slug)+ (create-draft! slug)+ (throw e)))))+;;; ----------------------------------------------------- Discovery -----------------------------------------------------(defn- discover-app-configs@@ -72,7 +99,8 @@:when (some #{config-path} (list-dir dir))](try(if-let [content (read-file config-path)]- (let [{:keys [slug display_name description path allowed_hosts]} (data-app.config/parse-app-config (->bytes content) dir)]+ (let [{:keys [slug display_name description path allowed_hosts]}+ (data-app.config/parse-app-config (->bytes content) dir)]{:slug slug:display_name display_name:description description@@ -125,46 +153,79 @@(data-apps.db/update-data-app-by-slug! slug {:sync_error message})true)))-(defn- sync-app!- "Materialize one app. On bundle failure, the row's metadata is still upserted- with `sync_error` set so the app appears in the list with its failure; the- previously cached bundle (if any) is kept. `existing` is the app's pre-sync row- (or nil); returns true when this sync actually changed the app's content (a new- app, differing bundle/metadata, or a new failure) so callers can count changes."+(defn- prepare-app+ "Read one app's bundle before taking the permissions lock.+ A bundle failure preserves the cached bundle and prepares metadata with `sync_error` instead."[existing {:keys [slug display_name description bundle sha read-file allowed_hosts]}]+ (let [metadata {:display_name display_name+ :description description+ :allowed_hosts allowed_hosts+ :bundle_path bundle}]+ (try+ (let [content (read-file bundle)+ _ (when-not content+ (throw (ex-info (tru "Bundle file \"{0}\" not found in the repository." bundle)+ {:status-code 400})))+ ^bytes bytes (->bytes content)]+ (when (> (alength bytes) max-bundle-bytes)+ (throw (ex-info (tru "Bundle for \"{0}\" must be less than {1} MiB."+ slug (quot max-bundle-bytes (* 1024 1024)))+ {:status-code 413})))+ (let [fields (assoc metadata :bundle_hash (bytes-hash bytes))]+ {:fields (assoc fields :bundle bytes :last_synced_sha sha+ :sync_error nil :draft false)+ :changed? (app-content-changed? existing fields)}))+ (catch Throwable e+ (log/warnf "[data-app] failed to read bundle for app %s: %s" slug (ex-message e))+ {:fields (assoc metadata :sync_error (ex-message e))+ :changed? (or (nil? existing)+ (not= (:sync_error existing) (ex-message e))+ (app-metadata-changed? existing metadata))}))))++(defn- record-app-failure!+ "Record a failure after the app transaction rolls back. Keep existing content and resource links intact."+ [existing slug fields message](try- (let [content (read-file bundle)- _ (when-not content- (throw (ex-info (tru "Bundle file \"{0}\" not found in the repository." bundle)- {:status-code 400})))- ^bytes bytes (->bytes content)]- (when (> (alength bytes) max-bundle-bytes)- (throw (ex-info (tru "Bundle for \"{0}\" must be less than {1} MiB."- slug (quot max-bundle-bytes (* 1024 1024)))- {:status-code 413})))- (let [fields {:display_name display_name- :description description- :allowed_hosts allowed_hosts- :bundle_path bundle- :bundle_hash (bytes-hash bytes)}]- (upsert-by-name! slug (assoc fields- :bundle bytes- :last_synced_sha sha- :sync_error nil))- (app-content-changed? existing fields)))+ (t2/with-transaction [_conn]+ (if existing+ (mark-config-error! existing slug message)+ (when fields+ (upsert-by-name! slug (assoc (select-keys fields [:display_name :description :allowed_hosts :bundle_path])+ :sync_error message))+ true)))(catch Throwable e- (let [fields {:display_name display_name- :description description- :allowed_hosts allowed_hosts- :bundle_path bundle}]- (upsert-by-name! slug (assoc fields :sync_error (ex-message e)))+ (log/warnf "[data-app] could not record sync error for app %s: %s" slug (ex-message e))+ false)))++(defn- sync-app!+ "Commit one app and its permission resources together. Return whether its recorded state changed."+ [existing {:keys [slug config-error] :as cfg}]+ (let [{:keys [fields changed?]} (when-not config-error (prepare-app existing cfg))]+ (try+ (perms/with-global-permissions-lock+ (t2/with-transaction [_conn]+ (data-apps.db/publish-data-app-drafts! [slug])+ (if config-error+ (mark-config-error! existing slug config-error)+ (do+ (upsert-by-name! slug fields)+ (data-app.resources/ensure-resources! (data-apps.db/non-blob-data-app-by-slug slug))+ changed?))))+ (catch Throwable e(log/warnf "[data-app] failed to sync app %s: %s" slug (ex-message e))- ;; A failing app counts as a change when the failure is new, and also when- ;; the metadata above moved: the upsert stores an edited description even- ;; though the bundle still fails, so the pull summary has to admit it.- (or (nil? existing)- (not= (:sync_error existing) (ex-message e))- (app-metadata-changed? existing fields))))))+ (record-app-failure! existing slug fields (ex-message e))))))++(defn- prune-apps!+ "Delete all absent apps. Preserve the sync summary if pruning rolls back."+ [present-slugs]+ (try+ {:removed (t2/with-transaction [_conn]+ (if (seq present-slugs)+ (data-apps.db/delete-data-apps-not-named! present-slugs)+ (data-apps.db/delete-all-data-apps!)))}+ (catch Throwable e+ (log/warnf "[data-app] pruning failed: %s" (ex-message e))+ {:removed 0 :pruning-error (ex-message e)})))(defn import-from-snapshot!"Materialize data apps from a synced repo `snapshot`:@@ -174,11 +235,13 @@:sha <commit-sha-string>}Discovers every `data_apps/<dir>/data_app.yaml`, upserts a row per app, and prunes- rows whose directory is gone from the snapshot — all in one transaction. Returns+ rows whose directory is gone from the snapshot. Apps are synced independently, so+ one failing app cannot roll back the others. Returns`{:synced <n>, :changed <n>, :removed <n>, :sha <sha>, :config-errors [<msg> ...]}`,where `:changed` counts apps actually created/updated (a `last_synced_sha` bump onunchanged content does not count) and `:removed` counts apps dropped for no longer- being in the repo.+ being in the repo. If pruning fails, `:removed` is zero and `:pruning-error` contains+ the error message. Counts for committed app updates are preserved.Two apps can't collide on a slug here: a slug *is* an app's directory name (seethe config namespace), a repo can't hold two `data_apps/<slug>` directories, and@@ -195,28 +258,14 @@;; pre-sync rows, so we can tell a real change from a sha/timestamp bumpexisting (into {} (map (juxt :name identity))(data-apps.db/data-apps-sync-info))- {:keys [changed removed]}- (t2/with-transaction [_conn]- (let [changed (reduce (fn [n {:keys [slug config-error] :as cfg}]- (cond-> n- ;; A parse failure on an app that still exists marks- ;; that row failed rather than syncing it; everything- ;; else is materialized normally.- (if config-error- (mark-config-error! (get existing slug) slug config-error)- (sync-app! (get existing slug)- (assoc cfg :sha sha :read-file read-file)))- inc))- 0 results)- ;; `enabled` is deliberately not consulted — see the README's- ;; source-of-truth table. (`[:not-in #{}]` is invalid SQL, so delete-all.)- removed (if (seq present-slugs)- (data-apps.db/delete-data-apps-not-named! present-slugs)- (data-apps.db/delete-all-data-apps!))]- {:changed changed, :removed removed}))]+ changed (count (filter (fn [{:keys [slug] :as cfg}]+ (sync-app! (get existing slug) (assoc cfg :sha sha :read-file read-file)))+ results))+ {:keys [removed] :as pruning-result} (prune-apps! present-slugs)](log/infof "[data-app] synced sha=%s apps=%d changed=%d removed=%d errors=%d"sha (count good) changed removed (count errors))- {:synced (count good), :changed changed, :removed removed, :sha sha, :config-errors errors}))+ (merge {:synced (count good), :changed changed, :sha sha, :config-errors errors}+ pruning-result)))(defn sync-from-snapshot!"Entry point for the remote-sync import pipeline. Materializes data apps fromdiff --git a/enterprise/backend/src/metabase_enterprise/data_apps/user_access.clj b/enterprise/backend/src/metabase_enterprise/data_apps/user_access.cljnew file mode 100644index 00000000000..7a8afe3e97a--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/user_access.clj@@ -0,0 +1,84 @@+(ns metabase-enterprise.data-apps.user-access+ (:require+ [clojure.string :as str]+ [metabase-enterprise.data-apps.db :as data-apps.db]))++(set! *warn-on-reflection* true)++(defn- table-details+ [table-ids]+ (if (seq table-ids)+ (data-apps.db/table-details table-ids)+ []))++(defn- sandboxed-user-table-pairs+ [user-ids table-ids]+ (if (and (seq user-ids) (seq table-ids))+ (into #{}+ (map (juxt :user_id :table_id))+ (data-apps.db/sandboxed-user-table-access user-ids table-ids))+ #{}))++(defn- unrestricted-user-table-pairs+ [user-ids table-ids]+ (if (and (seq user-ids) (seq table-ids))+ (into #{}+ (map (juxt :user_id :table_id))+ (data-apps.db/unrestricted-user-table-access user-ids table-ids))+ #{}))++(defn- user-warning+ [user tables unrestricted-pairs sandboxed-pairs]+ (when-not (:is_superuser user)+ (let [user-id (:id user)+ has-access? (fn [{table-id :id}]+ (or (unrestricted-pairs [user-id table-id])+ (sandboxed-pairs [user-id table-id])))+ missing (remove has-access? tables)]+ (when (seq missing)+ {:user_id (:id user)+ :missing_tables (vec missing)}))))++(defn permission-warnings+ "Returns access warnings for the requested users who cannot access every table in `table-ids`.+ Superusers and users with unrestricted or sandboxed access to every table are omitted."+ [table-ids users]+ (if (seq table-ids)+ (let [tables (table-details table-ids)+ user-ids (map :id users)+ unrestricted-pairs (unrestricted-user-table-pairs user-ids table-ids)+ sandboxed-pairs (sandboxed-user-table-pairs user-ids table-ids)]+ (into [] (keep #(user-warning % tables unrestricted-pairs sandboxed-pairs)) users))+ []))++(defn- active-group-members+ [group-ids]+ (if (seq group-ids)+ (->> (data-apps.db/active-group-members group-ids)+ (remove #(str/ends-with? (:email %) "@api-key.invalid")))+ []))++(defn- group-has-permission-warning?+ [users table-ids unrestricted-pairs sandboxed-pairs]+ (let [tables (mapv (fn [table-id] {:id table-id}) table-ids)]+ (boolean (some #(user-warning % tables unrestricted-pairs sandboxed-pairs) users))))++(defn groups-with-permission-warnings+ "The permission group IDs for apps with an active member who cannot access every dependent table."+ [apps]+ (let [apps (filter #(and (:permission_group_id %) (seq (:table_ids %))) apps)+ group-ids (into #{} (map :permission_group_id) apps)+ memberships (active-group-members group-ids)+ group->users (group-by :group_id memberships)+ user-ids (into #{} (map :id) memberships)+ table-ids (into #{} (mapcat :table_ids) apps)+ unrestricted-pairs (unrestricted-user-table-pairs user-ids table-ids)+ sandboxed-pairs (sandboxed-user-table-pairs user-ids table-ids)]+ (into #{}+ (keep (fn [{:keys [permission_group_id table_ids]}]+ (when (group-has-permission-warning? (group->users permission_group_id)+ table_ids+ unrestricted-pairs+ sandboxed-pairs)+ permission_group_id)))+ apps)))diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.cljindex 009398ec139..d3a196c07e7 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj@@ -4,6 +4,7 @@[metabase-enterprise.advanced-permissions.common :as advanced-permissions.common][metabase-enterprise.impersonation.util-test :as advanced-perms.api.tu][metabase.driver :as driver]+ [metabase.permissions-rest.data-permissions.graph :as data-perms.graph][metabase.permissions.models.data-permissions :as data-perms][metabase.permissions.models.permissions :as perms][metabase.permissions.models.permissions-group :as perms-group]@@ -165,6 +166,43 @@(is (= :unrestricted (perm-value table-id-1)))(is (= :blocked (perm-value table-id-3)))))))))+(deftest new-view-data-permission-levels-block-data-app-groups-test+ (testing "data-app groups block newly-synced tables/databases even with no `:blocked` row (full manifest)"+ (mt/with-additional-premium-features #{:sandboxes :advanced-permissions}+ (mt/with-temp [:model/PermissionsGroup {app-group-id :id} {:is_data_app_group true}+ :model/PermissionsGroup {ctl-group-id :id} {} ; a normal, non-data-app group+ :model/DataApp _ {:name "perm-test-app" :display_name "Perm Test"+ :bundle_path "app/dist/index.js"+ :permission_group_id app-group-id}+ :model/Database {db-id :id} {}+ :model/Table {table-id-1 :id} {:db_id db-id :schema "PUBLIC"}+ :model/Table {table-id-2 :id} {:db_id db-id :schema "PUBLIC"}]+ ;; effective (coalesced) view-data — the control group inherits the DB-level value with no+ ;; table row of its own, so a raw-row check would see nil.+ (let [effective (fn [group-id table-id]+ (data-perms/table-permission-for-groups #{group-id} :perms/view-data db-id table-id))]+ (testing "a late table is blocked for the data-app group but not for a normal group"+ ;; a "full manifest" for both groups: all existing tables :unrestricted, so no `:blocked` row exists+ (doseq [group-id [app-group-id ctl-group-id]]+ (data-perms/set-table-permission! group-id table-id-1 :perms/view-data :unrestricted)+ (data-perms/set-table-permission! group-id table-id-2 :perms/view-data :unrestricted))+ (mt/with-temp [:model/Table {table-id-3 :id} {:db_id db-id :schema "PUBLIC"}]+ (is (= :blocked (effective app-group-id table-id-3))+ "the late table is blocked for the data-app group")+ (is (= :unrestricted (effective ctl-group-id table-id-3))+ "the same late table is NOT blocked for a normal group — the rule is scoped to app groups")+ (is (= :unrestricted (effective app-group-id table-id-1))+ "the app's declared tables stay unrestricted")+ ;; the going-granular apply keeps a clean per-table shape, so the permissions graph the+ ;; admin panel loads still builds (M1's db-level+table-override mix used to 500 it).+ (is (map? (data-perms.graph/api-graph))+ "the whole permissions graph still builds")))+ (testing "a newly-added database is blocked only for the data-app group"+ (let [levels (advanced-permissions.common/new-database-view-data-permission-levels+ [app-group-id ctl-group-id])]+ (is (= :blocked (levels app-group-id)) "blocked for the data-app group")+ (is (not= :blocked (levels ctl-group-id)) "not blocked for a normal group"))))))))+(deftest new-table-view-data-permission-levels-without-premium-features-test(testing "A newly-synced table fails CLOSED to :blocked for a sandboxed group even when premium features are unavailable (UXW-4927)";; This is the incident path: a table is discovered during sync while the sandboxes /diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.cljindex b60c6a084eb..d78a438eb01 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -2,8 +2,16 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [metabase-enterprise.data-apps.query-definition :as query-definition]+ [metabase-enterprise.data-apps.resources :as data-app.resources][metabase-enterprise.data-apps.sync :as data-app.sync]+ [metabase-enterprise.data-apps.user-access :as data-app.user-access][metabase-enterprise.remote-sync.source :as source]+ [metabase.actions.core :as actions]+ [metabase.api.macros.defendpoint.closed-schemas :as closed-schemas]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.permissions.core :as perms][metabase.test :as mt][toucan2.core :as t2]))@@ -48,45 +56,667 @@;;; ---------------------------------------------- Permissions -----------------------------------------------(deftest non-superuser-can-view-and-list-but-not-manage-test+(deftest data-app-access-requires-read-access-to-its-resource-collection-test;; global mode so the `:data-apps-preview` premium feature is visible to the real-HTTP;; `user-real-request` calls below (which run on Jetty threads that don't inherit;; a thread-local `binding`).(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](create-app!)- (testing "a non-superuser can view (open) a data app"- (is (= [{:name "demo" :display_name "Demo"}]- (mt/user-http-request :rasta :get 200 "apps")))- (is (= {:name "demo" :display_name "Demo"}- (mt/user-http-request :rasta :get 200 "apps/demo")))- (is (str/includes?- (str (mt/user-real-request :rasta :get 200 "apps/demo/bundle"))- "BUNDLE")))- (testing "but is still forbidden from managing data apps"+ (let [app (t2/select-one :model/DataApp :name "demo")+ {:keys [permission_group_id]} (data-app.resources/ensure-resources! app)]+ (testing "a non-member cannot open a data app or load its bundle"+ (is (= [{:name "demo" :display_name "Demo"}]+ (mt/user-http-request :rasta :get 200 "apps")))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "apps/demo")))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "apps/demo/bundle"))))+ (testing "a member can open a data app"+ (perms/add-user-to-group! (mt/user->id :rasta) permission_group_id)+ (is (= {:name "demo" :display_name "Demo"}+ (mt/user-http-request :rasta :get 200 "apps/demo")))+ (is (str/includes?+ (str (mt/user-real-request :rasta :get 200 "apps/demo/bundle"))+ "BUNDLE"))))+ (testing "a non-superuser is still forbidden from managing data apps"(is (= "You don't have permissions to do that."(mt/user-http-request :rasta :get 403 "apps/repo-status")))(is (= "You don't have permissions to do that."(mt/user-http-request :rasta :put 403 "apps/demo" {:enabled false}))))))))+(deftest data-app-without-a-resource-collection-is-not-published-test+ (mt/test-helpers-set-global-values!+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (is (nil? (t2/select-one-fn :resource_collection_id :model/DataApp :name "demo"))+ "precondition: the app has no resource collection")+ (testing "an app with no resource collection is not published: neither its metadata nor its+ bundle is served — to anyone — and a 409 lets the client show a \"not published\" screen"+ (doseq [user [:rasta :crowberto]]+ (is (= "This data app has not been published yet."+ (mt/user-http-request user :get 409 "apps/demo")))+ (is (= "This data app has not been published yet."+ (mt/user-http-request user :get 409 "apps/demo/bundle")))))))))+(deftest superuser-can-manage-and-view-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](create-app!)+ (let [app (t2/select-one :model/DataApp :name "demo")+ {:keys [resource_collection_id]} (data-app.resources/ensure-resources! app)]+ (is (not (some #(= resource_collection_id (:id %))+ (mt/user-http-request :rasta :get 200 "collection")))))(testing "a superuser can list, read metadata, and serve the bundle"(is (=? [{:name "demo" :display_name "Demo"}](mt/user-http-request :crowberto :get 200 "apps")))- (is (=? {:name "demo"}+ (is (=? {:name "demo"+ :resource_collection_id pos-int?+ :permission_group_id pos-int?}(mt/user-http-request :crowberto :get 200 "apps/demo")))(is (str/includes?(str (mt/user-real-request :crowberto :get 200 "apps/demo/bundle"))"BUNDLE")))))))-(deftest list-available-apps-test+(deftest deleting-a-data-app-removes-its-permission-group-test+ (testing "removing a data app through the admin API — clearing out one left behind after its+ repo was disconnected or a remote-sync branch switch — deletes its server-managed+ permission group and resource collection along with the row"+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [app (t2/select-one :model/DataApp :name "demo")+ {:keys [permission_group_id resource_collection_id]}+ (data-app.resources/ensure-resources! app)]+ (is (t2/exists? :model/PermissionsGroup :id permission_group_id)+ "precondition: the app has a permission group")+ (mt/user-http-request :crowberto :delete 204 "apps/demo")+ (is (not (t2/exists? :model/DataApp :id (:id app)))+ "the app row is gone")+ (is (not (t2/exists? :model/PermissionsGroup :id permission_group_id))+ "its permission group is removed too")+ (is (not (t2/exists? :model/Collection :id resource_collection_id))+ "and so is its resource collection"))))))++(deftest ^:parallel query-definition-request-schema-is-closed-test+ (is (empty? (closed-schemas/findings ::query-definition/query-definition))))++(deftest superuser-can-resolve-a-query-definition-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues) :name "Venues"+ :fields {:price {:type "column" :name "PRICE" :jsType "number"}}+ :segments {} :measures {}+ :columns [{:name "PRICE" :jsType "number"}]}+ :orderBys [{:type "column" :name "PRICE" :tableId (mt/id :venues)+ :fieldId (mt/id :venues :price) :baseType "type/Integer"+ :effectiveType "type/Integer" :defaultTemporalBucket nil+ :direction "asc" :jsType "number" :description "Price tier"}]+ :filters [{:type "operator" :operator ">"+ :args [{:type "column" :name "PRICE" :description "Price tier"}+ {:type "literal" :value 2}]}]+ :limit 5}]})]+ (is (= (mt/id) (:database_id response)))+ (is (=? {:dataset_query {:lib/type "mbql/query"+ :database (mt/id)+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table (mt/id :venues)+ :filters [[">" {} ["field" {} (mt/id :venues :price)] 2]]+ :order-by [["asc" {} ["field" {} (mt/id :venues :price)]]]+ :limit 5}]}}+ response))))))++(deftest query-definition-normalizes-nested-binning-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (doseq [[field-name field-id binning]+ [["PRICE" (mt/id :venues :price) {:strategy "num-bins" :num-bins 10}]+ ["LATITUDE" (mt/id :venues :latitude) {:strategy "bin-width" :bin-width 20.0}]]]+ (let [column {:type "column" :name field-name :description "A numeric field" :binning binning}+ response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues)}+ :aggregations [{:type "operator" :operator "count" :args []}]+ :breakouts [column]+ :orderBys [(assoc column :direction "asc")]}]})]+ (is (=? {:dataset_query+ {:stages [{:breakout [["field" {:binning binning} field-id]]+ :order-by [["asc" {} ["field" {:binning binning} field-id]]]}]}}+ response)))))))++(deftest query-definition-rejects-unknown-nested-binning-options-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [response (mt/user-http-request+ :crowberto :post 400 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues)}+ :breakouts [{:type "column" :name "PRICE"+ :binning {:strategy "num-bins" :num-bins 10 :unexpected true}}]}]})]+ (is (= {:errors {:stages [{:breakouts [{:binning {:unexpected ["disallowed key"]}}]}]}}+ response))))))++(deftest query-definition-resolves-an-aggregation-with-sdk-metadata-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues)}+ :aggregations [{:type "operator"+ :operator "count"+ :args []+ :columns [{:name "count"+ :displayName "Count"+ :jsType "number"}]}]}]})]+ (is (=? {:dataset_query {:stages [{:aggregation [["count" {}]]}]}}+ response))))))++(deftest query-definition-ignores-the-enabled-option-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [table-id (mt/id :venues)+ response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id table-id}+ :enabled false}]})]+ (is (=? {:dataset_query {:stages [{:source-table table-id}]}}+ response))))))++(deftest query-definition-rejects-unsupported-fields-over-http-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (doseq [[path expected-errors]+ [[[:unexpected] {:unexpected ["disallowed key"]}]+ [[:stages 0 :joins] {:stages [{:joins ["disallowed key"]}]}]+ [[:stages 0 :expressions] {:stages [{:expressions ["disallowed key"]}]}]+ [[:stages 0 :source :unexpected] {:stages [{:source {:unexpected ["disallowed key"]}}]}]+ [[:stages 0 :fields 0 :unexpected] {:stages [{:fields [{:unexpected ["disallowed key"]}]}]}]]]+ (testing (str "Reject unsupported fields at " path)+ (let [query {:stages [{:source {:type "table" :id (mt/id :venues)}+ :fields [{:type "column" :name "PRICE"}]}]}+ response (mt/user-http-request :crowberto :post 400 "apps/demo/query"+ (assoc-in query path []))]+ (is (= {:errors expected-errors} response))))))))++(deftest query-definition-resolves-a-metric-with-sdk-metadata-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [metadata-provider (mt/metadata-provider)+ venue-count-query (-> (lib/query metadata-provider+ (lib.metadata/table metadata-provider (mt/id :venues)))+ (lib/aggregate (lib/count)))]+ (mt/with-temp [:model/Card {metric-id :id}+ {:name "Venue count"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query venue-count-query}]+ (let [response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues)}+ :aggregations [{:type "metric" :id metric-id :name "Venue count"+ :databaseId (mt/id) :sourceTableId (mt/id :venues)+ :sourceCardId nil :mappedTableIds [(mt/id :venues)]+ :columns {:count {:type "column" :name "count" :jsType "number"}}+ :dimensions {}}]}]})]+ (is (= [metric-id] (mapv :id (:metrics response))))))))))++(deftest rejects-metrics-whose-definition-reads-another-card-test+ (testing "sync copies a referenced metric but rewrites nothing inside the copy, so a metric that+ itself reads another card would publish and then fail for viewers without access to that+ card's collection -- resolving the query has to refuse it"+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [metadata-provider (mt/metadata-provider)+ venues (lib.metadata/table metadata-provider (mt/id :venues))+ venue-count-query (-> (lib/query metadata-provider venues)+ (lib/aggregate (lib/count)))+ orders-query (lib/query metadata-provider+ (lib.metadata/table metadata-provider (mt/id :orders)))+ app-query (fn [metric-id]+ {:stages [{:source {:type "table" :id (mt/id :venues)}+ :aggregations [{:type "metric" :id metric-id}]}]})]+ (mt/with-temp [:model/Card {inner-metric-id :id}+ {:name "Venue count"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query venue-count-query}+ :model/Card {question-id :id}+ {:name "Orders"+ :type :question+ :database_id (mt/id)+ :table_id (mt/id :orders)+ :dataset_query orders-query}]+ (let [;; built after the cards exist, so the provider can resolve them+ provider (mt/metadata-provider)+ nested-query (lib/test-query provider (app-query inner-metric-id))+ question-sourced-query (lib/query provider (lib.metadata/card provider question-id))]+ (testing "the inner metric on its own resolves"+ (is (= [inner-metric-id]+ (mapv :id (:metrics (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ (app-query inner-metric-id)))))))+ (mt/with-temp [:model/Card {nested-metric-id :id}+ {:name "Nested venue count"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query nested-query}+ :model/Card {question-metric-id :id}+ {:name "Orders question metric"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :orders)+ :dataset_query question-sourced-query}]+ (testing "a metric that references another metric is refused"+ (is (= (str "Data app queries cannot use metrics that reference other saved questions"+ " or metrics: Nested venue count")+ (mt/user-http-request+ :crowberto :post 400 "apps/demo/query"+ (app-query nested-metric-id)))))+ (testing "so is one built on a saved question, which sync does not copy either"+ (is (= (str "Data app queries cannot use metrics that reference other saved questions"+ " or metrics: Orders question metric")+ (mt/user-http-request+ :crowberto :post 400 "apps/demo/query"+ (app-query question-metric-id)))))))))))))++(deftest resolved-query-includes-implicitly-joined-tables-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [orders-id (mt/id :orders)+ products-id (mt/id :products)+ product-id-field-id (mt/id :orders :product_id)+ response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query"+ {:stages [{:source {:type "table" :id orders-id}+ :breakouts [{:type "column"+ :name "CATEGORY"+ :source-field-id product-id-field-id}]}]})]+ (is (= #{orders-id products-id}+ (set (:table_ids response))))))))++(deftest saved-query-table-dependencies-include-implicitly-joined-tables-test+ (testing "sync copies models, actions and metrics whose queries never pass through /query, and the+ table an implicit join reaches is named nowhere in such a query -- only this lookup finds it"+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [metadata-provider (mt/metadata-provider)+ orders-query (lib/query metadata-provider+ (lib.metadata/table metadata-provider (mt/id :orders)))+ category (->> (lib/breakoutable-columns orders-query)+ (filter #(= (:id %) (mt/id :products :category)))+ first)+ model-query (lib/breakout orders-query category)]+ (mt/with-temp [:model/Card {model-id :id}+ {:name "Orders by category"+ :type :model+ :database_id (mt/id)+ :table_id (mt/id :orders)+ :dataset_query model-query}]+ (let [dataset-query (t2/select-one-fn :dataset_query :model/Card :id model-id)+ response (mt/user-http-request+ :crowberto :post 200 "apps/demo/query-table-dependencies"+ {:dataset_queries [dataset-query]})]+ (is (= #{(mt/id :orders) (mt/id :products)}+ (set (:table_ids response)))))))))))++(deftest superuser-can-store-table-dependencies-test(mt/with-premium-features #{:data-apps-preview}(mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (let [table-ids [(mt/id :venues) (mt/id :orders)]]+ (is (= (sort table-ids)+ (:table_ids+ (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"+ {:table_ids (reverse table-ids)}))))+ (is (= (sort table-ids)+ (t2/select-one-fn :table_ids :model/DataApp :name "demo")))+ (is (= []+ (:table_ids+ (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"+ {:table_ids []}))))))))++(deftest non-superuser-cannot-store-table-dependencies-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 "apps/demo/table-dependencies"+ {:table_ids [(mt/id :venues)]}))))))++(deftest table-dependencies-validates-table-ids-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (is (= "One or more tables do not exist."+ (mt/user-http-request :crowberto :put 400 "apps/demo/table-dependencies"+ {:table_ids [Integer/MAX_VALUE]})))+ (is (= [] (t2/select-one-fn :table_ids :model/DataApp :name "demo"))))))++(deftest user-permission-warnings-test+ (mt/with-premium-features #{:data-apps-preview :advanced-permissions :sandboxes}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Sandbox]+ (mt/with-no-data-perms-for-all-users!+ (create-app!)+ (let [{app-group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))+ allowed-table-id (mt/id :venues)+ missing-table-id (mt/id :orders)+ user-id (mt/user->id :rasta)]+ (testing "an app with no synchronized dependencies has no warnings"+ (is (= []+ (mt/user-http-request :crowberto :post 200 "apps/demo/user-permission-warnings"+ {:user_ids [user-id]}))))+ (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"+ {:table_ids [allowed-table-id missing-table-id]})+ (perms/add-user-to-group! user-id app-group-id)+ (perms/set-table-permission! app-group-id+ missing-table-id+ :perms/view-data+ :unrestricted)+ (perms/set-table-permission! (perms/all-users-group)+ allowed-table-id+ :perms/view-data+ :unrestricted)+ (testing "returns only users who lack access from a non-data-app group"+ (is (=? [{:user_id user-id+ :missing_tables [{:id missing-table-id+ :name "Orders"+ :database_id (mt/id)}]}]+ (mt/user-http-request :crowberto :post 200 "apps/demo/user-permission-warnings"+ {:user_ids [user-id (mt/user->id :crowberto)]}))))+ (testing "unrestricted access from another group is adequate"+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}]+ (perms/add-user-to-group! user-id group-id)+ (perms/set-table-permission! group-id+ missing-table-id+ :perms/view-data+ :unrestricted)+ (is (= []+ (mt/user-http-request :crowberto :post 200 "apps/demo/user-permission-warnings"+ {:user_ids [user-id]})))))+ (testing "sandboxed access is adequate"+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/Sandbox _ {:group_id group-id :table_id missing-table-id}]+ (perms/add-user-to-group! user-id group-id)+ (is (= []+ (mt/user-http-request :crowberto :post 200 "apps/demo/user-permission-warnings"+ {:user_ids [user-id]}))))))))))++(deftest permission-warning-lookups-are-batched-test+ (mt/with-premium-features #{:data-apps-preview :advanced-permissions :sandboxes}+ (mt/with-no-data-perms-for-all-users!+ (let [table-ids [(mt/id :venues) (mt/id :orders)]+ users [{:id (mt/user->id :rasta) :is_superuser false}+ {:id (mt/user->id :lucky) :is_superuser false}]+ query-count (fn [users]+ (t2/with-call-count [call-count]+ (data-app.user-access/permission-warnings table-ids users)+ (call-count)))]+ (is (= 3 (query-count users)))+ (is (= (query-count (take 1 users))+ (query-count users))+ "permission warning query count must not grow with the number of users")))))++(deftest data-app-list-warning-lookups-are-batched-test+ (mt/with-premium-features #{:data-apps-preview :advanced-permissions :sandboxes}+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/PermissionsGroup {first-group-id :id} {}+ :model/PermissionsGroup {second-group-id :id} {}]+ (perms/add-user-to-group! (mt/user->id :rasta) first-group-id)+ (perms/add-user-to-group! (mt/user->id :lucky) second-group-id)+ (let [apps [{:permission_group_id first-group-id+ :table_ids [(mt/id :venues)]}+ {:permission_group_id second-group-id+ :table_ids [(mt/id :orders)]}]+ warning-groups #(t2/with-call-count [call-count]+ (let [result (data-app.user-access/groups-with-permission-warnings %)]+ {:result result :query-count (call-count)}))+ one-app (warning-groups (take 1 apps))+ two-apps (warning-groups apps)]+ (is (= #{first-group-id} (:result one-app)))+ (is (= #{first-group-id second-group-id} (:result two-apps)))+ (is (= 3 (:query-count one-app) (:query-count two-apps))+ "warning status query count must not grow with the number of apps"))))))++(deftest data-app-list-includes-user-permission-warning-status-test+ (mt/with-premium-features #{:data-apps-preview :advanced-permissions :sandboxes}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-no-data-perms-for-all-users!+ (create-app!)+ (let [{app-group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))+ table-id (mt/id :orders)+ user-id (mt/user->id :rasta)+ warning? #(->> (mt/user-http-request :crowberto :get 200 "apps")+ (filter (comp #{"demo"} :name))+ first+ :has_user_permission_warnings)]+ (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"+ {:table_ids [table-id]})+ (perms/add-user-to-group! user-id app-group-id)+ (is (true? (warning?)))+ (perms/set-table-permission! (perms/all-users-group)+ table-id+ :perms/view-data+ :unrestricted)+ (is (false? (warning?))))))))++(deftest data-app-list-warning-status-ignores-deactivated-members-test+ (mt/with-premium-features #{:data-apps-preview :advanced-permissions :sandboxes}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-no-data-perms-for-all-users!+ (create-app!)+ (let [{app-group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))+ table-id (mt/id :orders)]+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]+ (perms/add-user-to-group! user-id app-group-id)+ (t2/update! :model/User :id user-id {:is_active false})+ (mt/user-http-request :crowberto :put 200 "apps/demo/table-dependencies"+ {:table_ids [table-id]})+ (is (false? (->> (mt/user-http-request :crowberto :get 200 "apps")+ (filter (comp #{"demo"} :name))+ first+ :has_user_permission_warnings)))))))))++(deftest deactivated-users-cannot-be-added-to-data-apps-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [{app-group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))]+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"+ :is_active false}]+ (is (= "Deactivated users cannot be added to data apps."+ (mt/user-http-request :crowberto :post 400 "permissions/membership"+ {:group_id app-group-id :user_id user-id})))+ (is (= "Deactivated users cannot be added to data apps."+ (mt/user-http-request :crowberto :post 400 "apps/demo/user-permission-warnings"+ {:user_ids [user-id]}))))))))++(deftest user-permission-warnings-validates-users-test+ (mt/with-premium-features #{:data-apps-preview :tenants}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (testing "unknown users"+ (mt/user-http-request :crowberto :post 404 "apps/demo/user-permission-warnings"+ {:user_ids [Integer/MAX_VALUE]}))+ (testing "tenant users"+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Data app tenant" :slug "data-app-tenant"}+ :model/User {user-id :id} {:email "[email protected]"+ :tenant_id tenant-id}]+ (is (= "Tenant users cannot be added to data apps."+ (mt/user-http-request :crowberto :post 400 "apps/demo/user-permission-warnings"+ {:user_ids [user-id]}))))))))++(deftest non-superuser-cannot-read-user-permission-warnings-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "apps/demo/user-permission-warnings"+ {:user_ids [(mt/user->id :rasta)]}))))))++(deftest data-app-write-endpoints-require-feature-token-test+ (mt/with-premium-features #{}+ (mt/user-http-request :crowberto :put 402 "apps/demo/table-dependencies"+ {:table_ids []})+ (mt/user-http-request :crowberto :post 402 "apps/demo/user-permission-warnings"+ {:user_ids [(mt/user->id :rasta)]})+ (mt/user-http-request :crowberto :post 402 "apps/demo/draft")))++(deftest data-app-membership-additions-require-feature-token-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [{group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))]+ (mt/with-premium-features #{}+ (mt/user-http-request :crowberto :post 402 "permissions/membership"+ {:group_id group-id :user_id (mt/user->id :lucky)})+ (is (not (t2/exists? :model/PermissionsGroupMembership :group_id group-id)))))))++(deftest data-app-membership-removal-without-feature-token-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [{group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))+ user-id (mt/user->id :rasta)]+ (perms/add-user-to-group! user-id group-id)+ (let [membership-id (t2/select-one-pk :model/PermissionsGroupMembership+ :group_id group-id :user_id user-id)+ endpoint (format "permissions/membership/%d" membership-id)]+ (mt/with-premium-features #{}+ (mt/user-http-request :rasta :delete 403 endpoint)+ (is (t2/exists? :model/PermissionsGroupMembership :id membership-id))+ ;; memberships and collection grants still remain after the token expires,+ ;; so admins must still be able to remove a member without the feature token.+ (mt/user-http-request :crowberto :delete 204 endpoint)+ (is (not (t2/exists? :model/PermissionsGroupMembership :id membership-id))))))))++(deftest data-app-membership-clearing-without-feature-token-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (let [{group-id :permission_group_id}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))+ endpoint (format "permissions/membership/%d/clear" group-id)]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (perms/add-user-to-group! (mt/user->id :lucky) group-id)+ (mt/with-premium-features #{}+ (mt/user-http-request :rasta :put 403 endpoint)+ (is (= 2 (t2/count :model/PermissionsGroupMembership :group_id group-id)))+ ;; memberships and collection grants still remain after the token expires,+ ;; so admins must still be able to remove all members without the feature token.+ (mt/user-http-request :crowberto :put 204 endpoint)+ (is (not (t2/exists? :model/PermissionsGroupMembership :group_id group-id)))))))++(deftest query-definition-must-use-a-table-source-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (is (some? (mt/user-http-request :crowberto :post 400 "apps/demo/query"+ {:stages [{:source {:type "card" :id 1}}]}))))))++(deftest query-definition-source-must-be-valid-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (create-app!)+ (is (some? (mt/user-http-request :crowberto :post 400 "apps/demo/query"+ {:stages [{:source {:type 1 :id (mt/id :venues)}}]}))))))++(deftest non-superuser-cannot-resolve-a-query-definition-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "apps/demo/query"+ {:stages [{:source {:type "table" :id (mt/id :venues)}}]}))))))++(deftest superuser-can-create-or-reuse-a-data-app-draft-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [first-response (mt/user-http-request :crowberto :post 200 "apps/draft-app/draft")+ second-response (mt/user-http-request :crowberto :post 200 "apps/draft-app/draft")]+ (is (=? {:name "draft-app"+ :resource_collection_id pos-int?+ :permission_group_id pos-int?}+ first-response))+ (is (= (select-keys first-response [:resource_collection_id :permission_group_id])+ (select-keys second-response [:resource_collection_id :permission_group_id])))+ (is (=? {:bundle nil :draft true}+ (t2/select-one :model/DataApp :name "draft-app")))))))++(deftest non-superuser-cannot-create-a-data-app-draft-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "apps/draft-app/draft")))+ (is (not (t2/exists? :model/DataApp :name "draft-app"))))))++(deftest data-app-draft-must-have-a-valid-slug-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp]+ (is (= "Data app draft slugs must use lowercase letters, numbers, and dashes."+ (mt/user-http-request :crowberto :post 400 "apps/Draft/draft")))+ (is (not (t2/exists? :model/DataApp :name "Draft"))))))++(deftest data-app-group-reaches-only-copied-actions-test+ (testing "an action is reachable exactly when its model lives in the data app collection"+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-non-admin-groups-no-root-collection-perms+ ;; Its own slug: the `Data App: <slug>` group outlives other tests in+ ;; this namespace, so sharing "demo" collides on the group name.+ (let [{:keys [permission_group_id resource_collection_id]}+ (data-app.sync/ensure-draft! "action-perms-app")+ metadata-provider (mt/metadata-provider)+ venues (lib.metadata/table metadata-provider (mt/id :venues))]+ (perms/add-user-to-group! (mt/user->id :rasta) permission_group_id)+ (mt/with-temp+ [:model/Collection {source-collection-id :id} {}+ :model/Card {source-model-id :id} {:type :model+ :collection_id source-collection-id+ :dataset_query (lib/query metadata-provider venues)}+ ;; What `npm run sync-resources` produces: a copy of the model in the+ ;; app's own collection, carrying its own copy of the action.+ :model/Card {copied-model-id :id} {:type :model+ :collection_id resource_collection_id+ :dataset_query (lib/query metadata-provider venues)}]+ (let [action {:name "Create Venue", :type :implicit, :kind :row/create}+ source-id (actions/insert! (assoc action :model_id source-model-id))+ copied-id (actions/insert! (assoc action :model_id copied-model-id))]+ (testing "the app's group reads the action copied into its 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 "copying does not widen access to the source model"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 (str "card/" source-model-id)))))+ (testing "a superuser still reads both"+ (is (=? {:id source-id}+ (mt/user-http-request :crowberto :get 200 (str "action/" source-id)))))))))))))++(deftest list-available-apps-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](t2/insert! :model/DataApp :name "ready" :display_name "Ready" :bundle_path "data_apps/ready/index.js")(t2/insert! :model/DataApp :name "disabled" :display_name "Disabled" :bundle_path "data_apps/disabled/index.js":enabled false)@@ -97,7 +727,7 @@(deftest bundle-includes-allowed-hosts-header-test(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](t2/insert! :model/DataApp:name "demo":display_name "Demo"@@ -105,6 +735,8 @@:bundle (.getBytes "BUNDLE" "UTF-8"):bundle_hash "abc123":allowed_hosts ["https://api.example.com"])+ ;; publish the app so its bundle is served (crowberto, as a superuser, can read the collection)+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))(testing "the bundle response carries the app's allowed_hosts as a JSON header"(let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")](is (= "[\"https://api.example.com\"]"@@ -117,7 +749,7 @@(deftest list-includes-allowed-hosts-test(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](t2/insert! :model/DataApp:name "withhosts" :display_name "With":bundle_path "data_apps/withhosts/index.js"@@ -136,7 +768,7 @@;;; ----------------------------------------------------- Sync -----------------------------------------------------(deftest import-materializes-apps-test- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [result (data-app.sync/import-from-snapshot!(snapshot (merge (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "SALES-BUNDLE"})(app-files "ops" {:name "Ops" :path "dist/app.js" :bundle "OPS-BUNDLE"}))))]@@ -151,7 +783,7 @@(is (nil? (:sync_error sales)))))))(deftest import-stores-allowed-hosts-test- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](testing "allowed_hosts from data_app.yaml are persisted on the row"(data-app.sync/import-from-snapshot!(snapshot (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "B"@@ -164,7 +796,7 @@(is (= [] (:allowed_hosts (t2/select-one :model/DataApp :name "sales")))))))(deftest import-prunes-apps-absent-from-snapshot-test- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (merge (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})(app-files "gone" {:name "Gone" :path "index.js" :bundle "GONE"}))))@@ -181,20 +813,31 @@(deftest delete-endpoint-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](create-app!)- (testing "a non-superuser cannot remove an app"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :delete 403 "apps/demo")))- (is (t2/exists? :model/DataApp :name "demo")))- (testing "a superuser removes the app"- (is (nil? (mt/user-http-request :crowberto :delete 204 "apps/demo")))- (is (not (t2/exists? :model/DataApp :name "demo"))))- (testing "removing a non-existent app 404s"- (mt/user-http-request :crowberto :delete 404 "apps/missing"))))))+ (let [{:keys [resource_collection_id permission_group_id]}+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))]+ (mt/with-temp [:model/Card {card-id :id} {:collection_id resource_collection_id}+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)+ :group_id permission_group_id}]+ (testing "a non-superuser cannot remove an app"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :delete 403 "apps/demo")))+ (is (t2/exists? :model/DataApp :name "demo")))+ ;; each data app owns a permission group and a collection+ ;; containing saved questions and models+ (testing "a superuser removes the app, its resources, and their contents"+ (is (nil? (mt/user-http-request :crowberto :delete 204 "apps/demo")))+ (is (not (t2/exists? :model/DataApp :name "demo")))+ (is (not (t2/exists? :model/Collection :id resource_collection_id)))+ (is (not (t2/exists? :model/Card :id card-id)))+ (is (not (t2/exists? :model/PermissionsGroup :id permission_group_id)))+ (is (not (t2/exists? :model/PermissionsGroupMembership :group_id permission_group_id))))+ (testing "removing a non-existent app 404s"+ (mt/user-http-request :crowberto :delete 404 "apps/missing"))))))))(deftest import-preserves-enabled-across-syncs-test- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "a" {:name "A" :path "index.js" :bundle "V1"})))(t2/update! :model/DataApp :name "a" {:enabled false})@@ -207,7 +850,7 @@(deftest import-per-app-error-test(testing "a missing bundle file fails just that app, not the whole import"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (merge (app-files "good" {:name "Good" :path "index.js" :bundle "GOOD"});; "bad" declares a path that doesn't exist@@ -222,7 +865,7 @@(deftest import-serves-each-app-from-its-directory-test(testing "the directory an app lives in is the slug it's served at — two apps can't collide on one"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (merge (app-files "one" {:name "One" :path "a.js" :bundle "A"})(app-files "two" {:name "Two" :path "b.js" :bundle "B"}))))@@ -230,7 +873,7 @@(deftest import-isolates-bad-config-test(testing "a malformed data_app.yaml is isolated: sibling apps in the same repo still sync and are not pruned, the bad one is reported"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "existing" {:name "Existing" :path "i.js" :bundle "E"})));; The repo still holds "existing" and adds "good", alongside a broken "bad".@@ -247,13 +890,13 @@(deftest sync-from-snapshot!-never-throws-test(mt/with-premium-features #{:data-apps-preview}(testing "a malformed data_app.yaml is isolated into :config-errors; the app just doesn't appear, the sync doesn't throw"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [result (data-app.sync/sync-from-snapshot!(snapshot {"data_apps/x/data_app.yaml" "name: [unterminated"}))](is (seq (:config-errors result)))(is (empty? (t2/select-fn-set :name :model/DataApp))))))(testing "a clean sync materializes the app with no config errors"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [result (data-app.sync/sync-from-snapshot!(snapshot (app-files "a" {:name "A" :path "index.js" :bundle "A"})))](is (empty? (:config-errors result)))@@ -264,7 +907,7 @@(deftest list-and-bundle-endpoints-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "demo" {:name "Demo app" :path "dist/index.js" :bundle "DEMOBUNDLE"})))(testing "GET / lists the synced apps"@@ -290,7 +933,7 @@(deftest enable-disable-endpoint-test(mt/test-helpers-set-global-values!(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "demo" {:name "Demo" :path "index.js" :bundle "BUNDLE"})))(testing "PUT /:slug can disable an app"@@ -333,7 +976,7 @@;; routed as a data app named "sandbox-host" and 404.(testing "the route is not shadowed by the /:slug route"(mt/with-premium-features #{:data-apps-preview}- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](create-app!)(is (= 200 (:status (mt/user-http-request-full-response:crowberto :get 200 "apps/sandbox-host"))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/config_test.cljindex 37878e5e884..c71e8aaf21d 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj@@ -101,8 +101,9 @@ path: ./dist/index.js"))))(is (thrown-with-msg? clojure.lang.ExceptionInfo #"must not contain"(parse "name: X\npath: dist/../../escape.js"))))(testing "a directory whose name collides with an API sub-route is rejected"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"reserved slug"- (parse "name: X\npath: dist/index.js" "data_apps/repo-status")))))+ (doseq [slug ["repo-status" "sandbox-host"]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"reserved slug"+ (parse "name: X\npath: dist/index.js" (str "data_apps/" slug)))))))(deftest parse-errors-carry-400-test(trydiff --git a/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.cljnew file mode 100644index 00000000000..d0c3361c78f--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.clj@@ -0,0 +1,176 @@+(ns metabase-enterprise.data-apps.permissions-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.advanced-permissions.models.permissions.block-permissions :as block-perms]+ [metabase-enterprise.data-apps.permissions :as data-app.permissions]+ [metabase-enterprise.data-apps.resources :as data-app.resources]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.permissions-rest.data-permissions.graph :as data-perms.graph]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(defn- app-group!+ [name]+ (:permission_group_id+ (data-app.resources/ensure-resources!+ (t2/insert-returning-instance! :model/DataApp+ {:name name :display_name name :bundle_path (str "data_apps/" name "/index.js")}))))++(defn- view-data-rows+ [group-id db-id]+ (t2/select [:model/DataPermissions :id :table_id :perm_value]+ :group_id group-id :db_id db-id :perm_type :perms/view-data))++(defn- database-permission-value+ [group-id db-id perm-type]+ (t2/select-one-fn :perm_value :model/DataPermissions+ :group_id group-id :db_id db-id :perm_type perm-type :table_id nil))++(deftest denies-data-permissions-for-new-databases-to-existing-data-app-group-test+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/Database]+ (let [group-id (app-group! "finches")]+ ;; data app group exists before any database permissions have been assigned+ (t2/delete! :model/DataPermissions :group_id group-id)+ ;; should not grant data permissions for new databases to the data app group+ (let [new-database-id (t2/insert-returning-pk! :model/Database (mt/with-temp-defaults :model/Database))]+ (is (= {:perms/view-data :blocked+ :perms/create-queries :no+ :perms/download-results :no+ :perms/manage-table-metadata :no+ :perms/manage-database :no+ :perms/transforms :no}+ (t2/select-fn->fn :perm_type :perm_value :model/DataPermissions+ :group_id group-id :db_id new-database-id :table_id nil))))))))++(deftest reconcile-resets-create-queries-left-by-old-database-defaults-test+ (testing "Reconciliation removes query-authoring grants left by the old database defaults."+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-restored-data-perms-for-group! (:id (perms/all-users-group))+ (let [db-id (mt/id)+ group-id (app-group! "finches")]+ ;; Written as a row, the way the database defaults insert it -- the model rejects updates,+ ;; so they delete and re-insert too. `set-database-permission!` is no use here: it cascades+ ;; view-data to :unrestricted for any create-queries value other than :no, so no permission+ ;; API call can produce this pairing.+ (t2/delete! :model/DataPermissions+ :group_id group-id :db_id db-id :perm_type :perms/create-queries)+ (t2/insert! :model/DataPermissions+ {:group_id group-id+ :db_id db-id+ :perm_type :perms/create-queries+ :perm_value :query-builder-and-native})+ (is (= :query-builder-and-native+ (database-permission-value group-id db-id :perms/create-queries))+ "precondition: the permissive grant is in place")+ (is (=? [{:table_id nil :perm_value :blocked}] (view-data-rows group-id db-id))+ "precondition: view-data is already blocked, so nothing cascades")+ (data-app.permissions/reconcile-data-app-permissions! #{db-id})+ (is (= :no (database-permission-value group-id db-id :perms/create-queries)))+ (is (=? [{:table_id nil :perm_value :blocked}] (view-data-rows group-id db-id)))))))))++(deftest membership-preserves-legacy-block-permission-check-test+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-restored-data-perms-for-group! (:id (perms/all-users-group))+ (let [db-id (mt/id)+ provider (mt/metadata-provider)+ query (lib/query provider (lib.metadata/table provider (mt/id :venues)))+ check-block-permissions #(mt/with-test-user :rasta (block-perms/check-block-permissions query))]+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/create-queries :no)+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/view-data :legacy-no-self-service)+ (perms/set-table-permission! (perms/all-users-group) (mt/id :categories) :perms/create-queries :query-builder)+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/download-results :ten-thousand-rows)+ ;; user should not be blocked from viewing the query+ (is (true? (check-block-permissions)))+ (let [group-id (app-group! "wrens")]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (is (true? (check-block-permissions)))+ (is (=? [{:table_id nil :perm_value :legacy-no-self-service}] (view-data-rows group-id db-id)))+ (testing "other groups still supply query creation and download permissions"+ (is (= :query-builder+ (perms/table-permission-for-user (mt/user->id :rasta) :perms/create-queries+ db-id (mt/id :categories))))+ (is (= :ten-thousand-rows+ (perms/table-permission-for-user (mt/user->id :rasta) :perms/download-results+ db-id (mt/id :venues)))))))))))++(deftest resource-setup-reconciles-only-its-app-group-test+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [db-id (mt/id)+ group-id (app-group! "wrens")+ other-group-id (app-group! "finches")+ app (t2/select-one :model/DataApp :permission_group_id group-id)]+ (doseq [id [group-id other-group-id]]+ (perms/set-database-permission! id db-id :perms/manage-database :yes))+ (data-app.resources/ensure-resources! app)+ (is (= :no (database-permission-value group-id db-id :perms/manage-database)))+ (is (= :yes (database-permission-value other-group-id db-id :perms/manage-database)))))))++(deftest permission-edits-reconcile-all-app-groups-test+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id :schema "PUBLIC"}+ :model/PermissionsGroup {ordinary-group-id :id} {}]+ (let [group-ids [(app-group! "wrens") (app-group! "finches")]+ set-view-data! #(data-perms.graph/update-data-perms-graph!+ {:groups {ordinary-group-id {db-id {:view-data % :create-queries :no}}}})]+ (set-view-data! :legacy-no-self-service)+ (doseq [group-id group-ids]+ (is (=? [{:table_id nil :perm_value :legacy-no-self-service}] (view-data-rows group-id db-id))))+ (testing "new tables preserve the database-wide legacy permission"+ (mt/with-temp [:model/Table {new-table-id :id} {:db_id db-id :schema "PUBLIC"}]+ (doseq [group-id group-ids]+ (is (=? [{:table_id nil :perm_value :legacy-no-self-service}] (view-data-rows group-id db-id)))+ (is (= :legacy-no-self-service+ (perms/table-permission-for-groups #{group-id} :perms/view-data db-id new-table-id))))))+ (testing "reconciliation removes manual management grants"+ (doseq [group-id group-ids+ perm-type [:perms/manage-table-metadata :perms/manage-database]]+ (perms/set-database-permission! group-id db-id perm-type :yes))+ (set-view-data! :legacy-no-self-service)+ (doseq [group-id group-ids]+ (is (= #{[:perms/manage-table-metadata :no] [:perms/manage-database :no]}+ (t2/select-fn-set (juxt :perm_type :perm_value) :model/DataPermissions+ :group_id group-id :db_id db-id+ :perm_type [:in [:perms/manage-table-metadata :perms/manage-database]])))))+ (testing "an unchanged permission edit preserves row IDs"+ (let [before (mapv #(view-data-rows % db-id) group-ids)]+ (set-view-data! :legacy-no-self-service)+ (is (= before (mapv #(view-data-rows % db-id) group-ids)))))+ (testing "copied legacy does not keep itself alive after the ordinary grant is removed"+ (set-view-data! :blocked)+ (doseq [group-id group-ids]+ (is (=? [{:table_id nil :perm_value :blocked}] (view-data-rows group-id db-id)))))+ (testing "a table-level legacy grant also updates the whole database"+ (set-view-data! {"PUBLIC" {table-id :legacy-no-self-service}})+ (doseq [group-id group-ids]+ (is (=? [{:table_id nil :perm_value :legacy-no-self-service}] (view-data-rows group-id db-id))))))))))++(deftest unrelated-legacy-permissions-do-not-unblock-app-members-test+ (mt/with-premium-features #{:advanced-permissions :data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/PermissionsGroup {ordinary-group-id :id} {}]+ (perms/set-database-permission! ordinary-group-id (mt/id) :perms/view-data :legacy-no-self-service)+ (let [group-id (app-group! "finches")+ provider (mt/metadata-provider)+ query (lib/query provider (lib.metadata/table provider (mt/id :venues)))]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (is (=? [{:table_id nil :perm_value :legacy-no-self-service}] (view-data-rows group-id (mt/id))))+ (is (= :blocked (perms/table-permission-for-user (mt/user->id :rasta)+ :perms/view-data (mt/id) (mt/id :venues))))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You do not have permissions to run this query"+ (mt/with-test-user :rasta (block-perms/check-block-permissions query))))+ (testing "the app group grants no other data capabilities"+ (is (= #{[:perms/create-queries :no] [:perms/download-results :no]+ [:perms/manage-table-metadata :no] [:perms/manage-database :no] [:perms/transforms :no]}+ (t2/select-fn-set (juxt :perm_type :perm_value) :model/DataPermissions+ :group_id group-id :db_id (mt/id)+ :perm_type [:in [:perms/create-queries :perms/download-results+ :perms/manage-table-metadata :perms/manage-database :perms/transforms]]))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.cljnew file mode 100644index 00000000000..b42527c5cd5--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/query_definition_test.clj@@ -0,0 +1,54 @@+(ns metabase-enterprise.data-apps.query-definition-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase-enterprise.data-apps.query-definition :as query-definition]+ [metabase.lib.schema.test-spec :as test-spec]+ [metabase.util.malli.registry :as mr]))++(def ^:private query-definition+ {:stages [{:source {:type :table :id 1}+ :fields [{:type :column :name "ID"}+ {:type :column :name "NAME" :source-field-id 2}]+ :filters [{:type :operator :operator :>+ :args [{:type :column :name "PRICE"}+ {:type :literal :value 1}]}+ {:type :segment :id 1}]+ :aggregations [{:type :operator :operator :count :args []}+ {:type :measure :id 1}+ {:type :metric :id 1}]+ :breakouts [{:type :column :name "DATE" :unit :month}+ {:type :column :name "PRICE" :bins 10}]+ :order-bys [{:type :column :name "DATE" :unit :month :direction :asc}]+ :limit 10}]})++(deftest ^:parallel supported-query-fields-test+ (is (nil? (mr/explain ::query-definition/query-definition query-definition))))++(deftest ^:parallel unknown-query-fields-test+ (doseq [path [[] [:stages 0] [:stages 0 :source]+ [:stages 0 :fields 0]+ [:stages 0 :filters 0 :args 1]+ [:stages 0 :aggregations 1] [:stages 0 :breakouts 0]+ [:stages 0 :order-bys 0]]]+ (testing (str "Unknown fields are not part of the request contract at " path)+ (is (not (mr/validate ::query-definition/query-definition+ (assoc-in query-definition (conj path :unexpected) true)))))))++(deftest ^:parallel required-query-source-test+ (is (not (mr/validate ::query-definition/query-definition {:stages []})))+ (is (not (mr/validate ::query-definition/query-definition {:stages [{}]}))))++(deftest ^:parallel internal-column-schemas-remain-open-test+ (let [column {:type :column :name "DATE" :unit :month}]+ (is (mr/validate ::test-spec/test-column-spec column))+ (is (not (mr/validate ::query-definition/column column)))+ (is (mr/validate ::query-definition/breakout column))))++(deftest ^:parallel unsupported-query-features-test+ (doseq [query [{:stages (repeat 2 (first (:stages query-definition)))}+ (assoc-in query-definition [:stages 0 :source] {:type :card :id 1})+ (assoc-in query-definition [:stages 0 :joins] [])+ (assoc-in query-definition [:stages 0 :expressions] [])+ (assoc-in query-definition [:stages 0 :aggregations]+ [{:name "count" :value {:type :operator :operator :count :args []}}])]]+ (is (not (mr/validate ::query-definition/query-definition query)))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.cljnew file mode 100644index 00000000000..91b59b1af5f--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj@@ -0,0 +1,153 @@+(ns metabase-enterprise.data-apps.resources-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.data-apps.resources :as data-app.resources]+ [metabase.collections.models.collection :as collection]+ [metabase.permissions.core :as perms]+ [metabase.sso.core :as sso]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- create-data-app!+ [name]+ (t2/insert-returning-instance! :model/DataApp+ {:name name+ :display_name name+ :bundle_path (format "data_apps/%s/index.js" name)}))++(deftest ensure-resources-restores-a-collection-trashed-through-an-ancestor-test+ (testing "an app collection filed under another collection is archived indirectly when that+ ancestor is trashed, and the ancestor stays there — so it is restored to the root+ rather than to a parent that would reject it"+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-test-user :crowberto+ (mt/with-temp [:model/Collection {ancestor-id :id} {:name "Filed under" :location "/"}]+ (let [app (create-data-app! "wrens")+ {:keys [resource_collection_id]} (data-app.resources/ensure-resources! app)]+ (collection/move-collection!+ (t2/select-one :model/Collection :id resource_collection_id)+ (collection/children-location (t2/select-one :model/Collection :id ancestor-id)))+ (collection/archive-or-unarchive-collection!+ (t2/select-one :model/Collection :id ancestor-id)+ {:archived true})+ (is (true? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "precondition: the ancestor took the app collection with it")+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :id (:id app)))+ (is (false? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "the app collection is usable again")+ (is (= "/" (t2/select-one-fn :location :model/Collection :id resource_collection_id))+ "and sits at the root, not under the ancestor still in the trash")+ (is (true? (t2/select-one-fn :archived :model/Collection :id ancestor-id))+ "the ancestor is left where the admin put it")))))))++(deftest ensure-resources-restores-a-trashed-collection-test+ (testing "trashing the resource collection archives the copies the app is served from,+ so ensure-resources! has to bring both back or a successful sync leaves the app blank"+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [app (create-data-app! "sparrows")+ {:keys [resource_collection_id]} (data-app.resources/ensure-resources! app)]+ ;; The app collection is readable by its own group alone, so only an admin+ ;; can put the copy there.+ (mt/with-test-user :crowberto+ (mt/with-temp [:model/Card {card-id :id} {:collection_id resource_collection_id}]+ (collection/archive-or-unarchive-collection!+ (t2/select-one :model/Collection :id resource_collection_id)+ {:archived true})+ (is (true? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "precondition: the collection is in the trash")+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id))+ "precondition: trashing the collection archived the copy")+ (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :id (:id app)))+ (is (false? (t2/select-one-fn :archived :model/Collection :id resource_collection_id))+ "the app collection is out of the trash")+ (is (false? (t2/select-one-fn :archived :model/Card :id card-id))+ "the copy the app serves is readable again")))))))++(deftest ensure-resources-blocks-the-app-groups-view-data-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [app (create-data-app! "birds")+ {:keys [permission_group_id]} (data-app.resources/ensure-resources! app)+ perm (fn [perm-type] (t2/select [:model/DataPermissions :table_id :perm_value]+ :group_id permission_group_id+ :db_id (mt/id)+ :perm_type perm-type))]+ (testing "the app group is flagged as a data-app group (its own namespace)"+ (is (true? (t2/select-one-fn :is_data_app_group :model/PermissionsGroup :id permission_group_id))))+ (testing "the app group is blocked at the database level, granting no data access of its own"+ (is (=? [{:table_id nil, :perm_value :blocked}] (perm :perms/view-data)))+ (testing "view-data :blocked cascades download-results/transforms to :no"+ (is (=? [{:table_id nil, :perm_value :no}] (perm :perms/download-results)))+ (is (=? [{:table_id nil, :perm_value :no}] (perm :perms/transforms)))))+ (testing "a manual table-level view-data grant is swept back to the database-wide block on the next sync"+ (perms/set-table-permissions! permission_group_id :perms/view-data+ {(mt/id :venues) :unrestricted})+ (data-app.resources/ensure-resources! app)+ (is (=? [{:table_id nil, :perm_value :blocked}] (perm :perms/view-data))))+ (testing "a manual download-results grant that left view-data blocked is swept back too"+ (perms/set-database-permission! permission_group_id (mt/id) :perms/download-results :one-million-rows)+ (data-app.resources/ensure-resources! app)+ (is (=? [{:table_id nil, :perm_value :no}] (perm :perms/download-results)))+ (is (=? [{:table_id nil, :perm_value :blocked}] (perm :perms/view-data)))))))++(deftest data-app-groups-hidden-from-the-groups-api-test+ (testing "GET /api/permissions/group never lists data-app groups — they are a server-managed namespace"+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-temp [:model/PermissionsGroup {normal-group-id :id} {:name "Normal Group"}]+ (let [{app-group-id :permission_group_id} (data-app.resources/ensure-resources! (create-data-app! "some-app"))+ listed-ids (into #{} (map :id) (mt/user-http-request :crowberto :get 200 "permissions/group"))]+ (is (contains? listed-ids normal-group-id) "a normal group is listed")+ (is (not (contains? listed-ids app-group-id)) "the data-app group is hidden"))))))++(deftest sso-group-sync-does-not-add-a-user-to-a-data-app-group-test+ (testing "a data app's permission group is server-managed: membership is granted by an admin, not+ an IdP claim. SSO group sync must not add a user to it, or an IdP `groups` value naming+ \"Data App: <slug>\" would hand the app's collection to whoever it names."+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-temp [:model/User {user-id :id} {}]+ (let [app (create-data-app! "birds")+ {:keys [permission_group_id]} (data-app.resources/ensure-resources! app)]+ ;; As a name-based SSO sync would, ask to put the user in the data-app group.+ (sso/sync-group-memberships! user-id [permission_group_id])+ (is (not (t2/exists? :model/PermissionsGroupMembership+ :user_id user-id :group_id permission_group_id))+ "SSO group sync must not add a user to a data-app group"))))))++(deftest ensure-resources-preserves-collection-grants-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [app (create-data-app! "birds")+ {group-id :permission_group_id collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)+ read-path (perms/collection-read-path collection-id)+ grant (t2/select-one :model/Permissions :group_id group-id :object read-path)]+ (is (some? grant))+ (data-app.resources/ensure-resources! app)+ ; correct grants should not be changed after sync+ (is (= grant (t2/select-one :model/Permissions :group_id group-id :object read-path))))))++(deftest ensure-resources-repairs-collection-grants-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (mt/with-temp [:model/PermissionsGroup {other-group-id :id} {}]+ (let [app (create-data-app! "birds")+ {group-id :permission_group_id collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)+ read-path (perms/collection-read-path collection-id)+ write-path (perms/collection-readwrite-path collection-id)]+ ; grant incorrect permission: write access to the data app collection+ (perms/grant-collection-readwrite-permissions! group-id collection-id)+ ; grant incorrect permission: let other groups read the data app collection+ (perms/grant-collection-read-permissions! other-group-id collection-id)+ (data-app.resources/ensure-resources! app)+ ; the two bad grants should be removed after sync.+ ; only the correct grants should remain.+ (is (= [{:group_id group-id :object read-path}]+ (t2/select [:model/Permissions :group_id :object]+ :object [:in [read-path write-path]])))))))++(deftest ensure-resources-restores-missing-collection-grant-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [app (create-data-app! "birds")+ {group-id :permission_group_id collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)]+ (perms/revoke-collection-permissions! group-id collection-id)+ (data-app.resources/ensure-resources! app)+ ; read access should be restored after sync+ (is (t2/exists? :model/Permissions :group_id group-id :object (perms/collection-read-path collection-id))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.cljindex 51923829a13..3ab7627da85 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj@@ -6,8 +6,11 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.resources :as data-app.resources][metabase-enterprise.data-apps.sync :as data-app.sync][metabase-enterprise.remote-sync.source :as source]+ [metabase.permissions.core :as perms][metabase.test :as mt][toucan2.core :as t2]))@@ -47,8 +50,75 @@"with the feature it materializes the app as usual")(is (t2/exists? :model/DataApp :name "a")))))))-(deftest changed-count-tracks-content-not-sha-bumps-test+(deftest resource-provisioning-failures-are-isolated-test(mt/with-model-cleanup [:model/DataApp]+ (let [files (merge (app-files "broken" {:name "Broken" :path "index.js" :bundle "BROKEN"})+ (app-files "working" {:name "Working" :path "index.js" :bundle "WORKING"}))]+ (with-redefs [data-app.resources/ensure-resources!+ (fn [app]+ (when (= "broken" (:name app))+ (throw (ex-info "Resource provisioning failed." {}))))]+ (is (=? {:synced 2 :changed 2}+ (data-app.sync/import-from-snapshot! (snapshot files))))+ (is (= "Resource provisioning failed."+ (t2/select-one-fn :sync_error :model/DataApp :name "broken")))+ (is (nil? (t2/select-one-fn :sync_error :model/DataApp :name "working")))))))++(deftest sync-creates-stable-permission-resources-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [database-id (mt/id)+ files (app-files "sales" {:name "Sales" :path "index.js" :bundle "V1"})]+ (data-app.sync/import-from-snapshot! (snapshot files))+ (let [{:keys [resource_collection_id permission_group_id]}+ (t2/select-one :model/DataApp :name "sales")]+ (testing "the first sync creates a dedicated group and collection"+ (is (pos-int? resource_collection_id))+ (is (pos-int? permission_group_id))+ (is (= "Data App: sales"+ (t2/select-one-fn :name :model/Collection :id resource_collection_id)))+ (is (= "Data App: sales"+ (t2/select-one-fn :name :model/PermissionsGroup :id permission_group_id)))+ (is (t2/exists? :model/Permissions+ :group_id permission_group_id+ :object (perms/collection-read-path resource_collection_id)))+ (is (not (t2/exists? :model/Permissions+ :group_id permission_group_id+ :object (perms/collection-readwrite-path resource_collection_id))))+ (let [permissions (t2/select-fn-vec :perm_value :model/DataPermissions+ :group_id permission_group_id+ :db_id database-id+ :perm_type :perms/create-queries)]+ (is (seq permissions))+ (is (every? #(= :no %) permissions))))+ (testing "later syncs reuse the same resources"+ (data-app.sync/import-from-snapshot! (snapshot files))+ (is (=? {:resource_collection_id resource_collection_id+ :permission_group_id permission_group_id}+ (t2/select-one :model/DataApp :name "sales"))))+ (testing "removing the app deletes its resources"+ (data-app.sync/import-from-snapshot! (snapshot {}))+ (is (not (t2/exists? :model/Collection :id resource_collection_id)))+ (is (not (t2/exists? :model/PermissionsGroup :id permission_group_id))))))))++(deftest sync-restores-deleted-collection-and-permission-group-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [files (app-files "sales" {:name "Sales" :path "index.js" :bundle "V1"})]+ (data-app.sync/import-from-snapshot! (snapshot files))+ (let [before (select-keys (t2/select-one :model/DataApp :name "sales")+ [:resource_collection_id :permission_group_id])]+ (t2/delete! :model/Collection :id (:resource_collection_id before))+ (t2/delete! :model/PermissionsGroup :id (:permission_group_id before))+ (data-app.sync/import-from-snapshot! (snapshot files))+ ; after syncing the app again, the data app collection and+ ; permission group should be re-created+ (let [after (select-keys (t2/select-one :model/DataApp :name "sales") (keys before))]+ (is (every? pos-int? (vals after)))+ (is (t2/exists? :model/Collection :id (:resource_collection_id after)))+ (is (t2/exists? :model/PermissionsGroup :id (:permission_group_id after)))+ (is (not= before after)))))))++(deftest changed-count-tracks-content-not-sha-bumps-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [files (app-files "a" {:name "A" :path "index.js" :bundle "V1"})](testing "the first sync counts the new app"(is (=? {:synced 1 :changed 1}@@ -67,7 +137,7 @@(snapshot (app-files "a" {:name "A renamed" :path "index.js" :bundle "V2"})))))))))(deftest description-is-optional-and-tracked-like-other-metadata-test- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [sync-app (fn [& {:as app}](data-app.sync/import-from-snapshot!(snapshot (app-files "a" (merge {:name "A" :path "index.js" :bundle "V1"} app)))))]@@ -85,13 +155,11 @@(deftest metadata-edits-count-while-an-app-keeps-failing-test(testing "an app whose bundle is missing still stores metadata edits, so they count as changes"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [sync-app (fn [& {:as app}]- (data-app.sync/import-from-snapshot!- (snapshot {"data_apps/a/data_app.yaml"- (str "name: A\npath: index.js\n"- (when-let [d (:description app)]- (format "description: %s\n" d)))})))]+ (let [files (app-files "a" (merge {:name "A" :path "index.js" :bundle "unused"} app))]+ (data-app.sync/import-from-snapshot!+ (snapshot (dissoc files "data_apps/a/index.js")))))](is (=? {:changed 1} (sync-app :description "First")) "the first failure is a change")(is (some? (t2/select-one-fn :sync_error :model/DataApp :name "a")))(testing "re-syncing the same failing app unchanged is not a change"@@ -103,7 +171,7 @@(deftest switching-repos-prunes-old-apps-overrides-shared-adds-new-test(testing "syncing a different repo: drop apps only the old repo had, override shared slugs, add new ones"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup];; Repo A: Foo + Bar(data-app.sync/import-from-snapshot!(snapshot (merge (app-files "foo" {:name "Foo" :path "index.js" :bundle "FOO"})@@ -125,7 +193,7 @@(deftest an-empty-repo-prunes-all-apps-test(testing "syncing a repo with no data_apps/ removes every app (the repo has none)"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "solo" {:name "Solo" :path "index.js" :bundle "S"})))(is (= #{"solo"} (t2/select-fn-set :name :model/DataApp)))@@ -133,9 +201,48 @@(data-app.sync/import-from-snapshot! (snapshot {}))))(is (empty? (t2/select-fn-set :name :model/DataApp))))))+(deftest remote-sync-preserves-unpublished-data-app-drafts-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (data-app.sync/ensure-draft! "draft-app")+ (is (=? {:removed 0}+ (data-app.sync/import-from-snapshot! (snapshot {}))))+ (is (true? (t2/select-one-fn :draft :model/DataApp :name "draft-app")))+ (data-app.sync/import-from-snapshot!+ (snapshot (app-files "draft-app" {:name "Draft" :path "index.js" :bundle "BUNDLE"})))+ (is (false? (t2/select-one-fn :draft :model/DataApp :name "draft-app")))+ (is (=? {:removed 1}+ (data-app.sync/import-from-snapshot! (snapshot {}))))+ (is (not (t2/exists? :model/DataApp :name "draft-app")))))++(deftest repository-claims-a-draft-before-a-successful-import-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (data-app.sync/ensure-draft! "draft-app")+ (data-app.sync/import-from-snapshot!+ (snapshot {"data_apps/draft-app/data_app.yaml" "name: Draft\n"}))+ (is (false? (t2/select-one-fn :draft :model/DataApp :name "draft-app")))+ (is (=? {:removed 1}+ (data-app.sync/import-from-snapshot! (snapshot {}))))+ (is (not (t2/exists? :model/DataApp :name "draft-app")))))++(deftest concurrent-draft-creation-is-safe-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [drafts (doall (repeatedly 2 #(future (data-app.sync/ensure-draft! "draft-app"))))]+ (doseq [draft drafts]+ @draft)+ (is (= 1 (t2/count :model/DataApp :name "draft-app"))))))++(deftest remote-sync-prunes-never-successful-repository-apps-test+ (mt/with-model-cleanup [:model/DataApp]+ (data-app.sync/import-from-snapshot!+ (snapshot {"data_apps/broken/data_app.yaml" "name: Broken\npath: missing.js\n"}))+ (is (false? (t2/select-one-fn :draft :model/DataApp :name "broken")))+ (is (=? {:removed 1}+ (data-app.sync/import-from-snapshot! (snapshot {}))))+ (is (not (t2/exists? :model/DataApp :name "broken")))))+(deftest a-broken-config-does-not-prune-the-existing-app-test(testing "a directory that still exists but whose data_app.yaml is now broken keeps the app (as a sync_error), it is not pruned"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "app" {:name "App" :path "index.js" :bundle "GOOD"})))(is (= "GOOD" (String. ^bytes (:bundle (t2/select-one :model/DataApp :name "app")) "UTF-8")))@@ -157,7 +264,7 @@(deftest a-broken-config-for-a-brand-new-app-materializes-nothing-test(testing "an app whose config never parsed has no row to mark — it simply isn't materialized"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [result (data-app.sync/import-from-snapshot!(snapshot {"data_apps/newbie/data_app.yaml" "name: Newbie\n" ; missing required "path""data_apps/newbie/index.js" "X"}))]@@ -170,7 +277,7 @@(deftest oversized-bundle-is-rejected-test(testing "a bundle over the size cap is rejected with a sync_error, no bundle cached"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "big" {:name "Big" :path "index.js":bundle (oversized-bundle)})))@@ -181,7 +288,7 @@(deftest oversized-resync-keeps-the-previous-bundle-test(testing "an oversized re-sync sets sync_error but keeps the last good bundle"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](data-app.sync/import-from-snapshot!(snapshot (app-files "app" {:name "App" :path "index.js" :bundle "GOOD"})))(data-app.sync/import-from-snapshot!@@ -194,7 +301,7 @@(deftest a-directory-without-a-config-is-not-an-app-test(testing "a data_apps/<dir> that ships a bundle but no data_app.yaml is not discovered — no app, no error"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [result (data-app.sync/import-from-snapshot!(snapshot {"data_apps/orphan/index.js" "BUNDLE"}))](is (=? {:synced 0 :changed 0 :config-errors []} result))@@ -202,10 +309,56 @@(deftest an-unreadable-config-is-a-config-error-test(testing "a data_app.yaml the snapshot lists but can't read is isolated as a config-error, not a crash"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup];; the config is listed in the tree, but reading its blob yields nothing(let [result (data-app.sync/import-from-snapshot!(snapshot {"data_apps/ghost/data_app.yaml" nil}))](is (= 1 (count (:config-errors result))))(is (str/includes? (first (:config-errors result)) "data_apps/ghost/data_app.yaml"))(is (empty? (t2/select-fn-set :name :model/DataApp)))))))++(deftest resource-failure-rolls-back-only-that-app-test+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [files (merge (app-files "broken" {:name "Broken" :path "index.js" :bundle "OLD"})+ (app-files "working" {:name "Working" :path "index.js" :bundle "OLD"}))+ ensure-resources! data-app.resources/ensure-resources!]+ (data-app.sync/import-from-snapshot! (snapshot files))+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :name "broken")+ old-name (t2/select-one-fn :name :model/Collection :id collection-id)]+ ; inject an error into `ensure-resources!` for the "broken" app+ (with-redefs [data-app.resources/ensure-resources!+ (fn [app]+ (ensure-resources! app)+ (when (= "broken" (:name app))+ (t2/update! :model/Collection :id collection-id {:name "Partial update"})+ (throw (ex-info "Resource provisioning failed." {}))))]+ (data-app.sync/import-from-snapshot!+ (snapshot (assoc files "data_apps/broken/index.js" "NEW" "data_apps/working/index.js" "NEW"))))+ ; the "broken" app bundle with sync error should be rolled back to "OLD"+ (is (= "OLD" (String. ^bytes (t2/select-one-fn :bundle :model/DataApp :name "broken") "UTF-8")))+ ; the collection name should be rolled back to the old name+ (is (= old-name (t2/select-one-fn :name :model/Collection :id collection-id)))+ ; the thrown exception in ensure-resources! should be reported in the sync error+ (is (= "Resource provisioning failed." (t2/select-one-fn :sync_error :model/DataApp :name "broken")))+ ; the "working" app without sync errors should not be rolled back to "OLD"+ (is (= "NEW" (String. ^bytes (t2/select-one-fn :bundle :model/DataApp :name "working") "UTF-8")))))))++(deftest pruning-failure-does-not-roll-back-synced-apps-test+ (mt/with-premium-features #{:data-apps-preview}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [working-files (app-files "working" {:name "Working" :path "index.js" :bundle "OLD"})+ files (merge working-files (app-files "removed" {:name "Removed" :path "index.js" :bundle "OLD"}))+ prune! data-apps.db/delete-data-apps-not-named!]+ (data-app.sync/import-from-snapshot! (snapshot files))+ ; inject an error into deleting data apps+ (with-redefs [data-apps.db/delete-data-apps-not-named!+ (fn [slugs]+ (prune! slugs)+ (throw (ex-info "Pruning failed." {})))]+ ; sync should report the error from pruning step+ (is (=? {:synced 1 :changed 1 :removed 0 :pruning-error "Pruning failed."}+ (data-app.sync/sync-from-snapshot!+ (snapshot (assoc working-files "data_apps/working/index.js" "NEW"))))))+ ; a pruning failure should not roll back the updated app's bundle+ (is (= "NEW" (String. ^bytes (t2/select-one-fn :bundle :model/DataApp :name "working") "UTF-8")))+ (is (t2/exists? :model/DataApp :name "removed"))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.cljindex c9f3ab94f81..5bfd4dba648 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj@@ -19,7 +19,6 @@(use-fixtures :once (fixtures/initialize :db))(use-fixtures :each rs.test/clean-remote-sync-state rs.test/commit-with-temp)-(defn- import-at!"Run `import!` against the source's snapshot at `version`, complete the task (so`last-version` advances for the next pull), and return the result."@@ -30,7 +29,7 @@(impl/handle-task-result! result task)result))-(defn- app-tree+(defn- app-tree!"Repo files for one data app: its `data_app.yaml` + a bundle at `dist/index.js`."[slug bundle]{(str "data_apps/" slug "/data_app.yaml") (str "name: " slug "\npath: dist/index.js\n")@@ -58,9 +57,9 @@(search.tu/with-index-disabled(mt/with-premium-features #{:data-apps-preview}(mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]- (mt/with-model-cleanup [:model/DataApp]- (let [outcome (pull-outcome! (app-tree "sales" "BUNDLE-V1")- (app-tree "sales" "BUNDLE-V2"))]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (let [outcome (pull-outcome! (app-tree! "sales" "BUNDLE-V1")+ (app-tree! "sales" "BUNDLE-V2"))](is (= "pulled" (:kind outcome)) "not reported as skipped")(is (= 1 (:count outcome)) "the one changed data app is counted"))))))))@@ -69,9 +68,9 @@(search.tu/with-index-disabled(mt/with-premium-features #{:data-apps-preview}(mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]- (mt/with-model-cleanup [:model/DataApp :model/Collection]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup];; v1 adds a collection; the data app is byte-for-byte the same as v0.- (let [app (app-tree "sales" "BUNDLE")+ (let [app (app-tree! "sales" "BUNDLE")outcome (pull-outcome! app (merge coll-file app))](is (= "pulled" (:kind outcome)))(is (= 1 (:count outcome)) "the collection counts; the unchanged app adds 0"))))))))@@ -81,9 +80,9 @@(search.tu/with-index-disabled(mt/with-premium-features #{:data-apps-preview}(mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]- (mt/with-model-cleanup [:model/DataApp :model/Collection]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup];; v1 adds a collection AND changes the data app's bundle.- (let [outcome (pull-outcome! (app-tree "ops" "BUNDLE")- (merge coll-file (app-tree "ops" "BUNDLE-V2")))]+ (let [outcome (pull-outcome! (app-tree! "ops" "BUNDLE")+ (merge coll-file (app-tree! "ops" "BUNDLE-V2")))](is (= "pulled" (:kind outcome)))(is (= 2 (:count outcome)) "the collection (1) plus the changed data app (1)"))))))))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 1d9220ac185..ea81e16d3c0 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@@ -13,7 +13,6 @@(use-fixtures :once (fixtures/initialize :db))(use-fixtures :each (fn [f] (test-helpers/clean-remote-sync-state f)))-(comment metabase-enterprise.data-apps.models.data-app/keep-me)(defn- import! [files]@@ -32,7 +31,7 @@(deftest import-materializes-data-apps-test(testing "a remote-sync import materializes data apps from data_apps/ alongside serdes content"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [files {"main" {"collections/c/c.yaml"(test-helpers/generate-collection-yaml "data-apps-test-collx" "DA Coll")"data_apps/sales/data_app.yaml" "name: Sales\npath: ./dist/index.js\n"@@ -48,7 +47,7 @@(deftest import-prunes-data-apps-absent-from-repo-test(testing "an import whose repo no longer has an app dir prunes that app (the repo is the source of truth)"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](import! {"main" {"data_apps/gone/data_app.yaml" "name: Gone\npath: ./i.js\n""data_apps/gone/i.js" "X""data_apps/kept/data_app.yaml" "name: Kept\npath: ./i.js\n"@@ -63,7 +62,7 @@(deftest deletion-only-pull-counts-the-removal-test(testing "a pull whose only change is removing an app still reports as a pull — the removal is counted, not a no-op"- (mt/with-model-cleanup [:model/DataApp]+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup];; No serdes content, so the outcome's count comes purely from data apps.(import! {"main" {"README.md" "x""data_apps/gone/data_app.yaml" "name: Gone\npath: ./i.js\n"diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.ts b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.tsnew file mode 100644index 00000000000..9cc22e16225--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.ts@@ -0,0 +1,12 @@+import path from "node:path";++import { getResourceSyncCredentials } from "../../data-app-query-sync/env";+import { syncResources } from "../../data-app-query-sync/sync";++export async function syncResourcesAction(appRoot = process.cwd()) {+ const resolvedRoot = path.resolve(appRoot);+ await syncResources({+ appRoot: resolvedRoot,+ ...getResourceSyncCredentials(resolvedRoot),+ });+}diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.tsnew file mode 100644index 00000000000..110a31c30c0--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/cli/actions/sync-resources.unit.spec.ts@@ -0,0 +1,49 @@+import path from "node:path";++import { getResourceSyncCredentials } from "../../data-app-query-sync/env";+import { syncResources } from "../../data-app-query-sync/sync";++import { syncResourcesAction } from "./sync-resources";++jest.mock("../../data-app-query-sync/env", () => ({+ getResourceSyncCredentials: jest.fn(),+}));+jest.mock("../../data-app-query-sync/sync", () => ({+ syncResources: jest.fn(),+}));++describe("syncResourcesAction", () => {+ it("resolves the app root and loads its credentials", async () => {+ jest.mocked(getResourceSyncCredentials).mockReturnValue({+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ });++ await syncResourcesAction("data_apps/orders");++ const appRoot = path.resolve("data_apps/orders");+ expect(getResourceSyncCredentials).toHaveBeenCalledWith(appRoot);+ expect(syncResources).toHaveBeenCalledWith({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ });+ });++ it("uses the current directory by default", async () => {+ jest.mocked(getResourceSyncCredentials).mockReturnValue({+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ });++ await syncResourcesAction();++ const appRoot = path.resolve(process.cwd());+ expect(getResourceSyncCredentials).toHaveBeenCalledWith(appRoot);+ expect(syncResources).toHaveBeenCalledWith({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ });+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/cli.ts b/enterprise/frontend/src/embedding-sdk-package/cli/cli.tsindex 0dbd0a6ee53..4131d7c2ef6 100644--- a/enterprise/frontend/src/embedding-sdk-package/cli/cli.ts+++ b/enterprise/frontend/src/embedding-sdk-package/cli/cli.ts@@ -1,6 +1,8 @@import { Command } from "commander";import { start } from "./actions/start";+import { addDataAppsCommands } from "./commands/data-apps";+import { printError } from "./utils/print";const program = new Command();@@ -13,4 +15,9 @@ program.description("downloads and starts a local Metabase instance").action(start);-program.parse();+addDataAppsCommands(program);++program.parseAsync().catch((error: unknown) => {+ printError(error instanceof Error ? error.message : String(error));+ process.exitCode = 1;+});diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.tsnew file mode 100644index 00000000000..274a724e29f--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.ts@@ -0,0 +1,17 @@+import type { Command } from "commander";++import { syncResourcesAction } from "../actions/sync-resources";++export function addDataAppsCommands(program: Command) {+ const dataAppsCommand = program+ .command("data-apps")+ .description("manage Metabase data apps");++ dataAppsCommand+ .command("sync-resources")+ .description(+ "synchronize data app query and action definitions into its collection",+ )+ .option("--app-root <path>", "data app directory", process.cwd())+ .action(({ appRoot }: { appRoot: string }) => syncResourcesAction(appRoot));+}diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.tsnew file mode 100644index 00000000000..1a308e458f8--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/cli/commands/data-apps.unit.spec.ts@@ -0,0 +1,36 @@+import { Command } from "commander";++import { syncResourcesAction } from "../actions/sync-resources";++import { addDataAppsCommands } from "./data-apps";++jest.mock("../actions/sync-resources", () => ({+ syncResourcesAction: jest.fn(),+}));++describe("data app commands", () => {+ it("runs resource synchronization for the requested app root", async () => {+ const program = new Command();+ addDataAppsCommands(program);++ await program.parseAsync([+ "node",+ "cli",+ "data-apps",+ "sync-resources",+ "--app-root",+ "data_apps/orders",+ ]);++ expect(syncResourcesAction).toHaveBeenCalledWith("data_apps/orders");+ });++ it("runs resource synchronization from the current directory by default", async () => {+ const program = new Command();+ addDataAppsCommands(program);++ await program.parseAsync(["node", "cli", "data-apps", "sync-resources"]);++ expect(syncResourcesAction).toHaveBeenCalledWith(process.cwd());+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.tsindex e5a1d21a9a4..4ad5840d3df 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts@@ -8,6 +8,8 @@ import {loadEnv,} from "vite";+import { checkResourcesSynced } from "../data-app-query-sync/sync";+import { dataAppBuildPlugins, dataAppLibBuild } from "./config/build-config";import { getDataAppDefine } from "./config/define";import { buildDevCsp } from "./config/dev-connect-src";@@ -36,6 +38,13 @@ function dataAppVitePlugin(): PluginOption[] {react(),...dataAppBuildPlugins(),dataAppSandboxDevPlugin(appSlug, allowedHosts),+ {+ name: "metabase-resource-sync-check",+ apply: "build",+ buildStart: async () => {+ await checkResourcesSynced(appRoot);+ },+ },{name: "metabase-data-app",// Merged over the user's config, so these win — the bundle Metabase loadsdiff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.md b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.mdnew file mode 100644index 00000000000..7fe5ed2cc67--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/README.md@@ -0,0 +1,125 @@+# Resource sync++A data app runs in a browser sandbox as one of its viewers, not as its author. Those viewers reach+Metabase through a permission group that can read exactly one collection: the app's own. So a query+the app runs, and an action it triggers, have to be reachable **through that collection** or they+fail on permissions.++Resource sync is the build-time step that makes that true. It reads the definitions an app commits+to source control, materializes them inside the app's collection, and writes back the generated IDs.+`npm run sync-resources` (`embedding-sdk-react data-apps sync-resources`) is the entry point.++The backend half — the collection and permission group themselves — lives in+`metabase_enterprise/data_apps/resources.clj`. See that module's README for how apps are served.++## What an app declares++Two directories at the data-app root, beside `package.json`:++```+queries/orders.query.ts export const RevenueQuery = defineQuery({ source: schema.tables.orders })+actions/orders.action.ts export const CreateOrder = defineAction({ action: schema.models.orders.actions.create })+```++Nothing else is scanned — definitions under `src/` are invisible to sync, which is a common+authoring mistake.++## The pipeline++`syncResources` (`sync.ts`) runs four steps:++1. **Discover** every `defineQuery` / `defineAction` in those directories (`discover.ts`).+2. **Ensure resources** — `POST /api/apps/:slug/draft` creates the app row if it doesn't exist+ yet, plus its collection and permission group.+3. **Reconcile queries** (`reconcile.ts`) — each authored query becomes a saved question in the+ collection, and its ID is injected back into the source as `savedQuestionSourceId`.+4. **Reconcile models** (`reconcile-models.ts`) — each declared action's model is copied into the+ collection, the action is copied onto that copy, and the copy's ID is injected back as+ `copiedActionId`.++## Why actions copy a whole model++An action's permissions resolve through its parent model's collection+(`metabase.actions.models`, `perms-objects-set`). Copying a card does **not** copy its actions —+`create-card!` writes one row and nothing traverses Card → Action — so making an action reachable+means copying its model _and_ recreating the action on that copy.++Models are therefore reference-counted by the actions that need them. The lockfile entry holds the+set of actions, not a count, because a count drifts across repeated runs while a set converges:++| Event | Model | Action |+| ------------------------------------- | --------------- | ------------------------- |+| action declared, model not yet copied | copy it | recreate on the copy |+| action declared, model already copied | reuse | recreate just this action |+| declaration dropped, siblings remain | keep | delete that copied action |+| last declaration dropped | delete the copy | cascade removes the rest |++The last row is free: `action.model_id` is `ON DELETE CASCADE`, so deleting the copied model takes+its copied actions with it.++## Discovery is deliberately strict++`discover.ts` parses each file twice over. The TypeScript AST locates `defineQuery`/`defineAction`+calls and enforces that each one directly initializes a **named exported** variable with a single+object literal. The file is then bundled with esbuild and evaluated — **twice** — and the two results+compared, so a definition that isn't deterministic can't produce a fingerprint that changes under it.++Write-back re-parses from disk rather than reusing the AST from discovery, because reconciliation+injects sequentially and an earlier injection into the same file shifts every offset after it.++## The lockfile is ownership proof++`resources_metadata.json` is generated, committed, and never hand-edited:++```jsonc+{+ "queries": [+ { "tableId": 1, "hash": "v1:sha256:…", "savedQuestionSourceId": 54 },+ ],+ "models": [+ {+ "sourceModelId": 5,+ "copiedModelId": 80,+ "hash": "v1:sha256:…",+ "actions": [+ { "sourceActionId": 51, "copiedActionId": 91, "hash": "v1:sha256:…" },+ ],+ },+ ],+}+```++It is not a cache. It is the only evidence that a card or action in Metabase belongs to this app,+and every mutating path checks it first. The `hash` fields fingerprint the **source** payload — the+only way to notice that someone edited the upstream model or action, since nothing in the app's own+source changes when they do.++## Invariants++These hold across both reconcilers, and are what the tests are mostly about:++- **Nothing is mutated or deleted without lockfile proof**, plus a live ownership check — still a+ question/model, still in the app's collection, action still hanging off the copied model. Anything+ that has moved is refused with recovery instructions rather than silently touched.+- **The lockfile flushes after every single mutation**, so a crash mid-run leaves resumable state.+- **`404` is the only recoverable failure.** Any other status rethrows; recreate-after-404+ additionally requires lockfile proof.+- **On the backend, ownership is the foreign key, never the name.** A same-named group is refused,+ not adopted — adoption would hand its existing members the app's data access on a name match.++## Dev preview vs production build++Generated IDs only take effect in a production build. `isDataAppDev()` gates both swaps, so an app+runs against the original table and the authored action before it has ever been synchronized:++| | Dev preview | Production |+| ------------ | ------------------- | -------------------------------------------- |+| query source | the table | the saved question (`savedQuestionSourceId`) |+| action | the authored action | the copy (`copiedActionId`) |++Both swaps live in the bundle — `toSourceInput` and `toExecutableActionId` — not in app code, so an+author passes the definition and never branches on the environment.++`checkResourcesSynced` runs at `buildStart` for production builds only. It re-reads the source and+the lockfile and fails the build when they disagree, so a stale app can't ship: a stale build isn't+broken, it's silently pointed at whatever the saved question was when it was last synced.diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.tsnew file mode 100644index 00000000000..27565b04093--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/ast/query-source.ts@@ -0,0 +1,259 @@+import fs from "node:fs";+import path from "node:path";++import ts from "typescript";++import { SDK_PACKAGE_NAME } from "embedding-sdk-package/cli/constants/config";++export interface QuerySource {+ exportName: string;+ filePath: string;+}++interface InspectedQuerySource extends QuerySource {+ object: ts.ObjectLiteralExpression;+ sourceFile: ts.SourceFile;+}++/** A source-controlled definition kind, and where synchronization looks for it. */+export interface DefinitionKind {+ directory: string;+ factory: string;+ idKey: string;+ /** Article included, so it reads in "did not evaluate to … object". */+ description: string;+}++export const QUERY_DEFINITIONS: DefinitionKind = {+ directory: "queries",+ factory: "defineQuery",+ idKey: "savedQuestionSourceId",+ description: "a query",+};++export const ACTION_DEFINITIONS: DefinitionKind = {+ directory: "actions",+ factory: "defineAction",+ idKey: "copiedActionId",+ description: "an action",+};++const DATA_APP_MODULE = SDK_PACKAGE_NAME + "/data-app";++const QUERY_FILE_EXTENSIONS = [+ ".js",+ ".jsx",+ ".ts",+ ".tsx",+ ".cjs",+ ".cts",+ ".mjs",+ ".mts",+];++export function findDefinitionSources(+ appRoot: string,+ kind: DefinitionKind,+): QuerySource[] {+ return listQueryFiles(path.join(appRoot, kind.directory)).flatMap(+ (filePath) => inspectFile(filePath, kind),+ );+}++/** Writes a generated ID back into its definition. */+export function injectGeneratedId(+ target: QuerySource,+ kind: DefinitionKind,+ id: number,+) {+ const source = inspectFile(target.filePath, kind).find(+ ({ exportName }) => exportName === target.exportName,+ );++ if (!source) {+ throw new Error(+ `Could not find ${target.exportName} in ${target.filePath}.`,+ );+ }++ // Keep the definition's other properties and spreads, removing the old ID.+ const propertiesWithoutId = source.object.properties.filter(+ (prop) =>+ !(+ prop.name &&+ (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) &&+ prop.name.text === kind.idKey+ ),+ );++ // Put the generated ID last so a spread cannot overwrite it with an old ID.+ const updatedDefinition = ts.factory.updateObjectLiteralExpression(+ source.object,+ [+ ...propertiesWithoutId,++ ts.factory.createPropertyAssignment(+ kind.idKey,+ ts.factory.createNumericLiteral(id),+ ),+ ],+ );++ const replacement = ts+ .createPrinter()+ .printNode(ts.EmitHint.Expression, updatedDefinition, source.sourceFile);++ const contents = source.sourceFile.text;+ const updated = `${contents.slice(0, source.object.getStart(source.sourceFile))}${replacement}${contents.slice(source.object.getEnd())}`;+ fs.writeFileSync(target.filePath, updated);+}++function listQueryFiles(directory: string): string[] {+ if (!fs.existsSync(directory)) {+ return [];+ }++ return fs+ .readdirSync(directory, { withFileTypes: true })+ .flatMap((entry) => {+ const itemPath = path.join(directory, entry.name);+ return entry.isDirectory() ? listQueryFiles(itemPath) : [itemPath];+ })+ .filter(isQueryFile)+ .sort();+}++const isQueryFile = (filePath: string) =>+ QUERY_FILE_EXTENSIONS.some((extension) => filePath.endsWith(extension));++const hasExportModifier = (node: ts.Node) =>+ ts.canHaveModifiers(node)+ ? ts+ .getModifiers(node)+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)+ : false;++function isDataAppImport(+ statement: ts.Statement,+): statement is ts.ImportDeclaration {+ return (+ ts.isImportDeclaration(statement) &&+ ts.isStringLiteral(statement.moduleSpecifier) &&+ statement.moduleSpecifier.text === DATA_APP_MODULE+ );+}++function getDataAppNamedImports(statement: ts.Statement) {+ if (!isDataAppImport(statement)) {+ return undefined;+ }++ const namedBindings = statement.importClause?.namedBindings;++ if (!namedBindings || !ts.isNamedImports(namedBindings)) {+ return undefined;+ }++ return namedBindings.elements;+}++const isFactoryImport = (item: ts.ImportSpecifier, factory: string) =>+ (item.propertyName ?? item.name).text === factory;++const isDirectVariableInitialization = (+ declaration: ts.Node,+ initializer: ts.CallExpression,+): declaration is ts.VariableDeclaration & { name: ts.Identifier } =>+ ts.isVariableDeclaration(declaration) &&+ declaration.initializer === initializer &&+ ts.isIdentifier(declaration.name);++const isNamedExportStatement = (statement: ts.Node | undefined) =>+ Boolean(+ statement &&+ ts.isVariableStatement(statement) &&+ hasExportModifier(statement),+ );++const definitionObjectArgument = (node: ts.CallExpression) => {+ const [argument] = node.arguments;+ return node.arguments.length === 1 && ts.isObjectLiteralExpression(argument)+ ? argument+ : undefined;+};++const isDirectNamedDefinition = (+ node: ts.CallExpression,+ declaration: ts.Node,+ statement: ts.Node | undefined,+): declaration is ts.VariableDeclaration & { name: ts.Identifier } =>+ isDirectVariableInitialization(declaration, node) &&+ isNamedExportStatement(statement);++const isFactoryCall = (+ node: ts.Node,+ names: Set<string>,+): node is ts.CallExpression =>+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ names.has(node.expression.text);++function inspectFile(+ filePath: string,+ kind: DefinitionKind,+): InspectedQuerySource[] {+ const contents = fs.readFileSync(filePath, "utf8");++ const sourceFile = ts.createSourceFile(+ filePath,+ contents,+ ts.ScriptTarget.Latest,+ true,+ filePath.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );++ const factoryNames = new Set<string>();++ for (const statement of sourceFile.statements) {+ const namedImports = getDataAppNamedImports(statement);++ if (!namedImports) {+ continue;+ }++ for (const item of namedImports) {+ if (isFactoryImport(item, kind.factory)) {+ factoryNames.add(item.name.text);+ }+ }+ }++ const definitionSources: InspectedQuerySource[] = [];++ const visit = (node: ts.Node) => {+ if (isFactoryCall(node, factoryNames)) {+ const declaration = node.parent;+ const statement = declaration.parent?.parent;+ const object = definitionObjectArgument(node);++ if (!isDirectNamedDefinition(node, declaration, statement) || !object) {+ throw new Error(+ `${filePath}: ${kind.factory} must directly initialize a named exported variable with one object literal.`,+ );+ }++ definitionSources.push({+ exportName: declaration.name.text,+ filePath,+ object,+ sourceFile,+ });+ }++ ts.forEachChild(node, visit);+ };++ visit(sourceFile);++ return definitionSources;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.tsnew file mode 100644index 00000000000..a94441eccda--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/canonical.ts@@ -0,0 +1,135 @@+import { createHash } from "node:crypto";++import { isRecord } from "./guards";++/** Serializes a query with stable object-key ordering. */+export const canonicalJson = (value: unknown): string =>+ JSON.stringify(canonicalize(value));++/** Returns the source table and stable hash of an authored query. */+export function getQueryFingerprint(query: Record<string, unknown>) {+ const source = query.source;++ if (+ !isRecord(source) ||+ source.type !== "table" ||+ typeof source.id !== "number" ||+ !Number.isInteger(source.id) ||+ source.id <= 0+ ) {+ throw new Error("Synchronized queries must use a valid table source.");+ }++ const tableId = source.id;+ const authoredDsl: Record<string, unknown> = {+ ...query,+ source: { type: "table" },+ };++ delete authoredDsl.savedQuestionSourceId;++ const hash = createHash("sha256")+ .update(canonicalJson(authoredDsl))+ .digest("hex");++ return { tableId, hash: `v1:sha256:${hash}` };+}++/**+ * Returns the stable hash of a payload copied into a data app collection.+ * Generated Lib UUIDs are normalized so a re-read of the same source does not+ * read as drift.+ */+export function getPayloadFingerprint(value: unknown): string {+ const hash = createHash("sha256")+ .update(getCanonicalQueryJson(value))+ .digest("hex");++ return `v1:sha256:${hash}`;+}++/** Serializes a resolved query while removing generated Lib-only fields. */+export function getCanonicalQueryJson(value: unknown): string {+ const canonical = canonicalize(value);+ const generatedIds = new Map<string, number>();++ JSON.stringify(canonical, (key, item) => {+ if (+ key === "lib/uuid" &&+ typeof item === "string" &&+ !generatedIds.has(item)+ ) {+ generatedIds.set(item, generatedIds.size);+ }+ return item;+ });++ return JSON.stringify(canonical, (key, item) => {+ if (key === "lib/uuid") {+ return undefined;+ }+ if (key === "lib/metadata" && item === null) {+ return undefined;+ }+ const generatedId =+ typeof item === "string" ? generatedIds.get(item) : undefined;+ return generatedId === undefined+ ? item+ : `generated-query-id:${generatedId}`;+ });+}++/** Validates a query value and recursively sorts object keys. */+function canonicalize(value: unknown, seen = new Set<object>()): unknown {+ const type = typeof value;++ if (value === null || type === "string" || type === "boolean") {+ return value;+ }++ if (type === "number") {+ if (!Number.isFinite(value)) {+ throw new Error("Query definitions cannot contain non-finite numbers.");+ }++ return value;+ }++ if (typeof value !== "object") {+ throw new Error(`Query definitions cannot contain ${type} values.`);+ }++ if (seen.has(value)) {+ throw new Error("Query definitions cannot contain circular references.");+ }++ if (!Array.isArray(value)) {+ const prototype = Object.getPrototypeOf(value);++ if (prototype !== Object.prototype && prototype !== null) {+ throw new Error("Query definitions must contain only plain objects.");+ }+ }++ seen.add(value);++ const result = Array.isArray(value)+ ? value.map((item) => canonicalize(item, seen))+ : Object.fromEntries(+ Object.entries(value)+ .sort(([first], [second]) => {+ if (first < second) {+ return -1;+ }+ if (first > second) {+ return 1;+ }+ return 0;+ })+ .map(([key, item]) => [key, canonicalize(item, seen)]),+ );++ seen.delete(value);++ return result;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.tsnew file mode 100644index 00000000000..77b1a9223b5--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/discover.ts@@ -0,0 +1,229 @@+import { createRequire } from "node:module";+import path from "node:path";++import { build } from "esbuild";++import {+ ACTION_DEFINITIONS,+ type DefinitionKind,+ QUERY_DEFINITIONS,+ type QuerySource,+ findDefinitionSources,+} from "./ast/query-source";+import { canonicalJson, getQueryFingerprint } from "./canonical";+import { isPositiveInteger, isRecord } from "./guards";+import { getRelativeDefinitionLocation } from "./messages";+import type { DiscoveredAction, DiscoveredQuery } from "./types";++interface EvaluatedDefinition extends QuerySource {+ value: Record<string, unknown>;+}++async function evaluateModule(filePath: string) {+ const result = await build({+ absWorkingDir: path.dirname(filePath),+ bundle: true,+ entryPoints: [filePath],+ format: "cjs",+ packages: "external",+ platform: "node",+ target: "node20",+ write: false,+ logLevel: "silent",+ });++ const compiled = result.outputFiles[0]?.text;++ if (!compiled) {+ throw new Error(`Could not evaluate ${filePath}.`);+ }++ const runtimeModule: { exports: Record<string, unknown> } = { exports: {} };+ const runtimeRequire = createRequire(filePath);++ new Function("require", "module", "exports", compiled)(+ runtimeRequire,+ runtimeModule,+ runtimeModule.exports,+ );++ return runtimeModule.exports;+}++function positiveId(value: unknown, location: string, idKey: string) {+ if (value === undefined) {+ return undefined;+ }++ if (!isPositiveInteger(value)) {+ throw new Error(`${location} has an invalid ${idKey}.`);+ }++ return value;+}++/**+ * Evaluates every definition of `kind`, proving each one is deterministic so a+ * generated ID always describes the same authored value.+ */+async function evaluateDefinitions(+ appRoot: string,+ kind: DefinitionKind,+): Promise<EvaluatedDefinition[]> {+ const sourcesByFile = new Map<string, QuerySource[]>();++ for (const source of findDefinitionSources(appRoot, kind)) {+ sourcesByFile.set(source.filePath, [+ ...(sourcesByFile.get(source.filePath) ?? []),+ source,+ ]);+ }++ const evaluated: EvaluatedDefinition[] = [];++ for (const [filePath, fileSources] of sourcesByFile) {+ const [first, second] = await Promise.all([+ evaluateModule(filePath),+ evaluateModule(filePath),+ ]);++ for (const { exportName } of fileSources) {+ const value = first[exportName];+ const repeatedValue = second[exportName];++ const location = getRelativeDefinitionLocation(appRoot, {+ filePath,+ exportName,+ });++ if (!isRecord(value)) {+ throw new Error(+ `${location} did not evaluate to ${kind.description} object.`,+ );+ }++ let deterministic: boolean;+ try {+ deterministic = canonicalJson(value) === canonicalJson(repeatedValue);+ } catch (error) {+ throw new Error(+ `${location} could not be canonicalized: ${String(error)}`,+ );+ }++ if (!deterministic) {+ throw new Error(`${location} is not deterministic.`);+ }++ evaluated.push({ exportName, filePath, value });+ }+ }++ return evaluated;+}++/**+ * Rejects two definitions claiming the same ID, which would otherwise let one+ * copied definition silently take ownership of another's Metabase entity.+ */+function assertUniqueIds(+ entries: Array<{ id: number | undefined; location: string }>,+ subject: string,+) {+ const byId = new Map<number, string[]>();++ for (const { id, location } of entries) {+ if (id) {+ byId.set(id, [...(byId.get(id) ?? []), location]);+ }+ }++ for (const [id, locations] of byId) {+ if (locations.length > 1) {+ throw new Error(+ `${subject} ${id} is referenced by ${locations.join(", ")}. Remove the ID from the copied definition and sync again.`,+ );+ }+ }+}++export async function discoverQueries(+ appRoot: string,+): Promise<DiscoveredQuery[]> {+ const definitions = await evaluateDefinitions(appRoot, QUERY_DEFINITIONS);++ const discovered = definitions.map(({ exportName, filePath, value }) => {+ const { tableId, hash } = getQueryFingerprint(value);++ return {+ exportName,+ filePath,+ query: value,+ savedQuestionSourceId: positiveId(+ value[QUERY_DEFINITIONS.idKey],+ getRelativeDefinitionLocation(appRoot, { filePath, exportName }),+ QUERY_DEFINITIONS.idKey,+ ),+ tableId,+ hash,+ };+ });++ assertUniqueIds(+ discovered.map((query) => ({+ id: query.savedQuestionSourceId,+ location: getRelativeDefinitionLocation(appRoot, query),+ })),+ "Saved question",+ );++ return discovered;+}++export async function discoverActions(+ appRoot: string,+): Promise<DiscoveredAction[]> {+ const definitions = await evaluateDefinitions(appRoot, ACTION_DEFINITIONS);++ const discovered = definitions.map(({ exportName, filePath, value }) => {+ const location = getRelativeDefinitionLocation(appRoot, {+ filePath,+ exportName,+ });+ const action = value.action;++ if (!isRecord(action) || !isPositiveInteger(action.id)) {+ throw new Error(+ `${location} must reference a generated action, such as \`schema.models.<model>.actions.<action>\`.`,+ );+ }++ return {+ exportName,+ filePath,+ copiedActionId: positiveId(+ value[ACTION_DEFINITIONS.idKey],+ location,+ ACTION_DEFINITIONS.idKey,+ ),+ sourceActionId: action.id,+ };+ });++ assertUniqueIds(+ discovered.map((action) => ({+ id: action.sourceActionId,+ location: getRelativeDefinitionLocation(appRoot, action),+ })),+ "Action",+ );+ assertUniqueIds(+ discovered.map((action) => ({+ id: action.copiedActionId,+ location: getRelativeDefinitionLocation(appRoot, action),+ })),+ "Generated action",+ );++ return discovered;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.tsnew file mode 100644index 00000000000..cc908a52ddc--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/env.ts@@ -0,0 +1,27 @@+import fs from "node:fs";+import path from "node:path";+import { parseEnv } from "node:util";++import { findEnvRoot } from "../data-app-dev/config/find-env-root";++function parseEnvFile(filePath: string) {+ if (!fs.existsSync(filePath)) {+ return {};+ }+ return parseEnv(fs.readFileSync(filePath, "utf8"));+}++export function getResourceSyncCredentials(appRoot: string) {+ const values = {+ ...parseEnvFile(path.join(findEnvRoot(appRoot), ".env.local")),+ ...process.env,+ };+ const metabaseUrl = values.DATA_APP_MB_URL;+ const apiKey = values.DATA_APP_MB_API_KEY;+ if (!metabaseUrl || !apiKey) {+ throw new Error(+ "DATA_APP_MB_URL and DATA_APP_MB_API_KEY must be set in .env.local.",+ );+ }+ return { metabaseUrl, apiKey };+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.tsnew file mode 100644index 00000000000..de7346b74c4--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/guards.ts@@ -0,0 +1,8 @@+/** Metabase IDs are always positive integers, so anything else is corrupt input. */+export function isPositiveInteger(value: unknown): value is number {+ return typeof value === "number" && Number.isInteger(value) && value > 0;+}++/** A plain object, as distinct from an array or null. */+export const isRecord = (value: unknown): value is Record<string, unknown> =>+ value !== null && typeof value === "object" && !Array.isArray(value);diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.tsnew file mode 100644index 00000000000..49fdb0f1e26--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/lockfile.ts@@ -0,0 +1,189 @@+import fs from "node:fs";+import path from "node:path";++import { isPositiveInteger, isRecord } from "./guards";+import type {+ ActionLockEntry,+ MetricLockEntry,+ ModelLockEntry,+ QueryLockEntry,+ ResourceLockfile,+} from "./types";++export const RESOURCE_LOCKFILE = "resources_metadata.json";++const HASH_PATTERN = /^v1:sha256:[0-9a-f]{64}$/;++function isHash(value: unknown): value is string {+ return typeof value === "string" && HASH_PATTERN.test(value);+}++function isQueryLockEntry(value: unknown): value is QueryLockEntry {+ return (+ isRecord(value) &&+ isPositiveInteger(value.tableId) &&+ isPositiveInteger(value.savedQuestionSourceId) &&+ isHash(value.hash)+ );+}++function isActionLockEntry(value: unknown): value is ActionLockEntry {+ return (+ isRecord(value) &&+ isPositiveInteger(value.sourceActionId) &&+ isPositiveInteger(value.copiedActionId) &&+ isHash(value.hash)+ );+}++function isModelLockEntry(value: unknown): value is ModelLockEntry {+ return (+ isRecord(value) &&+ isPositiveInteger(value.sourceModelId) &&+ isPositiveInteger(value.copiedModelId) &&+ isHash(value.hash) &&+ Array.isArray(value.actions) &&+ value.actions.every(isActionLockEntry)+ );+}++function isMetricLockEntry(value: unknown): value is MetricLockEntry {+ return (+ isRecord(value) &&+ isPositiveInteger(value.sourceMetricId) &&+ isPositiveInteger(value.copiedMetricId) &&+ isHash(value.hash)+ );+}++function parseMetrics(value: unknown): MetricLockEntry[] {+ if (value === undefined) {+ return [];+ }++ if (+ !Array.isArray(value) ||+ value.some((entry) => !isMetricLockEntry(entry))+ ) {+ throw new Error(`${RESOURCE_LOCKFILE} contains an invalid metric entry.`);+ }++ assertUnique(+ value.map((entry) => entry.sourceMetricId),+ "source metric ID",+ );++ assertUnique(+ value.map((entry) => entry.copiedMetricId),+ "copied metric ID",+ );++ return value;+}++function assertUnique(ids: number[], subject: string) {+ if (new Set(ids).size !== ids.length) {+ throw new Error(`${RESOURCE_LOCKFILE} contains a duplicate ${subject}.`);+ }+}++function parseQueries(value: unknown): QueryLockEntry[] {+ if (+ !Array.isArray(value) ||+ value.some((entry) => !isQueryLockEntry(entry))+ ) {+ throw new Error(`${RESOURCE_LOCKFILE} contains an invalid entry.`);+ }++ const queries: QueryLockEntry[] = value;++ assertUnique(+ queries.map((entry) => entry.savedQuestionSourceId),+ "saved question ID",+ );++ return queries;+}++function parseModels(value: unknown): ModelLockEntry[] {+ if (value === undefined) {+ return [];+ }++ if (+ !Array.isArray(value) ||+ value.some((entry) => !isModelLockEntry(entry))+ ) {+ throw new Error(`${RESOURCE_LOCKFILE} contains an invalid model entry.`);+ }++ const models: ModelLockEntry[] = value;++ assertUnique(+ models.map((entry) => entry.sourceModelId),+ "source model ID",+ );+ assertUnique(+ models.map((entry) => entry.copiedModelId),+ "copied model ID",+ );+ assertUnique(+ models.flatMap((entry) =>+ entry.actions.map(({ sourceActionId }) => sourceActionId),+ ),+ "source action ID",+ );+ assertUnique(+ models.flatMap((entry) =>+ entry.actions.map(({ copiedActionId }) => copiedActionId),+ ),+ "copied action ID",+ );++ return models;+}++export function readResourceLockfile(appRoot: string): ResourceLockfile {+ const lockfilePath = path.join(appRoot, RESOURCE_LOCKFILE);++ if (!fs.existsSync(lockfilePath)) {+ return { queries: [], models: [], metrics: [] };+ }++ let value: unknown;+ try {+ value = JSON.parse(fs.readFileSync(lockfilePath, "utf8"));+ } catch (error) {+ throw new Error(`Could not read ${RESOURCE_LOCKFILE}: ${String(error)}`);+ }++ if (!isRecord(value)) {+ throw new Error(`${RESOURCE_LOCKFILE} contains an invalid entry.`);+ }++ if (+ value.collectionId !== undefined &&+ !isPositiveInteger(value.collectionId)+ ) {+ throw new Error(`${RESOURCE_LOCKFILE} contains an invalid collection ID.`);+ }++ return {+ ...(value.collectionId === undefined+ ? undefined+ : { collectionId: value.collectionId }),+ queries: parseQueries(value.queries ?? []),+ models: parseModels(value.models),+ metrics: parseMetrics(value.metrics),+ };+}++export function writeResourceLockfile(+ appRoot: string,+ lockfile: ResourceLockfile,+) {+ fs.writeFileSync(+ path.join(appRoot, RESOURCE_LOCKFILE),+ `${JSON.stringify(lockfile, null, 2)}\n`,+ );+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.tsnew file mode 100644index 00000000000..66c6841ee81--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/messages.ts@@ -0,0 +1,12 @@+import path from "node:path";++export function getErrorMessage(error: unknown) {+ return error instanceof Error ? error.message : String(error);+}++export function getRelativeDefinitionLocation(+ appRoot: string,+ { filePath, exportName }: { filePath: string; exportName: string },+) {+ return `${path.relative(appRoot, filePath)}:${exportName}`;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.tsnew file mode 100644index 00000000000..775a8203e9a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/metabase-client.ts@@ -0,0 +1,268 @@+import type {+ DataAppMetadata,+ DataAppMetric,+ MetabaseAction,+ MetabaseCard,+} from "./types";++export class MetabaseApiError extends Error {+ constructor(+ public readonly status: number,+ message: string,+ ) {+ super(message);+ }+}++/**+ * Resolves to `null` on a confirmed 404, so a caller can treat "gone" as+ * recoverable. Any other failure still throws: only a 404 proves the entity is+ * absent rather than unreachable.+ */+export const orNullOn404 = async <T>(+ request: Promise<T>,+): Promise<T | null> => {+ try {+ return await request;+ } catch (error) {+ if (error instanceof MetabaseApiError && error.status === 404) {+ return null;+ }+ throw error;+ }+};++export class MetabaseClient {+ constructor(+ private readonly baseUrl: string,+ private readonly apiKey: string,+ ) {}++ private async request<T>(pathname: string, init?: RequestInit): Promise<T> {+ const baseUrl = new URL(this.baseUrl);+ baseUrl.pathname = `${baseUrl.pathname.replace(/\/?$/, "/")}api/${pathname.replace(/^\//, "")}`;+ const requestUrl = baseUrl;+ const method = (init?.method ?? "GET").toUpperCase();+ const response = await fetch(requestUrl, {+ ...init,+ signal: init?.signal ?? AbortSignal.timeout(60_000),+ headers: {+ "content-type": "application/json",+ "x-api-key": this.apiKey,+ ...init?.headers,+ },+ });+ if (!response.ok) {+ const message = await response.text();+ throw new MetabaseApiError(+ response.status,+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- CLI protocol error names the remote service.+ `Metabase returned ${response.status} for ${method} ${requestUrl}: ${message}`,+ );+ }+ if (response.status === 204) {+ // The generic return type is controlled by the caller for no-content requests.+ return undefined as T;+ }+ const body: unknown = await response.json();+ // The endpoint-specific methods define the trusted API response contract.+ return body as T;+ }++ ensureDraft(slug: string) {+ return this.request<DataAppMetadata>(+ `apps/${encodeURIComponent(slug)}/draft`,+ { method: "POST" },+ );+ }++ updateTableDependencies(slug: string, tableIds: number[]) {+ return this.request<DataAppMetadata>(+ `apps/${encodeURIComponent(slug)}/table-dependencies`,+ {+ method: "PUT",+ body: JSON.stringify({ table_ids: tableIds }),+ },+ );+ }++ /**+ * Resolves the tables that already-saved queries read. Only the server sees an+ * implicit join: the table a foreign key reaches appears nowhere in the query,+ * so walking its JSON would leave that table out of the app's dependencies.+ */+ async resolveTableDependencies(+ slug: string,+ datasetQueries: ReadonlyArray<Record<string, unknown>>,+ ): Promise<number[]> {+ if (datasetQueries.length === 0) {+ return [];+ }++ const { table_ids } = await this.request<{ table_ids: number[] }>(+ `apps/${encodeURIComponent(slug)}/query-table-dependencies`,+ {+ method: "POST",+ body: JSON.stringify({ dataset_queries: datasetQueries }),+ },+ );++ return table_ids;+ }++ async resolveQuery(slug: string, query: Record<string, unknown>) {+ const resolved = await this.request<{+ database_id: number;+ dataset_query: Record<string, unknown>;+ table_ids: number[];+ metrics?: DataAppMetric[];+ }>(`apps/${encodeURIComponent(slug)}/query`, {+ method: "POST",+ body: JSON.stringify({ stages: [query] }),+ });+ return { ...resolved, metrics: resolved.metrics ?? [] };+ }++ getCard(id: number) {+ return this.request<MetabaseCard>(`card/${id}`);+ }++ createCard(input: {+ name: string;+ collectionId: number;+ datasetQuery: Record<string, unknown>;+ }) {+ return this.request<MetabaseCard>("card", {+ method: "POST",+ body: JSON.stringify({+ name: input.name,+ type: "question",+ dataset_query: input.datasetQuery,+ display: "table",+ visualization_settings: {},+ collection_id: input.collectionId,+ }),+ });+ }++ updateCard(+ id: number,+ input: {+ name: string;+ collectionId: number;+ datasetQuery: Record<string, unknown>;+ },+ ) {+ return this.request<MetabaseCard>(`card/${id}`, {+ method: "PUT",+ body: JSON.stringify({+ name: input.name,+ type: "question",+ dataset_query: input.datasetQuery,+ collection_id: input.collectionId,+ archived: false,+ }),+ });+ }++ moveCardToCollection(id: number, collectionId: number) {+ return this.request<MetabaseCard>(`card/${id}`, {+ method: "PUT",+ body: JSON.stringify({ collection_id: collectionId }),+ });+ }++ deleteCard(id: number) {+ return this.request<void>(`card/${id}`, { method: "DELETE" });+ }++ createModel(input: ModelInput) {+ return this.request<MetabaseCard>("card", {+ method: "POST",+ body: JSON.stringify(modelBody(input)),+ });+ }++ createMetric(input: MetricInput) {+ return this.request<MetabaseCard>("card", {+ method: "POST",+ body: JSON.stringify(metricBody(input)),+ });+ }++ updateMetric(id: number, input: MetricInput) {+ return this.request<MetabaseCard>(`card/${id}`, {+ method: "PUT",+ body: JSON.stringify(metricBody(input)),+ });+ }++ updateModel(id: number, input: ModelInput) {+ return this.request<MetabaseCard>(`card/${id}`, {+ method: "PUT",+ body: JSON.stringify(modelBody(input)),+ });+ }++ getAction(id: number) {+ return this.request<MetabaseAction>(`action/${id}`);+ }++ createAction(body: Record<string, unknown>) {+ return this.request<MetabaseAction>("action", {+ method: "POST",+ body: JSON.stringify(body),+ });+ }++ updateAction(id: number, body: Record<string, unknown>) {+ return this.request<MetabaseAction>(`action/${id}`, {+ method: "PUT",+ body: JSON.stringify(body),+ });+ }++ deleteAction(id: number) {+ return this.request<void>(`action/${id}`, { method: "DELETE" });+ }+}++interface ModelInput {+ name: string;+ collectionId: number;+ datasetQuery: Record<string, unknown>;+ display: string;+ visualizationSettings: Record<string, unknown>;+ description: string | null;+}++interface MetricInput {+ name: string;+ collectionId: number;+ datasetQuery: Record<string, unknown>;+ display: string;+ visualizationSettings: Record<string, unknown>;+ description: string | null;+}++const modelBody = (input: ModelInput) => ({+ name: input.name,+ type: "model",+ archived: false,+ dataset_query: input.datasetQuery,+ display: input.display,+ visualization_settings: input.visualizationSettings,+ description: input.description,+ collection_id: input.collectionId,+});++const metricBody = (input: MetricInput) => ({+ name: input.name,+ type: "metric",+ archived: false,+ dataset_query: input.datasetQuery,+ display: input.display,+ visualization_settings: input.visualizationSettings,+ description: input.description,+ collection_id: input.collectionId,+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.tsnew file mode 100644index 00000000000..4b7e3e69e66--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-metrics.ts@@ -0,0 +1,309 @@+import { getPayloadFingerprint } from "./canonical";+import { isPositiveInteger, isRecord } from "./guards";+import { writeResourceLockfile } from "./lockfile";+import type { MetabaseClient } from "./metabase-client";+import { orNullOn404 } from "./metabase-client";+import { getSavedCardSourceIds } from "./saved-card-sources";+import type { DataAppMetric, ResourceLockfile } from "./types";++interface ResolvedQuery {+ dataset_query: Record<string, unknown>;+ metrics: DataAppMetric[];+}++const metricInput = (metric: DataAppMetric, collectionId: number) => ({+ name: metric.name,+ collectionId,+ datasetQuery: metric.dataset_query,+ display: metric.display ?? "table",+ visualizationSettings: metric.visualization_settings ?? {},+ description: metric.description ?? null,+});++type MetricClause = readonly [+ type: "metric",+ options: unknown,+ metricId: number,+ ...rest: unknown[],+];++// A MBQL metric clause has the form ["metric", options, metricId].+const METRIC_ID_INDEX = 2;++const isMetricCard = (value: { type: string }): value is DataAppMetric =>+ value.type === "metric";++const isMetricClause = (clause: unknown): clause is MetricClause =>+ Array.isArray(clause) &&+ clause[0] === "metric" &&+ typeof clause[METRIC_ID_INDEX] === "number";++function getMetricClauseIds(+ clause: unknown,+ ids = new Set<number>(),+): Set<number> {+ if (Array.isArray(clause)) {+ if (isMetricClause(clause)) {+ ids.add(clause[METRIC_ID_INDEX]);++ return ids;+ }++ clause.forEach((item) => getMetricClauseIds(item, ids));+ } else if (isRecord(clause)) {+ Object.values(clause).forEach((item) => getMetricClauseIds(item, ids));+ }++ return ids;+}++/**+ * Rewrite a metric clause to+ * swap the original metric id with the copied metric id.+ */+function rewriteMetricClause(+ [type, options, metricId, ...rest]: MetricClause,+ copiedMetricIdBySourceMetricId: Map<number, number>,+): MetricClause {+ const copiedMetricId = copiedMetricIdBySourceMetricId.get(metricId);++ if (copiedMetricId === undefined) {+ throw new Error(`Missing copied metric for metric ${metricId}.`);+ }++ return [type, options, copiedMetricId, ...rest];+}++function rewriteMetricClauses(+ clause: unknown,+ copiedMetricIdBySourceMetricId: Map<number, number>,+): unknown {+ if (Array.isArray(clause)) {+ if (isMetricClause(clause)) {+ return rewriteMetricClause(clause, copiedMetricIdBySourceMetricId);+ }++ return clause.map((item) =>+ rewriteMetricClauses(item, copiedMetricIdBySourceMetricId),+ );+ }++ if (clause === null || typeof clause !== "object") {+ return clause;+ }++ return Object.fromEntries(+ Object.entries(clause).map(([key, item]) => [+ key,+ rewriteMetricClauses(item, copiedMetricIdBySourceMetricId),+ ]),+ );+}++function removeMetricLockEntry(+ appRoot: string,+ lockfile: ResourceLockfile,+ sourceMetricId: number,+) {+ const index = lockfile.metrics.findIndex(+ (entry) => entry.sourceMetricId === sourceMetricId,+ );++ if (index >= 0) {+ lockfile.metrics.splice(index, 1);+ writeResourceLockfile(appRoot, lockfile);+ }+}++type ReconcilerContext = {+ appRoot: string;+ collectionId: number;+ lockfile: ResourceLockfile;+ log: (message: string) => void;+};++export async function reconcileRemovedMetrics({+ appRoot,+ collectionId,+ previousEntries,+ liveMetricIds,+ lockfile,+ client,+ log,+}: ReconcilerContext & {+ liveMetricIds: Set<number>;+ previousEntries: ResourceLockfile["metrics"];++ client: Pick<MetabaseClient, "getCard" | "deleteCard">;+}) {+ for (const entry of previousEntries) {+ if (liveMetricIds.has(entry.sourceMetricId)) {+ continue;+ }++ const copiedMetric = await orNullOn404(+ client.getCard(entry.copiedMetricId),+ );++ if (copiedMetric?.archived === true) {+ // archived metrics are moved to the trash collection, so we cannot tell+ // whether the copied metric were moved elsewhere before being trashed.+ // leave it in trash and stop tracking it instead of permanently deleting it.+ log(`left in the trash: metric ${copiedMetric.id}`);+ } else if (copiedMetric) {+ if (+ !isMetricCard(copiedMetric) ||+ copiedMetric.collection_id !== collectionId+ ) {+ throw new Error(+ `Metric ${copiedMetric.id} is no longer in data app collection ${collectionId}. Move it back, then run sync-resources again.`,+ );+ }++ await client.deleteCard(copiedMetric.id);++ log(`deleted metric: ${copiedMetric.id}`);+ }++ removeMetricLockEntry(appRoot, lockfile, entry.sourceMetricId);+ }+}++export async function reconcileMetrics({+ appRoot,+ collectionId,+ resolvedQueries,+ lockfile,+ client,+ log,+}: ReconcilerContext & {+ resolvedQueries: ResolvedQuery[];++ client: Pick<+ MetabaseClient,+ "getCard" | "createMetric" | "updateMetric" | "deleteCard"+ >;+}) {+ const previousEntries = [...lockfile.metrics];++ const metrics = [+ ...new Map(+ resolvedQueries.flatMap(({ metrics }) =>+ metrics.map((metric) => [metric.id, metric]),+ ),+ ).values(),+ ];++ const liveMetricIds = new Set(metrics.map((metric) => metric.id));++ const missingMetricIds = [+ ...new Set(+ resolvedQueries.flatMap(({ dataset_query }) => [+ ...getMetricClauseIds(dataset_query),+ ]),+ ),+ ]+ .filter((metricId) => !liveMetricIds.has(metricId))+ .sort((a, b) => a - b);++ if (missingMetricIds.length > 0) {+ throw new Error(+ `These metrics are missing and cannot be reconciled: ${missingMetricIds.join(", ")}.`,+ );+ }++ const metricsWithSavedCardSources = metrics+ .filter((metric) => getSavedCardSourceIds(metric.dataset_query).size > 0)+ .map((metric) => metric.id)+ .sort((a, b) => a - b);++ if (metricsWithSavedCardSources.length > 0) {+ throw new Error(+ `Metrics with saved-card joins cannot be synchronized: ${metricsWithSavedCardSources.join(", ")}.`,+ );+ }++ const copiedMetricIdBySourceMetricId = new Map<number, number>();++ for (const metric of metrics) {+ const input = metricInput(metric, collectionId);+ const hash = getPayloadFingerprint(input);++ const entry = lockfile.metrics.find(+ ({ sourceMetricId }) => sourceMetricId === metric.id,+ );++ const copiedMetric = entry+ ? await orNullOn404(client.getCard(entry.copiedMetricId))+ : null;++ if (copiedMetric) {+ // track metrics that are moved out of the data app collection, but allow+ // archived metrics (moved to the trash collection) to be restored+ const isOutsideDataAppCollection =+ copiedMetric.collection_id !== collectionId &&+ copiedMetric.archived !== true;++ if (!isMetricCard(copiedMetric) || isOutsideDataAppCollection) {+ throw new Error(+ `Metric ${copiedMetric.id} is not managed by data app collection ${collectionId}.`,+ );+ }++ const changed =+ copiedMetric.archived === true ||+ getPayloadFingerprint(metricInput(copiedMetric, collectionId)) !== hash;++ if (changed) {+ await client.updateMetric(copiedMetric.id, input);+ }++ copiedMetricIdBySourceMetricId.set(metric.id, copiedMetric.id);++ if (entry) {+ entry.hash = hash;+ }++ log(+ `${changed ? "updated" : "unchanged"} metric: ${metric.id} -> ${copiedMetric.id}`,+ );+ } else {+ const created = await client.createMetric(input);++ if (!isPositiveInteger(created.id)) {+ throw new Error("The copied metric does not have a valid ID.");+ }++ copiedMetricIdBySourceMetricId.set(metric.id, created.id);++ if (entry) {+ Object.assign(entry, { copiedMetricId: created.id, hash });+ } else {+ lockfile.metrics.push({+ hash,+ sourceMetricId: metric.id,+ copiedMetricId: created.id,+ });+ }++ log(`copied metric: ${metric.id} -> ${created.id}`);+ }++ writeResourceLockfile(appRoot, lockfile);+ }++ for (const resolved of resolvedQueries) {+ const rewrittenMetricQuery = rewriteMetricClauses(+ resolved.dataset_query,+ copiedMetricIdBySourceMetricId,+ );++ if (!isRecord(rewrittenMetricQuery)) {+ throw new Error("Rewritten metric query must be an object.");+ }++ resolved.dataset_query = rewrittenMetricQuery;+ }++ return { previousEntries, liveMetricIds };+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-models.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-models.tsnew file mode 100644index 00000000000..deedc03c543--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile-models.ts@@ -0,0 +1,453 @@+import { ACTION_DEFINITIONS, injectGeneratedId } from "./ast/query-source";+import { getPayloadFingerprint } from "./canonical";+import { isPositiveInteger } from "./guards";+import { writeResourceLockfile } from "./lockfile";+import { getErrorMessage, getRelativeDefinitionLocation } from "./messages";+import type { MetabaseClient } from "./metabase-client";+import { orNullOn404 } from "./metabase-client";+import { getSavedCardSourceIds } from "./saved-card-sources";+import type {+ ActionLockEntry,+ DiscoveredAction,+ MetabaseAction,+ MetabaseCard,+ ModelLockEntry,+ ResourceLockfile,+} from "./types";++export interface ReconcileModelsOptions {+ appRoot: string;+ slug: string;+ collectionId: number;+ actions: DiscoveredAction[];+ lockfile: ResourceLockfile;+ client: MetabaseClient;+ log: (message: string) => void;+}++interface ResolvedAction {+ action: DiscoveredAction;+ source: MetabaseAction;+}++interface ModelContext {+ appRoot: string;+ collectionId: number;+ client: MetabaseClient;+ lockfile: ResourceLockfile;+ log: (message: string) => void;+}++function pickDefined(source: Record<string, unknown>) {+ return Object.fromEntries(+ Object.entries(source).filter(([, value]) => value !== undefined),+ );+}++/** Also the fingerprint input, so drift is measured over exactly what gets copied. */+function modelCopyInput(source: MetabaseCard) {+ return {+ name: source.name,+ datasetQuery: source.dataset_query,+ display: source.display ?? "table",+ visualizationSettings: source.visualization_settings ?? {},+ description: source.description ?? null,+ };+}++/**+ * Implicit actions omit `parameters` and `parameter_mappings`: Metabase derives+ * those from the model's fields on every read.+ */+function actionCopyFields(source: MetabaseAction) {+ const common = {+ name: source.name,+ type: source.type,+ description: source.description,+ visualization_settings: source.visualization_settings,+ };++ if (source.type === "implicit") {+ return pickDefined({ ...common, kind: source.kind });+ }++ if (source.type === "query") {+ return pickDefined({+ ...common,+ parameters: source.parameters,+ parameter_mappings: source.parameter_mappings,+ dataset_query: source.dataset_query,+ database_id: source.database_id,+ });+ }+ return pickDefined(common);+}++async function resolveActions(+ appRoot: string,+ actions: DiscoveredAction[],+ client: MetabaseClient,+): Promise<ResolvedAction[]> {+ return Promise.all(+ actions.map(async (action) => {+ let source: MetabaseAction;+ try {+ // `GET /api/action/:id` filters archived actions out, so an archived+ // source surfaces here as a 404 rather than a readable payload.+ source = await client.getAction(action.sourceActionId);+ } catch (error) {+ throw new Error(+ `Could not read action ${action.sourceActionId} for ${getRelativeDefinitionLocation(appRoot, action)}: ${getErrorMessage(error)}`,+ );+ }++ if (!isPositiveInteger(source.model_id)) {+ throw new Error(+ `${getRelativeDefinitionLocation(appRoot, action)} references action ${action.sourceActionId}, which does not belong to a model.`,+ );+ }++ return { action, source };+ }),+ );+}++async function fetchSourceModels(+ appRoot: string,+ desired: Map<number, ResolvedAction[]>,+ client: MetabaseClient,+): Promise<Map<number, MetabaseCard>> {+ const models = await Promise.all(+ [...desired].map(async ([id, actions]) => {+ const location = getRelativeDefinitionLocation(+ appRoot,+ actions[0].action,+ );++ let card: MetabaseCard;+ try {+ card = await client.getCard(id);+ } catch (error) {+ throw new Error(+ `Could not read model ${id} for ${location}: ${getErrorMessage(error)}`,+ );+ }++ if (card.type !== "model") {+ throw new Error(+ `${location} references an action on card ${id}, which is not a model.`,+ );+ }++ // A trashed action reads as a 404 and stops the run; a trashed model is+ // still readable, so refuse it here rather than copying from something+ // its author deleted.+ if (card.archived === true) {+ throw new Error(+ `${location} references an action on model ${id}, which is in the trash. Restore the model or remove the declaration, then run sync-resources again.`,+ );+ }++ if (getSavedCardSourceIds(card.dataset_query).size > 0) {+ throw new Error(+ `Model ${id} depends on saved questions and cannot be synchronized. Use a model without saved question sources or joins.`,+ );+ }++ return [id, card] as const;+ }),+ );++ return new Map(models);+}++function assertOwnedActionCopy(+ action: MetabaseAction,+ sourceActionId: number,+ copiedModelId: number,+) {+ if (action.model_id !== copiedModelId) {+ throw new Error(+ `Action ${action.id} is the copy of action ${sourceActionId} but no longer hangs off copied model ${copiedModelId}, so it was left untouched. Move it back or delete it manually, then run sync-resources again.`,+ );+ }+}++function assertOwnedModelCopy(card: MetabaseCard, collectionId: number) {+ if (card.type !== "model") {+ throw new Error(+ `Card ${card.id} belongs to a synchronized model but is no longer a model, so it was left untouched. Change it back to a model in data app collection ${collectionId} or delete it manually, then run sync-resources again.`,+ );+ }++ // A trashed copy reports the Trash as its collection, so its real one says+ // nothing here. Only the restore path reaches this with one, and it puts both+ // the card and its collection back.+ if (card.archived !== true && card.collection_id !== collectionId) {+ throw new Error(+ `Card ${card.id} belongs to a synchronized model but is no longer in the data app collection, so it was left untouched. Move card ${card.id} back to data app collection ${collectionId} or delete it manually, then run sync-resources again.`,+ );+ }+}++async function reconcileModelActions(+ context: ModelContext,+ entry: ModelLockEntry,+ desiredActions: ResolvedAction[],+) {+ const { appRoot, client, lockfile, log } = context;+ const desiredIds = new Set(desiredActions.map(({ source }) => source.id));++ for (const { action, source } of desiredActions) {+ const fields = actionCopyFields(source);+ const hash = getPayloadFingerprint(fields);+ let mapping: ActionLockEntry | undefined = entry.actions.find(+ ({ sourceActionId }) => sourceActionId === source.id,+ );+ const copiedAction = mapping+ ? await orNullOn404(client.getAction(mapping.copiedActionId))+ : null;++ if (mapping && copiedAction) {+ assertOwnedActionCopy(copiedAction, source.id, entry.copiedModelId);+ }++ if (mapping && !copiedAction) {+ entry.actions.splice(entry.actions.indexOf(mapping), 1);+ mapping = undefined;+ }++ if (!mapping || !copiedAction) {+ const created = await client.createAction({+ ...fields,+ model_id: entry.copiedModelId,+ });++ if (!isPositiveInteger(created.id)) {+ throw new Error("The Action API did not return a valid action ID.");+ }++ entry.actions.push({+ sourceActionId: source.id,+ copiedActionId: created.id,+ hash,+ });++ injectGeneratedId(action, ACTION_DEFINITIONS, created.id);+ writeResourceLockfile(appRoot, lockfile);+ log(`copied action: action ${source.id} -> action ${created.id}`);++ continue;+ }++ // Fingerprint the copy rather than trusting the lockfile: that also catches+ // a copy edited directly in Metabase, which the source hash cannot see.+ if (getPayloadFingerprint(actionCopyFields(copiedAction)) !== hash) {+ await client.updateAction(mapping.copiedActionId, fields);++ mapping.hash = hash;++ writeResourceLockfile(appRoot, lockfile);+ log(`updated action: action ${mapping.copiedActionId}`);+ }++ if (action.copiedActionId !== mapping.copiedActionId) {+ injectGeneratedId(action, ACTION_DEFINITIONS, mapping.copiedActionId);+ log(+ `restored action ID: ${action.exportName} -> action ${mapping.copiedActionId}`,+ );+ }+ }++ for (const mapping of [...entry.actions]) {+ if (desiredIds.has(mapping.sourceActionId)) {+ continue;+ }++ const copiedAction = await orNullOn404(+ client.getAction(mapping.copiedActionId),+ );++ if (copiedAction && copiedAction.model_id !== entry.copiedModelId) {+ throw new Error(+ `Action ${mapping.copiedActionId} belongs to a removed declaration but no longer hangs off copied model ${entry.copiedModelId}, so it was left untouched. Move it back or delete it manually, then run sync-resources again.`,+ );+ }++ if (copiedAction) {+ await client.deleteAction(mapping.copiedActionId);+ log(`deleted action: action ${mapping.copiedActionId}`);+ }++ entry.actions.splice(entry.actions.indexOf(mapping), 1);+ writeResourceLockfile(appRoot, lockfile);+ }+}++async function reconcileModel(+ context: ModelContext,+ sourceModel: MetabaseCard,+ desiredActions: ResolvedAction[],+) {+ const { appRoot, collectionId, client, lockfile, log } = context;+ const hash = getPayloadFingerprint(modelCopyInput(sourceModel));+ const index = lockfile.models.findIndex(+ ({ sourceModelId }) => sourceModelId === sourceModel.id,+ );+ const previous = index >= 0 ? lockfile.models[index] : undefined;+ const copy = previous+ ? await orNullOn404(client.getCard(previous.copiedModelId))+ : null;++ if (previous && copy) {+ assertOwnedModelCopy(copy, collectionId);++ // `archived` is deliberately not part of the fingerprint: it describes the+ // copy's state, not the payload, and folding it in would invalidate every+ // lockfile written before this.+ if (+ copy.archived === true ||+ getPayloadFingerprint(modelCopyInput(copy)) !== hash+ ) {+ await client.updateModel(previous.copiedModelId, {+ ...modelCopyInput(sourceModel),+ collectionId,+ });+ previous.hash = hash;+ writeResourceLockfile(appRoot, lockfile);+ log(`updated model: card ${previous.copiedModelId}`);+ }++ await reconcileModelActions(context, previous, desiredActions);++ return;+ }++ if (previous) {+ lockfile.models.splice(index, 1);+ }++ const created = await client.createModel({+ ...modelCopyInput(sourceModel),+ collectionId,+ });++ if (!isPositiveInteger(created.id)) {+ throw new Error("The Card API did not return a valid model ID.");+ }++ const entry: ModelLockEntry = {+ sourceModelId: sourceModel.id,+ copiedModelId: created.id,+ hash,+ actions: [],+ };++ lockfile.models.push(entry);++ writeResourceLockfile(appRoot, lockfile);+ log(+ previous+ ? `recreated model: card ${previous.copiedModelId} -> card ${created.id}`+ : `copied model: model ${sourceModel.id} -> card ${created.id}`,+ );++ await reconcileModelActions(context, entry, desiredActions);+}++async function removeUnusedModels(+ context: ModelContext,+ previousModels: ModelLockEntry[],+ desiredModelIds: Set<number>,+) {+ const { appRoot, collectionId, client, lockfile, log } = context;+ for (const entry of previousModels) {+ if (desiredModelIds.has(entry.sourceModelId)) {+ continue;+ }++ const index = lockfile.models.findIndex(+ ({ sourceModelId }) => sourceModelId === entry.sourceModelId,+ );++ if (index < 0) {+ continue;+ }++ const copy = await orNullOn404(client.getCard(entry.copiedModelId));++ if (copy?.archived === true) {+ // The trash masks a card's collection, so this reads the same as a copy+ // moved out and trashed afterwards. Deleting is permanent, and the card is+ // already where someone put it to be deleted.+ log(`left in the trash: card ${copy.id}`);+ } else if (copy) {+ assertOwnedModelCopy(copy, collectionId);+ // Deleting the copy cascades to the actions copied onto it.+ await client.deleteCard(copy.id);+ log(`deleted model: card ${copy.id}`);+ }++ lockfile.models.splice(index, 1);++ writeResourceLockfile(appRoot, lockfile);+ }+}++/**+ * Makes the data app collection hold exactly the models its actions belong to,+ * copying a model when its first action appears and deleting it when its last+ * action goes away. Returns the tables those models and actions read.+ */+export async function reconcileModels({+ appRoot,+ slug,+ collectionId,+ actions,+ lockfile,+ client,+ log,+}: ReconcileModelsOptions) {+ const previousModels = [...lockfile.models];+ const resolved = await resolveActions(appRoot, actions, client);++ const desired = new Map<number, ResolvedAction[]>();++ for (const entry of resolved) {+ desired.set(entry.source.model_id, [+ ...(desired.get(entry.source.model_id) ?? []),+ entry,+ ]);+ }++ const sourceModels = await fetchSourceModels(appRoot, desired, client);+ const context: ModelContext = {+ appRoot,+ collectionId,+ client,+ lockfile,+ log,+ };++ for (const [sourceModelId, desiredActions] of desired) {+ const sourceModel = sourceModels.get(sourceModelId);+ if (sourceModel) {+ await reconcileModel(context, sourceModel, desiredActions);+ }+ }++ await removeUnusedModels(context, previousModels, new Set(desired.keys()));++ const modelQueries = [...sourceModels.values()].map(+ (model) => model.dataset_query,+ );++ const actionQueries = resolved.flatMap(({ source }) =>+ source.dataset_query ? [source.dataset_query] : [],+ );++ return client.resolveTableDependencies(slug, [+ ...modelQueries,+ ...actionQueries,+ ]);+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.tsnew file mode 100644index 00000000000..cbe94ecb983--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/reconcile.ts@@ -0,0 +1,507 @@+import fs from "node:fs";+import path from "node:path";++import { QUERY_DEFINITIONS, injectGeneratedId } from "./ast/query-source";+import { getCanonicalQueryJson } from "./canonical";+import { isPositiveInteger } from "./guards";+import { RESOURCE_LOCKFILE, writeResourceLockfile } from "./lockfile";+import { getErrorMessage, getRelativeDefinitionLocation } from "./messages";+import type { MetabaseClient } from "./metabase-client";+import { orNullOn404 } from "./metabase-client";+import { reconcileMetrics, reconcileRemovedMetrics } from "./reconcile-metrics";+import type {+ DiscoveredQuery,+ QueryLockEntry,+ ResourceLockfile,+} from "./types";++type QueryCard = Awaited<ReturnType<MetabaseClient["getCard"]>>;++interface ResolvedQuery {+ query: DiscoveredQuery;+ resolved: Awaited<ReturnType<MetabaseClient["resolveQuery"]>>;+}++interface ReconciliationContext {+ appRoot: string;+ collectionId: number;+ client: MetabaseClient;+ lockfile: ResourceLockfile;+ recoveredIds: Map<DiscoveredQuery, number>;+ repairedLockfileIds: Set<number>;+ cardsById: Map<number, QueryCard | null>;+ log: (message: string) => void;+}++export interface ReconcileQueriesOptions {+ appRoot: string;+ slug: string;+ collectionId: number;+ queries: DiscoveredQuery[];+ lockfile: ResourceLockfile;+ client: MetabaseClient;+ log: (message: string) => void;+}++function queryWithoutGeneratedId(query: DiscoveredQuery) {+ const authored = { ...query.query };+ delete authored.savedQuestionSourceId;+ return authored;+}++function lockEntry(query: DiscoveredQuery, id: number): QueryLockEntry {+ return {+ tableId: query.tableId,+ hash: query.hash,+ savedQuestionSourceId: id,+ };+}++function replaceLockEntry(+ entries: QueryLockEntry[],+ previousId: number | undefined,+ next: QueryLockEntry,+) {+ const index = previousId+ ? entries.findIndex(+ ({ savedQuestionSourceId }) => savedQuestionSourceId === previousId,+ )+ : -1;+ if (index >= 0) {+ entries[index] = next;+ } else {+ entries.push(next);+ }+}++function recoverMissingQueryIds(+ appRoot: string,+ queries: DiscoveredQuery[],+ previousEntries: QueryLockEntry[],+) {+ const claimedIds = new Set(+ queries.flatMap(({ savedQuestionSourceId }) =>+ savedQuestionSourceId ? [savedQuestionSourceId] : [],+ ),+ );+ const recoveredIds = new Map<DiscoveredQuery, number>();++ for (const query of queries) {+ if (query.savedQuestionSourceId) {+ continue;+ }++ const candidates = previousEntries.filter(+ (entry) =>+ entry.tableId === query.tableId &&+ entry.hash === query.hash &&+ !claimedIds.has(entry.savedQuestionSourceId),+ );++ if (candidates.length > 1) {+ throw new Error(+ `${getRelativeDefinitionLocation(appRoot, query)} matches multiple lockfile entries. Restore its savedQuestionSourceId manually and run sync-resources again.`,+ );+ }++ const [candidate] = candidates;++ if (candidate) {+ recoveredIds.set(query, candidate.savedQuestionSourceId);+ claimedIds.add(candidate.savedQuestionSourceId);+ }+ }++ return recoveredIds;+}++function savedQuestionId(+ query: DiscoveredQuery,+ recoveredIds: Map<DiscoveredQuery, number>,+) {+ return query.savedQuestionSourceId ?? recoveredIds.get(query);+}++async function resolveQueries(+ appRoot: string,+ slug: string,+ queries: DiscoveredQuery[],+ client: MetabaseClient,+): Promise<ResolvedQuery[]> {+ return Promise.all(+ queries.map(async (query) => {+ try {+ return {+ query,+ resolved: await client.resolveQuery(+ slug,+ queryWithoutGeneratedId(query),+ ),+ };+ } catch (error) {+ throw new Error(+ `Could not resolve ${getRelativeDefinitionLocation(appRoot, query)}: ${getErrorMessage(error)}`,+ );+ }+ }),+ );+}++async function fetchReferencedCards(+ queries: DiscoveredQuery[],+ recoveredIds: Map<DiscoveredQuery, number>,+ client: MetabaseClient,+) {+ const cardsById = new Map<number, QueryCard | null>();+ await Promise.all(+ queries.map(async (query) => {+ const id = savedQuestionId(query, recoveredIds);++ if (!id) {+ return;+ }++ cardsById.set(id, await orNullOn404(client.getCard(id)));+ }),+ );+ return cardsById;+}++function findLockfileRepairs(+ queries: DiscoveredQuery[],+ recoveredIds: Map<DiscoveredQuery, number>,+ entries: QueryLockEntry[],+ cardsById: Map<number, QueryCard | null>,+ collectionId: number,+) {+ const repairs: Array<{ query: DiscoveredQuery; id: number }> = [];++ for (const query of queries) {+ const id = savedQuestionId(query, recoveredIds);++ if (!id) {+ continue;+ }++ const card = cardsById.get(id);++ if (card && card.id !== id) {+ throw new Error(+ `The Card API returned card ${card.id} when card ${id} was requested.`,+ );+ }++ if (!card) {+ continue;+ }++ const isLockfileProven = entries.some(+ ({ savedQuestionSourceId }) => savedQuestionSourceId === id,+ );++ if (isLockfileProven) {+ if (card.type !== "question") {+ throw new Error(`Card ${id} is no longer a saved question.`);+ }++ continue;+ }++ if (card.archived === true) {+ throw new Error(+ `${query.exportName} references card ${id}, which is in the trash. Restore it to data app collection ${collectionId} to publish it again, or drop \`savedQuestionSourceId: ${id}\` from the declaration to publish a new copy, then run sync-resources again.`,+ );+ }++ if (card.type !== "question" || card.collection_id !== collectionId) {+ throw new Error(+ `${query.exportName} references card ${id}, but the lockfile does not prove ownership and the card cannot be safely adopted.`,+ );+ }++ repairs.push({ query, id });+ }++ return repairs;+}++function applyLockfileRepairs(+ appRoot: string,+ lockfile: ResourceLockfile,+ repairs: Array<{ query: DiscoveredQuery; id: number }>,+) {+ const repairedIds = new Set<number>();++ for (const { query, id } of repairs) {+ lockfile.queries.push(lockEntry(query, id));+ writeResourceLockfile(appRoot, lockfile);+ repairedIds.add(id);+ }++ return repairedIds;+}++function queriesMatch(card: QueryCard, resolved: ResolvedQuery["resolved"]) {+ return (+ getCanonicalQueryJson(card.dataset_query) ===+ getCanonicalQueryJson(resolved.dataset_query)+ );+}++function logExistingCardOutcome(+ context: ReconciliationContext,+ query: DiscoveredQuery,+ card: QueryCard,+ existingEntry: QueryLockEntry,+ needsUpdate: boolean,+) {+ const { recoveredIds, repairedLockfileIds, log } = context;+ const recoveredId = recoveredIds.get(query);++ if (needsUpdate) {+ const authoredChanged =+ existingEntry.tableId !== query.tableId ||+ existingEntry.hash !== query.hash;+ const action =+ authoredChanged || card.name !== query.exportName+ ? "updated"+ : "restored";+ const checkpoint = recoveredId+ ? "restored source ID, "+ : repairedLockfileIds.has(card.id)+ ? "repaired lockfile, "+ : "";++ log(`${checkpoint}${action}: card ${card.id}`);+ } else if (recoveredId) {+ log(`restored source ID: ${query.exportName} -> card ${card.id}`);+ } else if (repairedLockfileIds.has(card.id)) {+ log(`repaired lockfile: ${query.exportName} -> card ${card.id}`);+ } else {+ log(`unchanged: card ${card.id}`);+ }+}++async function reconcileLiveQuery(+ context: ReconciliationContext,+ { query, resolved }: ResolvedQuery,+) {+ const { appRoot, collectionId, client, lockfile, recoveredIds, cardsById } =+ context;+ const authoritative = {+ name: query.exportName,+ collectionId,+ datasetQuery: resolved.dataset_query,+ };+ const recoveredId = recoveredIds.get(query);+ const previousId = savedQuestionId(query, recoveredIds);+ const card = previousId ? cardsById.get(previousId) : null;++ if (!card) {+ const created = await client.createCard(authoritative);++ if (!isPositiveInteger(created.id)) {+ throw new Error("The Card API did not return a valid saved question ID.");+ }++ injectGeneratedId(query, QUERY_DEFINITIONS, created.id);+ replaceLockEntry(+ lockfile.queries,+ previousId,+ lockEntry(query, created.id),+ );+ writeResourceLockfile(appRoot, lockfile);+ context.log(+ previousId+ ? `recreated: card ${previousId} -> card ${created.id}`+ : `created: ${query.exportName} -> card ${created.id}`,+ );++ return created.id;+ }++ if (recoveredId) {+ injectGeneratedId(query, QUERY_DEFINITIONS, recoveredId);+ }++ const existingEntry = lockfile.queries.find(+ ({ savedQuestionSourceId }) => savedQuestionSourceId === card.id,+ );++ if (!existingEntry) {+ throw new Error(+ `${query.exportName} references card ${card.id}, but the lockfile does not prove ownership.`,+ );+ }++ if (card.type !== "question") {+ throw new Error(`Card ${card.id} is no longer a saved question.`);+ }++ const needsUpdate =+ card.name !== query.exportName ||+ card.collection_id !== collectionId ||+ // A copy trashed on its own keeps its collection, so only `archived` says so.+ card.archived === true ||+ !queriesMatch(card, resolved);++ if (needsUpdate) {+ await client.updateCard(card.id, authoritative);+ }++ logExistingCardOutcome(context, query, card, existingEntry, needsUpdate);+ replaceLockEntry(lockfile.queries, card.id, lockEntry(query, card.id));+ writeResourceLockfile(appRoot, lockfile);++ return card.id;+}++async function reconcileLiveQueries(+ context: ReconciliationContext,+ resolvedQueries: ResolvedQuery[],+) {+ const liveIds = new Set<number>();++ for (const resolvedQuery of resolvedQueries) {+ liveIds.add(await reconcileLiveQuery(context, resolvedQuery));+ }++ return liveIds;+}++function removeLockEntry(+ appRoot: string,+ lockfile: ResourceLockfile,+ id: number,+) {+ const index = lockfile.queries.findIndex(+ ({ savedQuestionSourceId }) => savedQuestionSourceId === id,+ );++ if (index >= 0) {+ lockfile.queries.splice(index, 1);+ writeResourceLockfile(appRoot, lockfile);+ }+}++async function reconcileRemovedQueries(+ context: ReconciliationContext,+ previousEntries: QueryLockEntry[],+ liveIds: Set<number>,+) {+ const { appRoot, collectionId, client, lockfile, log } = context;+ for (const entry of previousEntries) {+ if (liveIds.has(entry.savedQuestionSourceId)) {+ continue;+ }++ const card = await orNullOn404(client.getCard(entry.savedQuestionSourceId));++ if (!card) {+ removeLockEntry(appRoot, lockfile, entry.savedQuestionSourceId);++ continue;+ }++ // The trash masks a card's collection, so a copy trashed from the app+ // collection reads the same as one moved out and trashed afterwards. Stop+ // tracking it either way: deleting is permanent, and the card is already+ // where someone put it to be deleted.+ if (card.archived === true) {+ removeLockEntry(appRoot, lockfile, card.id);+ log(`left in the trash: card ${card.id}`);++ continue;+ }++ if (card.type !== "question" || card.collection_id !== collectionId) {+ const recovery =+ card.type === "question"+ ? `Move card ${card.id} back to data app collection ${collectionId} or delete it manually`+ : `Change card ${card.id} back to a saved question in data app collection ${collectionId} or delete it manually`;++ throw new Error(+ `Card ${card.id} belongs to a removed query but is no longer an owned question in the data app collection, so it was left untouched. ${recovery}, then run sync-resources again.`,+ );+ }++ await client.deleteCard(card.id);++ removeLockEntry(appRoot, lockfile, card.id);+ log(`deleted: card ${card.id}`);+ }+}++export async function reconcileQueries({+ appRoot,+ slug,+ collectionId,+ queries,+ lockfile,+ client,+ log,+}: ReconcileQueriesOptions) {+ const previousEntries = [...lockfile.queries];+ const recoveredIds = recoverMissingQueryIds(+ appRoot,+ queries,+ previousEntries,+ );+ const resolvedQueries = await resolveQueries(appRoot, slug, queries, client);+ const metricReconciliation = await reconcileMetrics({+ appRoot,+ collectionId,+ resolvedQueries: resolvedQueries.map(({ resolved }) => resolved),+ lockfile,+ client,+ log,+ });+ const cardsById = await fetchReferencedCards(queries, recoveredIds, client);+ const repairs = findLockfileRepairs(+ queries,+ recoveredIds,+ lockfile.queries,+ cardsById,+ collectionId,+ );+ const repairedLockfileIds = applyLockfileRepairs(appRoot, lockfile, repairs);+ const context: ReconciliationContext = {+ appRoot,+ collectionId,+ client,+ lockfile,+ recoveredIds,+ repairedLockfileIds,+ cardsById,+ log,+ };+ const liveIds = await reconcileLiveQueries(context, resolvedQueries);++ await reconcileRemovedMetrics({+ appRoot,+ collectionId,+ ...metricReconciliation,+ lockfile,+ client,+ log,+ });+ await reconcileRemovedQueries(context, previousEntries, liveIds);++ if (!fs.existsSync(path.join(appRoot, RESOURCE_LOCKFILE))) {+ writeResourceLockfile(appRoot, lockfile);+ }++ const queryTableIds = resolvedQueries.flatMap(+ ({ resolved }) => resolved.table_ids,+ );+ const metricTableIds = await client.resolveTableDependencies(+ slug,+ resolvedQueries.flatMap(({ resolved }) =>+ resolved.metrics.map((metric) => metric.dataset_query),+ ),+ );++ return [...new Set([...queryTableIds, ...metricTableIds])].sort(+ (a, b) => a - b,+ );+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.tsnew file mode 100644index 00000000000..2155e6caf5f--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/saved-card-sources.ts@@ -0,0 +1,31 @@+import { isPositiveInteger, isRecord } from "./guards";++/**+ * Finds saved-question IDs used as sources anywhere in a query, including joins and nested stages.+ * Supports `source-card` IDs and legacy `source-table: "card__<id>"` references.+ */+export function getSavedCardSourceIds(+ query: unknown,+ ids = new Set<number>(),+): Set<number> {+ if (Array.isArray(query)) {+ query.forEach((item) => getSavedCardSourceIds(item, ids));+ } else if (isRecord(query)) {+ Object.entries(query).forEach(([key, value]) => {+ if (key === "source-card" && isPositiveInteger(value)) {+ ids.add(value);+ } else if (key === "source-table" && typeof value === "string") {+ const match = /^card__(\d+)$/.exec(value);+ const id = match && Number(match[1]);++ if (isPositiveInteger(id)) {+ ids.add(id);+ }+ }++ getSavedCardSourceIds(value, ids);+ });+ }++ return ids;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.tsnew file mode 100644index 00000000000..0f26582cfe3--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/sync.ts@@ -0,0 +1,202 @@+import path from "node:path";++import { discoverActions, discoverQueries } from "./discover";+import { isPositiveInteger } from "./guards";+import {+ RESOURCE_LOCKFILE,+ readResourceLockfile,+ writeResourceLockfile,+} from "./lockfile";+import { MetabaseClient, orNullOn404 } from "./metabase-client";+import { reconcileQueries } from "./reconcile";+import { reconcileModels } from "./reconcile-models";+import type { DiscoveredAction, ResourceLockfile } from "./types";++export interface SyncResourcesOptions {+ appRoot: string;+ metabaseUrl: string;+ apiKey: string;+ log?: (message: string) => void;+}++function staleDefinition(+ appRoot: string,+ definition: { filePath: string; exportName: string },+): never {+ throw new Error(+ `${path.relative(appRoot, definition.filePath)}:${definition.exportName} is not synchronized. Run \`npm run sync-resources\` and rebuild.`,+ );+}++function checkQueriesSynchronized(+ appRoot: string,+ queries: Awaited<ReturnType<typeof discoverQueries>>,+ lockfile: ResourceLockfile,+) {+ const byId = new Map(+ lockfile.queries.map((entry) => [entry.savedQuestionSourceId, entry]),+ );+ for (const query of queries) {+ const id = query.savedQuestionSourceId;+ const entry = id ? byId.get(id) : undefined;+ if (+ !id ||+ !entry ||+ entry.tableId !== query.tableId ||+ entry.hash !== query.hash+ ) {+ staleDefinition(appRoot, query);+ }+ }+ const liveIds = new Set(+ queries.flatMap(({ savedQuestionSourceId }) =>+ savedQuestionSourceId ? [savedQuestionSourceId] : [],+ ),+ );+ if (+ lockfile.queries.some(+ ({ savedQuestionSourceId }) => !liveIds.has(savedQuestionSourceId),+ )+ ) {+ throw new Error(+ `${RESOURCE_LOCKFILE} contains a removed query. Run \`npm run sync-resources\` and rebuild.`,+ );+ }+}++function checkActionsSynchronized(+ appRoot: string,+ actions: DiscoveredAction[],+ lockfile: ResourceLockfile,+) {+ const byId = new Map(+ lockfile.models.flatMap((model) =>+ model.actions.map((entry) => [entry.sourceActionId, entry] as const),+ ),+ );++ for (const action of actions) {+ const entry = byId.get(action.sourceActionId);++ if (!entry || entry.copiedActionId !== action.copiedActionId) {+ staleDefinition(appRoot, action);+ }+ }++ const liveIds = new Set(actions.map(({ sourceActionId }) => sourceActionId));+ const hasRemovedAction = lockfile.models.some(+ (model) =>+ model.actions.length === 0 ||+ model.actions.some(({ sourceActionId }) => !liveIds.has(sourceActionId)),+ );++ if (hasRemovedAction) {+ throw new Error(+ `${RESOURCE_LOCKFILE} contains a removed action. Run \`npm run sync-resources\` and rebuild.`,+ );+ }+}++export async function checkResourcesSynced(appRoot: string) {+ const [queries, actions] = await Promise.all([+ discoverQueries(appRoot),+ discoverActions(appRoot),+ ]);+ const lockfile = readResourceLockfile(appRoot);++ checkQueriesSynchronized(appRoot, queries, lockfile);+ checkActionsSynchronized(appRoot, actions, lockfile);+}++/**+ * Move synchronized copies when the app gets a new collection. Collection read+ * access lets app viewers run the copies. Move only copies that remain in the+ * previous synchronized collection.+ */+async function moveCopiesToAppCollection(+ appRoot: string,+ lockfile: ResourceLockfile,+ collectionId: number,+ client: MetabaseClient,+ log: (message: string) => void,+) {+ const previousCollectionId = lockfile.collectionId;++ if (previousCollectionId === collectionId) {+ return;+ }++ if (previousCollectionId !== undefined) {+ const copiedCardIds = [+ ...lockfile.queries.map((entry) => entry.savedQuestionSourceId),+ ...lockfile.models.map((entry) => entry.copiedModelId),+ ...lockfile.metrics.map((entry) => entry.copiedMetricId),+ ];++ for (const cardId of copiedCardIds) {+ const card = await orNullOn404(client.getCard(cardId));++ if (card?.collection_id !== previousCollectionId) {+ continue;+ }++ await client.moveCardToCollection(cardId, collectionId);+ log(`moved card ${cardId} into data app collection ${collectionId}`);+ }+ }++ lockfile.collectionId = collectionId;+ writeResourceLockfile(appRoot, lockfile);+}++export async function syncResources({+ appRoot,+ metabaseUrl,+ apiKey,+ log = (message) => process.stdout.write(`${message}\n`),+}: SyncResourcesOptions) {+ const [queries, actions] = await Promise.all([+ discoverQueries(appRoot),+ discoverActions(appRoot),+ ]);+ const lockfile = readResourceLockfile(appRoot);+ const client = new MetabaseClient(metabaseUrl, apiKey);+ const slug = path.basename(appRoot);+ const app = await client.ensureDraft(slug);+ if (!isPositiveInteger(app.resource_collection_id)) {+ throw new Error(`Data app ${slug} does not have a resource collection.`);+ }++ await moveCopiesToAppCollection(+ appRoot,+ lockfile,+ app.resource_collection_id,+ client,+ log,+ );++ const queryTableIds = await reconcileQueries({+ appRoot,+ slug,+ collectionId: app.resource_collection_id,+ queries,+ lockfile,+ client,+ log,+ });+ const modelTableIds = await reconcileModels({+ appRoot,+ slug,+ collectionId: app.resource_collection_id,+ actions,+ lockfile,+ client,+ log,+ });++ const tableIds = [...new Set([...queryTableIds, ...modelTableIds])].sort(+ (a, b) => a - b,+ );++ await client.updateTableDependencies(slug, tableIds);+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.tsnew file mode 100644index 00000000000..230d0206348--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/canonical.unit.spec.ts@@ -0,0 +1,86 @@+import {+ canonicalJson,+ getCanonicalQueryJson,+ getQueryFingerprint,+} from "../canonical";++import { setupResourceSyncTests } from "./setup";++describe("query canonicalization", () => {+ setupResourceSyncTests();++ it("uses a property-order-independent authored DSL fingerprint", () => {+ const first = getQueryFingerprint({+ source: { type: "table", id: 1 },+ limit: 5,+ });+ const second = getQueryFingerprint({+ limit: 5,+ source: { id: 2, type: "table" },+ savedQuestionSourceId: 99,+ });+ expect(first.hash).toBe(second.hash);+ expect(first.tableId).toBe(1);+ expect(second.tableId).toBe(2);+ expect(canonicalJson({ b: 1, a: 2 })).toBe('{"a":2,"b":1}');+ expect(canonicalJson({ ä: 2, z: 1 })).toBe('{"z":1,"ä":2}');+ });++ it("rejects non-serializable query definitions", () => {+ expect(() => canonicalJson({ value: undefined })).toThrow(+ "cannot contain undefined values",+ );+ });++ it("rejects unsupported values and invalid table sources", () => {+ const circular: { self?: unknown } = {};+ circular.self = circular;++ expect(() => canonicalJson(circular)).toThrow("circular references");+ expect(() => canonicalJson({ value: new Date() })).toThrow(+ "only plain objects",+ );+ expect(() => canonicalJson({ value: Infinity })).toThrow(+ "non-finite numbers",+ );+ expect(() => getQueryFingerprint({})).toThrow("valid table source");+ expect(() =>+ getQueryFingerprint({ source: { type: "table", id: 0 } }),+ ).toThrow("valid table source");+ });++ it("preserves references while normalizing generated query IDs", () => {+ const queryWithGeneratedIds = (+ firstId: string,+ secondId: string,+ orderById: string,+ ) => ({+ stages: [+ {+ aggregation: [+ ["sum", { "lib/uuid": firstId }, ["field", {}, 1]],+ ["sum", { "lib/uuid": secondId }, ["field", {}, 2]],+ ],+ "order-by": [["desc", {}, ["aggregation", {}, orderById]]],+ },+ ],+ });+ const normalized = (value: unknown) => getCanonicalQueryJson(value);+ const first = queryWithGeneratedIds("first-a", "second-a", "second-a");+ const same = queryWithGeneratedIds("first-b", "second-b", "second-b");+ const different = queryWithGeneratedIds("first-c", "second-c", "first-c");++ expect(normalized(first)).toBe(normalized(same));+ expect(normalized(first)).not.toBe(normalized(different));+ });++ it("omits empty lib/metadata from query", () => {+ expect(+ getCanonicalQueryJson({+ database: 1,+ stages: [],+ "lib/metadata": null,+ }),+ ).toBe(getCanonicalQueryJson({ database: 1, stages: [] }));+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.tsnew file mode 100644index 00000000000..fa6c372eebf--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/discover.unit.spec.ts@@ -0,0 +1,228 @@+import fs from "node:fs";++import {+ ACTION_DEFINITIONS,+ QUERY_DEFINITIONS,+ injectGeneratedId,+} from "../ast/query-source";+import { discoverActions, discoverQueries } from "../discover";+import { checkResourcesSynced } from "../sync";++import {+ FAKE_HASH,+ makeApp,+ setupResourceSyncTests,+ writeAction,+ writeQuery,+ writeQueryLockfile,+} from "./setup";++describe("query discovery", () => {+ setupResourceSyncTests();++ it("discovers a direct named definition", async () => {+ const appRoot = makeApp();+ writeQuery(+ appRoot,+ `export const Orders = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 }, limit: 5 });`,+ );++ await expect(discoverQueries(appRoot)).resolves.toEqual([+ expect.objectContaining({+ exportName: "Orders",+ savedQuestionSourceId: 10,+ tableId: 1,+ hash: expect.stringMatching(/^v1:sha256:[a-f0-9]{64}$/),+ }),+ ]);+ });++ it("rejects copied saved question IDs", async () => {+ const appRoot = makeApp();++ writeQuery(+ appRoot,+ `export const First = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 } });+ export const Second = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 } });`,+ );++ await expect(discoverQueries(appRoot)).rejects.toThrow(+ "Saved question 10 is referenced by",+ );+ });++ it("replaces a quoted saved question ID", async () => {+ const appRoot = makeApp();+ const filePath = writeQuery(+ appRoot,+ `export const Orders = defineQuery({ "savedQuestionSourceId": 10, source: { type: "table", id: 1 } });`,+ );+ const [query] = await discoverQueries(appRoot);++ injectGeneratedId(query, QUERY_DEFINITIONS, 20);++ const contents = fs.readFileSync(filePath, "utf8");+ expect(contents).toContain("savedQuestionSourceId: 20");+ expect(contents).not.toContain('savedQuestionSourceId": 10');+ });++ it.each([+ ["a shorthand ID", "savedQuestionSourceId"],+ ["a spread ID", "...defaults"],+ [+ "an explicit ID followed by a spread",+ "savedQuestionSourceId: 10, ...defaults",+ ],+ ])("reuses the generated query ID instead of %s", async (_, properties) => {+ const appRoot = makeApp();++ writeQuery(+ appRoot,+ `const savedQuestionSourceId = 10;+ const defaults = { savedQuestionSourceId };+ export const Orders = defineQuery({ ${properties}, source: { type: "table", id: 1 } });`,+ );++ const [query] = await discoverQueries(appRoot);+ injectGeneratedId(query, QUERY_DEFINITIONS, 20);++ const [updatedQuery] = await discoverQueries(appRoot);+ expect(updatedQuery.savedQuestionSourceId).toBe(20);+ injectGeneratedId(updatedQuery, QUERY_DEFINITIONS, 30);++ const [recoveredQuery] = await discoverQueries(appRoot);+ expect(recoveredQuery.savedQuestionSourceId).toBe(30);+ });++ it("fails a read-only build check when source and lockfile drift", async () => {+ const appRoot = makeApp();++ writeQuery(+ appRoot,+ `export const Orders = defineQuery({ savedQuestionSourceId: 10, source: { type: "table", id: 1 }, limit: 5 });`,+ );++ writeQueryLockfile(appRoot, [+ {+ tableId: 1,+ hash: FAKE_HASH,+ savedQuestionSourceId: 10,+ },+ ]);++ await expect(checkResourcesSynced(appRoot)).rejects.toThrow(+ "is not synchronized",+ );+ });+});++describe("action discovery", () => {+ setupResourceSyncTests();++ it("discovers named definitions and the action each references", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `export const Create = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });+ export const Update = defineAction({ action: { id: 52, parameters: [] } });`,+ );++ const discovered = await discoverActions(appRoot);++ expect(+ discovered.map(({ exportName, sourceActionId, copiedActionId }) => ({+ exportName,+ sourceActionId,+ copiedActionId,+ })),+ ).toEqual([+ { exportName: "Create", sourceActionId: 51, copiedActionId: 91 },+ { exportName: "Update", sourceActionId: 52, copiedActionId: undefined },+ ]);+ });++ it("reuses the generated action ID instead of shorthand and spread IDs", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `const copiedActionId = 91;+ const defaults = { copiedActionId };+ export const Create = defineAction({ copiedActionId, ...defaults, action: { id: 51, parameters: [] } });`,+ );++ const [action] = await discoverActions(appRoot);+ injectGeneratedId(action, ACTION_DEFINITIONS, 92);++ const [updatedAction] = await discoverActions(appRoot);+ expect(updatedAction.copiedActionId).toBe(92);+ });++ it("rejects two definitions claiming the same source action", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `export const First = defineAction({ action: { id: 51, parameters: [] } });+ export const Second = defineAction({ action: { id: 51, parameters: [] } });`,+ );++ await expect(discoverActions(appRoot)).rejects.toThrow(+ "Action 51 is referenced by",+ );+ });++ it("rejects a copied definition that carries another's generated ID", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `export const First = defineAction({ copiedActionId: 91, action: { id: 51, parameters: [] } });+ export const Second = defineAction({ copiedActionId: 91, action: { id: 52, parameters: [] } });`,+ );++ await expect(discoverActions(appRoot)).rejects.toThrow(+ "Generated action 91 is referenced by",+ );+ });++ it("rejects a definition that does not reference a generated action", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `export const Create = defineAction({ action: { name: "not a schema entry" } });`,+ );++ await expect(discoverActions(appRoot)).rejects.toThrow(+ "must reference a generated action",+ );+ });++ it("rejects a hand-edited generated ID", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `export const Create = defineAction({ copiedActionId: 0, action: { id: 51, parameters: [] } });`,+ );++ await expect(discoverActions(appRoot)).rejects.toThrow(+ "has an invalid copiedActionId",+ );+ });++ it("requires a definition to initialize an exported variable", async () => {+ const appRoot = makeApp();++ writeAction(+ appRoot,+ `const Create = defineAction({ action: { id: 51, parameters: [] } });`,+ );++ await expect(discoverActions(appRoot)).rejects.toThrow(+ "defineAction must directly initialize a named exported variable",+ );+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.tsnew file mode 100644index 00000000000..5538152f687--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/env.unit.spec.ts@@ -0,0 +1,43 @@+import fs from "node:fs";+import path from "node:path";++import { getResourceSyncCredentials } from "../env";++import { makeApp, setupResourceSyncTests } from "./setup";++describe("resource sync credentials", () => {+ setupResourceSyncTests();++ it("loads credentials from the repository .env.local", () => {+ const repoRoot = makeApp();+ const appRoot = path.join(repoRoot, "data_apps/orders");+ fs.mkdirSync(appRoot, { recursive: true });+ fs.writeFileSync(+ path.join(repoRoot, ".env.local"),+ "DATA_APP_MB_URL=http://metabase.test\nDATA_APP_MB_API_KEY=file-key\n",+ );+ jest.replaceProperty(process, "env", {});++ expect(getResourceSyncCredentials(appRoot)).toEqual({+ metabaseUrl: "http://metabase.test",+ apiKey: "file-key",+ });+ });++ it("prefers process environment credentials", () => {+ const appRoot = makeApp();+ fs.writeFileSync(+ path.join(appRoot, ".env.local"),+ "DATA_APP_MB_URL=http://file.test\nDATA_APP_MB_API_KEY=file-key\n",+ );+ jest.replaceProperty(process, "env", {+ DATA_APP_MB_URL: "http://process.test",+ DATA_APP_MB_API_KEY: "process-key",+ });++ expect(getResourceSyncCredentials(appRoot)).toEqual({+ metabaseUrl: "http://process.test",+ apiKey: "process-key",+ });+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.tsnew file mode 100644index 00000000000..28ef8e6a0dc--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/lockfile.unit.spec.ts@@ -0,0 +1,138 @@+import fs from "node:fs";+import path from "node:path";++import { RESOURCE_LOCKFILE, readResourceLockfile } from "../lockfile";+import type { ResourceLockfile } from "../types";++import { FAKE_HASH, makeApp, setupResourceSyncTests } from "./setup";++function write(appRoot: string, value: unknown) {+ fs.writeFileSync(+ path.join(appRoot, RESOURCE_LOCKFILE),+ typeof value === "string" ? value : JSON.stringify(value),+ );+}++function query(savedQuestionSourceId: number) {+ return { tableId: 1, hash: FAKE_HASH, savedQuestionSourceId };+}++function model(+ sourceModelId: number,+ copiedModelId: number,+ actions: Array<[number, number]> = [],+) {+ return {+ sourceModelId,+ copiedModelId,+ hash: FAKE_HASH,+ actions: actions.map(([sourceActionId, copiedActionId]) => ({+ sourceActionId,+ copiedActionId,+ hash: FAKE_HASH,+ })),+ };+}++describe("resource lockfile", () => {+ setupResourceSyncTests();++ it("reads an absent lockfile as empty", () => {+ expect(readResourceLockfile(makeApp())).toEqual({+ queries: [],+ models: [],+ metrics: [],+ });+ });++ it("round-trips queries and models", () => {+ const appRoot = makeApp();+ const lockfile: ResourceLockfile = {+ queries: [query(40)],+ models: [model(5, 80, [[51, 91]])],+ metrics: [],+ };+ write(appRoot, lockfile);++ expect(readResourceLockfile(appRoot)).toEqual(lockfile);+ });++ it("defaults a missing models key rather than failing", () => {+ const appRoot = makeApp();+ write(appRoot, { queries: [query(40)] });++ expect(readResourceLockfile(appRoot)).toEqual({+ queries: [query(40)],+ models: [],+ metrics: [],+ });+ });++ // A lockfile is an ownership record: every rejection below is a file that+ // would otherwise let synchronization mutate content it cannot prove it owns.+ it.each([+ ["unparseable JSON", "{ not json", "Could not read"],+ // A bare array is the shape no version writes; accepting it would let a+ // hand-edited file silently drop every model entry.+ ["a bare array", [query(40)], "contains an invalid entry"],+ [+ "a malformed hash",+ { queries: [{ ...query(40), hash: "nope" }] },+ "contains an invalid entry",+ ],+ [+ "a non-integer saved question ID",+ { queries: [{ ...query(40), savedQuestionSourceId: 1.5 }] },+ "contains an invalid entry",+ ],+ [+ "a model entry missing its actions",+ { queries: [], models: [{ sourceModelId: 5, copiedModelId: 80 }] },+ "contains an invalid model entry",+ ],+ [+ "a malformed action mapping",+ {+ queries: [],+ models: [{ ...model(5, 80), actions: [{ sourceActionId: 51 }] }],+ },+ "contains an invalid model entry",+ ],+ [+ "a duplicate saved question ID",+ { queries: [query(40), query(40)] },+ "duplicate saved question ID",+ ],+ [+ "a duplicate source model ID",+ { queries: [], models: [model(5, 80), model(5, 81)] },+ "duplicate source model ID",+ ],+ [+ "a duplicate copied model ID",+ { queries: [], models: [model(5, 80), model(6, 80)] },+ "duplicate copied model ID",+ ],+ [+ "a source action ID claimed by two models",+ {+ queries: [],+ models: [model(5, 80, [[51, 91]]), model(6, 81, [[51, 92]])],+ },+ "duplicate source action ID",+ ],+ [+ "a copied action ID claimed by two models",+ {+ queries: [],+ models: [model(5, 80, [[51, 91]]), model(6, 81, [[52, 91]])],+ },+ "duplicate copied action ID",+ ],+ ])("rejects %s", (_name, value, message) => {+ const appRoot = makeApp();+ write(appRoot, value);++ expect(() => readResourceLockfile(appRoot)).toThrow(message);+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.tsnew file mode 100644index 00000000000..a4ec352e44a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-metrics.unit.spec.ts@@ -0,0 +1,487 @@+import { MetabaseApiError, MetabaseClient } from "../metabase-client";+import {+ reconcileMetrics,+ reconcileRemovedMetrics,+} from "../reconcile-metrics";+import type { DataAppMetric, ResourceLockfile } from "../types";++import { jsonResponse, makeApp, setupResourceSyncTests } from "./setup";++const HASH = `v1:sha256:${"0".repeat(64)}`;++const createMockClient = () => ({+ getCard: jest.fn(),+ updateMetric: jest.fn(),+ createMetric: jest.fn(),+ deleteCard: jest.fn(),+});++describe("metric reconciliation", () => {+ setupResourceSyncTests();++ it("does not update an unchanged copied metric", async () => {+ const client = createMockClient();++ client.getCard.mockResolvedValue({+ id: 404,+ name: "Lifetime value",+ type: "metric",+ collection_id: 35,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ });++ const lockfile: ResourceLockfile = {+ queries: [],+ models: [],+ metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],+ };++ const log = jest.fn();++ await reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [+ {+ dataset_query: { aggregation: [["metric", {}, 251]] },+ metrics: [+ {+ id: 251,+ name: "Lifetime value",+ type: "metric",+ collection_id: 1,+ dataset_query: {+ database: 1,+ "lib/metadata": null,+ stages: [],+ },+ display: "table",+ visualization_settings: {},+ description: null,+ },+ ],+ },+ ],+ lockfile,+ client,+ log,+ });++ expect(client.updateMetric).not.toHaveBeenCalled();+ expect(log).toHaveBeenCalledWith("unchanged metric: 251 -> 404");+ });++ it("copies a missing metric and rewrites metric references", async () => {+ const client = createMockClient();+ client.createMetric.mockResolvedValue({ id: 404 });++ const lockfile: ResourceLockfile = {+ queries: [],+ models: [],+ metrics: [],+ };++ const metric: DataAppMetric = {+ id: 251,+ name: "Lifetime value",+ type: "metric",+ collection_id: 1,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ };++ const resolvedQuery = {+ dataset_query: {+ stages: [{ aggregation: [["metric", {}, 251]] }],+ },+ metrics: [metric],+ };++ await reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [resolvedQuery],+ lockfile,+ client,+ log: jest.fn(),+ });++ expect(client.createMetric).toHaveBeenCalledWith({+ name: "Lifetime value",+ collectionId: 35,+ datasetQuery: { database: 1, stages: [] },+ display: "table",+ visualizationSettings: {},+ description: null,+ });++ expect(lockfile.metrics).toEqual([+ { sourceMetricId: 251, copiedMetricId: 404, hash: expect.any(String) },+ ]);++ expect(resolvedQuery.dataset_query).toEqual({+ stages: [{ aggregation: [["metric", {}, 404]] }],+ });+ });++ it("updates a changed copied metric", async () => {+ const client = createMockClient();++ client.getCard.mockResolvedValue({+ id: 404,+ name: "Old metric name",+ type: "metric",+ collection_id: 35,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ });++ const lockfile: ResourceLockfile = {+ queries: [],+ models: [],+ metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],+ };++ await reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [+ {+ dataset_query: { aggregation: [["metric", {}, 251]] },+ metrics: [+ {+ id: 251,+ name: "Lifetime value",+ type: "metric",+ collection_id: 1,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ },+ ],+ },+ ],+ lockfile,+ client,+ log: jest.fn(),+ });++ expect(client.updateMetric).toHaveBeenCalledWith(404, {+ name: "Lifetime value",+ collectionId: 35,+ datasetQuery: { database: 1, stages: [] },+ display: "table",+ visualizationSettings: {},+ description: null,+ });+ });++ it("replaces a missing copied metric and rewrites its references", async () => {+ const client = createMockClient();++ client.getCard.mockRejectedValue(+ new MetabaseApiError(404, "Metric not found"),+ );++ client.createMetric.mockResolvedValue({ id: 405 });++ const lockfile: ResourceLockfile = {+ queries: [],+ models: [],+ metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],+ };++ const resolvedQuery = {+ dataset_query: { stages: [{ aggregation: [["metric", {}, 251]] }] },+ metrics: [+ {+ id: 251,+ name: "Lifetime value",+ type: "metric" as const,+ collection_id: 1,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ },+ ],+ };++ await reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [resolvedQuery],+ lockfile,+ client,+ log: jest.fn(),+ });++ expect(client.createMetric).toHaveBeenCalledTimes(1);++ expect(lockfile.metrics).toEqual([+ { sourceMetricId: 251, copiedMetricId: 405, hash: expect.any(String) },+ ]);++ expect(resolvedQuery.dataset_query).toEqual({+ stages: [{ aggregation: [["metric", {}, 405]] }],+ });+ });++ it("fails before copying metrics when a resolved query omits a metric", async () => {+ const client = createMockClient();++ await expect(+ reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [+ {+ dataset_query: {+ stages: [{ aggregation: [["metric", {}, 251]] }],+ },+ metrics: [],+ },+ ],+ lockfile: { queries: [], models: [], metrics: [] },+ client,+ log: jest.fn(),+ }),+ ).rejects.toThrow(+ "These metrics are missing and cannot be reconciled: 251.",+ );++ expect(client.createMetric).not.toHaveBeenCalled();+ expect(client.updateMetric).not.toHaveBeenCalled();+ });++ it("rejects a metric that joins a saved card", async () => {+ const client = createMockClient();++ await expect(+ reconcileMetrics({+ appRoot: makeApp(),+ collectionId: 35,+ resolvedQueries: [+ {+ dataset_query: {+ stages: [{ aggregation: [["metric", {}, 251]] }],+ },+ metrics: [+ {+ id: 251,+ name: "Lifetime value",+ type: "metric",+ collection_id: 1,+ dataset_query: {+ stages: [+ {+ "source-table": 1,+ joins: [{ stages: [{ "source-card": 99 }] }],+ },+ ],+ },+ display: "table",+ visualization_settings: {},+ description: null,+ },+ ],+ },+ ],+ lockfile: { queries: [], models: [], metrics: [] },+ client,+ log: jest.fn(),+ }),+ ).rejects.toThrow(+ "Metrics with saved-card joins cannot be synchronized: 251.",+ );++ expect(client.createMetric).not.toHaveBeenCalled();+ expect(client.updateMetric).not.toHaveBeenCalled();+ });++ it("deletes a copied metric when no query references it", async () => {+ const appRoot = makeApp();+ const client = createMockClient();++ client.getCard.mockResolvedValue({+ id: 404,+ name: "Lifetime value",+ type: "metric",+ collection_id: 35,+ dataset_query: { database: 1, stages: [] },+ });++ const lockfile: ResourceLockfile = {+ queries: [],+ models: [],+ metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],+ };++ const log = jest.fn();++ const metricReconciliation = await reconcileMetrics({+ appRoot,+ collectionId: 35,+ resolvedQueries: [],+ lockfile,+ client,+ log,+ });++ expect(client.deleteCard).not.toHaveBeenCalled();++ await reconcileRemovedMetrics({+ appRoot,+ collectionId: 35,+ ...metricReconciliation,+ lockfile,+ client,+ log,+ });++ expect(client.deleteCard).toHaveBeenCalledWith(404);+ expect(lockfile.metrics).toEqual([]);+ expect(log).toHaveBeenCalledWith("deleted metric: 404");+ });++ describe("archived and moved copies", () => {+ const metric: DataAppMetric = {+ id: 251,+ name: "Lifetime value",+ type: "metric",+ collection_id: 1,+ dataset_query: { database: 1, stages: [] },+ display: "table",+ visualization_settings: {},+ description: null,+ };++ let appRoot: string;+ let lockfile: ResourceLockfile;++ beforeEach(() => {+ appRoot = makeApp();++ lockfile = {+ queries: [],+ models: [],+ metrics: [{ sourceMetricId: 251, copiedMetricId: 404, hash: HASH }],+ };+ });++ it("sends the restore payload for an unchanged archived metric", async () => {+ const copy = {+ ...metric,+ id: 404,+ collection_id: 99,+ archived: true,+ };++ const fetchMock = jest+ .spyOn(global, "fetch")+ .mockResolvedValueOnce(jsonResponse(copy))+ .mockResolvedValueOnce(jsonResponse({ ...copy, archived: false }));++ const resolvedQuery = {+ dataset_query: { aggregation: [["metric", {}, 251]] },+ metrics: [metric],+ };++ await reconcileMetrics({+ appRoot,+ collectionId: 35,+ resolvedQueries: [resolvedQuery],+ lockfile,+ client: new MetabaseClient("http://metabase.test", "secret"),+ log: jest.fn(),+ });++ expect(fetchMock).toHaveBeenCalledTimes(2);++ expect(fetchMock).toHaveBeenLastCalledWith(+ new URL("http://metabase.test/api/card/404"),+ expect.objectContaining({+ method: "PUT",+ body: expect.any(String),+ }),+ );++ expect(JSON.parse(String(fetchMock.mock.calls[1][1]?.body))).toEqual({+ name: "Lifetime value",+ type: "metric",+ archived: false,+ collection_id: 35,+ dataset_query: metric.dataset_query,+ display: "table",+ visualization_settings: {},+ description: null,+ });+ });++ describe("unarchived copies moved outside the app collection", () => {+ let client: ReturnType<typeof createMockClient>;++ beforeEach(() => {+ client = createMockClient();++ client.getCard.mockResolvedValue({+ ...metric,+ id: 404,+ collection_id: 99,+ archived: false,+ });+ });++ it("does not update a metric copy that is moved to other collection", async () => {+ await expect(+ reconcileMetrics({+ appRoot,+ collectionId: 35,+ lockfile,+ client,+ log: jest.fn(),+ resolvedQueries: [{ dataset_query: {}, metrics: [metric] }],+ }),+ ).rejects.toThrow(/data app collection 35/);++ expect(client.updateMetric).not.toHaveBeenCalled();+ expect(client.createMetric).not.toHaveBeenCalled();+ expect(client.deleteCard).not.toHaveBeenCalled();++ expect(lockfile.metrics).toEqual([+ { sourceMetricId: 251, copiedMetricId: 404, hash: HASH },+ ]);+ });++ it("does not delete a metric copy that is moved to other collection when its source is removed", async () => {+ await expect(+ reconcileRemovedMetrics({+ appRoot,+ collectionId: 35,+ lockfile,+ client,+ log: jest.fn(),+ previousEntries: [...lockfile.metrics],+ liveMetricIds: new Set(),+ }),+ ).rejects.toThrow(/data app collection 35/);++ expect(client.updateMetric).not.toHaveBeenCalled();+ expect(client.createMetric).not.toHaveBeenCalled();+ expect(client.deleteCard).not.toHaveBeenCalled();++ expect(lockfile.metrics).toEqual([+ { sourceMetricId: 251, copiedMetricId: 404, hash: HASH },+ ]);+ });+ });+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.tsnew file mode 100644index 00000000000..04de498b7f2--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/reconcile-upsert.unit.spec.ts@@ -0,0 +1,152 @@+import path from "node:path";++import { discoverQueries } from "../discover";+import { syncResources } from "../sync";++import {+ jsonResponse,+ makeApp,+ setupResourceSyncTests,+ writeQuery,+ writeQueryLockfile,+} from "./setup";++describe("query reconciliation upserts", () => {+ setupResourceSyncTests();++ it("ignores fresh generated UUIDs when comparing saved questions", async () => {+ const appRoot = makeApp();+ const slug = path.basename(appRoot);+ writeQuery(+ appRoot,+ `export const Orders = defineQuery({ savedQuestionSourceId: 35, source: { type: "table", id: 1 } });`,+ );+ const [query] = await discoverQueries(appRoot);+ writeQueryLockfile(appRoot, [+ {+ tableId: query.tableId,+ hash: query.hash,+ savedQuestionSourceId: 35,+ },+ ]);+ const queryWithAggregationUuid = (uuid: string) => ({+ database: 1,+ stages: [+ {+ aggregation: [["sum", { "lib/uuid": uuid }, ["field", {}, 1]]],+ "order-by": [["desc", {}, ["aggregation", {}, uuid]]],+ },+ ],+ });+ const requests: Array<{ method: string; pathname: string }> = [];+ const log = jest.fn();+ jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {+ const pathname = new URL(String(input)).pathname;+ const method = init?.method ?? "GET";+ requests.push({ method, pathname });+ if (pathname === `/api/apps/${slug}/draft` && method === "POST") {+ return jsonResponse({ name: slug, resource_collection_id: 20 });+ }+ if (pathname === `/api/apps/${slug}/query` && method === "POST") {+ return jsonResponse({+ database_id: 1,+ dataset_query: queryWithAggregationUuid("fresh-uuid"),+ table_ids: [1],+ });+ }+ if (pathname === "/api/card/35" && method === "GET") {+ return jsonResponse({+ id: 35,+ name: "Orders",+ type: "question",+ collection_id: 20,+ dataset_query: queryWithAggregationUuid("saved-uuid"),+ });+ }+ if (pathname === "/api/card/35" && method === "PUT") {+ return jsonResponse({ id: 35 });+ }+ if (+ pathname === `/api/apps/${slug}/table-dependencies` &&+ method === "PUT"+ ) {+ return jsonResponse({ name: slug, table_ids: [1] });+ }+ throw new Error(`Unexpected ${method} ${pathname}`);+ });++ await syncResources({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ log,+ });++ expect(requests).not.toContainEqual({+ method: "PUT",+ pathname: "/api/card/35",+ });+ expect(log).toHaveBeenCalledWith("unchanged: card 35");+ });++ it("reports an exported query rename as an update", async () => {+ const appRoot = makeApp();+ const slug = path.basename(appRoot);+ writeQuery(+ appRoot,+ `export const RenamedOrders = defineQuery({ savedQuestionSourceId: 80, source: { type: "table", id: 1 } });`,+ );+ const [query] = await discoverQueries(appRoot);+ writeQueryLockfile(appRoot, [+ {+ tableId: query.tableId,+ hash: query.hash,+ savedQuestionSourceId: 80,+ },+ ]);+ const log = jest.fn();+ jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {+ const pathname = new URL(String(input)).pathname;+ const method = init?.method ?? "GET";+ if (pathname === `/api/apps/${slug}/draft` && method === "POST") {+ return jsonResponse({ name: slug, resource_collection_id: 20 });+ }+ if (pathname === `/api/apps/${slug}/query` && method === "POST") {+ return jsonResponse({+ database_id: 1,+ dataset_query: { database: 1 },+ table_ids: [1],+ });+ }+ if (pathname === "/api/card/80" && method === "GET") {+ return jsonResponse({+ id: 80,+ name: "Orders",+ type: "question",+ collection_id: 20,+ dataset_query: { database: 1 },+ });+ }+ if (pathname === "/api/card/80" && method === "PUT") {+ return jsonResponse({ id: 80 });+ }+ if (+ pathname === `/api/apps/${slug}/table-dependencies` &&+ method === "PUT"+ ) {+ return jsonResponse({ name: slug, table_ids: [1] });+ }++ throw new Error(`Unexpected ${method} ${pathname}`);+ });++ await syncResources({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ log,+ });++ expect(log).toHaveBeenCalledWith("updated: card 80");+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.tsnew file mode 100644index 00000000000..58fd7e8868a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/setup.ts@@ -0,0 +1,95 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++export function setupResourceSyncTests(): void {+ const appRoots: string[] = [];++ afterEach(() => {+ jest.restoreAllMocks();++ appRoots.forEach((appRoot) =>+ fs.rmSync(appRoot, { recursive: true, force: true }),+ );+ });++ trackedAppRoots = appRoots;+}++let trackedAppRoots: string[] | undefined;++export function makeApp() {+ const appRoot = fs.mkdtempSync(+ path.join(os.tmpdir(), "data-app-query-sync-"),+ );++ trackedAppRoots?.push(appRoot);++ fs.mkdirSync(path.join(appRoot, "queries"));+ fs.mkdirSync(path.join(appRoot, "actions"));++ const packageRoot = path.join(+ appRoot,+ "node_modules/@metabase/embedding-sdk-react",+ );++ fs.mkdirSync(packageRoot, { recursive: true });+ fs.writeFileSync(+ path.join(packageRoot, "package.json"),+ JSON.stringify({+ name: "@metabase/embedding-sdk-react",+ exports: { "./data-app": "./data-app.js" },+ }),+ );++ fs.writeFileSync(+ path.join(packageRoot, "data-app.js"),+ [+ "exports.defineQuery = (query) => query;",+ "exports.defineAction = (definition) => definition;",+ ].join("\n"),+ );++ return appRoot;+}++export function writeAction(appRoot: string, body: string) {+ const filePath = path.join(appRoot, "actions/orders.action.ts");+ fs.writeFileSync(+ filePath,+ `import { defineAction } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,+ );+ return filePath;+}++export const FAKE_HASH = `v1:sha256:${"0".repeat(64)}`;++export function writeQueryLockfile(+ appRoot: string,+ queries: Array<{+ tableId: number;+ hash: string;+ savedQuestionSourceId: number;+ }>,+) {+ fs.writeFileSync(+ path.join(appRoot, "resources_metadata.json"),+ JSON.stringify({ queries, models: [] }),+ );+}++export function writeQuery(appRoot: string, body: string) {+ const filePath = path.join(appRoot, "queries/orders.query.ts");+ fs.writeFileSync(+ filePath,+ `import { defineQuery } from "@metabase/embedding-sdk-react/data-app";\n${body}\n`,+ );+ return filePath;+}++export function jsonResponse(body: unknown, status = 200) {+ return new Response(status === 204 ? null : JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.tsnew file mode 100644index 00000000000..3cf88b7187a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/tests/sync.unit.spec.ts@@ -0,0 +1,175 @@+import path from "node:path";++import { discoverQueries } from "../discover";+import { syncResources } from "../sync";++import {+ jsonResponse,+ makeApp,+ setupResourceSyncTests,+ writeQuery,+ writeQueryLockfile,+} from "./setup";++describe("query synchronization", () => {+ setupResourceSyncTests();++ it("identifies the request that failed", async () => {+ const appRoot = makeApp();+ const slug = path.basename(appRoot);+ jest.spyOn(global, "fetch").mockResolvedValue(+ new Response("Not found.", {+ status: 404,+ headers: { "content-type": "text/plain" },+ }),+ );++ await expect(+ syncResources({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ log: jest.fn(),+ }),+ ).rejects.toThrow(+ `Metabase returned 404 for POST http://metabase.test/api/apps/${slug}/draft: Not found.`,+ );+ });++ it("stores an empty dependency set after synchronizing an empty app", async () => {+ const appRoot = makeApp();+ const slug = path.basename(appRoot);+ const requests: Array<{+ method: string;+ pathname: string;+ body?: string;+ }> = [];++ jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {+ const pathname = new URL(String(input)).pathname;+ const method = init?.method ?? "GET";+ requests.push({ method, pathname, body: init?.body?.toString() });++ if (pathname === `/api/apps/${slug}/draft` && method === "POST") {+ return jsonResponse({ name: slug, resource_collection_id: 20 });+ }+ if (+ pathname === `/api/apps/${slug}/table-dependencies` &&+ method === "PUT"+ ) {+ return jsonResponse({ name: slug, table_ids: [] });+ }++ throw new Error(`Unexpected ${method} ${pathname}`);+ });++ await syncResources({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ log: jest.fn(),+ });++ expect(requests.at(-1)).toEqual({+ method: "PUT",+ pathname: `/api/apps/${slug}/table-dependencies`,+ body: JSON.stringify({ table_ids: [] }),+ });+ });++ it("stores the tables a copied metric reaches through a foreign key", async () => {+ const appRoot = makeApp();+ const slug = path.basename(appRoot);+ writeQuery(+ appRoot,+ `export const Orders = defineQuery({ savedQuestionSourceId: 35, source: { type: "table", id: 1 } });`,+ );+ const [query] = await discoverQueries(appRoot);+ writeQueryLockfile(appRoot, [+ { tableId: query.tableId, hash: query.hash, savedQuestionSourceId: 35 },+ ]);++ // Sources table 1 and groups by a table 2 column reached through a foreign+ // key, so 2 appears nowhere in the query and only the server can report it.+ const metricQuery = { database: 1, stages: [{ "source-table": 1 }] };+ const requests: Array<{+ method: string;+ pathname: string;+ body?: string;+ }> = [];++ jest.spyOn(global, "fetch").mockImplementation(async (input, init) => {+ const pathname = new URL(String(input)).pathname;+ const method = init?.method ?? "GET";+ requests.push({ method, pathname, body: init?.body?.toString() });++ if (pathname === `/api/apps/${slug}/draft` && method === "POST") {+ return jsonResponse({ name: slug, resource_collection_id: 20 });+ }+ if (pathname === `/api/apps/${slug}/query` && method === "POST") {+ return jsonResponse({+ database_id: 1,+ dataset_query: { database: 1 },+ table_ids: [1],+ metrics: [+ {+ id: 251,+ name: "Revenue",+ type: "metric",+ collection_id: 1,+ dataset_query: metricQuery,+ database_id: 1,+ display: "table",+ visualization_settings: {},+ description: null,+ },+ ],+ });+ }+ if (pathname === "/api/card" && method === "POST") {+ return jsonResponse({ id: 404 });+ }+ if (pathname === "/api/card/35" && method === "GET") {+ return jsonResponse({+ id: 35,+ name: "Orders",+ type: "question",+ collection_id: 20,+ dataset_query: { database: 1 },+ });+ }+ if (+ pathname === `/api/apps/${slug}/query-table-dependencies` &&+ method === "POST"+ ) {+ return jsonResponse({ table_ids: [1, 2] });+ }+ if (+ pathname === `/api/apps/${slug}/table-dependencies` &&+ method === "PUT"+ ) {+ return jsonResponse({ name: slug, table_ids: [1, 2] });+ }++ throw new Error(`Unexpected ${method} ${pathname}`);+ });++ await syncResources({+ appRoot,+ metabaseUrl: "http://metabase.test",+ apiKey: "secret",+ log: jest.fn(),+ });++ expect(requests).toContainEqual({+ method: "POST",+ pathname: `/api/apps/${slug}/query-table-dependencies`,+ body: JSON.stringify({ dataset_queries: [metricQuery] }),+ });+ expect(requests.at(-1)).toEqual({+ method: "PUT",+ pathname: `/api/apps/${slug}/table-dependencies`,+ body: JSON.stringify({ table_ids: [1, 2] }),+ });+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.tsnew file mode 100644index 00000000000..db37e451dba--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-query-sync/types.ts@@ -0,0 +1,93 @@+export interface QueryLockEntry {+ tableId: number;+ hash: string;+ savedQuestionSourceId: number;+}++export interface ActionLockEntry {+ sourceActionId: number;+ copiedActionId: number;+ hash: string;+}++/**+ * A model copied into the data app collection. `actions` is both the+ * reference count that keeps the copy alive and the mapping the app's+ * definitions address.+ */+export interface ModelLockEntry {+ sourceModelId: number;+ copiedModelId: number;+ hash: string;+ actions: ActionLockEntry[];+}++export interface MetricLockEntry {+ sourceMetricId: number;+ copiedMetricId: number;+ hash: string;+}++export interface ResourceLockfile {+ /** Where the copies were last synchronized, so a moved app reads apart from a moved copy. */+ collectionId?: number;+ queries: QueryLockEntry[];+ models: ModelLockEntry[];+ metrics: MetricLockEntry[];+}++export interface DataAppMetric extends MetabaseCard {+ type: "metric";+}++export interface DiscoveredQuery {+ exportName: string;+ filePath: string;+ query: Record<string, unknown>;+ savedQuestionSourceId?: number;+ tableId: number;+ hash: string;+}++export interface DiscoveredAction {+ exportName: string;+ filePath: string;+ copiedActionId?: number;+ sourceActionId: number;+}++export interface DataAppMetadata {+ name: string;+ resource_collection_id: number;+}++export interface MetabaseCard {+ id: number;+ name: string;+ type: string;+ collection_id: number | null;+ archived?: boolean;+ dataset_query: Record<string, unknown>;+ database_id?: number | null;+ display?: string | null;+ visualization_settings?: Record<string, unknown> | null;+ description?: string | null;+}++export interface MetabaseAction {+ id: number;+ name: string;+ type: string;+ model_id: number;+ archived?: boolean;+ description?: string | null;+ parameters?: unknown[] | null;+ parameter_mappings?: Record<string, unknown> | null;+ visualization_settings?: Record<string, unknown> | null;+ /** Present on implicit actions. */+ kind?: string | null;+ /** Present on query actions. */+ dataset_query?: Record<string, unknown> | null;+ /** Present on query actions. */+ database_id?: number | null;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.tsindex a3ccdd17c63..a37a1c4e06b 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts@@ -14,6 +14,8 @@ export { DataAppRouter } from "./components/public/DataAppRouter";export { DataAppLink } from "./components/public/DataAppLink";export { copy } from "./lib/public/copy";export { useDataAppLocation } from "./hooks/public/use-data-app-location";+export { defineQuery } from "./hooks/public/use-metabase-query/define-query";+export { defineAction } from "./hooks/public/use-action/define-action";export {aggregations,breakout,@@ -25,11 +27,12 @@ export {export type {LocalFieldReference,MetabaseBreakout,+ MetabaseDynamicColumn,+ MetabaseDynamicQuery,MetabaseOrderBy,MetabaseQueryOptions,MetabaseQueryObject,OrderByDirection,- QuestionColumnReference,UseMetabaseQueryObjectResult,UseMetabaseQueryResult,} from "./hooks/public/use-metabase-query";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.tsnew file mode 100644index 00000000000..44b5a9ca3b7--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/define-action.ts@@ -0,0 +1,13 @@+/**+ * Defines a source-controlled data app action. `action` names the generated+ * action the app runs. `copiedActionId` is generated state — synchronization+ * writes it back, so never set or edit it by hand.+ */+export function defineAction<+ const TDefinition extends {+ action: { id: number; parameters: readonly unknown[] };+ copiedActionId?: number;+ },+>(definition: TDefinition): TDefinition {+ return definition;+}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 3f8e3d0033b..7690a93b7b6 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@@ -1,5 +1,4 @@export { useAction } from "./use-action";-export type { UseActionResult } from "./use-action";export type {ActionExecuteError,ActionImplicitKind,@@ -15,4 +14,5 @@ export type {ActionResultForUpdate,ActionSchema,AnyActionResult,+ 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 825803d7d21..1a68da3dbdf 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@@ -9,11 +9,9 @@* schema directly.*/-import type {- RowValue,- SchemaColumn,- SchemaJavaScriptType,-} from "../data-schema";+import type { SdkActionId } from "embedding-sdk-bundle/types/action";++import type { RowValue, SchemaJavaScriptType } from "../data-schema";/*** Flat public kind union. Maps onto the backend's namespaced@@ -137,14 +135,9 @@ export type ActionResultForKind<TKind extends ActionKind | undefined> =// ============================================================================// Data App schema-derived helpers// -----------------------------------------------------------------------------// These layer on top of the schema-agnostic types above. They read the shape-// of a single action entry in a generated `metabase.data.ts` schema and-// derive the hook's `TParameters` / `TKind` generics, so a Data App author-// writes `useAction<ActionParametersFromDataAppSchema<typeof action>,-// ActionKindFromDataAppSchema<typeof action>>(action.id)` and gets-// compile-time parameter checking plus a typed `result` with no casts.-// Mode-1 (raw SDK) callers don't import these — they declare `TParameters`-// by hand and pass `TKind` as a literal.+// These read a single action entry in a generated `metabase.data.ts` schema+// and derive the hook's `TParameters` / `TKind`. `useAction` applies them to a+// `defineAction(...)` export, so a Data App writes neither generic.// ============================================================================/**@@ -163,19 +156,22 @@ export type ActionImplicitKind =/*** Shape of a single action parameter as it appears in a generated- * `metabase.data.ts` schema entry.+ * `metabase.data.ts` schema entry. An action parameter is not a column, so it+ * carries no `name`.** @category useAction*/-export type ActionParameterSchema = SchemaColumn & {+export type ActionParameterSchema = {slug: string;+ displayName?: string;+ jsType?: SchemaJavaScriptType;required?: boolean;};/*** Shape of a single action entry in a generated `metabase.data.ts` schema.- * The `id` is the numeric action id passed to `useAction`; `parameters`- * drives `ActionParametersFromDataAppSchema`; `implicitKind` / `type` drive+ * The entry is what `defineAction` wraps; `parameters` drives+ * `ActionParametersFromDataAppSchema`, and `implicitKind` / `type` drive* `ActionKindFromDataAppSchema`.** @category useAction@@ -258,3 +254,53 @@ export type ActionKindFromDataAppSchema<TAction> = TAction extends {: TAction extends { type: "query" }? "sql": ActionKind;++/**+ * @interface+ * @expand+ * @category useAction+ */+export type UseActionResult<+ TParameters extends Record<string, unknown> = Record<string, unknown>,+ TKind extends ActionKind | undefined = undefined,+> = {+ /**+ * Trigger the action with the given parameters. Returns the response body+ * on success AND throws on failure — the same error is stored in `error`+ * for render-time consumers. Resolves to the discriminated `result` shape+ * (see `ActionResultForKind<TKind>`); when `TKind` is omitted it resolves+ * to `AnyActionResult`, narrowable via `"<key>" in r`.+ *+ * Resolves to `null` (without making a request) when `actionId` is `null`+ * or the SDK is not yet initialized — guard the host-side caller with+ * `if (!actionId) return;` if these cases are reachable.+ */+ execute: (+ parameters: TParameters,+ ) => Promise<ActionResultForKind<TKind> | null>;+ isExecuting: boolean;+ /** Last response, or `null` before first call and after `reset()`. */+ result: ActionResultForKind<TKind> | null;+ /** Last thrown error, normalized to the public `ActionExecuteError` shape, or `null`. */+ error: ActionExecuteError | null;+ /** Clear `result` and `error`. */+ reset: () => void;+};++export interface UseAction {+ /** A `defineAction(...)` export, which types `execute` and `result` itself. */+ <TDefinition extends { action: ActionSchema }>(+ action: TDefinition | null,+ ): UseActionResult<+ ActionParametersFromDataAppSchema<TDefinition["action"]>,+ ActionKindFromDataAppSchema<TDefinition["action"]>+ >;++ /** An id, which describes nothing: `useAction<Parameters, "create">(42)`. */+ <+ TParameters extends Record<string, unknown> = Record<string, unknown>,+ TKind extends ActionKind | undefined = undefined,+ >(+ actionId: SdkActionId | null,+ ): UseActionResult<TParameters, TKind>;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.tsindex a354f9ffbf2..888de656413 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/use-action.ts@@ -1,7 +1,7 @@import { useCallback, useState } from "react";import type { ExecuteActionResult } from "embedding-sdk-bundle/lib/execute-action";-import type { SdkActionId } from "embedding-sdk-bundle/types/action";+import type { SdkActionInput } from "embedding-sdk-bundle/types/action";import { useMetabaseProviderPropsStore } from "embedding-sdk-package/lib/provider-props-store";import { getWindow } from "embedding-sdk-shared/lib/get-window";@@ -10,52 +10,12 @@ import type {ActionExecuteError,ActionKind,ActionResultForKind,+ UseAction,+ UseActionResult,} from "./types";/**- * @interface- * @expand- * @category useAction- */-export type UseActionResult<- TParameters extends Record<string, unknown> = Record<string, unknown>,- TKind extends ActionKind | undefined = undefined,-> = {- /**- * Trigger the action with the given parameters. Returns the response body- * on success AND throws on failure — the same error is stored in `error`- * for render-time consumers. Resolves to the discriminated `result` shape- * (see `ActionResultForKind<TKind>`); when `TKind` is omitted it resolves- * to `AnyActionResult`, narrowable via `"<key>" in r`.- *- * Resolves to `null` (without making a request) when `actionId` is `null`- * or the SDK is not yet initialized — guard the host-side caller with- * `if (!actionId) return;` if these cases are reachable.- */- execute: (- parameters: TParameters,- ) => Promise<ActionResultForKind<TKind> | null>;- isExecuting: boolean;- /** Last response, or `null` before first call and after `reset()`. */- result: ActionResultForKind<TKind> | null;- /** Last thrown error, normalized to the public `ActionExecuteError` shape, or `null`. */- error: ActionExecuteError | null;- /** Clear `result` and `error`. */- reset: () => void;-};--/**- * Triggers a pre-existing Metabase action. The first arg is the action's- * numeric id or its `entity_id` string; supply `TParameters` as the first- * generic to type the `execute` argument, and optionally `TKind` as the- * second generic to type the discriminated `result` shape.- *- * Without `TKind`, `result` defaults to a union of every possible response- * body (`AnyActionResult`) — authors who don't know the kind upfront can- * narrow with `"<key>" in result` instead of casting from- * `Record<string, unknown>`.- *- * useAction<{ name: string; email: string }, "create">(42);+ * Triggers a pre-existing Metabase action.** Unlike the query hooks, this does NOT run on mount — the caller invokes* `execute` explicitly from an event handler. To gate execution@@ -65,11 +25,11 @@ export type UseActionResult<* @function* @category useAction*/-export const useAction = <+const useActionImpl = <TParameters extends Record<string, unknown> = Record<string, unknown>,TKind extends ActionKind | undefined = undefined,>(- actionId: SdkActionId | null,+ actionId: SdkActionInput | null,): UseActionResult<TParameters, TKind> => {const {state: {@@ -129,3 +89,6 @@ export const useAction = <reset,};};++/** @notExported UseAction */+export const useAction: UseAction = useActionImpl;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.tsnew file mode 100644index 00000000000..5a1e12c3ad0--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.ts@@ -0,0 +1,30 @@+import type { TableSchema } from "../data-schema";++import type {+ MetabaseQueryOptions,+ RequireAggregationsForBreakouts,+} from "./types";++type SavedQuestionBinding = {+ savedQuestionSourceId?: number;+};++/**+ * Defines a source-controlled data app query that can be synchronized to a+ * saved question.+ */+export function defineQuery<+ TEntity extends TableSchema | undefined = undefined,+ TSchema = unknown,+ const TQuery = MetabaseQueryOptions<TEntity, TSchema>,+>(+ query: TQuery &+ (TQuery extends SavedQuestionBinding ? unknown : SavedQuestionBinding) &+ (TQuery extends MetabaseQueryOptions<TEntity, TSchema>+ ? TQuery extends { source: unknown }+ ? RequireAggregationsForBreakouts<TQuery>+ : unknown+ : MetabaseQueryOptions<TEntity, TSchema>),+): TQuery {+ return query;+}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.tsnew file mode 100644index 00000000000..13aa1589042--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/define-query.unit.spec.ts@@ -0,0 +1,13 @@+import { defineQuery } from "./define-query";++describe("defineQuery", () => {+ it("returns the query definition unchanged", () => {+ const query = {+ savedQuestionSourceId: 54,+ source: { type: "table", id: 1 },+ limit: 10,+ } as const;++ expect(defineQuery(query)).toBe(query);+ });+});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 faf12c8920d..cede3cccba1 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@@ -14,10 +14,11 @@ export { useMetabaseQueryObject } from "./use-metabase-query-object";export type {LocalFieldReference,MetabaseBreakout,+ MetabaseDynamicColumn,+ MetabaseDynamicQuery,MetabaseOrderBy,MetabaseQueryOptions,OrderByDirection,- QuestionColumnReference,UseMetabaseQueryResult,} from "./types";export type { UseMetabaseQueryObjectResult } from "./use-metabase-query-object";diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.serialization.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.serialization.unit.spec.tsnew file mode 100644index 00000000000..411bcf54cb2--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.serialization.unit.spec.ts@@ -0,0 +1,17 @@+import { breakout, orderBy } from "./query-helpers";++const categoryField = {+ type: "column" as const,+ name: "category",+ tableId: 1,+};++describe("serializable query helpers", () => {+ it.each([+ ["breakout", breakout(categoryField)],+ ["orderBy", orderBy(categoryField, "asc")],+ ])("omits an unused unit from %s", (_name, clause) => {+ expect(clause).not.toHaveProperty("unit");+ expect(JSON.stringify(clause)).not.toContain("unit");+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.tsindex 5d464d686a1..9c008a2c43a 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts@@ -89,7 +89,7 @@ export function breakout<TDimension extends object>() {return {...dimension,- unit: options && "unit" in options ? options.unit : undefined,+ ...(options?.unit !== undefined ? { unit: options.unit } : undefined),...getBinningOptions(options),};}@@ -138,7 +138,7 @@ export function orderBy<TDimension>(return {...orderableDimension,...(direction ? { direction } : undefined),- unit: options && "unit" in options ? options.unit : undefined,+ ...(options?.unit !== undefined ? { unit: options.unit } : undefined),...getBinningOptions(options),};}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsxnew file mode 100644index 00000000000..c2728bf554a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx@@ -0,0 +1,216 @@+/* eslint-disable import/order */++import { createMockStore, resetTestState, stagesOf } from "./setup";+import { TEST_SCHEMA } from "./fixtures";++import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";++import { count, filter, orderBy } from "..";++beforeEach(resetTestState);+afterEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = false;+ EMBEDDING_SDK_CONFIG.isDataAppDev = false;+});++const STATIC_QUERY = {+ source: TEST_SCHEMA.tables.orders,+ savedQuestionSourceId: 41,+};++const statusFilter = filter(+ TEST_SCHEMA.tables.orders.fields.status,+ "=",+ "paid",+);++describe("an unsynchronized table source", () => {+ const UNSYNCHRONIZED_QUERY = { source: TEST_SCHEMA.tables.orders };++ it("is refused in a deployed data app", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;++ await expect(+ resolveDatasetQueryInBundle(createMockStore())(UNSYNCHRONIZED_QUERY),+ ).rejects.toThrow("has not been synchronized");+ });++ it("still runs in the dev preview, before the first sync", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ const datasetQuery =+ await resolveDatasetQueryInBundle(createMockStore())(+ UNSYNCHRONIZED_QUERY,+ );++ expect(stagesOf(datasetQuery)).toMatchObject([{ "source-table": 1 }]);+ });++ it("still runs outside a data app, where the SDK addresses tables directly", async () => {+ const datasetQuery =+ await resolveDatasetQueryInBundle(createMockStore())(+ UNSYNCHRONIZED_QUERY,+ );++ expect(stagesOf(datasetQuery)).toMatchObject([{ "source-table": 1 }]);+ });+});++describe("dynamic query clauses", () => {+ // The swap these cover is a data-app rule; elsewhere the table is what runs.+ beforeEach(() => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ });++ it("runs the published card in production and layers the dynamic stage on top", async () => {+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(+ STATIC_QUERY,+ { filters: [statusFilter] },+ );++ expect(stagesOf(datasetQuery)).toMatchObject([+ { "source-card": 41 },+ {+ filters: [+ [+ "=",+ expect.anything(),+ ["field", expect.anything(), "STATUS"],+ "paid",+ ],+ ],+ },+ ]);+ });++ it("keeps the table source in the dev preview, with the same dynamic stage", async () => {+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(+ STATIC_QUERY,+ { filters: [statusFilter] },+ );++ expect(stagesOf(datasetQuery)).toMatchObject([+ { "source-table": 1 },+ {+ filters: [+ [+ "=",+ expect.anything(),+ ["field", expect.anything(), "STATUS"],+ "paid",+ ],+ ],+ },+ ]);+ });++ // The static clauses are already inside the published card, so the swapped+ // source must drop them rather than apply them a second time.+ it("drops the static clauses when it swaps in the published card", async () => {+ const aggregatingQuery = {+ source: TEST_SCHEMA.tables.orders,+ aggregations: [count()],+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],+ savedQuestionSourceId: 41,+ };++ const production = await resolveDatasetQueryInBundle(createMockStore())(+ aggregatingQuery,+ { filters: [filter({ type: "column", name: "STATUS" }, "=", "paid")] },+ );++ expect(stagesOf(production)[0]).toEqual({+ "lib/type": "mbql.stage/mbql",+ "source-card": 41,+ });++ // The dev preview keeps them, since nothing has been published into a card.+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ const preview = await resolveDatasetQueryInBundle(createMockStore())(+ aggregatingQuery,+ { filters: [filter({ type: "column", name: "count" }, ">", 1)] },+ );++ expect(stagesOf(preview)[0]).toMatchObject({+ "source-table": 1,+ aggregation: [["count", expect.anything()]],+ breakout: [["field", expect.anything(), 101]],+ });+ });++ it("stays a single stage when there is no dynamic part", async () => {+ const datasetQuery =+ await resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY);++ expect(stagesOf(datasetQuery)).toMatchObject([{ "source-card": 41 }]);+ });++ it("layers the dynamic stage on a preview query that has no card", async () => {+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(+ { source: TEST_SCHEMA.tables.orders },+ { filters: [statusFilter] },+ );++ expect(stagesOf(datasetQuery)).toMatchObject([+ { "source-table": 1 },+ { filters: [expect.anything()] },+ ]);+ });++ it("groups and orders in the dynamic stage", async () => {+ const countAgg = count();++ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(+ STATIC_QUERY,+ {+ filters: [statusFilter],+ aggregations: [countAgg],+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],+ orderBys: [orderBy(countAgg, "desc")],+ limit: 5,+ },+ );++ expect(stagesOf(datasetQuery)[1]).toMatchObject({+ aggregation: [["count", expect.anything()]],+ breakout: [["field", expect.anything(), "STATUS"]],+ "order-by": [["desc", expect.anything(), expect.anything()]],+ limit: 5,+ });+ });++ it("rejects table-scoped references in the dynamic part", async () => {+ await expect(+ resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY, {+ // @ts-expect-error Segments belong to a table source+ filters: [TEST_SCHEMA.tables.orders.segments.completed],+ }),+ ).rejects.toThrow(+ "Dynamic query filters cannot use Segments, which belong to a table source.",+ );++ await expect(+ resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY, {+ // @ts-expect-error Measures belong to a table source+ aggregations: [TEST_SCHEMA.tables.orders.measures.revenue],+ }),+ ).rejects.toThrow(+ "Dynamic query aggregations cannot use Measures or Metrics, which belong to a table source.",+ );+ });++ it("rejects an invalid dynamic limit", async () => {+ await expect(+ resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY, {+ limit: 0,+ }),+ ).rejects.toThrow("Dynamic query limit must be a positive integer.");+ });+});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 b58cb2b27ca..7c9cc19e876 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@@ -158,6 +158,41 @@ export const TEST_SCHEMA = {sourceCardId: 41,},},+ models: {+ orders: {+ actions: {+ create: {+ kind: "action" as const,+ id: 51,+ name: "Create Order",+ type: "implicit" as const,+ implicitKind: "row/create" as const,+ parameters: [+ {+ slug: "status",+ displayName: "Status",+ jsType: "string" as const,+ },+ ],+ },+ update: {+ kind: "action" as const,+ id: 52,+ name: "Update Order",+ type: "implicit" as const,+ implicitKind: "row/update" 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-validation.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query-validation.unit.spec.tsxindex 0b811754ac6..8f16dd372d6 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query-validation.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query-validation.unit.spec.tsx@@ -10,6 +10,25 @@ import { avg, breakout, filter, orderBy, sum } from "..";beforeEach(resetTestState);describe("resolveDatasetQuery validation", () => {+ it("does not emit an explicit undefined time unit", () => {+ const field = TEST_SCHEMA.tables.orders.fields.createdAt;++ expect(breakout(field, { unit: undefined })).not.toHaveProperty("unit");+ expect(orderBy(field, "asc", { unit: undefined })).not.toHaveProperty(+ "unit",+ );+ });++ it("rejects unknown dynamic query properties", async () => {+ await expect(+ resolveDatasetQueryInBundle(createMockStore())(+ { source: TEST_SCHEMA.tables.orders },+ // The runtime validator must receive a shape the public type rejects.+ { filter: [] } as never,+ ),+ ).rejects.toThrow("Dynamic queries only support");+ });+it("rejects invalid limits with a clear error message", async () => {await expect(resolveDatasetQueryInBundle(createMockStore())({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 1e63984d419..5a61c8f8e30 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@@ -8,10 +8,11 @@ import {resetTestState,stagesOf,} from "./setup";-import { TEST_SCHEMA } from "./fixtures";+import { TEST_METADATA, TEST_SCHEMA } from "./fixtures";import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";import { cardApi } from "metabase/api";+import * as Lib from "metabase-lib";import { avg, breakout, count, filter, orderBy, sum } from "..";@@ -426,6 +427,43 @@ describe("resolveDatasetQuery", () => {});});+ // `/api/card/:id/query_metadata` returns empty databases/tables/fields for a+ // user who may read the card but not create queries. Lib then cannot resolve a+ // database and omits `:database`, which `/api/dataset` rejects outright.+ //+ // Built without spreading `TEST_METADATA`: `Lib.metadataProvider` caches the+ // provider on the metadata object itself, so copying that key would hand back+ // a provider built from the full metadata and the empty databases would be+ // ignored.+ it("sets the database when the user cannot see database metadata", async () => {+ const metadataWithoutDatabases = {+ databases: {},+ tables: {},+ fields: {},+ segments: {},+ measures: {},+ questions: TEST_METADATA.questions,+ };++ mockSelectMetadataProviderUnfiltered.mockImplementation(+ (_state, databaseId) =>+ Lib.metadataProvider(+ databaseId,+ // The fixture supplies the plain metadata shape instead of the Metadata class.+ metadataWithoutDatabases as unknown as Lib.Metadata,+ ),+ );++ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({+ source: TEST_SCHEMA.questions.ordersQuestion,+ });++ expect(datasetQuery).toMatchObject({+ database: 1,+ stages: [{ "source-card": 41 }],+ });+ });+it("applies filters to id-only saved question sources", async () => {const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({source: { type: "card", id: 41 },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 02e8f834168..4dd2803e965 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@@ -5,10 +5,44 @@ import { TEST_SCHEMA } from "./fixtures";import type { MetabaseCard } from "metabase/embedding-sdk/types/question";import type { MetabaseQueryOptions, UseMetabaseQueryObjectResult } from "..";-import { breakout, count, filter, sum, useMetabaseQuery } from "..";+import { breakout, count, sum, useMetabaseQuery } from "..";+import { useAction } from "../../use-action";+import { defineAction, defineQuery } from "../../../../data-app";type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];-type OrdersQuestion = (typeof TEST_SCHEMA)["questions"]["ordersQuestion"];++const queryWithInvalidSavedQuestionSourceId = {+ savedQuestionSourceId: "54",+ source: TEST_SCHEMA.tables.orders,+} as const;++// @ts-expect-error saved-question source IDs are numeric+defineQuery(queryWithInvalidSavedQuestionSourceId);++// @ts-expect-error query definitions with breakouts require aggregations+defineQuery({+ source: TEST_SCHEMA.tables.orders,+ breakouts: [breakout(TEST_SCHEMA.tables.orders.fields.createdAt)],+});++const actionWithInvalidActionSourceId = {+ copiedActionId: "91",+ action: TEST_SCHEMA.models.orders.actions.create,+} as const;++// @ts-expect-error generated action source IDs are numeric+defineAction(actionWithInvalidActionSourceId);++// @ts-expect-error action definitions must reference a generated action+defineAction({ action: TEST_SCHEMA.tables.orders });++const CreateOrder = defineAction({+ action: TEST_SCHEMA.models.orders.actions.create,+});++const UpdateOrder = defineAction({+ action: TEST_SCHEMA.models.orders.actions.update,+});// --------// Compile-time contracts that must **fail** type-checking.@@ -41,37 +75,6 @@ const _invalidCrossTableFieldQuery = {],} satisfies MetabaseQueryOptions<OrdersTable>;-const _invalidSavedQuestionClauseQuery = {- source: TEST_SCHEMA.questions.ordersQuestion,-- // @ts-expect-error a card stage returns the question's columns, so it has no field list- fields: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],-} satisfies MetabaseQueryOptions<OrdersQuestion>;--const _invalidSavedQuestionFilterQuery = {- source: TEST_SCHEMA.questions.ordersQuestion,- filters: [- // @ts-expect-error saved question filters must name a result column of the question- filter(TEST_SCHEMA.tables.orders.fields.id, "=", 1),- ],-} satisfies MetabaseQueryOptions<OrdersQuestion>;--const _invalidSavedQuestionSegmentQuery = {- source: TEST_SCHEMA.questions.ordersQuestion,- filters: [- // @ts-expect-error Segments belong to a table source- TEST_SCHEMA.tables.orders.segments.completed,- ],-} satisfies MetabaseQueryOptions<OrdersQuestion>;--const _invalidSavedQuestionMeasureQuery = {- source: TEST_SCHEMA.questions.ordersQuestion,- aggregations: [- // @ts-expect-error Measures belong to a table source- TEST_SCHEMA.tables.orders.measures.revenue,- ],-} satisfies MetabaseQueryOptions<OrdersQuestion>;-// Only this value's type is used to reject passing the entire hook result to a card.const hookResult = {} as UseMetabaseQueryObjectResult;const _invalidHookResultCard = {@@ -108,7 +111,28 @@ const _invalidMetricSourceQuery = {source: TEST_SCHEMA.metrics.revenue,} satisfies MetabaseQueryOptions;+// @ts-expect-error `unit` buckets a date, so only a date dimension offers it+breakout(TEST_SCHEMA.tables.orders.fields.status, { unit: "month" });+function InvalidTypeFixtures() {+ // @ts-expect-error saved-question metadata cannot be passed to querying hooks+ useMetabaseQuery({ source: TEST_SCHEMA.questions.ordersQuestion });++ // @ts-expect-error pass the `defineAction` export, not the schema entry+ useAction(TEST_SCHEMA.models.orders.actions.create);++ // @ts-expect-error the definition's parameter slugs are the only keys+ useAction(CreateOrder).execute({ stauts: "shipped" });++ // @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 kind+ void useAction(CreateOrder).result?.["rows-updated"];+const scalarAggregationResult = useMetabaseQuery({source: TEST_SCHEMA.tables.orders,aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],@@ -146,20 +170,36 @@ function InvalidTypeFixtures() {],});- // @ts-expect-error grouped saved question queries must include an explicit aggregation- useMetabaseQuery<OrdersQuestion>({- source: TEST_SCHEMA.questions.ordersQuestion,- breakouts: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],+ const staticQuery = {+ source: TEST_SCHEMA.tables.orders,+ savedQuestionSourceId: 41,+ } satisfies MetabaseQueryOptions<OrdersTable>;++ useMetabaseQuery(staticQuery, {+ // @ts-expect-error Segments belong to a table source, so the dynamic stage+ // cannot resolve one. Filter the static query with it instead.+ filters: [TEST_SCHEMA.tables.orders.segments.completed],+ });++ useMetabaseQuery(staticQuery, {+ aggregations: [+ // @ts-expect-error Measures belong to a table source, so the dynamic stage+ // cannot resolve one. Aggregate the static query with it instead.+ TEST_SCHEMA.tables.orders.measures.revenue,+ ],+ });+ // @ts-expect-error grouped dynamic clauses must include an explicit aggregation+ useMetabaseQuery(staticQuery, {+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],});- const groupedQuestionResult = useMetabaseQuery({- source: TEST_SCHEMA.questions.ordersQuestion,+ const groupedDynamicResult = useMetabaseQuery(staticQuery, {aggregations: [count()],- breakouts: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],});- // @ts-expect-error grouped queries return only their breakouts and aggregations- void groupedQuestionResult.data?.rows[0]?.AMOUNT;+ // @ts-expect-error grouping in the dynamic stage drops the source columns+ void groupedDynamicResult.data?.rows[0]?.AMOUNT;return null;}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 dcfb8d3913c..b445fc7b80f 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@@ -16,9 +16,32 @@ import {useMetabaseQuery,useMetabaseQueryObject,} from "..";+import { useAction } from "../../use-action";+import { defineAction, defineQuery } from "../../../../data-app";type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];-type OrdersQuestion = (typeof TEST_SCHEMA)["questions"]["ordersQuestion"];++const revenueQuery = defineQuery({+ savedQuestionSourceId: 54,+ source: TEST_SCHEMA.tables.orders,+ limit: 10,+});++const _savedQuestionSourceId: 54 = revenueQuery.savedQuestionSourceId;+const _queryLimit: 10 = revenueQuery.limit;++const CreateOrder = defineAction({+ copiedActionId: 91,+ action: TEST_SCHEMA.models.orders.actions.create,+});++const _copiedActionId: 91 = CreateOrder.copiedActionId;+const _sourceActionId: 51 = CreateOrder.action.id;++// A definition is authored without a generated ID; synchronization writes one.+const UpdateOrder = defineAction({+ action: TEST_SCHEMA.models.orders.actions.update,+});// --------// Compile-time contracts that must pass type-checking.@@ -45,6 +68,30 @@ const _validHookResultCard = {} satisfies MetabaseCard;function ValidTypeFixtures() {+ // A definition types `execute` and `result` on its own, no generics written.+ const createOrder = useAction(CreateOrder);++ void createOrder.execute({ status: "shipped" });++ const createdRow: RowValue | undefined =+ createOrder.result?.["created-row"].ID;++ void createdRow;++ const updateOrder = useAction(UpdateOrder);++ void updateOrder.execute({ id: 1 });++ const updatedRows: readonly RowValue[] | undefined =+ updateOrder.result?.["rows-updated"];++ void updatedRows;++ // A raw id types nothing, so the generics still stand in for a definition.+ const rawAction = useAction<{ status: string }, "create">(51);++ void rawAction.execute({ status: "shipped" });+const selectedFieldsResult = useMetabaseQuery({source: TEST_SCHEMA.tables.orders,fields: [TEST_SCHEMA.tables.orders.fields.id],@@ -110,54 +157,35 @@ function ValidTypeFixtures() {orderBys: [orderBy(sortFields[sortKey], "desc")],});- const groupedQuestionQuery = {- source: TEST_SCHEMA.questions.ordersQuestion,- filters: [- filter(TEST_SCHEMA.questions.ordersQuestion.columns[0], "=", "paid"),- ],- aggregations: [count()],- breakouts: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],- limit: 10,- } satisfies MetabaseQueryOptions<OrdersQuestion>;+ // A static query published as a card, with dynamic clauses layered on top.+ const staticQuery = {+ source: TEST_SCHEMA.tables.orders,+ savedQuestionSourceId: 41,+ } satisfies MetabaseQueryOptions<OrdersTable>;- const groupedQuestionResult = useMetabaseQuery(groupedQuestionQuery);+ const dynamicResult = useMetabaseQuery(staticQuery, {+ filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid")],+ aggregations: [count()],+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],+ });- // Grouping replaces the question's result columns with the query's own.- const groupedQuestionCount: number | null | undefined =- groupedQuestionResult.data?.rows[0]?.count;+ // Grouping in the dynamic stage re-keys the result rows.+ const dynamicCount: number | null | undefined =+ dynamicResult.data?.rows[0]?.count;- void groupedQuestionCount;+ void dynamicCount;- // `useMetabaseQueryObject` takes no generic, so it must accept both sources.- useMetabaseQueryObject({- source: TEST_SCHEMA.questions.ordersQuestion,- filters: [- filter(TEST_SCHEMA.questions.ordersQuestion.columns[1], ">", 100),- ],+ // Filtering alone leaves the static query's rows in place.+ const filteredResult = useMetabaseQuery(staticQuery, {+ filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid")],});- // Apps without a generated schema name the question's result column by hand.- useMetabaseQueryObject({- source: { type: "card", id: 41 },- filters: [filter({ type: "column", name: "STATUS" }, "=", "paid")],- });+ const filteredStatus: string | null | undefined =+ filteredResult.data?.rows[0]?.STATUS;- useMetabaseQuery({- source: { type: "card", id: 41 },- filters: [filter({ type: "column", name: "STATUS" }, "=", "paid")],- aggregations: [count()],- breakouts: [- breakout(- { type: "column", name: "CREATED_AT", jsType: "Date" },- { unit: "month" },- ),- ],- orderBys: [- orderBy({ type: "column", name: "CREATED_AT", jsType: "Date" }, "desc", {- unit: "month",- }),- ],- });+ void filteredStatus;++ useMetabaseQueryObject(staticQuery, { limit: 10 });return null;}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsxindex aa286340de9..aa00d320975 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/use-metabase-query.unit.spec.tsx@@ -16,7 +16,7 @@ import type { QueryDatasetResult } from "embedding-sdk-bundle/lib/query-dataset"import type { QueryInput } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";import type { DatasetQuery } from "metabase-types/api";-import { useMetabaseQuery, useMetabaseQueryObject } from "..";+import { filter, useMetabaseQuery, useMetabaseQueryObject } from "..";beforeEach(resetTestState);@@ -28,7 +28,7 @@ describe("useMetabaseQueryObject", () => {it("returns a loading state until async query creation resolves", async () => {const deferred = createDeferred<DatasetQuery>();- const resolveDatasetQuery = jest.fn(() => jest.fn(() => deferred.promise));+ const resolveDatasetQuery = jest.fn(() => () => deferred.promise);stubSdkBundle({ resolveDatasetQuery });const { result } = renderHook(() => useMetabaseQueryObject(query));@@ -52,9 +52,7 @@ describe("useMetabaseQueryObject", () => {it("returns query creation errors instead of swallowing them", async () => {const error = new Error("No column found");- const resolveDatasetQuery = jest.fn(() =>- jest.fn(() => Promise.reject(error)),- );+ const resolveDatasetQuery = jest.fn(() => () => Promise.reject(error));stubSdkBundle({ resolveDatasetQuery });@@ -70,9 +68,7 @@ describe("useMetabaseQueryObject", () => {});it("waits for login before resolving the query", async () => {- const resolveDatasetQuery = jest.fn(() =>- jest.fn(() => Promise.resolve(TEST_DATASET_QUERY)),- );+ const resolveDatasetQuery = jest.fn(() => async () => TEST_DATASET_QUERY);stubSdkBundle({ resolveDatasetQuery });mockUseLazySelector.mockReturnValue({ status: "loading" });@@ -165,6 +161,76 @@ describe("useMetabaseQueryObject", () => {isLoading: false,});});++ it.each([+ ["query.enabled", { queryEnabled: false, dynamicEnabled: true }],+ ["dynamicQuery.enabled", { queryEnabled: true, dynamicEnabled: false }],+ ])(+ "does not expose or resolve a query while %s is false",+ async (_name, disabledProps) => {+ const resolveDatasetQuery = jest.fn(() => async () => TEST_DATASET_QUERY);+ stubSdkBundle({ resolveDatasetQuery });++ const { result, rerender } = renderHook(+ ({ queryEnabled, dynamicEnabled }) =>+ useMetabaseQueryObject(+ { ...query, enabled: queryEnabled },+ { enabled: dynamicEnabled },+ ),+ { initialProps: disabledProps },+ );++ expect(result.current).toEqual({+ query: null,+ error: null,+ isLoading: false,+ });++ expect(resolveDatasetQuery).not.toHaveBeenCalled();+ rerender({ queryEnabled: true, dynamicEnabled: true });++ await waitFor(() =>+ expect(result.current.query).toEqual(TEST_DATASET_QUERY),+ );++ resolveDatasetQuery.mockClear();+ rerender(disabledProps);++ expect(result.current).toEqual({+ query: null,+ error: null,+ isLoading: false,+ });++ expect(resolveDatasetQuery).not.toHaveBeenCalled();+ },+ );++ it("does not expose a pending result after the query is disabled", async () => {+ const deferred = createDeferred<DatasetQuery>();++ stubSdkBundle({+ resolveDatasetQuery: jest.fn(() => () => deferred.promise),+ });++ const { result, rerender } = renderHook(+ ({ enabled }) => useMetabaseQueryObject({ ...query, enabled }),+ { initialProps: { enabled: true } },+ );++ rerender({ enabled: false });++ await act(async () => {+ deferred.resolve(TEST_DATASET_QUERY);+ await deferred.promise;+ });++ expect(result.current).toEqual({+ query: null,+ error: null,+ isLoading: false,+ });+ });});describe("useMetabaseQuery", () => {@@ -270,7 +336,7 @@ describe("useMetabaseQuery", () => {);stubSdkBundle({- resolveDatasetQuery: jest.fn(() => jest.fn(() => deferred.promise)),+ resolveDatasetQuery: jest.fn(() => () => deferred.promise),queryDataset: jest.fn(() => queryDataset),});@@ -292,3 +358,121 @@ describe("useMetabaseQuery", () => {);});});++describe("dynamic query clauses", () => {+ const staticQuery = { source: TEST_SCHEMA.tables.orders };++ it("re-resolves when only the dynamic part changes", async () => {+ const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));+ stubSdkBundle({ resolveDatasetQuery: jest.fn(() => resolveQuery) });++ const { rerender } = renderHook(+ ({ dynamicQuery }) => useMetabaseQueryObject(staticQuery, dynamicQuery),+ { initialProps: { dynamicQuery: { limit: 10 } } },+ );++ await waitFor(() => expect(resolveQuery).toHaveBeenCalledTimes(1));++ // The static query object is referentially identical across renders, so only+ // the dynamic part can invalidate the cached result.+ rerender({ dynamicQuery: { limit: 20 } });++ await waitFor(() => expect(resolveQuery).toHaveBeenCalledTimes(2));+ expect(resolveQuery).toHaveBeenLastCalledWith(staticQuery, { limit: 20 });+ });++ it("does not re-resolve when the dynamic part is deep-equal", async () => {+ const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));+ stubSdkBundle({ resolveDatasetQuery: jest.fn(() => resolveQuery) });++ const { rerender } = renderHook(+ ({ dynamicQuery }) => useMetabaseQueryObject(staticQuery, dynamicQuery),+ { initialProps: { dynamicQuery: { limit: 10 } } },+ );++ await waitFor(() => expect(resolveQuery).toHaveBeenCalledTimes(1));++ // A new object with the same contents — a UI rebuilding it every render.+ rerender({ dynamicQuery: { limit: 10 } });++ await act(async () => {+ await Promise.resolve();+ });+ expect(resolveQuery).toHaveBeenCalledTimes(1);+ });++ it("does not refetch when a re-render rebuilds both arguments", async () => {+ const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));+ const queryDataset = jest.fn(() =>+ Promise.resolve({ rowCount: 0, runningTime: 1, columns: [], rows: [] }),+ );+ stubSdkBundle({+ resolveDatasetQuery: jest.fn(() => resolveQuery),+ queryDataset: jest.fn(() => queryDataset),+ });++ // Both arguments are fresh objects on every render, the way a component+ // builds them inline. The hooks key on content, so this must not refetch.+ const { rerender } = renderHook(() =>+ useMetabaseQuery(+ { source: TEST_SCHEMA.tables.orders, savedQuestionSourceId: 41 },+ {+ filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "x")],+ },+ ),+ );++ await waitFor(() => expect(queryDataset).toHaveBeenCalledTimes(1));++ rerender();+ rerender();++ await act(async () => {+ await Promise.resolve();+ });+ expect(queryDataset).toHaveBeenCalledTimes(1);+ expect(resolveQuery).toHaveBeenCalledTimes(1);+ });++ it("passes the dynamic part to the dataset query", async () => {+ const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));+ const queryDataset = jest.fn(() =>+ Promise.resolve({ rowCount: 0, runningTime: 1, columns: [], rows: [] }),+ );+ stubSdkBundle({+ resolveDatasetQuery: jest.fn(() => resolveQuery),+ queryDataset: jest.fn(() => queryDataset),+ });++ const dynamicQuery = { limit: 5 };++ renderHook(() => useMetabaseQuery(staticQuery, dynamicQuery));++ await waitFor(() =>+ expect(resolveQuery).toHaveBeenCalledWith(staticQuery, dynamicQuery),+ );+ });++ it("does not run while the dynamic part is disabled", async () => {+ const resolveQuery = jest.fn(() => Promise.resolve(TEST_DATASET_QUERY));+ const queryDataset = jest.fn(() =>+ Promise.resolve({ rowCount: 0, runningTime: 1, columns: [], rows: [] }),+ );+ stubSdkBundle({+ resolveDatasetQuery: jest.fn(() => resolveQuery),+ queryDataset: jest.fn(() => queryDataset),+ });++ const { rerender } = renderHook(+ ({ dynamicQuery }) => useMetabaseQuery(staticQuery, dynamicQuery),+ { initialProps: { dynamicQuery: { enabled: false, limit: 10 } } },+ );++ await waitFor(() => expect(resolveQuery).not.toHaveBeenCalled());++ // A UI that holds the query back until the user picks a filter value.+ rerender({ dynamicQuery: { enabled: true, limit: 10 } });++ await waitFor(() => expect(resolveQuery).toHaveBeenCalledTimes(1));+ });+});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 e908033cc5d..89c6308ef20 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@@ -15,7 +15,6 @@ import type {InferSchema,MetricSchema,QueryData,- QuestionSchema,SchemaColumn,SchemaJavaScriptType,SchemaValue,@@ -315,7 +314,7 @@ type NonDateBucketDimension<TDimension> = TDimension extends unknownexport type BreakoutOptionsArgument<TDimension> = [DateBucketDimension<TDimension>,] extends [never]- ? { binning?: BinningOptions } & BinningOptionsInput+ ? { unit?: never; binning?: BinningOptions } & BinningOptionsInput: { unit?: TemporalUnit; binning?: BinningOptions } & BinningOptionsInput;export type MetabaseBreakoutObjectForDimension<TDimension> =@@ -397,42 +396,14 @@ type StageClauses<TDimension, TAggregation, TFilter> = {type TableQueryBase<TTable> = {source: TTable extends TableSchema ? SourceQuerySpec<TTable> : TableSchema;fields?: readonly FieldReference<TTable>[];+ savedQuestionSourceId?: number;} & StageClauses<FieldReference<TTable>,AnyAggregation<TTable>,SegmentReference<TTable>>;-type QuestionResultColumn<TQuestion> = TQuestion extends {- columns?: infer TColumns;-}- ? TupleElement<NonNullable<TColumns>>- : never;--/**- * What `filter`, `breakout`, and `orderBy` take on a question source. A card- * stage exposes the question's result columns, not the fields underneath, so they- * resolve by name — an app without a generated schema names one by hand.- */-export type QuestionColumnReference<TQuestion = unknown> = [- QuestionResultColumn<TQuestion>,-] extends [never]- ? SchemaColumn & { type: "column" }- : QuestionResultColumn<TQuestion>;--export type QuestionQuery<TQuestion = unknown> = {- source: TQuestion extends QuestionSchema ? TQuestion : QuestionSchema;-- // A card stage returns the question's columns; there is no field list to- // narrow. Use the question's own `fields` upstream instead.- fields?: never;-} & StageClauses<- QuestionColumnReference<TQuestion>,- DimensionAggregation<QuestionColumnReference<TQuestion>>,- never->;--type RequireAggregationsForBreakouts<TQuery> = TQuery extends {+export type RequireAggregationsForBreakouts<TQuery> = TQuery extends {breakouts: readonly [unknown, ...unknown[]];}? TQuery extends { aggregations: readonly [unknown, ...unknown[]] }@@ -443,13 +414,10 @@ type RequireAggregationsForBreakouts<TQuery> = TQuery extends {export type TableQuery<TTable, TQuery = unknown> = TableQueryBase<TTable> &RequireAggregationsForBreakouts<TQuery>;-export type MetabaseQueryOptions<TEntity = unknown, _TSchema = unknown> = [- TEntity,-] extends [undefined]- ? TableQuery<TEntity> | QuestionQuery<TEntity>- : TEntity extends QuestionSchema- ? QuestionQuery<TEntity>- : TableQuery<TEntity>;+export type MetabaseQueryOptions<+ TEntity = unknown,+ _TSchema = unknown,+> = TableQuery<TEntity>;type EmptyRow = Record<never, never>;@@ -522,6 +490,44 @@ type InferQuerySchema<TEntity, TQuery> = DefaultSourceRow<TEntity, TQuery> &| QueryAggregationColumns<TQuery>>;+type DefaultQuestionColumns<TEntity, TQuery> =+ ReshapesResultColumns<TQuery> extends true+ ? never+ : TEntity extends { columns?: infer TColumns }+ ? TupleElement<NonNullable<TColumns>>+ : never;++type QueryResultColumn<TEntity, TQuery> =+ | DefaultTableColumns<TEntity, TQuery>+ | DefaultQuestionColumns<TEntity, TQuery>+ | QueryFieldColumns<TQuery>+ | QueryBreakoutColumns<TQuery>+ | QueryAggregationColumns<TQuery>;++/**+ * A column the static query returns — what the dynamic clauses take. Apps+ * without a generated schema name a result column by hand.+ */+export type MetabaseDynamicColumn<TEntity = unknown, TQuery = unknown> = [+ QueryResultColumn<TEntity, TQuery>,+] extends [never]+ ? SchemaColumn & { type: "column" }+ : QueryResultColumn<TEntity, TQuery>;++/**+ * Clauses layered on top of a static query — the part a UI changes at runtime.+ * They run as their own stage, so they see the static query's result columns and+ * behave the same whether it runs from its table or from its published card.+ */+export type MetabaseDynamicQuery<+ TEntity = unknown,+ TQuery = unknown,+> = StageClauses<+ MetabaseDynamicColumn<TEntity, TQuery>,+ DimensionAggregation<MetabaseDynamicColumn<TEntity, TQuery>>,+ never+>;+type InferQueryEntity<TQuery> = TQuery extends { source: infer TTable }? TTable: undefined;@@ -530,17 +536,29 @@ type QueryEntity<TEntity, TQuery> = [TEntity] extends [undefined]? InferQueryEntity<TQuery>: TEntity;-export type UseMetabaseQueryResult<TEntity = unknown, TQuery = unknown> = {- data: QueryData<InferQuerySchema<TEntity, TQuery>> | null;+type InferResultSchema<TEntity, TQuery, TDynamic> =+ ReshapesResultColumns<TDynamic> extends true+ ? RowsFromColumns<+ QueryBreakoutColumns<TDynamic> | QueryAggregationColumns<TDynamic>+ >+ : InferQuerySchema<TEntity, TQuery>;++export type UseMetabaseQueryResult<+ TEntity = unknown,+ TQuery = unknown,+ TDynamic = undefined,+> = {+ data: QueryData<InferResultSchema<TEntity, TQuery, TDynamic>> | null;isLoading: boolean;error: unknown;refetch: () => Promise<void>;};export type UseMetabaseQuery = <- TEntity extends TableSchema | QuestionSchema | undefined = undefined,+ TEntity extends TableSchema | undefined = undefined,TSchema = unknown,const TQuery = MetabaseQueryOptions<TEntity, TSchema>,+ const TDynamic = undefined,>(query: TQuery &(TQuery extends MetabaseQueryOptions<TEntity, TSchema>@@ -548,4 +566,8 @@ export type UseMetabaseQuery = <? RequireAggregationsForBreakouts<TQuery>: unknown: MetabaseQueryOptions<TEntity, TSchema>),-) => UseMetabaseQueryResult<QueryEntity<TEntity, TQuery>, TQuery>;+ dynamicQuery?: TDynamic &+ (TDynamic extends MetabaseDynamicQuery<TEntity, TQuery>+ ? RequireAggregationsForBreakouts<TDynamic>+ : MetabaseDynamicQuery<TEntity, TQuery>),+) => UseMetabaseQueryResult<QueryEntity<TEntity, TQuery>, TQuery, TDynamic>;diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.tsindex 5504079a0cd..75eea5cb15b 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts@@ -11,7 +11,7 @@ import {getResolveDatasetQueryFromBundle,} from "./bundle";import { stableStringifyQuery } from "./stable-query-key";-import type { MetabaseQueryOptions } from "./types";+import type { MetabaseDynamicQuery, MetabaseQueryOptions } from "./types";export type UseMetabaseQueryObjectResult = {query: MetabaseQueryObject | null;@@ -29,6 +29,7 @@ type QueryObjectState = {*/export function useMetabaseQueryObject(query: MetabaseQueryOptions<undefined>,+ dynamicQuery?: MetabaseDynamicQuery,): UseMetabaseQueryObjectResult {const { loadingState } = useSdkLoadingState();@@ -40,11 +41,20 @@ export function useMetabaseQueryObject(},} = useMetabaseProviderPropsStore();- const queryKey = useMemo(() => stableStringifyQuery(query), [query]);+ const isEnabled = query.enabled !== false && dynamicQuery?.enabled !== false;++ const queryKey = useMemo(+ () => stableStringifyQuery([query, dynamicQuery]),+ [query, dynamicQuery],+ );const queryRef = useRef(query);+ const dynamicQueryRef = useRef(dynamicQuery);const pendingQueryKeyRef = useRef<string | null>(null);- queryRef.current = query;+ useEffect(() => {+ queryRef.current = query;+ dynamicQueryRef.current = dynamicQuery;+ }, [query, dynamicQuery]);const [{ value, error, loading }, resolveQueryObject] =useAsyncFn(async (): Promise<QueryObjectState | null> => {@@ -54,7 +64,10 @@ export function useMetabaseQueryObject(return null;}- const result = await resolveDatasetQuery(reduxStore)(queryRef.current);+ const result = await resolveDatasetQuery(reduxStore)(+ queryRef.current,+ dynamicQueryRef.current,+ );return {// The bundle returns the opaque `DatasetQuery`; the public API publishes@@ -66,6 +79,7 @@ export function useMetabaseQueryObject(useEffect(() => {if (+ !isEnabled ||!reduxStore ||!getResolveDatasetQueryFromBundle() ||loginStatus?.status !== "success"@@ -76,6 +90,7 @@ export function useMetabaseQueryObject(pendingQueryKeyRef.current = queryKey;resolveQueryObject();}, [+ isEnabled,loadingState,loginStatus?.status,queryKey,@@ -83,6 +98,10 @@ export function useMetabaseQueryObject(resolveQueryObject,]);+ if (!isEnabled) {+ return { query: null, error: null, isLoading: false };+ }+if (error && !loading && pendingQueryKeyRef.current === queryKey) {return { query: null, error, isLoading: false };}diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.tsindex fe2f7bbd618..234da2adc1a 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts@@ -5,7 +5,7 @@ import { useLazySelector } from "embedding-sdk-package/hooks/private/use-lazy-seimport { useMetabaseProviderPropsStore } from "embedding-sdk-package/lib/provider-props-store";import { isQueryInput } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";-import type { QuestionSchema, TableSchema } from "../data-schema";+import type { TableSchema } from "../data-schema";import {getEmbeddingSdkBundle,@@ -14,21 +14,24 @@ import {import { mapDatasetQueryData } from "./map-dataset-query-data";import { stableStringifyQuery } from "./stable-query-key";import type {+ MetabaseDynamicQuery,MetabaseQueryOptions,UseMetabaseQuery,UseMetabaseQueryResult,} from "./types";const useMetabaseQueryImpl = <- TEntity extends TableSchema | QuestionSchema | undefined = undefined,+ TEntity extends TableSchema | undefined = undefined,TSchema = unknown,TQuery extends MetabaseQueryOptions<TEntity, TSchema> = MetabaseQueryOptions<TEntity,TSchema>,+ TDynamic extends MetabaseDynamicQuery | undefined = undefined,>(query: TQuery,-): UseMetabaseQueryResult<TEntity, TQuery> => {+ dynamicQuery?: TDynamic,+): UseMetabaseQueryResult<TEntity, TQuery, TDynamic> => {const {state: {internalProps: { reduxStore },@@ -40,20 +43,31 @@ const useMetabaseQueryImpl = <const queryDataset = getEmbeddingSdkBundle()?.queryDataset;const resolveDatasetQuery = getResolveDatasetQueryFromBundle();- const queryKey = useMemo(() => stableStringifyQuery(query), [query]);+ const queryKey = useMemo(+ () => stableStringifyQuery([query, dynamicQuery]),+ [query, dynamicQuery],+ );const queryRef = useRef(query);+ const dynamicQueryRef = useRef(dynamicQuery);useEffect(() => {queryRef.current = query;- }, [query, queryKey]);+ dynamicQueryRef.current = dynamicQuery;+ }, [query, dynamicQuery, queryKey]);const [{ value: data = null, loading: isLoading, error }, fetchQuery] =useAsyncFn(async (): Promise<- UseMetabaseQueryResult<TEntity, TQuery>["data"]+ UseMetabaseQueryResult<TEntity, TQuery, TDynamic>["data"]> => {const currentQuery = queryRef.current;-- if (currentQuery.enabled === false) {+ const currentDynamicQuery = dynamicQueryRef.current;++ // Either part can gate the query — a UI commonly holds the dynamic part+ // back until the user has picked a value.+ if (+ currentQuery.enabled === false ||+ currentDynamicQuery?.enabled === false+ ) {return null;}@@ -66,8 +80,10 @@ const useMetabaseQueryImpl = <return null;}- const datasetQuery =- await resolveDatasetQuery(reduxStore)(currentQuery);+ const datasetQuery = await resolveDatasetQuery(reduxStore)(+ currentQuery,+ currentDynamicQuery,+ );const result = await queryDataset(reduxStore)({ datasetQuery });return mapDatasetQueryData(result);diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex 4dfe11dc349..102fa371ec9 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -165,6 +165,8 @@ export type {SdkUserId,SqlParameterValues,SdkActionId,+ SdkActionDefinition,+ SdkActionInput,} from "embedding-sdk-bundle/types";export type {FieldSchema,diff --git a/enterprise/frontend/src/embedding-sdk-package/package.template.json b/enterprise/frontend/src/embedding-sdk-package/package.template.jsonindex a66533456f7..3d4dfd98308 100644--- a/enterprise/frontend/src/embedding-sdk-package/package.template.json+++ b/enterprise/frontend/src/embedding-sdk-package/package.template.json@@ -49,5 +49,9 @@"peerDependencies": {"react": ">=18 <=19","react-dom": ">=18 <=19"+ },+ "dependencies": {+ "esbuild": "^0.28.1",+ "typescript": "^6.0.3"}}diff --git a/enterprise/frontend/src/embedding-sdk-package/test/generate-sdk-package.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/test/generate-sdk-package.unit.spec.tsnew file mode 100644index 00000000000..7e89f6183bb--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/test/generate-sdk-package.unit.spec.ts@@ -0,0 +1,44 @@+import fs from "fs";+import path from "path";++jest.mock("fs");++describe("SDK package generation", () => {+ it("publishes only esbuild and typescript as CLI runtime dependencies", async () => {+ const repositoryManifest = {+ dependencies: { typescript: "6.0.3", react: "19.0.0" },+ devDependencies: { esbuild: "0.28.1", jest: "30.0.0" },+ };++ jest.mocked(fs.readFileSync).mockImplementation((filename) => {+ if (filename === path.resolve("package.json")) {+ return JSON.stringify(repositoryManifest);+ }++ return JSON.stringify({ version: "1.0.0" });+ });++ await jest.isolateModulesAsync(async () => {+ await import("../../../../../bin/embedding-sdk/generate-sdk-package-files.js");+ });++ expect(fs.writeFileSync).toHaveBeenCalledWith(+ path.resolve("resources/embedding-sdk/package.json"),+ expect.any(String),+ "utf-8",+ );++ const packageJsonPath = path.resolve(+ "resources/embedding-sdk/package.json",+ );++ const [, manifest] = jest+ .mocked(fs.writeFileSync)+ .mock.calls.find(([filename]) => filename === packageJsonPath)!;++ expect(JSON.parse(String(manifest)).dependencies).toStrictEqual({+ esbuild: "0.28.1",+ typescript: "6.0.3",+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts b/enterprise/frontend/src/metabase-enterprise/api/data-app.tsindex 2cb5792b528..367e15e9df2 100644--- a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts@@ -1,6 +1,8 @@import type {DataApp,DataAppRepoStatus,+ DataAppUserPermissionWarning,+ GetDataAppUserPermissionWarningsRequest,SetDataAppEnabledRequest,} from "metabase-types/api";@@ -40,6 +42,16 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({}),providesTags: () => [REPO_STATUS_TAG],}),+ getDataAppUserPermissionWarnings: builder.query<+ DataAppUserPermissionWarning[],+ GetDataAppUserPermissionWarningsRequest+ >({+ query: ({ name, user_ids }) => ({+ method: "POST",+ url: `/api/apps/${encodeURIComponent(name)}/user-permission-warnings`,+ body: { user_ids },+ }),+ }),setDataAppEnabled: builder.mutation<DataApp, SetDataAppEnabledRequest>({query: ({ name, enabled }) => ({method: "PUT",@@ -64,6 +76,7 @@ export const {useListDataAppsQuery,useGetDataAppQuery,useGetDataAppRepoStatusQuery,+ useGetDataAppUserPermissionWarningsQuery,useSetDataAppEnabledMutation,useDeleteDataAppMutation,} = dataAppApi;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.tsxnew file mode 100644index 00000000000..43b8ba53d5f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.tsx@@ -0,0 +1,135 @@+import { skipToken } from "@reduxjs/toolkit/query";+import { useMemo, useState } from "react";+import { t } from "ttag";++import { AdminPaneLayout } from "metabase/admin/components/AdminPaneLayout";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";+import {+ useCreateMembershipMutation,+ useDeleteMembershipMutation,+ useGetPermissionsGroupQuery,+} from "metabase/api";+import { Breadcrumbs } from "metabase/common/components/Breadcrumbs";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useToast } from "metabase/common/hooks";+import { isApiKeyGroupMember } from "metabase/common/utils/groups";+import { useParams } from "metabase/router";+import { Box, Button, Stack, Text } from "metabase/ui";+import { useGetDataAppQuery } from "metabase-enterprise/api";+import type { Group, Member } from "metabase-types/api";++import { DataAppUserList } from "./components/DataAppUserList/DataAppUserList";++export const ManageDataAppUsersPage = () => {+ const { slug = "" } = useParams<{ slug: string }>();+ const appRequest = useGetDataAppQuery(slug);++ const groupRequest = useGetPermissionsGroupQuery(+ appRequest.data?.permission_group_id ?? skipToken,+ );++ const error = appRequest.error ?? groupRequest.error;+ const isLoading = appRequest.isLoading || groupRequest.isLoading;++ return (+ <SettingsPageWrapper>+ <LoadingAndErrorWrapper error={error} loading={isLoading}>+ {appRequest.data && groupRequest.data && (+ <DataAppUsers+ appName={slug}+ appTitle={appRequest.data.display_name}+ group={groupRequest.data}+ />+ )}+ </LoadingAndErrorWrapper>+ </SettingsPageWrapper>+ );+};++const DataAppUsers = ({+ appName,+ appTitle,+ group,+}: {+ appName: string;+ appTitle: string;+ group: Group;+}) => {+ const [sendToast] = useToast();+ const [isAdding, setIsAdding] = useState(false);++ const [createMembership] = useCreateMembershipMutation();+ const [deleteMembership] = useDeleteMembershipMutation();++ const members = useMemo(+ () => group.members.filter((member) => !isApiKeyGroupMember(member)),+ [group.members],+ );++ const handleAddUsers = async (userIds: number[]) => {+ const results = await Promise.allSettled(+ userIds.map((userId) =>+ createMembership({ group_id: group.id, user_id: userId }).unwrap(),+ ),+ );++ const failedUserIds = userIds.filter(+ (_, index) => results[index].status === "rejected",+ );++ if (failedUserIds.length > 0) {+ sendToast({ message: t`Failed to add users`, icon: "warning" });+ } else {+ setIsAdding(false);+ }++ return failedUserIds;+ };++ const handleRemoveUser = async (member: Member) => {+ const { error } = await deleteMembership(member);++ if (error) {+ sendToast({ message: t`Failed to remove user`, icon: "warning" });+ }++ return !error;+ };++ return (+ <Stack gap="xl">+ <Box px="md">+ <Breadcrumbs+ crumbs={[[t`Data apps`, "/admin/settings/apps"], [appTitle]]}+ size="large"+ />+ </Box>++ <AdminPaneLayout+ title={+ <Text component="span" fz="2rem" lh="2rem">+ {t`Manage access to this app`}+ </Text>+ }+ titleActions={+ <Button+ variant="filled"+ onClick={() => setIsAdding(true)}+ disabled={isAdding}+ >+ {t`Add users`}+ </Button>+ }+ >+ <DataAppUserList+ appName={appName}+ isAdding={isAdding}+ members={members}+ onAddUsers={handleAddUsers}+ onCancelAdd={() => setIsAdding(false)}+ onRemoveUser={handleRemoveUser}+ />+ </AdminPaneLayout>+ </Stack>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.unit.spec.tsxnew file mode 100644index 00000000000..859e0e7f7e6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppUsersPage.unit.spec.tsx@@ -0,0 +1,440 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { UndoListing } from "metabase/common/components/UndoListing";+import { Route } from "metabase/router";+import type { Group, Member } from "metabase-types/api";+import {+ createMockDataApp,+ createMockGroup,+ createMockUser,+} from "metabase-types/api/mocks";++import { ManageDataAppUsersPage } from "./ManageDataAppUsersPage";++const createMockMember = (opts?: Partial<Member>): Member => ({+ user_id: 1,+ group_id: 9,+ membership_id: 10,+ email: "[email protected]",+ first_name: "Existing",+ last_name: "User",+ is_group_manager: false,+ is_superuser: false,+ ...opts,+});++const createMockMembers = (count: number) =>+ Array.from({ length: count }, (_, index) =>+ createMockMember({+ user_id: index + 100,+ membership_id: index + 100,+ first_name: `Member ${index + 1}`,+ last_name: "",+ email: `member${index + 1}@example.com`,+ }),+ );++const setup = ({+ warningRequestFails = false,+ members = [createMockMember()],+}: {+ warningRequestFails?: boolean;+ members?: Member[];+} = {}) => {+ const group: Group = {+ ...createMockGroup({ id: 9, name: "Data App: sales" }),+ members,+ };++ const candidate = createMockUser({+ id: 2,+ first_name: "Pending",+ last_name: "User",+ email: "[email protected]",+ });++ const deactivatedCandidate = createMockUser({+ id: 3,+ first_name: "Deactivated",+ last_name: "User",+ is_active: false,+ });++ const anotherCandidate = createMockUser({+ id: 5,+ first_name: "Another",+ last_name: "User",+ email: "[email protected]",+ });++ const tenantCandidate = createMockUser({+ id: 4,+ first_name: "Tenant",+ last_name: "User",+ tenant_id: 12,+ });++ fetchMock.get(+ "path:/api/apps/sales",+ createMockDataApp({ permission_group_id: 9 }),+ );+ fetchMock.get("path:/api/permissions/group/9", () => group);+ fetchMock.get("path:/api/user", {+ data: [candidate, anotherCandidate, deactivatedCandidate, tenantCandidate],+ total: 4,+ });+ fetchMock.post(+ "path:/api/apps/sales/user-permission-warnings",+ warningRequestFails+ ? 500+ : {+ body: [+ {+ user_id: 1,+ missing_tables: [+ {+ id: 8,+ name: "Orders",+ schema: "PUBLIC",+ database_id: 2,+ database_name: "Sample Database",+ },+ ],+ },+ ],+ },+ );++ renderWithProviders(+ <Route+ path="admin/settings/apps/:slug/users"+ element={+ <>+ <ManageDataAppUsersPage />+ <UndoListing />+ </>+ }+ />,+ {+ withRouter: true,+ initialRoute: "/admin/settings/apps/sales/users",+ },+ );++ return { group };+};++describe("ManageDataAppUsersPage", () => {+ it("links back to data apps and shows the app name in the breadcrumb", async () => {+ setup();++ const breadcrumb = await screen.findByTestId("breadcrumbs");++ const dataAppsLink = within(breadcrumb).getByRole("link", {+ name: "Data apps",+ });++ expect(dataAppsLink).toHaveAttribute("href", "/admin/settings/apps");+ expect(within(breadcrumb).getByText("Sales")).toBeInTheDocument();+ });++ it("does not check data access for users before adding them", async () => {+ setup();++ expect(+ await screen.findByRole("button", { name: "Missing data access" }),+ ).toBeInTheDocument();++ expect(+ fetchMock.callHistory.calls(+ "path:/api/apps/sales/user-permission-warnings",+ ),+ ).toHaveLength(1);++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ await userEvent.click(await screen.findByText("Pending User"));++ expect(+ fetchMock.callHistory.calls(+ "path:/api/apps/sales/user-permission-warnings",+ ),+ ).toHaveLength(1);+ });++ it("keeps the empty state visible while adding the first user", async () => {+ setup({ members: [] });++ expect(+ await screen.findByText("No one has access yet"),+ ).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Add users" }));++ expect(+ screen.getByRole("textbox", { name: "Search for a user to add" }),+ ).toBeInTheDocument();+ expect(screen.getByText("No one has access yet")).toBeInTheDocument();+ });++ // Maps between pasted emails and the resolved users.+ it.each([+ [" [email protected] ", ["Pending User"]],+ [+ ["Pending User", "Another User"],+ ],+ ])("selects users pasted as %s", async (emails, names) => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ // Pasting can match email addresses only after the user list has loaded.+ await screen.findByText("Pending User");++ const searchInput = screen.getByRole("textbox", {+ name: "Search for a user to add",+ });++ await userEvent.click(searchInput);+ await userEvent.paste(emails);++ expect(searchInput).toHaveValue("");+ expect(screen.getByRole("button", { name: "Add" })).toBeEnabled();++ for (const name of names) {+ expect(screen.getByText(name)).toBeInTheDocument();+ }+ });++ it("only offers active internal users to add", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ expect(await screen.findByText("Pending User")).toBeInTheDocument();+ expect(screen.queryByText("Deactivated User")).not.toBeInTheDocument();+ expect(screen.queryByText("Tenant User")).not.toBeInTheDocument();+ });++ it("keeps adding enabled when the existing-user warning check fails", async () => {+ setup({ warningRequestFails: true });++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ await userEvent.click(await screen.findByText("Pending User"));++ expect(+ (await screen.findAllByText(/couldn't check data access/i)).length,+ ).toBeGreaterThan(0);++ expect(screen.getByRole("button", { name: "Add" })).toBeEnabled();+ });++ it("prevents re-submission while users are still being added", async () => {+ setup();++ let finishAdding!: () => void;++ const pendingAddition = new Promise<void>((resolve) => {+ finishAdding = resolve;+ });++ fetchMock.post("path:/api/permissions/membership", async () => {+ await pendingAddition;++ return 204;+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ await userEvent.click(await screen.findByText("Pending User"));++ const addButton = screen.getByRole("button", { name: "Add" });+ await userEvent.click(addButton);++ try {+ expect(addButton).toBeDisabled();++ await userEvent.click(addButton);++ expect(+ fetchMock.callHistory.calls("path:/api/permissions/membership"),+ ).toHaveLength(1);+ } finally {+ finishAdding();+ }++ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Add" }),+ ).not.toBeInTheDocument(),+ );+ });++ it("retries only the users that failed to be added", async () => {+ setup();++ let finishSuccessfulAddition!: () => void;++ const pendingAddition = new Promise<void>((resolve) => {+ finishSuccessfulAddition = resolve;+ });++ const submittedUserIds: number[] = [];++ fetchMock.post("path:/api/permissions/membership", async ({ options }) => {+ const { user_id } = JSON.parse(String(options.body));+ submittedUserIds.push(user_id);++ if (user_id === 2) {+ await pendingAddition;++ return 204;+ }++ // The other user's first attempt fails, but their retry succeeds.+ return submittedUserIds.filter((id) => id === user_id).length === 1+ ? 500+ : 204;+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Add users" }),+ );++ await screen.findByText("Pending User");++ await userEvent.click(+ screen.getByRole("textbox", { name: "Search for a user to add" }),+ );++ await userEvent.paste("[email protected], [email protected]");+ await userEvent.click(screen.getByRole("button", { name: "Add" }));++ try {+ await waitFor(() => expect(submittedUserIds).toEqual([2, 5]));++ expect(screen.getByRole("button", { name: "Add" })).toBeDisabled();+ } finally {+ finishSuccessfulAddition();+ }++ expect(await screen.findByText("Failed to add users")).toBeInTheDocument();+ expect(screen.queryByText("Pending User")).not.toBeInTheDocument();+ expect(screen.getByText("Another User")).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Add" }));++ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Add" }),+ ).not.toBeInTheDocument(),+ );++ expect(submittedUserIds).toEqual([2, 5, 5]);+ });++ it("returns to the previous page after removing its last member", async () => {+ const members = createMockMembers(26);+ const { group } = setup({ members });++ fetchMock.delete("path:/api/permissions/membership/125", () => {+ group.members = members.slice(0, 25);++ return 204;+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Next page" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Remove Member 26" }),+ );++ // should show the first page's member+ expect(await screen.findByText("[email protected]")).toBeInTheDocument();+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ });++ it("returns to the previous page when removing two members before the first removal finishes", async () => {+ const members = createMockMembers(27);+ const { group } = setup({ members });++ let finishRemovals!: () => void;++ const pendingRemovals = new Promise<void>((resolve) => {+ finishRemovals = resolve;+ });++ for (const memberId of [125, 126]) {+ fetchMock.delete(+ `path:/api/permissions/membership/${memberId}`,+ async () => {+ await pendingRemovals;++ group.members = group.members.filter(+ (member) => member.membership_id !== memberId,+ );++ return 204;+ },+ );+ }++ await userEvent.click(+ await screen.findByRole("button", { name: "Next page" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Remove Member 26" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Remove Member 27" }),+ );++ // let both delete handlers remove their members+ finishRemovals();++ // should show the first page's member+ expect(await screen.findByText("[email protected]")).toBeInTheDocument();+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ });++ it("stays on the current page when removing a member fails", async () => {+ setup({ members: createMockMembers(26) });++ fetchMock.delete("path:/api/permissions/membership/125", 500);++ await userEvent.click(+ await screen.findByRole("button", { name: "Next page" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Remove Member 26" }),+ );++ expect(+ await screen.findByText("Failed to remove user"),+ ).toBeInTheDocument();++ // should show the current page's member+ expect(screen.getByText("[email protected]")).toBeInTheDocument();+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.module.cssnew file mode 100644index 00000000000..2bbc377b5fa--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.module.css@@ -0,0 +1,14 @@+.row {+ border: 1px solid var(--mb-color-border);+}++.row:focus-within {+ border-color: var(--mb-color-core-brand);+}++.row[data-has-current-users="true"]:focus-within {+ box-shadow:+ inset 1px 0 0 var(--mb-color-core-brand),+ inset -1px 0 0 var(--mb-color-core-brand),+ inset 0 1px 0 var(--mb-color-core-brand);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.tsxnew file mode 100644index 00000000000..158105c9096--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppUsers/AddDataAppUsers.tsx@@ -0,0 +1,290 @@+import {+ type ChangeEvent,+ type ClipboardEvent,+ type ReactNode,+ useMemo,+ useState,+} from "react";+import { t } from "ttag";++import { userToColor } from "metabase/admin/people/colors";+import { useListUsersQuery } from "metabase/api";+import { UserAvatar } from "metabase/common/components/UserAvatar";+import {+ Box,+ Button,+ Flex,+ Input,+ Pill,+ Popover,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";+import type { Member, User } from "metabase-types/api";++import S from "./AddDataAppUsers.module.css";++const MAX_SELECTED_USERS = 100;++type Props = {+ hasCurrentUsers: boolean;+ members: Member[];+ onAddUsers: (userIds: number[]) => Promise<number[]>;+ onCancel: () => void;+};++export const AddDataAppUsers = ({+ hasCurrentUsers,+ members,+ onAddUsers,+ onCancel,+}: Props) => {+ const [text, setText] = useState("");+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [isPickerOpen, setIsPickerOpen] = useState(true);++ const [selectedUsers, setSelectedUsers] = useState<Map<number, User>>(+ new Map(),+ );++ const { data, error, isLoading } = useListUsersQuery({ tenancy: "internal" });++ const memberIds = useMemo(+ () => new Set(members.map(({ user_id }) => user_id)),+ [members],+ );++ const eligibleUsers = useMemo(+ () =>+ (data?.data ?? []).filter(+ (user) =>+ user.is_active && user.tenant_id === null && !memberIds.has(user.id),+ ),+ [data, memberIds],+ );++ const suggestedUsers = useMemo(() => {+ const input = text.toLowerCase();++ return eligibleUsers.filter(+ (user) =>+ !selectedUsers.has(user.id) &&+ (user.common_name.toLowerCase().includes(input) ||+ user.email.toLowerCase().includes(input)),+ );+ }, [eligibleUsers, selectedUsers, text]);++ const addUser = (user: User) => {+ if (selectedUsers.size >= MAX_SELECTED_USERS) {+ return;+ }++ setSelectedUsers(new Map(selectedUsers).set(user.id, user));++ setText("");+ setIsPickerOpen(false);+ };++ const handlePaste = (event: ClipboardEvent<HTMLInputElement>) => {+ const emails = event.clipboardData+ .getData("text")+ .split(",")+ .map((email) => email.trim().toLowerCase())+ .filter(Boolean);++ const usersByEmail = new Map(+ eligibleUsers.map((user) => [user.email.toLowerCase(), user]),+ );++ const nextUsers = new Map(selectedUsers);+ const unmatchedEmails: string[] = [];++ for (const email of emails) {+ const user = usersByEmail.get(email);++ if (user && nextUsers.size < MAX_SELECTED_USERS) {+ nextUsers.set(user.id, user);+ } else {+ unmatchedEmails.push(email);+ }+ }++ if (nextUsers.size > selectedUsers.size) {+ event.preventDefault();++ setSelectedUsers(nextUsers);+ setText(unmatchedEmails.join(", "));+ setIsPickerOpen(false);+ }+ };++ const removeUser = (user: User) => {+ const nextUsers = new Map(selectedUsers);++ nextUsers.delete(user.id);+ setSelectedUsers(nextUsers);+ };++ const handleSubmit = async () => {+ if (isSubmitting) {+ return;+ }++ setIsSubmitting(true);+ setIsPickerOpen(false);++ try {+ const failedUserIds = await onAddUsers(Array.from(selectedUsers.keys()));++ // keep users who could not be added in the selection, so admins can try that again+ setSelectedUsers((users) => {+ const failedUsers = Array.from(users).filter(([id]) =>+ failedUserIds.includes(id),+ );++ return new Map(failedUsers);+ });+ } finally {+ setIsSubmitting(false);+ }+ };++ return (+ <Popover+ opened={isPickerOpen && !isLoading && !error && suggestedUsers.length > 0}+ onChange={setIsPickerOpen}+ position="bottom-start"+ shadow="md"+ >+ <Popover.Target>+ <Box+ mx={hasCurrentUsers ? "-1px" : 0}+ mt={hasCurrentUsers ? "-1px" : 0}+ >+ <AddUsersRow+ value={text}+ isValid={selectedUsers.size > 0}+ isSubmitting={isSubmitting}+ hasCurrentUsers={hasCurrentUsers}+ placeholder={t`Pick someone from the list, or paste a list of email addresses separated by commas`}+ ariaLabel={t`Search for a user to add`}+ onChange={(event) => {+ setText(event.target.value);+ setIsPickerOpen(true);+ }}+ onPaste={handlePaste}+ onDone={handleSubmit}+ onCancel={onCancel}+ >+ {Array.from(selectedUsers.values()).map((user, index) => (+ <Pill+ key={user.id}+ size="md"+ ms={index > 0 ? "sm" : ""}+ withRemoveButton={!isSubmitting}+ onRemove={() => removeUser(user)}+ >+ {user.common_name}+ </Pill>+ ))}+ </AddUsersRow>+ </Box>+ </Popover.Target>++ <Popover.Dropdown>+ <Stack gap={0} miw="15rem">+ {suggestedUsers.map((user) => (+ <Flex+ key={user.id}+ component={UnstyledButton}+ align="center"+ gap="md"+ p="0.5rem 1rem"+ onClick={() => addUser(user)}+ >+ <UserAvatar bg={userToColor(user)} user={user} />+ <Text fw="bold" size="lg">+ {user.common_name}+ </Text>+ </Flex>+ ))}+ </Stack>+ </Popover.Dropdown>+ </Popover>+ );+};++interface AddUsersRowProps {+ value: string;+ isValid: boolean;+ isSubmitting: boolean;+ hasCurrentUsers: boolean;+ placeholder: string;+ ariaLabel: string;+ onPaste: (event: ClipboardEvent<HTMLInputElement>) => void;+ onChange: (event: ChangeEvent<HTMLInputElement>) => void;+ onDone: () => void;+ onCancel: () => void;+ children?: ReactNode;+}++const AddUsersRow = ({+ value,+ isValid,+ isSubmitting,+ hasCurrentUsers,+ placeholder,+ ariaLabel,+ onPaste,+ onChange,+ onDone,+ onCancel,+ children,+}: AddUsersRowProps) => (+ <Flex+ className={S.row}+ data-has-current-users={hasCurrentUsers}+ p="0.5rem"+ align="center"+ style={{+ borderRadius: hasCurrentUsers ? "0.5rem 0.5rem 0 0" : "0.5rem",+ }}+ >+ {children}++ <Input+ disabled={isSubmitting}+ type="text"+ variant="unstyled"+ flex="1 0 auto"+ fz="lg"+ styles={{ input: { background: "transparent" } }}+ value={value}+ placeholder={placeholder}+ aria-label={ariaLabel}+ autoFocus+ onPaste={onPaste}+ onChange={onChange}+ />++ <Button+ variant="subtle"+ bg="transparent"+ onClick={onCancel}+ mr="sm"+ disabled={isSubmitting}+ >+ {t`Cancel`}+ </Button>++ <Button+ variant={isValid ? "filled" : "outline"}+ disabled={!isValid || isSubmitting}+ loading={isSubmitting}+ onClick={onDone}+ >+ {t`Add`}+ </Button>+ </Flex>+);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsxindex 8235ab0abd7..28534c31cc8 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx@@ -2,6 +2,7 @@ import { useCallback } from "react";import { t } from "ttag";import { useConfirmation, useToast } from "metabase/common/hooks";+import { Link } from "metabase/router";import { ActionIcon, Icon, Menu } from "metabase/ui";import {useDeleteDataAppMutation,@@ -62,6 +63,24 @@ export const DataAppActionsMenu = ({ app, canRemove = false }: Props) => {</Menu.Target><Menu.Dropdown>+ {app.resource_collection_id != null && (+ <Menu.Item+ component={Link}+ to={`/collection/${app.resource_collection_id}`}+ >+ {t`View resources`}+ </Menu.Item>+ )}++ {app.permission_group_id != null && (+ <Menu.Item+ component={Link}+ to={`/admin/settings/apps/${app.name}/users`}+ >+ {t`Manage user access`}+ </Menu.Item>+ )}+<Menu.Item onClick={handleToggleEnabled}>{app.enabled ? t`Disable` : t`Re-enable`}</Menu.Item>diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsxindex 3069531f97c..d264aa4a92b 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx@@ -7,11 +7,23 @@ import { createMockDataApp } from "metabase-types/api/mocks";import { DataAppActionsMenu } from "./DataAppActionsMenu";-const setup = ({ enabled = true, canRemove = false } = {}) => {+const setup = ({+ enabled = true,+ canRemove = false,+ resourceCollectionId = 9,+ permissionGroupId = 9,+}: {+ enabled?: boolean;+ canRemove?: boolean;+ resourceCollectionId?: number | null;+ permissionGroupId?: number | null;+} = {}) => {const app = createMockDataApp({name: "sales",display_name: "Sales",enabled,+ resource_collection_id: resourceCollectionId,+ permission_group_id: permissionGroupId,});renderWithProviders(<>@@ -19,6 +31,7 @@ const setup = ({ enabled = true, canRemove = false } = {}) => {{/* Mounts the toaster so failure toasts are assertable in the DOM. */}<UndoListing /></>,+ { withRouter: true },);};@@ -33,6 +46,44 @@ const confirmRemove = async () =>);describe("DataAppActionsMenu", () => {+ it("links to the app's resources and group above the enable action", async () => {+ setup();++ await openMenu();++ const menuItems = await screen.findAllByRole("menuitem");++ expect(menuItems).toHaveLength(3);+ expect(menuItems[0]).toHaveTextContent("View resources");+ expect(menuItems[0]).toHaveAttribute("href", "/collection/9");+ expect(menuItems[1]).toHaveTextContent("Manage user access");+ expect(menuItems[1]).toHaveAttribute(+ "href",+ "/admin/settings/apps/sales/users",+ );+ expect(menuItems[2]).toHaveTextContent("Disable");+ });++ it("does not show the collection link before an app has a collection", async () => {+ setup({ resourceCollectionId: null });++ await openMenu();++ expect(+ screen.queryByRole("menuitem", { name: "View resources" }),+ ).not.toBeInTheDocument();+ });++ it("does not show the group link before an app has a permission group", async () => {+ setup({ permissionGroupId: null });++ await openMenu();++ expect(+ screen.queryByRole("menuitem", { name: "Manage user access" }),+ ).not.toBeInTheDocument();+ });+it("should show a toast when toggling enabled fails", async () => {fetchMock.put("path:/api/apps/sales", 500);setup({ enabled: true });diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.cssnew file mode 100644index 00000000000..30dbb4d15ac--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css@@ -0,0 +1,17 @@+.badge {+ background-color: var(--mb-color-background_surface-warning-strong);+ transition: background-color 150ms ease;+}++.button {+ cursor: pointer;+}++.button:hover .badge,+.button:focus-visible .badge {+ background-color: color-mix(+ in srgb,+ var(--mb-color-background_surface-warning-strong) 92%,+ var(--mb-color-text-primary)+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsxnew file mode 100644index 00000000000..051b50035a9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx@@ -0,0 +1,143 @@+import { t } from "ttag";++import { getDatabaseFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";+import { Link } from "metabase/router";+import {+ Anchor,+ Badge,+ Flex,+ HoverCard,+ Icon,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";+import type {+ DataAppMissingTable,+ DataAppUserPermissionWarning,+} from "metabase-types/api";++import S from "./DataAppDataAccessWarning.module.css";++interface Props {+ warning: DataAppUserPermissionWarning;+ userName: string;+}++export const DataAppDataAccessWarning = ({ warning, userName }: Props) => {+ const label = t`Missing data access`;++ return (+ <HoverCard+ position="bottom-end"+ openDelay={150}+ closeDelay={100}+ shadow="md"+ >+ <HoverCard.Target>+ <UnstyledButton+ className={S.button}+ aria-label={label}+ style={{ flexShrink: 0 }}+ >+ <Badge+ className={S.badge}+ size="sm"+ c="text-primary"+ bdrs="sm"+ tt="none"+ >+ {label}+ </Badge>+ </UnstyledButton>+ </HoverCard.Target>++ <HoverCard.Dropdown+ data-testid="data-access-warning-popover"+ p="lg"+ w="30rem"+ >+ <Stack gap="lg">+ <Text size="sm">+ {t`${userName} doesn’t have permission to view these tables used in this app:`}+ </Text>++ <Stack+ component="ul"+ data-testid="missing-tables-list"+ gap="sm"+ m={0}+ pl={0}+ style={{ listStyle: "none" }}+ >+ {warning.missing_tables.map((table) => {+ const parts = getMissingTableSegments(table);++ return (+ <Flex+ component="li"+ key={table.id}+ align="center"+ gap={4}+ wrap="wrap"+ >+ {parts.map((part, index) => (+ <Flex key={part.url} align="center" gap={4}>+ <Anchor+ component={Link}+ to={part.url}+ target="_blank"+ rel="noopener noreferrer"+ size="sm"+ fw={700}+ >+ {part.label}+ </Anchor>++ {index < parts.length - 1 && (+ <Icon+ name="chevronright"+ size={12}+ c="text-secondary"+ aria-hidden+ />+ )}+ </Flex>+ ))}+ </Flex>+ );+ })}+ </Stack>+ </Stack>+ </HoverCard.Dropdown>+ </HoverCard>+ );+};++const getMissingTableSegments = (table: DataAppMissingTable) => [+ {+ label: table.database_name,+ url: getDatabaseFocusPermissionsUrl({+ databaseId: table.database_id,+ }),+ },+ ...(table.schema+ ? [+ {+ label: table.schema,+ url: getDatabaseFocusPermissionsUrl({+ databaseId: table.database_id,+ schemaName: table.schema,+ }),+ },+ ]+ : []),+ {+ label: table.name,+ url: getDatabaseFocusPermissionsUrl({+ databaseId: table.database_id,+ schemaName: table.schema ?? undefined,+ tableId: table.id,+ }),+ },+];diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsxindex d5b9b5bd4ac..e8a3a881357 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx@@ -1,4 +1,7 @@-import { Flex, Group } from "metabase/ui";+import { t } from "ttag";++import { Link } from "metabase/router";+import { ActionIcon, Flex, Group, Icon, Tooltip } from "metabase/ui";import type { DataApp } from "metabase-types/api";import { DataAppActionsMenu } from "../DataAppActionsMenu/DataAppActionsMenu";@@ -23,6 +26,22 @@ export const DataAppListItem = ({ app, canRemove = false }: Props) => (<Group flex="0 0 auto" gap="lg" wrap="nowrap" align="center"><DataAppStatusBadge app={app} />+ {app.has_user_permission_warnings && (+ <Tooltip label={t`Some users are missing data access.`}>+ <ActionIcon+ aria-label={t`Some users are missing data access.`}+ component={Link}+ to={`/admin/settings/apps/${app.name}/users`}+ bg="background_surface-warning-strong"+ c="text-primary"+ bdrs="sm"+ size="sm"+ >+ <Icon name="warning" size={14} />+ </ActionIcon>+ </Tooltip>+ )}+<DataAppActionsMenu app={app} canRemove={canRemove} /></Group></Flex>diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.module.cssnew file mode 100644index 00000000000..03325d250d2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.module.css@@ -0,0 +1,21 @@+.userListContent {+ display: flex;+ flex-direction: column;+ gap: var(--mantine-spacing-lg);+}++.userListContent.transitioningUserListContent {+ display: grid;+}++.transitioningUserListContent > * {+ grid-area: 1 / 1;+}++.userTable thead {+ display: none;+}++.userTable tbody tr:not(:last-child) {+ border-bottom: 1px solid var(--mb-color-border);+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.tsxnew file mode 100644index 00000000000..1ef9783d8b5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppUserList/DataAppUserList.tsx@@ -0,0 +1,238 @@+import { skipToken } from "@reduxjs/toolkit/query";+import cx from "classnames";+import { useEffect, useMemo } from "react";+import { t } from "ttag";++import NoResults from "assets/img/no_results.svg";+import { AdminContentTable } from "metabase/admin/components/AdminContentTable";+import { EmptyState } from "metabase/common/components/EmptyState";+import { PaginationControls } from "metabase/common/components/PaginationControls";+import { usePagination } from "metabase/common/hooks/use-pagination";+import Animation from "metabase/css/core/animation.module.css";+import {+ Alert,+ Box,+ Collapse,+ Flex,+ Icon,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";+import { getFullName } from "metabase/utils/user";+import { useGetDataAppUserPermissionWarningsQuery } from "metabase-enterprise/api";+import type { DataAppUserPermissionWarning, Member } from "metabase-types/api";++import { AddDataAppUsers } from "../AddDataAppUsers/AddDataAppUsers";+import { DataAppDataAccessWarning } from "../DataAppDataAccessWarning/DataAppDataAccessWarning";++import S from "./DataAppUserList.module.css";++const PAGE_SIZE = 25;++type Props = {+ appName: string;+ isAdding: boolean;+ members: Member[];+ onAddUsers: (userIds: number[]) => Promise<number[]>;+ onCancelAdd: () => void;+ onRemoveUser: (member: Member) => Promise<boolean>;+};++export const DataAppUserList = ({+ appName,+ isAdding,+ members,+ onAddUsers,+ onCancelAdd,+ onRemoveUser,+}: Props) => {+ const { handleNextPage, handlePreviousPage, page, setPage } = usePagination();++ const lastPage = Math.max(0, Math.ceil(members.length / PAGE_SIZE) - 1);++ // make sure user does not stay in an empty page if the+ // removed member is the last one in the page+ useEffect(() => {+ setPage((page) => Math.min(page, lastPage));+ }, [lastPage, setPage]);++ const visibleMembers = useMemo(+ () => members.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE),+ [members, page],+ );++ const visibleMemberIds = useMemo(+ () => visibleMembers.map(({ user_id }) => user_id),+ [visibleMembers],+ );++ const warnings = useDataAppUserWarnings(appName, visibleMemberIds);++ return (+ <Stack data-testid="user-management-sections" gap="lg">+ {warnings.isError && <WarningRequestError />}++ <Box+ className={cx(+ S.userListContent,+ !isAdding && S.transitioningUserListContent,+ )}+ >+ {(isAdding || members.length > 0) && (+ <Box+ data-testid="data-app-users-card"+ bd={members.length > 0 ? "1px solid var(--mb-color-border)" : 0}+ bdrs="md"+ bg="background-primary"+ style={{ overflow: "hidden" }}+ >+ {isAdding && (+ <AddDataAppUsers+ hasCurrentUsers={members.length > 0}+ members={members}+ onAddUsers={onAddUsers}+ onCancel={onCancelAdd}+ />+ )}++ {members.length > 0 && (+ <AdminContentTable+ className={cx(S.userTable, Animation.fadeIn)}+ columnTitles={[]}+ >+ {visibleMembers.map((member) => (+ <MemberRow+ key={member.membership_id}+ member={member}+ warning={warnings.byUserId.get(member.user_id)}+ onRemove={onRemoveUser}+ />+ ))}+ </AdminContentTable>+ )}++ {members.length > PAGE_SIZE && (+ <Flex align="center" justify="flex-end" p="md">+ <PaginationControls+ page={page}+ pageSize={PAGE_SIZE}+ itemsLength={visibleMembers.length}+ total={members.length}+ onNextPage={handleNextPage}+ onPreviousPage={handlePreviousPage}+ />+ </Flex>+ )}+ </Box>+ )}++ <Collapse+ in={members.length === 0}+ transitionDuration={150}+ transitionTimingFunction="ease-out"+ >+ <DataAppUsersEmptyState />+ </Collapse>+ </Box>+ </Stack>+ );+};++const DataAppUsersEmptyState = () => (+ <Box+ data-testid="data-app-users-empty-state"+ bg="background-secondary"+ bdrs="md"+ py="5rem"+ >+ <EmptyState+ title={t`No one has access yet`}+ spacing="sm"+ illustrationElement={+ <img+ src={NoResults}+ alt={t`No results`}+ width={120}+ height={120}+ data-testid="data-app-users-empty-state-icon"+ />+ }+ />+ </Box>+);++const useDataAppUserWarnings = (appName: string, userIds: number[]) => {+ const request = useGetDataAppUserPermissionWarningsQuery(+ userIds.length > 0 ? { name: appName, user_ids: userIds } : skipToken,+ );++ const warningByUserId = useMemo(+ () =>+ new Map(request.data?.map((warning) => [warning.user_id, warning]) ?? []),+ [request.data],+ );++ return {+ byUserId: warningByUserId,+ isError: request.isError,+ };+};++const MemberRow = ({+ member,+ warning,+ onRemove,+}: {+ member: Member;+ warning?: DataAppUserPermissionWarning;+ onRemove: (member: Member) => void;+}) => {+ const name = getFullName(member) ?? member.email;++ return (+ <tr>+ <td>+ <Text fw={700}>{name}</Text>+ </td>++ <td>{member.email}</td>++ <Box component="td" w="1%" style={{ whiteSpace: "nowrap" }}>+ <Flex+ data-testid="data-app-user-actions"+ align="center"+ justify="flex-end"+ gap="lg"+ wrap="nowrap"+ style={{ minWidth: "max-content" }}+ >+ {warning && (+ <DataAppDataAccessWarning+ warning={warning}+ userName={member.first_name || name}+ />+ )}++ <UnstyledButton+ aria-label={t`Remove ${name}`}+ onClick={() => onRemove(member)}+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <Icon name="close" c="text-disabled" size={16} />+ </UnstyledButton>+ </Flex>+ </Box>+ </tr>+ );+};++const WarningRequestError = () => (+ <Alert color="warning" icon={<Icon name="warning" />}>+ {t`We couldn't check data access for some users. You can still update access to this data app.`}+ </Alert>+);diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsxindex 7223955f782..9f9d34fc8cf 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx@@ -9,7 +9,7 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport CS from "metabase/css/core/index.css";import QueryBuilderS from "metabase/css/query_builder.module.css";import { useParams } from "metabase/router";-import { Box, Flex } from "metabase/ui";+import { Box, Flex, Icon } from "metabase/ui";import { useGetDataAppQuery } from "metabase-enterprise/api";import {@@ -228,6 +228,42 @@ export function DataAppView() {);}+ if (status === 409) {+ return (+ <Flex+ direction="column"+ w="100%"+ h="100%"+ justify="center"+ align="center"+ >+ <EmptyState+ title={t`This data app isn’t published yet`}+ message={t`An administrator needs to publish this data app before it can be opened.`}+ illustrationElement={<Icon name="hourglass" size={64} />}+ />+ </Flex>+ );+ }++ if (status === 403) {+ return (+ <Flex+ direction="column"+ w="100%"+ h="100%"+ justify="center"+ align="center"+ >+ <EmptyState+ title={t`You don’t have access to this data app`}+ message={t`Ask an administrator for access to this data app.`}+ illustrationElement={<Icon name="key" size={64} />}+ />+ </Flex>+ );+ }+return (<GenericErrortitle={t`Couldn’t load this data app`}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsxindex 7f650a19f7f..c5a01f0bf43 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx@@ -72,6 +72,38 @@ describe("DataAppView", () => {expect(screen.getByText("Couldn’t load this data app")).toBeInTheDocument();});+ it("shows a permission error when the user cannot access the data app", () => {+ setup({ error: { status: 403 } });++ expect(+ screen.getByText("You don’t have access to this data app"),+ ).toBeInTheDocument();++ expect(+ screen.getByText("Ask an administrator for access to this data app."),+ ).toBeInTheDocument();++ expect(screen.queryByText("Show error details")).not.toBeInTheDocument();++ expect(+ screen.queryByText("Gather diagnostic information"),+ ).not.toBeInTheDocument();+ });++ it("shows a not-published screen when the app has no resource collection yet", () => {+ setup({ error: { status: 409 } });++ expect(+ screen.getByText("This data app isn’t published yet"),+ ).toBeInTheDocument();++ expect(+ screen.getByText(+ "An administrator needs to publish this data app before it can be opened.",+ ),+ ).toBeInTheDocument();+ });+it("renders the app inside an iframe once metadata resolves", () => {setup({ data: createMockDataApp({ display_name: "Sales" }) });diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsxindex 271a6892375..b46c5d0b6c9 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx@@ -1,6 +1,7 @@import { PLUGIN_DATA_APPS } from "metabase/plugins";import { hasPremiumFeature } from "metabase-enterprise/settings";+import { ManageDataAppUsersPage } from "./admin/ManageDataAppUsersPage";import { ManageDataAppsPage } from "./admin/ManageDataAppsPage";import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";import { getRoutes } from "./routes";@@ -17,6 +18,7 @@ export function initializePlugin() {PLUGIN_DATA_APPS.isEnabled = true;PLUGIN_DATA_APPS.getRoutes = getRoutes;PLUGIN_DATA_APPS.ManageDataAppsPage = ManageDataAppsPage;+ PLUGIN_DATA_APPS.ManageDataAppUsersPage = ManageDataAppUsersPage;PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;}}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 08c46a7854d..f86c0929372 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,5 +1,6 @@import type { SdkStore } from "embedding-sdk-bundle/store/types";import {+ type DynamicQueryInput,type QueryInput,isQueryInput,isQuestionInput,@@ -7,6 +8,7 @@ import {} from "embedding-sdk-shared/lib/create-metabase-query/input-guards";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 { fetchTableMetadata } from "metabase/redux/tables";import * as Lib from "metabase-lib";@@ -15,34 +17,75 @@ import type {TestColumnSpec,TestExpressionSpec,TestQuerySpec,+ TestStageSpec,TestStageWithSourceSpec,} from "metabase-types/api";import { loadReferencedMetricMetadata } from "./metric-metadata";-import { validateQueryInput } from "./validation";+import { validateDynamicQuery, validateQueryInput } from "./validation";export type ResolveDatasetQuery = (store: SdkStore,-) => (input: QueryInput) => Promise<DatasetQuery>;+) => (+ input: QueryInput,+ dynamicQuery?: DynamicQueryInput,+) => Promise<DatasetQuery>;export const resolveDatasetQuery: ResolveDatasetQuery =- (store) => async (input: QueryInput) => {+ (store) => async (input: QueryInput, dynamicQuery?: DynamicQueryInput) => {if (!isQueryInput(input)) {throw new Error('Query object creation requires a source reference like `{ type: "table", id }` or `{ type: "card", id }`.',);}- validateQueryInput(input);+ const sourceInput = toSourceInput(input);- await loadSourceMetadata(store, input);+ validateQueryInput(sourceInput);+ validateDynamicQuery(dynamicQuery);- return resolveQueryFromLoadedMetadata(input, store.getState());+ await loadSourceMetadata(store, sourceInput);++ return resolveQueryFromLoadedMetadata(+ sourceInput,+ dynamicQuery,+ store.getState(),+ );};type SdkState = ReturnType<SdkStore["getState"]>;-function resolveQueryFromLoadedMetadata(input: QueryInput, state: SdkState) {+/**+ * The query whose source actually runs. Outside the dev preview a published card+ * replaces the table source: the card is what grants an app's viewers permission+ * to run the query, through the collection it lives in. Its static clauses are+ * already baked into the card, so only the source and the dynamic stage remain.+ */+function toSourceInput(input: QueryInput): QueryInput {+ // Only a data app runs published cards. In the dev preview they do not exist+ // yet, and outside a data app they never do, so the table is what runs.+ if (!isTableInput(input) || isDataAppDev() || !isDataApp()) {+ return input;+ }++ if (+ input.savedQuestionSourceId === null ||+ input.savedQuestionSourceId === undefined+ ) {+ // An app's viewers can only read the published cards, so a table source 403s.+ throw new Error(+ "This query has not been synchronized. Define it with `defineQuery(...)` in `queries/`, run `npm run sync-resources`, and rebuild.",+ );+ }++ return { source: { type: "card", id: input.savedQuestionSourceId } };+}++function resolveQueryFromLoadedMetadata(+ input: QueryInput,+ dynamicQuery: DynamicQueryInput | undefined,+ state: SdkState,+) {if (!isQueryInput(input)) {throw new Error('Query object creation requires a source reference like `{ type: "table", id }` or `{ type: "card", id }`.',@@ -51,12 +94,25 @@ function resolveQueryFromLoadedMetadata(input: QueryInput, state: SdkState) {const databaseId = getSourceDatabaseId(input, state);const provider = selectMetadataProviderUnfiltered(state, databaseId);+ const sourceStage = toStageSpec(input);- return Lib.toJsQuery(+ const datasetQuery = Lib.toJsQuery(Lib.createTestQuery(provider, {- stages: [toStageSpec(input)],+ // The dynamic clauses run as their own stage rather than merging into the+ // source stage. Merged, they would apply before the static aggregation on+ // a table source but after it on the published card — the same app would+ // return different numbers in the dev preview and in production.+ stages: dynamicQuery+ ? [sourceStage, toResultColumnStageSpec(dynamicQuery)]+ : [sourceStage],} satisfies TestQuerySpec),);++ // Lib reads the database off the metadata provider, and a user who may read a+ // card but not create queries gets none from `/api/card/:id/query_metadata` —+ // so the query comes back without `:database`, which `/api/dataset` rejects.+ // The source itself carries the id, so set it explicitly.+ return { ...datasetQuery, database: databaseId };}function toStageSpec(input: QueryInput): TestStageWithSourceSpec {@@ -64,10 +120,24 @@ function toStageSpec(input: QueryInput): TestStageWithSourceSpec {return input;}- const { source, filters, aggregations, breakouts, orderBys, limit } = input;+ return {+ source: { type: "card", id: input.source.id },+ ...toResultColumnStageSpec(input),+ };+}+/**+ * A stage whose dimensions are the previous stage's result columns — a card+ * stage or a dynamic stage. Both resolve their columns by name.+ */+function toResultColumnStageSpec({+ filters,+ aggregations,+ breakouts,+ orderBys,+ limit,+}: DynamicQueryInput): TestStageSpec {return {- source: { type: "card", id: source.id },...(filters && { filters: filters.map(toResultColumnExpressionSpec) }),...(aggregations && {aggregations: aggregations.map(toResultColumnExpressionSpec),diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.tsindex 519f0479d70..45f551b2bf0 100644--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts@@ -1,4 +1,5 @@import {+ type DynamicQueryInput,type QueryInput,type QuestionQueryInput,type TableQueryInput,@@ -24,6 +25,15 @@ const QUESTION_QUERY_KEYS: readonly string[] = ["enabled",] satisfies readonly (keyof QuestionQueryInput)[];+const DYNAMIC_QUERY_KEYS: readonly string[] = [+ "filters",+ "aggregations",+ "breakouts",+ "orderBys",+ "limit",+ "enabled",+] satisfies readonly (keyof DynamicQueryInput)[];+export function validateQueryInput(input: QueryInput) {if (isQuestionQueryInput(input)) {validateLimit(input.limit, "Saved question query");@@ -62,24 +72,67 @@ function validateQuestionScopedInputs(input: QuestionQueryInput) {);}+ validateResultColumnClauses(+ input,+ "Saved question query",+ (reference, context) =>+ validateQuestionResultColumn(reference, input.source, context),+ );+}++/**+ * The dynamic clauses a caller layers on top of a static query. They run as a+ * stage of their own, so they see result columns rather than the source table —+ * the same scoping a card stage has.+ */+export function validateDynamicQuery(input: DynamicQueryInput | undefined) {+ if (!input) {+ return;+ }++ const extraKeys = Object.keys(input).filter(+ (key) => !DYNAMIC_QUERY_KEYS.includes(key),+ );++ if (extraKeys.length > 0) {+ throw new Error(+ `Dynamic queries only support ${DYNAMIC_QUERY_KEYS.join(+ ", ",+ )}, but received ${extraKeys.join(", ")}.`,+ );+ }++ validateLimit(input.limit, "Dynamic query");+ validateResultColumnClauses(+ input,+ "Dynamic query",+ validateResultColumnShape,+ );+}++/**+ * Clause checks shared by every stage whose dimensions are result columns.+ * `validateDimension` supplies the part that depends on knowing those columns.+ */+function validateResultColumnClauses(+ input: DynamicQueryInput,+ label: string,+ validateDimension: (reference: unknown, context: string) => void,+) {input.filters?.forEach((filter) => {if (isSegmentReference(filter)) {throw new Error(- "Saved question query filters cannot use Segments, which belong to a table source.",+ `${label} filters cannot use Segments, which belong to a table source.`,);}- validateQuestionResultColumn(- getFirstOperatorArg(filter),- input.source,- "Saved question query filters",- );+ validateDimension(getFirstOperatorArg(filter), `${label} filters`);});input.aggregations?.forEach((aggregation) => {if (isMeasureReference(aggregation) || isMetricReference(aggregation)) {throw new Error(- "Saved question query aggregations cannot use Measures or Metrics, which belong to a table source.",+ `${label} aggregations cannot use Measures or Metrics, which belong to a table source.`,);}@@ -87,34 +140,30 @@ function validateQuestionScopedInputs(input: QuestionQueryInput) {return;}- validateQuestionResultColumn(+ validateDimension(getFirstOperatorArg(aggregation),- input.source,- "Saved question query aggregations",+ `${label} aggregations`,);});input.breakouts?.forEach((breakout) => {- validateQuestionResultColumn(- breakout,- input.source,- "Saved question query breakouts",- );+ validateDimension(breakout, `${label} breakouts`);});validateOrderBys(input,- "Saved question query orderBys",- (orderBy) =>- validateQuestionResultColumn(- orderBy,- input.source,- "Saved question query orderBys",- ),+ `${label} orderBys`,+ (orderBy) => validateDimension(orderBy, `${label} orderBys`),{ matchBreakoutsByName: true },);}+function validateResultColumnShape(reference: unknown, context: string) {+ if (!isObject(reference) || typeof reference.name !== "string") {+ throw new Error(`${context} must reference a result column.`);+ }+}+function validateQuestionResultColumn(reference: unknown,source: QuestionSchema,diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.tsindex 68b19cd36d1..f464823f57f 100644--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts@@ -1,17 +1,23 @@import type { SdkStore } from "embedding-sdk-bundle/store/types";-import type { SdkActionId } from "embedding-sdk-bundle/types/action";+import type {+ SdkActionDefinition,+ SdkActionId,+ SdkActionInput,+} from "embedding-sdk-bundle/types/action";import { executeAction as executeActionMutation } from "metabase/api/action";+import { isDataApp, isDataAppDev } from "metabase/embedding-sdk/config";import type {BaseEntityId,ParametersForActionExecution,WritebackActionId,} from "metabase-types/api";import { isBaseEntityID } from "metabase-types/api";+import { isObject } from "metabase-types/guards";type ActionParametersPayload = Record<string, unknown>;export type ExecuteActionParams = {- actionId: SdkActionId;+ actionId: SdkActionInput;parameters?: ActionParametersPayload;};@@ -36,9 +42,43 @@ const parseActionId = (if (typeof actionId === "number" || isBaseEntityID(actionId)) {return actionId;}+throw new Error(`Invalid action id: ${actionId}`);};+const isActionDefinition = (+ input: SdkActionInput,+): input is SdkActionDefinition => isObject(input) && "action" in input;++/**+ * The action that actually runs. Outside the dev preview the synchronized copy+ * replaces the authored action: the copy is what grants an app's viewers+ * permission to run it, through the collection its model lives in.+ */+function toExecutableActionId(input: SdkActionInput): SdkActionId {+ if (!isActionDefinition(input)) {+ if (isDataApp()) {+ throw new Error(+ `Action ${input} was passed to \`useAction\` as a raw id. A data app must pass the \`defineAction(...)\` export, so the synchronized action runs.`,+ );+ }++ return input;+ }++ if (isDataAppDev() || !isDataApp()) {+ return input.action.id;+ }++ if (input.copiedActionId === null || input.copiedActionId === undefined) {+ throw new Error(+ "This action has not been synchronized. Run `npm run sync-resources` and rebuild.",+ );+ }++ return input.copiedActionId;+}+/*** Triggers a pre-existing Metabase action. The curried `(store) => fn` shape* mirrors `createDashboard` / `queryQuestion` so the package@@ -55,7 +95,7 @@ export const executeAction =return reduxStore.dispatch(executeActionMutation.initiate({- id: parseActionId(actionId),+ id: parseActionId(toExecutableActionId(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 71142932e47..19818841a03 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@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";import { getStore } from "__support__/entities-store";import type { SdkStore } from "embedding-sdk-bundle/store/types";import { Api } from "metabase/api";+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import { executeAction } from "./execute-action";@@ -29,6 +30,74 @@ describe("executeAction", () => {activeStore?.dispatch(Api.util.resetApiState());activeStore = undefined;fetchMock.removeRoutes().clearHistory();+ EMBEDDING_SDK_CONFIG.isDataApp = false;+ EMBEDDING_SDK_CONFIG.isDataAppDev = false;+ });++ describe("a synchronized action definition", () => {+ const AUTHORED_ID = 51;+ const COPIED_ID = 91;+ const definition = {+ action: { id: AUTHORED_ID },+ copiedActionId: COPIED_ID,+ };++ const expectExecuted = async (+ id: number,+ actionId: Parameters<ReturnType<typeof executeAction>>[0]["actionId"],+ ) => {+ fetchMock.post(`path:/api/action/${id}/execute`, {+ status: 200,+ body: { "rows-affected": 1 },+ });++ await executeAction(setup())({ actionId });++ expect(+ fetchMock.callHistory.calls(`path:/api/action/${id}/execute`),+ ).toHaveLength(1);+ };++ it("runs the copy in a production build", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;++ await expectExecuted(COPIED_ID, definition);+ });++ it("runs the authored action in the dev preview", async () => {+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ await expectExecuted(AUTHORED_ID, definition);+ });++ it("runs the authored action outside a data app, where no copy exists", async () => {+ await expectExecuted(AUTHORED_ID, { action: { id: AUTHORED_ID } });+ });++ it("refuses an unsynchronized definition in a production build", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;++ await expect(+ executeAction(setup())({ actionId: { action: { id: AUTHORED_ID } } }),+ ).rejects.toThrow("has not been synchronized");+ });++ it("refuses a raw id inside a data app", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;++ await expect(+ executeAction(setup())({ actionId: AUTHORED_ID }),+ ).rejects.toThrow("passed to `useAction` as a raw id");+ });++ it("refuses a raw id in the dev preview, before it can reach production", async () => {+ EMBEDDING_SDK_CONFIG.isDataApp = true;+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;++ await expect(+ executeAction(setup())({ actionId: AUTHORED_ID }),+ ).rejects.toThrow("passed to `useAction` as a raw id");+ });});it("POSTs to /api/action/:id/execute with the given parameters", async () => {diff --git a/frontend/src/embedding-sdk-bundle/types/action.ts b/frontend/src/embedding-sdk-bundle/types/action.tsindex ee12de6ae5f..22e6e7fdf51 100644--- a/frontend/src/embedding-sdk-bundle/types/action.ts+++ b/frontend/src/embedding-sdk-bundle/types/action.ts@@ -1,3 +1,18 @@import type { SdkEntityId } from "embedding-sdk-bundle/types/entity";+/** How the raw SDK names an action: the id it was given. */export type SdkActionId = number | SdkEntityId;++/**+ * How a data app names an action: the `defineAction` export, which is what a+ * data app must pass. `copiedActionId` addresses the copy synchronization made+ * in the app's own collection — the only one its viewers can read. The dev+ * preview runs `action` instead, so an app works before its first+ * synchronization.+ */+export type SdkActionDefinition = {+ action: { id: SdkActionId };+ copiedActionId?: number;+};++export type SdkActionInput = SdkActionId | SdkActionDefinition;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 a63a90c84c8..609242fbd7e 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@@ -17,18 +17,34 @@ export type TableQueryInput = Omit<TestStageWithSourceSpec, "source"> & {source: TableSchema;limit?: number;enabled?: boolean;++ /**+ * The saved question this static query was published as at build time. Running+ * the card is what lets an app's viewers run the query at all: it sits in a+ * collection whose permission group grants them access, which a table source+ * cannot do. The dev preview ignores it and keeps the table source.+ */+ savedQuestionSourceId?: number;};-export type QuestionQueryInput = Pick<+/**+ * The dynamic clauses applied on top of a static query. They become a stage of+ * their own, and a stage above the source sees only the previous stage's result+ * columns — so it takes the same clause set as a card stage.+ */+export type DynamicQueryInput = Pick<TestStageSpec,"breakouts" | "orderBys" | "limit"> & {- source: QuestionSchema;filters?: readonly TestExpressionSpec[];aggregations?: readonly TestExpressionSpec[];enabled?: boolean;};+export type QuestionQueryInput = DynamicQueryInput & {+ source: QuestionSchema;+};+export type QueryInput = TableQueryInput | QuestionQueryInput;export const isTableInput = (input: unknown): input is TableQueryInput =>diff --git a/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.tsindex 8b253dab6f3..1d146d23d28 100644--- a/frontend/src/metabase-types/api/data-app.ts+++ b/frontend/src/metabase-types/api/data-app.ts@@ -17,6 +17,14 @@ export interface DataApp {bundle_path: string;/** Admin toggle. When false the app is not served. */enabled: boolean;+ /** The collection that contains this app's saved questions and models. */+ resource_collection_id: number | null;+ /** The group that grants users access to this data app. */+ permission_group_id: number | null;+ /** Tables used by the last successful resource synchronization. */+ table_ids: number[];+ /** Whether any app member lacks access to a table used by this app. */+ has_user_permission_warnings?: boolean;/*** External origins the app's sandboxed bundle may `fetch`/XHR, from its* `data_app.yaml`. Empty means none (Metabase data still flows through the@@ -51,3 +59,21 @@ export interface SetDataAppEnabledRequest {name: string;enabled: boolean;}++export interface DataAppMissingTable {+ id: number;+ name: string;+ schema: string | null;+ database_id: number;+ database_name: string;+}++export interface DataAppUserPermissionWarning {+ user_id: number;+ missing_tables: DataAppMissingTable[];+}++export interface GetDataAppUserPermissionWarningsRequest {+ name: string;+ user_ids: number[];+}diff --git a/frontend/src/metabase-types/api/mocks/data-app.ts b/frontend/src/metabase-types/api/mocks/data-app.tsindex e4d78d3450b..8df4cbb0858 100644--- a/frontend/src/metabase-types/api/mocks/data-app.ts+++ b/frontend/src/metabase-types/api/mocks/data-app.ts@@ -7,6 +7,10 @@ export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({description: null,bundle_path: "data_apps/sales/dist/index.js",enabled: true,+ resource_collection_id: 1,+ permission_group_id: 1,+ table_ids: [],+ has_user_permission_warnings: false,allowed_hosts: [],bundle_hash: "abc123",last_synced_sha: "0123456789abcdef",diff --git a/frontend/src/metabase/actions/types.ts b/frontend/src/metabase/actions/types.tsindex 1285ebc3d4a..c7836dafca5 100644--- a/frontend/src/metabase/actions/types.ts+++ b/frontend/src/metabase/actions/types.ts@@ -8,17 +8,19 @@ import type {WritebackQueryAction,} from "metabase-types/api";+// A fetched action always carries a description; creating one need not send it.type BaseCreateActionParams = Pick<WritebackAction,- "name" | "description" | "model_id" | "parameters" | "visualization_settings"->;+ "name" | "model_id" | "parameters" | "visualization_settings"+> &+ Partial<Pick<WritebackAction, "description">>;type BaseUpdateActionParams = {id: WritebackAction["id"];};export type CreateQueryActionParams = BaseCreateActionParams &- Pick<WritebackQueryAction, "type" | "dataset_query">;+ Pick<WritebackQueryAction, "type" | "dataset_query" | "database_id">;export type UpdateQueryActionParams = Partial<CreateQueryActionParams> &BaseUpdateActionParams;diff --git a/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx b/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsxindex 83ba03ed462..74a0cc9d9dc 100644--- a/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx+++ b/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx@@ -6,7 +6,11 @@ import { AdminContentTable } from "metabase/admin/components/AdminContentTable";import { Link } from "metabase/common/components/Link";import { PaginationControls } from "metabase/common/components/PaginationControls";import { usePagination } from "metabase/common/hooks/use-pagination";-import { isAdminGroup, isDefaultGroup } from "metabase/common/utils/groups";+import {+ isAdminGroup,+ isApiKeyGroupMember,+ isDefaultGroup,+} from "metabase/common/utils/groups";import { getUser } from "metabase/current-user";import { PLUGIN_GROUP_MANAGERS, PLUGIN_TENANTS } from "metabase/plugins";import { useSelector } from "metabase/redux";@@ -16,9 +20,6 @@ import type { Group, Member, Membership } from "metabase-types/api";import { AddMemberRow } from "../AddMemberRow";-const isApiKeyGroupMember = (member: Member) =>- member.email.endsWith("@api-key.invalid");-const canEditMembership = (group: Group) =>!isDefaultGroup(group) &&!PLUGIN_TENANTS.isExternalUsersGroup(group) &&diff --git a/frontend/src/metabase/admin/people/components/GroupsListing.tsx b/frontend/src/metabase/admin/people/components/GroupsListing.tsxindex 6436b100467..83199f971ca 100644--- a/frontend/src/metabase/admin/people/components/GroupsListing.tsx+++ b/frontend/src/metabase/admin/people/components/GroupsListing.tsx@@ -215,6 +215,28 @@ function EditingGroupRow({// ------------------------------------------------------------ Groups Table: not editing ------------------------------------------------------------+function GroupNameCell({ group }: { group: GroupInfo }) {+ const name = getGroupNameLocalized(group);+ const membersLink = PLUGIN_TENANTS.isTenantGroup(group)+ ? `/admin/people/tenants/groups/${group.id}`+ : `/admin/people/groups/${group.id}`;++ return (+ <Flex+ component={Link}+ align="center"+ to={membersLink}+ className={CS.link}+ gap="md"+ >+ <UserAvatar user={{ name }} bg={groupIdToColor(group.id)} />+ <Box component="span" fw={700} c="core-brand">+ {name}+ </Box>+ </Flex>+ );+}+interface GroupRowProps {group: GroupInfo;groupBeingEdited: GroupInfo | null;@@ -236,19 +258,12 @@ function GroupRow({onEditGroupCancelClicked,onEditGroupDoneClicked,}: GroupRowProps) {- const backgroundColor = groupIdToColor(group.id);const showActionsButton =!isDefaultGroup(group) &&!isAdminGroup(group) &&!PLUGIN_TENANTS.isExternalUsersGroup(group);const editing = groupBeingEdited && groupBeingEdited.id === group.id;- const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);-- const membersLink = isTenantGroup- ? `/admin/people/tenants/groups/${group.id}`- : `/admin/people/groups/${group.id}`;-return editing ? (<EditingGroupRowgroup={groupBeingEdited}@@ -260,21 +275,7 @@ function GroupRow({) : (<tr aria-label={`group-${group.id}-row`}><td>- <Flex- component={Link}- align="center"- to={membersLink}- className={CS.link}- gap="lg"- >- <UserAvatar- user={{ name: getGroupNameLocalized(group) }}- bg={backgroundColor}- />- <Box component="span" fw={700} c="core-brand">- {getGroupNameLocalized(group)}- </Box>- </Flex>+ <GroupNameCell group={group} /></td><td aria-label="member-count">{group.member_count || 0}diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsxindex 5c6d8ce0ed0..9c9f769ae9b 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx@@ -28,3 +28,7 @@ export function DataAppsManagePage() {return <PLUGIN_DATA_APPS.ManageDataAppsPage />;}++export function DataAppUsersManagePage() {+ return <PLUGIN_DATA_APPS.ManageDataAppUsersPage />;+}diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsxindex f5d0038fb6b..4be71747924 100644--- a/frontend/src/metabase/admin/settingsRoutes.tsx+++ b/frontend/src/metabase/admin/settingsRoutes.tsx@@ -139,6 +139,13 @@ const dataAppsManage = () =>/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage").then(({ DataAppsManagePage }) => ({ Component: DataAppsManagePage }));+const dataAppUsersManage = () =>+ import(+ /* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage"+ ).then(({ DataAppUsersManagePage }) => ({+ Component: DataAppUsersManagePage,+ }));+const uploadSettings = () =>import(/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/UploadSettingsPage"@@ -250,6 +257,7 @@ export const getSettingsRoutes = (element={<IsAdmin />}><Route index lazy={dataAppsManage} />+ <Route path=":slug/users" lazy={dataAppUsersManage} /></Route>)}<Route path="uploads" lazy={uploadSettings} />diff --git a/frontend/src/metabase/common/utils/groups.ts b/frontend/src/metabase/common/utils/groups.tsindex 9a0e2f3d21f..c18ef0f8cd9 100644--- a/frontend/src/metabase/common/utils/groups.ts+++ b/frontend/src/metabase/common/utils/groups.ts@@ -1,7 +1,10 @@import { t } from "ttag";import { PLUGIN_TENANTS } from "metabase/plugins";-import type { GroupInfo, SpecialGroupType } from "metabase-types/api";+import type { GroupInfo, Member, SpecialGroupType } from "metabase-types/api";++export const isApiKeyGroupMember = (member: Member) =>+ member.email.endsWith("@api-key.invalid");const SPECIAL_GROUP_NAMES: Record<string, () => string> = {"All Users": () => t`All Users`,diff --git a/frontend/src/metabase/plugins/oss/data-apps.ts b/frontend/src/metabase/plugins/oss/data-apps.tsindex 8a104ef466a..399d1fb9a0f 100644--- a/frontend/src/metabase/plugins/oss/data-apps.ts+++ b/frontend/src/metabase/plugins/oss/data-apps.ts@@ -8,6 +8,7 @@ export type DataAppsPlugin = {isEnabled: boolean;getRoutes: () => ReactNode | null;ManageDataAppsPage: ComponentType;+ ManageDataAppUsersPage: ComponentType;MainNavbarSection: ComponentType<{ onItemSelect: () => void }>;};@@ -15,6 +16,7 @@ const getDefaultPluginDataApps = (): DataAppsPlugin => ({isEnabled: false,getRoutes: () => null,ManageDataAppsPage: PluginPlaceholder,+ ManageDataAppUsersPage: PluginPlaceholder,MainNavbarSection: PluginPlaceholder,});diff --git a/resources/migrations/064/20260907_data_app_permission.yaml b/resources/migrations/064/20260907_data_app_permission.yamlnew file mode 100644index 00000000000..14e8fe3e92e--- /dev/null+++ b/resources/migrations/064/20260907_data_app_permission.yaml@@ -0,0 +1,109 @@+databaseChangeLog:+ - changeSet:+ id: v64.2026-09-07T00:00:00+ author: poom+ comment: Bind each data app to its generated resource collection+ changes:+ - addColumn:+ tableName: data_app+ columns:+ - column:+ name: resource_collection_id+ type: int+ remarks: Server-owned collection containing the data app's generated saved questions+ constraints:+ nullable: true++ - changeSet:+ id: v64.2026-09-07T00:00:01+ author: poom+ comment: Bind each data app to its generated permission group+ changes:+ - addColumn:+ tableName: data_app+ columns:+ - column:+ name: permission_group_id+ type: int+ remarks: Server-owned read-only permissions group for the data app's users+ constraints:+ nullable: true++ - changeSet:+ id: v64.2026-09-07T00:00:02+ author: poom+ comment: Add the data app resource collection foreign key+ changes:+ - addForeignKeyConstraint:+ baseTableName: data_app+ baseColumnNames: resource_collection_id+ referencedTableName: collection+ referencedColumnNames: id+ constraintName: fk_data_app_resource_collection_id+ onDelete: SET NULL++ - changeSet:+ id: v64.2026-09-07T00:00:03+ author: poom+ comment: Add the data app permission group foreign key+ changes:+ - addForeignKeyConstraint:+ baseTableName: data_app+ baseColumnNames: permission_group_id+ referencedTableName: permissions_group+ referencedColumnNames: id+ constraintName: fk_data_app_permission_group_id+ onDelete: SET NULL++ - changeSet:+ id: v64.2026-09-07T00:00:04+ author: poom+ comment: Track data app drafts before repository import+ changes:+ - addColumn:+ tableName: data_app+ columns:+ - column:+ name: draft+ type: ${boolean.type}+ defaultValueBoolean: false+ remarks: Whether this row is a data app draft before its first repository import+ constraints:+ nullable: false++ - changeSet:+ id: v64.2026-09-07T00:00:05+ author: timofei+ comment: Add permissions_group.is_data_app_group boolean column+ changes:+ - addColumn:+ tableName: permissions_group+ columns:+ - column:+ name: is_data_app_group+ type: ${boolean.type}+ defaultValueBoolean: false+ remarks: "true iff this is a Data App group (server-managed, hidden from the groups UI)"+ constraints:+ nullable: false+ rollback:+ - dropColumn:+ tableName: permissions_group+ columnName: is_data_app_group++ - changeSet:+ id: v64.2026-09-07T00:00:06+ author: poom+ comment: Store table ids used by the last successful resource sync in data apps+ changes:+ - addColumn:+ tableName: data_app+ columns:+ - column:+ name: table_ids+ type: ${text.type}+ remarks: JSON array of table ids used by the last successful resource sync+ rollback:+ - dropColumn:+ tableName: data_app+ columnName: table_idsdiff --git a/rspack.embedding-sdk-node.config.js b/rspack.embedding-sdk-node.config.jsindex 82434a2b329..04bee1faad6 100644--- a/rspack.embedding-sdk-node.config.js+++ b/rspack.embedding-sdk-node.config.js@@ -69,6 +69,7 @@ const cliConfig = {library: { type: "commonjs2" },},resolve: sharedResolve,+ externals: ["esbuild", "typescript"],module: sharedModule,plugins: [new rspack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),@@ -97,6 +98,8 @@ const dataAppDevConfig = {"@vitejs/plugin-react","vite-plugin-svgr","vite-plugin-css-injected-by-js",+ "esbuild",+ "typescript",],externalsType: "module",output: {diff --git a/skills/metabase-data-app-actions/SKILL.md b/skills/metabase-data-app-actions/SKILL.mdindex 60be2de76b3..ad21d21c40e 100644--- a/skills/metabase-data-app-actions/SKILL.md+++ b/skills/metabase-data-app-actions/SKILL.md@@ -28,20 +28,12 @@ Before writing any action-invoking code, look at the schema and enumerate what's```tsimport { useAction } from "@metabase/embedding-sdk-react";-import {- type ActionKindFromDataAppSchema,- type ActionParametersFromDataAppSchema,-} from "@metabase/embedding-sdk-react/data-app";--const { execute, isExecuting, result, error, reset } = useAction<- ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>,- ActionKindFromDataAppSchema<typeof schema.models.<model>.actions.<action>>->(schema.models.<model>.actions.<action>.id);++const { execute, isExecuting, result, error, reset } = useAction(MyAction);```-- **First argument** is the action's numeric **id** — read it off the schema entry as `schema.models.<model>.actions.<action>.id`. The hook also accepts an action's `entity_id` string, but in a Data App you always have the numeric id on hand from the schema, so pass that.-- **`TParameters` generic** — the type of the parameters object you'll pass to `execute`. In a Data App, derive it from the schema with `ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` imported from `@metabase/embedding-sdk-react/data-app`; the helper expands the schema's `parameters[]` into a keyed object, marks `required: true` entries as required keys, and types each value from its `jsType`. Skip the generic and `execute` accepts any `Record<string, unknown>`.-- **`TKind` generic** — the action kind literal that drives the discriminated `result` shape. In a Data App, derive it from the same schema entry with `ActionKindFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` imported from `@metabase/embedding-sdk-react/data-app`; the helper maps `implicitKind` (`"row/create"` → `"create"`, `"row/update"` → `"update"`, `"row/delete"` → `"delete"`, any `"bulk/*"` → `"bulk"`) and `type === "query"` → `"sql"`. Skip the generic and `result` defaults to the `AnyActionResult` union — TS-narrowable via `"<key>" in result`, but you lose the per-kind precision.+- **The argument** is the `defineAction(...)` export itself — pass `MyAction`, not `MyAction.copiedActionId`. A production build then runs the synchronized copy, whose model sits in the app's own collection; the dev preview keeps running the authored action, so an app works before it has ever been synchronized. Do **not** pass `schema.models.<model>.actions.<action>` or its `.id`: the entry is a compile error, and the raw id belongs to the original model, which the app's users cannot read, so the call fails on permissions in production. Outside a data app the hook also accepts a raw numeric id or an `entity_id` string.+- **Don't write the generics.** The definition carries its schema entry, so the hook infers both the parameters object and the discriminated `result` from it: `parameters[]` becomes a keyed object (`required: true` entries are required keys, each value typed from its `jsType`), and `implicitKind` / `type` become the kind (`"row/create"` → `"create"`, `"row/update"` → `"update"`, `"row/delete"` → `"delete"`, any `"bulk/*"` → `"bulk"`, `type === "query"` → `"sql"`). Only the raw-id form still needs them spelled out — `useAction<TParameters, TKind>(42)` — since an id describes nothing.- **`execute(parameters)`** — triggers the action. Parameters object is keyed by parameter `slug`; parameters declared `required: true` are required keys, everything else optional. Returns the response body on success AND throws on failure (the error is also written to `error` state for render-time consumers). Resolves to `null` (without making a request) when `actionId` is `null` or the SDK is not yet initialized — guard the call site if those cases are reachable.- **No `enabled` / `options` argument.** The hook only ever runs when `execute(...)` is called, so a gate option would be redundant. Skip the action by branching in the event handler:```ts@@ -61,19 +53,12 @@ const { execute, isExecuting, result, error, reset } = useAction<```tsximport { useAction } from "@metabase/embedding-sdk-react";-import {- type ActionKindFromDataAppSchema,- type ActionParametersFromDataAppSchema,-} from "@metabase/embedding-sdk-react/data-app";-import schema from "../metabase.data";+import { CreatePerson } from "../../actions/people.action";function AddPersonForm({ onCreated }: { onCreated: () => void }) {const { useState } = React;- const { execute, isExecuting, error, reset } = useAction<- ActionParametersFromDataAppSchema<typeof schema.models.people.actions.create>,- ActionKindFromDataAppSchema<typeof schema.models.people.actions.create>- >(schema.models.people.actions.create.id);+ const { execute, isExecuting, error, reset } = useAction(CreatePerson);const [name, setName] = useState("");const [email, setEmail] = useState("");@@ -158,7 +143,7 @@ The rule is simple and absolute: **after an action resolves successfully, everyEach `parameters[]` entry on a schema action exposes `slug`, `displayName`, `jsType`, and optionally `required`. The Data App's job:-- **Object keys in `execute({ … })` match the parameter `slug` strings.** Use them as literal string keys — the typed `ActionParametersFromDataAppSchema<TAction>` shape will reject typos at compile time, but only when the action arg is the schema entry (not a bare id).+- **Object keys in `execute({ … })` match the parameter `slug` strings.** Use them as literal string keys — the shape the hook derives from the definition rejects typos at compile time, but only when the argument is the `defineAction(...)` export (not a bare id).- **Pick the right input `type` from `jsType`** so the browser provides the correct UX and built-in coercion. The agent never invents the input type from the slug name (a slug called `"phone"` is still `jsType: "string"` → `type="text"`).| `jsType` | Input element |@@ -201,7 +186,7 @@ No hand-rolled `!name || !email` checks.When an action appears to succeed but the screen doesn't update, or a call fails with a 400:1. Log `result`, `error`, and `isExecuting` after `await execute(...)` to confirm the request actually went through and succeeded.-2. Confirm `useAction` was called with `schema.models.<model>.actions.<action>.id` (the numeric id) AND the `ActionParametersFromDataAppSchema<typeof …>` generic — without the generic, `execute` won't type-check the parameters object and typos slip through.+2. Confirm `useAction` was called with the `defineAction(...)` export. Passing the schema entry is a compile error; passing its `.id` compiles but leaves `execute` untyped and 403s in production, since the authored action is not the one an app's users can run.3. Log the object passed to `execute({ ... })`. Every key must match a parameter `slug` from `schema.models.<model>.actions.<action>.parameters`; every value must match its declared `jsType`.4. List every data view on the screen that reads from the mutated model. Confirm each one's data hook is mounted ABOVE the action trigger so its refresh callback can be passed down.5. Confirm the refresh callback is called AFTER `await execute(...)` AND that the refresh itself is awaited. When multiple refreshes apply, confirm they're awaited together (`Promise.all`).@@ -210,7 +195,7 @@ When an action appears to succeed but the screen doesn't update, or a call fails## Common Mistakes-- Omitting the `ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` generic on `useAction`. `execute` then accepts any `Record<string, unknown>` and typos like `{ wrongKey: 1 }` slip through.+- Passing `schema.models.<model>.actions.<action>.id` to `useAction` instead of the `defineAction(...)` export. `execute` then accepts any `Record<string, unknown>`, typos like `{ wrongKey: 1 }` slip through, and production 403s because the authored action is not the one an app's users can run.- Forgetting to refresh after a successful action. The UI keeps rendering stale data with no error or warning.- Rendering `"Failed"` / `"Something went wrong"` / `String(error)` instead of the real backend message. Always extract `error.data.message` / `error.data.errors` (the diagnostic the user needs is in there) and render it verbatim — see *Showing the error message*.- Calling the refresh callback without `await`ing it. The modal dismisses or the form clears before fresh data arrives, leaving the user staring at the stale view for a beat.diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.mdindex 6632167f543..e2c4425b379 100644--- a/skills/metabase-data-app-semantic-layer/SKILL.md+++ b/skills/metabase-data-app-semantic-layer/SKILL.md@@ -12,11 +12,13 @@ Keep the semantic layer and presentation layer separate.- All Metabase context must come from the generated schema file, usually `src/metabase.data.ts` or `src/*.metabase.data.ts`.- Do not discover data through MCP tools, create Metabase content, create tables, or edit the semantic layer while building the React UI.- Import data app query helpers from `@metabase/embedding-sdk-react/data-app`.+- Never remove, edit, or copy a generated `savedQuestionSourceId` or `copiedActionId`, even if it appears unused. Preserve it during refactors; use `npm run sync-resources` to repair or replace generated IDs.- Prefer generated schema objects over raw IDs or strings. Extract local constants for top-level table objects.- Never hand-write `DatasetQuery`/MBQL objects in app code. Do not pass inline query objects like `{ type: "query", query: { "source-table": table.id } }`, raw `source-table` clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, `useMetabaseQuery`, or `useMetabaseQueryObject`. Prefer generated table and metric schema objects; for simple table-source queries, an explicit source reference like `{ type: "table", id: table.id }` is also valid.-- Build queries with `source: schema.tables.<name>` or `source: schema.questions.<name>`, generated `fields`, generated `segments`, generated `measures`, generated metrics in `aggregations`, generated metric `dimensions`, generated question `columns`, `filter(...)`, `breakout(...)`, `orderBy(...)`, and `aggregations` helpers such as `aggregations.count()` and `aggregations.sum(...)`. Do not use `source: schema.metrics.<name>`; metrics are aggregation expressions, not query sources.+- Build queries with `source: schema.tables.<name>`, generated `fields`, generated `segments`, generated `measures`, generated metrics in `aggregations`, generated metric `dimensions`, `filter(...)`, `breakout(...)`, `orderBy(...)`, and `aggregations` helpers such as `aggregations.count()` and `aggregations.sum(...)`. Do not use `source: schema.metrics.<name>`; metrics are aggregation expressions, not query sources.+- Do not use existing saved questions as `useMetabaseQuery` or `useMetabaseQueryObject` sources. Typed schemas do not expose `schema.questions` or support `question-collections` while data-app reconciliation cannot copy existing saved questions into the app collection.- Prefer semantically rich table queries over shallow table dumps. Use curated table measures, segments, filters, and breakouts when they make the generated app more useful.-- Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows.+- Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows. Both belong to the static query only — the dynamic second argument cannot take them, see *Static and dynamic query parts*.- Filter UI must default to showing data. Empty controls, "All" options, and incomplete custom ranges should produce no filter instead of blocking queries or showing a blank dashboard.- Do not hardcode categorical filter option values. A generated schema field only proves the field exists, not which values exist; query options from Metabase at runtime using the same generated schema field that the filter applies.- Dashboard-level filters should visibly affect every compatible card, table, KPI, and trend. If a filter can only apply to one query, make that scope obvious in the UI; do not show duplicate or no-op date controls.@@ -33,6 +35,7 @@ Keep the semantic layer and presentation layer separate.- `useMetabaseQuery().rows` are keyed objects, not tuple arrays. Never read `row[0]` / `row[1]`, and never silence this with `as unknown as [string, number][]`, `DisplayRow`, or another tuple cast. If TypeScript says property `0` does not exist, it is catching a real bug. For typed `data.rows`, use literal keys such as `row.count` or generated field names such as `row[ordersTable.fields.createdAt.name]`. Use `data.columns` with `rawRows` or after explicitly narrowing a key; do not index typed rows with arbitrary `string` values from `data.columns`.- Do not cast query objects to `Parameters<typeof useMetabaseQuery>[0]`. That erases the generated table/metric validation. Use `useMetabaseQuery<typeof table>(...)`, or type a reusable query object with `satisfies MetabaseQueryOptions<typeof table>`.- Do not build shared filter arrays with `ReturnType<typeof filter>[]` or `push(...)`; this can collapse overload inference. Pass raw filter state between components and build each query's `filters: [...]` inline with spreads.+- Keep runtime state out of the base query in `queries/`. A clause whose value comes from a control — a selected plan, a date range, a search box — belongs in the second argument to `useMetabaseQuery`/`useMetabaseQueryObject`, not in the query. See "Static and dynamic query parts".- Do not include `fields` in queries with `aggregations` and `breakouts`; breakouts determine grouped result columns. Use `fields` only for row-selection queries.- Before rendering a field, verify it exists in the generated schema object and is returned by the query. Do not guess table keys, field keys, or column names from the Metabase API, business intuition, or old mock data; only use entries actually emitted in `src/metabase.data.ts`.- Avoid unsupported freshness or operational claims such as "real-time", "live", "understaffed", or "risk" unless the returned data or curated semantic-layer definition supports them.@@ -47,11 +50,10 @@ Before generating, make sure the user has explicitly chosen the library scope th- `include-data-library=true` for the whole `Library / Data` tree.- `include-metric-library=true` for the whole `Library / metrics` tree.- `library-collections=<id-or-entity-id>[,<id-or-entity-id>]` for specific Data or metrics library subcollections.-- `question-collections=<id-or-entity-id>[,<id-or-entity-id>]` for specific normal collections that contain saved questions.- `include-models=true` for readable models that have actions. When combined with `database=<name-or-id>`, it includes models with actions for that database only.- `database=<name-or-id>` when the app should use tables from one database.-Use `question-collections` when the app needs `schema.questions.*` to be generated. Use `include-models=true` when the app needs any saved action under `schema.models.<model>.actions`; it includes all readable models with executable actions, unless `database` scopes them to one database. Models without executable actions are omitted to keep generated schemas compact. It can be combined with `library-collections`, `include-data-library`, `include-metric-library`, or `question-collections` so one schema can include selected tables/metrics/questions plus all readable actions.+Use `include-models=true` when the app needs any saved action under `schema.models.<model>.actions`; it includes all readable models with executable actions, unless `database` scopes them to one database. Models without executable actions are omitted to keep generated schemas compact. It can be combined with `library-collections`, `include-data-library`, or `include-metric-library` so one schema can include selected tables/metrics plus all readable actions.If the user asks for any mutation-like flow, such as creating, updating, deleting, submitting, approving, executing an action, or running a write operation, include `include-models=true` in the typed-schema URL. Do this even when the user names one specific model/action, because actions are only discoverable through generated model entries.@@ -96,9 +98,46 @@ fi)```-When the app needs saved questions, include `question-collections=<id-or-entity-id>[,<id-or-entity-id>]` in the typed-schema URL. When the app needs models or actions, include `include-models=true`.+When the app needs models or actions, include `include-models=true`.-If schema generation fails while building a selected saved question, model, or model action, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing `card-id` / `card-name` / `card-type`, `model-id` / `model-name`, dropped action ids, and message when present. This usually means a selected model/question/action was readable enough to select, but its details could not be built, often because its source table, source card, or action details are not published, accessible, valid, or resolvable in the fetch context. The schema would otherwise omit the entire `schema.models.<model>` or `schema.questions.<question>` entry, or return a model whose `actions` map silently omits an action, so the user needs to curate or publish the missing dependency before regenerating.+If schema generation fails while building a selected model or model action, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing `card-id` / `card-name` / `card-type`, `model-id` / `model-name`, dropped action ids, and message when present.++## Synchronize every query and action++Everything an end-to-end prototype runs is permission-bound: it runs against a copy in the app's own collection; read access to that collection lets viewers run the app's cards, but they see the data only if they already have access to the underlying tables — the app grants the collection, not the tables. Declare each one as a named export in a root-level directory beside `package.json` — `queries/` for `defineQuery(...)`, `actions/` for `defineAction(...)`. `npm run sync-resources` scans only those two directories, so a definition under `src/queries/`, `src/actions/`, or any other source directory is silently never synchronized. Discovery covers `.js`, `.jsx`, `.ts`, `.tsx`, `.cjs`, `.cts`, `.mjs`, and `.mts`.++```ts+import { defineAction, defineQuery } from "@metabase/embedding-sdk-react/data-app";+import schema from "../src/metabase.data";++// queries/revenue.query.ts+export const RevenueQuery = defineQuery({ source: schema.tables.orders });++// actions/orders.action.ts+export const CreateOrder = defineAction({+ action: schema.models.orders.actions.create,+});+```++One `sync-resources` run reconciles both. For a query it materializes the authored table query as a saved question and injects `savedQuestionSourceId`. For an action it copies the action's parent model into the app collection, copies the action onto that copy, and injects `copiedActionId`; a model is copied once no matter how many of its actions the app declares, siblings reuse that copy, and it disappears with the last declaration. Never copy a model into the app collection by hand.++Pass the definition itself to the hook and let the SDK resolve what runs — a production build runs the copy, while the dev preview runs the authored table or action, so an app works before its first synchronization:++```ts+const { data } = useMetabaseQuery(RevenueQuery, {+ filters: [filter(RevenueQuery.source.fields.status, "=", selectedStatus)],+});++const { execute, isExecuting, error } = useAction(CreateOrder);+```++Never pass an inline table-source query (not even a read-only, filter-option, or helper query), a raw action id, `savedQuestionSourceId`, `copiedActionId`, or a hand-built `{ source: { type: "card", id } }`, and never spread a definition into a new object. Each defeats the swap; the authored ids also bypass the permission boundary, and `schema.models.<model>.actions.<action>` is a type error. Keep fixed permission-boundary filters, aggregations, and breakouts inside `defineQuery` — synchronization bakes them into the saved question, so don't apply them again outside it, and put runtime clauses in the hook's second argument (see *Static and dynamic query parts*). `useAction` needs no generics: the definition types `execute`'s parameters and `result`.++Wire `package.json` with `"sync-resources": "embedding-sdk-react data-apps sync-resources"` and `"build": "npm run sync-resources && vite build"`, then run `npm run build` after adding, changing, renaming, or removing any definition; run `sync-resources` directly only to inspect generated state before a build. It reads `DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` from the repo-root `.env.local`.++Inline generated IDs and `resources_metadata.json` are generated state: never delete or hand-edit either. A missing ID is restored automatically when the definition still identifies its resource — a query by its table and authored hash matching one unclaimed lockfile entry, an action by naming the same action — while a duplicated ID fails the run. Do not test or hand off the app until `npm run build` succeeds, every live definition carries a positive generated ID, and `resources_metadata.json` holds its matching entry. Commit every generated change. The build stops before bundling when synchronization fails.++If synchronization fails, surface the exact error and stop. Fix local shape, serialization, duplicate-ID, or lockfile errors before retrying. A confirmed `404` is recovered automatically; authentication, permission, network, server, collection-ownership, and Card-type failures must not trigger manual Card creation, deletion, ID replacement, or lockfile editing. Treat a successful run that discovers nothing as a failure when the app has queries or actions. Synchronization copies actions but never creates them, so an action the app needs must already exist in Metabase and be picked up by a regenerated schema; if the run reports that actions are not enabled for the database, stop and tell the user to enable them rather than working around it.## Standard pattern@@ -136,7 +175,6 @@ Use keyed schema objects:- Tables: `source: schema.tables.<table>`- metrics: `schema.metrics.<metric>` inside `aggregations`-- Saved questions: `source: schema.questions.<question>`- Fields: `schema.tables.<table>.fields.<field>`- Segments: `schema.tables.<table>.segments.<segment>`- Measures: `schema.tables.<table>.measures.<measure>`@@ -144,6 +182,55 @@ Use keyed schema objects:Do not pass raw dimension strings like `"created_at"` or `"segment"`.+## Static and dynamic query parts++Both query hooks take an optional second argument: the clauses that change while the app runs.++```ts+// revenue.query.ts — static, and identical on every render+const orders = schema.tables.orders;++export const RevenueQuery = defineQuery({+ source: orders,+ aggregations: [aggregations.sum(orders.fields.total)],+ breakouts: [+ breakout(orders.fields.createdAt, { unit: "month" }),+ breakout(orders.fields.plan),+ ],+});++// the component supplies only what the UI changes+const { data } = useMetabaseQuery(RevenueQuery, {+ filters: plan === null ? [] : [filter(orders.fields.plan, "=", plan)],+});+```++Split them this way even when nothing appears to depend on it: the first argument must be identical on every render, and only the second may vary with runtime state.++The dynamic clauses run as their own stage, so they see the **result columns** of the static query, not its source table. That is why `plan` is a breakout above: a control that filters on a source column only works if that column survives into the result. If it does not, add it as a breakout, or leave the static query unaggregated. Likewise, filter an aggregated static query on `count`/`sum`, not on the fields behind them.++**Segments and measures belong to the static part only.** They are defined against a table, and the dynamic stage has no table — so `filters: [orders.segments.completed]` and `aggregations: [orders.measures.revenue]` are rejected, at compile time and again at runtime. This is the one place the usual "prefer the curated definition" rule does not apply.++Put the curated definition in the static query where it resolves, and let the dynamic clause work on what came out:++```ts+export const CompletedOrders = defineQuery({+ source: orders,+ filters: [orders.segments.completed], // the segment resolves here+ aggregations: [orders.measures.revenue],+ breakouts: [breakout(orders.fields.plan)],+});++const { data } = useMetabaseQuery(CompletedOrders, {+ // a result column, not a segment or measure+ filters: plan === null ? [] : [filter({ type: "column", name: "PLAN" }, "=", plan)],+});+```++If a control must switch a segment on and off, that is a choice between static queries, not a dynamic clause: define one query per state and pick the query, or express the same condition as a filter on a result column.++Do not remove or hand-edit `savedQuestionSourceId` if you find it on a query object, or `copiedActionId` on an action definition. Both are generated synchronization state — see *Synchronize every query and action*.+## Table query recipesFor a table query, pass the generated table object as `source`:@@ -245,30 +332,6 @@ useMetabaseQuery({A metric aggregation must belong to the table source. Do not use source-card metrics in table-source queries. Generated metric dimensions are scoped to their owning metric: if a query uses `revenueMetric.dimensions.*` in filters, helper aggregations, breakouts, or orderBys, it must also include `revenueMetric` in `aggregations`. Do not use metric dimensions as standalone table fields for unrelated `count()` or table-measure queries. Generated metric dimensions must also resolve to the table source. For reusable query objects, use `satisfies MetabaseQueryOptions<typeof ordersTable>` so TypeScript can validate the query while preserving precise row keys.-## Saved question query recipes--A saved question source takes the same clauses as a table source — `filters`, `aggregations`, `breakouts`, `orderBys`, `limit` — applied on top of the question's results, with three differences:--- Dimensions come from `schema.questions.<question>.columns`, a positional array in the order the question returns them, not a keyed `fields` record. Read the generated schema for that order.-- Segments, Measures, and Metrics are rejected; they are scoped to a table source. A generated table field still resolves when its name matches a result column, but prefer the question's `columns` — a renamed or computed column has no matching field.-- `fields` is not supported: a question query returns the question's columns.--```ts-const ordersQuestion = schema.questions.ordersQuestion;-const [status, amount, createdAt] = ordersQuestion.columns;--const { data } = useMetabaseQuery({- source: ordersQuestion,- filters: [filter(status, "=", "paid")],- aggregations: [aggregations.sum(amount)],- breakouts: [breakout(createdAt, { unit: "month" })],-});-```--Adding `aggregations` or `breakouts` replaces the question's result columns with the query's own, so `data.rows` is keyed by the breakout and aggregation column names. For reusable query objects, use `satisfies MetabaseQueryOptions<typeof ordersQuestion>`.--SQL parameters stay on the existing `questionId` query path. Do not pass SQL parameter values through `source: schema.questions.<question>`.-## SDK-rendered viewsTable fields, segments, measure aggregations, and metric aggregations must come from the queried table. Generated metric dimensions used in filters, helper aggregations, breakouts, and orderBys must resolve to the queried table and belong to a metric included in the same query's `aggregations`.@@ -278,7 +341,7 @@ When table queries use `fields`, `segments`, `aggregations`, `breakouts`, or `orWhether an element is an SDK question at all — and whether it is `StaticQuestion` or `InteractiveQuestion` — is decided in the data-app setup skill (*Rendering a chart: Metabase first*). Once it is: build a semantic query with `useMetabaseQueryObject`, then pass it through the SDK question component's `card` prop.-`useMetabaseQueryObject` supports generated table queries, including metric aggregations, and generated saved question queries. Use `useMetabaseQuery` when custom React needs direct row data; use `useMetabaseQueryObject` when Metabase should render or manage the visualization. Do not pass generics to `useMetabaseQueryObject`; it returns `{ query, error, isLoading }`, not query result rows.+`useMetabaseQueryObject` supports generated table queries, including metric aggregations. Use `useMetabaseQuery` when custom React needs direct row data; use `useMetabaseQueryObject` when Metabase should render or manage the visualization. Do not pass generics to `useMetabaseQueryObject`; it returns `{ query, error, isLoading }`, not query result rows.The examples under *Rendering With SDK Components* use `return null` for minimal loading and error handling. In a real app, render the app's existing loading or error UI there. Passing `card={{ query }}` is safe while `query` is `null`; do not pass the full `{ query, error, isLoading }` hook result as `card.query`.@@ -444,8 +507,7 @@ import type { MetabaseQueryOptions } from "@metabase/embedding-sdk-react/data-aptype SortKey = "revenue" | "orders";type ScorecardTable = typeof scorecardTable;-type ScorecardField =- ScorecardTable["fields"][keyof ScorecardTable["fields"]];+type ScorecardField = ScorecardTable["fields"][keyof ScorecardTable["fields"]];const sortFields = {revenue: scorecardTable.fields.netRevenue,@@ -588,6 +650,7 @@ If no curated schema entry supports the intended UI, leave the section out or as## Final Checks- Run `npm run typecheck`.+- Run `npm run build`; it synchronizes queries before producing the bundle.- Keep TypeScript diagnostics compact in the chat or handoff. Use the full output locally to fix the app, but report grouped root causes and only a few representative diagnostics instead of pasting the entire `tsc` output.- Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.- Search touched files for `row[0]`, `row[1]`, `row.orderedAt`, `row.orderDate`, `as unknown as`, `DisplayRow`, `<select`, `margin`, `rate`, `score`, `percent`, `%`, `* 100`, and `.toFixed`; fix positional rows, result-key guesses, entity `<select>` filters, and unsupported business-field interpretations.@@ -605,6 +668,7 @@ If no curated schema entry supports the intended UI, leave the section out or as- Adding lookup helpers instead of using keyed generated schema objects.- Inventing SDK component prop names instead of using `query` for generated table queries.- Mixing fields, segments, or measures from unrelated tables.+- Passing a segment or measure to the dynamic second argument, where only result columns resolve.- Adding a filter UI that sends empty values instead of omitting the filter.- Hardcoding categorical filter values instead of querying the runtime values from Metabase.- Displaying entity names but filtering by those names when a stable ID is available.diff --git a/skills/metabase-data-app-setup/template/package.json b/skills/metabase-data-app-setup/template/package.jsonindex d5142d69049..32d2e236fc6 100644--- a/skills/metabase-data-app-setup/template/package.json+++ b/skills/metabase-data-app-setup/template/package.json@@ -5,7 +5,8 @@"type": "module","scripts": {"dev": "vite --port 5174",- "build": "vite build",+ "build": "npm run sync-resources && vite build",+ "sync-resources": "embedding-sdk-react data-apps sync-resources","typecheck": "tsc --noEmit"},"dependencies": {diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.cljindex 7f03af64f1f..d0503827020 100644--- a/src/metabase/collections/core.clj+++ b/src/metabase/collections/core.clj@@ -15,6 +15,7 @@[metabase.collections.createcreate-collection!][metabase.collections.models.collection+ archive-or-unarchive-collection!has-remote-synced-collection?check-for-remote-sync-updatecheck-non-remote-synced-dependenciesdiff --git a/src/metabase/lib/schema/metadata/fingerprint.cljc b/src/metabase/lib/schema/metadata/fingerprint.cljcindex 9788f568fc1..c50ac803eb4 100644--- a/src/metabase/lib/schema/metadata/fingerprint.cljc+++ b/src/metabase/lib/schema/metadata/fingerprint.cljc@@ -54,6 +54,8 @@[:percent-state {:optional true} [:maybe [:ref ::percent]]][:percent-blank {:optional true} [:maybe [:ref ::percent]]][:average-length {:optional true} [:maybe number?]]+ [:min-length {:optional true} [:maybe number?]]+ [:max-length {:optional true} [:maybe number?]][:mode-fraction {:optional true} [:maybe [:ref ::percent]]][:top-3-fraction {:optional true} [:maybe [:ref ::percent]]]])@@ -63,6 +65,9 @@{:closed true, :decode/normalize lib.schema.common/normalize-map-no-kebab-case}[:earliest {:optional true} [:maybe :string]][:latest {:optional true} [:maybe :string]]+ [:skewness {:optional true} [:maybe number?]]+ [:weekday-distribution {:optional true} [:maybe [:sequential [:ref ::percent]]]]+ [:hour-distribution {:optional true} [:maybe [:sequential [:ref ::percent]]]][:mode-fraction {:optional true} [:maybe [:ref ::percent]]][:top-3-fraction {:optional true} [:maybe [:ref ::percent]]]])diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.cljindex 984b428c8b7..90d63dca481 100644--- a/src/metabase/permissions/core.clj+++ b/src/metabase/permissions/core.clj@@ -42,6 +42,8 @@at-least-as-permissive?batch-delete-permissions!batch-insert-permissions!+ data-app-group-ids+ data-app-view-data-permission-leveldisable-perms-cachedownload-perms-levelfull-database-permission-for-userdiff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.cljindex 87a89013bc2..253f9afb79e 100644--- a/src/metabase/permissions/models/data_permissions.clj+++ b/src/metabase/permissions/models/data_permissions.clj@@ -1270,6 +1270,19 @@[_db-id group-ids](zipmap group-ids (repeat :unrestricted)))+(defenterprise data-app-view-data-permission-level+ "The app-group View Data level to preserve when a new table is created."+ metabase-enterprise.data-apps.permissions+ [_database-id]+ :blocked)++(defenterprise data-app-group-ids+ "Ids of the permission groups Metabase owns and manages itself (data-app groups). They grant no data+ access beyond ordinary groups' permissions. SSO group sync must never touch their membership. OSS has none."+ metabase-enterprise.data-apps.models.data-app+ []+ #{})+;;; ---------------------------------------- Bulk permission functions ------------------------------------------------;; These functions set permissions for newly-created entities (groups, databases, tables) using batch SQL operations;; instead of per-row mutations. They are intended to be called from within a coarse cluster lock.@@ -1330,6 +1343,7 @@(defn set-default-database-permissions!"Bulk-sets default permissions for a newly-created database across all groups.For tenant groups, uses least-permissive values. For audit DBs, uses hardcoded values.+ Data-app groups use least-permissive values for other databases.For other groups, values are based on the group's lowest existing permission level.Uses batch SQL operations instead of per-row mutations."[database groups]@@ -1337,6 +1351,7 @@(let [db-id (u/the-id database)is-audit (:is_audit database)group-ids (map u/the-id groups)+ app-group-ids (set (data-app-group-ids))defaults (least-permissive-defaults);; Batch-fetch distinct (group, perm-type, value) triples — we only need the set of unique values per;; group to find the most restrictive level;@@ -1371,6 +1386,10 @@:perms/manage-database :no:perms/transforms :no}+ ;; new databases must not grant any permissions to existing data app groups+ (contains? app-group-ids group-id)+ defaults+;; Normal: compute based on group's lowest existing perm level:else(let [view-data-level (get view-data-levels group-id :unrestricted)diff --git a/src/metabase/permissions/schema.clj b/src/metabase/permissions/schema.cljindex 1ed6e256be4..5884c86c294 100644--- a/src/metabase/permissions/schema.clj+++ b/src/metabase/permissions/schema.clj@@ -142,11 +142,12 @@(mr/def ::permissions-group"A PermissionsGroup as selected from the app DB: every column of `:permissions_group`."[:map {:closed true}- [:id ms/PositiveInt]- [:name :string]- [:entity_id :string]- [:magic_group_type [:maybe [:or :keyword :string]]]- [:is_tenant_group :boolean]])+ [:id ms/PositiveInt]+ [:name :string]+ [:entity_id :string]+ [:magic_group_type [:maybe [:or :keyword :string]]]+ [:is_tenant_group :boolean]+ [:is_data_app_group :boolean]])(mr/def ::permissions-group.member"A member of a PermissionsGroup as `metabase.permissions.db/group-members` selects it: the User columns the group@@ -167,10 +168,11 @@(mr/def ::permissions-group.update"What an update (or insert) of a PermissionsGroup accepts: every column of `:permissions_group` except `id`, all optional."[:map {:closed true}- [:name {:optional true} [:maybe :string]]- [:entity_id {:optional true} [:maybe :string]]- [:magic_group_type {:optional true} [:maybe [:or :keyword :string]]]- [:is_tenant_group {:optional true} [:maybe :boolean]]])+ [:name {:optional true} [:maybe :string]]+ [:entity_id {:optional true} [:maybe :string]]+ [:magic_group_type {:optional true} [:maybe [:or :keyword :string]]]+ [:is_tenant_group {:optional true} [:maybe :boolean]]+ [:is_data_app_group {:optional true} [:maybe :boolean]]])(mr/def ::permissions-group-membership"A PermissionsGroupMembership as selected from the app DB: every column of `:permissions_group_membership`."diff --git a/src/metabase/permissions_rest/api.clj b/src/metabase/permissions_rest/api.cljindex 9d489dbe8c7..7ebc06bec94 100644--- a/src/metabase/permissions_rest/api.clj+++ b/src/metabase/permissions_rest/api.clj@@ -169,7 +169,8 @@(-> (ordered-groups (request/limit) (request/offset){:tenancy tenancy:manager-user-id manager-user-id- :tenants-enabled? (setting/get :use-tenants)+ :tenants-enabled? (setting/get :use-tenants)+ :exclude-data-app-groups? true:advanced-permissions-enabled? (premium-features/enable-advanced-permissions?)})(t2/hydrate :member_count)(maybe-fix-names))))@@ -291,6 +292,12 @@(u/the-id (perms/data-analyst-group))):exclude-tenant-groups? (not (setting/get :use-tenants))})))+(defn- check-data-app-group-feature!+ [group-id]+ (when (permissions-rest.db/data-app-group? group-id)+ (premium-features/assert-has-feature :data-apps-preview (tru "Data Apps"))+ true))+;; 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;;@@ -306,6 +313,9 @@(let [is_group_manager (boolean is_group_manager)](perms/check-manager-of-group group_id)(perms/check-tenant-groups-visible! [group_id])+ (when (check-data-app-group-feature! group_id)+ (api/check-400 (permissions-rest.db/active-user-exists? user_id)+ (tru "Deactivated users cannot be added to data apps.")))(when is_group_manager;; enable `is_group_manager` require advanced-permissions enabled(perms/check-advanced-permissions-enabled :group-manager)diff --git a/src/metabase/permissions_rest/data_permissions/graph.clj b/src/metabase/permissions_rest/data_permissions/graph.cljindex 232c3212965..5ae3e7c4df7 100644--- a/src/metabase/permissions_rest/data_permissions/graph.clj+++ b/src/metabase/permissions_rest/data_permissions/graph.clj@@ -626,6 +626,12 @@(assoc-in ks new-value)update-data-perms-graph!*)))+(defenterprise reconcile-data-app-permissions!+ "Update data app groups after ordinary permissions change, within the same permissions transaction."+ metabase-enterprise.data-apps.permissions+ [_database-ids]+ nil)+(mu/defn update-data-perms-graph!"Takes an API-style perms graph and sets the permissions in the database accordingly. Additionally ensuresimpersonations and sandboxes are consistent if necessary."@@ -637,7 +643,8 @@(check-audit-db-permissions group-updates)(update-data-perms-graph!* group-updates)(delete-impersonations-if-needed-after-permissions-change! group-updates)- (delete-gtaps-if-needed-after-permissions-change! group-updates)))))+ (delete-gtaps-if-needed-after-permissions-change! group-updates)+ (reconcile-data-app-permissions! (into #{} (mapcat keys) (vals group-updates)))))));; The following arity is provided solely for convenience for tests/REPL usage([ks :- [:vector :any] new-value]diff --git a/src/metabase/permissions_rest/db.clj b/src/metabase/permissions_rest/db.cljindex 8d9bf957572..731dc3ed262 100644--- a/src/metabase/permissions_rest/db.clj+++ b/src/metabase/permissions_rest/db.clj@@ -23,17 +23,21 @@`tenancy` (\"external\"/\"internal\"/nil) narrows to tenant/non-tenant groups (nil returns both); when`tenancy` is \"external\" and `tenants-enabled?` is false, no groups are returned. `manager-user-id`, when given,restricts to the groups that User manages. `advanced-permissions-enabled?` false excludes the data-analyst magic- group. `tenants-enabled?` false also excludes tenant groups outright, independent of `tenancy`."+ group. `tenants-enabled?` false also excludes tenant groups outright, independent of `tenancy`.+ `exclude-data-app-groups?` excludes groups that a data app manages."[limit :- [:maybe ms/PositiveInt]offset :- [:maybe ms/IntGreaterThanOrEqualToZero]- {:keys [tenancy manager-user-id tenants-enabled? advanced-permissions-enabled?]}+ {:keys [tenancy manager-user-id tenants-enabled? advanced-permissions-enabled?+ exclude-data-app-groups?]}:- [:map {:closed true}[:tenancy {:optional true} [:maybe [:enum "external" "internal"]]][:manager-user-id {:optional true} [:maybe ::lib.schema.id/user]][:tenants-enabled? {:optional true} :boolean]- [:advanced-permissions-enabled? {:optional true} :boolean]]]+ [:advanced-permissions-enabled? {:optional true} :boolean]+ [:exclude-data-app-groups? {:optional true} :boolean]]](let [base-where [:and(managed-groups-clause :id manager-user-id)+ (when exclude-data-app-groups? [:not :is_data_app_group])(when-not tenants-enabled? [:not :is_tenant_group])(when-not advanced-permissions-enabled?[:or [:= nil :magic_group_type] [:not= "data-analyst" :magic_group_type]])]@@ -58,6 +62,11 @@[id :- ms/PositiveInt](t2/exists? :model/PermissionsGroup :id id))+(defn data-app-group?+ "Whether the PermissionsGroup with `id` is managed by a data app."+ [id]+ (t2/exists? :model/PermissionsGroup :id id :is_data_app_group true))+(mu/defn insert-permissions-group!"Insert a PermissionsGroup and return the inserted instance."[group-name :- :string@@ -99,6 +108,11 @@[user-id :- ::lib.schema.id/user](t2/exists? :model/User :id user-id :is_superuser false))+(defn active-user-exists?+ "Whether an active User with `user-id` exists."+ [user-id]+ (t2/exists? :model/User :id user-id :is_active true))+(mu/defn group-membership"The PermissionsGroupMembership with `id`, or nil."[id :- ms/PositiveInt]diff --git a/src/metabase/sso/common.clj b/src/metabase/sso/common.cljindex d113a0e8dc1..5fc25e878e4 100644--- a/src/metabase/sso/common.clj+++ b/src/metabase/sso/common.clj@@ -10,8 +10,9 @@(defn- excluded-group-ids[]- #{(u/the-id (perms/all-users-group))- (u/the-id (perms/all-external-users-group))})+ (into #{(u/the-id (perms/all-users-group))+ (u/the-id (perms/all-external-users-group))}+ (perms/data-app-group-ids)))(defn- sync-group-memberships*![user-or-id to-remove to-add]@@ -45,18 +46,20 @@(defn sync-group-memberships!"Update the PermissionsGroups a User belongs to, adding or deleting membership entries as needed so that Users is- only in `new-groups-or-ids`. Ignores special groups like `all-users`, and only optionally only touches groups with mappings set."+ only in `new-groups-or-ids`. Ignores special groups like `all-users`, and only optionally only touches groups with mappings set."([user-or-id new-groups-or-ids]- (let [current-group-ids (sso.db/user-group-ids-excluding (u/the-id user-or-id) (excluded-group-ids))+ (let [excluded (excluded-group-ids)+ current-group-ids (sso.db/user-group-ids-excluding (u/the-id user-or-id) excluded)[to-remove to-add] (data/diff current-group-ids (set/difference (set (map u/the-id new-groups-or-ids))- (excluded-group-ids)))]+ excluded))](sync-group-memberships*! user-or-id to-remove to-add)))([user-or-id new-groups-or-ids mapped-groups-or-ids]- (let [mapped-group-ids (set (map u/the-id mapped-groups-or-ids))+ (let [excluded (excluded-group-ids)+ mapped-group-ids (set (map u/the-id mapped-groups-or-ids))current-group-ids (when (seq mapped-group-ids)- (sso.db/user-group-ids-among (u/the-id user-or-id) mapped-group-ids (excluded-group-ids)))+ (sso.db/user-group-ids-among (u/the-id user-or-id) mapped-group-ids excluded))new-group-ids (-> (set (map u/the-id new-groups-or-ids))(set/intersection mapped-group-ids)- (set/difference (excluded-group-ids)))+ (set/difference excluded))[to-remove to-add] (data/diff current-group-ids new-group-ids)](sync-group-memberships*! user-or-id to-remove to-add))))diff --git a/src/metabase/typed_schemas/build.clj b/src/metabase/typed_schemas/build.cljindex f6cfda0497f..fc222a4b5ab 100644--- a/src/metabase/typed_schemas/build.clj+++ b/src/metabase/typed_schemas/build.clj@@ -42,10 +42,6 @@[:sequential {:description (str "Limits tables and metrics to library collections. ""Each reference accepts `{:id <collection-id>}` or `{:entity-id <collection-entity-id>}`.")}CollectionRef]]- [:question-collection-refs {:optional true}- [:sequential {:description (str "Includes saved questions from collections. "- "Each reference accepts `{:id <collection-id>}` or `{:entity-id <collection-entity-id>}`.")}- CollectionRef]][:include-data-library? {:optional true}[:boolean {:description "Whether to include the root data library."}]][:include-metric-library? {:optional true}@@ -61,7 +57,6 @@Each entry holds entity maps shaped by the `metabase.typed-schemas.schema.*`builders; `:key` on each entity seeds the generated object keys."[:map {:closed true}- [:questions [:sequential :map]][:models [:sequential :map]][:tables [:sequential :map]][:metrics [:sequential :map]]])@@ -71,13 +66,12 @@(throw (ex-info message {:status-code 400})))(defn- validate-options!- [{:keys [database library-collection-refs question-collection-refs+ [{:keys [database library-collection-refsinclude-data-library? include-metric-library?] :as options}](when-not (mr/validate SemanticSchemaOptions options)(invalid-options! "Invalid semantic schema options."))(let [include-library-root? (or include-data-library? include-metric-library?)collection-scoped? (or (seq library-collection-refs)- (seq question-collection-refs)include-library-root?)](when (and collection-scoped? database)(invalid-options!@@ -114,16 +108,14 @@([options](fetch-items options source/app-db-source))([options source]- (let [{:keys [database library-collection-refs question-collection-refs+ (let [{:keys [database library-collection-refsinclude-data-library? include-metric-library? include-models?]:or {library-collection-refs []- question-collection-refs []include-data-library? falseinclude-metric-library? falseinclude-models? false}} options](validate-options! (assoc options:library-collection-refs library-collection-refs- :question-collection-refs question-collection-refs:include-data-library? include-data-library?:include-metric-library? include-metric-library?:include-models? include-models?))@@ -132,21 +124,15 @@:include-data-library? include-data-library?:include-metric-library? include-metric-library?})database-ids (source/database-ids source database)- question-collection-ids (source/collection-ids source question-collection-refs)models (models-for-scope source database-ids include-models?)](if (or library-scope- (seq question-collection-refs)(and include-models? (nil? database-ids)))(let [{:keys [tables metrics]} (when library-scope(library-items source library-scope))]- {:questions (if (seq question-collection-refs)- (source/questions source nil question-collection-ids)- [])- :models (vec models)+ {:models (vec models):tables (vec tables):metrics (vec metrics)})- {:questions (source/questions source database-ids nil)- :models (vec models)+ {:models (vec models):tables (source/tables source database-ids nil):metrics (source/metrics source database-ids nil)})))))@@ -158,12 +144,11 @@to the current time and the configured site URL."([items](create-schema items nil))- ([{:keys [questions models tables metrics]} {:keys [generated-at instance-url]}]+ ([{:keys [models tables metrics]} {:keys [generated-at instance-url]}](array-map:schemaVersion 2:generatedAt (str (or generated-at (Instant/now))):metabase {:instanceUrl (or instance-url (system/site-url))}- :questions (common/keyed-map questions):models (common/keyed-model-map models):tables (common/keyed-map tables):metrics (common/keyed-map metrics))))diff --git a/src/metabase/typed_schemas/schema/metric.clj b/src/metabase/typed_schemas/schema/metric.cljindex 14579a2da38..49cccb72b48 100644--- a/src/metabase/typed_schemas/schema/metric.clj+++ b/src/metabase/typed_schemas/schema/metric.clj@@ -2,6 +2,7 @@"Typed schema generation for metrics and metric dimensions."(:require[medley.core :as m]+ [metabase.lib.core :as lib][metabase.metabot.core :as metabot][metabase.metrics.core :as metrics][metabase.models.interface :as mi]@@ -271,10 +272,27 @@:mappedTableIds (not-empty mapped-table-ids):dimensions (not-empty (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.++ `all-source-card-ids` throws on anything that is not an MBQL 5 query, and a `dataset_query` the app+ DB fails to deserialize arrives as `{}`; report no references for those and leave them to+ `metric-details`, which is what decides whether a metric it cannot read is emitted."+ [metric]+ (let [query (:dataset_query metric)]+ (and (= (:lib/type query) :mbql/query)+ (boolean (seq (lib/all-source-card-ids query))))))+(defn metric-schemas"Returns metric schemas, with optional database and collection scopes."[database-ids collection-ids]- (for [card (schema.common/select-schema-cards :metric database-ids collection-ids)- :let [details (metric-details card)]+ (for [metric (remove source-card-id+ (schema.common/select-schema-cards :metric database-ids collection-ids))+ ;; Sync only supports metrics that resolve entirely from tables, and the CLI aborts+ ;; `sync-resources` on one that does not. `source-card-id` sees only stage 0, so a+ ;; table-sourced metric joining a saved question reached the CLI and failed there;+ ;; check the whole query for saved-card dependencies to match what sync accepts.+ :when (not (references-saved-card? metric))+ :let [details (metric-details metric)]:when details]- (metric-schema details card)))+ (metric-schema details metric)))diff --git a/src/metabase/typed_schemas_rest/api.clj b/src/metabase/typed_schemas_rest/api.cljindex 5757293a4fe..39452bbe877 100644--- a/src/metabase/typed_schemas_rest/api.clj+++ b/src/metabase/typed_schemas_rest/api.clj@@ -28,10 +28,6 @@[:maybe {:description (str "Comma-separated library collection ids or entity ids. ""Limits tables and metrics to those library collections.")}ms/NonBlankString]]- [:question-collections {:optional true}- [:maybe {:description (str "Comma-separated collection ids or entity ids. "- "Includes saved questions from those collections.")}- ms/NonBlankString]][:include-data-library {:optional true}[:maybe {:description "Whether to include the entire data library."}:boolean]]@@ -46,7 +42,12 @@(api.macros/defendpoint :get "/v1/typescript" :- :any"Generate a TypeScript semantic schema module."[_route-params- query-params :- TypedSchemaQueryParams]+ query-params :- TypedSchemaQueryParams+ _body-params+ {{question-collections "question-collections"} :query-params}]+ (when (some? question-collections)+ (throw (ex-info "The question-collections query parameter is not supported."+ {:status-code 400}))){:status 200:headers typescript-response-headers:body (-> query-paramsdiff --git a/src/metabase/typed_schemas_rest/api/query_params.clj b/src/metabase/typed_schemas_rest/api/query_params.cljindex 6e871a04328..cfdd77b12c0 100644--- a/src/metabase/typed_schemas_rest/api/query_params.clj+++ b/src/metabase/typed_schemas_rest/api/query_params.clj@@ -40,7 +40,6 @@[query-params]{:database (database-reference (:database query-params)):library-collection-refs (comma-separated-references (:library-collections query-params))- :question-collection-refs (comma-separated-references (:question-collections query-params)):include-data-library? (enabled? (:include-data-library query-params)):include-metric-library? (enabled? (:include-metric-library query-params)):include-models? (enabled? (:include-models query-params))})diff --git a/test/metabase/typed_schemas/core_test.clj b/test/metabase/typed_schemas/core_test.cljindex b7484312a78..a4b6eba48fc 100644--- a/test/metabase/typed_schemas/core_test.clj+++ b/test/metabase/typed_schemas/core_test.clj@@ -42,21 +42,18 @@(is (= {:schemaVersion 2:generatedAt "2026-01-01T00:00:00Z":metabase {:instanceUrl "https://metabase.example.com"}- :questions {"ordersByMonth" {:type "card", :key "ordersByMonth", :id 1}}:models {"orders" {:actions {"create" {:kind "action", :id 9}}}}:tables {"orders" {:type "table", :key "orders", :id 3}}:metrics {"revenue" {:type "metric", :key "revenue", :id 2}}}(build/create-schema- {:questions [{:type "card", :key "ordersByMonth", :id 1}]- :models [{:key "orders", :name "Orders", :actions {"create" {:kind "action", :id 9}}}]+ {:models [{:key "orders", :name "Orders", :actions {"create" {:kind "action", :id 9}}}]:tables [{:type "table", :key "orders", :id 3}]:metrics [{:type "metric", :key "revenue", :id 2}]}test-info))))(deftest create-schema-disambiguates-duplicate-keys-test(let [schema (build/create-schema- {:questions []- :models []+ {:models []:tables [{:type "table", :key "orders", :id 3}{:type "table", :key "orders", :id 4}]:metrics []}@@ -65,7 +62,7 @@(is (= ["orders3" "orders4"] (map :key (vals (:tables schema)))))))(deftest create-schema-defaults-info-test- (let [schema (build/create-schema {:questions [], :models [], :tables [], :metrics []})]+ (let [schema (build/create-schema {:models [], :tables [], :metrics []})](is (string? (:generatedAt schema)))(is (contains? (:metabase schema) :instanceUrl))))@@ -96,13 +93,17 @@:tables [{:id 10, :type "table", :key "publishedTable"}{:id 42, :type "table", :key "mappedTable"}{:id 99, :type "table", :key "notInScope"}]})]- (is (= {:questions []- :models []+ (is (= {:models []:tables [{:id 10, :type "table", :key "publishedTable"}{:id 42, :type "table", :key "mappedTable"}]:metrics [{:type "metric", :key "revenue", :id 1, :mappedTableIds [42]}]}(build/fetch-items {:include-data-library? true} source)))))+(deftest options-reject-question-collection-refs-test+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid semantic schema options\."+ (build/fetch-items {:question-collection-refs [{:id 1}]}))))+;; One end-to-end test over the real test-data dataset: cards for every entity;; kind on real synced tables, run through the whole pipeline to TypeScript.;; Everything above tests the stages with cheap literal data; this proves the@@ -139,16 +140,17 @@(testing "every entity kind lands in the schema with its real relationships"(is (=? {:generatedAt "2026-01-01T00:00:00Z":metabase {:instanceUrl "https://metabase.example.com"}- :questions {"orderTotals" {:type "card", :id int?}}:tables {"orders" {:fields {"total" {:jsType "number"}}}}:metrics {"orderRevenue" {:mappedTableIds [(mt/id :orders)]:columns [{:displayName "Sum of Total":jsType "number"}]}}:models {"orderModel" {:actions {"updateOrder" {:kind "action"}}}}}schema)))- (testing "only the temp cards are in scope for the dataset database"- (is (= {:questions ["orderTotals"], :metrics ["orderRevenue"], :models ["orderModel"]}- (update-vals (select-keys schema [:questions :metrics :models])+ (testing "saved questions are absent from the schema"+ (is (not (contains? schema :questions))))+ (testing "only the temp metric and model are in scope for the dataset database"+ (is (= {:metrics ["orderRevenue"], :models ["orderModel"]}+ (update-vals (select-keys schema [:metrics :models])(comp vec keys)))))(testing "the rendered module carries the real entities"(is (str/includes? body "orders: {"))diff --git a/test/metabase/typed_schemas/schema/metric_test.clj b/test/metabase/typed_schemas/schema/metric_test.cljindex bba572b96a3..36fc2cf3f0d 100644--- a/test/metabase/typed_schemas/schema/metric_test.clj+++ b/test/metabase/typed_schemas/schema/metric_test.clj@@ -3,11 +3,13 @@[clojure.test :refer :all][metabase.metabot.core :as metabot][metabase.models.interface :as mi]+ [metabase.permissions.core :as perms][metabase.test :as mt][metabase.test.fixtures :as fixtures]+ [metabase.typed-schemas.db :as typed-schemas.db]+ [metabase.typed-schemas.schema.common :as schema.common][metabase.typed-schemas.schema.metric :as schema.metric]- [metabase.typed-schemas.schema.table :as schema.table]- [toucan2.core :as t2]))+ [metabase.typed-schemas.schema.table :as schema.table]))(use-fixtures :once (fixtures/initialize :db))@@ -79,9 +81,77 @@:error-message "Not found."}(ex-data exception))))))+(deftest metric-schemas-excludes-card-sourced-metrics-test+ (with-redefs [schema.common/select-schema-cards+ (constantly [{:id 247+ :dataset_query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 10}]}}+ {:id 258+ :dataset_query {:query {:source-table "card__42"}}}+ {:id 259+ :dataset_query {:stages [{:source-card 42}]}}])+ schema.metric/metric-details identity+ schema.metric/metric-schema (fn [details _card] (:id details))]+ (is (= [247]+ (vec (schema.metric/metric-schemas nil nil))))))++(deftest metric-schemas-excludes-metrics-that-reference-other-metrics-test+ (with-redefs [schema.common/select-schema-cards+ (constantly [{:id 247+ :dataset_query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 10}]}}+ {:id 258+ :dataset_query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 10+ :aggregation [[:metric+ {:lib/uuid+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}+ 247]]}]}}])+ schema.metric/metric-details identity+ schema.metric/metric-schema (fn [details _card] (:id details))]+ (is (= [247]+ (vec (schema.metric/metric-schemas nil nil))))))++(deftest metric-schemas-excludes-metrics-that-join-a-saved-question-test+ ;; Metric 258 is table-sourced and joins a saved question, so `source-card-id` — which only reads+ ;; stage 0's source — passes it. The CLI checks the whole query and rejects it, aborting+ ;; `sync-resources` for any app that uses it, so codegen has to drop it here as well.+ (with-redefs [schema.common/select-schema-cards+ (constantly [{:id 247+ :dataset_query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 10}]}}+ {:id 258+ :dataset_query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 10+ :joins [{:lib/type :mbql/join+ :alias "Question"+ :stages [{:lib/type :mbql.stage/mbql+ :source-card 42}]+ :conditions+ [[:=+ {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}+ [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"} 11]+ [:field {:lib/uuid "cccccccc-cccc-cccc-cccc-cccccccccccc"} 12]]]}]}]}}])+ schema.metric/metric-details identity+ schema.metric/metric-schema (fn [details _card] (:id details))]+ (is (= [247]+ (vec (schema.metric/metric-schemas nil nil))))))+(deftest table-source-names-filters-unreadable-tables-test- (with-redefs [t2/select (constantly [{:id 10 :name "orders" :display_name "Orders"}- {:id 20 :name "franchises" :display_name "Franchises"}])+ (with-redefs [perms/prime-table-perms-cache (constantly nil)+ typed-schemas.db/table-names+ (constantly [{:id 10 :name "orders" :display_name "Orders"}+ {:id 20 :name "franchises" :display_name "Franchises"}])mi/can-read? (fn [{:keys [id]}] (= id 10))](is (= {10 "orders"}(#'schema.metric/table-source-names [10 20])))@@ -132,10 +202,11 @@:name "orders":table-id 10}])mi/can-read? (constantly true)- t2/select (fn [columns & _args]- (when (= columns [:model/Table :id :name :display_name])- (swap! table-select-count inc)- [{:id 10 :name "orders" :display_name "Orders"}]))]+ perms/prime-table-perms-cache (constantly nil)+ typed-schemas.db/table-names+ (fn [_table-ids]+ (swap! table-select-count inc)+ [{:id 10 :name "orders" :display_name "Orders"}])](#'schema.metric/metric-schema{:id 247:name "Customer Lifetime Value"}@@ -153,11 +224,11 @@schema.table/table-by-field-id (fn [field-id](swap! field-lookup-attempts conj field-id)({42 10, 84 20} field-id))- t2/select (fn [columns & _args]- (when (= columns [:model/Field :id :table_id])- (swap! field-select-count inc)- [{:id 42 :table_id 10}- {:id 84 :table_id 20}]))]+ typed-schemas.db/field-ids-and-table-ids+ (fn [_field-ids]+ (swap! field-select-count inc)+ [{:id 42 :table_id 10}+ {:id 84 :table_id 20}])](is (= (mapv vector dimensions [10 20])(#'schema.metric/metric-dimensions-with-table-ids {:id 247} nil)))(is (= 1 @field-select-count))diff --git a/test/metabase/typed_schemas/schema/table_test.clj b/test/metabase/typed_schemas/schema/table_test.cljindex b83876f300d..ce20fa4efd1 100644--- a/test/metabase/typed_schemas/schema/table_test.clj+++ b/test/metabase/typed_schemas/schema/table_test.clj@@ -158,3 +158,20 @@(schema.table/table-schema (assoc orders-table :measures measures))(is (= 1 @measure-select-count))(is (= 1 @metadata-provider-count)))))++(deftest table-schemas-with-stored-fingerprint-statistics-test+ (mt/with-temp [:model/Table table {:db_id (mt/id) :name "customers"}+ :model/Field _ {:table_id (:id table)+ :name "customer_id"+ :base_type :type/Text+ :fingerprint {:type {:type/Text {:min-length 8.0 :max-length 9.0}}}}+ :model/Field _ {:table_id (:id table)+ :name "last_ordered_at"+ :base_type :type/DateTime+ :fingerprint {:type {:type/DateTime+ {:skewness -1.2937+ :weekday-distribution [0.1 0.1 0.1 0.1 0.2 0.2 0.2]+ :hour-distribution (vec (repeat 24 (/ 1.0 24)))}}}}]+ (mt/with-test-user :crowberto+ (let [schema (first (schema.table/table-schemas [table]))]+ (is (= #{"customerId" "lastOrderedAt"} (set (keys (:fields schema)))))))))diff --git a/test/metabase/typed_schemas_rest/api/query_params_test.clj b/test/metabase/typed_schemas_rest/api/query_params_test.cljindex a8157e2275a..95ad9af63ac 100644--- a/test/metabase/typed_schemas_rest/api/query_params_test.clj+++ b/test/metabase/typed_schemas_rest/api/query_params_test.clj@@ -6,20 +6,17 @@(deftest ^:parallel query-params->options-test(is (= {:database {:name "Boba"}:library-collection-refs [{:id 10} {:id 20}]- :question-collection-refs [{:entity-id "question-entity-id-1"}]:include-data-library? false:include-metric-library? false:include-models? true}(query-params/query-params->options{:database " Boba ":library-collections " 10, 20 "- :question-collections " question-entity-id-1 ":include-models true}))))(deftest ^:parallel query-params->options-coerces-values-and-applies-defaults-test(is (= {:database {:id 1}:library-collection-refs [{:id 3}]- :question-collection-refs []:include-data-library? true:include-metric-library? true:include-models? false}diff --git a/test/metabase/typed_schemas_rest/api_test.clj b/test/metabase/typed_schemas_rest/api_test.cljindex 1f47d4a4045..51b9fc03688 100644--- a/test/metabase/typed_schemas_rest/api_test.clj+++ b/test/metabase/typed_schemas_rest/api_test.clj@@ -18,10 +18,9 @@(is (= "text/typescript; charset=utf-8" (get-in response [:headers "Content-Type"])));; `includes?` rather than `starts-with?`: instances with compactable;; metrics render the pickFields helper before the first const.- (is (str/includes? (:body response) "const questions = "))(is (str/includes? (:body response) "\nconst schema = {"))(is (str/includes? (:body response) "\n schemaVersion: 2"))- (is (str/includes? (:body response) "\n questions: questions"))+ (is (not (str/includes? (:body response) "\n questions:")))(is (str/includes? (:body response) "\n tables: tables"))(is (str/includes? (:body response) "\n metrics: metrics"))(is (str/ends-with? (:body response) "export default schema;\n"))@@ -60,7 +59,7 @@(is (str/includes? schema-by-id "name: \"Venues\"")))(testing "a non-matching database name returns an empty semantic schema"(is (str/includes? missing-schema "schemaVersion: 2"))- (is (str/includes? missing-schema "const questions = { }"))+ (is (not (str/includes? missing-schema "const questions = { }")))(is (str/includes? missing-schema "const tables = { }"))(is (str/includes? missing-schema "const metrics = { }")))))@@ -70,3 +69,10 @@:get400"typed-schemas/v1/typescript?library-collections=1,2&database=1"))++(deftest question-collections-query-param-is-rejected-test+ (mt/user-http-request-full-response+ :crowberto+ :get+ 400+ "typed-schemas/v1/typescript?question-collections=1"))