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
Manage data app access through permission groups (#83082)
Phoomparin Mano9cb3f1602fbc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 841062f7516..83f2fbb32ba 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -862,6 +862,11 @@:model/Query:model/User}}+ data-apps+ {:team "Embedding"+ :api #{metabase.data-apps.core}+ :uses #{premium-features}}+data-studio{:team "Gadget":api #{metabase.data-studio.api}@@ -2569,6 +2574,7 @@app-dbappearancecore.initialization-status+ data-appsdriverembeddinglib.be@@ -3785,11 +3791,9 @@:model-imports #{:model/Action:model/Card:model/Collection- :model/DataPermissions:model/Database:model/Field:model/Permissions- :model/PermissionsGroup:model/QueryAction:model/Table}:model-exports #{:model/DataApp}}diff --git a/e2e/support/assets/data-apps/group-access-test/data_app.yaml b/e2e/support/assets/data-apps/group-access-test/data_app.yamlnew file mode 100644index 00000000000..fb3cde24bc6--- /dev/null+++ b/e2e/support/assets/data-apps/group-access-test/data_app.yaml@@ -0,0 +1,10 @@+name: Group Access Test+slug: group-access-test+version: 1+path: ./dist/index.js+collection: groupAccessAppColl001+entity_id: tQ8R4p2Y7mN6aX9cV3kL5+serdes/meta:+- model: DataApp+ id: tQ8R4p2Y7mN6aX9cV3kL5+ label: group-access-testdiff --git a/e2e/support/assets/data-apps/group-access-test/src/index.tsx b/e2e/support/assets/data-apps/group-access-test/src/index.tsxnew file mode 100644index 00000000000..0980e129501--- /dev/null+++ b/e2e/support/assets/data-apps/group-access-test/src/index.tsx@@ -0,0 +1,9 @@+import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";++function App() {+ return <h1>Group access app</h1>;+}++const factory: DataAppFactory = () => ({ component: App });++export default factory;diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.tsindex efb10d564b2..4bcc6705ab5 100644--- a/e2e/support/helpers/e2e-data-app-helpers.ts+++ b/e2e/support/helpers/e2e-data-app-helpers.ts@@ -11,6 +11,7 @@ import type {CollectionPermissionsGraph,DataApp,Group,+ GroupInfo,RemoteSyncTask,WritebackAction,} from "metabase-types/api";@@ -47,7 +48,6 @@ export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({bundle_path: "dist/index.js",enabled: true,resource_collection_id: 1,- permission_group_id: null,table_ids: [],allowed_hosts: [],bundle_hash: "e2e-bundle-hash",@@ -78,6 +78,33 @@ export const mockDataApp = <TestEnv = DataAppTestEnv>(const displayName = options.displayName ?? appName;const allowedHosts = options.allowedHosts ?? [];+ // the entrypoint checks for app access before serving its HTML+ // we need to have a real app in the database - mocking the endpoint isn't enough+ cy.request({+ url: `/api/apps/${slug}`,+ failOnStatusCode: false,+ }).then(({ status }) => {+ if (status === 200) {+ return;+ }++ expect(status).to.equal(404);++ cy.log("register the data app");+ cy.request("POST", "/api/apps", {+ name: slug,+ display_name: displayName,+ bundle_path: "dist/index.js",+ allowed_hosts: allowedHosts,+ bundle: "",+ });++ cy.log("assign the data app to all users group");+ cy.request("POST", `/api/apps/${slug}/groups`, {+ group_ids: [USER_GROUPS.ALL_USERS_GROUP],+ });+ });+// Prelude runs in the sandbox realm before the bundle's factory, so the app// can read the injected config as a global (see MockDataAppOptions.testEnv).const prelude =@@ -587,10 +614,9 @@ export function pullExampleDataApps({configureGitAndPullChanges("read-write");}-/** A data app whose resources loaded: it has its collection and its permission group. */+/** A data app whose resources loaded into its collection. */export type SyncedDataApp = DataApp & {resource_collection_id: number;- permission_group_id: number;};/** The host app's checked-in `data_app.yaml`, as serialization reads it. */@@ -608,8 +634,7 @@ serdes/meta:`;const isSyncedDataApp = (app: DataApp): app is SyncedDataApp =>- typeof app.resource_collection_id === "number" &&- typeof app.permission_group_id === "number";+ typeof app.resource_collection_id === "number";/*** Writes the app's manifest into the sync repository as `data_apps/<slug>`, makes@@ -730,6 +755,21 @@ export function buildDataAppHostApp() {});}+/** Create a group and assign it to a data app by slug. */+export function assignTestGroupToDataApp(slug: string) {+ cy.request<GroupInfo>("POST", "/api/permissions/group", {+ name: `Data app test group: ${slug}`,+ })+ .its("body")+ .as("dataAppTestGroup");++ cy.get<GroupInfo>("@dataAppTestGroup").then(({ id }) =>+ cy.request("POST", `/api/apps/${slug}/groups`, { group_ids: [id] }),+ );++ return cy.get<GroupInfo>("@dataAppTestGroup").its("id");+}+const DATA_APP_DEV_HOST_APP_DIR ="e2e/embedding-sdk-host-apps/vite-6-data-app-host-app";diff --git a/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts b/e2e/test-host-app/data-apps/resources-actions.cy.spec.tsindex a5823cb9261..cb23c3047bd 100644--- a/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts+++ b/e2e/test-host-app/data-apps/resources-actions.cy.spec.ts@@ -118,7 +118,9 @@ describe(// the app's group alone, and the source action, in the root collection,// through none of them.H.publishDataApp(APP_ROOT(), APP_SLUG).then((app) => {- H.addUserToGroup(app.permission_group_id, USERS.nocollection.email);+ H.assignTestGroupToDataApp(app.name).then((groupId) => {+ H.addUserToGroup(groupId, USERS.nocollection.email);+ });});cy.signIn("nocollection");diff --git a/e2e/test-host-app/data-apps/resources.cy.spec.ts b/e2e/test-host-app/data-apps/resources.cy.spec.tsindex 7ce06e6905d..dffb44fb74a 100644--- a/e2e/test-host-app/data-apps/resources.cy.spec.ts+++ b/e2e/test-host-app/data-apps/resources.cy.spec.ts@@ -155,7 +155,9 @@ describe("Embedding SDK: data-app resources (queries)", () => {expect(card.collection_id).to.eq(app.resource_collection_id);expect(card.name).to.eq("Orders");- H.addUserToGroup(app.permission_group_id, USERS.normal.email);+ H.assignTestGroupToDataApp(app.name).then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ });cy.signInAsNormalUser();cy.request(`/api/card/${question}`)@@ -211,7 +213,9 @@ describe("Embedding SDK: data-app resources (queries)", () => {const [copy] = metrics;expect(copy.id, "a copy, not the source metric").not.to.eq(metric.id);- H.addUserToGroup(app.permission_group_id, USERS.normal.email);+ H.assignTestGroupToDataApp(app.name).then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ });cy.signInAsNormalUser();cy.request(`/api/card/${copy.id}`).its("status").should("eq", 200);diff --git a/e2e/test/scenarios/data-apps/admin.cy.spec.ts b/e2e/test/scenarios/data-apps/admin.cy.spec.tsindex ea9936ec56c..84697a63443 100644--- a/e2e/test/scenarios/data-apps/admin.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/admin.cy.spec.ts@@ -52,26 +52,6 @@ describe("scenarios > data apps > admin management", () => {});});- it("keeps a data app's permission group out of the admin Groups list", () => {- // Pulling an app creates its permission group as a side effect.- H.pullExampleDataApps();- cy.request<DataApp>("GET", "/api/apps/good").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: good").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/group-access.cy.spec.ts b/e2e/test/scenarios/data-apps/group-access.cy.spec.tsnew file mode 100644index 00000000000..e8b5aad6eb4--- /dev/null+++ b/e2e/test/scenarios/data-apps/group-access.cy.spec.ts@@ -0,0 +1,154 @@+import { COLLECTION_GROUP_ID } from "e2e/support/cypress_sample_instance_data";++const { H } = cy;++const APP_NAME = "group-access-test";+const APP_DISPLAY_NAME = "Group Access Test";+const APP_LINK_REGEX = new RegExp(`${APP_DISPLAY_NAME}$`);++describe("scenarios > data apps > group access (EMB-2415)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ H.setupGitSync();+ H.copySyncedCollectionFixture();++ H.writeDataAppResources(H.LOCAL_GIT_PATH, {+ collection: H.dataAppRepresentations.collection(+ "groupAccessAppColl001",+ `Data App: ${APP_DISPLAY_NAME}`,+ ),+ });++ // commit a built bundle and manifest so remote sync publishes a+ // real app, to use real permission checks.+ cy.task<string>("buildDataApp", { appName: APP_NAME }).then((bundle) =>+ cy.writeFile(+ `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/dist/index.js`,+ bundle,+ ),+ );++ cy.readFile(`e2e/support/assets/data-apps/${APP_NAME}/data_app.yaml`).then(+ (manifest) =>+ cy.writeFile(+ `${H.LOCAL_GIT_PATH}/data_apps/${APP_NAME}/data_app.yaml`,+ manifest,+ ),+ );++ H.commitToRepo("Add data apps for testing group accesses");+ H.configureGitAndPullChanges("read-write");++ cy.request("GET", `/api/apps/${APP_NAME}`).its("body").should("include", {+ name: APP_NAME,+ display_name: APP_DISPLAY_NAME,+ enabled: true,+ });++ cy.request("GET", `/api/permissions/group/${COLLECTION_GROUP_ID}`)+ .its("body.name")+ .as("groupName");+ });++ it("changes accesses to data apps when assigning and removing groups", () => {+ cy.log("app is hidden and access is denied by default");+ cy.signIn("nodata");+ assertAppIsHidden();+ assertAppAccessDenied();++ cy.signInAsAdmin();+ cy.visit("/admin/settings/apps");++ cy.findByTestId(`data-app-list-item-${APP_NAME}`)+ .findByRole("button", { name: `Actions for ${APP_DISPLAY_NAME}` })+ .click();++ H.popover().findByRole("menuitem", { name: "Manage group access" }).click();+ H.main().findByText("No groups have access yet").should("be.visible");++ cy.findByRole("button", { name: "Add groups" }).click();+ cy.findByRole("textbox", { name: "Search for groups to add" }).click();++ cy.log("add a group to the data app");+ cy.get<string>("@groupName").then((name) =>+ cy.findByRole("option", { name }).click(),+ );++ cy.findByTestId("data-app-groups-card")+ .findByRole("button", { name: "Add" })+ .click();++ cy.get<string>("@groupName").then((name) =>+ H.main()+ .findByRole("button", { name: `Remove ${name}`, timeout: 10000 })+ .should("be.visible"),+ );++ cy.log("the group should let members access the app");+ cy.signIn("nodata");+ visitHome();++ H.navigationSidebar()+ .findByRole("link", { name: APP_LINK_REGEX })+ .should("be.visible")+ .invoke("removeAttr", "target")+ .click();++ assertAppIsRendered();++ cy.log("remove the group");+ cy.signInAsAdmin();+ cy.visit(`/admin/settings/apps/${APP_NAME}/groups`);+ cy.get<string>("@groupName").then((name) =>+ cy.findByRole("button", { name: `Remove ${name}` }).click(),+ );++ H.main()+ .findByText("No groups have access yet", { timeout: 10000 })+ .should("be.visible");++ cy.log("admins still can access the apps");+ H.openDataApp(APP_NAME);+ assertAppIsRendered();++ cy.log("the app access is revoked after the group is removed");+ cy.signIn("nodata");+ assertAppIsHidden();+ assertAppAccessDenied();+ });+});++function visitHome() {+ cy.intercept("GET", "/api/apps?available=true").as("availableApps");+ cy.visit("/");+ cy.wait("@availableApps");++ H.navigationSidebar()+ .findByRole("listitem", { name: "Home" })+ .should("be.visible");+}++function assertAppIsHidden() {+ visitHome();++ H.navigationSidebar()+ .findByRole("link", { name: APP_LINK_REGEX })+ .should("not.exist");+}++function assertAppAccessDenied() {+ H.openDataApp(APP_NAME);++ H.main()+ .findByText("You don’t have access to this data app")+ .should("be.visible");+}++function assertAppIsRendered() {+ H.dataAppIframe(APP_DISPLAY_NAME)+ .findByRole("heading", { name: "Group access app" })+ .should("be.visible");+}diff --git a/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts b/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.tsdeleted file mode 100644index 450d3ec1d76..00000000000--- a/e2e/test/scenarios/data-apps/legacy-permissions.cy.spec.ts+++ /dev/null@@ -1,154 +0,0 @@-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 = "good";--// 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();- H.pullExampleDataApps();- cy.request<DataApp>(`/api/apps/${APP_NAME}`).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/resources-production-actions.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.tsindex 5ca9cff28ef..e8de43d1a50 100644--- a/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/resources-production-actions.cy.spec.ts@@ -105,7 +105,9 @@ describe(it("executes the app's copy rather than the authored action, for a member of the app's group", () => {publishApp().then(({ app, actionCopy }) => {- H.addUserToGroup(app.permission_group_id, USERS.normal.email);+ H.assignTestGroupToDataApp(app.name).then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ });cy.signInAsNormalUser();cy.intercept("POST", "/api/action/*/execute").as("execute");diff --git a/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts b/e2e/test/scenarios/data-apps/resources-production.cy.spec.tsindex 32b0d0cc56f..3b1faf127c9 100644--- a/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/resources-production.cy.spec.ts@@ -166,7 +166,9 @@ describe("scenarios > data apps > resources in production", () => {it("serves the app to a member of its permission group", () => {publishApp().then(({ app }) => {- H.addUserToGroup(app.permission_group_id, USERS.normal.email);+ H.assignTestGroupToDataApp(app.name).then((groupId) => {+ H.addUserToGroup(groupId, USERS.normal.email);+ });cy.signInAsNormalUser();H.mockDataApp(APP_SLUG, { displayName: APP_DISPLAY_NAME });diff --git a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts b/e2e/test/scenarios/data-apps/sandbox.cy.spec.tsindex 581065ba323..ba92be95e1f 100644--- a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts@@ -182,10 +182,14 @@ describe("scenarios > data apps > sandbox & isolation", () => {describe("iframe security headers", () => {it("serves the embed document with the expected CSP + framing headers", () => {+ H.mockDataApp(APP_NAME, { displayName: APP_DISPLAY_NAME });+cy.request({url: `/embed/apps/${APP_NAME}`,failOnStatusCode: false,}).then((res) => {+ expect(res.status).to.equal(200);+const csp = String(res.headers["content-security-policy"] ?? "");expect(csp).to.contain("frame-ancestors 'self'");expect(csp).to.contain("default-src 'none'");diff --git a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts b/e2e/test/scenarios/data-apps/viewing.cy.spec.tsindex 46aec9b5eaf..ff3ea761cb4 100644--- a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/viewing.cy.spec.ts@@ -1,13 +1,26 @@+import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";import {DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,DATA_APP_NAME as APP_NAME,visitDataAppRoute as visitAppRoute,} from "e2e/support/helpers";+import {+ DataPermission,+ DataPermissionValue,+ type GroupPermissions,+} from "metabase-types/api";import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";const { H } = cy;+const BLOCKED_PERMISSION: GroupPermissions = {+ [SAMPLE_DB_ID]: {+ [DataPermission.VIEW_DATA]: DataPermissionValue.BLOCKED,+ [DataPermission.CREATE_QUERIES]: DataPermissionValue.NO,+ },+};+describe("scenarios > data apps > viewing & routing", () => {beforeEach(() => {H.restore();@@ -38,20 +51,26 @@ describe("scenarios > data apps > viewing & routing", () => {});it("opens the app shell for a user without data access, but shows no data", () => {+ cy.updatePermissionsGraph({+ [USER_GROUPS.ALL_USERS_GROUP]: BLOCKED_PERMISSION,+ [USER_GROUPS.COLLECTION_GROUP]: BLOCKED_PERMISSION,+ });+H.mockDataApp(APP_NAME, {displayName: APP_DISPLAY_NAME,testEnv: TEST_ENV,});- // The `nodata` user can open the app (viewing isn't gated), but the query- // the app runs goes through the QP with the user's own permissions — with- // no data access it resolves to no data (the fixture renders "—").cy.signIn("nodata");H.openDataApp(APP_NAME);H.dataAppIframe(APP_DISPLAY_NAME).within(() => {+ // Group access lets users view the app shell.cy.findByRole("heading", { name: "Orders overview" }).should("be.visible",);++ // The user's incomplete data permissions still blocks its query,+ // so the orders-count renders "—".cy.findByTestId("orders-count", { timeout: 30000 }).should("have.text","—",diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.cljindex 389f6003344..a9ccf826173 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj@@ -177,9 +177,8 @@(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 (perms/data-app-group-ids)))]+ (concat impersonation-group-ids sandbox-group-ids))](zipmap group-ids (map #(if (blocked-groups %) :blocked :unrestricted) group-ids)))))(defenterprise new-table-sandboxed-groups@@ -211,14 +210,9 @@;; DB-level, so a new table should get `:unrestricted` and inherit the DB-level impersonation policy.(let [blocked-group-ids (advanced-permissions.db/blocked-group-ids-for-database db-id group-ids)sandbox-group-ids (new-table-sandboxed-groups db-id 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 f84139bc96f..98c156117fc 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/README.md+++ b/enterprise/backend/src/metabase_enterprise/data_apps/README.md@@ -14,9 +14,9 @@ themselves, cached in the app DB so serving never reads a repository.The model's hooks hold its invariants: every write is normalized and validated against the columnschemas in `schema.clj`, `bundle_hash` always matches `bundle`, an inserted app gets the collection-and permission group it owns (see Permissions), and a deleted one loses them. Its default fields-leave the bundle out, so listing apps never drags bundles out of the DB; `db.clj`'s-`data-app-bundle` reads it explicitly.+it owns (see Permissions), and deleting an app deletes its collection and group assignments while+preserving the assigned permission groups. Its default fields leave the bundle out, so listing apps+never drags bundles out of the DB; `db.clj`'s `data-app-bundle` reads it explicitly.An app with a lower `version` than this Metabase serves is outdated — badged for admins, hiddenfrom everyone else, and a 409 to open.@@ -44,13 +44,13 @@ Collections of the `data-apps` namespace are written under `collections/data_appThe YAML keeps the keys a hand-written manifest uses: `slug` is the `name` column, `name` the`display_name`, `path` the `bundle_path`, and `collection` the entity ID of the app's resource-collection, which the app depends on and so loads after. The bundle travels as a serdes *resource-file*: the entity carries it in `:serdes/resources` on export, the storage writers put it next to+collection, which the app depends on and so loads after. The bundle travels as a serdes _resource+file_: the entity carries it in `:serdes/resources` on export, the storage writers put it next tothe YAML, and ingestion reads the paths `serdes/resource-paths` returns back in. A resource pathmust stay inside the entity's directory.-`enabled` is admin-owned and never leaves the instance; the permission group and `table_ids` are-server-managed; `bundle_hash` is recomputed from the bundle on import.+`enabled` is admin-owned and never leaves the instance; group assignments also stay local to the+instance. `table_ids` are server-managed, and `bundle_hash` is recomputed from the bundle on import.A targeted export of an app brings its collection and what it holds along (`serdes/descendants`).An import matches an app by `entity_id` and reasserts the app's resources; a manifest whose slug an app@@ -103,45 +103,52 @@ middleware's lookup doesn't pull in route code.## Permissions-Each app owns two server-managed resources, created with the app and reasserted on-every import: a **collection** holding the copies the app is served from (saved questions, actions,-table-sourced metrics) and a **permissions group** its users belong to. The collection is a root-collection of the `data-apps` namespace, created as the app's row is inserted unless an import names-one (`models/data_app.clj`), and can never be swapped for another; `resources.clj` keeps its name and-permissions in step and brings it out of the trash. Deleting the app deletes both, and the-collection's own hooks delete what it holds.+Each app owns a resource collection, created with the app in the `data-apps` namespace. The collection+is never swapped for another; `resources.clj` keeps its name and permissions in step and restores it from the trash.+Administrators assign existing internal permission groups through `/api/apps/:slug/groups`. Assignments live in+`data_app_group_assignment` and stay local to the instance. Repository sync preserves them while the app row exists.-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.+Admins reuse existing permission groups through `/api/apps/:slug/groups`. Assignments are stored in+`data_app_group_assignment`: an app can have multiple groups, and a group can be assigned to multiple apps.-**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.+Membership in any assigned group grants app access. Administrators can access every app. The list API hides+unassigned apps from other users, and metadata, bundle, and HTML entry-point requests check the same assignment.+Collection access alone does not grant app access.-**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.+Every app owns a collection from insertion. If its collection is deleted separately, resource reconciliation recreates it.-**Managing is superuser-only** — enabling, disabling, deleting, and repo status.+Assignments grant read-only access to the resource collection. Sync restores these grants and removes collection+access from unassigned groups. Assignment changes never change data permissions. Deleting an app deletes its+collection and assignments, but preserves the assigned groups.++**A viewer sees an app's data only through access they already hold.** Assignment changes never change+View Data permissions; the viewer's other groups and sandboxes continue to determine data access.++**Managing is superuser-only** — assignments, enabling, disabling, deleting, and repo status.Exporting an app's resources also needs a superuser.+The Data Apps feature is required for all app API endpoints, including group listing and removal.+## Namespace map-| Namespace | Responsibility |-| --------------------- | --------------------------------------------------------------------------------------------------- |-| `apps.clj` | Creating apps; the connected repository's URL. |-| `core.clj` | What other modules ask: resource file problems and table dependencies. |-| `config.clj` | The serialized layout and data app contract version constants. |-| `schema.clj` | Column schemas, with the normalization and validation every write goes through. |-| `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: hooks, permissions, default fields, serialization. |-| `resource_serialization.clj` | The serialization an app's resource files are written from: built queries, actions, metrics. |-| `query_definition.clj`| The closed schema of a `defineQuery` definition the serialization accepts. |-| `resource_validation.clj` | What the files of an app's collection may hold, checked on the whole snapshot before an import. |-| `resource_tables.clj` | The tables an app's resources read, recorded on the app after an import. |-| `db.clj` | The module's application-database queries. |-| `csp.clj` | `allowed_hosts` lookup for the core CSP middleware. |-| `init.clj` | Loads the above so endpoints, models, and hooks register. |+| Namespace | Responsibility |+| -------------------------------------- | ----------------------------------------------------------------------------------------------- |+| `apps.clj` | Creating apps; the connected repository's URL. |+| `core.clj` | Public access checks, resource file problems, and table dependencies. |+| `config.clj` | The serialized layout and data app contract version constants. |+| `schema.clj` | Column schemas, with the normalization and validation every write goes through. |+| `api.clj` | The `/api/apps` endpoints, bundle serving, ETag handling. |+| `resources.clj` | Lifecycle of the app-owned collection and derived collection permissions. |+| `models/data_app.clj` | The `:model/DataApp` Toucan model: hooks, permissions, default fields, serialization. |+| `resource_serialization.clj` | The serialization an app's resource files are written from: built queries, actions, metrics. |+| `query_definition.clj` | The closed schema of a `defineQuery` definition the serialization accepts. |+| `resource_validation.clj` | What the files of an app's collection may hold, checked on the whole snapshot before an import. |+| `resource_tables.clj` | The tables an app's resources read, recorded on the app after an import. |+| `access.clj` | App access through assigned groups. |+| `group_access.clj` | Assignment management and collection grant reconciliation. |+| `models/data_app_group_assignment.clj` | App-to-group assignments. |+| `db.clj` | The module's application-database queries. |+| `csp.clj` | `allowed_hosts` lookup for the core CSP middleware. |+| `init.clj` | Loads the above so endpoints, models, and hooks register. |++`group_access.clj` manages assignments. `models/data_app_group_assignment.clj` defines the local association model.diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/access.clj b/enterprise/backend/src/metabase_enterprise/data_apps/access.cljnew file mode 100644index 00000000000..62bd7aa7650--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/access.clj@@ -0,0 +1,20 @@+(ns metabase-enterprise.data-apps.access+ "Read access through group assignments."+ (:require+ [metabase-enterprise.data-apps.db :as data-apps.db]))++(defn- read-scope+ [{:keys [user-id superuser?]}]+ (if superuser? :all {:user-id user-id}))++(defn readable-apps+ "List of apps the user can view."+ [user available?]+ (data-apps.db/non-blob-data-apps (read-scope user) available?))++(defn can-read?+ "Whether the user can view the app through an assignment or admin access."+ [user app-id]+ (let [scope (read-scope user)]+ (or (= scope :all)+ (data-apps.db/readable-data-app? scope app-id))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex 198ef108981..f221cd166e6 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -7,9 +7,11 @@`metabase.server.routes/static-files-handler`)."(:require[clojure.string :as str]+ [metabase-enterprise.data-apps.access :as data-app.access][metabase-enterprise.data-apps.apps :as data-apps.apps][metabase-enterprise.data-apps.config :as data-app.config][metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.group-access :as data-app.group-access][metabase-enterprise.data-apps.models.data-app :as data-app][metabase-enterprise.data-apps.query-definition :as query-definition][metabase-enterprise.data-apps.resource-serialization :as data-app.resource-serialization]@@ -95,7 +97,6 @@[:enabled :boolean][:allowed_hosts [:sequential :string]][:resource_collection_id ms/PositiveInt]- [:permission_group_id [:maybe ms/PositiveInt]][:table_ids [:sequential ms/PositiveInt]][:bundle_hash [:maybe :string]][:created_at :any]@@ -164,6 +165,16 @@[:queries [:sequential SerializedQuery]][:actions [:sequential SerializedEntity]][:metrics [:sequential SerializedEntity]]])++(def ^:private AddGroupsRequest+ [:map {:closed true+ :decode/api (fn [body]+ (when (map? body)+ (api/check-400 (every? #{:group_ids} (keys body))+ (tru "Only group_ids can be specified.")))+ body)}+ [:group_ids [:sequential {:min 1 :max 100 :distinct true} ms/PositiveInt]]])+;;; --------------------------------------------- Repo status ---------------------------------------------(api.macros/defendpoint :get "/repo-status" :- RepoStatusResponse@@ -231,7 +242,7 @@"Refuse an app built for an older contract than this Metabase serves with a 409 carrying`:error-code \"data-app-outdated\"`, so the client can show what to do. Applied where thecontract is served: the bundle for everyone, and the metadata for non-superusers, who have no- other use for it. Superusers still read it, to badge the app and manage its users."+ other use for it. Superusers still read it, to badge the app and manage its groups."[app](when (data-app.config/outdated? app)(throw (ex-info (tru (str "This app was built for version {0} of data apps. Migrate it to the current "@@ -245,11 +256,10 @@available, and otherwise listed only to superusers, who see it badged."[_route-params{:keys [available]} :- [:map {:closed true} [:available {:optional true} [:maybe :boolean]]]]- (let [apps (->> (data-apps.db/data-apps available)- (remove #(and (or available (not api/*is-superuser?*))- (data-app.config/outdated? %)))- (mapv api/read-check))]- (mapv data-app-response apps)))+ (->> (data-app.access/readable-apps {:user-id api/*current-user-id* :superuser? api/*is-superuser?*} available)+ (remove #(and (or available (not api/*is-superuser?*))+ (data-app.config/outdated? %)))+ (mapv data-app-response)));; NOTE on the `slug-regex` constraint: the default path-param matcher allows;; slashes inside a segment, so `/:slug` would otherwise swallow `/x/bundle`.@@ -301,7 +311,7 @@(data-app-response app))))(api.macros/defendpoint :delete ["/:slug" :slug slug-regex] :- :nil- "Delete a data app, its bundle, and the collection and permission group it owns."+ "Delete a data app, its bundle, its collection, and its group assignments."[{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]](let [app (write-check-data-app slug)](check-editable! app)@@ -323,6 +333,32 @@(api/check-superuser)(data-app.resource-serialization/serialize-resources collection queries actions))+(def ^:private AssignedGroup+ [:map+ [:id ms/PositiveInt]+ [:name :string]+ [:member_count ms/IntGreaterThanOrEqualToZero]])++(api.macros/defendpoint :get ["/:slug/groups" :slug slug-regex] :- [:sequential AssignedGroup]+ "List the groups assigned to a data app."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]+ (api/check-superuser)+ (data-app.group-access/assigned-groups (api/check-404 (data-apps.db/data-app-by-slug slug))))++(api.macros/defendpoint :post ["/:slug/groups" :slug slug-regex] :- [:sequential AssignedGroup]+ "Assign a batch of internal groups atomically."+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]+ _query-params+ {group-ids :group_ids} :- AddGroupsRequest]+ (api/check-superuser)+ (data-app.group-access/add-groups! (api/check-404 (data-apps.db/data-app-by-slug slug)) group-ids))++(api.macros/defendpoint :delete ["/:slug/groups/:group-id" :slug slug-regex] :- :nil+ "Remove a group's assignment and collection access."+ [{:keys [slug group-id]} :- [:map {:closed true} [:slug ms/NonBlankString] [:group-id ms/PositiveInt]]]+ (api/check-superuser)+ (data-app.group-access/remove-group! (api/check-404 (data-apps.db/data-app-by-slug slug)) group-id))+;; Not tagged `data-apps:base`, though the bundle route below is — which looks backwards until;; you place the two callers. `DataAppView` fetches this metadata on the *host* page to decide;; what iframe to render, before any data-app realm exists, so the request never carries thediff --git a/enterprise/backend/src/metabase_enterprise/data_apps/core.clj b/enterprise/backend/src/metabase_enterprise/data_apps/core.cljindex b9cd0f49064..35a3ee7be7c 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/core.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/core.clj@@ -2,8 +2,12 @@"What other modules may ask the data-apps module: what the files of an app's collection may hold, and the tablesthose read."(:require+ [metabase-enterprise.data-apps.access :as data-app.access]+ [metabase-enterprise.data-apps.db :as data-apps.db][metabase-enterprise.data-apps.resource-tables :as resource-tables][metabase-enterprise.data-apps.resource-validation :as resource-validation]+ [metabase.api.common :as api]+ [metabase.premium-features.core :refer [defenterprise]][potemkin :as p]))(p/import-vars@@ -12,3 +16,12 @@[resource-validationproblemswarnings])++(defenterprise check-data-app-access!+ "Checks that the user belongs to one of the assigned groups"+ :feature :data-apps+ [request]+ (let [app (api/check-404 (data-apps.db/enabled-data-app-by-slug (get-in request [:route-params :name])))]+ (api/check-403 (data-app.access/can-read? {:user-id (:metabase-user-id request)+ :superuser? (:is-superuser? request)}+ (:id app)))))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.cljindex d1cc708ab4f..ae2e081232c 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj@@ -12,7 +12,7 @@(def non-blob-columns"Every DataApp column except the raw bundle blob."[:id :entity_id :name :display_name :description :version :bundle_path :enabled :allowed_hosts- :resource_collection_id :permission_group_id :table_ids :bundle_hash :created_at :updated_at])+ :resource_collection_id :table_ids :bundle_hash :created_at :updated_at])(def ^:private non-blob-model(into [:model/DataApp] non-blob-columns))@@ -39,6 +39,31 @@(cond-> {:order-by [[:display_name :asc]]}available? (assoc :where [:= :enabled true]))))+(defn- read-scope-clause+ [scope]+ (if (= scope :all)+ [:= 1 1]+ [:in :id ^:allow-subquery+ {:select [:assignment.data_app_id]+ :from [[:data_app_group_assignment :assignment]]+ :join [[:permissions_group_membership :pgm] [:= :pgm.group_id :assignment.permission_group_id]+ [:core_user :u] [:= :u.id :pgm.user_id]]+ :where [:and [:= :u.id (:user-id scope)] [:= :u.tenant_id nil]]}]))++(mu/defn non-blob-data-apps+ "DataApps in the read scope without bundles, ordered by display name. Optionally restrict to enabled apps."+ [scope :- [:or [:= :all] [:map {:closed true} [:user-id ms/PositiveInt]]]+ available? :- [:maybe :boolean]]+ (t2/select non-blob-model+ {:order-by [[:display_name :asc]]+ :where (cond-> [:and (read-scope-clause scope)]+ available? (conj [:= :enabled true]))}))++(defn readable-data-app?+ "Whether the app exists in the read scope."+ [scope app-id]+ (t2/exists? :model/DataApp :id app-id {:where (read-scope-clause scope)}))+(mu/defn data-app-bundle"The bundle bytes of the DataApp with `data-app-id`."[data-app-id :- ms/PositiveInt]@@ -91,31 +116,6 @@[data-app-id :- ms/PositiveInt](t2/delete! :model/DataApp :id data-app-id))-(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/select-pks-set :model/PermissionsGroup :is_data_app_group true))-(defn resource-collection-ids"The IDs of the resource collections owned by data apps."[]@@ -126,21 +126,6 @@[data-app-id :- ms/PositiveInt](t2/select-one-fn :resource_collection_id :model/DataApp :id data-app-id))-(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-owned?"Whether a data app owns the collection with `collection-id`."[collection-id]@@ -231,11 +216,6 @@[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]@@ -262,16 +242,20 @@(t2/select :model/Card :id [:in card-ids])[]))-(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 [(warehouse-schema-overlay/table-query {:alias :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 app-assignments+ "Assignments for the requested apps."+ [app-ids]+ (if (seq app-ids)+ (t2/select :model/DataAppGroupAssignment :data_app_id [:in app-ids])+ []))++(defn insert-assignments!+ "Assign groups to an app. The unique constraint rejects concurrent duplicates."+ [app-id group-ids]+ (t2/insert! :model/DataAppGroupAssignment+ (mapv (fn [group-id] {:data_app_id app-id :permission_group_id group-id}) group-ids)))++(defn delete-assignment!+ "Remove one group assignment."+ [app-id group-id]+ (t2/delete! :model/DataAppGroupAssignment :data_app_id app-id :permission_group_id group-id))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj b/enterprise/backend/src/metabase_enterprise/data_apps/group_access.cljnew file mode 100644index 00000000000..0725686ba0c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj@@ -0,0 +1,57 @@+(ns metabase-enterprise.data-apps.group-access+ (:require+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.resources :as resources]+ [metabase.api.common :as api]+ [metabase.permissions.core :as perms]+ [metabase.settings.core :as setting]+ [metabase.util.i18n :refer [tru]]+ [toucan2.core :as t2]))++(defn- check-groups-for-app-assignment+ "Reject missing groups, tenant groups and admin groups. Those cannot be assigned to data apps."+ [group-ids]+ (api/check-400 (= (count group-ids) (count (distinct group-ids)))+ (tru "Group IDs must be unique."))++ (let [group-tenant-flags (perms/group-tenant-flags (set group-ids))+ admin-group-id (:id (perms/admin-group))]+ ; every specified groups must exist+ (api/check-404 (= (count group-tenant-flags) (count group-ids)))+ (api/check-400 (every? (fn [[group-id tenant?]]+ (and (not tenant?) (not= group-id admin-group-id)))+ group-tenant-flags)+ (tru "Tenant groups and admins cannot be assigned to data apps."))))++(defn assigned-groups+ "Assigned groups with their member counts."+ [app]+ (let [using-tenants? (setting/get :use-tenants)+ group-ids (into #{} (map :permission_group_id) (data-apps.db/app-assignments [(:id app)]))]+ (mapv (fn [group]+ (assoc group :name (perms/group-display-name group using-tenants?)))+ (t2/hydrate (perms/groups-by-ids group-ids) :member_count))))++(defn add-groups!+ "Assign groups to app and update app collection grants."+ [app group-ids]+ (perms/with-global-permissions-lock+ (t2/with-transaction [_conn]+ (check-groups-for-app-assignment group-ids)+ (let [assigned (into #{} (map :permission_group_id) (data-apps.db/app-assignments [(:id app)]))]+ (api/check-400 (not-any? assigned group-ids) (tru "One or more groups already have access to this data app.")))+ (data-apps.db/insert-assignments! (:id app) group-ids)+ (resources/reconcile-existing-collection-permissions! app)))+ (assigned-groups app))++(defn remove-group!+ "Remove an assignment and its collection grants in one transaction."+ [app group-id]+ (perms/with-global-permissions-lock+ (t2/with-transaction [_conn]+ (api/check-404 (pos? (data-apps.db/delete-assignment! (:id app) group-id)))+ (when-not (= group-id (:id (perms/admin-group)))+ (when-let [collection (some-> (:id app) data-apps.db/data-app :resource_collection_id+ data-apps.db/resource-collection)]+ (perms/revoke-collection-permissions! group-id collection)))))+ nil)diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/init.clj b/enterprise/backend/src/metabase_enterprise/data_apps/init.cljindex 2a02e6ec974..4b9b3b50cd1 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/init.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/init.clj@@ -4,4 +4,5 @@[metabase-enterprise.data-apps.apps][metabase-enterprise.data-apps.config][metabase-enterprise.data-apps.csp]- [metabase-enterprise.data-apps.models.data-app]))+ [metabase-enterprise.data-apps.models.data-app]+ [metabase-enterprise.data-apps.models.data-app-group-assignment]))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 c97e982a670..6e2dfb1d3c2 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,5 +1,6 @@(ns metabase-enterprise.data-apps.models.data-app(:require+ [metabase-enterprise.data-apps.access :as data-app.access][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]@@ -102,12 +103,10 @@(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-;; README's permissions section for why this is safe.(defmethod mi/can-read? :model/DataApp- ([_instance] true)- ([_model _pk] true))+ ([app] (mi/can-read? :model/DataApp (:id app)))+ ([_model pk]+ (data-app.access/can-read? {:user-id api/*current-user-id* :superuser? api/*is-superuser?*} pk)))(defmethod mi/can-write? :model/DataApp([_instance] api/*is-superuser?*)@@ -155,7 +154,7 @@;; set by the import itself:bundle_hash;; server-managed resources, recreated on import- :permission_group_id :table_ids]+ :table_ids]:transform {:created_at (serdes/date);; the app's resource collection, a collection in the `data-apps` namespace that loads before the app:resource_collection_id (assoc (serdes/fk :model/Collection) :as :collection)@@ -212,13 +211,6 @@(data-app.resources/ensure-resources! app))app))-(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))-(defenterprise data-app-collection-ids"The resource collections of the data apps, which hold the copies an app runs.":feature :nonediff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app_group_assignment.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app_group_assignment.cljnew file mode 100644index 00000000000..6bd3b94d3b2--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app_group_assignment.clj@@ -0,0 +1,8 @@+(ns metabase-enterprise.data-apps.models.data-app-group-assignment+ (:require+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/DataAppGroupAssignment [_model] :data_app_group_assignment)++(derive :model/DataAppGroupAssignment :metabase/model)diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/permissions.clj b/enterprise/backend/src/metabase_enterprise/data_apps/permissions.cljdeleted file mode 100644index b71b640ff4c..00000000000--- a/enterprise/backend/src/metabase_enterprise/data_apps/permissions.clj+++ /dev/null@@ -1,55 +0,0 @@-(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/resources.clj b/enterprise/backend/src/metabase_enterprise/data_apps/resources.cljindex 6a71688fd46..4cfcc4d6b66 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/resources.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/resources.clj@@ -1,12 +1,7 @@(ns metabase-enterprise.data-apps.resources- "Lifecycle for the permission group and resource collection owned by a data app.-- The collection is created with the app, in the `data-apps` collection namespace, and is never replaced: the- model's hooks hold that invariant. What this namespace keeps in step afterwards is its name, its place out of- the trash, the permissions on it and on the group, and its existence, should it have been deleted on its own."+ "Lifecycle for the 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]))@@ -24,17 +19,6 @@(collection/create-collection! {:name (resource-name app):namespace (name collection/data-apps-ns)})))-(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.@@ -52,26 +36,27 @@(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)+(defn- reconcile-collection-permissions!+ "Restore read-only collection grants from the app assignments. Preserve correct rows."+ [app collection]+ (let [group-ids (into #{} (map :permission_group_id) (data-apps.db/app-assignments [(:id app)]))+ read-path (perms/collection-read-path collection)write-path (perms/collection-readwrite-path collection)++ ;; existing permissions for the app collection for each groupspermissions-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+ read-only? (fn [group-id]+ (= #{read-path} (set (map :object (get permissions-by-group group-id)))))]+ ;; revoke app collection access from unassigned groups(doseq [group-id (keys permissions-by-group)- :when (not (and (= group-id (:id group)) app-read-only?))]+ :when (not (and (group-ids group-id) (read-only? group-id)))](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))+ ;; grant app collection access to assigned groups+ (doseq [group-id group-ids+ :when (not (read-only? group-id))]+ (perms/grant-collection-read-permissions! group-id collection))))(defn- resource-collection!"The resource collection of `app`, created again if the app's was deleted out from under it: the reference is@@ -83,26 +68,28 @@(data-apps.db/update-data-app! (:id app) {:resource_collection_id (:id collection)})collection)))+(defn reconcile-existing-collection-permissions!+ "Reconcile grants for an existing resource collection without creating or restoring it."+ [app]+ (perms/with-global-permissions-lock+ (when-let [collection (some-> (:id app) data-apps.db/data-app :resource_collection_id+ data-apps.db/resource-collection)]+ (reconcile-collection-permissions! app collection))))+(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/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)})))+ (reconcile-collection-permissions! app collection)+ {: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]}]+ "Delete the app collection."+ [{:keys [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)))+ (data-apps.db/delete-resource-collection! resource_collection_id)))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj b/enterprise/backend/src/metabase_enterprise/data_apps/schema.cljindex f44f703efd6..5f5bc0138f7 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/schema.clj@@ -113,7 +113,6 @@[:description {:optional true} ::description][:version {:optional true} ::version][:resource_collection_id {:optional true} [:maybe ms/PositiveInt]]- [:permission_group_id {:optional true} [:maybe ms/PositiveInt]][:table_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]])(mr/def ::data-app.insertdiff --git a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj b/enterprise/backend/src/metabase_enterprise/scim/v2/api.cljindex ec99dc91fad..a81c60b6c79 100644--- a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj@@ -148,11 +148,9 @@;;; +----------------------------------------------------------------------------------------------------------------+(defn- hidden-group-ids- "IDs of the groups SCIM never exposes or manages: the static Administrators and All Users groups, and the groups- data apps own (see [[perms/data-app-group-ids]])."+ "IDs of the static groups that SCIM never exposes or manages."[]- (into [(:id (perms/all-users-group)) (:id (perms/admin-group))]- (perms/data-app-group-ids)))+ [(:id (perms/all-users-group)) (:id (perms/admin-group))])(mi/define-batched-hydration-method add-scim-user-group-memberships:scim_user_group_memberships@@ -380,8 +378,8 @@(sort-by :entity_id)))))))(mu/defn ^:private get-group-by-entity-id- "Fetches a group by entity ID, or throws a 404. Cannot fetch the Administrators or All Users groups, as these are- static, nor data-app groups, as Metabase manages their membership itself, so none can be managed via SCIM."+ "Fetches a group by entity ID, or throws a 404. Cannot fetch the Administrators or All Users groups,+ as these are static and cannot be managed via SCIM."[entity-id :- ms/NonBlankString](or (scim.db/scim-group-by-entity-id entity-id (hidden-group-ids))(throw-scim-error 404 "Group not found")))diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 577e7f8185a..fc274e5dfba 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -93,6 +93,7 @@"ConnectionImpersonation""ContentTranslation""DashboardBookmark"+ "DataAppGroupAssignment""DataComplexityScore""DataPermissions""DatabaseRouter"diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.cljindex 4aa87d861d6..05aa6041efc 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj@@ -4,7 +4,6 @@[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]@@ -185,43 +184,6 @@(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 b5b73e6b303..71cfe1f3c13 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -4,6 +4,7 @@[clojure.test :refer :all][metabase-enterprise.data-apps.apps :as data-apps.apps][metabase-enterprise.data-apps.config :as data-app.config]+ [metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.data-apps.query-definition :as query-definition][metabase-enterprise.data-apps.resources :as data-app.resources][metabase.actions.core :as actions]@@ -34,7 +35,7 @@;;; ---------------------------------------------- Permissions -----------------------------------------------(deftest data-app-access-requires-read-access-to-its-resource-collection-test+(deftest assigned-users-can-load-bundles-but-cannot-manage-apps-test;; global mode so the `:data-apps` 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`).@@ -43,18 +44,14 @@(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]} (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"))))+ {:keys [resource_collection_id]} (data-app.resources/ensure-resources! app)+ permission_group_id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Finches"}))]+ (testing "collection access alone does not assign an app"+ (perms/grant-collection-read-permissions! (perms/all-users-group) resource_collection_id)+ (mt/user-http-request :rasta :get 403 "apps/demo"))(testing "a member can open a data app"+ (group-access/add-groups! app [permission_group_id])(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"))))@@ -77,33 +74,12 @@(is (=? [{:name "demo" :display_name "Demo"}](mt/user-http-request :crowberto :get 200 "apps")))(is (=? {:name "demo"- :resource_collection_id pos-int?- :permission_group_id pos-int?}+ :resource_collection_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 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}- (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 read-only-remote-sync-blocks-data-app-changes-test(mt/with-premium-features #{:data-apps}(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup :model/RemoteSyncObject]@@ -140,79 +116,23 @@(deftest ^:parallel query-definition-request-schema-is-closed-test(is (empty? (closed-schemas/findings ::query-definition/query-definition))))-(deftest deactivated-users-cannot-be-added-to-data-apps-test- (mt/with-premium-features #{:data-apps}- (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}))))))))-(deftest data-app-write-endpoints-require-feature-token-test(mt/with-premium-features #{}(mt/user-http-request :crowberto :post 402 "apps/serialize-resources"{:collection "goodAppCollection0000" :queries [] :actions []})))-(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 data-app-group-reaches-only-copied-actions-test+(deftest assigned-group-reaches-only-copied-actions-test(testing "an action is reachable exactly when it lives in the data app collection"(mt/with-premium-features #{:data-apps}(mt/with-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]}+ (let [{:keys [resource_collection_id] :as app}(first (t2/insert-returning-instances! :model/DataApp{:name "action-perms-app":display_name "Action perms app"- :bundle_path "data_apps/action-perms-app/index.js"}))]+ :bundle_path "data_apps/action-perms-app/index.js"}))+ permission_group_id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Action readers"}))+ _ (group-access/add-groups! app [permission_group_id])](perms/add-user-to-group! (mt/user->id :rasta) permission_group_id);; an action on no model lives in a data actions collection, as a data app runs them(mt/with-temp [:model/Collection {source-collection-id :id} {:namespace :data-actions}]@@ -223,7 +143,7 @@:dataset_query (lib/native-query (mt/metadata-provider) "UPDATE venues SET name = 'x'")}source-id (actions/insert! (assoc action :collection_id source-collection-id))copied-id (actions/insert! (assoc action :collection_id resource_collection_id))]- (testing "the app's group reads the action copied into its collection"+ (testing "the assigned group reads the action copied into the app collection"(is (=? {:id copied-id}(mt/user-http-request :rasta :get 200 (str "action/" copied-id)))))(testing "the same group cannot read the source action it was copied from"@@ -240,7 +160,7 @@(t2/insert! :model/DataApp :name "disabled" :display_name "Disabled" :bundle_path "data_apps/disabled/index.js":enabled false)(is (=? [{:name "ready" :display_name "Ready"}]- (mt/user-http-request :rasta :get 200 "apps?available=true"))))))+ (mt/user-http-request :crowberto :get 200 "apps?available=true"))))))(deftest outdated-apps-are-hidden-from-users-and-badged-for-admins-test(mt/test-helpers-set-global-values!@@ -250,10 +170,12 @@:bundle (.getBytes "BUNDLE" "UTF-8") :bundle_hash "abc123" :version 1)(t2/insert! :model/DataApp :name "current" :display_name "Current" :bundle_path "data_apps/current/index.js":bundle (.getBytes "BUNDLE" "UTF-8") :bundle_hash "def456" :version 2)- (doseq [slug ["old" "current"]- :let [{:keys [permission_group_id]}- (data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name slug))]]- (perms/add-user-to-group! (mt/user->id :rasta) permission_group_id))+ (let [group-id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Data app test group"}))]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (doseq [slug ["old" "current"]+ :let [app (t2/select-one :model/DataApp :name slug)]]+ (data-app.resources/ensure-resources! app)+ (group-access/add-groups! app [group-id])))(with-redefs [data-app.config/supported-app-version 2](testing "a regular user is never told about the outdated app in a list"(doseq [url ["apps" "apps?available=true"]]@@ -270,14 +192,14 @@(is (str/includes?(str (mt/user-real-request :crowberto :get 200 "apps/current/bundle"))"BUNDLE")))- (testing "an admin sees the outdated app flagged, and can still read it to manage its users"+ (testing "an admin sees the outdated app flagged, and can still read it to manage its groups"(is (=? [{:name "current" :version 2 :outdated false}{:name "old" :version 1 :outdated true}](mt/user-http-request :crowberto :get 200 "apps")))(is (=? [{:name "current"}](mt/user-http-request :crowberto :get 200 "apps?available=true"))"but the navbar's available list leaves it out for admins too")- (is (=? {:name "old" :version 1 :outdated true :permission_group_id pos-int?}+ (is (=? {:name "old" :version 1 :outdated true}(mt/user-http-request :crowberto :get 200 "apps/old"))))(testing "nobody gets an outdated bundle"(is (=? {:error-code "data-app-outdated"}@@ -352,8 +274,7 @@:version 1:enabled true:bundle_hash string?- :resource_collection_id pos-int?- :permission_group_id pos-int?}+ :resource_collection_id pos-int?}(mt/user-http-request :crowberto :post 200 "apps"(assoc app-request :bundle_path "./dist/index.js"))))(is (str/includes? (str (mt/user-real-request :crowberto :get 200 "apps/demo/bundle"))@@ -395,31 +316,41 @@(testing "updating a missing app 404s"(mt/user-http-request :crowberto :put 404 "apps/missing" {:enabled false})))))))-(deftest delete-endpoint-test- (mt/test-helpers-set-global-values!- (mt/with-premium-features #{:data-apps}- (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]- (create-app!)- (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 delete-endpoint-requires-a-superuser-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection]+ (create-app!)+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta), :group_id group-id}]+ (let [app (t2/select-one :model/DataApp :name "demo")]+ (data-app.resources/ensure-resources! app)+ (group-access/add-groups! app [group-id]))+ (testing "an assigned user can open the app"+ (mt/user-http-request :rasta :get 200 "apps/demo"))+ (testing "an assigned user cannot delete the 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")))))))++(deftest delete-endpoint-404s-for-a-missing-app-test+ (mt/with-premium-features #{:data-apps}+ (mt/user-http-request :crowberto :delete 404 "apps/missing")))++(deftest delete-endpoint-preserves-assigned-groups-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]+ (create-app!)+ (mt/with-temp [:model/PermissionsGroup group {}]+ (let [app (t2/select-one :model/DataApp :name "demo")+ {collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)]+ (mt/with-temp [:model/Card {card-id :id} {:collection_id collection-id}]+ (group-access/add-groups! app [(:id group)])+ (mt/user-http-request :crowberto :delete 204 "apps/demo")+ (is (not (t2/exists? :model/DataApp :id (:id app))))+ (is (not (t2/exists? :model/Collection :id collection-id)))+ (is (not (t2/exists? :model/Card :id card-id)))+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (t2/exists? :model/PermissionsGroup :id (:id group)))))))));;; ----------------------------------------------------- API -----------------------------------------------------diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_test.cljnew file mode 100644index 00000000000..55b9a9f9e09--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_test.clj@@ -0,0 +1,309 @@+(ns metabase-enterprise.data-apps.group-access-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.data-apps.group-access :as group-access]+ [metabase-enterprise.data-apps.resources :as resources]+ [metabase.api.macros :as api.macros]+ [metabase.collections.core :as collection]+ [metabase.data-apps.core :as data-apps]+ [metabase.models.interface :as mi]+ [metabase.permissions.core :as perms]+ [metabase.sso.core :as sso]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(deftest assignments-authorize-access-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (resources/ensure-resources! app)+ (mt/with-current-user (mt/user->id :rasta)+ (is (not (mi/can-read? app))))+ (group-access/add-groups! app [(:id group)])+ (perms/add-user-to-group! (mt/user->id :rasta) (:id group))+ (mt/with-current-user (mt/user->id :rasta)+ (is (mi/can-read? app)))+ (group-access/remove-group! app (:id group))+ (mt/with-current-user (mt/user->id :rasta)+ (is (not (mi/can-read? app))))+ (mt/with-current-user (mt/user->id :crowberto)+ (is (mi/can-read? app)))))++(deftest app-list-authorizes-in-one-query-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/DataApp disabled {:name "disabled" :display_name "Disabled" :bundle_path "disabled.js"+ :enabled false}+ :model/DataApp _ {:name "hidden" :display_name "Hidden" :bundle_path "hidden.js"}+ :model/PermissionsGroup finches {}+ :model/PermissionsGroup owls {}]+ (group-access/add-groups! app [(:id finches) (:id owls)])+ (group-access/add-groups! disabled [(:id finches)])+ (perms/add-user-to-group! (mt/user->id :rasta) (:id finches))+ (perms/add-user-to-group! (mt/user->id :rasta) (:id owls))+ (let [list-apps (api.macros/find-route-fn 'metabase-enterprise.data-apps.api :get "/")]+ (mt/with-current-user (mt/user->id :rasta)+ (list-apps {} {})+ (doseq [[query expected] [[{} [{:name "birds" :display_name "Birds"}+ {:name "disabled" :display_name "Disabled"}]]+ [{:available true} [{:name "birds" :display_name "Birds"}]]]]+ (t2/with-call-count [call-count]+ (is (= expected (list-apps {} query)))+ (is (= 1 (call-count)))))))))++(deftest read-access-agrees-across-entry-points-test+ (mt/with-premium-features #{:data-apps :tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant tenant {:name "Tenant"}+ :model/User tenant-user {:tenant_id (:id tenant)}+ :model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"+ :bundle (.getBytes "BUNDLE" "UTF-8")}+ :model/PermissionsGroup tenant-group {:is_tenant_group true}+ :model/PermissionsGroup group {}]+ (resources/ensure-resources! app)+ (group-access/add-groups! app [(:id group)])+ (perms/add-user-to-group! (mt/user->id :rasta) (:id group))+ ;; A stale assignment must not admit tenant users.+ (perms/add-user-to-group! (:id tenant-user) (:id tenant-group))+ (t2/insert! :model/DataAppGroupAssignment {:data_app_id (:id app) :permission_group_id (:id tenant-group)})+ (doseq [[user-id admin? allowed?] [[(mt/user->id :crowberto) true true]+ [(mt/user->id :rasta) false true]+ [(mt/user->id :lucky) false false]+ [(:id tenant-user) false false]]]+ (testing (str "read access for user " user-id)+ (is (= (if allowed? ["birds"] [])+ (mapv :name (mt/user-http-request user-id :get 200 "apps"))))+ (mt/user-http-request user-id :get (if allowed? 200 403) "apps/birds")+ (mt/user-http-request user-id :get (if allowed? 200 403) "apps/birds/bundle")+ (mt/with-current-user user-id+ (is (= allowed? (boolean (mi/can-read? app)))))+ (let [request {:route-params {:name "birds"} :metabase-user-id user-id :is-superuser? admin?}]+ (if allowed?+ (is (true? (data-apps/check-data-app-access! request)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permissions"+ (data-apps/check-data-app-access! request)))))))))))++(deftest group-api-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup finches {:name "Finches"}+ :model/PermissionsGroup owls {:name "Owls"}+ :model/PermissionsGroup tenant {:is_tenant_group true}]+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/groups")))+ (doseq [ids [[(:id finches) (:id (perms/admin-group))]+ [(:id finches) (:id tenant)]+ [(:id finches) (:id finches)]+ []+ (vec (range 1 102))]]+ (mt/user-http-request :crowberto :post 400 "apps/birds/groups" {:group_ids ids})+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app)))))+ (mt/user-http-request :crowberto :post 404 "apps/birds/groups" {:group_ids [(:id finches) Integer/MAX_VALUE]})+ (is (=? [{:id (:id finches) :name "Finches" :member_count 0}+ {:id (:id owls) :name "Owls" :member_count 0}]+ (mt/user-http-request :crowberto :post 200 "apps/birds/groups"+ {:group_ids [(:id finches) (:id owls)]})))+ (mt/user-http-request :crowberto :post 400 "apps/birds/groups" {:group_ids [(:id finches)]})+ (mt/user-http-request :crowberto :delete 204 (str "apps/birds/groups/" (:id finches)))+ (is (= [(:id owls)] (mapv :id (mt/user-http-request :crowberto :get 200 "apps/birds/groups"))))+ (doseq [[method path body] [[:get "groups" nil]+ [:post "groups" {:group_ids [(:id finches)]}]+ [:delete (str "groups/" (:id owls)) nil]]]+ (apply mt/user-http-request :rasta method 403 (str "apps/birds/" path) (when body [body]))))))++(deftest group-api-rejects-unknown-fields-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (mt/user-http-request :crowberto :post 400 "apps/birds/groups"+ {:group_ids [(:id group)] :user_ids [(mt/user->id :rasta)]})+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (= (:resource_collection_id app)+ (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app)))))))++(deftest assignment-does-not-recreate-deleted-collection-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (t2/delete! :model/Collection :id (:resource_collection_id app))+ (mt/user-http-request :crowberto :post 200 "apps/birds/groups" {:group_ids [(:id group)]})+ (is (t2/exists? :model/DataAppGroupAssignment :data_app_id (:id app) :permission_group_id (:id group)))+ (is (nil? (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app)))))))++(deftest assigned-group-display-name-test+ (mt/with-premium-features #{:data-apps :tenants}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (group-access/add-groups! app [(:id (perms/all-users-group))])+ (doseq [[tenants? expected-name] [[false "All Users"] [true "All internal users"]]]+ (mt/with-temporary-setting-values [use-tenants tenants?]+ (is (= [expected-name]+ (mapv :name (mt/user-http-request :crowberto :get 200 "apps/birds/groups")))))))))++(deftest revoke-assignment-with-trashed-collection-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (resources/ensure-resources! app)+ (group-access/add-groups! app [(:id group)])+ (perms/add-user-to-group! (mt/user->id :rasta) (:id group))+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app))]+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-dynamic-fn-redefs [perms/data-app-collection? (constantly false)]+ (collection/archive-or-unarchive-collection!+ (t2/select-one :model/Collection :id collection-id) {:archived true})))+ (mt/user-http-request :crowberto :delete 204 (str "apps/birds/groups/" (:id group)))+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (empty? (t2/select :model/Permissions :group_id (:id group)+ :object [:in [(perms/collection-read-path collection-id)+ (perms/collection-readwrite-path collection-id)]])))+ (is (true? (t2/select-one-fn :archived :model/Collection :id collection-id)))+ (mt/with-current-user (mt/user->id :rasta)+ (is (not (mi/can-read? app))))))))++(deftest assignment-transaction-rolls-back-grant-failure-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (let [{collection-id :resource_collection_id} (resources/ensure-resources! app)+ reconcile-permissions! (mt/original-fn #'resources/reconcile-existing-collection-permissions!)]+ (mt/with-dynamic-fn-redefs [resources/reconcile-existing-collection-permissions!+ (fn [app]+ (reconcile-permissions! app)+ (throw (ex-info "Failed after granting collection access" {})))]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Failed after granting collection access"+ (group-access/add-groups! app [(:id group)]))))+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (not (t2/exists? :model/Permissions :group_id (:id group)+ :object (perms/collection-read-path collection-id)))))))++(deftest assignments-preserve-data-permissions-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (perms/set-database-permission! (:id group) (mt/id) :perms/create-queries :query-builder-and-native)+ (let [before (t2/select :model/DataPermissions :group_id (:id group))]+ (testing "assignment preserves existing data permissions"+ (group-access/add-groups! app [(:id group)])+ (is (= before (t2/select :model/DataPermissions :group_id (:id group)))))+ (testing "reconciliation preserves existing data permissions"+ (resources/ensure-resources! app)+ (is (= before (t2/select :model/DataPermissions :group_id (:id group)))))+ (testing "removal preserves existing data permissions"+ (group-access/remove-group! app (:id group))+ (is (= before (t2/select :model/DataPermissions :group_id (:id group))))))))++(deftest group-deletion-cascades-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (group-access/add-groups! app [(:id group)])+ (t2/delete! :model/PermissionsGroup :id (:id group))+ (is (empty? (t2/select :model/DataAppGroupAssignment :data_app_id (:id app))))+ (is (t2/exists? :model/DataApp :id (:id app)))))++(deftest all-users-assignment-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (group-access/add-groups! app [(:id (perms/all-users-group))])+ (mt/with-current-user (mt/user->id :rasta)+ (is (mi/can-read? app)))+ (is (true? (data-apps/check-data-app-access!+ {:route-params {:name "birds"} :metabase-user-id (mt/user->id :rasta)}))))))++(deftest group-endpoints-require-feature-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (resources/ensure-resources! app)+ (group-access/add-groups! app [(:id group)])+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app))]+ (mt/with-premium-features #{}+ (mt/user-http-request :crowberto :get 402 "apps")+ (mt/user-http-request :crowberto :get 402 "apps/birds/groups")+ (mt/user-http-request :crowberto :post 402 "apps/birds/groups" {:group_ids [(:id group)]})+ (mt/user-http-request :crowberto :delete 402 (str "apps/birds/groups/" (:id group)))+ (is (t2/exists? :model/DataAppGroupAssignment :data_app_id (:id app) :permission_group_id (:id group)))+ (is (t2/exists? :model/Permissions :group_id (:id group)+ :object (perms/collection-read-path collection-id))))))))++(deftest assignment-uniqueness-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (let [assignment {:data_app_id (:id app) :permission_group_id (:id group)}]+ (t2/insert! :model/DataAppGroupAssignment assignment)+ (is (thrown? Exception+ (t2/with-transaction [_conn]+ (t2/insert! :model/DataAppGroupAssignment assignment))))+ (is (= 1 (t2/count :model/DataAppGroupAssignment+ :data_app_id (:id app) :permission_group_id (:id group)))))))++(deftest revoke-assignment-after-group-becomes-ineligible-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}]+ (resources/ensure-resources! app)+ (group-access/add-groups! app [(:id group)])+ (t2/update! :model/PermissionsGroup (:id group) {:is_tenant_group true})+ (mt/user-http-request :rasta :delete 403 (str "apps/birds/groups/" (:id group)))+ (is (= [(:id group)] (mapv :id (group-access/assigned-groups app))))+ (mt/user-http-request :crowberto :delete 204 (str "apps/birds/groups/" (:id group)))+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/groups")))+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app))]+ (is (not (t2/exists? :model/Permissions :group_id (:id group)+ :object (perms/collection-read-path collection-id))))))))++(deftest revoke-invalid-admin-assignment-preserves-admin-permissions-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (resources/ensure-resources! app)+ (let [admin-id (:id (perms/admin-group))+ permissions (t2/select :model/Permissions :group_id admin-id)]+ (t2/insert! :model/DataAppGroupAssignment {:data_app_id (:id app) :permission_group_id admin-id})+ (mt/user-http-request :crowberto :delete 204 (str "apps/birds/groups/" admin-id))+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/groups")))+ (is (= permissions (t2/select :model/Permissions :group_id admin-id)))))))++(deftest revoke-assignment-requires-matching-app-and-group-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/DataApp _ {:name "wrens" :display_name "Wrens" :bundle_path "wrens.js"}+ :model/PermissionsGroup group {}]+ (group-access/add-groups! app [(:id group)])+ (doseq [[path status] [[(str "apps/wrens/groups/" (:id group)) 404]+ [(str "apps/missing/groups/" (:id group)) 404]+ ["apps/birds/groups/2147483647" 404]+ ["apps/birds/groups/0" 400]+ ["apps/birds/groups/not-an-id" 400]]]+ (mt/user-http-request :crowberto :delete status path))+ (is (= [(:id group)]+ (mapv :id (mt/user-http-request :crowberto :get 200 "apps/birds/groups")))))))++(deftest collection-drift-denies-access-until-grants-are-reconciled-test+ (mt/with-premium-features #{:data-apps}+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (resources/ensure-resources! app)+ (let [group-id (:id (perms/all-users-group))]+ (group-access/add-groups! app [group-id])+ (let [collection-id (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app))]+ (perms/revoke-collection-permissions! group-id collection-id)+ (mt/user-http-request :rasta :get 403 "apps/birds")+ (resources/ensure-resources! app)+ (is (= {:name "birds" :display_name "Birds"}+ (mt/user-http-request :rasta :get 200 "apps/birds"))))))))++(deftest tenant-users-cannot-inherit-app-access-test+ (mt/with-premium-features #{:tenants}+ (mt/with-temp [:model/Tenant tenant {:name "Tenant"}+ :model/User user {:tenant_id (:id tenant)}+ :model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}]+ (group-access/add-groups! app [(:id (perms/all-users-group))])+ (mt/with-current-user (:id user)+ (is (not (mi/can-read? app)))))))++(deftest sso-membership-controls-assigned-app-access-test+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"}+ :model/PermissionsGroup group {}+ :model/User user {}]+ (group-access/add-groups! app [(:id group)])+ (sso/sync-group-memberships! (:id user) [(:id group)])+ (mt/with-current-user (:id user)+ (is (mi/can-read? app)))+ (sso/sync-group-memberships! (:id user) [])+ (mt/with-current-user (:id user)+ (is (not (mi/can-read? app))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.cljindex 781c45991c2..a2b1e7ba78a 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj@@ -40,11 +40,11 @@(deftest insert-creates-the-resources-the-app-owns-test(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]- (let [{:keys [resource_collection_id permission_group_id]} (t2/select-one :model/DataApp (insert-app!))]+ (let [{:keys [id resource_collection_id]} (t2/select-one :model/DataApp (insert-app!))](is (=? {:name "Data App: m" :namespace :data-apps :location "/"}(t2/select-one :model/Collection :id resource_collection_id))"the collection is the app's own, in the data-apps namespace")- (is (t2/exists? :model/PermissionsGroup :id permission_group_id :is_data_app_group true)))))+ (is (not (t2/exists? :model/DataAppGroupAssignment :data_app_id id))))))(deftest insert-publishes-the-creation-of-the-collection-test(testing "the collection is created the way any collection is, so what listens to collection events (remote sync,@@ -85,13 +85,12 @@(t2/update! :model/DataApp id {:resource_collection_id other-id})(is (= other-id (t2/select-one-fn :resource_collection_id :model/DataApp id))))))))-(deftest delete-removes-the-resources-the-app-owns-test+(deftest delete-removes-the-resource-collection-the-app-owns-test(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](let [id (insert-app!)- {:keys [resource_collection_id permission_group_id]} (t2/select-one :model/DataApp id)]+ {:keys [resource_collection_id]} (t2/select-one :model/DataApp id)](t2/delete! :model/DataApp id)- (is (not (t2/exists? :model/Collection :id resource_collection_id)))- (is (not (t2/exists? :model/PermissionsGroup :id permission_group_id))))))+ (is (not (t2/exists? :model/Collection :id resource_collection_id))))))(deftest writes-are-normalized-and-validated-against-the-schema-test(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup]@@ -148,8 +147,8 @@(is (mi/can-read? :model/DataApp 1))(is (mi/can-write? :model/DataApp 1))(is (mi/can-create? :model/DataApp {}))))- (testing "any signed-in user can read (view), but write/create stay superuser-only"+ (testing "an unassigned user cannot read, write, or create"(binding [api/*is-superuser?* false]- (is (mi/can-read? :model/DataApp 1))+ (is (not (mi/can-read? :model/DataApp 1)))(is (not (mi/can-write? :model/DataApp 1)))(is (not (mi/can-create? :model/DataApp {}))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.cljdeleted file mode 100644index d0c3361c78f..00000000000--- a/enterprise/backend/test/metabase_enterprise/data_apps/permissions_test.clj+++ /dev/null@@ -1,176 +0,0 @@-(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/resources_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.cljindex 7b91f521dd3..7e2d35eed00 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/resources_test.clj@@ -1,10 +1,10 @@(ns metabase-enterprise.data-apps.resources-test(:require[clojure.test :refer :all]+ [metabase-enterprise.data-apps.group-access :as group-access][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]))@@ -69,59 +69,12 @@(t2/select-one :model/Collection :id resource_collection_id)))(is (= resource_collection_id (t2/select-one-fn :resource_collection_id :model/DataApp :id (:id app)))))))))-(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)+ {collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)+ group-id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Finches"}))+ _ (group-access/add-groups! app [group-id])read-path (perms/collection-read-path collection-id)grant (t2/select-one :model/Permissions :group_id group-id :object read-path)](is (some? grant))@@ -133,7 +86,9 @@(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)+ {collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)+ group-id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Finches"}))+ _ (group-access/add-groups! app [group-id])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@@ -150,7 +105,9 @@(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)]+ {collection-id :resource_collection_id} (data-app.resources/ensure-resources! app)+ group-id (:id (t2/insert-returning-instance! :model/PermissionsGroup {:name "Finches"}))+ _ (group-access/add-groups! app [group-id])](perms/revoke-collection-permissions! group-id collection-id)(data-app.resources/ensure-resources! app); read access should be restored after syncdiff --git a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.cljindex 4dace786d2e..99335222e26 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/serialization_test.clj@@ -2,6 +2,7 @@(:require[clojure.java.io :as io][clojure.test :refer :all]+ [metabase-enterprise.data-apps.group-access :as group-access][metabase-enterprise.serialization.core :as serialization][metabase-enterprise.serialization.test-util :as ts][metabase-enterprise.serialization.v2.extract :as extract]@@ -102,10 +103,10 @@:allowed_hosts ["https://api.example.com"]}imported))(is (= "console.log(1)" (bundle-text imported)))- (testing "the import links the collection the manifest names and creates the permission group"+ (testing "the import links the collection the manifest names without importing group assignments"(is (=? {:entity_id collection-entity-id :namespace :data-apps}(t2/select-one :model/Collection :id (:resource_collection_id imported))))- (is (t2/exists? :model/PermissionsGroup :id (:permission_group_id imported))))))))))+ (is (not (t2/exists? :model/DataAppGroupAssignment :data_app_id (:id imported)))))))))))(deftest import-refuses-a-manifest-that-names-another-collection-test(mt/with-premium-features #{:data-apps}@@ -133,7 +134,9 @@(mt/with-premium-features #{:data-apps}(mt/with-model-cleanup [:model/DataApp :model/Collection :model/PermissionsGroup](ts/with-random-dump-dir [dump-dir "data-app-update-"]- (let [app (insert-app! :enabled false)]+ (let [app (insert-app! :enabled false)+ group (t2/insert-returning-instance! :model/PermissionsGroup {:name "Assigned group"})]+ (group-access/add-groups! app [(:id group)])(write-app-files! dump-dir "sales-ops" (app-yaml (:entity_id app) "sales-ops" :name "Renamed":path "./dist/index.js"){"dist/index.js" "console.log(2)"})@@ -141,9 +144,10 @@(let [updated (t2/select-one :model/DataApp :id (:id app))](is (=? {:display_name "Renamed":enabled false- :resource_collection_id (:resource_collection_id app)- :permission_group_id (:permission_group_id app)}+ :resource_collection_id (:resource_collection_id app)}updated))+ (is (t2/exists? :model/DataAppGroupAssignment+ :data_app_id (:id app) :permission_group_id (:id group)))(is (= "console.log(2)" (bundle-text updated)))(is (not= (:bundle_hash app) (:bundle_hash updated)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.cljindex 8e3b5abffb5..c82c5e563f5 100644--- a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj@@ -105,15 +105,6 @@:display "Test Group"}]:meta {:resourceType "User"}}response)))))- (testing "Data-app group memberships are not exposed"- (mt/with-temp [:model/User user {:email "[email protected]"}- :model/PermissionsGroup group {:name "Test Group"}- :model/PermissionsGroup app-group {:name "App Group" :is_data_app_group true}- :model/PermissionsGroupMembership _ {:user_id (:id user) :group_id (:id group)}- :model/PermissionsGroupMembership _ {:user_id (:id user) :group_id (:id app-group)}]- (let [entity-id (t2/select-one-fn :entity_id :model/User :id (:id user))- response (scim-client :get 200 (format "ee/scim/v2/Users/%s" entity-id))]- (is (= ["Test Group"] (map :display (:groups response)))))))(testing "404 is returned when fetching a non-existent user"(scim-client :get 404 (format "ee/scim/v2/Users/%s" (random-uuid))))))@@ -373,17 +364,7 @@(is (= 0 (count (get response :Resources))))))(testing "Error if unsupported filter operation is provided"(scim-client :get 400 (format "ee/scim/v2/Users?filter=%s"- (codec/url-encode "displayName ne \"Group 1\""))))- (testing "Data-app groups are not listed"- (mt/with-temp [:model/PermissionsGroup app-group {:name "App Group" :is_data_app_group true}]- (let [app-entity-id (t2/select-one-fn :entity_id :model/PermissionsGroup :id (:id app-group))- response (scim-client :get 200 "ee/scim/v2/Groups")]- (is (not (contains? (into #{} (map :id) (:Resources response)) app-entity-id)))- (is (= (count (:Resources response)) (:totalResults response))))- (let [response (scim-client :get 200 (format "ee/scim/v2/Groups?filter=%s"- (codec/url-encode "displayName eq \"App Group\"")))]- (is (= 0 (get response :totalResults)))- (is (= 0 (count (get response :Resources))))))))))+ (codec/url-encode "displayName ne \"Group 1\"")))))))(deftest fetch-group-test(with-scim-setup!@@ -407,10 +388,6 @@(let [entity-ids (t2/select-fn-set :entity_id :model/PermissionsGroup{:where [:in :id #{(:id (perms-group/admin)) (:id (perms-group/all-users))}]})](doseq [entity-id entity-ids]- (scim-client :get 404 (format "ee/scim/v2/Groups/%s" entity-id)))))- (testing "404 is returned when fetching a data-app group"- (mt/with-temp [:model/PermissionsGroup app-group {:name "App Group" :is_data_app_group true}]- (let [entity-id (t2/select-one-fn :entity_id :model/PermissionsGroup :id (:id app-group))](scim-client :get 404 (format "ee/scim/v2/Groups/%s" entity-id)))))))(deftest create-group-test@@ -456,19 +433,7 @@:members [{:value (str (random-uuid))}]}](scim-client :put 200 (format "ee/scim/v2/Groups/%s" entity-id) group-update)(is (= #{(mt/user->id :rasta)}- (t2/select-fn-set :user_id :model/PermissionsGroupMembership :group_id (:id group)))))))- (testing "404 is returned when trying to update a data-app group, and its membership is left alone"- (mt/with-temp [:model/PermissionsGroup app-group {:name "App Group" :is_data_app_group true}- :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id (:id app-group)}]- (let [entity-id (t2/select-one-fn :entity_id :model/PermissionsGroup :id (:id app-group))- group-update {:schemas ["urn:ietf:params:scim:schemas:core:2.0:Group"]- :id entity-id- :displayName "Renamed App Group"- :members [{:value (t2/select-one-fn :entity_id :model/User :id (mt/user->id :crowberto))}]}]- (scim-client :put 404 (format "ee/scim/v2/Groups/%s" entity-id) group-update)- (is (= "App Group" (t2/select-one-fn :name :model/PermissionsGroup :id (:id app-group))))- (is (= #{(mt/user->id :rasta)}- (t2/select-fn-set :user_id :model/PermissionsGroupMembership :group_id (:id app-group)))))))))+ (t2/select-fn-set :user_id :model/PermissionsGroupMembership :group_id (:id group)))))))))(deftest delete-group-test(with-scim-setup!@@ -485,12 +450,7 @@(let [entity-ids (t2/select-fn-set :entity_id :model/PermissionsGroup{:where [:in :id #{(:id (perms-group/admin)) (:id (perms-group/all-users))}]})](doseq [entity-id entity-ids]- (scim-client :delete 404 (format "ee/scim/v2/Groups/%s" entity-id)))))- (testing "404 is returned when trying to delete a data-app group, and it survives"- (mt/with-temp [:model/PermissionsGroup app-group {:name "App Group" :is_data_app_group true}]- (let [entity-id (t2/select-one-fn :entity_id :model/PermissionsGroup :id (:id app-group))]- (scim-client :delete 404 (format "ee/scim/v2/Groups/%s" entity-id))- (is (t2/exists? :model/PermissionsGroup :id (:id app-group))))))))+ (scim-client :delete 404 (format "ee/scim/v2/Groups/%s" entity-id)))))));;; ------------------------- Data Analysts group: additions gated, removals never -------------------------diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex d447052bfbc..19099f1f387 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -54,6 +54,7 @@:model/CollectionBookmark:model/ContentTranslation:model/DashboardBookmark+ :model/DataAppGroupAssignment:model/DataComplexityScore:model/DataPermissions:model/DatabaseRouterdiff --git a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts b/enterprise/frontend/src/metabase-enterprise/api/data-app.tsindex 2cb5792b528..4e52eddaa9e 100644--- a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts@@ -1,6 +1,9 @@import type {+ AddDataAppGroupsRequest,DataApp,+ DataAppGroup,DataAppRepoStatus,+ RemoveDataAppGroupRequest,SetDataAppEnabledRequest,} from "metabase-types/api";@@ -40,6 +43,32 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({}),providesTags: () => [REPO_STATUS_TAG],}),+ getDataAppGroups: builder.query<DataAppGroup[], string>({+ query: (name) => ({+ method: "GET",+ url: `/api/apps/${encodeURIComponent(name)}/groups`,+ }),+ providesTags: (_, __, name) => [idTag("data-app", name)],+ }),+ addDataAppGroups: builder.mutation<DataAppGroup[], AddDataAppGroupsRequest>(+ {+ query: ({ name, group_ids }) => ({+ method: "POST",+ url: `/api/apps/${encodeURIComponent(name)}/groups`,+ body: { group_ids },+ }),+ invalidatesTags: (_, error, { name }) =>+ invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),+ },+ ),+ removeDataAppGroup: builder.mutation<void, RemoveDataAppGroupRequest>({+ query: ({ name, group_id }) => ({+ method: "DELETE",+ url: `/api/apps/${encodeURIComponent(name)}/groups/${group_id}`,+ }),+ invalidatesTags: (_, error, { name }) =>+ invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),+ }),setDataAppEnabled: builder.mutation<DataApp, SetDataAppEnabledRequest>({query: ({ name, enabled }) => ({method: "PUT",@@ -64,6 +93,9 @@ export const {useListDataAppsQuery,useGetDataAppQuery,useGetDataAppRepoStatusQuery,+ useGetDataAppGroupsQuery,+ useAddDataAppGroupsMutation,+ useRemoveDataAppGroupMutation,useSetDataAppEnabledMutation,useDeleteDataAppMutation,} = dataAppApi;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsxnew file mode 100644index 00000000000..e72071eb991--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx@@ -0,0 +1,125 @@+import { useState } from "react";+import { t } from "ttag";++import { AdminPaneLayout } from "metabase/admin/components/AdminPaneLayout";+import { Breadcrumbs } from "metabase/common/components/Breadcrumbs";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useToast } from "metabase/common/hooks";+import { useParams } from "metabase/router";+import { SettingsPageWrapper } from "metabase/settings-components";+import { Box, Button, Stack, Text } from "metabase/ui";+import {+ useAddDataAppGroupsMutation,+ useGetDataAppGroupsQuery,+ useListDataAppsQuery,+ useRemoveDataAppGroupMutation,+} from "metabase-enterprise/api";+import type { DataAppGroup } from "metabase-types/api";++import { DataAppGroupList } from "./components/DataAppGroupList/DataAppGroupList";++export const ManageDataAppGroupsPage = () => {+ const { slug = "" } = useParams<{ slug: string }>();++ const listQuery = useListDataAppsQuery();+ const listGroupsQuery = useGetDataAppGroupsQuery(slug);++ const app = listQuery.data?.find((app) => app.name === slug);+ const isAppMissing = listQuery.isSuccess && !app;++ const error =+ listQuery.error ??+ listGroupsQuery.error ??+ (isAppMissing ? t`Data app not found.` : undefined);++ const isLoading = listQuery.isLoading || listGroupsQuery.isLoading;++ return (+ <SettingsPageWrapper>+ <LoadingAndErrorWrapper error={error} loading={isLoading}>+ {app && listGroupsQuery.data && (+ <DataAppGroups+ appName={slug}+ appTitle={app.display_name}+ groups={listGroupsQuery.data}+ />+ )}+ </LoadingAndErrorWrapper>+ </SettingsPageWrapper>+ );+};++const DataAppGroups = ({+ appName,+ appTitle,+ groups,+}: {+ appName: string;+ appTitle: string;+ groups: DataAppGroup[];+}) => {+ const [sendToast] = useToast();+ const [isAdding, setIsAdding] = useState(false);++ const [addGroups] = useAddDataAppGroupsMutation();+ const [removeGroup] = useRemoveDataAppGroupMutation();++ const handleAddGroups = async (groupIds: number[]) => {+ const { error } = await addGroups({ name: appName, group_ids: groupIds });++ if (error) {+ sendToast({ message: t`Failed to add groups`, icon: "warning" });+ return false;+ }++ setIsAdding(false);++ return true;+ };++ const handleRemoveGroup = async (group: DataAppGroup) => {+ const { error } = await removeGroup({ name: appName, group_id: group.id });++ if (error) {+ sendToast({ message: t`Failed to remove group`, 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 ${appTitle}`}+ </Text>+ }+ titleActions={+ <Button+ variant="filled"+ onClick={() => setIsAdding(true)}+ disabled={isAdding}+ >+ {t`Add groups`}+ </Button>+ }+ >+ <DataAppGroupList+ isAdding={isAdding}+ groups={groups}+ onAddGroups={handleAddGroups}+ onCancelAdd={() => setIsAdding(false)}+ onRemoveGroup={handleRemoveGroup}+ />+ </AdminPaneLayout>+ </Stack>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsxnew file mode 100644index 00000000000..a89478fc299--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.unit.spec.tsx@@ -0,0 +1,259 @@+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 { DataApp, DataAppGroup } from "metabase-types/api";+import { createMockDataApp, createMockGroup } from "metabase-types/api/mocks";++import { ManageDataAppGroupsPage } from "./ManageDataAppGroupsPage";++const FINCHES_GROUP_ID = 3;+const OWLS_GROUP_ID = 4;++const candidates = [+ createMockGroup({+ id: 1,+ name: "All Users",+ magic_group_type: "all-internal-users",+ }),++ createMockGroup({+ id: 2,+ name: "Administrators",+ magic_group_type: "admin",+ }),++ createMockGroup({ id: FINCHES_GROUP_ID, name: "Finches" }),+ createMockGroup({ id: OWLS_GROUP_ID, name: "Owls" }),++ createMockGroup({+ id: 5,+ name: "Tenant",+ is_tenant_group: true,+ }),+];++const setup = ({+ app = createMockDataApp(),+ groups = [],++ failFirstAdd = false,+}: {+ app?: DataApp;+ groups?: DataAppGroup[];++ failFirstAdd?: boolean;+} = {}) => {+ let assigned = [...groups];++ fetchMock.get("path:/api/apps", [app]);+ fetchMock.get("path:/api/permissions/group", candidates);+ fetchMock.get("path:/api/apps/sales/groups", () => assigned);++ fetchMock.get(+ "path:/api/apps/sales",+ !app.enabled ? 404 : !app.resource_collection_id ? 409 : app,+ );++ fetchMock.post("path:/api/apps/sales/groups", ({ options: { body } }) => {+ if (failFirstAdd) {+ failFirstAdd = false;+ return 500;+ }++ const { group_ids } = JSON.parse(String(body));++ assigned = [+ ...assigned,+ ...candidates+ .filter((group) => group_ids.includes(group.id))+ .map((group) => ({ ...group, member_count: 0 })),+ ];++ return assigned;+ });++ fetchMock.delete("express:/api/apps/sales/groups/:id", ({ url }) => {+ // `/api/apps/sales/groups/5` -> `5`+ const groupId = Number(url.split("/").pop());+ assigned = assigned.filter((group) => group.id !== groupId);++ return 204;+ });++ renderWithProviders(+ <Route+ path="admin/settings/apps/:slug/groups"+ element={+ <>+ <ManageDataAppGroupsPage />+ <UndoListing />+ </>+ }+ />,+ { withRouter: true, initialRoute: "/admin/settings/apps/sales/groups" },+ );+};++describe("ManageDataAppGroupsPage", () => {+ it("manages assignments when the app is disabled", async () => {+ setup({ app: createMockDataApp({ enabled: false }) });++ await openGroupAssignmentPicker();++ // can assign groups+ await userEvent.click(screen.getByRole("option", { name: "Finches" }));+ await userEvent.click(screen.getByRole("button", { name: "Add" }));++ expect(+ await screen.findByRole("button", { name: "Remove Finches" }),+ ).toBeInTheDocument();++ // can unassign groups+ await userEvent.click(+ screen.getByRole("button", { name: "Remove Finches" }),+ );++ expect(+ await screen.findByText("No groups have access yet"),+ ).toBeInTheDocument();+ });++ it("shows member counts and filters invalid and assigned groups", async () => {+ setup({ groups: [{ id: OWLS_GROUP_ID, name: "Owls", member_count: 7 }] });++ expect(+ await screen.findByText("Manage access to Sales"),+ ).toBeInTheDocument();++ // member count should be visible+ expect(screen.getByText("7")).toBeInTheDocument();++ await openGroupAssignmentPicker();++ expect(+ screen.getByRole("option", { name: "All Users" }),+ ).toBeInTheDocument();++ expect(screen.getByRole("option", { name: "Finches" })).toBeInTheDocument();++ // assigned groups, admins and tenant groups must not be selectable+ for (const invalid of ["Owls", "Administrators", "Tenant"]) {+ expect(+ screen.queryByRole("option", { name: invalid }),+ ).not.toBeInTheDocument();+ }+ });++ it("batch-assign selected groups", async () => {+ setup();++ await openGroupAssignmentPicker();++ // assign these groups+ await userEvent.click(screen.getByRole("option", { name: "Finches" }));+ await userEvent.click(screen.getByRole("option", { name: "Owls" }));+ await userEvent.click(screen.getByRole("button", { name: "Add" }));++ await waitFor(() => {+ const requests = fetchMock.callHistory.calls(+ "path:/api/apps/sales/groups",+ { method: "POST" },+ );++ expect(+ requests.map(({ options }) => JSON.parse(String(options.body))),+ ).toEqual([{ group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] }]);+ });++ expect(+ await screen.findByRole("button", { name: "Remove Finches" }),+ ).toBeInTheDocument();+ });++ it("retries with the full selection if assigning group fails", async () => {+ setup({ failFirstAdd: true });+ await openGroupAssignmentPicker();++ await userEvent.click(screen.getByRole("option", { name: "Finches" }));+ await userEvent.click(screen.getByRole("option", { name: "Owls" }));++ const addGroups = () =>+ within(screen.getByTestId("data-app-groups-card")).getByRole("button", {+ name: "Add",+ });++ // first attempt should fail+ await userEvent.click(addGroups());+ expect(await screen.findByText("Failed to add groups")).toBeInTheDocument();++ expect(+ screen.queryByRole("button", { name: "Remove Finches" }),+ ).not.toBeInTheDocument();++ await userEvent.click(addGroups());++ // second retry attempt should pass+ expect(+ await screen.findByRole("button", { name: "Remove Finches" }),+ ).toBeInTheDocument();++ const requests = fetchMock.callHistory.calls(+ "path:/api/apps/sales/groups",+ { method: "POST" },+ );++ expect(+ requests.map(({ options }) => JSON.parse(String(options.body))),+ ).toEqual([+ { group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] },++ // second retry request should include the full selection+ { group_ids: [FINCHES_GROUP_ID, OWLS_GROUP_ID] },+ ]);+ });++ it("returns to the previous page after removing the last group", async () => {+ setup({+ groups: Array.from({ length: 26 }, (_, index) => ({+ id: index + 100,+ name: `Group ${index + 1}`,+ member_count: 0,+ })),+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Next page" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Remove Group 26" }),+ );++ expect(+ await screen.findByRole("button", { name: "Remove Group 1" }),+ ).toBeInTheDocument();++ expect(+ screen.queryByRole("button", { name: "Remove Group 26" }),+ ).not.toBeInTheDocument();+ });+});++async function openGroupAssignmentPicker() {+ await userEvent.click(+ await screen.findByRole("button", { name: "Add groups" }),+ );++ await waitFor(() =>+ expect(+ screen.getByRole("textbox", { name: "Search for groups to add" }),+ ).toBeEnabled(),+ );++ await userEvent.click(+ screen.getByRole("textbox", { name: "Search for groups to add" }),+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.cssnew file mode 100644index 00000000000..3e9c798f458--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.module.css@@ -0,0 +1,29 @@+.row {+ border: 1px solid var(--mb-color-border);+ border-radius: 0.5rem;+}++.row .pill {+ padding: 0.375rem 0.75rem;+ gap: 0.375rem;+ font-size: var(--mantine-font-size-md);+}++.row .pill[data-with-remove] {+ padding-inline-end: var(--mantine-spacing-sm);+}++.row[data-has-current-groups="true"] {+ border-radius: 0.5rem 0.5rem 0 0;+}++.row:focus-within {+ border-color: var(--mb-color-core-brand);+}++.row[data-has-current-groups="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/AddDataAppGroups/AddDataAppGroups.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.tsxnew file mode 100644index 00000000000..708c23a3f5f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/AddDataAppGroups/AddDataAppGroups.tsx@@ -0,0 +1,119 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { useListPermissionsGroupsQuery } from "metabase/api";+import {+ getGroupNameLocalized,+ isAdminGroup,+} from "metabase/common/utils/groups";+import { Alert, Button, Group, MultiSelect, Stack } from "metabase/ui";+import type { DataAppGroup } from "metabase-types/api";++import S from "./AddDataAppGroups.module.css";++type Props = {+ groups: DataAppGroup[];++ onCancel: () => void;+ onAddGroups: (groupIds: number[]) => Promise<boolean>;+};++export const AddDataAppGroups = ({ groups, onAddGroups, onCancel }: Props) => {+ const [selectedIds, setSelectedIds] = useState<string[]>([]);+ const [isSubmitting, setIsSubmitting] = useState(false);++ const groupsQuery = useListPermissionsGroupsQuery({ tenancy: "internal" });++ const selectableGroupOptions = useMemo(+ () =>+ groupsQuery.data+ ?.filter(+ (group) =>+ !group.is_tenant_group &&+ !isAdminGroup(group) &&+ !groups.some((assigned) => assigned.id === group.id),+ )+ .map((group) => ({+ value: String(group.id),+ label: getGroupNameLocalized(group),+ })),+ [groupsQuery.data, groups],+ );++ const handleSubmit = async () => {+ setIsSubmitting(true);++ try {+ const success = await onAddGroups(selectedIds.map(Number));++ if (success) {+ setSelectedIds([]);+ }+ } finally {+ setIsSubmitting(false);+ }+ };++ return (+ <Stack gap="md">+ <Group+ className={S.row}+ data-has-current-groups={groups.length > 0}+ mx={groups.length > 0 ? "-1px" : 0}+ mt={groups.length > 0 ? "-1px" : 0}+ p="0.5rem"+ pr="md"+ gap={0}+ align="center"+ wrap="nowrap"+ >+ <MultiSelect+ flex={1}+ miw={0}+ variant="unstyled"+ rightSection={null}+ classNames={{ pill: S.pill }}+ comboboxProps={{+ withinPortal: true,+ keepMounted: false,++ // Leave a gap beyond the surrounding row's padding and border.+ offset: 18,+ }}+ styles={MULTI_SELECT_STYLES}+ aria-label={t`Search for groups to add`}+ placeholder={t`Search for groups to add`}+ searchable+ maxValues={100}+ data={selectableGroupOptions}+ value={selectedIds}+ onChange={setSelectedIds}+ disabled={isSubmitting || groupsQuery.isLoading}+ />++ <Button+ variant="subtle"+ color="neutral"+ mr="sm"+ onClick={onCancel}+ disabled={isSubmitting}+ >{t`Cancel`}</Button>++ <Button+ variant={selectedIds.length > 0 ? "filled" : "default"}+ onClick={handleSubmit}+ loading={isSubmitting}+ disabled={!selectedIds.length}+ >{t`Add`}</Button>+ </Group>++ {groupsQuery.isError && (+ <Alert color="error">{t`Could not load groups`}</Alert>+ )}+ </Stack>+ );+};++const MULTI_SELECT_STYLES = {+ input: { background: "transparent", fontSize: "var(--mantine-font-size-lg)" },+};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 bd46c277ff1..f391c0c28cc 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@@ -70,6 +70,13 @@ export const DataAppActionsMenu = ({ app, canRemove = false }: Props) => {{t`View resources`}</Menu.Item>+ <Menu.Item+ component={Link}+ to={`/admin/settings/apps/${encodeURIComponent(app.name)}/groups`}+ >+ {t`Manage group 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 babfdebeead..3aa7bb048a5 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@@ -43,17 +43,26 @@ const confirmRemove = async () =>);describe("DataAppActionsMenu", () => {- it("links to the app's resources above the enable action", async () => {+ 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).toHaveLength(2);- expect(menuItems[0]).toHaveTextContent("View resources");- expect(menuItems[0]).toHaveAttribute("href", "/collection/9");- expect(menuItems[1]).toHaveTextContent("Disable");+ const [viewResource, manageAccess, disable] = menuItems;++ expect(viewResource).toHaveTextContent("View resources");+ expect(viewResource).toHaveAttribute("href", "/collection/9");++ expect(manageAccess).toHaveTextContent("Manage group access");+ expect(manageAccess).toHaveAttribute(+ "href",+ "/admin/settings/apps/sales/groups",+ );++ expect(disable).toHaveTextContent("Disable");});it("should show a toast when toggling enabled fails", async () => {diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.cssnew file mode 100644index 00000000000..922636c24d1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.module.css@@ -0,0 +1,28 @@+.groupListContent {+ display: flex;+ flex-direction: column;+ gap: var(--mantine-spacing-lg);+}++.groupListContent.overlappingGroupListContent {+ display: grid;+}++/**+ Overlap the group card and empty state, so the+ collapsing empty state does not add a second row+ when transitioning from and to empty states+ */+.overlappingGroupListContent > * {+ grid-area: 1 / 1;+}++.groupTable tbody tr:not(:last-child) {+ border-bottom: 1px solid var(--mb-color-border);+}++.removeGroupButton {+ display: flex;+ align-items: center;+ justify-content: center;+}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsxnew file mode 100644index 00000000000..4b0a1990ccc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppGroupList/DataAppGroupList.tsx@@ -0,0 +1,188 @@+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 { getGroupNameLocalized } from "metabase/common/utils/groups";+import Animation from "metabase/css/core/animation.module.css";+import {+ Box,+ Collapse,+ Flex,+ Icon,+ Stack,+ Text,+ UnstyledButton,+} from "metabase/ui";+import type { DataAppGroup } from "metabase-types/api";++import { AddDataAppGroups } from "../AddDataAppGroups/AddDataAppGroups";++import S from "./DataAppGroupList.module.css";++const PAGE_SIZE = 25;++type Props = {+ isAdding: boolean;+ groups: DataAppGroup[];++ onAddGroups: (groupIds: number[]) => Promise<boolean>;+ onCancelAdd: () => void;+ onRemoveGroup: (group: DataAppGroup) => Promise<boolean>;+};++export const DataAppGroupList = ({+ isAdding,+ groups,+ onAddGroups,+ onCancelAdd,+ onRemoveGroup,+}: Props) => {+ const { handleNextPage, handlePreviousPage, page, setPage } = usePagination();++ const lastPage = Math.max(0, Math.ceil(groups.length / PAGE_SIZE) - 1);++ // make sure user does not stay in an empty page if the+ // removed group is the last one in the page+ useEffect(() => {+ setPage((page) => Math.min(page, lastPage));+ }, [lastPage, setPage]);++ const visibleGroups = useMemo(+ () => groups.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE),+ [groups, page],+ );++ return (+ <Stack data-testid="group-management-sections" gap="lg">+ <Box+ className={cx(+ S.groupListContent,++ // transitions between empty state and group list content+ !isAdding && S.overlappingGroupListContent,+ )}+ >+ {(isAdding || groups.length > 0) && (+ <Box+ data-testid="data-app-groups-card"+ bd={groups.length > 0 ? "1px solid var(--mb-color-border)" : 0}+ bdrs="sm"+ bg="background-primary"+ style={{ overflow: "hidden" }}+ >+ {isAdding && (+ <AddDataAppGroups+ groups={groups}+ onAddGroups={onAddGroups}+ onCancel={onCancelAdd}+ />+ )}++ {groups.length > 0 && (+ <AdminContentTable+ className={cx(S.groupTable, Animation.fadeIn)}+ columnTitles={[t`Group name`, t`Members`, null]}+ >+ {visibleGroups.map((group) => (+ <GroupRow+ key={group.id}+ group={group}+ onRemove={onRemoveGroup}+ />+ ))}+ </AdminContentTable>+ )}++ {groups.length > PAGE_SIZE && (+ <Flex align="center" justify="flex-end" p="md">+ <PaginationControls+ page={page}+ pageSize={PAGE_SIZE}+ itemsLength={visibleGroups.length}+ total={groups.length}+ onNextPage={handleNextPage}+ onPreviousPage={handlePreviousPage}+ />+ </Flex>+ )}+ </Box>+ )}++ <Collapse+ in={groups.length === 0}+ transitionDuration={150}+ transitionTimingFunction="ease-out"+ >+ <DataAppGroupsEmptyState />+ </Collapse>+ </Box>+ </Stack>+ );+};++const DataAppGroupsEmptyState = () => (+ <Box+ data-testid="data-app-groups-empty-state"+ bg="background-secondary"+ bdrs="md"+ py="5rem"+ >+ <EmptyState+ title={t`No groups have access yet`}+ spacing="sm"+ illustrationElement={+ <img+ src={NoResults}+ alt={t`No results`}+ width={120}+ height={120}+ data-testid="data-app-groups-empty-state-icon"+ />+ }+ />+ </Box>+);++const GroupRow = ({+ group,+ onRemove,+}: {+ group: DataAppGroup;+ onRemove: (group: DataAppGroup) => void;+}) => {+ const name = getGroupNameLocalized(group);++ return (+ <tr>+ <td>+ <Text fw={700}>{name}</Text>+ </td>++ <td>{group.member_count}</td>++ <Box component="td" w="1%" style={{ whiteSpace: "nowrap" }}>+ <Flex+ data-testid="data-app-group-actions"+ align="center"+ justify="flex-end"+ gap="lg"+ wrap="nowrap"+ style={{ minWidth: "max-content" }}+ >+ <UnstyledButton+ className={S.removeGroupButton}+ aria-label={t`Remove ${name}`}+ onClick={() => onRemove(group)}+ >+ <Icon name="close" c="text-disabled" size={16} />+ </UnstyledButton>+ </Flex>+ </Box>+ </tr>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsxindex ae41fea51f5..6464b8a1e9b 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 { ManageDataAppGroupsPage } from "./admin/ManageDataAppGroupsPage";import { ManageDataAppsPage } from "./admin/ManageDataAppsPage";import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";import { getRoutes, registerDataAppsPagePrefetch } 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.ManageDataAppGroupsPage = ManageDataAppGroupsPage;PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;registerDataAppsPagePrefetch();}diff --git a/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.tsindex 85e011b7253..9512e955a4f 100644--- a/frontend/src/metabase-types/api/data-app.ts+++ b/frontend/src/metabase-types/api/data-app.ts@@ -26,8 +26,6 @@ export interface DataApp {enabled: boolean;/** The collection that contains this app's saved questions and models. */resource_collection_id: number;- /** 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[];/**@@ -58,3 +56,19 @@ export interface SetDataAppEnabledRequest {name: string;enabled: boolean;}++export interface DataAppGroup {+ id: number;+ name: string;+ member_count: number;+}++export interface AddDataAppGroupsRequest {+ name: string;+ group_ids: number[];+}++export interface RemoveDataAppGroupRequest {+ name: string;+ group_id: number;+}diff --git a/frontend/src/metabase-types/api/mocks/data-app.ts b/frontend/src/metabase-types/api/mocks/data-app.tsindex 7a386d0b6ba..61ef6177ea9 100644--- a/frontend/src/metabase-types/api/mocks/data-app.ts+++ b/frontend/src/metabase-types/api/mocks/data-app.ts@@ -11,7 +11,6 @@ export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({bundle_path: "dist/index.js",enabled: true,resource_collection_id: 1,- permission_group_id: 1,table_ids: [],allowed_hosts: [],bundle_hash: "abc123",diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsxindex 1ce48b6e2da..8e8f6ef3037 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx@@ -22,3 +22,7 @@ export function DataAppsManagePage() {return <PLUGIN_DATA_APPS.ManageDataAppsPage />;}++export function DataAppGroupsManagePage() {+ return <PLUGIN_DATA_APPS.ManageDataAppGroupsPage />;+}diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsxindex 6a9fdd6cf89..8eb2eae1c3a 100644--- a/frontend/src/metabase/admin/settingsRoutes.tsx+++ b/frontend/src/metabase/admin/settingsRoutes.tsx@@ -138,6 +138,13 @@ const dataAppsManage = () =>/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage").then(({ DataAppsManagePage }) => ({ Component: DataAppsManagePage }));+const dataAppGroupsManage = () =>+ import(+ /* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DataAppsSettingsPage"+ ).then(({ DataAppGroupsManagePage }) => ({+ Component: DataAppGroupsManagePage,+ }));+const uploadSettings = () =>import(/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/UploadSettingsPage"@@ -246,6 +253,7 @@ export const getSettingsRoutes = (element={<IsAdmin />}><Route index lazy={dataAppsManage} />+ <Route path=":slug/groups" lazy={dataAppGroupsManage} /></Route><Route path="uploads" lazy={uploadSettings} /><Routediff --git a/frontend/src/metabase/plugins/oss/data-apps.ts b/frontend/src/metabase/plugins/oss/data-apps.tsindex 8a104ef466a..c88a360c649 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;+ ManageDataAppGroupsPage: ComponentType;MainNavbarSection: ComponentType<{ onItemSelect: () => void }>;};@@ -15,6 +16,7 @@ const getDefaultPluginDataApps = (): DataAppsPlugin => ({isEnabled: false,getRoutes: () => null,ManageDataAppsPage: PluginPlaceholder,+ ManageDataAppGroupsPage: PluginPlaceholder,MainNavbarSection: PluginPlaceholder,});diff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.cljindex b265a49d8e4..25a76501171 100644--- a/mage/src/mage/modules.clj+++ b/mage/src/mage/modules.clj@@ -150,6 +150,7 @@explorations.contextual-interestingnesscustom-viz-plugindashboards+ data-appsdocumentsapi.eid-translationembeddingdiff --git a/resources/migrations/065/20260916_replace_legacy_data_app_access.yaml b/resources/migrations/065/20260916_replace_legacy_data_app_access.yamlnew file mode 100644index 00000000000..b8eae1d6013--- /dev/null+++ b/resources/migrations/065/20260916_replace_legacy_data_app_access.yaml@@ -0,0 +1,142 @@+databaseChangeLog:+ - changeSet:+ id: v65.2026-09-16T00:00:00+ author: poom+ comment: Assign existing permission groups to data apps+ changes:+ - createTable:+ tableName: data_app_group_assignment+ remarks: Permission group assignments for data apps+ columns:+ - column:+ name: id+ type: int+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ primaryKeyName: pk_data_app_group_assignment+ - column:+ name: data_app_id+ remarks: Data app receiving access through the assigned group+ type: int+ constraints:+ nullable: false+ - column:+ name: permission_group_id+ remarks: Permission group assigned to the data app+ type: int+ constraints:+ nullable: false++ - changeSet:+ id: v65.2026-09-16T00:00:01+ author: poom+ comment: Prevent duplicate data app group assignments+ changes:+ - addUniqueConstraint:+ tableName: data_app_group_assignment+ columnNames: data_app_id, permission_group_id+ constraintName: uq_data_app_group_assignment++ - changeSet:+ id: v65.2026-09-16T00:00:02+ author: poom+ comment: Index data app assignments by permission group+ changes:+ - createIndex:+ tableName: data_app_group_assignment+ indexName: idx_data_app_group_assignment_group+ columns:+ - column:+ name: permission_group_id++ - changeSet:+ id: v65.2026-09-16T00:00:03+ author: poom+ comment: Remove group assignments when a data app is deleted+ changes:+ - addForeignKeyConstraint:+ baseTableName: data_app_group_assignment+ baseColumnNames: data_app_id+ referencedTableName: data_app+ referencedColumnNames: id+ constraintName: fk_data_app_group_assignment_app+ onDelete: CASCADE++ - changeSet:+ id: v65.2026-09-16T00:00:04+ author: poom+ comment: Remove app assignments when a permission group is deleted+ changes:+ - addForeignKeyConstraint:+ baseTableName: data_app_group_assignment+ baseColumnNames: permission_group_id+ referencedTableName: permissions_group+ referencedColumnNames: id+ constraintName: fk_data_app_group_assignment_group+ onDelete: CASCADE++ - changeSet:+ id: v65.2026-09-16T00:00:05+ author: poom+ comment: Remove generated groups and individual assignments from older data apps implementation+ changes:+ - delete:+ tableName: permissions_group+ where: is_data_app_group = true+ rollback: [] # Deleted groups and assignments are not restored.++ - changeSet:+ id: v65.2026-09-16T00:00:06+ author: poom+ comment: Remove the generated data app group foreign key from older implementation+ changes:+ - dropForeignKeyConstraint:+ baseTableName: data_app+ constraintName: fk_data_app_permission_group_id+ rollback:+ - 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: v65.2026-09-16T00:00:07+ author: poom+ comment: Remove the generated data app group reference from older implementation+ changes:+ - dropColumn:+ tableName: data_app+ columnName: permission_group_id+ rollback:+ - addColumn:+ tableName: data_app+ columns:+ - column:+ name: permission_group_id+ type: int+ constraints:+ nullable: true++ - changeSet:+ id: v65.2026-09-16T00:00:08+ author: poom+ comment: Remove the generated data app group marker from older implementation+ changes:+ - dropColumn:+ tableName: permissions_group+ columnName: is_data_app_group+ rollback:+ - addColumn:+ tableName: permissions_group+ columns:+ - column:+ name: is_data_app_group+ type: ${boolean.type}+ defaultValueBoolean: false+ constraints:+ nullable: falsediff --git a/src/metabase/data_apps/core.clj b/src/metabase/data_apps/core.cljnew file mode 100644index 00000000000..214e67d7ee5--- /dev/null+++ b/src/metabase/data_apps/core.clj@@ -0,0 +1,9 @@+(ns metabase.data-apps.core+ (:require+ [metabase.premium-features.core :refer [defenterprise]]))++(defenterprise check-data-app-access!+ "Authorize the data app before serving its HTML entry point."+ metabase-enterprise.data-apps.core+ [_request]+ nil)diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex c66e7bb12ca..3fb1f8d0f40 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -37,6 +37,7 @@:model/ContentTranslation metabase.content-translation.models:model/CustomVizPlugin metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin:model/DataApp metabase-enterprise.data-apps.models.data-app+ :model/DataAppGroupAssignment metabase-enterprise.data-apps.models.data-app-group-assignment:model/Dashboard metabase.dashboards.models.dashboard:model/DashboardBookmark metabase.bookmarks.models.bookmark:model/DashboardCard metabase.dashboards.models.dashboard-carddiff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.cljindex 75b5c272739..e2b891270c2 100644--- a/src/metabase/permissions/core.clj+++ b/src/metabase/permissions/core.clj@@ -2,6 +2,7 @@"`permissions` module API namespace."(:require[metabase.permissions.data-access-token]+ [metabase.permissions.db][metabase.permissions.models.application-permissions-revision][metabase.permissions.models.collection-permission-graph-revision][metabase.permissions.models.collection.graph]@@ -37,14 +38,15 @@metabase.permissions.validation/keep-me)(p/import-vars+ [metabase.permissions.db+ group-tenant-flags+ groups-by-ids][metabase.permissions.models.data-permissionsat-least-as-permissive?batch-delete-permissions!batch-insert-permissions!data-app-collection-idsdata-app-collection?- data-app-group-ids- data-app-view-data-permission-leveldisable-perms-cachedownload-perms-levelfull-database-permission-for-user@@ -109,6 +111,7 @@set-has-full-permissions-for-set?set-has-full-permissions?][metabase.permissions.models.permissions-group+ group-display-namenon-magic-groupsall-users-magic-group-type][metabase.permissions.models.permissions-group-membershipdiff --git a/src/metabase/permissions/db.clj b/src/metabase/permissions/db.cljindex 432e8da7cda..cf761ffa325 100644--- a/src/metabase/permissions/db.clj+++ b/src/metabase/permissions/db.clj@@ -347,6 +347,15 @@[group-ids :- [:set ms/PositiveInt]](t2/select-pk->fn :is_tenant_group [:model/PermissionsGroup :id :is_tenant_group] :id [:in group-ids]))+(mu/defn groups-by-ids+ "The ID, name, and magic type of the requested groups, ordered by name."+ [group-ids :- [:set ms/PositiveInt]]+ (if (seq group-ids)+ (t2/select [:model/PermissionsGroup :id :name :magic_group_type]+ :id [:in group-ids]+ {:order-by [:%lower.name]})+ []))+(mu/defn group-members"The active Users in the PermissionsGroups with `group-ids`. When `include-group-manager?` is true each row alsocarries the membership's `:is_group_manager` flag."diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.cljindex 8f4756cc07d..696803f2c55 100644--- a/src/metabase/permissions/models/data_permissions.clj+++ b/src/metabase/permissions/models/data_permissions.clj@@ -1329,19 +1329,6 @@[_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- []- #{})-(defenterprise data-app-collection-ids"Ids of the collections data apps own, which hold the copies an app runs. OSS has none."metabase-enterprise.data-apps.models.data-app@@ -1424,7 +1411,6 @@(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]@@ -1432,7 +1418,6 @@(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;@@ -1467,10 +1452,6 @@: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/models/permissions_group.clj b/src/metabase/permissions/models/permissions_group.cljindex 2db256a2250..ced4ce28e3b 100644--- a/src/metabase/permissions/models/permissions_group.clj+++ b/src/metabase/permissions/models/permissions_group.clj@@ -74,6 +74,13 @@"The magic-group type of the \"Data Analysts\" magic group.""data-analyst")+(defn group-display-name+ "The group's display name, with internal membership explicit when tenants are enabled."+ [{:keys [magic_group_type name]} using-tenants?]+ (if (and (= magic_group_type all-users-magic-group-type) using-tenants?)+ "All internal users"+ name))+(def ^{:arglists '([])} data-analyst"Fetch the `Data Analysts` permissions group"(magic-group data-analyst-magic-group-type))diff --git a/src/metabase/permissions/schema.clj b/src/metabase/permissions/schema.cljindex 1b7dd2cc3b4..756ed39ce93 100644--- a/src/metabase/permissions/schema.clj+++ b/src/metabase/permissions/schema.clj@@ -173,8 +173,7 @@[: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]]])+ [:is_tenant_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 0be7199c8ed..54bb71b74cf 100644--- a/src/metabase/permissions_rest/api.clj+++ b/src/metabase/permissions_rest/api.clj@@ -128,12 +128,8 @@Actually changing the name brings a whole host of problems, and we very rarely actually present the names ofPermissions Groups to users. (These are the only endpoints that reveal them.) So I think it makes sense to justadjust them here."- [{:keys [magic_group_type] :as group} using-tenants?]- (update group :name (fn [n]- (if (and (= magic_group_type perms/all-users-magic-group-type)- using-tenants?)- "All internal users"- n))))+ [group using-tenants?]+ (assoc group :name (perms/group-display-name group using-tenants?)))(defn- maybe-fix-names"See [[maybe-fix-name]] for details."@@ -170,7 +166,6 @@{:tenancy tenancy:manager-user-id manager-user-id: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))))@@ -292,12 +287,6 @@api/*current-user-id*):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 (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;;@@ -313,9 +302,6 @@(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 285403f0350..01e96464ada 100644--- a/src/metabase/permissions_rest/data_permissions/graph.clj+++ b/src/metabase/permissions_rest/data_permissions/graph.clj@@ -638,12 +638,6 @@(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."@@ -655,8 +649,7 @@(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)- (reconcile-data-app-permissions! (into #{} (mapcat keys) (vals group-updates)))))))+ (delete-gtaps-if-needed-after-permissions-change! group-updates)))));; The following arity is provided solely for convenience for tests/REPL usage([ks :- [:vector [:or :int :string :keyword]]diff --git a/src/metabase/permissions_rest/db.clj b/src/metabase/permissions_rest/db.cljindex 2e79177dc6b..f1ef3c4174c 100644--- a/src/metabase/permissions_rest/db.clj+++ b/src/metabase/permissions_rest/db.clj@@ -38,20 +38,17 @@`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 magicgroup unless it has at least one active member. `tenants-enabled?` false also excludes tenant groups outright,- independent of `tenancy`. `exclude-data-app-groups?` excludes groups that a data app manages."+ independent of `tenancy`."[limit :- [:maybe ms/PositiveInt]offset :- [:maybe ms/IntGreaterThanOrEqualToZero]- {:keys [tenancy manager-user-id tenants-enabled? advanced-permissions-enabled?- exclude-data-app-groups?]}+ {:keys [tenancy manager-user-id tenants-enabled? advanced-permissions-enabled?]}:- [: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]- [:exclude-data-app-groups? {:optional true} :boolean]]]+ [:advanced-permissions-enabled? {: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? (data-analyst-visibility-clause))]where (case tenancy@@ -75,11 +72,6 @@[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@@ -118,11 +110,6 @@[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/server/routes/index.clj b/src/metabase/server/routes/index.cljindex 5cf0c73941e..8be197c56cf 100644--- a/src/metabase/server/routes/index.clj+++ b/src/metabase/server/routes/index.clj@@ -8,6 +8,7 @@[hiccup.util][metabase.appearance.core :as appearance][metabase.config.core :as config]+ [metabase.data-apps.core :as data-apps][metabase.initialization-status.core :as init-status][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting]@@ -155,4 +156,10 @@(cond(not (premium-features/enable-data-apps?)) (respond nil)(nil? (:metabase-user-id request)) (respond (login-redirect request))- :else (data-app-shell request respond raise)))+ :else (if-let [error (try+ (data-apps/check-data-app-access! request)+ nil+ (catch Throwable e+ e))]+ (raise error)+ (data-app-shell request respond raise))))diff --git a/src/metabase/sso/common.clj b/src/metabase/sso/common.cljindex 5fc25e878e4..22072017f7c 100644--- a/src/metabase/sso/common.clj+++ b/src/metabase/sso/common.clj@@ -10,9 +10,8 @@(defn- excluded-group-ids[]- (into #{(u/the-id (perms/all-users-group))- (u/the-id (perms/all-external-users-group))}- (perms/data-app-group-ids)))+ #{(u/the-id (perms/all-users-group))+ (u/the-id (perms/all-external-users-group))})(defn- sync-group-memberships*![user-or-id to-remove to-add]diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.cljindex cbb782de655..e4d8f979e42 100644--- a/test/metabase/app_db/custom_migrations_test.clj+++ b/test/metabase/app_db/custom_migrations_test.clj@@ -3119,7 +3119,7 @@(is (= 21 (count (t2/select-one-fn :entity_id :collection :id collection-id))))))))))(deftest delete-data-app-drafts-test- (testing "v65.2026-10-07T00:00:00: draft rows go, with their groups and the collections they left empty"+ (testing "v65.2026-10-07T00:00:00: draft rows go with their assignments and empty collections"(impl/test-migrations ["v65.2026-10-07T00:00:00"] [migrate!](let [insert-collection! (fn [name](t2/insert-returning-pk! :collection {:name name@@ -3128,29 +3128,25 @@:namespace "data-apps":entity_id (u/generate-nano-id):created_at :%now}))- insert-group! (fn [slug]- (t2/insert-returning-pk! :permissions_group {:name (str "Data App: " slug)- :entity_id (u/generate-nano-id)- :is_data_app_group true}))- insert-app! (fn [slug draft? collection-id group-id]+ insert-app! (fn [slug draft? collection-id](t2/insert-returning-pk! :data_app {:name slug:display_name slug:bundle_path "dist/index.js":entity_id (u/generate-nano-id):draft draft?:resource_collection_id collection-id- :permission_group_id group-id:created_at :%now:updated_at :%now}))empty-coll (insert-collection! "empty")used-coll (insert-collection! "used")kept-coll (insert-collection! "kept")- empty-group (insert-group! "empty-draft")- used-group (insert-group! "used-draft")- kept-group (insert-group! "real")- empty-draft (insert-app! "empty-draft" true empty-coll empty-group)- used-draft (insert-app! "used-draft" true used-coll used-group)- real-app (insert-app! "real" false kept-coll kept-group)]+ shared-group (t2/insert-returning-pk! :permissions_group {:name "App viewers"+ :entity_id (u/generate-nano-id)})+ empty-draft (insert-app! "empty-draft" true empty-coll)+ used-draft (insert-app! "used-draft" true used-coll)+ real-app (insert-app! "real" false kept-coll)]+ (doseq [app-id [empty-draft used-draft real-app]]+ (t2/insert! :data_app_group_assignment {:data_app_id app-id :permission_group_id shared-group}))(t2/insert! :permissions {:object (str "/collection/" empty-coll "/read/") :group_id 1 :collection_id empty-coll});; something was put in the used draft's collection: a child collection here, cards and actions count the same(t2/insert! :collection {:name "Inside"@@ -3160,10 +3156,10 @@:entity_id (u/generate-nano-id):created_at :%now})(migrate!)- (testing "every draft row is gone, with its group"+ (testing "every draft row is gone, with its assignments"(is (not (t2/exists? :data_app :id empty-draft)))(is (not (t2/exists? :data_app :id used-draft)))- (is (not (t2/exists? :permissions_group :id [:in [empty-group used-group]]))))+ (is (not (t2/exists? :data_app_group_assignment :data_app_id [:in [empty-draft used-draft]]))))(testing "the empty collection went with its draft, grants included"(is (not (t2/exists? :collection :id empty-coll)))(is (not (t2/exists? :permissions :collection_id empty-coll))))@@ -3172,4 +3168,6 @@(testing "an app that is not a draft is untouched"(is (t2/exists? :data_app :id real-app))(is (t2/exists? :collection :id kept-coll))- (is (t2/exists? :permissions_group :id kept-group)))))))+ (is (t2/exists? :data_app_group_assignment :data_app_id real-app :permission_group_id shared-group)))+ (testing "the shared permission group survives draft deletion"+ (is (t2/exists? :permissions_group :id shared-group)))))))diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex a8261b402c6..d5a9b5acf8d 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -3767,6 +3767,7 @@(impl/test-migrations ["v65.2026-10-06T16:00:00" "v65.2026-10-06T16:00:02"] [migrate!](migrate!)(is (not (t2/exists? :collection :entity_id "librarylibrarydashbrd"))))))+(deftest metabot-message-finish-reason-column-test(testing "v65.2026-10-08T00:00:00: metabot_message gains a nullable finish_reason, and finished is left alone"(impl/test-migrations ["v65.2026-10-08T00:00:00"] [migrate!]@@ -3850,3 +3851,48 @@(migrate! :down 64)(is (not (contains? (message) :context_window_full)))(is (true? (:finished (message)))))))))++(deftest data-app-group-assignment-migration-test+ (impl/test-migrations ["v65.2026-09-16T00:00:00" "v65.2026-09-16T00:00:08"] [migrate!]+ (let [legacy-group (t2/insert-returning-pk! :permissions_group+ {:name "Data App: birds"+ :is_data_app_group true+ :entity_id "legacy-app-group"})+ ordinary-group (t2/insert-returning-pk! :permissions_group+ {:name "Finches" :entity_id "ordinary-group"})+ user-id (t2/insert-returning-pk! :core_user+ {:email "[email protected]"+ :entity_id "migration-finch"+ :date_joined :%now+ :password "password"+ :password_salt "salt"})+ app-id (t2/insert-returning-pk! :data_app+ {:name "birds"+ :display_name "Birds"+ :bundle_path "birds.js"+ :permission_group_id legacy-group+ :created_at :%now+ :updated_at :%now})]+ (t2/insert! :permissions_group_membership {:group_id legacy-group :user_id user-id})+ (t2/insert! :permissions {:group_id legacy-group :object "/collection/999/read/"})+ (testing "migration removes legacy groups and their access"+ (migrate!)+ (is (not (t2/exists? :permissions_group :id legacy-group)))+ (is (not (t2/exists? :permissions_group_membership :group_id legacy-group)))+ (is (not (t2/exists? :permissions :group_id legacy-group))))+ (testing "migration preserves apps and ordinary groups without converting legacy access"+ (is (t2/exists? :permissions_group :id ordinary-group))+ (is (t2/exists? :data_app :id app-id))+ (is (empty? (t2/select :data_app_group_assignment))))+ (testing "migration removes the obsolete columns"+ (is (not (contains? (t2/select-one :data_app :id app-id) :permission_group_id)))+ (is (not (contains? (t2/select-one :permissions_group :id ordinary-group) :is_data_app_group))))+ (testing "rollback restores the old columns without deleting apps or ordinary groups"+ (migrate! :down 64)+ (is (contains? (t2/select-one :data_app :id app-id) :permission_group_id))+ (is (false? (:is_data_app_group (t2/select-one :permissions_group :id ordinary-group)))))+ (testing "the migration can run again after rollback"+ (migrate!)+ (is (t2/exists? :data_app :id app-id))+ (is (t2/exists? :permissions_group :id ordinary-group))+ (is (empty? (t2/select :data_app_group_assignment)))))))diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.cljindex 9eb39099f0f..9b4f61f2e15 100644--- a/test/metabase/cmd/copy_test.clj+++ b/test/metabase/cmd/copy_test.clj@@ -89,6 +89,7 @@:model/ContentTranslation:model/DashboardFavorite:model/DataApp+ :model/DataAppGroupAssignment:model/DataComplexityScore:model/DatabaseRouter:model/Dependencydiff --git a/test/metabase/permissions/models/permissions_group_test.clj b/test/metabase/permissions/models/permissions_group_test.cljindex 379b1e6d68c..27205a9a609 100644--- a/test/metabase/permissions/models/permissions_group_test.clj+++ b/test/metabase/permissions/models/permissions_group_test.clj@@ -16,6 +16,11 @@(use-fixtures :once (fixtures/initialize :test-users))+(deftest ^:parallel group-display-name-preserves-stored-name-test+ (let [group {:magic_group_type perms-group/all-users-magic-group-type :name "Stored group name"}]+ (is (= "Stored group name" (perms-group/group-display-name group false)))+ (is (= "All internal users" (perms-group/group-display-name group true)))))+(deftest admin-root-entry-test(testing "Check that the root entry for Admin was created"(is (t2/exists? :model/Permissions :group_id (u/the-id (perms-group/admin)), :object "/"))))diff --git a/test/metabase/server/routes_test.clj b/test/metabase/server/routes_test.cljindex 832707f7198..8cac01e9667 100644--- a/test/metabase/server/routes_test.clj+++ b/test/metabase/server/routes_test.clj@@ -2,6 +2,8 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [metabase.data-apps.core :as data-apps]+ [metabase.premium-features.core :as premium-features][metabase.server.routes.index :as index][metabase.test :as mt][metabase.test.http-client :as client]))@@ -37,9 +39,9 @@(testing "the /embed/apps/:name entrypoint is served only with :data-apps; without it itresponds nil so routing falls through to the generic embed handler — exactly as if dataapps did not exist"- ;; Stub the raw shell so the test needs no built frontend HTML; the feature gate lives in- ;; `index/data-app` itself, which is what we're exercising here.- (with-redefs [index/data-app-shell (fn [_req respond _raise] (respond {:status 200 :body "DATA-APP"}))]+ ;; Stub authorization and HTML rendering to isolate the feature gate.+ (with-redefs [data-apps/check-data-app-access! (constantly nil)+ index/data-app-shell (fn [_req respond _raise] (respond {:status 200 :body "DATA-APP"}))](let [request {:uri "/embed/apps/sales" :metabase-user-id (mt/user->id :rasta)}];; `enable-data-apps?` also requires the EE code to be present (`config/ee-available?`), so the;; served path exists only on EE; on OSS the entrypoint always falls through.@@ -123,3 +125,14 @@(let [response (get-static-asset 200 {"if-modified-since" held})](is (= 200 (:status response)))(is (not (str/blank? (body-text (:body response)))))))))))++(deftest data-app-entrypoint-raises-access-errors-test+ (let [error (ex-info "Access denied" {:status-code 403})+ callbacks (atom [])]+ (with-redefs [premium-features/enable-data-apps? (constantly true)+ data-apps/check-data-app-access! (fn [_request] (throw error))+ index/data-app-shell (fn [& _args] (swap! callbacks conj :shell))]+ (index/data-app {:metabase-user-id 1}+ (fn [response] (swap! callbacks conj [:respond response]))+ (fn [error] (swap! callbacks conj [:raise error]))))+ (is (= [[:raise error]] @callbacks))))