Skip to content

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

Scope the invite group picker to the groups with access to the shared item (#77898)

Andrei Chernykh0a9e61f44f71
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 4908bcde706..2f6cce44842 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1621,7 +1621,9 @@
request
settings
util}
- :model-imports #{:model/DataPermissions
+ :model-imports #{:model/Card
+ :model/Dashboard
+ :model/DataPermissions
:model/Database
:model/PermissionsGroup
:model/PermissionsGroupMembership
diff --git a/frontend/src/metabase-types/api/group.ts b/frontend/src/metabase-types/api/group.ts
index 9490a00d94a..ba428b23266 100644
--- a/frontend/src/metabase-types/api/group.ts
+++ b/frontend/src/metabase-types/api/group.ts
@@ -45,6 +45,11 @@ export type BaseGroupInfo = {
is_tenant_group?: boolean;
};
+export type ListInviteGroupIdsRequest = {
+ type: "dashboard" | "question";
+ id: number;
+};
+
export type ListUserMembershipsResponse = Record<UserId, Membership[]>;
export type CreateMembershipRequest = {
diff --git a/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx b/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx
index 2a4c30bbeb5..718a60ec2c7 100644
--- a/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx
+++ b/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx
@@ -4,6 +4,7 @@ import { t } from "ttag";
import {
skipToken,
useGetUserQuery,
+ useListPermissionsGroupsQuery,
useUpdateUserMutation,
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
@@ -24,6 +25,9 @@ export const EditUserModal = ({
}: EditUserModalProps) => {
const userId = params.userId ? parseInt(params.userId) : null;
const { data: user, isLoading, error } = useGetUserQuery(userId ?? skipToken);
+ const { data: groups } = useListPermissionsGroupsQuery({
+ tenancy: external ? "external" : "internal",
+ });
const [updateUser] = useUpdateUserMutation();
const initialValues = useMemo(
@@ -63,6 +67,7 @@ export const EditUserModal = ({
initialValues={initialValues}
onSubmit={handleSubmit}
external={external}
+ groups={groups}
userId={userId}
edit
/>
diff --git a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx b/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
index 91c774f66d0..e37a8ea757f 100644
--- a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
+++ b/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
@@ -1,6 +1,9 @@
import { t } from "ttag";
-import { useCreateUserMutation } from "metabase/api";
+import {
+ useCreateUserMutation,
+ useListPermissionsGroupsQuery,
+} from "metabase/api";
import { isEmailAlreadyInUse } from "metabase/api/utils/errors";
import { trackUserInvited } from "metabase/common/analytics";
import { UserForm } from "metabase/common/components/UserForm";
@@ -27,6 +30,9 @@ export const NewUserModal = ({
const dispatch = useDispatch();
const [createUser] = useCreateUserMutation();
+ const { data: groups } = useListPermissionsGroupsQuery({
+ tenancy: external ? "external" : "internal",
+ });
const handleSubmit = async (vals: Partial<UserType>) => {
const password = MetabaseSettings.isEmailConfigured()
@@ -75,6 +81,7 @@ export const NewUserModal = ({
<Modal opened title={title} padding="xl" onClose={onClose}>
<UserForm
external={external}
+ groups={groups}
initialValues={{}}
submitText={t`Create`}
onCancel={onClose}
diff --git a/frontend/src/metabase/api/permission.ts b/frontend/src/metabase/api/permission.ts
index 7cefc435ae6..38dd0363dea 100644
--- a/frontend/src/metabase/api/permission.ts
+++ b/frontend/src/metabase/api/permission.ts
@@ -5,6 +5,7 @@ import type {
Group,
GroupId,
GroupListQuery,
+ ListInviteGroupIdsRequest,
ListUserMembershipsResponse,
Membership,
PermissionsGraph,
@@ -61,6 +62,13 @@ export const permissionApi = Api.injectEndpoints({
}),
providesTags: (groups = []) => providePermissionsGroupListTags(groups),
}),
+ listInviteGroupIds: builder.query<GroupId[], ListInviteGroupIdsRequest>({
+ query: (params) => ({
+ method: "GET",
+ url: "/api/permissions/invite-group-ids",
+ params,
+ }),
+ }),
getPermissionsGroup: builder.query<Group, GroupId>({
query: (id) => ({
method: "GET",
@@ -172,6 +180,7 @@ export const {
useGetDatabasePermissionsGraphQuery,
useUpdatePermissionsGraphMutation,
useListPermissionsGroupsQuery,
+ useListInviteGroupIdsQuery,
useGetPermissionsGroupQuery,
useCreatePermissionsGroupMutation,
useUpdatePermissionsGroupMutation,
diff --git a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.module.css b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.module.css
index 52e8ed2bfde..01ce87f2d7a 100644
--- a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.module.css
+++ b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.module.css
@@ -19,3 +19,18 @@
margin: 0 !important;
transform: translateY(1px);
}
+
+/* The checkbox is decorative; clicks must fall through to the option row. */
+.checkbox {
+ pointer-events: none;
+}
+
+/* The raw Combobox theme leaves the section-header color transparent (unlike Select),
+ so set a visible one; matches Select's group-label treatment. */
+.groupLabel {
+ color: var(--mb-color-text-secondary);
+
+ &::after {
+ display: none;
+ }
+}
diff --git a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.tsx b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.tsx
index 1beafe81b28..d7273d77d77 100644
--- a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.tsx
+++ b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.tsx
@@ -1,4 +1,4 @@
-import { Fragment, type KeyboardEvent, useState } from "react";
+import { type KeyboardEvent, useState } from "react";
import { t } from "ttag";
import {
@@ -25,6 +25,11 @@ import type { GroupId, GroupInfo } from "metabase-types/api";
import S from "./GroupsMultiSelect.module.css";
+export interface GroupSection {
+ label: string;
+ groupIds: GroupId[];
+}
+
interface GroupsMultiSelectProps {
groups: GroupInfo[];
value: GroupId[];
@@ -34,6 +39,9 @@ interface GroupsMultiSelectProps {
isCurrentUser?: boolean;
placeholder?: string;
"aria-label"?: string;
+ // Ordered labeled sections (a group counts toward the first section listing it);
+ // unclaimed groups fall under a trailing "Other groups" section.
+ sections?: GroupSection[];
}
export const GroupsMultiSelect = ({
@@ -45,6 +53,7 @@ export const GroupsMultiSelect = ({
isCurrentUser = false,
placeholder,
"aria-label": ariaLabel = t`Groups`,
+ sections,
}: GroupsMultiSelectProps) => {
const combobox = useCombobox();
const [search, setSearch] = useState("");
@@ -85,11 +94,10 @@ export const GroupsMultiSelect = ({
getGroupSortOrder(a) - getGroupSortOrder(b),
);
+ const searchTerm = search.trim().toLowerCase();
const visibleGroups = groups
.filter((group) =>
- getGroupNameLocalized(group)
- .toLowerCase()
- .includes(search.trim().toLowerCase()),
+ getGroupNameLocalized(group).toLowerCase().includes(searchTerm),
)
// Pinned groups lead so the divider sits at the single pinned-to-custom boundary;
// getGroupSortOrder alone leaves the external default (rank 3) among custom groups.
@@ -131,10 +139,98 @@ export const GroupsMultiSelect = ({
}
};
+ const renderOption = (group: GroupInfo) => (
+ <GroupOption
+ key={group.id}
+ group={group}
+ isSelected={value.includes(group.id)}
+ isLocked={isGroupLocked(group)}
+ showManagerToggle={canEditManager(group)}
+ isManager={isManager(group.id)}
+ onToggleManager={() => onToggleManager?.(group.id)}
+ />
+ );
+
+ const renderOptions = () => {
+ if (visibleGroups.length === 0) {
+ return <Combobox.Empty>{t`No groups found`}</Combobox.Empty>;
+ }
+
+ if (sections && sections.length > 0) {
+ // A group renders in the first section listing it.
+ const sectionIndexByGroupId = new Map<GroupId, number>();
+ sections.forEach(({ groupIds }, index) =>
+ groupIds.forEach((id) => {
+ if (!sectionIndexByGroupId.has(id)) {
+ sectionIndexByGroupId.set(id, index);
+ }
+ }),
+ );
+
+ const sectionedGroups: { label: string; members: GroupInfo[] }[] =
+ sections.map(({ label }) => ({ label, members: [] }));
+
+ const otherGroups: GroupInfo[] = [];
+
+ visibleGroups.forEach((group) => {
+ const sectionIndex = sectionIndexByGroupId.get(group.id);
+ if (sectionIndex != null) {
+ sectionedGroups[sectionIndex].members.push(group);
+ } else {
+ otherGroups.push(group);
+ }
+ });
+ return (
+ <>
+ {sectionedGroups.map(
+ ({ label, members }) =>
+ members.length > 0 && (
+ <Combobox.Group
+ key={label}
+ label={label}
+ role="group"
+ aria-label={label}
+ >
+ {members.map(renderOption)}
+ </Combobox.Group>
+ ),
+ )}
+ {otherGroups.length > 0 && (
+ <Combobox.Group
+ label={t`Other groups`}
+ role="group"
+ aria-label={t`Other groups`}
+ >
+ {otherGroups.map(renderOption)}
+ </Combobox.Group>
+ )}
+ </>
+ );
+ }
+
+ // Without sections: unlabeled groups with a divider at the pinned-to-custom boundary.
+ const pinnedGroups = visibleGroups.filter(isPinnedGroup);
+ const customGroups = visibleGroups.filter((group) => !isPinnedGroup(group));
+ return (
+ <>
+ {pinnedGroups.length > 0 && (
+ <Combobox.Group>{pinnedGroups.map(renderOption)}</Combobox.Group>
+ )}
+ {pinnedGroups.length > 0 && customGroups.length > 0 && (
+ <Divider my="sm" />
+ )}
+ {customGroups.length > 0 && (
+ <Combobox.Group>{customGroups.map(renderOption)}</Combobox.Group>
+ )}
+ </>
+ );
+ };
+
return (
<Combobox
store={combobox}
floatingStrategy="fixed"
+ classNames={{ groupLabel: S.groupLabel }}
onOptionSubmit={handleOptionSubmit}
>
<Combobox.DropdownTarget>
@@ -184,53 +280,54 @@ export const GroupsMultiSelect = ({
</Combobox.DropdownTarget>
<Combobox.Dropdown>
- <Combobox.Options>
- {visibleGroups.length === 0 ? (
- <Combobox.Empty>{t`No groups found`}</Combobox.Empty>
- ) : (
- visibleGroups.map((group, index) => {
- const isSelected = value.includes(group.id);
- const previousGroup = visibleGroups[index - 1];
- const showDivider =
- previousGroup != null &&
- isPinnedGroup(previousGroup) &&
- !isPinnedGroup(group);
- return (
- <Fragment key={group.id}>
- {showDivider && <Divider my="sm" />}
- <Combobox.Option
- value={String(group.id)}
- aria-label={getGroupNameLocalized(group)}
- active={isSelected}
- disabled={isGroupLocked(group)}
- >
- <Flex align="center" justify="space-between" gap="sm">
- <Flex align="center" gap="sm">
- <Checkbox
- checked={isSelected}
- readOnly
- aria-hidden
- tabIndex={-1}
- style={{ pointerEvents: "none" }}
- />
- <span>{getGroupNameLocalized(group)}</span>
- </Flex>
- {canEditManager(group) && (
- <Box onMouseDown={(event) => event.preventDefault()}>
- <PLUGIN_GROUP_MANAGERS.UserTypeToggle
- isManager={isManager(group.id)}
- onChange={() => onToggleManager?.(group.id)}
- />
- </Box>
- )}
- </Flex>
- </Combobox.Option>
- </Fragment>
- );
- })
- )}
- </Combobox.Options>
+ <Combobox.Options>{renderOptions()}</Combobox.Options>
</Combobox.Dropdown>
</Combobox>
);
};
+
+interface GroupOptionProps {
+ group: GroupInfo;
+ isSelected: boolean;
+ isLocked: boolean;
+ showManagerToggle: boolean;
+ isManager: boolean;
+ onToggleManager: () => void;
+}
+
+const GroupOption = ({
+ group,
+ isSelected,
+ isLocked,
+ showManagerToggle,
+ isManager,
+ onToggleManager,
+}: GroupOptionProps) => (
+ <Combobox.Option
+ value={String(group.id)}
+ aria-label={getGroupNameLocalized(group)}
+ active={isSelected}
+ disabled={isLocked}
+ >
+ <Flex align="center" justify="space-between" gap="sm">
+ <Flex align="center" gap="sm">
+ <Checkbox
+ className={S.checkbox}
+ checked={isSelected}
+ readOnly
+ aria-hidden
+ tabIndex={-1}
+ />
+ <span>{getGroupNameLocalized(group)}</span>
+ </Flex>
+ {showManagerToggle && (
+ <Box onMouseDown={(event) => event.preventDefault()}>
+ <PLUGIN_GROUP_MANAGERS.UserTypeToggle
+ isManager={isManager}
+ onChange={onToggleManager}
+ />
+ </Box>
+ )}
+ </Flex>
+ </Combobox.Option>
+);
diff --git a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.unit.spec.tsx b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.unit.spec.tsx
index 18da6174717..c65f8d3068e 100644
--- a/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/GroupsMultiSelect/GroupsMultiSelect.unit.spec.tsx
@@ -10,7 +10,7 @@ import {
createMockTokenFeatures,
} from "metabase-types/api/mocks";
-import { GroupsMultiSelect } from "./GroupsMultiSelect";
+import { type GroupSection, GroupsMultiSelect } from "./GroupsMultiSelect";
const ALL_USERS = createMockGroup({
id: 1,
@@ -50,7 +50,12 @@ function setup(
{
managerGroupIds = [],
groups = GROUPS,
- }: { managerGroupIds?: GroupId[]; groups?: GroupInfo[] } = {},
+ sections,
+ }: {
+ managerGroupIds?: GroupId[];
+ groups?: GroupInfo[];
+ sections?: GroupSection[];
+ } = {},
) {
const onChange = jest.fn<void, [GroupId[]]>();
const onToggleManager = jest.fn<void, [GroupId]>();
@@ -75,6 +80,7 @@ function setup(
: [...prev, id],
);
}}
+ sections={sections}
/>
);
}
@@ -105,6 +111,10 @@ const expectSingleDividerBetween = (before: string, after: string) => {
).toBe(true);
};
+// The labeled sections carry role="group", so their contents can be scoped.
+const getSection = (name: string) =>
+ within(screen.getByRole("group", { name }));
+
describe("GroupsMultiSelect", () => {
it("renders the selected groups as pills", () => {
setup([ALL_USERS.id, ADMINISTRATORS.id]);
@@ -193,6 +203,116 @@ describe("GroupsMultiSelect", () => {
).not.toBeInTheDocument();
});
+ describe("with sections", () => {
+ const SECTIONS = [
+ {
+ label: "Can view this dashboard",
+ groupIds: [ADMINISTRATORS.id, MARKETING.id],
+ },
+ ];
+
+ it("splits the dropdown into the given and other sections instead of the pinned divider", async () => {
+ setup([ALL_USERS.id], { sections: SECTIONS });
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Groups" }));
+ await screen.findByRole("option", { name: "Marketing" });
+
+ // Administrators and Marketing sit in the listed section...
+ const accessSection = "Can view this dashboard";
+ expect(
+ getSection(accessSection).getByRole("option", {
+ name: "Administrators",
+ }),
+ ).toBeInTheDocument();
+ expect(
+ getSection(accessSection).getByRole("option", { name: "Marketing" }),
+ ).toBeInTheDocument();
+
+ // ...while All Users and Sales fall under "Other groups".
+ expect(
+ getSection("Other groups").getByRole("option", { name: "All Users" }),
+ ).toBeInTheDocument();
+ expect(
+ getSection("Other groups").getByRole("option", { name: "Sales" }),
+ ).toBeInTheDocument();
+
+ // The sections replace the flat layout's pinned divider.
+ expect(screen.queryByRole("separator")).not.toBeInTheDocument();
+ });
+
+ it("omits a section none of whose groups are visible", async () => {
+ setup([ALL_USERS.id], {
+ groups: [ALL_USERS, MARKETING],
+ sections: [{ label: "Can view this dashboard", groupIds: [SALES.id] }],
+ });
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Groups" }));
+ await screen.findByRole("option", { name: "Marketing" });
+
+ expect(
+ screen.queryByRole("group", { name: "Can view this dashboard" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("group", { name: "Other groups" }),
+ ).toBeInTheDocument();
+ });
+
+ it("omits the other-groups section when every group is claimed", async () => {
+ setup([ALL_USERS.id], {
+ sections: [
+ {
+ label: "Can view this dashboard",
+ groupIds: GROUPS.map((group) => group.id),
+ },
+ ],
+ });
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Groups" }));
+ await screen.findByRole("option", { name: "Marketing" });
+
+ expect(
+ screen.getByRole("group", { name: "Can view this dashboard" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("group", { name: "Other groups" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders multiple sections in order, each group counting toward the first that lists it", async () => {
+ setup([ALL_USERS.id], {
+ sections: [
+ { label: "First", groupIds: [MARKETING.id] },
+ // Marketing is already claimed by "First", so only Sales lands here.
+ { label: "Second", groupIds: [MARKETING.id, SALES.id] },
+ ],
+ });
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Groups" }));
+ await screen.findByRole("option", { name: "Marketing" });
+
+ // getAllByRole returns DOM order, pinning the section sequence.
+ expect(
+ screen
+ .getAllByRole("group")
+ .map((section) => section.getAttribute("aria-label")),
+ ).toEqual(["First", "Second", "Other groups"]);
+
+ // Marketing renders once, in "First"; "Second" only gets Sales.
+ expect(screen.getAllByRole("option", { name: "Marketing" })).toHaveLength(
+ 1,
+ );
+ expect(
+ getSection("First").getByRole("option", { name: "Marketing" }),
+ ).toBeInTheDocument();
+ expect(
+ getSection("Second").getByRole("option", { name: "Sales" }),
+ ).toBeInTheDocument();
+ expect(
+ getSection("Other groups").getByRole("option", { name: "All Users" }),
+ ).toBeInTheDocument();
+ });
+ });
+
describe("with the group-managers feature (EE)", () => {
beforeEach(() => {
mockSettings({
diff --git a/frontend/src/metabase/common/components/GroupsMultiSelect/index.ts b/frontend/src/metabase/common/components/GroupsMultiSelect/index.ts
index 970248cecf0..9e562551cc7 100644
--- a/frontend/src/metabase/common/components/GroupsMultiSelect/index.ts
+++ b/frontend/src/metabase/common/components/GroupsMultiSelect/index.ts
@@ -1 +1 @@
-export { GroupsMultiSelect } from "./GroupsMultiSelect";
+export { GroupsMultiSelect, type GroupSection } from "./GroupsMultiSelect";
diff --git a/frontend/src/metabase/common/components/UserForm.tsx b/frontend/src/metabase/common/components/UserForm.tsx
index dffca13f2db..48190e9be41 100644
--- a/frontend/src/metabase/common/components/UserForm.tsx
+++ b/frontend/src/metabase/common/components/UserForm.tsx
@@ -1,14 +1,12 @@
import { useField } from "formik";
import type { HTMLAttributes } from "react";
import { t } from "ttag";
-import _ from "underscore";
import * as Yup from "yup";
-import { useListPermissionsGroupsQuery } from "metabase/api";
import { FormField } from "metabase/common/components/FormField";
import { FormFooter } from "metabase/common/components/FormFooter";
import { GroupsMultiSelect } from "metabase/common/components/GroupsMultiSelect";
-import { isDefaultGroup } from "metabase/common/utils/groups";
+import { isAdminGroup, isDefaultGroup } from "metabase/common/utils/groups";
import {
Form,
FormErrorMessage,
@@ -20,9 +18,9 @@ import {
PLUGIN_ADMIN_USER_FORM_FIELDS,
PLUGIN_TENANTS,
} from "metabase/plugins";
-import { Button } from "metabase/ui";
+import { Alert, Button } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
-import type { GroupId, User, UserId } from "metabase-types/api";
+import type { GroupId, GroupInfo, User, UserId } from "metabase-types/api";
const localUserSchema = Yup.object({
first_name: Yup.string().nullable().max(100, Errors.maxLength).default(null),
@@ -34,9 +32,19 @@ const externalUserSchema = localUserSchema.shape({
tenant_id: Yup.number().required(Errors.required),
});
+// Groups that can view the item the person is being invited to (Administrators is
+// implied); drives the sectioned dropdown and the no-access warning.
+interface InviteTargetAccess {
+ groupIds: GroupId[];
+ sectionLabel: string;
+ warningMessage: string;
+}
+
interface FormGroupsWidgetProps extends HTMLAttributes<HTMLDivElement> {
name: string;
external?: boolean;
+ groups?: GroupInfo[];
+ inviteTargetAccess?: InviteTargetAccess;
}
const FormGroupsWidget = ({
@@ -45,20 +53,17 @@ const FormGroupsWidget = ({
style,
title = t`Groups`,
external,
+ groups,
+ inviteTargetAccess,
}: FormGroupsWidgetProps) => {
const [{ value: formValue }, , { setValue }] =
useField<{ id: GroupId; is_group_manager?: boolean }[]>(name);
- const { data: groups, isLoading } = useListPermissionsGroupsQuery({
- tenancy: external ? "external" : "internal",
- });
-
- if (isLoading || !groups) {
+ if (!groups) {
return null;
}
- const defaultGroup = _.find(
- groups,
+ const defaultGroup = groups.find(
external ? PLUGIN_TENANTS.isExternalUsersGroup : isDefaultGroup,
);
@@ -66,23 +71,18 @@ const FormGroupsWidget = ({
formValue ??
(defaultGroup ? [{ id: defaultGroup.id, is_group_manager: false }] : []);
- // Preserve each group's manager flag across selection changes.
- const managerFlagByGroupId = new Map(
- memberships.map((membership) => [
- membership.id,
- membership.is_group_manager ?? false,
- ]),
- );
-
const handleChange = (groupIds: GroupId[]) => {
const ids = defaultGroup
? Array.from(new Set([defaultGroup.id, ...groupIds]))
: groupIds;
+ // Preserve each group's manager flag across selection changes.
setValue(
ids.map((id) => ({
id,
- is_group_manager: managerFlagByGroupId.get(id) ?? false,
+ is_group_manager:
+ memberships.find((membership) => membership.id === id)
+ ?.is_group_manager ?? false,
})),
);
};
@@ -101,6 +101,15 @@ const FormGroupsWidget = ({
);
};
+ const adminGroupId = groups.find(isAdminGroup)?.id;
+ const accessGroupIds = inviteTargetAccess && [
+ ...(adminGroupId != null ? [adminGroupId] : []),
+ ...inviteTargetAccess.groupIds,
+ ];
+ const showNoAccessWarning =
+ accessGroupIds != null &&
+ !memberships.some(({ id }) => accessGroupIds.includes(id));
+
return (
<FormField className={className} style={style} title={title}>
<GroupsMultiSelect
@@ -109,7 +118,21 @@ const FormGroupsWidget = ({
onChange={handleChange}
managerGroupIds={managerGroupIds}
onToggleManager={handleToggleManager}
+ sections={
+ inviteTargetAccess &&
+ accessGroupIds && [
+ {
+ label: inviteTargetAccess.sectionLabel,
+ groupIds: accessGroupIds,
+ },
+ ]
+ }
/>
+ {showNoAccessWarning && (
+ <Alert color="warning" size="compact" mt="sm">
+ {inviteTargetAccess?.warningMessage}
+ </Alert>
+ )}
</FormField>
);
};
@@ -124,6 +147,8 @@ interface UserFormProps {
userId?: UserId | null;
hideNameFields?: boolean;
hideAttributes?: boolean;
+ groups?: GroupInfo[];
+ inviteTargetAccess?: InviteTargetAccess;
}
export const UserForm = ({
@@ -136,6 +161,8 @@ export const UserForm = ({
userId,
hideNameFields = false,
hideAttributes = false,
+ groups,
+ inviteTargetAccess,
}: UserFormProps) => {
return (
<FormProvider
@@ -179,6 +206,8 @@ export const UserForm = ({
name="user_group_memberships"
external={external}
title={PLUGIN_TENANTS.getFormGroupsTitle(external) ?? t`Groups`}
+ groups={groups}
+ inviteTargetAccess={inviteTargetAccess}
/>
{external && (
<PLUGIN_TENANTS.FormTenantWidget
diff --git a/frontend/src/metabase/common/components/UserForm.unit.spec.tsx b/frontend/src/metabase/common/components/UserForm.unit.spec.tsx
index 71e661c941f..9bba122d1f9 100644
--- a/frontend/src/metabase/common/components/UserForm.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/UserForm.unit.spec.tsx
@@ -6,7 +6,7 @@ import { setupTenantEntpoints } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import type { Tenant } from "metabase-types/api";
+import type { GroupId, GroupInfo, Tenant, User } from "metabase-types/api";
import {
createMockGroup,
createMockTenant,
@@ -36,12 +36,18 @@ const USER = createMockUser({
interface SetupOpts {
enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
- initialValues?: typeof USER;
+ initialValues?: Partial<User>;
external?: boolean;
tenants?: Tenant[];
hideNameFields?: boolean;
hideAttributes?: boolean;
tokenFeatures?: Parameters<typeof createMockTokenFeatures>[0];
+ groups?: GroupInfo[];
+ inviteTargetAccess?: {
+ groupIds: GroupId[];
+ sectionLabel: string;
+ warningMessage: string;
+ };
}
const setup = ({
@@ -53,12 +59,12 @@ const setup = ({
hideNameFields = false,
hideAttributes = false,
tokenFeatures = { sandboxes: true, tenants: true },
+ groups = GROUPS,
+ inviteTargetAccess,
}: SetupOpts = {}) => {
const onSubmit = jest.fn();
const onCancel = jest.fn();
- fetchMock.get("path:/api/permissions/group", GROUPS);
-
setupTenantEntpoints(tenants);
const state = createMockState({
@@ -81,6 +87,8 @@ const setup = ({
external={external}
hideNameFields={hideNameFields}
hideAttributes={hideAttributes}
+ groups={groups}
+ inviteTargetAccess={inviteTargetAccess}
/>,
{
storeInitialState: state,
@@ -113,8 +121,7 @@ describe("UserForm", () => {
});
it("should not show validation errors before fields are touched (UXW-3719)", async () => {
- // Unjustified type cast. FIXME
- setup({ initialValues: {} as typeof USER });
+ setup({ initialValues: {} });
expect(await screen.findByLabelText(/Email/)).toBeInTheDocument();
expect(screen.queryByText(/required/i)).not.toBeInTheDocument();
@@ -403,6 +410,96 @@ describe("UserForm", () => {
expect(await screen.findByLabelText(/Email/)).toBeInTheDocument();
expect(screen.queryByText("Attributes")).not.toBeInTheDocument();
});
+
+ it("scopes the picker to provided groups without fetching the full list", async () => {
+ setup({
+ initialValues: {},
+ groups: [createMockGroup({ id: 7, name: "scoped" })],
+ });
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+
+ expect(
+ await screen.findByRole("option", { name: "scoped" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("option", { name: "foo" }),
+ ).not.toBeInTheDocument();
+ expect(fetchMock.callHistory.called("path:/api/permissions/group")).toBe(
+ false,
+ );
+ });
+ });
+
+ describe("item access marking (UXW-4533)", () => {
+ const INVITE_TARGET_ACCESS = {
+ groupIds: [4], // bar
+ sectionLabel: "Can view this dashboard",
+ warningMessage: "None of the selected groups can view this dashboard.",
+ };
+
+ it("warns while no selected group grants access, and clears once one is added", async () => {
+ // USER belongs to All Users (1) and foo (3); neither grants access.
+ setup({ inviteTargetAccess: INVITE_TARGET_ACCESS });
+
+ expect(
+ await screen.findByText(INVITE_TARGET_ACCESS.warningMessage),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+ await userEvent.click(await screen.findByRole("option", { name: "bar" }));
+
+ expect(
+ screen.queryByText(INVITE_TARGET_ACCESS.warningMessage),
+ ).not.toBeInTheDocument();
+ });
+
+ it("counts the Administrators group's implicit access", async () => {
+ setup({
+ inviteTargetAccess: { ...INVITE_TARGET_ACCESS, groupIds: [] },
+ initialValues: {
+ ...USER,
+ user_group_memberships: [
+ { id: 1, is_group_manager: false },
+ { id: 2, is_group_manager: false },
+ ],
+ },
+ });
+
+ expect(await screen.findByRole("list")).toBeInTheDocument();
+ expect(
+ screen.queryByText(INVITE_TARGET_ACCESS.warningMessage),
+ ).not.toBeInTheDocument();
+ });
+
+ it("places Administrators in the access section implicitly", async () => {
+ setup({ inviteTargetAccess: INVITE_TARGET_ACCESS });
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+ const accessSection = await screen.findByRole("group", {
+ name: INVITE_TARGET_ACCESS.sectionLabel,
+ });
+
+ // Administrators joins bar (the granted group) in the access section.
+ expect(
+ within(accessSection).getByRole("option", { name: "Administrators" }),
+ ).toBeInTheDocument();
+ expect(
+ within(accessSection).getByRole("option", { name: "bar" }),
+ ).toBeInTheDocument();
+ expect(
+ within(screen.getByRole("group", { name: "Other groups" })).getByRole(
+ "option",
+ { name: "foo" },
+ ),
+ ).toBeInTheDocument();
+ });
});
describe("group manager memberships (EE)", () => {
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
index f0b3fa4e03f..b9ae615ae39 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
@@ -354,6 +354,7 @@ describe("DashboardSharingMenu", () => {
describe("invite to view", () => {
const inviteAndGetRequestBody = async (dashboard: Partial<Dashboard>) => {
fetchMock.get("path:/api/permissions/group", []);
+ fetchMock.get("path:/api/permissions/invite-group-ids", []);
fetchMock.post("path:/api/user", createMockUser({ id: 99 }));
setupDashboardSharingMenu({
isAdmin: true,
@@ -401,6 +402,7 @@ describe("DashboardSharingMenu", () => {
it("opens the invite modal for the dashboard", async () => {
fetchMock.get("path:/api/permissions/group", []);
+ fetchMock.get("path:/api/permissions/invite-group-ids", []);
setupDashboardSharingMenu({ isAdmin: true });
await openMenu();
await userEvent.click(screen.getByText("Invite someone to view this"));
diff --git a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx
index 35fbfbb43fb..19762cb440a 100644
--- a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx
+++ b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx
@@ -1,7 +1,12 @@
import { type ReactNode, useEffect, useState } from "react";
import { jt, t } from "ttag";
-import { useCreateUserMutation } from "metabase/api";
+import {
+ skipToken,
+ useCreateUserMutation,
+ useListInviteGroupIdsQuery,
+ useListPermissionsGroupsQuery,
+} from "metabase/api";
import { isEmailAlreadyInUse } from "metabase/api/utils/errors";
import {
trackInviteToViewOpened,
@@ -14,7 +19,16 @@ import { useSetting, useToast } from "metabase/common/hooks";
import { useSelector } from "metabase/redux";
import { Link } from "metabase/router";
import { getSetting, isSsoEnabled } from "metabase/selectors/settings";
-import { Button, Group, Icon, Modal, Stack, Text } from "metabase/ui";
+import {
+ Button,
+ Center,
+ Group,
+ Icon,
+ Loader,
+ Modal,
+ Stack,
+ Text,
+} from "metabase/ui";
import { generatePassword } from "metabase/utils/password";
import type { InviteTarget, User } from "metabase-types/api";
@@ -53,6 +67,27 @@ export const InviteToViewModal = ({
trackInviteToViewOpened({ triggeredFrom, targetId });
}, [triggeredFrom, targetId]);
+ // isLoading, not isFetching: a tag-invalidated background refetch must not unmount the form mid-typing.
+ const {
+ data: groups,
+ isLoading: isLoadingGroups,
+ isError: isGroupsError,
+ refetch: refetchGroups,
+ } = useListPermissionsGroupsQuery(
+ inviteTarget ? { tenancy: "internal" } : skipToken,
+ );
+
+ // The access set changes whenever collection permissions do, so refetch on every open.
+ const {
+ data: accessGroupIds,
+ isFetching: isFetchingAccessGroupIds,
+ isError: isAccessGroupIdsError,
+ refetch: refetchAccessGroupIds,
+ } = useListInviteGroupIdsQuery(
+ inviteTarget ? { type: inviteTarget.type, id: inviteTarget.id } : skipToken,
+ { refetchOnMountOrArgChange: true },
+ );
+
const createInvitedUser = async (
values: Partial<User>,
password?: string,
@@ -112,10 +147,52 @@ export const InviteToViewModal = ({
onClose={onClose}
/>
);
+ } else if (isLoadingGroups || isFetchingAccessGroupIds) {
+ body = (
+ <Center py="xl">
+ <Loader />
+ </Center>
+ );
+ } else if (isGroupsError || isAccessGroupIdsError) {
+ // Without the access data the picker loses its "can view" safety net, so fail loudly instead.
+ body = (
+ <Stack gap="lg" align="center" py="xl">
+ <Text>{t`Couldn't load groups. Please try again.`}</Text>
+ <Button
+ onClick={() => {
+ refetchGroups();
+ refetchAccessGroupIds();
+ }}
+ >
+ {t`Try again`}
+ </Button>
+ </Stack>
+ );
} else {
+ const accessCopy: Record<
+ InviteTarget["type"],
+ { sectionLabel: string; warningMessage: string }
+ > = {
+ dashboard: {
+ sectionLabel: t`Can view this dashboard`,
+ warningMessage: t`None of the selected groups can view this dashboard, so this person won't be able to see it.`,
+ },
+ question: {
+ sectionLabel: t`Can view this question`,
+ warningMessage: t`None of the selected groups can view this question, so this person won't be able to see it.`,
+ },
+ };
body = (
<UserForm
initialValues={{}}
+ groups={groups}
+ inviteTargetAccess={
+ inviteTarget &&
+ accessGroupIds && {
+ groupIds: accessGroupIds,
+ ...accessCopy[inviteTarget.type],
+ }
+ }
submitText={t`Send invitation`}
onCancel={onClose}
onSubmit={
diff --git a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx
index 45b7d15b961..338c4a861d0 100644
--- a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx
+++ b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx
@@ -2,9 +2,9 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
-import type { InviteTarget } from "metabase-types/api";
+import type { GroupId, GroupInfo, InviteTarget } from "metabase-types/api";
import { createMockGroup, createMockUser } from "metabase-types/api/mocks";
import { InviteToViewModal } from "./InviteToViewModal";
@@ -15,11 +15,27 @@ const { trackUserInvited, trackInviteToViewOpened } = jest.requireMock(
"metabase/common/analytics",
);
-const GROUPS = [
- createMockGroup({ id: 1, magic_group_type: "all-internal-users" }),
- createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),
- createMockGroup({ id: 3, name: "foo", magic_group_type: null }),
-];
+const ALL_USERS = createMockGroup({
+ id: 1,
+ name: "All Users",
+ magic_group_type: "all-internal-users",
+});
+const ADMINISTRATORS = createMockGroup({
+ id: 2,
+ name: "Administrators",
+ magic_group_type: "admin",
+});
+const MARKETING = createMockGroup({
+ id: 3,
+ name: "Marketing",
+ magic_group_type: null,
+});
+const SALES = createMockGroup({ id: 4, name: "Sales", magic_group_type: null });
+
+const GROUPS: GroupInfo[] = [ALL_USERS, ADMINISTRATORS, MARKETING, SALES];
+
+// By default All Users and Marketing can view the invite target.
+const ACCESS_GROUP_IDS: GroupId[] = [ALL_USERS.id, MARKETING.id];
const TITLE = "Invite someone to view this dashboard";
@@ -39,6 +55,11 @@ interface SetupOpts {
ssoEnabled?: boolean;
passwordLoginEnabled?: boolean;
createError?: boolean;
+ groups?: GroupInfo[];
+ accessGroupIds?: GroupId[];
+ groupsError?: boolean;
+ accessGroupIdsError?: boolean;
+ inviteTarget?: InviteTarget;
}
const setup = ({
@@ -47,10 +68,22 @@ const setup = ({
ssoEnabled = false,
passwordLoginEnabled = true,
createError = false,
+ groups = GROUPS,
+ accessGroupIds = ACCESS_GROUP_IDS,
+ groupsError = false,
+ accessGroupIdsError = false,
+ inviteTarget = INVITE_TARGET,
}: SetupOpts = {}) => {
const onClose = jest.fn();
- fetchMock.get("path:/api/permissions/group", GROUPS);
+ fetchMock.get(
+ "path:/api/permissions/group",
+ groupsError ? { status: 500 } : groups,
+ );
+ fetchMock.get(
+ "path:/api/permissions/invite-group-ids",
+ accessGroupIdsError ? { status: 500 } : accessGroupIds,
+ );
fetchMock.post(
"path:/api/user",
createError
@@ -77,7 +110,7 @@ const setup = ({
title={title}
shareUrl={SHARE_URL}
triggeredFrom="dashboard"
- inviteTarget={INVITE_TARGET}
+ inviteTarget={inviteTarget}
onClose={onClose}
/>,
{ storeInitialState: state },
@@ -93,6 +126,14 @@ const submitInvite = async (email: string) => {
);
};
+const getCreateUserRequestBody = async () => {
+ const call = fetchMock.callHistory.calls("path:/api/user", {
+ method: "POST",
+ })[0];
+ // fetch-mock types the captured body as BodyInit, but hands back a promise of the JSON string
+ return JSON.parse(await (call.options?.body as unknown as Promise<string>));
+};
+
describe("InviteToViewModal", () => {
beforeEach(() => {
trackUserInvited.mockClear();
@@ -182,16 +223,132 @@ describe("InviteToViewModal", () => {
await waitFor(() => expect(onClose).toHaveBeenCalled());
- const call = fetchMock.callHistory.calls("path:/api/user", {
- method: "POST",
- })[0];
- const body = JSON.parse(
- // Unjustified type cast. FIXME
- await (call.options?.body as unknown as Promise<string>),
- );
+ const body = await getCreateUserRequestBody();
expect(body.invite_target).toEqual(INVITE_TARGET);
});
+ describe("group picker access (UXW-4533)", () => {
+ it("offers every group, sectioned by access to the item", async () => {
+ setup();
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+
+ expect(
+ await screen.findByRole("option", { name: "All Users" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("option", { name: "Administrators" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("option", { name: "Marketing" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("option", { name: "Sales" })).toBeInTheDocument();
+
+ expect(screen.getByText("Can view this dashboard")).toBeInTheDocument();
+ expect(screen.getByText("Other groups")).toBeInTheDocument();
+ });
+
+ it("labels the access section for questions", async () => {
+ setup({ inviteTarget: { type: "question", id: 7, name: "My question" } });
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+
+ expect(
+ await screen.findByText("Can view this question"),
+ ).toBeInTheDocument();
+ });
+
+ it("preselects All Users as a locked membership and leaves the rest to the admin", async () => {
+ const { onClose } = setup();
+
+ const pills = within(await screen.findByRole("list"));
+ expect(pills.getByText("All Users")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Remove All Users" }),
+ ).not.toBeInTheDocument();
+
+ await submitInvite("[email protected]");
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ // An untouched picker sends no memberships; the backend then defaults to just All Users.
+ const body = await getCreateUserRequestBody();
+ expect(body.user_group_memberships).toBeUndefined();
+ });
+
+ it("sends added groups along with the locked All Users membership", async () => {
+ const { onClose } = setup();
+
+ await userEvent.click(
+ await screen.findByRole("combobox", { name: "Groups" }),
+ );
+ await userEvent.click(
+ await screen.findByRole("option", { name: "Sales" }),
+ );
+
+ await submitInvite("[email protected]");
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ const body = await getCreateUserRequestBody();
+ expect(body.user_group_memberships).toEqual([
+ { id: ALL_USERS.id, is_group_manager: false },
+ { id: SALES.id, is_group_manager: false },
+ ]);
+ });
+
+ it("warns when no selected group can view the item, until one is added", async () => {
+ setup({ accessGroupIds: [MARKETING.id] });
+
+ expect(
+ await screen.findByText(
+ "None of the selected groups can view this dashboard, so this person won't be able to see it.",
+ ),
+ ).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Groups" }));
+ await userEvent.click(
+ await screen.findByRole("option", { name: "Marketing" }),
+ );
+
+ expect(
+ screen.queryByText(/None of the selected groups/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not warn while a selected group has access", async () => {
+ setup();
+
+ expect(await screen.findByRole("list")).toBeInTheDocument();
+ expect(
+ screen.queryByText(/None of the selected groups/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a retryable error instead of the form when the access query fails", async () => {
+ setup({ accessGroupIdsError: true });
+
+ expect(
+ await screen.findByText("Couldn't load groups. Please try again."),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Try again" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText(/Email/)).not.toBeInTheDocument();
+ });
+
+ it("shows a retryable error instead of the form when the groups query fails", async () => {
+ setup({ groupsError: true });
+
+ expect(
+ await screen.findByText("Couldn't load groups. Please try again."),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText(/Email/)).not.toBeInTheDocument();
+ });
+ });
+
it("tracks invite_to_view_opened when the modal opens", () => {
setup();
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
index d38d98ab97d..bc5245594c3 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
@@ -290,6 +290,7 @@ describe("QuestionSharingMenu", () => {
it("opens the invite modal for the question", async () => {
fetchMock.get("path:/api/permissions/group", []);
+ fetchMock.get("path:/api/permissions/invite-group-ids", []);
await setupQuestionSharingMenu({ isAdmin: true });
await openMenu();
await userEvent.click(screen.getByText("Invite someone to view this"));
diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.clj
index b83644e9906..32b47d03fbb 100644
--- a/src/metabase/permissions/core.clj
+++ b/src/metabase/permissions/core.clj
@@ -87,6 +87,7 @@
collection-based-visibility-search-models
collection-id-only-read-method
collection-id-only-read-models
+ collection-read-access-group-ids
current-user-has-application-permissions?
define-collection-based-visibility!
grant-application-permissions!
diff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.clj
index d361414ac33..359bf3cfe24 100644
--- a/src/metabase/permissions/models/permissions.clj
+++ b/src/metabase/permissions/models/permissions.clj
@@ -273,6 +273,21 @@
{:metabase.collections.models.collection.root/is-root? true
:namespace collection-namespace}))})))
+(mu/defn collection-read-access-group-ids :- [:set ms/PositiveInt]
+ "Set of `PermissionsGroup` ids holding a stored read (or read-write) permission row for the collection with
+ `collection-id`, or for the Root Collection when `collection-id` is `nil`. Reflects explicit grant rows only, so
+ groups whose access is implicit don't appear: the Administrators group never does (it has no stored collection
+ rows in normal operation), and collections that don't use grant rows at all (personal collections and their
+ descendants, trash) return an empty set."
+ [collection-id :- [:maybe ms/PositiveInt]]
+ (let [collection-or-root (or collection-id
+ {:metabase.collections.models.collection.root/is-root? true})]
+ (or (t2/select-fn-set :group_id :model/Permissions
+ {:where [:in :object
+ [(permissions.path/collection-read-path collection-or-root)
+ (permissions.path/collection-readwrite-path collection-or-root)]]})
+ #{})))
+
(doto :perms/use-parent-collection-perms
(derive ::mi/read-policy.full-perms-for-perms-set)
(derive ::mi/write-policy.full-perms-for-perms-set))
diff --git a/src/metabase/permissions_rest/api.clj b/src/metabase/permissions_rest/api.clj
index 63d03ad18ea..d8c2f0e9f53 100644
--- a/src/metabase/permissions_rest/api.clj
+++ b/src/metabase/permissions_rest/api.clj
@@ -218,6 +218,24 @@
(t2/hydrate :members)
(maybe-fix-name (setting/get :use-tenants)))))
+(api.macros/defendpoint :get "/invite-group-ids"
+ :- [:sequential ms/PositiveInt]
+ "IDs of the permission groups holding a stored read (or read-write) grant on the collection of a shareable item (a
+ `dashboard` or a `question`). The \"invite someone to view\" group picker lists all groups and uses these ids to mark
+ the ones whose members can already see the item; the Administrators group has implicit access to everything and is
+ never included. The ids are otherwise unfiltered; system-managed groups like Data Analysts appear when they hold a
+ grant, and clients intersect the ids with the groups they display. Superuser-only, like the invite action itself."
+ [_route-params
+ {:keys [id] item-type :type} :- [:map
+ [:type [:enum "dashboard" "question"]]
+ [:id ms/PositiveInt]]]
+ (api/check-superuser)
+ (let [model (case item-type
+ "dashboard" :model/Dashboard
+ "question" :model/Card)
+ item (api/read-check model id)]
+ (vec (sort (perms/collection-read-access-group-ids (:collection_id item))))))
+
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
;;
diff --git a/test/metabase/permissions_rest/api_test.clj b/test/metabase/permissions_rest/api_test.clj
index 3a79a70fb82..3a3bff0023e 100644
--- a/test/metabase/permissions_rest/api_test.clj
+++ b/test/metabase/permissions_rest/api_test.clj
@@ -3,6 +3,7 @@
(:require
[clojure.test :refer :all]
[medley.core :as m]
+ [metabase.collections.models.collection :as collection]
[metabase.config.core :as config]
[metabase.permissions-rest.api :as api.permissions]
[metabase.permissions-rest.api-test-util :as perm-test-util]
@@ -167,6 +168,61 @@
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (format "permissions/group/%d" (:id (perms-group/all-users)))))))))
+(deftest invite-group-ids-test
+ (testing "GET /api/permissions/invite-group-ids"
+ (mt/with-temp [:model/Collection coll {}
+ :model/Dashboard dash {:collection_id (u/the-id coll)}
+ :model/PermissionsGroup readers {:name "Readers"}
+ :model/PermissionsGroup writers {:name "Writers"}
+ :model/PermissionsGroup no-access {:name "No access"}]
+ (perms/grant-collection-read-permissions! readers coll)
+ (perms/grant-collection-readwrite-permissions! writers coll)
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll)
+ (perms/grant-collection-read-permissions! (perms-group/data-analyst) coll)
+ (let [ids (set (mt/user-http-request :crowberto :get 200 "permissions/invite-group-ids"
+ :type "dashboard" :id (u/the-id dash)))]
+ (testing "includes ids of groups with read or read-write access to the item's collection"
+ (is (contains? ids (u/the-id readers)))
+ (is (contains? ids (u/the-id writers)))
+ (is (contains? ids (u/the-id (perms-group/all-users)))))
+ (testing "the ids are unfiltered: system-managed groups like Data Analysts are included when they hold a grant"
+ (is (contains? ids (u/the-id (perms-group/data-analyst)))))
+ (testing "excludes groups without access"
+ (is (not (contains? ids (u/the-id no-access)))))
+ (testing "excludes the Administrators group, whose access is implicit rather than granted"
+ (is (not (contains? ids (u/the-id (perms-group/admin))))))))
+ (testing "works for questions, resolving the card's collection"
+ (mt/with-temp [:model/Collection coll {}
+ :model/Card card {:collection_id (u/the-id coll)}
+ :model/PermissionsGroup g {:name "Q Readers"}]
+ (perms/grant-collection-read-permissions! g coll)
+ (is (contains? (set (mt/user-http-request :crowberto :get 200 "permissions/invite-group-ids"
+ :type "question" :id (u/the-id card)))
+ (u/the-id g)))))
+ (testing "resolves the Root collection for items with no collection_id"
+ (mt/with-temp [:model/PermissionsGroup g {:name "Root Readers"}
+ :model/Dashboard dash {:collection_id nil}
+ :model/Permissions _ {:group_id (u/the-id g), :object "/collection/root/read/"}]
+ (is (contains? (set (mt/user-http-request :crowberto :get 200 "permissions/invite-group-ids"
+ :type "dashboard" :id (u/the-id dash)))
+ (u/the-id g)))))
+ (testing "returns no ids for an item in a personal collection (no permission rows exist)"
+ (let [personal-coll (collection/user->personal-collection (mt/user->id :crowberto))]
+ (mt/with-temp [:model/Dashboard dash {:collection_id (u/the-id personal-coll)}]
+ (is (= [] (mt/user-http-request :crowberto :get 200 "permissions/invite-group-ids"
+ :type "dashboard" :id (u/the-id dash)))))))
+ (testing "requires superuser, even for users who can read the item"
+ (mt/with-temp [:model/Collection coll {}
+ :model/Dashboard dash {:collection_id (u/the-id coll)}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "permissions/invite-group-ids"
+ :type "dashboard" :id (u/the-id dash))))))
+ (testing "returns 404 for a nonexistent item"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :get 404 "permissions/invite-group-ids"
+ :type "dashboard" :id Integer/MAX_VALUE))))))
+
(deftest create-group-test
(testing "POST /permissions/group"
(testing "happy path"