Skip to content

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

Allow internal users to have perms on tenant colls (#68181)

John Swanson25cd50c5c483
diff --git a/e2e/support/helpers/e2e-permissions-helpers.js b/e2e/support/helpers/e2e-permissions-helpers.js
index 0e87bc29221..72bcd927c61 100644
--- a/e2e/support/helpers/e2e-permissions-helpers.js
+++ b/e2e/support/helpers/e2e-permissions-helpers.js
@@ -17,18 +17,20 @@ export function modifyPermission(
item,
permissionIndex,
value,
- shouldPropagate = null,
+ shouldPropagateToChildren = null,
) {
selectPermissionRow(item, permissionIndex);
popover()
.should("have.length", 1)
.within(() => {
- if (shouldPropagate !== null) {
+ if (shouldPropagateToChildren !== null) {
cy.findByRole("switch")
.as("toggle")
.then(($el) => {
- if ($el.attr("aria-checked") !== shouldPropagate.toString()) {
+ if (
+ $el.attr("aria-checked") !== shouldPropagateToChildren.toString()
+ ) {
cy.get("@toggle").click();
}
});
diff --git a/enterprise/backend/src/metabase_enterprise/tenants/api.clj b/enterprise/backend/src/metabase_enterprise/tenants/api.clj
index ec271ebe183..522189b0065 100644
--- a/enterprise/backend/src/metabase_enterprise/tenants/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/tenants/api.clj
@@ -5,6 +5,7 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
+ [metabase.collections.models.collection :as collection]
[metabase.events.core :as events]
[metabase.request.core :as request]
[metabase.util :as u]
@@ -66,7 +67,7 @@
{:keys [status]} :- [:map
[:status {:default "all"} [:enum "all" "deactivated" "active"]]]
_]
- (api/check-403 api/*is-superuser?*)
+ (api/check-403 (or api/*is-superuser?* (not (:tenant_id @api/*current-user*))))
{:data (present-tenants
(t2/select :model/Tenant (cond-> {:order-by [[:id :asc]]}
(request/paged?) (assoc :limit (request/limit) :offset (request/offset))
@@ -85,18 +86,28 @@
"Updates a tenant, publishing any necessary events after doing so"
[tenant-id :- ms/PositiveInt
{:keys [is_active] :as tenant} :- UpdateTenantArguments]
- (when (false? is_active)
- (t2/update! :model/User {:is_active true :tenant_id tenant-id}
- {:is_active false :deactivated_with_tenant true}))
- (when (true? is_active)
- (t2/update! :model/User {:is_active false :tenant_id tenant-id :deactivated_with_tenant true}
- {:is_active true :deactivated_with_tenant nil}))
- (let [tenant-before-update (t2/select-one :model/Tenant tenant-id)
- _ (t2/update! :model/Tenant {:id tenant-id} tenant)
- tenant-after-update (t2/select-one :model/Tenant tenant-id)]
- (events/publish-event! :event/tenant-update {:object tenant-after-update
- :previous-object tenant-before-update})
- tenant-after-update))
+ (t2/with-transaction [_cn]
+ (collection/with-allow-modifying-tenant-root-collections
+ (let [tenant-before-update (t2/select-one :model/Tenant tenant-id)
+ _ (t2/update! :model/Tenant {:id tenant-id} tenant)
+ tenant-after-update (t2/select-one :model/Tenant tenant-id)]
+ (when (false? is_active)
+ (t2/update! :model/User {:is_active true :tenant_id tenant-id}
+ {:is_active false :deactivated_with_tenant true})
+ (some-> (t2/select-one :model/Collection
+ :id (:tenant_collection_id tenant-before-update)
+ :archived false)
+ collection/archive-collection!))
+ (when (true? is_active)
+ (t2/update! :model/User {:is_active false :tenant_id tenant-id :deactivated_with_tenant true}
+ {:is_active true :deactivated_with_tenant nil})
+ (some-> (t2/select-one :model/Collection
+ :id (:tenant_collection_id tenant-before-update)
+ :archived true)
+ (collection/unarchive-collection! {})))
+ (events/publish-event! :event/tenant-update {:object tenant-after-update
+ :previous-object tenant-before-update})
+ tenant-after-update))))
(api.macros/defendpoint :put "/:id" :- Tenant
"Update a tenant, can set name, attributes, or whether this tenant is active."
@@ -112,7 +123,7 @@
(api.macros/defendpoint :get "/:id" :- Tenant
"Get info about a tenant"
[{id :id} :- [:map {:closed true} [:id ms/PositiveInt]]]
- (api/check-403 api/*is-superuser?*)
+ (api/check-403 (or api/*is-superuser?* (not (:tenant_id @api/*current-user*))))
(present-tenant (t2/select-one :model/Tenant :id id)))
(def ^{:arglists '([request respond raise])} routes
diff --git a/enterprise/backend/src/metabase_enterprise/tenants/model.clj b/enterprise/backend/src/metabase_enterprise/tenants/model.clj
index 728a0b0c602..c2fa577d67b 100644
--- a/enterprise/backend/src/metabase_enterprise/tenants/model.clj
+++ b/enterprise/backend/src/metabase_enterprise/tenants/model.clj
@@ -2,6 +2,7 @@
(:require
[metabase.api.common :as api]
[metabase.audit-app.core :as audit-app]
+ [metabase.collections.models.collection :as collection]
[metabase.models.interface :as mi]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.util :as u]
@@ -26,7 +27,7 @@
(t2/define-before-insert :model/Tenant
[tenant]
- (let [tenant-collection-id (t2/insert-returning-pk! :model/Collection {:type "tenant-specific-root-collection"
+ (let [tenant-collection-id (t2/insert-returning-pk! :model/Collection {:type collection/tenant-specific-root-collection-type
:name (format "Tenant Collection: %s" (:name tenant))
:namespace "tenant-specific"})]
(u/prog1 (assoc tenant :tenant_collection_id tenant-collection-id)
@@ -92,7 +93,7 @@
:feature :tenants
[collections]
(let [tenant-collection-ids (keep (fn [c]
- (when (= (:type c) "tenant-specific-root-collection")
+ (when (= (:type c) collection/tenant-specific-root-collection-type)
(:id c)))
collections)
collection-id->tenant-name-and-id
@@ -102,7 +103,7 @@
:tenant_collection_id [:in tenant-collection-ids]))]
(mapv (fn [{ttype :type id :id :as coll}]
(cond-> coll
- (= ttype "tenant-specific-root-collection")
+ (= ttype collection/tenant-specific-root-collection-type)
(assoc :name (if-let [user-tenant-id (:tenant_id @api/*current-user*)]
(let [[_tenant-name tenant-id] (collection-id->tenant-name-and-id id)]
;; this should never happen, but juuuuuust in case
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
index 01490c77999..1094320910d 100644
--- a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
@@ -641,7 +641,7 @@
(deftest shared-tenant-collections-appear-in-trash-test
(testing "GET /api/collection/:id/items for trash collection"
- (testing "archived collections with shared-tenant-collection and tenant-specific namespaces appear in trash"
+ (testing "archived collections with shared-tenant-collection namespace appear in trash"
(mt/with-premium-features #{:tenants}
(mt/with-temporary-setting-values [use-tenants true]
(mt/with-temp [:model/Collection {normal-id :id} {:name "Normal Collection"}
@@ -658,3 +658,87 @@
(into #{}))]
(is (= #{"Normal Collection" "Shared Tenant Collection" "Tenant Specific Collection"}
trash-items)))))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Tenant Deactivation Archives Collections Tests |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(deftest tenant-collection-archived-when-tenant-deactivated-test
+ (testing "Tenant-specific root collection is archived when tenant is deactivated"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id
+ tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test-archive"}]
+ (testing "initially the collection is not archived"
+ (is (false? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id))))
+ (testing "deactivate the tenant"
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active false}))
+ (testing "tenant collection is now archived"
+ (is (true? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))))))))
+
+(deftest tenant-collection-children-archived-when-tenant-deactivated-test
+ (testing "Children of tenant-specific collection are also archived when tenant is deactivated"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id
+ tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test-children"}]
+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]
+ (mt/with-temp [:model/Collection {child-id :id} {:name "Child Collection"
+ :namespace :tenant-specific
+ :location (collection/children-location tenant-coll)}
+ :model/Collection {grandchild-id :id} {:name "Grandchild Collection"
+ :namespace :tenant-specific
+ :location (str (collection/children-location tenant-coll)
+ child-id "/")}]
+ (testing "initially none of the collections are archived"
+ (is (false? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))
+ (is (false? (t2/select-one-fn :archived :model/Collection :id child-id)))
+ (is (false? (t2/select-one-fn :archived :model/Collection :id grandchild-id))))
+ (testing "deactivate the tenant"
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active false}))
+ (testing "all collections are now archived"
+ (is (true? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))
+ (is (true? (t2/select-one-fn :archived :model/Collection :id child-id)))
+ (is (true? (t2/select-one-fn :archived :model/Collection :id grandchild-id)))))))))))
+
+(deftest tenant-collection-unarchived-when-tenant-reactivated-test
+ (testing "Tenant-specific root collection is unarchived when tenant is reactivated"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id
+ tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test-unarchive"}]
+ ;; First deactivate
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active false})
+ (testing "collection is archived after deactivation"
+ (is (true? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id))))
+ ;; Then reactivate
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active true})
+ (testing "collection is unarchived after reactivation"
+ (is (false? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))))))))
+
+(deftest tenant-collection-children-unarchived-when-tenant-reactivated-test
+ (testing "Children of tenant-specific collection are also unarchived when tenant is reactivated"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id
+ tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test-children-unarchive"}]
+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]
+ (mt/with-temp [:model/Collection {child-id :id} {:name "Child Collection"
+ :namespace :tenant-specific
+ :location (collection/children-location tenant-coll)}
+ :model/Collection {grandchild-id :id} {:name "Grandchild Collection"
+ :namespace :tenant-specific
+ :location (str (collection/children-location tenant-coll)
+ child-id "/")}]
+ ;; First deactivate
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active false})
+ (testing "all collections are archived after deactivation"
+ (is (true? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))
+ (is (true? (t2/select-one-fn :archived :model/Collection :id child-id)))
+ (is (true? (t2/select-one-fn :archived :model/Collection :id grandchild-id))))
+ ;; Then reactivate
+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active true})
+ (testing "all collections are unarchived after reactivation"
+ (is (false? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))
+ (is (false? (t2/select-one-fn :archived :model/Collection :id child-id)))
+ (is (false? (t2/select-one-fn :archived :model/Collection :id grandchild-id)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj
index 5367170e7fb..b334ef84e5b 100644
--- a/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj
@@ -132,7 +132,7 @@
(testing "attempting to set personal_owner_id should fail"
(is (thrown-with-msg?
Exception
- #"Personal Collections must be in the default namespace"
+ #"You are not allowed to change the owner of a Tenant Collection."
(t2/update! :model/Collection tenant-collection-id
{:personal_owner_id user-id}))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/CanAccessTenantSpecificRoute.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/CanAccessTenantSpecificRoute.tsx
new file mode 100644
index 00000000000..6280080c5d6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/CanAccessTenantSpecificRoute.tsx
@@ -0,0 +1,37 @@
+import type { ReactNode } from "react";
+
+import { useGetCollectionQuery } from "metabase/api";
+import { Unauthorized } from "metabase/common/components/ErrorPages";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useSelector } from "metabase/lib/redux";
+import { getUserIsAdmin } from "metabase/selectors/user";
+
+type Props = {
+ children: ReactNode;
+};
+
+export const CanAccessTenantSpecificRoute = ({ children }: Props) => {
+ const isAdmin = useSelector(getUserIsAdmin);
+
+ // Admins always have access, skip the API call
+ const { data, isLoading } = useGetCollectionQuery(
+ { id: "root", namespace: "tenant-specific" },
+ { skip: isAdmin },
+ );
+
+ if (isAdmin) {
+ return <>{children}</>;
+ }
+
+ if (isLoading) {
+ return <LoadingAndErrorWrapper loading />;
+ }
+
+ // If we got data back, user has access
+ if (data) {
+ return <>{children}</>;
+ }
+
+ // Error or no data means no access
+ return <Unauthorized />;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/index.ts
new file mode 100644
index 00000000000..b3fddf40ee5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/CanAccessTenantSpecificRoute/index.ts
@@ -0,0 +1 @@
+export { CanAccessTenantSpecificRoute } from "./CanAccessTenantSpecificRoute";
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
index 926775cd295..de2aa497962 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
@@ -28,9 +28,11 @@ import { CollectionSyncStatusBadge } from "metabase-enterprise/remote_sync/compo
import type { Collection } from "metabase-types/api";
export const MainNavSharedCollections = ({
+ canAccessTenantSpecificCollections,
canCreateSharedCollection,
sharedTenantCollections,
}: {
+ canAccessTenantSpecificCollections: boolean;
canCreateSharedCollection: boolean;
sharedTenantCollections: Collection[] | undefined;
}) => {
@@ -109,7 +111,9 @@ export const MainNavSharedCollections = ({
sharedTenantCollectionTree.length > 0;
const shouldShowSharedCollectionsSection =
- hasVisibleSharedTenantCollections || canCreateSharedCollection;
+ hasVisibleSharedTenantCollections ||
+ canCreateSharedCollection ||
+ canAccessTenantSpecificCollections;
return (
<>
@@ -142,7 +146,7 @@ export const MainNavSharedCollections = ({
showChangesBadge(item?.id) && <CollectionSyncStatusBadge />
}
/>
- {isAdmin && (
+ {canAccessTenantSpecificCollections && (
<PaddedSidebarLink icon="group" url={tenantSpecificCollections()}>
{t`Tenant collections`}
</PaddedSidebarLink>
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
index 12f95069ec5..54ed15d278b 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
@@ -22,11 +22,13 @@ const setup = ({
tenantCollections = MOCK_TENANT_COLLECTIONS,
currentUser = createMockUser({ is_superuser: isAdmin }),
canWriteToSharedCollectionRoot = false,
+ canAccessTenantSpecificCollections = isAdmin,
}: {
isAdmin?: boolean;
tenantCollections?: Collection[];
currentUser?: ReturnType<typeof createMockUser>;
canWriteToSharedCollectionRoot?: boolean;
+ canAccessTenantSpecificCollections?: boolean;
} = {}) => {
const settings = mockSettings({ "use-tenants": true });
@@ -42,6 +44,7 @@ const setup = ({
renderWithProviders(
<MainNavSharedCollections
+ canAccessTenantSpecificCollections={canAccessTenantSpecificCollections}
canCreateSharedCollection={canWriteToSharedCollectionRoot}
sharedTenantCollections={tenantCollections}
/>,
@@ -142,6 +145,7 @@ describe("MainNavSharedCollections > section visibility", () => {
renderWithProviders(
<MainNavSharedCollections
+ canAccessTenantSpecificCollections={false}
canCreateSharedCollection={false}
sharedTenantCollections={[]}
/>,
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
index 388409b4e19..53f7ec9edf9 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx
@@ -58,7 +58,7 @@ type UpdateCollectionPermissionParams = {
groupId: GroupId;
collection: Collection;
value: unknown;
- shouldPropagate: boolean;
+ shouldPropagateToChildren: boolean;
};
type TenantCollectionPermissionsPageProps = {
@@ -71,7 +71,7 @@ type TenantCollectionPermissionsPageProps = {
groupId,
collection,
value,
- shouldPropagate,
+ shouldPropagateToChildren,
}: UpdateCollectionPermissionParams) => void;
isDirty: boolean;
savePermissions: () => void;
@@ -107,7 +107,7 @@ function TenantCollectionPermissionsPageView({
groupId: item.id,
collection,
value,
- shouldPropagate: toggleState,
+ shouldPropagateToChildren: toggleState,
});
},
[collection, updateCollectionPermission],
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts
index 452a0d40311..826edd1a795 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts
@@ -5,6 +5,7 @@ import { createMockTokenFeatures } from "metabase-types/api/mocks";
import type { State } from "metabase-types/store";
import {
createMockAdminState,
+ createMockPermissionsState,
createMockState,
} from "metabase-types/store/mocks";
@@ -34,16 +35,10 @@ const createMockStateWithPermissions = ({
"token-features": createMockTokenFeatures({ tenants: true }),
}),
admin: createMockAdminState({
- permissions: {
- dataPermissions: {},
- originalDataPermissions: {},
- collectionPermissions: {},
- originalCollectionPermissions: {},
+ permissions: createMockPermissionsState({
tenantCollectionPermissions,
originalTenantCollectionPermissions,
- isHelpReferenceOpen: false,
- hasRevisionChanged: { revision: null, hasChanged: false },
- },
+ }),
}),
});
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/TenantSpecificCollectionPermissionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/TenantSpecificCollectionPermissionsPage.tsx
new file mode 100644
index 00000000000..f26f04b2b95
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/TenantSpecificCollectionPermissionsPage.tsx
@@ -0,0 +1,162 @@
+import { useCallback, useEffect, useMemo } from "react";
+import type { Route } from "react-router";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { CollectionPermissionsHelp } from "metabase/admin/permissions/components/CollectionPermissionsHelp";
+import {
+ PermissionsEditor,
+ PermissionsEditorEmptyState,
+} from "metabase/admin/permissions/components/PermissionsEditor";
+import { PermissionsPageLayout } from "metabase/admin/permissions/components/PermissionsPageLayout";
+import { PermissionsSidebar } from "metabase/admin/permissions/components/PermissionsSidebar";
+import {
+ initializeTenantSpecificCollectionPermissions,
+ loadTenantSpecificCollectionPermissions,
+ saveTenantSpecificCollectionPermissions,
+ updateTenantSpecificCollectionPermission,
+} from "metabase/admin/permissions/permissions";
+import type { CollectionIdProps } from "metabase/admin/permissions/selectors/collection-permissions";
+import { Collections } from "metabase/entities/collections";
+import { Groups } from "metabase/entities/groups";
+import { useDispatch, useSelector } from "metabase/lib/redux";
+import type { Collection, CollectionId, GroupId } from "metabase-types/api";
+
+import {
+ getIsTenantSpecificDirty,
+ getTenantSpecificCollectionEntity,
+ getTenantSpecificCollectionsPermissionEditor,
+ getTenantSpecificCollectionsSidebar,
+ tenantSpecificCollectionsQuery,
+} from "./selectors";
+
+type UpdateCollectionPermissionParams = {
+ groupId: GroupId;
+ collection: Collection;
+ value: unknown;
+ shouldPropagateToChildren: boolean;
+};
+
+type TenantSpecificCollectionPermissionsPageProps = {
+ params: CollectionIdProps["params"];
+ route: Route;
+};
+
+function TenantSpecificCollectionPermissionsPageView({
+ params,
+ route,
+}: TenantSpecificCollectionPermissionsPageProps) {
+ const dispatch = useDispatch();
+
+ const props = useMemo(() => ({ params }), [params]);
+ const sidebar = useSelector((state) =>
+ getTenantSpecificCollectionsSidebar(state, props),
+ );
+ const permissionEditor = useSelector((state) =>
+ getTenantSpecificCollectionsPermissionEditor(state, props),
+ );
+ const isDirty = useSelector(getIsTenantSpecificDirty);
+ const collection = useSelector((state) =>
+ getTenantSpecificCollectionEntity(state, props),
+ );
+
+ const initialize = useCallback(() => {
+ dispatch(initializeTenantSpecificCollectionPermissions());
+ }, [dispatch]);
+
+ const loadPermissions = useCallback(() => {
+ dispatch(loadTenantSpecificCollectionPermissions());
+ }, [dispatch]);
+
+ const savePermissions = useCallback(() => {
+ dispatch(saveTenantSpecificCollectionPermissions());
+ }, [dispatch]);
+
+ const navigateToItem = useCallback(
+ ({ id }: { id: CollectionId }) => {
+ dispatch(push(`/admin/permissions/tenant-specific-collections/${id}`));
+ },
+ [dispatch],
+ );
+
+ const updateCollectionPermission = useCallback(
+ ({
+ groupId,
+ collection,
+ value,
+ shouldPropagateToChildren,
+ }: UpdateCollectionPermissionParams) => {
+ dispatch(
+ updateTenantSpecificCollectionPermission({
+ groupId,
+ collection,
+ value,
+ shouldPropagateToChildren,
+ }),
+ );
+ },
+ [dispatch],
+ );
+
+ useEffect(() => {
+ initialize();
+ }, [initialize]);
+
+ const handlePermissionChange = useCallback(
+ (
+ item: { id: GroupId },
+ _permission: unknown,
+ value: unknown,
+ _toggleState: boolean,
+ ) => {
+ if (!collection) {
+ return;
+ }
+ // Always propagate to sub-collections for tenant-specific collections
+ updateCollectionPermission({
+ groupId: item.id,
+ collection: collection as Collection,
+ value,
+ shouldPropagateToChildren: true,
+ });
+ },
+ [collection, updateCollectionPermission],
+ );
+
+ return (
+ <PermissionsPageLayout
+ tab="tenant-specific-collections"
+ isDirty={isDirty}
+ route={route}
+ onSave={savePermissions}
+ onLoad={() => loadPermissions()}
+ helpContent={<CollectionPermissionsHelp />}
+ >
+ <PermissionsSidebar {...sidebar} onSelect={navigateToItem} />
+
+ {!permissionEditor && (
+ <PermissionsEditorEmptyState
+ icon="folder"
+ message={t`Select a collection to see its permissions`}
+ />
+ )}
+
+ {permissionEditor && (
+ <PermissionsEditor
+ isLoading={undefined}
+ error={undefined}
+ {...permissionEditor}
+ onChange={handlePermissionChange}
+ />
+ )}
+ </PermissionsPageLayout>
+ );
+}
+
+export const TenantSpecificCollectionPermissionsPage = _.compose(
+ Collections.loadList({
+ entityQuery: tenantSpecificCollectionsQuery,
+ }),
+ Groups.loadList(),
+)(TenantSpecificCollectionPermissionsPageView);
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/index.ts
new file mode 100644
index 00000000000..8adafc08c13
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/index.ts
@@ -0,0 +1 @@
+export { TenantSpecificCollectionPermissionsPage } from "./TenantSpecificCollectionPermissionsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/selectors.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/selectors.tsx
new file mode 100644
index 00000000000..f0bd8238243
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionPermissionsPage/selectors.tsx
@@ -0,0 +1,259 @@
+import { createSelector } from "@reduxjs/toolkit";
+import { getIn } from "icepick";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { COLLECTION_OPTIONS } from "metabase/admin/permissions/constants/collections-permissions";
+import { Messages } from "metabase/admin/permissions/constants/messages";
+import type {
+ CollectionIdProps,
+ CollectionPermissionEditorType,
+ CollectionSidebarType,
+} from "metabase/admin/permissions/selectors/collection-permissions";
+import { getPermissionWarningModal } from "metabase/admin/permissions/selectors/confirmations";
+import type { DataPermissionValue } from "metabase/admin/permissions/types";
+import { findCollectionById } from "metabase/common/utils/collections";
+import {
+ Collections,
+ ROOT_COLLECTION,
+ getCollectionIcon,
+} from "metabase/entities/collections";
+import { Groups } from "metabase/entities/groups";
+import {
+ getGroupNameLocalized,
+ isAdminGroup,
+ isDefaultGroup,
+} from "metabase/lib/groups";
+import { PLUGIN_TENANTS } from "metabase/plugins";
+import type {
+ CollectionId,
+ CollectionPermissions,
+ Group as GroupType,
+} from "metabase-types/api";
+import type { ExpandedCollection, State } from "metabase-types/store";
+
+export const tenantSpecificCollectionsQuery = {
+ tree: true,
+ "exclude-other-user-collections": true,
+ "exclude-archived": true,
+ namespace: "tenant-specific",
+};
+
+export const getIsTenantSpecificDirty = createSelector(
+ (state: State) => state.admin.permissions.tenantSpecificCollectionPermissions,
+ (state: State) =>
+ state.admin.permissions.originalTenantSpecificCollectionPermissions,
+ (
+ permissions: CollectionPermissions,
+ originalPermissions: CollectionPermissions,
+ ) => !_.isEqual(permissions, originalPermissions),
+);
+
+export const getCurrentTenantSpecificCollectionId = (
+ _state: State,
+ props: CollectionIdProps,
+) => {
+ if (props.params.collectionId == null) {
+ return undefined;
+ }
+
+ // collectionId comes from the route param and is either "root" or a numeric string
+ return props.params.collectionId === ROOT_COLLECTION.id
+ ? ROOT_COLLECTION.id
+ : parseInt(String(props.params.collectionId));
+};
+
+const getTenantSpecificRootCollectionTreeItem = () => {
+ const rootCollectionIcon = getCollectionIcon(ROOT_COLLECTION);
+ return {
+ ...ROOT_COLLECTION,
+ name: t`Root tenant collection`,
+ icon: rootCollectionIcon.name,
+ iconColor: rootCollectionIcon.color,
+ };
+};
+
+const getTenantSpecificCollections = (state: State) =>
+ Collections.selectors.getList(state, {
+ entityQuery: tenantSpecificCollectionsQuery,
+ }) ?? [];
+
+const getTenantSpecificCollectionsTree = () => {
+ // Only show the single "Root tenant collection" in the sidebar
+ return [getTenantSpecificRootCollectionTreeItem()];
+};
+
+export const getTenantSpecificCollectionsSidebar = createSelector(
+ getTenantSpecificCollectionsTree,
+ getCurrentTenantSpecificCollectionId,
+ (collectionsTree, collectionId): CollectionSidebarType => {
+ return {
+ selectedId: collectionId,
+ title: t`Tenant collections`,
+ entityGroups: [collectionsTree || []],
+ filterPlaceholder: t`Search for a collection`,
+ };
+ },
+);
+
+const getTenantSpecificCollectionsPermissions = (state: State) =>
+ state.admin.permissions.tenantSpecificCollectionPermissions;
+
+const getTenantSpecificCollection = createSelector(
+ [getCurrentTenantSpecificCollectionId, getTenantSpecificCollections],
+ (collectionId, collections) => {
+ if (collectionId == null) {
+ return null;
+ }
+
+ if (collectionId === ROOT_COLLECTION.id) {
+ return {
+ ...ROOT_COLLECTION,
+ name: t`Root tenant collection`,
+ children: collections,
+ };
+ }
+
+ return findCollectionById(collections, collectionId);
+ },
+);
+
+export const getTenantSpecificCollectionEntity = (
+ state: State,
+ props: CollectionIdProps,
+) => {
+ return getTenantSpecificCollection(state, props);
+};
+
+const getTenantSpecificCollectionPermission = (
+ permissions: CollectionPermissions,
+ groupId: number,
+ collectionId: CollectionId,
+) => getIn(permissions, [groupId, collectionId]) || "none";
+
+export const getTenantSpecificCollectionsPermissionEditor = createSelector(
+ getTenantSpecificCollectionsPermissions,
+ getTenantSpecificCollectionEntity,
+ Groups.selectors.getList,
+ (permissions, collection, groups): CollectionPermissionEditorType => {
+ if (!permissions || collection == null) {
+ return null;
+ }
+
+ // Filter out tenant groups - they get implicit permissions based on tenant membership
+ const nonTenantGroups = groups.filter(
+ (group: GroupType) => !PLUGIN_TENANTS.isTenantGroup(group),
+ );
+
+ const entities = nonTenantGroups
+ .map((group: GroupType) => {
+ const isAdmin = isAdminGroup(group);
+
+ const defaultGroup = _.find(nonTenantGroups, isDefaultGroup);
+
+ const defaultGroupPermission = defaultGroup
+ ? getTenantSpecificCollectionPermission(
+ permissions,
+ defaultGroup.id,
+ collection.id,
+ )
+ : "none";
+
+ const confirmations = (newValue: DataPermissionValue) => [
+ getPermissionWarningModal(
+ newValue,
+ defaultGroupPermission,
+ null,
+ defaultGroup,
+ group.id,
+ ),
+ ];
+
+ const options = [
+ COLLECTION_OPTIONS.write,
+ COLLECTION_OPTIONS.read,
+ COLLECTION_OPTIONS.none,
+ ];
+
+ const disabled = isAdmin;
+
+ return {
+ id: group.id,
+ name: getGroupNameLocalized(group),
+ permissions: [
+ {
+ // Always show toggle as checked and disabled for tenant-specific collections
+ toggleLabel: t`Also change sub-collections`,
+ hasChildren: true,
+ toggleDisabled: true,
+ toggleDefaultValue: true,
+ isDisabled: disabled,
+ disabledTooltip: disabled
+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS
+ : null,
+ value: getTenantSpecificCollectionPermission(
+ permissions,
+ group.id,
+ collection.id,
+ ),
+ warning: getTenantSpecificCollectionWarning(
+ group.id,
+ collection as ExpandedCollection,
+ permissions,
+ ),
+ confirmations,
+ options,
+ },
+ ],
+ };
+ })
+ .filter(Boolean);
+
+ return {
+ title: t`Permissions for ${collection.name}`,
+ filterPlaceholder: t`Search for a group`,
+ columns: [{ name: t`Group name` }, { name: t`Collection access` }],
+ entities,
+ };
+ },
+);
+
+const permissionsCollectionFilter = (collection: ExpandedCollection) =>
+ !collection.is_personal;
+
+function getDescendentCollections(
+ collection: ExpandedCollection,
+): ExpandedCollection[] {
+ const subCollections =
+ collection.children?.filter(permissionsCollectionFilter) || [];
+ return subCollections.concat(...subCollections.map(getDescendentCollections));
+}
+
+function getTenantSpecificCollectionWarning(
+ groupId: number,
+ collection: ExpandedCollection,
+ permissions: CollectionPermissions,
+) {
+ if (!collection) {
+ return;
+ }
+ const collectionPerm = getTenantSpecificCollectionPermission(
+ permissions,
+ groupId,
+ collection.id,
+ );
+ const descendentCollections = getDescendentCollections(collection);
+ const descendentPerms = new Set(
+ descendentCollections.map((c) =>
+ getTenantSpecificCollectionPermission(permissions, groupId, c.id),
+ ),
+ );
+ if (
+ collectionPerm === "none" &&
+ (descendentPerms.has("read") || descendentPerms.has("write"))
+ ) {
+ return t`This group has permission to view at least one subcollection of this collection.`;
+ } else if (collectionPerm === "read" && descendentPerms.has("write")) {
+ return t`This group has permission to edit at least one subcollection of this collection.`;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 880b9d3c21c..91fc46a98b0 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -25,13 +25,14 @@ import {
PLUGIN_ADMIN_USER_MENU_ROUTES,
PLUGIN_TENANTS,
} from "metabase/plugins";
-import { getIsTenantUser } from "metabase/selectors/user";
+import { getIsTenantUser, getUserIsAdmin } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Text } from "metabase/ui";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { EditUserStrategyModal } from "./EditUserStrategyModal";
import { EditUserStrategySettingsButton } from "./EditUserStrategySettingsButton";
+import { CanAccessTenantSpecificRoute } from "./components/CanAccessTenantSpecificRoute";
import { ExternalGroupDetailApp } from "./components/ExternalGroupDetailApp/ExternalGroupDetailApp";
import { ExternalGroupsListingApp } from "./components/ExternalGroupsListingApp/ExternalGroupsListingApp";
import { ExternalPeopleListingApp } from "./components/ExternalPeopleListingApp/ExternalPeopleListingApp";
@@ -43,6 +44,7 @@ import { TenantCollectionPermissionsPage } from "./components/TenantCollectionPe
import { TenantDisplayName } from "./components/TenantDisplayName";
import { FormTenantWidget } from "./components/TenantFormWidget";
import { TenantGroupHintIcon } from "./components/TenantGroupHintIcon";
+import { TenantSpecificCollectionPermissionsPage } from "./components/TenantSpecificCollectionPermissionsPage";
import { TenantSpecificCollectionsItemList } from "./components/TenantSpecificCollectionsItemList";
import { TenantUsersList } from "./components/TenantUsersList";
import { TenantUsersPersonalCollectionList } from "./components/TenantUsersPersonalCollectionList";
@@ -68,19 +70,32 @@ export function initializePlugin() {
if (hasPremiumFeature("tenants")) {
PLUGIN_TENANTS.isEnabled = true;
- // Register tenant collection permissions tab and routes
+ // Register tenant collection permissions tabs and routes
PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.push({
name: t`Shared collections`,
value: "tenant-collections",
});
+ PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.push({
+ name: t`Tenant collections`,
+ value: "tenant-specific-collections",
+ });
+
PLUGIN_ADMIN_PERMISSIONS_TABS.getRoutes = () => (
- <Route
- path="tenant-collections"
- component={TenantCollectionPermissionsPage}
- >
- <Route path=":collectionId" />
- </Route>
+ <>
+ <Route
+ path="tenant-collections"
+ component={TenantCollectionPermissionsPage}
+ >
+ <Route path=":collectionId" />
+ </Route>
+ <Route
+ path="tenant-specific-collections"
+ component={TenantSpecificCollectionPermissionsPage}
+ >
+ <Route path=":collectionId" />
+ </Route>
+ </>
);
PLUGIN_TENANTS.EditUserStrategyModal = EditUserStrategyModal;
@@ -178,6 +193,7 @@ export function initializePlugin() {
PLUGIN_TENANTS.TenantSpecificCollectionsItemList =
TenantSpecificCollectionsItemList;
PLUGIN_TENANTS.TenantCollectionList = TenantCollectionList;
+ PLUGIN_TENANTS.CanAccessTenantSpecificRoute = CanAccessTenantSpecificRoute;
PLUGIN_TENANTS.TenantUsersList = TenantUsersList;
PLUGIN_TENANTS.TenantUsersPersonalCollectionList =
TenantUsersPersonalCollectionList;
@@ -252,6 +268,7 @@ export function initializePlugin() {
};
PLUGIN_TENANTS.useTenantMainNavbarData = () => {
const isTenantUser = useSelector(getIsTenantUser);
+ const isAdmin = useSelector(getUserIsAdmin);
const useTenants = useSetting("use-tenants");
const { data: sharedTenantCollections } = useListCollectionsTreeQuery(
@@ -265,6 +282,14 @@ export function initializePlugin() {
{ skip: !useTenants || isTenantUser },
);
+ // Check if non-admin user has access to tenant-specific namespace
+ const { data: tenantSpecificRoot } = useGetCollectionQuery(
+ { id: "root", namespace: "tenant-specific" },
+ { skip: !useTenants || isTenantUser || isAdmin },
+ );
+ const canAccessTenantSpecificCollections =
+ isAdmin || !!tenantSpecificRoot;
+
// Non-admins can create shared collections if they have curate permissions on the root shared collection
const canCreateSharedCollection =
sharedCollectionRoot?.can_write ?? false;
@@ -273,9 +298,12 @@ export function initializePlugin() {
const showExternalCollectionsSection =
useTenants &&
!isTenantUser &&
- (hasVisibleSharedCollections || canCreateSharedCollection);
+ (hasVisibleSharedCollections ||
+ canCreateSharedCollection ||
+ canAccessTenantSpecificCollections);
return {
+ canAccessTenantSpecificCollections,
canCreateSharedCollection,
showExternalCollectionsSection,
sharedTenantCollections,
diff --git a/frontend/src/metabase-types/store/admin.ts b/frontend/src/metabase-types/store/admin.ts
index 8249eafff16..07b8d35017f 100644
--- a/frontend/src/metabase-types/store/admin.ts
+++ b/frontend/src/metabase-types/store/admin.ts
@@ -30,10 +30,16 @@ export interface AdminState {
permissions: {
dataPermissions: GroupsPermissions;
originalDataPermissions: GroupsPermissions;
+ dataPermissionsRevision: number | null;
collectionPermissions: CollectionPermissions;
originalCollectionPermissions: CollectionPermissions;
+ collectionPermissionsRevision: number | null;
tenantCollectionPermissions: CollectionPermissions;
originalTenantCollectionPermissions: CollectionPermissions;
+ tenantCollectionPermissionsRevision: number | null;
+ tenantSpecificCollectionPermissions: CollectionPermissions;
+ originalTenantSpecificCollectionPermissions: CollectionPermissions;
+ tenantSpecificCollectionPermissionsRevision: number | null;
saveError?: string;
isHelpReferenceOpen: boolean;
hasRevisionChanged: {
diff --git a/frontend/src/metabase-types/store/mocks/admin.ts b/frontend/src/metabase-types/store/mocks/admin.ts
index 60990281685..1c50cffdd16 100644
--- a/frontend/src/metabase-types/store/mocks/admin.ts
+++ b/frontend/src/metabase-types/store/mocks/admin.ts
@@ -25,10 +25,16 @@ export const createMockPermissionsState = (
return {
dataPermissions: {},
originalDataPermissions: {},
+ dataPermissionsRevision: null,
collectionPermissions: {},
originalCollectionPermissions: {},
+ collectionPermissionsRevision: null,
tenantCollectionPermissions: {},
originalTenantCollectionPermissions: {},
+ tenantCollectionPermissionsRevision: null,
+ tenantSpecificCollectionPermissions: {},
+ originalTenantSpecificCollectionPermissions: {},
+ tenantSpecificCollectionPermissionsRevision: null,
isHelpReferenceOpen: false,
hasRevisionChanged: {
revision: null,
diff --git a/frontend/src/metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.jsx b/frontend/src/metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.jsx
index f464e08e174..dc3abdb0eb0 100644
--- a/frontend/src/metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.jsx
+++ b/frontend/src/metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal.jsx
@@ -116,7 +116,7 @@ const CollectionPermissionsModal = ({
groupId: item.id,
collection,
value,
- shouldPropagate: toggleState,
+ shouldPropagateToChildren: toggleState,
originalPermissionsState,
});
},
diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx
index 03a62705565..65b0625761b 100644
--- a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx
+++ b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx
@@ -44,7 +44,8 @@ type PermissionsPageTab =
| "data"
| "collections"
| "application"
- | "tenant-collections";
+ | "tenant-collections"
+ | "tenant-specific-collections";
type PermissionsPageLayoutProps = {
children: ReactNode;
tab: PermissionsPageTab;
diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx
index f190e7c62be..7caab04d861 100644
--- a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx
+++ b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx
@@ -11,7 +11,7 @@ import {
} from "metabase/plugins";
const propTypes = {
- tab: PropTypes.oneOf(["data", "collections"]).isRequired,
+ tab: PropTypes.string.isRequired,
onChangeTab: PropTypes.func.isRequired,
};
@@ -21,7 +21,9 @@ export const PermissionsTabs = ({ tab, onChangeTab }) => {
const adminPermissionsTabs = isUsingTenants
? PLUGIN_ADMIN_PERMISSIONS_TABS.tabs
: PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.filter(
- (tab) => tab.value !== "tenant-collections",
+ (tab) =>
+ tab.value !== "tenant-collections" &&
+ tab.value !== "tenant-specific-collections",
);
return (
diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx
index ca17e3007cb..ce711f3e6ac 100644
--- a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx
+++ b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx
@@ -27,6 +27,8 @@ const propTypes = {
value: PropTypes.string.isRequired,
toggleLabel: PropTypes.string,
hasChildren: PropTypes.bool,
+ toggleDisabled: PropTypes.bool,
+ toggleDefaultValue: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onAction: PropTypes.func,
isDisabled: PropTypes.bool,
@@ -41,6 +43,8 @@ export const PermissionsSelect = memo(function PermissionsSelect({
value,
toggleLabel,
hasChildren,
+ toggleDisabled,
+ toggleDefaultValue,
onChange,
onAction,
isDisabled,
@@ -48,7 +52,7 @@ export const PermissionsSelect = memo(function PermissionsSelect({
warning,
isHighlighted,
}) {
- const [toggleState, setToggleState] = useState(null);
+ const [toggleState, setToggleState] = useState(toggleDefaultValue ?? null);
const [opened, setOpened] = useState(false);
const selectedOption = options.find((option) => option.value === value);
const selectableOptions = hasChildren
@@ -137,6 +141,7 @@ export const PermissionsSelect = memo(function PermissionsSelect({
small
value={toggleState || false}
onChange={onToggleChange}
+ disabled={toggleDisabled}
/>
</ToggleContainer>
)}
diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
index 91daf6a700e..fbecd87d2d7 100644
--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/CollectionPermissionsPage.tsx
@@ -63,7 +63,7 @@ type UpdateCollectionPermissionParams = {
groupId: GroupId;
collection: Collection;
value: unknown;
- shouldPropagate: boolean | null;
+ shouldPropagateToChildren: boolean | null;
originalPermissionsState: CollectionPermissions;
};
@@ -77,7 +77,7 @@ type CollectionPermissionsPageProps = {
groupId,
collection,
value,
- shouldPropagate,
+ shouldPropagateToChildren,
}: UpdateCollectionPermissionParams) => void;
isDirty: boolean;
savePermissions: () => void;
@@ -117,7 +117,7 @@ function CollectionsPermissionsPageView({
groupId: item.id,
collection,
value,
- shouldPropagate: toggleState,
+ shouldPropagateToChildren: toggleState,
originalPermissionsState,
});
},
diff --git a/frontend/src/metabase/admin/permissions/permissions.js b/frontend/src/metabase/admin/permissions/permissions.js
index 5ce93257329..eca3423389e 100644
--- a/frontend/src/metabase/admin/permissions/permissions.js
+++ b/frontend/src/metabase/admin/permissions/permissions.js
@@ -251,9 +251,12 @@ export const saveCollectionPermissions = createThunkAction(
},
);
-// Tenant Collection Permissions
+// Shared Tenant Collection Permissions
const TENANT_NAMESPACE = "shared-tenant-collection";
+// Tenant-Specific Collection Permissions
+const TENANT_SPECIFIC_NAMESPACE = "tenant-specific";
+
const INITIALIZE_TENANT_COLLECTION_PERMISSIONS =
"metabase/admin/permissions/INITIALIZE_TENANT_COLLECTION_PERMISSIONS";
export const initializeTenantCollectionPermissions = createThunkAction(
@@ -310,6 +313,63 @@ export const saveTenantCollectionPermissions = createThunkAction(
},
);
+// Tenant-Specific Collection Permissions Actions
+const INITIALIZE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS =
+ "metabase/admin/permissions/INITIALIZE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS";
+export const initializeTenantSpecificCollectionPermissions = createThunkAction(
+ INITIALIZE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS,
+ () => async (dispatch) => {
+ await Promise.all([
+ dispatch(loadTenantSpecificCollectionPermissions()),
+ dispatch(Groups.actions.fetchList()),
+ ]);
+ },
+);
+
+const LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS =
+ "metabase/admin/permissions/LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS";
+export const loadTenantSpecificCollectionPermissions = createThunkAction(
+ LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS,
+ () => async () => {
+ return CollectionsApi.graph({ namespace: TENANT_SPECIFIC_NAMESPACE });
+ },
+);
+
+const UPDATE_TENANT_SPECIFIC_COLLECTION_PERMISSION =
+ "metabase/admin/permissions/UPDATE_TENANT_SPECIFIC_COLLECTION_PERMISSION";
+export const updateTenantSpecificCollectionPermission = createAction(
+ UPDATE_TENANT_SPECIFIC_COLLECTION_PERMISSION,
+);
+
+const SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS =
+ "metabase/admin/permissions/data/SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS";
+export const saveTenantSpecificCollectionPermissions = createThunkAction(
+ SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS,
+ () => async (_dispatch, getState) => {
+ const {
+ originalTenantSpecificCollectionPermissions,
+ tenantSpecificCollectionPermissions,
+ tenantSpecificCollectionPermissionsRevision,
+ } = getState().admin.permissions;
+
+ const modifiedPermissions = getModifiedCollectionPermissionsGraphParts(
+ originalTenantSpecificCollectionPermissions,
+ tenantSpecificCollectionPermissions,
+ );
+
+ const result = await CollectionsApi.updateGraph({
+ namespace: TENANT_SPECIFIC_NAMESPACE,
+ revision: tenantSpecificCollectionPermissionsRevision,
+ groups: modifiedPermissions,
+ });
+
+ return {
+ ...result,
+ groups: tenantSpecificCollectionPermissions,
+ };
+ },
+);
+
const CLEAR_SAVE_ERROR = "metabase/admin/permissions/CLEAR_SAVE_ERROR";
export const clearSaveError = createAction(CLEAR_SAVE_ERROR);
@@ -338,6 +398,10 @@ const saveError = handleActions(
[LOAD_TENANT_COLLECTION_PERMISSIONS]: {
next: (state) => null,
},
+ [SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: savePermission,
+ [LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (state) => null,
+ },
[CLEAR_SAVE_ERROR]: { next: () => null },
},
null,
@@ -525,7 +589,7 @@ const collectionPermissions = handleActions(
collection,
groupId,
originalPermissionsState,
- shouldPropagate,
+ shouldPropagateToChildren,
value,
} = payload;
let newPermissionsState = assocIn(
@@ -535,15 +599,15 @@ const collectionPermissions = handleActions(
);
/**
- * Check if shouldPropagate is explicitly set (true or false) vs unset (null or undefined).
+ * Check if shouldPropagateToChildren is explicitly set (true or false) vs unset (null or undefined).
* If it's a boolean, we either propagate the new value or restore the original. When not a boolean, we do nothing.
*/
- if (isBoolean(shouldPropagate)) {
+ if (isBoolean(shouldPropagateToChildren)) {
for (const descendent of getDecendentCollections(collection)) {
newPermissionsState = assocIn(
newPermissionsState,
[groupId, descendent.id],
- shouldPropagate
+ shouldPropagateToChildren
? value
: getIn(originalPermissionsState, [groupId, descendent.id]),
);
@@ -592,10 +656,11 @@ const tenantCollectionPermissions = handleActions(
},
[UPDATE_TENANT_COLLECTION_PERMISSION]: {
next: (state, { payload }) => {
- const { groupId, collection, value, shouldPropagate } = payload;
+ const { groupId, collection, value, shouldPropagateToChildren } =
+ payload;
let newPermissions = assocIn(state, [groupId, collection.id], value);
- if (shouldPropagate) {
+ if (shouldPropagateToChildren) {
for (const descendent of getDecendentCollections(collection)) {
newPermissions = assocIn(
newPermissions,
@@ -638,6 +703,61 @@ const tenantCollectionPermissionsRevision = handleActions(
null,
);
+// Tenant-Specific Collection Permissions Reducers
+const tenantSpecificCollectionPermissions = handleActions(
+ {
+ [LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (_state, { payload }) => payload.groups,
+ },
+ [UPDATE_TENANT_SPECIFIC_COLLECTION_PERMISSION]: {
+ next: (state, { payload }) => {
+ const { groupId, collection, value, shouldPropagateToChildren } =
+ payload;
+ let newPermissions = assocIn(state, [groupId, collection.id], value);
+
+ if (shouldPropagateToChildren) {
+ for (const descendent of getDecendentCollections(collection)) {
+ newPermissions = assocIn(
+ newPermissions,
+ [groupId, descendent.id],
+ value,
+ );
+ }
+ }
+ return newPermissions;
+ },
+ },
+ [SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (_state, { payload }) => payload.groups,
+ },
+ },
+ null,
+);
+
+const originalTenantSpecificCollectionPermissions = handleActions(
+ {
+ [LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (_state, { payload }) => payload.groups,
+ },
+ [SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (state, { payload }) => payload.groups,
+ },
+ },
+ null,
+);
+
+const tenantSpecificCollectionPermissionsRevision = handleActions(
+ {
+ [LOAD_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (_state, { payload }) => payload.revision,
+ },
+ [SAVE_TENANT_SPECIFIC_COLLECTION_PERMISSIONS]: {
+ next: (_state, { payload }) => payload.revision,
+ },
+ },
+ null,
+);
+
export const TOGGLE_HELP_REFERENCE =
"metabase/admin/permissions/TOGGLE_HELP_REFERENCE";
export const toggleHelpReference = createAction(TOGGLE_HELP_REFERENCE);
@@ -702,6 +822,9 @@ export const permissions = combineReducers({
tenantCollectionPermissions,
originalTenantCollectionPermissions,
tenantCollectionPermissionsRevision,
+ tenantSpecificCollectionPermissions,
+ originalTenantSpecificCollectionPermissions,
+ tenantSpecificCollectionPermissionsRevision,
isHelpReferenceOpen,
hasRevisionChanged,
});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
index 7b29587e51d..f44316786f3 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
@@ -111,6 +111,7 @@ function MainNavbarContainer({
});
const {
+ canAccessTenantSpecificCollections,
canCreateSharedCollection,
showExternalCollectionsSection,
sharedTenantCollections,
@@ -210,6 +211,7 @@ function MainNavbarContainer({
handleCloseNavbar={closeNavbar}
handleLogout={logout}
sharedTenantCollections={sharedTenantCollections}
+ canAccessTenantSpecificCollections={canAccessTenantSpecificCollections}
canCreateSharedCollection={canCreateSharedCollection}
showExternalCollectionsSection={showExternalCollectionsSection}
/>
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
index e51a8258535..9070d7b87cc 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
@@ -60,6 +60,7 @@ type Props = {
collections: CollectionTreeItem[];
selectedItems: SelectedItem[];
sharedTenantCollections?: Collection[];
+ canAccessTenantSpecificCollections: boolean;
canCreateSharedCollection: boolean;
showExternalCollectionsSection: boolean;
handleCloseNavbar: () => void;
@@ -84,6 +85,7 @@ export function MainNavbarView({
handleCreateNewCollection,
handleCloseNavbar,
sharedTenantCollections,
+ canAccessTenantSpecificCollections,
canCreateSharedCollection,
showExternalCollectionsSection,
}: Props) {
@@ -233,6 +235,9 @@ export function MainNavbarView({
{/* Tenant users don't see the section about "External collections" */}
{showExternalCollectionsSection && (
<PLUGIN_TENANTS.MainNavSharedCollections
+ canAccessTenantSpecificCollections={
+ canAccessTenantSpecificCollections
+ }
canCreateSharedCollection={canCreateSharedCollection}
sharedTenantCollections={sharedTenantCollections}
/>
diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.ts
index f85899a2a4c..dbf43db3987 100644
--- a/frontend/src/metabase/plugins/oss/tenants.ts
+++ b/frontend/src/metabase/plugins/oss/tenants.ts
@@ -43,6 +43,7 @@ const getDefaultPluginTenants = () => ({
null as React.ReactElement | null,
TenantGroupHintIcon: PluginPlaceholder,
MainNavSharedCollections: PluginPlaceholder as React.ComponentType<{
+ canAccessTenantSpecificCollections: boolean;
canCreateSharedCollection: boolean;
sharedTenantCollections: Collection[] | undefined;
}>,
@@ -51,6 +52,9 @@ const getDefaultPluginTenants = () => ({
TenantSpecificCollectionsItemList: (_props: { pathIndex: number }) =>
null as React.ReactElement | null,
TenantCollectionList: PluginPlaceholder,
+ CanAccessTenantSpecificRoute: PluginPlaceholder as React.ComponentType<{
+ children: React.ReactNode;
+ }>,
TenantUsersList: PluginPlaceholder,
TenantUsersPersonalCollectionList: PluginPlaceholder as React.ComponentType<{
params: { tenantId: string };
@@ -71,6 +75,7 @@ const getDefaultPluginTenants = () => ({
null as string | null,
getFlattenedCollectionsForNavbar: () => [],
useTenantMainNavbarData: () => ({
+ canAccessTenantSpecificCollections: false,
canCreateSharedCollection: false,
showExternalCollectionsSection: false,
sharedTenantCollections: [],
@@ -81,6 +86,7 @@ export const PLUGIN_TENANTS: {
isEnabled: boolean;
userStrategyRoute: React.ReactElement | null;
useTenantMainNavbarData: () => {
+ canAccessTenantSpecificCollections: boolean;
canCreateSharedCollection: boolean;
showExternalCollectionsSection: boolean;
sharedTenantCollections: Collection[] | undefined;
@@ -103,6 +109,7 @@ export const PLUGIN_TENANTS: {
}) => React.ReactElement | null;
TenantGroupHintIcon: React.ComponentType;
MainNavSharedCollections: React.ComponentType<{
+ canAccessTenantSpecificCollections: boolean;
canCreateSharedCollection: boolean;
sharedTenantCollections: Collection[] | undefined;
}>;
@@ -113,6 +120,9 @@ export const PLUGIN_TENANTS: {
pathIndex: number;
}) => React.ReactElement | null;
TenantCollectionList: React.ComponentType;
+ CanAccessTenantSpecificRoute: React.ComponentType<{
+ children: React.ReactNode;
+ }>;
TenantUsersList: React.ComponentType;
TenantUsersPersonalCollectionList: React.ComponentType<{
params: { tenantId: string };
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index 5a5e0886fae..e88cd5b168f 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -185,7 +185,10 @@ export const getRoutes = (store) => {
<IndexRoute component={UserCollectionList} />
</Route>
- <Route path="collection/tenant-specific" component={IsAdmin}>
+ <Route
+ path="collection/tenant-specific"
+ component={PLUGIN_TENANTS.CanAccessTenantSpecificRoute}
+ >
<IndexRoute component={PLUGIN_TENANTS.TenantCollectionList} />
</Route>
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index d149989b840..d77829a3a80 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -75,6 +75,10 @@
"The value of the `:type` field for collections that only allow metrics."
"library-metrics")
+(def ^:constant tenant-specific-root-collection-type
+ "The value of the `:type` field for root collections that belong to a single tenant"
+ "tenant-specific-root-collection")
+
(def transforms-ns
"Namespace for transforms"
:transforms)
@@ -1492,6 +1496,17 @@
(cons (perms/collection-readwrite-path collection)
(map perms/collection-readwrite-path descendant-ids)))))
+(def ^:dynamic *allow-modifying-tenant-root-collections?*
+ "We archive tenant root collections only when the tenant is archived."
+ false)
+
+(defmacro with-allow-modifying-tenant-root-collections
+ "Usually we don't allow archiving tenant specific root collections, just like personal collections. But
+ if a tenant is deactivated, we should allow archiving them."
+ [& body]
+ `(binding [*allow-modifying-tenant-root-collections?* true]
+ (do ~@body)))
+
(mu/defn archive-collection!
"Mark a collection as archived, along with all its children."
[collection :- CollectionWithLocationAndIDOrRoot]
@@ -1500,7 +1515,8 @@
@api/*current-user-permissions-set*
(perms-for-archiving collection)))
(api/check-400
- (not= (:type collection) "tenant-specific-root-collection"))
+ (or *allow-modifying-tenant-root-collections?*
+ (not= (:type collection) tenant-specific-root-collection-type)))
(t2/with-transaction [_conn]
(let [archive-operation-id (str (random-uuid))
affected-collection-ids (cons (u/the-id collection)
@@ -1617,7 +1633,7 @@
(throw (ex-info "Cannot `move-collection!` into the Trash. Call `archive-collection!` instead."
{:collection collection
:new-location new-location})))
- (when (= (:type collection) "tenant-specific-root-collection")
+ (when (= (:type collection) tenant-specific-root-collection-type)
(throw (ex-info "Can't move a tenant collection" {:status-code 400})))
;; first move this Collection
(log/infof "Moving Collection %s and its descendants from %s to %s"
@@ -1704,7 +1720,6 @@
For newly created Collections at the root-level, copy the existing permissions for the Root Collection."
[{:keys [location id], collection-namespace :namespace, :as collection}]
(when-not (or (is-personal-collection-or-descendant-of-one? collection)
- (is-dedicated-tenant-collection-or-descendant? collection)
(is-trash-or-descendant? collection))
(let [parent-collection-id (location-path->parent-id location)]
(copy-collection-permissions! (or parent-collection-id (assoc root-collection :namespace collection-namespace))
@@ -1847,7 +1862,8 @@
;; VARIOUS CHECKS BEFORE DOING ANYTHING:
;; (1) if this is a personal Collection, check that the 'propsed' changes are allowed
(when (or (:personal_owner_id collection-before-updates)
- (= (:type collection-before-updates) "tenant-specific-collection"))
+ (and (not *allow-modifying-tenant-root-collections?*)
+ (= (:type collection-before-updates) tenant-specific-root-collection-type)))
(check-changes-allowed-for-protected-collection collection-before-updates collection-updates))
;; (2) make sure the location is valid if we're changing it
(assert-valid-location collection-updates)
diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.clj
index eb61dfdd846..ac1ef9277e7 100644
--- a/src/metabase/collections_rest/api.clj
+++ b/src/metabase/collections_rest/api.clj
@@ -741,6 +741,10 @@
[:= :id (collection/trash-collection-id)]]
[:and [:= :archived false] [:not= :id (collection/trash-collection-id)]])]
(perms/namespace-clause :namespace (u/qualified-name collection-namespace) (collection/is-trash? collection))
+ ;; never show tenant-specific root collections as children of another collection
+ [:or
+ [:= :type nil]
+ [:not= :type collection/tenant-specific-root-collection-type]]
(snippets-collection-filter-clause))
;; We get from the effective-children-query a normal set of columns selected:
;; want to make it fit the others to make UNION ALL work
@@ -1643,7 +1647,7 @@
(let [collection-before-update (t2/hydrate (api/write-check :model/Collection id) :parent_id)]
;; tenant-specific-root-collection collections cannot be updated
(api/check-400
- (not= (:type collection-before-update) "tenant-specific-root-collection"))
+ (not= (:type collection-before-update) collection/tenant-specific-root-collection-type))
;; if authority_level is changing, make sure we're allowed to do that
(when (and (contains? collection-updates :authority_level)
(not= (keyword authority-level) (:authority_level collection-before-update)))
diff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.clj
index 67f3fcf8a5f..0013edfc631 100644
--- a/src/metabase/permissions/models/permissions.clj
+++ b/src/metabase/permissions/models/permissions.clj
@@ -456,7 +456,7 @@
(defn- is-trash-or-descendant? [collection]
((requiring-resolve 'metabase.collections.models.collection/is-trash-or-descendant?) collection))
-(defn- tenant-collection?
+(defn- shared-tenant-collection?
[collection]
((requiring-resolve 'metabase.collections.models.collection/shared-tenant-collection?) collection))
@@ -504,9 +504,9 @@
[group-or-id :- permissions.path/MapOrID collection-or-id :- permissions.path/MapOrID]
(check-is-modifiable-collection collection-or-id)
(let [collection (collection-or-id->collection collection-or-id)]
- (when (and (not (tenant-collection? collection))
- (perms-group/is-tenant-group? group-or-id))
- (throw (ex-info (tru "Tenant groups cannot receive access to non-tenant collections.") {}))))
+ (when (perms-group/is-tenant-group? group-or-id)
+ (when-not (shared-tenant-collection? collection)
+ (throw (ex-info (tru "Tenant groups cannot receive access to non-tenant collections.") {})))))
(grant-permissions! (u/the-id group-or-id) (permissions.path/collection-read-path collection-or-id)))
(defenterprise current-user-has-application-permissions?