Skip to content

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

Show missing data access warnings for assigned data app groups (#83083)

Phoomparin Manoae1a3f320688
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 83f2fbb32ba..77590d7d155 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3791,6 +3791,7 @@
:model-imports #{:model/Action
:model/Card
:model/Collection
+ :model/DataPermissions
:model/Database
:model/Field
:model/Permissions
diff --git a/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.ts b/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.ts
new file mode 100644
index 00000000000..418ce86e8c4
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/group-access-warnings.cy.spec.ts
@@ -0,0 +1,113 @@
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { ALL_USERS_GROUP_ID } from "e2e/support/cypress_sample_instance_data";
+import type { GroupInfo } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+const APP_NAME = "good";
+
+const GROUP_NAME = "Finches";
+const GROUP_MATCHER = new RegExp(GROUP_NAME);
+
+const DATA_ACCESS_PERMISSION_INDEX = 0;
+
+describe("scenarios > data apps > group access warnings (EMB-2416)", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ H.pullExampleDataApps({
+ goodAppCards: [
+ H.dataAppRepresentations.card({
+ entityId: "warningsOrdersCard000",
+ name: "Orders",
+ type: "question",
+ collection: "goodAppCollection0000",
+ table: ["Sample Database", "PUBLIC", "ORDERS"],
+ }),
+ ],
+ });
+
+ cy.request<GroupInfo>("POST", "/api/permissions/group", {
+ name: GROUP_NAME,
+ })
+ .its("body")
+ .as("group");
+
+ H.blockUserGroupPermissions(ALL_USERS_GROUP_ID);
+ cy.get<GroupInfo>("@group").then(({ id }) =>
+ H.blockUserGroupPermissions(id),
+ );
+ });
+
+ it("shows missing table access after assignment and clears it after granting data permissions", () => {
+ cy.visit(`/admin/settings/apps/${APP_NAME}/groups`);
+
+ H.main().findByText("No groups have access yet").should("be.visible");
+
+ H.main().findByRole("button", { name: "Add groups" }).click();
+ H.main()
+ .findByRole("textbox", { name: "Search for groups to add" })
+ .click();
+
+ cy.findByRole("option", { name: GROUP_NAME }).click();
+ cy.findByTestId("data-app-groups-card")
+ .findByRole("button", { name: "Add" })
+ .click();
+
+ cy.log("some table accesses are missing initially");
+ H.main()
+ .findByRole("row", { name: GROUP_MATCHER })
+ .findByRole("button", { name: "Missing data access" })
+ .realHover();
+
+ cy.log("database and table should be visible in card");
+ cy.findByTestId("data-access-warning-popover").within(() => {
+ cy.findByText(
+ `${GROUP_NAME} doesn’t have permission to view these tables used in this app:`,
+ ).should("be.visible");
+
+ cy.findByRole("link", { name: "Sample Database" }).should("be.visible");
+
+ cy.findByRole("link", { name: "Orders" }).should("be.visible").click();
+ });
+
+ cy.log("orders table link navigates to the table permission page");
+ cy.location("pathname")
+ .should("include", `/admin/permissions/data/database/${SAMPLE_DB_ID}/`)
+ .and("include", `/table/${ORDERS_ID}`);
+
+ H.assertPermissionForItem(
+ GROUP_NAME,
+ DATA_ACCESS_PERMISSION_INDEX,
+ "Blocked",
+ );
+
+ cy.log("grant access to the table");
+ H.modifyPermission(GROUP_NAME, DATA_ACCESS_PERMISSION_INDEX, "Can view");
+ H.savePermissions();
+
+ cy.intercept("GET", `/api/apps/${APP_NAME}/group-permission-warnings`).as(
+ "groupWarnings",
+ );
+
+ cy.go("back");
+ cy.location("pathname").should(
+ "equal",
+ `/admin/settings/apps/${APP_NAME}/groups`,
+ );
+
+ cy.log("group warnings should be gone");
+ cy.wait("@groupWarnings").its("response.body").should("deep.equal", []);
+
+ cy.log("group warnings should not show in the ui");
+ H.main()
+ .findByRole("row", { name: GROUP_MATCHER })
+ .should("be.visible")
+ .findByRole("button", { name: "Missing data access" })
+ .should("not.exist");
+ });
+});
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
index f221cd166e6..557c4c9b405 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
@@ -333,6 +333,25 @@
(api/check-superuser)
(data-app.resource-serialization/serialize-resources collection queries actions))
+(def ^:private GroupPermissionWarning
+ [:map
+ [:group_id ms/PositiveInt]
+ [:missing_tables
+ [:sequential
+ [:map
+ [:id ms/PositiveInt]
+ [:name :string]
+ [:schema [:maybe :string]]
+ [:database_id ms/PositiveInt]
+ [:database_name :string]]]]])
+
+(api.macros/defendpoint :get ["/:slug/group-permission-warnings" :slug slug-regex]
+ :- [:sequential GroupPermissionWarning]
+ "Return missing table access for groups already assigned to this app."
+ [{:keys [slug]} :- [:map {:closed true} [:slug ms/NonBlankString]]]
+ (api/check-superuser)
+ (data-app.group-access/permission-warnings (api/check-404 (data-apps.db/data-app-by-slug slug))))
+
(def ^:private AssignedGroup
[:map
[:id ms/PositiveInt]
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
index ae2e081232c..34988055ee1 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj
@@ -259,3 +259,26 @@
"Remove one group assignment."
[app-id group-id]
(t2/delete! :model/DataAppGroupAssignment :data_app_id app-id :permission_group_id group-id))
+
+(defn permissions-for-warnings
+ "View-data permission rows for the warning tables and their databases."
+ [group-ids database-ids table-ids]
+ (t2/select [:model/DataPermissions :group_id :db_id :perm_type :table_id :perm_value]
+ :group_id [:in group-ids]
+ :db_id [:in database-ids]
+ :perm_type :perms/view-data
+ {:where [:or [:in :table_id table-ids] [:= :table_id nil]]}))
+
+(defn table-details
+ "Names and database details for the active tables in `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 [[(t2/table-name :model/Database) :d] [:= :d.id :t.db_id]]
+ :where [:and [:in :t.id table-ids] [:= :t.active true]]
+ :order-by [[:d.name :asc] [:t.schema :asc] [:t.display_name :asc]]}))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj b/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj
index 0725686ba0c..a602fa72e0c 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/group_access.clj
@@ -55,3 +55,36 @@
data-apps.db/resource-collection)]
(perms/revoke-collection-permissions! group-id collection)))))
nil)
+
+(defn- group-has-table-access?
+ [{:keys [permissions]} group-id {table-id :id database-id :database_id}]
+ (some (fn [{permission-table-id :table_id value :perm_value}]
+ (and (or (nil? permission-table-id) (= permission-table-id table-id))
+ (= value :unrestricted)))
+ (get permissions [group-id database-id :perms/view-data])))
+
+(defn- group-table-access
+ [group-ids tables]
+ (let [table-ids (mapv :id tables)
+ database-ids (into #{} (map :database_id) tables)]
+ (when (seq tables)
+ {:permissions (group-by (juxt :group_id :db_id :perm_type)
+ (data-apps.db/permissions-for-warnings group-ids database-ids table-ids))})))
+
+(defn permission-warnings
+ "Missing table access for assigned groups, including access inherited from All Users."
+ [{app-id :id table-ids :table_ids}]
+ (let [assigned-ids (mapv :permission_group_id (data-apps.db/app-assignments [app-id]))]
+ (if (and (seq assigned-ids) (seq table-ids))
+ (let [tables (data-apps.db/table-details table-ids)
+ all-users-id (:id (perms/all-users-group))
+ access (group-table-access (conj (set assigned-ids) all-users-id) tables)]
+ (into []
+ (keep (fn [group-id]
+ (let [missing (filterv #(not (or (group-has-table-access? access group-id %)
+ (group-has-table-access? access all-users-id %)))
+ tables)]
+ (when (seq missing)
+ {:group_id group-id :missing_tables missing}))))
+ assigned-ids))
+ [])))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj
new file mode 100644
index 00000000000..613c889da18
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/group_access_warnings_test.clj
@@ -0,0 +1,211 @@
+(ns metabase-enterprise.data-apps.group-access-warnings-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.group-access :as group-access]
+ [metabase.permissions-rest.data-permissions.graph :as data-perms.graph]
+ [metabase.permissions.core :as perms]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(deftest group-permission-warnings-exclude-inactive-tables-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders) (mt/id :categories)]}
+ :model/PermissionsGroup group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (group-access/add-groups! app [(:id group)])
+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:active false}
+ (mt/with-temp-vals-in-db :model/Table (mt/id :orders) {:visibility_type :hidden}
+ ;; exclude inactive tables, but keep active visible and hidden tables.
+ ;; permissions editor also follow this filtering.
+ (is (=? [{:group_id (:id group)
+ :missing_tables [{:id (mt/id :categories)} {:id (mt/id :orders)}]}]
+ (group-access/permission-warnings app)))))))))
+
+(deftest group-permission-warnings-ignore-apps-with-only-inactive-tables-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues)]}
+ :model/PermissionsGroup group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (group-access/add-groups! app [(:id group)])
+ ; if data apps only references inactive tables, there will be no access warnings
+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:active false}
+ (is (= [] (group-access/permission-warnings app))))))))
+
+(deftest group-permission-warnings-ignore-unassigned-groups-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp _app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warnings-include-inherited-access-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (group-access/add-groups! app [(:id group)])
+ (perms/set-table-permission! (perms/all-users-group) (mt/id :venues) :perms/view-data :unrestricted)
+ (is (=? [{:group_id (:id group)
+ :missing_tables [{:id (mt/id :orders) :name "Orders" :database_id (mt/id)}]}]
+ (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warnings-preserve-permissions-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (group-access/add-groups! app [(:id group)])
+ (let [before (t2/select :model/DataPermissions)]
+ (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")
+ (is (= before (t2/select :model/DataPermissions))))))))
+
+(deftest group-permission-warnings-include-direct-access-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (perms/set-table-permission! (:id group) (mt/id :venues) :perms/view-data :unrestricted)
+ (perms/set-table-permission! (:id group) (mt/id :orders) :perms/view-data :unrestricted)
+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warnings-include-sandbox-access-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (mt/user-http-request :crowberto :put 200 "permissions/graph"
+ (-> (data-perms.graph/api-graph)
+ (assoc-in [:groups (:id group) (mt/id) :view-data]
+ {"PUBLIC" {(mt/id :venues) :unrestricted
+ (mt/id :orders) :sandboxed}})
+ (assoc :sandboxes [{:group_id (:id group) :table_id (mt/id :orders)}])))
+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))
+ (mt/user-http-request :crowberto :put 200 "permissions/graph"
+ (assoc-in (data-perms.graph/api-graph)
+ [:groups (:id group) (mt/id) :view-data "PUBLIC" (mt/id :orders)]
+ :blocked))
+ (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :orders)}]}]
+ (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warnings-require-admin-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (mt/user-http-request :rasta :get 403 "apps/birds/group-permission-warnings")))))
+
+(deftest group-permission-warnings-without-dependencies-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions :sandboxes}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids []}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warnings-missing-app-test
+ (mt/with-premium-features #{:data-apps}
+ (mt/user-http-request :crowberto :get 404 "apps/missing/group-permission-warnings")))
+
+(deftest group-permission-warnings-use-group-access-not-memberships-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues)]}
+ :model/PermissionsGroup group {}
+ :model/PermissionsGroup other-group {}]
+ (perms/set-database-permission! (:id group) (mt/id) :perms/view-data :blocked)
+ (perms/set-database-permission! (:id other-group) (mt/id) :perms/view-data :unrestricted)
+ (group-access/add-groups! app [(:id group)])
+ (perms/add-user-to-group! (mt/user->id :rasta) (:id group))
+ (perms/add-user-to-group! (mt/user->id :rasta) (:id other-group))
+ (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :venues)}]}]
+ (group-access/permission-warnings app)))))))
+
+(deftest group-permission-warnings-include-impersonated-access-test
+ (mt/with-premium-features #{:data-apps :advanced-permissions}
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues)]}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (mt/user-http-request :crowberto :put 200 "permissions/graph"
+ (-> (data-perms.graph/api-graph)
+ (assoc-in [:groups (:id group) (mt/id) :view-data] :impersonated)
+ (assoc :impersonations [{:group_id (:id group) :db_id (mt/id)
+ :attribute "role"}])))
+ (is (= [] (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))
+ (mt/user-http-request :crowberto :put 200 "permissions/graph"
+ (assoc-in (data-perms.graph/api-graph)
+ [:groups (:id group) (mt/id) :view-data]
+ :blocked))
+ (is (=? [{:group_id (:id group) :missing_tables [{:id (mt/id :venues)}]}]
+ (mt/user-http-request :crowberto :get 200 "apps/birds/group-permission-warnings")))))))
+
+(deftest group-permission-warning-lookups-are-batched-test
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues) (mt/id :orders)]}
+ :model/PermissionsGroup finches {}
+ :model/PermissionsGroup owls {}]
+ (group-access/add-groups! app [(:id finches)])
+ (group-access/permission-warnings app)
+ (let [query-count #(t2/with-call-count [calls]
+ (group-access/permission-warnings app)
+ (calls))
+ one-group-count (query-count)]
+ (group-access/add-groups! app [(:id owls)])
+ (is (= one-group-count (query-count)))))))
+
+(deftest group-permission-warnings-require-feature-test
+ (mt/with-temp [:model/DataApp app {:name "birds" :display_name "Birds" :bundle_path "birds.js"
+ :table_ids [(mt/id :venues)]}
+ :model/PermissionsGroup group {}]
+ (group-access/add-groups! app [(:id group)])
+ (mt/with-premium-features #{}
+ (mt/user-http-request :crowberto :get 402 "apps/birds/group-permission-warnings")
+ (mt/user-http-request :rasta :get 402 "apps/birds/group-permission-warnings"))))
+
+(deftest group-permission-warning-lookups-exclude-unrelated-permissions-test
+ (mt/with-temp [:model/Database other-db {}
+ :model/PermissionsGroup finches {}
+ :model/PermissionsGroup owls {}
+ :model/PermissionsGroup sparrows {}]
+ (t2/delete! :model/DataPermissions :group_id [:in [(:id finches) (:id owls) (:id sparrows)]])
+ (let [table-permission {:group_id (:id finches) :db_id (mt/id) :table_id (mt/id :venues)
+ :perm_type :perms/view-data :perm_value :unrestricted}
+ database-permission {:group_id (:id owls) :db_id (mt/id) :table_id nil
+ :perm_type :perms/view-data :perm_value :unrestricted}]
+ (t2/insert! :model/DataPermissions
+ [table-permission
+ database-permission
+ (assoc table-permission :table_id (mt/id :orders))
+ (assoc table-permission :perm_type :perms/create-queries :perm_value :query-builder)
+ (assoc database-permission :group_id (:id sparrows))
+ (assoc database-permission :db_id (:id other-db))])
+ (let [access (#'group-access/group-table-access
+ #{(:id finches) (:id owls)}
+ [{:id (mt/id :venues) :database_id (mt/id)}])
+ permission-rows (mapcat val (:permissions access))]
+ ;; exclude loading permission rows that the data access warning check does not need
+ (is (= #{table-permission database-permission}
+ (into #{} (map #(select-keys % (keys table-permission))) permission-rows)))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts
index 4e52eddaa9e..9df7ed2fdb6 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts
@@ -2,6 +2,7 @@ import type {
AddDataAppGroupsRequest,
DataApp,
DataAppGroup,
+ DataAppGroupPermissionWarning,
DataAppRepoStatus,
RemoveDataAppGroupRequest,
SetDataAppEnabledRequest,
@@ -43,6 +44,16 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({
}),
providesTags: () => [REPO_STATUS_TAG],
}),
+ getDataAppGroupPermissionWarnings: builder.query<
+ DataAppGroupPermissionWarning[],
+ string
+ >({
+ query: (name) => ({
+ method: "GET",
+ url: `/api/apps/${encodeURIComponent(name)}/group-permission-warnings`,
+ }),
+ providesTags: (_, __, name) => [idTag("data-app", name)],
+ }),
getDataAppGroups: builder.query<DataAppGroup[], string>({
query: (name) => ({
method: "GET",
@@ -57,6 +68,23 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({
url: `/api/apps/${encodeURIComponent(name)}/groups`,
body: { group_ids },
}),
+ async onQueryStarted({ name }, { dispatch, queryFulfilled }) {
+ try {
+ const { data: groups } = await queryFulfilled;
+
+ // pending group-permission-warnings request delays tag invalidation; after a
+ // successful add, replace the groups cache so new groups appear immediately.
+ dispatch(
+ dataAppApi.util.updateQueryData(
+ "getDataAppGroups",
+ name,
+ () => groups,
+ ),
+ );
+ } catch {
+ return;
+ }
+ },
invalidatesTags: (_, error, { name }) =>
invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),
},
@@ -66,6 +94,24 @@ export const dataAppApi = EnterpriseApi.injectEndpoints({
method: "DELETE",
url: `/api/apps/${encodeURIComponent(name)}/groups/${group_id}`,
}),
+
+ async onQueryStarted({ name, group_id }, { dispatch, queryFulfilled }) {
+ try {
+ await queryFulfilled;
+
+ // pending group-permission-warnings request delays tag invalidation; after a
+ // successful removal, filter the group from the cache so it disappears immediately.
+ dispatch(
+ dataAppApi.util.updateQueryData(
+ "getDataAppGroups",
+ name,
+ (groups) => groups.filter((group) => group.id !== group_id),
+ ),
+ );
+ } catch {
+ return;
+ }
+ },
invalidatesTags: (_, error, { name }) =>
invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),
}),
@@ -94,6 +140,7 @@ export const {
useGetDataAppQuery,
useGetDataAppRepoStatusQuery,
useGetDataAppGroupsQuery,
+ useGetDataAppGroupPermissionWarningsQuery,
useAddDataAppGroupsMutation,
useRemoveDataAppGroupMutation,
useSetDataAppEnabledMutation,
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsx
new file mode 100644
index 00000000000..9dd95759169
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage-warnings.unit.spec.tsx
@@ -0,0 +1,199 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { screen, waitFor, within } from "__support__/ui";
+import { defer } from "metabase/utils/promise";
+import type { DataAppGroupPermissionWarning } from "metabase-types/api";
+
+import {
+ FINCHES_GROUP_ID,
+ OWLS_GROUP_ID,
+ openGroupAssignmentPicker,
+ setup,
+} from "./tests/ManageDataAppGroupsPage.setup";
+
+const FINCHES_WARNING = {
+ group_id: FINCHES_GROUP_ID,
+ missing_tables: [
+ {
+ id: 10,
+ name: "Orders",
+ schema: "public",
+ database_id: 1,
+ database_name: "Birds",
+ },
+ ],
+};
+
+describe("ManageDataAppGroupsPage warnings", () => {
+ it("shows missing tables for assigned groups on hover", async () => {
+ setup({
+ groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],
+ warnings: [FINCHES_WARNING],
+ });
+
+ await userEvent.hover(
+ await screen.findByRole("button", { name: "Missing data access" }),
+ );
+
+ expect(
+ screen.getByRole("columnheader", { name: "Data access" }),
+ ).toBeInTheDocument();
+
+ expect(
+ await screen.findByText(
+ "Finches doesn’t have permission to view these tables used in this app:",
+ ),
+ ).toBeInTheDocument();
+
+ await userEvent.hover(screen.getByRole("link", { name: "Orders" }));
+
+ const ordersLink = screen.getByRole("link", { name: "Orders" });
+ expect(ordersLink).toBeVisible();
+
+ expect(ordersLink).toHaveAttribute(
+ "href",
+ expect.stringContaining("/admin/permissions/data"),
+ );
+
+ // should not open in new tab
+ expect(ordersLink).not.toHaveAttribute("target");
+ });
+
+ it("clears a removed group's warning", async () => {
+ setup({
+ groups: [
+ { id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 },
+ { id: OWLS_GROUP_ID, name: "Owls", member_count: 2 },
+ ],
+ warnings: [FINCHES_WARNING],
+ });
+
+ expect(
+ await within(
+ await screen.findByRole("row", { name: /Finches/ }),
+ ).findByRole("button", { name: "Missing data access" }),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Remove Finches" }),
+ );
+
+ // after group is removed, there should be no warning
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: "Missing data access" }),
+ ).not.toBeInTheDocument(),
+ );
+ });
+
+ it("updates assignments while warning check is still pending", async () => {
+ const warningsResponse = defer<DataAppGroupPermissionWarning[]>();
+
+ setup({
+ groups: [{ id: OWLS_GROUP_ID, name: "Owls", member_count: 2 }],
+ warningsResponse: warningsResponse.promise,
+ });
+
+ try {
+ await openGroupAssignmentPicker();
+
+ await userEvent.click(screen.getByRole("option", { name: "Finches" }));
+ await userEvent.click(screen.getByRole("button", { name: "Add" }));
+
+ // without updating the cache, finches group never shows because
+ // RTK Query delays cache invalidation until the "group warning" request is done;
+ // see `onQueryStarted` in `api/data-app.ts`
+ expect(
+ await screen.findByRole("button", { name: "Remove Finches" }),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Remove Owls" }),
+ );
+
+ // owls group should be removed
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: "Remove Owls" }),
+ ).not.toBeInTheDocument(),
+ );
+
+ expect(
+ screen.getByRole("button", { name: "Remove Finches" }),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Remove Finches" }),
+ );
+
+ // finches group should be removed
+ expect(
+ await screen.findByText("No groups have access yet"),
+ ).toBeInTheDocument();
+ } finally {
+ warningsResponse.resolve([]);
+ }
+ });
+
+ it("shows a loading indicator until the warning check finishes", async () => {
+ const warningsResponse = defer<DataAppGroupPermissionWarning[]>();
+
+ setup({
+ groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],
+ warningsResponse: warningsResponse.promise,
+ });
+
+ try {
+ expect(
+ await screen.findByLabelText("Checking data access"),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("button", { name: "Remove Finches" }),
+ ).toBeEnabled();
+
+ warningsResponse.resolve([FINCHES_WARNING]);
+
+ expect(
+ await screen.findByRole("button", { name: "Missing data access" }),
+ ).toBeInTheDocument();
+
+ // loading indicator should disappear after the warning check finishes
+ expect(
+ screen.queryByLabelText("Checking data access"),
+ ).not.toBeInTheDocument();
+ } finally {
+ warningsResponse.resolve([]);
+ }
+ });
+
+ it("shows an error banner and retries the warning check", async () => {
+ setup({
+ groups: [{ id: FINCHES_GROUP_ID, name: "Finches", member_count: 0 }],
+ warningsError: true,
+ });
+
+ const banner = await screen.findByRole("alert");
+ expect(banner).toHaveTextContent("Could not check data access");
+
+ expect(
+ screen.getByRole("button", { name: "Remove Finches" }),
+ ).toBeEnabled();
+
+ fetchMock.modifyRoute("data-app-group-permission-warnings", {
+ response: [FINCHES_WARNING],
+ });
+
+ await userEvent.click(
+ within(banner).getByRole("button", { name: "Retry" }),
+ );
+
+ // show the warning after retry succeeds
+ expect(
+ await screen.findByRole("button", { name: "Missing data access" }),
+ ).toBeInTheDocument();
+
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx
index e72071eb991..9017140bd11 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppGroupsPage.tsx
@@ -113,6 +113,7 @@ const DataAppGroups = ({
}
>
<DataAppGroupList
+ appName={appName}
isAdding={isAdding}
groups={groups}
onAddGroups={handleAddGroups}
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.tsx
index a89478fc299..f5a35dea56a 100644
--- 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.tsx
@@ -1,101 +1,15 @@
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 })),
- ];
+import { screen, waitFor, within } from "__support__/ui";
+import { createMockDataApp } from "metabase-types/api/mocks";
- 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" },
- );
-};
+import {
+ FINCHES_GROUP_ID,
+ OWLS_GROUP_ID,
+ openGroupAssignmentPicker,
+ setup,
+} from "./tests/ManageDataAppGroupsPage.setup";
describe("ManageDataAppGroupsPage", () => {
it("manages assignments when the app is disabled", async () => {
@@ -241,19 +155,3 @@ describe("ManageDataAppGroupsPage", () => {
).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/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css
new file mode 100644
index 00000000000..e321b7543d0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.module.css
@@ -0,0 +1,13 @@
+.badge {
+ background-color: var(--mb-color-background_surface-warning-strong);
+ transition: background-color 150ms ease;
+}
+
+.button {
+ cursor: pointer;
+}
+
+.button:hover .badge,
+.button:focus-visible .badge {
+ background-color: var(--mb-color-background_surface-warning);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx
new file mode 100644
index 00000000000..a35008d2149
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppDataAccessWarning/DataAppDataAccessWarning.tsx
@@ -0,0 +1,135 @@
+import { t } from "ttag";
+
+import { getDatabaseFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";
+import { Link } from "metabase/router";
+import {
+ Anchor,
+ Badge,
+ Flex,
+ HoverCard,
+ Icon,
+ Stack,
+ Text,
+ UnstyledButton,
+} from "metabase/ui";
+import type {
+ DataAppGroupPermissionWarning,
+ DataAppMissingTable,
+} from "metabase-types/api";
+
+import S from "./DataAppDataAccessWarning.module.css";
+
+interface Props {
+ warning: DataAppGroupPermissionWarning;
+ groupName: string;
+}
+
+export const DataAppDataAccessWarning = ({ warning, groupName }: Props) => {
+ const label = t`Missing data access`;
+
+ return (
+ <HoverCard position="bottom-end" shadow="md">
+ <HoverCard.Target>
+ <UnstyledButton
+ className={S.button}
+ aria-label={label}
+ style={{ flexShrink: 0 }}
+ >
+ <Badge
+ className={S.badge}
+ size="sm"
+ c="text-primary"
+ bdrs="sm"
+ tt="none"
+ >
+ {label}
+ </Badge>
+ </UnstyledButton>
+ </HoverCard.Target>
+
+ <HoverCard.Dropdown
+ p="lg"
+ w="30rem"
+ data-testid="data-access-warning-popover"
+ >
+ <Stack gap="lg">
+ <Text size="sm">
+ {t`${groupName} doesn’t have permission to view these tables used in this app:`}
+ </Text>
+
+ <Stack
+ component="ul"
+ data-testid="missing-tables-list"
+ gap="sm"
+ m={0}
+ pl={0}
+ style={{ listStyle: "none" }}
+ >
+ {warning.missing_tables.map((table) => {
+ const parts = getMissingTableSegments(table);
+
+ return (
+ <Flex
+ component="li"
+ key={table.id}
+ align="center"
+ gap={4}
+ wrap="wrap"
+ >
+ {parts.map((part, index) => (
+ <Flex key={part.url} align="center" gap={4}>
+ <Anchor component={Link} to={part.url} size="sm" fw={700}>
+ {part.label}
+ </Anchor>
+
+ {index < parts.length - 1 && (
+ <Icon
+ name="chevronright"
+ size={12}
+ c="text-secondary"
+ aria-hidden
+ />
+ )}
+ </Flex>
+ ))}
+ </Flex>
+ );
+ })}
+ </Stack>
+ </Stack>
+ </HoverCard.Dropdown>
+ </HoverCard>
+ );
+};
+
+const getMissingTableSegments = (table: DataAppMissingTable) => {
+ const databaseSection = {
+ label: table.database_name,
+ url: getDatabaseFocusPermissionsUrl({
+ databaseId: table.database_id,
+ }),
+ };
+
+ const schemaSection = table.schema
+ ? [
+ {
+ label: table.schema,
+ url: getDatabaseFocusPermissionsUrl({
+ databaseId: table.database_id,
+ schemaName: table.schema,
+ }),
+ },
+ ]
+ : [];
+
+ const tableSection = {
+ label: table.name,
+ url: getDatabaseFocusPermissionsUrl({
+ databaseId: table.database_id,
+ schemaName: table.schema ?? undefined,
+ tableId: table.id,
+ }),
+ };
+
+ return [databaseSection, ...schemaSection, tableSection];
+};
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.tsx
index 4b0a1990ccc..bd138f47ff7 100644
--- 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.tsx
@@ -1,3 +1,4 @@
+import { skipToken } from "@reduxjs/toolkit/query";
import cx from "classnames";
import { useEffect, useMemo } from "react";
import { t } from "ttag";
@@ -10,32 +11,42 @@ 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 {
+ Alert,
+ Anchor,
Box,
Collapse,
Flex,
Icon,
+ Loader,
Stack,
Text,
UnstyledButton,
} from "metabase/ui";
-import type { DataAppGroup } from "metabase-types/api";
+import { useGetDataAppGroupPermissionWarningsQuery } from "metabase-enterprise/api";
+import type {
+ DataAppGroup,
+ DataAppGroupPermissionWarning,
+} from "metabase-types/api";
import { AddDataAppGroups } from "../AddDataAppGroups/AddDataAppGroups";
+import { DataAppDataAccessWarning } from "../DataAppDataAccessWarning/DataAppDataAccessWarning";
import S from "./DataAppGroupList.module.css";
const PAGE_SIZE = 25;
type Props = {
+ appName: string;
isAdding: boolean;
groups: DataAppGroup[];
- onAddGroups: (groupIds: number[]) => Promise<boolean>;
onCancelAdd: () => void;
+ onAddGroups: (groupIds: number[]) => Promise<boolean>;
onRemoveGroup: (group: DataAppGroup) => Promise<boolean>;
};
export const DataAppGroupList = ({
+ appName,
isAdding,
groups,
onAddGroups,
@@ -57,8 +68,52 @@ export const DataAppGroupList = ({
[groups, page],
);
+ const warningsQuery = useGetDataAppGroupPermissionWarningsQuery(
+ groups.length > 0 ? appName : skipToken,
+ { refetchOnMountOrArgChange: true },
+ );
+
+ const warningsByGroupId = useMemo(
+ () =>
+ new Map(
+ warningsQuery.currentData?.map((warning) => [
+ warning.group_id,
+ warning,
+ ]),
+ ),
+ [warningsQuery.currentData],
+ );
+
return (
<Stack data-testid="group-management-sections" gap="lg">
+ {groups.length > 0 && warningsQuery.isError && (
+ <Alert
+ color="error"
+ icon={<Icon name="warning" />}
+ size="compact"
+ styles={{ wrapper: { alignItems: "center" } }}
+ >
+ {t`Could not check data access`}
+
+ <Anchor
+ component="button"
+ inherit
+ ml="0.5rem"
+ c="core-brand"
+ fw={700}
+ disabled={warningsQuery.isFetching}
+ onClick={() => warningsQuery.refetch()}
+ >{t`Retry`}</Anchor>
+ </Alert>
+ )}
+
+ {groups.length > 0 && warningsQuery.isLoading && (
+ <Flex align="center" gap="sm">
+ <Loader size="xs" aria-label={t`Checking data access`} />
+ <Text c="text-secondary">{t`Checking data access…`}</Text>
+ </Flex>
+ )}
+
<Box
className={cx(
S.groupListContent,
@@ -86,12 +141,13 @@ export const DataAppGroupList = ({
{groups.length > 0 && (
<AdminContentTable
className={cx(S.groupTable, Animation.fadeIn)}
- columnTitles={[t`Group name`, t`Members`, null]}
+ columnTitles={[t`Group name`, t`Members`, t`Data access`, null]}
>
{visibleGroups.map((group) => (
<GroupRow
key={group.id}
group={group}
+ warning={warningsByGroupId.get(group.id)}
onRemove={onRemoveGroup}
/>
))}
@@ -150,9 +206,11 @@ const DataAppGroupsEmptyState = () => (
const GroupRow = ({
group,
+ warning,
onRemove,
}: {
group: DataAppGroup;
+ warning?: DataAppGroupPermissionWarning;
onRemove: (group: DataAppGroup) => void;
}) => {
const name = getGroupNameLocalized(group);
@@ -165,6 +223,12 @@ const GroupRow = ({
<td>{group.member_count}</td>
+ <td>
+ {warning && (
+ <DataAppDataAccessWarning warning={warning} groupName={name} />
+ )}
+ </td>
+
<Box component="td" w="1%" style={{ whiteSpace: "nowrap" }}>
<Flex
data-testid="data-app-group-actions"
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsx
new file mode 100644
index 00000000000..68f2d7a4eaf
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/tests/ManageDataAppGroupsPage.setup.tsx
@@ -0,0 +1,138 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { Route } from "metabase/router";
+import type {
+ DataApp,
+ DataAppGroup,
+ DataAppGroupPermissionWarning,
+} from "metabase-types/api";
+import { createMockDataApp, createMockGroup } from "metabase-types/api/mocks";
+
+import { ManageDataAppGroupsPage } from "../ManageDataAppGroupsPage";
+
+export const FINCHES_GROUP_ID = 3;
+export 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,
+ }),
+];
+
+export const setup = ({
+ app = createMockDataApp(),
+ groups = [],
+
+ failFirstAdd = false,
+
+ warnings = [],
+ warningsError = false,
+ warningsResponse,
+}: {
+ app?: DataApp;
+ groups?: DataAppGroup[];
+
+ failFirstAdd?: boolean;
+
+ warnings?: DataAppGroupPermissionWarning[];
+ warningsError?: boolean;
+ warningsResponse?: Promise<DataAppGroupPermissionWarning[]>;
+} = {}) => {
+ 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.get(
+ "path:/api/apps/sales/group-permission-warnings",
+ () =>
+ warningsResponse ??
+ (warningsError
+ ? 500
+ : warnings.filter((warning) =>
+ assigned.some((group) => group.id === warning.group_id),
+ )),
+ { name: "data-app-group-permission-warnings" },
+ );
+
+ 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" },
+ );
+};
+
+export 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/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.ts
index 9512e955a4f..833921ff15f 100644
--- a/frontend/src/metabase-types/api/data-app.ts
+++ b/frontend/src/metabase-types/api/data-app.ts
@@ -72,3 +72,16 @@ export interface RemoveDataAppGroupRequest {
name: string;
group_id: number;
}
+
+export interface DataAppMissingTable {
+ id: number;
+ name: string;
+ schema: string | null;
+ database_id: number;
+ database_name: string;
+}
+
+export interface DataAppGroupPermissionWarning {
+ group_id: number;
+ missing_tables: DataAppMissingTable[];
+}