The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Tenants, External Users, and tenant based JWT with Audit Events (#66661)
Edward Pagetcee9d99700cd
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex b4ba209044a..28d0694e685 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -921,6 +921,7 @@permissionspremium-featuresrequest+ settingsutil}}pivot@@ -1426,6 +1427,12 @@taskutil}}+ tenants+ {:team "Admin Webapp"+ :api #{metabase.tenants.core}+ :uses #{premium-features+ util}}+testing-api{:team "DevEx":api #{metabase.testing-api.api@@ -1517,6 +1524,7 @@settingssetupsystem+ tenantsutil}}users-rest@@ -1530,10 +1538,13 @@configeventsmodels+ notificationpermissionspremium-featuresrequest+ settingssso+ tenantsusersutilenterprise/advanced-permissions}}@@ -1965,6 +1976,7 @@appearanceaudit-appembedding+ permissionspremium-featuresenterprise/sso}}@@ -2116,6 +2128,7 @@premium-featuresquery-processorrequest+ tenantsusersutilwarehouse-schema@@ -2242,6 +2255,21 @@systemutil}}+ enterprise/tenants+ {:team "Admin Webapp"+ :api #{metabase-enterprise.tenants.api}+ :uses #{api+ audit-app+ auth-identity+ collections+ events+ models+ permissions+ premium-features+ request+ settings+ util}}+enterprise/transforms{:team "Querying":api #{metabase-enterprise.transforms.apidiff --git a/docs/people-and-groups/assigning-users-to-tenants.md b/docs/people-and-groups/assigning-users-to-tenants.mdnew file mode 100644index 00000000000..83372d48533--- /dev/null+++ b/docs/people-and-groups/assigning-users-to-tenants.md@@ -0,0 +1,52 @@+---+title: Assigning tenant users to tenants+description: How to automatically assign users to tenants using SSO authentication (JWT and SAML).+---++# Assigning tenant users to tenants++{% include plans-blockquote.html feature="Tenants" %}++If you're running a multi-tenant application, you can assign users to tenants based on a claim in the JWT token.++## Prerequisites++- Multi-tenant user strategy must be enabled in Metabase+- JWT authentication must be configured++## How it works++When a user logs in with JWT:++1. Metabase reads the tenant identifier from the JWT claim. By default, this is the `tenant` key.+2. If the tenant doesn't exist, Metabase automatically creates it+3. New users are automatically assigned to the tenant from their JWT++## Example JWT with tenant claim++```json+{+ "email": "[email protected]",+ "first_name": "Jane",+ "last_name": "Doe",+ "tenant": "acme-corp"+}+```++## Important restrictions++**Users cannot change tenants.** Once an external user is assigned to a tenant, they cannot switch to other tenant.++If a user attempts to log in with mismatched tenant information, they will receive one of these errors:++- `Cannot add tenant claim to internal user` - JWT includes a tenant, but the user is an internal user. Only tenant users can have a tenant.+- `Tenant claim required for external user` - JWT lacks a tenant claim, but the user is an external user.+- `Tenant ID mismatch with existing user` - JWT has a different tenant than the user's assigned tenant+- `Tenant is not active` - The tenant exists but has been deactivated++# Configuring the tenant claim++By default, Metabase looks for a `tenant` key in your JWT. You can customize this:++1. Go to **Admin** > **Settings** > **Authentication** > **JWT** > **User attribute configuration**+2. Change the **Tenant assignment attribute** key to your preferred identifier.diff --git a/docs/people-and-groups/authenticating-with-jwt.md b/docs/people-and-groups/authenticating-with-jwt.mdindex ca8c8658e15..d9f98712cc0 100644--- a/docs/people-and-groups/authenticating-with-jwt.md+++ b/docs/people-and-groups/authenticating-with-jwt.md@@ -42,6 +42,7 @@ These are additional settings you can fill in to pass user attributes to Metabas- **First name attribute:** the key to retrieve each JWT user's first name.- **Last name attribute:** if you guessed that this is the key to retrieve each JWT user's last name, well then you have been paying attention.- **Group assignment attribute:** the key to retrieve each JWT user's group assignments.+- **Tenant attribute:** the key to retrieve each JWT user's tenant. Default is `tenant`. See [Assigning tenant users to tenants](./assigning-users-to-tenants.md).You can send additional user attributes to Metabase by adding the attributes as key/value pairs to your JWT. These attributes will be synced on every login.@@ -106,6 +107,10 @@ To require people to log in with SSO, disable password authentication from **Adm+## Assigning tenant users to tenants++If you're running a multi-tenant application, you can use JWT to automatically assign users to tenants based on a claim in the JWT token. See [Assigning tenant users to tenants](./assigning-users-to-tenants.md) for details.+## Note about AzureIf you're using Azure, you may need to use Azure AD B2C. Check out their [tokens overview](https://docs.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview).diff --git a/e2e/snapshot-creators/default.cy.snap.js b/e2e/snapshot-creators/default.cy.snap.jsindex ac7c3a6d122..88449af0a0b 100644--- a/e2e/snapshot-creators/default.cy.snap.js+++ b/e2e/snapshot-creators/default.cy.snap.js@@ -9,6 +9,7 @@ import {USER_GROUPS,} from "e2e/support/cypress_data";import {+ activateToken,createQuestion,createQuestionAndDashboard,restore,@@ -37,6 +38,8 @@ const {} = USER_GROUPS;const { admin } = USERS;+const { IS_ENTERPRISE } = Cypress.env();+describe("snapshots", () => {describe("default", () => {it("default", () => {@@ -122,22 +125,22 @@ describe("snapshots", () => {// groupscy.request("POST", "/api/permissions/group", { name: "collection" }).then(({ body }) => {- expect(body.id).to.eq(COLLECTION_GROUP); // 3+ expect(body.id).to.eq(COLLECTION_GROUP); // 4},);cy.request("POST", "/api/permissions/group", { name: "data" }).then(({ body }) => {- expect(body.id).to.eq(DATA_GROUP); // 4+ expect(body.id).to.eq(DATA_GROUP); // 5},);cy.request("POST", "/api/permissions/group", { name: "readonly" }).then(({ body }) => {- expect(body.id).to.eq(READONLY_GROUP); // 5+ expect(body.id).to.eq(READONLY_GROUP); // 6},);cy.request("POST", "/api/permissions/group", { name: "nosql" }).then(({ body }) => {- expect(body.id).to.eq(NOSQL_GROUP); // 6+ expect(body.id).to.eq(NOSQL_GROUP); // 7},);@@ -318,6 +321,17 @@ describe("snapshots", () => {});function getDefaultInstanceData() {+ // This is something we need to do to ensure that the All tenant users group+ // comes back with the call to /api/permissions/groups. After the API calls are+ // finished, we disable it+ if (IS_ENTERPRISE) {+ // Once the feature is released, we will not need to use the bleeding-edge token+ activateToken("bleeding-edge");+ cy.request("PUT", "/api/setting", {+ "use-tenants": true,+ });+ }+const instanceData = {};instanceData.loginCache = loginCache;@@ -357,5 +371,11 @@ function getDefaultInstanceData() {}});+ if (IS_ENTERPRISE) {+ cy.request("PUT", "/api/setting", {+ "use-tenants": false,+ });+ }+return instanceData;}diff --git a/e2e/support/cypress_data.js b/e2e/support/cypress_data.jsindex 4719d1a0f66..9f4c40ff3c9 100644--- a/e2e/support/cypress_data.js+++ b/e2e/support/cypress_data.js@@ -43,10 +43,14 @@ export const SAMPLE_DB_TABLES = {export const USER_GROUPS = {ALL_USERS_GROUP: 1,ADMIN_GROUP: 2,- COLLECTION_GROUP: 3,- DATA_GROUP: 4,- READONLY_GROUP: 5,- NOSQL_GROUP: 6,+ COLLECTION_GROUP: 4,+ DATA_GROUP: 5,+ READONLY_GROUP: 6,+ NOSQL_GROUP: 7,+};++export const TENANT_USER_GROUPS = {+ EXTERNAL_USERS_GROUP: 3,};const {diff --git a/e2e/support/cypress_sample_instance_data.js b/e2e/support/cypress_sample_instance_data.jsindex a5b6b187cba..33f229d087d 100644--- a/e2e/support/cypress_sample_instance_data.js+++ b/e2e/support/cypress_sample_instance_data.js@@ -142,13 +142,20 @@ export const IMPERSONATED_USER_ID = _.findWhere(SAMPLE_INSTANCE_DATA.users, {export const ADMINISTRATORS_GROUP_ID = _.findWhere(SAMPLE_INSTANCE_DATA.groups,- { name: "Administrators" },+ { magic_group_type: "admin" },).id;export const ALL_USERS_GROUP_ID = _.findWhere(SAMPLE_INSTANCE_DATA.groups, {- name: "All Users",+ magic_group_type: "all-internal-users",}).id;+export const ALL_EXTERNAL_USERS_GROUP_ID = _.findWhere(+ SAMPLE_INSTANCE_DATA.groups,+ {+ magic_group_type: "all-external-users",+ },+)?.id;+export const COLLECTION_GROUP_ID = _.findWhere(SAMPLE_INSTANCE_DATA.groups, {name: "collection",}).id;diff --git a/e2e/support/helpers/e2e-permissions-helpers.js b/e2e/support/helpers/e2e-permissions-helpers.jsindex a92320a4e23..86a8407e128 100644--- a/e2e/support/helpers/e2e-permissions-helpers.js+++ b/e2e/support/helpers/e2e-permissions-helpers.js@@ -91,14 +91,12 @@ export function assertPermissionForItem(* @param {string} permission* @param {boolean} isDisabled*/-export function isPermissionDisabled(index, permission, isDisabled) {+export function isPermissionDisabled(row, index, permission, isDisabled) {// eslint-disable-next-line no-unsafe-element-filtering- return cy- .findAllByTestId("permissions-select")+ return getPermissionRowPermissions(row).eq(index)- .contains(permission)- .closest("a")- .should("have.attr", "aria-disabled", isDisabled.toString());+ .should("have.attr", "aria-disabled", isDisabled.toString())+ .contains(permission);}export const dismissSplitPermsModal = () => {@@ -115,7 +113,7 @@ export function savePermissions() {export function selectImpersonatedAttribute(attribute) {cy.findByRole("dialog").within(() => {- cy.findByTestId("select-button").click();+ cy.findByRole("textbox", { name: "User attribute" }).click();});popover().findByText(attribute).click();diff --git a/e2e/support/helpers/e2e-remote-sync-helpers.ts b/e2e/support/helpers/e2e-remote-sync-helpers.tsindex ea17d53aa29..922fb3fdd98 100644--- a/e2e/support/helpers/e2e-remote-sync-helpers.ts+++ b/e2e/support/helpers/e2e-remote-sync-helpers.ts@@ -164,8 +164,32 @@ export const goToSyncedCollection = (opts?: Partial<Cypress.ClickOptions>) =>.findByRole("treeitem", { name: /Synced Collection/ }).click(opts);+// Git sync controls are now in the app bar, not the sidebar+export const getGitSyncControls = () => cy.findByTestId("git-sync-controls");++export const getPullButton = () =>+ getGitSyncControls().findByTestId("git-pull-button");++export const getPushButton = () =>+ getGitSyncControls().findByTestId("git-push-button");++// Branch picker is now in the app bar (git-sync-controls), not the sidebarexport const branchPicker = (opts?: Partial<MatcherOptions>) =>- navigationSidebar().findByTestId("branch-picker-button", opts);+ getGitSyncControls().findByTestId("branch-picker-button", opts);++// Enable tenants feature for testing+export const enableTenants = () => {+ cy.request("PUT", "/api/setting/use-tenants", { value: true });+};++// Create a shared tenant collection for testing+// Note: namespace must be "shared-tenant-collection" to match the API query in SharedTenantCollectionsList+export const createSharedTenantCollection = (name: string) => {+ return cy.request("POST", "/api/collection", {+ name,+ namespace: "shared-tenant-collection",+ });+};export const interceptTask = () =>cy.intercept("/api/ee/remote-sync/current-task").as("currentTask");diff --git a/e2e/test/scenarios/admin-2/people.cy.spec.js b/e2e/test/scenarios/admin-2/people.cy.spec.jsindex 8dcb377a891..7ef5f25d4f1 100644--- a/e2e/test/scenarios/admin-2/people.cy.spec.js+++ b/e2e/test/scenarios/admin-2/people.cy.spec.js@@ -711,7 +711,7 @@ describe("scenarios > admin > people > group managers", () => {cy.icon("ellipsis").eq(0).click();// eslint-disable-next-line no-unscoped-text-selectors -- deprecated usagecy.findByText("Edit Name").click();- cy.get("input").type(" updated");+ cy.findByDisplayValue("collection").type(" updated");cy.button("Done").click();// Click on the group with the new namediff --git a/e2e/test/scenarios/admin-2/tenants.cy.spec.ts b/e2e/test/scenarios/admin-2/tenants.cy.spec.tsnew file mode 100644index 00000000000..d9f892224b0--- /dev/null+++ b/e2e/test/scenarios/admin-2/tenants.cy.spec.ts@@ -0,0 +1,931 @@+const { H } = cy;+import {+ SAMPLE_DB_ID,+ SAMPLE_DB_TABLES,+ WRITABLE_DB_ID,+} from "e2e/support/cypress_data";+import {+ ALL_EXTERNAL_USERS_GROUP_ID,+ COLLECTION_GROUP_ID,+} from "e2e/support/cypress_sample_instance_data";+import { getPermissionRowPermissions } from "e2e/support/helpers";++const { STATIC_ORDERS_ID, STATIC_PRODUCTS_ID } = SAMPLE_DB_TABLES;++const JWT_SECRET =+ "0000000000000000000000000000000000000000000000000000000000000000";++interface TenantAttributes {+ CAPS?: string;+ color?: string;+}++interface Tenant {+ name: string;+ slug: string;+ attributes?: TenantAttributes;+}++interface TenantUser {+ first_name: string;+ last_name: string;+ email: string;+ "@tenant": string;+}++const GIZMO_TENANT: Tenant = {+ name: "Gizmos",+ slug: "gizmo",+ attributes: {+ CAPS: "✨GIZMO✨",+ color: "cerulean",+ },+};++const DOOHICKEY_TENANT: Tenant = {+ name: "Doohickey",+ slug: "doohickey",+};++const GIZMO_USER: TenantUser = {+ first_name: "gizmo",+ last_name: "user",+ email: "[email protected]",+ "@tenant": GIZMO_TENANT.slug,+};++const DOOHICKEY_USER: TenantUser = {+ first_name: "doohickey",+ last_name: "user",+ email: "[email protected]",+ "@tenant": DOOHICKEY_TENANT.slug,+};++const SECOND_DOOHICKEY_USER: TenantUser = {+ first_name: "donthickey",+ last_name: "user",+ email: "[email protected]",+ "@tenant": DOOHICKEY_TENANT.slug,+};++const TENANTS: Tenant[] = [GIZMO_TENANT, DOOHICKEY_TENANT];+const USERS: TenantUser[] = [GIZMO_USER, DOOHICKEY_USER, SECOND_DOOHICKEY_USER];++const GIZMO_FULL_NAME = H.getFullName(GIZMO_USER);++describe("Tenants - management OSS", { tags: "@OSS" }, () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ it("should not show the popup to enable multi tenancy", () => {+ cy.visit("/admin/tenants");+ cy.location("pathname").should("eq", "/admin/people");++ cy.findByRole("link", { name: /gear/ }).should("not.exist");+ });+});++describe("Tenants - management", () => {+ beforeEach(() => {+ cy.intercept("GET", "/api/ee/tenant/*").as("getTenant");+ cy.intercept("GET", "/api/user/*").as("getUser");+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ it("should disable the feature if the token feature is not enabled", () => {+ H.deleteToken();++ cy.visit("/admin/tenants");+ cy.location("pathname").should("eq", "/admin/people");++ cy.findByRole("link", { name: /gear/ }).should("not.exist");+ });++ it("should allow users to enable multi tenancy, and create / manage tenants and tenant users", () => {+ // We expect this to redirect to /admin/people+ cy.visit("/admin/tenants");++ cy.location("pathname").should("eq", "/admin/people");+ cy.visit("/admin/tenants");++ cy.findByRole("navigation", { name: "people-nav" })+ .findByRole("link", { name: /Groups/ })+ .click();++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /All Users/ }).should("exist");+ cy.findByRole("link", { name: /Tenant users/ }).should("not.exist");+ });++ cy.findByRole("navigation", { name: "people-nav" })+ .findByRole("link", { name: /People/ })+ .click();++ cy.findByRole("link", { name: /Tenant users/ }).should("not.exist");+ cy.findByRole("link", { name: /Tenants/ }).should("not.exist");++ cy.findByRole("link", { name: /gear/ }).click();++ H.modal().within(() => {+ cy.findByRole("radio", { name: /Multi tenant/i }).click();+ cy.button("Apply").click();+ });++ cy.log("should show toast hint message about tenant collections");+ cy.findAllByText(+ "You can create tenant collections from the main Metabase navigation",+ )+ .first()+ .should("be.visible");++ cy.findByRole("link", { name: /Tenant users/ }).should("exist");+ cy.findByRole("link", { name: /Tenants/ }).click();++ // Create some tenants+ cy.findByRole("button", { name: "New tenant" }).click();+ H.modal().within(() => {+ cy.findByRole("textbox", { name: "Display name" }).type("Parrot");+ cy.findByRole("textbox", { name: "Slug" }).should("have.value", "parrot");+ cy.button("Create").click();+ });++ cy.findByRole("button", { name: "New tenant" }).click();+ H.modal().within(() => {+ cy.findByRole("textbox", { name: "Display name" }).type("Eagle");+ cy.button("Create").click();+ });++ cy.findByRole("button", { name: "New tenant" }).click();+ H.modal().within(() => {+ cy.findByRole("textbox", { name: "Display name" }).type("Turkey");+ cy.button("Create").click();+ });++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /Parrot/ }).should("exist");+ cy.findByRole("link", { name: /Eagle/ }).should("exist");+ cy.findByRole("link", { name: /Turkey/ }).should("exist");++ // Edit a tenant+ cy.findAllByRole("button", { name: /ellipsis/ })+ .eq(2)+ .click();+ });++ H.popover().findByText("Edit tenant").click();++ H.modal().within(() => {+ cy.findByRole("textbox", { name: "Display name" })+ .should("have.value", "Turkey")+ .clear()+ .type("Chicken");+ cy.findByRole("textbox", { name: "Slug" })+ .should("have.value", "turkey")+ .should("be.disabled");++ cy.button("Update").click();+ });++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /Parrot/ }).should("exist");+ cy.findByRole("link", { name: /Eagle/ }).should("exist");+ cy.findByRole("link", { name: /Chicken/ }).should("exist");++ // Edit a tenant+ cy.findAllByRole("button", { name: /ellipsis/ })+ .eq(1)+ .click();+ });++ // Deactivate a tenant+ H.popover().findByText("Deactivate tenant").click();+ H.modal().button("Deactivate").click();++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /Parrot/ }).should("exist");+ cy.findByRole("link", { name: /Chicken/ }).should("exist");+ cy.findByRole("link", { name: /Eagle/ }).should("not.exist");+ });++ cy.findByRole("tab", { name: "Deactivated" }).click();++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /Parrot/ }).should("not.exist");+ cy.findByRole("link", { name: /Chicken/ }).should("not.exist");+ cy.findByRole("link", { name: /Eagle/ }).should("exist");+ });++ // Create an external user+ cy.findByRole("link", { name: /Tenant users/ }).click();+ cy.button("Create tenant user").click();++ H.modal().within(() => {+ cy.findByRole("textbox", { name: "First name" }).type("Test");+ cy.findByRole("textbox", { name: "Last name" }).type("User");+ cy.findByRole("textbox", { name: "Email" }).type("[email protected]");+ cy.findByRole("generic", { name: "Groups" }).should("not.exist");+ cy.findByRole("textbox", { name: "Tenant" }).click();+ });++ H.popover().within(() => {+ cy.findByText("Eagle").should("not.exist");+ cy.findByText("Parrot").click();+ });++ H.modal().within(() => {+ cy.findByText("Attributes").click();+ cy.findByTestId("mapping-editor").within(() => {+ cy.findByText("@tenant.slug").should("exist");+ cy.findByDisplayValue("parrot").should("exist");++ cy.findByRole("button", { name: /Add an attribute/i }).click();+ cy.findByPlaceholderText("Key").type("@tenant.name", {+ parseSpecialCharSequences: false,+ });++ cy.findByText(+ 'Keys starting with "@" are reserved for system use',+ ).should("exist");+ cy.findByPlaceholderText("Key").clear().type("my-special-attr");++ cy.findAllByPlaceholderText("Value")+ .should("have.length", 2)+ .last()+ .type("Snowflake");+ });++ cy.button("Create").click();+ });++ cy.button("Done").click();+ cy.findByTestId("admin-people-list-table").should("contain.text", "Parrot");++ // Reactivate tenant+ cy.findByRole("link", { name: /Tenants/ }).click();+ cy.findByTestId("admin-content-table").should("contain.text", "1");++ cy.findByRole("tab", { name: "Deactivated" }).click();+ cy.findByTestId("admin-content-table")+ .findByRole("button", { name: /ellipsis/ })+ .click();+ H.popover().findByText("Reactivate tenant").click();+ H.modal().button("Reactivate").click();++ cy.log(+ "after reactivating the last deactivated tenant, tabs should disappear and show all active tenants",+ );+ cy.findByRole("tab", { name: "Deactivated" }).should("not.exist");+ cy.findByRole("tab", { name: /Active/ }).should("not.exist");++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /Parrot/ }).should("exist");+ cy.findByRole("link", { name: /Eagle/ }).should("exist");+ });++ cy.findByRole("navigation", { name: "people-nav" })+ .findAllByRole("link", { name: /Groups/ })+ .should("have.length", 2)+ .first()+ .click();++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /All Internal Users/ }).should(+ "be.visible",+ );+ cy.findByRole("link", { name: /All tenant users/ }).should("not.exist");+ });++ cy.findByRole("navigation", { name: "people-nav" })+ .findAllByRole("link", { name: /Tenant Groups/ })+ .click();++ cy.findByTestId("admin-content-table").within(() => {+ cy.findByRole("link", { name: /All Internal Users/ }).should("not.exist");+ cy.findByRole("row", {+ name: `group-${ALL_EXTERNAL_USERS_GROUP_ID}-row`,+ }).within(() => {+ cy.findByRole("cell", { name: "member-count" }).should(+ "contain.text",+ "1",+ );+ cy.findByRole("button", {+ name: "group-action-button",+ }).should("not.exist");+ cy.findByRole("link", { name: /All tenant users/ }).click();+ });+ });++ cy.findByTestId("admin-panel")+ .findByText(/All tenant users group and can't be removed from it/)+ .should("exist");+ });++ it("should allow you to manage external user permissions once multi tenancy is enabled", () => {+ const EXTERNAL_USER_GROUP_NAME = "All tenant users";+ const TENANT_GROUP_NAME = "Favorite tenant users";++ cy.request("POST", "/api/permissions/group", {+ name: TENANT_GROUP_NAME,+ is_tenant_group: true,+ });++ cy.visit("/admin/permissions");+ cy.findByRole("menuitem", { name: "Administrators" }).should("be.visible");+ cy.findByRole("menuitem", { name: EXTERNAL_USER_GROUP_NAME }).should(+ "not.exist",+ );++ cy.request("PUT", "/api/setting", {+ "use-tenants": true,+ });++ cy.reload();+ cy.findByRole("menuitem", { name: "Administrators" }).should("be.visible");+ cy.findByRole("menuitem", { name: TENANT_GROUP_NAME }).should("be.visible");+ cy.findByRole("menuitem", { name: EXTERNAL_USER_GROUP_NAME }).click();++ assertPermissionTableColumnsExist([+ "exist",+ "exist",+ "exist",+ "not.exist",+ "not.exist",+ ]);++ cy.findByRole("menuitem", { name: "Administrators" }).click();++ assertPermissionTableColumnsExist([+ "exist",+ "exist",+ "exist",+ "exist",+ "exist",+ ]);++ cy.findByRole("radio", { name: "Databases" }).click({ force: true });+ cy.findByRole("menuitem", { name: "Sample Database" }).click();++ assertPermissionTableColumnsExist([+ "exist",+ "exist",+ "exist",+ "exist",+ "exist",+ ]);++ getPermissionRowPermissions("All tenant users")+ .eq(3)+ .should("have.attr", "aria-disabled", "true");+ getPermissionRowPermissions("All tenant users")+ .eq(4)+ .should("have.attr", "aria-disabled", "true");++ hasGlobeIcon(EXTERNAL_USER_GROUP_NAME);+ hasGlobeIcon(TENANT_GROUP_NAME);+ lacksGlobeIcon("Administrators");+ lacksGlobeIcon("All Internal Users");+ });++ it("should show 'All tenant users' in permission warning tooltip for tenant groups (UXW-2474)", () => {+ cy.request("PUT", "/api/setting", { "use-tenants": true });++ // Create a tenant group+ cy.request("POST", "/api/permissions/group", {+ name: "Test Tenant Group",+ is_tenant_group: true,+ }).then(({ body: group }) => {+ const tenantGroupId = group.id;++ cy.visit(`/admin/permissions/data/group/${tenantGroupId}`);++ cy.findByRole("radio", { name: "Groups" }).click({ force: true });++ cy.findByRole("menuitem", { name: "All tenant users" }).click();++ cy.log("sample database's view data permission should be 'Can view'");+ getPermissionRowPermissions("Sample Database")+ .first()+ .should("contain", "Can view");++ cy.findByRole("menuitem", { name: "Test Tenant Group" }).click();++ cy.log("tenant group view data permission should be 'Blocked'");+ getPermissionRowPermissions("Sample Database")+ .first()+ .should("contain", "Blocked");++ cy.log("tenant group permission should contain a warning");+ getPermissionRowPermissions("Sample Database")+ .first()+ .findByLabelText("warning icon")+ .realHover();++ // Tooltip must reference "All tenant users" not "All Internal Users"+ H.tooltip().should(+ "contain",+ 'The "All tenant users" group has a higher level of access',+ );+ H.tooltip().should("not.contain", "All Internal Users");+ });+ });++ it("should not show send email modal when creating tenant users when SMTP is configured", () => {+ H.setupSMTP();+ cy.request("PUT", "/api/setting", {+ "use-tenants": true,+ });++ createTenants();++ cy.visit("admin/tenants/people");++ cy.findByRole("link", { name: /Tenant users/ }).click();+ cy.button("Create tenant user").click();++ H.modal().within(() => {+ cy.findByRole("textbox", { name: "First name" }).type("Test");+ cy.findByRole("textbox", { name: "Last name" }).type("User");+ cy.findByRole("textbox", { name: "Email" }).type("[email protected]");+ cy.findByRole("generic", { name: "Groups" }).should("not.exist");+ cy.findByRole("textbox", { name: "Tenant" }).click();+ });++ H.popover().within(() => {+ cy.findByText("Gizmos").click();+ });++ H.modal().button("Create").click();++ H.modal().should("not.exist");+ });++ it("should show tenant attributes in user attribute lists when multi tenancy is enabled", () => {+ H.restore("postgres-writable");+ H.activateToken("bleeding-edge");++ cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);++ cy.findByRole("switch", { name: /model actions/i }).click({ force: true });+ cy.findByRole("switch", { name: /database routing/i }).click({+ force: true,+ });++ cy.findByPlaceholderText("Choose an attribute").click();++ H.popover().findByText("@tenant.slug").should("not.exist");+ cy.visit(+ `/admin/permissions/data/database/${WRITABLE_DB_ID}/impersonated/group/${COLLECTION_GROUP_ID}`,+ );+ cy.findByPlaceholderText("Pick a user attribute").click();++ H.popover().findByText("@tenant.slug").should("not.exist");+ cy.visit(+ `/admin/permissions/data/group/${COLLECTION_GROUP_ID}/database/${SAMPLE_DB_ID}/schema/PUBLIC/${STATIC_ORDERS_ID}/segmented`,+ );++ cy.findByPlaceholderText("Pick a user attribute").click();+ H.popover().findByText("@tenant.slug").should("not.exist");++ cy.request("PUT", "/api/setting/use-tenants", { value: true });++ createTenants();+ createUsers();++ cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);+ cy.findByRole("switch", { name: /database routing/i }).click({+ force: true,+ });++ cy.findByPlaceholderText("Choose an attribute").click();+ H.popover()+ .findByRole("option", { name: /@tenant.slug/ })+ .findByTestId("system-defined-tooltip-icon")+ .realHover();+ // The select input also has a tooltip on hover, so we need to findAll+ cy.findAllByRole("tooltip").should(+ "contain.text",+ "This attribute is system defined",+ );++ cy.visit(+ `/admin/permissions/data/database/${WRITABLE_DB_ID}/impersonated/group/${COLLECTION_GROUP_ID}`,+ );+ cy.findByPlaceholderText("Pick a user attribute").click();+ H.popover()+ .findByRole("option", { name: /@tenant.slug/ })+ .findByTestId("system-defined-tooltip-icon");++ cy.visit(+ `/admin/permissions/data/group/${COLLECTION_GROUP_ID}/database/${SAMPLE_DB_ID}/schema/PUBLIC/${STATIC_ORDERS_ID}/segmented`,+ );+ cy.findByPlaceholderText("Pick a user attribute").click();+ H.popover()+ .findByRole("option", { name: /@tenant.slug/ })+ .findByTestId("system-defined-tooltip-icon");++ cy.log("check that tenant attributes propagate to users");++ cy.visit("/admin/tenants/people");+ cy.findByTestId("nav-item-external-users").findByText("Tenant users", 1000);+ cy.findByTestId("admin-people-list-table").within(() => {+ cy.findByText(`${GIZMO_USER.first_name} ${GIZMO_USER.last_name}`).should(+ "exist",+ );+ });++ cy.findAllByRole("button", { name: /ellipsis/ })+ .should("have.length", 3)+ .last()+ .click();+ H.popover().findByText("Edit user").click();++ cy.wait(["@getUser", "@getTenant"]);++ H.modal().within(() => {+ cy.findByText("Attributes").click();+ Object.entries(GIZMO_TENANT.attributes!).forEach(([key, value]) => {+ cy.findByText(key).should("be.visible");+ cy.findByDisplayValue(value).should("be.visible");+ });+ });+ });+});++describe("tenant users", () => {+ beforeEach(() => {+ cy.intercept("GET", "/api/ee/tenant/*").as("getTenant");+ cy.intercept("GET", "/api/user/*").as("getUser");++ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ cy.request("PUT", "/api/setting", {+ "jwt-attribute-email": "email",+ "jwt-attribute-firstname": "first_name",+ "jwt-attribute-lastname": "last_name",+ "jwt-enabled": true,+ "jwt-identity-provider-uri": "localhost:4000",+ "jwt-shared-secret": JWT_SECRET,+ "jwt-user-provisioning-enabled?": true,+ "use-tenants": true,+ });++ createTenants();+ USERS.forEach((user) =>+ cy+ .task<string>("signJwt", {+ payload: user,+ secret: JWT_SECRET,+ })+ .then((key) =>+ cy.request(+ "GET",+ `/auth/sso?return_to=/question/notebook&jwt=${key}`,+ ),+ ),+ );++ //Need to sign in as admin again because of the JWT logins+ cy.signInAsAdmin();++ const TTAG_NAME = "tenant.name";++ H.createNativeQuestion({+ name: "sql param in a dashboard",+ native: {+ query: `select * from products where lower(Category) = {{${TTAG_NAME}}}`,+ "template-tags": {+ [TTAG_NAME]: {+ id: "6b8b10ef-0104-1047-1e1b-2492d5954555",+ name: TTAG_NAME,+ "display-name": "tenant name",+ type: "text",+ },+ },+ },+ }).then(({ body: { id: QUESTION_ID } }) => {+ cy.sandboxTable({+ table_id: STATIC_PRODUCTS_ID,+ card_id: QUESTION_ID,+ group_id: ALL_EXTERNAL_USERS_GROUP_ID,+ attribute_remappings: {+ "@tenant.slug": ["variable", ["template-tag", TTAG_NAME]],+ },+ });+ });+ });++ it("should disable users on a tenant when disabling the tenant", () => {+ cy.visit("/admin/tenants/people");++ cy.findAllByRole("row")+ .contains("tr", "donthickey user")+ .findByRole("button", { name: /ellipsis/ })+ .click();++ H.popover().findByText("Deactivate user").click();+ H.modal().button("Deactivate").click();++ cy.findByRole("link", { name: /tenants/i }).click();++ cy.findAllByRole("row")+ .contains("tr", "doohickey")+ .findByRole("button", { name: /ellipsis/ })+ .click();++ H.popover().findByText("Deactivate tenant").click();+ H.modal().button("Deactivate").click();++ cy.findByRole("link", { name: /tenant users/i }).click();++ // assert that only gizmo users are still active+ cy.findByTestId("admin-layout-content").findByText("1 person found");++ cy.findAllByRole("row")+ .contains("tr", GIZMO_FULL_NAME)+ .findByRole("button", { name: /ellipsis/ })+ .click();++ H.popover().findByText("Deactivate user").click();+ H.modal().button("Deactivate").click();++ cy.findByRole("tab", { name: "Deactivated" }).click({ force: true });++ cy.findByTestId("admin-layout-content").findByText("3 people found");++ // Disabled users should still show their tenant names+ cy.findAllByRole("row")+ .contains("tr", "donthickey user")+ .findByRole("cell", { name: "Doohickey" })+ .should("exist");++ cy.findAllByRole("row")+ .contains("tr", "donthickey user")+ .findByRole("link", { name: /refresh/ })+ .realHover();++ H.tooltip().should(+ "contain.text",+ "Cannot reactivate users on a disabled tenant",+ );++ cy.findAllByRole("row")+ .contains("tr", GIZMO_FULL_NAME)+ .findByRole("link", { name: /refresh/ })+ .realHover();++ H.tooltip().should("contain.text", "Reactivate this account");++ cy.findByRole("link", { name: /tenants/i }).click();+ cy.findByRole("tab", { name: "Deactivated" }).click();++ cy.findAllByRole("row")+ .contains("tr", "doohickey")+ .findByRole("button", { name: /ellipsis/ })+ .click();++ H.popover().findByText("Reactivate tenant").click();+ H.modal().button("Reactivate").click();++ cy.findByRole("link", { name: /tenant users/i }).click();++ // Only 1 Doohickey user should have been re-activated+ cy.findByTestId("admin-layout-content").findByText("1 person found");++ cy.findAllByRole("row").contains("tr", "doohickey").should("exist");+ });++ it("should accept a tenant when provisioning a user via JWT", () => {+ cy.task<string>("signJwt", {+ payload: GIZMO_USER,+ secret: JWT_SECRET,+ }).then((key) =>+ cy.visit(`/auth/sso?return_to=/question/notebook&jwt=${key}`),+ );++ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Products").click();+ });+ cy.button("Visualize").click();++ cy.get("[data-column-id=CATEGORY]")+ .should("not.contain.text", "Doohickey")+ .should("not.contain.text", "Gadget")+ .should("not.contain.text", "Widget")+ .should("contain.text", "Gizmo");++ cy.task<string>("signJwt", {+ payload: DOOHICKEY_USER,+ secret: JWT_SECRET,+ }).then((key) =>+ cy.visit(`/auth/sso?return_to=/question/notebook&jwt=${key}`),+ );++ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Databases").click();+ H.entityPickerModalItem(1, "Products").click();+ });+ cy.button("Visualize").click();++ cy.get("[data-column-id=CATEGORY]")+ .should("not.contain.text", "Gizmo")+ .should("not.contain.text", "Gadget")+ .should("not.contain.text", "Widget")+ .should("contain.text", "Doohickey");++ H.openNavigationSidebar();++ H.navigationSidebar()+ .findByTestId("navbar-new-collection-button")+ .should("not.exist");+ });++ it("should create a tenant group and add users to it", () => {+ cy.intercept("POST", "/api/user").as("createUser");+ cy.intercept("PUT", "/api/user/*").as("updateUser");++ const GROUP_NAME = "Favorites";+ createTenantGroupFromUI(GROUP_NAME);+ cy.findByTestId("admin-content-table").findByText(GROUP_NAME);++ cy.findByTestId("admin-layout-sidebar")+ .findByText(/Tenant users/)+ .click();++ cy.log("put existing user in a group");+ cy.findByTestId("admin-people-list-table")+ .findAllByLabelText("ellipsis icon")+ .first()+ .click();+ H.popover().findByText("Edit user").click();++ H.modal().within(() => {+ cy.findByText("Tenant Groups");+ cy.findByText("All tenant users").click();+ });++ H.popover().findByText(GROUP_NAME).click();++ H.modal().within(() => {+ cy.findByText("Tenant Groups").click(); // trigger blur+ cy.findByText("2 other groups").should("be.visible");+ cy.button("Update").click();+ });++ cy.wait("@updateUser").then(+ ({ request: { body: reqBody }, response: { body: resBody } }) => {+ expect(reqBody.user_group_memberships).to.have.length(2);+ expect(resBody.user_group_memberships).to.have.length(2);+ },+ );++ cy.log("add user in a group");+ cy.button("Create tenant user").click();++ H.modal().within(() => {+ cy.findByLabelText("First name").type("Misty");+ cy.findByLabelText("Last name").type("Cerulean");+ cy.findByLabelText(/Email/).type("[email protected]");+ cy.findByLabelText(/Tenant/).click();+ });++ H.popover().findByText(GIZMO_TENANT.name).click();+ H.modal().findByText("All tenant users").click();+ H.popover().findByText(GROUP_NAME).click();++ H.modal().within(() => {+ cy.findByText("Tenant Groups").click(); // trigger blur+ cy.findByText("2 other groups").should("be.visible");+ cy.button("Create").click();+ });+ cy.wait("@createUser").then(+ ({ request: { body: reqBody }, response: { body: resBody } }) => {+ expect(reqBody.user_group_memberships).to.have.length(2);+ expect(resBody.user_group_memberships).to.have.length(2);+ },+ );+ });++ it("can add tenant users to a tenant group via 'Add members", () => {+ cy.intercept("GET", "/api/user*").as("listUsers");++ const GROUP_NAME = "Marketing Team";+ createTenantGroupFromUI(GROUP_NAME);+ cy.findByTestId("admin-content-table").findByText(GROUP_NAME).click();++ cy.findByTestId("admin-pane-page-title", { name: GROUP_NAME }).should(+ "be.visible",+ );++ cy.button("Add members").click();+ cy.wait("@listUsers");++ cy.findByRole("textbox", { name: /search for a user to add/i }).type(+ "gizmo",+ );++ H.popover().within(() => {+ cy.log("tenant user should be visible");+ cy.findByText(GIZMO_FULL_NAME).should("be.visible");++ cy.log("internal user should not be visible");+ cy.findByText("Bobby Tables").should("not.exist");++ cy.log("select a tenant user to add");+ cy.findByText(GIZMO_FULL_NAME).click();+ });++ cy.button("Add").click();++ cy.log("user should be added to the group");+ cy.findByTestId("admin-content-table")+ .findByText(GIZMO_FULL_NAME)+ .should("be.visible");+ });+});++type AssertionType = "exist" | "not.exist";++const assertPermissionTableColumnsExist = (+ assertions: [+ AssertionType,+ AssertionType,+ AssertionType,+ AssertionType,+ AssertionType,+ ],+) => {+ cy.findByRole("columnheader", { name: "View data" }).should(assertions[0]);+ cy.findByRole("columnheader", { name: "Create queries" }).should(+ assertions[1],+ );+ cy.findByRole("columnheader", { name: /Download results/ }).should(+ assertions[2],+ );+ cy.findByRole("columnheader", { name: "Manage table metadata" }).should(+ assertions[3],+ );+ cy.findByRole("columnheader", { name: "Manage database" }).should(+ assertions[4],+ );+};++function hasGlobeIcon(groupName: string) {+ cy.findByTestId("permission-table")+ .findByText(groupName)+ .parent()+ .parent()+ .icon("globe")+ .should("be.visible");+}++function lacksGlobeIcon(groupName: string) {+ cy.findByTestId("permission-table")+ .findByText(groupName)+ .parent()+ .parent()+ .icon("globe")+ .should("not.exist");+}+const createUsers = () => {+ cy.request("GET", "/api/ee/tenant").then(({ body }) => {+ USERS.forEach((user) => {+ const tenantId = body.data.find(+ (tenant: Tenant) => tenant.slug === user["@tenant"],+ ).id;++ cy.request("POST", "/api/user", { ...user, tenant_id: tenantId });+ });+ });+};++const createTenants = () => {+ TENANTS.forEach((tenant) => cy.request("POST", "/api/ee/tenant", tenant));+};++const createTenantGroupFromUI = (groupName: string) => {+ cy.intercept("POST", "/api/permissions/group").as("createGroup");+ cy.visit("/admin/tenants/groups");++ // FIXME shouldn't be necessary - caused by slow route guard+ cy.findByTestId("admin-layout-sidebar")+ .findByText(/Tenant Groups/)+ .click();++ cy.findByTestId("admin-layout-content")+ .findByRole("heading", { name: /Tenant Groups/ })+ .should("be.visible");++ cy.button("Create a group").click();+ cy.findByPlaceholderText(/something like/i).type(groupName);+ cy.findByRole("button", { name: "Add" }).click();+ cy.wait("@createGroup");+};diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex 6827b65c89d..9bb94890b6e 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -51,9 +51,7 @@ describe("Remote Sync", () => {H.collectionTable().findByText(REMOTE_QUESTION_NAME).should("exist");- H.navigationSidebar()- .findByRole("button", { name: "Push to Git" })- .click();+ H.getPushButton().click();H.modal().button(/Push changes/)@@ -62,7 +60,7 @@ describe("Remote Sync", () => {H.waitForTask({ taskName: "export" });H.expectUnstructuredSnowplowEvent({event: "remote_sync_push_changes",- triggered_from: "sidebar",+ triggered_from: "app-bar",});H.navigationSidebar()@@ -80,14 +78,12 @@ describe("Remote Sync", () => {},);- cy.findByTestId("main-navbar-root")- .findByRole("button", { name: "Pull from Git" })- .click();+ H.getPullButton().click();H.waitForTask({ taskName: "import" });H.expectUnstructuredSnowplowEvent({event: "remote_sync_pull_changes",- triggered_from: "sidebar",+ triggered_from: "app-bar",});H.collectionTable()@@ -153,9 +149,7 @@ describe("Remote Sync", () => {return doc;});- H.navigationSidebar()- .findByRole("button", { name: "Push to Git" })- .click();+ H.getPushButton().click();// Attempt to push changescy.findByRole("dialog", { name: "Push to Git" })@@ -172,9 +166,7 @@ describe("Remote Sync", () => {H.waitForTask({ taskName: "export" });// Ensure that we are on the newly created branch- H.navigationSidebar()- .findByTestId("branch-picker-button")- .should("contain.text", NEW_BRANCH);+ H.branchPicker().should("contain.text", NEW_BRANCH);H.goToSyncedCollection();H.collectionTable().within(() => {@@ -184,7 +176,7 @@ describe("Remote Sync", () => {cy.findByText("Remote Sync Test Question");});- H.navigationSidebar().findByTestId("branch-picker-button").click();+ H.branchPicker().click();H.popover().findByRole("option", { name: "main" }).click();H.waitForTask({ taskName: "import" });@@ -204,7 +196,7 @@ describe("Remote Sync", () => {const createNewBranch = (newBranchName: string) => {branchCount++;- H.navigationSidebar().findByTestId("branch-picker-button").click();+ H.branchPicker().click();H.popover().findByPlaceholderText("Find or create a branch...").type(newBranchName);@@ -220,13 +212,11 @@ describe("Remote Sync", () => {branchCount,);- H.navigationSidebar()- .findByTestId("branch-picker-button")- .should("contain.text", newBranchName);+ H.branchPicker().should("contain.text", newBranchName);};const switchToExistingBranch = (branch: string) => {- H.navigationSidebar().findByTestId("branch-picker-button").click();+ H.branchPicker().click();H.popover().findByPlaceholderText("Find or create a branch...").type(branch);@@ -234,19 +224,15 @@ describe("Remote Sync", () => {};const pushUpdates = () => {- H.navigationSidebar()- .findByRole("button", { name: "Push to Git" })- .click();+ H.getPushButton().click();H.modal().button(/Push changes/).click();H.waitForTask({ taskName: "export" });- // Push button should be hidden when local changes are synced- H.navigationSidebar()- .findByRole("button", { name: "Push to Git" })- .should("not.exist");+ // Push button should be disabled when local changes are synced+ H.getPushButton().should("be.disabled");};it("should allow you to create new branches and switch between them", () => {@@ -287,7 +273,7 @@ describe("Remote Sync", () => {H.expectUnstructuredSnowplowEvent({event: "remote_sync_branch_switched",- triggered_from: "sidebar",+ triggered_from: "app-bar",});H.collectionTable().findByText("Orders, Count").should("exist");@@ -319,9 +305,7 @@ describe("Remote Sync", () => {switchToExistingBranch("main");// Check that we haven't switched to main- H.navigationSidebar()- .findByTestId("branch-picker-button")- .should("not.contain.text", "main");+ H.branchPicker().should("not.contain.text", "main");H.modal().should("exist");H.modal().within(() => {@@ -335,15 +319,13 @@ describe("Remote Sync", () => {// Choose discard so that we can switch latercy.findByLabelText(- "Delete unsynced changes (can’t be undone)",+ /Delete unsynced changes \(can.t be undone\)/,).click();cy.button(/Delete unsynced changes/).click();});// Now we switched to main- H.navigationSidebar()- .findByTestId("branch-picker-button")- .should("contain.text", "main");+ H.branchPicker().should("contain.text", "main");});});@@ -360,9 +342,7 @@ describe("Remote Sync", () => {H.moveCollectionItemToSyncedCollection("Orders");H.goToSyncedCollection();- H.navigationSidebar()- .findByRole("button", { name: "Pull from Git" })- .click();+ H.getPullButton().click();});it("push changes", () => {@@ -451,6 +431,8 @@ describe("Remote Sync", () => {it("can set up read-write mode", () => {cy.visit("/admin/settings/remote-sync");cy.findByLabelText(/repository url/i)+ .should("be.visible")+ .click().clear().type(LOCAL_GIT_URL);cy.findByTestId("admin-layout-content").findByText("Read-write").click();@@ -469,11 +451,11 @@ describe("Remote Sync", () => {H.modal().should("not.exist");cy.findByTestId("exit-admin").click();+ // Branch picker is now in the app bar+ H.branchPicker().should("contain.text", "main");++ // Synced collection appears in regular collections list (no separate heading)H.navigationSidebar().within(() => {- cy.findByRole("heading", { name: /synced collections/i }).should(- "exist",- );- cy.findByTestId("branch-picker-button").should("contain.text", "main");cy.findByRole("treeitem", { name: /Synced Collection/i }).should("exist",);@@ -490,6 +472,8 @@ describe("Remote Sync", () => {cy.visit("/admin/settings/remote-sync");cy.findByLabelText(/repository url/i)+ .should("be.visible")+ .click().clear().type(LOCAL_GIT_URL);@@ -502,12 +486,10 @@ describe("Remote Sync", () => {H.modal().should("not.exist", { timeout: 10000 });cy.findByTestId("exit-admin").click();- H.navigationSidebar().within(() => {- cy.findByRole("heading", { name: /synced collections/i }).should(- "not.exist",- );- cy.findByTestId("branch-picker-button").should("not.exist");+ // In read-only mode, git sync controls should not be visible in app bar+ H.getGitSyncControls().should("not.exist");+ H.navigationSidebar().within(() => {cy.findByRole("treeitem", { name: /Synced Collection/ }).click();});});@@ -524,12 +506,17 @@ describe("Remote Sync", () => {cy.button("Set up Remote Sync").should("be.disabled");cy.findByLabelText(/Access Token/i)+ .should("be.visible")+ .click().clear().type("SecretToken");// Still disabled - url is not setcy.button("Set up Remote Sync").should("be.disabled");cy.findByLabelText(/repository url/i)+ .scrollIntoView()+ .should("be.visible")+ .click().clear().type(LOCAL_GIT_URL);@@ -541,6 +528,8 @@ describe("Remote Sync", () => {cy.intercept("PUT", "/api/ee/remote-sync/settings").as("saveSettings");cy.visit("/admin/settings/remote-sync");cy.findByLabelText(/repository url/i)+ .should("be.visible")+ .click().clear().type("file://invalid-path");cy.button("Set up Remote Sync").click();@@ -563,11 +552,8 @@ describe("Remote Sync", () => {cy.visit("/admin/settings/remote-sync");- cy.findByTestId("admin-layout-content")- .findByText("Enabled")- .should("exist");-- cy.button("Disable Remote Sync").click();+ // The button may be scrolled off screen - scroll to bottom of the settings content first+ cy.button(/Disable remote sync/).click();H.modal().within(() => {cy.findByRole("heading", { name: "Disable Remote Sync?" }).should(@@ -621,7 +607,7 @@ describe("Remote Sync", () => {});cy.visit("/admin/settings/remote-sync");- cy.findByLabelText("Sync branch").clear().type("test");+ cy.findByLabelText("Sync branch").scrollIntoView().clear().type("test");cy.findByTestId("remote-sync-submit-button").click();cy.findByTestId("admin-layout-content")@@ -644,6 +630,235 @@ describe("Remote Sync", () => {H.collectionTable().findByText(UPDATED_REMOTE_QUESTION_NAME);});});++ describe("shared tenant collections", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.setupGitSync();+ H.interceptTask();++ // Enable tenants feature+ H.enableTenants();+ });++ afterEach(() => {+ H.expectNoBadSnowplowEvents();+ });++ describe("admin settings", () => {+ it("should show shared tenant collections section when tenants are enabled and remote sync is configured", () => {+ // First set up remote sync+ H.configureGit("read-write");++ // Create some tenant collections+ H.createSharedTenantCollection("Tenant A Shared");+ H.createSharedTenantCollection("Tenant B Shared");++ cy.visit("/admin/settings/remote-sync");++ cy.findByTestId("admin-layout-content").within(() => {+ // Section should be visible+ cy.findByText("Shared tenant collections to sync").should("exist");++ // Should show the tenant collections+ cy.findByText("Tenant A Shared").should("exist");+ cy.findByText("Tenant B Shared").should("exist");++ // Each collection should have a sync toggle+ cy.findAllByRole("switch").should("have.length.at.least", 2);+ });+ });++ it("should not show shared tenant collections section when tenants are disabled", () => {+ // Disable tenants+ cy.request("PUT", "/api/setting/use-tenants", { value: false });++ H.configureGit("read-write");+ cy.visit("/admin/settings/remote-sync");++ // Section should NOT be visible+ cy.findByTestId("admin-layout-content")+ .findByText("Shared tenant collections to sync")+ .should("not.exist");+ });++ it("should not show shared tenant collections section when remote sync is not enabled", () => {+ cy.visit("/admin/settings/remote-sync");++ // Section should NOT be visible (remote sync not yet configured)+ cy.findByTestId("admin-layout-content")+ .findByText("Shared tenant collections to sync")+ .should("not.exist");+ });++ it("should show empty state when no shared tenant collections exist", () => {+ H.configureGit("read-write");+ cy.visit("/admin/settings/remote-sync");++ cy.findByTestId("admin-layout-content").within(() => {+ cy.findByText("Shared tenant collections to sync").should("exist");+ cy.findByText("No shared tenant collections found").should("exist");+ });+ });++ it("can toggle sync for a shared tenant collection", () => {+ H.configureGit("read-write");++ // Create a tenant collection+ H.createSharedTenantCollection("Tenant Collection To Sync");++ cy.visit("/admin/settings/remote-sync");++ cy.findByTestId("admin-layout-content").within(() => {+ // Find the collection row and toggle sync on+ cy.findByRole("switch", {+ name: "Sync Tenant Collection To Sync",+ }).click({ force: true });++ // Save changes+ cy.button("Save changes").click();++ // Verify the setting was saved+ cy.findByText(/success/i).should("exist");+ });+ });++ it("should disable sync toggles in read-only mode", () => {+ H.copySyncedCollectionFixture();+ H.commitToRepo();+ H.configureGit("read-only");++ // Create a tenant collection+ H.createSharedTenantCollection("Read Only Tenant Collection");++ cy.visit("/admin/settings/remote-sync");++ // The switch should be disabled in read-only mode+ cy.findByTestId("admin-layout-content")+ .findByRole("switch", { name: "Sync Read Only Tenant Collection" })+ .should("be.disabled");+ });++ it("should reset collection toggles when switching from read-write to read-nly", () => {+ H.copySyncedCollectionFixture();+ H.commitToRepo();+ H.configureGit("read-write");++ // Create a tenant collection+ H.createSharedTenantCollection("Mode Switch Test Collection");++ cy.visit("/admin/settings/remote-sync");++ cy.findByTestId("admin-layout-content").within(() => {+ // Toggle sync on+ cy.findByRole("switch", {+ name: "Sync Mode Switch Test Collection",+ }).click({ force: true });++ // Verify it's checked+ cy.findByRole("switch", {+ name: "Sync Mode Switch Test Collection",+ }).should("be.checked");++ // Switch to read-only mode+ cy.findByText("Read-only").click();++ // The toggle should reset to unchecked (initial value)+ cy.findByRole("switch", {+ name: "Sync Mode Switch Test Collection",+ }).should("not.be.checked");+ });+ });+ });++ describe("syncing tenant collections", () => {+ it("can push changes from a synced tenant collection", () => {+ H.configureGit("read-write");++ // Create a tenant collection+ H.createSharedTenantCollection("Syncable Tenant Collection").then(+ (response) => {+ const tenantCollectionId = response.body.id;++ // Enable sync for this collection via admin settings+ cy.visit("/admin/settings/remote-sync");+ // Mantine Switch has a hidden input (0x0 pixels), so we need force: true+ cy.findByTestId("admin-layout-content")+ .findByRole("switch", { name: "Sync Syncable Tenant Collection" })+ .click({ force: true });+ cy.findByTestId("admin-layout-content")+ .button("Save changes")+ .click();++ // Create a question in the tenant collection+ H.createQuestion({+ name: "Tenant Question",+ query: {+ "source-table": PRODUCTS_ID,+ },+ collection_id: tenantCollectionId,+ });++ cy.visit("/");++ // Verify sync status indicator appears+ H.getSyncStatusIndicators().should("have.length.greaterThan", 0);++ // Push changes+ H.getPushButton().click();+ H.modal()+ .button(/Push changes/)+ .click();+ H.waitForTask({ taskName: "export" });++ // Verify changes were pushed (status indicator should clear)+ H.navigationSidebar()+ .findByRole("link", { name: /Syncable Tenant Collection/ })+ .findByTestId("remote-sync-status")+ .should("not.exist");+ },+ );+ });++ it("shows sync status badge on synced tenant collections in sidebar", () => {+ H.configureGit("read-write");++ // Create a tenant collection+ H.createSharedTenantCollection("Badge Test Collection").then(+ (response) => {+ const collectionId = response.body.id;++ // Enable sync+ cy.visit("/admin/settings/remote-sync");+ // Mantine Switch has a hidden input (0x0 pixels), so we need force: true+ cy.findByTestId("admin-layout-content")+ .findByRole("switch", { name: "Sync Badge Test Collection" })+ .click({ force: true });+ cy.findByTestId("admin-layout-content")+ .button("Save changes")+ .click();++ // Create content to trigger dirty state+ H.createQuestion({+ name: "Status Badge Test Question",+ query: { "source-table": PRODUCTS_ID },+ collection_id: collectionId,+ });++ cy.visit("/");++ // Verify the sync status badge appears on the tenant collection+ H.navigationSidebar()+ .findByRole("treeitem", { name: /Badge Test Collection/ })+ .findByTestId("remote-sync-status")+ .should("exist");+ },+ );+ });+ });+ });});const ensureSyncedCollectionIsVisible = () => {diff --git a/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js b/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.jsindex d7f391a494b..2dacfae4950 100644--- a/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js+++ b/e2e/test/scenarios/dashboard-filters/dashboard-filters-auto-wiring.cy.spec.js@@ -502,13 +502,13 @@ describe("dashboard filters auto-wiring", () => {goToFilterMapping("ID");H.undoToastList()- .findByText("Auto-connect “Orders Question” to “ID”?")+ .contains("Auto-connect “Orders Question” to “ID”?").closest("[data-testid='toast-undo']").findByRole("button", { name: "Auto-connect" }).click();H.undoToastList()- .findByText("Auto-connect “Reviews Question” to “ID”?")+ .contains("Auto-connect “Reviews Question” to “ID”?").closest("[data-testid='toast-undo']").findByRole("button", { name: "Auto-connect" }).click();diff --git a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.tsindex 7b4df9bc13a..41a67f11b45 100644--- a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts+++ b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts@@ -259,5 +259,76 @@ describe("scenarios - embedding hub", () => {.findByText("Get started with modular embedding").should("not.exist");});++ it('"Set up tenants" card should navigate to admin settings', () => {+ H.restore("setup");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ cy.request("PUT", "/api/setting/embedding-homepage", {+ value: "visible",+ });++ cy.visit("/");++ H.main().findByText("Set up tenants").should("be.visible").click();++ H.modal().within(() => {+ cy.findByText("User strategy").should("be.visible");+ cy.findByText("Multi tenant").click();+ cy.button("Apply").click();+ });++ cy.log("the internal prefix should show up on the page");+ H.main()+ .findAllByText("Internal Users")+ .should("have.length", 2)+ .should("be.visible");++ cy.visit("/");++ cy.log("'Set up tenants' should now be marked as done");+ H.main()+ .findByText("Set up tenants")+ .closest("button")+ .scrollIntoView()+ .findByText("Done", { timeout: 10_000 })+ .should("be.visible");++ cy.log("clicking on tenants should go to tenants page");+ H.main().findByText("Set up tenants").click();+ cy.url().should("include", "/admin/tenants");+ });++ it("should link to user strategy when tenants are disabled", () => {+ H.restore("setup");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ cy.visit("/admin/embedding/setup-guide");++ H.main()+ .findByText("Tenants")+ .scrollIntoView()+ .should("be.visible")+ .closest("a")+ .should("have.attr", "href", "/admin/people/user-strategy");+ });++ it("should link to tenants page when tenants are enabled", () => {+ H.restore("setup");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");++ H.updateSetting("use-tenants", true);+ cy.visit("/admin/embedding/setup-guide");++ H.main()+ .findByText("Tenants")+ .scrollIntoView()+ .should("be.visible")+ .closest("a")+ .should("have.attr", "href", "/admin/tenants");+ });});});diff --git a/e2e/test/scenarios/embedding/modular-embedding-settings.cy.spec.ts b/e2e/test/scenarios/embedding/modular-embedding-settings.cy.spec.tsnew file mode 100644index 00000000000..ed948d828fe--- /dev/null+++ b/e2e/test/scenarios/embedding/modular-embedding-settings.cy.spec.ts@@ -0,0 +1,32 @@+const { H } = cy;++describe("scenarios > modular embedding settings", { tags: "@EE" }, () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ it("should link to user strategy when tenants are disabled", () => {+ cy.visit("/admin/embedding/modular");++ H.main()+ .findByText("Tenants")+ .scrollIntoView()+ .should("be.visible")+ .closest("a")+ .should("have.attr", "href", "/admin/people/user-strategy");+ });++ it("should link to tenants page when tenants are enabled", () => {+ H.updateSetting("use-tenants", true);+ cy.visit("/admin/embedding/modular");++ H.main()+ .findByText("Tenants")+ .scrollIntoView()+ .should("be.visible")+ .closest("a")+ .should("have.attr", "href", "/admin/tenants");+ });+});diff --git a/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.tsnew file mode 100644index 00000000000..2aa626b2282--- /dev/null+++ b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts@@ -0,0 +1,362 @@+const { H } = cy;+import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";++const TENANT_ROOT_NAME = "Shared collections";+const TENANT_NAMESPACE = "shared-tenant-collection";++/**+ * Create a collection in the shared-tenant-collection namespace.+ * Collections with this namespace and no parent_id are children of the virtual root.+ */+function createTenantCollection(name: string, parentId?: number) {+ return cy.request("POST", "/api/collection", {+ name,+ namespace: TENANT_NAMESPACE,+ parent_id: parentId ?? null,+ });+}++/**+ * Create test data: a tenant collection and sub-collection+ */+function setupTenantCollections() {+ return createTenantCollection("Test Tenant Collection").then((response) => {+ const tenantCollectionId = response.body.id;++ return createTenantCollection(+ "Tenant Sub-Collection",+ tenantCollectionId,+ ).then((subResponse) => {+ return {+ tenantCollectionId,+ subCollectionId: subResponse.body.id,+ };+ });+ });+}++describe("scenarios > organization > entity picker > shared-tenant-collection namespace", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.updateSetting("use-tenants", true);+ });++ describe("virtual tenant root display", () => {+ it("should display Shared collections in the entity picker when tenants are enabled", () => {+ setupTenantCollections().then(() => {+ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).should("be.visible");+ });+ });+ });++ it("should NOT display Shared collections when tenants are disabled", () => {+ H.updateSetting("use-tenants", false);++ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).should("not.exist");+ });+ });++ it("should navigate into Shared collections and see sub-collections", () => {+ setupTenantCollections().then(() => {+ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.findByText("Test Tenant Collection").should("be.visible");+ });+ });+ });+ });++ describe("collection creation (allowed)", () => {+ it("should allow creating a new collection inside the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ cy.visit("/collection/root");++ H.startNewCollectionFromSidebar();++ cy.findByTestId("new-collection-modal").within(() => {+ cy.findByPlaceholderText(/My new fantastic collection/).type(+ "New Collection In Tenant Root",+ );+ cy.findByLabelText(/Collection it's saved in/).click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.button("Select").should("not.be.disabled");+ cy.button("Select").click();+ });++ cy.findByTestId("new-collection-modal").within(() => {+ cy.button("Create").click();+ });+ });+ });++ it("should not allow moving a collection to the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ H.createCollection({ name: "Collection To Move" }).then(+ ({ body: collection }) => {+ H.visitCollection(collection.id);++ H.openCollectionMenu();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.findByText(TENANT_ROOT_NAME).should("not.exist");++ // Close the modal+ cy.button("Cancel").click();+ });++ // The collection should still be in Our analytics (root)+ H.navigationSidebar().within(() => {+ cy.findByText("Our analytics").click();+ });+ H.navigationSidebar()+ .findByText("Collection To Move")+ .should("be.visible");+ },+ );+ });+ });+ });++ describe("dashboard restrictions", () => {+ it("should NOT allow saving a dashboard to the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ cy.visit("/");++ H.newButton("Dashboard").click();++ H.modal().within(() => {+ cy.findByLabelText(/Which collection/).click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.button("Select").should("be.disabled");+ });+ });+ });++ it("should allow saving a dashboard to a sub-collection within tenant namespace", () => {+ setupTenantCollections().then(() => {+ cy.visit("/");++ H.newButton("Dashboard").click();++ H.modal().within(() => {+ cy.findByLabelText(/Which collection/).click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.findByText(TENANT_ROOT_NAME).click();+ cy.findByText("Test Tenant Collection").click();++ cy.button("Select").should("not.be.disabled");+ cy.button("Select").click();+ });++ H.modal().within(() => {+ cy.findByLabelText(/Name/).type("Dashboard in Tenant Collection");+ cy.button("Create").click();+ });++ cy.url().should("include", "/dashboard/");+ });+ });++ it("should NOT allow moving a dashboard to the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ H.createDashboard({+ name: "Dashboard to Move",+ collection_id: null,+ }).then(({ body: dashboard }) => {+ H.visitDashboard(dashboard.id);++ cy.findByTestId("dashboard-header").icon("ellipsis").click();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.button("Move").should("be.disabled");++ cy.findByText("Test Tenant Collection").click();+ cy.button("Move").should("not.be.disabled");+ });+ });+ });+ });+ });++ describe("question restrictions", () => {+ it("should NOT allow saving a question to the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ H.startNewQuestion();+ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Databases").click();+ cy.findByText("Orders").click();+ });++ H.visualize();+ cy.findByTestId("qb-save-button").click();++ H.modal().within(() => {+ cy.findByLabelText(/Where do you want to save this/).click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.button("Select this collection").should("be.disabled");+ });+ });+ });++ it("should allow saving a question to a sub-collection within tenant namespace", () => {+ setupTenantCollections().then(() => {+ H.startNewQuestion();+ H.miniPickerBrowseAll().click();+ H.entityPickerModal().within(() => {+ H.entityPickerModalItem(0, "Databases").click();+ cy.findByText("Orders").click();+ });++ H.visualize();+ cy.findByTestId("qb-save-button").click();++ H.modal().within(() => {+ cy.findByLabelText(/Where do you want to save this/).click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).click();+ cy.findByText("Test Tenant Collection").click();++ cy.button("Select this collection").should("not.be.disabled");+ cy.button("Select this collection").click();+ });++ H.modal().within(() => {+ cy.findByLabelText(/Name/)+ .clear()+ .type("Question in Tenant Collection");+ cy.button("Save").click();+ });++ cy.findByTestId("qb-header").should(+ "contain",+ "Question in Tenant Collection",+ );+ });+ });++ it("should NOT allow moving a question to the tenant namespace root", () => {+ setupTenantCollections().then(() => {+ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Browse").click();+ cy.findByText(TENANT_ROOT_NAME).click();++ cy.button("Move").should("be.disabled");++ cy.findByText("Test Tenant Collection").click();+ cy.button("Move").should("not.be.disabled");+ });+ });+ });+ });++ describe("search functionality", () => {+ it("should find tenant collections via search", () => {+ setupTenantCollections().then(() => {+ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ cy.findByPlaceholderText(/Search/).type("Test Tenant Collection");++ cy.findByText("Test Tenant Collection").should("be.visible");+ });+ });+ });++ it("should NOT show tenant collections in search when moving a non-tenant collection", () => {+ setupTenantCollections().then(() => {+ H.createCollection({ name: "Regular Collection" }).then(+ ({ body: collection }) => {+ H.visitCollection(collection.id);++ H.openCollectionMenu();+ H.popover().findByText("Move").click();++ H.entityPickerModal().within(() => {+ // Search for the tenant collection+ cy.findByPlaceholderText(/Search/).type("Test Tenant Collection");++ // Tenant collection should NOT appear in search results+ cy.findByText("Test Tenant Collection").should("not.exist");++ // Clear search and verify regular collections are still searchable+ cy.findByPlaceholderText(/Search/)+ .clear()+ .type("First collection");+ cy.findByText("First collection").should("be.visible");+ });+ },+ );+ });+ });+ });++ describe("add to dashboard flow", () => {+ it("should NOT allow creating new dashboard in tenant root via add-to-dashboard flow", () => {+ setupTenantCollections().then(() => {+ H.visitQuestion(ORDERS_QUESTION_ID);+ H.openQuestionActions();+ H.popover().findByText("Add to dashboard").click();++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Dashboards").click();+ cy.findByText(TENANT_ROOT_NAME).click();+ cy.button(/New dashboard/).should("be.disabled");+ });+ });+ });+ });+});diff --git a/e2e/test/scenarios/permissions/downgrade-ee-to-oss.cy.spec.js b/e2e/test/scenarios/permissions/downgrade-ee-to-oss.cy.spec.jsindex 30bc5538777..4c44600ceb9 100644--- a/e2e/test/scenarios/permissions/downgrade-ee-to-oss.cy.spec.js+++ b/e2e/test/scenarios/permissions/downgrade-ee-to-oss.cy.spec.js@@ -35,7 +35,13 @@ describe("scenarios > admin > permissions > downgrade ee to oss", () => {cy.reload();H.assertPermissionTable([["Sample Database", "No"]]);- H.isPermissionDisabled(OSS_NATIVE_QUERIES_PERMISSION_INDEX, "No", false);++ H.isPermissionDisabled(+ "Sample Database",+ OSS_NATIVE_QUERIES_PERMISSION_INDEX,+ "No",+ false,+ );H.modifyPermission("Sample Database",diff --git a/e2e/test/scenarios/permissions/view-data.cy.spec.js b/e2e/test/scenarios/permissions/view-data.cy.spec.jsindex 25041b6084b..df0a9fb7694 100644--- a/e2e/test/scenarios/permissions/view-data.cy.spec.js+++ b/e2e/test/scenarios/permissions/view-data.cy.spec.js@@ -462,7 +462,13 @@ describe("scenarios > admin > permissions > view data > legacy no self-service",H.popover().should("not.contain", "No self-service (Deprecated)");H.selectPermissionRow("Sample Database", CREATE_QUERIES_PERM_IDX);- H.isPermissionDisabled(CREATE_QUERIES_PERM_IDX, "No", false);++ H.isPermissionDisabled(+ "Sample Database",+ CREATE_QUERIES_PERM_IDX,+ "No",+ false,+ );// load the page w/ legacy value in the graph and test that it does existcy.reload();@@ -494,7 +500,12 @@ describe("scenarios > admin > permissions > view data > legacy no self-service",]);// User should not be able to modify Create queries permission while set to legacy-no-self-service- H.isPermissionDisabled(CREATE_QUERIES_PERM_IDX, "No", true);+ H.isPermissionDisabled(+ "Sample Database",+ CREATE_QUERIES_PERM_IDX,+ "No",+ true,+ );H.modifyPermission("Sample Database", DATA_ACCESS_PERM_IDX, "Can view");diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.cljindex 1f888d33cd8..bdf10d368ec 100644--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj@@ -36,6 +36,7 @@[metabase-enterprise.serialization.api][metabase-enterprise.stale.api][metabase-enterprise.support-access-grants.api]+ [metabase-enterprise.tenants.api][metabase-enterprise.transforms-python.api][metabase-enterprise.transforms.api][metabase-enterprise.upload-management.api]@@ -48,11 +49,11 @@(def ^:private required-feature->message{:advanced-permissions (deferred-tru "Advanced Permissions")- :attached-dwh (deferred-tru "Attached DWH")- :audit-app (deferred-tru "Audit app"):ai-sql-fixer (deferred-tru "AI SQL Fixer"):ai-sql-generation (deferred-tru "AI SQL Generation"):ai-entity-analysis (deferred-tru "AI Entity Analysis")+ :attached-dwh (deferred-tru "Attached DWH")+ :audit-app (deferred-tru "Audit app"):collection-cleanup (deferred-tru "Collection Cleanup"):content-translation (deferred-tru "Content translation"):data-studio (deferred-tru "Data Studio")@@ -68,6 +69,7 @@:serialization (deferred-tru "Serialization"):table-data-editing (deferred-tru "Table Data Editing"):transforms (deferred-tru "Transforms")+ :tenants (deferred-tru "Tenants"):upload-management (deferred-tru "Upload Management"):database-routing (deferred-tru "Database Routing"):cloud-custom-smtp (deferred-tru "Custom SMTP")@@ -131,6 +133,7 @@"/transform" (premium-handler metabase-enterprise.transforms.api/routes :transforms)"/transform-job" (premium-handler metabase-enterprise.transforms.api/transform-job-routes :transforms)"/transform-tag" (premium-handler metabase-enterprise.transforms.api/transform-tag-routes :transforms)+ "/tenant" (premium-handler metabase-enterprise.tenants.api/routes :tenants)"/upload-management" (premium-handler metabase-enterprise.upload-management.api/routes :upload-management)});;; ↑↑↑ KEEP THIS SORTED OR ELSE ↑↑↑diff --git a/enterprise/backend/src/metabase_enterprise/auth_identity/provider.clj b/enterprise/backend/src/metabase_enterprise/auth_identity/provider.cljindex 0c90fa71f0e..af1e110b451 100644--- a/enterprise/backend/src/metabase_enterprise/auth_identity/provider.clj+++ b/enterprise/backend/src/metabase_enterprise/auth_identity/provider.clj@@ -14,5 +14,7 @@(cond-> [:email :first_name :last_name :sso_source](some premium-features/has-feature? [:sso-ldap :sso-jwt :sso-saml])(conj :login_attributes)+ (premium-features/has-feature? :tenants)+ (conj :tenant_id)(premium-features/has-feature? :sso-jwt)(conj :jwt_attributes)))diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/common.clj b/enterprise/backend/src/metabase_enterprise/database_routing/common.cljindex 51eb4cc4191..454dd5c7d2e 100644--- a/enterprise/backend/src/metabase_enterprise/database_routing/common.clj+++ b/enterprise/backend/src/metabase_enterprise/database_routing/common.clj@@ -14,30 +14,27 @@(def ^:dynamic ^:private *database-routing-on* :unset)-(defn router-db-or-id->destination-db-id- "Given a user and a database (or id), returns the ID of the destination database that the user's query should ultimately be- routed to. If the database is not a Router Database, returns `nil`. If the database is a Router Database but no- current user exists, an exception will be thrown."- [db-or-id]+(defn- router-db-or-id->destination-db-id*+ [is-anonymous-user? user-attributes is-superuser? db-or-id](when-let [attr-name (user-attribute db-or-id)]- (let [database-name (get (api/current-user-attributes) attr-name)]+ (let [database-name (get user-attributes attr-name)](cond- ;; if database routing is EXPLICITLY off, e.g. in `POST /api/database/:id/sync_schema`, don't do any routing.+ ;; if database routing is EXPLICITLY off, e.g. in `POST /api/database/:id/sync_schema`, don't do any routing.(= :off *database-routing-on*)nil- (nil? @api/*current-user*)+ is-anonymous-user?(throw (ex-info (tru "Anonymous users cannot access a database with routing enabled.") {:status-code 400}))(= database-name "__METABASE_ROUTER__")nil- ;; superusers default to the Router Database+ ;; superusers default to the Router Database(and (nil? database-name)- api/*is-superuser?*)+ is-superuser?)nil- ;; non-superusers get an error+ ;; non-superusers get an error(nil? database-name)(throw (ex-info (tru "Required user attribute is missing. Cannot route to a Destination Database."){:database-name database-name@@ -54,6 +51,17 @@:router-database-id (u/the-id db-or-id):status-code 400})))))))+(defn router-db-or-id->destination-db-id+ "Given a user and a database (or id), returns the ID of the destination database that the user's query should ultimately be+ routed to. If the database is not a Router Database, returns `nil`. If the database is a Router Database but no+ current user exists, an exception will be thrown."+ [db-or-id]+ (router-db-or-id->destination-db-id*+ (nil? @api/*current-user*)+ (api/current-user-attributes)+ api/*is-superuser?*+ db-or-id))+;; We want, at all times, a guarantee that we are not hitting a router *or* destination database without being;; intentional about it. It would be bad to EITHER:;;diff --git a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.cljindex 97d37b943a7..ce5ba948f4c 100644--- a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj+++ b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj@@ -6,6 +6,7 @@[metabase.appearance.core :as appearance][metabase.audit-app.core :as audit][metabase.embedding.settings :as embedding.settings]+ [metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][toucan2.core :as t2]))@@ -59,7 +60,8 @@"configure-row-column-security" (has-configured-sandboxes?)"create-test-embed" (embedding.settings/embedding-hub-test-embed-snippet-created)"embed-production" (embedding.settings/embedding-hub-production-embed-snippet-created)- "secure-embeds" (has-configured-sso?)})+ "secure-embeds" (has-configured-sso?)+ "setup-tenants" (perms/use-tenants)});; 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 happendiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.cljindex 000a913ab53..775280f2e29 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.remote-sync.api(:require[medley.core :as m]+ [metabase-enterprise.remote-sync.core :as remote-sync.core][metabase-enterprise.remote-sync.impl :as impl][metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object][metabase-enterprise.remote-sync.models.remote-sync-task :as remote-sync.task]@@ -111,17 +112,29 @@"Update Remote Sync related settings. You must be a superuser to do this."[_route-params_query-params- {:keys [remote-sync-type] :as settings}+ {:keys [remote-sync-type collections] :as settings}:- [:map[:remote-sync-url {:optional true} [:maybe :string]][:remote-sync-token {:optional true} [:maybe :string]][:remote-sync-type {:optional true} [:maybe [:enum :read-only :read-write]]]- [:remote-sync-branch {:optional true} [:maybe :string]]]]+ [:remote-sync-branch {:optional true} [:maybe :string]]+ [:collections {:optional true} [:maybe [:map-of pos-int? :boolean]]]]](api/check-superuser)(api/check-400 (not (and (remote-sync.object/dirty-global?) (= :read-only remote-sync-type)))"There are unsaved changes in the Remote Sync collection which will be overwritten switching to read-only mode.")+ ;; Check if trying to change collections while in read-only mode+ (let [effective-type (or remote-sync-type (settings/remote-sync-type))]+ (api/check-400 (not (and (seq collections) (= :read-only effective-type)))+ "Cannot change synced collections when remote-sync-type is read-only."))+ (when (seq collections)+ (try+ (remote-sync.core/bulk-set-remote-sync collections)+ (catch Exception e+ (throw (ex-info (or (ex-message e) "Invalid collection settings")+ {:error (ex-message e)+ :status-code 400} e)))))(try- (settings/check-and-update-remote-settings! settings)+ (settings/check-and-update-remote-settings! (dissoc settings :collections))(catch Exception e(throw (ex-info (or (ex-message e) "Invalid settings"){:error (ex-message e)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.cljindex 81f09a49589..34951b62846 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj@@ -3,9 +3,13 @@[metabase-enterprise.remote-sync.settings :as settings][metabase-enterprise.remote-sync.source :as source][metabase-enterprise.remote-sync.source.protocol :as source.p]+ [metabase.api.common :as api][metabase.collections.core :as collections]+ [metabase.events.core :as events][metabase.premium-features.core :refer [defenterprise]]- [potemkin :as p]))+ [metabase.util.malli :as mu]+ [potemkin :as p]+ [toucan2.core :as t2]))(commentsource/keep-me)@@ -27,3 +31,43 @@[collection](or (= (settings/remote-sync-type) :read-write)(not (collections/remote-synced-collection? collection))))++(mu/defn bulk-set-remote-sync :- :nil+ "Sets remote sync to true/false on one or collections in a single transaction. Checks that the remote sync state+ afterwards is consistent in terms of dependency rules. Collections are provided as a map of collection-id -> sync state."+ [collection-states :- [:map-of pos-int? :boolean]]+ (let [{:keys [sync-on sync-off]} (-> (reduce-kv (fn [sync-states collection-id sync-state]+ (if sync-state+ (update sync-states :sync-on conj collection-id)+ (update sync-states :sync-off conj collection-id)))+ {:sync-on #{} :sync-off #{}}+ collection-states)+ (update :sync-on #(when-let [sync-on (seq %)]+ (t2/select :model/Collection :id [:in sync-on])))+ (update :sync-off #(when-let [sync-off (seq %)]+ (t2/select :model/Collection :id [:in sync-off]))))]+ (t2/with-transaction [_]+ (when (seq sync-on)+ (t2/query {:update (t2/table-name :model/Collection)+ :set {:is_remote_synced true}+ :where (into [:or [:in :id (map :id sync-on)]]+ (for [collection sync-on]+ [:like :location (str (collections/location-path collection) "%")]))}))+ (when (seq sync-off)+ (t2/query {:update (t2/table-name :model/Collection)+ :set {:is_remote_synced false}+ :where (into [:or [:in :id (map :id sync-off)]]+ (for [collection sync-off]+ [:like :location (str (collections/location-path collection) "%")]))}))+ (doseq [collection sync-on]+ (collections/check-non-remote-synced-dependencies collection))+ (doseq [collection sync-off]+ (collections/check-remote-synced-dependents collection)))+ (doseq [collection sync-on+ ;; only publish event when this changed+ :when (not (:is_remote_synced collection))]+ (events/publish-event! :event/collection-update {:object collection :user-id api/*current-user-id*}))+ (doseq [collection sync-off+ ;; only publish event when this changed+ :when (:is_remote_synced collection)]+ (events/publish-event! :event/collection-update {:object collection :user-id api/*current-user-id*}))))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex f217509f532..2b5a036196c 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -199,7 +199,15 @@:continue-on-error false:skip-archived true})](remote-sync.task/update-progress! task-id 0.3)- (let [written-version (source/store! models snapshot task-id message)]+ (let [top-level-removed-prefixes (->> (t2/query {:select [:c.entity_id]+ :from [[:collection :c]]+ :join [[:remote_sync_object :rso]+ [:and [:= :rso.model_type [:inline "Collection"]]+ [:= :rso.status [:inline "removed"]]+ [:= :rso.model_id :c.id]]]+ :where [:= :location "/"]})+ (map #(str "collections/" (:entity_id %))))+ written-version (source/store! models top-level-removed-prefixes snapshot task-id message)](remote-sync.task/set-version! task-id written-version))(t2/update! :model/RemoteSyncObject {:status "synced" :status_changed_at sync-timestamp}))){:status :successdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source.cljindex 9e13d46c53c..13862e93c5c 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj@@ -59,26 +59,33 @@(when (instance? Exception entity);; Just short-circuit if there are errors.(throw entity))- (u/prog1 {:path (remote-sync-path opts entity)- :content (yaml/generate-string (serialization/serialization-deep-sort entity)- {:dumper-options {:flow-style :block :split-lines false}})}+ (u/prog1 (if (string? entity)+ ;; when an entity is a string that means it's a path to delete+ {:path entity+ :remove? true}+ {:path (remote-sync-path opts entity)+ :content (yaml/generate-string (serialization/serialization-deep-sort entity)+ {:dumper-options {:flow-style :block :split-lines false}})})(remote-sync.task/update-progress! task-id (-> (inc idx) (/ count) (* 0.65) (+ 0.3)))))(defn store!"Stores serialized entities from a stream to a remote source and commits the changes.- Takes a stream (a sequence of serialized entities to be stored), a snapshot (the remote source implementing the- SourceSnapshot protocol where files will be written), a task-id (the RemoteSyncTask identifier used to track progress- updates), and a message (the commit message to use when writing files to the source).+ Takes a stream (a sequence of serialized entities to be stored), a list of prefixes to recursively-delete at,+ a snapshot (the remote source implementing the SourceSnapshot protocol where files will be written), a task-id+ (the RemoteSyncTask identifier used to track progress updates), and a message (the commit message to use when+ writing files to the source).Returns the version written to the source.Throws Exception if any entity in the stream is an Exception instance."- [stream snapshot task-id message]+ [stream delete-prefixes snapshot task-id message](let [opts (serdes/storage-base-context);; Bound the count of the items in the stream we don't accidentally realize the entire list into memorystream-count (bounded-count 10000 stream)]- (source.p/write-files! snapshot message (map-indexed #(->file-spec task-id stream-count opts %1 %2) stream))))+ (->> (concat stream delete-prefixes)+ (map-indexed #(->file-spec task-id stream-count opts %1 %2))+ (source.p/write-files! snapshot message))))(defn source-from-settings"Creates a git source from the current remote sync settings.diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.cljindex db6f184dd65..8c182a20ab8 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj@@ -228,9 +228,15 @@"Writes multiple files to the git repository and commits the changes.Takes a snapshot map containing a :git Git instance and :version, a commit message string,- and a sequence of file maps each with :path and :content keys (paths should be relative to the repository root).+ and a sequence of file specs (paths should be relative to the repository root).++ Each file spec is a map with either:+ - :path and :content keys for writing/updating a file+ - :path and :remove? true for recursively removing all files at that path+Replaces all files in the branch organized by collection prefix - files not in the provided list but in the same- collection prefix will be deleted.+ collection prefix will be deleted. Removal entries with empty paths are no-ops. Removing non-existent paths+ is also a no-op (idempotent).Returns the version written. Throws ExceptionInfo if the write or pushoperation fails."@@ -242,15 +248,21 @@(with-open [inserter (.newObjectInserter repo)](let [index (DirCache/newInCore)builder (.builder index)- updated-prefixes (into #{} (map (fn [{:keys [path content]}]- (let [blob-id (.insert inserter Constants/OBJ_BLOB (.getBytes ^String content "UTF-8"))- entry (doto (DirCacheEntry. ^String path)- (.setFileMode FileMode/REGULAR_FILE)- (.setObjectId blob-id))]- (.add builder entry))- (path-prefix path)) files))]-- ;; Copy existing tree entries, excluding the file we're updating+ updated-prefixes (into #{}+ (comp+ (map (fn [{:keys [path content remove?]}]+ (when-not remove?+ (let [blob-id (.insert inserter Constants/OBJ_BLOB (.getBytes ^String content "UTF-8"))+ entry (doto (DirCacheEntry. ^String path)+ (.setFileMode FileMode/REGULAR_FILE)+ (.setObjectId blob-id))]+ (.add builder entry)))+ (when (not-empty path)+ (path-prefix path))))+ (remove nil?))+ files)]++ ;; Copy existing tree entries, excluding files under updated-prefixes(when parent-id(with-open [rev-walk (RevWalk. repo)tree-walk (TreeWalk. repo)]@@ -258,11 +270,12 @@(.addTree tree-walk (.getTree commit))(.setRecursive tree-walk true)(while (.next tree-walk)- (when-not (matches-prefix (.getPathString tree-walk) updated-prefixes)- (let [entry (doto (DirCacheEntry. (.getPathString tree-walk))- (.setFileMode (.getFileMode tree-walk 0))- (.setObjectId (.getObjectId tree-walk 0)))]- (.add builder entry)))))))+ (let [path (.getPathString tree-walk)]+ (when-not (matches-prefix path updated-prefixes)+ (let [entry (doto (DirCacheEntry. path)+ (.setFileMode (.getFileMode tree-walk 0))+ (.setObjectId (.getObjectId tree-walk 0)))]+ (.add builder entry))))))))(.finish builder)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/protocol.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/protocol.cljindex ad360e4e11b..aa42e1923d0 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/protocol.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/protocol.clj@@ -51,7 +51,11 @@"Writes multiple files to the source with a commit message.Takes a SourceSnapshot instance implementing this protocol, a message (the commit message to use when writing files),- and files (a sequence of file specs, which are maps with :path and :content keys).+ and files (a sequence of file specs). Each file spec is a map with either:+ - :path and :content keys for writing/updating a file+ - :path and :remove? true for recursively removing all files at that path++ Removal entries with empty paths are no-ops. Removing non-existent paths is also a no-op (idempotent).Returns the version of the written files.")diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.cljindex 4f5e3dfdc24..a875d9f6aaa 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj@@ -3,6 +3,7 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.tenants.core :as tenants][metabase.util.i18n :refer [deferred-tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -39,10 +40,10 @@;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/attributes"- "Fetch a list of possible keys for User `login_attributes`. This just looks at keys that have already been set for- existing Users and returns those. "+ "Fetch a list of possible keys for User `login_attributes`. This includes keys from tenant model+ attributes and keys that have already been set for existing Users."[]- (into #{}+ (into (tenants/login-attribute-keys)(comp(mapcat keys)(distinct)diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 133d748ace5..8316ff02fd7 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -108,6 +108,7 @@"Session""SupportAccessGrantLog""TaskHistory"+ "Tenant""TransformJobRun""TransformRun""TransformRunCancelation"diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.cljindex 803862b44ed..7129db8c15f 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/ldap.clj@@ -12,7 +12,7 @@(def ^:private EEUserInfo[:merge sso/LDAPUserInfo- [:map [:attributes [:maybe [:map-of :keyword :any]]]]])+ [:map [:attributes [:maybe [:map-of :string :any]]]]])(defn- syncable-user-attributes [m](when (ee.sso.settings/ldap-sync-user-attributes)@@ -30,7 +30,7 @@resultsettings(ee.sso.settings/ldap-group-membership-filter))]- (assoc user-info :attributes (syncable-user-attributes result)))))+ (assoc user-info :attributes (some-> (syncable-user-attributes result) (update-keys name))))))(defenterprise check-provision-ldap"Throw if creating new users from ldap is disallowed."diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.cljindex 6f9a493642f..9a143b8a4ba 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.sso.integrations.sso-utils"Functions shared by the various SSO implementations"(:require+ [clojure.string :as str][metabase-enterprise.sso.settings :as sso-settings][metabase.api.common :as api][metabase.appearance.core :as appearance]@@ -65,12 +66,18 @@{:status-code 400:redirect-url redirect-url})))))-(defn filter-non-stringable-attributes- "Removes vectors and map json attribute values that cannot be turned into strings."+(defn stringify-valid-attributes+ "Remove all invalid attributes from passed user attributes, make sure all the remaining keys and values are strings"[attrs](->> attrs(keep (fn [[key value]]- (if (or (vector? value) (map? value) (nil? value))+ (cond+ (or (vector? value) (map? value) (nil? value))(log/warnf "Dropping attribute '%s' with non-stringable value: %s" (name key) value)- [key value])))++ (str/starts-with? (name key) "@")+ (log/warnf "Dropping attribute '%s', keys beginning with `@` are reserved" (name key))++ :else+ [(u/qualified-name key) (str value)])))(into {})))diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.cljindex 2731aa9e651..3555c442ef9 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj@@ -5,6 +5,7 @@[metabase-enterprise.sso.integrations.sso-utils :as sso-utils][metabase-enterprise.sso.settings :as sso-settings][metabase.auth-identity.core :as auth-identity]+ [metabase.settings.core :as setting][metabase.sso.core :as sso][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -17,6 +18,7 @@;; Register JWT provider(derive :provider/jwt :metabase.auth-identity.provider/provider)(derive :provider/jwt :metabase.auth-identity.provider/create-user-if-not-exists)+(derive :provider/jwt :metabase-enterprise.tenants.auth-provider/create-tenant-if-not-exists);; JWTs use seconds since Epoch, not milliseconds since Epoch for the `iat` and `max_age` time.;; 3 minutes is the time used by Zendesk for their JWT SSO@@ -34,6 +36,9 @@(def ^:private ^{:arglists '([])} jwt-attribute-groups(comp keyword sso-settings/jwt-attribute-groups))+(def ^:private ^{:arglists '([])} jwt-attribute-tenant+ (comp keyword sso-settings/jwt-attribute-tenant))+(def ^:private registered-claims"Registered claims in the JWT standard which we should not interpret as login attributes."[:iss :iat :sub :aud :exp :nbf :jti])@@ -45,8 +50,10 @@[(jwt-attribute-email)(jwt-attribute-firstname)(jwt-attribute-lastname)- (jwt-attribute-groups)])]- (sso-utils/filter-non-stringable-attributes (apply dissoc jwt-data excluded-keys))))+ (jwt-attribute-groups)]+ (when (setting/get :use-tenants)+ [(jwt-attribute-tenant)]))]+ (sso-utils/stringify-valid-attributes (apply dissoc jwt-data excluded-keys))))(defn- decode-and-verify-jwt"Decode and verify a JWT token. Returns the JWT data if valid, throws on error."@@ -78,6 +85,7 @@email (get jwt-data (jwt-attribute-email))first-name (get jwt-data (jwt-attribute-firstname))last-name (get jwt-data (jwt-attribute-lastname))+ tenant-slug (get jwt-data (jwt-attribute-tenant))user-attributes (jwt-data->user-attributes jwt-data)](when-not email(throw (ex-info (str (tru "JWT token missing email claim"))@@ -85,11 +93,14 @@:error :missing-email})))(log/infof "Successfully authenticated JWT token for: %s %s" first-name last-name){:success? true- :user-data {:email email- :first_name first-name- :last_name last-name- :sso_source :jwt- :jwt_attributes user-attributes}+ :tenant-slug tenant-slug+ :user-data (->> {:email email+ :first_name first-name+ :last_name last-name+ :sso_source :jwt+ :jwt_attributes user-attributes}+ (remove #(nil? (val %)))+ (into {})):jwt-data jwt-data:provider-id email})(catch clojure.lang.ExceptionInfo ediff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.cljindex aea3203b16c..099084232c1 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj@@ -5,6 +5,7 @@[metabase-enterprise.sso.integrations.sso-utils :as sso-utils][metabase-enterprise.sso.settings :as sso-settings][metabase.auth-identity.core :as auth-identity]+ [metabase.settings.core :as setting][metabase.sso.core :as sso][metabase.system.core :as system][metabase.util :as u]@@ -18,6 +19,7 @@;; Register SAML provider(derive :provider/saml :metabase.auth-identity.provider/provider)(derive :provider/saml :metabase.auth-identity.provider/create-user-if-not-exists)+(derive :provider/saml :metabase-enterprise.tenants.auth-provider/create-tenant-if-not-exists)(defn- acs-url"Get the Assertion Consumer Service URL."@@ -115,7 +117,10 @@first-name (get attrs (sso-settings/saml-attribute-firstname))last-name (get attrs (sso-settings/saml-attribute-lastname))groups (get attrs (sso-settings/saml-attribute-group))- user-attributes (sso-utils/filter-non-stringable-attributes attrs)]+ tenant-slug (when (and (not-empty (sso-settings/saml-attribute-tenant))+ (setting/get :use-tenants))+ (get attrs (sso-settings/saml-attribute-tenant)))+ user-attributes (sso-utils/stringify-valid-attributes attrs)](when-not email(throw (ex-info (str (tru "Invalid SAML configuration: could not find user email. We tried looking for {0}, but couldn''t find the attribute. Please make sure your SAML IdP is properly configured."(sso-settings/saml-attribute-email)))@@ -128,6 +133,7 @@:last_name last-name:sso_source :saml:login_attributes user-attributes}+ :tenant-slug tenant-slug:saml-data {:group-names groups:user-attributes user-attributes}:provider-id email})diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.cljindex 03d7c839a16..04091c34141 100644--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj@@ -120,6 +120,13 @@ on your IdP, this usually looks something like `http://www.example.com/141xkex60:encryption :when-encryption-key-set:audit :getter)+(defsetting saml-attribute-tenant+ (deferred-tru "SAML attribute for the user''s tenant slug")+ :encryption :when-encryption-key-set+ :export? false+ :feature :sso-saml+ :audit :getter)+(defsetting saml-attribute-firstname(deferred-tru "SAML attribute for the user''s first name"):default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"@@ -237,6 +244,14 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e:feature :sso-jwt:audit :getter)+(defsetting jwt-attribute-tenant+ (deferred-tru "Key to retrieve the JWT user''s tenant")+ :export? false+ :encryption :when-encryption-key-set+ :default "@tenant"+ :feature :sso-jwt+ :audit :getter)+(defsetting jwt-attribute-groups(deferred-tru "Key to retrieve the JWT user''s groups"):default "groups"diff --git a/enterprise/backend/src/metabase_enterprise/stale/api.clj b/enterprise/backend/src/metabase_enterprise/stale/api.cljindex 03db66ef28e..62e56ea13e1 100644--- a/enterprise/backend/src/metabase_enterprise/stale/api.clj+++ b/enterprise/backend/src/metabase_enterprise/stale/api.clj@@ -97,7 +97,8 @@:as dashboard} (api.collection/annotate-dashboards dashboards)](assoc dashboard:location (or (some-> parent-coll collection/children-location)- "/"))))+ "/")+ :is_tenant_dashboard (some-> parent-coll collection/shared-tenant-collection?))))(defmethod present-model-items :model/Dashboard [_ dashboards](->> (t2/hydrate (t2/select [:model/Dashboarddiff --git a/enterprise/backend/src/metabase_enterprise/tenants/api.clj b/enterprise/backend/src/metabase_enterprise/tenants/api.cljnew file mode 100644index 00000000000..ce4ebf3bc3b--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/api.clj@@ -0,0 +1,119 @@+(ns metabase-enterprise.tenants.api+ (:require+ [malli.util]+ [metabase-enterprise.tenants.model :as tenant]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.api.routes.common :refer [+auth]]+ [metabase.events.core :as events]+ [metabase.request.core :as request]+ [metabase.util :as u]+ [metabase.util.i18n :refer [deferred-tru]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(def ^:private Slug (mu/with-api-error-message tenant/Slug+ (deferred-tru "invalid slug")))++(def ^:private CreateTenantArguments [:map {:closed true}+ [:name ms/NonBlankString]+ [:attributes {:optional true} [:maybe tenant/Attributes]]+ [:slug Slug]])++(def ^:private Tenant [:map {:closed true}+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:slug Slug]+ [:is_active ms/BooleanValue]+ [:member_count ms/Int]+ [:attributes [:maybe [:map-of :string :string]]]+ [:tenant_collection_id ms/PositiveInt]])++(defn- present-tenants [tenants]+ (->> (t2/hydrate tenants :member_count)+ (map #(select-keys % [:id :name :slug :is_active :member_count :attributes :tenant_collection_id]))))++(defn- present-tenant [tenant]+ (first (present-tenants [tenant])))++(defn create-tenant!+ "Creates a new tenant, validating it, verifying that it does not already exist and publishing audit events as+ necessary."+ [tenant]+ (when-not (mr/validate CreateTenantArguments tenant)+ (throw (ex-info "Invalid Tenant"+ {:status-code 400+ :errors (mr/explain CreateTenantArguments tenant)})))+ (api/check-403 api/*is-superuser?*)+ (api/check-400 (not (tenant/tenant-exists? tenant))+ "This tenant name or slug is already taken.")+ (u/prog1 (present-tenant+ (t2/insert-returning-instance! :model/Tenant tenant))+ (events/publish-event! :event/tenant-create {:object <>})))++(api.macros/defendpoint :post "/" :- Tenant+ "Create a new Tenant"+ [_route-params+ _query-params+ tenant :- CreateTenantArguments]+ (create-tenant! tenant))++(api.macros/defendpoint :get "/" :- [:map {:closed true} [:data [:sequential Tenant]]]+ "Get all tenants"+ [_+ {:keys [status]} :- [:map+ [:status {:default "all"} [:enum "all" "deactivated" "active"]]]+ _]+ (api/check-403 api/*is-superuser?*)+ {:data (present-tenants+ (t2/select :model/Tenant (cond-> {:order-by [[:id :asc]]}+ (request/paged?) (assoc :limit (request/limit) :offset (request/offset))+ true (assoc :where (case status+ "all" [:inline [:= 1 1]]+ "active" [:= :is_active true]+ "deactivated" [:= :is_active false])))))})++(def ^:private UpdateTenantArguments+ [:map {:closed true}+ [:name {:optional true} [:maybe ms/NonBlankString]]+ [:attributes {:optional true} [:maybe tenant/Attributes]]+ [:is_active {:optional true} [:maybe ms/BooleanValue]]])++(mu/defn- update-tenant!+ [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))++(api.macros/defendpoint :put "/:id" :- Tenant+ "Update a tenant, can set name, attributes, or whether this tenant is active."+ [{id :id} :- [:map {:closed true} [:id ms/PositiveInt]]+ _query-params+ tenant :- UpdateTenantArguments]+ (api/check-403 api/*is-superuser?*)+ (when (:name tenant)+ (api/check-400 (not (t2/exists? :model/Tenant :name (:name tenant) :id [:not= id]))+ "This name is already taken."))+ (present-tenant (update-tenant! id tenant)))++(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?*)+ (present-tenant (t2/select-one :model/Tenant :id id)))++(def ^{:arglists '([request respond raise])} routes+ "`/api/ee/tenant` routes"+ (api.macros/ns-handler *ns* +auth))diff --git a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.cljnew file mode 100644index 00000000000..1cb7b654a71--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj@@ -0,0 +1,74 @@+(ns metabase-enterprise.tenants.auth-provider+ (:require+ [metabase-enterprise.tenants.api :as api.tenants]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.request.core :as request]+ [metabase.settings.core :as setting]+ [metabase.util :as u]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(defn- validate-user-and-tenant-slug!+ [{:keys [tenant_id] :as user} existing-tenant user-will-have-tenant?]+ (let [user-exists? (boolean user)+ user-has-tenant? (boolean tenant_id)]+ (cond+ (and user-exists?+ user-will-have-tenant?+ (not user-has-tenant?))+ (throw (ex-info "Cannot add tenant claim to internal user"+ {:user/tenant-id tenant_id+ :tenant-slug/tenant-id (:id existing-tenant)+ :tenant-slug/slug (:slug existing-tenant)+ :status-code 403}))++ (and user-exists?+ (not user-will-have-tenant?)+ user-has-tenant?)+ (throw (ex-info "Tenant claim required for external user"+ {:user/tenant-id tenant_id+ :user/tenant-slug (t2/select-one-fn :slug :model/Tenant :id tenant_id)+ :status-code 403}))++ (and user-exists?+ (not= tenant_id (u/id existing-tenant)))+ (throw (ex-info "Tenant ID mismatch with existing user"+ {:user/tenant-id tenant_id+ :user/tenant-slug (t2/select-one-fn :slug :model/Tenant :id tenant_id)+ :tenant-slug/tenant-id (:id existing-tenant)+ :tenant-slug/slug (:slug existing-tenant)+ :status-code 403}))++ (and existing-tenant+ (not (:is_active existing-tenant)))+ (throw (ex-info "Tenant is not active"+ {:tenant-slug/tenant-id (:id existing-tenant)+ :tenant-slug/slug (:slug existing-tenant)+ :tenant-slug/is-active (:is_active existing-tenant)+ :status-code 403})))))++(defn- validate-with-tenants-disabled! [{:keys [user tenant-slug]}]+ (when (or (:tenant_id user) (not-empty tenant-slug))+ (throw (ex-info "Tenants and tenant users are disabled." {:status-code 403}))))++(defn- create-tenant-if-not-exists!+ [{:as request :keys [user tenant-slug]} existing-tenant]+ (if-not (setting/get :use-tenants)+ (do (validate-with-tenants-disabled! request)+ request)+ (do (validate-user-and-tenant-slug! user existing-tenant (boolean tenant-slug))+ (cond-> request+ (boolean tenant-slug)+ (assoc-in [:user-data :tenant_id]+ (u/the-id (or existing-tenant+ (request/as-admin+ (api.tenants/create-tenant! {:slug tenant-slug :name tenant-slug})))))))))++(methodical/defmethod auth-identity/login! ::create-tenant-if-not-exists+ [provider {:keys [tenant-slug]+ :as request}]+ (let [existing-tenant (t2/select-one :model/Tenant :slug tenant-slug)]+ (next-method provider (create-tenant-if-not-exists! request existing-tenant))))++(methodical/prefer-method! #'auth-identity/login! :metabase.auth-identity.provider/provider ::create-tenant-if-not-exists)+(methodical/prefer-method! #'auth-identity/login! ::create-tenant-if-not-exists :metabase.auth-identity.provider/create-user-if-not-exists)diff --git a/enterprise/backend/src/metabase_enterprise/tenants/core.clj b/enterprise/backend/src/metabase_enterprise/tenants/core.cljnew file mode 100644index 00000000000..f955d918a1d--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/core.clj@@ -0,0 +1,63 @@+(ns metabase-enterprise.tenants.core+ (:require+ [metabase-enterprise.tenants.api :as tenants.api]+ [metabase-enterprise.tenants.auth-provider]+ [metabase.api.common :as api]+ [metabase.collections.models.collection :as collection]+ [metabase.permissions.core :as perms]+ [metabase.premium-features.core :refer [defenterprise]]+ [toucan2.core :as t2]))++(defenterprise login-attributes+ "EE version of `login-attributes` - a map of tenant attributes that should be merged into the user's login+ attributes."+ :feature :tenants+ [{:keys [tenant_id] :as _user}]+ (or (when (and (perms/use-tenants) tenant_id)+ (when-let [{:keys [slug attributes]} (t2/select-one :model/Tenant tenant_id)]+ (merge attributes {"@tenant.slug" slug})))+ {}))++(defenterprise login-attribute-keys+ "The set of tenant attribute keys that attempt to be merged into tenant users' attributes"+ :feature :tenants+ []+ (if (perms/use-tenants)+ (into #{"@tenant.slug"}+ (comp+ (mapcat keys)+ (distinct))+ (t2/select-fn-reducible :attributes [:model/Tenant :attributes]+ {:where [:and+ [:not= :attributes nil]+ [:not= :attributes "{}"]]}))+ #{}))++(defenterprise tenant-is-active?+ "Whether the tenant with this ID is active or not."+ :feature :tenants+ [tenant-id]+ (or (nil? tenant-id)+ (t2/exists? :model/Tenant :id tenant-id :is_active true)))++(defenterprise create-tenant!+ "Creates a tenant"+ :feature :tenants+ [tenant]+ (tenants.api/create-tenant! tenant))++(defenterprise user->tenant+ "EE version of `user->tenant`"+ :feature :tenants+ [user]+ (when-let [tenant-id (:tenant_id user)]+ (t2/select-one :model/Tenant :id tenant-id)))++(defenterprise validate-new-tenant-collection!+ "Throws API exceptions if the passed collection is an invalid tenant collection."+ :feature :tenants+ [collection]+ (when (collection/shared-tenant-collection? collection)+ ;; make sure tenants is enabled+ (api/check-400 (perms/use-tenants)))+ collection)diff --git a/enterprise/backend/src/metabase_enterprise/tenants/model.clj b/enterprise/backend/src/metabase_enterprise/tenants/model.cljnew file mode 100644index 00000000000..383c78a4094--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/model.clj@@ -0,0 +1,87 @@+(ns metabase-enterprise.tenants.model+ (:require+ [metabase.audit-app.core :as audit-app]+ [metabase.models.interface :as mi]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util :as u]+ [metabase.util.i18n :refer [deferred-tru]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.schema :as ms]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/Tenant [_model] :tenant)++(defmethod audit-app/model-details :model/Tenant+ [entity _event-type]+ (select-keys entity [:name :slug :is_active]))++(t2/deftransforms :model/Tenant+ {:attributes mi/transform-json-no-keywordization})++(def Slug+ "The malli schema for a tenant's slug"+ [:re #"^[-_a-z0-9]{1,255}$"])++(t2/define-before-insert :model/Tenant+ [tenant]+ (let [tenant-collection-id (t2/insert-returning-pk! :model/Collection {:type "tenant-specific-root-collection"+ :name (format "Tenant Collection: %s" (:name tenant))+ :namespace "tenant-specific"})]+ (u/prog1 (assoc tenant :tenant_collection_id tenant-collection-id)+ ;; The API layer is responsible for doing validation with nice error messages, here we just throw as a final layer+ ;; of defense.+ (mu/validate-throw Slug (:slug tenant)))))++(defn tenant-exists?+ "Given a tenant name, returns truthy if the name (or its slugified version) is already reserved."+ [{n :name slug :slug}]+ (t2/exists? :model/Tenant {:where [:or+ [:= :slug slug]+ [:= :name n]]}))++(doto :model/Tenant+ (derive :metabase/model)+ (derive :hook/timestamped?))++(methodical/defmethod t2/batched-hydrate [:model/Tenant :member_count]+ [_model k tenants]+ (mi/instances-with-hydrated-data+ tenants k+ (fn []+ (->> (t2/query {:select [[:tenant_id] [[:count :*] :count]]+ :from [(t2/table-name :model/User)]+ :where [:and+ [:in :tenant_id (map u/the-id tenants)]+ [:= :type "personal"]+ :is_active]+ :group-by [:tenant_id]})+ (map (juxt :tenant_id :count))+ (into {})))+ :id+ {:default 0}))++(def Attributes+ "Attributes attached to a tenant that will be passed down to users in the tenant."+ [:map-of+ [:and+ (mu/with-api-error-message+ ms/KeywordOrString+ (deferred-tru "attribute keys must be a keyword or string"))+ (mu/with-api-error-message+ [:fn (fn [k] (re-matches #"^(?!@).*" (name k)))]+ (deferred-tru "attribute keys must not start with `@`"))]+ :any])++(defenterprise user->tenant-collection-and-descendant-ids+ "EE version of user->tenant-collection-and-descendant-ids. Returns a vector of the tenant collection ID and all+ descendant collection IDs for the user's tenant, or an empty vector if the user has no tenant."+ :feature :tenants+ [user-or-id]+ (into []+ (when-let [tenant-id (t2/select-one-fn :tenant_id :model/User :id (u/the-id user-or-id))]+ (when-let [tenant-collection-id (t2/select-one-fn :tenant_collection_id :model/Tenant :id tenant-id)]+ (let [descendant-ids (t2/select-pks-set :model/Collection+ :location+ [:like (str "/" tenant-collection-id "/%")])]+ (conj descendant-ids tenant-collection-id))))))diff --git a/enterprise/backend/src/metabase_enterprise/tenants/permissions.clj b/enterprise/backend/src/metabase_enterprise/tenants/permissions.cljnew file mode 100644index 00000000000..9a44f519304--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/permissions.clj@@ -0,0 +1,57 @@+(ns metabase-enterprise.tenants.permissions+ "Enterprise implementation of tenant-specific collection permissions management."+ (:require+ [metabase.collections.models.collection :as collection]+ [metabase.permissions.core :as perms]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(mu/defn- revoke-perms-when-moving-into-tenant-specific!+ "When moving a `collection` that is *not* in the tenant-specific namespace into the tenant-specific namespace+ (or one of its descendants), any previous Group Permissions entries for it need to be deleted, as tenant-specific+ collections do not use the Permissions table.++ This needs to be done recursively for all descendants as well."+ [collection :- (ms/InstanceOf :model/Collection)]+ (t2/query-one {:delete-from :permissions+ :where [:in :object (for [coll (cons collection (collection/descendants collection))+ path-fn [perms/collection-read-path+ perms/collection-readwrite-path]]+ (path-fn coll))]}))++(mu/defn- grant-perms-when-moving-out-of-tenant-specific!+ "When moving a descendant of a tenant-specific Collection into a regular Collection namespace, we need to grant it+ Permissions by copying the new parent's permissions, since now that it has moved across the boundary into the+ regular namespace it *requires* Permissions to be seen or 'curated'. If we did not grant Permissions when moving,+ it would immediately become invisible to all save admins, because no Group would have perms for it. This is+ obviously a bad experience -- we do not want a User to move a Collection that they have read/write perms for+ (by definition) to somewhere else and lose all access for it."+ [collection :- (ms/InstanceOf :model/Collection) new-location :- @#'collection/LocationPath]+ ;; TODO(johnswanson, 2025-11-25) fix the private bits+ (#'collection/copy-collection-permissions! (#'collection/parent {:location new-location})+ (cons collection (collection/descendants collection))))++(defenterprise update-perms-for-tenant-specific-namespace-change!+ "If a Collection is moving into or out of the tenant-specific namespace, adjust the Permissions for it accordingly.++ EE version: When moving INTO tenant-specific namespace, deletes all permissions entries. When moving OUT, copies+ parent permissions to the collection and all descendants."+ :feature :tenants+ [collection-before-updates collection-updates]+ ;; First, figure out if the collection is in the tenant-specific namespace now, and whether it will be after the update+ (let [is-tenant-specific? (collection/is-dedicated-tenant-collection-or-descendant? collection-before-updates)+ will-be-tenant-specific? (collection/is-dedicated-tenant-collection-or-descendant?+ (merge collection-before-updates collection-updates))]+ ;; See if whether it is in the tenant-specific namespace or not is set to change. If it's not going to+ ;; change, we don't need to do anything+ (when (not= is-tenant-specific? will-be-tenant-specific?)+ ;; If it *is* in the tenant-specific namespace, and is about to be moved into the 'regular' namespace, we need+ ;; to copy the new parent's perms for it and for all of its descendants+ (if is-tenant-specific?+ (grant-perms-when-moving-out-of-tenant-specific! collection-before-updates (:location collection-updates))+ ;; Otherwise, if it is *not* in the tenant-specific namespace, but is set to become one, we need to delete+ ;; any perms entries for it and for all of its descendants, as tenant-specific collections don't use the+ ;; Permissions table+ (revoke-perms-when-moving-into-tenant-specific! collection-before-updates)))))diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.cljindex 75303685a86..f8a5fcf5cc8 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj@@ -28,7 +28,7 @@(is (partial= {:first_name "Cam":last_name "Era":email "[email protected]"- :login_attributes {"a" 1}}+ :login_attributes {"a" "1"}}(t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]")))(is (= 1@@ -51,7 +51,7 @@(is (partial= {:first_name "Cam":last_name "Saul":email "[email protected]"- :login_attributes {"a" 1 "b" 2}}+ :login_attributes {"a" "1" "b" "2"}}(t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]")))(testing "Password should be hashed, but it should be a NEW HASH"diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/group_manager_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/group_manager_test.cljindex 728fca3ad53..53e65b396e3 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/group_manager_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/group_manager_test.clj@@ -79,7 +79,7 @@(delete-group user 204 true)(testing "admins could view all groups"- (is (= (t2/select-fn-set :name :model/PermissionsGroup)+ (is (= (t2/select-fn-set :name :model/PermissionsGroup :is_tenant_group false)(set (map :name (get-groups :crowberto 200)))))))))))))(defn- get-membership [user status]@@ -126,8 +126,8 @@(map :group_id)set))-(deftest memebership-apis-permissions-test- (testing "/api/permissions/memebership"+(deftest membership-apis-permissions-test+ (testing "/api/permissions/membership"(mt/with-user-in-groups[group {:name "New Group"}user [group]]@@ -175,8 +175,8 @@(delete-membership! user-2 204 group-2)(clear-memberships! user-2 204 group-2))))))))-(deftest memebership-apis-edge-cases-test- (testing "/api/permissions/memebership"+(deftest membership-apis-edge-cases-test+ (testing "/api/permissions/membership"(mt/with-user-in-groups[group {:name "New Group"}user [group]]@@ -211,7 +211,7 @@:is_group_manager true})))))(testing "Admin can could view all groups"- (is (= (t2/select-fn-set :id :model/PermissionsGroup)+ (is (= (t2/select-fn-set :id :model/PermissionsGroup :is_tenant_group false)(membership->groups-ids (get-membership :crowberto 200))))))))))(deftest get-users-api-testdiff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.cljindex cec332f9732..95e8deb824f 100644--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj@@ -56,6 +56,7 @@:whitelabel:collection-cleanup:database-routing+ :tenants:cloud-custom-smtp}(is (= {:advanced_permissions true:attached_dwh true@@ -104,6 +105,7 @@:whitelabel true:collection_cleanup true:database_routing true+ :tenants true:cloud_custom_smtp true:etl_connections false:etl_connections_pg falsediff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.cljindex bf023cb9631..1c3d672af10 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj@@ -544,6 +544,187 @@:remote-sync-url "https://github.com/test/repo.git":remote-sync-token "test-token"}))))))))+;;; ------------------------------------------- Settings Collections Tests -------------------------------------------++(deftest settings-collections-enables-remote-sync-on-single-collection-test+ (testing "PUT /api/ee/remote-sync/settings with collections enables remote sync on a single collection"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {coll-id true}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll-id))))))))))++(deftest settings-collections-disables-remote-sync-on-single-collection-test+ (testing "PUT /api/ee/remote-sync/settings with collections disables remote sync on a single collection"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {coll-id false}})]+ (is (= {:success true} response))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id))))))))))++(deftest settings-collections-enables-multiple-collections-test+ (testing "PUT /api/ee/remote-sync/settings with collections enables remote sync on multiple collections"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced false}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {coll1-id true coll2-id true}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll2-id))))))))))++(deftest settings-collections-mixed-enable-disable-test+ (testing "PUT /api/ee/remote-sync/settings with collections handles mixed enable/disable operations"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {coll1-id true coll2-id false}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll2-id))))))))))++(deftest settings-collections-cascades-to-descendants-test+ (testing "PUT /api/ee/remote-sync/settings with collections cascades to descendants"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced false}+ :model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced false}+ :model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced false}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {parent-id true}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id parent-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id child-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id grandchild-id))))))))))++(deftest settings-collections-cascades-disable-to-descendants-test+ (testing "PUT /api/ee/remote-sync/settings with collections cascades disable to descendants"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced true}+ :model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced true}+ :model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced true}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {parent-id false}})]+ (is (= {:success true} response))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id parent-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id child-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id grandchild-id))))))))))++(deftest settings-collections-errors-on-non-remote-synced-dependencies-test+ (testing "PUT /api/ee/remote-sync/settings with collections errors when enabling a collection with non-remote-synced dependencies"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {remote-synced-coll-id :id} {:name "Remote Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-coll-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id regular-coll-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id remote-synced-coll-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:collections {remote-synced-coll-id true}})]+ (is (= "Uses content that is not remote synced." (:error response)))))))))++(deftest settings-collections-errors-on-remote-synced-dependents-test+ (testing "PUT /api/ee/remote-sync/settings with collections errors when disabling a collection that has remote-synced dependents"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id coll1-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id coll2-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:collections {coll1-id false}})]+ (is (= "Used by remote synced content." (:error response)))))))))++(deftest settings-collections-empty-is-no-op-test+ (testing "PUT /api/ee/remote-sync/settings with empty collections is a no-op"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {}})]+ (is (= {:success true} response))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))))))))++(deftest settings-collections-requires-superuser-test+ (testing "PUT /api/ee/remote-sync/settings with collections requires superuser permissions"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 "ee/remote-sync/settings"+ {:collections {coll-id true}}))))))++(deftest settings-collections-rejects-changes-in-read-only-mode-test+ (testing "PUT /api/ee/remote-sync/settings rejects collection changes when remote-sync-type is read-only"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}+ :model/Collection {synced-coll-id :id} {:name "Synced Collection" :location "/" :is_remote_synced true}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (testing "rejects enabling collections when remote-sync-type is explicitly read-only"+ (is (= "Cannot change synced collections when remote-sync-type is read-only."+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:remote-sync-type :read-only+ :collections {coll-id true}}))))+ (testing "rejects disabling collections when remote-sync-type is explicitly read-only"+ (is (= "Cannot change synced collections when remote-sync-type is read-only."+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:remote-sync-type :read-only+ :collections {synced-coll-id false}}))))+ (testing "rejects collection changes when remote-sync-type is already read-only (default)"+ (mt/with-temporary-setting-values [remote-sync-type :read-only]+ (is (= "Cannot change synced collections when remote-sync-type is read-only."+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:collections {coll-id true}})))))))))++(deftest settings-collections-allows-changes-in-read-write-mode-test+ (testing "PUT /api/ee/remote-sync/settings allows collection changes when remote-sync-type is read-write"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (with-redefs [settings/check-and-update-remote-settings! (constantly nil)+ impl/finish-remote-config! (constantly nil)]+ (testing "allows enabling collections when remote-sync-type is explicitly read-write"+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-type :read-write+ :collections {coll-id true}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll-id))))))+ (testing "allows disabling collections when remote-sync-type is explicitly read-write"+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-type :read-write+ :collections {coll-id false}})]+ (is (= {:success true} response))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id))))))+ (testing "allows collection changes when remote-sync-type is already read-write"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (let [response (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:collections {coll-id true}})]+ (is (= {:success true} response))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))))))))))+(deftest create-branch(testing "POST /api/ee/remote-sync/create-branch creates a new branch")(let [mock-source (test-helpers/create-mock-source)]diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.cljnew file mode 100644index 00000000000..61dbd941b47--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj@@ -0,0 +1,202 @@+(ns metabase-enterprise.remote-sync.core-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.remote-sync.core :as core]+ [metabase.events.core :as events]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db))++;; bulk-set-remote-sync tests++(deftest bulk-set-remote-sync-enables-single-collection-test+ (testing "bulk-set-remote-sync enables remote sync on a single collection"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (core/bulk-set-remote-sync {coll-id true})+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))))))++(deftest bulk-set-remote-sync-disables-single-collection-test+ (testing "bulk-set-remote-sync disables remote sync on a single collection"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]+ (core/bulk-set-remote-sync {coll-id false})+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))))))++(deftest bulk-set-remote-sync-enables-multiple-collections-test+ (testing "bulk-set-remote-sync enables remote sync on multiple collections"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced false}]+ (core/bulk-set-remote-sync {coll1-id true coll2-id true})+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll2-id)))))))++(deftest bulk-set-remote-sync-mixed-operations-test+ (testing "bulk-set-remote-sync handles mixed enable/disable operations"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}]+ (core/bulk-set-remote-sync {coll1-id true coll2-id false})+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll2-id)))))))++(deftest bulk-set-remote-sync-cascades-to-descendants-test+ (testing "bulk-set-remote-sync cascades remote sync to descendant collections when enabling"+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced false}+ :model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced false}+ :model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced false}]+ (core/bulk-set-remote-sync {parent-id true})+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id parent-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id child-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id grandchild-id)))))))++(deftest bulk-set-remote-sync-cascades-disable-to-descendants-test+ (testing "bulk-set-remote-sync cascades disable to descendant collections"+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced true}+ :model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id) :is_remote_synced true}+ :model/Collection {grandchild-id :id} {:name "Grandchild" :location (format "/%d/%d/" parent-id child-id) :is_remote_synced true}]+ (core/bulk-set-remote-sync {parent-id false})+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id parent-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id child-id))))+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id grandchild-id)))))))++(deftest bulk-set-remote-sync-throws-on-non-remote-synced-dependencies-test+ (testing "bulk-set-remote-sync throws when enabling a collection with non-remote-synced dependencies"+ (mt/with-temp [:model/Collection {remote-synced-coll-id :id} {:name "Remote Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-coll-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id regular-coll-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id remote-synced-coll-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Uses content that is not remote synced"+ (core/bulk-set-remote-sync {remote-synced-coll-id true}))))))++(deftest bulk-set-remote-sync-throws-on-remote-synced-dependents-test+ (testing "bulk-set-remote-sync throws when disabling a collection that has remote-synced dependents"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id coll1-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id coll2-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Used by remote synced content"+ (core/bulk-set-remote-sync {coll1-id false}))))))++(deftest bulk-set-remote-sync-empty-map-no-op-test+ (testing "bulk-set-remote-sync with empty map is a no-op"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (core/bulk-set-remote-sync {})+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll-id)))))))++(deftest bulk-set-remote-sync-transaction-rollback-on-error-test+ (testing "bulk-set-remote-sync rolls back all changes on error"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id coll1-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id coll2-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ ;; Try to disable one - should fail because coll1 has dependents in coll2+ (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {coll1-id false})))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id))))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id coll2-id)))))))++(deftest bulk-set-remote-sync-allows-disabling-when-no-dependents-test+ (testing "bulk-set-remote-sync allows disabling when there are no external remote-synced dependents"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id coll1-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id coll2-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ ;; Should succeed because dependents are not in a remote-synced collection+ (core/bulk-set-remote-sync {coll1-id false})+ (is (false? (:is_remote_synced (t2/select-one :model/Collection :id coll1-id)))))))++;;; ------------------------------------------- Event Publishing Tests -------------------------------------------++(deftest bulk-set-remote-sync-publishes-event-when-enabling-test+ (testing "bulk-set-remote-sync publishes :event/collection-update when enabling remote sync"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (let [published-events (atom [])]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! published-events conj [topic event])+ event)]+ (core/bulk-set-remote-sync {coll-id true})+ (is (= 1 (count @published-events)))+ (is (= :event/collection-update (ffirst @published-events)))+ (is (= coll-id (get-in (first @published-events) [1 :object :id]))))))))++(deftest bulk-set-remote-sync-publishes-event-when-disabling-test+ (testing "bulk-set-remote-sync publishes :event/collection-update when disabling remote sync"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]+ (let [published-events (atom [])]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! published-events conj [topic event])+ event)]+ (core/bulk-set-remote-sync {coll-id false})+ (is (= 1 (count @published-events)))+ (is (= :event/collection-update (ffirst @published-events)))+ (is (= coll-id (get-in (first @published-events) [1 :object :id]))))))))++(deftest bulk-set-remote-sync-no-event-when-already-enabled-test+ (testing "bulk-set-remote-sync does not publish event when collection is already remote-synced"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]+ (let [published-events (atom [])]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! published-events conj [topic event])+ event)]+ (core/bulk-set-remote-sync {coll-id true})+ (is (= 0 (count @published-events))))))))++(deftest bulk-set-remote-sync-no-event-when-already-disabled-test+ (testing "bulk-set-remote-sync does not publish event when collection is already not remote-synced"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced false}]+ (let [published-events (atom [])]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! published-events conj [topic event])+ event)]+ (core/bulk-set-remote-sync {coll-id false})+ (is (= 0 (count @published-events))))))))++(deftest bulk-set-remote-sync-events-only-for-changed-collections-test+ (testing "bulk-set-remote-sync only publishes events for collections whose status actually changed"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced false}+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}+ :model/Collection {coll3-id :id} {:name "Collection 3" :location "/" :is_remote_synced true}+ :model/Collection {coll4-id :id} {:name "Collection 4" :location "/" :is_remote_synced false}]+ (let [published-events (atom [])]+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic event]+ (swap! published-events conj [topic event])+ event)]+ ;; coll1: false -> true (should publish)+ ;; coll2: true -> true (should NOT publish)+ ;; coll3: true -> false (should publish)+ ;; coll4: false -> false (should NOT publish)+ (core/bulk-set-remote-sync {coll1-id true coll2-id true coll3-id false coll4-id false})+ (is (= 2 (count @published-events)))+ (let [event-collection-ids (set (map #(get-in % [1 :object :id]) @published-events))]+ (is (contains? event-collection-ids coll1-id))+ (is (contains? event-collection-ids coll3-id))+ (is (not (contains? event-collection-ids coll2-id)))+ (is (not (contains? event-collection-ids coll4-id)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.cljindex c3840ed9b60..12e541573d7 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj@@ -345,6 +345,120 @@(is (= "synced" (:status (t2/select-one :model/RemoteSyncObject :model_type "Card" :model_id card-id))))(is (= "synced" (:status (t2/select-one :model/RemoteSyncObject :model_type "Dashboard" :model_id dash-id))))))))))))+(deftest export!-deletes-files-for-removed-top-level-collections-test+ (testing "export! deletes files from git source for collections with location '/' that have been removed"+ (mt/with-model-cleanup [:model/RemoteSyncObject]+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (let [task-id (t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type "export" :initiated_by (mt/user->id :rasta)})]+ (mt/with-temp [:model/Collection {active-coll-id :id} {:name "Active Collection"+ :is_remote_synced true+ :entity_id "active-collection-xxx"+ :location "/"}+ :model/Card _ {:name "Active Card"+ :collection_id active-coll-id+ :entity_id "active-card-xxxxxxxxx"}+ :model/Collection {removed-coll-id :id} {:name "Removed Collection"+ :is_remote_synced false+ :entity_id "removed-collection-xx"+ :location "/"}]+ (t2/insert! :model/RemoteSyncObject+ [{:model_type "Collection" :model_id active-coll-id :status "synced" :status_changed_at (t/offset-date-time)}+ {:model_type "Collection" :model_id removed-coll-id :status "removed" :status_changed_at (t/offset-date-time)}])+ (let [initial-files {"main" {"collections/active-collection-xxx_active_collection/active-collection-xxx.yaml"+ (test-helpers/generate-collection-yaml "active-collection-xxx" "Active Collection")+ "collections/active-collection-xxx_active_collection/cards/active-card.yaml"+ (test-helpers/generate-card-yaml "active-card-xxxxxxxxx" "Active Card" "active-collection-xxx")+ "collections/removed-collection-xx_removed_collection/removed-collection-xx.yaml"+ (test-helpers/generate-collection-yaml "removed-collection-xx" "Removed Collection")+ "collections/removed-collection-xx_removed_collection/cards/removed-card.yaml"+ (test-helpers/generate-card-yaml "removed-card-xxxxxxxx" "Removed Card" "removed-collection-xx")}}+ mock-source (test-helpers/create-mock-source :initial-files initial-files)+ result (impl/export! (source.p/snapshot mock-source) task-id "Test commit")]+ (is (= :success (:status result)))+ (let [files-after-export (get @(:files-atom mock-source) "main")]+ (is (some #(str/includes? % "active-collection-xxx") (keys files-after-export))+ "Active collection files should exist after export")+ (is (not (some #(str/includes? % "removed-collection-xx") (keys files-after-export)))+ "Removed collection files should be deleted after export")))))))))++(deftest export!-only-deletes-top-level-removed-collections-test+ (testing "export! only deletes files for removed collections at location '/', not nested ones"+ (mt/with-model-cleanup [:model/RemoteSyncObject]+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (let [task-id (t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type "export" :initiated_by (mt/user->id :rasta)})]+ (mt/with-temp [:model/Collection {parent-coll-id :id}+ {:name "Parent Collection"+ :is_remote_synced true+ :entity_id "parent-collection-xx"+ :location "/"}+ :model/Collection {nested-coll-id :id}+ {:name "Nested Removed Collection"+ :is_remote_synced true+ :entity_id "nested-removed-collxx"+ :location (format "/%d/" parent-coll-id)}]+ (t2/insert! :model/RemoteSyncObject+ [{:model_type "Collection" :model_id parent-coll-id :status "synced" :status_changed_at (t/offset-date-time)}+ {:model_type "Collection" :model_id nested-coll-id :status "removed" :status_changed_at (t/offset-date-time)}])+ (let [initial-files {"main" {"collections/parent-collection-xx_parent_collection/parent-collection-xx.yaml"+ (test-helpers/generate-collection-yaml "parent-collection-xx" "Parent Collection")+ "collections/parent-collection-xx_parent_collection/nested-removed-collxx_nested_removed_collection/nested-removed-collxx.yaml"+ (test-helpers/generate-collection-yaml "nested-removed-collxx" "Nested Removed Collection"+ :parent-id "parent-collection-xx")}}+ mock-source (test-helpers/create-mock-source :initial-files initial-files)+ result (impl/export! (source.p/snapshot mock-source) task-id "Test commit")]+ (is (= :success (:status result)))+ (let [files-after-export (get @(:files-atom mock-source) "main")]+ (is (some #(str/includes? % "parent-collection-xx") (keys files-after-export))+ "Parent collection files should exist after export")+ (is (some #(str/includes? % "nested-removed-collxx") (keys files-after-export))+ "Nested removed collection files should NOT be deleted (only top-level removals are processed)")))))))))++(deftest export!-handles-multiple-removed-top-level-collections-test+ (testing "export! correctly handles multiple removed top-level collections"+ (mt/with-model-cleanup [:model/RemoteSyncObject]+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (let [task-id (t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type "export" :initiated_by (mt/user->id :rasta)})]+ ;; Note: entity_id must be exactly 21 characters+ (mt/with-temp [:model/Collection {active-coll-id :id}+ {:name "Active Collection"+ :is_remote_synced true+ :entity_id "active-coll-xxxxxxxxx" ;; 21 chars+ :location "/"}+ :model/Collection {removed-coll-1-id :id}+ {:name "Removed Collection 1"+ :is_remote_synced false+ :entity_id "removed-coll-1xxxxxxx" ;; 21 chars+ :location "/"}+ :model/Collection {removed-coll-2-id :id}+ {:name "Removed Collection 2"+ :is_remote_synced false+ :entity_id "removed-coll-2xxxxxxx" ;; 21 chars+ :location "/"}]+ (t2/insert! :model/RemoteSyncObject+ [{:model_type "Collection" :model_id active-coll-id :status "synced" :status_changed_at (t/offset-date-time)}+ {:model_type "Collection" :model_id removed-coll-1-id :status "removed" :status_changed_at (t/offset-date-time)}+ {:model_type "Collection" :model_id removed-coll-2-id :status "removed" :status_changed_at (t/offset-date-time)}])+ (let [initial-files {"main" {"collections/removed-coll-1xxxxxxx_removed_collection_1/removed-coll-1xxxxxxx.yaml"+ (test-helpers/generate-collection-yaml "removed-coll-1xxxxxxx" "Removed Collection 1")+ "collections/removed-coll-1xxxxxxx_removed_collection_1/cards/card-1.yaml"+ (test-helpers/generate-card-yaml "card-1-entity-idxxxxx" "Card 1" "removed-coll-1xxxxxxx")+ "collections/removed-coll-2xxxxxxx_removed_collection_2/removed-coll-2xxxxxxx.yaml"+ (test-helpers/generate-collection-yaml "removed-coll-2xxxxxxx" "Removed Collection 2")+ "collections/removed-coll-2xxxxxxx_removed_collection_2/dashboards/dash-1.yaml"+ (test-helpers/generate-dashboard-yaml "dash-1-entity-idxxxxx" "Dashboard 1" "removed-coll-2xxxxxxx")}}+ mock-source (test-helpers/create-mock-source :initial-files initial-files)+ result (impl/export! (source.p/snapshot mock-source) task-id "Test commit")]+ (is (= :success (:status result)))+ (let [files-after-export (get @(:files-atom mock-source) "main")]+ ;; Active collection should be written by export+ (is (some #(str/includes? % "active-coll-xxxxxxxxx") (keys files-after-export))+ "Active collection files should exist after export")+ ;; Both removed collections should be deleted+ (is (not (some #(str/includes? % "removed-coll-1xxxxxxx") (keys files-after-export)))+ "First removed collection files should be deleted")+ (is (not (some #(str/includes? % "removed-coll-2xxxxxxx") (keys files-after-export)))+ "Second removed collection files should be deleted")))))))))+(deftest finish-remote-config!-sets-default-branch-when-blank-test(testing "finish-remote-config! sets default branch when branch setting is blank"(mt/with-model-cleanup [:model/RemoteSyncTask]diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.cljindex b93cc0cba3d..78a58f54f71 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][metabase-enterprise.remote-sync.settings :as settings]+ [metabase.collections.models.collection :as collections][metabase.models.interface :as mi][metabase.test :as mt][toucan2.core :as t2]))@@ -20,20 +21,17 @@(mt/with-temporary-setting-values [settings/remote-sync-type :read-only](mt/with-temp [:model/Collection {library-coll-id :id} {:name "Library Collection":is_remote_synced true}]-(testing "Cards in remote-synced collections have can_write=false"(mt/with-temp [:model/Card {card-id :id} {:name "Library Card":collection_id library-coll-id:dataset_query (mt/native-query {:query "SELECT 1"})}](is (false? (mi/can-write? (t2/select-one :model/Card :id card-id)))"Card in remote-synced collection should not be writable when remote-sync-type is read-only")))-(testing "Dashboards in remote-synced collections have can_write=false"(mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Library Dashboard":collection_id library-coll-id}](is (false? (mi/can-write? (t2/select-one :model/Dashboard :id dashboard-id)))"Dashboard in remote-synced collection should not be writable when remote-sync-type is read-only")))-(testing "Documents in remote-synced collections have can_write=false"(mt/with-temp [:model/Document {document-id :id} {:name "Library Document":document (text->prose-mirror-ast "Library content")@@ -47,20 +45,17 @@(mt/with-temporary-setting-values [settings/remote-sync-type :read-write](mt/with-temp [:model/Collection {library-coll-id :id} {:name "Library Collection":is_remote_synced true}]-(testing "Cards in remote-synced collections have can_write=true"(mt/with-temp [:model/Card {card-id :id} {:name "Library Card":collection_id library-coll-id:dataset_query (mt/native-query {:query "SELECT 1"})}](is (true? (mi/can-write? (t2/select-one :model/Card :id card-id)))"Card in remote-synced collection should be writable when remote-sync-type is read-write")))-(testing "Dashboards in remote-synced collections have can_write=true"(mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Library Dashboard":collection_id library-coll-id}](is (true? (mi/can-write? (t2/select-one :model/Dashboard :id dashboard-id)))"Dashboard in remote-synced collection should be writable when remote-sync-type is read-write")))-(testing "Documents in remote-synced collections have can_write=true"(mt/with-temp [:model/Document {document-id :id} {:name "Library Document":document (text->prose-mirror-ast "Library content")@@ -73,24 +68,20 @@(mt/with-current-user (mt/user->id :rasta)(mt/with-temp [:model/Collection {regular-coll-id :id} {:name "Regular Collection":type nil}]-(doseq [remote-sync-setting [:read-only :read-write]](testing (str "When remote-sync-type is " remote-sync-setting)(mt/with-temporary-setting-values [settings/remote-sync-type remote-sync-setting]-(testing "Cards in regular collections have can_write=true"(mt/with-temp [:model/Card {card-id :id} {:name "Regular Card":collection_id regular-coll-id:dataset_query (mt/native-query {:query "SELECT 1"})}](is (true? (mi/can-write? (t2/select-one :model/Card :id card-id)))"Card in regular collection should always be writable regardless of remote-sync-type")))-(testing "Dashboards in regular collections have can_write=true"(mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Regular Dashboard":collection_id regular-coll-id}](is (true? (mi/can-write? (t2/select-one :model/Dashboard :id dashboard-id)))"Dashboard in regular collection should always be writable regardless of remote-sync-type")))-(testing "Documents in regular collections have can_write=true"(mt/with-temp [:model/Document {document-id :id} {:name "Regular Document":document (text->prose-mirror-ast "Regular content")@@ -106,46 +97,38 @@:model/Collection {child-library-id :id} {:name "Child Library Collection":location (format "/%d/" parent-library-id):is_remote_synced true}]-(testing "When remote-sync-type is read-only"(mt/with-temporary-setting-values [settings/remote-sync-type :read-only]-(testing "Cards in nested remote-synced collections have can_write=false"(mt/with-temp [:model/Card {card-id :id} {:name "Nested Library Card":collection_id child-library-id:dataset_query (mt/native-query {:query "SELECT 1"})}](is (false? (mi/can-write? (t2/select-one :model/Card :id card-id)))"Card in nested remote-synced collection should not be writable when remote-sync-type is read-only")))-(testing "Dashboards in nested remote-synced collections have can_write=false"(mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Nested Library Dashboard":collection_id child-library-id}](is (false? (mi/can-write? (t2/select-one :model/Dashboard :id dashboard-id)))"Dashboard in nested remote-synced collection should not be writable when remote-sync-type is read-only")))-(testing "Documents in nested remote-synced collections have can_write=false"(mt/with-temp [:model/Document {document-id :id} {:name "Nested Library Document":document (text->prose-mirror-ast "Nested library content"):collection_id child-library-id}](is (false? (mi/can-write? (t2/select-one :model/Document :id document-id)))"Document in nested remote-synced collection should not be writable when remote-sync-type is read-only")))))-(testing "When remote-sync-type is read-write"(mt/with-temporary-setting-values [settings/remote-sync-type :read-write]-(testing "Cards in nested remote-synced collections have can_write=true"(mt/with-temp [:model/Card {card-id :id} {:name "Nested Library Card":collection_id child-library-id:dataset_query (mt/native-query {:query "SELECT 1"})}](is (true? (mi/can-write? (t2/select-one :model/Card :id card-id)))"Card in nested remote-synced collection should be writable when remote-sync-type is read-write")))-(testing "Dashboards in nested remote-synced collections have can_write=true"(mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Nested Library Dashboard":collection_id child-library-id}](is (true? (mi/can-write? (t2/select-one :model/Dashboard :id dashboard-id)))"Dashboard in nested remote-synced collection should be writable when remote-sync-type is read-write")))-(testing "Documents in nested remote-synced collections have can_write=true"(mt/with-temp [:model/Document {document-id :id} {:name "Nested Library Document":document (text->prose-mirror-ast "Nested library content")@@ -160,10 +143,8 @@:is_remote_synced true}:model/Collection {regular-coll-id :id} {:name "Regular Collection":type nil}]-(testing "When remote-sync-type is read-only"(mt/with-temporary-setting-values [settings/remote-sync-type :read-only]-(testing "Library items have can_write=false while regular items have can_write=true"(mt/with-temp [:model/Card {library-card-id :id} {:name "Library Card":collection_id library-coll-id@@ -181,17 +162,14 @@:model/Document {regular-document-id :id} {:name "Regular Document":document (text->prose-mirror-ast "Regular content"):collection_id regular-coll-id}]-(is (false? (mi/can-write? (t2/select-one :model/Card :id library-card-id)))"Library card should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Card :id regular-card-id)))"Regular card should be writable")-(is (false? (mi/can-write? (t2/select-one :model/Dashboard :id library-dashboard-id)))"Library dashboard should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Dashboard :id regular-dashboard-id)))"Regular dashboard should be writable")-(is (false? (mi/can-write? (t2/select-one :model/Document :id library-document-id)))"Library document should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Document :id regular-document-id)))@@ -204,10 +182,8 @@:is_remote_synced true}:model/Collection {regular-coll-id :id} {:name "Regular Collection":type nil}]-(testing "When remote-sync-type is read-only"(mt/with-temporary-setting-values [settings/remote-sync-type :read-only]-(testing "Library items have can_write=false while regular items have can_write=true"(mt/with-temp [:model/Card {library-card-id :id} {:name "Library Card":collection_id library-coll-id@@ -225,17 +201,14 @@:model/Document {regular-document-id :id} {:name "Regular Document":document (text->prose-mirror-ast "Regular content"):collection_id regular-coll-id}]-(is (false? (mi/can-write? (t2/select-one :model/Card :id library-card-id)))"Library card should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Card :id regular-card-id)))"Regular card should be writable")-(is (false? (mi/can-write? (t2/select-one :model/Dashboard :id library-dashboard-id)))"Library dashboard should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Dashboard :id regular-dashboard-id)))"Regular dashboard should be writable")-(is (false? (mi/can-write? (t2/select-one :model/Document :id library-document-id)))"Library document should not be writable")(is (true? (mi/can-write? (t2/select-one :model/Document :id regular-document-id)))@@ -243,7 +216,6 @@(deftest remote-synced-collection-itself-permissions-test(testing "can_write for remote-synced collections themselves should respect remote-sync-type"-(testing "When remote-sync-type is read-only"(mt/with-temporary-setting-values [settings/remote-sync-type :read-only](mt/with-temp [:model/Collection {library-coll-id :id} {:name "Library Collection"@@ -251,7 +223,6 @@(mt/with-current-user (mt/user->id :rasta))(is (false? (mi/can-write? (t2/select-one :model/Collection :id library-coll-id)))"Library collection itself should not be writable when remote-sync-type is read-only"))))-(testing "When remote-sync-type is read-write"(mt/with-temporary-setting-values [settings/remote-sync-type :read-write](mt/with-temp [:model/Collection {library-coll-id :id} {:name "Library Collection"@@ -259,7 +230,6 @@(mt/with-current-user (mt/user->id :rasta)(is (true? (mi/can-write? (t2/select-one :model/Collection :id library-coll-id)))"Library collection itself should be writable when remote-sync-type is read-write")))))-(testing "Regular collections are always writable regardless of remote-sync-type"(doseq [remote-sync-setting [:read-only :read-write]](mt/with-temporary-setting-values [settings/remote-sync-type remote-sync-setting]@@ -268,3 +238,130 @@(mt/with-current-user (mt/user->id :rasta)(is (true? (mi/can-write? (t2/select-one :model/Collection :id regular-coll-id)))(str "Regular collection should always be writable when remote-sync-type is " remote-sync-setting)))))))))++;;; ------------------------------------------------ Tenant Collection Remote Sync Tests ------------------------------------------------++(deftest tenant-collection-remote-sync-off-by-default-test+ (testing "By default, tenant collections are not remote-synced"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {tenant-coll-id :id} {:name "Tenant Collection"+ :namespace collections/shared-tenant-ns}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-coll-id)]+ (testing "remote-synced-collection? returns false for tenant collections by default"+ (is (false? (collections/remote-synced-collection? tenant-coll))+ "Tenant collection should NOT be remote-synced by default"))++ (testing "Tenant collections are editable by superuser by default"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (true? (mi/can-write? tenant-coll))+ "Tenant collection should be writable by superuser by default")))))))))++(deftest tenant-collection-with-is-remote-synced-flag-test+ (testing "Tenant collections with is_remote_synced=true respect remote-sync-type setting"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {tenant-coll-id :id} {:name "Tenant Collection"+ :namespace collections/shared-tenant-ns+ :is_remote_synced true}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-coll-id)]+ (testing "remote-synced-collection? returns true when is_remote_synced flag is set"+ (is (true? (collections/remote-synced-collection? tenant-coll))+ "Tenant collection should be remote-synced when flag is set"))++ (testing "Tenant collections are NOT editable by superuser when remote-sync-type is read-only"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (false? (mi/can-write? tenant-coll))+ "Tenant collection should not be writable when remote-sync-type is read-only")))))))))++(deftest tenant-collection-with-is-remote-synced-flag-read-write-test+ (testing "Tenant collections with is_remote_synced=true are editable when remote-sync-type is read-write"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ settings/remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {tenant-coll-id :id} {:name "Tenant Collection"+ :namespace collections/shared-tenant-ns+ :is_remote_synced true}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-coll-id)]+ (testing "remote-synced-collection? returns true when is_remote_synced flag is set"+ (is (true? (collections/remote-synced-collection? tenant-coll))+ "Tenant collection should be remote-synced when flag is set"))++ (testing "Tenant collections ARE editable by superuser when remote-sync-type is read-write"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (true? (mi/can-write? tenant-coll))+ "Tenant collection should be writable when remote-sync-type is read-write")))))))))++(deftest tenant-collection-nested-inherits-remote-synced-test+ (testing "Nested tenant collections inherit is_remote_synced from parent"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {parent-tenant-id :id} {:name "Parent Tenant Collection"+ :namespace collections/shared-tenant-ns+ :is_remote_synced true}+ :model/Collection {child-tenant-id :id} {:name "Child Tenant Collection"+ :namespace collections/shared-tenant-ns+ :location (format "/%d/" parent-tenant-id)+ :is_remote_synced true}]+ (let [parent-coll (t2/select-one :model/Collection :id parent-tenant-id)+ child-coll (t2/select-one :model/Collection :id child-tenant-id)]+ (testing "Parent tenant collection is remote-synced"+ (is (true? (collections/remote-synced-collection? parent-coll))+ "Parent tenant collection should be remote-synced"))++ (testing "Child tenant collection is remote-synced"+ (is (true? (collections/remote-synced-collection? child-coll))+ "Child tenant collection should be remote-synced"))++ (testing "Parent tenant collection is not editable by superuser"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (false? (mi/can-write? parent-coll))+ "Parent tenant collection should not be writable")))++ (testing "Child tenant collection is not editable by superuser"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (false? (mi/can-write? child-coll))+ "Child tenant collection should not be writable")))))))))++(deftest tenant-collection-mixed-remote-synced-status-test+ (testing "Mixed scenario: some tenant collections remote-synced, others not"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {remote-synced-tenant-id :id} {:name "Remote-Synced Tenant Collection"+ :namespace collections/shared-tenant-ns+ :is_remote_synced true}+ :model/Collection {regular-tenant-id :id} {:name "Regular Tenant Collection"+ :namespace collections/shared-tenant-ns+ :is_remote_synced false}+ :model/Collection {regular-coll-id :id} {:name "Regular Collection"}]+ (let [remote-synced-tenant (t2/select-one :model/Collection :id remote-synced-tenant-id)+ regular-tenant (t2/select-one :model/Collection :id regular-tenant-id)+ regular-coll (t2/select-one :model/Collection :id regular-coll-id)]+ (testing "Remote-synced tenant collection is remote-synced"+ (is (true? (collections/remote-synced-collection? remote-synced-tenant))+ "Remote-synced tenant collection should be remote-synced"))++ (testing "Regular tenant collection is NOT remote-synced"+ (is (false? (collections/remote-synced-collection? regular-tenant))+ "Regular tenant collection should NOT be remote-synced"))++ (testing "Regular collection is NOT remote-synced"+ (is (false? (collections/remote-synced-collection? regular-coll))+ "Regular collection should NOT be remote-synced"))++ (mt/with-current-user (mt/user->id :crowberto)+ (testing "Remote-synced tenant collection is not editable by superuser"+ (is (false? (mi/can-write? remote-synced-tenant))+ "Remote-synced tenant collection should not be writable"))++ (testing "Regular tenant collection is editable by superuser"+ (is (true? (mi/can-write? regular-tenant))+ "Regular tenant collection should be writable"))++ (testing "Regular collection remains editable by superuser"+ (is (true? (mi/can-write? regular-coll))+ "Regular collection should be writable")))))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.cljindex 1a22ab102aa..12b7235b0de 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][metabase-enterprise.remote-sync.settings :as settings]+ [metabase.collections.models.collection.root :as collection.root][metabase.settings.core :as setting][metabase.test :as mt]))@@ -52,3 +53,16 @@(is (false? (settings/remote-sync-enabled))))(mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"](is (true? (settings/remote-sync-enabled)))))++;;; ------------------------------------------------- Root Collection Remote Sync -------------------------------------------------++(deftest root-collection-is-not-remote-synced-test+ (testing "Root collection for shared-tenant-collection namespace is never remote-synced (individual children can be toggled)"+ (let [root-coll (collection.root/root-collection-with-ui-details :shared-tenant-collection)]+ (is (false? (:is_remote_synced root-coll)))))+ (testing "Root collection for default namespace is not remote-synced"+ (let [root-coll (collection.root/root-collection-with-ui-details nil)]+ (is (false? (:is_remote_synced root-coll)))))+ (testing "Root collection for snippets namespace is not remote-synced"+ (let [root-coll (collection.root/root-collection-with-ui-details :snippets)]+ (is (false? (:is_remote_synced root-coll))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.cljindex 7df5f2ef0c3..78140c90e2a 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj@@ -355,3 +355,65 @@(mt/with-temp-dir [remote-dir nil](let [[master _remote] (init-source! "master" remote-dir)](is (= "master" (git/default-branch master))))))++(deftest write-files-removal-test+ (let [subdir-path (str "collections/" "r" (subs (u/generate-nano-id "a") 1) "_subdir/")+ otherdir-path (str "collections/" "o" (subs (u/generate-nano-id "b") 1) "_otherdir/")]+ (mt/with-temp-dir [remote-dir nil]+ (let [[master _remote] (init-source! "master" remote-dir+ :files {"master.txt" "File in master"+ (str subdir-path "file1.yaml") "File 1 in subdir"+ (str subdir-path "file2.yaml") "File 2 in subdir"+ (str otherdir-path "file1.yaml") "File 1 in otherdir"+ (str otherdir-path "file2.yaml") "File 2 in otherdir"})]+ (testing "Removal entry deletes all files under that path recursively"+ (source.p/write-files! (source.p/snapshot master) "Remove subdir"+ [{:path (subs subdir-path 0 (dec (count subdir-path))) :remove? true}])+ (let [files (set (source.p/list-files (source.p/snapshot master)))]+ (is (contains? files "master.txt") "Root files should remain")+ (is (contains? files (str otherdir-path "file1.yaml")) "Other collection files should remain")+ (is (contains? files (str otherdir-path "file2.yaml")) "Other collection files should remain")+ (is (not (contains? files (str subdir-path "file1.yaml"))) "Subdir files should be removed")+ (is (not (contains? files (str subdir-path "file2.yaml"))) "Subdir files should be removed")))))))++(deftest write-files-mixed-write-and-removal-test+ (let [subdir-path (str "collections/" "r" (subs (u/generate-nano-id "a") 1) "_subdir/")+ newdir-path (str "collections/" "n" (subs (u/generate-nano-id "b") 1) "_newdir/")]+ (mt/with-temp-dir [remote-dir nil]+ (let [[master _remote] (init-source! "master" remote-dir+ :files {"master.txt" "File in master"+ (str subdir-path "old-file.yaml") "Old file in subdir"})]+ (testing "Can combine write and removal entries in same call"+ (source.p/write-files! (source.p/snapshot master) "Mixed operations"+ [{:path (subs subdir-path 0 (dec (count subdir-path))) :remove? true}+ {:path (str newdir-path "new-file.yaml") :content "New file content"}])+ (let [snap (source.p/snapshot master)+ files (set (source.p/list-files snap))]+ (is (contains? files "master.txt") "Root files should remain")+ (is (contains? files (str newdir-path "new-file.yaml")) "New files should be added")+ (is (not (contains? files (str subdir-path "old-file.yaml"))) "Old files should be removed")+ (is (= "New file content" (source.p/read-file snap (str newdir-path "new-file.yaml"))))))))))++(deftest write-files-empty-removal-path-test+ (mt/with-temp-dir [remote-dir nil]+ (let [[master _remote] (init-source! "master" remote-dir+ :files {"master.txt" "File in master"+ "subdir/file.yaml" "File in subdir"})]+ (testing "Empty removal paths are ignored (no-op)"+ (source.p/write-files! (source.p/snapshot master) "Empty removal"+ [{:path "" :remove? true}+ {:path " " :remove? true}])+ (let [files (set (source.p/list-files (source.p/snapshot master)))]+ (is (= #{"master.txt" "subdir/file.yaml"} files)+ "All files should remain when removal path is empty"))))))++(deftest write-files-nonexistent-removal-path-test+ (mt/with-temp-dir [remote-dir nil]+ (let [[master _remote] (init-source! "master" remote-dir+ :files {"master.txt" "File in master"})]+ (testing "Removing non-existent path is a no-op"+ (source.p/write-files! (source.p/snapshot master) "Remove nonexistent"+ [{:path "collections/nonexistent" :remove? true}])+ (let [files (set (source.p/list-files (source.p/snapshot master)))]+ (is (= #{"master.txt"} files)+ "Files should remain unchanged"))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source/wrapping_source_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source/wrapping_source_test.cljindex 7bc3bea0a34..89446734b9a 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source/wrapping_source_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source/wrapping_source_test.clj@@ -157,3 +157,26 @@(is (= []@written-files)"Should write no files when none match"))))++(deftest wrapping-source-write-files-removal-entries-test+ (testing "WrappingSource filters removal entries based on path-filters"+ (let [written-files (atom [])+ mock-snap (reify source.p/SourceSnapshot+ (list-files [_]+ [])+ (read-file [_ _path]+ nil)+ (write-files! [_ _message files]+ (reset! written-files (vec files))+ nil)+ (version [_]+ "mock-version"))+ wrapped-snap (source/->WrappingSnapshot mock-snap [#"collections/.*"])+ files-to-write [{:path "collections/foo.yaml" :content "foo-content"}+ {:path "collections/abc123" :remove? true}+ {:path "databases/db1" :remove? true}]]+ (source.p/write-files! wrapped-snap "test commit" files-to-write)+ (is (= [{:path "collections/foo.yaml" :content "foo-content"}+ {:path "collections/abc123" :remove? true}]+ @written-files)+ "Should pass through removal entries that match filter and filter out those that don't"))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source_test.cljindex 019289056aa..21e452f8c5d 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source_test.clj@@ -63,7 +63,7 @@test-entities [(create-test-entity "test-id-1" "entity-one" "Collection")(create-test-entity "test-id-2" "entity-two" "Card")]]- (is (= "mock-written-version" (source/store! test-entities (source.p/snapshot mock-source) task-id "Test commit message")))+ (is (= "mock-written-version" (source/store! test-entities [] (source.p/snapshot mock-source) task-id "Test commit message")))(testing "write-files! was called with correct message"(is (= "Test commit message" (:message @written-files))))@@ -108,7 +108,7 @@(let [initial-task (t2/select-one :model/RemoteSyncTask :id task-id)](is (nil? (:progress initial-task)) "Progress should be nil initially"))- (source/store! test-entities (source.p/snapshot mock-source) task-id "Test commit")+ (source/store! test-entities [] (source.p/snapshot mock-source) task-id "Test commit")(let [final-task (t2/select-one :model/RemoteSyncTask :id task-id)](is (some? (:progress final-task)) "Progress should be updated after store!")@@ -128,7 +128,7 @@(let [written-files (atom nil)mock-source (->MockSource written-files)]- (source/store! [] (source.p/snapshot mock-source) task-id "Empty commit")+ (source/store! [] [] (source.p/snapshot mock-source) task-id "Empty commit")(testing "write-files! was called even with empty stream"(is (some? @written-files)))@@ -158,17 +158,14 @@:display "table":dataset_query {:z_field 1 :a_field 2 :database 3}:visualization_settings {:zebra true :apple false}}]-;; Store the same entity twice- (source/store! [test-entity] (source.p/snapshot mock-source-1) task-id "First commit")- (source/store! [test-entity] (source.p/snapshot mock-source-2) task-id "Second commit")-+ (source/store! [test-entity] [] (source.p/snapshot mock-source-1) task-id "First commit")+ (source/store! [test-entity] [] (source.p/snapshot mock-source-2) task-id "Second commit")(testing "YAML content is identical between runs"(let [content-1 (-> @written-files-1 :files first :content)content-2 (-> @written-files-2 :files first :content)](is (= content-1 content-2)"YAML content should be identical for the same entity")))-(testing "known keys appear in serialization-order.edn order"(let [content (-> @written-files-1 :files first :content)name-pos (str/index-of content "name:")@@ -179,7 +176,6 @@"name should appear before description")(is (< description-pos display-pos)"description should appear before display")))-(testing "unknown keys are sorted alphabetically after known keys"(let [content (-> @written-files-1 :files first :content)a-first-pos (str/index-of content "a_first_field:")diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers.cljindex ae7d8e9a874..6b65f850269 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers.clj@@ -182,8 +182,22 @@ width: fixed:write-files-error (throw (Exception. "Failed to write files")):store-error (throw (Exception. "Store failed")):network-error (throw (java.net.UnknownHostException. "Remote host not found"))- ;; Default success case - write files to atom- (swap! files-atom assoc branch (into {} (map (juxt :path :content) files))))+ ;; Default success case - handle both writes and removals+ (let [write-entries (remove #(or (:remove? %) (str/blank? (:path %))) files)+ removal-prefixes (into #{} (comp (filter :remove?)+ (map :path)+ (remove str/blank?))+ files)+ current-files (get @files-atom branch {})+ ;; Remove files matching removal prefixes+ after-removals (into {}+ (remove (fn [[path _]]+ (some #(or (= path %) (str/starts-with? path %))+ removal-prefixes))+ current-files))+ ;; Add new files+ final-files (into after-removals (map (juxt :path :content) write-entries))]+ (swap! files-atom assoc branch final-files)))"write-files-version")(version [_this]diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers_test.cljnew file mode 100644index 00000000000..00cddf64e33--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers_test.clj@@ -0,0 +1,68 @@+(ns metabase-enterprise.remote-sync.test-helpers-test+ "Tests for the MockSource implementation in test-helpers."+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.remote-sync.source.protocol :as source.p]+ [metabase-enterprise.remote-sync.test-helpers :as th]))++(deftest mock-source-write-files-removal-test+ (testing "MockSource handles removal entries correctly"+ (let [source (th/create-mock-source+ :initial-files {"main" {"collections/abc/file1.yaml" "content1"+ "collections/abc/file2.yaml" "content2"+ "collections/def/file3.yaml" "content3"+ "other/file4.yaml" "content4"}})+ snapshot (source.p/snapshot source)]+ (source.p/write-files! snapshot "Remove abc collection"+ [{:path "collections/abc" :remove? true}])+ (is (= #{"collections/def/file3.yaml" "other/file4.yaml"}+ (set (source.p/list-files snapshot)))+ "Should remove all files under collections/abc recursively"))))++(deftest mock-source-write-files-removal-exact-path-test+ (testing "MockSource removal matches exact path"+ (let [source (th/create-mock-source+ :initial-files {"main" {"collections/abc.yaml" "content1"+ "collections/abcdef/file.yaml" "content2"}})+ snapshot (source.p/snapshot source)]+ (source.p/write-files! snapshot "Remove abc.yaml"+ [{:path "collections/abc.yaml" :remove? true}])+ (is (= #{"collections/abcdef/file.yaml"}+ (set (source.p/list-files snapshot)))+ "Should only remove exact path match, not prefix match without slash"))))++(deftest mock-source-write-files-mixed-write-and-removal-test+ (testing "MockSource handles both write and removal entries"+ (let [source (th/create-mock-source+ :initial-files {"main" {"collections/old/file1.yaml" "old-content"+ "collections/keep/file2.yaml" "keep-content"}})+ snapshot (source.p/snapshot source)]+ (source.p/write-files! snapshot "Mixed operations"+ [{:path "collections/old" :remove? true}+ {:path "collections/new/file3.yaml" :content "new-content"}])+ (is (= #{"collections/keep/file2.yaml" "collections/new/file3.yaml"}+ (set (source.p/list-files snapshot)))+ "Should remove old files and add new files"))))++(deftest mock-source-write-files-empty-removal-path-test+ (testing "MockSource ignores removal entries with empty paths"+ (let [source (th/create-mock-source+ :initial-files {"main" {"collections/abc/file1.yaml" "content1"}})+ snapshot (source.p/snapshot source)]+ (source.p/write-files! snapshot "Empty removal"+ [{:path "" :remove? true}+ {:path " " :remove? true}])+ (is (= #{"collections/abc/file1.yaml"}+ (set (source.p/list-files snapshot)))+ "Should not remove anything when removal path is empty or blank"))))++(deftest mock-source-write-files-nonexistent-removal-path-test+ (testing "MockSource handles removal of non-existent paths (no-op)"+ (let [source (th/create-mock-source+ :initial-files {"main" {"collections/abc/file1.yaml" "content1"}})+ snapshot (source.p/snapshot source)]+ (source.p/write-files! snapshot "Remove nonexistent"+ [{:path "collections/xyz" :remove? true}])+ (is (= #{"collections/abc/file1.yaml"}+ (set (source.p/list-files snapshot)))+ "Should be a no-op when removing non-existent path"))))diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.cljindex 584e2bb050e..db881e2622c 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj@@ -71,6 +71,25 @@(is (= 2(count (mt/user-http-request :crowberto :get 200 "mt/user/attributes")))))))))+(deftest get-user-attributes-with-tenants-test+ (mt/with-premium-features #{:tenants :sandboxes}+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "includes tenant attributes from tenant models"+ (mt/with-temp+ [:model/Tenant _ {:name "Test Tenant"+ :slug "test-tenant"+ :attributes {"tenant-key-1" "value1"+ "tenant-key-2" "value2"}}+ :model/Tenant _ {:name "Another Tenant"+ :slug "another-tenant"+ :attributes {"tenant-key-3" "value3"+ "tenant-key-1" "different-value"}}+ :model/User _ {:login_attributes {:user-key "user-value"}}]++ (let [attributes (set (mt/user-http-request :crowberto :get 200 "mt/user/attributes"))]+ (is (set/subset? #{"tenant-key-1" "tenant-key-2" "tenant-key-3" "user-key"}+ attributes))))))))+(deftest update-user-attributes-test(mt/with-premium-features #{}(testing "requires sandbox enabled"diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.cljindex 902d380385c..831cfd2d38c 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj@@ -881,7 +881,7 @@(met/with-user-attributes! :rasta {"cat" 40};; re-bind current user so updated attributes come in to effect(mt/with-test-user :rasta- (is (= {"cat" 40}+ (is (= {"cat" "40"} ;; attributes are always stringified(:login_attributes @api/*current-user*)))(let [result (run-query)](is (= nildiff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex b055e6716fe..80f895e0f62 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -89,6 +89,7 @@:model/Session:model/SupportAccessGrantLog:model/TaskHistory+ :model/Tenant:model/TimelineEvent;; TODO we should remove these models from here once serialization is supported:model/TransformRundiff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.cljindex 2c3e888b76e..457ac80d84a 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj@@ -7,6 +7,7 @@[metabase-enterprise.sso.integrations.saml-test :as saml-test][metabase-enterprise.sso.integrations.token-utils :as token-utils][metabase-enterprise.sso.settings :as sso-settings]+ [metabase-enterprise.tenants.auth-provider] ;; make sure the auth provider is actually registered[metabase.appearance.settings :as appearance.settings][metabase.config.core :as config][metabase.premium-features.token-check :as token-check]@@ -60,15 +61,16 @@(defmacro ^:private with-jwt-default-setup! [& body]`(mt/test-helpers-set-global-values!- (mt/with-premium-features #{:audit-app}- (do-with-other-sso-types-disabled!- (fn []- (mt/with-additional-premium-features #{:sso-jwt}- (saml-test/call-with-login-attributes-cleared!- (fn []- (call-with-default-jwt-config!- (fn []- ~@body))))))))))+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]+ (mt/with-premium-features #{:audit-app}+ (do-with-other-sso-types-disabled!+ (fn []+ (mt/with-additional-premium-features #{:sso-jwt}+ (saml-test/call-with-login-attributes-cleared!+ (fn []+ (call-with-default-jwt-config!+ (fn []+ ~@body)))))))))))(deftest sso-prereqs-test(do-with-other-sso-types-disabled!@@ -411,23 +413,6 @@(mt/boolean-ids-and-timestamps (t2/select :model/User :email "[email protected]"))(map #(dissoc % :last_login))))))))))))-#_(deftest group-mappings-test- (testing "make sure our setting for mapping group names -> IDs works"- (mt/with-additional-premium-features #{:sso-jwt}- (mt/with-temporary-setting-values- [jwt-group-mappings- {"group_1" [1 2 3]- "group_2" [3 4]- "group_3" [5]}]- (testing "keyword group names"- (is- (= #{1 2 3 4}- (#'mt.jwt/group-names->ids [:group_1 :group_2]))))- (testing "string group names"- (is- (= #{3 4 5}- (#'mt.jwt/group-names->ids ["group_2" "group_3"]))))))))-(defn- group-memberships [user-or-id](when-let [group-ids (seq(t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (u/the-id user-or-id)))]@@ -473,7 +458,7 @@:model/PermissionsGroup _ {:name "admins"}](mt/with-temporary-setting-values[jwt-group-sync true- jwt-group-mappings nil ; No mappings defined+ jwt-group-mappings nil ; No mappings definedjwt-attribute-groups "groups"](mt/with-model-cleanup [:model/User](let [response (client/client-real-response :get 302 "/auth/sso"@@ -502,27 +487,27 @@(with-jwt-default-setup!(mt/with-model-cleanup [:model/User];; just create the user- (let [response (client/client-real-response :get 302 "/auth/sso"- {:request-options {:redirect-strategy :none}}- :return_to default-redirect-uri- :jwt- (jwt/sign- {:email "[email protected]"- :first_name "New"- :last_name "User"}- default-jwt-secret))]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))](is (saml-test/successful-login? response)));; then log in again- (let [response (client/client-real-response :get 302 "/auth/sso"- {:request-options {:redirect-strategy :none}}- :return_to default-redirect-uri- :jwt- (jwt/sign- {:email "[email protected]"- :first_name "New"- :last_name "User"}- default-jwt-secret))]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))](is (saml-test/successful-login? response))))))(testing "Existing user login attributes are not changed on subsequent logins"@@ -568,30 +553,30 @@(with-jwt-default-setup!(mt/with-model-cleanup [:model/User];; just create the user- (let [response (client/client-real-response :get 302 "/auth/sso"- {:request-options {:redirect-strategy :none}}- :return_to default-redirect-uri- :jwt- (jwt/sign- {:email "[email protected]"- :first_name "New"- :last_name "User"}- default-jwt-secret))]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))](is (saml-test/successful-login? response)));; deactivate the user(t2/update! :model/User :email "[email protected]" {:is_active false})(is (not (t2/select-one-fn :is_active :model/User :email "[email protected]")))- (let [response (client/client-real-response :get 302 "/auth/sso"- {:request-options {:redirect-strategy :none}}- :return_to default-redirect-uri- :jwt- (jwt/sign- {:email "[email protected]"- :first_name "New"- :last_name "User"}- default-jwt-secret))]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))](is (saml-test/successful-login? response))(is (t2/select-one-fn :is_active :model/User :email "[email protected]")))@@ -611,6 +596,285 @@:last_name "User"}default-jwt-secret)))))))))+(deftest tenants-can-be-auto-provisioned+ (mt/with-model-cleanup [:model/Tenant]+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}]+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is (some? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))+ (is (t2/exists? :model/Tenant :slug "tenant-mctenantson")))+ (testing "they should be able to log in again"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response)))))))))))++(deftest new-users-should-be-set-to-the-correct-tenant+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}+ :model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}]+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is+ (= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))+ (testing "they should be able to log in again"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is+ (= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))))))))++(deftest new-users-are-not-assigned-a-tenant-if-tenants-is-not-enabled+ (with-jwt-default-setup!+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}+ :model/Tenant _ {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}]+ (mt/with-model-cleanup [:model/User]+ (mt/with-temporary-setting-values [use-tenants false]+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is+ (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))+ (testing "they should be able to log in without the tenant bit, of course"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is+ (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))++(deftest name-does-not-get-overwritten-on-new-login+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}+ :model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email :email+ first-name :first_name+ last-name :last_name} {:tenant_id tenant-id+ :first_name (mt/random-name)+ :last_name (mt/random-name)}]+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "they should be able to log in without specifying a name"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email email+ "@tenant" "tenant-mctenantson"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (testing "their name is unchanged"+ (is (= [first-name last-name] (t2/select-one-fn (juxt :first_name :last_name) :model/User :email email))))))))))))++(deftest a-user-cannot-log-in-with-a-deactivated-tenant+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}+ :model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"+ :is_active false}+ :model/User {existing-email :email} {:tenant_id tenant-id}]+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "a new user fails to log in with correct error message"+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is (str/includes? (:body response) "Tenant is not active")))))+ (testing "an existing user also fails to log in with correct error message"+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email existing-email+ "@tenant" "tenant-mctenantson"+ :first_name "Existing"+ :last_name "User"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is (str/includes? (:body response) "Tenant is not active"))))))))))++;; not yet - we need to figure out what to do about personal collections here first+#_(deftest existing-users-can-be-updated-with-a-tenant+ (with-jwt-default-setup!+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}]+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-model-cleanup [:model/User]+ (testing "log in without a tenant"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))+ (testing "now log in WITH a tenant"+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ "@tenant" "tenant-mctenantson"+ :first_name "New"+ :last_name "User"}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (is+ (= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))++(deftest a-tenant-cannot-be-changed-once-set+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/Tenant _ {:slug "other"+ :name "Other"}+ :model/User {email-with-tenant :email} {:tenant_id tenant-id}]+ (testing "tenant -> other tenant fails with correct error message"+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign {:email email-with-tenant "@tenant" "other"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is (str/includes? (:body response) "Tenant ID mismatch with existing user")))))))))++(deftest external-user-requires-tenant-claim+ (testing "External user must include tenant claim in JWT"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email-with-tenant :email} {:tenant_id tenant-id}]+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email email-with-tenant}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is (str/includes? (:body response) "Tenant claim required for external user")))))))))++(deftest internal-user-cannot-have-tenant-claim+ (testing "Internal user cannot log in with tenant claim in JWT"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant _ {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email-without-tenant :email} {}]+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email email-without-tenant+ "@tenant" "tenant-mctenantson"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ (is (str/includes? (:body response) "Cannot add tenant claim to internal user")))))))))++(deftest internal-user-cannot-login-with-tenant-claim-if-tenants-disabled+ (testing "Internal user cannot log in with tenant claim in JWT"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants false]+ (mt/with-temp [:model/Tenant _ {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email-without-tenant :email} {}]+ (let [response (client/client-real-response :get 403 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email email-without-tenant+ "@tenant" "tenant-mctenantson"+ :foo "bar"}+ default-jwt-secret))]+ (is (not (saml-test/successful-login? response)))+ ;; the `@tenant` key is special, does not become a user attribute+ (is (nil? (t2/select-one-fn :jwt_attributes :model/User :email email-without-tenant))))))))))+(deftest create-new-jwt-user-no-user-provisioning-test(testing "When user provisioning is disabled, throw an error if we attempt to create a new user."(with-jwt-default-setup!@@ -644,20 +908,23 @@:boolean_attr false:array_attr ["item1" "item2"]:object_attr {:nested "value"}- :null_attr nil}+ :null_attr nil+ "@attribute" "foo"}default-jwt-secret))](is (saml-test/successful-login? response))(testing "only string attributes are saved to jwt_attributes"(is (= {"string_attr" "valid-string"- "number_attr" 42- "boolean_attr" false}+ "number_attr" "42"+ "boolean_attr" "false"}(t2/select-one-fn :jwt_attributes :model/User :email "[email protected]"))))(testing "warning messages are logged for non-stringable values"(is (some #(re-find #"Dropping attribute 'array_attr' with non-stringable value: \[\"item1\" \"item2\"\]" %) (map :message (jwt-log-messages))))(is (some #(re-find #"Dropping attribute 'object_attr' with non-stringable value: \{:nested \"value\"\}" %) (map :message (jwt-log-messages))))(is (some #(re-find #"Dropping attribute 'null_attr' with non-stringable value: null" %) (map :message (jwt-log-messages)))))+ (testing "warning messages are logged for `@`-prefixed keys"+ (is (some #(re-find #"Dropping attribute '@attribute', keys beginning with `@` are reserved" %) (map :message (jwt-log-messages)))))(testing "no warning for valid string attribute"(is (not (some #(re-find #"string_attr" %) (map :message (jwt-log-messages)))))))))))@@ -766,3 +1033,129 @@:return_to default-redirect-uri:jwt jwt-payload)](is result nil))))))++(deftest tenant-user-assigned-to-tenant-group-via-mapping-test+ (testing "JWT user with tenant claim can be assigned to tenant user groups via group mapping"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "test-tenant"+ :name "Test Tenant"}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Engineers"+ :is_tenant_group true}]+ (mt/with-temporary-setting-values+ [jwt-group-sync true+ jwt-group-mappings {"engineers" [tenant-group-id]}+ jwt-attribute-groups "groups"]+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "Tenant"+ :last_name "User"+ "@tenant" "test-tenant"+ :groups ["engineers"]}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (let [user (t2/select-one :model/User :email "[email protected]")]+ (testing "user is assigned to the correct tenant"+ (is (= tenant-id (:tenant_id user))))+ (testing "user is assigned to the mapped tenant group"+ (is (contains? (group-memberships (u/the-id user)) "Tenant Engineers")))+ (testing "user is assigned to All tenant users (magic group for tenant users)"+ (is (contains? (group-memberships (u/the-id user)) "All tenant users")))))))))))))++(deftest tenant-user-assigned-to-tenant-group-via-name-matching-test+ (testing "JWT user with tenant claim can be assigned to tenant user groups via group name matching (no explicit mappings)"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "test-tenant"+ :name "Test Tenant"}+ :model/PermissionsGroup _ {:name "tenant-developers"+ :is_tenant_group true}+ :model/PermissionsGroup _ {:name "tenant-analysts"+ :is_tenant_group true}+ :model/PermissionsGroup _ {:name "tenant-admins"+ :is_tenant_group true}]+ (mt/with-temporary-setting-values+ [jwt-group-sync true+ jwt-group-mappings nil+ jwt-attribute-groups "groups"]+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "Tenant"+ :last_name "User"+ "@tenant" "test-tenant"+ :groups ["tenant-developers" "tenant-analysts"]}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (let [user (t2/select-one :model/User :email "[email protected]")]+ (testing "user is assigned to the correct tenant"+ (is (= tenant-id (:tenant_id user))))+ (testing "user is assigned to groups matching the names from JWT claims"+ (is (= #{"All tenant users" "tenant-developers" "tenant-analysts"}+ (group-memberships (u/the-id user)))))+ (testing "user is not assigned to groups not mentioned in JWT claims"+ (is (not (contains? (group-memberships (u/the-id user)) "tenant-admins"))))))))))))))++(deftest tenant-user-group-sync-on-subsequent-login-test+ (testing "JWT tenant user group memberships are synced correctly on subsequent logins"+ (with-jwt-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "test-tenant"+ :name "Test Tenant"}+ :model/PermissionsGroup _ {:name "Group A"+ :is_tenant_group true}+ :model/PermissionsGroup _ {:name "Group B"+ :is_tenant_group true}]+ (mt/with-temporary-setting-values+ [jwt-group-sync true+ jwt-group-mappings nil+ jwt-attribute-groups "groups"]+ (mt/with-model-cleanup [:model/User]+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "Tenant"+ :last_name "User"+ "@tenant" "test-tenant"+ :groups ["Group A"]}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (let [user (t2/select-one :model/User :email "[email protected]")]+ (is (= tenant-id (:tenant_id user)))+ (is (= #{"All tenant users" "Group A"}+ (group-memberships (u/the-id user))))))+ (let [response (client/client-real-response :get 302 "/auth/sso"+ {:request-options {:redirect-strategy :none}}+ :return_to default-redirect-uri+ :jwt+ (jwt/sign+ {:email "[email protected]"+ :first_name "Tenant"+ :last_name "User"+ "@tenant" "test-tenant"+ :groups ["Group B"]}+ default-jwt-secret))]+ (is (saml-test/successful-login? response))+ (let [user (t2/select-one :model/User :email "[email protected]")]+ (testing "user remains assigned to the same tenant"+ (is (= tenant-id (:tenant_id user))))+ (testing "user group memberships are updated to reflect JWT claims"+ (is (= #{"All tenant users" "Group B"}+ (group-memberships (u/the-id user)))))+ (testing "user is no longer in Group A"+ (is (not (contains? (group-memberships (u/the-id user)) "Group A"))))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.cljindex aec26904af5..d079b6fb9ea 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/ldap_test.clj@@ -16,120 +16,120 @@(mt/with-premium-features #{:sso-ldap}(ldap.test/with-ldap-server!(testing "find by username"- (is (= {:dn "cn=John Smith,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=John Smith,ou=People,dc=metabase,dc=com":first-name "John"- :last-name "Smith"- :email "[email protected]"- :attributes {:uid "jsmith1"- :mail "[email protected]"- :givenname "John"- :sn "Smith"- :cn "John Smith"}- :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}+ :last-name "Smith"+ :email "[email protected]"+ :attributes {"uid" "jsmith1"+ "mail" "[email protected]"+ "givenname" "John"+ "sn" "Smith"+ "cn" "John Smith"}+ :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "jsmith1"))))(testing "find by email"- (is (= {:dn "cn=John Smith,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=John Smith,ou=People,dc=metabase,dc=com":first-name "John"- :last-name "Smith"- :email "[email protected]"- :attributes {:uid "jsmith1"- :mail "[email protected]"- :givenname "John"- :sn "Smith"- :cn "John Smith"}- :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}+ :last-name "Smith"+ :email "[email protected]"+ :attributes {"uid" "jsmith1"+ "mail" "[email protected]"+ "givenname" "John"+ "sn" "Smith"+ "cn" "John Smith"}+ :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))(testing "find by email, no groups"- (is (= {:dn "cn=Fred Taylor,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=Fred Taylor,ou=People,dc=metabase,dc=com":first-name "Fred"- :last-name "Taylor"- :email "[email protected]"- :attributes {:mail "[email protected]"- :cn "Fred Taylor"- :givenname "Fred"- :sn "Taylor"}- :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}+ :last-name "Taylor"+ :email "[email protected]"+ :attributes {"mail" "[email protected]"+ "cn" "Fred Taylor"+ "givenname" "Fred"+ "sn" "Taylor"}+ :groups ["cn=Accounting,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))(testing "find by email, no givenName"- (is (= {:dn "cn=Jane Miller,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=Jane Miller,ou=People,dc=metabase,dc=com":first-name nil- :last-name "Miller"- :email "[email protected]"- :attributes {:uid "jmiller"- :mail "[email protected]"- :cn "Jane Miller"- :sn "Miller"}- :groups []}+ :last-name "Miller"+ :email "[email protected]"+ :attributes {"uid" "jmiller"+ "mail" "[email protected]"+ "cn" "Jane Miller"+ "sn" "Miller"}+ :groups []}(ldap/find-user "[email protected]"))))(mt/with-temporary-setting-values [ldap-group-membership-filter "memberUid={uid}"](testing "find by username with custom group membership filter"- (is (= {:dn "cn=Sally Brown,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=Sally Brown,ou=People,dc=metabase,dc=com":first-name "Sally"- :last-name "Brown"- :email "[email protected]"- :attributes {:uid "sbrown20"- :mail "[email protected]"- :givenname "Sally"- :sn "Brown"- :cn "Sally Brown"}- :groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}+ :last-name "Brown"+ :email "[email protected]"+ :attributes {"uid" "sbrown20"+ "mail" "[email protected]"+ "givenname" "Sally"+ "sn" "Brown"+ "cn" "Sally Brown"}+ :groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "sbrown20"))))(testing "find by email with custom group membership filter"- (is (= {:dn "cn=Sally Brown,ou=People,dc=metabase,dc=com"+ (is (= {:dn "cn=Sally Brown,ou=People,dc=metabase,dc=com":first-name "Sally"- :last-name "Brown"- :email "[email protected]"- :attributes {:uid "sbrown20"- :mail "[email protected]"- :givenname "Sally"- :sn "Brown"- :cn "Sally Brown"}- :groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}+ :last-name "Brown"+ :email "[email protected]"+ :attributes {"uid" "sbrown20"+ "mail" "[email protected]"+ "givenname" "Sally"+ "sn" "Brown"+ "cn" "Sally Brown"}+ :groups ["cn=Engineering,ou=Groups,dc=metabase,dc=com"]}(ldap/find-user "[email protected]"))))))))(deftest attribute-sync-test(mt/with-premium-features #{:sso-ldap}(ldap.test/with-ldap-server!(testing "find by email/username should return other attributes as well"- (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"+ (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com":first-name "Lucky"- :last-name "Pigeon"- :email "[email protected]"- :attributes {:uid "lucky"- :mail "[email protected]"- :title "King Pigeon"- :givenname "Lucky"- :sn "Pigeon"- :cn "Lucky Pigeon"}- :groups []}+ :last-name "Pigeon"+ :email "[email protected]"+ :attributes {"uid" "lucky"+ "mail" "[email protected]"+ "title" "King Pigeon"+ "givenname" "Lucky"+ "sn" "Pigeon"+ "cn" "Lucky Pigeon"}+ :groups []}(ldap/find-user "lucky"))))(testing "ignored attributes should not be returned"(mt/with-temporary-setting-values [ldap-sync-user-attributes-blacklist(cons "title" (sso-settings/ldap-sync-user-attributes-blacklist))]- (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"+ (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com":first-name "Lucky"- :last-name "Pigeon"- :email "[email protected]"- :attributes {:uid "lucky"- :mail "[email protected]"- :givenname "Lucky"- :sn "Pigeon"- :cn "Lucky Pigeon"}- :groups []}+ :last-name "Pigeon"+ :email "[email protected]"+ :attributes {"uid" "lucky"+ "mail" "[email protected]"+ "givenname" "Lucky"+ "sn" "Pigeon"+ "cn" "Lucky Pigeon"}+ :groups []}(ldap/find-user "lucky")))))(testing "if attribute sync is disabled, no attributes should come back at all"(mt/with-temporary-setting-values [ldap-sync-user-attributes false]- (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com"+ (is (= {:dn "cn=Lucky Pigeon,ou=Birds,dc=metabase,dc=com":first-name "Lucky"- :last-name "Pigeon"- :email "[email protected]"+ :last-name "Pigeon"+ :email "[email protected]":attributes nil- :groups []}+ :groups []}(ldap/find-user "lucky"))))))))(deftest new-user-attributes-synced-test@@ -145,15 +145,15 @@:ip_address "127.0.0.1":embedded false}})](is (true? (:success? result)))- (is (= {:first_name "John"- :last_name "Smith"- :email "[email protected]"- :login_attributes {"uid" "jsmith1"- "mail" "[email protected]"+ (is (= {:first_name "John"+ :last_name "Smith"+ :email "[email protected]"+ :login_attributes {"uid" "jsmith1"+ "mail" "[email protected]""givenname" "John"- "sn" "Smith"- "cn" "John Smith"}- :common_name "John Smith"}+ "sn" "Smith"+ "cn" "John Smith"}+ :common_name "John Smith"}(into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]"))))))))))@@ -171,11 +171,11 @@:ip_address "127.0.0.1":embedded false}})](is (true? (:success? result)))- (is (= {:first_name "John"- :last_name "Smith"- :email "[email protected]"+ (is (= {:first_name "John"+ :last_name "Smith"+ :email "[email protected]":login_attributes nil- :common_name "John Smith"}+ :common_name "John Smith"}(into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]")))))))))))@@ -200,14 +200,14 @@:embedded false}})](is (true? (:success? result1)))(is (true? (:success? result2)))- (is (= {:first_name "John"- :last_name "Smith"- :common_name "John Smith"- :email "[email protected]"- :login_attributes {"uid" "jsmith1"- "mail" "[email protected]"- "givenname" "John"- "sn" "Smith"+ (is (= {:first_name "John"+ :last_name "Smith"+ :common_name "John Smith"+ :email "[email protected]"+ :login_attributes {"uid" "jsmith1"+ "mail" "[email protected]"+ "givenname" "John"+ "sn" "Smith""cn" "John Smith"}}(into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]"))))))))))@@ -234,10 +234,10 @@:embedded false}})](is (true? (:success? result1)))(is (true? (:success? result2)))- (is (= {:first_name "John"- :last_name "Smith"- :common_name "John Smith"- :email "[email protected]"+ (is (= {:first_name "John"+ :last_name "Smith"+ :common_name "John Smith"+ :email "[email protected]":login_attributes nil}(into {} (t2/select-one [:model/User :first_name :last_name :email :login_attributes]:email "[email protected]")))))))))))@@ -255,10 +255,10 @@:ip_address "127.0.0.1":embedded false}})](is (true? (:success? result)))- (is (= {:first_name "John"- :last_name "Smith"- :common_name "John Smith"- :email "[email protected]"}+ (is (= {:first_name "John"+ :last_name "Smith"+ :common_name "John Smith"+ :email "[email protected]"}(into {} (t2/select-one [:model/User :first_name :last_name :email] :email "[email protected]"))))))))))(deftest create-user-without-givenname-test@@ -274,9 +274,9 @@:ip_address "127.0.0.1":embedded false}})](is (true? (:success? result)))- (is (= {:first_name nil- :last_name "Miller"- :common_name "Miller"}+ (is (= {:first_name nil+ :last_name "Miller"+ :common_name "Miller"}(into {} (t2/select-one [:model/User :first_name :last_name] :email "[email protected]"))))))))))(deftest ldap-no-user-provisioning-testdiff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.cljindex 3e460282d91..4d2e8b3800d 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj@@ -6,6 +6,7 @@[metabase-enterprise.sso.integrations.token-utils :as token-utils][metabase-enterprise.sso.providers.saml :as saml.p][metabase-enterprise.sso.settings :as sso-settings]+ [metabase-enterprise.tenants.auth-provider] ;; make sure the auth provider is actually registered[metabase.appearance.settings :as appearance.settings][metabase.premium-features.token-check :as token-check][metabase.request.core :as request]@@ -523,16 +524,9 @@(-> (mt/boolean-ids-and-timestamps new-user)(dissoc :last_login))))(testing "User Invite Event is logged."- (is (= {:details {:email "[email protected]"- :first_name "New"- :last_name "User"- :user_group_memberships [{:id 1}]- :sso_source "saml"}- :model "User"- :model_id (:id new-user)- :topic :user-invited- :user_id nil}- (mt/latest-audit-log-entry :user-invited (:id new-user))))))+ (is (= "[email protected]"+ (get-in (mt/latest-audit-log-entry :user-invited (:id new-user))+ [:details :email])))))(testing "attributes"(is (= (some-saml-attributes "newuser")(saml-login-attributes "[email protected]"))))@@ -921,5 +915,174 @@(testing "only string attributes are saved to login_attributes"(let [user-attrs (t2/select-one-fn :login_attributes :model/User :email "[email protected]")](is (=? {"string_attr" "valid-string"- "number_attr" 42- "boolean_attr" true} user-attrs))))))))))))+ "number_attr" "42"+ "boolean_attr" "true"} user-attrs))))))))))))++;;; ------------------------------------------------ Tenant Tests ----------------------------------------------------++(defn- new-user-with-tenant-saml-test-response []+ (saml-response-from-file "test_resources/saml-test-response-new-user-with-tenant.xml"))++(deftest tenants-can-be-auto-provisioned-via-saml+ (with-other-sso-types-disabled!+ (mt/with-model-cleanup [:model/Tenant]+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (do-with-some-validators-disabled!+ (fn []+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response))+ (is (some? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))+ (is (t2/exists? :model/Tenant :slug "tenant-mctenantson")))+ (testing "they should be able to log in again"+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response)))))))))))))++(deftest new-users-should-be-set-to-the-correct-tenant-via-saml+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}]+ (do-with-some-validators-disabled!+ (fn []+ (mt/with-model-cleanup [:model/User]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response))+ (is (= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))+ (testing "they should be able to log in again"+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response))+ (is (= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))))))++(deftest new-users-are-not-assigned-a-tenant-if-tenants-is-not-enabled-via-saml+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant _ {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}]+ (do-with-some-validators-disabled!+ (fn []+ (mt/with-model-cleanup [:model/User]+ (mt/with-temporary-setting-values [use-tenants false]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (testing "They are able to log in"+ (is (successful-login? response)))+ (testing "But don't get assigned a tenant"+ (is (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))+ (testing "they should be able to log in without the tenant attribute configured"+ (mt/with-temporary-setting-values [saml-attribute-tenant nil]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response))+ (is (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))))))++(deftest a-user-cannot-log-in-with-a-deactivated-tenant-via-saml+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"+ :is_active false}+ :model/User {existing-email :email} {:tenant_id tenant-id}]+ (do-with-some-validators-disabled!+ (fn []+ (testing "a new user fails to log in"+ (mt/with-model-cleanup [:model/User]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 401 "/auth/sso" req-options)]+ (is (not (successful-login? response))))))+ (testing "an existing user also fails to log in"+ (with-redefs [saml.p/saml-response->attributes+ (fn [_]+ {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" existing-email+ "tenant" "tenant-mctenantson"})]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 401 "/auth/sso" req-options)]+ (is (not (successful-login? response))))))))))))))++(deftest a-tenant-cannot-be-changed-once-set-via-saml+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/Tenant _ {:slug "other"+ :name "Other"}+ :model/User {email-with-tenant :email} {:tenant_id tenant-id}]+ (do-with-some-validators-disabled!+ (fn []+ (testing "tenant -> other tenant fails with correct error message"+ (with-redefs [saml.p/saml-response->attributes+ (fn [_]+ {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-with-tenant+ "tenant" "other"})]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 401 "/auth/sso" req-options)]+ (is (not (successful-login? response))))))))))))))++(deftest external-user-requires-tenant-claim-via-saml+ (testing "External user must include tenant claim in SAML response"+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email-with-tenant :email} {:tenant_id tenant-id}]+ (do-with-some-validators-disabled!+ (fn []+ ;; Use the regular new-user response which doesn't have tenant attribute+ (with-redefs [saml.p/saml-response->attributes+ (fn [_]+ {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-with-tenant})]+ (let [req-options (saml-post-request-options (new-user-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 401 "/auth/sso" req-options)]+ (is (not (successful-login? response))))))))))))))++(deftest internal-user-cannot-have-tenant-claim-via-saml+ (testing "Internal user cannot log in with tenant claim in SAML response"+ (with-other-sso-types-disabled!+ (with-saml-default-setup!+ (mt/with-additional-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true+ saml-attribute-tenant "tenant"]+ (mt/with-temp [:model/Tenant _ {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}+ :model/User {email-without-tenant :email} {:tenant_id nil}]+ (do-with-some-validators-disabled!+ (fn []+ (with-redefs [saml.p/saml-response->attributes+ (fn [_]+ {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email-without-tenant+ "tenant" "tenant-mctenantson"})]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 401 "/auth/sso" req-options)]+ (is (not (successful-login? response))))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/stale/api_test.clj b/enterprise/backend/test/metabase_enterprise/stale/api_test.cljindex 50f826f6229..6a27a77d813 100644--- a/enterprise/backend/test/metabase_enterprise/stale/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/stale/api_test.clj@@ -32,7 +32,7 @@(mt/user-http-request :get 200 (str "collection/" (u/the-id a) "/items"):models "dashboard" :models "card")(dissoc :models)- (update :data (fn [results] (map (fn [result] (dissoc result :moderated_status :is_remote_synced)) results))))+ (update :data (fn [results] (map (fn [result] (dissoc result :moderated_status :is_remote_synced :namespace :collection_namespace)) results))))(update result :data (fn [results] (map (fn [result] (dissoc result :collection :moderated_status :card_schema)) results))))))(testing "The card and dashboard are in there"(is (= #{["card" (u/the-id card)] ["dashboard" (u/the-id dashboard)]}diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.cljindex 36dfcc11e4b..a749c4ae731 100644--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj@@ -31,7 +31,7 @@(t2/update! :model/SupportAccessGrantLog grant-id {:notes "Updated notes"})(is (some? (t2/select-one :model/Session :id session-id))"Session should still exist after non-revocation update")- (is (nil? (:expires_at (t2/select-one :model/AuthIdentity :id support-user-id)))+ (is (nil? (:expires_at (t2/select-one :model/AuthIdentity :provider "password" :user_id support-user-id)))"Auth identity expires_at should remain unchanged")))))))(deftest revoke-grant-only-affects-support-user-testdiff --git a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/api_test.cljnew file mode 100644index 00000000000..8c6308a861d--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj@@ -0,0 +1,640 @@+(ns metabase-enterprise.tenants.api-test+ (:require+ [clojure.test :refer [deftest testing is use-fixtures]]+ [metabase.collections.models.collection :as collection]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(defn with-premium-feature-fixture [f]+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (f)))++(use-fixtures :each with-premium-feature-fixture)++(deftest can-create-tenant-with-unique-name-test+ (testing "I can create a tenant with a unique name"+ (mt/with-model-cleanup [:model/Tenant]+ (mt/user-http-request :crowberto :post 200 "ee/tenant/"+ {:name "My Tenant"+ :slug "my-tenant"})+ (is (t2/exists? :model/Tenant :name "My Tenant")))))++(deftest duplicate-tenant-names-error-test+ (testing "Duplicate names results in an error"+ (mt/with-model-cleanup [:model/Tenant]+ (mt/user-http-request :crowberto :post 200 "ee/tenant/"+ {:name "My Tenant" :slug "my-tenant"})+ (is (t2/exists? :model/Tenant :name "My Tenant"))+ (is (= "This tenant name or slug is already taken."+ (mt/user-http-request :crowberto :post 400 "ee/tenant/"+ {:name "My Tenant" :slug "foo"})))+ (is (= "This tenant name or slug is already taken."+ (mt/user-http-request :crowberto :post 400 "ee/tenant/"+ {:name "Foo" :slug "my-tenant"}))))))++(deftest invalid-tenant-slug-error-test+ (testing "invalid slug results in an error"+ (mt/user-http-request :crowberto :post 400 "ee/tenant/"+ {:name "My Tenant"+ :slug "FOOBAR"})))++(deftest can-get-tenant-info+ (mt/with-temp [:model/Tenant {id1 :id} {:name "Tenant Name" :slug "sluggy" :attributes {"env" "test"}}+ :model/User _ {:tenant_id id1}]+ (is (=? {:id id1+ :name "Tenant Name"+ :is_active true+ :slug "sluggy"+ :member_count 1+ :attributes {:env "test"}+ :tenant_collection_id integer?}+ (mt/user-http-request :crowberto :get 200 (str "ee/tenant/" id1))))))++(deftest can-update-tenant-name+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Name" :slug "sluggy"}+ :model/Tenant _ {:name "Other Name" :slug "sluggy2"}]+ (is (=? {:id id+ :name "New Name"+ :slug "sluggy"+ :is_active true+ :member_count 0+ :attributes nil+ :tenant_collection_id integer?}+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id) {:name "New Name"})))+ (is (= "This name is already taken."+ (mt/user-http-request :crowberto :put 400 (str "ee/tenant/" id) {:name "Other Name"})))+ (testing "Can send current name without error"+ (is (=? {:id id+ :name "New Name"+ :slug "sluggy"+ :is_active true+ :member_count 0+ :attributes nil+ :tenant_collection_id integer?}+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id) {:name "New Name"}))))))++(deftest can-mark-tenant-as-active-or-inactive+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Name" :slug "sluggy"}]+ (is (=? {:id id+ :name "Tenant Name"+ :slug "sluggy"+ :is_active false+ :attributes nil+ :member_count 0+ :tenant_collection_id integer?}+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id) {:is_active false})))))++(deftest can-list-tenants+ (testing "I can list tenants"+ (mt/with-temp [:model/Tenant {id1 :id} {:name "Name 1" :slug "slug-1" :attributes {"env" "prod"}}+ :model/User {} {:tenant_id id1}+ :model/Tenant {id2 :id} {:name "Name 2" :slug "slug-2" :attributes {"env" "dev"}}]+ (is (=? {:data [{:id id1 :member_count 1 :attributes {:env "prod"}}+ {:id id2 :member_count 0 :attributes {:env "dev"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/")))+ (is (=? {:data [{:id id1 :name "Name 1" :slug "slug-1" :attributes {:env "prod"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/?limit=1")))+ (is (=? {:data [{:id id2 :attributes {:env "dev"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/?offset=1"))))))++(deftest can-list-deactivated-tenants+ (testing "I can list deactivated tenants only"+ (mt/with-temp [:model/Tenant {id1 :id} {:name "Name 1" :slug "slug-1" :attributes {"status" "active"}}+ :model/User {} {:tenant_id id1}+ :model/Tenant {id2 :id} {:name "Name 2" :slug "slug-2" :is_active false :attributes {"status" "inactive"}}+ :model/User {} {:tenant_id id2}]+ (is (=? {:data [{:id id1 :member_count 1 :attributes {:status "active"}}+ {:id id2 :member_count 1 :attributes {:status "inactive"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/")))+ (is (=? {:data [{:id id1 :member_count 1 :attributes {:status "active"}}+ {:id id2 :member_count 1 :attributes {:status "inactive"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/?status=all")))+ (is (=? {:data [{:id id1 :member_count 1 :attributes {:status "active"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/?status=active")))+ (is (=? {:data [{:id id2 :member_count 1 :attributes {:status "inactive"}}]}+ (mt/user-http-request :crowberto :get 200 "ee/tenant/?status=deactivated"))))))++(deftest tenant-users-can-only-list-tenant-recipients-visibility-all-test+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Tenant" :slug "tenant-slug"}+ :model/Tenant {other-tenant-id :id} {:name "Other Tenant" :slug "other-tenant-slug"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/User {other-tenant-user-id :id} {:tenant_id other-tenant-id}+ :model/User {normal-user-id :id} {}]+ (let [get-recipient-ids (fn [user-id]+ (->> (mt/user-http-request user-id :get 200 "user/recipients")+ :data+ (filter #(contains? #{tenant-user-id normal-user-id other-tenant-user-id} (:id %)))+ (map :id)+ (into #{})))]+ (mt/with-temporary-setting-values [user-visibility :all+ use-tenants true]+ (is (=? #{normal-user-id} (get-recipient-ids normal-user-id)))+ (is (=? #{tenant-user-id} (get-recipient-ids tenant-user-id)))+ (is (=? #{other-tenant-user-id} (get-recipient-ids other-tenant-user-id)))+ ;; note that even superusers only see recipients in the same tenant - maybe revisit this?+ (is (=? #{tenant-user-id+ other-tenant-user-id+ normal-user-id} (get-recipient-ids :crowberto)))))))++(deftest tenant-users-can-only-list-tenant-recipients-visibility-group-test+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Tenant" :slug "tenant-slug"}+ :model/Tenant {other-tenant-id :id} {:name "Other Tenant" :slug "other-tenant-slug"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/User {other-tenant-user-id :id} {:tenant_id other-tenant-id}+ :model/User {normal-user-id :id} {}]+ (let [get-recipient-ids (fn [user-id]+ (->> (mt/user-http-request user-id :get 200 "user/recipients")+ :data+ (filter #(contains? #{tenant-user-id normal-user-id other-tenant-user-id} (:id %)))+ (map :id)+ (into #{})))]+ (mt/with-temporary-setting-values [user-visibility :group+ use-tenants true]+ (is (=? #{normal-user-id} (get-recipient-ids normal-user-id)))+ (is (=? #{tenant-user-id} (get-recipient-ids tenant-user-id)))+ (is (=? #{other-tenant-user-id} (get-recipient-ids other-tenant-user-id)))+ (is (=? #{tenant-user-id+ other-tenant-user-id+ normal-user-id} (get-recipient-ids :crowberto)))))))++(deftest tenant-users-can-only-list-tenant-recipients-visibility-none-test+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Tenant" :slug "tenant-slug"}+ :model/Tenant {other-tenant-id :id} {:name "Other Tenant" :slug "other-tenant-slug"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/User {other-tenant-user-id :id} {:tenant_id other-tenant-id}+ :model/User {normal-user-id :id} {}]+ (let [get-recipient-ids (fn [user-id]+ (->> (mt/user-http-request user-id :get 200 "user/recipients")+ :data+ (filter #(contains? #{tenant-user-id normal-user-id other-tenant-user-id} (:id %)))+ (map :id)+ (into #{})))]+ (mt/with-temporary-setting-values [user-visibility :none+ use-tenants true]+ (is (=? #{normal-user-id} (get-recipient-ids normal-user-id)))+ (is (=? #{tenant-user-id} (get-recipient-ids tenant-user-id)))+ (is (=? #{other-tenant-user-id} (get-recipient-ids other-tenant-user-id)))+ (is (=? #{tenant-user-id+ other-tenant-user-id+ normal-user-id} (get-recipient-ids :crowberto)))))))++(deftest list-users-can-list-tenant-users+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Tenant" :slug "tenant-slug"}+ :model/Tenant {other-tenant-id :id} {:name "Other Tenant" :slug "other-tenant-slug"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/User {other-tenant-user-id :id} {:tenant_id other-tenant-id}+ :model/User {normal-user-id :id} {}]+ (let [get-users (fn [& query-params]+ (->> (mt/user-http-request :crowberto :get 200 (apply str "user?" query-params))+ :data+ (filter #(contains? #{tenant-user-id normal-user-id other-tenant-user-id} (:id %)))+ (sort-by :id)))]+ (is (=? [{:id normal-user-id :tenant_id nil}] (get-users)))+ (is (=? [{:id tenant-user-id :tenant_id tenant-id}] (get-users "tenant_id=" tenant-id)))+ (is (=? [{:id other-tenant-user-id :tenant_id other-tenant-id}] (get-users "tenant_id=" other-tenant-id)))+ (is (=? [{:id normal-user-id}] (get-users "tenancy=internal")))+ (is (=? [{:id tenant-user-id}+ {:id other-tenant-user-id}+ {:id normal-user-id}]+ (get-users "tenancy=all")))+ (is (=? [{:id tenant-user-id}+ {:id other-tenant-user-id}]+ (get-users "tenancy=external")))+ (is (= "You cannot specify both `tenancy` and `tenant_id`"+ ;; even though this makes sense as a query (it's just redundant), let's just prohibit specifying both+ (mt/user-http-request :crowberto :get 400 (str "user?tenancy=external&tenant_id=" tenant-id)))))))++(deftest users-are-deactivated-with-tenants+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Tenant" :slug "tenant-slug"}+ :model/User {user-id :id} {:tenant_id tenant-id}+ :model/User {other-user-id :id} {:tenant_id tenant-id}]+ (let [active? (fn [user-id]+ (t2/select-one-fn :is_active :model/User :id user-id))]+ ;; setup: deactivate "other user", do a sanity check to make sure one is active, one is not+ (mt/user-http-request :crowberto :delete 200 (str "user/" other-user-id))+ (testing "Sanity check, user starts activated"+ (is (active? user-id))+ (is (not (active? other-user-id))))+ ;; deactivate the tenant+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active false})+ (testing "After deactivating the tenant, both users are deactivated"+ (is (not (active? user-id)))+ (is (not (active? other-user-id))))+ (testing "After deactivating the tenant, it's not possible to reactivate either user"+ (mt/user-http-request :crowberto :put 400 (str "user/" user-id "/reactivate"))+ (mt/user-http-request :crowberto :put 400 (str "user/" other-user-id "/reactivate")))+ ;; reactivate the tenant+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" tenant-id) {:is_active true})+ (testing "After reactivating the tenant, only one user is reactivated"+ (is (active? user-id))+ (is (not (active? other-user-id))))+ (testing "Now that the tenant is active, it's possible to reactivate a user"+ (mt/user-http-request :crowberto :put 200 (str "user/" other-user-id "/reactivate"))))))++(deftest can-create-tenant-with-valid-attributes-test+ (testing "Can create tenant with valid attributes"+ (mt/with-model-cleanup [:model/Tenant]+ (let [tenant-data {:name "Tenant with Attributes"+ :slug "tenant-attrs"+ :attributes {"key1" "value1"+ "key2" "value2"+ "environment" "production"}}]+ (mt/user-http-request :crowberto :post 200 "ee/tenant/" tenant-data)+ (let [created-tenant (t2/select-one :model/Tenant :name "Tenant with Attributes")]+ (is (some? created-tenant))+ (is (= {"key1" "value1"+ "key2" "value2"+ "environment" "production"}+ (:attributes created-tenant))))))))++(deftest can-create-tenant-with-keyword-attributes-test+ (testing "Can create tenant with keyword attributes (converted to strings)"+ (mt/with-model-cleanup [:model/Tenant]+ (let [tenant-data {:name "Tenant with Keyword Attrs"+ :slug "tenant-kw-attrs"+ :attributes {:region "us-east"+ :tier "premium"}}]+ (mt/user-http-request :crowberto :post 200 "ee/tenant/" tenant-data)+ (let [created-tenant (t2/select-one :model/Tenant :name "Tenant with Keyword Attrs")]+ (is (some? created-tenant))+ ;; Keywords are converted to strings in the JSON storage+ (is (= {"region" "us-east"+ "tier" "premium"}+ (:attributes created-tenant))))))))++(deftest cannot-create-tenant-with-at-prefix-attributes-test+ (testing "Cannot create tenant with attributes starting with @"+ (mt/with-model-cleanup [:model/Tenant]+ (let [tenant-data {:name "Invalid Tenant"+ :slug "invalid-tenant"+ :attributes {"@system" "value"+ "valid-key" "value"}}+ response (mt/user-http-request :crowberto :post 400 "ee/tenant/" tenant-data)]+ (is (contains? (:errors response) :attributes))+ (is (contains? (:specific-errors response) :attributes))+ (is (contains? (get-in response [:specific-errors :attributes]) (keyword "@system")))))))++(deftest can-update-tenant-attributes-via-put-test+ (testing "Can update tenant attributes via PUT"+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Test"+ :slug "test-tenant"+ :attributes {"initial" "value"}}]+ (let [updated-attrs {"updated" "new-value"+ "environment" "staging"}+ response (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id)+ {:attributes updated-attrs})]+ (is (= updated-attrs (:attributes (t2/select-one :model/Tenant :id id))))+ (is (=? {:id id+ :name "Tenant Test"+ :slug "test-tenant"+ :is_active true+ :member_count 0+ :tenant_collection_id integer?}+ (dissoc response :attributes)))))))++(deftest can-update-existing-tenant-attributes-test+ (testing "Can update existing attributes"+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Test 2"+ :slug "test-tenant-2"+ :attributes {"existing" "value"}}]+ (let [new-attrs {"existing" "value2"+ "new-key" "new-value"}]+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id)+ {:attributes new-attrs})+ (is (= new-attrs (:attributes (t2/select-one :model/Tenant :id id))))))))++(deftest can-clear-tenant-attributes-test+ (testing "Can clear attributes by setting to empty map"+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Test 3"+ :slug "test-tenant-3"+ :attributes {"to-be" "cleared"}}]+ (mt/user-http-request :crowberto :put 200 (str "ee/tenant/" id)+ {:attributes {}})+ (is (= {} (:attributes (t2/select-one :model/Tenant :id id)))))))++(deftest cannot-update-tenant-with-at-prefix-attributes-test+ (testing "Cannot update with attributes starting with @"+ (mt/with-temp [:model/Tenant {id :id} {:name "Tenant Test 4"+ :slug "test-tenant-4"+ :attributes {"valid" "value"}}]+ (let [invalid-attrs {"@system" "value"+ "valid-key" "value"}+ response (mt/user-http-request :crowberto :put 400 (str "ee/tenant/" id)+ {:attributes invalid-attrs})]+ (is (contains? (:errors response) :attributes))+ (is (contains? (:specific-errors response) :attributes))+ (is (contains? (get-in response [:specific-errors :attributes]) (keyword "@system")))+ ;; Original attributes should remain unchanged+ (is (= {"valid" "value"} (:attributes (t2/select-one :model/Tenant :id id))))))))++(deftest can-get-tenant-collections-from-tree-api+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {parent-id :id :as parent} {:namespace collection/shared-tenant-ns}+ :model/Collection {other-rooty-id :id} {:namespace collection/shared-tenant-ns}+ :model/Collection {coll-id :id} {:namespace collection/shared-tenant-ns+ :location (collection/children-location parent)}+ :model/Collection {non-tenant-coll-id :id} {}]+ (letfn [(simplify-children [children]+ (into #{} (->> children+ (filter #(contains?+ #{parent-id other-rooty-id coll-id non-tenant-coll-id}+ (:id %)))+ (map #(-> %+ (select-keys [:id :children])+ (update :children simplify-children))))))]+ (let [res (mt/user-http-request :crowberto :get 200 "collection/tree" :namespace (name collection/shared-tenant-ns))]+ (is (= #{{:id parent-id+ :children #{{:id coll-id :children #{}}}}+ {:id other-rooty-id+ :children #{}}}+ (simplify-children res))))+ (is (= #{{:id non-tenant-coll-id+ :children #{}}}+ (simplify-children+ (mt/user-http-request :crowberto :get 200 "collection/tree"))+ (simplify-children+ (mt/user-http-request :crowberto :get 200 "collection/tree")))))))+ (mt/with-temporary-setting-values [use-tenants false]+ (let [res (mt/user-http-request :crowberto :get 200 "collection/tree" :namespace (name collection/shared-tenant-ns))]+ (is (= [] res))))))++(deftest root-collection-items-does-not-include-tenant-collections+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {parent-id :id} {:namespace collection/shared-tenant-ns}]+ (is (= []+ (->> (mt/user-http-request :rasta :get 200 "collection/root/items")+ :data+ (map :id)+ (filter #(= parent-id %)))))))))++(deftest admins-can-create-shared-tenant-collections-at-root-level+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-model-cleanup [:model/Collection]+ (let [{id :id} (mt/user-http-request :crowberto :post 200 "collection/" {:namespace collection/shared-tenant-ns+ :name (mt/random-name)})+ coll (t2/select-one :model/Collection id)]+ (is (some? coll))+ (is (= collection/shared-tenant-ns (:namespace coll))))))))++(deftest tenant-collections-cant-be-created-if-tenants-disabled+ (mt/with-temporary-setting-values [use-tenants false]+ (mt/user-http-request :crowberto :post 400 "collection/" {:namespace collection/shared-tenant-ns :name (mt/random-name)})))++(deftest admins-can-create-shared-tenant-collections-as-children-of-other-collections+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {parent-id :id} {:namespace collection/shared-tenant-ns}]+ (let [id (:id (mt/user-http-request :crowberto :post 200 "collection/" {:name (mt/random-name)+ :parent_id parent-id}))+ coll (t2/select-one :model/Collection id)]+ (is (some? id))+ (is (= collection/shared-tenant-ns (:namespace coll))))))))++(deftest a-child-of-a-shared-tenant-collection-defaults-to-shared-tenant-collection-type+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {parent-id :id} {:namespace collection/shared-tenant-ns}]+ (is (= "shared-tenant-collection"+ (:namespace (mt/user-http-request :crowberto :post 200 "collection/" {:name (mt/random-name)+ :parent_id parent-id}))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Tenant Collection Protection Tests |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest cannot-archive-tenant-root-collection-test+ (testing "Cannot archive a tenant-specific-root-collection via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}]+ (testing "attempting to archive tenant root collection returns 400"+ (mt/user-http-request :crowberto :put 400 (str "collection/" tenant-collection-id)+ {:archived true}))++ (testing "tenant root collection remains unarchived"+ (is (false? (t2/select-one-fn :archived :model/Collection :id tenant-collection-id)))))))))++(deftest can-archive-tenant-collection-descendants-test+ (testing "*Can* archive descendants of tenant-specific collections via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}]+ (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)}]+ (testing "archive child collection returns 200"+ (mt/user-http-request :crowberto :put 200 (str "collection/" child-id)+ {:archived true}))++ (testing "child collection is archived"+ (is (t2/select-one-fn :archived :model/Collection :id child-id))))))))))++(deftest cannot-delete-tenant-root-collection-test+ (testing "Cannot delete a tenant-specific-root-collection via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}]+ (testing "attempting to delete tenant root collection returns 400"+ (mt/user-http-request :crowberto :delete 400 (str "collection/" tenant-collection-id)))++ (testing "tenant root collection still exists"+ (is (t2/exists? :model/Collection :id tenant-collection-id))))))))++(deftest cannot-delete-tenant-collection-descendants-test+ (testing "Cannot delete descendants of tenant collections via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}]+ (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)+ :archived true}]+ (testing "deleting the collection is allowed"+ (mt/user-http-request :crowberto :delete 200 (str "collection/" child-id)))++ (testing "child collection still exists"+ (is (not (t2/exists? :model/Collection :id child-id)))))))))))++(deftest cannot-move-tenant-root-collection-test+ (testing "Cannot move tenant-specific-root-collection to a different parent"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}+ :model/Collection {target-id :id} {:name "Target Collection"+ :location "/"+ :namespace :tenant-specific}]+ (testing "attempting to move tenant root collection returns 400"+ (mt/user-http-request :crowberto :put 400 (str "collection/" tenant-collection-id)+ {:parent_id target-id}))++ (testing "tenant root collection location remains at root"+ (is (= "/" (t2/select-one-fn :location :model/Collection :id tenant-collection-id)))))))))++(deftest can-move-tenant-descendants-within-tenant-namespace-test+ (testing "Can move tenant collection descendants within the same tenant namespace"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (mt/with-temp [:model/Collection {child-a-id :id} {:name "Child A"+ :namespace :tenant-specific+ :location (collection/children-location tenant-coll)}+ :model/Collection {child-b-id :id} {:name "Child B"+ :namespace :tenant-specific+ :location (collection/children-location tenant-coll)}]+ (testing "can move child B under child A"+ (mt/user-http-request :crowberto :put 200 (str "collection/" child-b-id)+ {:parent_id child-a-id})++ (is (= (str "/" tenant-collection-id "/" child-a-id "/")+ (t2/select-one-fn :location :model/Collection :id child-b-id)))))))))))++(deftest cannot-move-regular-collection-into-tenant-namespace-test+ (testing "Can move regular collection into tenant namespace via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}+ :model/Collection {regular-id :id} {:name "Regular Collection" :location "/"}]+ (testing "moving regular collection into tenant namespace succeeds"+ (mt/user-http-request :crowberto :put 400 (str "collection/" regular-id)+ {:parent_id tenant-collection-id})))))))++(deftest cannot-move-tenant-collection-out-of-tenant-namespace-test+ (testing "Can move tenant collection out of tenant namespace via API"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}+ :model/Collection {target-id :id} {:name "Target Collection" :location "/"}]+ (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)}]+ (testing "moving tenant child out to regular namespace succeeds"+ (mt/user-http-request :crowberto :put 400 (str "collection/" child-id)+ {:parent_id target-id})))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Tenant Collection Visibility Tests |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest non-tenant-users-dont-see-tenant-collections-test+ (testing "Non-tenant users cannot see tenant collections"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}+ :model/User {regular-user-id :id} {}]+ (mt/user-http-request regular-user-id :get 403 (str "collection/" tenant-collection-id)))))))++(deftest tenant-users-can-read-items-in-tenant-collection-test+ (testing "Tenant users can read items in their tenant collection"+ (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"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}]+ (mt/with-temp [:model/Card {card-id :id} {:name "Tenant Card"+ :collection_id tenant-collection-id+ :database_id db-id+ :dataset_query {:database db-id+ :type :query+ :query {:source-table table-id}}}]+ (testing "tenant user can fetch collection items"+ (let [items (mt/user-http-request tenant-user-id :get 200 (str "collection/" tenant-collection-id "/items"))+ card-ids (set (map :id (:data items)))]+ (is (contains? card-ids card-id))))))))))++(deftest non-tenant-users-cannot-access-tenant-collection-items-test+ (testing "Non-tenant users get 403 when accessing tenant collection items"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Tenant Test" :slug "test"}+ :model/User {regular-user-id :id} {}]+ (testing "regular user gets 403 for tenant collection items"+ (mt/user-http-request regular-user-id :get 403 (str "collection/" tenant-collection-id "/items"))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | CRUD Operations in Tenant Collections |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest can-create-cards-in-tenant-collections-test+ (testing "Can create cards in tenant collections"+ (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"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}]+ (mt/with-perm-for-group-and-table! (perms/all-external-users-group) (mt/id :venues) :perms/view-data :unrestricted+ (mt/with-perm-for-group-and-table! (perms/all-external-users-group) (mt/id :venues) :perms/create-queries :query-builder+ (let [card-data {:name "New Card"+ :collection_id tenant-collection-id+ :visualization_settings {}+ :display "table"+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ response (mt/user-http-request tenant-user-id :post 200 "card" card-data)]+ ;; TODO look into why this is failing+ (testing "card is created in tenant collection"+ (is (some? (:id response)))+ (is (= tenant-collection-id (:collection_id response))))))))))))++(deftest can-create-dashboards-in-tenant-collections-test+ (testing "Can create dashboards in tenant collections"+ (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"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}]+ (let [dashboard-data {:name "New Dashboard"+ :collection_id tenant-collection-id}+ response (mt/user-http-request tenant-user-id :post 200 "dashboard" dashboard-data)]+ (testing "dashboard is created in tenant collection"+ (is (some? (:id response)))+ (is (= tenant-collection-id (:collection_id response))))))))))++(deftest can-update-items-in-tenant-collections-test+ (testing "Can update items in tenant collections"+ (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"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}]+ (mt/with-temp [:model/Card {card-id :id} {:name "Original Name"+ :collection_id tenant-collection-id+ :database_id db-id+ :dataset_query {:database db-id+ :type :query+ :query {:source-table table-id}}}]+ (let [response (mt/user-http-request tenant-user-id :put 200 (str "card/" card-id)+ {:name "Updated Name"})]+ (testing "card name is updated"+ (is (= "Updated Name" (:name response)))))))))))++(deftest can-archive-items-in-tenant-collections-test+ (testing "Can archive items in tenant collections"+ (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"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}]+ (mt/with-temp [:model/Card {card-id :id} {:name "Card to Archive"+ :collection_id tenant-collection-id+ :database_id db-id+ :dataset_query {:database db-id+ :type :query+ :query {:source-table table-id}}}]+ (mt/user-http-request tenant-user-id :put 200 (str "card/" card-id)+ {:archived true})+ (testing "card is archived"+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/core_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/core_test.cljnew file mode 100644index 00000000000..220f853d117--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/core_test.clj@@ -0,0 +1,124 @@+(ns metabase-enterprise.tenants.core-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.tenants.core :as tenants]+ [metabase.test :as mt]))++(deftest login-attribute-keys-disabled-feature-test+ (testing "returns empty set when tenants feature is disabled"+ (mt/with-premium-features #{}+ (is (= #{} (tenants/login-attribute-keys))))))++(deftest login-attribute-keys-disabled-setting-test+ (testing "returns empty set when use-tenants setting is false"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants false]+ (is (= #{} (tenants/login-attribute-keys)))))))++(deftest login-attribute-keys-no-tenants-test+ (testing "returns tenant.slug when tenants are enabled but no tenant models exist"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (is (= #{"@tenant.slug"} (tenants/login-attribute-keys)))))))++(deftest login-attribute-keys-with-tenant-attributes-test+ (testing "includes tenant model attributes when tenants exist"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant _ {:name "Test Tenant"+ :slug "test-tenant"+ :attributes {"environment" "production"+ "region" "us-east-1"}}+ :model/Tenant _ {:name "Dev Tenant"+ :slug "dev-tenant"+ :attributes {"environment" "development"+ "cluster" "dev-cluster"}}]+ (is (= #{"@tenant.slug" "environment" "region" "cluster"}+ (tenants/login-attribute-keys))))))))++(deftest login-attribute-keys-no-attributes-test+ (testing "handles tenants with no attributes"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant _ {:name "Empty Tenant"+ :slug "empty-tenant"}+ :model/Tenant _ {:name "Attributed Tenant"+ :slug "attributed-tenant"+ :attributes {"key" "value"}}]+ (is (= #{"@tenant.slug" "key"}+ (tenants/login-attribute-keys))))))))++(deftest login-attribute-keys-empty-attributes-test+ (testing "handles tenants with empty attributes map"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant _ {:name "Empty Attrs Tenant"+ :slug "empty-attrs-tenant"+ :attributes {}}+ :model/Tenant _ {:name "Normal Tenant"+ :slug "normal-tenant"+ :attributes {"test-key" "test-value"}}]+ (is (= #{"@tenant.slug" "test-key"}+ (tenants/login-attribute-keys))))))))++(deftest login-attributes-disabled-feature-test+ (testing "returns an empty map when tenants feature is disabled"+ (mt/with-premium-features #{}+ (is (empty? (tenants/login-attributes {:tenant_id 1}))))))++(deftest login-attributes-disabled-setting-test+ (testing "returns nil when use-tenants setting is false"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants false]+ (is (empty? (tenants/login-attributes {:tenant_id 1})))))))++(deftest login-attributes-no-tenant-id-test+ (testing "returns nil when user has no tenant_id"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (is (empty? (tenants/login-attributes {:id 1})))+ (is (empty? (tenants/login-attributes {:tenant_id nil})))))))++(deftest login-attributes-with-tenant-test+ (testing "returns tenant attributes merged with @tenant.slug"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant {tenant-id :id} {:name "Test Tenant"+ :slug "test-tenant"+ :attributes {"environment" "production"+ "region" "us-east-1"}}]+ (is (= {"environment" "production"+ "region" "us-east-1"+ "@tenant.slug" "test-tenant"}+ (tenants/login-attributes {:tenant_id tenant-id}))))))))++(deftest login-attributes-no-attributes-test+ (testing "returns only @tenant.slug when tenant has no attributes"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant {tenant-id :id} {:name "Empty Tenant"+ :slug "empty-tenant"}]+ (is (= {"@tenant.slug" "empty-tenant"}+ (tenants/login-attributes {:tenant_id tenant-id}))))))))++(deftest login-attributes-empty-attributes-test+ (testing "returns only @tenant.slug when tenant has empty attributes map"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp+ [:model/Tenant {tenant-id :id} {:name "Empty Attrs Tenant"+ :slug "empty-attrs-tenant"+ :attributes {}}]+ (is (= {"@tenant.slug" "empty-attrs-tenant"}+ (tenants/login-attributes {:tenant_id tenant-id}))))))))++(deftest login-attributes-nonexistent-tenant-test+ (testing "returns nil when tenant_id doesn't exist"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (is (empty? (tenants/login-attributes {:tenant_id 99999})))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/e2e_test.cljnew file mode 100644index 00000000000..05195f35727--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/e2e_test.clj@@ -0,0 +1,38 @@+(ns metabase-enterprise.tenants.e2e-test+ (:require+ [clojure.test :refer [deftest is]]+ [metabase.test :as mt]))++(deftest tenant-users-can-use-metabase+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (let [email (mt/random-email)+ password (mt/random-hash)]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User user {:tenant_id tenant-id+ :email email+ :password password}]+ (mt/user-http-request user :get 200 "user/current"))))))++(deftest tenant-users-can-not-use-metabase-if-their-tenant-is-disabled+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (let [email (mt/random-email)+ password (mt/random-hash)]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:is_active false}+ :model/User user {:tenant_id tenant-id+ :email email+ :password password}]+ (is (= "Unauthenticated" (mt/user-http-request user :get 401 "user/current"))))))))++(deftest tenant-users-can-not-use-metabase-if-tenants-feature-unavailable+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (let [email (mt/random-email)+ password (mt/random-hash)]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User user {:tenant_id tenant-id+ :email email+ :password password}]+ (mt/with-premium-features #{}+ (is (= "Unauthenticated" (mt/user-http-request user :get 401 "user/current")))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/model_test.cljnew file mode 100644index 00000000000..1bea44e1f6d--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/model_test.clj@@ -0,0 +1,149 @@+(ns metabase-enterprise.tenants.model-test+ (:require+ [clojure.test :refer [deftest testing is]]+ [metabase-enterprise.tenants.model :as tenants.model]+ [metabase.collections.models.collection :as collection]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Tenant Collection Creation |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest tenant-auto-creates-collection-test+ (testing "Creating a Tenant automatically creates a dedicated collection"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}]+ (testing "tenant_collection_id is set and references a valid collection"+ (is (some? tenant-collection-id))+ (is (t2/exists? :model/Collection :id tenant-collection-id)))+ (let [coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (testing "collection has correct namespace"+ (is (= :tenant-specific (:namespace coll))))+ (testing "collection has correct type"+ (is (= "tenant-specific-root-collection" (:type coll))))+ (testing "collection has correct name"+ (is (= "Tenant Collection: TestyLilTenant" (:name coll))))+ (testing "collection location is at root"+ (is (= "/" (:location coll))))))))))++(deftest tenant-collection-name-follows-tenant-name-test+ (testing "Tenant collection name includes the tenant name"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "My Company Inc" :slug "mycompany"}]+ (let [coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (is (= "Tenant Collection: My Company Inc" (:name coll)))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Collection Namespace Constraints |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest tenant-collection-children-inherit-namespace-test+ (testing "Children of tenant collections must have tenant-specific namespace"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (mt/with-temp [:model/Collection child {:name "Child Collection"+ :namespace :tenant-specific+ :location (collection/children-location tenant-coll)}]+ (testing "child has tenant-specific namespace"+ (is (= :tenant-specific (:namespace child))))+ (testing "child does NOT have tenant-specific-root-collection type"+ (is (not= "tenant-specific-root-collection" (:type child)))))))))))++(deftest tenant-collection-descendants-must-be-tenant-specific-test+ (testing "All descendants in tenant hierarchy must have tenant-specific namespace"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (mt/with-temp [:model/Collection {child-id :id} {:name "Child"+ :namespace :tenant-specific+ :location (collection/children-location tenant-coll)}+ :model/Collection grandchild {:name "Grandchild"+ :namespace :tenant-specific+ :location (str "/" tenant-collection-id "/" child-id "/")}]+ (testing "grandchild has tenant-specific namespace"+ (is (= :tenant-specific (:namespace grandchild))))+ (testing "grandchild does NOT have root collection type"+ (is (not= "tenant-specific-root-collection" (:type grandchild)))))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Helper Function Tests |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest is-dedicated-tenant-collection-or-descendant-test+ (testing "is-dedicated-tenant-collection-or-descendant? correctly identifies tenant collections"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}+ :model/Collection regular-coll {:name "Regular Collection" :location "/"}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (testing "returns true for tenant root collection"+ (is (collection/is-dedicated-tenant-collection-or-descendant? tenant-coll)))+ (testing "returns false for regular collection"+ (is (not (collection/is-dedicated-tenant-collection-or-descendant? regular-coll))))+ (mt/with-temp [:model/Collection child {:name "Child"+ :namespace "tenant-specific"+ :location (collection/children-location tenant-coll)}]+ (testing "returns true for tenant collection descendant"+ (is (collection/is-dedicated-tenant-collection-or-descendant? child))))))))))++(deftest user-tenant-collection-and-descendant-ids-test+ (testing "user->tenant-collection-and-descendant-ids returns correct collection IDs"+ (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 "TestyLilTenant" :slug "test"}+ :model/User {tenant-user-id :id} {:tenant_id tenant-id}+ :model/User {regular-user-id :id} {}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (mt/with-temp [:model/Collection {child-id :id} {:name "Child"+ :namespace "tenant-specific"+ :location (collection/children-location tenant-coll)}+ :model/Collection {grandchild-id :id} {:name "Grandchild"+ :namespace "tenant-specific"+ :location (str "/" tenant-collection-id "/" child-id "/")}]+ (testing "tenant user gets root collection and all descendants"+ (let [ids (set (tenants.model/user->tenant-collection-and-descendant-ids tenant-user-id))]+ (is (contains? ids tenant-collection-id))+ (is (contains? ids child-id))+ (is (contains? ids grandchild-id))+ (is (= 3 (count ids)))))+ (testing "regular user gets empty vector"+ (is (= [] (tenants.model/user->tenant-collection-and-descendant-ids regular-user-id)))))))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Tenant Collection Constraints |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest cannot-set-personal-owner-on-tenant-collection-test+ (testing "Tenant collections should not have personal_owner_id set"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}+ :model/User {user-id :id} {}]+ (let [tenant-coll (t2/select-one :model/Collection :id tenant-collection-id)]+ (testing "tenant root collection has no personal_owner_id"+ (is (nil? (:personal_owner_id tenant-coll))))+ (testing "attempting to set personal_owner_id should fail"+ (is (thrown-with-msg?+ Exception+ #"Personal Collections must be in the default namespace"+ (t2/update! :model/Collection tenant-collection-id+ {:personal_owner_id user-id}))))))))))++(deftest cannot-change-namespace-after-creation-test+ (testing "Cannot change namespace of tenant collection after creation"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "TestyLilTenant" :slug "test"}]+ (testing "attempting to change namespace to nil should fail"+ (is (thrown-with-msg?+ Exception+ #"cannot move a Collection to a different namespace"+ (t2/update! :model/Collection tenant-collection-id+ {:namespace nil})))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/permissions_api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/permissions_api_test.cljnew file mode 100644index 00000000000..3c7f4242135--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/permissions_api_test.clj@@ -0,0 +1,35 @@+(ns metabase-enterprise.tenants.permissions-api-test+ "Tests for `/api/permissions` endpoints with EE features."+ (:require+ [clojure.test :refer :all]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :test-users))++(deftest create-group-test+ (testing "POST /permissions/group"+ (testing "creates tenant group when is_tenant_group is true (enterprise only)"+ (mt/with-premium-features #{:tenants}+ (mt/with-model-cleanup [:model/PermissionsGroup]+ (mt/user-http-request :crowberto :post 200 "permissions/group" {:name "Tenants Group" :is_tenant_group true})+ (let [group (t2/select-one :model/PermissionsGroup :name "Tenants Group")]+ (is (some? group))+ (is (true? (:is_tenant_group group)))))))++ (testing "validates is_tenant_group parameter type"+ (testing "rejects invalid type"+ (is (= {:errors {:is_tenant_group "nullable boolean"}+ :specific-errors {:is_tenant_group '("should be a boolean, received: \"invalid\"")}}+ (mt/user-http-request :crowberto :post 400 "permissions/group" {:name "Invalid Group" :is_tenant_group "invalid"})))))))++(deftest create-group-test-enterprise-features+ (testing "POST /permissions/group enterprise feature enforcement"+ (testing "allows creating tenant groups with tenants feature enabled"+ (mt/with-premium-features #{:tenants}+ (mt/with-model-cleanup [:model/PermissionsGroup]+ (mt/user-http-request :crowberto :post 200 "permissions/group" {:name "Tenant Group EE" :is_tenant_group true})+ (let [group (t2/select-one :model/PermissionsGroup :name "Tenant Group EE")]+ (is (some? group))+ (is (true? (:is_tenant_group group)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/permissions_test.cljnew file mode 100644index 00000000000..68ef73c2802--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/permissions_test.clj@@ -0,0 +1,115 @@+(ns metabase-enterprise.tenants.permissions-test+ (:require+ [clojure.test :refer [deftest testing is]]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(deftest tenant-users-are-added-to-correct-groups+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "name" :slug "name"}+ :model/User {user-id :id} {:tenant_id tenant-id}]+ (testing "Should NOT be added to the 'All Users' group"+ (is (not (t2/exists? :model/PermissionsGroupMembership+ :user_id user-id+ :group_id (u/the-id (perms/all-users-group))))))+ (testing "Should be added to the 'All tenant users' group"+ (is (t2/exists? :model/PermissionsGroupMembership+ :user_id user-id+ :group_id (u/the-id (perms/all-external-users-group)))))))++(deftest tenant-groups-get-no-perms-on-new-dbs+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:is_tenant_group true}+ :model/Database {db-id :id} {}]+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/view-data :perm_value :blocked))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/create-queries :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/download-results :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/manage-table-metadata :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/manage-database :perm_value :no))))++(deftest new-tenant-groups-get-no-perms-on-existing-dbs+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/PermissionsGroup {group-id :id} {:is_tenant_group true}]+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/view-data :perm_value :blocked))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/create-queries :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/download-results :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/manage-table-metadata :perm_value :no))+ (is (t2/exists? :model/DataPermissions :db_id db-id :group_id group-id :perm_type :perms/manage-database :perm_value :no))))++(deftest tenant-users-and-groups+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "name" :slug "slug"}+ :model/User {tenant-user :id} {:tenant_id tenant-id}+ :model/User {normal-user :id} {}+ :model/PermissionsGroup {tenant-group :id} {:is_tenant_group true}+ :model/PermissionsGroup {normal-group :id} {:is_tenant_group false}]+ (testing "A tenant user"+ (testing "cannot be added to a normal group"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Cannot add non-tenant user to tenant-group or vice versa"+ (perms/add-user-to-group! tenant-user normal-group))))+ (testing "can be added to tenant groups"+ (perms/add-user-to-group! tenant-user tenant-group)))+ (testing "A normal user"+ (testing "cannot be added to a tenant group"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Cannot add non-tenant user to tenant-group or vice versa"+ (perms/add-user-to-group! normal-user tenant-group))))+ (testing "can be added to a normal group"+ (perms/add-user-to-group! normal-user normal-group)))))++(deftest tenant-users-cannot-be-group-managers-of-tenant-group-test+ (testing "External/tenant users cannot be made group managers of tenant groups"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/User {external-user-id :id} {:tenant_id tenant-id}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Group"+ :is_tenant_group true}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Tenant users cannot be made group managers"+ (perms/add-users-to-groups! [{:user external-user-id+ :group tenant-group-id+ :is-group-manager? true}]))))))))++(deftest tenant-users-cannot-be-group-managers-of-normal-group-test+ (testing "External/tenant users cannot be made group managers of normal groups"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/User {external-user-id :id} {:tenant_id tenant-id}+ :model/PermissionsGroup {normal-group-id :id} {:name "Normal Group"+ :is_tenant_group false}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Tenant users cannot be made group managers"+ (perms/add-users-to-groups! [{:user external-user-id+ :group normal-group-id+ :is-group-manager? true}]))))))))++(deftest tenant-users-can-be-regular-members-of-tenant-group-test+ (testing "External user can be regular member of tenant group"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/User {external-user-id :id} {:tenant_id tenant-id}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Group"+ :is_tenant_group true}]+ (is (nil? (perms/add-users-to-groups! [{:user external-user-id+ :group tenant-group-id+ :is-group-manager? false}]))))))))++(deftest tenant-users-cannot-be-members-of-normal-group-test+ (testing "External user cannot be member of normal group at all"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/User {external-user-id :id} {:tenant_id tenant-id}+ :model/PermissionsGroup {normal-group-id :id} {:name "Normal Group"+ :is_tenant_group false}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Cannot add non-tenant user to tenant-group or vice versa"+ (perms/add-users-to-groups! [{:user external-user-id+ :group normal-group-id+ :is-group-manager? false}]))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/search_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/search_test.cljnew file mode 100644index 00000000000..e82f4665832--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/search_test.clj@@ -0,0 +1,33 @@+(ns metabase-enterprise.tenants.search-test+ (:require+ [clojure.test :refer :all]+ [metabase.search.appdb.core :as search.engines.appdb]+ [metabase.search.ingestion :as search.ingestion]+ [metabase.search.test-util :as search.tu]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(comment+ ;; We need this to ensure the engine hierarchy is registered+ search.engines.appdb/keep-me)++(use-fixtures :once (fixtures/initialize :db))+(use-fixtures :each (fn [thunk] (binding [search.ingestion/*force-sync* true]+ (search.tu/with-new-search-if-available-otherwise-legacy (thunk)))))++(deftest dedicated-tenant-collection-dataset-search-test+ (testing "Search returns datasets (models) from dedicated tenant collections"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-collection-id :tenant_collection_id} {:name "Test Tenant" :slug "test-tenant"}+ :model/Card {model-name :name} {:name "Dedicated Tenant Model"+ :type :model+ :collection_id tenant-collection-id}]+ (t2/select-one :model/Collection tenant-collection-id)+ (let [results (->> (mt/user-http-request :crowberto :get 200 "search" :q "Dedicated Tenant Model")+ :data+ (filter #(= (:model %) "dataset"))+ first)]+ (testing "datasets in dedicated tenant collections are returned"+ (is (=? {:name model-name} results)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.cljnew file mode 100644index 00000000000..a5010874f6b--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj@@ -0,0 +1,211 @@+(ns metabase-enterprise.tenants.user-api-test+ (:require+ [clojure.test :refer :all]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [metabase.users.models.user-test :as user-test]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn- group-or-ids->user-group-memberships+ [group-or-ids]+ (map (fn [group-or-id] {:id (u/the-id group-or-id)}) group-or-ids))++(deftest create-tenant-user-auto-assigned-to-external-users-group-test+ (testing "POST /api/user"+ (testing "Creating a tenant user automatically assigns them to All tenant users group even when no groups are specified"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test-tenant"}]+ (let [user-name (mt/random-name)+ email (mt/random-email)]+ (mt/with-model-cleanup [:model/User]+ (mt/with-fake-inbox+ (let [resp (mt/user-http-request :crowberto :post 200 "user"+ {:first_name user-name+ :last_name user-name+ :email email+ :tenant_id tenant-id})]+ (testing "response includes user_group_memberships"+ (is (= #{{:id (:id (perms/all-external-users-group))}}+ (set (:user_group_memberships resp)))))++ (testing "user is actually assigned to all expected groups in database"+ (let [created-user (t2/select-one :model/User :email email)]+ (is (= #{"All tenant users"}+ (user-test/user-group-names created-user)))))++ (testing "tenant_id is set correctly"+ (let [created-user (t2/select-one :model/User :email email)]+ (is (= tenant-id (:tenant_id created-user)))))))))))))))++(deftest create-tenant-user-must-assign-to-external-users-group-test+ (testing "POST /api/user"+ (testing "Creating a tenant user automatically assigns them to All Tenant users group even when other groups are specified"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup group-1 {:name "Custom Group 1" :is_tenant_group true}+ :model/PermissionsGroup group-2 {:name "Custom Group 2" :is_tenant_group true}+ :model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test-tenant"}]+ (let [user-name (mt/random-name)+ email (mt/random-email)]+ (mt/with-model-cleanup [:model/User]+ (mt/with-fake-inbox+ (let [resp (mt/user-http-request :crowberto :post 400 "user"+ {:first_name user-name+ :last_name user-name+ :email email+ :tenant_id tenant-id+ :user_group_memberships (group-or-ids->user-group-memberships+ [group-1 group-2])})]+ (is (= "You cannot add or remove users to/from the 'All tenant users' group." resp))))))))))))++(deftest create-user-tenant-group-restrictions-test+ (testing "POST /api/user with tenant groups"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Group"+ :is_tenant_group true}+ :model/PermissionsGroup {normal-group-id :id} {:name "Normal Group"+ :is_tenant_group false}]+ (mt/with-model-cleanup [:model/User]+ (testing "tenant users cannot be added to non-tenant groups via POST"+ (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}+ (mt/user-http-request :crowberto :post 400 "user"+ {:first_name "External"+ :last_name "User"+ :email (mt/random-email)+ :tenant_id tenant-id+ :user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}+ {:id normal-group-id}]}))))++ (testing "internal users cannot be added to tenant groups via POST"+ (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}+ (mt/user-http-request :crowberto :post 400 "user"+ {:first_name "Internal"+ :last_name "User"+ :email (mt/random-email)+ :user_group_memberships [{:id (u/the-id (perms/all-users-group))}+ {:id tenant-group-id}]}))))))))))++(deftest update-user-tenant-group-restrictions-test+ (testing "PUT /api/user/:id with tenant groups"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Group"+ :is_tenant_group true}+ :model/PermissionsGroup {normal-group-id :id} {:name "Normal Group"+ :is_tenant_group false}]++ (testing "tenant users cannot be added to non-tenant groups via PUT"+ (mt/with-temp [:model/User {external-user-id :id} {:tenant_id tenant-id}]+ (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}+ (mt/user-http-request :crowberto :put 400 (str "user/" external-user-id)+ {:user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}+ {:id normal-group-id}]})))))++ (testing "internal users cannot be added to tenant groups via PUT"+ (mt/with-temp [:model/User {internal-user-id :id} {}]+ (is (=? {:message "Cannot add non-tenant user to tenant-group or vice versa"}+ (mt/user-http-request :crowberto :put 400 (str "user/" internal-user-id)+ {:user_group_memberships [{:id (u/the-id (perms/all-users-group))}+ {:id tenant-group-id}]}))))))))))++(deftest external-user-group-manager-restrictions-test+ (testing "Tenant users cannot be made group managers"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "Test Tenant" :slug "test"}+ :model/PermissionsGroup {tenant-group-id :id} {:name "Tenant Group"+ :is_tenant_group true}]++ (testing "cannot create tenant user as group manager via POST"+ (mt/with-model-cleanup [:model/User]+ (is (=? {:message "Tenant users cannot be made group managers"}+ (mt/user-http-request :crowberto :post 400 "user"+ {:first_name "External"+ :last_name "Manager"+ :email (mt/random-email)+ :tenant_id tenant-id+ :user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}+ {:id tenant-group-id+ :is_group_manager true}]})))))++ (testing "cannot make external user group manager via PUT"+ (mt/with-temp [:model/User {external-user-id :id} {:tenant_id tenant-id}]+ ;; This test is expected to fail until group manager restrictions are implemented+ (is (=? {:message "Tenant users cannot be made group managers"}+ (mt/user-http-request :crowberto :put 400 (str "user/" external-user-id)+ {:user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}+ {:id tenant-group-id+ :is_group_manager true}]}))))))))))++(deftest tenant-users-can-be-converted-to-internal-users-test+ (testing "Tenant users can be converted to internal users"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User {user-id :id} {:tenant_id tenant-id}+ :model/PermissionsGroup {pg-id :id} {:is_tenant_group true}+ :model/PermissionsGroupMembership _ {:user_id user-id+ :group_id pg-id}]+ (testing "before: the user is a member of the All tenant users group and the group we added them to"+ (is (= #{(u/the-id (perms/all-external-users-group))+ pg-id}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))))+ ;; make the change+ (mt/user-http-request :crowberto :put 200 (str "user/" user-id) {:tenant_id nil})+ (testing "the user is now a normal user"+ (is (nil? (t2/select-one-fn :tenant_id :model/User user-id))))+ (testing "the user is now ONLY a member of the All Users group"+ (is (= #{(u/the-id (perms/all-users-group))}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id)))))))))++(deftest internal-users-can-be-converted-to-tenant-users-test+ (testing "internal users can be converted to tenant users"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User {user-id :id} {}+ :model/PermissionsGroup {pg-id :id} {:is_tenant_group false}+ :model/PermissionsGroupMembership _ {:user_id user-id+ :group_id pg-id}]+ (testing "before: the user is a member of the All Users group and the group we added them to"+ (is (= #{(u/the-id (perms/all-users-group))+ pg-id}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))))+ ;; make the change+ (mt/user-http-request :crowberto :put 200 (str "user/" user-id) {:tenant_id tenant-id})+ (testing "the user is now a tenant user"+ (is (= tenant-id (t2/select-one-fn :tenant_id :model/User user-id))))+ (testing "the user is now ONLY a member of All tenant users"+ (is (= #{(u/the-id (perms/all-external-users-group))}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id)))))))))++(deftest cannot-turn-an-external-user-into-a-superuser+ (testing "tenant users can't become superusers"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User {user-id :id} {:tenant_id tenant-id}]+ (mt/user-http-request :crowberto :put 400 (str "user/" user-id) {:is_superuser true}))))))++(deftest cannot-make-an-external-user-and-superuser+ (testing "can't make a user an external user + a superuser"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User {user-id :id} {}]+ (mt/user-http-request :crowberto :put 400 (str "user/" user-id) {:tenant_id tenant-id :is_superuser true}))))))++(deftest superusers-lose-admin-access-if-they-become-tenant-users+ (testing "superusers can't become tenant users"+ (mt/with-premium-features #{:tenants :advanced-permissions}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Tenant {tenant-id :id} {}+ :model/User {user-id :id} {:is_superuser true}]+ (mt/user-http-request :crowberto :put 200 (str "user/" user-id) {:tenant_id tenant-id})+ (is (= #{(u/the-id (perms/all-external-users-group))}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))))))))diff --git a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.jsx b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.jsxindex 577a06ea6f8..f0d952a4c74 100644--- a/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.jsx+++ b/enterprise/frontend/src/embedding/data-picker/saved-entity-picker/SavedEntityPicker.jsx@@ -173,7 +173,11 @@ export const SavedEntityPicker = _.compose(loadingAndErrorWrapper: false,}),Collections.loadList({- query: () => ({ tree: true, "exclude-archived": true }),+ query: () => ({+ tree: true,+ "exclude-archived": true,+ namespaces: ["", "shared-tenant-collection", "tenant-specific"],+ }),}),connect(mapStateToProps),)(InnerSavedEntityPicker);diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsxindex f6894b9ade1..8f5e9085b64 100644--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.unit.spec.tsx@@ -145,7 +145,9 @@ describe("impersonation modal", () => {it("should create impersonation", async () => {const store = await setup({ hasImpersonation: false });- await userEvent.click(await screen.findByText(/pick a user attribute/i));+ await userEvent.click(+ await screen.findByPlaceholderText("Pick a user attribute"),+ );await userEvent.click(await screen.findByText("foo"));expect(await screen.findByRole("button", { name: /save/i })).toBeEnabled();@@ -167,7 +169,9 @@ describe("impersonation modal", () => {it("should update impersonation", async () => {const store = await setup();- await userEvent.click(await screen.findByText(selectedAttribute));+ await userEvent.click(+ await screen.findByPlaceholderText("Pick a user attribute"),+ );await userEvent.click(await screen.findByText("bar"));expect(await screen.findByRole("button", { name: /save/i })).toBeEnabled();@@ -189,7 +193,9 @@ describe("impersonation modal", () => {it("should show only already selected attribute if attributes array is empty", async () => {await setup({ hasImpersonation: true, userAttributes: [] });- await screen.findByText(selectedAttribute);+ await expect(+ screen.getByPlaceholderText("Pick a user attribute"),+ ).toHaveValue(selectedAttribute);expect(await screen.findByRole("button", { name: /save/i })).toBeEnabled();});diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModalView.tsx b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModalView.tsxindex 83af0e38549..83e52e26005 100644--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModalView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModalView.tsx@@ -7,13 +7,13 @@ import Button from "metabase/common/components/Button";import ExternalLink from "metabase/common/components/ExternalLink/ExternalLink";import FormErrorMessage from "metabase/common/components/FormErrorMessage";import { FormFooter } from "metabase/common/components/FormFooter";-import FormSelect from "metabase/common/components/FormSelect";import FormSubmitButton from "metabase/common/components/FormSubmitButton";import Link from "metabase/common/components/Link/Link";import { useDocsUrl } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";-import { Form, FormProvider } from "metabase/forms";+import { Form, FormProvider, FormSelect } from "metabase/forms";import * as Errors from "metabase/lib/errors";+import { renderUserAttributesForSelect } from "metabase-enterprise/sandboxes/utils";import type Database from "metabase-lib/v1/metadata/Database";import type { UserAttributeKey } from "metabase-types/api";@@ -55,10 +55,7 @@ export const ImpersonationModalView = ({? [selectedAttribute, ...attributes]: attributes;- return selectableAttributes.map((attribute) => ({- name: attribute,- value: attribute,- }));+ return selectableAttributes;}, [attributes, selectedAttribute]);const hasAttributes = attributeOptions.length > 0;@@ -126,8 +123,10 @@ export const ImpersonationModalView = ({<FormSelectname="attribute"placeholder={t`Pick a user attribute`}- title={t`User attribute`}- options={attributeOptions}+ label={t`User attribute`}+ data={attributeOptions}+ mb="1.25rem"+ renderOption={renderUserAttributesForSelect}/><ImpersonationWarning database={database} />diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.tsindex 8edd9e2e5e6..d5c412f9ab8 100644--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts@@ -15,6 +15,7 @@ export * from "./scim";export * from "./support-access-grants";export * from "./table";export * from "./tags";+export * from "./tenants";export * from "./transform";export * from "./transform-job";export * from "./transform-tag";diff --git a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.tsindex 52b717905c0..f9fe580eb80 100644--- a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts@@ -13,7 +13,7 @@ import type {} from "metabase-types/api";import { EnterpriseApi } from "./api";-import { tag } from "./tags";+import { listTag, tag } from "./tags";export const remoteSyncApi = EnterpriseApi.injectEndpoints({endpoints: (builder) => ({@@ -87,7 +87,11 @@ export const remoteSyncApi = EnterpriseApi.injectEndpoints({url: `/api/ee/remote-sync/settings`,body: settings,}),- invalidatesTags: () => [tag("session-properties")],+ invalidatesTags: () => [+ tag("session-properties"),+ // Invalidate collection list to refresh is_remote_synced values+ listTag("collection"),+ ],}),getBranches: builder.query<GetBranchesResponse, void>({query: () => ({diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.tsindex 8eddd5500f5..a9d02e0ee14 100644--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts@@ -1,5 +1,6 @@import type { TagDescription } from "@reduxjs/toolkit/query";+import type { TagType } from "metabase/api/tags";import {TAG_TYPES,provideCollectionTags,@@ -53,7 +54,7 @@ export const ENTERPRISE_TAG_TYPES = ["library-collection",] as const;-export type EnterpriseTagType = (typeof ENTERPRISE_TAG_TYPES)[number];+export type EnterpriseTagType = TagType | (typeof ENTERPRISE_TAG_TYPES)[number];export function tag(type: EnterpriseTagType,diff --git a/enterprise/frontend/src/metabase-enterprise/api/tenants.ts b/enterprise/frontend/src/metabase-enterprise/api/tenants.tsnew file mode 100644index 00000000000..e5fb3d0e099--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/api/tenants.ts@@ -0,0 +1,60 @@+import type {+ CreateTenantInput,+ Tenant,+ UpdateTenantInput,+} from "metabase-types/api";++import { EnterpriseApi } from "./api";+import { idTag, invalidateTags, listTag } from "./tags";++export const tenantsApi = EnterpriseApi.injectEndpoints({+ endpoints: (builder) => ({+ createTenant: builder.mutation<void, CreateTenantInput>({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/tenant",+ body,+ }),+ invalidatesTags: (_, error) => invalidateTags(error, [listTag("tenant")]),+ }),+ getTenant: builder.query<Tenant, Tenant["id"]>({+ query: (id) => ({+ method: "GET",+ url: `/api/ee/tenant/${id}`,+ }),+ providesTags: (_, __, id) => [idTag("tenant", id)],+ }),+ listTenants: builder.query<+ { data: Tenant[] },+ { status: "active" | "deactivated" | "all" }+ >({+ query: (params) => ({+ method: "GET",+ url: "/api/ee/tenant",+ params,+ }),+ providesTags: [listTag("tenant")],+ }),+ updateTenant: builder.mutation<void, UpdateTenantInput>({+ query: ({ id, ...body }) => ({+ method: "PUT",+ url: `/api/ee/tenant/${id}`,+ body,+ }),+ invalidatesTags: (_, error, { id }) =>+ invalidateTags(error, [+ listTag("tenant"),+ idTag("tenant", id),+ // since users inherit tenant attributes, we can get stale caches+ "user",+ ]),+ }),+ }),+});++export const {+ useCreateTenantMutation,+ useGetTenantQuery,+ useListTenantsQuery,+ useUpdateTenantMutation,+} = tenantsApi;diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.tsxsimilarity index 77%rename from enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.tsrename to enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.tsxindex 339cffc023c..430d28d760e 100644--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.ts+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/selectors.tsx@@ -3,13 +3,14 @@ import { getIn } from "icepick";import { t } from "ttag";import _ from "underscore";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import { getDefaultGroupHasHigherAccessText } from "metabase/admin/permissions/selectors/confirmations";import {- getAdminGroup,+ getDefaultGroup,getOrderedGroups,} from "metabase/admin/permissions/selectors/data-permissions/groups";import { getGroupNameLocalized, isAdminGroup } from "metabase/lib/groups";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { Group } from "metabase-types/api";import { APPLICATION_PERMISSIONS_OPTIONS } from "./constants";@@ -63,6 +64,8 @@ const getPermission = (groupId: number,defaultGroup: Group,permissionKey: ApplicationPermissionKey,+ isDisabled: boolean,+ tooltip: string | null = null,) => {const value = getApplicationPermission(permissions, groupId, permissionKey);const defaultGroupValue = getApplicationPermission(@@ -75,9 +78,11 @@ const getPermission = (return {permission: permissionKey,- isDisabled: isAdmin,+ isDisabled,warning,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : tooltip,value: getApplicationPermission(permissions, groupId, permissionKey),options: [APPLICATION_PERMISSIONS_OPTIONS.yes,@@ -90,39 +95,54 @@ export const getApplicationPermissionEditor = createSelector((state: ApplicationPermissionsState) =>state.plugins.applicationPermissionsPlugin?.applicationPermissions,getOrderedGroups,- getAdminGroup,+ getDefaultGroup,(permissions, groups: Group[][], defaultGroup?: Group) => {if (!permissions || groups == null || !defaultGroup) {return null;}- const entities = groups.flat().map((group) => {+ const allGroups = groups.flat();++ const externalUsersGroup = _.find(+ allGroups,+ PLUGIN_TENANTS.isExternalUsersGroup,+ );++ const entities = allGroups.map((group) => {const isAdmin = isAdminGroup(group);+ const isExternal =+ !!externalUsersGroup && PLUGIN_TENANTS.isTenantGroup(group);return {id: group.id,name: getGroupNameLocalized(group),+ icon: isExternal ? <PLUGIN_TENANTS.TenantGroupHintIcon /> : undefined,permissions: [getPermission(permissions,isAdmin,group.id,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,"setting",+ isAdmin || isExternal,+ isExternal ? Messages.EXTERNAL_USERS_NO_ACCESS_SETTINGS : null,),getPermission(permissions,isAdmin,group.id,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,"monitoring",+ isAdmin || isExternal,+ isExternal ? Messages.EXTERNAL_USERS_NO_ACCESS_MONITORING : null,),getPermission(permissions,isAdmin,group.id,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,"subscription",+ isAdmin,),],};diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js b/enterprise/frontend/src/metabase-enterprise/audit_app/index.jsindex b785f74927c..079a7ec89f9 100644--- a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/index.js@@ -1,6 +1,7 @@import { t } from "ttag";import { ForwardRefLink } from "metabase/common/components/Link";+import { isInternalUser } from "metabase/lib/urls";import {PLUGIN_ADMIN_USER_MENU_ITEMS,PLUGIN_ADMIN_USER_MENU_ROUTES,@@ -22,7 +23,11 @@ export function initializePlugin() {const menuItemFunction = (user) => [<Menu.Itemcomponent={ForwardRefLink}- to={`/admin/people/${user.id}/unsubscribe`}+ to={+ isInternalUser(user)+ ? `/admin/people/${user.id}/unsubscribe`+ : `/admin/tenants/people/${user.id}/unsubscribe`+ }key="unsubscribe">{t`Unsubscribe from all subscriptions / alerts`}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsxindex b25175557e0..33cbba3a3a0 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx@@ -143,6 +143,15 @@ export const SettingsJWTForm = () => {settingDetails?.["jwt-attribute-groups"],)}/>+ {settingValues["use-tenants"] && (+ <FormTextInput+ name="jwt-attribute-tenant"+ label={t`Tenant assignment attribute`}+ {...getExtraFormFieldProps(+ settingDetails?.["jwt-attribute-tenant"],+ )}+ />+ )}</Stack></FormSection><FormSection title={"Group Sync"} data-testid="jwt-group-schema">@@ -183,6 +192,7 @@ const getFormValues = ("jwt-attribute-firstname","jwt-attribute-lastname","jwt-attribute-groups",+ "jwt-attribute-tenant",]);if (jwtSettings["jwt-user-provisioning-enabled?"] == null) {diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsxindex f2488b50657..d1545c00c0c 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx@@ -21,7 +21,10 @@ const GROUPS = [];const setup = async (- settingValues?: Partial<JWTFormValues> & { "jwt-enabled"?: boolean },+ settingValues?: Partial<JWTFormValues> & {+ "jwt-enabled"?: boolean;+ "use-tenants"?: boolean;+ },) => {const settings = createMockSettings(settingValues);setupSettingsEndpoints([]);@@ -45,6 +48,7 @@ describe("SettingsJWTForm", () => {"jwt-attribute-firstname": "John","jwt-attribute-lastname": "Doe","jwt-attribute-groups": "grouper",+ "jwt-attribute-tenant": null,"jwt-enabled": true,"jwt-group-sync": true,};@@ -93,6 +97,45 @@ describe("SettingsJWTForm", () => {expect(body).toEqual(ATTRS);});+ it("should not show tenant attribute unless tenanting is on", async () => {+ await setup();++ expect(+ screen.queryByText(/Tenant assignment attribute/),+ ).not.toBeInTheDocument();+ });++ it("should show tenant attribute when tenanting is on", async () => {+ await setup({ "use-tenants": true });++ await userEvent.type(+ await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),+ ATTRS["jwt-identity-provider-uri"],+ );+ await userEvent.type(+ await screen.findByRole("textbox", {+ name: /String used by the JWT signing key/,+ }),+ ATTRS["jwt-shared-secret"],+ );++ await userEvent.type(+ await screen.findByRole("textbox", {+ name: /Tenant assignment attribute/,+ }),+ "Cat",+ );++ await userEvent.click(await screen.findByRole("button", { name: /Save/ }));++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ const [{ url, body }] = puts;++ expect(url).toMatch(/\/api\/setting$/);+ expect(body).toHaveProperty("jwt-attribute-tenant", "Cat");+ });+it("User provisioning should not appear if JWT has not been enabled", async () => {await setup({ "jwt-enabled": false });diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsxindex 7157f1b2ad4..68f01c7ef30 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx@@ -39,6 +39,7 @@ export type SAMLFormSettings = Pick<| "saml-attribute-email"| "saml-attribute-firstname"| "saml-attribute-lastname"+ | "saml-attribute-tenant"| "saml-identity-provider-uri"| "saml-identity-provider-issuer"| "saml-identity-provider-certificate"@@ -151,6 +152,16 @@ export function SettingsSAMLForm() {settingDetails?.["saml-attribute-lastname"],)}/>+ {settingValues["use-tenants"] && (+ <FormTextInput+ name="saml-attribute-tenant"+ label={t`Tenant assignment attribute`}+ hasCopyButton+ {...getExtraFormFieldProps(+ settingDetails?.["saml-attribute-tenant"],+ )}+ />+ )}</Stack></FormSection>@@ -284,6 +295,7 @@ const getFormValues = ("saml-attribute-email","saml-attribute-firstname","saml-attribute-lastname",+ "saml-attribute-tenant","saml-identity-provider-uri","saml-identity-provider-issuer","saml-identity-provider-certificate",diff --git a/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.tsx b/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.tsxindex 28ba6cc3f6e..62b7891bca1 100644--- a/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.tsx@@ -30,6 +30,7 @@ import {UnstyledButton,} from "metabase/ui";import { useUpdateRouterDatabaseMutation } from "metabase-enterprise/api";+import { renderUserAttributesForSelect } from "metabase-enterprise/sandboxes/utils";import * as Urls from "metabase-enterprise/urls";import type { Database } from "metabase-types/api";import { isEngineKey } from "metabase-types/guards";@@ -177,6 +178,7 @@ export const DatabaseRoutingSection = ({disabled={!isAdmin || !!disabledFeatMsg}value={userAttribute}onChange={handleUserAttributeChange}+ renderOption={renderUserAttributesForSelect}/></Tooltip></Flex>diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.tsindex d5be49277cd..83e555f97bf 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.ts@@ -1,7 +1,7 @@import { push } from "react-router-redux";import { t } from "ttag";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import {getPermissionWarning,getPermissionWarningModal,@@ -89,6 +89,7 @@ export const buildDataModelPermission = (entityId: EntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,defaultGroup: Group,permissionSubject: PermissionSubject,@@ -132,12 +133,16 @@ export const buildDataModelPermission = (return {permission: DataPermission.DATA_MODEL,type: DataPermissionType.DATA_MODEL,- isDisabled: isAdmin,+ isDisabled: isAdmin || isExternal,warning,confirmations,value,isHighlighted: isAdmin,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : isExternal+ ? Messages.EXTERNAL_USERS_NO_ACCESS_DATABASE+ : null,options: [DATA_MODEL_PERMISSION_OPTIONS.none,...(hasChildEntities ? [DATA_MODEL_PERMISSION_OPTIONS.controlled] : []),diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.unit.spec.tsindex 9e0504088be..911e92c6383 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/data-model-permission.unit.spec.ts@@ -31,6 +31,7 @@ const getPermissionGraph = (value = "all"): GroupsPermissions =>const isAdmin = true;const isNotAdmin = false;+const isNotExternal = false;const defaultGroup: Group = {id: defaultGroupId,@@ -43,6 +44,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -58,6 +60,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -74,6 +77,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -89,6 +93,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -98,6 +103,7 @@ describe("buildDataModelPermission", () => {{ databaseId, schemaName: "schema" },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"tables",@@ -118,6 +124,7 @@ describe("buildDataModelPermission", () => {{ databaseId, schemaName: "schema", tableId: 1 },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"fields",@@ -138,6 +145,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -156,6 +164,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph("none"),defaultGroup,"schemas",@@ -175,6 +184,7 @@ describe("buildDataModelPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph("block"),defaultGroup,"schemas",diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.tsindex 7d1e1db825d..d39badbc2f5 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.ts@@ -1,7 +1,7 @@import { getIn } from "icepick";import { t } from "ttag";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import {getPermissionWarning,getPermissionWarningModal,@@ -50,6 +50,7 @@ export const buildDetailsPermission = (entityId: EntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,defaultGroup: Group,permissionSubject: PermissionSubject,@@ -89,11 +90,15 @@ export const buildDetailsPermission = (permission: DataPermission.DETAILS,type: DataPermissionType.DETAILS,value,- isDisabled: isAdmin,+ isDisabled: isAdmin || isExternal,isHighlighted: isAdmin,warning,confirmations,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : isExternal+ ? Messages.EXTERNAL_USERS_NO_ACCESS_DATABASE+ : null,options: [DETAILS_PERMISSION_OPTIONS.no, DETAILS_PERMISSION_OPTIONS.yes],};};diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.unit.spec.tsindex 7edfdb2410e..c26b2474bc2 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/details-permission.unit.spec.ts@@ -27,6 +27,7 @@ const getPermissionGraph = (value = "yes"): GroupsPermissions =>const isAdmin = true;const isNotAdmin = false;+const isNotExternal = false;const defaultGroup: Group = {id: defaultGroupId,@@ -39,6 +40,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"fields",@@ -48,6 +50,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"tables",@@ -62,6 +65,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -78,6 +82,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -92,6 +97,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -109,6 +115,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph(),defaultGroup,"schemas",@@ -127,6 +134,7 @@ describe("buildDetailsPermission", () => {{ databaseId },groupId,isNotAdmin,+ isNotExternal,getPermissionGraph("no"),defaultGroup,"schemas",diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/download-permission.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/download-permission.tsindex f8a650b5e1a..e939908ab75 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/download-permission.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/download-permission.ts@@ -1,7 +1,7 @@import { push } from "react-router-redux";import { t } from "ttag";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import {getPermissionWarning,getPermissionWarningModal,@@ -24,16 +24,13 @@ import {import { getGroupFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";import type { Group, GroupsPermissions } from "metabase-types/api";-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045-export const UNABLE_TO_DOWNLOAD_RESULTS = t`Groups with Block data access can't download results`;-const getTooltipMessage = (isAdmin: boolean, isBlockedAccess: boolean) => {if (isAdmin) {- return UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;+ return Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;}if (isBlockedAccess) {- return UNABLE_TO_DOWNLOAD_RESULTS;+ return Messages.UNABLE_TO_DOWNLOAD_RESULTS;}return null;diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/index.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/index.tsindex f46c7d5b195..02dbde49c3a 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/permission-management/index.ts@@ -13,10 +13,12 @@ export const getFeatureLevelDataPermissions = (entityId: EntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,dataAccessPermissionValue: DataPermissionValue,defaultGroup: Group,permissionSubject: PermissionSubject,+ permissionView?: "group" | "database",) => {const downloadPermission = buildDownloadPermission(entityId,@@ -28,23 +30,29 @@ export const getFeatureLevelDataPermissions = (permissionSubject,);- const dataModelPermission = buildDataModelPermission(- entityId,- groupId,- isAdmin,- permissions,- defaultGroup,- permissionSubject,- );+ const dataModelPermission =+ (!isExternal || permissionView === "database") &&+ buildDataModelPermission(+ entityId,+ groupId,+ isAdmin,+ isExternal,+ permissions,+ defaultGroup,+ permissionSubject,+ );- const detailsPermission = buildDetailsPermission(- entityId,- groupId,- isAdmin,- permissions,- defaultGroup,- permissionSubject,- );+ const detailsPermission =+ (!isExternal || permissionView === "database") &&+ buildDetailsPermission(+ entityId,+ groupId,+ isAdmin,+ isExternal,+ permissions,+ defaultGroup,+ permissionSubject,+ );return [downloadPermission, dataModelPermission, detailsPermission].filter(Boolean,diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.tsindex f45fe7ce858..1d898eabb1b 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts@@ -28,18 +28,24 @@ export const databaseManagementPermissionAllowedPathGetter = (return canUserAccessDatabaseManagement(user) ? ["databases"] : [];};-export const getDataColumns = (subject: PermissionSubject) => {- const allSubjectsColumns = [+export const getDataColumns = (+ subject: PermissionSubject,+ isExternal?: boolean,+) => {+ const allSubjectsColumns: { name: string; hint?: string }[] = [{name: t`Download results`,hint: t`Downloads of native queries are only allowed if a group has download permissions for the entire database.`,},- {- name: t`Manage table metadata`,- },];- if (subject === "schemas") {+ if (!isExternal) {+ allSubjectsColumns.push({+ name: t`Manage table metadata`,+ });+ }++ if (subject === "schemas" && !isExternal) {allSubjectsColumns.push({name: t`Manage database`,});diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.jsindex 9db99e40043..8d2a88c474b 100644--- a/enterprise/frontend/src/metabase-enterprise/plugins.js+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js@@ -42,6 +42,7 @@ import { initializePlugin as initializeSmtpOverride } from "./smtp-override";import { initializePlugin as initializeSnippets } from "./snippets";import { initializePlugin as initializeSupport } from "./support";import { initializePlugin as initializeTableEditing } from "./table-editing";+import { initializePlugin as initializeTenants } from "./tenants";import { initializePlugin as initializeTools } from "./tools";import { initializePlugin as initializeTransforms } from "./transforms";import { initializePlugin as initializeTransformsPython } from "./transforms-python";@@ -93,4 +94,5 @@ export function initializePlugins() {initializeTransforms();initializeTransformsPython();initializeSupport();+ initializeTenants?.();}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.tsindex 0b2fb4b4f77..1e3d84229ce 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts@@ -3,7 +3,7 @@ import { trackSimpleEvent } from "metabase/lib/analytics";export const trackBranchSwitched = ({triggeredFrom,}: {- triggeredFrom: "sidebar" | "admin-settings";+ triggeredFrom: "admin-settings" | "app-bar";}) => {trackSimpleEvent({event: "remote_sync_branch_switched",@@ -26,7 +26,7 @@ export const trackPullChanges = ({triggeredFrom,force,}: {- triggeredFrom: "sidebar" | "admin-settings";+ triggeredFrom: "admin-settings" | "app-bar";force: boolean;}) => {trackSimpleEvent({@@ -40,7 +40,7 @@ export const trackPushChanges = ({triggeredFrom,force,}: {- triggeredFrom: "sidebar" | "conflict-modal";+ triggeredFrom: "app-bar" | "conflict-modal";force: boolean;}) => {trackSimpleEvent({diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsxindex 5156142255e..2249d80eaab 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx@@ -44,17 +44,29 @@ export const AllChangesView = ({}: AllChangesViewProps) => {const { data: collectionTree = [] } = useListCollectionsTreeQuery();+ // Fetch collection tree for shared-tenant-collections namespace+ // This is needed to show changes in tenant collections that have is_remote_synced=true+ const { data: tenantCollectionTree = [] } = useListCollectionsTreeQuery({+ namespace: "shared-tenant-collection",+ });+const collectionMap = useMemo(() => {- const map = buildCollectionMap(collectionTree);+ const map = new Map([+ ...buildCollectionMap(collectionTree),+ ...buildCollectionMap(tenantCollectionTree),+ ]);+ // Add all synced collections to the map, including those from namespaces.+ // This ensures that collections from namespaces like "shared-tenant-collection"+ // are available when building collection path segments.collections.forEach((c) => {- if (typeof c.id === "number" && !map.has(c.id)) {+ if (typeof c.id === "number") {map.set(c.id, c);}});return map;- }, [collectionTree, collections]);+ }, [collectionTree, tenantCollectionTree, collections]);const hasRemovals = useMemo(() => {return (diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsxindex 0aee34ac216..cdddd95596f 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx@@ -31,6 +31,9 @@ const setup = ({const collections = [createMockCollection({ name: "Entity Collection" })];fetchMock.get("/api/collection/tree", collections);+ fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", []);+ fetchMock.get("path:/api/session/properties", {});+renderWithProviders(<AllChangesView entities={entities} collections={collections} />,);@@ -58,4 +61,98 @@ describe("AllChangesView", () => {).not.toBeInTheDocument();});});++ describe("namespaced collections", () => {+ it("should display collections from namespaces like shared-tenant-collection", () => {+ const namespacedCollection = createMockCollection({+ id: 10,+ name: "Tenant Collection",+ namespace: "shared-tenant-collection",+ effective_ancestors: [],+ });+ const entityInNamespacedCollection = createMockRemoteSyncEntity({+ id: 20,+ name: "Dashboard in Tenant Collection",+ model: "dashboard",+ collection_id: 10,+ sync_status: "update",+ });++ fetchMock.get("/api/collection/tree", []);+ fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", [+ namespacedCollection,+ ]);+ fetchMock.get("path:/api/session/properties", {});++ renderWithProviders(+ <AllChangesView+ entities={[entityInNamespacedCollection]}+ collections={[namespacedCollection]}+ />,+ );++ expect(screen.getByText("Tenant Collection")).toBeInTheDocument();+ expect(+ screen.getByText("Dashboard in Tenant Collection"),+ ).toBeInTheDocument();+ });++ it("should display collection hierarchy for namespaced collections with ancestors", () => {+ const parentCollection = createMockCollection({+ id: 5,+ name: "Parent Tenant Collection",+ namespace: "shared-tenant-collection",+ });+ const childCollection = createMockCollection({+ id: 10,+ name: "Child Tenant Collection",+ namespace: "shared-tenant-collection",+ effective_ancestors: [+ { id: 5, name: "Parent Tenant Collection" } as any,+ ],+ });+ const entityInChildCollection = createMockRemoteSyncEntity({+ id: 20,+ name: "Item in Child Collection",+ model: "card",+ collection_id: 10,+ sync_status: "create",+ });++ fetchMock.get("/api/collection/tree", []);+ fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", [+ parentCollection,+ childCollection,+ ]);+ fetchMock.get("path:/api/session/properties", {});++ renderWithProviders(+ <AllChangesView+ entities={[entityInChildCollection]}+ collections={[parentCollection, childCollection]}+ />,+ );++ expect(screen.getByText("Parent Tenant Collection")).toBeInTheDocument();+ expect(screen.getByText("Child Tenant Collection")).toBeInTheDocument();+ expect(screen.getByText("Item in Child Collection")).toBeInTheDocument();+ });++ it("should display regular items in collections", () => {+ const entityInCollection = createMockRemoteSyncEntity({+ id: 20,+ name: "Regular Item",+ model: "card",+ collection_id: 1,+ sync_status: "update",+ });++ setup({+ entities: [entityInCollection],+ });++ expect(screen.getByText("Entity Collection")).toBeInTheDocument();+ expect(screen.getByText("Regular Item")).toBeInTheDocument();+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsxnew file mode 100644index 00000000000..dc1a183ee5d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx@@ -0,0 +1,70 @@+import { useCallback, useMemo } from "react";++import { useListCollectionsQuery } from "metabase/api";+import { Tree } from "metabase/common/components/tree";+import type { ITreeNodeItem } from "metabase/common/components/tree/types";+import type { CollectionTreeItem } from "metabase/entities/collections";+import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";+import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";++import { CollectionSyncStatusBadge } from "../SyncedCollectionsSidebarSection/CollectionSyncStatusBadge";++interface CollectionsNavTreeProps {+ collections: CollectionTreeItem[];+ selectedId?: number | string;+ onSelect?: (item: ITreeNodeItem) => void;+}++export const CollectionsNavTree = ({+ collections,+ selectedId,+ onSelect,+}: CollectionsNavTreeProps) => {+ // Fetch flat list to check for remote-synced collections+ const { data: collectionsList = [] } = useListCollectionsQuery({+ archived: false,+ });++ const hasRemoteSyncedCollections = useMemo(+ () => collectionsList.some((c) => c.is_remote_synced),+ [collectionsList],+ );++ const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {+ skip: !hasRemoteSyncedCollections,+ refetchOnFocus: true,+ });++ const changedCollections = useMemo(+ () => dirtyData?.changedCollections ?? {},+ [dirtyData?.changedCollections],+ );++ const showChangesBadge = useCallback(+ (itemId?: number | string) => {+ if (+ !hasRemoteSyncedCollections ||+ !changedCollections ||+ typeof itemId !== "number"+ ) {+ return false;+ }+ return !!changedCollections[itemId];+ },+ [hasRemoteSyncedCollections, changedCollections],+ );++ return (+ <Tree+ data={collections}+ selectedId={selectedId}+ onSelect={onSelect}+ TreeNode={SidebarCollectionLink}+ role="tree"+ aria-label="collection-tree"+ rightSection={(item) =>+ showChangesBadge(item?.id) && <CollectionSyncStatusBadge />+ }+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsxnew file mode 100644index 00000000000..fc4d251ca5b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx@@ -0,0 +1,216 @@+import fetchMock from "fetch-mock";+import { Route } from "react-router";++import {+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { Collection } from "metabase-types/api";+import {+ createMockCollection,+ createMockSettings,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import { CollectionsNavTree } from "./CollectionsNavTree";++const createMockCollectionTreeItem = (+ overrides: Partial<Collection> = {},+): Collection => ({+ ...createMockCollection({+ id: 1,+ name: "Test Collection",+ is_remote_synced: false,+ ...overrides,+ }),+});++const setupEndpoints = ({+ collections = [createMockCollectionTreeItem()],+ dirty = [],+ changedCollections = {},+}: {+ collections?: Collection[];+ dirty?: { id: number; name: string; model: string; collection_id: number }[];+ changedCollections?: Record<number, boolean>;+} = {}) => {+ fetchMock.get("path:/api/collection", collections);+ fetchMock.get("path:/api/ee/remote-sync/dirty", {+ dirty,+ changedCollections,+ });+ setupPropertiesEndpoints(createMockSettings());+ setupSettingsEndpoints([]);+};++const setup = ({+ collections = [createMockCollectionTreeItem()],+ collectionsList = [createMockCollectionTreeItem()],+ dirty = [],+ changedCollections = {},+}: {+ collections?: Collection[];+ collectionsList?: Collection[];+ dirty?: { id: number; name: string; model: string; collection_id: number }[];+ changedCollections?: Record<number, boolean>;+} = {}) => {+ setupEndpoints({ collections: collectionsList, dirty, changedCollections });++ return renderWithProviders(+ <Route+ path="/"+ component={() => (+ <CollectionsNavTree+ collections={collections as any}+ selectedId={undefined}+ onSelect={jest.fn()}+ />+ )}+ />,+ {+ storeInitialState: createMockState({+ settings: mockSettings({}),+ }),+ withDND: true,+ withRouter: true,+ },+ );+};++describe("CollectionsNavTree", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("rendering", () => {+ it("should render collections tree", async () => {+ const collection = createMockCollectionTreeItem({+ name: "My Collection",+ });+ setup({ collections: [collection] });++ await waitFor(() => {+ expect(screen.getByText("My Collection")).toBeInTheDocument();+ });+ });++ it("should render multiple collections", async () => {+ const collection1 = createMockCollectionTreeItem({+ id: 1,+ name: "Collection 1",+ });+ const collection2 = createMockCollectionTreeItem({+ id: 2,+ name: "Collection 2",+ });+ setup({ collections: [collection1, collection2] });++ await waitFor(() => {+ expect(screen.getByText("Collection 1")).toBeInTheDocument();+ });+ expect(screen.getByText("Collection 2")).toBeInTheDocument();+ });+ });++ describe("dirty state badges", () => {+ it("should not show badge when no collections are remote-synced", async () => {+ const collection = createMockCollectionTreeItem({+ id: 1,+ name: "Regular Collection",+ is_remote_synced: false,+ });+ setup({+ collections: [collection],+ collectionsList: [collection],+ dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],+ changedCollections: { 1: true },+ });++ await waitFor(() => {+ expect(screen.getByText("Regular Collection")).toBeInTheDocument();+ });++ // Badge should not be present since collection is not remote-synced+ expect(+ screen.queryByTestId("remote-sync-status"),+ ).not.toBeInTheDocument();+ });++ it("should show badge when collection has dirty changes and is remote-synced", async () => {+ const collection = createMockCollectionTreeItem({+ id: 1,+ name: "Synced Collection",+ is_remote_synced: true,+ });+ setup({+ collections: [collection],+ collectionsList: [collection],+ dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],+ changedCollections: { 1: true },+ });++ await waitFor(() => {+ expect(screen.getByText("Synced Collection")).toBeInTheDocument();+ });++ await waitFor(() => {+ expect(screen.getByTestId("remote-sync-status")).toBeInTheDocument();+ });+ });++ it("should not show badge for collection without dirty changes", async () => {+ const syncedCollection = createMockCollectionTreeItem({+ id: 1,+ name: "Clean Synced Collection",+ is_remote_synced: true,+ });+ setup({+ collections: [syncedCollection],+ collectionsList: [syncedCollection],+ dirty: [],+ changedCollections: {},+ });++ await waitFor(() => {+ expect(screen.getByText("Clean Synced Collection")).toBeInTheDocument();+ });++ // Badge should not be present since there are no dirty changes+ expect(+ screen.queryByTestId("remote-sync-status"),+ ).not.toBeInTheDocument();+ });++ it("should show badge only for collections with changes", async () => {+ const dirtyCollection = createMockCollectionTreeItem({+ id: 1,+ name: "Dirty Collection",+ is_remote_synced: true,+ });+ const cleanCollection = createMockCollectionTreeItem({+ id: 2,+ name: "Clean Collection",+ is_remote_synced: true,+ });+ setup({+ collections: [dirtyCollection, cleanCollection],+ collectionsList: [dirtyCollection, cleanCollection],+ dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],+ changedCollections: { 1: true },+ });++ await waitFor(() => {+ expect(screen.getByText("Dirty Collection")).toBeInTheDocument();+ });+ expect(screen.getByText("Clean Collection")).toBeInTheDocument();++ await waitFor(() => {+ // Only one badge should be present+ const badges = screen.getAllByTestId("remote-sync-status");+ expect(badges).toHaveLength(1);+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/index.tsnew file mode 100644index 00000000000..38ac53e775b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/index.ts@@ -0,0 +1 @@+export { CollectionsNavTree } from "./CollectionsNavTree";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/BranchPicker.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsxsimilarity index 96%rename from enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/BranchPicker.tsxrename to enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsxindex 04432941987..f1b63a51c13 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/BranchPicker.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsx@@ -113,18 +113,20 @@ export const BranchPicker = ({><Combobox.Target><Button- p={0}+ px="0.5rem"+ py="1rem"size="compact-sm"- variant="subtle"+ variant="default"disabled={disabled || isLoading || isCreating}onClick={() => combobox.toggleDropdown()}- leftSection={<Icon name="git_branch" c="brand" size={14} />}+ leftSection={<Icon name="git_branch" c="text-medium" size={14} />}rightSection={isLoading || isCreating ? (<Loader size="xs" />) : (<Iconname="chevrondown"+ c="text-medium"size={12}style={{transform: combobox.dropdownOpened@@ -137,7 +139,7 @@ export const BranchPicker = ({}data-testid="branch-picker-button">- <Text fw="bold" c="brand" size="sm" lh="md" truncate>+ <Text fw="bold" c="text-medium" size="sm" lh="md" truncate>{value}</Text></Button>diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.unit.spec.tsxnew file mode 100644index 00000000000..b74c56126bf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.unit.spec.tsx@@ -0,0 +1,239 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor } from "__support__/ui";++import { BranchPicker } from "./BranchPicker";++const defaultProps = {+ value: "main",+ onChange: jest.fn(),+ disabled: false,+ isLoading: false,+ baseBranch: "main",+ allowCreate: true,+};++const setupEndpoints = () => {+ fetchMock.get("path:/api/ee/remote-sync/branches", {+ items: ["main", "develop", "feature-1"],+ });+ fetchMock.post("path:/api/ee/remote-sync/create-branch", {});+};++const setup = (props: Partial<typeof defaultProps> = {}) => {+ const onChange = jest.fn();+ const mergedProps = { ...defaultProps, onChange, ...props };++ setupEndpoints();++ renderWithProviders(<BranchPicker {...mergedProps} />);++ return { onChange };+};++describe("BranchPicker", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("rendering", () => {+ it("should render button with current branch name", () => {+ setup({ value: "main" });++ expect(screen.getByTestId("branch-picker-button")).toBeInTheDocument();+ expect(screen.getByText("main")).toBeInTheDocument();+ });++ it("should render with different branch name", () => {+ setup({ value: "feature-branch" });++ expect(screen.getByText("feature-branch")).toBeInTheDocument();+ });+ });++ describe("disabled state", () => {+ it("should disable button when disabled prop is true", () => {+ setup({ disabled: true });++ expect(screen.getByTestId("branch-picker-button")).toBeDisabled();+ });++ it("should disable button when isLoading is true", () => {+ setup({ isLoading: true });++ expect(screen.getByTestId("branch-picker-button")).toBeDisabled();+ });+ });++ describe("dropdown behavior", () => {+ it("should open dropdown when button is clicked", async () => {+ setup();++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(+ screen.getByPlaceholderText("Find or create a branch..."),+ ).toBeInTheDocument();+ });+ });++ it("should show available branches in dropdown", async () => {+ setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ // Other branches should be visible+ expect(screen.getByTestId("branch-item-develop")).toBeInTheDocument();+ });+ // Current branch (main) should not be in the list+ expect(screen.queryByTestId("branch-item-main")).not.toBeInTheDocument();+ expect(screen.getByTestId("branch-item-feature-1")).toBeInTheDocument();+ });++ it("should filter branches based on search input", async () => {+ setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(screen.getByTestId("branch-item-develop")).toBeInTheDocument();+ });++ await userEvent.type(+ screen.getByPlaceholderText("Find or create a branch..."),+ "feat",+ );++ await waitFor(() => {+ expect(screen.getByTestId("branch-item-feature-1")).toBeInTheDocument();+ });+ expect(+ screen.queryByTestId("branch-item-develop"),+ ).not.toBeInTheDocument();+ });+ });++ describe("branch selection", () => {+ it("should call onChange with branch name when branch is selected", async () => {+ const { onChange } = setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(screen.getByTestId("branch-item-develop")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByTestId("branch-item-develop"));++ expect(onChange).toHaveBeenCalledWith("develop", false);+ });+ });++ describe("branch creation", () => {+ it("should show create option when search does not match existing branches", async () => {+ setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(+ screen.getByPlaceholderText("Find or create a branch..."),+ ).toBeInTheDocument();+ });++ await userEvent.type(+ screen.getByPlaceholderText("Find or create a branch..."),+ "new-branch",+ );++ await waitFor(() => {+ expect(screen.getByTestId("create-branch-button")).toBeInTheDocument();+ });+ expect(+ screen.getByText('Create branch "new-branch"'),+ ).toBeInTheDocument();+ });++ it("should not show create option when allowCreate is false", async () => {+ setup({ value: "main", allowCreate: false });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(+ screen.getByPlaceholderText("Find or create a branch..."),+ ).toBeInTheDocument();+ });++ await userEvent.type(+ screen.getByPlaceholderText("Find or create a branch..."),+ "new-branch",+ );++ await waitFor(() => {+ expect(+ screen.queryByTestId("create-branch-button"),+ ).not.toBeInTheDocument();+ });+ });++ it("should not show create option when search matches existing branch", async () => {+ setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(+ screen.getByPlaceholderText("Find or create a branch..."),+ ).toBeInTheDocument();+ });++ await userEvent.type(+ screen.getByPlaceholderText("Find or create a branch..."),+ "develop",+ );++ await waitFor(() => {+ expect(+ screen.queryByTestId("create-branch-button"),+ ).not.toBeInTheDocument();+ });+ });++ it("should call createBranch mutation and onChange when create option is clicked", async () => {+ const { onChange } = setup({ value: "main" });++ await userEvent.click(screen.getByTestId("branch-picker-button"));++ await waitFor(() => {+ expect(+ screen.getByPlaceholderText("Find or create a branch..."),+ ).toBeInTheDocument();+ });++ await userEvent.type(+ screen.getByPlaceholderText("Find or create a branch..."),+ "new-feature",+ );++ await waitFor(() => {+ expect(screen.getByTestId("create-branch-button")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByTestId("create-branch-button"));++ await waitFor(() => {+ expect(+ fetchMock.callHistory.done("path:/api/ee/remote-sync/create-branch"),+ ).toBe(true);+ });++ await waitFor(() => {+ expect(onChange).toHaveBeenCalledWith("new-feature", true);+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsxnew file mode 100644index 00000000000..214431aaaf3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx@@ -0,0 +1,238 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { useListCollectionsTreeQuery } from "metabase/api";+import { useAdminSetting } from "metabase/api/utils";+import { isSyncedCollection } from "metabase/collections/utils";+import { useToast } from "metabase/common/hooks";+import { buildCollectionTree } from "metabase/entities/collections";+import { useSelector } from "metabase/lib/redux";+import { getUserIsAdmin } from "metabase/selectors/user";+import { Button, Icon, Loader, Tooltip } from "metabase/ui";+import {+ useGetRemoteSyncChangesQuery,+ useImportChangesMutation,+} from "metabase-enterprise/api";++import { trackBranchSwitched, trackPullChanges } from "../../analytics";+import { BRANCH_KEY, REMOTE_SYNC_KEY, TYPE_KEY } from "../../constants";+import { useSyncStatus } from "../../hooks/use-sync-status";+import { type SyncError, parseSyncError } from "../../utils";+import { PushChangesModal } from "../PushChangesModal";+import {+ SyncConflictModal,+ type SyncConflictVariant,+} from "../SyncConflictModal";++import { BranchPicker } from "./BranchPicker";++export const GitSyncControls = () => {+ const isAdmin = useSelector(getUserIsAdmin);+ const { value: isRemoteSyncEnabled } = useAdminSetting(REMOTE_SYNC_KEY);+ const { value: currentBranch } = useAdminSetting(BRANCH_KEY);+ const { value: syncType } = useAdminSetting(TYPE_KEY);++ const [importChanges, { isLoading: isImporting }] =+ useImportChangesMutation();+ const [syncConflictVariant, setSyncConflictVariant] =+ useState<SyncConflictVariant>();+ const { isRunning: isSyncTaskRunning } = useSyncStatus();++ const [nextBranch, setNextBranch] = useState<string | null>(null);+ const [showPushModal, setShowPushModal] = useState(false);+ const [sendToast] = useToast();++ const { data: dirtyData, refetch: refetchDirty } =+ useGetRemoteSyncChangesQuery(undefined, {+ skip: !isRemoteSyncEnabled,+ refetchOnFocus: true,+ });++ // Fetch collections to filter synced ones for the push modal+ const { data: collections = [] } = useListCollectionsTreeQuery(+ {+ "exclude-other-user-collections": true,+ "exclude-archived": true,+ },+ { skip: !isRemoteSyncEnabled },+ );++ const syncedCollections = useMemo(() => {+ const synced = collections.filter(isSyncedCollection);+ return buildCollectionTree(synced);+ }, [collections]);++ const isSwitchingBranch = !!nextBranch;+ const isDirty = !!(dirtyData?.dirty && dirtyData.dirty.length > 0);+ const isLoading = isSyncTaskRunning || isSwitchingBranch || isImporting;++ const changeBranch = useCallback(+ async (branch: string | null, isNewBranch?: boolean) => {+ if (branch == null) {+ console.warn("Trying to switch to null branch");+ return;+ }++ if (!isNewBranch) {+ await importChanges({ branch });++ trackBranchSwitched({+ triggeredFrom: "app-bar",+ });+ }++ setNextBranch(null);+ },+ [importChanges],+ );++ const handleBranchSelect = useCallback(+ async (branch: string, isNewBranch?: boolean) => {+ try {+ if (branch === currentBranch) {+ return;+ }++ setNextBranch(branch);++ const freshDirtyData = await refetchDirty().unwrap();+ const hasDirtyChanges = freshDirtyData.dirty.length > 0;++ if (hasDirtyChanges && !isNewBranch) {+ setSyncConflictVariant("switch-branch");+ } else {+ await changeBranch(branch, isNewBranch);+ setNextBranch(null);+ }+ } catch {+ sendToast({+ icon: "warning",+ toastColor: "error",+ message: t`Sorry, we were unable to switch branches.`,+ });+ setNextBranch(null);+ }+ },+ [currentBranch, changeBranch, refetchDirty, sendToast],+ );++ const handlePullClick = useCallback(async () => {+ if (!currentBranch) {+ return;+ }++ try {+ await importChanges({ branch: currentBranch }).unwrap();++ trackPullChanges({+ triggeredFrom: "app-bar",+ force: false,+ });++ sendToast({+ message: t`Your branch is now up to date with remote`,+ icon: "check",+ });+ } catch (error) {+ const { hasConflict, errorMessage } = parseSyncError(error as SyncError);++ if (hasConflict) {+ setSyncConflictVariant("pull");+ return;+ }++ sendToast({+ message: errorMessage || t`Failed to pull from remote`,+ icon: "warning",+ });+ }+ }, [currentBranch, importChanges, sendToast]);++ const handlePushClick = useCallback(() => {+ setShowPushModal(true);+ }, []);++ const handleClosePushModal = useCallback(() => {+ setShowPushModal(false);+ }, []);++ const handleCloseSyncConflictModal = useCallback(() => {+ setSyncConflictVariant(undefined);+ setNextBranch(null);+ }, []);++ // Don't render if remote sync is not enabled, user is not admin, or not in read-write mode+ if (+ !isRemoteSyncEnabled ||+ !isAdmin ||+ !currentBranch ||+ syncType !== "read-write"+ ) {+ return null;+ }++ return (+ <>+ <Button.Group data-testid="git-sync-controls" mr="2rem">+ <BranchPicker+ isLoading={isLoading}+ value={currentBranch}+ onChange={handleBranchSelect}+ baseBranch={currentBranch}+ />++ <Tooltip label={t`Pull from Git`}>+ <Button+ variant="default"+ size="compact-sm"+ px="0.5rem"+ py="1rem"+ onClick={handlePullClick}+ disabled={isLoading}+ aria-label={t`Pull from Git`}+ data-testid="git-pull-button"+ leftSection={+ isImporting ? (+ <Loader size="xs" />+ ) : (+ <Icon name="arrow_down" size={16} />+ )+ }+ />+ </Tooltip>++ <Tooltip label={isDirty ? t`Push to Git` : t`No changes to push`}>+ <Button+ variant="default"+ size="compact-sm"+ px="0.5rem"+ py="1rem"+ onClick={handlePushClick}+ disabled={isLoading || !isDirty}+ aria-label={t`Push to Git`}+ data-testid="git-push-button"+ leftSection={<Icon name="arrow_up" size={16} />}+ />+ </Tooltip>+ </Button.Group>++ {showPushModal && (+ <PushChangesModal+ onClose={handleClosePushModal}+ collections={syncedCollections}+ currentBranch={currentBranch}+ />+ )}++ {syncConflictVariant && (+ <SyncConflictModal+ collections={syncedCollections}+ currentBranch={currentBranch}+ nextBranch={nextBranch}+ onClose={handleCloseSyncConflictModal}+ variant={syncConflictVariant}+ />+ )}+ </>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsxnew file mode 100644index 00000000000..a1f92d9ebc4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx@@ -0,0 +1,250 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupRemoteSyncEndpoints } from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";++import { GitSyncControls } from "./GitSyncControls";+import {+ createMockDirtyEntity,+ createRemoteSyncStoreState,+ setupCollectionEndpoints,+ setupSessionEndpoints,+} from "./test-utils";++const setup = ({+ isAdmin = true,+ remoteSyncEnabled = true,+ currentBranch = "main",+ syncType = "read-write",+ dirty = [],+ branches = ["main", "develop"],+}: {+ isAdmin?: boolean;+ remoteSyncEnabled?: boolean;+ currentBranch?: string | null;+ syncType?: "read-only" | "read-write";+ dirty?: ReturnType<typeof createMockDirtyEntity>[];+ branches?: string[];+} = {}) => {+ setupRemoteSyncEndpoints({ branches, dirty });+ setupCollectionEndpoints();+ setupSessionEndpoints({ remoteSyncEnabled, currentBranch, syncType });++ return renderWithProviders(<GitSyncControls />, {+ storeInitialState: createRemoteSyncStoreState({+ isAdmin,+ remoteSyncEnabled,+ currentBranch,+ syncType,+ }),+ });+};++describe("GitSyncControls", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("visibility", () => {+ it("should not render when remote sync is disabled", async () => {+ setup({ remoteSyncEnabled: false });++ // Wait a tick to ensure component has rendered+ await waitFor(() => {+ expect(+ screen.queryByTestId("git-sync-controls"),+ ).not.toBeInTheDocument();+ });+ });++ it("should not render when user is not admin", async () => {+ setup({ isAdmin: false });++ await waitFor(() => {+ expect(+ screen.queryByTestId("git-sync-controls"),+ ).not.toBeInTheDocument();+ });+ });++ it("should not render when currentBranch is null", async () => {+ setup({ currentBranch: null });++ await waitFor(() => {+ expect(+ screen.queryByTestId("git-sync-controls"),+ ).not.toBeInTheDocument();+ });+ });++ it("should not render when sync type is read-only", async () => {+ setup({ syncType: "read-only" });++ await waitFor(() => {+ expect(+ screen.queryByTestId("git-sync-controls"),+ ).not.toBeInTheDocument();+ });+ });++ it("should render pill when all conditions are met", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByTestId("git-sync-controls")).toBeInTheDocument();+ });+ });+ });++ describe("branch picker integration", () => {+ it("should display current branch name", async () => {+ setup({ currentBranch: "main" });++ await waitFor(() => {+ expect(screen.getByTestId("branch-picker-button")).toBeInTheDocument();+ });+ expect(screen.getByText("main")).toBeInTheDocument();+ });++ it("should display different branch name", async () => {+ setup({ currentBranch: "develop" });++ await waitFor(() => {+ expect(screen.getByText("develop")).toBeInTheDocument();+ });+ });+ });++ describe("pull button", () => {+ it("should render pull button", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByTestId("git-pull-button")).toBeInTheDocument();+ });+ });++ it("should have correct aria-label", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByLabelText("Pull from Git")).toBeInTheDocument();+ });+ });++ it("should call import mutation when clicked", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByTestId("git-pull-button")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByTestId("git-pull-button"));++ await waitFor(() => {+ expect(+ fetchMock.callHistory.done("path:/api/ee/remote-sync/import"),+ ).toBe(true);+ });+ });+ });++ describe("push button", () => {+ it("should render push button", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeInTheDocument();+ });+ });++ it("should have correct aria-label", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByLabelText("Push to Git")).toBeInTheDocument();+ });+ });++ it("should be disabled when there are no changes", async () => {+ setup({ dirty: [] });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeDisabled();+ });+ });++ it("should be enabled when there are changes", async () => {+ setup({+ dirty: [createMockDirtyEntity()],+ });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeEnabled();+ });+ });++ it("should open push modal when clicked with changes", async () => {+ setup({+ dirty: [createMockDirtyEntity()],+ });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeEnabled();+ });++ await userEvent.click(screen.getByTestId("git-push-button"));++ await waitFor(() => {+ // The PushChangesModal should be rendered+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });+ });+ });++ describe("pill structure", () => {+ it("should render all three sections (branch picker, pull, push)", async () => {+ setup();++ await waitFor(() => {+ expect(screen.getByTestId("git-sync-controls")).toBeInTheDocument();+ });+ expect(screen.getByTestId("branch-picker-button")).toBeInTheDocument();+ expect(screen.getByTestId("git-pull-button")).toBeInTheDocument();+ expect(screen.getByTestId("git-push-button")).toBeInTheDocument();+ });+ });++ describe("dirty state detection", () => {+ it("should detect dirty state with updated entity", async () => {+ setup({+ dirty: [createMockDirtyEntity({ sync_status: "update" })],+ });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeEnabled();+ });+ });++ it("should detect dirty state with created entity", async () => {+ setup({+ dirty: [createMockDirtyEntity({ sync_status: "create" })],+ });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeEnabled();+ });+ });++ it("should detect dirty state with deleted entity", async () => {+ setup({+ dirty: [createMockDirtyEntity({ sync_status: "delete" })],+ });++ await waitFor(() => {+ expect(screen.getByTestId("git-push-button")).toBeEnabled();+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/index.tsnew file mode 100644index 00000000000..fc7490207cf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/index.ts@@ -0,0 +1 @@+export { GitSyncControls } from "./GitSyncControls";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/test-utils.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/test-utils.tsnew file mode 100644index 00000000000..ffd4bb23373--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/test-utils.ts@@ -0,0 +1,68 @@+import fetchMock from "fetch-mock";++import {+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import type { RemoteSyncEntity } from "metabase-types/api";+import { createMockSettings, createMockUser } from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++export const setupCollectionEndpoints = () => {+ fetchMock.get("path:/api/collection/tree", []);+};++export const setupSessionEndpoints = ({+ remoteSyncEnabled = true,+ currentBranch = "main",+ syncType = "read-write",+}: {+ remoteSyncEnabled?: boolean;+ currentBranch?: string | null;+ syncType?: "read-only" | "read-write";+} = {}) => {+ setupPropertiesEndpoints(+ createMockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-branch": currentBranch,+ "remote-sync-type": syncType,+ }),+ );+ setupSettingsEndpoints([]);+};++export const createRemoteSyncStoreState = ({+ isAdmin = true,+ remoteSyncEnabled = true,+ currentBranch = "main",+ syncType = "read-write",+}: {+ isAdmin?: boolean;+ remoteSyncEnabled?: boolean;+ currentBranch?: string | null;+ syncType?: "read-only" | "read-write";+} = {}) => {+ return createMockState({+ currentUser: createMockUser({ is_superuser: isAdmin }),+ settings: mockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-branch": currentBranch,+ "remote-sync-type": syncType,+ }),+ });+};++export const createMockDirtyEntity = (+ overrides: Partial<RemoteSyncEntity> = {},+): RemoteSyncEntity => ({+ id: 1,+ name: "Test Card",+ description: null,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: null,+ model: "card",+ sync_status: "update",+ collection_id: 1,+ ...overrides,+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsxindex bcf1972e43f..0c2156b5a16 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx@@ -61,7 +61,7 @@ export const PushChangesModal = ({});trackPushChanges({- triggeredFrom: "sidebar",+ triggeredFrom: "app-bar",force: false,});}, [commitMessage, exportChanges, currentBranch]);diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsxindex 5f95f9e6a19..131dd0cc2b5 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx@@ -8,6 +8,7 @@ import {import {useGetAdminSettingsDetailsQuery,useGetSettingsQuery,+ useListCollectionItemsQuery,} from "metabase/api";import ExternalLink from "metabase/common/components/ExternalLink";import { useDocsUrl, useSetting, useToast } from "metabase/common/hooks";@@ -21,15 +22,16 @@ import {FormSwitch,FormTextInput,} from "metabase/forms";+import { useSelector } from "metabase/lib/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";import {- Badge,Box,Button,Flex,+ Icon,Radio,Stack,Text,- Title,Tooltip,} from "metabase/ui";import {@@ -49,12 +51,14 @@ import {import {AUTO_IMPORT_KEY,BRANCH_KEY,+ COLLECTIONS_KEY,REMOTE_SYNC_KEY,REMOTE_SYNC_SCHEMA,TOKEN_KEY,TYPE_KEY,URL_KEY,} from "../../constants";+import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";import { PullChangesButton } from "./PullChangesButton";@@ -69,6 +73,19 @@ export const RemoteSyncAdminSettings = () => {const pendingConfirmationSettingsRef =useRef<RemoteSyncConfigurationSettings | null>(null);+ const isRemoteSyncEnabled = useSetting(REMOTE_SYNC_KEY);+ const useTenants = useSetting("use-tenants");+ const applicationName = useSelector(getApplicationName);++ // Fetch tenant collections to build initial sync state+ const { data: tenantCollectionsData } = useListCollectionItemsQuery(+ {+ id: "root",+ namespace: "shared-tenant-collection",+ },+ { skip: !isRemoteSyncEnabled || !useTenants },+ );+const {show: showChangeBranchConfirmation,modalContent: changeBranchConfirmationModal,@@ -173,11 +190,19 @@ export const RemoteSyncAdminSettings = () => {});const tokenValue =settingDetails?.[TOKEN_KEY]?.value ?? settingValues?.[TOKEN_KEY];++ // Build initial collection sync map from server data+ const collectionSyncMap: Record<number, boolean> = {};+ tenantCollectionsData?.data?.forEach((collection) => {+ collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;+ });+return {...values,[TOKEN_KEY]: tokenValue,+ [COLLECTIONS_KEY]: collectionSyncMap,};- }, [settingValues, settingDetails]);+ }, [settingValues, settingDetails, tenantCollectionsData]);// eslint-disable-next-line no-unconditional-metabase-links-render -- This links only shows for admins.const { url: docsUrl } = useDocsUrl(@@ -187,143 +212,153 @@ export const RemoteSyncAdminSettings = () => {},);- const isRemoteSyncEnabled = useSetting(REMOTE_SYNC_KEY);const hasUnsyncedChanges = !!dirtyData?.dirty?.length;return (- <SettingsPageWrapper>- <SettingsSection>- <Box flex={1} maw="52rem">- <Flex align="flex-end" gap="sm" mb="xs">- <Title order={2}>{t`Remote Sync`}</Title>- {isRemoteSyncEnabled && (- <Badge- style={{ textTransform: "none" }}- py={10}- px="sm"- >{t`Enabled`}</Badge>- )}- </Flex>- <Text c="text-dark" size="sm" mb="md" maw="40rem" lh="1.5rem">- {t`Keep your dashboards, questions, and collections safely backed up in Git.`}- </Text>+ <SettingsPageWrapper+ title={t`Remote Sync`}+ description={t`Keep your dashboards, questions, and collections safely backed up in Git.`}+ >+ <FormProvider+ initialValues={initialValues as RemoteSyncConfigurationSettings}+ enableReinitialize+ validationSchema={REMOTE_SYNC_SCHEMA}+ validationContext={settingValues}+ onSubmit={handleSubmit}+ >+ {({ dirty, values }) => (+ <Form disabled={!dirty}>+ <Stack gap="xl" maw="52rem">+ {!isRemoteSyncEnabled && (+ <Text c="text-medium" size="sm">+ {jt`Need help setting this up? Check out our ${(+ <ExternalLink key="link" href={docsUrl}>+ {t`setup guide`}+ </ExternalLink>+ )}.`}+ </Text>+ )}- <FormProvider- initialValues={initialValues as RemoteSyncConfigurationSettings}- enableReinitialize- validationSchema={REMOTE_SYNC_SCHEMA}- validationContext={settingValues}- onSubmit={handleSubmit}- >- {({ dirty, values }) => (- <Form disabled={!dirty}>- <Stack gap="md">- {!isRemoteSyncEnabled && (- <Text c="text-medium" size="sm">- {jt`Need help setting this up? Check out our ${(- <ExternalLink key="link" href={docsUrl}>- {t`setup guide`}- </ExternalLink>- )}.`}- </Text>- )}+ {/* Section 1: Git Settings */}+ <SettingsSection title={t`Git Settings`}>+ <FormTextInput+ name={URL_KEY}+ label={t`Repository URL`}+ placeholder="https://github.com/yourcompany/metabase-library.git"+ {...getEnvSettingProps(settingDetails?.[URL_KEY])}+ />+ <FormTextInput+ name={TOKEN_KEY}+ label={t`Access Token`}+ description={t`Personal access token with write permissions`}+ type="password"+ {...getEnvSettingProps(settingDetails?.[TOKEN_KEY])}+ />+ </SettingsSection>- <FormTextInput- name={URL_KEY}- label={t`Repository URL`}- placeholder="https://github.com/yourcompany/metabase-library.git"- {...getEnvSettingProps(settingDetails?.[URL_KEY])}- />-- <FormTextInput- name={TOKEN_KEY}- label={t`Access Token`}- description={t`Personal access token with write permissions`}- type="password"- {...getEnvSettingProps(settingDetails?.[TOKEN_KEY])}- />+ {/* Section 2: Sync Mode for this Instance */}+ <SettingsSection title={t`Sync Mode for this Instance`}>+ <FormRadioGroup name={TYPE_KEY}>+ <Stack mt="sm">+ <Tooltip+ disabled={!hasUnsyncedChanges}+ label={t`You can't switch to Read-only as you have unpublished changes.`}+ position="bottom-start"+ >+ <Box>+ <Radio+ description={t`Usually you should use this for your production ${applicationName} instance. All synced collections are read-only, and will automatically sync with the specified branch (we'd recommend syncing with main).`}+ disabled={hasUnsyncedChanges}+ label={t`Read-only`}+ value="read-only"+ />+ </Box>+ </Tooltip>+ <Radio+ value="read-write"+ label={t`Read-write`}+ description={t`This mode is generally for development or local instances of ${applicationName}. Changes you make to content in synced collections can be pushed and pulled from any git branch.`}+ />+ </Stack>+ </FormRadioGroup>+ </SettingsSection>- <FormRadioGroup name={TYPE_KEY} label={t`Remote Sync Mode`}>- <Stack mt="sm">- <Radio- value="read-write"- label={t`Read-write`}- description={t`In read-write mode, you can make changes to synced collections and pull and push from any git branch`}+ {/* Section 3: Branch to sync with (Read-only only) */}+ {values?.[TYPE_KEY] === "read-only" && (+ <SettingsSection title={t`Branch to sync with`}>+ <Flex align="center" gap="md">+ <Box style={{ flex: 1 }}>+ <FormTextInput+ name={BRANCH_KEY}+ placeholder="main"+ label={`Sync branch`}+ {...getEnvSettingProps(settingDetails?.[BRANCH_KEY])}/>- <Tooltip- disabled={!hasUnsyncedChanges}- label={t`You can't switch to Read-only as you have unpublished changes.`}- position="bottom-start"- >- <Box>- <Radio- description={t`In Read-only mode, synced collections are read-only, and automatically sync with the specified branch`}- disabled={hasUnsyncedChanges}- label={t`Read-only`}- value="read-only"- />- </Box>- </Tooltip>- </Stack>- </FormRadioGroup>-- {values?.[TYPE_KEY] === "read-only" && (- <Stack ml="1.875rem">- <Flex align="end" gap="md">- <Box style={{ flex: 1 }}>- <FormTextInput- name={BRANCH_KEY}- label={t`Sync branch`}- mr={0}- placeholder="main"- {...getEnvSettingProps(- settingDetails?.[BRANCH_KEY],- )}- />- </Box>- {isRemoteSyncEnabled && (- <PullChangesButton- branch={values?.[BRANCH_KEY] || "main"}- dirty={dirty}- forcePull- />- )}- </Flex>- <FormSwitch- size="sm"- name={AUTO_IMPORT_KEY}- label={t`Auto-sync with git`}+ </Box>+ <FormSwitch+ size="sm"+ name={AUTO_IMPORT_KEY}+ label={t`Auto-sync with git`}+ />+ </Flex>+ {isRemoteSyncEnabled && (+ <Box>+ <PullChangesButton+ branch={values?.[BRANCH_KEY] || "main"}+ dirty={dirty}+ forcePull/>- </Stack>+ </Box>)}+ </SettingsSection>+ )}- <Flex justify="end" align="center" gap="md">- <FormErrorMessage />- {isRemoteSyncEnabled && (- <Button onClick={handleDisable}>- {t`Disable Remote Sync`}- </Button>- )}- <FormSubmitButton- data-testid="remote-sync-submit-button"- label={- isRemoteSyncEnabled- ? t`Save changes`- : t`Set up Remote Sync`- }- variant="filled"- disabled={- isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]- }- flex="auto 0 0"- />- </Flex>- </Stack>- </Form>- )}- </FormProvider>- </Box>- </SettingsSection>+ {/* Section 4: Shared tenant collections to sync */}+ {isRemoteSyncEnabled && useTenants && (+ <SettingsSection+ title={t`Shared tenant collections to sync`}+ description={t`Choose which shared tenant collections to sync with git.`}+ >+ <SharedTenantCollectionsList />+ </SettingsSection>+ )}++ {/* Footer Actions - Outside Sections */}+ <Flex justify="space-between" align="center">+ <Box>+ {isRemoteSyncEnabled && (+ <Button+ c="error"+ variant="subtle"+ size="md"+ w="12rem"+ leftSection={<Icon name="close" />}+ onClick={handleDisable}+ >+ {t`Disable remote sync`}+ </Button>+ )}+ </Box>+ <Flex align="center" gap="md">+ <FormErrorMessage />+ <FormSubmitButton+ data-testid="remote-sync-submit-button"+ size="md"+ w="12rem"+ label={+ isRemoteSyncEnabled+ ? t`Save changes`+ : t`Set up Remote Sync`+ }+ variant="filled"+ disabled={isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]}+ />+ </Flex>+ </Flex>+ </Stack>+ </Form>+ )}+ </FormProvider>{changeBranchConfirmationModal}{disableConfirmationModal}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsxnew file mode 100644index 00000000000..192a54e33c6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsx@@ -0,0 +1,138 @@+import { useFormikContext } from "formik";+import { useCallback, useEffect, useMemo } from "react";+import { usePrevious } from "react-use";+import { c, t } from "ttag";++import { useListCollectionItemsQuery } from "metabase/api";+import { PLUGIN_COLLECTIONS } from "metabase/plugins";+import { Box, Flex, Icon, Loader, Switch, Text } from "metabase/ui";+import type {+ CollectionItem,+ CollectionSyncPreferences,+ RemoteSyncConfigurationSettings,+} from "metabase-types/api";++import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";++export const SharedTenantCollectionsList = () => {+ const { data, isLoading, error } = useListCollectionItemsQuery({+ id: "root",+ namespace: "shared-tenant-collection",+ });+ const { values, setFieldValue, initialValues } =+ useFormikContext<RemoteSyncConfigurationSettings>();++ const collections = data?.data ?? [];+ const syncMap: CollectionSyncPreferences = useMemo(+ () => values[COLLECTIONS_KEY] ?? {},+ [values],+ );+ const currentType = values[TYPE_KEY];+ const isReadOnly = currentType === "read-only";+ const previousType = usePrevious(currentType);++ // Reset collections to initial values when switching from read-write to read-only+ useEffect(() => {+ if (previousType === "read-write" && currentType === "read-only") {+ setFieldValue(COLLECTIONS_KEY, initialValues[COLLECTIONS_KEY] ?? {});+ }+ }, [currentType, initialValues, setFieldValue, previousType]);++ const handleToggle = useCallback(+ (collection: CollectionItem, checked: boolean) => {+ // Update form state directly via Formik context+ setFieldValue(COLLECTIONS_KEY, {+ ...syncMap,+ [collection.id]: checked,+ });+ },+ [syncMap, setFieldValue],+ );++ if (isLoading) {+ return (+ <Flex justify="center" py="lg">+ <Loader data-testid="loading-indicator" />+ </Flex>+ );+ }++ if (error) {+ return <Text c="error">{t`Failed to load shared tenant collections`}</Text>;+ }++ if (collections.length === 0) {+ return <Text c="text-medium">{t`No shared tenant collections found`}</Text>;+ }++ return (+ <Box+ style={{+ borderRadius: "var(--mantine-radius-md)",+ border: "1px solid var(--mb-color-border)",+ backgroundColor: "var(--mb-color-bg-white)",+ overflow: "hidden",+ }}+ >+ {collections.map((collection, index) => (+ <CollectionSyncRow+ key={collection.id}+ collection={collection}+ isChecked={syncMap[collection.id] ?? false}+ onToggle={handleToggle}+ isLast={index === collections.length - 1}+ isReadOnly={isReadOnly}+ />+ ))}+ </Box>+ );+};++interface CollectionSyncRowProps {+ collection: CollectionItem;+ isChecked: boolean;+ onToggle: (collection: CollectionItem, checked: boolean) => void;+ isLast: boolean;+ isReadOnly: boolean;+}++const CollectionSyncRow = ({+ collection,+ isChecked,+ onToggle,+ isLast,+ isReadOnly,+}: CollectionSyncRowProps) => {+ const canWrite = collection.can_write ?? false;+ const icon = PLUGIN_COLLECTIONS.getIcon({+ model: "collection",+ is_remote_synced: isChecked,+ });++ return (+ <Box+ p="md"+ style={{+ borderBottom: isLast ? undefined : "1px solid var(--mb-color-border)",+ }}+ >+ <Flex justify="space-between" align="center">+ <Flex align="center" gap="sm">+ <Icon name={icon.name} c={icon.color ?? "text-medium"} />+ <Text fw="medium">{collection.name}</Text>+ </Flex>+ <Flex align="center" gap="sm">+ <Switch+ size="sm"+ checked={isChecked}+ onChange={(e) => onToggle(collection, e.currentTarget.checked)}+ disabled={!canWrite || isReadOnly}+ aria-label={c("{0} is the name of a metabase collection")+ .t`Sync ${collection.name}`}+ />+ <Text>{t`Sync`}</Text>+ </Flex>+ </Flex>+ </Box>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.unit.spec.tsxnew file mode 100644index 00000000000..bae65368230--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.unit.spec.tsx@@ -0,0 +1,482 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ Form,+ FormProvider,+ FormRadioGroup,+ FormSubmitButton,+} from "metabase/forms";+import { Radio, Stack } from "metabase/ui";+import type { CollectionSyncPreferences } from "metabase-types/api";+import { createMockCollectionItem } from "metabase-types/api/mocks";++import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";++import { SharedTenantCollectionsList } from "./SharedTenantCollectionsList";++const createMockTenantCollectionItem = (+ overrides?: Partial<ReturnType<typeof createMockCollectionItem>>,+) =>+ createMockCollectionItem({+ model: "collection",+ name: "Tenant Collection",+ can_write: true,+ is_remote_synced: false,+ ...overrides,+ });++const setupEndpoints = ({+ collections = [createMockTenantCollectionItem()],+}: {+ collections?: ReturnType<typeof createMockCollectionItem>[];+} = {}) => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { data: collections },+ { name: "root-items" },+ );+};++interface SetupOpts {+ collections?: ReturnType<typeof createMockCollectionItem>[];+ initialSyncMap?: CollectionSyncPreferences;+ syncType?: "read-only" | "read-write";+}++const setup = ({+ collections = [createMockTenantCollectionItem()],+ initialSyncMap = {},+ syncType = "read-write",+}: SetupOpts = {}) => {+ setupEndpoints({ collections });++ const onSubmit = jest.fn();++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ }}+ onSubmit={onSubmit}+ >+ <Form>+ <SharedTenantCollectionsList />+ <FormSubmitButton label="Save" />+ </Form>+ </FormProvider>,+ );++ return { onSubmit };+};++// Setup with sync type toggle for testing mode switching behavior+const setupWithSyncTypeToggle = ({+ collections = [createMockTenantCollectionItem()],+ initialSyncMap = {},+ syncType = "read-write",+}: SetupOpts = {}) => {+ setupEndpoints({ collections });++ const onSubmit = jest.fn();++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ }}+ onSubmit={onSubmit}+ >+ <Form>+ <FormRadioGroup name={TYPE_KEY}>+ <Stack>+ <Radio label="Read-only" value="read-only" />+ <Radio label="Read-write" value="read-write" />+ </Stack>+ </FormRadioGroup>+ <SharedTenantCollectionsList />+ <FormSubmitButton label="Save" />+ </Form>+ </FormProvider>,+ );++ return { onSubmit };+};++describe("SharedTenantCollectionsList", () => {+ beforeEach(() => {+ fetchMock.removeRoutes();+ fetchMock.clearHistory();+ });++ describe("rendering", () => {+ it("should show loading state while fetching", async () => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { data: [] },+ {+ name: "root-items",+ delay: 100,+ },+ );++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: {},+ [TYPE_KEY]: "read-write",+ }}+ onSubmit={jest.fn()}+ >+ <Form>+ <SharedTenantCollectionsList />+ </Form>+ </FormProvider>,+ );++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ });++ it("should show empty state when no collections exist", async () => {+ setup({ collections: [] });++ await waitFor(() => {+ expect(+ screen.getByText("No shared tenant collections found"),+ ).toBeInTheDocument();+ });+ });++ it("should show error state when API fails", async () => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { status: 500 },+ { name: "root-items" },+ );++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: {},+ [TYPE_KEY]: "read-write",+ }}+ onSubmit={jest.fn()}+ >+ <Form>+ <SharedTenantCollectionsList />+ </Form>+ </FormProvider>,+ );++ await waitFor(() => {+ expect(+ screen.getByText("Failed to load shared tenant collections"),+ ).toBeInTheDocument();+ });+ });++ it("should render list of collections", async () => {+ const collections = [+ createMockTenantCollectionItem({ id: 1, name: "Collection A" }),+ createMockTenantCollectionItem({ id: 2, name: "Collection B" }),+ ];++ setup({ collections });++ await waitFor(() => {+ expect(screen.getByText("Collection A")).toBeInTheDocument();+ });+ expect(screen.getByText("Collection B")).toBeInTheDocument();+ });+ });++ describe("toggle state from form values", () => {+ it("should show unchecked when syncMap has false value", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: { 1: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).not.toBeChecked();+ });+ });++ it("should show checked when syncMap has true value", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: { 1: true },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeChecked();+ });+ });++ it("should show unchecked when collection not in syncMap", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: {},+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).not.toBeChecked();+ });+ });+ });++ describe("deferred save behavior", () => {+ it("should NOT call collection API when toggling", async () => {+ // Set up a mock for collection update that should NOT be called+ fetchMock.put(+ /\/api\/collection\/\d+/,+ { id: 1 },+ { name: "update-collection" },+ );++ setup({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: { 1: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));++ // Wait a bit to ensure no API call is made+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(fetchMock.callHistory.called("update-collection")).toBe(false);+ });++ it("should update form state when toggling on", async () => {+ const { onSubmit } = setup({+ collections: [createMockTenantCollectionItem({ id: 42 })],+ initialSyncMap: { 42: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: true },+ }),+ expect.anything(),+ );+ });+ });++ it("should update form state when toggling off", async () => {+ const { onSubmit } = setup({+ collections: [createMockTenantCollectionItem({ id: 42 })],+ initialSyncMap: { 42: true },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: false },+ }),+ expect.anything(),+ );+ });+ });++ it("should handle multiple collections independently", async () => {+ const { onSubmit } = setup({+ collections: [+ createMockTenantCollectionItem({ id: 1, name: "Collection A" }),+ createMockTenantCollectionItem({ id: 2, name: "Collection B" }),+ ],+ initialSyncMap: { 1: false, 2: false },+ });++ await waitFor(() => {+ expect(screen.getByText("Collection A")).toBeInTheDocument();+ });++ const switches = screen.getAllByRole("switch");+ expect(switches).toHaveLength(2);++ // Toggle only the first collection+ await userEvent.click(switches[0]);+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true, 2: false },+ }),+ expect.anything(),+ );+ });+ });++ it("should preserve other collections when toggling one", async () => {+ const { onSubmit } = setup({+ collections: [+ createMockTenantCollectionItem({ id: 1, name: "Collection A" }),+ createMockTenantCollectionItem({ id: 2, name: "Collection B" }),+ createMockTenantCollectionItem({ id: 3, name: "Collection C" }),+ ],+ initialSyncMap: { 1: true, 2: false, 3: true },+ });++ await waitFor(() => {+ expect(screen.getByText("Collection B")).toBeInTheDocument();+ });++ const switches = screen.getAllByRole("switch");++ // Toggle the second collection (index 1)+ await userEvent.click(switches[1]);+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true, 2: true, 3: true },+ }),+ expect.anything(),+ );+ });+ });+ });++ describe("permissions", () => {+ it("should disable toggle when can_write is false", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ can_write: false })],+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeDisabled();+ });+ });++ it("should enable toggle when can_write is true", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ can_write: true })],+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeEnabled();+ });+ });++ it("should disable toggle when sync type is read-only", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ can_write: true })],+ syncType: "read-only",+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeDisabled();+ });+ });++ it("should enable toggle when sync type is read-write and can_write is true", async () => {+ setup({+ collections: [createMockTenantCollectionItem({ can_write: true })],+ syncType: "read-write",+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeEnabled();+ });+ });+ });++ describe("mode switching", () => {+ it("should reset collection sync state to initial values when switching from read-write to read-only", async () => {+ const { onSubmit } = setupWithSyncTypeToggle({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: { 1: false },+ syncType: "read-write",+ });++ // Wait for the component to render+ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ // Toggle the collection sync on+ await userEvent.click(screen.getByRole("switch"));+ expect(screen.getByRole("switch")).toBeChecked();++ // Switch to read-only mode+ await userEvent.click(screen.getByLabelText("Read-only"));++ // The collection sync should be reset to initial value (false)+ await waitFor(() => {+ expect(screen.getByRole("switch")).not.toBeChecked();+ });++ // Submit and verify the collections were reset+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: false },+ [TYPE_KEY]: "read-only",+ }),+ expect.anything(),+ );+ });+ });++ it("should not reset collection sync state when switching from read-only to read-write", async () => {+ const { onSubmit } = setupWithSyncTypeToggle({+ collections: [createMockTenantCollectionItem({ id: 1 })],+ initialSyncMap: { 1: true },+ syncType: "read-only",+ });++ // Wait for the component to render+ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ // Verify initial state is checked+ expect(screen.getByRole("switch")).toBeChecked();++ // Switch to read-write mode+ await userEvent.click(screen.getByLabelText("Read-write"));++ // The collection sync should remain as is+ expect(screen.getByRole("switch")).toBeChecked();++ // Submit and verify the collections were not reset+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true },+ [TYPE_KEY]: "read-write",+ }),+ expect.anything(),+ );+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/index.tsnew file mode 100644index 00000000000..ceb3d26798f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/index.ts@@ -0,0 +1 @@+export { SharedTenantCollectionsList } from "./SharedTenantCollectionsList";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PullFromRemoteButton.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PullFromRemoteButton.tsxdeleted file mode 100644index 0a4649c9b78..00000000000--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PullFromRemoteButton.tsx+++ /dev/null@@ -1,68 +0,0 @@-import type { Dispatch, SetStateAction } from "react";-import { t } from "ttag";--import { useToast } from "metabase/common/hooks";-import { ActionIcon, Icon } from "metabase/ui";-import { useImportChangesMutation } from "metabase-enterprise/api";-import {- type SyncError,- parseSyncError,-} from "metabase-enterprise/remote_sync/utils";--import { trackPullChanges } from "../../analytics";-import type { SyncConflictVariant } from "../SyncConflictModal";--interface PushChangesButtonProps {- branch: string;- setSyncConflictVariant: Dispatch<- SetStateAction<SyncConflictVariant | undefined>- >;-}--export const PullFromRemoteButton = (props: PushChangesButtonProps) => {- const { branch, setSyncConflictVariant } = props;- const [importChanges, { isLoading }] = useImportChangesMutation();- const [sendToast] = useToast();-- const handleClick = async () => {- try {- await importChanges({ branch }).unwrap();-- trackPullChanges({- triggeredFrom: "sidebar",- force: false,- });-- sendToast({- message: t`Your branch is now up to date with remote`,- icon: "check",- });- } catch (error) {- const { hasConflict, errorMessage } = parseSyncError(error as SyncError);-- if (hasConflict) {- setSyncConflictVariant("pull");- return;- }-- sendToast({- message: errorMessage || t`Failed to pull from remote`,- icon: "warning",- });- }- };-- return (- <ActionIcon- aria-label={t`Pull from Git`}- c="icon-secondary"- disabled={isLoading}- h={24}- onClick={handleClick}- px={0}- variant="subtle"- >- <Icon name="arrow_down" size={16} tooltip={t`Pull from Git`} />- </ActionIcon>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsxdeleted file mode 100644index 0edfbc63a8f..00000000000--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { useDisclosure } from "@mantine/hooks";-import { t } from "ttag";--import type { CollectionTreeItem } from "metabase/entities/collections";-import { ActionIcon, Icon } from "metabase/ui";--import { PushChangesModal } from "../PushChangesModal";--interface PushChangesButtonProps {- currentBranch: string;- syncedCollections: CollectionTreeItem[];-}--export const PushChangesButton = (props: PushChangesButtonProps) => {- const { syncedCollections, currentBranch } = props;- const [showPush, { open: openPush, close: closePush }] = useDisclosure(false);-- return (- <>- <ActionIcon- aria-label={t`Push to Git`}- c="icon-secondary"- h={24}- onClick={openPush}- px={0}- variant="subtle"- >- <Icon name="arrow_up" size={16} tooltip={t`Push to Git`} />- </ActionIcon>- {showPush && (- <PushChangesModal- onClose={closePush}- collections={syncedCollections}- currentBranch={currentBranch!}- />- )}- </>- );-};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsxindex a553ab2eb1a..4b47e00c006 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx@@ -1,36 +1,20 @@-import { useCallback, useState } from "react";import { t } from "ttag";import ErrorBoundary from "metabase/ErrorBoundary";import { useAdminSetting } from "metabase/api/utils";import { Tree } from "metabase/common/components/tree";-import { useToast } from "metabase/common/hooks";-import { useSelector } from "metabase/lib/redux";import {SidebarHeading,SidebarSection,} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";import type { SyncedCollectionsSidebarSectionProps } from "metabase/plugins/types";-import { getUserIsAdmin } from "metabase/selectors/user";import { Box, Flex, Group, Text } from "metabase/ui";-import {- useGetRemoteSyncChangesQuery,- useImportChangesMutation,-} from "metabase-enterprise/api";+import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";-import { trackBranchSwitched } from "../../analytics";-import { BRANCH_KEY, REMOTE_SYNC_KEY } from "../../constants";-import { useSyncStatus } from "../../hooks/use-sync-status";-import {- SyncConflictModal,- type SyncConflictVariant,-} from "../SyncConflictModal";+import { REMOTE_SYNC_KEY } from "../../constants";-import { BranchPicker } from "./BranchPicker";import { CollectionSyncStatusBadge } from "./CollectionSyncStatusBadge";-import { PullFromRemoteButton } from "./PullFromRemoteButton";-import { PushChangesButton } from "./PushChangesButton";export const SyncedCollectionsSidebarSection = ({onItemSelect,@@ -38,84 +22,25 @@ export const SyncedCollectionsSidebarSection = ({syncedCollections,}: SyncedCollectionsSidebarSectionProps) => {const hasSyncedCollections = syncedCollections.length > 0;- const isAdmin = useSelector(getUserIsAdmin);const { value: isRemoteSyncEnabled } = useAdminSetting(REMOTE_SYNC_KEY);- const { value: currentBranch } = useAdminSetting(BRANCH_KEY);- const [importChanges] = useImportChangesMutation();- const [syncConflictVariant, setSyncConflictVariant] =- useState<SyncConflictVariant>();- const { isRunning: isSyncTaskRunning } = useSyncStatus();- const [nextBranch, setNextBranch] = useState<string | null>(null);- const [sendToast] = useToast();+ const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {+ skip: !isRemoteSyncEnabled,+ refetchOnFocus: true,+ });- const { data: dirtyData, refetch: refetchDirty } =- useGetRemoteSyncChangesQuery(undefined, {- refetchOnFocus: true,- });-- const isSwitchingBranch = !!nextBranch;- const isDirty = !!(dirtyData?.dirty && dirtyData.dirty.length > 0);+ const changedCollections = dirtyData?.changedCollections ?? {};const hasEntityRemoved = dirtyData?.dirty?.some((entity) => entity.sync_status === "removed",);- const changeBranch = useCallback(- async (branch: string | null, isNewBranch?: boolean) => {- if (branch == null) {- console.warn("Trying to switch to null branch");- return;- }-- if (!isNewBranch) {- await importChanges({ branch });-- // Tracking only when not creating a new branch since it has its own event- trackBranchSwitched({- triggeredFrom: "sidebar",- });- }-- setNextBranch(null);- },- [importChanges, setNextBranch],- );-- const handleBranchSelect = useCallback(- async (branch: string, isNewBranch?: boolean) => {- try {- if (branch === currentBranch) {- return;- }-- setNextBranch(branch);-- const freshDirtyData = await refetchDirty().unwrap();- const isDirty = freshDirtyData.dirty.length > 0;-- if (isDirty && !isNewBranch) {- setSyncConflictVariant("switch-branch");- } else {- await changeBranch(branch, isNewBranch);- setNextBranch(null);- }- } catch {- sendToast({- icon: "warning",- toastColor: "error",- message: t`Sorry, we were unable to switch branches.`,- });- }- },- [currentBranch, changeBranch, refetchDirty, sendToast],- );const showChangesBadge = (itemId?: number | string) => {- if (!dirtyData?.changedCollections || typeof itemId !== "number") {+ if (!changedCollections || typeof itemId !== "number") {return false;}- const collectionIsUpdated = !!dirtyData?.changedCollections[itemId];+ const collectionIsUpdated = !!changedCollections[itemId];const hasSingleRootCollection = syncedCollections.length === 1;return (@@ -133,75 +58,35 @@ export const SyncedCollectionsSidebarSection = ({}return (- <>- <SidebarSection>- <ErrorBoundary>- <Flex justify="space-between">- <Box w="100%">- <Group gap="sm" pb="sm">- <SidebarHeading>{t`Synced Collections`}</SidebarHeading>- </Group>- {isAdmin && (- <Group pb="sm" pl="0.875rem" gap="sm" w="100%">- {!!currentBranch && (- <>- <BranchPicker- isLoading={isSyncTaskRunning || isSwitchingBranch}- value={currentBranch}- onChange={handleBranchSelect}- baseBranch={currentBranch}- />- <Group ml="auto" gap="xs">- <PullFromRemoteButton- branch={currentBranch}- setSyncConflictVariant={setSyncConflictVariant}- />- {isDirty && (- <PushChangesButton- currentBranch={currentBranch}- syncedCollections={syncedCollections}- />- )}- </Group>- </>- )}- </Group>- )}- </Box>- </Flex>-- {!hasSyncedCollections && (- <Text c="text-light" fz="sm" ta="center">- {t`No synced collections`}- </Text>- )}- <Box>- <Tree- data={syncedCollections}- selectedId={selectedId}- onSelect={onItemSelect}- TreeNode={SidebarCollectionLink}- role="tree"- aria-label="collection-tree"- rightSection={(item) =>- showChangesBadge(item?.id) && <CollectionSyncStatusBadge />- }- />+ <SidebarSection>+ <ErrorBoundary>+ <Flex justify="space-between">+ <Box w="100%">+ <Group gap="sm" pb="sm">+ <SidebarHeading>{t`Synced Collections`}</SidebarHeading>+ </Group></Box>- </ErrorBoundary>- </SidebarSection>- {!!syncConflictVariant && (- <SyncConflictModal- collections={syncedCollections}- currentBranch={currentBranch!}- nextBranch={nextBranch}- onClose={() => {- setSyncConflictVariant(undefined);- setNextBranch(null);- }}- variant={syncConflictVariant}- />- )}- </>+ </Flex>++ {!hasSyncedCollections && (+ <Text c="text-light" fz="sm" ta="center">+ {t`No synced collections`}+ </Text>+ )}+ <Box>+ <Tree+ data={syncedCollections}+ selectedId={selectedId}+ onSelect={onItemSelect}+ TreeNode={SidebarCollectionLink}+ role="tree"+ aria-label="collection-tree"+ rightSection={(item) =>+ showChangesBadge(item?.id) && <CollectionSyncStatusBadge />+ }+ />+ </Box>+ </ErrorBoundary>+ </SidebarSection>);};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/constants.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/constants.tsindex 069700bcfb1..3a05269556f 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/constants.ts@@ -8,6 +8,7 @@ export const TYPE_KEY = "remote-sync-type";export const BRANCH_KEY = "remote-sync-branch";export const REMOTE_SYNC_KEY = "remote-sync-enabled";export const AUTO_IMPORT_KEY = "remote-sync-auto-import";+export const COLLECTIONS_KEY = "collections";export const REMOTE_SYNC_SCHEMA = Yup.object({[REMOTE_SYNC_KEY]: Yup.boolean().nullable().default(true),@@ -19,6 +20,7 @@ export const REMOTE_SYNC_SCHEMA = Yup.object({.nullable().default("read-only"),[BRANCH_KEY]: Yup.string().nullable().default("main"),+ [COLLECTIONS_KEY]: Yup.object().nullable().default({}),});export const REMOTE_SYNC_INVALIDATION_TAGS = [diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.tsindex 0d20e3305f5..25244e23809 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts@@ -6,6 +6,8 @@ import {import { hasPremiumFeature } from "metabase-enterprise/settings";import { LibraryNav } from "./LibraryNav";+import { CollectionsNavTree } from "./components/CollectionsNavTree";+import { GitSyncControls } from "./components/GitSyncControls";import { RemoteSyncAdminSettings } from "./components/RemoteSyncAdminSettings/RemoteSyncAdminSettings";import { SyncedCollectionsSidebarSection } from "./components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection";import { REMOTE_SYNC_INVALIDATION_TAGS } from "./constants";@@ -22,6 +24,8 @@ export function initializePlugin() {PLUGIN_REMOTE_SYNC.LibraryNav = LibraryNav;PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection =SyncedCollectionsSidebarSection;+ PLUGIN_REMOTE_SYNC.GitSyncAppBarControls = GitSyncControls;+ PLUGIN_REMOTE_SYNC.CollectionsNavTree = CollectionsNavTree;PLUGIN_REMOTE_SYNC.REMOTE_SYNC_INVALIDATION_TAGS =REMOTE_SYNC_INVALIDATION_TAGS;PLUGIN_REMOTE_SYNC.useSyncStatus = useSyncStatus;diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.tsindex 17320ee8782..e2897d4d083 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts@@ -37,11 +37,6 @@ function invalidateRemoteSyncTags(dispatch: any) {dispatch(Api.util.invalidateTags(REMOTE_SYNC_INVALIDATION_TAGS as any));}-function isDeactivatingRemoteSync(action: any): boolean {- const settings = action.meta?.arg?.originalArgs;- return settings?.["remote-sync-url"] === "";-}-const ALL_INVALIDATION_TAGS = [tag("action"),tag("alert"),@@ -328,19 +323,18 @@ remoteSyncListenerMiddleware.startListening({});remoteSyncListenerMiddleware.startListening({- matcher: remoteSyncApi.endpoints.updateRemoteSyncSettings.matchPending,+ matcher: remoteSyncApi.endpoints.updateRemoteSyncSettings.matchFulfilled,effect: async (action, { dispatch }) => {- if (!isDeactivatingRemoteSync(action)) {+ const response = action.payload;+ // Only show modal if a task was actually started (indicated by task_id presence)+ if (response.task_id) {dispatch(taskStarted({ taskType: "import" }));}},});remoteSyncListenerMiddleware.startListening({- matcher: isAnyOf(- remoteSyncApi.endpoints.importChanges.matchRejected,- remoteSyncApi.endpoints.updateRemoteSyncSettings.matchRejected,- ),+ matcher: remoteSyncApi.endpoints.importChanges.matchRejected,effect: async (_action, { dispatch }) => {dispatch(taskCleared());},diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.unit.spec.tsnew file mode 100644index 00000000000..930fad74406--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.unit.spec.ts@@ -0,0 +1,228 @@+import { combineReducers, configureStore } from "@reduxjs/toolkit";+import fetchMock from "fetch-mock";++import { Api } from "metabase/api";+import { remoteSyncApi } from "metabase-enterprise/api/remote-sync";++import {+ type SyncTaskState,+ initialState,+ remoteSyncReducer,+} from "../sync-task-slice";++import { remoteSyncListenerMiddleware } from "./remote-sync-listener-middleware";++interface TestState {+ remoteSyncPlugin: SyncTaskState;+}++const createTestStore = () => {+ return configureStore({+ reducer: combineReducers({+ remoteSyncPlugin: remoteSyncReducer,+ // EnterpriseApi is an enhanced version of Api, so they share the same reducer+ [Api.reducerPath]: Api.reducer,+ }),+ preloadedState: {+ remoteSyncPlugin: initialState,+ },+ middleware: (getDefaultMiddleware) =>+ getDefaultMiddleware({+ immutableCheck: false,+ serializableCheck: false,+ })+ .concat(Api.middleware)+ // Cast to any to avoid complex type mismatch between the listener middleware+ // and the test store's State type (test store uses simplified State)+ .concat(remoteSyncListenerMiddleware.middleware as any),+ });+};++const waitForCondition = async (+ condition: () => boolean,+ timeout = 1000,+): Promise<void> => {+ const start = Date.now();+ while (Date.now() - start < timeout) {+ if (condition()) {+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+};++describe("remote-sync-listener-middleware", () => {+ describe("updateRemoteSyncSettings listener", () => {+ it("should show modal when settings save succeeds with task_id", async () => {+ fetchMock.put("path:/api/ee/remote-sync/settings", {+ success: true,+ task_id: 123,+ });++ const store = createTestStore();++ // Dispatch the mutation+ store.dispatch(+ remoteSyncApi.endpoints.updateRemoteSyncSettings.initiate({+ "remote-sync-url": "https://github.com/test/repo.git",+ "remote-sync-token": "token123",+ }),+ );++ // Wait for the request to complete and middleware to process+ await waitForCondition(() => {+ const state = store.getState() as TestState;+ return state.remoteSyncPlugin?.showModal === true;+ });++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(true);+ expect(state.remoteSyncPlugin?.currentTask?.sync_task_type).toBe(+ "import",+ );+ });++ it("should NOT show modal when settings save succeeds without task_id", async () => {+ fetchMock.put("path:/api/ee/remote-sync/settings", {+ success: true,+ });++ const store = createTestStore();++ // Dispatch the mutation+ store.dispatch(+ remoteSyncApi.endpoints.updateRemoteSyncSettings.initiate({+ "remote-sync-url": "https://github.com/test/repo.git",+ "remote-sync-token": "token123",+ }),+ );++ // Wait for the request to complete+ await waitForCondition(() =>+ fetchMock.callHistory.done("path:/api/ee/remote-sync/settings"),+ );++ // Give middleware time to process+ await new Promise((resolve) => setTimeout(resolve, 100));++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(false);+ expect(state.remoteSyncPlugin?.currentTask).toBeNull();+ });++ it("should NOT show modal when settings save fails", async () => {+ fetchMock.put("path:/api/ee/remote-sync/settings", {+ status: 500,+ body: { message: "Internal server error" },+ });++ const store = createTestStore();++ // Dispatch the mutation+ store.dispatch(+ remoteSyncApi.endpoints.updateRemoteSyncSettings.initiate({+ "remote-sync-url": "https://github.com/test/repo.git",+ "remote-sync-token": "token123",+ }),+ );++ // Wait for the request to complete+ await waitForCondition(() =>+ fetchMock.callHistory.done("path:/api/ee/remote-sync/settings"),+ );++ // Give middleware time to process+ await new Promise((resolve) => setTimeout(resolve, 100));++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(false);+ expect(state.remoteSyncPlugin?.currentTask).toBeNull();+ });++ it("should NOT show modal when disabling remote sync", async () => {+ fetchMock.put("path:/api/ee/remote-sync/settings", {+ success: true,+ // No task_id when disabling - backend doesn't start a sync+ });++ const store = createTestStore();++ // Dispatch the mutation with empty URL (disabling remote sync)+ store.dispatch(+ remoteSyncApi.endpoints.updateRemoteSyncSettings.initiate({+ "remote-sync-url": "",+ }),+ );++ // Wait for the request to complete+ await waitForCondition(() =>+ fetchMock.callHistory.done("path:/api/ee/remote-sync/settings"),+ );++ // Give middleware time to process+ await new Promise((resolve) => setTimeout(resolve, 100));++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(false);+ expect(state.remoteSyncPlugin?.currentTask).toBeNull();+ });+ });++ describe("importChanges listener", () => {+ it("should show modal when import request starts", async () => {+ fetchMock.post("path:/api/ee/remote-sync/import", {+ status: "running",+ task_id: 456,+ });++ const store = createTestStore();++ // Dispatch the mutation+ store.dispatch(+ remoteSyncApi.endpoints.importChanges.initiate({+ branch: "main",+ }),+ );++ // The import listener triggers on matchPending, so modal should show immediately+ await waitForCondition(() => {+ const state = store.getState() as TestState;+ return state.remoteSyncPlugin?.showModal === true;+ });++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(true);+ expect(state.remoteSyncPlugin?.currentTask?.sync_task_type).toBe(+ "import",+ );+ });++ it("should clear task when import request fails", async () => {+ fetchMock.post("path:/api/ee/remote-sync/import", {+ status: 500,+ body: { message: "Import failed" },+ });++ const store = createTestStore();++ // Dispatch the mutation+ store.dispatch(+ remoteSyncApi.endpoints.importChanges.initiate({+ branch: "main",+ }),+ );++ // Wait for the request to fail+ await waitForCondition(() =>+ fetchMock.callHistory.done("path:/api/ee/remote-sync/import"),+ );++ // Give middleware time to process the rejection+ await new Promise((resolve) => setTimeout(resolve, 100));++ const state = store.getState() as TestState;+ expect(state.remoteSyncPlugin?.showModal).toBe(false);+ expect(state.remoteSyncPlugin?.currentTask).toBeNull();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.tsindex 5fdbe674c69..0ab6c980b89 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts@@ -116,16 +116,20 @@ export const buildCollectionMap = (): Map<number, Collection> => {const map = new Map<number, Collection>();- const processCollection = (collection: Collection) => {+ const processCollection = (parents: Collection[], collection: Collection) => {if (typeof collection.id === "number") {- map.set(collection.id, collection);+ map.set(collection.id, { ...collection, effective_ancestors: parents });}if (collection.children) {- collection.children.forEach(processCollection);+ collection.children.forEach((child) => {+ processCollection([...parents, collection], child);+ });}};- collectionTree.forEach(processCollection);+ collectionTree.forEach((collection) => {+ processCollection([], collection);+ });return map;};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.tsnew file mode 100644index 00000000000..61dae16b2cb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts@@ -0,0 +1,191 @@+import { createMockCollection } from "metabase-types/api/mocks";++import { buildCollectionMap, getCollectionPathSegments } from "./utils";++describe("remote_sync utils", () => {+ describe("buildCollectionMap", () => {+ it("should create a map of collections by id", () => {+ const collection1 = createMockCollection({ id: 1, name: "Collection 1" });+ const collection2 = createMockCollection({ id: 2, name: "Collection 2" });++ const map = buildCollectionMap([collection1, collection2]);++ expect(map.size).toBe(2);+ expect(map.get(1)?.name).toBe("Collection 1");+ expect(map.get(2)?.name).toBe("Collection 2");+ });++ it("should create effective_ancestors for root level collections", () => {+ const collection = createMockCollection({+ id: 1,+ name: "Root Collection",+ });++ const map = buildCollectionMap([collection]);++ const result = map.get(1);+ expect(result?.effective_ancestors).toEqual([]);+ });++ it("should create effective_ancestors for nested collections", () => {+ const parent = createMockCollection({+ id: 1,+ name: "Parent",+ });+ const child = createMockCollection({+ id: 2,+ name: "Child",+ });+ const grandchild = createMockCollection({+ id: 3,+ name: "Grandchild",+ });++ // Build the tree structure+ child.children = [grandchild];+ parent.children = [child];++ const map = buildCollectionMap([parent]);++ // Parent should have empty ancestors+ const parentResult = map.get(1);+ expect(parentResult?.effective_ancestors).toEqual([]);++ // Child should have parent as ancestor+ const childResult = map.get(2);+ expect(childResult?.effective_ancestors).toHaveLength(1);+ expect(childResult?.effective_ancestors?.[0].id).toBe(1);+ expect(childResult?.effective_ancestors?.[0].name).toBe("Parent");++ // Grandchild should have parent and child as ancestors+ const grandchildResult = map.get(3);+ expect(grandchildResult?.effective_ancestors).toHaveLength(2);+ expect(grandchildResult?.effective_ancestors?.[0].id).toBe(1);+ expect(grandchildResult?.effective_ancestors?.[0].name).toBe("Parent");+ expect(grandchildResult?.effective_ancestors?.[1].id).toBe(2);+ expect(grandchildResult?.effective_ancestors?.[1].name).toBe("Child");+ });++ it("should handle multiple root level collections with children", () => {+ const parent1 = createMockCollection({ id: 1, name: "Parent 1" });+ const child1 = createMockCollection({ id: 2, name: "Child 1" });+ parent1.children = [child1];++ const parent2 = createMockCollection({ id: 3, name: "Parent 2" });+ const child2 = createMockCollection({ id: 4, name: "Child 2" });+ parent2.children = [child2];++ const map = buildCollectionMap([parent1, parent2]);++ expect(map.size).toBe(4);++ // Check first tree+ expect(map.get(1)?.effective_ancestors).toEqual([]);+ expect(map.get(2)?.effective_ancestors).toHaveLength(1);+ expect(map.get(2)?.effective_ancestors?.[0].id).toBe(1);++ // Check second tree+ expect(map.get(3)?.effective_ancestors).toEqual([]);+ expect(map.get(4)?.effective_ancestors).toHaveLength(1);+ expect(map.get(4)?.effective_ancestors?.[0].id).toBe(3);+ });++ it("should preserve original collection properties except effective_ancestors", () => {+ const parent = createMockCollection({+ id: 1,+ name: "Parent",+ description: "Parent description",+ archived: false,+ });+ const child = createMockCollection({+ id: 2,+ name: "Child",+ description: "Child description",+ archived: false,+ // Set some existing effective_ancestors that should be overridden+ effective_ancestors: [{ id: 99, name: "Old Ancestor" }] as any,+ });+ parent.children = [child];++ const map = buildCollectionMap([parent]);++ const childResult = map.get(2);+ expect(childResult?.name).toBe("Child");+ expect(childResult?.description).toBe("Child description");+ expect(childResult?.archived).toBe(false);+ // effective_ancestors should be overridden with the actual parent+ expect(childResult?.effective_ancestors).toHaveLength(1);+ expect(childResult?.effective_ancestors?.[0].id).toBe(1);+ expect(childResult?.effective_ancestors?.[0].name).toBe("Parent");+ });+ });++ describe("getCollectionPathSegments", () => {+ it("should return Root for undefined collection id", () => {+ const map = new Map();+ const segments = getCollectionPathSegments(undefined, map);++ expect(segments).toEqual([{ id: "root", name: "Root" }]);+ });++ it("should return Root if collection is not found in map", () => {+ const map = new Map();+ const segments = getCollectionPathSegments(999, map);++ expect(segments).toEqual([{ id: "root", name: "Root" }]);+ });++ it("should return collection path with ancestors", () => {+ const parent = createMockCollection({ id: 1, name: "Parent" });+ const child = createMockCollection({+ id: 2,+ name: "Child",+ effective_ancestors: [{ id: 1, name: "Parent" }] as any,+ });++ const map = new Map([+ [1, parent],+ [2, child],+ ]);++ const segments = getCollectionPathSegments(2, map);++ expect(segments).toHaveLength(2);+ expect(segments[0]).toEqual({ id: 1, name: "Parent" });+ expect(segments[1]).toEqual({ id: 2, name: "Child" });+ });++ it("should handle collection without ancestors", () => {+ const collection = createMockCollection({+ id: 1,+ name: "Single Collection",+ });++ const map = new Map([[1, collection]]);++ const segments = getCollectionPathSegments(1, map);++ expect(segments).toHaveLength(1);+ expect(segments[0]).toEqual({ id: 1, name: "Single Collection" });+ });++ it("should build path from buildCollectionMap's effective_ancestors", () => {+ const parent = createMockCollection({ id: 1, name: "Parent" });+ const child = createMockCollection({ id: 2, name: "Child" });+ const grandchild = createMockCollection({ id: 3, name: "Grandchild" });++ child.children = [grandchild];+ parent.children = [child];++ // Use buildCollectionMap to create the map with effective_ancestors+ const map = buildCollectionMap([parent]);++ const segments = getCollectionPathSegments(3, map);++ expect(segments).toHaveLength(3);+ expect(segments[0]).toEqual({ id: 1, name: "Parent" });+ expect(segments[1]).toEqual({ id: 2, name: "Child" });+ expect(segments[2]).toEqual({ id: 3, name: "Grandchild" });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.tsxindex 54c0b71cc06..5d8581efbff 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.tsx@@ -73,7 +73,9 @@ export const buildStructuredEntries = (disabled: frozen,revert:original ||- (source === "jwt" ? { value, source, frozen: false } : undefined),+ (source === "jwt" || source === "tenant"+ ? { value, source, frozen: false }+ : undefined),},})).sort((a, b) =>@@ -103,6 +105,7 @@ export const LoginAttributeMappingEditor = ({);useEffect(() => {+ // structuredAttributes can change if a different tenant is selectedif (structuredAttributes) {setEntries((previousEntries) => [...buildStructuredEntries(structuredAttributes),@@ -266,19 +269,25 @@ const ValueInput = ({);};-const infoText = (source?: "system" | "jwt" | "user"): string => {+const infoText = (source?: "system" | "jwt" | "user" | "tenant"): string => {switch (source) {case "system":return t`This attribute is system defined`;case "jwt":return t`This attribute was set by the login token, but you can override its value`;+ case "tenant":+ return t`This attribute is inherited from the tenant, but you can override its value`;default:return "";}};-const InfoCard = ({ source }: { source?: "system" | "user" | "jwt" }) =>- !["system", "jwt"].includes(source ?? "") ? null : (+const InfoCard = ({+ source,+}: {+ source?: "tenant" | "system" | "user" | "jwt";+}) =>+ !["tenant", "system", "jwt"].includes(source ?? "") ? null : (<HoverCard><HoverCard.Target><Icon name="info" c="text-light" />diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.unit.spec.tsxindex 65528524104..dc5b2479f86 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributeMappingEditor.unit.spec.tsx@@ -1,3 +1,4 @@+import { waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { renderWithProviders, screen } from "__support__/ui";@@ -32,6 +33,23 @@ const structuredAttributes: StructuredUserAttributes = {value: "user",},},+ type: {+ // overridden tenant attribute+ source: "user",+ frozen: false,+ value: "insect",+ original: {+ source: "tenant",+ frozen: false,+ value: "bug",+ },+ },+ color: {+ // inherited tenant attribute+ source: "tenant",+ frozen: false,+ value: "green",+ },personal: {// personal attributesource: "user",@@ -178,6 +196,15 @@ describe("LoginAttributeMappingEditor", () => {expect(await screen.findByDisplayValue("bug_gym")).toBeInTheDocument();});+ it("shows tenant attributes with text keys", async () => {+ setup({ structuredAttributes });++ expect(await screen.findByText("type")).toBeInTheDocument();+ expect(await screen.findByDisplayValue("insect")).toBeInTheDocument();+ expect(await screen.findByText("color")).toBeInTheDocument();+ expect(await screen.findByDisplayValue("green")).toBeInTheDocument();+ });+it("shows user defined attributes with editable keys and values", async () => {setup({ structuredAttributes });@@ -212,6 +239,8 @@ describe("LoginAttributeMappingEditor", () => {"@tenant.slug": "bug_gym",session: "abc123",role: "admin",+ type: "insect",+ color: "green",personal: "secret",newAttribute: "newValue",});@@ -227,6 +256,8 @@ describe("LoginAttributeMappingEditor", () => {"@tenant.slug": "bug_gym",session: "abc123",role: "admin",+ type: "insect",+ color: "green",public: "newSecret",});});@@ -241,6 +272,8 @@ describe("LoginAttributeMappingEditor", () => {"@tenant.slug": "bug_gym",session: "abc123",role: "admin",+ type: "insect",+ color: "green",});});@@ -252,6 +285,22 @@ describe("LoginAttributeMappingEditor", () => {"@tenant.slug": "bug_gym",session: "xyz789",role: "admin",+ type: "insect",+ color: "green",+ personal: "secret",+ });+ });++ it("can override a tenant attribute value", async () => {+ const { onChange } = setup({ structuredAttributes });++ await changeInput("green", "blue");+ expect(onChange).toHaveBeenLastCalledWith({+ "@tenant.slug": "bug_gym",+ session: "abc123",+ role: "admin",+ type: "insect",+ color: "blue",personal: "secret",});});@@ -264,6 +313,22 @@ describe("LoginAttributeMappingEditor", () => {"@tenant.slug": "bug_gym",session: "abc123",role: "superuser",+ type: "insect",+ color: "green",+ personal: "secret",+ });+ });++ it("can change an overridden tenant attribute value", async () => {+ const { onChange } = setup({ structuredAttributes });++ await changeInput("insect", "ick");+ expect(onChange).toHaveBeenLastCalledWith({+ "@tenant.slug": "bug_gym",+ session: "abc123",+ role: "admin",+ type: "ick",+ color: "green",personal: "secret",});});@@ -272,19 +337,51 @@ describe("LoginAttributeMappingEditor", () => {const { onChange } = setup({ structuredAttributes });expect(await screen.findByDisplayValue("admin")).toBeInTheDocument();- const revertButtons = await screen.findAllByLabelText("refresh icon");- // Click the revert button for the JWT attribute (role)- await userEvent.click(revertButtons[0]);- expect(await screen.findByDisplayValue("user")).toBeInTheDocument();- expect(screen.queryByDisplayValue("admin")).not.toBeInTheDocument();+ const revertButtons = await screen.findAllByTestId("revert-mapping");+ expect(revertButtons).toHaveLength(2);++ await userEvent.click(revertButtons[1]);++ await waitFor(() => {+ expect(screen.getByDisplayValue("user")).toBeInTheDocument();+ });expect(onChange).toHaveBeenLastCalledWith({"@tenant.slug": "bug_gym",session: "abc123",role: "user",+ type: "insect",+ color: "green",personal: "secret",});++ expect(screen.queryByDisplayValue("admin")).not.toBeInTheDocument();+ });++ it("can revert a tenant attribute value", async () => {+ const { onChange } = setup({ structuredAttributes });++ expect(await screen.findByDisplayValue("insect")).toBeInTheDocument();++ const revertButtons = await screen.findAllByTestId("revert-mapping");++ await userEvent.click(revertButtons[0]);++ await waitFor(() => {+ expect(screen.getByDisplayValue("bug")).toBeInTheDocument();+ });++ expect(onChange).toHaveBeenLastCalledWith({+ "@tenant.slug": "bug_gym",+ session: "abc123",+ role: "admin",+ type: "bug",+ color: "green",+ personal: "secret",+ });++ expect(screen.queryByDisplayValue("insect")).not.toBeInTheDocument();});});diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.tsxindex 5ba438c78db..68c33f596c8 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.tsx@@ -5,6 +5,7 @@ import { t } from "ttag";import { skipToken, useGetUserQuery } from "metabase/api";import FormField from "metabase/common/components/FormField";import { Accordion, Box, Loader, Text } from "metabase/ui";+import { useGetTenantQuery } from "metabase-enterprise/api";import { getExtraAttributes } from "metabase-enterprise/sandboxes/utils";import type {StructuredUserAttributes,@@ -34,7 +35,9 @@ const isInheritedValue = (const inheritedValue =attribute?.original?.value ??- (attribute.source === "jwt" ? attribute.value : undefined);+ (attribute.source === "jwt" || attribute.source === "tenant"+ ? attribute.value+ : undefined);return inheritedValue === inputValue;};@@ -48,11 +51,16 @@ export const LoginAttributesWidget = ({}: Props) => {const [{ value }, , { setValue, setError }] = useField(name);+ const [{ value: tenantId }] = useField("tenant_id");const { data: userData, isLoading } = useGetUserQuery(userId ?? skipToken);+ const { data: tenant, isLoading: isLoadingTenant } = useGetTenantQuery(+ tenantId ?? skipToken,+ );+const structuredAttributes = useMemo(() => {- return getExtraAttributes(userData?.structured_attributes);- }, [userData?.structured_attributes]);+ return getExtraAttributes(userData?.structured_attributes, tenant);+ }, [tenant, userData?.structured_attributes]);const handleChange = (newValue: UserAttributeMap) => {const validEntries = Object.entries(newValue).filter(@@ -78,7 +86,7 @@ export const LoginAttributesWidget = ({</Accordion.Control><Accordion.Panel><Box pt="md">- {isLoading ? (+ {isLoading || isLoadingTenant ? (<Loader />) : (<LoginAttributeMappingEditordiff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.unit.spec.tsxindex 594af5aadb3..a683b4bb4b9 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget.unit.spec.tsx@@ -18,21 +18,41 @@ const changeInput = async (fromValue: string, toValue: string) => {};const simpleAttributes: UserAttributeMap = {+ "@tenant.slug": "bug_gym",+ color: "green",+ type: "insect",personal: "secret",- session: "abc123",};const structuredAttributes: StructuredUserAttributes = {+ type: {+ // overridden tenant attribute+ source: "user",+ frozen: false,+ value: "insect",+ original: {+ source: "tenant",+ frozen: false,+ value: "bug",+ },+ },+ color: {+ // inherited tenant attribute+ source: "tenant",+ frozen: false,+ value: "green",+ },personal: {// personal attributesource: "user",frozen: false,value: "secret",},- session: {- source: "jwt",- frozen: false,- value: "abc123",+ "@tenant.slug": {+ // immutable tenant slug+ source: "system",+ frozen: true,+ value: "bug_gym",},};@@ -72,16 +92,17 @@ describe("LoginAttributesWidget", () => {const submittedValues = onSubmit.mock.calls[0][0];expect(submittedValues).toEqual({login_attributes: {+ type: "insect",personal: "super",},});});- it("should not save a user attribute with the same key and value as a JWT attribute", async () => {+ it("should not save a user attribute with the same key and value as a tenant attribute", async () => {const { onSubmit } = setup();await screen.findByText("Attributes");- await changeInput("abc123", "abc123");+ await changeInput("insect", "bug");await userEvent.click(screen.getByRole("button", { name: "Submit" }));const submittedValues = onSubmit.mock.calls[0][0];diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsxindex 22f0f00c1ed..c8d4e5e3407 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx@@ -1,8 +1,12 @@-import { Group, type SelectProps } from "metabase/ui";+import type { ReactNode } from "react";+import { t } from "ttag";++import { Group, Icon, type SelectProps, Tooltip } from "metabase/ui";import type {GroupTableAccessPolicy,StructuredUserAttributes,Table,+ Tenant,} from "metabase-types/api";import type {@@ -11,6 +15,16 @@ import type {MappingType,} from "./types";+const TENANT_SLUG_ATTRIBUTE = "@tenant.slug";++const GET_USER_ATTRIBUTE_ICON_MAP: () => Record<string, ReactNode> = () => ({+ [TENANT_SLUG_ATTRIBUTE]: (+ <Tooltip label={t`This attribute is system defined`}>+ <Icon data-testid="system-defined-tooltip-icon" name="info" />+ </Tooltip>+ ),+});+export const getPolicyKeyFromParams = ({groupId,tableId,@@ -32,6 +46,7 @@ export const renderUserAttributesForSelect: SelectProps["renderOption"] = ({}) => (<Group flex="1" p="sm" gap="xs" justify="space-between">{option.label}+ {GET_USER_ATTRIBUTE_ICON_MAP()[option.value]}</Group>);@@ -85,6 +100,28 @@ export const buildMapping = <T,>(export const getExtraAttributes = (structuredAttributes?: StructuredUserAttributes,+ tenant?: Tenant,): StructuredUserAttributes | undefined => {- return structuredAttributes;+ if (!tenant || structuredAttributes?.[TENANT_SLUG_ATTRIBUTE]) {+ return structuredAttributes;+ }++ // for newly created tenant users, we want to pre-populate their inherited attributes+ return {+ [TENANT_SLUG_ATTRIBUTE]: {+ value: tenant.slug,+ source: "tenant",+ frozen: true,+ },+ ...Object.fromEntries(+ Object.entries(tenant.attributes ?? {}).map(([key, value]) => [+ key,+ {+ value,+ source: "tenant",+ frozen: false,+ },+ ]),+ ),+ };};diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.tsindex b4449b27182..a419dd74e66 100644--- a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts@@ -12,6 +12,7 @@ import { initializePlugin as initializeContentTranslation } from "./content_tranimport { initializePlugin as initializeEmbedding } from "./embedding";import { initializePlugin as initializeEmbeddingSdk } from "./embedding-sdk";import { initializePlugin as initializeMetabot } from "./metabot";+import { initializePlugin as initializeTenants } from "./tenants";import { initializePlugin as initializeWhitelabelPlugin } from "./whitelabel";import { initializePlugin as initializeWhitelabelOverridePlugin } from "./whitelabel/sdk-overrides";@@ -23,6 +24,7 @@ export function initializePlugins() {initializeEmbedding?.();initializeEmbeddingSdk?.();initializeMetabot?.();+ initializeTenants?.();initializeWhitelabelPlugin?.();initializeWhitelabelOverridePlugin?.();initializeContentTranslation?.();diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.module.css b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.module.cssnew file mode 100644index 00000000000..827741241bb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.module.css@@ -0,0 +1,8 @@+.radioCard {+ cursor: pointer;+ border: 1px solid var(--mb-color-border);+}++.radioCard[data-checked] {+ border-color: var(--mb-color-brand);+}diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.tsxnew file mode 100644index 00000000000..a42f6a4d039--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.tsx@@ -0,0 +1,173 @@+import { useEffect, useState } from "react";+import { t } from "ttag";++import { permissionApi } from "metabase/api";+import { useAdminSetting } from "metabase/api/utils";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useToast } from "metabase/common/hooks";+import { useConfirmation } from "metabase/common/hooks/use-confirmation";+import { useDispatch } from "metabase/lib/redux";+import { Button, Flex, Group, Modal, Radio, Stack, Text } from "metabase/ui";++import S from "./EditUserStrategyModal.module.css";++interface EditUserStrategyModalProps {+ onClose: () => void;+}++export const EditUserStrategyModal = ({+ onClose,+}: EditUserStrategyModalProps) => {+ const dispatch = useDispatch();++ const { isLoading, error, value, updateSetting } =+ useAdminSetting("use-tenants");++ const [addToast] = useToast();+ const { modalContent: confirmationModal, show: showConfirmation } =+ useConfirmation();++ // When the confirmation modal is confirmed, we don't have to show the parent modal while the request is ongoing+ const [isApplyingAfterConfirm, setIsApplyingAfterConfirm] = useState(false);++ const initialStrategy = value ? "multi-tenant" : "single-tenant";++ // Needed to disable the apply button when the strategy does not change+ const [selectedStrategy, setSelectedStrategy] = useState(initialStrategy);++ useEffect(() => {+ setSelectedStrategy(initialStrategy);+ }, [initialStrategy]);++ const isDisablingTenants =+ initialStrategy === "multi-tenant" && selectedStrategy === "single-tenant";++ const handleApply = async () => {+ if (isDisablingTenants) {+ const confirmed = await new Promise<boolean>((resolve) =>+ showConfirmation({+ title: t`Disable tenants?`,+ message: t`Disabling the tenants feature will automatically disable all tenant users. Email addresses must be unique across internal and tenant users, so if you are planning to set up existing tenant users as regular users again, you should first change their email addresses.`,+ confirmButtonText: t`Proceed and disable`,+ onConfirm: () => resolve(true),+ onCancel: () => resolve(false),+ }),+ );++ if (!confirmed) {+ return;+ } else {+ setIsApplyingAfterConfirm(true);+ }+ }++ const response = await updateSetting({+ key: "use-tenants",+ value: selectedStrategy === "multi-tenant",+ });++ // Revert selection to initial value if update fails+ if (response.error) {+ setSelectedStrategy(initialStrategy);+ setIsApplyingAfterConfirm(false);+ return;+ }++ addToast({+ message:+ selectedStrategy === "multi-tenant"+ ? // eslint-disable-next-line no-literal-metabase-strings -- used in admin+ t`You can create tenant collections from the main Metabase navigation`+ : t`Changes saved`,+ });++ dispatch(+ permissionApi.util.invalidateTags([+ "permissions-group",+ "embedding-hub-checklist",+ ]),+ );++ setIsApplyingAfterConfirm(false);+ onClose();+ };++ const handleCancel = () => {+ setSelectedStrategy(initialStrategy);+ onClose();+ };++ const strategyOptions = [+ {+ value: "single-tenant",+ title: t`Single tenant`,+ // eslint-disable-next-line no-literal-metabase-strings -- in admin settings+ description: t`All users exist in the same world and are managed via Metabase groups. Ideal for internal company analytics, proof of concept, or simple embedding setups.`,+ },+ {+ value: "multi-tenant",+ title: t`Multi tenant`,+ description: t`Each tenant operates in an isolated environment with dedicated resources and permissions. Best for SaaS platforms, scalable embedding, or strict data isolation needs.`,+ },+ ];++ return (+ <>+ <Modal+ opened={!confirmationModal && !isApplyingAfterConfirm}+ title={t`User strategy`}+ padding="xl"+ size="md"+ onClose={onClose}+ >+ <LoadingAndErrorWrapper loading={isLoading} error={error}>+ <Stack gap="md" mt="sm">+ <Radio.Group+ value={selectedStrategy}+ onChange={setSelectedStrategy}+ >+ <Stack gap="md">+ {strategyOptions.map((option) => (+ <Radio.Card+ key={option.value}+ value={option.value}+ radius="md"+ p="md"+ className={S.radioCard}+ >+ <Group wrap="nowrap">+ <Radio.Indicator />++ <div>+ <Text fw={700} fz="lg" lh="xl" mb="xs">+ {option.title}+ </Text>++ <Text c="text-secondary" fz="sm" lh="lg">+ {option.description}+ </Text>+ </div>+ </Group>+ </Radio.Card>+ ))}+ </Stack>+ </Radio.Group>++ <Flex justify="flex-end" gap="md" mt="md">+ <Button variant="outline" onClick={handleCancel}>+ {t`Cancel`}+ </Button>++ <Button+ onClick={handleApply}+ disabled={initialStrategy === selectedStrategy}+ variant="filled"+ >{t`Apply`}</Button>+ </Flex>+ </Stack>+ </LoadingAndErrorWrapper>+ </Modal>+ {confirmationModal}+ </>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.unit.spec.tsxnew file mode 100644index 00000000000..91e79735de5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/EditUserStrategyModal.unit.spec.tsx@@ -0,0 +1,255 @@+import { within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ findRequests,+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ createMockSettingDefinition,+ createMockSettings,+} from "metabase-types/api/mocks";+import {+ createMockSettingsState,+ createMockState,+} from "metabase-types/store/mocks";++import { EditUserStrategyModal } from "./EditUserStrategyModal";++interface SetupOpts {+ useTenants?: boolean;+ setupEndpoints?: () => void;+ onClose?: () => void;+}++const setup = async (options?: SetupOpts) => {+ const useTenants = options?.useTenants ?? false;+ const settings = { "use-tenants": useTenants };+ const properties = createMockSettings(settings);++ fetchMock.put("path:/api/setting/use-tenants", 204);+ setupPropertiesEndpoints(properties);+ setupSettingsEndpoints([+ createMockSettingDefinition({ key: "use-tenants", value: useTenants }),+ ]);+ options?.setupEndpoints?.();++ renderWithProviders(+ <EditUserStrategyModal onClose={options?.onClose ?? (() => {})} />,+ {+ storeInitialState: createMockState({+ settings: createMockSettingsState(settings),+ }),+ },+ );+};++describe("EditUserStrategyModal", () => {+ it("should handle loading state", async () => {+ await setup();+ expect(screen.getByText("Loading...")).toBeInTheDocument();+ await screen.findByText("User strategy");+ });++ it("should correctly select single-tenancy if use-tenants setting is false", async () => {+ await setup();++ expect(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();+ });++ it("should correctly display multi-tenancy as selected if use-tenants setting is true", async () => {+ await setup({ useTenants: true });++ expect(+ await screen.findByRole("radio", {+ name: /Multi tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();+ });++ it("should allow changing selection and applying the change", async () => {+ await setup();++ const multiTenantCard = await screen.findByRole("radio", {+ name: /Multi tenant/,+ checked: false,+ });+ expect(multiTenantCard).toBeInTheDocument();+ await userEvent.click(multiTenantCard);++ expect(+ screen.getByRole("radio", { name: /Multi tenant/, checked: true }),+ ).toBeInTheDocument();++ const applyButton = screen.getByRole("button", { name: /Apply/ });+ await userEvent.click(applyButton);++ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ });++ const puts = await findRequests("PUT");+ expect(puts[0].body).toEqual({ value: true });+ });++ it("asks for confirmation before disabling and only sends after confirm", async () => {+ await setup({ useTenants: true });++ await userEvent.click(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: false,+ }),+ );++ await userEvent.click(screen.getByRole("button", { name: /Apply/ }));++ const confirmModal = await screen.findByTestId("confirm-modal");+ expect(+ within(confirmModal).getByText(/Disable tenants\?/i),+ ).toBeInTheDocument();++ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(0);+ });++ await userEvent.click(+ within(confirmModal).getByRole("button", {+ name: /Proceed and disable/i,+ }),+ );++ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ });++ const puts = await findRequests("PUT");+ expect(puts[0].body).toEqual({ value: false });+ });++ it("closes confirmation without sending when disabling is cancelled", async () => {+ await setup({ useTenants: true });++ await userEvent.click(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: false,+ }),+ );++ await userEvent.click(screen.getByRole("button", { name: /Apply/ }));++ const confirmModal = await screen.findByTestId("confirm-modal");+ await userEvent.click(+ within(confirmModal).getByRole("button", { name: /Cancel/i }),+ );++ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(0);+ });++ expect(+ screen.getByRole("radio", { name: /Single tenant/, checked: true }),+ ).toBeInTheDocument();+ });++ it("reverts the selected user strategy if the setting update fails", async () => {+ fetchMock.put("path:/api/setting/use-tenants", {+ throws: new Error("Internal server error"),+ });++ await setup();++ expect(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();++ const multiTenantCard = screen.getByRole("radio", {+ name: /Multi tenant/,+ });+ await userEvent.click(multiTenantCard);++ const applyButton = screen.getByRole("button", { name: /Apply/ });+ await userEvent.click(applyButton);++ await waitFor(() => findRequests("PUT"));++ // Revert to single tenant as the API call failed+ expect(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();+ });++ it("should disable the apply button when the user strategy has not changed", async () => {+ await setup();++ expect(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();++ const applyButton = screen.getByRole("button", { name: /Apply/ });+ expect(applyButton).toBeDisabled();++ await userEvent.click(screen.getByRole("radio", { name: /Multi tenant/ }));+ expect(applyButton).toBeEnabled();++ await userEvent.click(screen.getByRole("radio", { name: /Single tenant/ }));+ expect(applyButton).toBeDisabled();+ });++ it("should clear selection when cancel button is clicked", async () => {+ const onClose = jest.fn();+ await setup({ onClose });++ expect(+ await screen.findByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();++ // Change selection to multi-tenant+ await userEvent.click(screen.getByRole("radio", { name: /Multi tenant/ }));++ expect(+ screen.getByRole("radio", { name: /Multi tenant/, checked: true }),+ ).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: /Cancel/ }));++ // selection should revert back to single tenant+ expect(+ screen.getByRole("radio", {+ name: /Single tenant/,+ checked: true,+ }),+ ).toBeInTheDocument();++ expect(onClose).toHaveBeenCalledTimes(1);++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(0);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/index.tsxnew file mode 100644index 00000000000..1ff9a9a0010--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategyModal/index.tsx@@ -0,0 +1 @@+export * from "./EditUserStrategyModal";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategySettingsButton.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategySettingsButton.tsxnew file mode 100644index 00000000000..aec4080c79c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/EditUserStrategySettingsButton.tsx@@ -0,0 +1,20 @@+import { Link } from "react-router";+import { t } from "ttag";++import { ActionIcon, Icon, Tooltip } from "metabase/ui";+import * as Urls from "metabase-enterprise/urls";++export const EditUserStrategySettingsButton = () => (+ <Link to={Urls.editUserStrategy()}>+ <Tooltip label={t`Edit user strategy`}>+ <ActionIcon+ size="lg"+ variant="outline"+ c="text-primary"+ bd="1px solid var(--mb-color-border)"+ >+ <Icon name="gear" />+ </ActionIcon>+ </Tooltip>+ </Link>+);diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/CreateTenantCollectionButton.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/CreateTenantCollectionButton.tsxnew file mode 100644index 00000000000..d8c3e3c359b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/CreateTenantCollectionButton.tsx@@ -0,0 +1,57 @@+import { useDisclosure } from "@mantine/hooks";+import { useCallback } from "react";+import { push } from "react-router-redux";+import { t } from "ttag";++import { useCreateCollectionMutation } from "metabase/api";+import { CreateCollectionForm } from "metabase/collections/components/CreateCollectionForm";+import type { CreateCollectionProperties } from "metabase/collections/components/CreateCollectionForm/CreateCollectionForm";+import { useDispatch } from "metabase/lib/redux";+import { ActionIcon, Icon, Modal, Tooltip } from "metabase/ui";+import { Urls } from "metabase-enterprise/urls";++export const CreateTenantCollectionButton = () => {+ const [isModalOpen, modal] = useDisclosure(false);+ const [createCollection] = useCreateCollectionMutation();+ const dispatch = useDispatch();++ const handleCreateTenantCollection = useCallback(+ async (values: CreateCollectionProperties) => {+ const result = await createCollection({+ ...values,+ parent_id: null,+ namespace: "shared-tenant-collection",+ });++ dispatch(push(Urls.collection(result.data)));+ },+ [createCollection, dispatch],+ );++ return (+ <>+ <Tooltip label={t`Create shared collection`}>+ <ActionIcon+ size="lg"+ onClick={modal.open}+ variant="outline"+ c="text-primary"+ bd="1px solid var(--mb-color-border)"+ >+ <Icon name="add_collection" />+ </ActionIcon>+ </Tooltip>++ <Modal+ opened={isModalOpen}+ title={t`New shared collection`}+ onClose={modal.close}+ >+ <CreateCollectionForm+ showCollectionPicker={false}+ onSubmit={handleCreateTenantCollection}+ />+ </Modal>+ </>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/index.tsnew file mode 100644index 00000000000..647d1b2dfaa--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/CreateTenantCollectionButton/index.ts@@ -0,0 +1 @@+export { CreateTenantCollectionButton } from "./CreateTenantCollectionButton";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupDetailApp/ExternalGroupDetailApp.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupDetailApp/ExternalGroupDetailApp.tsxnew file mode 100644index 00000000000..5cfd472aebe--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupDetailApp/ExternalGroupDetailApp.tsx@@ -0,0 +1,9 @@+import { t } from "ttag";++import { GroupDetailApp } from "metabase/admin/people/containers/GroupDetailApp";++export const ExternalGroupDetailApp = (props: {+ params: { groupId: number };+}) => {+ return <GroupDetailApp title={t`Tenant Groups`} {...props} />;+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupsListingApp/ExternalGroupsListingApp.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupsListingApp/ExternalGroupsListingApp.tsxnew file mode 100644index 00000000000..d8cb318d579--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalGroupsListingApp/ExternalGroupsListingApp.tsx@@ -0,0 +1,12 @@+import { t } from "ttag";++import { GroupsListingApp } from "metabase/admin/people/containers/GroupsListingApp";++export const ExternalGroupsListingApp = () => {+ return (+ <GroupsListingApp+ description={t`Use tenant groups to manage access for tenant users. Every tenant has access to these groups.`}+ external+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.tsxnew file mode 100644index 00000000000..afd8e1568f2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.tsx@@ -0,0 +1,25 @@+import { t } from "ttag";++import { PeopleListingApp } from "metabase/admin/people/containers/PeopleListingApp";+import { useListTenantsQuery } from "metabase-enterprise/api";++export const ExternalPeopleListingApp = (props: React.PropsWithChildren) => {+ const { data: tenants } = useListTenantsQuery({+ status: "active",+ });++ const hasTenants = !!(tenants && tenants.data.length > 0);++ return (+ <PeopleListingApp+ {...props}+ external+ showInviteButton={hasTenants}+ noResultsMessage={+ !hasTenants+ ? t`Add your first tenant to add tenant users`+ : t`Invite tenant users or provision them via SSO`+ }+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.unit.spec.tsxnew file mode 100644index 00000000000..c66e465f7a1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ExternalPeopleListingApp/ExternalPeopleListingApp.unit.spec.tsx@@ -0,0 +1,108 @@+import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupPermissionMembershipEndpoint,+ setupTenantEntpoints,+ setupUsersEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import type { Tenant, User } from "metabase-types/api";+import {+ createMockTenant,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import { ExternalPeopleListingApp } from "./ExternalPeopleListingApp";++const setup = ({+ tenants = [],+ users = [createMockUser()],+ currentUser = createMockUser({+ is_superuser: true,+ }),+}: {+ tenants?: Tenant[];+ users?: User[];+ currentUser?: User;+} = {}) => {+ const settings = mockSettings({+ "token-features": createMockTokenFeatures({+ tenants: true,+ }),+ });++ setupUsersEndpoints(users);++ setupEnterprisePlugins();+ setupTenantEntpoints(tenants);+ setupPermissionMembershipEndpoint({});++ renderWithProviders(<ExternalPeopleListingApp />, {+ storeInitialState: createMockState({+ settings,+ currentUser,+ }),+ });+};++describe("ExternalPeopleListingApp", () => {+ it("should show tenant association when viewing users", async () => {+ setup({+ users: [createMockUser({ tenant_id: 2 })],+ tenants: [createMockTenant({ id: 2, name: "Testy Tenant" })],+ });++ expect(await screen.findByText("Name")).toBeInTheDocument();+ expect(await screen.findByText("Email")).toBeInTheDocument();+ expect(await screen.findByText("Tenant")).toBeInTheDocument();+ expect(await screen.findByText("Last Login")).toBeInTheDocument();++ expect(await screen.findByText("Testy Tableton")).toBeInTheDocument();+ expect(await screen.findByText("Testy Tenant")).toBeInTheDocument();+ });++ it("should not show a user strategy button", async () => {+ setup();++ expect(+ screen.queryByRole("button", { name: /gear/i }),+ ).not.toBeInTheDocument();+ });++ it("should show an invite button if there are tenants", async () => {+ setup({+ tenants: [createMockTenant({})],+ });++ expect(await screen.findByText("Create tenant user")).toBeInTheDocument();+ });++ it("should not show an invite button if there are no tenants", async () => {+ setup({});++ expect(screen.queryByText("Create tenant user")).not.toBeInTheDocument();+ });++ it("should show a no results special message if there are no tenants", async () => {+ setup({+ users: [],+ });++ expect(+ await screen.findByText("Add your first tenant to add tenant users"),+ ).toBeInTheDocument();+ });++ it("should show a no results special message if there are tenants", async () => {+ setup({+ users: [],+ tenants: [createMockTenant()],+ });++ expect(+ await screen.findByText("Invite tenant users or provision them via SSO"),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsxnew file mode 100644index 00000000000..a121342921d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx@@ -0,0 +1,162 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import {+ useCreateCollectionMutation,+ useListCollectionsQuery,+ useListCollectionsTreeQuery,+} from "metabase/api";+import { CreateCollectionForm } from "metabase/collections/components/CreateCollectionForm";+import type { CreateCollectionProperties } from "metabase/collections/components/CreateCollectionForm/CreateCollectionForm";+import { Tree } from "metabase/common/components/tree";+import { useSetting } from "metabase/common/hooks";+import { buildCollectionTree } from "metabase/entities/collections";+import { useSelector } from "metabase/lib/redux";+import { tenantSpecificCollections } from "metabase/lib/urls";+import {+ PaddedSidebarLink,+ SidebarHeading,+ SidebarSection,+} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";+import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";+import { getUser, getUserIsAdmin } from "metabase/selectors/user";+import { ActionIcon, Flex, Icon, Modal, Tooltip } from "metabase/ui";+import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";+import { CollectionSyncStatusBadge } from "metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge";++export const MainNavSharedCollections = () => {+ const [modalOpen, setModalOpen] = useState(false);+ const isTenantsEnabled = useSetting("use-tenants");+ const isAdmin = useSelector(getUserIsAdmin);+ const currentUser = useSelector(getUser);++ const { data: tenantCollections } = useListCollectionsTreeQuery(+ { namespace: "shared-tenant-collection" },+ {+ skip: !isTenantsEnabled,+ },+ );++ // Fetch flat list of tenant collections to check if any are remote-synced+ const { data: tenantCollectionsList = [] } = useListCollectionsQuery(+ { namespace: "shared-tenant-collection" },+ { skip: !isTenantsEnabled },+ );++ // Check if any tenant collections have is_remote_synced=true+ const hasRemoteSyncedTenantCollections = useMemo(+ () => tenantCollectionsList.some((c) => c.is_remote_synced),+ [tenantCollectionsList],+ );++ const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {+ skip: !hasRemoteSyncedTenantCollections,+ refetchOnFocus: true,+ });++ const [createCollection] = useCreateCollectionMutation();++ const tenantCollectionTree = useMemo(+ () => buildCollectionTree(tenantCollections),+ [tenantCollections],+ );++ const changedCollections = useMemo(+ () => dirtyData?.changedCollections ?? {},+ [dirtyData?.changedCollections],+ );++ const showChangesBadge = useCallback(+ (itemId?: number | string) => {+ if (+ !hasRemoteSyncedTenantCollections ||+ !changedCollections ||+ typeof itemId !== "number"+ ) {+ return false;+ }++ return !!changedCollections[itemId];+ },+ [hasRemoteSyncedTenantCollections, changedCollections],+ );++ const handleCreateTenantCollection = useCallback(+ async (values: CreateCollectionProperties) => {+ await createCollection({+ ...values,+ parent_id: null,+ namespace: "shared-tenant-collection",+ });+ setModalOpen(false);+ },+ [createCollection],+ );++ if (!isTenantsEnabled) {+ return null;+ }++ const userTenantCollectionId = currentUser?.tenant_collection_id;+ const hasVisibleTenantCollections = tenantCollectionTree.length > 0;+ const shouldShowSharedCollectionsSection =+ isAdmin || hasVisibleTenantCollections;++ return (+ <>+ {userTenantCollectionId && (+ <SidebarSection>+ <SidebarHeading>{t`My tenant collection`}</SidebarHeading>+ <PaddedSidebarLink+ icon="folder"+ url={`/collection/${userTenantCollectionId}`}+ >+ {t`My Tenant Collection`}+ </PaddedSidebarLink>+ </SidebarSection>+ )}++ {shouldShowSharedCollectionsSection && (+ <SidebarSection>+ <Flex align="center" justify="space-between">+ <SidebarHeading>{t`External collections`}</SidebarHeading>+ {isAdmin && (+ <Tooltip label={t`Create a shared collection`}>+ <ActionIcon+ color="text-medium"+ onClick={() => setModalOpen(true)}+ >+ <Icon name="add" />+ </ActionIcon>+ </Tooltip>+ )}+ </Flex>+ <Tree+ data={tenantCollectionTree}+ TreeNode={SidebarCollectionLink}+ role="tree"+ aria-label="tenant-collection-tree"+ rightSection={(item) =>+ showChangesBadge(item?.id) && <CollectionSyncStatusBadge />+ }+ />+ {isAdmin && (+ <PaddedSidebarLink icon="group" url={tenantSpecificCollections()}>+ {t`Tenant collections`}+ </PaddedSidebarLink>+ )}+ </SidebarSection>+ )}+ <Modal+ opened={modalOpen}+ title={t`New shared collection`}+ onClose={() => setModalOpen(false)}+ >+ <CreateCollectionForm+ showCollectionPicker={false}+ onSubmit={handleCreateTenantCollection}+ />+ </Modal>+ </>+ );+};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.tsxnew file mode 100644index 00000000000..37848e81280--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx@@ -0,0 +1,90 @@+import fetchMock from "fetch-mock";++import { setupCollectionsEndpoints } from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import type { Collection } from "metabase-types/api";+import { createMockCollection, createMockUser } from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import { MainNavSharedCollections } from "./MainNavSharedCollections";++const MOCK_TENANT_COLLECTIONS = [+ createMockCollection({+ id: 1,+ name: "Tenant Collection 1",+ namespace: "shared-tenant-collection",+ }),+];++const setup = ({+ isAdmin = false,+ tenantCollections = MOCK_TENANT_COLLECTIONS,+ currentUser = createMockUser({ is_superuser: isAdmin }),+}: {+ isAdmin?: boolean;+ tenantCollections?: Collection[];+ currentUser?: ReturnType<typeof createMockUser>;+} = {}) => {+ const settings = mockSettings({ "use-tenants": true });+ setupCollectionsEndpoints({ collections: tenantCollections });++ renderWithProviders(<MainNavSharedCollections />, {+ storeInitialState: createMockState({ settings, currentUser }),+ });+};++describe("MainNavSharedCollections > create shared tenant collection button", () => {+ it("shows the create button for admin users", async () => {+ setup({ isAdmin: true });+ await screen.findByText("External collections");++ expect(screen.getByRole("button", { name: /add/i })).toBeInTheDocument();+ });++ it("hides the create button for non-admin users", async () => {+ setup({ isAdmin: false });+ await screen.findByText("External collections");++ expect(+ screen.queryByRole("button", { name: /add/i }),+ ).not.toBeInTheDocument();+ });+});++describe("MainNavSharedCollections > section visibility", () => {+ it("shows the section for admins when there are no collections", async () => {+ setup({ isAdmin: true, tenantCollections: [] });++ expect(await screen.findByText("External collections")).toBeInTheDocument();+ });++ it("shows the section for non-admins when some collections exist", async () => {+ setup({ isAdmin: false, tenantCollections: MOCK_TENANT_COLLECTIONS });++ expect(await screen.findByText("External collections")).toBeInTheDocument();+ });++ it("hides the section for non-admins when there are no collections", () => {+ setup({ isAdmin: false, tenantCollections: [] });++ expect(screen.queryByText("External collections")).not.toBeInTheDocument();+ });++ it("hides the section for non-admins when collections exist but are filtered out by permissions", () => {+ const settings = mockSettings({ "use-tenants": true });+ const currentUser = createMockUser({ is_superuser: false });++ // List endpoint has some collections (exists in the DB)+ fetchMock.get("path:/api/collection", () => MOCK_TENANT_COLLECTIONS);++ // Tree endpoint returns an empty array as it is filtered by permissions+ fetchMock.get("path:/api/collection/tree", () => []);++ renderWithProviders(<MainNavSharedCollections />, {+ storeInitialState: createMockState({ settings, currentUser }),+ });++ expect(screen.queryByText("External collections")).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/index.tsnew file mode 100644index 00000000000..ee539a89340--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/index.ts@@ -0,0 +1 @@+export * from "./MainNavSharedCollections";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/ReactivateExternalUserButton.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/ReactivateExternalUserButton.tsxnew file mode 100644index 00000000000..f53064bff25--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/ReactivateExternalUserButton.tsx@@ -0,0 +1,28 @@+import { t } from "ttag";++import { ReactivateUserButton } from "metabase/admin/people/components/ReactivateUserButton";+import { useListTenantsQuery } from "metabase-enterprise/api";+import type { User } from "metabase-types/api";++export const ReactivateExternalUserButton = ({ user }: { user: User }) => {+ // This is set to all to avoid making another API request to the BE. <TenantDisplayName> should be+ // Making the same API request, so we can leverage the cached result+ const { data: tenants } = useListTenantsQuery({+ status: "all",+ });++ const userTenantIsActive = Boolean(+ tenants?.data.find((tenants) => tenants.id === user.tenant_id)?.is_active,+ );+ const tooltip = !userTenantIsActive+ ? t`Cannot reactivate users on a disabled tenant`+ : undefined;++ return (+ <ReactivateUserButton+ user={user}+ disabled={!userTenantIsActive}+ tooltipLabel={tooltip}+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/index.tsnew file mode 100644index 00000000000..94679cb0990--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/ReactivateExternalUserButton/index.ts@@ -0,0 +1 @@+export * from "./ReactivateExternalUserButton";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsxnew file mode 100644index 00000000000..888048f05ab--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/TenantCollectionItemList.tsx@@ -0,0 +1,38 @@+import { useListCollectionItemsQuery } from "metabase/api";+import { ItemList } from "metabase/common/components/EntityPicker/components/ItemList";+import type {+ CollectionItemListProps,+ CollectionPickerItem,+} from "metabase/common/components/Pickers/CollectionPicker/types";++export const TenantCollectionItemList = ({+ onClick,+ selectedItem,+ isFolder,+ isCurrentLevel,+ shouldDisableItem,+ shouldShowItem,+}: CollectionItemListProps) => {+ const {+ data: collectionItems,+ error,+ isLoading,+ } = useListCollectionItemsQuery({+ id: "root",+ namespace: "shared-tenant-collection",+ });++ return (+ <ItemList+ items={collectionItems?.data as CollectionPickerItem[] | undefined}+ isLoading={isLoading}+ error={error}+ onClick={onClick}+ selectedItem={selectedItem}+ isFolder={isFolder}+ isCurrentLevel={isCurrentLevel}+ shouldDisableItem={shouldDisableItem}+ shouldShowItem={shouldShowItem}+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/index.tsnew file mode 100644index 00000000000..7b828eb880b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionItemList/index.ts@@ -0,0 +1 @@+export * from "./TenantCollectionItemList";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.styled.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.styled.tsxnew file mode 100644index 00000000000..ed332679d40--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.styled.tsx@@ -0,0 +1,20 @@+import styled from "@emotion/styled";++import { GridItem } from "metabase/common/components/Grid";++export const ListHeader = styled.div`+ padding: 1rem 0;+`;++export const ListGridItem = styled(GridItem)`+ width: 33.33%;++ &:hover {+ color: var(--mb-color-brand);+ }+`;++export const CardContent = styled.div`+ display: flex;+ align-items: center;+`;diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.tsxnew file mode 100644index 00000000000..ced2a60cd66--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/TenantCollectionList.tsx@@ -0,0 +1,65 @@+import { t } from "ttag";++import { BrowserCrumbs } from "metabase/common/components/BrowserCrumbs";+import { Grid } from "metabase/common/components/Grid";+import Link from "metabase/common/components/Link";+import CS from "metabase/css/core/index.css";+import { ROOT_COLLECTION } from "metabase/entities/collections/constants";+import * as Urls from "metabase/lib/urls";+import { Box, Card, Flex, Group, Icon, Loader } from "metabase/ui";+import { useListTenantsQuery } from "metabase-enterprise/api";++import { ListGridItem, ListHeader } from "./TenantCollectionList.styled";++export const TenantCollectionList = () => {+ const { data, isLoading } = useListTenantsQuery({ status: "active" });++ const tenants = data?.data ?? [];++ return (+ <Flex direction="column" p="1.5rem" h="100%">+ <ListHeader>+ <BrowserCrumbs+ crumbs={[+ {+ title: ROOT_COLLECTION.name,+ to: Urls.collection({ id: "root", name: "" }),+ },+ { title: t`Tenant collections` },+ ]}+ />+ </ListHeader>+ <Box style={{ flexGrow: 1, overflowY: "auto" }} pr="0.5rem">+ {isLoading ? (+ <Flex justify="center" align="center" h="100%">+ <Loader size="lg" />+ </Flex>+ ) : (+ <Grid>+ {tenants.map(+ (tenant) =>+ tenant.tenant_collection_id && (+ <ListGridItem key={tenant.id} role="list-item">+ <Link to={`/collection/${tenant.tenant_collection_id}`}>+ <Card shadow="none" withBorder>+ <Group gap="xs">+ <Icon+ name="folder"+ className={CS.mr1}+ c="text-medium"+ size={18}+ />++ <h3>{tenant.name}</h3>+ </Group>+ </Card>+ </Link>+ </ListGridItem>+ ),+ )}+ </Grid>+ )}+ </Box>+ </Flex>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/index.tsnew file mode 100644index 00000000000..2228f377045--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionList/index.ts@@ -0,0 +1 @@+export { TenantCollectionList } from "./TenantCollectionList";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsxnew file mode 100644index 00000000000..725861f64a2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/TenantCollectionPermissionsPage.tsx@@ -0,0 +1,152 @@+import { useCallback, useEffect } 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 {+ initializeTenantCollectionPermissions,+ loadTenantCollectionPermissions,+ saveTenantCollectionPermissions,+ updateTenantCollectionPermission,+} from "metabase/admin/permissions/permissions";+import type {+ CollectionIdProps,+ CollectionPermissionEditorType,+ CollectionSidebarType,+} from "metabase/admin/permissions/selectors/collection-permissions";+import Collections from "metabase/entities/collections";+import Groups from "metabase/entities/groups";+import { connect } from "metabase/lib/redux";+import type { Collection, CollectionId, GroupId } from "metabase-types/api";+import type { State } from "metabase-types/store";++import {+ getIsTenantDirty,+ getTenantCollectionEntity,+ getTenantCollectionsPermissionEditor,+ getTenantCollectionsSidebar,+ tenantCollectionsQuery,+} from "./selectors";++const mapDispatchToProps = {+ initialize: initializeTenantCollectionPermissions,+ loadPermissions: loadTenantCollectionPermissions,+ navigateToItem: ({ id }: { id: CollectionId }) =>+ push(`/admin/permissions/tenant-collections/${id}`),+ updateCollectionPermission: updateTenantCollectionPermission,+ savePermissions: saveTenantCollectionPermissions,+};++const mapStateToProps = (state: State, props: CollectionIdProps) => {+ return {+ sidebar: getTenantCollectionsSidebar(state, props),+ permissionEditor: getTenantCollectionsPermissionEditor(state, props),+ isDirty: getIsTenantDirty(state),+ collection: getTenantCollectionEntity(state, props),+ };+};++type UpdateCollectionPermissionParams = {+ groupId: GroupId;+ collection: Collection;+ value: unknown;+ shouldPropagate: boolean;+};++type TenantCollectionPermissionsPageProps = {+ params: CollectionIdProps["params"];+ sidebar: CollectionSidebarType;+ permissionEditor: CollectionPermissionEditorType;+ collection: Collection;+ navigateToItem: (item: { id: CollectionId }) => void;+ updateCollectionPermission: ({+ groupId,+ collection,+ value,+ shouldPropagate,+ }: UpdateCollectionPermissionParams) => void;+ isDirty: boolean;+ savePermissions: () => void;+ loadPermissions: () => void;+ initialize: () => void;+ route: Route;+};++function TenantCollectionPermissionsPageView({+ sidebar,+ permissionEditor,+ collection,+ isDirty,+ savePermissions,+ loadPermissions,+ updateCollectionPermission,+ navigateToItem,+ initialize,+ route,+}: TenantCollectionPermissionsPageProps) {+ useEffect(() => {+ initialize();+ }, [initialize]);++ const handlePermissionChange = useCallback(+ (+ item: { id: GroupId },+ _permission: unknown,+ value: unknown,+ toggleState: boolean,+ ) => {+ updateCollectionPermission({+ groupId: item.id,+ collection,+ value,+ shouldPropagate: toggleState,+ });+ },+ [collection, updateCollectionPermission],+ );++ return (+ <PermissionsPageLayout+ tab="tenant-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 TenantCollectionPermissionsPage = _.compose(+ Collections.loadList({+ entityQuery: tenantCollectionsQuery,+ }),+ Groups.loadList(),+ connect(mapStateToProps, mapDispatchToProps),+)(TenantCollectionPermissionsPageView);diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/index.tsnew file mode 100644index 00000000000..3b7c449c5ff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/index.ts@@ -0,0 +1 @@+export { TenantCollectionPermissionsPage } from "./TenantCollectionPermissionsPage";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.tsxnew file mode 100644index 00000000000..0177a015607--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.tsx@@ -0,0 +1,286 @@+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 { buildCollectionTree } from "metabase/admin/permissions/selectors/collection-permissions";+import { getPermissionWarningModal } from "metabase/admin/permissions/selectors/confirmations";+import type { DataPermissionValue } from "metabase/admin/permissions/types";+import Collections, {+ ROOT_COLLECTION,+ getCollectionIcon,+} from "metabase/entities/collections";+import Group from "metabase/entities/groups";+import { getGroupNameLocalized, isAdminGroup } from "metabase/lib/groups";+import { PLUGIN_TENANTS } from "metabase/plugins";+import type {+ Collection,+ CollectionId,+ CollectionPermissions,+ Group as GroupType,+} from "metabase-types/api";+import type { ExpandedCollection, State } from "metabase-types/store";++export const tenantCollectionsQuery = {+ tree: true,+ "exclude-other-user-collections": true,+ "exclude-archived": true,+ namespace: "shared-tenant-collection",+};++export const getIsTenantDirty = createSelector(+ (state: State) => state.admin.permissions.tenantCollectionPermissions,+ (state: State) => state.admin.permissions.originalTenantCollectionPermissions,+ (+ permissions: CollectionPermissions,+ originalPermissions: CollectionPermissions,+ ) => JSON.stringify(permissions) !== JSON.stringify(originalPermissions),+);++export const getCurrentTenantCollectionId = (+ _state: State,+ props: CollectionIdProps,+) => {+ if (props.params.collectionId == null) {+ return undefined;+ }++ return props.params.collectionId === ROOT_COLLECTION.id+ ? ROOT_COLLECTION.id+ : parseInt(String(props.params.collectionId));+};++const getTenantRootCollectionTreeItem = () => {+ const rootCollectionIcon = getCollectionIcon(ROOT_COLLECTION);+ return {+ ...ROOT_COLLECTION,+ name: t`Root shared collection`,+ icon: rootCollectionIcon.name,+ iconColor: rootCollectionIcon.color,+ };+};++const getTenantCollections = (state: State) =>+ Collections.selectors.getList(state, {+ entityQuery: tenantCollectionsQuery,+ }) ?? [];++const getTenantCollectionsTree = createSelector(+ [getTenantCollections],+ (collections) => {+ return [+ getTenantRootCollectionTreeItem(),+ ...buildCollectionTree(collections),+ ];+ },+);++export const getTenantCollectionsSidebar = createSelector(+ getTenantCollectionsTree,+ getCurrentTenantCollectionId,+ (collectionsTree, collectionId): CollectionSidebarType => {+ return {+ selectedId: collectionId,+ title: t`Tenant Collections`,+ entityGroups: [collectionsTree || []],+ filterPlaceholder: t`Search for a collection`,+ };+ },+);++const getTenantCollectionsPermissions = (state: State) =>+ state.admin.permissions.tenantCollectionPermissions;++const findCollection = (+ collections: Collection[],+ collectionId: CollectionId,+): Collection | null => {+ if (collections.length === 0) {+ return null;+ }++ const collection = collections.find(+ (collection) => collection.id === collectionId,+ );++ if (collection) {+ return collection;+ }++ return findCollection(+ collections.map((collection) => collection.children ?? []).flat(),+ collectionId,+ );+};++const getTenantCollection = createSelector(+ [getCurrentTenantCollectionId, getTenantCollections],+ (collectionId, collections) => {+ if (collectionId == null) {+ return null;+ }++ if (collectionId === ROOT_COLLECTION.id) {+ return {+ ...ROOT_COLLECTION,+ name: t`Root shared collection`,+ children: collections,+ };+ }++ return findCollection(collections, collectionId);+ },+);++export const getTenantCollectionEntity = (+ state: State,+ props: CollectionIdProps,+) => {+ return getTenantCollection(state, props);+};++const getTenantCollectionPermission = (+ permissions: CollectionPermissions,+ groupId: number,+ collectionId: CollectionId,+) => getIn(permissions, [groupId, collectionId]) || "none";++export const getTenantCollectionsPermissionEditor = createSelector(+ getTenantCollectionsPermissions,+ getTenantCollectionEntity,+ Group.selectors.getList,+ (permissions, collection, groups): CollectionPermissionEditorType => {+ if (!permissions || collection == null) {+ return null;+ }++ const hasChildren = collection.children?.length > 0;+ const toggleLabel = hasChildren ? t`Also change sub-collections` : null;++ const entities = groups+ .map((group: GroupType) => {+ const isAdmin = isAdminGroup(group);+ const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);++ const defaultGroup = _.find(+ groups,+ PLUGIN_TENANTS.isExternalUsersGroup,+ );++ const defaultGroupPermission = defaultGroup+ ? getTenantCollectionPermission(+ permissions,+ defaultGroup.id,+ collection.id,+ )+ : "none";++ const confirmations = (newValue: DataPermissionValue) => [+ getPermissionWarningModal(+ newValue,+ defaultGroupPermission,+ null,+ defaultGroup,+ group.id,+ ),+ ];++ const options = isTenantGroup+ ? [COLLECTION_OPTIONS.read, COLLECTION_OPTIONS.none]+ : [+ COLLECTION_OPTIONS.write,+ COLLECTION_OPTIONS.read,+ COLLECTION_OPTIONS.none,+ ];++ const disabledTooltip = isTenantGroup+ ? Messages.EXTERNAL_USERS_NO_ACCESS_COLLECTION+ : Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;++ const disabled = isAdmin;++ return {+ id: group.id,+ name: getGroupNameLocalized(group),+ icon: isTenantGroup ? (+ <PLUGIN_TENANTS.TenantGroupHintIcon />+ ) : undefined,+ permissions: [+ {+ toggleLabel,+ hasChildren,+ isDisabled: disabled,+ disabledTooltip: disabled ? disabledTooltip : null,+ value: getTenantCollectionPermission(+ permissions,+ group.id,+ collection.id,+ ),+ warning: getTenantCollectionWarning(+ 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 getTenantCollectionWarning(+ groupId: number,+ collection: ExpandedCollection,+ permissions: CollectionPermissions,+) {+ if (!collection) {+ return;+ }+ const collectionPerm = getTenantCollectionPermission(+ permissions,+ groupId,+ collection.id,+ );+ const descendentCollections = getDescendentCollections(collection);+ const descendentPerms = new Set(+ descendentCollections.map((c) =>+ getTenantCollectionPermission(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/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.tsnew file mode 100644index 00000000000..452a0d40311--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantCollectionPermissionsPage/selectors.unit.spec.ts@@ -0,0 +1,165 @@+import { setupEnterprisePlugins } from "__support__/enterprise";+import { mockSettings } from "__support__/settings";+import type { CollectionPermissions } from "metabase-types/api";+import { createMockTokenFeatures } from "metabase-types/api/mocks";+import type { State } from "metabase-types/store";+import {+ createMockAdminState,+ createMockState,+} from "metabase-types/store/mocks";++import {+ getCurrentTenantCollectionId,+ getIsTenantDirty,+ tenantCollectionsQuery,+} from "./selectors";++// Note: The more complex selectors (getTenantCollectionsSidebar,+// getTenantCollectionsPermissionEditor, getTenantCollectionEntity)+// depend on entity framework state which requires full store setup.+// These are better tested via integration tests.++const ADMIN_GROUP_ID = 2;+const ALL_USERS_GROUP_ID = 1;++const createMockStateWithPermissions = ({+ tenantCollectionPermissions = {},+ originalTenantCollectionPermissions = {},+}: {+ tenantCollectionPermissions?: CollectionPermissions;+ originalTenantCollectionPermissions?: CollectionPermissions;+} = {}): State => {+ const state = createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({ tenants: true }),+ }),+ admin: createMockAdminState({+ permissions: {+ dataPermissions: {},+ originalDataPermissions: {},+ collectionPermissions: {},+ originalCollectionPermissions: {},+ tenantCollectionPermissions,+ originalTenantCollectionPermissions,+ isHelpReferenceOpen: false,+ hasRevisionChanged: { revision: null, hasChanged: false },+ },+ }),+ });++ return state as unknown as State;+};++describe("TenantCollectionPermissionsPage selectors", () => {+ beforeEach(() => {+ setupEnterprisePlugins();+ });++ describe("tenantCollectionsQuery", () => {+ it("should have correct query parameters", () => {+ expect(tenantCollectionsQuery).toEqual({+ tree: true,+ "exclude-other-user-collections": true,+ "exclude-archived": true,+ namespace: "shared-tenant-collection",+ });+ });+ });++ describe("getIsTenantDirty", () => {+ it("should return false when permissions are unchanged", () => {+ const permissions: CollectionPermissions = {+ [ADMIN_GROUP_ID]: { root: "write", 100: "write" },+ [ALL_USERS_GROUP_ID]: { root: "none", 100: "none" },+ };++ const state = createMockStateWithPermissions({+ tenantCollectionPermissions: permissions,+ originalTenantCollectionPermissions: permissions,+ });++ expect(getIsTenantDirty(state)).toBe(false);+ });++ it("should return true when permissions are changed", () => {+ const state = createMockStateWithPermissions({+ tenantCollectionPermissions: {+ [ADMIN_GROUP_ID]: { root: "write", 100: "write" },+ [ALL_USERS_GROUP_ID]: { root: "read", 100: "read" },+ },+ originalTenantCollectionPermissions: {+ [ADMIN_GROUP_ID]: { root: "write", 100: "write" },+ [ALL_USERS_GROUP_ID]: { root: "none", 100: "none" },+ },+ });++ expect(getIsTenantDirty(state)).toBe(true);+ });++ it("should return false when both are empty objects", () => {+ const state = createMockStateWithPermissions({+ tenantCollectionPermissions: {},+ originalTenantCollectionPermissions: {},+ });++ expect(getIsTenantDirty(state)).toBe(false);+ });++ it("should detect deeply nested permission changes", () => {+ const state = createMockStateWithPermissions({+ tenantCollectionPermissions: {+ [ADMIN_GROUP_ID]: { root: "write", 100: "write", 101: "read" },+ },+ originalTenantCollectionPermissions: {+ [ADMIN_GROUP_ID]: { root: "write", 100: "write", 101: "none" },+ },+ });++ expect(getIsTenantDirty(state)).toBe(true);+ });+ });++ describe("getCurrentTenantCollectionId", () => {+ it("should return undefined when collectionId is null", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: null as any } };++ expect(getCurrentTenantCollectionId(state, props)).toBeUndefined();+ });++ it("should return undefined when collectionId is undefined", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: undefined as any } };++ expect(getCurrentTenantCollectionId(state, props)).toBeUndefined();+ });++ it("should return root for root collection", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: "root" } };++ expect(getCurrentTenantCollectionId(state, props)).toBe("root");+ });++ it("should return parsed integer for string numeric collection id", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: "100" } };++ expect(getCurrentTenantCollectionId(state, props)).toBe(100);+ });++ it("should handle numeric collection id", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: 100 as any } };++ expect(getCurrentTenantCollectionId(state, props)).toBe(100);+ });++ it("should handle large collection ids", () => {+ const state = createMockStateWithPermissions();+ const props = { params: { collectionId: "999999" } };++ expect(getCurrentTenantCollectionId(state, props)).toBe(999999);+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/TenantDisplayName.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/TenantDisplayName.tsxnew file mode 100644index 00000000000..d2961d4d45c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/TenantDisplayName.tsx@@ -0,0 +1,19 @@+import { t } from "ttag";++import { Loader } from "metabase/ui";+import { useListTenantsQuery } from "metabase-enterprise/api";+import type { Tenant } from "metabase-types/api";++export const TenantDisplayName = ({ id }: { id: Tenant["id"] }) => {+ const { data: tenants, isLoading } = useListTenantsQuery({+ status: "all",+ });++ if (isLoading || !tenants) {+ return <Loader />;+ }++ const currentTenant = tenants.data.find((tenants) => tenants.id === id);++ return <>{currentTenant?.name || t`Unknown tenant`}</>;+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/index.tsnew file mode 100644index 00000000000..64ddbb7a78b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantDisplayName/index.ts@@ -0,0 +1 @@+export * from "./TenantDisplayName";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/TenantForm.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/TenantForm.tsxnew file mode 100644index 00000000000..231cded48c7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/TenantForm.tsx@@ -0,0 +1,107 @@+import { t } from "ttag";+import * as Yup from "yup";++import { FormFooter } from "metabase/common/components/FormFooter";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormSubmitButton,+ FormTextInput,+} from "metabase/forms";+import * as Errors from "metabase/lib/errors";+import { Button } from "metabase/ui";+import { LoginAttributesWidget } from "metabase-enterprise/sandboxes/components/LoginAttributesWidget/LoginAttributesWidget";+import type { Tenant } from "metabase-types/api";++const MAX_SLUG_LENGTH = 255;++const localTenantSchema = Yup.object({+ name: Yup.string().default("").required().max(254, Errors.maxLength),+ slug: Yup.string()+ .default("")+ .required()+ .matches(/^[-_a-z0-9]+$/, {+ excludeEmptyString: true,+ get message() {+ return t`Only lowercase letters, numbers, hyphens (-), and underscores (_) are allowed`;+ },+ })+ .max(MAX_SLUG_LENGTH, Errors.maxLength),+});++interface TenantFormProps {+ initialValues?: Partial<Tenant>;+ onSubmit: (val: Partial<Tenant>) => void;+ onCancel: () => void;+ submitText?: string;+}++function slugify(str: string): string {+ return str+ .toLowerCase()+ .trim()+ .replace(/\s+/g, "_") // replace spaces with underscores+ .replace(/[^-_a-z0-9]/g, "") // remove any invalid chars+ .slice(0, MAX_SLUG_LENGTH); // limit to max allowed length+}++export const TenantForm = ({+ initialValues = {},+ onSubmit,+ onCancel,+ submitText = t`Update`,+}: TenantFormProps) => {+ return (+ <FormProvider+ initialValues={initialValues}+ validationSchema={localTenantSchema}+ enableReinitialize+ onSubmit={onSubmit}+ >+ {({ values, setFieldValue, dirty }) => (+ <Form disabled={!dirty} mt="sm">+ <FormTextInput+ name="name"+ title={t`Display name`}+ label={t`Display name`}+ description={t`Visible to admins and people assigned to the tenant. You can change the name at any time.`}+ mb="md"+ onChange={(e) => {+ const value = e.target.value;+ setFieldValue("name", value);++ const isSlugModified =+ slugify(values.name ?? "") !== (values.slug ?? "");+ const shouldAutoSetSlug = !initialValues.slug && !isSlugModified;+ if (shouldAutoSetSlug) {+ setFieldValue("slug", slugify(value));+ }+ }}+ />+ <FormTextInput+ name="slug"+ title={t`Slug`}+ label={t`Slug`}+ description={t`A unique identifier for the tenant. Cannot be changed later.`}+ disabled={!!initialValues.slug}+ mb="xl"+ />+ <LoginAttributesWidget+ name="attributes"+ description={t`Default attributes to be applied to all users in this tenant.`}+ />+ <FormFooter>+ <FormErrorMessage inline />+ <Button type="button" onClick={onCancel}>{t`Cancel`}</Button>+ <FormSubmitButton+ label={submitText}+ disabled={!dirty}+ variant="filled"+ />+ </FormFooter>+ </Form>+ )}+ </FormProvider>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/index.tsxnew file mode 100644index 00000000000..a65e4070b34--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantForm/index.tsx@@ -0,0 +1 @@+export * from "./TenantForm";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/TenantFormWidget.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/TenantFormWidget.tsxnew file mode 100644index 00000000000..ef2d9c50438--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/TenantFormWidget.tsx@@ -0,0 +1,40 @@+import { useField } from "formik";+import { t } from "ttag";++import { Select, type SelectProps } from "metabase/ui";+import { useListTenantsQuery } from "metabase-enterprise/api";+import type { Tenant } from "metabase-types/api";++interface FormTenantWidget extends Partial<SelectProps> {+ name: string;+}++export const FormTenantWidget = ({ name, ...props }: FormTenantWidget) => {+ const [{ value: formValue }, , { setValue }] = useField<Tenant["id"] | null>(+ name,+ );++ const { data: tenants, isLoading } = useListTenantsQuery({+ status: "active",+ });++ if (isLoading || !tenants) {+ return null;+ }++ const options = tenants.data.map((tenant) => ({+ label: tenant.name,+ value: tenant.id.toString(),+ }));++ return (+ <Select+ value={formValue?.toString()}+ onChange={(val) => setValue(parseInt(val))}+ data={options}+ label={t`Tenant`}+ mb="1rem"+ {...props}+ ></Select>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/index.tsnew file mode 100644index 00000000000..6d9becc553a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantFormWidget/index.ts@@ -0,0 +1 @@+export * from "./TenantFormWidget";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantGroupHintIcon.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantGroupHintIcon.tsxnew file mode 100644index 00000000000..f6455d6816c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantGroupHintIcon.tsx@@ -0,0 +1,9 @@+import { t } from "ttag";++import { Icon, Tooltip } from "metabase/ui";++export const TenantGroupHintIcon = () => (+ <Tooltip label={t`This is a tenant group`}>+ <Icon name="globe" c="text-medium" />+ </Tooltip>+);diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsxnew file mode 100644index 00000000000..d7d5f42d96a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/TenantSpecificCollectionsItemList.tsx@@ -0,0 +1,62 @@+import { useMemo } from "react";++import { ItemList } from "metabase/common/components/EntityPicker/components/ItemList";+import type {+ CollectionItemListProps,+ CollectionPickerItem,+} from "metabase/common/components/Pickers/CollectionPicker/types";+import { useListTenantsQuery } from "metabase-enterprise/api";+import type { Tenant } from "metabase-types/api";++export const TenantSpecificCollectionsItemList = ({+ onClick,+ selectedItem,+ isFolder,+ isCurrentLevel,+ shouldDisableItem,+ shouldShowItem,+}: CollectionItemListProps) => {+ const {+ data: tenantsData,+ error,+ isLoading,+ } = useListTenantsQuery({ status: "active" });++ const tenantCollections = useMemo(+ () => getTenantCollections(tenantsData?.data),+ [tenantsData?.data],+ );++ return (+ <ItemList+ items={tenantCollections}+ error={error}+ isLoading={isLoading}+ onClick={onClick}+ selectedItem={selectedItem}+ isFolder={isFolder}+ isCurrentLevel={isCurrentLevel}+ shouldDisableItem={shouldDisableItem}+ shouldShowItem={shouldShowItem}+ />+ );+};++const getTenantCollections = (+ tenants?: Tenant[],+): CollectionPickerItem[] | null =>+ tenants+ ?.filter((tenant) => tenant.tenant_collection_id != null)+ .map(+ (tenant): CollectionPickerItem => ({+ id: tenant.tenant_collection_id!,+ name: tenant.name,+ here: ["collection"], // tenant collections can contain collections+ model: "collection",+ location: "/",+ can_write: true,+ type: "tenant-specific-root-collection",+ collection_id: "tenant-specific",+ }),+ )+ .sort((a, b) => a.name.localeCompare(b.name)) ?? null;diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/index.ts b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/index.tsnew file mode 100644index 00000000000..163c56ce7e1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantSpecificCollectionsItemList/index.ts@@ -0,0 +1 @@+export { TenantSpecificCollectionsItemList } from "./TenantSpecificCollectionsItemList";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/TenantsListing.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/TenantsListing.tsxnew file mode 100644index 00000000000..94494c70e6f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/TenantsListing.tsx@@ -0,0 +1,162 @@+import { useMemo } from "react";+import { push } from "react-router-redux";+import { t } from "ttag";++import { SearchFilter } from "metabase/admin/people/components/SearchFilter";+import {+ ACTIVE_STATUS,+ type ActiveStatus,+} from "metabase/admin/people/constants";+import { AdminContentTable } from "metabase/common/components/AdminContentTable";+import { ForwardRefLink } from "metabase/common/components/Link";+import UserAvatar from "metabase/common/components/UserAvatar";+import CS from "metabase/css/core/index.css";+import { useDispatch } from "metabase/lib/redux";+import { regexpEscape } from "metabase/lib/string";+import {+ Box,+ Button,+ Flex,+ Group,+ Icon,+ Menu,+ Text,+ UnstyledButton,+} from "metabase/ui";+import { tenantIdToColor } from "metabase-enterprise/tenants/utils/colors";+import * as Urls from "metabase-enterprise/urls";+import type { Tenant } from "metabase-types/api";++interface TenantsListingProps {+ tenants: Tenant[];+ isAdmin: boolean;+ children?: React.ReactNode;+ searchInputValue: string;+ setSearchInputValue: (value: string) => void;+ status: ActiveStatus;+}++export const TenantsListing = ({+ tenants,+ isAdmin,+ searchInputValue,+ setSearchInputValue,+ status,+ children,+}: TenantsListingProps) => {+ const dispatch = useDispatch();++ const openNewTenantModal = () => {+ dispatch(push(Urls.newTenant()));+ };++ const filteredTenants = useMemo(() => {+ const filter = new RegExp(`\\b${regexpEscape(searchInputValue)}`, "i");+ return tenants.filter((g) => filter.test(g.name));+ }, [searchInputValue, tenants]);++ return (+ <div>+ <Group w="100%" justify="space-between" mb="lg" gap="md">+ <Flex flex="1">+ <SearchFilter+ value={searchInputValue}+ onChange={setSearchInputValue}+ placeholder={t`Find a tenant`}+ />+ </Flex>++ {isAdmin && (+ <Flex gap="sm">+ <Button+ variant="filled"+ onClick={openNewTenantModal}+ >{t`New tenant`}</Button>+ </Flex>+ )}+ </Group>++ <AdminContentTable columnTitles={[t`Tenant`, t`Slug`, t`Users`]}>+ {filteredTenants.map((tenant) => (+ <tr key={tenant.id}>+ <td>+ <Flex+ component={ForwardRefLink}+ align="center"+ to={Urls.editTenant(tenant.id)}+ className={CS.link}+ gap="md"+ >+ <UserAvatar+ user={{ first_name: tenant.name }}+ bg={tenantIdToColor(tenant.id)}+ />+ <Box component="span" fw={700} c="brand">+ {tenant.name}+ </Box>+ </Flex>+ </td>+ <td>{tenant.slug}</td>+ <td>{tenant.member_count || 0}</td>+ <Box component="td" ta="end">+ <ActionsPopover tenant={tenant} />+ </Box>+ </tr>+ ))}+ </AdminContentTable>++ {((tenants.length !== 0 && filteredTenants.length === 0) ||+ (tenants.length === 0 && status === ACTIVE_STATUS.deactivated)) && (+ <Text size="lg" fw="700" ta="center" mt="xl" py="xl" c="text-light">+ {t`No matching tenants found.`}+ </Text>+ )}++ {tenants.length === 0 && status === ACTIVE_STATUS.active && (+ <Text size="lg" fw="700" ta="center" mt="xl" py="xl" c="text-light">+ {t`Add your first tenant to get started.`}+ </Text>+ )}++ {children}+ </div>+ );+};++interface ActionsPopoverProps {+ tenant: Tenant;+}++function ActionsPopover({ tenant }: ActionsPopoverProps) {+ return (+ <Menu shadow="md" width={200} position="bottom-end">+ <Menu.Target>+ <UnstyledButton>+ <Icon c="text-light" name="ellipsis" />+ </UnstyledButton>+ </Menu.Target>+ <Menu.Dropdown>+ <Menu.Item component={ForwardRefLink} to={Urls.editTenant(tenant.id)}>+ {t`Edit tenant`}+ </Menu.Item>+ {tenant.is_active ? (+ <Menu.Item+ c="danger"+ component={ForwardRefLink}+ to={Urls.deactivateTenant(tenant.id)}+ >+ {t`Deactivate tenant`}+ </Menu.Item>+ ) : (+ <Menu.Item+ c="danger"+ component={ForwardRefLink}+ to={Urls.reactivateTenant(tenant.id)}+ >+ {t`Reactivate tenant`}+ </Menu.Item>+ )}+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/index.tsxnew file mode 100644index 00000000000..2304fcb9bfe--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/TenantsListing/index.tsx@@ -0,0 +1 @@+export * from "./TenantsListing";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsxnew file mode 100644index 00000000000..1bd97bcd740--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsx@@ -0,0 +1,61 @@+import { useMemo } from "react";+import type { Params } from "react-router/lib/Router";+import { t } from "ttag";+import _ from "underscore";++import { skipToken } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useToast } from "metabase/common/hooks";+import { Modal } from "metabase/ui";+import {+ useGetTenantQuery,+ useUpdateTenantMutation,+} from "metabase-enterprise/api";+import type { Tenant } from "metabase-types/api";++import { TenantForm } from "../../components/TenantForm";++interface EditUserModalProps {+ onClose: () => void;+ params: Params;+}++export const EditTenantModal = ({ params, onClose }: EditUserModalProps) => {+ const [sendToast] = useToast();++ const tenantId = params.tenantId ? parseInt(params.tenantId, 10) : undefined;+ const {+ data: tenant = {},+ isLoading,+ error,+ } = useGetTenantQuery(tenantId ?? skipToken);+ const [updateTenant] = useUpdateTenantMutation();++ const initialValues = useMemo(+ () => _.pick(tenant, ["id", "name", "slug", "attributes"]),+ [tenant],+ );++ const handleSubmit = async (vals: Partial<Tenant>) => {+ if (typeof vals.id !== "number") {+ throw new Error("tenant should have an id");+ }+ const tenant = _.omit({ ...vals, id: vals.id ?? 0 }, "slug");++ await updateTenant(tenant).unwrap();+ sendToast({ message: t`Tenant update successful` });+ onClose();+ };++ return (+ <Modal opened title={t`Edit tenant`} padding="xl" onClose={onClose}>+ <LoadingAndErrorWrapper loading={isLoading} error={error}>+ <TenantForm+ initialValues={initialValues}+ onCancel={onClose}+ onSubmit={handleSubmit}+ />+ </LoadingAndErrorWrapper>+ </Modal>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/index.tsxnew file mode 100644index 00000000000..47bfed2515c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/index.tsx@@ -0,0 +1 @@+export * from "./EditTenantModal";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/NewTenantModal.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/NewTenantModal.tsxnew file mode 100644index 00000000000..9d226105b55--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/NewTenantModal.tsx@@ -0,0 +1,40 @@+import { t } from "ttag";++import { useDispatch } from "metabase/lib/redux";+import { addUndo } from "metabase/redux/undo";+import { Modal } from "metabase/ui";+import { useCreateTenantMutation } from "metabase-enterprise/api";+import type { Tenant } from "metabase-types/api";++import { TenantForm } from "../../components/TenantForm";++interface NewUserModalProps {+ onClose: () => void;+}++export const NewTenantModal = ({ onClose }: NewUserModalProps) => {+ const dispatch = useDispatch();++ const [createTenant] = useCreateTenantMutation();++ const handleSubmit = async (vals: Partial<Tenant>) => {+ await createTenant({+ ...vals,+ name: vals.name ?? "",+ slug: vals.slug ?? "",+ }).unwrap();+ dispatch(addUndo({ message: t`Tenant creation successful` }));+ onClose();+ };++ return (+ <Modal opened title={t`New tenant`} padding="xl" onClose={onClose}>+ <TenantForm+ initialValues={{}}+ submitText={t`Create`}+ onCancel={onClose}+ onSubmit={handleSubmit}+ />+ </Modal>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/index.tsxnew file mode 100644index 00000000000..8c9c1d21395--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/NewTenantModal/index.tsx@@ -0,0 +1 @@+export * from "./NewTenantModal";diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantActivationModal.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantActivationModal.tsxnew file mode 100644index 00000000000..a1a974d4518--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantActivationModal.tsx@@ -0,0 +1,62 @@+import { t } from "ttag";++import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { useDispatch } from "metabase/lib/redux";+import { addUndo } from "metabase/redux/undo";+import {+ useGetTenantQuery,+ useUpdateTenantMutation,+} from "metabase-enterprise/api";++interface UserActivationModalInnerProps {+ params: { tenantId: string };+ onClose: () => void;+}++export const TenantActivationModal = ({+ params,+ onClose,+}: UserActivationModalInnerProps) => {+ const tenantId = parseInt(params.tenantId, 10);+ const { data: tenant } = useGetTenantQuery(tenantId);++ const dispatch = useDispatch();++ const [updateTenant] = useUpdateTenantMutation();++ if (!tenant) {+ return null;+ }++ if (tenant.is_active) {+ return (+ <ConfirmModal+ opened+ title={t`Deactivate ${tenant.name}?`}+ message={t`This is disable all users on this tenant`}+ confirmButtonText={t`Deactivate`}+ onClose={onClose}+ onConfirm={async () => {+ await updateTenant({ id: tenantId, is_active: false });+ dispatch(addUndo({ message: t`Tenant deactivated` }));+ onClose();+ }}+ />+ );+ }++ return (+ <ConfirmModal+ opened+ title={t`Reactivate ${tenant.name}?`}+ message={t`This will allow users on this tenant to login`}+ confirmButtonText={t`Reactivate`}+ onClose={onClose}+ onConfirm={async () => {+ await updateTenant({ id: tenantId, is_active: true });+ dispatch(addUndo({ message: t`Tenant reactivated` }));+ onClose();+ }}+ />+ );+};diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp.module.css b/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantsListingApp.module.csssimilarity index 100%rename from frontend/src/metabase/admin/people/containers/PeopleListingApp.module.cssrename to enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantsListingApp.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantsListingApp.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantsListingApp.tsxnew file mode 100644index 00000000000..e9d48138744--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/TenantsListingApp.tsx@@ -0,0 +1,92 @@+import { useEffect, useMemo, useState } from "react";+import { t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import {+ ACTIVE_STATUS,+ type ActiveStatus,+} from "metabase/admin/people/constants";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSelector } from "metabase/lib/redux";+import { getUserIsAdmin } from "metabase/selectors/user";+import { Group, Tabs, Title } from "metabase/ui";+import { useListTenantsQuery } from "metabase-enterprise/api";++import { CreateTenantCollectionButton } from "../components/CreateTenantCollectionButton";+import { TenantsListing } from "../components/TenantsListing";++import S from "./TenantsListingApp.module.css";++export const TenantsListingApp = ({+ children,+}: {+ children: React.ReactNode;+}) => {+ const isAdmin = useSelector(getUserIsAdmin);++ const [searchInputValue, setSearchInputValue] = useState("");+ const [status, setStatus] = useState<ActiveStatus>(ACTIVE_STATUS.active);++ const { isLoading, error, data } = useListTenantsQuery({ status: "all" });++ const tenants = useMemo(+ () =>+ data?.data.filter((tenant) =>+ status === ACTIVE_STATUS.active ? tenant.is_active : !tenant.is_active,+ ) ?? [],+ [data?.data, status],+ );++ const hasDeactivatedTenants = useMemo(+ () => data?.data.some((tenant) => !tenant.is_active),+ [data?.data],+ );++ const handleTabChange = (tab: string | null) => {+ if (tab) {+ setStatus(tab as ActiveStatus);+ }+ };++ useEffect(() => {+ if (!hasDeactivatedTenants) {+ setStatus("active");+ }+ }, [hasDeactivatedTenants]);++ return (+ <div>+ <Group justify="space-between" w="100%" mb="lg">+ <Title order={1}>{t`Tenants`}</Title>++ <CreateTenantCollectionButton />+ </Group>++ {isAdmin && hasDeactivatedTenants && (+ <Tabs value={status} onChange={handleTabChange} pl="md">+ <Tabs.List className={S.tabs}>+ <Tabs.Tab value={ACTIVE_STATUS.active}>{t`Active`}</Tabs.Tab>++ <Tabs.Tab+ value={ACTIVE_STATUS.deactivated}+ >{t`Deactivated`}</Tabs.Tab>+ </Tabs.List>+ </Tabs>+ )}++ <SettingsSection>+ <LoadingAndErrorWrapper error={error} loading={isLoading}>+ <TenantsListing+ isAdmin={isAdmin}+ tenants={tenants}+ searchInputValue={searchInputValue}+ setSearchInputValue={setSearchInputValue}+ status={status}+ />+ </LoadingAndErrorWrapper>++ {children}+ </SettingsSection>+ </div>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsxnew file mode 100644index 00000000000..997fae998d6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx@@ -0,0 +1,267 @@+import { Fragment } from "react";+import { IndexRedirect, IndexRoute, Route } from "react-router";+import { t } from "ttag";++import { AdminPeopleApp } from "metabase/admin/people/containers/AdminPeopleApp";+import { EditUserModal } from "metabase/admin/people/containers/EditUserModal";+import { NewUserModal } from "metabase/admin/people/containers/NewUserModal";+import { UserActivationModal } from "metabase/admin/people/containers/UserActivationModal";+import { UserPasswordResetModal } from "metabase/admin/people/containers/UserPasswordResetModal";+import { UserSuccessModal } from "metabase/admin/people/containers/UserSuccessModal";+import { ModalRoute } from "metabase/hoc/ModalRoute";+import { getGroupNameLocalized } from "metabase/lib/groups";+import { useSelector } from "metabase/lib/redux";+import {+ PLUGIN_ADMIN_PERMISSIONS_TABS,+ PLUGIN_ADMIN_USER_MENU_ROUTES,+ PLUGIN_TENANTS,+} from "metabase/plugins";+import type { TenantCollectionPathItem } from "metabase/plugins/oss/tenants";+import { getApplicationName } from "metabase/selectors/whitelabel";+import { Box, Text } from "metabase/ui";+import { hasPremiumFeature } from "metabase-enterprise/settings";+import type { CollectionId, CollectionNamespace } from "metabase-types/api";++import { EditUserStrategyModal } from "./EditUserStrategyModal";+import { EditUserStrategySettingsButton } from "./EditUserStrategySettingsButton";+import { ExternalGroupDetailApp } from "./components/ExternalGroupDetailApp/ExternalGroupDetailApp";+import { ExternalGroupsListingApp } from "./components/ExternalGroupsListingApp/ExternalGroupsListingApp";+import { ExternalPeopleListingApp } from "./components/ExternalPeopleListingApp/ExternalPeopleListingApp";+import { MainNavSharedCollections } from "./components/MainNavSharedCollections";+import { ReactivateExternalUserButton } from "./components/ReactivateExternalUserButton";+import { TenantCollectionItemList } from "./components/TenantCollectionItemList";+import { TenantCollectionList } from "./components/TenantCollectionList";+import { TenantCollectionPermissionsPage } from "./components/TenantCollectionPermissionsPage";+import { TenantDisplayName } from "./components/TenantDisplayName";+import { FormTenantWidget } from "./components/TenantFormWidget";+import { TenantGroupHintIcon } from "./components/TenantGroupHintIcon";+import { TenantSpecificCollectionsItemList } from "./components/TenantSpecificCollectionsItemList";+import { EditTenantModal } from "./containers/EditTenantModal";+import { NewTenantModal } from "./containers/NewTenantModal";+import { TenantActivationModal } from "./containers/TenantActivationModal";+import { TenantsListingApp } from "./containers/TenantsListingApp";+import {+ isExternalUser,+ isExternalUsersGroup,+ isTenantCollection,+ isTenantGroup,+} from "./utils/utils";++const SHARED_TENANT_NAMESPACE: CollectionNamespace = "shared-tenant-collection";++const isTenantNamespace = (namespace?: CollectionNamespace): boolean => {+ return (+ namespace === SHARED_TENANT_NAMESPACE || namespace === "tenant-specific"+ );+};++const isTenantCollectionId = (id: CollectionId): boolean => {+ return id === "tenant" || id === "tenant-specific";+};++const getNamespaceForTenantId = (id: CollectionId): CollectionNamespace => {+ if (id === "tenant") {+ return SHARED_TENANT_NAMESPACE;+ }+ return null;+};++const getTenantCollectionPathPrefix = (+ collection: TenantCollectionPathItem,+): CollectionId[] | null => {+ if (collection.id === "tenant") {+ return ["tenant"];+ }+ if (collection.id === "tenant-specific") {+ return ["tenant-specific"];+ }++ if (collection.type === "tenant-specific-root-collection") {+ if (collection.collection_id === "tenant-specific") {+ return ["tenant-specific", collection.id];+ }+ return [collection.id];+ }++ if (collection.namespace === "tenant-specific") {+ return ["tenant"];+ }++ const isTenant =+ isTenantNamespace(collection.namespace) ||+ isTenantNamespace(collection.collection_namespace) ||+ collection.is_shared_tenant_collection ||+ collection.is_tenant_dashboard;++ if (isTenant) {+ return ["tenant"];+ }++ return null;+};++const getNamespaceDisplayName = (+ namespace?: CollectionNamespace,+): string | null => {+ if (namespace === SHARED_TENANT_NAMESPACE) {+ return t`Shared collections`;+ }+ return null;+};++export function initializePlugin() {+ if (hasPremiumFeature("tenants")) {+ PLUGIN_TENANTS.isEnabled = true;++ // Register tenant collection permissions tab and routes+ PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.push({+ name: t`Tenant Collections`,+ value: "tenant-collections",+ });++ PLUGIN_ADMIN_PERMISSIONS_TABS.getRoutes = () => (+ <Route+ path="tenant-collections"+ component={TenantCollectionPermissionsPage}+ >+ <Route path=":collectionId" />+ </Route>+ );++ PLUGIN_TENANTS.userStrategyRoute = (+ <ModalRoute path="user-strategy" modal={EditUserStrategyModal} noWrap />+ );++ PLUGIN_TENANTS.tenantsRoutes = (+ <>+ <Route component={AdminPeopleApp}>+ <IndexRoute component={TenantsListingApp} />+ <Route path="" component={TenantsListingApp}>+ <ModalRoute path="new" modal={NewTenantModal} noWrap />+ </Route>+ <Route path="groups">+ <IndexRoute component={ExternalGroupsListingApp} />+ <Route path=":groupId" component={ExternalGroupDetailApp} />+ </Route>+ <Route path="people" component={ExternalPeopleListingApp}>+ <ModalRoute+ path="new"+ modal={(props) => <NewUserModal {...props} external />}+ noWrap+ />+ <Route path=":userId">+ <IndexRedirect to="/admin/tenants/people" />+ <ModalRoute+ path="edit"+ // @ts-expect-error - params prop can't be infered+ modal={(props) => <EditUserModal {...props} external />}+ noWrap+ />+ <ModalRoute+ path="deactivate"+ // @ts-expect-error - params prop can't be infered+ modal={UserActivationModal}+ noWrap+ />+ <ModalRoute+ path="reactivate"+ // @ts-expect-error - params prop can't be infered+ modal={UserActivationModal}+ noWrap+ />+ {/* @ts-expect-error - params prop can't be infered */}+ <ModalRoute path="success" modal={UserSuccessModal} noWrap />+ {/* @ts-expect-error - params prop can't be infered */}+ <ModalRoute path="reset" modal={UserPasswordResetModal} noWrap />+ {PLUGIN_ADMIN_USER_MENU_ROUTES.map((getRoutes, index) => (+ <Fragment key={index}>{getRoutes()}</Fragment>+ ))}+ </Route>+ </Route>+ <Route path=":tenantId" component={TenantsListingApp}>+ <ModalRoute+ path="edit"+ // @ts-expect-error - params prop can't be infered+ modal={EditTenantModal}+ noWrap+ />+ <ModalRoute+ path="deactivate"+ // @ts-expect-error - params prop can't be infered+ modal={TenantActivationModal}+ noWrap+ />+ <ModalRoute+ path="reactivate"+ // @ts-expect-error - params prop can't be infered+ modal={TenantActivationModal}+ noWrap+ />+ </Route>+ </Route>+ </>+ );++ PLUGIN_TENANTS.EditUserStrategySettingsButton =+ EditUserStrategySettingsButton;++ PLUGIN_TENANTS.FormTenantWidget = FormTenantWidget;+ PLUGIN_TENANTS.TenantDisplayName = TenantDisplayName;+ PLUGIN_TENANTS.isExternalUsersGroup = isExternalUsersGroup;+ PLUGIN_TENANTS.isTenantGroup = isTenantGroup;+ PLUGIN_TENANTS.isExternalUser = isExternalUser;+ PLUGIN_TENANTS.isTenantCollection = isTenantCollection;+ PLUGIN_TENANTS.ReactivateExternalUserButton = ReactivateExternalUserButton;+ PLUGIN_TENANTS.TenantGroupHintIcon = TenantGroupHintIcon;+ PLUGIN_TENANTS.MainNavSharedCollections = MainNavSharedCollections;+ PLUGIN_TENANTS.TenantCollectionItemList = TenantCollectionItemList;+ PLUGIN_TENANTS.TenantSpecificCollectionsItemList =+ TenantSpecificCollectionsItemList;+ PLUGIN_TENANTS.TenantCollectionList = TenantCollectionList;++ // Category 1: UI Components+ PLUGIN_TENANTS.GroupDescription = function GroupDescription({ group }) {+ const applicationName = useSelector(getApplicationName);+ if (isExternalUsersGroup(group)) {+ return (+ <Box maw="38rem" px="1rem">+ <Text>+ {t`All tenant users belong to the ${getGroupNameLocalized(+ group,+ )} group and can't be removed from it. Setting permissions for this group is a great way to make sure you know what new ${applicationName} users will be able to see.`}+ </Text>+ </Box>+ );+ }+ return null;+ };++ PLUGIN_TENANTS.getNewUserModalTitle = (isExternal: boolean) => {+ return isExternal ? t`Create tenant user` : null;+ };++ PLUGIN_TENANTS.getFormGroupsTitle = (isExternal: boolean) => {+ return isExternal ? t`Tenant Groups` : null;+ };++ // Category 2: Collection namespace utilities+ PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE = SHARED_TENANT_NAMESPACE;+ PLUGIN_TENANTS.isTenantNamespace = isTenantNamespace;+ PLUGIN_TENANTS.isTenantCollectionId = isTenantCollectionId;+ PLUGIN_TENANTS.getNamespaceForTenantId = getNamespaceForTenantId;+ PLUGIN_TENANTS.getTenantCollectionPathPrefix =+ getTenantCollectionPathPrefix;+ PLUGIN_TENANTS.getTenantRootDisabledReason = () =>+ t`Items cannot be saved directly to the tenant root collection. Please select a sub-collection.`;+ PLUGIN_TENANTS.getNamespaceDisplayName = getNamespaceDisplayName;+ PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS = {+ id: "tenant-specific" as const,+ get name() {+ return t`Tenant collections`;+ },+ location: "/",+ path: ["root"],+ can_write: false,+ };+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/colors.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/colors.tsnew file mode 100644index 00000000000..85b13a4cc33--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/colors.ts@@ -0,0 +1,14 @@+import { color } from "metabase/lib/colors";+import type { Tenant } from "metabase-types/api";++const groupColorPalette = [+ color("error"),+ color("accent2"),+ color("brand"),+ color("accent4"),+ color("accent1"),+];++export const tenantIdToColor = (tenantId: Tenant["id"]) => {+ return groupColorPalette[tenantId % groupColorPalette.length];+};diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.tsnew file mode 100644index 00000000000..37bab8ba4ef--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts@@ -0,0 +1,18 @@+import type { Collection, Group, User } from "metabase-types/api";++export const isExternalUsersGroup = (+ group: Pick<Group, "magic_group_type">,+) => {+ return group.magic_group_type === "all-external-users";+};++export const isTenantGroup = (group: Pick<Group, "is_tenant_group">) => {+ return !!group.is_tenant_group;+};++export const isExternalUser = (user?: Pick<User, "tenant_id">) => {+ return user?.tenant_id !== null;+};++export const isTenantCollection = (collection: Collection) =>+ collection.namespace === "shared-tenant-collection";diff --git a/enterprise/frontend/src/metabase-enterprise/urls.ts b/enterprise/frontend/src/metabase-enterprise/urls.tsindex f8e8d22b727..991b6ce8e94 100644--- a/enterprise/frontend/src/metabase-enterprise/urls.ts+++ b/enterprise/frontend/src/metabase-enterprise/urls.ts@@ -1,4 +1,4 @@-import type { DatabaseId } from "metabase-types/api";+import type { DatabaseId, Tenant } from "metabase-types/api";export * as Urls from "metabase/lib/urls";@@ -27,3 +27,23 @@ export function removeDestinationDatabase(export function newMetabotConversation({ prompt }: { prompt: string }) {return `/metabot/new?q=${encodeURIComponent(prompt)}`;}++export function newTenant() {+ return `/admin/tenants/new`;+}++export function editTenant(tenantId: Tenant["id"]) {+ return `/admin/tenants/${tenantId}/edit`;+}++export function deactivateTenant(tenantId: Tenant["id"]) {+ return `/admin/tenants/${tenantId}/deactivate`;+}++export function reactivateTenant(tenantId: Tenant["id"]) {+ return `/admin/tenants/${tenantId}/reactivate`;+}++export function editUserStrategy() {+ return `/admin/people/user-strategy`;+}diff --git a/frontend/src/embedding-sdk-bundle/types/collection.ts b/frontend/src/embedding-sdk-bundle/types/collection.tsindex 778b4e6232a..51fd51e53f1 100644--- a/frontend/src/embedding-sdk-bundle/types/collection.ts+++ b/frontend/src/embedding-sdk-bundle/types/collection.ts@@ -27,6 +27,8 @@ export type MetabaseCollectionItem = {model: string;name: string;description: string | null;+ namespace?: string | null;+ collection_namespace?: string | null;type?:| "instance-analytics"| "trash"@@ -34,6 +36,8 @@ export type MetabaseCollectionItem = {| "library"| "library-data"| "library-metrics"+ | "shared-tenant-collection"+ | "tenant-specific-root-collection"| "model"| "question"| "metric"diff --git a/frontend/src/metabase-lib/v1/parameters/utils/click-behavior.ts b/frontend/src/metabase-lib/v1/parameters/utils/click-behavior.tsindex 2263026b89d..60f5ea19952 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/click-behavior.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/click-behavior.ts@@ -31,7 +31,7 @@ import type {DatasetColumn,DatetimeUnit,Parameter,- ParameterValuesMap,+ ParameterValueOrArray,QuestionDashboardCard,UserAttributeMap,} from "metabase-types/api";@@ -65,7 +65,7 @@ export function getDataFromClicked({}: {extraData?: {dashboard?: Dashboard;- parameterValuesBySlug?: ParameterValuesMap;+ parameterValuesBySlug?: Record<string, ParameterValueOrArray>;userAttributes?: UserAttributeMap | null;};dimensions?: DimensionType[];diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.tsindex 6cbb3ed531a..27aa76016ac 100644--- a/frontend/src/metabase-types/analytics/event.ts+++ b/frontend/src/metabase-types/analytics/event.ts@@ -473,7 +473,7 @@ export type ClickActionPerformedEvent = ValidateEvent<{export type RemoteSyncBranchSwitchedEvent = ValidateEvent<{event: "remote_sync_branch_switched";- triggered_from: "sidebar" | "admin-settings";+ triggered_from: "admin-settings" | "app-bar";}>;export type RemoteSyncBranchCreatedEvent = ValidateEvent<{@@ -483,13 +483,13 @@ export type RemoteSyncBranchCreatedEvent = ValidateEvent<{export type RemoteSyncPullChangesEvent = ValidateEvent<{event: "remote_sync_pull_changes";- triggered_from: "sidebar" | "admin-settings";+ triggered_from: "admin-settings" | "app-bar";event_detail?: "force";}>;export type RemoteSyncPushChangesEvent = ValidateEvent<{event: "remote_sync_push_changes";- triggered_from: "sidebar" | "conflict-modal";+ triggered_from: "conflict-modal" | "app-bar";event_detail?: "force";}>;diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.tsindex 2bb573b8de7..ca7d9c5122c 100644--- a/frontend/src/metabase-types/api/collection.ts+++ b/frontend/src/metabase-types/api/collection.ts@@ -16,7 +16,11 @@ import type { SortingOptions } from "./sorting";import type { TableId } from "./table";import type { UserId, UserInfo } from "./user";-export type CollectionNamespace = null | "snippets";+export type CollectionNamespace =+ | null+ | "snippets"+ | "tenant-specific"+ | "shared-tenant-collection";// Collection ID can be either a numeric or entity idexport type RegularCollectionId = number | string;@@ -26,6 +30,7 @@ export type CollectionId =| "root"| "personal"| "users"+ | "tenant"| "trash";export type CollectionContentModel = "card" | "dataset" | "metric";@@ -39,6 +44,8 @@ export type CollectionType =| "library"| "library-data"| "library-metrics"+ | "shared-tenant-collection"+ | "tenant-specific-root-collection"| null;export type LastEditInfo = Pick<@@ -129,6 +136,7 @@ export interface CollectionItem {based_on_upload?: TableId | null; // only for modelscollection?: Collection | null;collection_id: CollectionId | null; // parent collection id+ collection_namespace?: CollectionNamespace; // namespace of the parent collectiondisplay?: VisualizationDisplay;personal_owner_id?: UserId;database_id?: DatabaseId;@@ -156,6 +164,9 @@ export interface CollectionItem {collection: Pick<Collection, "id"> | Pick<Dashboard, "id">,) => void;setCollectionPreview?: (isEnabled: boolean) => void;+ is_shared_tenant_collection?: boolean;+ is_tenant_dashboard?: boolean;+ is_remote_synced?: boolean;}export interface CollectionListQuery {@@ -163,13 +174,13 @@ export interface CollectionListQuery {"exclude-other-user-collections"?: boolean;"exclude-archived"?: boolean;"personal-only"?: boolean;- namespace?: string;+ namespace?: CollectionNamespace;tree?: boolean;}export type getCollectionRequest = {id: CollectionId;- namespace?: "snippets";+ namespace?: CollectionNamespace;ignore_error?: boolean;};@@ -185,7 +196,7 @@ export type ListCollectionItemsRequest = {models?: CollectionItemModel[];archived?: boolean;pinned_state?: "all" | "is_pinned" | "is_not_pinned";- namespace?: "snippets";+ namespace?: CollectionNamespace;collection_type?: CollectionType;include_can_run_adhoc_query?: boolean;} & PaginationRequest &@@ -204,19 +215,21 @@ export interface UpdateCollectionRequest {parent_id?: RegularCollectionId | null;authority_level?: CollectionAuthorityLevel;type?: CollectionType;+ is_remote_synced?: boolean;}export interface CreateCollectionRequest {name: string;- description?: string;+ description?: string | null;parent_id?: CollectionId | null;- namespace?: string;+ namespace?: CollectionNamespace;authority_level?: CollectionAuthorityLevel;+ is_shared_tenant_collection?: boolean;}export interface ListCollectionsRequest {archived?: boolean;- namespace?: string;+ namespace?: CollectionNamespace;"personal-only"?: boolean;"exclude-other-user-collections"?: boolean;collection_type?: CollectionType;@@ -225,10 +238,12 @@ export interface ListCollectionsTreeRequest {"exclude-archived"?: boolean;"exclude-other-user-collections"?: boolean;"include-library"?: boolean;- namespace?: string;+ namespace?: CollectionNamespace;+ namespaces?: string[];shallow?: boolean;"collection-id"?: RegularCollectionId | null;collection_type?: CollectionType;+ "include-tenant-collections"?: boolean;}export interface DeleteCollectionRequest {diff --git a/frontend/src/metabase-types/api/group.ts b/frontend/src/metabase-types/api/group.tsindex 85f5b920a7c..1c7600ae7d1 100644--- a/frontend/src/metabase-types/api/group.ts+++ b/frontend/src/metabase-types/api/group.ts@@ -24,6 +24,12 @@ export type GroupInfo = {id: GroupId;name: string;member_count: number;+ magic_group_type:+ | "all-internal-users"+ | "admin"+ | "all-external-users"+ | null;+ is_tenant_group?: boolean;};export type Group = GroupInfo & {@@ -35,6 +41,7 @@ export type GroupListQuery = GroupInfo;export type BaseGroupInfo = {id: GroupId;name: string;+ is_tenant_group?: boolean;};export type ListUserMembershipsResponse = Record<User["id"], Membership[]>;diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex c6e1014893c..73cab89ddb2 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -53,6 +53,7 @@ export * from "./subscription";export * from "./support-access-grants";export * from "./table";export * from "./task";+export * from "./tenants";export * from "./timeline";export * from "./transform";export * from "./user";diff --git a/frontend/src/metabase-types/api/mocks/group.ts b/frontend/src/metabase-types/api/mocks/group.tsindex 8315d287dee..963fba2362a 100644--- a/frontend/src/metabase-types/api/mocks/group.ts+++ b/frontend/src/metabase-types/api/mocks/group.ts@@ -6,5 +6,6 @@ export const createMockGroup = (id: 1,name: "All Users",member_count: 1,+ magic_group_type: "all-internal-users",...opts,});diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex f7a93a7beaf..4108e3f64e7 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -36,6 +36,7 @@ export * from "./store";export * from "./support-access-grants";export * from "./table";export * from "./task";+export * from "./tenant";export * from "./timeline";export * from "./transform";export * from "./undo";diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 4687c248c2a..a0b8055c0de 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -144,6 +144,7 @@ export const createMockTokenFeatures = ("transforms-python": false,data_studio: false,"support-users": false,+ tenants: false,...opts,});@@ -288,6 +289,7 @@ export const createMockSettings = ("jwt-attribute-firstname": null,"jwt-attribute-lastname": null,"jwt-attribute-groups": null,+ "jwt-attribute-tenant": null,"jwt-group-sync": false,"ldap-configured?": false,"ldap-enabled": false,@@ -333,6 +335,7 @@ export const createMockSettings = ("saml-attribute-email": null,"saml-attribute-firstname": null,"saml-attribute-lastname": null,+ "saml-attribute-tenant": null,"saml-identity-provider-issuer": null,"saml-identity-provider-certificate": null,"saml-keystore-password": null,@@ -395,5 +398,6 @@ export const createMockSettings = ("trial-banner-dismissal-timestamp": null,"license-token-missing-banner-dismissal-timestamp": [],"sdk-iframe-embed-setup-settings": null,+ "use-tenants": false,...opts,});diff --git a/frontend/src/metabase-types/api/mocks/tenant.ts b/frontend/src/metabase-types/api/mocks/tenant.tsnew file mode 100644index 00000000000..d9c8bda17cb--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/tenant.ts@@ -0,0 +1,12 @@+import type { Tenant } from "../tenants";++export const createMockTenant = (opts?: Partial<Tenant>): Tenant => ({+ id: 1,+ name: "Foo",+ slug: "foo",+ member_count: 0,+ is_active: true,+ attributes: {},+ tenant_collection_id: null,+ ...opts,+});diff --git a/frontend/src/metabase-types/api/mocks/user.ts b/frontend/src/metabase-types/api/mocks/user.tsindex 6119bfb640a..189d6dd8bdd 100644--- a/frontend/src/metabase-types/api/mocks/user.ts+++ b/frontend/src/metabase-types/api/mocks/user.ts@@ -31,6 +31,9 @@ export const createMockUser = (opts?: Partial<User>): User => {updated_at: new Date().toISOString(),sso_source: null,permissions: createMockUserPermissions(),+ can_write_any_collection: true,+ tenant_id: null,+ tenant_collection_id: null,...opts,};};diff --git a/frontend/src/metabase-types/api/remote-sync.ts b/frontend/src/metabase-types/api/remote-sync.tsindex 421902e4299..0af0e17429b 100644--- a/frontend/src/metabase-types/api/remote-sync.ts+++ b/frontend/src/metabase-types/api/remote-sync.ts@@ -63,6 +63,8 @@ export type ImportFromBranchResponse = {message?: string;};+export type CollectionSyncPreferences = Record<number, boolean>;+export type RemoteSyncConfigurationSettings = Pick<EnterpriseSettings,| "remote-sync-enabled"@@ -70,7 +72,9 @@ export type RemoteSyncConfigurationSettings = Pick<| "remote-sync-token"| "remote-sync-type"| "remote-sync-branch"->;+> & {+ collections?: CollectionSyncPreferences;+};export type UpdateRemoteSyncConfigurationResponse = {success: boolean;diff --git a/frontend/src/metabase-types/api/search.ts b/frontend/src/metabase-types/api/search.tsindex d21282e6f8b..96ed38a5048 100644--- a/frontend/src/metabase-types/api/search.ts+++ b/frontend/src/metabase-types/api/search.ts@@ -1,7 +1,12 @@import type { UserId } from "metabase-types/api/user";import type { CardId } from "./card";-import type { Collection, CollectionId, LastEditInfo } from "./collection";+import type {+ Collection,+ CollectionId,+ CollectionNamespace,+ LastEditInfo,+} from "./collection";import type { Dashboard, DashboardId } from "./dashboard";import type { DatabaseId, InitialSyncStatus } from "./database";import type { Field } from "./field";@@ -142,6 +147,6 @@ export type SearchRequest = {// this should be in ListCollectionItemsRequest but legacy code expects them herecollection?: CollectionId;- namespace?: "snippets";+ namespace?: CollectionNamespace;calculate_available_models?: true;} & PaginationRequest;diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex cd10ebd89b9..90d8b664c63 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -331,6 +331,7 @@ export const tokenFeatures = ["transforms-python","data_studio","support-users",+ "tenants",] as const;export type TokenFeature = (typeof tokenFeatures)[number];@@ -561,6 +562,7 @@ interface PublicSettings {"version-info-last-checked": string | null;"airgap-enabled": boolean;"non-table-chart-generated": boolean;+ "use-tenants": boolean;}export type UserSettings = {@@ -681,6 +683,7 @@ export interface EnterpriseSettings extends Settings {"jwt-attribute-firstname": string | null;"jwt-attribute-lastname": string | null;"jwt-attribute-groups": string | null;+ "jwt-attribute-tenant": string | null;"jwt-group-sync": boolean | null;"saml-enabled": boolean;"saml-configured": boolean;@@ -695,6 +698,7 @@ export interface EnterpriseSettings extends Settings {"saml-attribute-email": string | null;"saml-attribute-firstname": string | null;"saml-attribute-lastname": string | null;+ "saml-attribute-tenant": string | null;"saml-attribute-group": string | null;"saml-group-sync": boolean | null;"saml-group-mappings": Record<string, GroupId[]> | null;diff --git a/frontend/src/metabase-types/api/tenants.ts b/frontend/src/metabase-types/api/tenants.tsnew file mode 100644index 00000000000..6928ce2bc12--- /dev/null+++ b/frontend/src/metabase-types/api/tenants.ts@@ -0,0 +1,16 @@+import type { UserAttributeMap } from "./user";++export type Tenant = {+ id: number;+ name: string;+ slug: string;+ member_count: number;+ is_active: boolean;+ attributes: UserAttributeMap | null;+ tenant_collection_id: number | null;+};++export type CreateTenantInput = Pick<Tenant, "name" | "slug">;++export type UpdateTenantInput = Pick<Tenant, "id"> &+ Partial<Pick<Tenant, "name" | "is_active">>;diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.tsindex 9c54886e6a5..e9e0faf990a 100644--- a/frontend/src/metabase-types/api/user.ts+++ b/frontend/src/metabase-types/api/user.ts@@ -7,7 +7,7 @@ export type UserAttributeKey = string;export type UserAttributeValue = string;export type UserAttributeMap = Record<UserAttributeKey, UserAttributeValue>;-export type UserAttributeSource = "system" | "jwt" | "user";+export type UserAttributeSource = "system" | "tenant" | "jwt" | "user";type StructuredAttributeBase = {frozen: boolean;@@ -39,6 +39,7 @@ export interface BaseUser {last_login: string;first_login: string;updated_at: string;+ tenant_id: number | null;}export interface UserPermissions {@@ -63,7 +64,9 @@ export interface User extends BaseUser {is_installer: boolean;has_invited_second_user: boolean;has_question_and_dashboard: boolean;+ can_write_any_collection: boolean;personal_collection_id: CollectionId;+ tenant_collection_id: CollectionId | null;sso_source: "jwt" | "ldap" | "google" | "scim" | "saml" | null;custom_homepage: {dashboard_id: DashboardId;@@ -135,6 +138,7 @@ export type ListUsersRequest = {query?: string;group_id?: number;include_deactivated?: boolean;+ tenancy?: UserTenancy;} & PaginationRequest;export type ListUsersResponse = {@@ -189,3 +193,5 @@ export type GetUserKeyValueRequest = UserKeyValueKey;export type UpdateUserKeyValueRequest = UserKeyValue & {expires_at?: string;};++export type UserTenancy = "internal" | "external" | "all";diff --git a/frontend/src/metabase-types/store/admin.ts b/frontend/src/metabase-types/store/admin.tsindex 63a445714fa..e4f50dd9425 100644--- a/frontend/src/metabase-types/store/admin.ts+++ b/frontend/src/metabase-types/store/admin.ts@@ -33,6 +33,8 @@ export interface AdminState {originalDataPermissions: GroupsPermissions;collectionPermissions: CollectionPermissions;originalCollectionPermissions: CollectionPermissions;+ tenantCollectionPermissions: CollectionPermissions;+ originalTenantCollectionPermissions: CollectionPermissions;saveError?: string;isHelpReferenceOpen: boolean;hasRevisionChanged: {diff --git a/frontend/src/metabase-types/store/mocks/admin.ts b/frontend/src/metabase-types/store/mocks/admin.tsindex 5b7671fd2c9..f216a437c57 100644--- a/frontend/src/metabase-types/store/mocks/admin.ts+++ b/frontend/src/metabase-types/store/mocks/admin.ts@@ -28,6 +28,8 @@ export const createMockPermissionsState = (originalDataPermissions: {},collectionPermissions: {},originalCollectionPermissions: {},+ tenantCollectionPermissions: {},+ originalTenantCollectionPermissions: {},isHelpReferenceOpen: false,hasRevisionChanged: {revision: null,diff --git a/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts b/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.tsindex dfa71f4e77c..fe0931ece06 100644--- a/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts+++ b/frontend/src/metabase/admin/components/RelatedSettingsSection/constants.ts@@ -1,5 +1,6 @@import { t } from "ttag";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { IconName } from "metabase/ui";export interface RelatedSettingItem {@@ -8,8 +9,14 @@ export interface RelatedSettingItem {to: string;}-export const getModularEmbeddingRelatedSettingItems =- (): RelatedSettingItem[] => [+export const getModularEmbeddingRelatedSettingItems = ({+ isUsingTenants,+}: {+ isUsingTenants?: boolean;+}): RelatedSettingItem[] => {+ const isTenantsFeatureAvailable = PLUGIN_TENANTS.isEnabled;++ const items: RelatedSettingItem[] = [{icon: "shield_outline",name: t`Security`,@@ -40,8 +47,22 @@ export const getModularEmbeddingRelatedSettingItems =name: t`Appearance`,to: "/admin/settings/appearance",},+ ...(isTenantsFeatureAvailable+ ? [+ {+ icon: "globe" as const,+ name: t`Tenants`,+ to: isUsingTenants+ ? "/admin/tenants"+ : "/admin/people/user-strategy",+ },+ ]+ : []),];+ return items;+};+export const getGuestEmbedsRelatedSettingItems = (): RelatedSettingItem[] => [{icon: "shield_outline",@@ -69,3 +90,42 @@ export const getGuestEmbedsRelatedSettingItems = (): RelatedSettingItem[] => [to: "/admin/settings/appearance",},];++export const getInteractiveEmbeddingRelatedSettingItems =+ (): RelatedSettingItem[] => [+ {+ icon: "shield_outline",+ name: t`Security`,+ to: "/admin/embedding/security",+ },+ {+ icon: "lock",+ name: t`Authentication`,+ to: "/admin/settings/authentication",+ },+ {+ icon: "database",+ name: t`Databases`,+ to: "/admin/databases",+ },+ {+ icon: "person",+ name: t`People`,+ to: "/admin/people",+ },+ {+ icon: "group",+ name: t`Permissions`,+ to: "/admin/permissions",+ },+ {+ icon: "metabot",+ name: t`Embedded Metabot`,+ to: "/admin/metabot/2",+ },+ {+ icon: "palette",+ name: t`Appearance`,+ to: "/admin/settings/appearance",+ },+ ];diff --git a/frontend/src/metabase/admin/people/components/ActiveStatusFilter.tsx b/frontend/src/metabase/admin/people/components/ActiveStatusFilter.tsxnew file mode 100644index 00000000000..4a3c15e3be3--- /dev/null+++ b/frontend/src/metabase/admin/people/components/ActiveStatusFilter.tsx@@ -0,0 +1,26 @@+import { t } from "ttag";++import { Group, Radio } from "metabase/ui";++import { ACTIVE_STATUS, type ActiveStatus } from "../constants";++interface ActiveStatusFilterProps {+ status: ActiveStatus;+ onStatusChange: (status: ActiveStatus) => void;+}+export const ActiveStatusFilter = ({+ status,+ onStatusChange,+}: ActiveStatusFilterProps) => {+ return (+ <Radio.Group+ value={status}+ onChange={(val) => onStatusChange(ACTIVE_STATUS[val])}+ >+ <Group>+ <Radio label={t`Active`} value={ACTIVE_STATUS.active} />+ <Radio label={t`Deactivated`} value={ACTIVE_STATUS.deactivated} />+ </Group>+ </Radio.Group>+ );+};diff --git a/frontend/src/metabase/admin/people/components/AddMemberRow.tsx b/frontend/src/metabase/admin/people/components/AddMemberRow.tsxindex 277c7b62b7a..721bb33b3d4 100644--- a/frontend/src/metabase/admin/people/components/AddMemberRow.tsx+++ b/frontend/src/metabase/admin/people/components/AddMemberRow.tsx@@ -3,28 +3,40 @@ import { t } from "ttag";import { useListUsersQuery } from "metabase/api";import UserAvatar from "metabase/common/components/UserAvatar";+import { PLUGIN_TENANTS } from "metabase/plugins";import { Flex, Pill, Popover, Text, UnstyledButton } from "metabase/ui";-import type { Member, User } from "metabase-types/api";+import type { Group, Member, User } from "metabase-types/api";import { userToColor } from "../colors";import { AddRow } from "./AddRow";interface AddMemberRowProps {+ group: Group;members: Member[];onCancel: () => void;onDone: (userIds: number[]) => void;}-export function AddMemberRow({ members, onCancel, onDone }: AddMemberRowProps) {- const listUsersReq = useListUsersQuery();+export function AddMemberRow({+ group,+ members,+ onCancel,+ onDone,+}: AddMemberRowProps) {+ const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);++ const listUsersQuery = useListUsersQuery(+ isTenantGroup ? { tenancy: "external" } : undefined,+ );+const [text, setText] = useState("");const [selectedUsersById, setSelectedUsersById] = useState<Map<number, User>>(new Map(),);const availableToSelectUsers = useMemo(() => {- const { isLoading, error, data } = listUsersReq;+ const { isLoading, error, data } = listUsersQuery;if (isLoading || error) {return [];}@@ -33,7 +45,7 @@ export function AddMemberRow({ members, onCancel, onDone }: AddMemberRowProps) {return allUsers.filter(({ id }) => !selectedUsersById.has(id) && !groupMemberIds.has(id),);- }, [members, selectedUsersById, listUsersReq]);+ }, [members, selectedUsersById, listUsersQuery]);const handleRemoveUser = (user: User) => {const newSelectedUsersById = new Map(selectedUsersById);@@ -77,6 +89,7 @@ export function AddMemberRow({ members, onCancel, onDone }: AddMemberRowProps) {onChange={(e) => setText(e.target.value)}onDone={handleDone}onCancel={onCancel}+ ariaLabel={t`Search for a user to add`}>{Array.from(selectedUsersById.values()).map((user, index) => (<Pilldiff --git a/frontend/src/metabase/admin/people/components/AddRow.tsx b/frontend/src/metabase/admin/people/components/AddRow.tsxindex 01c6a1a1055..c200540061e 100644--- a/frontend/src/metabase/admin/people/components/AddRow.tsx+++ b/frontend/src/metabase/admin/people/components/AddRow.tsx@@ -7,6 +7,7 @@ interface AddRowProps {value: string;isValid: boolean;placeholder?: string;+ ariaLabel?: string;onKeyDown?: (event: React.KeyboardEvent) => void;onChange: (event: ChangeEvent<HTMLInputElement>) => void;onDone: () => void;@@ -18,6 +19,7 @@ export const AddRow = ({value,isValid,placeholder,+ ariaLabel,onKeyDown,onChange,onDone,@@ -41,6 +43,7 @@ export const AddRow = ({styles={{ input: { background: "transparent" } }}value={value}placeholder={placeholder}+ aria-label={ariaLabel}autoFocusonKeyDown={onKeyDown}onChange={onChange}diff --git a/frontend/src/metabase/admin/people/components/GroupDetail.tsx b/frontend/src/metabase/admin/people/components/GroupDetail.tsxindex fff90ff90c6..bd4c86a2a5b 100644--- a/frontend/src/metabase/admin/people/components/GroupDetail.tsx+++ b/frontend/src/metabase/admin/people/components/GroupDetail.tsx@@ -16,9 +16,9 @@ import {isDefaultGroup,} from "metabase/lib/groups";import { useDispatch } from "metabase/lib/redux";-import { PLUGIN_GROUP_MANAGERS } from "metabase/plugins";+import { PLUGIN_GROUP_MANAGERS, PLUGIN_TENANTS } from "metabase/plugins";import { addUndo } from "metabase/redux/undo";-import { Box } from "metabase/ui";+import { Box, Button, Text } from "metabase/ui";import type { Group, Member, Membership, User } from "metabase-types/api";import Alert from "./Alert";@@ -128,9 +128,15 @@ export const GroupDetail = ({</Box></Fragment>}- buttonText={t`Add members`}- buttonAction={canEditMembership(group) ? onAddUsersClicked : undefined}- buttonDisabled={addUserVisible}+ titleActions={+ canEditMembership(group) && (+ <Button+ variant="filled"+ onClick={onAddUsersClicked}+ disabled={addUserVisible}+ >{t`Add members`}</Button>+ )+ }><GroupDescription group={group} /><GroupMembersTable@@ -149,15 +155,21 @@ export const GroupDetail = ({};const GroupDescription = ({ group }: { group: Group }) => {+ // Let plugin handle tenant-specific descriptions first+ const tenantDescription = PLUGIN_TENANTS.GroupDescription({ group });+ if (tenantDescription) {+ return tenantDescription;+ }+if (isDefaultGroup(group)) {return (<Box maw="38rem" px="1rem">- <p>+ <Text>{t`All users belong to the ${getGroupNameLocalized(group,)} group and can't be removed from it. Setting permissions for this group is a great way tomake sure you know what new Metabase users will be able to see.`}- </p>+ </Text></Box>);}@@ -165,13 +177,13 @@ const GroupDescription = ({ group }: { group: Group }) => {if (isAdminGroup(group)) {return (<Box maw="38rem" px="1rem">- <p>+ <Text>{t`This is a special group whose members can see everything in the Metabase instance, and who can access and make changes to thesettings in the Admin Panel, including changing permissions! So, add people to this group with care.`}- </p>- <p>+ </Text>+ <Text>{t`To make sure you don't get locked out of Metabase, there always has to be at least one user in this group.`}- </p>+ </Text></Box>);}diff --git a/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx b/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsxindex 428202eb1cf..ac3eff4ee94 100644--- a/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx+++ b/frontend/src/metabase/admin/people/components/GroupMembersTable/GroupMembersTable.tsx@@ -10,7 +10,7 @@ import { usePagination } from "metabase/common/hooks/use-pagination";import { isAdminGroup, isDefaultGroup } from "metabase/lib/groups";import { useSelector } from "metabase/lib/redux";import { getFullName } from "metabase/lib/user";-import { PLUGIN_GROUP_MANAGERS } from "metabase/plugins";+import { PLUGIN_GROUP_MANAGERS, PLUGIN_TENANTS } from "metabase/plugins";import { Box, Flex, Icon, Text, Tooltip, UnstyledButton } from "metabase/ui";import type { Group, Member, Membership } from "metabase-types/api";@@ -20,7 +20,9 @@ const isApiKeyGroupMember = (member: Member) =>member.email.endsWith("@api-key.invalid");const canEditMembership = (group: Group) =>- !isDefaultGroup(group) && PLUGIN_GROUP_MANAGERS.UserTypeCell;+ !isDefaultGroup(group) &&+ !PLUGIN_TENANTS.isExternalUsersGroup(group) &&+ PLUGIN_GROUP_MANAGERS.UserTypeCell;interface GroupMembersTableProps {group: Group;@@ -59,6 +61,7 @@ export function GroupMembersTable({>{showAddUser && (<AddMemberRow+ group={group}members={members}onCancel={onAddUserCancel}onDone={onAddUserDone}@@ -116,7 +119,9 @@ const UserMemberRow = ({const currentUser = useSelector(getCurrentUser);const isCurrentUser = member.user_id === currentUser.id;const canRemove =- !isDefaultGroup(group) && !(isAdminGroup(group) && isCurrentUser);+ !isDefaultGroup(group) &&+ !PLUGIN_TENANTS.isExternalUsersGroup(group) &&+ !(isAdminGroup(group) && isCurrentUser);const handleTypeUpdate = (isManager: boolean) => {onMembershipUpdate({ ...member, is_group_manager: isManager });diff --git a/frontend/src/metabase/admin/people/components/GroupSummary.tsx b/frontend/src/metabase/admin/people/components/GroupSummary.tsxindex 2ade4d817fc..45d0b6b3442 100644--- a/frontend/src/metabase/admin/people/components/GroupSummary.tsx+++ b/frontend/src/metabase/admin/people/components/GroupSummary.tsx@@ -1,11 +1,11 @@import { msgid, ngettext, t } from "ttag";-import type { UserGroupType } from "metabase/admin/types";import { isAdminGroup, isDefaultGroup } from "metabase/lib/groups";import { Box, type BoxProps } from "metabase/ui";+import type { GroupInfo } from "metabase-types/api";interface GroupSummaryProps extends BoxProps {- groups: UserGroupType[];+ groups: GroupInfo[];selectedGroupIds: number[];}diff --git a/frontend/src/metabase/admin/people/components/GroupsListing.tsx b/frontend/src/metabase/admin/people/components/GroupsListing.tsxindex 36d76045355..0c414d0ca8a 100644--- a/frontend/src/metabase/admin/people/components/GroupsListing.tsx+++ b/frontend/src/metabase/admin/people/components/GroupsListing.tsx@@ -18,6 +18,8 @@ import {isDefaultGroup,} from "metabase/lib/groups";import { KEYCODE_ENTER } from "metabase/lib/keyboard";+import { regexpEscape } from "metabase/lib/string";+import { PLUGIN_TENANTS } from "metabase/plugins";import {Box,Button,@@ -32,6 +34,7 @@ import type { ApiKey, GroupInfo } from "metabase-types/api";import { groupIdToColor } from "../colors";import { AddRow } from "./AddRow";+import { SearchFilter } from "./SearchFilter";// ------------------------------------------------------------ Add Group ------------------------------------------------------------@@ -144,7 +147,7 @@ function ActionsPopover({<><Menu shadow="md" width={200} position="bottom-end"><Menu.Target>- <UnstyledButton>+ <UnstyledButton aria-label={`group-action-button`}><Icon c="text-light" name="ellipsis" /></UnstyledButton></Menu.Target>@@ -235,9 +238,18 @@ function GroupRow({onEditGroupDoneClicked,}: GroupRowProps) {const backgroundColor = groupIdToColor(group.id);- const showActionsButton = !isDefaultGroup(group) && !isAdminGroup(group);+ const showActionsButton =+ !isDefaultGroup(group) &&+ !isAdminGroup(group) &&+ !PLUGIN_TENANTS.isExternalUsersGroup(group);const editing = groupBeingEdited && groupBeingEdited.id === group.id;+ const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);++ const membersLink = isTenantGroup+ ? `/admin/tenants/groups/${group.id}`+ : `/admin/people/groups/${group.id}`;+return editing ? (<EditingGroupRowgroup={groupBeingEdited}@@ -247,12 +259,12 @@ function GroupRow({onDoneClicked={onEditGroupDoneClicked}/>) : (- <tr>+ <tr aria-label={`group-${group.id}-row`}><td><Flexcomponent={Link}align="center"- to={"/admin/people/groups/" + group.id}+ to={membersLink}className={CS.link}gap="md">@@ -265,7 +277,7 @@ function GroupRow({</Box></Flex></td>- <td>+ <td aria-label="member-count">{group.member_count || 0}<ApiKeyCount apiKeys={apiKeys} /></td>@@ -372,9 +384,11 @@ interface GroupsListingProps {create: (group: { name: string }) => Promise<void>;update: (group: { id: number; name: string }) => Promise<void>;delete: (group: GroupInfo, groupCount: number) => Promise<void>;+ description?: string;}export const GroupsListing = (props: GroupsListingProps) => {+ const [searchText, setSearchText] = useState("");const [text, setText] = useState("");const [alertMessage, setAlertMessage] = useState<string | null>(null);const [groupBeingEdited, setGroupBeingEdited] = useState<GroupInfo | null>(@@ -483,16 +497,35 @@ export const GroupsListing = (props: GroupsListingProps) => {const { groups, isAdmin } = props;+ const groupNameFilter = new RegExp(`\\b${regexpEscape(searchText)}`, "i");+ const filteredGroups = groups.filter((g) => groupNameFilter.test(g.name));+return (<AdminPaneLayout- buttonText={isAdmin ? t`Create a group` : undefined}- buttonAction={- isShowingAddGroupRow ? undefined : onCreateAGroupButtonClicked+ headerContent={+ <SearchFilter+ value={searchText}+ onChange={setSearchText}+ placeholder={t`Find a group`}+ />+ }+ titleActions={+ isAdmin &&+ !isShowingAddGroupRow && (+ <Button+ variant="filled"+ onClick={onCreateAGroupButtonClicked}+ flex="0 1 140px"+ >{t`Create a group`}</Button>+ )+ }+ description={+ props.description ??+ t`You can use groups to control your users' access to your data. Put users in groups and then go to the Permissions section to control each group's access. The Administrators and All Users groups are special default groups that can't be removed.`}- description={t`You can use groups to control your users' access to your data. Put users in groups and then go to the Permissions section to control each group's access. The Administrators and All Users groups are special default groups that can't be removed.`}><GroupsTable- groups={groups}+ groups={filteredGroups}text={text}showAddGroupRow={isShowingAddGroupRow}groupBeingEdited={groupBeingEdited}diff --git a/frontend/src/metabase/admin/people/components/MembershipSelect/MembershipSelect.tsx b/frontend/src/metabase/admin/people/components/MembershipSelect/MembershipSelect.tsxindex 9bf2cb2970d..86ac8fcb6b2 100644--- a/frontend/src/metabase/admin/people/components/MembershipSelect/MembershipSelect.tsx+++ b/frontend/src/metabase/admin/people/components/MembershipSelect/MembershipSelect.tsx@@ -9,36 +9,41 @@ import {isDefaultGroup,} from "metabase/lib/groups";import { isNotNull } from "metabase/lib/types";-import { PLUGIN_GROUP_MANAGERS } from "metabase/plugins";+import { PLUGIN_GROUP_MANAGERS, PLUGIN_TENANTS } from "metabase/plugins";import { Box, Flex, Icon, Popover } from "metabase/ui";-import type { Group, Member } from "metabase-types/api";+import type { GroupInfo, Member } from "metabase-types/api";import { GroupSummary } from "../GroupSummary";import S from "./MembershipSelect.module.css";-const getGroupSections = (groups: Omit<Group, "members">[]) => {- const defaultGroup = groups.find(isDefaultGroup);+const getGroupSections = (groups: GroupInfo[], groupsTitle = t`Groups`) => {+ const defaultGroup = groups.find(+ (g) => isDefaultGroup(g) || PLUGIN_TENANTS.isExternalUsersGroup(g),+ );const adminGroup = groups.find(isAdminGroup);const pinnedGroups = [defaultGroup, adminGroup].filter(isNotNull);const regularGroups = groups.filter(- (group) => !isAdminGroup(group) && !isDefaultGroup(group),+ (group) =>+ !isAdminGroup(group) &&+ !isDefaultGroup(group) &&+ !PLUGIN_TENANTS.isExternalUsersGroup(group),);if (pinnedGroups.length > 0) {return [{ groups: pinnedGroups },- { groups: regularGroups, header: t`Groups` },+ { groups: regularGroups, header: groupsTitle },];}return [{ groups: regularGroups }];};-type Memberships = Map<Group["id"], Partial<Member>>;+type Memberships = Map<GroupInfo["id"], Partial<Member>>;interface MembershipSelectProps {- groups: Omit<Group, "members">[];+ groups: GroupInfo[];memberships: Memberships;isCurrentUser?: boolean;isUserAdmin: boolean;@@ -47,6 +52,7 @@ interface MembershipSelectProps {onRemove: (groupId: number) => void;onChange: (groupId: number, membershipData: Partial<Member>) => void;isConfirmModalOpen?: boolean;+ groupsTitle?: string;}export const MembershipSelect = ({@@ -58,12 +64,13 @@ export const MembershipSelect = ({isCurrentUser = false,isUserAdmin = false,emptyListMessage = t`No groups`,+ groupsTitle = t`Groups`,isConfirmModalOpen,}: MembershipSelectProps) => {const [popoverOpened, { open: openPopover, toggle: togglePopover }] =useDisclosure();const selectedGroupIds = Array.from(memberships.keys());- const groupSections = getGroupSections(groups);+ const groupSections = getGroupSections(groups, groupsTitle);const handleToggleMembership = (groupId: number) => {if (memberships.has(groupId)) {@@ -119,12 +126,14 @@ export const MembershipSelect = ({{section.groups.map((group) => {const isDisabled =(isAdminGroup(group) && isCurrentUser) ||- isDefaultGroup(group);+ isDefaultGroup(group) ||+ PLUGIN_TENANTS.isExternalUsersGroup(group);const isMember = memberships.has(group.id);const canEditMembershipType =isMember &&!isUserAdmin &&!isDisabled &&+ !PLUGIN_TENANTS.isTenantGroup(group) &&!isAdminGroup(group);return (diff --git a/frontend/src/metabase/admin/people/components/PeopleList.tsx b/frontend/src/metabase/admin/people/components/PeopleList.tsxindex ecc8b278938..5f16d2e962d 100644--- a/frontend/src/metabase/admin/people/components/PeopleList.tsx+++ b/frontend/src/metabase/admin/people/components/PeopleList.tsx@@ -17,9 +17,15 @@ import CS from "metabase/css/core/index.css";import { useDispatch } from "metabase/lib/redux";import { PLUGIN_GROUP_MANAGERS } from "metabase/plugins";import { Box, Flex, Icon, Text } from "metabase/ui";-import type { GroupId, GroupInfo, Member, User } from "metabase-types/api";+import type {+ GroupId,+ GroupInfo,+ Member,+ User,+ UserTenancy,+} from "metabase-types/api";-import { USER_STATUS, type UserStatus } from "../constants";+import { ACTIVE_STATUS, type ActiveStatus } from "../constants";import { PeopleListRow } from "./PeopleListRow";@@ -28,9 +34,10 @@ const defaultUsersValue: User[] = [];interface PeopleListQueryProps {query: {searchText: string;- status: UserStatus;+ status: ActiveStatus;page: number;pageSize: number;+ tenancy: UserTenancy;};}@@ -40,6 +47,8 @@ interface PeopleListProps extends PeopleListQueryProps {isAdmin: boolean;onNextPage?: () => void;onPreviousPage: () => void;+ external?: boolean;+ noResultsMessage: string;}export const PeopleList = ({@@ -49,6 +58,8 @@ export const PeopleList = ({query,onNextPage,onPreviousPage,+ external = false,+ noResultsMessage,}: PeopleListProps) => {const { modalContent, show } = useConfirmation();@@ -57,6 +68,7 @@ export const PeopleList = ({status: query.status === "active" ? undefined : query.status,limit: query.pageSize,offset: query.pageSize * query.page,+ tenancy: query.tenancy,});const users = data?.data || defaultUsersValue;@@ -74,7 +86,7 @@ export const PeopleList = ({const { page, pageSize, status } = query;const isCurrentUser = (u: User) => currentUser.id === u.id;- const showDeactivated = status === USER_STATUS.deactivated;+ const showDeactivated = status === ACTIVE_STATUS.deactivated;const hasUsers = users.length > 0;const handleChange = async (@@ -159,7 +171,7 @@ export const PeopleList = ({return (<LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>- <Box component="section" pb="xl">+ <Box component="section"><tabledata-testid="admin-people-list-table"className={cx(AdminS.ContentTable, CS.borderBottom)}@@ -171,12 +183,13 @@ export const PeopleList = ({<th>{t`Email`}</th>{showDeactivated ? (<Fragment>+ {external && <th>{t`Tenant`}</th>}<th>{t`Deactivated`}</th><th /></Fragment>) : (<Fragment>- <th>{t`Groups`}</th>+ {external ? <th>{t`Tenant`}</th> : <th>{t`Groups`}</th>}<th>{t`Last Login`}</th><th /></Fragment>@@ -238,12 +251,15 @@ export const PeopleList = ({align="center"justify="center"direction="column"- p="xl"+ px="xl"+ pt="xl"ta="center"><Box my="lg"><Icon name="search" mb="sm" size={32} />- <Text c="text-light" fz="lg" fw={700}>{t`No results found`}</Text>+ <Text c="text-light" fz="lg" fw={700}>+ {noResultsMessage}+ </Text></Box></Flex>)}diff --git a/frontend/src/metabase/admin/people/components/PeopleListRow.tsx b/frontend/src/metabase/admin/people/components/PeopleListRow.tsxindex 357f3d41a5e..e6583479183 100644--- a/frontend/src/metabase/admin/people/components/PeopleListRow.tsx+++ b/frontend/src/metabase/admin/people/components/PeopleListRow.tsx@@ -7,7 +7,7 @@ import UserAvatar from "metabase/common/components/UserAvatar";import { useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { getFullName } from "metabase/lib/user";-import { PLUGIN_ADMIN_USER_MENU_ITEMS } from "metabase/plugins";+import { PLUGIN_ADMIN_USER_MENU_ITEMS, PLUGIN_TENANTS } from "metabase/plugins";import { getSetting } from "metabase/selectors/settings";import {Box,@@ -29,7 +29,7 @@ import type {import { userToColor } from "../colors";import { MembershipSelect } from "./MembershipSelect";-import S from "./PeopleListRow.module.css";+import { ReactivateUserButton } from "./ReactivateUserButton";const enablePasswordLoginKey = "enable-password-login";@@ -58,6 +58,7 @@ export const PeopleListRow = ({onChange,isConfirmModalOpen,}: PeopleListRowProps) => {+ const isExternal = !!user.tenant_id;const membershipsByGroupId = useMemo(() =>userMemberships?.reduce((acc, membership) => {@@ -92,31 +93,37 @@ export const PeopleListRow = ({<td>{user.email}</td>{showDeactivated ? (<Fragment>+ {isExternal && (+ <td>+ <PLUGIN_TENANTS.TenantDisplayName id={user.tenant_id} />+ </td>+ )}<td>{dayjs(user.updated_at).fromNow()}</td><td>- <Tooltip label={t`Reactivate this account`}>- <ForwardRefLink- to={Urls.reactivateUser(user.id)}- className={S.refreshLink}- >- <Icon name="refresh" size={20} />- </ForwardRefLink>- </Tooltip>+ {isExternal ? (+ <PLUGIN_TENANTS.ReactivateExternalUserButton user={user} />+ ) : (+ <ReactivateUserButton user={user} />+ )}</td></Fragment>) : (<Fragment><td>- <MembershipSelect- groups={groups}- memberships={membershipsByGroupId}- isCurrentUser={isCurrentUser}- isUserAdmin={user.is_superuser}- onAdd={onAdd}- onRemove={onRemove}- onChange={onChange}- isConfirmModalOpen={isConfirmModalOpen}- />+ {isExternal ? (+ <PLUGIN_TENANTS.TenantDisplayName id={user.tenant_id} />+ ) : (+ <MembershipSelect+ groups={groups}+ memberships={membershipsByGroupId}+ isCurrentUser={isCurrentUser}+ isUserAdmin={user.is_superuser}+ onAdd={onAdd}+ onRemove={onRemove}+ onChange={onChange}+ isConfirmModalOpen={isConfirmModalOpen}+ />+ )}</td><td>{user.last_login ? dayjs(user.last_login).fromNow() : t`Never`}@@ -133,7 +140,7 @@ export const PeopleListRow = ({<Menu.Dropdown><Menu.Itemcomponent={ForwardRefLink}- to={Urls.editUser(user.id)}+ to={Urls.editUser(user)}>{t`Edit user`}</Menu.Item>@@ -141,7 +148,7 @@ export const PeopleListRow = ({{isPasswordLoginEnabled && (<Menu.Itemcomponent={ForwardRefLink}- to={Urls.resetPassword(user.id)}+ to={Urls.resetPassword(user)}>{t`Reset password`}</Menu.Item>@@ -154,7 +161,7 @@ export const PeopleListRow = ({{!isCurrentUser && (<Menu.Itemcomponent={ForwardRefLink}- to={Urls.deactivateUser(user.id)}+ to={Urls.deactivateUser(user)}c="danger">{t`Deactivate user`}diff --git a/frontend/src/metabase/admin/people/components/PeopleNav.tsx b/frontend/src/metabase/admin/people/components/PeopleNav.tsxindex 12a0b32a18c..0c198643e74 100644--- a/frontend/src/metabase/admin/people/components/PeopleNav.tsx+++ b/frontend/src/metabase/admin/people/components/PeopleNav.tsx@@ -7,35 +7,60 @@ import {} from "metabase/admin/components/AdminNav";import { shouldNudgeToPro } from "metabase/admin/people/selectors";import { UpsellSSO } from "metabase/admin/upsells";+import { useSetting } from "metabase/common/hooks";import { useSelector } from "metabase/lib/redux";import { getLocation } from "metabase/selectors/routing";-import { Stack } from "metabase/ui";+import { Divider, Stack } from "metabase/ui";export function PeopleNav() {const shouldNudge = useSelector(shouldNudgeToPro) as boolean;+ const isUsingTenants = useSetting("use-tenants");return (- <AdminNavWrapper justify="space-between">+ <AdminNavWrapper justify="space-between" aria-label="people-nav"><Stack gap="xs"><PeopleNavItempath="/admin/people"data-testid="nav-item"- label={t`People`}+ label={isUsingTenants ? t`Internal Users` : t`People`}icon="person"/><PeopleNavItempath="/admin/people/groups"data-testid="nav-item"- label={t`Groups`}+ label={isUsingTenants ? t`Internal Groups` : t`Groups`}icon="group"/>+ {isUsingTenants && (+ <>+ <Divider my="sm" />+ <PeopleNavItem+ path="/admin/tenants"+ data-testid="nav-item-tenants"+ label={t`Tenants`}+ icon="globe"+ />+ <PeopleNavItem+ path="/admin/tenants/groups"+ data-testid="nav-item-tenant-groups"+ label={t`Tenant Groups`}+ icon="group"+ />+ <PeopleNavItem+ path="/admin/tenants/people"+ data-testid="nav-item-external-users"+ label={t`Tenant users`}+ icon="person"+ />+ </>+ )}</Stack>{shouldNudge && <UpsellSSO location="people-groups-settings" />}</AdminNavWrapper>);}-const PeopleNavItem = (props: AdminNavItemProps) => {+export const PeopleNavItem = (props: AdminNavItemProps) => {const location = useSelector(getLocation);const subpath = location?.pathname;diff --git a/frontend/src/metabase/admin/people/components/PeopleListRow.module.css b/frontend/src/metabase/admin/people/components/ReactivateUserButton.module.csssimilarity index 62%rename from frontend/src/metabase/admin/people/components/PeopleListRow.module.cssrename to frontend/src/metabase/admin/people/components/ReactivateUserButton.module.cssindex 81040beb4d7..793bd0072dc 100644--- a/frontend/src/metabase/admin/people/components/PeopleListRow.module.css+++ b/frontend/src/metabase/admin/people/components/ReactivateUserButton.module.css@@ -6,4 +6,9 @@&:hover {color: var(--mb-color-brand);}++ &.disabled:hover {+ color: var(--mb-color-text-light);+ cursor: unset;+ }}diff --git a/frontend/src/metabase/admin/people/components/ReactivateUserButton.tsx b/frontend/src/metabase/admin/people/components/ReactivateUserButton.tsxnew file mode 100644index 00000000000..d341537a5a3--- /dev/null+++ b/frontend/src/metabase/admin/people/components/ReactivateUserButton.tsx@@ -0,0 +1,29 @@+import cx from "classnames";+import { t } from "ttag";++import { ForwardRefLink } from "metabase/common/components/Link";+import * as Urls from "metabase/lib/urls";+import { Icon, Tooltip } from "metabase/ui";+import type { User } from "metabase-types/api";++import S from "./ReactivateUserButton.module.css";++export const ReactivateUserButton = ({+ user,+ disabled = false,+ tooltipLabel = t`Reactivate this account`,+}: {+ user: User;+ disabled?: boolean;+ tooltipLabel?: string;+}) => (+ <Tooltip label={tooltipLabel}>+ <ForwardRefLink+ to={Urls.reactivateUser(user)}+ className={cx(S.refreshLink, { [S.disabled]: disabled })}+ onClick={(e) => (disabled ? e.preventDefault() : true)}+ >+ <Icon name="refresh" size={20} />+ </ForwardRefLink>+ </Tooltip>+);diff --git a/frontend/src/metabase/admin/people/components/SearchFilter.tsx b/frontend/src/metabase/admin/people/components/SearchFilter.tsxnew file mode 100644index 00000000000..4bd7fdebfd1--- /dev/null+++ b/frontend/src/metabase/admin/people/components/SearchFilter.tsx@@ -0,0 +1,36 @@+import { Icon, Input, TextInput } from "metabase/ui";++interface SearchFilterProps {+ value: string;+ onChange: (value: string) => void;+ placeholder: string;+}++export const SearchFilter = ({+ value,+ onChange,+ placeholder,+}: SearchFilterProps) => {+ return (+ <TextInput+ w="100%"+ fz="sm"+ type="text"+ placeholder={placeholder}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ leftSection={<Icon c="text-secondary" name="search" size={16} />}+ rightSectionPointerEvents="all"+ rightSection={+ value === "" ? (+ <div /> // rendering null causes width change+ ) : (+ <Input.ClearButton+ c={"text-secondary"}+ onClick={() => onChange("")}+ />+ )+ }+ />+ );+};diff --git a/frontend/src/metabase/admin/people/constants.ts b/frontend/src/metabase/admin/people/constants.tsindex 3b94b8e851e..b3b213c8194 100644--- a/frontend/src/metabase/admin/people/constants.ts+++ b/frontend/src/metabase/admin/people/constants.ts@@ -1,6 +1,6 @@-export type UserStatus = "active" | "deactivated";+export type ActiveStatus = "active" | "deactivated";-export const USER_STATUS: Record<string, UserStatus> = {+export const ACTIVE_STATUS: Record<string, ActiveStatus> = {active: "active",deactivated: "deactivated",};diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/AdminPeopleApp.unit.spec.tsxdeleted file mode 100644index 1ca9edd847e..00000000000--- a/frontend/src/metabase/admin/people/containers/AdminPeopleApp.unit.spec.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { Route } from "react-router";--import { renderWithProviders, screen } from "__support__/ui";-import { AdminPeopleApp } from "metabase/admin/people/containers/AdminPeopleApp";-import {- createMockTokenFeatures,- createMockUser,-} from "metabase-types/api/mocks";-import {- createMockSettingsState,- createMockState,-} from "metabase-types/store/mocks";-interface SetupOpts {- activeUsersCount: number;- ssoEnabled: boolean;- isSuperUser: boolean;-}--const setup = ({ activeUsersCount, ssoEnabled, isSuperUser }: SetupOpts) => {- const state = createMockState({- currentUser: createMockUser({- is_superuser: isSuperUser,- }),- settings: createMockSettingsState({- "active-users-count": activeUsersCount,- "token-features": createMockTokenFeatures({- sso_saml: ssoEnabled,- }),- }),- });-- renderWithProviders(- <Route path="*" component={() => <AdminPeopleApp>empty</AdminPeopleApp>} />,- {- storeInitialState: state,- withRouter: true,- initialRoute: "/admin/people",- },- );-};--describe("AdminPeopleApp", () => {- describe("nudge to pro", () => {- const nudgeText = /tired of manually managing people/i;- const setupOpts = {- activeUsersCount: 50,- ssoEnabled: false,- isSuperUser: true,- };-- it("should be visible when user is admin, has 50 active users, and SSO is not available", () => {- setup(setupOpts);- expect(screen.getByText(nudgeText)).toBeInTheDocument();- const link = screen.getByRole("link", { name: /try metabase pro/i });- expect(link).toBeInTheDocument();- expect(link).toHaveAttribute(- "href",- expect.stringMatching(/^https:\/\/www.metabase.com\/upgrade/),- );- });-- it("should not be visible with less than 50 users", () => {- setup({ ...setupOpts, activeUsersCount: 10 });- expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();- });-- it("should not be visible when user is not admin", () => {- setup({ ...setupOpts, isSuperUser: false });- expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();- });-- it("should not be visible when SSO is already available", () => {- setup({ ...setupOpts, ssoEnabled: true });- expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();- });- });-});diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp.tsx b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsxsimilarity index 86%rename from frontend/src/metabase/admin/people/containers/AdminPeopleApp.tsxrename to frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsxindex 4bf8fb06bf3..5ea326a8e53 100644--- a/frontend/src/metabase/admin/people/containers/AdminPeopleApp.tsx+++ b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsx@@ -2,7 +2,7 @@ import type * as React from "react";import { AdminSettingsLayout } from "metabase/common/components/AdminLayout/AdminSettingsLayout";-import { PeopleNav } from "../components/PeopleNav";+import { PeopleNav } from "../../components/PeopleNav";export const AdminPeopleApp = ({ children }: { children: React.ReactNode }) => {return (diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsxnew file mode 100644index 00000000000..5c4c96e1e02--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx@@ -0,0 +1,109 @@+import { Route } from "react-router";++import { renderWithProviders, screen } from "__support__/ui";+import {+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";+import {+ createMockSettingsState,+ createMockState,+} from "metabase-types/store/mocks";++import { AdminPeopleApp } from "./AdminPeopleApp";++interface SetupOpts {+ activeUsersCount?: number;+ ssoEnabled?: boolean;+ isSuperUser?: boolean;+ useTenants?: boolean;+}++const setup = async (inputSetupOpts?: Partial<SetupOpts>) => {+ const defaultSetupOpts: SetupOpts = {+ activeUsersCount: 50,+ ssoEnabled: false,+ isSuperUser: true,+ useTenants: false,+ };+ const setupOpts = Object.assign(defaultSetupOpts, inputSetupOpts ?? {});++ const state = createMockState({+ currentUser: createMockUser({+ is_superuser: setupOpts.isSuperUser,+ }),+ settings: createMockSettingsState({+ "active-users-count": setupOpts.activeUsersCount,+ "use-tenants": setupOpts.useTenants,+ "token-features": createMockTokenFeatures({+ sso_saml: setupOpts.ssoEnabled,+ }),+ }),+ });++ renderWithProviders(+ <Route path="/" component={() => <AdminPeopleApp>empty</AdminPeopleApp>} />,+ {+ storeInitialState: state,+ withRouter: true,+ },+ );+};++describe("AdminPeopleApp", () => {+ describe("sidebar", () => {+ it("should render only internal people and groups links if tenants is disabled", async () => {+ await setup();++ assertNavLink("People", "/admin/people");+ assertNavLink("Groups", "/admin/people/groups");+ expect(screen.queryByText("Tenants")).not.toBeInTheDocument();+ expect(screen.queryByText("Tenant users")).not.toBeInTheDocument();+ });++ it("should render both internal and external people links if tenants is enabled", async () => {+ await setup({ useTenants: true });++ assertNavLink("Internal Users", "/admin/people");+ assertNavLink("Internal Groups", "/admin/people/groups");+ assertNavLink("Tenants", "/admin/tenants");+ assertNavLink("Tenant users", "/admin/tenants/people");+ });+ });++ describe("nudge to pro", () => {+ const nudgeText = /tired of manually managing people/i;++ it("should be visible when user is admin, has 50 active users, and SSO is not available", () => {+ setup();+ expect(screen.getByText(nudgeText)).toBeInTheDocument();+ const link = screen.getByRole("link", { name: /try metabase pro/i });+ expect(link).toBeInTheDocument();+ expect(link).toHaveAttribute(+ "href",+ expect.stringMatching(/^https:\/\/www.metabase.com\/upgrade/),+ );+ });++ it("should not be visible with less than 50 users", () => {+ setup({ activeUsersCount: 10 });+ expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();+ });++ it("should not be visible when user is not admin", () => {+ setup({ isSuperUser: false });+ expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();+ });++ it("should not be visible when SSO is already available", () => {+ setup({ ssoEnabled: true });+ expect(screen.queryByText(nudgeText)).not.toBeInTheDocument();+ });+ });+});++async function assertNavLink(linkText: string, linkHref: string) {+ const link = await screen.findByText(linkText);+ expect(link).toBeInTheDocument();+ expect(link).toHaveAttribute("href", linkHref);+}diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/index.ts b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/index.tsnew file mode 100644index 00000000000..18d810ee1be--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/index.ts@@ -0,0 +1 @@+export * from "./AdminPeopleApp";diff --git a/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx b/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsxindex 4fb8b72d2bd..b4450dd328f 100644--- a/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx+++ b/frontend/src/metabase/admin/people/containers/EditUserModal/EditUserModal.tsx@@ -1,5 +1,6 @@import { useMemo } from "react";import type { Params } from "react-router/lib/Router";+import { t } from "ttag";import {skipToken,@@ -15,9 +16,14 @@ import { UserForm } from "../../forms/UserForm";interface EditUserModalProps {onClose: () => void;params: Params;+ external?: boolean;}-export const EditUserModal = ({ onClose, params }: EditUserModalProps) => {+export const EditUserModal = ({+ onClose,+ params,+ external = false,+}: EditUserModalProps) => {const userId = params.userId ? parseInt(params.userId) : null;const { data: user, isLoading, error } = useGetUserQuery(userId ?? skipToken);const [updateUser] = useUpdateUserMutation();@@ -27,10 +33,15 @@ export const EditUserModal = ({ onClose, params }: EditUserModalProps) => {first_name: user?.first_name,last_name: user?.last_name,email: user?.email,- user_group_memberships: user?.user_group_memberships || [],+login_attributes: user?.login_attributes || {},+ user_group_memberships: user?.user_group_memberships || [],++ ...(external+ ? { tenant_id: user?.tenant_id }+ : { user_group_memberships: user?.user_group_memberships || [] }),}),- [user],+ [user, external],);const handleSubmit = async (newValues: Partial<User>) => {@@ -47,13 +58,15 @@ export const EditUserModal = ({ onClose, params }: EditUserModalProps) => {};return (- <Modal opened title="Edit user" padding="xl" onClose={onClose}>+ <Modal opened title={t`Edit user`} padding="xl" onClose={onClose}><LoadingAndErrorWrapper loading={isLoading} error={error}><UserFormonCancel={onClose}initialValues={initialValues}onSubmit={handleSubmit}+ external={external}userId={userId}+ edit/></LoadingAndErrorWrapper></Modal>diff --git a/frontend/src/metabase/admin/people/containers/GroupDetailApp.tsx b/frontend/src/metabase/admin/people/containers/GroupDetailApp.tsxindex 087b7fbe222..c96e81d7617 100644--- a/frontend/src/metabase/admin/people/containers/GroupDetailApp.tsx+++ b/frontend/src/metabase/admin/people/containers/GroupDetailApp.tsx@@ -11,10 +11,16 @@ import { getUser } from "metabase/selectors/user";import { GroupDetail } from "../components/GroupDetail";-export const GroupDetailApp = (props: any) => {+export const GroupDetailApp = ({+ params: { groupId },+ title,+}: {+ params: { groupId: number };+ title?: string;+}) => {const currentUser = useSelector(getUser);- const getGroupReq = useGetPermissionsGroupQuery(props.params.groupId);+ const getGroupReq = useGetPermissionsGroupQuery(groupId);const membershipsByUserReq = useListUserMembershipsQuery();const error = getGroupReq.error ?? membershipsByUserReq.error;@@ -22,7 +28,7 @@ export const GroupDetailApp = (props: any) => {getGroupReq.isLoading ?? membershipsByUserReq.isLoading ?? !currentUser;return (- <SettingsPageWrapper title={t`Groups`}>+ <SettingsPageWrapper title={title ?? t`Groups`}><LoadingAndErrorWrapper error={error} loading={isLoading}>{currentUser && (<GroupDetaildiff --git a/frontend/src/metabase/admin/people/containers/GroupsListingApp.tsx b/frontend/src/metabase/admin/people/containers/GroupsListingApp.tsxindex c8c352ead7b..d7b6d72fffd 100644--- a/frontend/src/metabase/admin/people/containers/GroupsListingApp.tsx+++ b/frontend/src/metabase/admin/people/containers/GroupsListingApp.tsx@@ -1,4 +1,6 @@+import { useMemo } from "react";import { t } from "ttag";+import _ from "underscore";import {SettingsPageWrapper,@@ -11,26 +13,43 @@ import {useUpdatePermissionsGroupMutation,} from "metabase/api";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSetting } from "metabase/common/hooks";import { useDispatch, useSelector } from "metabase/lib/redux";-import { PLUGIN_GROUP_MANAGERS } from "metabase/plugins";+import { PLUGIN_GROUP_MANAGERS, PLUGIN_TENANTS } from "metabase/plugins";import { getUserIsAdmin } from "metabase/selectors/user";import type { Group } from "metabase-types/api";import { GroupsListing } from "../components/GroupsListing";-export const GroupsListingApp = () => {+export const GroupsListingApp = ({+ external,+ description,+}: {+ external?: boolean;+ description?: string;+}) => {const dispatch = useDispatch();const isAdmin = useSelector(getUserIsAdmin);+ const isUsingTenants = useSetting("use-tenants");- const { data, isLoading, error } = useListPermissionsGroupsQuery();- const groups = data ?? [];+ const { data, isLoading, error } = useListPermissionsGroupsQuery({});+ const groups = useMemo(() => {+ const [externalGroups, internalGroups] = _.partition(+ data ?? [],+ PLUGIN_TENANTS.isTenantGroup,+ );+ return external ? externalGroups : internalGroups;+ }, [data, external]);const [createGroup] = useCreatePermissionsGroupMutation();const [updateGroup] = useUpdatePermissionsGroupMutation();const [deleteGroup] = useDeletePermissionsGroupMutation();const handleCreate = async (group: { name: string }) => {- await createGroup(group).unwrap();+ await createGroup({+ ...group,+ is_tenant_group: external,+ }).unwrap();};const handleUpdate = async (group: { id: number; name: string }) => {@@ -48,11 +67,20 @@ export const GroupsListingApp = () => {}};+ const pageTitle = useMemo(() => {+ if (!isUsingTenants) {+ return t`Groups`;+ }++ return external ? t`Tenant Groups` : t`Internal Groups`;+ }, [external, isUsingTenants]);+return (- <SettingsPageWrapper title={t`Groups`}>+ <SettingsPageWrapper title={pageTitle}><SettingsSection><LoadingAndErrorWrapper error={error} loading={isLoading}><GroupsListing+ description={description}isAdmin={isAdmin}groups={groups}create={handleCreate}diff --git a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx b/frontend/src/metabase/admin/people/containers/NewUserModal.tsxindex 22a3fc76207..4fdb0e53d07 100644--- a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx+++ b/frontend/src/metabase/admin/people/containers/NewUserModal.tsx@@ -6,6 +6,7 @@ import { useDispatch } from "metabase/lib/redux";import { generatePassword } from "metabase/lib/security";import MetabaseSettings from "metabase/lib/settings";import * as Urls from "metabase/lib/urls";+import { PLUGIN_TENANTS } from "metabase/plugins";import { Modal } from "metabase/ui";import type { User as UserType } from "metabase-types/api";@@ -13,9 +14,13 @@ import { UserForm } from "../forms/UserForm";interface NewUserModalProps {onClose: () => void;+ external?: boolean;}-export const NewUserModal = ({ onClose }: NewUserModalProps) => {+export const NewUserModal = ({+ onClose,+ external = false,+}: NewUserModalProps) => {const dispatch = useDispatch();const [createUser] = useCreateUserMutation();@@ -32,12 +37,16 @@ export const NewUserModal = ({ onClose }: NewUserModalProps) => {: { password: generatePassword() }),}).unwrap();- dispatch(push(Urls.newUserSuccess(user.id)));+ dispatch(push(Urls.newUserSuccess(user)));};+ // Use plugin-provided title for external users, fallback to default+ const title = PLUGIN_TENANTS.getNewUserModalTitle(external) ?? t`Create user`;+return (- <Modal opened title={t`Create user`} padding="xl" onClose={onClose}>+ <Modal opened title={title} padding="xl" onClose={onClose}><UserForm+ external={external}initialValues={{}}submitText={t`Create`}onCancel={onClose}diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp.tsx b/frontend/src/metabase/admin/people/containers/PeopleListingApp.tsxdeleted file mode 100644index 8ca1088b3a5..00000000000--- a/frontend/src/metabase/admin/people/containers/PeopleListingApp.tsx+++ /dev/null@@ -1,147 +0,0 @@-import { useEffect } from "react";-import { Link } from "react-router";-import { t } from "ttag";--import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/admin/components/SettingsSection";-import { useListPermissionsGroupsQuery, useListUsersQuery } from "metabase/api";-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { useSelector } from "metabase/lib/redux";-import * as Urls from "metabase/lib/urls";-import { getUser, getUserIsAdmin } from "metabase/selectors/user";-import { Box, Button, Flex, Icon, Input, Stack, Tabs } from "metabase/ui";--import { PeopleList } from "../components/PeopleList";-import { USER_STATUS, type UserStatus } from "../constants";-import { usePeopleQuery } from "../hooks/use-people-query";--import S from "./PeopleListingApp.module.css";--const PAGE_SIZE = 25;--export function PeopleListingApp({ children }: { children: React.ReactNode }) {- const isAdmin = useSelector(getUserIsAdmin);- const currentUser = useSelector(getUser);-- const {- data: groups = [],- isLoading,- error,- } = useListPermissionsGroupsQuery();-- const {- query,- status,- searchInputValue,- updateSearchInputValue,- updateStatus,- handleNextPage,- handlePreviousPage,- } = usePeopleQuery(PAGE_SIZE);-- const { data: usersData } = useListUsersQuery({- status: "deactivated",- limit: 0,- });- const hasDeactivatedUsers = usersData && usersData.total > 0;-- const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {- updateSearchInputValue(e.target.value);- };-- const buttonText =- isAdmin && status === USER_STATUS.active ? t`Invite someone` : undefined;-- const handleTabChange = (tab: string | null) => {- if (tab) {- updateStatus(tab as UserStatus);- }- };-- useEffect(() => {- if (!hasDeactivatedUsers) {- updateStatus("active");- }- }, [hasDeactivatedUsers, updateStatus]);-- return (- <SettingsPageWrapper title={t`People`}>- <Stack gap={0}>- {isAdmin && hasDeactivatedUsers && (- <Tabs value={status} onChange={handleTabChange} pl="md">- <Tabs.List className={S.tabs}>- <Tabs.Tab value={USER_STATUS.active}>{t`Active`}</Tabs.Tab>- <Tabs.Tab- value={USER_STATUS.deactivated}- >{t`Deactivated`}</Tabs.Tab>- </Tabs.List>- </Tabs>- )}-- <SettingsSection>- <LoadingAndErrorWrapper- error={error}- loading={isLoading || !currentUser}- >- <div data-testid="admin-panel">- <Flex- align="center"- gap="xl"- justify="space-between"- mb="xl"- wrap="wrap"- >- <Input- miw="14rem"- fz="sm"- flex="1"- type="text"- placeholder={t`Find someone`}- value={searchInputValue}- onChange={handleSearchChange}- leftSection={- <Icon c="text-secondary" name="search" size={16} />- }- rightSectionPointerEvents="all"- rightSection={- searchInputValue === "" ? (- <div /> // rendering null causes width change- ) : (- <Input.ClearButton- c={"text-secondary"}- onClick={() => updateSearchInputValue("")}- />- )- }- />-- {buttonText && (- <Box>- <Link to={Urls.newUser()}>- <Button variant="filled">{buttonText}</Button>- </Link>- </Box>- )}- </Flex>-- {currentUser && (- <PeopleList- groups={groups}- isAdmin={isAdmin}- currentUser={currentUser}- query={query}- onNextPage={handleNextPage}- onPreviousPage={handlePreviousPage}- />- )}-- {children}- </div>- </LoadingAndErrorWrapper>- </SettingsSection>- </Stack>- </SettingsPageWrapper>- );-}diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.module.css b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.module.cssnew file mode 100644index 00000000000..56e849a0eff--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.module.css@@ -0,0 +1,5 @@+.tabs {+ &:before {+ display: none;+ }+}diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.tsx b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.tsxnew file mode 100644index 00000000000..f7c859dc09c--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.tsx@@ -0,0 +1,161 @@+import { useEffect, useMemo } from "react";+import { Link } from "react-router";+import { t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import { useListPermissionsGroupsQuery, useListUsersQuery } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSetting } from "metabase/common/hooks";+import { useSelector } from "metabase/lib/redux";+import * as Urls from "metabase/lib/urls";+import { PLUGIN_TENANTS } from "metabase/plugins";+import { getUser, getUserIsAdmin } from "metabase/selectors/user";+import { Box, Button, Flex, Group, Tabs, Title } from "metabase/ui";++import { PeopleList } from "../../components/PeopleList";+import { SearchFilter } from "../../components/SearchFilter";+import { ACTIVE_STATUS, type ActiveStatus } from "../../constants";+import { usePeopleQuery } from "../../hooks/use-people-query";++import S from "./PeopleListingApp.module.css";++const PAGE_SIZE = 25;++const DEFAULT_NO_RESULTS_MESSAGE = () => t`No results found`;++export function PeopleListingApp({+ children,+ external = false,+ showInviteButton = true,+ noResultsMessage = DEFAULT_NO_RESULTS_MESSAGE(),+}: {+ children?: React.ReactNode;+ external?: boolean;+ showInviteButton?: boolean;+ noResultsMessage?: string;+}) {+ const isAdmin = useSelector(getUserIsAdmin);+ const currentUser = useSelector(getUser);+ const isUsingTenants = useSetting("use-tenants");++ const {+ data: groups = [],+ isLoading,+ error,+ } = useListPermissionsGroupsQuery(+ { tenancy: "internal" },+ { skip: external },+ );++ const {+ query,+ status,+ searchInputValue,+ updateSearchInputValue,+ updateStatus,+ handleNextPage,+ handlePreviousPage,+ } = usePeopleQuery(PAGE_SIZE, external ? "external" : "internal");++ const { data: usersData } = useListUsersQuery({+ status: "deactivated",+ limit: 0,+ ...(external ? { tenancy: "external" } : { tenancy: "internal" }),+ });+ const hasDeactivatedUsers = usersData && usersData.total > 0;++ const noUsersFoundMessage =+ status === ACTIVE_STATUS.active+ ? noResultsMessage+ : DEFAULT_NO_RESULTS_MESSAGE();++ const buttonText =+ isAdmin && status === ACTIVE_STATUS.active && showInviteButton+ ? external+ ? t`Create tenant user`+ : t`Invite someone`+ : undefined;++ const handleTabChange = (tab: string | null) => {+ if (tab) {+ updateStatus(tab as ActiveStatus);+ }+ };++ useEffect(() => {+ if (!hasDeactivatedUsers) {+ updateStatus("active");+ }+ }, [hasDeactivatedUsers, updateStatus]);++ const pageTitle = useMemo(() => {+ if (!isUsingTenants) {+ return t`People`;+ }++ return external ? t`Tenant users` : t`Internal Users`;+ }, [external, isUsingTenants]);++ return (+ <div>+ <Group justify="space-between" w="100%" mb="lg">+ <Title order={1}>{pageTitle}</Title>++ {!external && <PLUGIN_TENANTS.EditUserStrategySettingsButton />}+ </Group>++ {isAdmin && hasDeactivatedUsers && (+ <Tabs value={status} onChange={handleTabChange} pl="md">+ <Tabs.List className={S.tabs}>+ <Tabs.Tab value={ACTIVE_STATUS.active}>{t`Active`}</Tabs.Tab>+ <Tabs.Tab+ value={ACTIVE_STATUS.deactivated}+ >{t`Deactivated`}</Tabs.Tab>+ </Tabs.List>+ </Tabs>+ )}++ <SettingsSection>+ <LoadingAndErrorWrapper+ error={error}+ loading={isLoading || !currentUser}+ >+ <div data-testid="admin-panel">+ <Group w="100%" justify="space-between" mb="lg" gap="md">+ <Flex flex="1">+ <SearchFilter+ value={searchInputValue}+ onChange={updateSearchInputValue}+ placeholder={t`Find someone`}+ />+ </Flex>++ {buttonText && (+ <Box>+ <Link to={external ? Urls.newTenantUser() : Urls.newUser()}>+ <Button variant="filled">{buttonText}</Button>+ </Link>+ </Box>+ )}+ </Group>++ {currentUser && (+ <PeopleList+ external={external}+ groups={groups}+ isAdmin={isAdmin}+ currentUser={currentUser}+ query={query}+ onNextPage={handleNextPage}+ onPreviousPage={handlePreviousPage}+ noResultsMessage={noUsersFoundMessage}+ />+ )}++ {children}+ </div>+ </LoadingAndErrorWrapper>+ </SettingsSection>+ </div>+ );+}diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsxnew file mode 100644index 00000000000..ccc54ff59c0--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx@@ -0,0 +1,170 @@+import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupGroupsEndpoint,+ setupPermissionMembershipEndpoint,+ setupTenantEntpoints,+ setupUsersEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import type { Tenant, User } from "metabase-types/api";+import {+ createMockGroup,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import { PeopleListingApp } from "./PeopleListingApp";++const setup = ({+ external = false,+ showInviteButton = true,+ noResultsMessage = "No results found",+ users = [createMockUser()],+ currentUser = createMockUser({+ is_superuser: true,+ }),+ tenants = [],+ useTenants = true,+}: {+ external?: boolean;+ showInviteButton?: boolean;+ noResultsMessage?: string;+ users?: User[];+ currentUser?: User;+ tenants?: Tenant[];+ useTenants?: boolean;+} = {}) => {+ const settings = mockSettings({+ "token-features": createMockTokenFeatures({+ tenants: true,+ }),+ "use-tenants": useTenants,+ });++ setupEnterprisePlugins();+ setupTenantEntpoints(tenants);++ setupGroupsEndpoint([+ createMockGroup(),+ createMockGroup({+ name: "Admin",+ id: 2,+ magic_group_type: "admin",+ }),+ ]);++ setupUsersEndpoints(users);++ setupPermissionMembershipEndpoint({});++ renderWithProviders(+ <PeopleListingApp+ external={external}+ showInviteButton={showInviteButton}+ noResultsMessage={noResultsMessage}+ >+ <></>+ </PeopleListingApp>,+ {+ storeInitialState: createMockState({+ settings,+ currentUser,+ }),+ },+ );+};++describe("page title", () => {+ it("should show 'People' when tenants is disabled", async () => {+ setup({ useTenants: false });++ expect(+ await screen.findByRole("heading", { name: "People", level: 1 }),+ ).toBeInTheDocument();+ });++ it("should show 'Internal Users' when tenants is enabled and viewing internal users", async () => {+ setup({ useTenants: true, external: false });++ expect(+ await screen.findByRole("heading", { name: "Internal Users", level: 1 }),+ ).toBeInTheDocument();+ });++ it("should show 'Tenant users' when tenants is enabled and viewing tenant users", async () => {+ setup({ useTenants: true, external: true });++ expect(+ await screen.findByRole("heading", { name: "Tenant users", level: 1 }),+ ).toBeInTheDocument();+ });+});++describe("people table", () => {+ it("should show group association when viewing internal users", async () => {+ setup();++ expect(await screen.findByText("Name")).toBeInTheDocument();+ expect(await screen.findByText("Email")).toBeInTheDocument();+ expect(await screen.findByText("Groups")).toBeInTheDocument();+ expect(await screen.findByText("Last Login")).toBeInTheDocument();+ });+});++describe("user strategy button", () => {+ it("should appear when viewing internal users page", async () => {+ setup();++ expect(+ await screen.findByRole("button", { name: /gear/i }),+ ).toBeInTheDocument();+ });+});++describe("invite button", () => {+ it("should show when looking at internal users", async () => {+ setup();++ expect(await screen.findByText("Invite someone")).toBeInTheDocument();+ });++ it("should be hidden when the current user is not an admin", () => {+ setup({+ currentUser: createMockUser({+ is_superuser: false,+ }),+ });++ expect(screen.queryByText("Invite someone")).not.toBeInTheDocument();+ });++ it("should hide when showInviteButton is false", () => {+ setup({+ showInviteButton: false,+ });++ expect(screen.queryByText("Invite someone")).not.toBeInTheDocument();+ });+});++describe("no results message", () => {+ it("should show a default message", async () => {+ setup({+ users: [],+ });++ expect(await screen.findByText("No results found")).toBeInTheDocument();+ });++ it("should allow you to show a custom message", async () => {+ const noResultsMessage = "These are not the users you are looking for";+ setup({+ users: [],+ noResultsMessage,+ });++ expect(await screen.findByText(noResultsMessage)).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp/index.ts b/frontend/src/metabase/admin/people/containers/PeopleListingApp/index.tsnew file mode 100644index 00000000000..c9bc6b57cb1--- /dev/null+++ b/frontend/src/metabase/admin/people/containers/PeopleListingApp/index.ts@@ -0,0 +1 @@+export * from "./PeopleListingApp";diff --git a/frontend/src/metabase/admin/people/containers/UserActivationModal.tsx b/frontend/src/metabase/admin/people/containers/UserActivationModal.tsxindex 8969a712254..c2342b1b50e 100644--- a/frontend/src/metabase/admin/people/containers/UserActivationModal.tsx+++ b/frontend/src/metabase/admin/people/containers/UserActivationModal.tsx@@ -20,7 +20,10 @@ export const UserActivationModal = ({onClose,}: UserActivationModalInnerProps) => {const userId = parseInt(params.userId, 10);- const { data } = useListUsersQuery({ include_deactivated: true });+ const { data } = useListUsersQuery({+ include_deactivated: true,+ tenancy: "all",+ });const user = useMemo(() => {const users = data?.data ?? [];diff --git a/frontend/src/metabase/admin/people/containers/UserSuccessModal.tsx b/frontend/src/metabase/admin/people/containers/UserSuccessModal.tsxindex e4eadd4167f..adae2bd0bc3 100644--- a/frontend/src/metabase/admin/people/containers/UserSuccessModal.tsx+++ b/frontend/src/metabase/admin/people/containers/UserSuccessModal.tsx@@ -1,6 +1,7 @@import cx from "classnames";import { useEffect } from "react";-import { push } from "react-router-redux";+import type { WithRouterProps } from "react-router";+import { push, replace } from "react-router-redux";import { jt, t } from "ttag";import { useGetUserQuery } from "metabase/api";@@ -10,6 +11,7 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport PasswordReveal from "metabase/common/components/PasswordReveal";import CS from "metabase/css/core/index.css";import { useDispatch, useSelector } from "metabase/lib/redux";+import { PLUGIN_TENANTS } from "metabase/plugins";import { getSetting, isSsoEnabled } from "metabase/selectors/settings";import { Box } from "metabase/ui";import type { User } from "metabase-types/api";@@ -17,7 +19,7 @@ import type { User } from "metabase-types/api";import { clearTemporaryPassword } from "../people";import { getUserTemporaryPassword } from "../selectors";-interface UserSuccessModalProps {+interface UserSuccessModalProps extends WithRouterProps {params: { userId: string };}@@ -25,6 +27,8 @@ export function UserSuccessModal({ params }: UserSuccessModalProps) {const userId = parseInt(params.userId);const { data: user, isLoading, error } = useGetUserQuery(userId);+ const isExternalUser = PLUGIN_TENANTS.isExternalUser(user);+const temporaryPassword = useSelector((state) =>getUserTemporaryPassword(state, { userId }),);@@ -35,7 +39,9 @@ export function UserSuccessModal({ params }: UserSuccessModalProps) {const dispatch = useDispatch();const handleClose = () => {- dispatch(push("/admin/people"));+ dispatch(+ isExternalUser ? push("/admin/tenants/people") : push("/admin/people"),+ );};useEffect(() => {@@ -44,6 +50,12 @@ export function UserSuccessModal({ params }: UserSuccessModalProps) {};}, [userId, dispatch]);+ useEffect(() => {+ if (isExternalUser && !temporaryPassword) {+ dispatch(replace("/admin/tenants/people"));+ }+ }, [isExternalUser, temporaryPassword, dispatch]);+if (!user || isLoading || error != null) {return <LoadingAndErrorWrapper loading={isLoading} error={error} />;}diff --git a/frontend/src/metabase/admin/people/forms/UserForm.tsx b/frontend/src/metabase/admin/people/forms/UserForm.tsxindex 066535f94a0..676f90c547b 100644--- a/frontend/src/metabase/admin/people/forms/UserForm.tsx+++ b/frontend/src/metabase/admin/people/forms/UserForm.tsx@@ -11,7 +11,10 @@ import {FormTextInput,} from "metabase/forms";import * as Errors from "metabase/lib/errors";-import { PLUGIN_ADMIN_USER_FORM_FIELDS } from "metabase/plugins";+import {+ PLUGIN_ADMIN_USER_FORM_FIELDS,+ PLUGIN_TENANTS,+} from "metabase/plugins";import { Button } from "metabase/ui";import type { User, UserId } from "metabase-types/api";@@ -21,11 +24,17 @@ const localUserSchema = Yup.object({email: Yup.string().email().required(Errors.required),});+const externalUserSchema = localUserSchema.shape({+ tenant_id: Yup.number().required(Errors.required),+});+interface UserFormProps {initialValues?: Partial<User>;onSubmit: (val: Partial<User>) => void;onCancel: () => void;submitText?: string;+ external?: boolean;+ edit?: boolean;userId?: UserId | null;}@@ -34,12 +43,15 @@ export const UserForm = ({onSubmit,onCancel,submitText = t`Update`,+ external = false,+ edit = false,userId,}: UserFormProps) => {return (<FormProviderinitialValues={initialValues}- validationSchema={localUserSchema}+ validationSchema={external ? externalUserSchema : localUserSchema}+ validateOnMountenableReinitializeonSubmit={onSubmit}>@@ -70,7 +82,19 @@ export const UserForm = ({requiredmb="md"/>- <FormGroupsWidget name="user_group_memberships" />+ <FormGroupsWidget+ name="user_group_memberships"+ external={external}+ title={PLUGIN_TENANTS.getFormGroupsTitle(external) ?? t`Groups`}+ />+ {external && (+ <PLUGIN_TENANTS.FormTenantWidget+ required+ name="tenant_id"+ placeholder={t`Select a tenant`}+ disabled={edit}+ />+ )}<PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes userId={userId} /><FormFooter><FormErrorMessage inline />diff --git a/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx b/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsxindex 4ea8733bb77..fbbf2871325 100644--- a/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx+++ b/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx@@ -2,10 +2,13 @@ import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { setupEnterprisePlugins } from "__support__/enterprise";+import { setupTenantEntpoints } from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { Tenant } from "metabase-types/api";import {createMockGroup,+ createMockTenant,createMockTokenFeatures,createMockUser,} from "metabase-types/api/mocks";@@ -14,11 +17,11 @@ import { createMockState } from "metabase-types/store/mocks";import { UserForm } from "./UserForm";const GROUPS = [- createMockGroup(),- createMockGroup({ id: 2, name: "Administrators" }),- createMockGroup({ id: 3, name: "foo" }),- createMockGroup({ id: 4, name: "bar" }),- createMockGroup({ id: 5, name: "flamingos" }),+ 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 }),+ createMockGroup({ id: 4, name: "bar", magic_group_type: null }),+ createMockGroup({ id: 5, name: "flamingos", magic_group_type: null }),];const USER = createMockUser({@@ -31,16 +34,24 @@ const USER = createMockUser({],});-const setup = ({ hasEnterprisePlugins = false, initialValues = USER } = {}) => {+const setup = ({+ hasEnterprisePlugins = false,+ initialValues = USER,+ external = false,+ tenants = [] as Tenant[],+} = {}) => {const onSubmit = jest.fn();const onCancel = jest.fn();fetchMock.get("path:/api/permissions/group", GROUPS);+ setupTenantEntpoints(tenants);+const state = createMockState({settings: mockSettings({"token-features": createMockTokenFeatures({sandboxes: true,+ tenants: true,}),}),});@@ -54,6 +65,7 @@ const setup = ({ hasEnterprisePlugins = false, initialValues = USER } = {}) => {onSubmit={onSubmit}onCancel={onCancel}initialValues={initialValues}+ external={external}/>,{storeInitialState: state,@@ -291,4 +303,72 @@ describe("UserForm", () => {);});});++ describe("Tenant users", () => {+ const TENANTS = [+ createMockTenant({ id: 1, name: "Acme Corp" }),+ createMockTenant({ id: 2, name: "TechStart Inc" }),+ ];++ it("should require tenant_id for tenant users", async () => {+ setup({+ hasEnterprisePlugins: true,+ external: true,+ tenants: TENANTS,+ initialValues: {+ ...USER,+ tenant_id: null,+ },+ });++ // Wait for form to render+ await screen.findByLabelText(/Email/);++ // The submit button should be disabled initially because tenant_id is required but not set+ expect(screen.getByRole("button", { name: "Update" })).toBeDisabled();+ });++ it("should allow you to submit when tenant_id is selected", async () => {+ const { onSubmit } = setup({+ hasEnterprisePlugins: true,+ external: true,+ tenants: TENANTS,+ initialValues: {+ ...USER,+ tenant_id: null,+ },+ });++ // Wait for form to render+ await screen.findByLabelText(/Email/);++ // Initially disabled because tenant_id is required but not set+ expect(screen.getByRole("button", { name: "Update" })).toBeDisabled();++ // Select a tenant+ await userEvent.click(+ await screen.findByRole("textbox", { name: "Tenant" }),+ );+ await userEvent.click(await screen.findByText("Acme Corp"));++ // Now the button should be enabled because form is dirty and valid+ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Update" })).toBeEnabled();+ });++ // Submit the form+ await userEvent.click(screen.getByRole("button", { name: "Update" }));++ // Verify form was submitted with the selected tenant_id+ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ ...USER,+ tenant_id: 1,+ }),+ expect.anything(),+ );+ });+ });+ });});diff --git a/frontend/src/metabase/admin/people/hooks/use-people-query.ts b/frontend/src/metabase/admin/people/hooks/use-people-query.tsindex a8f4e1b6445..f12c813ed7b 100644--- a/frontend/src/metabase/admin/people/hooks/use-people-query.ts+++ b/frontend/src/metabase/admin/people/hooks/use-people-query.ts@@ -2,8 +2,9 @@ import { useCallback, useEffect, useMemo, useState } from "react";import { usePagination } from "metabase/common/hooks/use-pagination";import { SEARCH_DEBOUNCE_DURATION } from "metabase/lib/constants";+import type { UserTenancy } from "metabase-types/api";-import { USER_STATUS, type UserStatus } from "../constants";+import { ACTIVE_STATUS, type ActiveStatus } from "../constants";const MIN_SEARCH_LENGTH = 2;@@ -11,10 +12,10 @@ const MIN_SEARCH_LENGTH = 2;// it is not the best place to store pagination state since we might want to// change it from the ancestors, for instance, when we change list filter props.// If users change any filters, we should reset the page state.-export const usePeopleQuery = (pageSize: number) => {+export const usePeopleQuery = (pageSize: number, tenancy: UserTenancy) => {const { handleNextPage, handlePreviousPage, setPage, page } = usePagination();- const [status, setStatus] = useState<UserStatus>(USER_STATUS.active);+ const [status, setStatus] = useState<ActiveStatus>(ACTIVE_STATUS.active);const [searchInputValue, setSearchInputValue] = useState("");const [searchText, setSearchText] = useState("");@@ -32,7 +33,7 @@ export const usePeopleQuery = (pageSize: number) => {}, [searchInputValue, setPage]);const updateStatus = useCallback(- (status: UserStatus) => {+ (status: ActiveStatus) => {setPage(0);setStatus(status);},@@ -45,8 +46,9 @@ export const usePeopleQuery = (pageSize: number) => {searchText,page,pageSize,+ tenancy,}),- [status, searchText, page, pageSize],+ [status, searchText, page, pageSize, tenancy],);return {diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsxindex 26053903c62..03a62705565 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx+++ b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsPageLayout.tsx@@ -40,7 +40,11 @@ import { ToolbarButton } from "../ToolbarButton";import { PermissionsEditBar } from "./PermissionsEditBar";import { PermissionsTabs } from "./PermissionsTabs";-type PermissionsPageTab = "data" | "collections" | "application";+type PermissionsPageTab =+ | "data"+ | "collections"+ | "application"+ | "tenant-collections";type PermissionsPageLayoutProps = {children: ReactNode;tab: PermissionsPageTab;@@ -88,6 +92,7 @@ export function PermissionsPageLayout({const navigateToTab = (tab: PermissionsPageTab) =>dispatch(push(`/admin/permissions/${tab}`));+const clearSaveError = () => {dispatch(clearPermissionsSaveError());};@@ -115,6 +120,8 @@ export function PermissionsPageLayout({/>)}+ <LeaveRouteConfirmModal isEnabled={Boolean(isDirty)} route={route} />+<ConfirmModalopened={saveError != null}onClose={clearSaveError}@@ -126,8 +133,6 @@ export function PermissionsPageLayout({closeButtonText={null}/>- <LeaveRouteConfirmModal isEnabled={!!isDirty} route={route} />-<TabsContainer className={CS.borderBottom}><PermissionsTabs tab={tab} onChangeTab={navigateToTab} /><ToolbarButtonsContainer>diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsxindex c6ef41bf089..aba20f14d6a 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx+++ b/frontend/src/metabase/admin/permissions/components/PermissionsPageLayout/PermissionsTabs.jsx@@ -3,28 +3,43 @@ import PropTypes from "prop-types";import { t } from "ttag";import Radio from "metabase/common/components/Radio";+import { useSetting } from "metabase/common/hooks";import CS from "metabase/css/core/index.css";-import { PLUGIN_APPLICATION_PERMISSIONS } from "metabase/plugins";+import {+ PLUGIN_ADMIN_PERMISSIONS_TABS,+ PLUGIN_APPLICATION_PERMISSIONS,+} from "metabase/plugins";const propTypes = {tab: PropTypes.oneOf(["data", "collections"]).isRequired,onChangeTab: PropTypes.func.isRequired,};-export const PermissionsTabs = ({ tab, onChangeTab }) => (- <div className={cx(CS.px3, CS.mt1)}>- <Radio- colorScheme="accent7"- value={tab}- options={[- { name: t`Data`, value: `data` },- { name: t`Collections`, value: `collections` },- ...PLUGIN_APPLICATION_PERMISSIONS.tabs,- ]}- onOptionClick={onChangeTab}- variant="underlined"- />- </div>-);+export const PermissionsTabs = ({ tab, onChangeTab }) => {+ const isUsingTenants = useSetting("use-tenants");++ const adminPermissionsTabs = isUsingTenants+ ? PLUGIN_ADMIN_PERMISSIONS_TABS.tabs+ : PLUGIN_ADMIN_PERMISSIONS_TABS.tabs.filter(+ (tab) => tab.value !== "tenant-collections",+ );++ return (+ <div className={cx(CS.px3, CS.mt1)}>+ <Radio+ colorScheme="accent7"+ value={tab}+ options={[+ { name: t`Data`, value: `data` },+ { name: t`Collections`, value: `collections` },+ ...adminPermissionsTabs,+ ...PLUGIN_APPLICATION_PERMISSIONS.tabs,+ ]}+ onOptionClick={onChangeTab}+ variant="underlined"+ />+ </div>+ );+};PermissionsTabs.propTypes = propTypes;diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsxindex 3597fa7b583..11e1c7547f8 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx+++ b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.jsx@@ -1,10 +1,9 @@import PropTypes from "prop-types";import { Fragment, memo, useState } from "react";-import PopoverWithTrigger from "metabase/common/components/PopoverWithTrigger";import Toggle from "metabase/common/components/Toggle";import { lighten } from "metabase/lib/colors";-import { Icon, Tooltip } from "metabase/ui";+import { Icon, Popover, Tooltip } from "metabase/ui";import {ActionsList,@@ -50,6 +49,7 @@ export const PermissionsSelect = memo(function PermissionsSelect({isHighlighted,}) {const [toggleState, setToggleState] = useState(null);+ const [opened, setOpened] = useState(false);const selectedOption = options.find((option) => option.value === value);const selectableOptions = hasChildren? options@@ -59,49 +59,45 @@ export const PermissionsSelect = memo(function PermissionsSelect({onChange(selectedOption.value, checked);};- const selectedOptionValue = (- <PermissionsSelectRoot- isDisabled={isDisabled}- aria-haspopup="listbox"- data-testid="permissions-select"- >- {isDisabled ? (- <DisabledPermissionOption- {...selectedOption}- isHighlighted={isHighlighted}- hint={disabledTooltip}- iconColor="text-light"- />- ) : (- <SelectedOption {...selectedOption} />- )}-- {warning && (- <Tooltip label={warning}>- <WarningIcon />- </Tooltip>- )}-- <Icon- style={{ visibility: isDisabled ? "hidden" : "visible" }}- name="chevrondown"- size={16}- color={lighten("text-light", 0.15)}- />- </PermissionsSelectRoot>- );-const actionsForCurrentValue = actions?.[selectedOption?.value] || [];const hasActions = actionsForCurrentValue.length > 0;return (- <PopoverWithTrigger- disabled={isDisabled}- targetOffsetX={16}- targetOffsetY={8}- triggerElement={selectedOptionValue}- >- {({ onClose }) => (+ <Popover opened={opened} onChange={setOpened} disabled={isDisabled}>+ <Popover.Target>+ <PermissionsSelectRoot+ isDisabled={isDisabled}+ aria-haspopup="listbox"+ data-testid="permissions-select"+ aria-disabled={isDisabled}+ onClick={isDisabled ? undefined : () => setOpened((o) => !o)}+ >+ {isDisabled ? (+ <DisabledPermissionOption+ {...selectedOption}+ isHighlighted={isHighlighted}+ hint={disabledTooltip}+ iconColor="text-light"+ />+ ) : (+ <SelectedOption {...selectedOption} />+ )}++ {warning && (+ <Tooltip label={warning}>+ <WarningIcon />+ </Tooltip>+ )}++ <Icon+ style={{ visibility: isDisabled ? "hidden" : "visible" }}+ name="chevrondown"+ size={16}+ color={lighten("text-light", 0.15)}+ />+ </PermissionsSelectRoot>+ </Popover.Target>+ <Popover.Dropdown><Fragment><OptionsList role="listbox">{selectableOptions.map((option) => (@@ -109,7 +105,7 @@ export const PermissionsSelect = memo(function PermissionsSelect({role="option"key={option.value}onClick={() => {- onClose();+ setOpened(false);onChange(option.value, toggleLabel ? toggleState : null);}}>@@ -124,7 +120,7 @@ export const PermissionsSelect = memo(function PermissionsSelect({key={index}role="option"onClick={() => {- onClose();+ setOpened(false);onAction(action);}}>@@ -145,8 +141,8 @@ export const PermissionsSelect = memo(function PermissionsSelect({</ToggleContainer>)}</Fragment>- )}- </PopoverWithTrigger>+ </Popover.Dropdown>+ </Popover>);});diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.unit.spec.js b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.unit.spec.jsindex 08e7417054a..f4c427a390c 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.unit.spec.js+++ b/frontend/src/metabase/admin/permissions/components/PermissionsSelect/PermissionsSelect.unit.spec.js@@ -1,6 +1,6 @@import userEvent from "@testing-library/user-event";-import { fireEvent, getIcon, render, screen } from "__support__/ui";+import { getIcon, render, screen } from "__support__/ui";import { DataPermissionValue } from "../../types";@@ -33,12 +33,12 @@ describe("PermissionSelect", () => {expect(screen.getByText("Allowed")).toBeInTheDocument();});- it("when clicked shows options except selected", () => {+ it("when clicked shows options except selected", async () => {render(<PermissionsSelect options={options} value="all" />);- fireEvent.click(screen.getByText("Allowed"));+ await userEvent.click(screen.getByText("Allowed"));- const optionsList = screen.getByRole("listbox");+ const optionsList = await screen.findByRole("listbox");expect(optionsList).toBeInTheDocument();const [limited, noAccess, ...rest] = screen.getAllByRole("option");@@ -48,7 +48,7 @@ describe("PermissionSelect", () => {expect(noAccess).toHaveTextContent("No access");});- it("selects an option", () => {+ it("selects an option", async () => {const onChangeMock = jest.fn();render(<PermissionsSelect@@ -58,14 +58,13 @@ describe("PermissionSelect", () => {/>,);- const selected = screen.queryByText("Allowed");- fireEvent.click(selected);+ await userEvent.click(screen.getByText("Allowed"));- const optionsList = screen.getByRole("listbox");+ const optionsList = await screen.findByRole("listbox");expect(optionsList).toBeInTheDocument();const [limited] = screen.getAllByRole("option");- fireEvent.click(limited);+ await userEvent.click(limited);expect(onChangeMock).toHaveBeenCalledWith(DataPermissionValue.CONTROLLED,@@ -73,18 +72,15 @@ describe("PermissionSelect", () => {);});- it("does not show options after click when disabled", () => {+ it("does not show options after click when disabled", async () => {render(<PermissionsSelect options={options} value="all" isDisabled={true} />,);- const selected = screen.queryByText("Allowed");- fireEvent.click(selected);+ await userEvent.click(screen.getByText("Allowed"));const optionsList = screen.queryByRole("listbox");expect(optionsList).not.toBeInTheDocument();-- fireEvent.mouseEnter(selected);});it("shows warning", async () => {@@ -93,7 +89,7 @@ describe("PermissionSelect", () => {<PermissionsSelect options={options} value="all" warning={WARNING} />,);- userEvent.hover(getIcon("warning"));+ await userEvent.hover(getIcon("warning"));expect(await screen.findByText(WARNING)).toBeInTheDocument();});diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.jsx b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.jsxindex 4fc34c1c152..ec172b0948c 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.jsx+++ b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.jsx@@ -5,13 +5,12 @@ import { useRef, useState } from "react";import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { Ellipsified } from "metabase/common/components/Ellipsified";import CS from "metabase/css/core/index.css";-import { Text, Tooltip } from "metabase/ui";+import { Flex, Text, Tooltip } from "metabase/ui";import { PermissionsSelect } from "../PermissionsSelect";import {ColumnName,- EntityName,EntityNameLink,HintIcon,PermissionTableHeaderCell,@@ -111,14 +110,20 @@ export function PermissionsTable({</span>);return (- <PermissionsTableRow key={entity.id}>+ <PermissionsTableRow+ key={entity.id}+ aria-label={`${entity.name} permissions`}+ ><PermissionsTableCell>{entity.canSelect ? (<EntityNameLink onClick={() => onSelect(entity)}>{entityName}</EntityNameLink>) : (- <EntityName>{entityName}</EntityName>+ <Flex gap="xs" fw="bold">+ {entityName}+ {entity.icon}+ </Flex>)}{entity.callout && (<Text c="text-secondary">{entity.callout}</Text>diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.styled.tsx b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.styled.tsxindex 7087e4467f9..8ddf9ee2fb6 100644--- a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.styled.tsx+++ b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.styled.tsx@@ -80,10 +80,6 @@ export const PermissionsTableRow = styled.tr`border-bottom: ${({ theme }) => getTableBorder(theme)};`;-export const EntityName = styled.span`- font-weight: 700;-`;-export const EntityNameLink = styled(Link)`display: inline;font-weight: 700;diff --git a/frontend/src/metabase/admin/permissions/constants/messages.ts b/frontend/src/metabase/admin/permissions/constants/messages.tsindex 2adc682b950..e98bdc23d77 100644--- a/frontend/src/metabase/admin/permissions/constants/messages.ts+++ b/frontend/src/metabase/admin/permissions/constants/messages.ts@@ -1,11 +1,32 @@import { t } from "ttag";-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045-export const UNABLE_TO_CHANGE_ADMIN_PERMISSIONS = t`Administrators always have the highest level of access to everything in Metabase.`;-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045-export const NATIVE_PERMISSION_REQUIRES_DATA_ACCESS = t`Groups with View data access set to "Blocked" can't create queries.`;-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045-export const UNABLE_TO_CHANGE_LEGACY_PERMISSIONS = t`Change "No self-service (Deprecated)" View data access to enable custom Create queries permissions.`;+export const Messages = {+ get UNABLE_TO_CHANGE_ADMIN_PERMISSIONS() {+ return t`Administrators always have the highest level of access to everything in Metabase.`;+ },+ get NATIVE_PERMISSION_REQUIRES_DATA_ACCESS() {+ return t`Groups with View data access set to "Blocked" can't create queries.`;+ },+ get UNABLE_TO_CHANGE_LEGACY_PERMISSIONS() {+ return t`Change "No self-service (Deprecated)" View data access to enable custom Create queries permissions.`;+ },+ get EXTERNAL_USERS_NO_ACCESS_COLLECTION() {+ return t`Tenant users can only access tenant collections`;+ },+ get EXTERNAL_USERS_NO_ACCESS_DATABASE() {+ return t`Tenant users cannot manage database permissions`;+ },++ get EXTERNAL_USERS_NO_ACCESS_SETTINGS() {+ return t`Tenant users cannot have settings permissions`;+ },+ get EXTERNAL_USERS_NO_ACCESS_MONITORING() {+ return t`Tenant users cannot have monitoring permissions`;+ },+ get UNABLE_TO_DOWNLOAD_RESULTS() {+ return t`Groups with Block data access can't download results`;+ },+};export const getLimitedPermissionAvailabilityMessage = () =>t`Only available in certain Metabase plans.`;diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/common.unit.spec.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/common.unit.spec.tsxindex 4d3c31e2c11..a0dfc296c45 100644--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/common.unit.spec.tsx@@ -14,15 +14,24 @@ describe("Admin > CollectionPermissionsPage", () => {await screen.findByText("Select a collection to see its permissions"),).toBeVisible();expect(await screen.findByText("Our analytics")).toBeVisible();- expect(await screen.findByText("Collection One")).toBeVisible();- expect(await screen.findByText("Collection Two")).toBeVisible();+ const collectionItems = await screen.findAllByRole("menuitem", {+ name: /Collection One/,+ });+ expect(collectionItems[0]).toBeVisible();++ const collectionTwoItems = await screen.findAllByRole("menuitem", {+ name: /Collection Two/,+ });+ expect(collectionTwoItems[0]).toBeVisible();});it("should allow expansion of nested collections", async () => {await setup();- const collection1 = await screen.findByText("Collection One");- expect(screen.queryByText("Nested One")).not.toBeInTheDocument();+ const collection1 = (+ await screen.findAllByRole("menuitem", { name: /Collection One/ })+ )[0];+ expect(screen.queryAllByText("Nested One")).toHaveLength(0);await userEvent.click(collection1);expect(await screen.findByText("Nested One")).toBeInTheDocument();});@@ -30,8 +39,12 @@ describe("Admin > CollectionPermissionsPage", () => {it("should not show personal collection", async () => {await setup();- expect(await screen.findByText("Collection One")).toBeInTheDocument();- expect(screen.queryByText("Personal")).not.toBeInTheDocument();+ expect(+ await screen.findByRole("menuitem", { name: /Collection One/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("menuitem", { name: /Personal/ }),+ ).not.toBeInTheDocument();});it("should show a permissions table for the selected collection", async () => {@@ -41,14 +54,18 @@ describe("Admin > CollectionPermissionsPage", () => {await screen.findByText("Select a collection to see its permissions"),).toBeVisible();- await userEvent.click(await screen.findByText("Collection One"));- await userEvent.click(await screen.findByText("Nested One"));+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Collection One/ }))[0],+ );+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Nested One/ }))[0],+ );expect(await screen.findByText("Permissions for Nested One"),).toBeVisible();expect(await screen.findByText("Administrators")).toBeVisible();- expect(await screen.findByText("All Users")).toBeVisible();+ expect(await screen.findByText("All Internal Users")).toBeVisible();expect(await screen.findByText("Other Users")).toBeVisible();// 1 groups has write, 1 has read, 1 has none@@ -64,8 +81,12 @@ describe("Admin > CollectionPermissionsPage", () => {await screen.findByText("Select a collection to see its permissions"),).toBeVisible();- await userEvent.click(await screen.findByText("Collection One"));- await userEvent.click(await screen.findByText("Nested One"));+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Collection One/ }))[0],+ );+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Nested One/ }))[0],+ );// change Other users from no access to viewawait userEvent.click(await screen.findByText("No access"));@@ -116,7 +137,9 @@ describe("Admin > CollectionPermissionsPage", () => {await screen.findByText("Select a collection to see its permissions"),).toBeVisible();- await userEvent.click(await screen.findByText("Collection One"));+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Collection One/ }))[0],+ );// change other users from read to curate on collection one// should also change permissions on nested one from no access to curate@@ -127,7 +150,7 @@ describe("Admin > CollectionPermissionsPage", () => {expect(within(otherUsersRow).getByText("Other Users")).toBeVisible();await userEvent.click(within(otherUsersRow).getByText("View"));- const popover = await screen.findByTestId("popover");+ const popover = await screen.findByRole("dialog");await userEvent.click(within(popover).getByRole("switch")); // propagate switchawait userEvent.click(within(popover).getByText("Curate"));@@ -171,7 +194,9 @@ describe("Admin > CollectionPermissionsPage", () => {it("should show toggle to change sub-collection permissions if the collection has sub-collections", async () => {await setup();- await userEvent.click(await screen.findByText("Collection One"));+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Collection One/ }))[0],+ );await userEvent.click(await screen.findByText("View"));expect(@@ -182,8 +207,12 @@ describe("Admin > CollectionPermissionsPage", () => {it("should not show toggle to change sub-collection permissions if the collection does not have sub-collections", async () => {await setup();- await userEvent.click(await screen.findByText("Collection One"));- await userEvent.click(await screen.findByText("Nested One"));+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Collection One/ }))[0],+ );+ await userEvent.click(+ (await screen.findAllByRole("menuitem", { name: /Nested One/ }))[0],+ );await userEvent.click(await screen.findByText("View"));expect(@@ -191,4 +220,12 @@ describe("Admin > CollectionPermissionsPage", () => {).not.toBeInTheDocument();});});++ it("hides the tenant collections tab when tenants feature is not available", async () => {+ setup();++ expect(+ screen.queryByRole("radio", { name: "Tenant Collections" }),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/enterprise.unit.spec.tsxindex 4badd8c47e2..29bb5865358 100644--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/enterprise.unit.spec.tsx@@ -1,13 +1,71 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import { screen } from "__support__/ui";+import { screen, within } from "__support__/ui";import type { CollectionPermissionsGraph } from "metabase-types/api";import { createMockCollection } from "metabase-types/api/mocks";-import { defaultCollections, defaultPermissionsGraph, setup } from "./setup";+import {+ defaultCollections,+ defaultPermissionGroupsWithTenants,+ defaultPermissionsGraph,+ defaultPermissionsGraphWithTenants,+ setup,+} from "./setup";++const tokenFeatures = { tenants: true, audit_app: true };describe("Admin > CollectionPermissionsPage (enterprise)", () => {+ describe("Tenant Collections Tab", () => {+ it("shows the tab when tenants are enabled", async () => {+ setup({ tokenFeatures, settings: { "use-tenants": true } });++ expect(+ await screen.findByRole("radio", { name: "Tenant Collections" }),+ ).toBeInTheDocument();+ });++ it("hides the tab when tenants are disabled", async () => {+ setup({ tokenFeatures, settings: { "use-tenants": false } });++ expect(+ screen.queryByRole("radio", { name: "Tenant Collections" }),+ ).not.toBeInTheDocument();+ });+ });++ describe("Tenant users Group", () => {+ it("should not be able get access to Our Analytics", async () => {+ await setup({+ tokenFeatures,+ initialRoute: "/admin/permissions/collections/root",+ permissionGroups: defaultPermissionGroupsWithTenants,+ permissionsGraph: defaultPermissionsGraphWithTenants,+ });++ await assertCollectionAccessForGroup("Administrators", "Curate");+ await assertCollectionAccessForGroup("All Internal Users", "View");+ await assertCollectionAccessForGroup("Other Users", "View");+ await assertCollectionAccessForGroup("All tenant users", "No access");+ await assertCollectionAccessIsDisabled("All tenant users");+ });++ it("should not be able get access to normal collections", async () => {+ await setup({+ tokenFeatures,+ initialRoute: "/admin/permissions/collections/2",+ permissionGroups: defaultPermissionGroupsWithTenants,+ permissionsGraph: defaultPermissionsGraphWithTenants,+ });++ await assertCollectionAccessForGroup("Administrators", "Curate");+ await assertCollectionAccessForGroup("All Internal Users", "Curate");+ await assertCollectionAccessForGroup("Other Users", "View");+ await assertCollectionAccessForGroup("All Tenant users", "No access");+ await assertCollectionAccessIsDisabled("All Tenant users");+ });+ });+describe("Instance Analytics", () => {const iaCollection = createMockCollection({id: 13371337,@@ -37,18 +95,17 @@ describe("Admin > CollectionPermissionsPage (enterprise)", () => {collections: [...defaultCollections, iaCollection],permissionsGraph: iaPermissionsGraph,initialRoute: `/admin/permissions/collections/${iaCollection.id}`,- tokenFeatures: { audit_app: true },+ tokenFeatures,});- expect(await screen.findByText("Instance Analytics")).toBeInTheDocument();- expect(await screen.findAllByText("View")).toHaveLength(3);+ await assertCollectionAccessForGroup("Administrators", "View");+ await assertCollectionAccessForGroup("All Internal Users", "View");+ await assertCollectionAccessForGroup("Other Users", "View");- await userEvent.click(- await screen.findAllByText("View").then((dropdowns) => dropdowns[2]),- );+ await userEvent.click(await getCollectionPermissionCell("Other Users"));- expect(await screen.findByText("No access")).toBeInTheDocument();- expect(screen.queryByText("Curate")).not.toBeInTheDocument();+ expect(await screen.findByRole("dialog")).toHaveTextContent("No access");+ expect(await screen.findByRole("dialog")).not.toHaveTextContent("Curate");});it("should display tooltip explaining why instance analytics collection cannot be curated by admins", async () => {@@ -56,14 +113,18 @@ describe("Admin > CollectionPermissionsPage (enterprise)", () => {collections: [...defaultCollections, iaCollection],permissionsGraph: iaPermissionsGraph,initialRoute: `/admin/permissions/collections/${iaCollection.id}`,- tokenFeatures: { audit_app: true },+ tokenFeatures,});- expect(await screen.findByText("Instance Analytics")).toBeInTheDocument();- expect(await screen.findAllByText("View")).toHaveLength(3);+ await assertCollectionAccessForGroup("Administrators", "View");+ await assertCollectionAccessForGroup("All Internal Users", "View");+ await assertCollectionAccessForGroup("Other Users", "View");+ await assertCollectionAccessIsDisabled("Administrators");await userEvent.hover(- await screen.findAllByText("View").then((dropdowns) => dropdowns[1]),+ within(await getCollectionPermissionCell("Administrators")).getByText(+ "View",+ ),);expect(@@ -76,7 +137,7 @@ describe("Admin > CollectionPermissionsPage (enterprise)", () => {collections: [...defaultCollections, iaCollection],permissionsGraph: iaPermissionsGraph,initialRoute: `/admin/permissions/collections/${iaCollection.id}`,- tokenFeatures: { audit_app: true },+ tokenFeatures,});// change all users users view to no access@@ -119,3 +180,25 @@ describe("Admin > CollectionPermissionsPage (enterprise)", () => {});});});++const assertCollectionAccessForGroup = async (+ group: string,+ access: string,+) => {+ expect(await getCollectionPermissionCell(group)).toHaveTextContent(access);+};++const assertCollectionAccessIsDisabled = async (+ group: string,+ disabled: boolean = true,+) => {+ expect(await getCollectionPermissionCell(group)).toHaveAttribute(+ "aria-disabled",+ disabled.toString(),+ );+};++const getCollectionPermissionCell = async (group: string) =>+ within(+ await screen.findByRole("row", { name: new RegExp(group, "i") }),+ ).getByTestId("permissions-select");diff --git a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsxindex 2297c02cd4c..c417a20c0d5 100644--- a/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx+++ b/frontend/src/metabase/admin/permissions/pages/CollectionPermissionsPage/tests/setup.tsx@@ -12,11 +12,13 @@ import { renderWithProviders } from "__support__/ui";import type {Collection,CollectionPermissionsGraph,- Group,+ GroupInfo,+ Settings,TokenFeatures,} from "metabase-types/api";import {createMockCollection,+ createMockGroup,createMockTokenFeatures,} from "metabase-types/api/mocks";import { createMockState } from "metabase-types/store/mocks";@@ -67,10 +69,26 @@ export const defaultRootCollection = createMockCollection({children: [collectionOne, collectionTwo],});-const defaultPermissionGroups: Omit<Group, "members">[] = [- { id: 1, name: "All Users", member_count: 40 },- { id: 2, name: "Administrators", member_count: 2 },- { id: 3, name: "Other Users", member_count: 33 },+export const defaultPermissionGroups: GroupInfo[] = [+ {+ id: 1,+ name: "All Internal Users",+ member_count: 40,+ magic_group_type: "all-internal-users",+ },+ { id: 2, name: "Administrators", member_count: 2, magic_group_type: "admin" },+ { id: 3, name: "Other Users", member_count: 33, magic_group_type: null },+];++const externalUsersGroup = createMockGroup({+ id: 4,+ name: "All tenant users",+ magic_group_type: "all-external-users",+});++export const defaultPermissionGroupsWithTenants = [+ ...defaultPermissionGroups,+ externalUsersGroup,];export const defaultPermissionsGraph: CollectionPermissionsGraph = {@@ -103,27 +121,45 @@ export const defaultPermissionsGraph: CollectionPermissionsGraph = {},};+export const defaultPermissionsGraphWithTenants: CollectionPermissionsGraph = {+ ...defaultPermissionsGraph,+ groups: {+ ...defaultPermissionsGraph.groups,+ 4: {+ // Tenant users+ 1: "none", // one+ 2: "none", // two+ 3: "none", // nested one+ 4: "none", // nested two+ root: "none",+ },+ },+};+interface SetupOptions {initialRoute?: string;collections?: Collection[];rootCollection?: Collection;permissionsGraph?: CollectionPermissionsGraph;- permissionGroups?: Omit<Group, "members">[];+ permissionGroups?: GroupInfo[];tokenFeatures?: Partial<TokenFeatures>;+ settings?: Partial<Settings>;}export function setup({- initialRoute = "/admin/permissions/collections/root",+ initialRoute = "/admin/permissions/collections",collections = defaultCollections,rootCollection = defaultRootCollection,permissionsGraph = defaultPermissionsGraph,permissionGroups = defaultPermissionGroups,tokenFeatures,+ settings = {},}: Partial<SetupOptions> = {}) {const initialState = createMockState({settings: mockSettings({"application-colors": {},"token-features": createMockTokenFeatures(tokenFeatures ?? {}),+ ...settings,}),});@@ -144,7 +180,7 @@ export function setup({renderWithProviders(<><Route- path="/admin/permissions/collections/root"+ path="/admin/permissions/collections"component={CollectionPermissionsPage}/><Routediff --git a/frontend/src/metabase/admin/permissions/permissions.js b/frontend/src/metabase/admin/permissions/permissions.jsindex 5653a5c1d97..b7d3e61880b 100644--- a/frontend/src/metabase/admin/permissions/permissions.js+++ b/frontend/src/metabase/admin/permissions/permissions.js@@ -250,6 +250,65 @@ export const saveCollectionPermissions = createThunkAction(},);+// Tenant Collection Permissions+const TENANT_NAMESPACE = "shared-tenant-collection";++const INITIALIZE_TENANT_COLLECTION_PERMISSIONS =+ "metabase/admin/permissions/INITIALIZE_TENANT_COLLECTION_PERMISSIONS";+export const initializeTenantCollectionPermissions = createThunkAction(+ INITIALIZE_TENANT_COLLECTION_PERMISSIONS,+ () => async (dispatch) => {+ await Promise.all([+ dispatch(loadTenantCollectionPermissions()),+ dispatch(Group.actions.fetchList()),+ ]);+ },+);++const LOAD_TENANT_COLLECTION_PERMISSIONS =+ "metabase/admin/permissions/LOAD_TENANT_COLLECTION_PERMISSIONS";+export const loadTenantCollectionPermissions = createThunkAction(+ LOAD_TENANT_COLLECTION_PERMISSIONS,+ () => async () => {+ return CollectionsApi.graph({ namespace: TENANT_NAMESPACE });+ },+);++const UPDATE_TENANT_COLLECTION_PERMISSION =+ "metabase/admin/permissions/UPDATE_TENANT_COLLECTION_PERMISSION";+export const updateTenantCollectionPermission = createAction(+ UPDATE_TENANT_COLLECTION_PERMISSION,+);++const SAVE_TENANT_COLLECTION_PERMISSIONS =+ "metabase/admin/permissions/data/SAVE_TENANT_COLLECTION_PERMISSIONS";+export const saveTenantCollectionPermissions = createThunkAction(+ SAVE_TENANT_COLLECTION_PERMISSIONS,+ () => async (_dispatch, getState) => {+ const {+ originalTenantCollectionPermissions,+ tenantCollectionPermissions,+ tenantCollectionPermissionsRevision,+ } = getState().admin.permissions;++ const modifiedPermissions = getModifiedCollectionPermissionsGraphParts(+ originalTenantCollectionPermissions,+ tenantCollectionPermissions,+ );++ const result = await CollectionsApi.updateGraph({+ namespace: TENANT_NAMESPACE,+ revision: tenantCollectionPermissionsRevision,+ groups: modifiedPermissions,+ });++ return {+ ...result,+ groups: tenantCollectionPermissions,+ };+ },+);+const CLEAR_SAVE_ERROR = "metabase/admin/permissions/CLEAR_SAVE_ERROR";export const clearSaveError = createAction(CLEAR_SAVE_ERROR);@@ -274,6 +333,10 @@ const saveError = handleActions([LOAD_COLLECTION_PERMISSIONS]: {next: (state) => null,},+ [SAVE_TENANT_COLLECTION_PERMISSIONS]: savePermission,+ [LOAD_TENANT_COLLECTION_PERMISSIONS]: {+ next: (state) => null,+ },[CLEAR_SAVE_ERROR]: { next: () => null },},null,@@ -501,6 +564,60 @@ const collectionPermissionsRevision = handleActions(null,);+// Tenant Collection Permissions Reducers+const tenantCollectionPermissions = handleActions(+ {+ [LOAD_TENANT_COLLECTION_PERMISSIONS]: {+ next: (_state, { payload }) => payload.groups,+ },+ [UPDATE_TENANT_COLLECTION_PERMISSION]: {+ next: (state, { payload }) => {+ const { groupId, collection, value, shouldPropagate } = payload;+ let newPermissions = assocIn(state, [groupId, collection.id], value);++ if (shouldPropagate) {+ for (const descendent of getDecendentCollections(collection)) {+ newPermissions = assocIn(+ newPermissions,+ [groupId, descendent.id],+ value,+ );+ }+ }+ return newPermissions;+ },+ },+ [SAVE_TENANT_COLLECTION_PERMISSIONS]: {+ next: (_state, { payload }) => payload.groups,+ },+ },+ null,+);++const originalTenantCollectionPermissions = handleActions(+ {+ [LOAD_TENANT_COLLECTION_PERMISSIONS]: {+ next: (_state, { payload }) => payload.groups,+ },+ [SAVE_TENANT_COLLECTION_PERMISSIONS]: {+ next: (state, { payload }) => payload.groups,+ },+ },+ null,+);++const tenantCollectionPermissionsRevision = handleActions(+ {+ [LOAD_TENANT_COLLECTION_PERMISSIONS]: {+ next: (_state, { payload }) => payload.revision,+ },+ [SAVE_TENANT_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);@@ -562,6 +679,9 @@ export default combineReducers({collectionPermissions,originalCollectionPermissions,collectionPermissionsRevision,+ tenantCollectionPermissions,+ originalTenantCollectionPermissions,+ tenantCollectionPermissionsRevision,isHelpReferenceOpen,hasRevisionChanged,});diff --git a/frontend/src/metabase/admin/permissions/routes.jsx b/frontend/src/metabase/admin/permissions/routes.jsxindex b5bfa19b084..90ae3b66ee3 100644--- a/frontend/src/metabase/admin/permissions/routes.jsx+++ b/frontend/src/metabase/admin/permissions/routes.jsx@@ -5,6 +5,7 @@ import {PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES,PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES,PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES,+ PLUGIN_ADMIN_PERMISSIONS_TABS,PLUGIN_APPLICATION_PERMISSIONS,} from "metabase/plugins";@@ -41,6 +42,7 @@ const getRoutes = () => (<Route path=":collectionId" /></Route>+ {PLUGIN_ADMIN_PERMISSIONS_TABS.getRoutes()}{PLUGIN_APPLICATION_PERMISSIONS.getRoutes()}</Route>);diff --git a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.ts b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsxsimilarity index 74%rename from frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsrename to frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsxindex f29b701b64a..12b0e993292 100644--- a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.ts+++ b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx@@ -19,10 +19,11 @@ import {isAdminGroup,isDefaultGroup,} from "metabase/lib/groups";-import { PLUGIN_COLLECTIONS } from "metabase/plugins";+import { PLUGIN_COLLECTIONS, PLUGIN_TENANTS } from "metabase/plugins";import type {Collection,CollectionId,+ CollectionNamespace,CollectionPermissions,Group as GroupType,} from "metabase-types/api";@@ -33,7 +34,7 @@ import type {} from "metabase-types/store";import { COLLECTION_OPTIONS } from "../constants/collections-permissions";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "../constants/messages";+import { Messages } from "../constants/messages";import type { DataPermissionValue } from "../types";import { getPermissionWarningModal } from "./confirmations";@@ -56,7 +57,7 @@ export const getIsDirty = createSelector(export type CollectionIdProps = {params: { collectionId: CollectionId };- namespace?: string;+ namespace?: CollectionNamespace;};export const getCurrentCollectionId = (@@ -122,7 +123,7 @@ export function buildCollectionTree(export type CollectionSidebarType = {selectedId?: CollectionId;title: string;- entityGroups: [CollectionTreeItem[]];+ entityGroups: CollectionTreeItem[][];filterPlaceholder: string;};@@ -204,7 +205,7 @@ const getCollectionPermission = (const getNamespace = (_state: State, props: CollectionIdProps) =>props.namespace;-const getToggleLabel = (namespace?: string) =>+const getToggleLabel = (namespace?: CollectionNamespace) =>namespace === "snippets"? t`Also change sub-folders`: t`Also change sub-collections`;@@ -246,62 +247,84 @@ export const getCollectionsPermissionEditor = createSelector(const hasChildren = collection.children?.length > 0;const toggleLabel = hasChildren ? getToggleLabel(namespace) : null;- const defaultGroup = _.find(groups, isDefaultGroup);-- const entities = groups.map((group: GroupType) => {- const isAdmin = isAdminGroup(group);-- const defaultGroupPermission = getCollectionPermission(- permissions,- defaultGroup.id,- collection.id,- );-- const confirmations = (newValue: DataPermissionValue) => [- getPermissionWarningModal(- newValue,- defaultGroupPermission,- null,- defaultGroup,- group.id,- ),- ];-- const isIACollection = isInstanceAnalyticsCollection(collection);-- const options = isIACollection- ? [COLLECTION_OPTIONS.read, COLLECTION_OPTIONS.none]- : [- COLLECTION_OPTIONS.write,- COLLECTION_OPTIONS.read,- COLLECTION_OPTIONS.none,- ];-- const disabledTooltip = isIACollection- ? PLUGIN_COLLECTIONS.INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE- : UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;-- return {- id: group.id,- name: getGroupNameLocalized(group),- permissions: [- {- toggleLabel,- hasChildren,- isDisabled: isAdmin,- disabledTooltip: isAdmin ? disabledTooltip : null,- value: getCollectionPermission(- permissions,- group.id,- collection.id,- ),- warning: getCollectionWarning(group.id, collection, permissions),- confirmations,- options,- },- ],- };- });+ const isTenantCollection = PLUGIN_TENANTS.isTenantCollection(collection);++ const entities = groups+ .map((group: GroupType) => {+ const isAdmin = isAdminGroup(group);+ const isExternal = PLUGIN_TENANTS.isExternalUsersGroup(group);+ const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);+ const defaultGroup = _.find(+ groups,+ isExternal ? PLUGIN_TENANTS.isExternalUsersGroup : isDefaultGroup,+ );++ if (isTenantGroup && !isTenantCollection) {+ return null;+ }++ const defaultGroupPermission = getCollectionPermission(+ permissions,+ defaultGroup.id,+ collection.id,+ );++ const confirmations = (newValue: DataPermissionValue) => [+ getPermissionWarningModal(+ newValue,+ defaultGroupPermission,+ null,+ defaultGroup,+ group.id,+ ),+ ];++ const isIACollection = isInstanceAnalyticsCollection(collection);++ const options =+ isIACollection ||+ (isTenantCollection && (isTenantGroup || isExternal))+ ? [COLLECTION_OPTIONS.read, COLLECTION_OPTIONS.none]+ : [+ COLLECTION_OPTIONS.write,+ COLLECTION_OPTIONS.read,+ COLLECTION_OPTIONS.none,+ ];++ const disabledTooltip = isIACollection+ ? PLUGIN_COLLECTIONS.INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE+ : isTenantGroup || isExternal+ ? Messages.EXTERNAL_USERS_NO_ACCESS_COLLECTION+ : Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;++ const disabled =+ (!isTenantCollection && (isTenantGroup || isExternal)) || isAdmin;++ return {+ id: group.id,+ name: getGroupNameLocalized(group),+ icon: isTenantGroup ? (+ <PLUGIN_TENANTS.TenantGroupHintIcon />+ ) : undefined,+ permissions: [+ {+ toggleLabel,+ hasChildren,+ isDisabled: disabled,+ disabledTooltip: isAdmin || isExternal ? disabledTooltip : null,+ value: getCollectionPermission(+ permissions,+ group.id,+ collection.id,+ ),+ warning: getCollectionWarning(group.id, collection, permissions),+ confirmations,+ options,+ },+ ],+ };+ })+ .filter(Boolean);return {title: t`Permissions for ${collection.name}`,diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.tsindex 4b574b9de4a..32d2eacc38c 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts@@ -1,3 +1,4 @@+import { createMockGroup } from "metabase-types/api/mocks";import { createMockSettingsState } from "metabase-types/store/mocks";import { DataPermission, DataPermissionValue } from "../../types";@@ -123,18 +124,21 @@ export const normalizedMetadata = {databasesList: [2, 3],groups: {- "1": {+ "1": createMockGroup({id: 1,name: "Group starting with full access",- },- "2": {+ magic_group_type: null,+ }),+ "2": createMockGroup({id: 2,name: "Group starting with no access at all",- },- "3": {+ magic_group_type: null,+ }),+ "3": createMockGroup({id: 3,name: "All Users",- },+ magic_group_type: "all-internal-users",+ }),},groups_list: { null: { list: [1, 2, 3] } },questions: {},diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/fields.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/fields.tsindex a8e372f1fae..fd825077fef 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/fields.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/fields.ts@@ -18,7 +18,7 @@ import type Database from "metabase-lib/v1/metadata/Database";import type { Group, GroupsPermissions } from "metabase-types/api";import { DATA_PERMISSION_OPTIONS } from "../../constants/data-permissions";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "../../constants/messages";+import { Messages } from "../../constants/messages";import type { PermissionSectionConfig, TableEntityId } from "../../types";import {DataPermission,@@ -129,7 +129,9 @@ const buildAccessPermission = (permission: DataPermission.VIEW_DATA,type: DataPermissionType.ACCESS,isDisabled,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : null,isHighlighted: isAdmin,value,warning,@@ -189,6 +191,7 @@ export const buildFieldsPermissions = (entityId: TableEntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,originalPermissions: GroupsPermissions,defaultGroup: Group,@@ -223,6 +226,7 @@ export const buildFieldsPermissions = (entityId,groupId,isAdmin,+ isExternal,permissions,accessPermission.value,defaultGroup,diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/group-sidebar.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/group-sidebar.tsindex ac32fbcb310..b260b24b5fb 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/group-sidebar.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/group-sidebar.ts@@ -27,7 +27,7 @@ export const getGroupsSidebar = createSelector((groups: Group[][], params) => {const { groupId } = params;- const [pinnedGroups, unpinnedGroups] = groups;+ const [pinnedGroups, externalGroups, internalGroups] = groups;const pinnedGroupItems = pinnedGroups.map((group) => ({...group,@@ -35,15 +35,27 @@ export const getGroupsSidebar = createSelector(icon: "bolt",}));- const unpinnedGroupItems = unpinnedGroups.map((group) => ({+ const internalGroupItems = internalGroups.map((group) => ({...group,name: getGroupNameLocalized(group),icon: "group",}));+ const externalGroupItems = externalGroups.map((group) => ({+ ...group,+ name: getGroupNameLocalized(group),+ icon: group.magic_group_type ? "bolt" : "globe",+ }));++ const entityGroups = [+ pinnedGroupItems,+ internalGroupItems,+ externalGroupItems,+ ].filter((groups) => groups.length > 0);+return {selectedId: groupId,- entityGroups: [pinnedGroupItems, unpinnedGroupItems],+ entityGroups,entityViewFocus: "group",filterPlaceholder: t`Search for a group`,};diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/groups.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/groups.tsindex 2f5bcc2dc50..e5bb18ff17e 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/groups.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/groups.ts@@ -3,6 +3,7 @@ import _ from "underscore";import Groups from "metabase/entities/groups";import { isAdminGroup, isDefaultGroup } from "metabase/lib/groups";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { Group } from "metabase-types/api";const isPinnedGroup = (group: Group) =>@@ -11,11 +12,15 @@ const isPinnedGroup = (group: Group) =>export const getOrderedGroups = createSelector(Groups.selectors.getList,(groups: Group[]) => {- return _.partition(groups, isPinnedGroup);+ const [pinnedGroups, unpinnedGroups] = _.partition(groups, isPinnedGroup);+ return [+ pinnedGroups,+ ..._.partition(unpinnedGroups, PLUGIN_TENANTS.isTenantGroup),+ ];},);-export const getAdminGroup = createSelector(+export const getDefaultGroup = createSelector(Groups.selectors.getList,(groups: Group[]) => groups.find(isDefaultGroup),);diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsxsimilarity index 90%rename from frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsrename to frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsxindex cd112013840..98c44926730 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx@@ -9,6 +9,7 @@ import { isAdminGroup, isDefaultGroup } from "metabase/lib/groups";import {PLUGIN_AUDIT,PLUGIN_FEATURE_LEVEL_PERMISSIONS,+ PLUGIN_TENANTS,} from "metabase/plugins";import { getMetadataWithHiddenTables } from "metabase/selectors/metadata";import type Schema from "metabase-lib/v1/metadata/Schema";@@ -185,11 +186,20 @@ export const getDatabasesPermissionEditor = createSelector(const isAdmin = isAdminGroup(group);const defaultGroup = _.find(groups, isDefaultGroup);+ const externalUsersGroup = _.find(+ groups,+ PLUGIN_TENANTS.isExternalUsersGroup,+ );if (!defaultGroup) {throw new Error("No default group found");}+ const isExternal =+ !!externalUsersGroup &&+ (PLUGIN_TENANTS.isExternalUsersGroup(group) ||+ PLUGIN_TENANTS.isTenantGroup(group));+const hasSingleSchema =databaseId != null &&metadata.database(databaseId)?.getSchemas().length === 1;@@ -217,9 +227,10 @@ export const getDatabasesPermissionEditor = createSelector(entityId,groupId,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,),};@@ -240,9 +251,10 @@ export const getDatabasesPermissionEditor = createSelector(entityId,groupId,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,),};@@ -270,10 +282,12 @@ export const getDatabasesPermissionEditor = createSelector(entityId,groupId,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,+ "group",),};});@@ -286,7 +300,10 @@ export const getDatabasesPermissionEditor = createSelector(showViewDataColumn && { name: t`View data` },{ name: t`Create queries` },...(permissionSubject- ? PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDataColumns(permissionSubject)+ ? PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDataColumns(+ permissionSubject,+ isExternal,+ ): []),]);@@ -369,6 +386,10 @@ export const getGroupsDataPermissionEditor: GetGroupsDataPermissionEditorSelectoconst sortedGroups = groups.flat();const defaultGroup = _.find(sortedGroups, isDefaultGroup);+ const externalUsersGroup = _.find(+ sortedGroups,+ PLUGIN_TENANTS.isExternalUsersGroup,+ );if (!defaultGroup) {throw new Error("No default group found");@@ -379,6 +400,10 @@ export const getGroupsDataPermissionEditor: GetGroupsDataPermissionEditorSelectoconst entities = sortedGroups.map((group) => {const isAdmin = isAdminGroup(group);+ const isExternal =+ !!externalUsersGroup && PLUGIN_TENANTS.isExternalUsersGroup(group);++ const isTenantGroup = PLUGIN_TENANTS.isTenantGroup(group);let groupPermissions;if (tableId != null) {@@ -390,9 +415,10 @@ export const getGroupsDataPermissionEditor: GetGroupsDataPermissionEditorSelecto},group.id,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,);} else if (schemaName != null) {@@ -403,9 +429,10 @@ export const getGroupsDataPermissionEditor: GetGroupsDataPermissionEditorSelecto},group.id,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,);} else if (databaseId != null) {@@ -415,16 +442,21 @@ export const getGroupsDataPermissionEditor: GetGroupsDataPermissionEditorSelecto},group.id,isAdmin,+ isExternal,permissions,originalPermissions,- defaultGroup,+ isExternal ? externalUsersGroup : defaultGroup,database,+ "database",);}return {id: group.id,name: group.name,+ icon: isTenantGroup ? (+ <PLUGIN_TENANTS.TenantGroupHintIcon />+ ) : undefined,hint: isAdmin? t`The Administrators group is special, and always has Unrestricted access.`: null,diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/schemas.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/schemas.tsindex e2736c67721..0eca672501a 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/schemas.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/schemas.ts@@ -12,7 +12,7 @@ import type Database from "metabase-lib/v1/metadata/Database";import type { Group, GroupsPermissions } from "metabase-types/api";import { DATA_PERMISSION_OPTIONS } from "../../constants/data-permissions";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "../../constants/messages";+import { Messages } from "../../constants/messages";import {limitDatabasePermission,navigateToGranularPermissions,@@ -98,7 +98,9 @@ const buildAccessPermission = (permission: DataPermission.VIEW_DATA,type: DataPermissionType.ACCESS,isDisabled: isAdmin,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : null,isHighlighted: isAdmin,value: accessPermissionValue,warning: accessPermissionWarning,@@ -193,10 +195,12 @@ export const buildSchemasPermissions = (entityId: DatabaseEntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,originalPermissions: GroupsPermissions,defaultGroup: Group,database: Database,+ permissionView: "group" | "database",): PermissionSectionConfig[] => {const accessPermission = buildAccessPermission(entityId,@@ -229,10 +233,12 @@ export const buildSchemasPermissions = (entityId,groupId,isAdmin,+ isExternal,permissions,accessPermission.value,defaultGroup,"schemas",+ permissionView,),]);};diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/shared.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/shared.tsindex b1068483145..01a6b37cee9 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/shared.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/shared.ts@@ -1,8 +1,4 @@-import {- NATIVE_PERMISSION_REQUIRES_DATA_ACCESS,- UNABLE_TO_CHANGE_ADMIN_PERMISSIONS,- UNABLE_TO_CHANGE_LEGACY_PERMISSIONS,-} from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import { isRestrictivePermission } from "metabase/admin/permissions/utils/graph";import { PLUGIN_ADVANCED_PERMISSIONS } from "metabase/plugins";@@ -13,7 +9,7 @@ export const getNativePermissionDisabledTooltip = (accessPermissionValue: DataPermissionValue,) => {if (isAdmin) {- return UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;+ return Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS;}// prevent tooltip from being disabled when the user can't modify the view data column@@ -22,11 +18,11 @@ export const getNativePermissionDisabledTooltip = (}if (accessPermissionValue === DataPermissionValue.LEGACY_NO_SELF_SERVICE) {- return UNABLE_TO_CHANGE_LEGACY_PERMISSIONS;+ return Messages.UNABLE_TO_CHANGE_LEGACY_PERMISSIONS;}if (isRestrictivePermission(accessPermissionValue)) {- return NATIVE_PERMISSION_REQUIRES_DATA_ACCESS;+ return Messages.NATIVE_PERMISSION_REQUIRES_DATA_ACCESS;}return null;diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/tables.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/tables.tsindex e6b279da932..231e247f68d 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/tables.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/tables.ts@@ -14,7 +14,7 @@ import type Database from "metabase-lib/v1/metadata/Database";import type { Group, GroupsPermissions } from "metabase-types/api";import { DATA_PERMISSION_OPTIONS } from "../../constants/data-permissions";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "../../constants/messages";+import { Messages } from "../../constants/messages";import { navigateToGranularPermissions } from "../../permissions";import type { PermissionSectionConfig, SchemaEntityId } from "../../types";import {@@ -110,7 +110,9 @@ const buildAccessPermission = (type: DataPermissionType.ACCESS,isDisabled,isHighlighted: isAdmin,- disabledTooltip: isAdmin ? UNABLE_TO_CHANGE_ADMIN_PERMISSIONS : null,+ disabledTooltip: isAdmin+ ? Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS+ : null,value,warning,confirmations,@@ -182,6 +184,7 @@ export const buildTablesPermissions = (entityId: SchemaEntityId,groupId: number,isAdmin: boolean,+ isExternal: boolean,permissions: GroupsPermissions,originalPermissions: GroupsPermissions,defaultGroup: Group,@@ -217,6 +220,7 @@ export const buildTablesPermissions = (entityId,groupId,isAdmin,+ isExternal,permissions,accessPermission.value,defaultGroup,diff --git a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsxindex 1dd1459381d..f11bb4b46ca 100644--- a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx@@ -27,8 +27,12 @@ const TEST_DATABASE = createSampleDatabase();// Order is important here for test to pass, since admin options aren't editableconst TEST_GROUPS = [- createMockGroup({ name: "All Users" }),- createMockGroup({ id: 2, name: "Administrators" }),+ createMockGroup({+ id: 1,+ name: "All Internal Users",+ magic_group_type: "all-internal-users",+ }),+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),];const setup = async () => {diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsxindex f2bd3e4f385..2eee6a7d2cd 100644--- a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx@@ -26,8 +26,12 @@ const NATIVE_QUERIES_PERMISSION_INDEX = 0;const TEST_DATABASE = createSampleDatabase();const TEST_GROUPS = [- createMockGroup({ id: 2, name: "Administrators" }),- createMockGroup({ name: "All Users" }),+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),+ createMockGroup({+ id: 1,+ name: "All Internal Users",+ magic_group_type: "all-internal-users",+ }),];const setup = async ({diff --git a/frontend/src/metabase/admin/routes.jsx b/frontend/src/metabase/admin/routes.jsxindex 78707fef2de..b083c43952b 100644--- a/frontend/src/metabase/admin/routes.jsx+++ b/frontend/src/metabase/admin/routes.jsx@@ -50,6 +50,7 @@ import {PLUGIN_DEPENDENCIES,PLUGIN_METABOT,PLUGIN_SUPPORT,+ PLUGIN_TENANTS,} from "metabase/plugins";import { ModelPersistenceConfiguration } from "./performance/components/ModelPersistenceConfiguration";@@ -57,7 +58,11 @@ import { StrategyEditorForDatabases } from "./performance/components/StrategyEdiimport { PerformanceTabId } from "./performance/types";import { getSettingsRoutes } from "./settingsRoutes";import { ToolsUpsell } from "./tools/components/ToolsUpsell";-import { RedirectToAllowedSettings, createAdminRouteGuard } from "./utils";+import {+ RedirectToAllowedSettings,+ createAdminRouteGuard,+ createTenantsRouteGuard,+} from "./utils";const getRoutes = (store, CanAccessSettings, IsAdmin) => (<Route path="/admin" component={CanAccessSettings}>@@ -126,6 +131,7 @@ const getRoutes = (store, CanAccessSettings, IsAdmin) => (<Route path="" component={PeopleListingApp}><ModalRoute path="new" modal={NewUserModal} noWrap />+ {PLUGIN_TENANTS.userStrategyRoute}</Route><Route path=":userId" component={PeopleListingApp}>@@ -208,6 +214,12 @@ const getRoutes = (store, CanAccessSettings, IsAdmin) => (<Route path="permissions" component={IsAdmin}>{getAdminPermissionsRoutes(store)}</Route>++ {/* Tenants */}+ <Route path="tenants" component={createTenantsRouteGuard()}>+ {PLUGIN_TENANTS.tenantsRoutes}+ </Route>+{/* PERFORMANCE */}<Routepath="performance"diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsxindex 4c89f1ec46c..a6095a7b9dd 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/EmbeddingSettings.tsx@@ -25,13 +25,14 @@ import { SharedCombinedEmbeddingSettings } from "../SharedCombinedEmbeddingSettifunction EmbeddingSettingsPageWrapper({ children }: PropsWithChildren) {const isEE = isEEBuild();+ const isUsingTenants = useSetting("use-tenants");return (<SettingsPageWrapper title={t`Embedding settings`}>{children}<RelatedSettingsSection- items={getModularEmbeddingRelatedSettingItems()}+ items={getModularEmbeddingRelatedSettingItems({ isUsingTenants })}/>{isEE && <UpsellDevInstances location="embedding-page" />}diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsxindex 8b719e6f5f1..d18cbb1c468 100644--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSettings/tests/enterprise.unit.spec.tsx@@ -31,4 +31,13 @@ describe("EmbeddingSdkSettings (EE)", () => {alertInfo.getByText("implement JWT or SAML SSO"),).toBeInTheDocument();});++ it("should show Tenants in related settings when tenants feature is available", async () => {+ await setup({+ hasEnterprisePlugins: true,+ tokenFeatures: { tenants: true },+ });++ expect(screen.getByText("Tenants")).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.jsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.jsxindex 664b6890adb..3d25be91269 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.jsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.jsx@@ -2,10 +2,18 @@ import userEvent from "@testing-library/user-event";import { render, screen, waitFor } from "__support__/ui";import { FormProvider } from "metabase/forms";+import { createMockGroup } from "metabase-types/api/mocks";import { GroupMappingsWidgetView } from "./GroupMappingsWidgetView";-const defaultGroups = [{ id: 1, name: "Administrators", member_count: 1 }];+const defaultGroups = [+ createMockGroup({+ id: 1,+ name: "Administrators",+ member_count: 1,+ magic_group_type: "admin",+ }),+];const defaultMappings = { "group=Administrators": [1] };const setup = ({diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsxindex a620f99a2e8..a74a8e2bc05 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx@@ -2,11 +2,7 @@ import cx from "classnames";import { t } from "ttag";import { GroupSummary } from "metabase/admin/people/components/GroupSummary";-import type {- GroupIds,- UserGroupType,- UserGroupsType,-} from "metabase/admin/types";+import type { GroupIds, UserGroupType } from "metabase/admin/types";import PopoverWithTrigger from "metabase/common/components/PopoverWithTrigger";import Select from "metabase/common/components/Select";import CS from "metabase/css/core/index.css";@@ -19,16 +15,17 @@ import {} from "metabase/lib/groups";import { isNotNull } from "metabase/lib/types";import { Icon } from "metabase/ui";+import type { GroupInfo } from "metabase-types/api";type GroupSelectProps = {- groups: UserGroupsType;+ groups: GroupInfo[];selectedGroupIds: GroupIds;onGroupChange: (group: UserGroupType, selected: boolean) => void;isCurrentUser?: boolean;emptyListMessage?: string;};-function getSections(groups: UserGroupsType) {+function getSections(groups: GroupInfo[]) {const adminGroup = groups.find(isAdminGroup);const defaultGroup = groups.find(isDefaultGroup);const topGroups = [defaultGroup, adminGroup].filter((g) => g != null);@@ -92,12 +89,12 @@ export const GroupSelect = ({).forEach((group) => onGroupChange(group, value.includes(group.id)));}}- optionDisabledFn={(group: UserGroupType) =>+ optionDisabledFn={(group: GroupInfo) =>(isAdminGroup(group) && isCurrentUser) || !canEditMembership(group)}- optionValueFn={(group: UserGroupType) => group.id}+ optionValueFn={(group: GroupInfo) => group.id}optionNameFn={getGroupNameLocalized}- optionStylesFn={(group: UserGroupType) => ({+ optionStylesFn={(group: GroupInfo) => ({color: getGroupColor(group),})}value={selectedGroupIds}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsxindex 445781eaf6b..0c687c656d9 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx@@ -7,13 +7,13 @@ import _ from "underscore";import type {DeleteMappingModalValueType,GroupIds,- UserGroupsType,} from "metabase/admin/types";import { ConfirmModal } from "metabase/common/components/ConfirmModal";import AdminS from "metabase/css/admin.module.css";import CS from "metabase/css/core/index.css";import { isAdminGroup } from "metabase/lib/groups";import { Icon, Tooltip } from "metabase/ui";+import type { GroupInfo } from "metabase-types/api";import DeleteGroupMappingModal from "../DeleteGroupMappingModal";import Selectbox from "../GroupSelect";@@ -28,7 +28,7 @@ type OnDeleteMappingType = (arg: {type MappingRowProps = {name: string;- groups: UserGroupsType;+ groups: GroupInfo[];selectedGroupIds: GroupIds;clearGroupMember: ({ id }: { id: number }) => void;deleteGroup: ({ id }: { id: number }) => void;diff --git a/frontend/src/metabase/admin/utils.js b/frontend/src/metabase/admin/utils.jsindex af1d975ec8c..1a7d7744e79 100644--- a/frontend/src/metabase/admin/utils.js+++ b/frontend/src/metabase/admin/utils.js@@ -4,6 +4,7 @@ import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";import { getAdminPaths } from "metabase/admin/app/selectors";import { MetabaseReduxContext, connect } from "metabase/lib/redux";+import { getSetting } from "metabase/selectors/settings";export const createAdminRouteGuard = (routeKey, Component) => {const Wrapper = connectedReduxRedirect({@@ -41,3 +42,18 @@ export const RedirectToAllowedSettings = connect(mapStateToProps,mapDispatchToProps,)(_RedirectToAllowedSettings);++export const createTenantsRouteGuard = () => {+ const Wrapper = connectedReduxRedirect({+ wrapperDisplayName: "CanAccessTenants",+ redirectPath: "/admin/people",+ allowRedirectBack: false,+ authenticatedSelector: (state) =>+ getAdminPaths(state)?.find((path) => path.key === "people") != null &&+ getSetting(state, "use-tenants"),+ redirectAction: routerActions.replace,+ context: MetabaseReduxContext,+ });++ return Wrapper(({ children }) => children);+};diff --git a/frontend/src/metabase/api/embedding-hub.ts b/frontend/src/metabase/api/embedding-hub.tsindex 57a27ac277c..a8fdecc108b 100644--- a/frontend/src/metabase/api/embedding-hub.ts+++ b/frontend/src/metabase/api/embedding-hub.ts@@ -9,7 +9,8 @@ type CheckListApiStep =| "configure-row-column-security"| "create-test-embed"| "embed-production"- | "secure-embeds";+ | "secure-embeds"+ | "setup-tenants";export type EmbeddingHubChecklist = Record<CheckListApiStep, boolean>;export const embeddingHubApi = Api.injectEndpoints({diff --git a/frontend/src/metabase/api/permission.ts b/frontend/src/metabase/api/permission.tsindex ded45f71b63..a098bd2548f 100644--- a/frontend/src/metabase/api/permission.ts+++ b/frontend/src/metabase/api/permission.ts@@ -19,10 +19,14 @@ import {export const permissionApi = Api.injectEndpoints({endpoints: (builder) => ({- listPermissionsGroups: builder.query<GroupListQuery[], void>({- query: () => ({+ listPermissionsGroups: builder.query<+ GroupListQuery[],+ { tenancy?: "external" | "internal" } | undefined+ >({+ query: (params) => ({method: "GET",url: "/api/permissions/group",+ params,}),providesTags: (groups = []) => providePermissionsGroupListTags(groups),}),@@ -34,7 +38,10 @@ export const permissionApi = Api.injectEndpoints({providesTags: (group) =>group ? providePermissionsGroupTags(group) : [],}),- createPermissionsGroup: builder.mutation<BaseGroupInfo, { name: string }>({+ createPermissionsGroup: builder.mutation<+ BaseGroupInfo,+ Pick<BaseGroupInfo, "name" | "is_tenant_group">+ >({query: (body) => ({method: "POST",url: "/api/permissions/group",diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex b70b6f06499..ba1f282edfb 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -51,6 +51,7 @@ export const TAG_TYPES = ["public-action","unique-tasks","user-key-value",+ "tenant",] as const;export const TAG_TYPE_MAPPING = {diff --git a/frontend/src/metabase/api/user.ts b/frontend/src/metabase/api/user.tsindex 5388218dc4d..caf512378a5 100644--- a/frontend/src/metabase/api/user.ts+++ b/frontend/src/metabase/api/user.ts@@ -53,7 +53,11 @@ export const userApi = Api.injectEndpoints({body,}),invalidatesTags: (_, error) =>- invalidateTags(error, [listTag("user"), listTag("permissions-group")]),+ invalidateTags(error, [+ listTag("user"),+ listTag("tenant"),+ listTag("permissions-group"),+ ]),onQueryStarted: (request, { dispatch, queryFulfilled }) =>handleQueryFulfilled(queryFulfilled, (user) => {if (request.password) {diff --git a/frontend/src/metabase/collections/components/CollectionMenu/CollectionMenu.tsx b/frontend/src/metabase/collections/components/CollectionMenu/CollectionMenu.tsxindex add62a2ea0c..37774f8967a 100644--- a/frontend/src/metabase/collections/components/CollectionMenu/CollectionMenu.tsx+++ b/frontend/src/metabase/collections/components/CollectionMenu/CollectionMenu.tsx@@ -2,6 +2,7 @@ import { type ReactNode, useState } from "react";import { t } from "ttag";import {+ isDedicatedTenantCollectionRoot,isInstanceAnalyticsCustomCollection,isPersonalCollection,isRootCollection,@@ -11,7 +12,7 @@ import { ForwardRefLink } from "metabase/common/components/Link";import { useHasDashboardQuestionCandidates } from "metabase/common/components/MoveQuestionsIntoDashboardsModal/hooks";import { UserHasSeenAll } from "metabase/common/components/UserHasSeen/UserHasSeenAll";import * as Urls from "metabase/lib/urls";-import { PLUGIN_COLLECTIONS } from "metabase/plugins";+import { PLUGIN_COLLECTIONS, PLUGIN_TENANTS } from "metabase/plugins";import { ActionIcon, Icon, Indicator, Menu, Tooltip } from "metabase/ui";import type { Collection } from "metabase-types/api";@@ -44,11 +45,14 @@ export const CollectionMenu = ({const isPersonal = isPersonalCollection(collection);const isInstanceAnalyticsCustom =isInstanceAnalyticsCustomCollection(collection);+ const isSharedTenantCollection =+ PLUGIN_TENANTS.isTenantCollection(collection);const canWrite = collection.can_write;const canMove =!isRoot &&!isRootPersonalCollection(collection) &&+ !isDedicatedTenantCollectionRoot(collection) &&canWrite &&!isInstanceAnalyticsCustom;@@ -77,7 +81,12 @@ export const CollectionMenu = ({);}- if (isAdmin && !isPersonal) {+ if (+ isAdmin &&+ !isPersonal &&+ !isDedicatedTenantCollectionRoot(collection) &&+ !isSharedTenantCollection+ ) {editItems.push(<Menu.Itemkey="collection-edit"diff --git a/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsxindex 290624c508e..d254dc8ebc5 100644--- a/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx@@ -1,7 +1,10 @@import userEvent from "@testing-library/user-event";import { getIcon, screen } from "__support__/ui";-import { createMockCollection } from "metabase-types/api/mocks";+import {+ createMockCollection,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";import type { SetupOpts } from "./setup";import { setup } from "./setup";@@ -24,4 +27,18 @@ describe("CollectionMenu", () => {screen.queryByText("Make collection official"),).not.toBeInTheDocument();});++ it("should not be able to edit permissions for shared tenant collections", async () => {+ setupEnterprise({+ collection: createMockCollection({+ can_write: true,+ namespace: "shared-tenant-collection",+ }),+ isAdmin: true,+ tokenFeatures: createMockTokenFeatures({ tenants: true }),+ });++ await userEvent.click(getIcon("ellipsis"));+ expect(screen.queryByText("Edit permissions")).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsxindex 727499aa1f1..fe9d3beca0e 100644--- a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo } from "react";+import { useMemo } from "react";import { withRouter } from "react-router";import { t } from "ttag";import _ from "underscore";@@ -30,9 +30,10 @@ const COLLECTION_SCHEMA = Yup.object({authority_level: Yup.mixed().oneOf(["official", null]).default(null),parent_id: Yup.number().nullable(),+ namespace: Yup.string().nullable().default(null),});-interface CreateCollectionProperties {+export interface CreateCollectionProperties {name: string;description: string | null;parent_id: Collection["id"];@@ -40,9 +41,10 @@ interface CreateCollectionProperties {export interface CreateCollectionFormOwnProps {collectionId?: Collection["id"]; // can be used by `getInitialCollectionId`- onCreate?: (collection: Collection) => void;+ onSubmit: (collection: CreateCollectionProperties) => void;onCancel?: () => void;filterPersonalCollections?: FilterItemsInPersonalCollection;+ showCollectionPicker?: boolean;}interface CreateCollectionFormStateProps {@@ -77,10 +79,10 @@ const mapDispatchToProps = {function CreateCollectionForm({initialCollectionId,- handleCreateCollection,- onCreate,+ onSubmit,onCancel,filterPersonalCollections,+ showCollectionPicker = true,}: Props) {const initialValues = useMemo(() => ({@@ -90,22 +92,13 @@ function CreateCollectionForm({[initialCollectionId],);- const handleCreate = useCallback(- async (values: CreateCollectionProperties) => {- const action = await handleCreateCollection(values);- const collection = Collections.HACK_getObjectFromAction(action);- onCreate?.(collection);- },- [handleCreateCollection, onCreate],- );-return (<FormProviderinitialValues={initialValues}validationSchema={COLLECTION_SCHEMA}- onSubmit={handleCreate}+ onSubmit={onSubmit}>- {({ dirty }) => (+ {({ dirty, setFieldValue }) => (<Form><FormInputname="name"@@ -120,12 +113,18 @@ function CreateCollectionForm({nullableoptional/>- <FormCollectionPicker- name="parent_id"- title={t`Collection it's saved in`}- filterPersonalCollections={filterPersonalCollections}- entityType="collection"- />+ {showCollectionPicker && (+ <FormCollectionPicker+ name="parent_id"+ setNamespace={(namespace) =>+ setFieldValue("namespace", namespace)+ }+ title={t`Collection it's saved in`}+ filterPersonalCollections={filterPersonalCollections}+ entityType="collection"+ savingModel="collection"+ />+ )}<FormAuthorityLevelField /><FormFooter><FormErrorMessage inline />diff --git a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsxindex 116105d2efc..1058652291e 100644--- a/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx+++ b/frontend/src/metabase/collections/components/MoveCollectionModal/MoveCollectionModal.tsx@@ -41,10 +41,12 @@ const MoveCollectionModalView = ({title={t`Move "${collection.name}"?`}initialCollectionId={collection.parent_id ?? "root"}movingCollectionId={collection.id}+ movingCollectionNamespace={collection.namespace ?? undefined}entityType="collection"onMove={handleMove}onClose={onClose}recentAndSearchFilter={recentsAndSearchFilter}+ savingModel="collection"/>);};diff --git a/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx b/frontend/src/metabase/collections/containers/CreateCollectionModal.tsxindex 971eb2d8274..c45cde66ccc 100644--- a/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx+++ b/frontend/src/metabase/collections/containers/CreateCollectionModal.tsx@@ -4,6 +4,7 @@ import { push } from "react-router-redux";import { t } from "ttag";import { useEscapeToCloseModal } from "metabase/common/hooks/use-escape-to-close-modal";+import Collections from "metabase/entities/collections";import { connect } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { Modal } from "metabase/ui";@@ -12,30 +13,40 @@ import type { State } from "metabase-types/store";import type { CreateCollectionFormOwnProps } from "../components/CreateCollectionForm";import { CreateCollectionForm } from "../components/CreateCollectionForm";+import type { CreateCollectionProperties } from "../components/CreateCollectionForm/CreateCollectionForm";interface CreateCollectionModalOwnProps- extends Omit<CreateCollectionFormOwnProps, "onCancel"> {+ extends Omit<CreateCollectionFormOwnProps, "onCancel" | "onSubmit"> {+ onCreate?: (collection: Collection) => void;onClose: () => void;}interface CreateCollectionModalDispatchProps {onChangeLocation: (location: LocationDescriptor) => void;+ handleCreateCollection: (+ collection: CreateCollectionProperties,+ ) => Promise<Collection>;}type Props = CreateCollectionModalOwnProps & CreateCollectionModalDispatchProps;const mapDispatchToProps = {onChangeLocation: push,+ handleCreateCollection: Collections.actions.create,};function CreateCollectionModal({onCreate,onChangeLocation,onClose,+ handleCreateCollection,...props}: Props) {const handleCreate = useCallback(- (collection: Collection) => {+ async (values: CreateCollectionProperties) => {+ const action = await handleCreateCollection(values);+ const collection = Collections.HACK_getObjectFromAction(action);+if (typeof onCreate === "function") {onCreate(collection);} else {@@ -43,7 +54,7 @@ function CreateCollectionModal({onChangeLocation(Urls.collection(collection));}},- [onCreate, onChangeLocation, onClose],+ [onCreate, onChangeLocation, onClose, handleCreateCollection],);useEscapeToCloseModal(onClose);@@ -60,7 +71,7 @@ function CreateCollectionModal({><CreateCollectionForm{...props}- onCreate={handleCreate}+ onSubmit={handleCreate}onCancel={onClose}/></Modal>diff --git a/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsxindex 4cd2316692c..8eae581fcf2 100644--- a/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx+++ b/frontend/src/metabase/collections/containers/FormCollectionAndDashboardPicker/FormCollectionAndDashboardPicker.tsx@@ -80,6 +80,11 @@ interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {entityType?: EntityType;zIndex?: number;collectionPickerModalProps?: Partial<CollectionPickerModalProps>;+ /**+ * The type of item being saved. When set to a non-collection model,+ * namespace root collections (like tenant root) will be disabled.+ */+ savingModel?: "collection" | "dashboard" | "question" | "model";}export function FormCollectionAndDashboardPicker({@@ -94,6 +99,7 @@ export function FormCollectionAndDashboardPicker({dashboardIdFieldName,dashboardTabIdFieldName,entityType,+ savingModel,}: FormCollectionPickerProps) {const id = useUniqueId();@@ -168,8 +174,14 @@ export function FormCollectionAndDashboardPicker({item === "dashboard"? t`Select this dashboard`: t`Select this collection`,+ savingModel,}),- [filterPersonalCollections, type, showCreateNewCollectionOption],+ [+ filterPersonalCollections,+ type,+ showCreateNewCollectionOption,+ savingModel,+ ],);const [fetchDashboard] = useLazyGetDashboardQuery();diff --git a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsxindex fd65c5cbd70..8ae125c4632 100644--- a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx+++ b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx@@ -22,8 +22,9 @@ import SnippetCollectionName from "metabase/common/components/SnippetCollectionNimport { useUniqueId } from "metabase/common/hooks/use-unique-id";import Collections from "metabase/entities/collections";import { useSelector } from "metabase/lib/redux";+import { PLUGIN_TENANTS } from "metabase/plugins";import { Button, Icon } from "metabase/ui";-import type { CollectionId } from "metabase-types/api";+import type { CollectionId, CollectionNamespace } from "metabase-types/api";interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {name: string;@@ -35,36 +36,59 @@ interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {filterPersonalCollections?: FilterItemsInPersonalCollection;entityType?: EntityType;collectionPickerModalProps?: Partial<CollectionPickerModalProps>;+ setNamespace?: (namespace: string | undefined) => void;+ /**+ * The type of item being saved. When set to a non-collection model,+ * namespace root collections (like tenant root) will be disabled.+ */+ savingModel?: "collection" | "dashboard" | "question" | "model";}function ItemName({id,type = "collections",+ namespace = null,}: {id: CollectionId;type?: "collections" | "snippet-collections";+ namespace?: string | null;}) {- return type === "snippet-collections" ? (- <SnippetCollectionName id={id} />- ) : (- <CollectionName id={id} />- );+ if (type === "snippet-collections") {+ return <SnippetCollectionName id={id} />;+ }++ // Check for tenant namespace display name via plugin+ if (id === null) {+ const namespaceDisplayName = PLUGIN_TENANTS.getNamespaceDisplayName(+ namespace as CollectionNamespace,+ );+ if (namespaceDisplayName) {+ return <span>{namespaceDisplayName}</span>;+ }+ }++ return <CollectionName id={id} />;}function FormCollectionPicker({className,style,name,+ setNamespace,title,placeholder = t`Select a collection`,type = "collections",filterPersonalCollections,entityType,collectionPickerModalProps,+ savingModel,}: FormCollectionPickerProps) {const id = useUniqueId();const [{ value }, { error, touched }, { setValue }] = useField(name);+ const [collectionNamespace, setCollectionNamespace] = useState<string | null>(+ null,+ );const formFieldRef = useRef<HTMLDivElement>(null);const [isPickerOpen, setIsPickerOpen] = useState(false);@@ -107,16 +131,27 @@ function FormCollectionPicker({namespace: type === "snippet-collections" ? "snippets" : undefined,allowCreateNew: showCreateNewCollectionOption,hasRecents: type !== "snippet-collections",+ savingModel,}),- [filterPersonalCollections, type, showCreateNewCollectionOption],+ [+ filterPersonalCollections,+ type,+ showCreateNewCollectionOption,+ savingModel,+ ],);const handleChange = useCallback(- ({ id }: CollectionPickerItem) => {+ ({ id, namespace }: CollectionPickerItem) => {+ if (namespace) {+ setNamespace?.(namespace);+ setCollectionNamespace(namespace);+ }+ setCollectionNamespace(namespace ?? null);setValue(canonicalCollectionId(id));setIsPickerOpen(false);},- [setValue],+ [setValue, setNamespace, setCollectionNamespace],);return (@@ -143,7 +178,7 @@ function FormCollectionPicker({}}>{isValidCollectionId(value) ? (- <ItemName id={value} type={type} />+ <ItemName id={value} type={type} namespace={collectionNamespace} />) : (placeholder)}diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.tsindex 0603e38e112..e771e9ddd12 100644--- a/frontend/src/metabase/collections/utils.ts+++ b/frontend/src/metabase/collections/utils.ts@@ -38,6 +38,12 @@ export function isRootPersonalCollection(return typeof collection.personal_owner_id === "number";}+export function isDedicatedTenantCollectionRoot(+ collection: Partial<Collection> | CollectionItem,+): boolean {+ return collection.type === "tenant-specific-root-collection";+}+export function isPersonalCollection(collection: Pick<Collection, "is_personal">,) {@@ -221,7 +227,10 @@ export function canArchiveItem(item: CollectionItem, collection?: Collection) {return (collection?.can_write &&!isReadOnlyCollection(item) &&- !(isItemCollection(item) && isRootPersonalCollection(item)) &&+ !(+ isItemCollection(item) &&+ (isRootPersonalCollection(item) || isDedicatedTenantCollectionRoot(item))+ ) &&!isLibraryCollection(item as Pick<Collection, "type">) &&item.model !== "table" &&!item.archived@@ -277,6 +286,7 @@ export function canonicalCollectionId(): number | null {if (collectionId === "root" ||+ collectionId === "tenant" ||collectionId === null ||collectionId === undefined) {diff --git a/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneLayout.tsx b/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneLayout.tsxindex ffce52bd683..f0491a73eb2 100644--- a/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneLayout.tsx+++ b/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneLayout.tsx@@ -1,32 +1,51 @@import type { ReactNode } from "react";-import { AdminPaneTitle } from "./AdminPaneTitle";-import type { AdminPaneProps } from "./types";+import CS from "metabase/css/core/index.css";+import { Flex, Stack, Text } from "metabase/ui";-type AdminPaneLayoutProps = AdminPaneProps & {+interface AdminPaneLayoutProps {+ title?: React.ReactNode;+ description?: string;+ titleActions?: ReactNode;+ headerContent?: ReactNode;children: ReactNode;-};+}export const AdminPaneLayout = ({title,description,- buttonText,- buttonAction,- buttonDisabled,children,- buttonLink,- headingContent,-}: AdminPaneLayoutProps) => (- <div data-testid="admin-panel">- <AdminPaneTitle- title={title}- description={description}- buttonText={buttonText}- buttonAction={buttonAction}- buttonDisabled={buttonDisabled}- buttonLink={buttonLink}- headingContent={headingContent}- />- {children}- </div>-);+ headerContent,+ titleActions,+}: AdminPaneLayoutProps) => {+ return (+ <div data-testid="admin-panel">+ <Stack component="section" px="md" mb="xl" gap="lg">+ {(title || description || titleActions) && (+ <Flex+ justify="space-between"+ align="flex-start"+ gap="md"+ wrap="nowrap"+ >+ <Stack gap="md">+ {title && (+ <h2 data-testid="admin-pane-page-title" className={CS.m0}>+ {title}+ </h2>+ )}+ {description && <Text maw="40rem">{description}</Text>}+ </Stack>+ {titleActions}+ </Flex>+ )}++ <Flex w="100%" align="center" gap="xl">+ {headerContent}+ </Flex>+ </Stack>++ {children}+ </div>+ );+};diff --git a/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneTitle.tsx b/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneTitle.tsxdeleted file mode 100644index ca8856fbf25..00000000000--- a/frontend/src/metabase/common/components/AdminPaneLayout/AdminPaneTitle.tsx+++ /dev/null@@ -1,52 +0,0 @@-import cx from "classnames";--import Button from "metabase/common/components/Button";-import Link from "metabase/common/components/Link";-import CS from "metabase/css/core/index.css";-import { Box, Flex, Text } from "metabase/ui";--import type { AdminPaneProps } from "./types";--export const AdminPaneTitle = ({- title,- description,- buttonText,- buttonAction,- buttonDisabled,- buttonLink,- headingContent,-}: AdminPaneProps) => {- const buttonClassName = cx(CS.mlAuto, CS.flexNoShrink);- return (- <Box px="md">- <Flex wrap="wrap" gap="md" justify="space-between">- <Box>- {headingContent && <>{headingContent}</>}- {title && (- <h2 data-testid="admin-pane-page-title" className={CS.m0}>- {title}- </h2>- )}- {description && <Text maw="40rem">{description}</Text>}- </Box>- <Box>- {buttonText && buttonLink && (- <Link to={buttonLink} className={buttonClassName}>- <Button primary>{buttonText}</Button>- </Link>- )}- {buttonText && buttonAction && (- <Button- className={buttonClassName}- primary={!buttonDisabled}- disabled={buttonDisabled}- onClick={buttonAction}- >- {buttonText}- </Button>- )}- </Box>- </Flex>- </Box>- );-};diff --git a/frontend/src/metabase/common/components/AdminPaneLayout/types.ts b/frontend/src/metabase/common/components/AdminPaneLayout/types.tsdeleted file mode 100644index 8a2b1ef84aa..00000000000--- a/frontend/src/metabase/common/components/AdminPaneLayout/types.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { ReactNode } from "react";--export type AdminPaneProps = {- title?: React.ReactNode;- description?: string;- buttonText?: string;- buttonAction?: () => void;- buttonDisabled?: boolean;- buttonLink?: string;- headingContent?: ReactNode;-};diff --git a/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.ts b/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.tsindex 9eb42898e8a..ecd8bffef92 100644--- a/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.ts+++ b/frontend/src/metabase/common/components/EntityPicker/hooks/use-scoped-search-results.ts@@ -49,7 +49,8 @@ export const useScopedSearchResults = <searchScope: EntityPickerSearchScope,folder: Item | undefined,): SearchItem[] | null => {- const isScopedSearchEnabled = searchScope === "folder" && folder != null;+ const isScopedSearchEnabled =+ searchScope === "folder" && folder != null && folder.id !== "tenant";const shouldUseCollectionItems =isScopedSearchEnabled &&@@ -62,7 +63,7 @@ export const useScopedSearchResults = <const { data: collectionItemsData, isFetching: isFetchingCollectionItems } =useListCollectionItemsQuery(- shouldUseCollectionItems+ shouldUseCollectionItems && searchQuery? {id: folder.id as CollectionId,models: searchModelsToCollectionItemModels(searchModels),@@ -72,7 +73,9 @@ export const useScopedSearchResults = <const { data: dashboardItemsData, isFetching: isFetchingDashboardItems } =useListDashboardItemsQuery(- shouldUseDashboardItems ? { id: folder.id as DashboardId } : skipToken,+ shouldUseDashboardItems && searchQuery+ ? { id: folder.id as DashboardId }+ : skipToken,);const dbId =diff --git a/frontend/src/metabase/common/components/MoveModal.tsx b/frontend/src/metabase/common/components/MoveModal.tsxindex bce2156f50b..d298b59fcbf 100644--- a/frontend/src/metabase/common/components/MoveModal.tsx+++ b/frontend/src/metabase/common/components/MoveModal.tsx@@ -20,9 +20,11 @@ import {type CollectionPickerValueItem,getCollectionType,} from "metabase/common/components/Pickers/CollectionPicker";+import { PLUGIN_TENANTS } from "metabase/plugins";import type {CollectionId,CollectionItem,+ CollectionNamespace,RecentItem,SearchResult,} from "metabase-types/api";@@ -34,6 +36,18 @@ interface BaseMoveModalProps {movingCollectionId?: CollectionId;entityType?: EntityType;recentAndSearchFilter?: (item: CollectionPickerItem) => boolean;+ /**+ * The type of item being moved. When set to a non-collection model,+ * namespace root collections (like tenant root) will be disabled.+ */+ savingModel?: "collection" | "dashboard" | "question" | "model";+ /**+ * The namespace of the collection being moved. Used to restrict which+ * collections are shown in the picker:+ * - If "shared-tenant-collection", only tenant collections are shown+ * - Otherwise, tenant collections are hidden from the picker+ */+ movingCollectionNamespace?: CollectionNamespace;}type MoveModalProps =@@ -77,7 +91,12 @@ export const MoveModal = ({entityType,canMoveToDashboard,recentAndSearchFilter,+ savingModel,+ movingCollectionNamespace,}: MoveModalProps) => {+ const isMovingTenantCollection = PLUGIN_TENANTS.isTenantNamespace(+ movingCollectionNamespace,+ );const shouldDisableItem = (item: CollectionPickerItem): boolean => {if (movingCollectionId) {if (@@ -147,6 +166,12 @@ export const MoveModal = ({? ["collection", "dashboard"]: ["collection"];+ const restrictToNamespace: string | undefined = movingCollectionId+ ? isMovingTenantCollection && PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE+ ? PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE+ : "default"+ : undefined;+return (<CollectionPickerModaltitle={title}@@ -157,12 +182,15 @@ export const MoveModal = ({onChange={handleMove}models={models}options={{- showSearch: true,+ showSearch: !isMovingTenantCollection,allowCreateNew: true,hasConfirmButtons: true,- showRootCollection: true,- showPersonalCollections: true,+ showRootCollection: !isMovingTenantCollection,+ showPersonalCollections: !isMovingTenantCollection,confirmButtonText: t`Move`,+ savingModel,+ hasRecents: !isMovingTenantCollection,+ restrictToNamespace,}}shouldDisableItem={shouldDisableItem}entityType={entityType}diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsxindex 199b45ba0db..569a1d96eb3 100644--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx@@ -23,12 +23,16 @@ console.error = jest.fn();type SetupOpts = {databases?: Database[];hasModels?: boolean;+ canWrite?: boolean;};const SAMPLE_DATABASE = createSampleDatabase();const COLLECTION = createMockCollection();-async function setup({ databases = [SAMPLE_DATABASE] }: SetupOpts = {}) {+async function setup({+ databases = [SAMPLE_DATABASE],+ canWrite = true,+}: SetupOpts = {}) {setupDatabasesEndpoints(databases);setupCollectionByIdEndpoint({collections: [COLLECTION],@@ -46,11 +50,12 @@ async function setup({ databases = [SAMPLE_DATABASE] }: SetupOpts = {}) {can_create_queries: true,can_create_native_queries: true,}),+ can_write_any_collection: canWrite,}),}),},);- await userEvent.click(screen.getByText("New"));+ await userEvent.click(await screen.findByText("New"));}describe("NewItemMenu", () => {@@ -99,5 +104,12 @@ describe("NewItemMenu", () => {const modal = await screen.findByRole("dialog");expect(modal).toHaveTextContent("New dashboard");});++ it("should not be available if the user has no write permissions to collection", async () => {+ await setup({ canWrite: false });+ expect(await screen.findByText("Question")).toBeInTheDocument();+ expect(await screen.findByText("SQL query")).toBeInTheDocument();+ expect(screen.queryByText("Dashboard")).not.toBeInTheDocument();+ });});});diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsxindex c8e294011de..f0a74c982f1 100644--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx@@ -7,6 +7,7 @@ import { useDispatch, useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { setOpenModal } from "metabase/redux/ui";import { getSetting } from "metabase/selectors/settings";+import { getUserCanWriteToCollections } from "metabase/selectors/user";import { Box, Icon, Menu } from "metabase/ui";import type { CollectionId } from "metabase-types/api";@@ -37,6 +38,8 @@ const NewItemMenuView = ({getSetting(state, "last-used-native-database-id"),);+ const canWriteToCollections = useSelector(getUserCanWriteToCollections);+const menuItems = useMemo(() => {const items = [];@@ -76,18 +79,21 @@ const NewItemMenuView = ({</Menu.Item>,);}- items.push(- <Menu.Item- key="dashboard"- onClick={() => {- trackNewMenuItemClicked("dashboard");- dispatch(setOpenModal("dashboard"));- }}- leftSection={<Icon name="dashboard" />}- >- {t`Dashboard`}- </Menu.Item>,- );++ if (canWriteToCollections) {+ items.push(+ <Menu.Item+ key="dashboard"+ onClick={() => {+ trackNewMenuItemClicked("dashboard");+ dispatch(setOpenModal("dashboard"));+ }}+ leftSection={<Icon name="dashboard" />}+ >+ {t`Dashboard`}+ </Menu.Item>,+ );+ }items.push(<Menu.Item@@ -108,8 +114,13 @@ const NewItemMenuView = ({lastUsedDatabaseId,hasDatabaseWithJsonEngine,dispatch,+ canWriteToCollections,]);+ if (menuItems.length === 0) {+ return null;+ }+return (<Menu position="bottom-end"><Menu.Target>diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsxindex 3acdbe68874..4393a000fb1 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsx+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemPickerResolver.tsx@@ -2,6 +2,7 @@ import _ from "underscore";import { TablePicker } from "metabase/common/components/Pickers/TablePicker";import { PERSONAL_COLLECTIONS } from "metabase/entities/collections";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { CollectionItemListProps, CollectionPickerItem } from "../types";@@ -52,6 +53,36 @@ export const CollectionItemPickerResolver = ({);}+ if (query.id === PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS?.id) {+ return (+ <PLUGIN_TENANTS.TenantSpecificCollectionsItemList+ onClick={onClick}+ selectedItem={selectedItem}+ isFolder={isFolder}+ isCurrentLevel={isCurrentLevel}+ shouldDisableItem={shouldDisableItem}+ shouldShowItem={shouldShowItem}+ options={options}+ />+ );+ }++ // Route to tenant collection list only for the root tenant collection+ // (not for subcollections within the tenant namespace)+ if (query.id === "tenant") {+ return (+ <PLUGIN_TENANTS.TenantCollectionItemList+ onClick={onClick}+ selectedItem={selectedItem}+ isFolder={isFolder}+ isCurrentLevel={isCurrentLevel}+ shouldDisableItem={shouldDisableItem}+ shouldShowItem={shouldShowItem}+ options={options}+ />+ );+ }+if (entity === "dashboard") {return (<DashboardItemListdiff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsxdeleted file mode 100644index d1f2f13102c..00000000000--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx+++ /dev/null@@ -1,267 +0,0 @@-import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";-import { useState } from "react";--import {- setupCollectionItemsEndpoint,- setupDatabasesEndpoints,-} from "__support__/server-mocks";-import {- act,- mockGetBoundingClientRect,- renderWithProviders,- screen,- waitFor,- within,-} from "__support__/ui";-import type { Collection, CollectionId } from "metabase-types/api";-import {- createMockCollection,- createMockCollectionItem,-} from "metabase-types/api/mocks";--import type { CollectionPickerItem, CollectionPickerStatePath } from "../types";--import { CollectionPicker } from "./CollectionPicker";--type MockCollection = {- id: CollectionId;- name: string;- location: string | null;- effective_location: string | null;- is_personal: boolean;- collections: MockCollection[];-};--const collectionTree: MockCollection[] = [- {- id: "root",- name: "Our Analytics",- location: null,- effective_location: null,- is_personal: false,- collections: [- {- id: 4,- name: "Collection 4",- location: "/",- effective_location: "/",- is_personal: false,- collections: [- {- id: 3,- name: "Collection 3",- collections: [],- location: "/4/",- effective_location: "/4/",- is_personal: false,- },- ],- },- {- id: 2,- is_personal: false,- name: "Collection 2",- location: "/",- effective_location: "/",- collections: [],- },- ],- },- {- name: "My personal collection",- id: 1,- location: "/",- effective_location: "/",- is_personal: true,- collections: [- {- id: 5,- location: "/1/",- effective_location: "/1/",- name: "personal sub_collection",- is_personal: true,- collections: [],- },- ],- },-];--const flattenCollectionTree = (- node: MockCollection[],-): Omit<MockCollection, "collections">[] => {- return [- ...node.map((n) => ({- name: n.name,- id: n.id,- is_personal: !!n.is_personal,- location: n.location,- effective_location: n.effective_location,- })),- ].concat(...node.map((n) => flattenCollectionTree(n.collections)));-};--const setupCollectionTreeMocks = (node: MockCollection[]) => {- node.forEach((n) => {- const collectionItems = n.collections.map((c: MockCollection) =>- createMockCollectionItem({- id: c.id as number,- name: c.name,- model: "collection",- location: c.location || "/",- effective_location: c.effective_location || "/",- }),- );-- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: n.id }),- collectionItems,- models: ["collection"],- });-- if (collectionItems.length > 0) {- setupCollectionTreeMocks(n.collections);- }- });-};--interface SetupOpts {- initialValue?: {- id: CollectionId;- model: "collection";- };- onItemSelect?: (item: CollectionPickerItem) => void;- shouldDisableItem?: (item: CollectionPickerItem) => boolean;-}--const setup = ({- initialValue = { id: "root", model: "collection" },- onItemSelect = jest.fn<void, [CollectionPickerItem]>(),- shouldDisableItem,-}: SetupOpts = {}) => {- mockGetBoundingClientRect();-- const allCollections = flattenCollectionTree(collectionTree).map((c) =>- createMockCollection(c as Collection),- );-- //Setup individual collection mocks- allCollections.forEach((collection) => {- fetchMock.get(`path:/api/collection/${collection.id}`, collection);- });-- setupCollectionTreeMocks(collectionTree);- setupDatabasesEndpoints([]);-- function TestComponent() {- const [path, setPath] = useState<CollectionPickerStatePath>();-- return (- <CollectionPicker- initialValue={initialValue}- path={path}- onInit={jest.fn()}- onItemSelect={onItemSelect}- onPathChange={setPath}- shouldDisableItem={shouldDisableItem}- />- );- }-- return renderWithProviders(<TestComponent />);-};--describe("CollectionPicker", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should select the root collection by default", async () => {- act(() => {- setup();- });-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toBeInTheDocument();-- expect(- await screen.findByRole("link", { name: /Collection 2/ }),- ).toBeInTheDocument();- });-- it("should render the path to the value provided", async () => {- act(() => {- setup({ initialValue: { id: 3, model: "collection" } });- });- await screen.findByRole("link", { name: /Our Analytics/ });- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path back to personal collection", async () => {- act(() => {- setup({ initialValue: { id: 5, model: "collection" } });- });- expect(- await screen.findByRole("link", { name: /My personal collection/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /personal sub_collection/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should allow selecting, but not navigating into collections without children", async () => {- act(() => {- setup({ initialValue: { id: 1, model: "collection" } });- });-- const personalSubCollectionButton = await screen.findByRole("link", {- name: /personal sub_collection/,- });- expect(personalSubCollectionButton).not.toHaveAttribute("data-active");-- expect(- within(personalSubCollectionButton).queryByLabelText("chevronright icon"),- ).not.toBeInTheDocument();-- await userEvent.click(personalSubCollectionButton);-- expect(personalSubCollectionButton).toHaveAttribute("data-active", "true");-- // selecting an empty collection should not show another column- await waitFor(() =>- expect(- screen.queryByTestId("item-picker-level-2"),- ).not.toBeInTheDocument(),- );- });-- it("should allow disabling certain items in the collection picker", async () => {- act(() => {- setup({- initialValue: { id: 1, model: "collection" },- shouldDisableItem: () => true,- });- });-- const links = await screen.findAllByRole("link");- for (const link of links) {- expect(link).toHaveAttribute("data-disabled", "true");- }- });-});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsxsimilarity index 94%rename from frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.tsxrename to frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsxindex c45facdffd1..c55eff849d2 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.tsx+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/CollectionPicker.tsx@@ -7,24 +7,23 @@ import { useSelector } from "metabase/lib/redux";import { getUserPersonalCollectionId } from "metabase/selectors/user";import type { Collection, Dashboard } from "metabase-types/api";-import { LoadingSpinner, NestedItemPicker } from "../../../EntityPicker";-import { handleNewDashboard as handleNewDashboardUtil } from "../../DashboardPicker/utils";-import { useGetInitialContainer } from "../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../utils";-import { useEnsureCollectionSelected } from "../hooks";+import { LoadingSpinner, NestedItemPicker } from "../../../../EntityPicker";+import { handleNewDashboard as handleNewDashboardUtil } from "../../../DashboardPicker/utils";+import { useGetInitialContainer } from "../../../hooks";+import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";+import { useEnsureCollectionSelected } from "../../hooks";import type {CollectionPickerItem,CollectionPickerModel,CollectionPickerOptions,CollectionPickerStatePath,-} from "../types";+} from "../../types";import {getParentCollectionId,getPathLevelForItem,isFolderFactory,-} from "../utils";--import { CollectionItemPickerResolver } from "./CollectionItemPickerResolver";+} from "../../utils";+import { CollectionItemPickerResolver } from "../CollectionItemPickerResolver";const defaultOptions: CollectionPickerOptions = {showPersonalCollections: true,@@ -220,6 +219,7 @@ export const CollectionPickerInner = (const newPath = getStateFromIdPath({idPath: getCollectionIdPath({+ ...currentCollection,id: currentCollection.id,location: currentCollection.effective_location,is_personal: currentCollection.is_personal,diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.tsnew file mode 100644index 00000000000..ac7145e8390--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/index.ts@@ -0,0 +1 @@+export * from "./CollectionPicker";diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsxnew file mode 100644index 00000000000..62513c1e705--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/common.unit.spec.tsx@@ -0,0 +1,100 @@+import userEvent from "@testing-library/user-event";++import { act, screen, waitFor, within } from "__support__/ui";++import { setup } from "./setup";++describe("CollectionPicker", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("should select the root collection by default", async () => {+ act(() => {+ setup();+ });++ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 4/ }),+ ).toBeInTheDocument();++ expect(+ await screen.findByRole("link", { name: /Collection 2/ }),+ ).toBeInTheDocument();+ });++ it("should render the path to the value provided", async () => {+ act(() => {+ setup({ initialValue: { id: 3, model: "collection" } });+ });+ await screen.findByRole("link", { name: /Our Analytics/ });+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 4/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 3/ }),+ ).toHaveAttribute("data-active", "true");+ });++ it("should render the path back to personal collection", async () => {+ act(() => {+ setup({ initialValue: { id: 5, model: "collection" } });+ });+ expect(+ await screen.findByRole("link", { name: /My personal collection/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /personal sub_collection/ }),+ ).toHaveAttribute("data-active", "true");+ });++ it("should allow selecting, but not navigating into collections without children", async () => {+ act(() => {+ setup({ initialValue: { id: 1, model: "collection" } });+ });++ const personalSubCollectionButton = await screen.findByRole("link", {+ name: /personal sub_collection/,+ });+ expect(personalSubCollectionButton).not.toHaveAttribute("data-active");++ expect(+ within(personalSubCollectionButton).queryByLabelText("chevronright icon"),+ ).not.toBeInTheDocument();++ await userEvent.click(personalSubCollectionButton);++ expect(personalSubCollectionButton).toHaveAttribute("data-active", "true");++ // selecting an empty collection should not show another column+ await waitFor(() =>+ expect(+ screen.queryByTestId("item-picker-level-2"),+ ).not.toBeInTheDocument(),+ );+ });++ it("should allow disabling certain items in the collection picker", async () => {+ act(() => {+ setup({+ initialValue: { id: 1, model: "collection" },+ shouldDisableItem: () => true,+ });+ });++ const links = await screen.findAllByRole("link");+ for (const link of links) {+ expect(link).toHaveAttribute("data-disabled", "true");+ }+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsxnew file mode 100644index 00000000000..078acf4138d--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/enterprise.unit.spec.tsx@@ -0,0 +1,119 @@+import userEvent from "@testing-library/user-event";++import { screen, waitFor } from "__support__/ui";+import { PLUGIN_TENANTS } from "metabase/plugins";++import { type SetupOpts, setup as coreSetup } from "./setup";++const setup = (opts: SetupOpts = {}) => coreSetup({ ...opts, ee: true });++describe("tenant collections", () => {+ it("should show tenant collections in the root panel and build a path", async () => {+ setup();++ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toBeInTheDocument();++ await userEvent.click(+ screen.getByRole("link", { name: /Shared collections/ }),+ );++ expect(+ await screen.findByRole("link", { name: /tcoll/ }),+ ).toBeInTheDocument();++ await userEvent.click(screen.getByRole("link", { name: /tcol/ }));++ expect(+ await screen.findByRole("link", { name: /tsubcol/ }),+ ).toBeInTheDocument();+ });++ it("should handle a tenant collection as an initial value", async () => {+ setup({+ initialValue: {+ model: "collection",+ id: 7,+ },+ });++ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toHaveAttribute("data-active", "true");++ expect(await screen.findByRole("link", { name: /tcol/ })).toHaveAttribute(+ "data-active",+ "true",+ );++ expect(+ await screen.findByRole("link", { name: /tsubcol/ }),+ ).toHaveAttribute("data-active", "true");+ });+});++describe("restrictToNamespace option", () => {+ it("should only show tenant collections when restricted to shared-tenant-collection namespace", async () => {+ setup({+ options: {+ restrictToNamespace:+ PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE ?? undefined,+ },+ });++ // Tenant root should be visible+ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toBeInTheDocument();++ // Regular collections should NOT be visible+ await waitFor(() => {+ expect(+ screen.queryByRole("link", { name: /Our Analytics/ }),+ ).not.toBeInTheDocument();+ });+ expect(+ screen.queryByRole("link", { name: /My personal collection/ }),+ ).not.toBeInTheDocument();+ });++ it("should hide tenant collections when restricted to default namespace", async () => {+ setup({+ options: {+ restrictToNamespace: "default",+ showRootCollection: true,+ showPersonalCollections: true,+ },+ });++ // Regular collections should be visible+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toBeInTheDocument();++ // Tenant root should NOT be visible+ await waitFor(() => {+ expect(+ screen.queryByRole("link", { name: /Shared collections/ }),+ ).not.toBeInTheDocument();+ });+ });++ it("should show all collections when restrictToNamespace is not set", async () => {+ setup({+ options: {+ showRootCollection: true,+ showPersonalCollections: true,+ },+ });++ // Both regular and tenant collections should be visible+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsxnew file mode 100644index 00000000000..8e6610730bb--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker/tests/setup.tsx@@ -0,0 +1,286 @@+import fetchMock from "fetch-mock";+import { useState } from "react";++import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupCollectionItemsEndpoint,+ setupDatabaseListEndpoint,+ setupRootCollectionItemsEndpoint,+ setupTenantCollectionItemsEndpoint,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { mockGetBoundingClientRect, renderWithProviders } from "__support__/ui";+import type {+ Collection,+ CollectionId,+ CollectionItem,+} from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+ createMockSettings,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import type {+ CollectionPickerItem,+ CollectionPickerOptions,+ CollectionPickerStatePath,+} from "../../../types";+import { CollectionPicker } from "../CollectionPicker";++type MockCollection = {+ id: CollectionId;+ name: string;+ location: string | null;+ effective_location: string | null;+ is_personal: boolean;+ is_shared_tenant_collection?: boolean;+ collections: MockCollection[];+ here: CollectionItem["here"];+};++const collectionTree: MockCollection[] = [+ {+ id: "root",+ name: "Our Analytics",+ location: null,+ effective_location: null,+ is_personal: false,+ here: ["collection"],+ collections: [+ {+ id: 4,+ name: "Collection 4",+ location: "/",+ effective_location: "/",+ is_personal: false,+ here: ["collection"],+ collections: [+ {+ id: 3,+ name: "Collection 3",+ collections: [],+ location: "/4/",+ effective_location: "/4/",+ here: [],+ is_personal: false,+ },+ ],+ },+ {+ id: 2,+ is_personal: false,+ name: "Collection 2",+ location: "/",+ effective_location: "/",+ here: [],+ collections: [],+ },+ ],+ },+ {+ name: "My personal collection",+ id: 1,+ location: "/",+ effective_location: "/",+ is_personal: true,+ here: ["collection"],+ collections: [+ {+ id: 5,+ location: "/1/",+ effective_location: "/1/",+ name: "personal sub_collection",+ is_personal: true,+ here: [],+ collections: [],+ },+ ],+ },+];++const tenantCollectionsTree: MockCollection[] = [+ {+ name: "tcoll",+ id: 6,+ location: "/",+ effective_location: "/",+ is_personal: false,+ is_shared_tenant_collection: true,+ here: ["collection"],+ collections: [+ {+ id: 7,+ location: "/6/",+ effective_location: "/6/",+ name: "tsubcoll",+ is_personal: false,+ is_shared_tenant_collection: true,+ collections: [],+ here: [],+ },+ ],+ },+];++const flattenCollectionTree = (+ node: MockCollection[],+): Omit<MockCollection, "collections">[] => {+ return [+ ...node.map((n) => ({+ name: n.name,+ id: n.id,+ is_personal: !!n.is_personal,+ ...(n.is_shared_tenant_collection !== undefined && {+ is_shared_tenant_collection: n.is_shared_tenant_collection,+ }),+ location: n.location,+ effective_location: n.effective_location,+ here: n.here,+ })),+ ].concat(...node.map((n) => flattenCollectionTree(n.collections)));+};++const mockCollectionToCollectionItem = (c: MockCollection) =>+ createMockCollectionItem({+ id: c.id as number,+ name: c.name,+ model: "collection",+ location: c.location || "/",+ effective_location: c.effective_location || "/",+ here: c.here,+ ...(c.is_shared_tenant_collection && {+ namespace: "shared-tenant-collection",+ }),+ });++const setupCollectionTreeMocks = (node: MockCollection[]) => {+ node.forEach((n) => {+ const collectionItems = n.collections.map(mockCollectionToCollectionItem);++ // Skip root since it's handled separately (tenant-aware in EE mode)+ if (n.id !== "root") {+ setupCollectionItemsEndpoint({+ collection: createMockCollection({ id: n.id }),+ collectionItems,+ models: ["collection"],+ });+ }++ if (collectionItems.length > 0) {+ setupCollectionTreeMocks(n.collections);+ }+ });+};++const setupTenantCollectionTreeMocks = (node: MockCollection[]) => {+ node.forEach((n) => {+ const collectionItems = n.collections.map(mockCollectionToCollectionItem);++ setupTenantCollectionItemsEndpoint({+ collection: createMockCollection({ id: n.id }),+ collectionItems,+ models: ["collection"],+ });++ if (collectionItems.length > 0) {+ setupTenantCollectionTreeMocks(n.collections);+ }+ });+};++export interface SetupOpts {+ initialValue?: {+ id: CollectionId;+ model: "collection";+ };+ onItemSelect?: (item: CollectionPickerItem) => void;+ shouldDisableItem?: (item: CollectionPickerItem) => boolean;+ ee?: boolean;+ options?: CollectionPickerOptions;+}++export const setup = ({+ initialValue = { id: "root", model: "collection" },+ onItemSelect = jest.fn<void, [CollectionPickerItem]>(),+ shouldDisableItem,+ ee = false,+ options,+}: SetupOpts = {}) => {+ mockGetBoundingClientRect();++ const allCollections = flattenCollectionTree(collectionTree).map((c) =>+ createMockCollection(c as Collection),+ );++ //Setup individual collection mocks+ allCollections.forEach((collection) => {+ fetchMock.get(`path:/api/collection/${collection.id}`, collection);+ });++ setupCollectionTreeMocks(collectionTree);++ setupRootCollectionItemsEndpoint({+ rootCollectionItems: collectionTree[0].collections.map(+ mockCollectionToCollectionItem,+ ),+ tenantRootItems: ee+ ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]+ : [],+ });++ setupDatabaseListEndpoint([]);++ const settings = mockSettings(+ createMockSettings({+ "token-features": createMockTokenFeatures({+ tenants: ee ? true : false,+ }),+ "use-tenants": ee ? true : false,+ }),+ );++ // Update root mock to handle tenant namespace in EE mode+ if (ee) {+ setupEnterprisePlugins();+ setupTenantCollectionTreeMocks(tenantCollectionsTree);++ const allTenantCollections = flattenCollectionTree(tenantCollectionsTree);++ //Setup individual collection mocks+ allTenantCollections.forEach((collection) => {+ fetchMock.get(`path:/api/collection/${collection.id}`, {+ ...collection,+ namespace: "shared-tenant-collection",+ });+ });+ }++ function TestComponent() {+ const [path, setPath] = useState<CollectionPickerStatePath>();++ const handlePathChange = (newPath: CollectionPickerStatePath) => {+ setPath(newPath);+ };++ return (+ <CollectionPicker+ initialValue={initialValue}+ path={path}+ onInit={jest.fn()}+ onItemSelect={onItemSelect}+ onPathChange={handlePathChange}+ shouldDisableItem={shouldDisableItem}+ options={options}+ />+ );+ }++ return renderWithProviders(<TestComponent />, {+ storeInitialState: createMockState({+ settings,+ }),+ });+};diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsxindex 328b7699c0a..6b401f00c17 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsx+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPickerModal.tsx@@ -18,6 +18,7 @@ import {} from "../../../EntityPicker";import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";import { NewDashboardDialog } from "../../DashboardPicker/components/NewDashboardDialog";+import { getNamespaceForItem, isNamespaceRoot } from "../../utils";import type {CollectionPickerItem,CollectionPickerModel,@@ -27,7 +28,7 @@ import type {} from "../types";import { getCollectionType } from "../types";-import { CollectionPicker } from "./CollectionPicker";+import { CollectionPicker } from "./CollectionPicker/CollectionPicker";import { NewCollectionDialog } from "./NewCollectionDialog";export interface CollectionPickerModalProps {@@ -129,6 +130,9 @@ export const CollectionPickerModal = ({const [selectedItem, setSelectedItem] = useState<CollectionPickerItem | null>(null,);++ // canSelectItem determines if the Confirm button should be enabled+ // Namespace roots can be navigated into but not selected as final destinationsconst canSelectItem = useCallback((item:@@ -151,9 +155,18 @@ export const CollectionPickerModal = ({}}+ // Check if namespace root is disallowed for this savingModel+ if (+ options.savingModel &&+ options.savingModel !== "collection" &&+ isNamespaceRoot(item as CollectionPickerItem)+ ) {+ return false;+ }+return true;},- [_canSelectItem, entityType],+ [_canSelectItem, entityType, options.savingModel],);const { tryLogRecentItem } = useLogRecentItem();@@ -218,7 +231,10 @@ export const CollectionPickerModal = ({miw="9.5rem"onClick={openCreateDashboardDialog}leftSection={<Icon name="add_to_dash" />}- disabled={selectedItem?.can_write === false}+ disabled={Boolean(+ selectedItem?.can_write === false ||+ (selectedItem && isNamespaceRoot(selectedItem)),+ )}>{t`New dashboard`}</Button>@@ -297,7 +313,13 @@ export const CollectionPickerModal = ({);const parentCollectionId = useMemo(() => {- if (canSelectItem(selectedItem)) {+ if (+ selectedItem &&+ isNamespaceRoot(selectedItem) &&+ selectedItem.can_write+ ) {+ return selectedItem.id;+ } else if (canSelectItem(selectedItem)) {return selectedItem.model === "dashboard"? selectedItem.collection_id: selectedItem.id;@@ -308,6 +330,18 @@ export const CollectionPickerModal = ({}}, [selectedItem, value, canSelectItem]);+ // Determine the effective namespace for creating new collections+ // Priority: 1) options.namespace (explicit), 2) selectedItem namespace, 3) undefined+ const effectiveNamespace = useMemo(() => {+ // If explicitly set in options, use that+ if (options.namespace) {+ return options.namespace;+ }++ // Get namespace from the currently selected item+ return getNamespaceForItem(selectedItem);+ }, [options.namespace, selectedItem]);+return (<><EntityPickerModal@@ -336,7 +370,7 @@ export const CollectionPickerModal = ({onClose={closeCreateCollectionDialog}parentCollectionId={parentCollectionId}onNewCollection={handleNewCollectionCreate}- namespace={options.namespace}+ namespace={effectiveNamespace}/><NewDashboardDialogisOpen={isCreateDashboardDialogOpen}diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsxindex be41c5f8513..3af1950e95e 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsx+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/NewCollectionDialog.tsx@@ -13,7 +13,7 @@ import {} from "metabase/forms";import * as Errors from "metabase/lib/errors";import { Button, Flex, Modal } from "metabase/ui";-import type { CollectionId } from "metabase-types/api";+import type { CollectionId, CollectionNamespace } from "metabase-types/api";import type { CollectionPickerItem } from "../types";@@ -29,7 +29,7 @@ interface NewCollectionDialogProps {onClose: () => void;parentCollectionId: CollectionId | null;onNewCollection: (item: CollectionPickerItem) => void;- namespace?: "snippets";+ namespace?: CollectionNamespace;}export const NewCollectionDialog = ({@@ -42,9 +42,14 @@ export const NewCollectionDialog = ({const [createCollection] = useCreateCollectionMutation();const onCreateNewCollection = async ({ name }: { name: string }) => {+ // Virtual collection IDs like "root" and "tenant" should be converted to null+ // These represent namespace roots which have no parent+ const isVirtualRoot =+ parentCollectionId === "root" || parentCollectionId === "tenant";+const newCollection = await createCollection({name,- parent_id: parentCollectionId === "root" ? null : parentCollectionId,+ parent_id: isVirtualRoot ? null : parentCollectionId,namespace,}).unwrap();diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.tsindex 3018bd8b03c..d02c6dfd850 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts@@ -8,9 +8,10 @@ import {useListDatabasesQuery,} from "metabase/api";import { isRootCollection } from "metabase/collections/utils";+import { useSetting } from "metabase/common/hooks";import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";import { useSelector } from "metabase/lib/redux";-import { PLUGIN_DATA_STUDIO } from "metabase/plugins";+import { PLUGIN_DATA_STUDIO, PLUGIN_TENANTS } from "metabase/plugins";import { getUser, getUserIsAdmin } from "metabase/selectors/user";import type { Collection, Dashboard } from "metabase-types/api";@@ -26,6 +27,22 @@ const personalCollectionsRoot: CollectionPickerItem = {below: ["collection"],};+const getTenantSpecificCollectionsRoot = (): CollectionPickerItem | null => {+ const base = PLUGIN_TENANTS.TENANT_SPECIFIC_COLLECTIONS;+ if (!base) {+ return null;+ }+ return {+ ...base,+ can_write: false,+ model: "collection",+ location: "/",+ description: "",+ here: ["collection", "card", "dashboard"],+ below: ["collection"],+ };+};+/*** This is a special item list that exists "above" our analytics and might include:* a) the highest-level collections the user can access (often "our analytics")@@ -41,6 +58,7 @@ export const useRootCollectionPickerItems = (const { data: databaseData, isLoading: isLoadingDatabases } =useListDatabasesQuery(undefined, { skip: !options.showDatabases });const databases = databaseData?.data ?? [];+ const tenantsEnabled = useSetting("use-tenants");const { data: personalCollection, isLoading: isLoadingPersonalCollecton } =useGetCollectionQuery(@@ -77,6 +95,24 @@ export const useRootCollectionPickerItems = (const items = useMemo(() => {const collectionItems: CollectionPickerItem[] = [];+ if (+ options?.restrictToNamespace === PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE+ ) {+ if (tenantsEnabled && currentUser) {+ collectionItems.push({+ name: t`Shared collections`,+ id: "tenant",+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ here: ["collection", "card", "dashboard"],+ description: null,+ can_write: true,+ model: "collection",+ location: "/",+ });+ }+ return collectionItems;+ }+if (options.showLibrary &&libraryCollection &&@@ -89,7 +125,7 @@ export const useRootCollectionPickerItems = (});}- if (options.showDatabases && databases.length > 0) {+ if (options?.showDatabases && databases.length > 0) {collectionItems.push({id: "databases",name: t`Databases`,@@ -101,7 +137,7 @@ export const useRootCollectionPickerItems = (});}- if (options.showRootCollection || options.namespace === "snippets") {+ if (options?.showRootCollection || options?.namespace === "snippets") {if (rootCollection && !rootCollectionError) {collectionItems.push({...rootCollection,@@ -127,8 +163,8 @@ export const useRootCollectionPickerItems = (}if (- options.showPersonalCollections &&- options.namespace !== "snippets" &&+ options?.showPersonalCollections &&+ options?.namespace !== "snippets" &¤tUser &&!!personalCollection) {@@ -144,6 +180,47 @@ export const useRootCollectionPickerItems = (}}+ // Only show tenant collections if NOT restricted to a different namespace+ // When restrictToNamespace is "default", we exclude tenant collections+ const shouldShowTenantCollections =+ tenantsEnabled &&+ currentUser &&+ options?.restrictToNamespace !== "default";++ if (shouldShowTenantCollections) {+ collectionItems.push({+ name: t`Shared collections`,+ id: "tenant",+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ here: ["collection", "card", "dashboard"],+ description: null,+ can_write: true,+ model: "collection",+ location: "/",+ });+ }++ const userTenantCollectionId = currentUser?.tenant_collection_id;+ if (shouldShowTenantCollections && userTenantCollectionId) {+ collectionItems.push({+ name: t`My Tenant Collection`,+ id: userTenantCollectionId,+ here: ["collection", "card", "dashboard"],+ description: null,+ can_write: true,+ model: "collection",+ location: "/",+ type: "tenant-specific-root-collection",+ });+ }++ if (shouldShowTenantCollections && isAdmin) {+ const tenantSpecificRoot = getTenantSpecificCollectionsRoot();+ if (tenantSpecificRoot) {+ collectionItems.push(tenantSpecificRoot);+ }+ }+return collectionItems;}, [currentUser,@@ -155,6 +232,7 @@ export const useRootCollectionPickerItems = (rootCollectionError,totalPersonalCollectionItems,libraryCollection,+ tenantsEnabled,]);const isLoading =diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.tsindex 2971f502ca5..d1a7b483e91 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts@@ -1,7 +1,9 @@import type {CardId,CollectionId,+ CollectionItem,CollectionItemModel,+ CollectionNamespace,CollectionType,DashboardId,ListCollectionItemsRequest,@@ -37,6 +39,14 @@ export type CollectionPickerItem = TypeWithModel<Pick<Partial<SearchResult>,"description" | "can_write" | "database_id" | "collection_type"+ > &+ Partial<+ Pick<+ CollectionItem,+ | "is_shared_tenant_collection"+ | "is_tenant_dashboard"+ | "collection_namespace"+ >> & {location?: string | null;effective_location?: string | null;@@ -45,6 +55,7 @@ export type CollectionPickerItem = TypeWithModel<here?: CollectionItemModel[];below?: CollectionItemModel[];type?: CollectionType;+ namespace?: CollectionNamespace;};/**@@ -70,11 +81,23 @@ export type CollectionPickerValueItem =});export type CollectionPickerOptions = EntityPickerModalOptions & {- namespace?: "snippets";+ namespace?: CollectionNamespace;allowCreateNew?: boolean;showPersonalCollections?: boolean;showRootCollection?: boolean;showLibrary?: boolean;+ /**+ * The type of item being saved. When set to a non-collection model,+ * namespace root collections (like tenant root) will be disabled.+ */+ savingModel?: "collection" | "dashboard" | "question" | "model";+ /**+ * Restricts the picker to only show collections in a specific namespace.+ * - When set to "shared-tenant-collection", only the tenant root is shown.+ * - When set to "default", the tenant root is hidden and regular collections are shown.+ * - When undefined, all roots are shown (default behavior).+ */+ restrictToNamespace?: string;};export type CollectionItemListProps = ListProps<diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.tsindex 139a0f3cf18..4dcbc2154dc 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.ts@@ -1,6 +1,7 @@import type {CollectionId,CollectionItemModel,+ CollectionNamespace,ListCollectionItemsRequest,} from "metabase-types/api";@@ -20,9 +21,23 @@ export const isFolderFactory =export const getParentCollectionId = (location?: string | null,+ namespace?: CollectionNamespace | null,+ type?: string | null,): CollectionId => {const parentCollectionId = location?.split("/").filter(Boolean).reverse()[0];- return parentCollectionId ? Number(parentCollectionId) : "root";+ if (parentCollectionId) {+ return Number(parentCollectionId);+ }++ if (namespace === "shared-tenant-collection") {+ return "tenant";+ }++ if (type === "tenant-specific-root-collection") {+ return "tenant-specific";+ }++ return "root";};export const getPathLevelForItem = (@@ -44,7 +59,11 @@ export const getPathLevelForItem = (const parentCollectionId =item.collection_id ??- getParentCollectionId(item?.effective_location ?? item?.location);+ getParentCollectionId(+ item?.effective_location ?? item?.location,+ item?.namespace,+ item?.type,+ );// set selected item at the correct levelconst pathLevel = path.findIndex(diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.tsindex 215dde9976d..05ae241b25a 100644--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.ts+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/utils.unit.spec.ts@@ -13,5 +13,43 @@ describe("CollectionPicker > utils", () => {expect(getParentCollectionId("1/2/3/4/5")).toEqual(5);expect(getParentCollectionId("/100/200/300/400/500/")).toEqual(500);});++ it.each([+ {+ location: "/",+ namespace: "shared-tenant-collection" as const,+ type: null,+ desc: "shared tenant",+ expected: "tenant",+ },+ {+ location: null,+ namespace: "shared-tenant-collection" as const,+ type: null,+ desc: "shared tenant",+ expected: "tenant",+ },+ {+ location: "/",+ namespace: null,+ type: "tenant-specific-root-collection",+ desc: "dedicated tenant",+ expected: "tenant-specific",+ },+ {+ location: null,+ namespace: null,+ type: "tenant-specific-root-collection",+ desc: "dedicated tenant",+ expected: "tenant-specific",+ },+ ])(+ "should return $expected for top-level $desc collection at $location",+ ({ location, namespace, type, expected }) => {+ expect(getParentCollectionId(location, namespace, type)).toEqual(+ expected,+ );+ },+ );});});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsxsimilarity index 88%rename from frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.tsxrename to frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsxindex ae48c546e44..17ed3c9d457 100644--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.tsx+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/DashboardPicker.tsx@@ -7,20 +7,20 @@ import { useSelector } from "metabase/lib/redux";import { getUserPersonalCollectionId } from "metabase/selectors/user";import type { CollectionItemModel, Dashboard } from "metabase-types/api";-import { LoadingSpinner, NestedItemPicker } from "../../../EntityPicker";-import { CollectionItemPickerResolver } from "../../CollectionPicker/components/CollectionItemPickerResolver";-import { getPathLevelForItem } from "../../CollectionPicker/utils";-import { useGetInitialContainer } from "../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../utils";+import { LoadingSpinner, NestedItemPicker } from "../../../../EntityPicker";+import { CollectionItemPickerResolver } from "../../../CollectionPicker/components/CollectionItemPickerResolver";+import { getPathLevelForItem } from "../../../CollectionPicker/utils";+import { useGetInitialContainer } from "../../../hooks";+import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";import type {DashboardPickerItem,DashboardPickerOptions,DashboardPickerStatePath,-} from "../types";+} from "../../types";import {handleNewDashboard as handleNewDashboardUtil,isFolder,-} from "../utils";+} from "../../utils";export const defaultOptions: DashboardPickerOptions = {showPersonalCollections: true,@@ -131,10 +131,7 @@ const DashboardPickerInner = (if (currentCollection?.id) {const idPath = getCollectionIdPath({- id: currentCollection.id,- location: currentCollection.effective_location,- is_personal: currentCollection.is_personal,- type: currentCollection.type,+ ...currentCollection,model: "collection",},userPersonalCollectionId,diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.ts b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.tsnew file mode 100644index 00000000000..5df0b889dd5--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/index.ts@@ -0,0 +1 @@+export * from "./DashboardPicker";diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsxnew file mode 100644index 00000000000..f408afc7f89--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/common.unit.spec.tsx@@ -0,0 +1,142 @@+import userEvent from "@testing-library/user-event";++import { screen } from "__support__/ui";++import { defaultOptions } from "../DashboardPicker";++import { setupModal, setupPicker } from "./setup";++describe("DashboardPicker", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("should select the root collection by default", async () => {+ await setupPicker();++ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 4/ }),+ ).toBeInTheDocument();++ expect(+ await screen.findByRole("link", { name: /Collection 2/ }),+ ).toBeInTheDocument();+ });++ it("should render the path to the collection provided", async () => {+ await setupPicker({ initialValue: { id: 3, model: "collection" } });+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 4/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 3/ }),+ ).toHaveAttribute("data-active", "true");+ });++ it("should render the path to the dashboard provided", async () => {+ await setupPicker({ initialValue: { id: 100, model: "dashboard" } });++ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 4/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Collection 3/ }),+ ).toHaveAttribute("data-active", "true");++ // dashboard itself should start selected+ expect(+ await screen.findByRole("link", { name: /My Dashboard 1/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /My Dashboard 2/ }),+ ).not.toHaveAttribute("data-active", "true");+ });+});++describe("DashboardPickerModal", () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it("should render the modal", async () => {+ await setupModal();++ expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toBeInTheDocument();++ expect(screen.getByRole("button", { name: /Select/ })).toBeInTheDocument();+ });++ it("should render the modal with no select button", async () => {+ await setupModal({+ options: { ...defaultOptions, hasConfirmButtons: false },+ });++ expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Select/ }),+ ).not.toBeInTheDocument();+ });++ it("should render no tabs by default", async () => {+ await setupModal();++ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ });++ it("should automatically switch to the search tab when a search query is provided", async () => {+ await setupModal();++ const searchInput = await screen.findByPlaceholderText(/search/i);++ await userEvent.type(searchInput, "sizzlipede");++ expect(+ await screen.findByRole("tab", { name: /Dashboards/ }),+ ).toHaveAttribute("aria-selected", "false");+ expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(+ "aria-selected",+ "true",+ );+ });++ it("should switch back to not having tabs when the search query is cleared", async () => {+ await setupModal();++ const searchInput = await screen.findByPlaceholderText(/search/i);++ await userEvent.type(searchInput, "sizzlipede");++ expect(+ await screen.findByRole("tab", { name: /Dashboards/ }),+ ).toHaveAttribute("aria-selected", "false");+ expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(+ "aria-selected",+ "true",+ );++ await userEvent.clear(searchInput);++ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsxnew file mode 100644index 00000000000..85b709596a6--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/enterprise.unit.spec.tsx@@ -0,0 +1,53 @@+import userEvent from "@testing-library/user-event";++import { screen } from "__support__/ui";++import { type SetupOpts, setupPicker } from "./setup";++const setup = (opts: SetupOpts = {}) => setupPicker({ ...opts, ee: true });++describe("tenant collections", () => {+ it("should show tenant collections in the root panel and build a path to a dashboard", async () => {+ await setup();++ await userEvent.click(+ await screen.findByRole("link", { name: /Shared collections/ }),+ );++ await userEvent.click(await screen.findByRole("link", { name: /tcoll/ }));++ await userEvent.click(+ await screen.findByRole("link", { name: /tsubcoll/ }),+ );++ expect(+ await screen.findByRole("link", { name: /Shared Dashboard/ }),+ ).toBeInTheDocument();+ });++ it("should handle a tenant tenant as an initial value", async () => {+ await setup({+ initialValue: {+ model: "dashboard",+ id: 102,+ },+ });++ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toHaveAttribute("data-active", "true");++ expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(+ "data-active",+ "true",+ );++ expect(+ await screen.findByRole("link", { name: /tsubcoll/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Shared Dashboard/ }),+ ).toHaveAttribute("data-active", "true");+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsxsimilarity index 52%rename from frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsxrename to frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsxindex ccc057593ce..674fa7aec27 100644--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker/tests/setup.tsx@@ -1,17 +1,19 @@-import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { useState } from "react";+import { setupEnterprisePlugins } from "__support__/enterprise";import {setupCollectionItemsEndpoint,setupDatabasesEndpoints,setupRecentViewsAndSelectionsEndpoints,+ setupRootCollectionItemsEndpoint,setupSearchEndpoints,+ setupTenantCollectionItemsEndpoint,} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";import {mockGetBoundingClientRect,renderWithProviders,- screen,waitForLoaderToBeRemoved,} from "__support__/ui";import type {@@ -23,16 +25,18 @@ import {createMockCollection,createMockCollectionItem,createMockDashboard,+ createMockSettings,+ createMockTokenFeatures,} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";import type {DashboardPickerItem,DashboardPickerStatePath,DashboardPickerValueModel,-} from "../types";--import { DashboardPicker, defaultOptions } from "./DashboardPicker";-import { DashboardPickerModal } from "./DashboardPickerModal";+} from "../../../types";+import { DashboardPickerModal } from "../../DashboardPickerModal";+import { DashboardPicker, defaultOptions } from "../DashboardPicker";type NestedCollectionItem = Partial<Omit<CollectionItem, "id">> & {id: any;@@ -52,6 +56,12 @@ const myDashboard2 = createMockDashboard({collection_id: 3,});+const sharedTenantDashboard = createMockDashboard({+ id: 102,+ name: "Shared Dashboard",+ collection_id: 7,+});+const collectionTree: NestedCollectionItem[] = [{id: "root",@@ -126,6 +136,42 @@ const collectionTree: NestedCollectionItem[] = [},];+const tenantCollectionsTree: NestedCollectionItem[] = [+ {+ name: "tcoll",+ id: 6,+ location: "/",+ effective_location: "/",+ is_personal: false,+ is_shared_tenant_collection: true,+ model: "collection",+ here: ["collection"],+ below: ["dashboard"],+ can_write: true,+ descendants: [+ {+ id: 7,+ location: "/6/",+ effective_location: "/6/",+ name: "tsubcoll",+ model: "collection",+ is_personal: false,+ is_shared_tenant_collection: true,+ can_write: true,+ descendants: [+ {+ ...sharedTenantDashboard,+ model: "dashboard",+ is_tenant_dashboard: true,+ descendants: [],+ },+ ],+ here: ["dashboard"],+ },+ ],+ },+];+const flattenCollectionTree = (nodes: NestedCollectionItem[],): Omit<NestedCollectionItem, "descendants">[] => {@@ -138,6 +184,14 @@ const flattenCollectionTree = (]);};+const mockCollectionToCollectionItem = (c: NestedCollectionItem) =>+ createMockCollectionItem({+ ...c,+ ...(c.is_shared_tenant_collection && {+ namespace: "shared-tenant-collection",+ }),+ });+const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {node.forEach((node) => {if (!node.descendants) {@@ -147,19 +201,40 @@ const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {createMockCollectionItem(c),);- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: node.id }),+ // Skip root since it's handled separately (tenant-aware)+ if (node.id !== "root") {+ setupCollectionItemsEndpoint({+ collection: createMockCollection({ id: node.id }),+ collectionItems,+ models: ["collection", "dashboard"],+ });+ }++ if (collectionItems.length > 0) {+ setupCollectionTreeMocks(node.descendants);+ }+ });+};++const setupTenantCollectionTreeMocks = (node: NestedCollectionItem[]): void => {+ node.forEach((n) => {+ const collectionItems = n.descendants.map((c: NestedCollectionItem) =>+ mockCollectionToCollectionItem(c),+ );++ setupTenantCollectionItemsEndpoint({+ collection: createMockCollection({ id: n.id }),collectionItems,models: ["collection", "dashboard"],});if (collectionItems.length > 0) {- setupCollectionTreeMocks(node.descendants);+ setupTenantCollectionTreeMocks(n.descendants);}});};-interface SetupOpts {+export interface SetupOpts {initialValue?: {id: CollectionId | DashboardId;model: "collection" | "dashboard";@@ -167,9 +242,10 @@ interface SetupOpts {onChange?: (item: DashboardPickerItem) => void;models?: [DashboardPickerValueModel, ...DashboardPickerValueModel[]];options?: typeof defaultOptions;+ ee?: boolean;}-const commonSetup = () => {+const commonSetup = ({ ee = false }: { ee?: boolean } = {}) => {setupRecentViewsAndSelectionsEndpoints([]);mockGetBoundingClientRect();setupSearchEndpoints([]);@@ -188,13 +264,53 @@ const commonSetup = () => {});setupCollectionTreeMocks(collectionTree);++ // Setup root collection items endpoint (handles both regular and tenant requests)+ setupRootCollectionItemsEndpoint({+ rootCollectionItems: collectionTree[0].descendants.map(+ createMockCollectionItem,+ ),+ tenantRootItems: ee+ ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]+ : [],+ });++ if (ee) {+ const allTenantItems = flattenCollectionTree(tenantCollectionsTree).map(+ createMockCollectionItem,+ );++ setupEnterprisePlugins();+ setupTenantCollectionTreeMocks(tenantCollectionsTree);++ allTenantItems.forEach((item) => {+ if (item.model !== "collection") {+ fetchMock.get(`path:/api/dashboard/${item.id}`, item);+ } else {+ fetchMock.get(`path:/api/collection/${item.id}`, {+ ...item,+ namespace: "shared-tenant-collection",+ });+ }+ });+ }};-const setupPicker = async ({+export const setupPicker = async ({initialValue = { id: "root", model: "collection" },onChange = jest.fn<void, [DashboardPickerItem]>(),+ ee = false,}: SetupOpts = {}) => {- commonSetup();+ const settings = mockSettings(+ createMockSettings({+ "token-features": createMockTokenFeatures({+ tenants: ee ? true : false,+ }),+ "use-tenants": ee,+ }),+ );++ commonSetup({ ee });function TestComponent() {const [path, setPath] = useState<DashboardPickerStatePath>();@@ -210,12 +326,14 @@ const setupPicker = async ({);}- renderWithProviders(<TestComponent />);+ renderWithProviders(<TestComponent />, {+ storeInitialState: createMockState({ settings }),+ });await waitForLoaderToBeRemoved();};-const setupModal = async ({+export const setupModal = async ({initialValue,onChange = jest.fn<void, [DashboardPickerItem]>(),options = defaultOptions,@@ -233,138 +351,3 @@ const setupModal = async ({await waitForLoaderToBeRemoved();};--describe("DashboardPicker", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should select the root collection by default", async () => {- await setupPicker();-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toBeInTheDocument();-- expect(- await screen.findByRole("link", { name: /Collection 2/ }),- ).toBeInTheDocument();- });-- it("should render the path to the collection provided", async () => {- await setupPicker({ initialValue: { id: 3, model: "collection" } });- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");- });-- it("should render the path to the dashboard provided", async () => {- await setupPicker({ initialValue: { id: 100, model: "dashboard" } });-- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 4/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /Collection 3/ }),- ).toHaveAttribute("data-active", "true");-- // dashboard itself should start selected- expect(- await screen.findByRole("link", { name: /My Dashboard 1/ }),- ).toHaveAttribute("data-active", "true");-- expect(- await screen.findByRole("link", { name: /My Dashboard 2/ }),- ).not.toHaveAttribute("data-active", "true");- });-});--describe("DashboardPickerModal", () => {- afterEach(() => {- jest.restoreAllMocks();- });-- it("should render the modal", async () => {- await setupModal();-- expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();-- expect(screen.getByRole("button", { name: /Select/ })).toBeInTheDocument();- });-- it("should render the modal with no select button", async () => {- await setupModal({- options: { ...defaultOptions, hasConfirmButtons: false },- });-- expect(await screen.findByText(/choose a dashboard/i)).toBeInTheDocument();- expect(- await screen.findByRole("link", { name: /Our Analytics/ }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /Select/ }),- ).not.toBeInTheDocument();- });-- it("should render no tabs by default", async () => {- await setupModal();-- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-- it("should automatically switch to the search tab when a search query is provided", async () => {- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Dashboards/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );- });-- it("should switch back to not having tabs when the search query is cleared", async () => {- await setupModal();-- const searchInput = await screen.findByPlaceholderText(/search/i);-- await userEvent.type(searchInput, "sizzlipede");-- expect(- await screen.findByRole("tab", { name: /Dashboards/ }),- ).toHaveAttribute("aria-selected", "false");- expect(await screen.findByRole("tab", { name: /Search/ })).toHaveAttribute(- "aria-selected",- "true",- );-- await userEvent.clear(searchInput);-- expect(screen.queryByRole("tab")).not.toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsxindex 94b3b797b3c..c2fe6951bdd 100644--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsx+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPickerModal.tsx@@ -12,6 +12,7 @@ import {defaultOptions as defaultEntityPickerOptions,} from "../../../EntityPicker";import { useLogRecentItem } from "../../../EntityPicker/hooks/use-log-recent-item";+import { isNamespaceRoot } from "../../utils";import type {DashboardPickerInitialValueItem,DashboardPickerItem,@@ -24,7 +25,7 @@ import { getCollectionId } from "../utils";import {DashboardPicker,defaultOptions as defaultDashboardPickerOptions,-} from "./DashboardPicker";+} from "./DashboardPicker/DashboardPicker";import { NewDashboardDialog } from "./NewDashboardDialog";export interface DashboardPickerModalProps {@@ -150,7 +151,10 @@ export const DashboardPickerModal = ({miw="9.5rem"onClick={openCreateDialog}leftSection={<Icon name="add_to_dash" />}- disabled={selectedItem?.can_write === false}+ disabled={Boolean(+ selectedItem?.can_write === false ||+ (selectedItem && isNamespaceRoot(selectedItem)),+ )}>{t`New dashboard`}</Button>,diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsxindex 14869bd8747..21033adc75e 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/ee.unit.spec.tsx@@ -35,7 +35,7 @@ const LIBRARY_METRICS_COLLECTION = createMockCollectionItem({describe("library", () => {it("should default to the library if it's available", async () => {- fetchMock.get("/api/ee/library", LIBRARY_COLLECTION);+ fetchMock.get("path:/api/ee/library", LIBRARY_COLLECTION);setupCollectionItemsEndpoint({collection: LIBRARY_COLLECTION,collectionItems: [LIBRARY_DATA_COLLECTION, LIBRARY_METRICS_COLLECTION],@@ -51,7 +51,7 @@ describe("library", () => {});it("should hide an empty library collection", async () => {- fetchMock.get("/api/ee/library", {+ fetchMock.get("path:/api/ee/library", {...LIBRARY_COLLECTION,below: [],});@@ -100,7 +100,7 @@ describe("library", () => {});it("should hide respect the shouldShowLibrary prop", async () => {- fetchMock.get("/api/ee/library", LIBRARY_COLLECTION);+ fetchMock.get("path:/api/ee/library", LIBRARY_COLLECTION);setupCollectionItemsEndpoint({collection: LIBRARY_COLLECTION,collectionItems: [LIBRARY_DATA_COLLECTION, LIBRARY_METRICS_COLLECTION],diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsxsimilarity index 89%rename from frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsxrename to frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsxindex 403bd7b6cac..87a524ee0ed 100644--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/QuestionPicker.tsx@@ -2,31 +2,35 @@ import { useCallback, useMemo } from "react";import { useDeepCompareEffect } from "react-use";import { useSelector } from "metabase/lib/redux";+import { PLUGIN_TENANTS } from "metabase/plugins";import { getUserPersonalCollectionId } from "metabase/selectors/user";-import { DelayedLoadingSpinner, NestedItemPicker } from "../../../EntityPicker";-import { useEnsureCollectionSelected } from "../../CollectionPicker";-import { CollectionItemPickerResolver } from "../../CollectionPicker/components/CollectionItemPickerResolver";-import { getPathLevelForItem } from "../../CollectionPicker/utils";+import {+ DelayedLoadingSpinner,+ NestedItemPicker,+} from "../../../../EntityPicker";+import { useEnsureCollectionSelected } from "../../../CollectionPicker";+import { CollectionItemPickerResolver } from "../../../CollectionPicker/components/CollectionItemPickerResolver";+import { getPathLevelForItem } from "../../../CollectionPicker/utils";import {type TablePickerItem,type TablePickerStatePath,type TablePickerValue,isTablePickerValue,-} from "../../TablePicker";-import { useGetInitialContainer } from "../../hooks";-import { getCollectionIdPath, getStateFromIdPath } from "../../utils";+} from "../../../TablePicker";+import { useGetInitialContainer } from "../../../hooks";+import { getCollectionIdPath, getStateFromIdPath } from "../../../utils";import type {QuestionPickerItem,QuestionPickerModel,QuestionPickerOptions,QuestionPickerStatePath,-} from "../types";+} from "../../types";import {getQuestionPickerValueModel,isFolder,isTablePickerFolderOrQuestionPickerFolder,-} from "../utils";+} from "../../utils";export const defaultOptions: QuestionPickerOptions = {showPersonalCollections: true,@@ -129,6 +133,9 @@ export const QuestionPicker = ({...currentDashboard,model: "dashboard",location,+ is_tenant_dashboard: PLUGIN_TENANTS.isTenantNamespace(+ currentDashboard?.collection?.namespace,+ ),},userPersonalCollectionId,);diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.tsnew file mode 100644index 00000000000..a438a409353--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/index.ts@@ -0,0 +1 @@+export * from "./QuestionPicker";diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsxsimilarity index 51%rename from frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsxrename to frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsxindex cc78047e157..43d70bc0ac3 100644--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/common.unit.spec.tsx@@ -1,373 +1,22 @@import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";-import { useState } from "react";-import { setupEnterprisePlugins } from "__support__/enterprise";-import {- setupCollectionItemsEndpoint,- setupDashboardItemsEndpoint,- setupDatabasesEndpoints,- setupRecentViewsAndSelectionsEndpoints,- setupSearchEndpoints,-} from "__support__/server-mocks";-import { mockSettings } from "__support__/settings";-import {- mockGetBoundingClientRect,- renderWithProviders,- screen,- waitForLoaderToBeRemoved,- within,-} from "__support__/ui";-import type {- CollectionId,- CollectionItem,- TokenFeatures,-} from "metabase-types/api";-import {- createMockCard,- createMockCollection,- createMockCollectionItem,- createMockDashboard,- createMockSettings,- createMockTokenFeatures,-} from "metabase-types/api/mocks";-import { createMockState } from "metabase-types/store/mocks";--import type {- QuestionPickerItem,- QuestionPickerStatePath,- QuestionPickerValueModel,-} from "../types";--import { QuestionPicker, defaultOptions } from "./QuestionPicker";-import { QuestionPickerModal } from "./QuestionPickerModal";--type NestedCollectionItem = Partial<CollectionItem> & {- id: any;- is_personal?: boolean;- descendants?: NestedCollectionItem[];-};--const rootQuestion = createMockCollectionItem({- ...createMockCard({- id: 104,- name: "Question in Root",- collection_id: null,- }),- model: "card",-});--const rootDashboard = createMockCollectionItem({- ...createMockDashboard({- name: "Root Dashboard",- collection_id: null,- }),- id: 105,- location: "/",- model: "dashboard",-});--const rootDashboardQuestion = createMockCollectionItem({- ...createMockCard({- id: 107,- name: "DQ in Root",- collection_id: null,- dashboard_id: rootDashboard.id,- }),- model: "card",-});--const nestedQuestion = createMockCollectionItem({- ...createMockCard({- id: 100,- name: "Nested Question",- collection_id: 3,- }),- model: "card",-});--const nestedDashboard = createMockCollectionItem({- ...createMockDashboard({- name: "Nested Dashboard",- collection_id: 3,- collection: createMockCollection({- id: 3,- location: "/4/",- }),- }),- location: "/4/",- id: 106,- model: "dashboard",-});--const nestedDashboardQuestion = createMockCollectionItem({- ...createMockCard({- id: 108,- name: "Nested DQ",- collection_id: 3,- dashboard_id: nestedDashboard.id,- dashboard: nestedDashboard,- }),- model: "card",-});--const myVerifiedQuestion = createMockCollectionItem({- ...createMockCard({- id: 103,- name: "My Verified Question",- collection_id: 3,- }),- moderated_status: "verified",-});--const myModel = createMockCollectionItem({- ...createMockCard({- id: 101,- name: "My Model",- collection_id: 3,- type: "model",- }),- model: "dataset",-});--const myMetric = createMockCollectionItem({- ...createMockCard({- id: 102,- name: "My Metric",- collection_id: 3,- type: "metric",- }),- model: "metric",-});--const collectionTree: NestedCollectionItem[] = [- {- id: "root" as any,- model: "collection",- name: "Our Analytics",- location: "",- can_write: true,- descendants: [- {- id: 4,- name: "Collection 4",- model: "collection",- location: "/",- can_write: true,- descendants: [- {- id: 3,- name: "Collection 3",- model: "collection",- descendants: [- nestedQuestion,- nestedDashboard,- nestedDashboardQuestion,- myModel,- myMetric,- myVerifiedQuestion,- ],- location: "/4/",- can_write: true,- is_personal: false,- },- ],- },- {- id: 2,- model: "collection",- is_personal: false,- name: "Collection 2",- location: "/",- can_write: true,- descendants: [],- },- rootQuestion,- rootDashboard,- rootDashboardQuestion,- ],- },- {- name: "My personal collection",- id: 1,- model: "collection",- location: "/",- is_personal: true,- can_write: true,- descendants: [- {- id: 5,- model: "collection",- location: "/1/",- name: "personal sub_collection",- is_personal: true,- can_write: true,- descendants: [],- },- ],- },-];--const flattenCollectionTree = (- nodes: NestedCollectionItem[],-): Omit<NestedCollectionItem, "descendants">[] => {- if (!nodes) {- return [];- }- return nodes.flatMap(({ descendants = [], ...node }) => [- node,- ...flattenCollectionTree(descendants),- ]);-};--const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {- node.forEach((node) => {- if (!node.descendants) {- return;- }- const collectionItems = node.descendants.map((c: NestedCollectionItem) =>- createMockCollectionItem(c),- );-- setupCollectionItemsEndpoint({- collection: createMockCollection({ id: node.id }),- collectionItems,- });+import { setupSearchEndpoints } from "__support__/server-mocks";+import { screen } from "__support__/ui";- if (collectionItems.length > 0) {- setupCollectionTreeMocks(node.descendants);- }- });-};--interface SetupOpts {- initialValue?: {- id: CollectionId;- model: "collection" | "card" | "dataset" | "metric";- };- onChange?: (item: QuestionPickerItem) => void;- models?: [QuestionPickerValueModel, ...QuestionPickerValueModel[]];- options?: typeof defaultOptions;- tokenFeatures?: Partial<TokenFeatures>;-}--const commonSetup = () => {- mockGetBoundingClientRect();- setupRecentViewsAndSelectionsEndpoints([]);- setupDatabasesEndpoints([]);-- const allItems = flattenCollectionTree(collectionTree).map(- createMockCollectionItem,- );-- allItems.forEach((item) => {- if (item.model === "collection") {- fetchMock.get(`path:/api/collection/${item.id}`, item);- } else if (item.model === "dashboard") {- fetchMock.get(`path:/api/dashboard/${item.id}`, item);-- const dashboardId = item.id;- const dashboardItems = allItems.filter(- (item: any) => item.dashboard_id === dashboardId,- );- setupDashboardItemsEndpoint({- dashboard: item as any,- dashboardItems,- });- } else {- fetchMock.get(`path:/api/card/${item.id}`, item);- }- });-- setupCollectionTreeMocks(collectionTree);-};--const setupPicker = async ({- initialValue = { id: "root", model: "collection" },- onChange = jest.fn<void, [QuestionPickerItem]>(),- tokenFeatures = {},-}: SetupOpts = {}) => {- commonSetup();-- const settings = createMockSettings();-- const settingValuesWithToken = {- ...settings,- "token-features": createMockTokenFeatures({- content_verification: true,- official_collections: true,- ...tokenFeatures,- }),- };-- const state = createMockState({- settings: mockSettings(settingValuesWithToken),- });-- setupEnterprisePlugins();-- function TestComponent() {- const [path, setPath] = useState<QuestionPickerStatePath>();-- return (- <QuestionPicker- initialValue={initialValue}- models={["card", "dashboard"]}- options={defaultOptions}- path={path}- onInit={jest.fn()}- onItemSelect={onChange}- onPathChange={setPath}- />- );- }-- renderWithProviders(<TestComponent />, { storeInitialState: state });-- await waitForLoaderToBeRemoved();-};--// zero indexed-const level = async (index: number) => {- return within(await screen.findByTestId(`item-picker-level-${index}`));-};--const setupModal = async ({- initialValue,- models = ["card", "dataset"],- onChange = jest.fn<void, [QuestionPickerItem]>(),- options = defaultOptions,- tokenFeatures = {},-}: SetupOpts = {}) => {- commonSetup();-- const state = createMockState({- settings: mockSettings({- "token-features": createMockTokenFeatures(tokenFeatures),- }),- });+import { defaultOptions } from "../QuestionPicker";- renderWithProviders(- <QuestionPickerModal- onChange={onChange}- value={initialValue}- onClose={jest.fn()}- models={models}- options={options}- />,- {- storeInitialState: state,- },- );-- await waitForLoaderToBeRemoved();-};+import {+ level,+ myMetric,+ myModel,+ nestedDashboardQuestion,+ nestedQuestion,+ rootDashboardQuestion,+ setupModal,+ setupPicker,+} from "./setup";describe("QuestionPicker", () => {- afterEach(() => {- jest.restoreAllMocks();- });-it("should select the root collection by default", async () => {await setupPicker();@@ -413,7 +62,9 @@ describe("QuestionPicker", () => {});it("should render the path to a question nested in multiple collections", async () => {- await setupPicker({ initialValue: { id: 100, model: "card" } });+ await setupPicker({+ initialValue: { id: 100, model: "card" },+ });expect(await (await level(0)).findByRole("link", { name: /Our Analytics/ }),@@ -431,12 +82,6 @@ describe("QuestionPicker", () => {expect(await (await level(3)).findByRole("link", { name: /Nested Question/ }),).toHaveAttribute("data-active", "true");-- expect(- await within(- await screen.findByRole("link", { name: /My Verified Question/ }),- ).findByRole("img", { name: /verified_filled/ }),- ).toBeInTheDocument();});it("should render the path to a dashboard question where dashboard is in the root collection", async () => {@@ -486,10 +131,6 @@ describe("QuestionPicker", () => {});describe("QuestionPickerModal", () => {- afterEach(() => {- jest.restoreAllMocks();- });-it("should render the modal", async () => {await setupModal();@@ -667,14 +308,15 @@ describe("QuestionPickerModal", () => {});it("should be able to search for metrics", async () => {- setupSearchEndpoints([nestedQuestion, myModel, myMetric]);- await setupModal({- tokenFeatures: { snippet_collections: true },- models: ["card", "dataset", "metric"],- });+ await setupSearchEndpoints([nestedQuestion, myModel, myMetric]);+ await setupModal({ models: ["card", "dataset", "metric"] });+ // Need to wait for the collections tab to render+ expect(+ await screen.findByRole("link", { name: /Our Analytics/ }),+ ).toBeInTheDocument();const searchInput = await screen.findByPlaceholderText(/search/i);await userEvent.type(searchInput, myMetric.name);- await userEvent.click(screen.getByText("Everywhere"));+ await userEvent.click(await screen.findByText("Everywhere"));expect(await screen.findByText(myMetric.name)).toBeInTheDocument();expect(screen.queryByText(nestedQuestion.name)).not.toBeInTheDocument();});diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.tsnew file mode 100644index 00000000000..d3654373ec9--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/enterprise.unit.spec.ts@@ -0,0 +1,111 @@+import userEvent from "@testing-library/user-event";++import { screen, within } from "__support__/ui";++import { level, setupPicker } from "./setup";++describe("verified questions", () => {+ it("should show a verified icon when showing verified cards", async () => {+ await setupPicker({+ initialValue: { id: 100, model: "card" },+ isEE: true,+ });++ expect(+ await (await level(0)).findByRole("link", { name: /Our Analytics/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await (await level(1)).findByRole("link", { name: /Collection 4/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await (await level(2)).findByRole("link", { name: /Collection 3/ }),+ ).toHaveAttribute("data-active", "true");++ // question itself should start selected+ expect(+ await (await level(3)).findByRole("link", { name: /Nested Question/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await within(+ await screen.findByRole("link", { name: /My Verified Question/ }),+ ).findByRole("img", { name: /verified_filled/ }),+ ).toBeInTheDocument();+ });+});++describe("tenant collection", () => {+ it("should show tenant collections in the root panel and build a path to a dashboard", async () => {+ await setupPicker({ isEE: true });++ await userEvent.click(+ await screen.findByRole("link", { name: /Shared collections/ }),+ );++ await userEvent.click(await screen.findByRole("link", { name: /tcoll/ }));++ await userEvent.click(+ await screen.findByRole("link", { name: /tsubcoll/ }),+ );++ expect(+ await screen.findByRole("link", { name: /Tenant Question/ }),+ ).toBeInTheDocument();+ });++ it("should handle a tenant question as an initial value", async () => {+ await setupPicker({+ initialValue: {+ model: "card",+ id: 110,+ },+ isEE: true,+ });++ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toHaveAttribute("data-active", "true");++ expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(+ "data-active",+ "true",+ );++ expect(+ await screen.findByRole("link", { name: /tsubcoll/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /Tenant Question/ }),+ ).toHaveAttribute("data-active", "true");+ });++ it("should handle a tenant dashboard question as an initial value", async () => {+ await setupPicker({+ initialValue: {+ model: "card",+ id: 121,+ },+ isEE: true,+ });++ expect(+ await screen.findByRole("link", { name: /Shared collections/ }),+ ).toHaveAttribute("data-active", "true");++ expect(await screen.findByRole("link", { name: /tcoll/ })).toHaveAttribute(+ "data-active",+ "true",+ );++ expect(+ await screen.findByRole("link", { name: /tsubcoll/ }),+ ).toHaveAttribute("data-active", "true");++ expect(+ await screen.findByRole("link", { name: /DQ in TenantDashboard/ }),+ ).toHaveAttribute("data-active", "true");+ });+});diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsxnew file mode 100644index 00000000000..a6ee476d41f--- /dev/null+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker/tests/setup.tsx@@ -0,0 +1,483 @@+import fetchMock from "fetch-mock";+import { useState } from "react";++import { setupEnterprisePlugins } from "__support__/enterprise";+import {+ setupCollectionItemsEndpoint,+ setupDashboardItemsEndpoint,+ setupRecentViewsAndSelectionsEndpoints,+ setupRootCollectionItemsEndpoint,+ setupTenantCollectionItemsEndpoint,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import type { CollectionId, CollectionItem } from "metabase-types/api";+import {+ createMockCard,+ createMockCollection,+ createMockCollectionItem,+ createMockDashboard,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import type {+ QuestionPickerItem,+ QuestionPickerStatePath,+ QuestionPickerValueModel,+} from "../../../types";+import { QuestionPickerModal } from "../../QuestionPickerModal";+import { QuestionPicker, defaultOptions } from "../QuestionPicker";++type NestedCollectionItem = Partial<Omit<CollectionItem, "id">> & {+ id: any;+ is_personal?: boolean;+ descendants?: NestedCollectionItem[];+ dashboard_id?: number;+};++const rootQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 104,+ name: "Question in Root",+ collection_id: null,+ }),+ model: "card",+});++const tenantQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 110,+ name: "Tenant Question",+ collection_id: 7,+ }),+ model: "card",+});++export const rootDashboard = createMockCollectionItem({+ ...createMockDashboard({+ name: "Root Dashboard",+ collection_id: null,+ }),+ id: 105,+ location: "/",+ model: "dashboard",+});++export const rootDashboardQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 111,+ name: "DQ in Root",+ collection_id: null,+ dashboard_id: rootDashboard.id,+ }),+ model: "card",+});++export const nestedQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 100,+ name: "Nested Question",+ collection_id: 3,+ }),+ model: "card",+});++const nestedDashboard = createMockCollectionItem({+ ...createMockDashboard({+ name: "Nested Dashboard",+ collection_id: 3,+ collection: createMockCollection({+ id: 3,+ location: "/4/",+ }),+ }),+ location: "/4/",+ id: 106,+ model: "dashboard",+});++const tenantDashboard = createMockCollectionItem({+ ...createMockDashboard({+ name: "Tenant Dashboard",+ collection_id: 7,+ collection: createMockCollection({+ id: 7,+ location: "/6/7/",+ namespace: "shared-tenant-collection",+ }),+ }),+ location: "/6/7/",+ id: 120,+ model: "dashboard",+ is_tenant_dashboard: true,+});++const tenantDashboardQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 121,+ name: "DQ in TenantDashboard",+ collection_id: 7,+ dashboard_id: tenantDashboard.id,+ dashboard: tenantDashboard,+ }),+ model: "card",+});++export const nestedDashboardQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 108,+ name: "Nested DQ",+ collection_id: 3,+ dashboard_id: nestedDashboard.id,+ dashboard: nestedDashboard,+ }),+ model: "card",+});++const myVerifiedQuestion = createMockCollectionItem({+ ...createMockCard({+ id: 103,+ name: "My Verified Question",+ collection_id: 3,+ }),+ moderated_status: "verified",+});++export const myModel = createMockCollectionItem({+ ...createMockCard({+ id: 101,+ name: "My Model",+ collection_id: 3,+ type: "model",+ }),+ model: "dataset",+});++export const myMetric = createMockCollectionItem({+ ...createMockCard({+ id: 102,+ name: "My Metric",+ collection_id: 3,+ type: "metric",+ }),+ model: "metric",+});++const collectionTree: NestedCollectionItem[] = [+ {+ id: "root" as any,+ model: "collection",+ name: "Our Analytics",+ location: "",+ can_write: true,+ descendants: [+ {+ id: 4,+ name: "Collection 4",+ model: "collection",+ location: "/",+ can_write: true,+ descendants: [+ {+ id: 3,+ name: "Collection 3",+ model: "collection",+ descendants: [+ nestedQuestion,+ nestedDashboard,+ nestedDashboardQuestion,+ myModel,+ myMetric,+ myVerifiedQuestion,+ ],+ location: "/4/",+ can_write: true,+ is_personal: false,+ },+ ],+ },+ {+ id: 2,+ model: "collection",+ is_personal: false,+ name: "Collection 2",+ location: "/",+ can_write: true,+ descendants: [],+ },+ rootQuestion,+ rootDashboard,+ rootDashboardQuestion,+ ],+ },+ {+ name: "My personal collection",+ id: 1,+ model: "collection",+ location: "/",+ is_personal: true,+ can_write: true,+ descendants: [+ {+ id: 5,+ model: "collection",+ location: "/1/",+ name: "personal sub_collection",+ is_personal: true,+ can_write: true,+ descendants: [],+ },+ ],+ },+];++const tenantCollectionsTree: NestedCollectionItem[] = [+ {+ name: "tcoll",+ id: 6,+ location: "/",+ effective_location: "/",+ is_personal: false,+ is_shared_tenant_collection: true,+ model: "collection",+ here: ["collection"],+ below: ["card", "dashboard"],+ can_write: true,+ descendants: [+ {+ id: 7,+ location: "/6/",+ effective_location: "/6/",+ name: "tsubcoll",+ model: "collection",+ is_personal: false,+ is_shared_tenant_collection: true,+ can_write: true,+ descendants: [tenantQuestion, tenantDashboard, tenantDashboardQuestion],+ here: ["card", "dashboard"],+ },+ ],+ },+];++const flattenCollectionTree = (+ nodes: NestedCollectionItem[],+): Omit<NestedCollectionItem, "descendants">[] => {+ if (!nodes) {+ return [];+ }+ return nodes.flatMap(({ descendants = [], ...node }) => [+ node,+ ...flattenCollectionTree(descendants),+ ]);+};++const mockCollectionToCollectionItem = (c: NestedCollectionItem) =>+ createMockCollectionItem({+ ...c,+ ...(c.is_shared_tenant_collection && {+ namespace: "shared-tenant-collection",+ }),+ });++const setupCollectionTreeMocks = (node: NestedCollectionItem[]) => {+ node.forEach((node) => {+ if (!node.descendants) {+ return;+ }+ const collectionItems = node.descendants+ .filter((item) => !item.dashboard_id) //We don't show dashboard items in collection item endpoints+ .map((c: NestedCollectionItem) => createMockCollectionItem(c));++ // Skip root since it's handled separately (tenant-aware)+ if (node.id !== "root") {+ setupCollectionItemsEndpoint({+ collection: createMockCollection({ id: node.id }),+ collectionItems,+ });+ }++ if (collectionItems.length > 0) {+ setupCollectionTreeMocks(node.descendants);+ }+ });+};++const setupTenantCollectionTreeMocks = (node: NestedCollectionItem[]): void => {+ node.forEach((n) => {+ if (!n.descendants) {+ return;+ }+ const collectionItems = n.descendants+ .filter((item) => !item.dashboard_id) //We don't show dashboard items in collection item endpoints+ .map((c: NestedCollectionItem) => mockCollectionToCollectionItem(c));++ setupTenantCollectionItemsEndpoint({+ collection: createMockCollection({ id: n.id }),+ collectionItems,+ });++ if (collectionItems.length > 0) {+ setupTenantCollectionTreeMocks(n.descendants);+ }+ });+};++interface SetupOpts {+ initialValue?: {+ id: CollectionId;+ model: "collection" | "card" | "dataset" | "metric";+ };+ onChange?: (item: QuestionPickerItem) => void;+ models?: [QuestionPickerValueModel, ...QuestionPickerValueModel[]];+ options?: typeof defaultOptions;+ isEE?: boolean;+}++const commonSetup = ({ isEE = false }: { isEE?: boolean } = {}) => {+ mockGetBoundingClientRect();+ setupRecentViewsAndSelectionsEndpoints([]);++ const allItems = flattenCollectionTree(collectionTree).map(+ createMockCollectionItem,+ );++ allItems.forEach((item) => {+ if (item.model === "collection") {+ fetchMock.get(`path:/api/collection/${item.id}`, item);+ } else if (item.model === "dashboard") {+ fetchMock.get(`path:/api/dashboard/${item.id}`, item);++ const dashboardId = item.id;+ const dashboardItems = allItems.filter(+ (item: any) => item.dashboard_id === dashboardId,+ );+ setupDashboardItemsEndpoint({+ dashboard: item as any,+ dashboardItems,+ });+ } else {+ fetchMock.get(`path:/api/card/${item.id}`, item);+ }+ });++ setupCollectionTreeMocks(collectionTree);++ setupRootCollectionItemsEndpoint({+ rootCollectionItems:+ collectionTree[0].descendants+ ?.filter((item) => !item.dashboard_id)+ .map(createMockCollectionItem) ?? [],+ tenantRootItems: isEE+ ? [mockCollectionToCollectionItem(tenantCollectionsTree[0])]+ : [],+ });++ if (isEE) {+ const allTenantItems = flattenCollectionTree(tenantCollectionsTree).map(+ createMockCollectionItem,+ );++ setupTenantCollectionTreeMocks(tenantCollectionsTree);++ allTenantItems.forEach((item) => {+ if (item.model === "collection") {+ fetchMock.get(`path:/api/collection/${item.id}`, {+ ...item,+ namespace: "shared-tenant-collection",+ });+ } else if (item.model === "dashboard") {+ fetchMock.get(`path:/api/dashboard/${item.id}`, item);++ const dashboardId = item.id;+ const dashboardItems = allTenantItems.filter(+ (item: any) => item.dashboard_id === dashboardId,+ );+ setupDashboardItemsEndpoint({+ dashboard: item as any,+ dashboardItems,+ });+ } else {+ fetchMock.get(`path:/api/card/${item.id}`, item);+ }+ });+ }+};++export const setupPicker = async ({+ initialValue = { id: "root", model: "collection" },+ onChange = jest.fn<void, [QuestionPickerItem]>(),+ isEE = false,+}: SetupOpts = {}) => {+ commonSetup({ isEE });++ const settings = mockSettings({+ "token-features": createMockTokenFeatures({+ content_verification: isEE,+ official_collections: isEE,+ tenants: isEE,+ }),+ "use-tenants": isEE,+ });++ const storeInitialState = createMockState({+ settings,+ });++ if (isEE) {+ setupEnterprisePlugins();+ }++ function TestComponent() {+ const [path, setPath] = useState<QuestionPickerStatePath>();++ return (+ <QuestionPicker+ initialValue={initialValue}+ models={["card", "dashboard"]}+ options={defaultOptions}+ path={path}+ onInit={jest.fn()}+ onItemSelect={onChange}+ onPathChange={setPath}+ />+ );+ }++ renderWithProviders(<TestComponent />, { storeInitialState });++ await waitForLoaderToBeRemoved();+};++// zero indexed+export const level = async (index: number) => {+ return within(await screen.findByTestId(`item-picker-level-${index}`));+};++export const setupModal = async ({+ initialValue,+ models = ["card", "dataset"],+ onChange = jest.fn<void, [QuestionPickerItem]>(),+ options = defaultOptions,+}: SetupOpts = {}) => {+ commonSetup();++ renderWithProviders(+ <QuestionPickerModal+ onChange={onChange}+ value={initialValue}+ onClose={jest.fn()}+ models={models}+ options={options}+ />,+ );++ await waitForLoaderToBeRemoved();+};diff --git a/frontend/src/metabase/common/components/Pickers/utils.ts b/frontend/src/metabase/common/components/Pickers/utils.tsindex 7366c48b4b7..42d10594fd3 100644--- a/frontend/src/metabase/common/components/Pickers/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/utils.ts@@ -1,9 +1,14 @@+import { t } from "ttag";+import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";import { isNullOrUndefined } from "metabase/lib/types";+import { PLUGIN_TENANTS } from "metabase/plugins";import type {+ Collection,CollectionId,CollectionItem,CollectionItemModel,+ CollectionNamespace,ListCollectionItemsRequest,} from "metabase-types/api";@@ -11,14 +16,42 @@ import type { PickerState } from "../EntityPicker";import type {CollectionPickerItem,+ CollectionPickerOptions,CollectionPickerStatePath,} from "./CollectionPicker";+export const getNamespaceForItem = (+ item: Pick<CollectionPickerItem, "id" | "namespace"> | null | undefined,+): CollectionNamespace | undefined => {+ if (!item) {+ return undefined;+ }++ const tenantNamespace = PLUGIN_TENANTS.getNamespaceForTenantId(item.id);+ if (tenantNamespace) {+ return tenantNamespace as CollectionNamespace;+ }++ return item.namespace;+};+export const getCollectionIdPath = (collection: Pick<CollectionPickerItem,- "id" | "location" | "is_personal" | "effective_location" | "model" | "type"- >,+ | "id"+ | "location"+ | "is_personal"+ | "effective_location"+ | "model"+ | "is_shared_tenant_collection"+ | "is_tenant_dashboard"+ | "type"+ | "namespace"+ | "collection_namespace"+ | "collection_id"+ > & {+ type?: Collection["type"];+ },userPersonalCollectionId?: CollectionId,): CollectionId[] => {if (collection.id === null || collection.id === "root") {@@ -29,6 +62,22 @@ export const getCollectionIdPath = (return ["databases"];}+ const tenantPath = PLUGIN_TENANTS.getTenantCollectionPathPrefix(collection);+ if (tenantPath) {+ if (+ PLUGIN_TENANTS.isTenantCollectionId(collection.id) ||+ collection.type === "tenant-specific-root-collection"+ ) {+ return tenantPath;+ }+ const location = collection?.effective_location ?? collection?.location;+ const pathFromRoot: CollectionId[] =+ location?.split("/").filter(Boolean).map(Number) ?? [];+ const id =+ collection.model === "collection" ? collection.id : -collection.id;+ return [...tenantPath, ...pathFromRoot, id];+ }+if (collection.type === "library") {return [collection.id];}@@ -72,9 +121,15 @@ export const getStateFromIdPath = ({models,}: {idPath: CollectionId[];- namespace?: "snippets";+ namespace?: CollectionNamespace;models: CollectionItemModel[];}): CollectionPickerStatePath => {+ const effectiveNamespace =+ PLUGIN_TENANTS.isTenantCollectionId(idPath[0]) &&+ PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE+ ? (PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE as CollectionNamespace)+ : namespace;+const statePath: PickerState<CollectionPickerItem,ListCollectionItemsRequest@@ -86,6 +141,7 @@ export const getStateFromIdPath = ({id: idPath[0],here: ["collection"],below: ["collection"],+ namespace: effectiveNamespace,},},];@@ -95,13 +151,14 @@ export const getStateFromIdPath = ({idPath[index + 1],);- const { entityId, model: entityModel } = resolveEntityId(id);+ const { entityId, model: entityModel, ...extra } = resolveEntityId(id);statePath.push({query: {id: entityId,models: ["collection", ...models],- namespace,+ namespace: effectiveNamespace,+ ...extra,},entity: entityModel,selectedItem: nextLevelId@@ -111,6 +168,7 @@ export const getStateFromIdPath = ({id: nextLevelId,here: ["collection"],below: ["collection"],+ namespace: effectiveNamespace,}: null,});@@ -140,6 +198,43 @@ const resolveEntityId = (}};+export const isNamespaceRoot = (item: CollectionPickerItem): boolean => {+ return PLUGIN_TENANTS.isTenantCollectionId(item.id);+};++export const shouldDisableItemForSavingModel = (+ item: CollectionPickerItem,+ savingModel?: CollectionPickerOptions["savingModel"],+): boolean => {+ if (!savingModel) {+ return false;+ }++ if (savingModel === "collection") {+ return false;+ }++ return isNamespaceRoot(item);+};++export const getDisabledReasonForSavingModel = (+ item: CollectionPickerItem,+ savingModel?: CollectionPickerOptions["savingModel"],+): string | undefined => {+ if (!shouldDisableItemForSavingModel(item, savingModel)) {+ return undefined;+ }++ if (PLUGIN_TENANTS.isTenantCollectionId(item.id)) {+ const tenantReason = PLUGIN_TENANTS.getTenantRootDisabledReason();+ if (tenantReason) {+ return tenantReason;+ }+ }++ return t`Items cannot be saved to this collection.`;+};+export const canCollectionCardBeUsed = (item: CollectionItem | CollectionPickerItem,): boolean => {diff --git a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.tsindex 455755b41e1..9c757171703 100644--- a/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts+++ b/frontend/src/metabase/common/components/Pickers/utils.unit.spec.ts@@ -1,4 +1,16 @@-import { getCollectionIdPath } from "./utils";+import { setupEnterpriseTest } from "__support__/enterprise";+import { PLUGIN_TENANTS } from "metabase/plugins";++import {+ getCollectionIdPath,+ getDisabledReasonForSavingModel,+ getNamespaceForItem,+ getStateFromIdPath,+ isNamespaceRoot,+ shouldDisableItemForSavingModel,+} from "./utils";++setupEnterpriseTest();describe("getCollectionIdPath", () => {it("should handle the current user's personal collection", () => {@@ -161,4 +173,372 @@ describe("getCollectionIdPath", () => {expect(path).toEqual(["root", 6, 7, 8, -9]);});++ it("should detect tenant collections via namespace", () => {+ const path = getCollectionIdPath(+ {+ id: 9,+ location: "/4/5/6/7/8/",+ effective_location: "/6/7/8/",+ model: "collection",+ namespace: "shared-tenant-collection" as const,+ },+ 1337,+ );++ expect(path).toEqual(["tenant", 6, 7, 8, 9]);+ });++ it("should detect tenant collection items via collection_namespace", () => {+ const path = getCollectionIdPath(+ {+ id: 9,+ location: "/4/5/6/7/8/",+ effective_location: "/6/7/8/",+ model: "collection",+ collection_namespace: "shared-tenant-collection" as const,+ },+ 1337,+ );++ expect(path).toEqual(["tenant", 6, 7, 8, 9]);+ });++ it("should detect tenant collection items - collections (legacy boolean)", () => {+ const path = getCollectionIdPath(+ {+ id: 9,+ location: "/4/5/6/7/8/",+ effective_location: "/6/7/8/",+ model: "collection",+ is_shared_tenant_collection: true,+ },+ 1337,+ );++ expect(path).toEqual(["tenant", 6, 7, 8, 9]);+ });++ it("should detect tenant collection items - dashboards (legacy boolean)", () => {+ const path = getCollectionIdPath(+ {+ id: 9,+ location: "/4/5/6/7/8/",+ effective_location: "/6/7/8/",+ model: "collection",+ is_tenant_dashboard: true,+ },+ 1337,+ );++ expect(path).toEqual(["tenant", 6, 7, 8, 9]);+ });++ it("should treat tenant collection root as a root-level item", () => {+ const path = getCollectionIdPath(+ {+ id: 1234,+ location: "/",+ effective_location: "/",+ model: "collection",+ type: "tenant-specific-root-collection",+ },+ 1337,+ );++ expect(path).toEqual([1234]);+ });++ it("should nest tenant collection under tenant-specific for admins", () => {+ const rootPath = getCollectionIdPath(+ {+ id: "tenant-specific",+ location: "/",+ model: "collection",+ },+ 1337,+ );++ expect(rootPath).toEqual(["tenant-specific"]);++ const childPath = getCollectionIdPath(+ {+ id: 1234,+ location: "/",+ effective_location: "/",+ model: "collection",+ type: "tenant-specific-root-collection",+ collection_id: "tenant-specific",+ },+ 1337,+ );++ expect(childPath).toEqual(["tenant-specific", 1234]);+ });+});++describe("getStateFromIdPath", () => {+ it("should propagate namespace through state path", () => {+ const statePath = getStateFromIdPath({+ idPath: ["root", 1, 2],+ namespace: "snippets",+ models: ["collection"],+ });++ // First item has no query+ expect(statePath[0].selectedItem?.namespace).toBe("snippets");++ // Subsequent items should have the namespace in their queries+ expect(statePath[1].query?.namespace).toBe("snippets");+ expect(statePath[2].query?.namespace).toBe("snippets");+ });++ it("should use shared-tenant-collection namespace for tenant paths", () => {+ const statePath = getStateFromIdPath({+ idPath: ["tenant", 1, 2],+ models: ["collection"],+ });++ // Should automatically use shared-tenant-collection namespace+ expect(statePath[0].selectedItem?.namespace).toBe(+ "shared-tenant-collection",+ );+ expect(statePath[1].query?.namespace).toBe("shared-tenant-collection");+ expect(statePath[2].query?.namespace).toBe("shared-tenant-collection");+ });++ it("should propagate namespace to selected items", () => {+ const statePath = getStateFromIdPath({+ idPath: ["tenant", 1],+ models: ["collection"],+ });++ // Selected items should have namespace+ expect(statePath[0].selectedItem?.namespace).toBe(+ "shared-tenant-collection",+ );+ expect(statePath[1].selectedItem?.namespace).toBe(+ "shared-tenant-collection",+ );+ });++ it("should handle root paths without explicit namespace", () => {+ const statePath = getStateFromIdPath({+ idPath: ["root", 1],+ models: ["collection"],+ });++ // Should have undefined namespace for root+ expect(statePath[0].selectedItem?.namespace).toBeUndefined();+ expect(statePath[1].query?.namespace).toBeUndefined();+ });+});++describe("isNamespaceRoot", () => {+ it("should return true for tenant root", () => {+ const item = {+ id: "tenant",+ name: "Shared collections",+ model: "collection" as const,+ namespace: "shared-tenant-collection" as const,+ };++ expect(isNamespaceRoot(item)).toBe(true);+ });++ it("should return false for regular collections", () => {+ const item = {+ id: 1,+ name: "My Collection",+ model: "collection" as const,+ location: "/",+ };++ expect(isNamespaceRoot(item)).toBe(false);+ });++ it("should return false for root collection", () => {+ const item = {+ id: "root",+ name: "Our Analytics",+ model: "collection" as const,+ location: "/",+ };++ expect(isNamespaceRoot(item)).toBe(false);+ });++ it("should return false for tenant sub-collections", () => {+ const item = {+ id: 123,+ name: "Tenant Sub-Collection",+ model: "collection" as const,+ namespace: "shared-tenant-collection" as const,+ location: "/tenant/",+ };++ expect(isNamespaceRoot(item)).toBe(false);+ });+});++describe("shouldDisableItemForSavingModel", () => {+ const tenantRoot = {+ id: "tenant",+ name: "Shared collections",+ model: "collection" as const,+ namespace: "shared-tenant-collection" as const,+ };++ const regularCollection = {+ id: 1,+ name: "My Collection",+ model: "collection" as const,+ location: "/",+ };++ const tenantSubCollection = {+ id: 123,+ name: "Tenant Sub-Collection",+ model: "collection" as const,+ namespace: "shared-tenant-collection" as const,+ location: "/tenant/",+ };++ it("should return true for tenant root when saving a dashboard", () => {+ expect(shouldDisableItemForSavingModel(tenantRoot, "dashboard")).toBe(true);+ });++ it("should return true for tenant root when saving a question", () => {+ expect(shouldDisableItemForSavingModel(tenantRoot, "question")).toBe(true);+ });++ it("should return true for tenant root when saving a model", () => {+ expect(shouldDisableItemForSavingModel(tenantRoot, "model")).toBe(true);+ });++ it("should return false for tenant root when saving a collection", () => {+ expect(shouldDisableItemForSavingModel(tenantRoot, "collection")).toBe(+ false,+ );+ });++ it("should return false for regular collections when saving any item type", () => {+ expect(+ shouldDisableItemForSavingModel(regularCollection, "dashboard"),+ ).toBe(false);+ expect(shouldDisableItemForSavingModel(regularCollection, "question")).toBe(+ false,+ );+ expect(+ shouldDisableItemForSavingModel(regularCollection, "collection"),+ ).toBe(false);+ });++ it("should return false for tenant sub-collections when saving any item type", () => {+ expect(+ shouldDisableItemForSavingModel(tenantSubCollection, "dashboard"),+ ).toBe(false);+ expect(+ shouldDisableItemForSavingModel(tenantSubCollection, "question"),+ ).toBe(false);+ });++ it("should return false when savingModel is not specified", () => {+ expect(shouldDisableItemForSavingModel(tenantRoot, undefined)).toBe(false);+ expect(shouldDisableItemForSavingModel(regularCollection, undefined)).toBe(+ false,+ );+ });+});++describe("getDisabledReasonForSavingModel", () => {+ const tenantRoot = {+ id: "tenant",+ name: "Shared collections",+ model: "collection" as const,+ namespace: "shared-tenant-collection" as const,+ };++ const regularCollection = {+ id: 1,+ name: "My Collection",+ model: "collection" as const,+ location: "/",+ };++ it("should return reason for disabled tenant root", () => {+ const reason = getDisabledReasonForSavingModel(tenantRoot, "dashboard");++ expect(reason).toBeDefined();+ expect(reason).toContain("tenant root collection");+ });++ it("should return undefined for enabled items", () => {+ expect(+ getDisabledReasonForSavingModel(regularCollection, "dashboard"),+ ).toBeUndefined();+ expect(+ getDisabledReasonForSavingModel(tenantRoot, "collection"),+ ).toBeUndefined();+ expect(+ getDisabledReasonForSavingModel(tenantRoot, undefined),+ ).toBeUndefined();+ });+});++describe("getNamespaceForItem", () => {+ it("should return shared tenant namespace for tenant root", () => {+ const item = {+ id: "tenant",+ namespace: "shared-tenant-collection" as const,+ };++ expect(getNamespaceForItem(item)).toBe(+ PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ );+ });++ it("should return the item namespace for regular collections with namespace", () => {+ const item = {+ id: 123,+ namespace: "shared-tenant-collection" as const,+ };++ expect(getNamespaceForItem(item)).toBe("shared-tenant-collection");+ });++ it("should return the item namespace for snippet collections", () => {+ const item = {+ id: 456,+ namespace: "snippets" as const,+ };++ expect(getNamespaceForItem(item)).toBe("snippets");+ });++ it("should return undefined for regular collections without namespace", () => {+ const item = {+ id: 789,+ namespace: undefined,+ };++ expect(getNamespaceForItem(item)).toBeUndefined();+ });++ it("should return undefined for null item", () => {+ expect(getNamespaceForItem(null)).toBeUndefined();+ });++ it("should return undefined for undefined item", () => {+ expect(getNamespaceForItem(undefined)).toBeUndefined();+ });++ it("should return undefined for root collection", () => {+ const item = {+ id: "root",+ namespace: undefined,+ };++ expect(getNamespaceForItem(item)).toBeUndefined();+ });});diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx b/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsxindex 3f42c74b0e7..eecd18e4b5c 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx+++ b/frontend/src/metabase/common/components/SaveQuestionForm/SaveQuestionForm.tsx@@ -58,6 +58,9 @@ export const SaveQuestionForm = ({? ["collection", "dashboard"]: ["collection"];+ // Determine the savingModel based on question type+ const savingModel = question.type() === "model" ? "model" : "question";+const showPickerInput =values.saveType === "create" && !targetCollection && !saveToDashboard;@@ -125,6 +128,7 @@ export const SaveQuestionForm = ({dashboardIdFieldName="dashboard_id"title={t`Where do you want to save this?`}entityType={getEntityTypeFromCardType(question.type())}+ savingModel={savingModel}collectionPickerModalProps={{models,recentFilter: (items) =>diff --git a/frontend/src/metabase/common/components/UserCollectionList.tsx b/frontend/src/metabase/common/components/UserCollectionList.tsxindex 65556970f8d..255158c053c 100644--- a/frontend/src/metabase/common/components/UserCollectionList.tsx+++ b/frontend/src/metabase/common/components/UserCollectionList.tsx@@ -3,7 +3,6 @@ import {useListUsersQuery,} from "metabase/api";import { BrowserCrumbs } from "metabase/common/components/BrowserCrumbs";-import Card from "metabase/common/components/Card";import { Grid } from "metabase/common/components/Grid";import Link from "metabase/common/components/Link";import { PaginationControls } from "metabase/common/components/PaginationControls";@@ -14,13 +13,9 @@ import {ROOT_COLLECTION,} from "metabase/entities/collections/constants";import * as Urls from "metabase/lib/urls";-import { Box, Flex, Icon, Loader } from "metabase/ui";+import { Box, Card, Flex, Group, Icon, Loader } from "metabase/ui";-import {- CardContent,- ListGridItem,- ListHeader,-} from "./UserCollectionList.styled";+import { ListGridItem, ListHeader } from "./UserCollectionList.styled";export const UserCollectionList = () => {const { page, handleNextPage, handlePreviousPage } = usePagination();@@ -61,16 +56,17 @@ export const UserCollectionList = () => {role="list-item"><Link to={`/collection/${user.personal_collection_id}`}>- <Card className={CS.p2} hoverable>- <CardContent>+ <Card shadow="none" withBorder>+ <Group gap="xs"><Iconname="person"className={CS.mr1}c="text-medium"size={18}/>+<h3>{user.common_name}</h3>- </CardContent>+ </Group></Card></Link></ListGridItem>diff --git a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsxindex 84c9bf57287..e4bede44022 100644--- a/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardMoveModal.tsx@@ -56,6 +56,7 @@ function DashboardMoveModal({onClose();}}recentAndSearchFilter={recentsAndSearchFilter}+ savingModel="dashboard"/>);}diff --git a/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx b/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsxindex fcdd1ad745a..36db0589987 100644--- a/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx+++ b/frontend/src/metabase/dashboard/containers/CopyDashboardForm.tsx@@ -134,6 +134,7 @@ function CopyDashboardForm({title={t`Which collection should this go in?`}filterPersonalCollections={filterPersonalCollections}entityType="dashboard"+ savingModel="dashboard"/>{!hideShallowCopy && (diff --git a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsxindex 6815a0997b7..db4e63155be 100644--- a/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx+++ b/frontend/src/metabase/dashboard/containers/CreateDashboardForm.tsx@@ -126,6 +126,7 @@ export function CreateDashboardForm({title={t`Which collection should this go in?`}filterPersonalCollections={filterPersonalCollections}entityType="dashboard"+ savingModel="dashboard"/><FormFooter><FormErrorMessage inline />diff --git a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubAdminSettingsPage.tsx b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubAdminSettingsPage.tsxindex 1601aafb8f5..1b1181fd45a 100644--- a/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubAdminSettingsPage.tsx+++ b/frontend/src/metabase/embedding/embedding-hub/components/EmbeddingHubAdminSettingsPage.tsx@@ -4,11 +4,14 @@ import {RelatedSettingsSection,getModularEmbeddingRelatedSettingItems,} from "metabase/admin/components/RelatedSettingsSection";+import { useSetting } from "metabase/common/hooks";import { Stack, Text, Title } from "metabase/ui";import { EmbeddingHub } from "./EmbeddingHub";export const EmbeddingHubAdminSettingsPage = () => {+ const isUsingTenants = useSetting("use-tenants");+return (<Stack mx="auto" py="xl" gap="xl" maw={800}><Stack gap="xs">@@ -24,7 +27,7 @@ export const EmbeddingHubAdminSettingsPage = () => {<Stack ml="2.7rem"><RelatedSettingsSection- items={getModularEmbeddingRelatedSettingItems()}+ items={getModularEmbeddingRelatedSettingItems({ isUsingTenants })}/></Stack></Stack>diff --git a/frontend/src/metabase/embedding/embedding-hub/hooks/use-completed-embedding-hub-steps.ts b/frontend/src/metabase/embedding/embedding-hub/hooks/use-completed-embedding-hub-steps.tsindex 64d7f46e998..3173afbaa63 100644--- a/frontend/src/metabase/embedding/embedding-hub/hooks/use-completed-embedding-hub-steps.ts+++ b/frontend/src/metabase/embedding/embedding-hub/hooks/use-completed-embedding-hub-steps.ts@@ -26,6 +26,7 @@ export const useCompletedEmbeddingHubSteps = (): {"secure-embeds": false,"embed-production": false,"create-models": false,+ "setup-tenants": false,};}diff --git a/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts b/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.tsindex b18485dd90c..3f92deccf9c 100644--- a/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts+++ b/frontend/src/metabase/embedding/embedding-hub/hooks/use-get-embedding-hub-steps.ts@@ -1,14 +1,19 @@import { useCallback, useMemo } from "react";import { t } from "ttag";+import { useSetting } from "metabase/common/hooks";import { useDispatch } from "metabase/lib/redux";-import type { SdkIframeEmbedSetupModalProps } from "metabase/plugins";+import {+ PLUGIN_TENANTS,+ type SdkIframeEmbedSetupModalProps,+} from "metabase/plugins";import { setOpenModalWithProps } from "metabase/redux/ui";import type { EmbeddingHubStep } from "../types";export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {const dispatch = useDispatch();+ const isUsingTenants = useSetting("use-tenants");const openEmbedModal = useCallback((props: Pick<SdkIframeEmbedSetupModalProps, "initialState">) => {@@ -23,6 +28,8 @@ export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {);return useMemo(() => {+ const isTenantsFeatureAvailable = PLUGIN_TENANTS.isEnabled;+const TEST_EMBED: EmbeddingHubStep = {id: "create-test-embed",title: t`Create embed`,@@ -41,6 +48,19 @@ export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {},variant: "outline",},+ ...(isTenantsFeatureAvailable+ ? [+ {+ title: t`Set up tenants`,+ description: t`Define a multi tenant user strategy to manage access for tenant users.`,+ to: isUsingTenants+ ? "/admin/tenants"+ : "/admin/people/user-strategy",+ optional: true,+ stepId: "setup-tenants" as const,+ },+ ]+ : []),],image: {src: "app/assets/img/embedding_hub_create_embed.png",@@ -161,5 +181,5 @@ export const useGetEmbeddingHubSteps = (): EmbeddingHubStep[] => {SECURE_EMBEDS,EMBED_PRODUCTION,];- }, [openEmbedModal]);+ }, [isUsingTenants, openEmbedModal]);};diff --git a/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts b/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.tsindex 1bc614399a8..60dd409f147 100644--- a/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts+++ b/frontend/src/metabase/embedding/embedding-hub/types/embedding-checklist.ts@@ -8,7 +8,8 @@ export type EmbeddingHubStepId =| "configure-row-column-security"| "secure-embeds"| "embed-production"- | "create-models";+ | "create-models"+ | "setup-tenants";export interface EmbeddingHubStep {id: EmbeddingHubStepId;diff --git a/frontend/src/metabase/forms/components/FormGroupsWidget/FormGroupsWidget.tsx b/frontend/src/metabase/forms/components/FormGroupsWidget/FormGroupsWidget.tsxindex bb1f9262dfa..6051c72cba2 100644--- a/frontend/src/metabase/forms/components/FormGroupsWidget/FormGroupsWidget.tsx+++ b/frontend/src/metabase/forms/components/FormGroupsWidget/FormGroupsWidget.tsx@@ -4,13 +4,15 @@ import { t } from "ttag";import _ from "underscore";import { MembershipSelect } from "metabase/admin/people/components/MembershipSelect";+import { useListPermissionsGroupsQuery } from "metabase/api";import FormField from "metabase/common/components/FormField";-import { useGroupListQuery } from "metabase/common/hooks";import { isAdminGroup, isDefaultGroup } from "metabase/lib/groups";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { GroupId, Member } from "metabase-types/api";interface FormGroupsWidgetProps extends HTMLAttributes<HTMLDivElement> {name: string;+ external?: boolean;}export const FormGroupsWidget = ({@@ -18,18 +20,24 @@ export const FormGroupsWidget = ({className,style,title = t`Groups`,+ external,}: FormGroupsWidgetProps) => {const [{ value: formValue }, , { setValue }] =useField<{ id: GroupId; is_group_manager?: boolean }[]>(name);- const { data: groups, isLoading } = useGroupListQuery();+ const { data: groups, isLoading } = useListPermissionsGroupsQuery({+ tenancy: external ? "external" : "internal",+ });if (isLoading || !groups) {return null;}const adminGroup = _.find(groups, isAdminGroup);- const defaultGroup = _.find(groups, isDefaultGroup);+ const defaultGroup = _.find(+ groups,+ external ? PLUGIN_TENANTS.isExternalUsersGroup : isDefaultGroup,+ );const value = formValue ?? [{ id: defaultGroup?.id, is_group_manager: false },@@ -99,6 +107,7 @@ export const FormGroupsWidget = ({onAdd={handleAdd}onRemove={handleRemove}onChange={handleChange}+ groupsTitle={title}isUserAdmin={isUserAdmin}/></FormField>diff --git a/frontend/src/metabase/lib/embed.js b/frontend/src/metabase/lib/embed.jsindex f89cceb2605..a3b1d85a8c0 100644--- a/frontend/src/metabase/lib/embed.js+++ b/frontend/src/metabase/lib/embed.js@@ -42,7 +42,6 @@ export function initializeEmbedding(store) {}}});-store.dispatch(setInitialUrlOptions(window.location));}}diff --git a/frontend/src/metabase/lib/groups.ts b/frontend/src/metabase/lib/groups.tsindex cd3100516f7..2beaf9afdf6 100644--- a/frontend/src/metabase/lib/groups.ts+++ b/frontend/src/metabase/lib/groups.ts@@ -1,32 +1,35 @@import { t } from "ttag";import { color } from "metabase/lib/colors";-import type { Group } from "metabase-types/api";+import { PLUGIN_TENANTS } from "metabase/plugins";+import type { GroupInfo } from "metabase-types/api";const SPECIAL_GROUP_NAMES = new Map([// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045["All Users", t`All Users`],// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045["Administrators", t`Administrators`],+ // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045+ ["All tenant users", t`All tenant users`],]);-export function isDefaultGroup(group: Pick<Group, "name">) {- return group.name === "All Users";+export function isDefaultGroup(group: Pick<GroupInfo, "magic_group_type">) {+ return group.magic_group_type === "all-internal-users";}-export function isAdminGroup(group: Pick<Group, "name">) {- return group.name === "Administrators";+export function isAdminGroup(group: Pick<GroupInfo, "magic_group_type">) {+ return group.magic_group_type === "admin";}-export function canEditPermissions(group: Pick<Group, "name">) {+export function canEditPermissions(group: Pick<GroupInfo, "magic_group_type">) {return !isAdminGroup(group);}-export function canEditMembership(group: Pick<Group, "name">) {- return !isDefaultGroup(group);+export function canEditMembership(group: Pick<GroupInfo, "magic_group_type">) {+ return !isDefaultGroup(group) && !PLUGIN_TENANTS.isExternalUsersGroup(group);}-export function getGroupColor(group: Pick<Group, "name">) {+export function getGroupColor(group: Pick<GroupInfo, "magic_group_type">) {if (isAdminGroup(group)) {return color("filter");} else if (isDefaultGroup(group)) {@@ -36,6 +39,6 @@ export function getGroupColor(group: Pick<Group, "name">) {}}-export function getGroupNameLocalized(group: Pick<Group, "name">) {+export function getGroupNameLocalized(group: Pick<GroupInfo, "name">) {return SPECIAL_GROUP_NAMES.get(group.name) ?? group.name;}diff --git a/frontend/src/metabase/lib/string.js b/frontend/src/metabase/lib/string.jsnew file mode 100644index 00000000000..5dd7aced30f--- /dev/null+++ b/frontend/src/metabase/lib/string.js@@ -0,0 +1,23 @@+import _ from "underscore";++// Creates a regex that will find an order dependent, case insensitive substring. All whitespace will be rendered as ".*" in the regex, to create a fuzzy search.+export function createMultiwordSearchRegex(input) {+ if (input) {+ return new RegExp(_.map(input.split(/\s+/), regexpEscape).join(".*?"), "i");+ }+}++// prefix special characters with "\" for creating a regex+export function regexpEscape(s) {+ const regexpSpecialChars = /[\^\$\\\.\*\+\?\(\)\[\]\{\}\|]/g;+ // "$&" in the replacement string is replaced with the matched string+ return s.replace(regexpSpecialChars, "\\$&");+}++export function caseInsensitiveSearch(haystack, needle) {+ return (+ !needle ||+ (haystack != null &&+ haystack.toLowerCase().indexOf(needle.toLowerCase()) >= 0)+ );+}diff --git a/frontend/src/metabase/lib/urls/admin.ts b/frontend/src/metabase/lib/urls/admin.tsindex 3b134e6563a..b62b9e6ce57 100644--- a/frontend/src/metabase/lib/urls/admin.ts+++ b/frontend/src/metabase/lib/urls/admin.ts@@ -1,36 +1,53 @@import type {+ BaseUser,DatabaseId,FieldId,SchemaName,SegmentId,TableId,- UserId,} from "metabase-types/api";+export const isInternalUser = (user: BaseUser) => user.tenant_id === null;+export function newUser() {return `/admin/people/new`;}+export function newTenantUser() {+ return "/admin/tenants/people/new";+}-export function editUser(userId: UserId) {- return `/admin/people/${userId}/edit`;+export function editUser(user: BaseUser) {+ return isInternalUser(user)+ ? `/admin/people/${user.id}/edit`+ : `/admin/tenants/people/${user.id}/edit`;}-export function resetPassword(userId: UserId) {- return `/admin/people/${userId}/reset`;+export function resetPassword(user: BaseUser) {+ return isInternalUser(user)+ ? `/admin/people/${user.id}/reset`+ : `/admin/tenants/people/${user.id}/reset`;}-export function newUserSuccess(userId: UserId) {- return `/admin/people/${userId}/success`;+export function newUserSuccess(user: BaseUser) {+ return isInternalUser(user)+ ? `/admin/people/${user.id}/success`+ : `/admin/tenants/people/${user.id}/success`;}-export function deactivateUser(userId: UserId) {- return `/admin/people/${userId}/deactivate`;+export function deactivateUser(user: BaseUser) {+ return isInternalUser(user)+ ? `/admin/people/${user.id}/deactivate`+ : `/admin/tenants/people/${user.id}/deactivate`;}-export function reactivateUser(userId: UserId) {- return `/admin/people/${userId}/reactivate`;+export function reactivateUser(user: BaseUser) {+ return isInternalUser(user)+ ? `/admin/people/${user.id}/reactivate`+ : `/admin/tenants/people/${user.id}/reactivate`;}+// TODO: move to EE urls+export function newDatabase() {return `/admin/databases/create`;}diff --git a/frontend/src/metabase/lib/urls/collections.ts b/frontend/src/metabase/lib/urls/collections.tsindex 35094ff90f5..635791b7f1c 100644--- a/frontend/src/metabase/lib/urls/collections.ts+++ b/frontend/src/metabase/lib/urls/collections.ts@@ -13,6 +13,8 @@ import { appendSlug, extractEntityId } from "./utils";export const otherUsersPersonalCollections = () => "/collection/users";+export const tenantSpecificCollections = () => "/collection/tenant-specific";+type Collection = Pick<BaseCollection,"id" | "name" | "originalName" | "personal_owner_id" | "type"@@ -65,7 +67,7 @@ export function isCollectionPath(path: string) {}export function extractCollectionId(slug = ""): CollectionId | undefined {- if (slug === "root" || slug === "users") {+ if (slug === "root" || slug === "users" || slug === "tenant-specific") {return slug;}return extractEntityId(slug);diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsxindex f878010371c..ff74a587ee2 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx@@ -2,7 +2,7 @@ import { t } from "ttag";import { Nav as DetailViewNav } from "metabase/detail-view/components";import { DETAIL_VIEW_PADDING_LEFT } from "metabase/detail-view/constants";-import { PLUGIN_METABOT } from "metabase/plugins";+import { PLUGIN_METABOT, PLUGIN_REMOTE_SYNC } from "metabase/plugins";import { Box, Flex } from "metabase/ui";import type { CollectionId } from "metabase-types/api";import type { DetailViewState } from "metabase-types/store";@@ -74,6 +74,7 @@ const AppBarLarge = ({isLogoVisible={isLogoVisible}isNavBarEnabled={isNavBarEnabled}/>+ <PLUGIN_REMOTE_SYNC.GitSyncAppBarControls /><AppBarInfoContainerisVisible={!isNavBarVisible || isQuestionLineageVisible}>diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsxindex 3c30636f484..e00261c5025 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx@@ -21,9 +21,13 @@ import Collections, {getCollectionIcon,} from "metabase/entities/collections";import Databases from "metabase/entities/databases";-import { connect } from "metabase/lib/redux";+import { connect, useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";-import { getUser, getUserIsAdmin } from "metabase/selectors/user";+import {+ getUser,+ getUserCanWriteToCollections,+ getUserIsAdmin,+} from "metabase/selectors/user";import type Database from "metabase-lib/v1/metadata/Database";import type { Bookmark, Collection, User } from "metabase-types/api";import type { State } from "metabase-types/store";@@ -87,12 +91,18 @@ function MainNavbarContainer({...props}: Props) {const [modal, setModal] = useState<NavbarModal>(null);+ const canWriteToCollections = useSelector(getUserCanWriteToCollections);const {data: trashCollection,isLoading,error,- } = useGetCollectionQuery({ id: "trash" });+ } = useGetCollectionQuery(+ {+ id: "trash",+ },+ { skip: !canWriteToCollections },+ );const { data: collections = [] } = useListCollectionsTreeQuery({"exclude-other-user-collections": true,diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsxindex 36a3a5a9205..bff091d1f51 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx@@ -9,7 +9,6 @@ import {isExamplesCollection,isLibraryCollection,isRootTrashCollection,- isSyncedCollection,} from "metabase/collections/utils";import CollapseSection from "metabase/common/components/CollapseSection";import { Tree } from "metabase/common/components/tree";@@ -24,7 +23,12 @@ import { isSmallScreen } from "metabase/lib/dom";import { useSelector } from "metabase/lib/redux";import * as Urls from "metabase/lib/urls";import { WhatsNewNotification } from "metabase/nav/components/WhatsNewNotification";-import { PLUGIN_DATA_STUDIO, PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import {+ PLUGIN_DATA_STUDIO,+ PLUGIN_REMOTE_SYNC,+ PLUGIN_TENANTS,+} from "metabase/plugins";+import { getUserCanWriteToCollections } from "metabase/selectors/user";import { ActionIcon, Icon, Tooltip } from "metabase/ui";import type { Bookmark } from "metabase-types/api";@@ -85,7 +89,7 @@ export function MainNavbarView({);const isAtHomepageDashboard = useIsAtHomepageDashboard();- const showSyncGroup = useSetting("remote-sync-type") === "read-write";+ const canWriteToCollections = useSelector(getUserCanWriteToCollections);const [addDataModalOpened,@@ -117,50 +121,27 @@ export function MainNavbarView({[isAtHomepageDashboard, onItemSelect],);- const {- regularCollections,- trashCollection,- examplesCollection,- syncedCollections,- } = useMemo(() => {- const syncedCollections = collections.filter(isSyncedCollection);- const trashCollection = collections.find(isRootTrashCollection);- const examplesCollection = collections.find(isExamplesCollection);-- const regularCollections = collections.filter((c) => {- const isNormalCollection =- !isRootTrashCollection(c) && !isExamplesCollection(c);- return (- isNormalCollection && !isSyncedCollection(c) && !isLibraryCollection(c)- );- });+ const { regularCollections, trashCollection, examplesCollection } =+ useMemo(() => {+ const trashCollection = collections.find(isRootTrashCollection);+ const examplesCollection = collections.find(isExamplesCollection);- const shouldMoveSyncedCollectionToTop =- !showSyncGroup &&- syncedCollections.length > 0 &&- regularCollections.length > 0;+ const regularCollections = collections.filter((c) => {+ const isNormalCollection =+ !isRootTrashCollection(c) && !isExamplesCollection(c);+ return isNormalCollection && !isLibraryCollection(c);+ });- const collectionsByCategory = {- trashCollection,- examplesCollection,- syncedCollections,- };-- if (shouldMoveSyncedCollectionToTop) {- const [root, ...rest] = regularCollections;- const reordered = [root, ...syncedCollections, ...rest];+ const collectionsByCategory = {+ trashCollection,+ examplesCollection,+ };return {...collectionsByCategory,- regularCollections: reordered,+ regularCollections,};- }-- return {- ...collectionsByCategory,- regularCollections,- };- }, [collections, showSyncGroup]);+ }, [collections]);const isNewInstance = useSelector(getIsNewInstance);const canAccessOnboarding = useSelector(getCanAccessOnboardingPage);@@ -170,6 +151,11 @@ export function MainNavbarView({const areThereOtherUsers = (activeUsersCount ?? 0) > 1;const showOtherUsersCollections = isAdmin && areThereOtherUsers;+ const useTenants = useSetting("use-tenants");+ const collectionsHeading = useTenants+ ? t`Internal Collections`+ : t`Collections`;+return (<ErrorBoundary><SidebarContentRoot>@@ -225,13 +211,7 @@ export function MainNavbarView({</SidebarSection>)}- {showSyncGroup && (- <PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection- onItemSelect={onItemSelect}- selectedId={collectionItem?.id}- syncedCollections={syncedCollections}- />- )}+ <PLUGIN_TENANTS.MainNavSharedCollections />{PLUGIN_DATA_STUDIO.isEnabled && (<PLUGIN_DATA_STUDIO.NavbarLibrarySection@@ -244,36 +224,46 @@ export function MainNavbarView({<SidebarSection><ErrorBoundary><CollapseSection- header={<SidebarHeading>{t`Collections`}</SidebarHeading>}+ header={<SidebarHeading>{collectionsHeading}</SidebarHeading>}initialState={expandCollections ? "expanded" : "collapsed"}iconPosition="right"iconSize={8}onToggle={setExpandCollections}rightAction={- <Tooltip label={t`Create a new collection`}>- <ActionIcon- aria-label={t`Create a new collection`}- color="var(--mb-color-text-medium)"- onClick={() => {- trackNewCollectionFromNavInitiated();- handleCreateNewCollection();- }}- >- <Icon name="add" />- </ActionIcon>- </Tooltip>+ canWriteToCollections ? (+ <Tooltip label={t`Create a new collection`}>+ <ActionIcon+ aria-label={t`Create a new collection`}+ color="var(--mb-color-text-medium)"+ onClick={() => {+ trackNewCollectionFromNavInitiated();+ handleCreateNewCollection();+ }}+ >+ <Icon name="add" />+ </ActionIcon>+ </Tooltip>+ ) : null}role="section"aria-label={t`Collections`}>- <Tree- data={regularCollections}- selectedId={collectionItem?.id}- onSelect={onItemSelect}- TreeNode={SidebarCollectionLink}- role="tree"- aria-label="collection-tree"- />+ {PLUGIN_REMOTE_SYNC.CollectionsNavTree ? (+ <PLUGIN_REMOTE_SYNC.CollectionsNavTree+ collections={regularCollections}+ selectedId={collectionItem?.id}+ onSelect={onItemSelect}+ />+ ) : (+ <Tree+ data={regularCollections}+ selectedId={collectionItem?.id}+ onSelect={onItemSelect}+ TreeNode={SidebarCollectionLink}+ role="tree"+ aria-label="collection-tree"+ />+ )}{showOtherUsersCollections && (<PaddedSidebarLinkicon="group"@@ -310,9 +300,9 @@ export function MainNavbarView({</ErrorBoundary></TrashSidebarSection>)}- </div>- <div>- <WhatsNewNotification />+ <div>+ <WhatsNewNotification />+ </div></div></SidebarContentRoot>diff --git a/frontend/src/metabase/nav/containers/MainNavbar/tests/common.unit.spec.tsx b/frontend/src/metabase/nav/containers/MainNavbar/tests/common.unit.spec.tsxindex 39665039194..b9849688335 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/tests/common.unit.spec.tsx@@ -357,6 +357,24 @@ describe("nav > containers > MainNavbar", () => {expect(screen.getByRole("treeitem", { name: /Our analytics/i }),).toHaveAttribute("aria-selected", "false");++ expect(+ screen.getByRole("button", { name: "Create a new collection" }),+ ).toBeInTheDocument();+ });++ it("should not display the new collection button if a user has no write permisisons", async () => {+ await setup({+ user: createMockUser({ can_write_any_collection: false }),+ });++ expect(+ await screen.findByRole("treeitem", { name: /Our analytics/i }),+ ).toBeInTheDocument();++ expect(+ screen.queryByRole("button", { name: "Create a new collection" }),+ ).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsxindex 3b603d6fd52..66947e19171 100644--- a/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx+++ b/frontend/src/metabase/nav/containers/MainNavbar/tests/setup.tsx@@ -138,6 +138,7 @@ export async function setup({setupCollectionsEndpoints({collections,rootCollection: OUR_ANALYTICS,+ currentUserId: user?.id,});setupCollectionByIdEndpoint({collections: [PERSONAL_COLLECTION_BASE, TEST_COLLECTION],diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 32ac3d926fe..9cb71c15997 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -102,6 +102,7 @@ export {PLUGIN_ADMIN_USER_MENU_ROUTES,PLUGIN_ADVANCED_PERMISSIONS,PLUGIN_FEATURE_LEVEL_PERMISSIONS,+ PLUGIN_ADMIN_PERMISSIONS_TABS,PLUGIN_APPLICATION_PERMISSIONS,PLUGIN_GROUP_MANAGERS,} from "./oss/permissions";@@ -138,6 +139,7 @@ export {export { PLUGIN_UPLOAD_MANAGEMENT } from "./oss/upload-management";export { PLUGIN_WHITELABEL } from "./oss/whitelabel";export { PLUGIN_SUPPORT } from "./oss/support";+export { PLUGIN_TENANTS } from "./oss/tenants";// Re-export types that are used by other filesexport type {@@ -176,6 +178,7 @@ import { reinitialize as reinitializeSettings } from "./oss/settings";import { reinitialize as reinitializeSmtpOverride } from "./oss/smtp-override";import { reinitialize as reinitializeSnippets } from "./oss/snippets";import { reinitialize as reinitializeSupport } from "./oss/support";+import { reinitialize as reinitializeTenants } from "./oss/tenants";import { reinitialize as reinitializeTransforms } from "./oss/transforms";import { reinitialize as reinitializeUploadManagement } from "./oss/upload-management";import { reinitialize as reinitializeWhitelabel } from "./oss/whitelabel";@@ -215,6 +218,7 @@ export function reinitialize() {reinitializeSmtpOverride();reinitializeSnippets();reinitializeSupport();+ reinitializeTenants();reinitializeTransforms();reinitializeUploadManagement();reinitializeWhitelabel();diff --git a/frontend/src/metabase/plugins/oss/collections.ts b/frontend/src/metabase/plugins/oss/collections.tsindex 4a453751d71..8f4e99f622e 100644--- a/frontend/src/metabase/plugins/oss/collections.ts+++ b/frontend/src/metabase/plugins/oss/collections.ts@@ -2,7 +2,7 @@ import type React from "react";import type { ComponentType } from "react";import { t } from "ttag";-import { UNABLE_TO_CHANGE_ADMIN_PERMISSIONS } from "metabase/admin/permissions/constants/messages";+import { Messages } from "metabase/admin/permissions/constants/messages";import { getIconBase } from "metabase/lib/icon";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type { IconProps } from "metabase/ui";@@ -70,7 +70,8 @@ const getDefaultPluginCollections = () => ({AUTHORITY_LEVEL_REGULAR,useGetDefaultCollectionId: null as GetCollectionIdType | null,CUSTOM_INSTANCE_ANALYTICS_COLLECTION_ENTITY_ID: "" as BaseEntityId | "",- INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE: UNABLE_TO_CHANGE_ADMIN_PERMISSIONS,+ INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE:+ Messages.UNABLE_TO_CHANGE_ADMIN_PERMISSIONS,getAuthorityLevelMenuItems: (_collection: Collection,_onUpdate: (collection: Collection, values: Partial<Collection>) => void,diff --git a/frontend/src/metabase/plugins/oss/permissions.ts b/frontend/src/metabase/plugins/oss/permissions.tsindex d6204ac000d..1019b9bebf2 100644--- a/frontend/src/metabase/plugins/oss/permissions.ts+++ b/frontend/src/metabase/plugins/oss/permissions.ts@@ -106,7 +106,7 @@ export const PLUGIN_DATA_PERMISSIONS: {const getDefaultAdminUserMenuItems = (): Array<(user: User) => React.ReactNode> => [];-const getDefaultAdminUserMenuRoutes = () => [];+const getDefaultAdminUserMenuRoutes = (): (() => React.ReactNode)[] => [];export const PLUGIN_ADMIN_USER_MENU_ITEMS = getDefaultAdminUserMenuItems();export const PLUGIN_ADMIN_USER_MENU_ROUTES = getDefaultAdminUserMenuRoutes();@@ -135,14 +135,17 @@ const getDefaultFeatureLevelPermissions = () => ({_entityId: DatabaseEntityId,_groupId: number,_isAdmin: boolean,+ _isExternal: boolean,_permissions: GroupsPermissions,_dataAccessPermissionValue: DataPermissionValue,_defaultGroup: Group,_permissionSubject: PermissionSubject,+ _permissionView?: "group" | "database",) => {return [] as any;},- getDataColumns: (_subject: PermissionSubject) => [] as any,+ getDataColumns: (_subject: PermissionSubject, _isExternal?: boolean) =>+ [] as any,getDownloadWidgetMessageOverride: (_result: Dataset): string | null => null,canDownloadResults: (_result: Dataset): boolean => true,canAccessDataModel: (state: State): boolean => getUserIsAdmin(state),@@ -153,6 +156,13 @@ const getDefaultFeatureLevelPermissions = () => ({export const PLUGIN_FEATURE_LEVEL_PERMISSIONS =getDefaultFeatureLevelPermissions();+const getDefaultAdminPermissionsTabs = () => ({+ getRoutes: (): ReactNode => null,+ tabs: [] as { name: string; value: string }[],+});++export const PLUGIN_ADMIN_PERMISSIONS_TABS = getDefaultAdminPermissionsTabs();+const getDefaultApplicationPermissions = () => ({getRoutes: (): ReactNode => null,tabs: [] as any,@@ -249,6 +259,12 @@ export function reinitialize() {PLUGIN_FEATURE_LEVEL_PERMISSIONS,getDefaultFeatureLevelPermissions(),);++ Object.assign(+ PLUGIN_ADMIN_PERMISSIONS_TABS,+ getDefaultAdminPermissionsTabs(),+ );+Object.assign(PLUGIN_APPLICATION_PERMISSIONS,getDefaultApplicationPermissions(),diff --git a/frontend/src/metabase/plugins/oss/remote-sync.ts b/frontend/src/metabase/plugins/oss/remote-sync.tsindex cd348f91cdd..11689894172 100644--- a/frontend/src/metabase/plugins/oss/remote-sync.ts+++ b/frontend/src/metabase/plugins/oss/remote-sync.ts@@ -1,6 +1,8 @@import type { TagDescription } from "@reduxjs/toolkit/query";import type { ComponentType, ReactNode } from "react";+import type { ITreeNodeItem } from "metabase/common/components/tree/types";+import type { CollectionTreeItem } from "metabase/entities/collections";import {NotFoundPlaceholder,PluginPlaceholder,@@ -8,10 +10,18 @@ import {import type { SyncedCollectionsSidebarSectionProps } from "../types";+export type CollectionsNavTreeProps = {+ collections: CollectionTreeItem[];+ selectedId?: number | string;+ onSelect?: (item: ITreeNodeItem) => void;+};+const getDefaultPluginRemoteSync = () => ({LibraryNav: PluginPlaceholder,RemoteSyncSettings: NotFoundPlaceholder,SyncedCollectionsSidebarSection: PluginPlaceholder,+ GitSyncAppBarControls: PluginPlaceholder,+ CollectionsNavTree: null as ComponentType<CollectionsNavTreeProps> | null,REMOTE_SYNC_INVALIDATION_TAGS: null,useSyncStatus: () => ({isIdle: true,@@ -26,6 +36,8 @@ export const PLUGIN_REMOTE_SYNC: {LibraryNav: ComponentType;RemoteSyncSettings: ComponentType;SyncedCollectionsSidebarSection: ComponentType<SyncedCollectionsSidebarSectionProps>;+ GitSyncAppBarControls: ComponentType;+ CollectionsNavTree: ComponentType<CollectionsNavTreeProps> | null;REMOTE_SYNC_INVALIDATION_TAGS: TagDescription<any>[] | null;useSyncStatus: () => {isIdle: boolean;diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.tsnew file mode 100644index 00000000000..98142a540fa--- /dev/null+++ b/frontend/src/metabase/plugins/oss/tenants.ts@@ -0,0 +1,117 @@+import type React from "react";++import type { CollectionItemListProps } from "metabase/common/components/Pickers/CollectionPicker/types";+import type {+ Collection,+ CollectionId,+ CollectionNamespace,+ Group,+ User,+} from "metabase-types/api";++import { PluginPlaceholder } from "../components/PluginPlaceholder";++export type TenantCollectionPathItem = {+ id: CollectionId;+ namespace?: CollectionNamespace;+ type?: Collection["type"];+ collection_id?: CollectionId | null;+ collection_namespace?: CollectionNamespace;+ is_shared_tenant_collection?: boolean;+ is_tenant_dashboard?: boolean;+};++const getDefaultPluginTenants = () => ({+ isEnabled: false,+ userStrategyRoute: null as React.ReactElement | null,+ tenantsRoutes: null as React.ReactElement | null,+ EditUserStrategySettingsButton: PluginPlaceholder,+ FormTenantWidget: (_props: any) => null as React.ReactElement | null,+ TenantDisplayName: (_props: any) => null as React.ReactElement | null,+ isExternalUsersGroup: (_group: Pick<Group, "magic_group_type">) => false,+ isTenantGroup: (_group: Pick<Group, "is_tenant_group">) => false,+ isExternalUser: (_user?: Pick<User, "tenant_id">) => false,+ isTenantCollection: (_collection: Collection) => false,+ PeopleNav: null as React.ReactElement | null,+ ReactivateExternalUserButton: ({ user: _user }: { user: User }) =>+ null as React.ReactElement | null,+ TenantGroupHintIcon: PluginPlaceholder,+ MainNavSharedCollections: PluginPlaceholder,+ TenantCollectionItemList: (_props: CollectionItemListProps) =>+ null as React.ReactElement | null,+ TenantSpecificCollectionsItemList: (_props: CollectionItemListProps) =>+ null as React.ReactElement | null,+ TenantCollectionList: PluginPlaceholder,+ GroupDescription: (_props: { group: Group }) =>+ null as React.ReactElement | null,+ getNewUserModalTitle: (_isExternal: boolean) => null as string | null,+ getFormGroupsTitle: (_isExternal: boolean) => null as string | null,+ SHARED_TENANT_NAMESPACE: null as CollectionNamespace,+ isTenantNamespace: (_namespace?: CollectionNamespace) => false,+ isTenantCollectionId: (_id: CollectionId) => false,+ getNamespaceForTenantId: (_id: CollectionId) => null as CollectionNamespace,+ getTenantCollectionPathPrefix: (_collection: TenantCollectionPathItem) =>+ null as CollectionId[] | null,+ getTenantRootDisabledReason: () => null as string | null,+ getNamespaceDisplayName: (_namespace?: CollectionNamespace) =>+ null as string | null,+ TENANT_SPECIFIC_COLLECTIONS: null as {+ id: "tenant-specific";+ name: string;+ location: string;+ path: CollectionId[];+ can_write: boolean;+ } | null,+});++export const PLUGIN_TENANTS: {+ isEnabled: boolean;+ userStrategyRoute: React.ReactElement | null;+ tenantsRoutes: React.ReactElement | null;+ EditUserStrategySettingsButton: React.ComponentType;+ FormTenantWidget: (props: any) => React.ReactElement | null;+ TenantDisplayName: (props: any) => React.ReactElement | null;+ isExternalUsersGroup: (group: Pick<Group, "magic_group_type">) => boolean;+ isTenantGroup: (group: Pick<Group, "is_tenant_group">) => boolean;+ isExternalUser: (user?: Pick<User, "tenant_id">) => boolean;+ isTenantCollection: (collection: Collection) => boolean;+ PeopleNav: React.ReactElement | null;+ ReactivateExternalUserButton: (props: {+ user: User;+ }) => React.ReactElement | null;+ TenantGroupHintIcon: React.ComponentType;+ MainNavSharedCollections: React.ComponentType;+ TenantCollectionItemList: (+ props: CollectionItemListProps,+ ) => React.ReactElement | null;+ TenantSpecificCollectionsItemList: (+ props: CollectionItemListProps,+ ) => React.ReactElement | null;+ TenantCollectionList: React.ComponentType;+ GroupDescription: (props: { group: Group }) => React.ReactElement | null;+ getNewUserModalTitle: (isExternal: boolean) => string | null;+ getFormGroupsTitle: (isExternal: boolean) => string | null;+ SHARED_TENANT_NAMESPACE: CollectionNamespace;+ isTenantNamespace: (namespace?: CollectionNamespace) => boolean;+ isTenantCollectionId: (id: CollectionId) => boolean;+ getNamespaceForTenantId: (id: CollectionId) => CollectionNamespace;+ getTenantCollectionPathPrefix: (+ collection: TenantCollectionPathItem,+ ) => CollectionId[] | null;+ getTenantRootDisabledReason: () => string | null;+ getNamespaceDisplayName: (namespace?: CollectionNamespace) => string | null;+ TENANT_SPECIFIC_COLLECTIONS: {+ id: "tenant-specific";+ name: string;+ location: string;+ path: CollectionId[];+ can_write: boolean;+ } | null;+} = getDefaultPluginTenants();++/**+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.+ */+export function reinitialize() {+ Object.assign(PLUGIN_TENANTS, getDefaultPluginTenants());+}diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsxindex 1e71937fee4..6ec964e3f2c 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/ViewTitleHeaderRightSide.tsx@@ -6,6 +6,7 @@ import { t } from "ttag";import CS from "metabase/css/core/index.css";import { QuestionSharingMenu } from "metabase/embedding/components/SharingMenu";import { SERVER_ERROR_TYPES } from "metabase/lib/errors";+import { useSelector } from "metabase/lib/redux";import MetabaseSettings from "metabase/lib/settings";import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";import { PLUGIN_AI_ENTITY_ANALYSIS } from "metabase/plugins";@@ -13,6 +14,7 @@ import RunButtonWithTooltip from "metabase/query_builder/components/RunButtonWitimport { canExploreResults } from "metabase/query_builder/components/view/ViewHeader/utils";import type { QueryModalType } from "metabase/query_builder/constants";import { MODAL_TYPES } from "metabase/query_builder/constants";+import { getUserCanWriteToCollections } from "metabase/selectors/user";import { Box, Button, Flex, Tooltip } from "metabase/ui";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";@@ -98,6 +100,7 @@ export function ViewTitleHeaderRightSide({}: ViewTitleHeaderRightSideProps): React.JSX.Element {const isShowingNotebook = queryBuilderMode === "notebook";const { isEditable } = Lib.queryDisplayInfo(question.query());+ const canWriteToCollections = useSelector(getUserCanWriteToCollections);const hasExploreResultsLink =canExploreResults(question) &&@@ -110,7 +113,9 @@ export function ViewTitleHeaderRightSide({!isModelOrMetric &&isDirty &&!question.isArchived() &&- isActionListVisible;+ isActionListVisible &&+ canWriteToCollections;+const isMissingPermissions =result?.error_type === SERVER_ERROR_TYPES.missingPermissions;const hasRunButton =@@ -223,7 +228,9 @@ export function ViewTitleHeaderRightSide({/></Box>)}- {!isShowingNotebook && <QuestionSharingMenu question={question} />}+ {!isShowingNotebook && (hasSaveButton || isSaved) && (+ <QuestionSharingMenu question={question} />+ )}{!isShowingNotebook &&PLUGIN_AI_ENTITY_ANALYSIS.canAnalyzeQuestion(question) ? (<PLUGIN_AI_ENTITY_ANALYSIS.AIQuestionAnalysisButton />diff --git a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsxindex f5a7a16c296..b50424ebdf6 100644--- a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx+++ b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx@@ -260,6 +260,9 @@ export const MoveCardModal = ({ card, onClose }: MoveCardModalProps) => {}};+ // Determine the savingModel based on card type+ const savingModel = card.type === "model" ? "model" : "question";+return (<MoveModaltitle={t`Where do you want to save this?`}@@ -269,6 +272,7 @@ export const MoveCardModal = ({ card, onClose }: MoveCardModalProps) => {canMoveToDashboard={card.type === "question"}entityType={getEntityTypeFromCardType(card.type)}recentAndSearchFilter={recentAndSearchFilter}+ savingModel={savingModel}/>);};diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsxindex 5f20104f7c3..a4c19f9f845 100644--- a/frontend/src/metabase/routes.jsx+++ b/frontend/src/metabase/routes.jsx@@ -44,6 +44,7 @@ import {PLUGIN_LANDING_PAGE,PLUGIN_METABOT,PLUGIN_TABLE_EDITING,+ PLUGIN_TENANTS,} from "metabase/plugins";import { QueryBuilder } from "metabase/query_builder/containers/QueryBuilder";import { loadCurrentUser } from "metabase/redux/user";@@ -184,6 +185,10 @@ export const getRoutes = (store) => {<IndexRoute component={UserCollectionList} /></Route>+ <Route path="collection/tenant-specific" component={IsAdmin}>+ <IndexRoute component={PLUGIN_TENANTS.TenantCollectionList} />+ </Route>+<Route path="collection/:slug" component={CollectionLanding}><ModalRoute path="move" modal={MoveCollectionModal} noWrap /><ModalRoute path="archive" modal={ArchiveCollectionModal} noWrap />diff --git a/frontend/src/metabase/selectors/user.ts b/frontend/src/metabase/selectors/user.tsindex bd9fc84ed37..5e91bfc0065 100644--- a/frontend/src/metabase/selectors/user.ts+++ b/frontend/src/metabase/selectors/user.ts@@ -49,3 +49,8 @@ export const canUserCreateNativeQueries = createSelector([getUser],(user) => user?.permissions?.can_create_native_queries ?? false,);++export const getUserCanWriteToCollections = createSelector(+ [getUser],+ (user) => user?.can_write_any_collection,+);diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/add_collection.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/add_collection.svgnew file mode 100644index 00000000000..a13adbfb58d--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/add_collection.svg@@ -0,0 +1,3 @@+<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg">+ <path d="M11.75 10C12.1642 10 12.5 10.3358 12.5 10.75V12H13.75C14.1642 12 14.5 12.3358 14.5 12.75C14.5 13.1642 14.1642 13.5 13.75 13.5H12.5V14.75C12.5 15.1642 12.1642 15.5 11.75 15.5C11.3358 15.5 11 15.1642 11 14.75V13.5H9.75C9.33579 13.5 9 13.1642 9 12.75C9 12.3358 9.33579 12 9.75 12H11V10.75C11 10.3358 11.3358 10 11.75 10ZM8.29004 4.06836H12.7998C13.2991 4.06836 13.7888 4.25177 14.1582 4.59375C14.5293 4.93751 14.75 5.41679 14.75 5.92969V9H13.25V5.92969C13.25 5.85336 13.2175 5.7673 13.1387 5.69434C13.0579 5.61957 12.937 5.56836 12.7998 5.56836H7.70996L5.70996 3.75H3.2002C3.06305 3.75 2.94207 3.80123 2.86133 3.87598C2.78252 3.94894 2.75 4.035 2.75 4.11133V11.8887C2.75 11.965 2.78252 12.0511 2.86133 12.124C2.94207 12.1988 3.06306 12.25 3.2002 12.25H7V13.75H3.2002C2.70086 13.75 2.21114 13.5666 1.8418 13.2246C1.47063 12.8808 1.25 12.4016 1.25 11.8887V4.11133C1.25 3.59838 1.47063 3.11916 1.8418 2.77539C2.21114 2.4334 2.70086 2.25 3.2002 2.25H6.29004L8.29004 4.06836Z"/>+</svg>diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex ac51412adb8..066e4bddbfe 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -4,6 +4,8 @@ import one_million_component from "./1m.svg?component";import one_million_source from "./1m.svg?source";import add_component from "./add.svg?component";import add_source from "./add.svg?source";+import add_collection_component from "./add_collection.svg?component";+import add_collection_source from "./add_collection.svg?source";import add_column_component from "./add_column.svg?component";import add_column_source from "./add_column.svg?source";import add_comment_component from "./add_comment.svg?component";@@ -543,6 +545,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: add_component,source: add_source,},+ add_collection: {+ component: add_collection_component,+ source: add_collection_source,+ },add_column: {component: add_column_component,source: add_column_source,@@ -1631,6 +1637,7 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =*/export type IconName =| "add"+ | "add_collection"| "add_column"| "add_data"| "add_folder"diff --git a/frontend/test/__support__/server-mocks/collection.ts b/frontend/test/__support__/server-mocks/collection.tsindex 308b995e722..529a9280758 100644--- a/frontend/test/__support__/server-mocks/collection.ts+++ b/frontend/test/__support__/server-mocks/collection.ts@@ -27,12 +27,14 @@ export interface CollectionEndpoints {collections: Collection[];rootCollection?: Collection;trashCollection?: Collection;+ currentUserId?: number;}export function setupCollectionsEndpoints({collections,rootCollection = createMockCollection(ROOT_COLLECTION),trashCollection = mockTrashCollection,+ currentUserId,}: CollectionEndpoints) {fetchMock.get("path:/api/collection/root", rootCollection, {name: "collection-root",@@ -44,15 +46,71 @@ export function setupCollectionsEndpoints({name: `collection-${trashCollection.id}`,});fetchMock.get(- "path:/api/collection/tree",- collections.filter((collection) => !collection.archived),- { name: "collection-tree-exclude-archived" },+ "path:/api/collection",+ (call) => {+ const url = new URL(call.url);++ const excludeOtherUserCollections =+ url.searchParams.get("exclude-other-user-collections") === "true";++ return collections.filter((collection) => {+ // Filter out other users' personal collections if requested+ // But keep the current user's personal collection+ if (+ excludeOtherUserCollections &&+ typeof collection.personal_owner_id === "number" &&+ collection.personal_owner_id !== currentUserId+ ) {+ return false;+ }++ return true;+ });+ },+ {+ name: "collection-list",+ },);- fetchMock.get("path:/api/collection/tree", collections, {- name: "collection-tree",- });- fetchMock.get("path:/api/collection", collections, {- name: "collection-list",++ fetchMock.get("path:/api/collection/tree", (call) => {+ const url = new URL(call.url);+ const excludeArchived = url.searchParams.get("exclude-archived") === "true";++ const excludeOtherUserCollections =+ url.searchParams.get("exclude-other-user-collections") === "true";++ const namespace = url.searchParams.get("namespace");++ return collections.filter((collection) => {+ // Filter out other users' personal collections if requested+ // But keep the current user's personal collection+ if (+ excludeOtherUserCollections &&+ typeof collection.personal_owner_id === "number" &&+ collection.personal_owner_id !== currentUserId+ ) {+ return false;+ }++ // Filter out archived collections if requested+ if (excludeArchived && collection.archived) {+ return false;+ }++ // Filter by namespace if specified+ if (namespace && collection.namespace !== namespace) {+ return false;+ }++ // By default, exclude tenant collections unless explicitly requested via namespace+ const isTenantCollection =+ collection.namespace === "shared-tenant-collection";+ if (isTenantCollection && namespace !== "shared-tenant-collection") {+ return false;+ }++ return true;+ });});}@@ -90,6 +148,37 @@ export function setupCollectionVirtualSchemaEndpoints(});}+function handleCollectionItemsResponse({+ call,+ collectionItems,+ modelsParam,+}: {+ call: { url: string };+ collectionItems: CollectionItem[];+ modelsParam?: string[];+}) {+ const url = new URL(call.url);+ const models = modelsParam ?? url.searchParams.getAll("models");++ // When the models filter is an empty array, return all items.+ // In the API, omitting the `models` param returns all collection items.+ const matchedItems =+ models.length === 0+ ? collectionItems+ : collectionItems.filter(({ model }) => models.includes(model));++ const limit = Number(url.searchParams.get("limit")) || matchedItems.length;+ const offset = Number(url.searchParams.get("offset")) || 0;++ return {+ data: matchedItems.slice(offset, offset + limit),+ total: matchedItems.length,+ models,+ limit,+ offset,+ };+}+export function setupCollectionItemsEndpoint({collection,collectionItems = [],@@ -102,25 +191,78 @@ export function setupCollectionItemsEndpoint({fetchMock.get(`path:/api/collection/${collection.id}/items`,(call) => {+ return handleCollectionItemsResponse({+ call,+ collectionItems,+ modelsParam,+ });+ },+ { name: `collection-${collection.id}-items` },+ );+}++export function setupTenantCollectionItemsEndpoint({+ collection,+ collectionItems = [],+ models: modelsParam,+}: {+ collection: Pick<Collection, "id">;+ collectionItems: CollectionItem[];+ models?: string[];+}) {+ fetchMock.get(+ `path:/api/collection/${collection.id}/items`,+ (call: { url: string }) => {+ // Check if this is a tenant collection request+ if (call.url.includes("namespace=shared-tenant-collection")) {+ return handleCollectionItemsResponse({+ call,+ collectionItems,+ modelsParam,+ });+ }++ throw new Error("MOCK_SKIP");+ },+ {+ name: `tenant-collection-${collection.id}-items`,+ },+ );+}++export function setupRootCollectionItemsEndpoint({+ rootCollectionItems,+ tenantRootItems = [],+}: {+ rootCollectionItems: CollectionItem[];+ tenantRootItems?: CollectionItem[];+}) {+ fetchMock.get(+ `path:/api/collection/root/items`,+ (call: { url: string }) => {const url = new URL(call.url);- const models = modelsParam ?? url.searchParams.getAll("models");- const matchedItems = models?.length- ? collectionItems.filter(({ model }) => models.includes(model))- : collectionItems;+ const models = url.searchParams.getAll("models");- const limit =- Number(url.searchParams.get("limit")) || matchedItems.length;- const offset = Number(url.searchParams.get("offset")) || 0;+ // Check if it's a tenant request+ if (call.url.includes("namespace=shared-tenant-collection")) {+ return {+ data: tenantRootItems,+ total: tenantRootItems.length,+ models,+ limit: null,+ offset: null,+ };+ }return {- data: matchedItems.slice(offset, offset + limit),- total: matchedItems.length,+ data: rootCollectionItems,+ total: rootCollectionItems.length,models,- limit,- offset,+ limit: null,+ offset: null,};},- { name: `collection-${collection.id}-items` },+ { name: "root-collection-items" },);}diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex b0d10fd932c..d8c2ee34090 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -34,6 +34,7 @@ export * from "./permissions";export * from "./premium-features";export * from "./public";export * from "./pulse";+export * from "./remote-sync";export * from "./revision";export * from "./search";export * from "./segment";@@ -45,6 +46,7 @@ export * from "./store";export * from "./support-access-grants";export * from "./table";export * from "./task";+export * from "./tenant";export * from "./timeline";export * from "./transform";export * from "./user";diff --git a/frontend/test/__support__/server-mocks/permissions.ts b/frontend/test/__support__/server-mocks/permissions.tsindex 64234987f04..eee8aff8399 100644--- a/frontend/test/__support__/server-mocks/permissions.ts+++ b/frontend/test/__support__/server-mocks/permissions.ts@@ -4,6 +4,7 @@ import type {CollectionPermissionsGraph,Database,Group,+ ListUserMembershipsResponse,} from "metabase-types/api";import { createMockPermissionsGraph } from "metabase-types/api/mocks";@@ -41,3 +42,9 @@ export const setupCollectionPermissionsGraphEndpoint = (return body;});};++export const setupPermissionMembershipEndpoint = (+ memberships: ListUserMembershipsResponse,+) => {+ fetchMock.get("path:/api/permissions/membership", memberships);+};diff --git a/frontend/test/__support__/server-mocks/remote-sync.ts b/frontend/test/__support__/server-mocks/remote-sync.tsnew file mode 100644index 00000000000..f5292de3014--- /dev/null+++ b/frontend/test/__support__/server-mocks/remote-sync.ts@@ -0,0 +1,22 @@+import fetchMock from "fetch-mock";++import type { RemoteSyncEntity } from "metabase-types/api";++export const setupRemoteSyncEndpoints = ({+ branches = ["main", "develop"],+ dirty = [],+ changedCollections = {},+}: {+ branches?: string[];+ dirty?: RemoteSyncEntity[];+ changedCollections?: Record<number, boolean>;+} = {}) => {+ fetchMock.get("path:/api/ee/remote-sync/branches", { items: branches });+ fetchMock.get("path:/api/ee/remote-sync/dirty", {+ dirty,+ changedCollections,+ });+ fetchMock.post("path:/api/ee/remote-sync/import", {});+ fetchMock.post("path:/api/ee/remote-sync/create-branch", {});+ fetchMock.get("path:/api/ee/remote-sync/current-task", { status: "idle" });+};diff --git a/frontend/test/__support__/server-mocks/tenant.ts b/frontend/test/__support__/server-mocks/tenant.tsnew file mode 100644index 00000000000..b9a385e8f93--- /dev/null+++ b/frontend/test/__support__/server-mocks/tenant.ts@@ -0,0 +1,7 @@+import fetchMock from "fetch-mock";++import type { Tenant } from "metabase-types/api";++export const setupTenantEntpoints = (tenants: Tenant[]) => {+ fetchMock.get(/\/api\/ee\/tenant/, { data: tenants });+};diff --git a/frontend/test/metabase/lib/string.unit.spec.js b/frontend/test/metabase/lib/string.unit.spec.jsnew file mode 100644index 00000000000..6632e327d42--- /dev/null+++ b/frontend/test/metabase/lib/string.unit.spec.js@@ -0,0 +1,17 @@+import { regexpEscape } from "metabase/lib/string";++describe("regexpEscape", () => {+ const testCases = [+ ["nothing special here", "nothing special here"],+ ["somewhat ./\\ special", "somewhat \\./\\\\ special"],+ [+ "extra special ^$\\.*+?()[]{}|",+ "extra special \\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|",+ ],+ ];+ for (const [raw, escaped] of testCases) {+ it(`should escape "${raw}" to "${escaped}"`, () => {+ expect(regexpEscape(raw)).toEqual(escaped);+ });+ }+});diff --git a/resources/migrations/058_update_migrations.yaml b/resources/migrations/058_update_migrations.yamlindex 4c60688c68b..45a949cc324 100644--- a/resources/migrations/058_update_migrations.yaml+++ b/resources/migrations/058_update_migrations.yaml@@ -773,6 +773,141 @@ databaseChangeLog:UPDATE metabase_tableSET data_layer = NULL+ - changeSet:+ id: v58.2025-11-18T12:31:27+ author: johnswanson+ comment: Create `tenant` table+ preConditions: # not needed+ changes:+ - createTable:+ tableName: tenant+ remarks: |+ Tenants (collections of external users). A user can be in exactly zero or one tenants.+ columns:+ - column:+ name: id+ type: int+ autoIncrement: true+ remarks: the ID of the tenant+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: "name"+ type: varchar(254)+ remarks: the unique name of the tenant+ constraints:+ nullable: false+ unique: true+ - column:+ name: "slug"+ type: varchar(254)+ remarks: "the slugified version of this tenant's name"+ constraints:+ nullable: false+ unique: true+ - column:+ name: "is_active"+ type: ${boolean.type}+ remarks: Whether the tenant is active or not+ defaultValueBoolean: true+ constraints:+ nullable: false+ - column:+ name: updated_at+ type: ${timestamp_type}+ remarks: The timestamp of when the tenant was updated+ constraints:+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: The timestamp of when the tenant was created+ constraints:+ nullable: false++ - changeSet:+ id: v58.2025-11-18T12:31:44+ author: johnswanson+ comment: add an index for `core_user.tenant_id`+ changes:+ - createIndex:+ tableName: core_user+ indexName: idx_core_user_tenant_id+ columns:+ - column:+ name: tenant_id++ - changeSet:+ id: v58.2025-11-18T12:31:47+ author: johnswanson+ comment: Add foreign key for `core_user.tenant_id`+ preConditions: # not needed+ changes:+ - addForeignKeyConstraint:+ baseTableName: core_user+ baseColumnNames: tenant_id+ referencedTableName: tenant+ referencedColumnNames: id+ constraintName: fk_core_user_tenant_id+ onDelete: RESTRICT++ - changeSet:+ id: v58.2025-11-18T12:31:49+ author: johnswanson+ comment: Rename any existing `@.+` user attributes to add a preceding underscore+ changes:+ - customChange:+ class: "metabase.app_db.custom_migrations.MoveExistingAtSymbolUserAttributes"++ - changeSet:+ id: v58.2025-11-18T12:31:51+ author: johnswanson+ comment: Mark users with `deactivated_with_tenant`+ changes:+ - addColumn:+ tableName: core_user+ columns:+ - column:+ name: deactivated_with_tenant+ remarks: |+ if this user and its tenant are both deactivated, represents whether the user was deactivated+ *with* the tenant (in which case it should be reactivated when the tenant is reactivated)+ or was deactivated independently.+ type: ${boolean.type}+ constraints:+ nullable: true++ - changeSet:+ id: v58.2025-11-18T12:31:53+ author: edpaget+ comment: add column for tenant attributes+ preConditions: # not needed+ changes:+ - addColumn:+ tableName: tenant+ columns:+ - column:+ name: attributes+ type: ${text.type}+ remarks: JSON object containing custom tenant attributes+ constraints:+ nullable: true+ - changeSet:+ id: v58.2025-11-18T12:31:54+ author: johnswanson+ comment: External Users groups+ rollback:+ - sql:+ sql: >-+ DELETE FROM permissions_group WHERE magic_group_type IN ('all-external-users', 'read-external-users', 'write-external-users');+ changes:+ - sql:+ sql: >-+ INSERT INTO permissions_group (name, magic_group_type, is_tenant_group)+ VALUES+ ('All tenant users', 'all-external-users', true);+- changeSet:id: v58.2025-11-19T00:00:00author: edpaget@@ -815,6 +950,52 @@ databaseChangeLog:- sql:sql: UPDATE collection SET type = 'remote-synced' WHERE is_remote_synced = true+ - changeSet:+ id: v58.2025-11-25T00:00:00+ author: edpaget+ comment: Add default read permissions for All Users group on shared-tenant-collection root+ changes:+ - sql:+ sql: >-+ INSERT INTO permissions (group_id, object)+ SELECT pg.id, '/collection/namespace/shared-tenant-collection/root/read/'+ FROM permissions_group pg+ WHERE pg.magic_group_type = 'all-internal-users'+ AND NOT EXISTS (+ SELECT 1 FROM permissions p+ WHERE p.group_id = pg.id+ AND p.object = '/collection/namespace/shared-tenant-collection/root/read/'+ );+ rollback:+ - sql:+ sql: >-+ DELETE FROM permissions+ WHERE object = '/collection/namespace/shared-tenant-collection/root/read/'+ AND group_id IN (SELECT id FROM permissions_group WHERE magic_group_type = 'all-internal-users');++ - changeSet:+ id: v58.2025-11-25T00:00:01+ author: edpaget+ comment: Add default read permissions for All External Users group on shared-tenant-collection root+ changes:+ - sql:+ sql: >-+ INSERT INTO permissions (group_id, object)+ SELECT pg.id, '/collection/namespace/shared-tenant-collection/root/read/'+ FROM permissions_group pg+ WHERE pg.magic_group_type = 'all-external-users'+ AND NOT EXISTS (+ SELECT 1 FROM permissions p+ WHERE p.group_id = pg.id+ AND p.object = '/collection/namespace/shared-tenant-collection/root/read/'+ );+ rollback:+ - sql:+ sql: >-+ DELETE FROM permissions+ WHERE object = '/collection/namespace/shared-tenant-collection/root/read/'+ AND group_id IN (SELECT id FROM permissions_group WHERE magic_group_type = 'all-external-users');+- changeSet:id: v58.2025-11-25T17:04:00author: dependencies@@ -890,6 +1071,21 @@ databaseChangeLog:constraints:nullable: false+ - changeSet:+ id: v58.2025-12-01T05:21:37+ author: johnswanson+ comment: Add a tenant_collection_id to tenants+ changes:+ - addColumn:+ tableName: tenant+ columns:+ - column:+ name: tenant_collection_id+ type: int+ remarks: The ID of the collection+ constraints:+ nullable: false+- changeSet:id: v58.2025-12-05T17:41:51author: ranquild@@ -964,38 +1160,6 @@ databaseChangeLog:value: 'library-models'where: type = 'library-data'- - changeSet:- id: v58.2025-12-09T00:00:00- author: nmezzopera- comment: Usage analytics; Add entity_type, visibility_type, estimated_row_count, view_count, owner_email, owner_user_id to tables- changes:- - sqlFile:- dbms: postgresql- path: instance_analytics_views/tables/v3/postgres-tables.sql- relativeToChangelogFile: true- - sqlFile:- dbms: mysql,mariadb- path: instance_analytics_views/tables/v3/mysql-tables.sql- relativeToChangelogFile: true- - sqlFile:- dbms: h2- path: instance_analytics_views/tables/v3/h2-tables.sql- relativeToChangelogFile: true- rollback:- - sqlFile:- dbms: postgresql- path: instance_analytics_views/tables/v1/postgres-tables.sql- relativeToChangelogFile: true- - sqlFile:- dbms: mysql,mariadb- path: instance_analytics_views/tables/v2/mysql-tables.sql- relativeToChangelogFile: true- - sqlFile:- dbms: h2- path: instance_analytics_views/tables/v1/h2-tables.sql- relativeToChangelogFile: true--# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<########################################################################################################################diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.cljindex c74ba4ddf85..dfaf055f869 100644--- a/src/metabase/analytics/stats.clj+++ b/src/metabase/analytics/stats.clj@@ -881,6 +881,9 @@{:name :sdk-embedding:available true:enabled (setting/get :enable-embedding-sdk)}+ {:name :tenants+ :enabled (setting/get :use-tenants)+ :available (premium-features/enable-tenants?)}{:name :starburst-legacy-impersonation:available true:enabled (->> (t2/select-fn-set (comp :impersonation :details) :model/Database :engine "starburst")diff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.cljindex 2d1572f7e3a..bdaf6cd2944 100644--- a/src/metabase/app_db/custom_migrations.clj+++ b/src/metabase/app_db/custom_migrations.clj@@ -26,6 +26,7 @@[metabase.app-db.connection :as mdb.connection][metabase.app-db.custom-migrations.metrics-v2 :as metrics-v2][metabase.app-db.custom-migrations.pulse-to-notification :as pulse-to-notification]+ [metabase.app-db.custom-migrations.reserve-at-symbol-user-attributes :as reserve-at-symbol-user-attributes][metabase.app-db.custom-migrations.util :as custom-migrations.util][metabase.config.core :as config][metabase.task.bootstrap]@@ -1819,3 +1820,6 @@(throw (ex-info (str "Unable to categorize transform with unknown source type: " source-type){:transform-id id :source-type source-type})))](t2/update! :transform id {:source_type transform-type})))))++(define-migration MoveExistingAtSymbolUserAttributes+ (reserve-at-symbol-user-attributes/migrate!))diff --git a/src/metabase/app_db/custom_migrations/reserve_at_symbol_user_attributes.clj b/src/metabase/app_db/custom_migrations/reserve_at_symbol_user_attributes.cljnew file mode 100644index 00000000000..3e7e2018b20--- /dev/null+++ b/src/metabase/app_db/custom_migrations/reserve_at_symbol_user_attributes.clj@@ -0,0 +1,100 @@+(ns metabase.app-db.custom-migrations.reserve-at-symbol-user-attributes+ "Going forward, we want to reserve user attributes startings with `@` for our own use.++ To support this, we will automatically migrate existing user attributes beginning with `@` to instead begin with+ `_@`.++ This is not the most efficient operation, because user attributes are arbitrary maps of JSON, making it difficult to+ do this in the database (especially given the number of databases we support). So instead, we can:++ - calculate the map of `user-attribute->new-name-for-existing-user-attribute` (generally, this will be something+ like `@foo => _@foo`, but in some cases an existing user attribute may block this rename, forcing us to use, e.g.,+ `__@foo`)+ - find all usages of each user attribute that will be renamed in:+ - users,+ - sandboxes,+ - impersonations, or+ - DB routing configurations+ - rename each of the above.+++ NOTE: Some of these operations are quite inefficient! For example, to migrate a user attribute, we will, for each+ renamed user attribute, go through each user whose attributes contain that attribute, rename it, and then move on to+ the next user.++ If we had thousands of attributes starting with `@` and thousands of users with those attributes this behavior could+ be *quite* horrible.++ However, I think it's quite probable that we have somewhere on the order of ~1 user attribute anywhere that this+ code will actually run on, plus this will only run one time per Metabase install, so I'd rather not spend a ton of+ time optimizing for an incredibly unlikely case."+ (:require+ #_{:clj-kondo/ignore [:discouraged-namespace]}+ [cheshire.core :as cheshire]+ [clojure.set :as set]+ [toucan2.core :as t2]))++(defn- parse-json [s] (cheshire/parse-string s false))+(defn- to-json [o] (cheshire/generate-string o))++(defn- migrate-sandboxes!+ [old-attr new-attr]+ (let [sandboxes (t2/select :sandboxes {:where [:like :attribute_remappings (str "%" old-attr "%")]})]+ (doseq [{:keys [id attribute_remappings]} sandboxes]+ (let [attribute-remappings (parse-json attribute_remappings)+ new-attribute-remappings (set/rename-keys attribute-remappings {old-attr new-attr})]+ ;; yes this is n+1 but we're not expecting big numbers here.+ (when (not= new-attribute-remappings attribute-remappings)+ (t2/update! :sandboxes :id id {:attribute_remappings (to-json new-attribute-remappings)}))))))++(defn- migrate-db-routing! [old-attr new-attr]+ (t2/update! :db_router :user_attribute old-attr {:user_attribute new-attr}))++(defn- migrate-impersonations! [old-attr new-attr]+ (t2/update! :connection_impersonations :attribute old-attr {:attribute new-attr}))++(defn- migrate-users! [old-attr new-attr]+ (let [users (t2/select :core_user :login_attributes [:like (str "%" old-attr "%")])]+ (doseq [{:keys [id login_attributes]} users]+ (let [login-attributes (parse-json login_attributes)+ new-login-attributes (set/rename-keys login-attributes {old-attr new-attr})]+ (when (not= login-attributes new-login-attributes)+ (t2/update! :core_user :id id {:login_attributes (to-json new-login-attributes)}))))))++(defn- find-rename-option+ "We want to rename `@foo` to `_@foo`, but maybe there's already an `_@foo`, so just keep adding `_` until it's available."+ [attrs k]+ (->> k+ (iterate #(str "_" %))+ (remove #(contains? attrs %))+ first))++(defn- all-possibly-relevant-user-attributes+ []+ (into #{}+ (comp+ (map parse-json)+ (mapcat keys)+ ;; we can't just check for *begins* with here, because we need to include cases that *might* be clobbered by renames.+ (filter #(re-matches #"^(_+)?@.+" %)))+ (t2/select-fn-reducible :login_attributes [:core_user :login_attributes]+ {:where [:and+ [:not= :login_attributes nil]+ [:not= :login_attributes "{}"]+ ;; contains a `"@`, a string starting with a `@` (it could be in a value+ ;; though, so we need to check later.)+ [:or+ [:like :login_attributes "%\"_"]+ [:like :login_attributes "%\"@%"]]]})))++(defn migrate!+ "We want to reserve any user attributes starting with `@`. To do this safely, we will rename any existing user attributes "+ []+ (let [all-attrs (all-possibly-relevant-user-attributes)]+ (doseq [attr all-attrs+ :when (= (first attr) \@)+ :let [new-attr (find-rename-option all-attrs attr)]]+ (migrate-users! attr new-attr)+ (migrate-sandboxes! attr new-attr)+ (migrate-db-routing! attr new-attr)+ (migrate-impersonations! attr new-attr))))diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.cljindex 3a64b167a4b..5942f5b94c6 100644--- a/src/metabase/audit_app/events/audit_log.clj+++ b/src/metabase/audit_app/events/audit_log.clj@@ -355,3 +355,11 @@(get-in event [:details :scope :table_id]))](audit-log/record-event! :event/table-data-edit (merge event {:model :model/Table :model-id table-id}))(audit-log/record-event! topic event))))++(derive ::tenant-event ::event)+(derive :event/tenant-create ::tenant-event)+(derive :event/tenant-update ::tenant-event)++(methodical/defmethod events/publish-event! ::tenant-event+ [topic event]+ (audit-log/record-event! topic event))diff --git a/src/metabase/audit_app/models/audit_log.clj b/src/metabase/audit_app/models/audit_log.cljindex 074326929c6..003347c4ad9 100644--- a/src/metabase/audit_app/models/audit_log.clj+++ b/src/metabase/audit_app/models/audit_log.clj@@ -82,11 +82,11 @@:user-update (select-keys (t2/hydrate entity :user_group_memberships)[:groups :first_name :last_name :email:invite_method :sso_source- :user_group_memberships])+ :user_group_memberships :tenant_id]):user-invited (select-keys (t2/hydrate entity :user_group_memberships)[:groups :first_name :last_name :email:invite_method :sso_source- :user_group_memberships])+ :user_group_memberships :tenant_id]):password-reset-initiated (select-keys entity [:token]):password-reset-successful (select-keys entity [:token]){}))diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.cljindex c7fa17e5097..24b72c8b77b 100644--- a/src/metabase/auth_identity/provider.clj+++ b/src/metabase/auth_identity/provider.clj@@ -289,9 +289,9 @@(as-> (merge request (authenticate provider request)) $(assoc $ :user(or (when-let [user-id (:user-id $)]- (t2/select-one [:model/User :id :is_active :last_login] :id user-id))+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id))(when-let [email (get-in $ [:user-data :email])]- (t2/select-one [:model/User :id :is_active :last_login] :%lower.email (u/lower-case-en email)))))+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email)))))(cond-> $(and (:provider-id $) (:user-data $))(assoc-in [:user-data :provider-id] (:provider-id $)))@@ -316,8 +316,8 @@[:last_name {:optional true} [:maybe :string]][:sso_source {:optional true} :keyword][:is_active {:optional true} :boolean]- [:jwt_attributes {:optional true} [:maybe :map]]- [:login_attributes {:optional true} [:maybe :map]]+ [:jwt_attributes {:optional true} [:maybe [:map-of :string [:maybe :string]]]]+ [:login_attributes {:optional true} [:maybe [:map-of :string [:maybe :string]]]][:provider-id {:optional true} [:maybe :string]]]provider :- :keyword](t2/with-transaction [_]@@ -334,13 +334,14 @@[:first_name {:optional true} [:maybe :string]][:last_name {:optional true} [:maybe :string]][:sso_source {:optional true} :keyword]- [:jwt_attributes {:optional true} [:maybe :map]]- [:login_attributes {:optional true} [:maybe :map]]- [:provider-id {:optional true} [:maybe :string]]]+ [:jwt_attributes {:optional true} [:maybe [:map-of :string [:maybe :string]]]]+ [:login_attributes {:optional true} [:maybe [:map-of :string [:maybe :string]]]]+ [:provider-id {:optional true} [:maybe :string]]+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]]provider :- :keyword](t2/with-transaction [_](u/prog1- (t2/insert-returning-instance! [:model/User :id :last_login :is_active]+ (t2/insert-returning-instance! [:model/User :id :last_login :is_active :tenant_id](select-keys user-data (sso-user-fields)))(t2/insert! :model/AuthIdentity (cond-> {:user_id (:id <>) :provider (name provider)}(:provider-id user-data) (assoc :provider_id (:provider-id user-data))))diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex 9ddc86b2542..fe6f14ebad6 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -123,6 +123,7 @@:model/CommentReaction](when config/ee-available?[:model/Sandbox+ :model/Tenant:model/ConnectionImpersonation:model/Metabot:model/MetabotConversationdiff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.cljindex ff06f3e72f5..ddd32c70e53 100644--- a/src/metabase/collections/core.clj+++ b/src/metabase/collections/core.clj@@ -16,7 +16,9 @@check-remote-synced-dependentslibrary-collectionlibrary-data-collection-type+ location-pathcreate-library-collection!moving-into-remote-synced?moving-from-remote-synced?- non-remote-synced-dependencies])+ non-remote-synced-dependencies+ shared-tenant-collection?])diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 00e399057c5..59009c1da65 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -63,10 +63,6 @@"The value of the `:type` field for the Trash collection that holds archived items.""trash")-(def ^:constant remote-synced-collection-type- "The value of the `:type` field for remote-synced collections."- "remote-synced")-(def ^:constant library-collection-type"The value of the `:type` field for library collections.""library")@@ -92,6 +88,16 @@[](assoc (get-trash) :name (deferred-tru "Trash"))))+(def shared-tenant-ns+ "Namespace for shared tenant collections"+ :shared-tenant-collection)++(mu/defn shared-tenant-collection?+ "Whether or not a collection is a tenant collection."+ [{:keys [namespace]} :- [:or RootCollection [:map [:namespace {:optional true} [:maybe [:or :keyword :string]]]]]]+ (= (some-> namespace name)+ (name shared-tenant-ns)))+(defn trash-collection-id"The ID representing the Trash collection."[] (u/the-id (trash-collection)))@@ -120,11 +126,12 @@(str/starts-with? (:location collection) (trash-path)))))(defn remote-synced-collection?- "Is this a remote-synced collection?"+ "Is this a remote-synced collection?+ Returns true if the collection has is_remote_synced=true in the database."[collection-or-id](cond(nil? collection-or-id) false ;; the root collection is never remote-synced- (map? collection-or-id) (:is_remote_synced collection-or-id)+ (map? collection-or-id) (boolean (get collection-or-id :is_remote_synced)):else (t2/select-one-fn :is_remote_synced :model/Collection :id (u/the-id collection-or-id))))(defn- is-library?@@ -228,16 +235,18 @@([instance](and (not (default-audit-collection? instance))(not (is-trash-or-descendant? instance))- (remote-sync/collection-editable? instance)- (mi/current-user-has-full-permissions? :write instance)))+ (mi/current-user-has-full-permissions? :write instance)+ (remote-sync/collection-editable? instance)))([_model pk](mi/can-write? (t2/select-one :model/Collection pk))))(mu/defmethod mi/can-read? :model/Collection([instance]- (perms/can-read-audit-helper :model/Collection instance))+ (or (is-trash? instance)+ (perms/can-read-audit-helper :model/Collection instance)))([_model pk :- pos-int?]- (mi/can-read? (t2/select-one :model/Collection :id pk))))+ (or (is-trash? pk)+ (mi/can-read? (t2/select-one :model/Collection :id pk)))))(def AuthorityLevel"Malli Schema for valid collection authority levels."@@ -360,6 +369,8 @@Collection."[{:keys [location], owner-id :personal_owner_id, collection-namespace :namespace, :as collection}]{:pre [(contains? collection :namespace)]}+ (when (and namespace (shared-tenant-collection? collection) (not (perms/use-tenants)))+ (throw (ex-info "Can't create a tenant collection without tenants enabled." {:type (:type collection)})))(when location(when-let [parent-id (location-path->parent-id location)](let [parent-namespace (t2/select-one-fn :namespace :model/Collection :id parent-id)]@@ -516,6 +527,19 @@:id id:personal_owner_id [:not= nil])))))+(def ^:private CollectionWithNamespace+ "Schema for a Collection instance that has a valid `:location`, and a `:namespace` key *present* (but not+ necessarily non-nil)."+ [:map+ [:namespace [:maybe [:or :keyword :string]]]])++(mu/defn is-dedicated-tenant-collection-or-descendant? :- :boolean+ "Is `collection` a Tenant Collection, or a descendant of one?"+ [collection :- CollectionWithNamespace]+ (boolean+ ;; If collection has namespace = "tenant-specific" we know it's in the dedicated tenant namespace+ (= (some-> (:namespace collection) name) "tenant-specific")))+(mu/defn user->existing-personal-collection :- [:maybe (ms/InstanceOf :model/Collection)]"For a `user-or-id`, return their personal Collection, if it already exists.Use [[metabase.collections.models.collection/user->personal-collection]] to fetch their personal Collection *and*@@ -526,6 +550,7 @@(mu/defn user->personal-collection :- [:maybe (ms/InstanceOf :model/Collection)]"Return the Personal Collection for `user-or-id`, if it already exists; if not, create it and return it."[user-or-id]+ ;; API key users do not get personal collections(when-not (api-key/is-api-key-user? (u/the-id user-or-id))(or (user->existing-personal-collection user-or-id)(try@@ -588,6 +613,12 @@(or (get user-id->collection-id (u/the-id user))(user->personal-collection-id (u/the-id user)))))))))+(mi/define-simple-hydration-method is-shared-tenant-collection+ :is_shared_tenant_collection+ "Hydrate the `is_shared_tenant_collection` property of collections - whether or not they're a tenant coll."+ [collection]+ (shared-tenant-collection? collection))+(mi/define-batched-hydration-method collection-is-personal:is_personal"Efficiently hydrate the `:is_personal` property of a sequence of Collections.@@ -693,6 +724,15 @@;; we're not looking for a particular `archive_operation_id`(not (:archive-operation-id visibility-config)))))+(def ^:private visible-union-columns+ [:c.id+ :c.location+ :c.archived+ :c.archive_operation_id+ :c.archived_directly+ :c.type+ :c.namespace])+(mu/defn visible-collection-query"Given a `CollectionVisibilityConfig`, return a HoneySQL query that selects all visible Collection IDs."([visibility-config :- CollectionVisibilityConfig]@@ -721,27 +761,31 @@;; c) their personal collection and its descendants:from [(if is-superuser?[:collection :c]- [{:union-all (keep identity [{:select [:c.id :c.location :c.archived :c.archive_operation_id :c.archived_directly]+ [{:union-all (keep identity [{:select visible-union-columns:from [[:collection :c]]- :where [:exists {:select [1]- :from [[:permissions :p]]- :inner-join [[:permissions_group_membership :pgm] [:= :p.group_id :pgm.group_id]]- :where [:and- [:= :pgm.user_id [:inline current-user-id]]- [:= :c.id :p.collection_id]- [:= :p.perm_type (h2x/literal "perms/collection-access")]- [:or- [:= :p.perm_value (h2x/literal "read-and-write")]- (when (= :read (:permission-level visibility-config))- [:= :p.perm_value (h2x/literal "read")])]]}]}- {:select [:c.id :c.location :c.archived :c.archive_operation_id :c.archived_directly]+ :where [:and [:exists {:select [1]+ :from [[:permissions :p]]+ :inner-join [[:permissions_group_membership :pgm] [:= :p.group_id :pgm.group_id]]+ :where [:and+ [:= :pgm.user_id [:inline current-user-id]]+ [:= :c.id :p.collection_id]+ [:= :p.perm_type (h2x/literal "perms/collection-access")]+ [:or+ [:= :p.perm_value (h2x/literal "read-and-write")]+ (when (= :read (:permission-level visibility-config))+ [:= :p.perm_value (h2x/literal "read")])]]}]]}+ {:select visible-union-columns:from [[:collection :c]]:where [:= :type (h2x/literal trash-collection-type)]}(when-let [personal-collection-and-descendant-ids(seq (user->personal-collection-and-descendant-ids current-user-id))]- {:select [:c.id :c.location :c.archived :c.archive_operation_id :c.archived_directly]+ {:select visible-union-columns:from [[:collection :c]]- :where [:in :id [:inline personal-collection-and-descendant-ids]]})])}+ :where [:in :id [:inline personal-collection-and-descendant-ids]]})+ (when-let [tenant-collection-and-descendant-ids (seq (perms/user->tenant-collection-and-descendant-ids current-user-id))]+ {:select visible-union-columns+ :from [[:collection :c]]+ :where [:in :id [:inline tenant-collection-and-descendant-ids]]})])}:c])];; The `WHERE` clause is where we apply the other criteria we were given::where [:and@@ -760,6 +804,12 @@;; the trash collection is included when viewing archived-only[:= :id [:inline (trash-collection-id)]]])+ (when-not (perms/use-tenants)+ [:not [:exists {:select [1]+ :from [[:collection :sub_c]]+ :where [:and [:= :c.id :sub_c.id]+ [:= :sub_c.namespace [:inline "shared-tenant-collection"]]]}]])+;; excluding things outside of the `archive_operation_id` you wanted...(when-let [op-id (:archive-operation-id visibility-config)][:or@@ -1106,61 +1156,64 @@(recur to-traverse traversed accum)))))(defn remote-synced-dependents- "Finds dependents of a model that are contained in the remote-synced collection the model is being moved from.+ "Finds dependents of a model that are contained in ANY remote-synced collection.For cards, checks if there are any other queries that reference this card. For collections, checks dependents ofall cards in the collection or subcollections. For all other models it returns an empty seq. Only checks forimmediate dependents.- Takes original-collection-id (the id of the collection the model was originally at) and model (the model to check- dependents for).-- Returns a sequence of models immediately dependent on the provided model."- [original-collection-id {:keys [id archived] :as model}]- (if-not original-collection-id- []- (let [original (t2/select-one :model/Collection original-collection-id)- root-collection-id (or (-> original :location location-path->ids first)- (:id original))- root-descendants (traverse-descendants ["Collection" root-collection-id] true)]- (case (t2/model model)- :model/Collection- ;; Get all descendents of the collection being moved and see if any of them are present in the- ;; set of all descendants of the root collection- (->> (traverse-descendants ["Collection" id] (not archived))- keys- (mapcat #(get root-descendants %)))-- ;; If this is not a colleciton see if the provided model appears anywhere in the descendants of- ;; the root collection- (get root-descendants [(name (t2/model model)) id] [])))))+ All remote-synced collections are treated as a unified pool - dependents in any remote-synced collection+ (regardless of root) are returned.++ Takes model (the model to check dependents for).++ Returns a sequence of models immediately dependent on the provided model that are in any remote-synced collection."+ [{:keys [id archived] :as model}]+ (let [;; Get ALL top-level remote-synced collections+ all-remote-synced-roots (t2/select-pks-set :model/Collection+ {:where [:and+ [:= :is_remote_synced true]+ [:= :location "/"]]})+ ;; Traverse descendants of all remote-synced roots combined+ all-remote-synced-descendants (reduce (fn [accum root-id]+ (merge-with concat accum+ (traverse-descendants ["Collection" root-id] true)))+ {}+ all-remote-synced-roots)]+ (case (t2/model model)+ :model/Collection+ ;; Get all descendants of the collection being moved and see if any of them are present in the+ ;; set of all descendants across all remote-synced roots+ (->> (traverse-descendants ["Collection" id] (not archived))+ keys+ (mapcat #(get all-remote-synced-descendants %)))++ ;; If this is not a collection see if the provided model appears anywhere in the descendants of+ ;; any remote-synced collection+ (get all-remote-synced-descendants [(name (t2/model model)) id] []))))(defn non-remote-synced-dependencies- "Finds dependencies of a model that are not contained in the Remote-synced collection.+ "Finds dependencies of a model that are not contained in ANY remote-synced collection.- Checks for dependencies that are possible to contain in the remote-synced collection but are not contained in the- Remote-synced collection or in subcollections of the Remote-synced collection the model is being moved to.+ Checks for dependencies that could be contained in a remote-synced collection but are not.+ All remote-synced collections are treated as a unified pool - a dependency in any remote-synced+ collection (regardless of root) is considered valid.Uses serdes/descendants to list dependencies of a model.Takes model (the model to check dependencies for).- Returns a sequence of model pairs for dependencies of the given model that are not in the Remote-synced- collection."+ Returns a set of model IDs for dependencies of the given model that are not in any remote-synced collection."[{:keys [id] :as model}]- (if-let [collection (t2/select-one :model/Collection :id (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))]- (let [root-collection-id (or (-> collection :location location-path->ids first)- (:id collection))- descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))]- (apply set/union (for [model (collectable-models)- :let [key (name model)]]+ (if (t2/select-one :model/Collection :id (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))+ (let [descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))]+ (apply set/union (for [m (collectable-models)+ :let [key (name m)]](set/difference (set (get descendants key))- (t2/select-pks-set model {:inner-join [[:collection :c]- [:and- [:= :c.id :collection_id]- [:or [:= :c.id root-collection-id]- [:like :c.location (str "/" root-collection-id "/%")]]- [:= :c.is_remote_synced true]]]})))))+ (t2/select-pks-set m {:inner-join [[:collection :c]+ [:and+ [:= :c.id :collection_id]+ [:= :c.is_remote_synced true]]]})))))#{}))(defn check-non-remote-synced-dependencies@@ -1181,76 +1234,47 @@(defn check-remote-synced-dependents"Checks if a model has remote-synced-dependents and throws if it does.- Takes original-collection-id (where the model is being moved from) and model (the model to check dependencies for).+ Takes model (the model to check dependencies for).Returns the model if no remote-synced dependents are found.Throws an ex-info object with remote-synced-dependencies and a 400 status code if dependents are found."- [original-collection-id model]- (when-let [remote-synced-deps (not-empty (remote-synced-dependents original-collection-id model))]+ [model]+ (when-let [remote-synced-deps (not-empty (remote-synced-dependents model))](throw (ex-info (str (deferred-tru "Used by remote synced content.")){:remote-synced-models remote-synced-deps:status-code 400})))model)-(defn- locations-do-not-share-top-level-parent- [location-a id-a location-b id-b]- (not= (or (first (location-path->ids location-a)) id-a)- (or (first (location-path->ids location-b)) id-b)))-(defn moving-into-remote-synced?- "Tests if a move means the object is moving into a remote-synced collection.+ "Tests if a move means the object is moving into a remote-synced collection from outside.- Checks if a move from old-collection-id to new-collection-id means the object is moving from a non-remote-synced- collection or a remote-synced collection with a different root into a remote-synced collection.+ Returns true only when moving from a non-remote-synced collection into a remote-synced collection.+ Moving between remote-synced collections (even with different roots) returns false.Takes old-collection-id (id of the collection the object is being moved from) and new-collection-id (id of the- collection the object is being moved to).-- Returns true if the old collection is not part of a remote-synced collection or shares a different root-parent and- the new collection is."+ collection the object is being moved to)."[old-collection-id new-collection-id](boolean- (and (not (nil? new-collection-id))- (when-let [new-parent-location (t2/select-one-fn :location :model/Collection- {:where [:and [:= :id new-collection-id]- [:= :is_remote_synced true]]})]- (or (nil? old-collection-id)- (if-let [old-parent-location (t2/select-one-fn :location :model/Collection- {:where [:and [:= :id old-collection-id]- [:= :is_remote_synced true]]})]- (locations-do-not-share-top-level-parent old-parent-location- old-collection-id- new-parent-location- new-collection-id)- true))))))+ (and (some? new-collection-id)+ (t2/exists? :model/Collection :id new-collection-id :is_remote_synced true)+ (or (nil? old-collection-id)+ (not (t2/exists? :model/Collection :id old-collection-id :is_remote_synced true))))))(defn moving-from-remote-synced?- "Tests if a move means the object is moving from a remote-synced collection.+ "Tests if a move means the object is leaving remote-synced collections entirely.- Checks if a move from old-collection-id to new-collection-id means the object is moving from a remote-synced- collection into a non-remote-synced collection or a remote-synced collection with a different root.+ Returns true only when moving from a remote-synced collection to a non-remote-synced collection.+ Moving between remote-synced collections (even with different roots) returns false.Takes old-collection-id (id of the collection the object is being moved from) and new-collection-id (id of the- collection the object is being moved to).-- Returns true if the old collection is part of the remote-synced collection and the new collection is not or has a- different remote-synced root."+ collection the object is being moved to)."[old-collection-id new-collection-id](boolean- (and (not (nil? old-collection-id))- (when-let [old-parent-location (t2/select-one-fn :location [:model/Collection :location]- {:where [:and [:= :id old-collection-id]- [:= :is_remote_synced true]]})]- (or (nil? new-collection-id)- (if-let [new-parent-location (t2/select-one-fn :location [:model/Collection :location]- {:where [:and [:= :id new-collection-id]- [:= :is_remote_synced true]]})]- (locations-do-not-share-top-level-parent old-parent-location- old-collection-id- new-parent-location- new-collection-id)- true))))))+ (and (some? old-collection-id)+ (t2/exists? :model/Collection :id old-collection-id :is_remote_synced true)+ (or (nil? new-collection-id)+ (not (t2/exists? :model/Collection :id new-collection-id :is_remote_synced true))))))(defn check-for-remote-sync-update"Checks collection items for remote-sync integrity during an update transaction.@@ -1269,10 +1293,10 @@(when (remote-synced-collection? collection-after-update)(check-non-remote-synced-dependencies model-after-update)(when (api/column-will-change? :archived model-before-update model-after-update)- (check-remote-synced-dependents collection-after-update model-after-update)))+ (check-remote-synced-dependents model-after-update)))(when (and (api/column-will-change? :collection_id model-before-update model-after-update)(moving-from-remote-synced? collection-before-update collection-after-update))- (check-remote-synced-dependents collection-before-update model-after-update)))))+ (check-remote-synced-dependents model-after-update)))))(methodical/defmethod t2/batched-hydrate [:default :is_remote_synced]"Batch hydration for whether an item is remote synced"@@ -1284,6 +1308,19 @@:id{:default false}))+(methodical/defmethod t2/batched-hydrate [:perms/use-parent-collection-perms :collection_namespace]+ "Batch hydration for whether an item is remote synced"+ [model k items]+ (mi/instances-with-hydrated-data items k+ #(into {}+ (t2/select-pk->fn :namespace [model :id [:c.namespace :namespace]]+ {:where [:in (keyword (str (name (t2/table-name model)) ".id"))+ (map :id items)]+ :join [[:collection :c]+ [:= :collection_id :c.id]]}))+ :id+ {:default nil}))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | Recursive Operations: Moving & Archiving |;;; +----------------------------------------------------------------------------------------------------------------+@@ -1383,6 +1420,8 @@(perms/set-has-full-permissions-for-set?@api/*current-user-permissions-set*(perms-for-archiving collection)))+ (api/check-400+ (not= (:type collection) "tenant-specific-root-collection"))(t2/with-transaction [_conn](let [archive-operation-id (str (random-uuid))affected-collection-ids (cons (u/the-id collection)@@ -1409,7 +1448,7 @@{:archived true})))(let [updated-collection (t2/select-one :model/Collection :id (:id collection))](when (:is_remote_synced updated-collection)- (check-remote-synced-dependents (parent-id* updated-collection) updated-collection)))))+ (check-remote-synced-dependents updated-collection)))))(mu/defn unarchive-collection!"Mark a collection as unarchived, along with any children that were archived along with the collection."@@ -1492,6 +1531,8 @@(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")+ (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"(u/the-id collection) (:location collection) new-location)@@ -1509,7 +1550,7 @@(when into-remote-synced?(check-non-remote-synced-dependencies collection))(when (moving-from-remote-synced? (parent-id* collection) (parent-id* {:location new-location}))- (check-remote-synced-dependents (parent-id* collection) collection))))))+ (check-remote-synced-dependents collection))))));;; +----------------------------------------------------------------------------------------------------------------+;;; | Toucan IModel & Perms Method Impls |@@ -1524,7 +1565,7 @@(throw (ex-info "Can't create a personal collection for an API key" {:user user-id}))))))(t2/define-before-insert :model/Collection- [{collection-name :name, :keys [location type] :as collection}]+ [{collection-name :name :keys [location type] :as collection}](assert-valid-location collection)(assert-not-personal-collection-for-api-key collection)(assert-valid-namespace (merge {:namespace nil} collection))@@ -1577,9 +1618,13 @@Descendants of Personal Collections, like Personal Collections themselves, cannot have permissions entries in theapplication database.+ This also does *not* apply to Tenant Collections or their descendants. Like Personal Collections, they+ cannot have permissions entries in the application database.+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))@@ -1587,25 +1632,29 @@(t2/define-after-insert :model/Collection[collection]- (u/prog1 collection- (copy-parent-permissions! (t2.realize/realize collection))))+ (u/prog1 (t2.realize/realize collection)+ (copy-parent-permissions! <>)));;; ----------------------------------------------------- UPDATE ------------------------------------------------------(mu/defn- check-changes-allowed-for-personal-collection- "If we're trying to UPDATE a Personal Collection, make sure the proposed changes are allowed. Personal Collections- have lots of restrictions -- you can't archive them, for example, nor can you transfer them to other Users."+(mu/defn- check-changes-allowed-for-protected-collection+ "If we're trying to UPDATE a Personal Collection or Tenant Collection, make sure the proposed changes are+ allowed. Personal Collections and TCs have lots of restrictions -- you can't archive them, for example, nor can you+ transfer them to other Users."[collection-before-updates :- CollectionWithLocationAndIDOrRootcollection-updates :- :map];; you're not allowed to change the `:personal_owner_id` of a Collection!;; double-check and make sure it's not just the existing value getting passed back in for whatever reason- (let [unchangeable {:personal_owner_id (tru "You are not allowed to change the owner of a Personal Collection.")- :authority_level (tru "You are not allowed to change the authority level of a Personal Collection.")+ (let [ctype (if (:personal_owner_id collection-before-updates)+ "Personal Collection"+ "Tenant Collection")+ unchangeable {:personal_owner_id (tru "You are not allowed to change the owner of a {0}." ctype)+ :authority_level (tru "You are not allowed to change the authority level of a {0}." ctype);; The checks below should be redundant because the `perms-for-moving` and `perms-for-archiving`;; functions also check to make sure you're not operating on Personal Collections. But as an extra safety net it;; doesn't hurt to check here too.- :location (tru "You are not allowed to move a Personal Collection.")- :archived (tru "You cannot archive a Personal Collection.")}]+ :location (tru "You are not allowed to move a {0}." ctype)+ :archived (tru "You cannot archive a {0}." ctype)}](when-let [[k msg] (->> unchangeable(filter (fn [[k _msg]](api/column-will-change? k collection-before-updates collection-updates)))@@ -1674,6 +1723,25 @@;; this newly privatized Collection(revoke-perms-when-moving-into-personal-collection! collection-before-updates)))))+(defenterprise update-perms-for-tenant-specific-namespace-change!+ "If a Collection is moving into or out of the tenant-specific namespace, adjust the Permissions for it accordingly.++ OSS version: Throws an exception if a collection attempts to cross the tenant-specific namespace boundary, as this+ should never happen in OSS and we want to maintain the invariant that tenant-specific collections have no+ permissions entries."+ metabase-enterprise.tenants.permissions+ [collection-before-updates collection-updates]+ ;; Check if the collection is moving across the tenant-specific namespace boundary+ (let [is-tenant-specific? (is-dedicated-tenant-collection-or-descendant? collection-before-updates)+ will-be-tenant-specific? (is-dedicated-tenant-collection-or-descendant? (merge collection-before-updates+ collection-updates))]+ (when (not= is-tenant-specific? will-be-tenant-specific?)+ (throw (ex-info (tru "Cannot move collections across tenant-specific namespace boundary in OSS.")+ {:status-code 400+ :collection collection-before-updates+ :is-tenant-specific is-tenant-specific?+ :will-be-tenant-specific will-be-tenant-specific?})))))+;; PUTTING IT ALL TOGETHER <3(defn- namespace-equals?@@ -1698,8 +1766,9 @@[400 "You cannot modify the Trash Collection."]);; VARIOUS CHECKS BEFORE DOING ANYTHING:;; (1) if this is a personal Collection, check that the 'propsed' changes are allowed- (when (:personal_owner_id collection-before-updates)- (check-changes-allowed-for-personal-collection collection-before-updates collection-updates))+ (when (or (:personal_owner_id collection-before-updates)+ (= (:type collection-before-updates) "tenant-specific-collection"))+ (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);; (3) make sure Collection namespace is valid@@ -1719,7 +1788,10 @@;; (4) If we're moving a Collection from a location on a Personal Collection hierarchy to a location not on one,;; or vice versa, we need to grant/revoke permissions as appropriate (see above for more details)(when (api/column-will-change? :location collection-before-updates collection-updates)- (update-perms-when-moving-across-personal-boundry! collection-before-updates collection-updates))+ (update-perms-when-moving-across-personal-boundry! collection-before-updates collection-updates)+ ;; (4.5) If we're moving a Collection across the tenant-specific namespace boundary, we need to adjust+ ;; permissions accordingly (delete when moving in, grant when moving out)+ (update-perms-for-tenant-specific-namespace-change! collection-before-updates collection-updates));; OK, AT THIS POINT THE CHANGES ARE VALIDATED. NOW START ISSUING UPDATES;; slugify the collection name in case it's changed in the output; the results of this will get passed along;; to Toucan's `update!` impl@@ -1867,10 +1939,11 @@[:= :collection_id id](when skip-archived [:not :archived])]})]{["Card" card-id] {"Collection" id}}))- documents (into {} (for [doc-id (t2/select-pks-set :model/Document {:where+ documents (when config/ee-available?+ (into {} (for [doc-id (t2/select-pks-set :model/Document {:where[:and [:= :collection_id id](when skip-archived [:not :archived])]})]- {["Document" doc-id] {"Collection" id}}))+ {["Document" doc-id] {"Collection" id}})))timelines (into {} (for [timeline-id (t2/select-pks-set :model/Timeline {:where [:and[:= :collection_id id](when skip-archived [:not :archived])]})]@@ -1951,7 +2024,7 @@(defmethod allowed-namespaces :default[_]- #{nil :analytics})+ #{nil :analytics :shared-tenant-collection :tenant-specific})(defn check-collection-namespace"Check that object's `:collection_id` refers to a Collection in an allowed namespace (see@@ -2171,7 +2244,10 @@:collection_name :name:collection_type :type:location true}- :where [:or [:= :namespace nil] [:= :namespace "analytics"]]+ :where [:or [:= :namespace nil]+ [:= :namespace "analytics"]+ [:= :namespace "shared-tenant-collection"]+ [:= :namespace "tenant-specific"]];; depends on the current user, used for rendering and ranking;; TODO not sure this is what it'll look like:bookmark [:model/CollectionBookmark [:anddiff --git a/src/metabase/collections/models/collection/root.clj b/src/metabase/collections/models/collection/root.cljindex 90ac9c93c71..8110deb5d39 100644--- a/src/metabase/collections/models/collection/root.clj+++ b/src/metabase/collections/models/collection/root.clj@@ -55,11 +55,15 @@[collection-namespace](m/assoc-some root-collection:name (case (keyword collection-namespace)+ :shared-tenant-collections (tru "Shared collections"):snippets (tru "SQL snippets")(tru "Our analytics")):namespace collection-namespace:is_personal false- :id "root"))+ :id "root"+ ;; Root collection itself is not remote-synced; individual top-level collections+ ;; within the shared-tenant-collection namespace can be toggled individually.+ :is_remote_synced false))(defn hydrated-root-collection"Return the root collection entity."diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex 192689bf383..14406704052 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -8,6 +8,7 @@[honey.sql.helpers :as sql.helpers][malli.core :as mc][malli.transform :as mtx]+ [malli.util][medley.core :as m][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -75,12 +76,11 @@The Trash Collection itself (the container for archived items) is *always* included.- To select only personal collections, pass in `personal-only` as `true`.This will select only collections where `personal_owner_id` is not `nil`.To include library collections and their descendants, pass in `include-library?` as `true`.- By default, library-type collections are excluded."- [{:keys [archived exclude-other-user-collections namespace shallow collection-id personal-only include-library?]}]+ By default, library-type collections are excluded. "+ [{:keys [archived exclude-other-user-collections namespaces shallow collection-id personal-only include-library?]}](cond->>(t2/select :model/Collection{:where [:and@@ -103,7 +103,11 @@[:not-in :type [collection/library-collection-typecollection/library-data-collection-typecollection/library-metrics-collection-type]]])- (perms/audit-namespace-clause :namespace namespace)+ [:or+ (when (contains? namespaces nil)+ [:= :namespace nil])+ (when (seq namespaces)+ [:in :namespace namespaces])](collection/visible-collection-filter-clause:id{:include-archived-items (if archived@@ -146,7 +150,11 @@(as->(select-collections {:archived (boolean archived):exclude-other-user-collections exclude-other-user-collections- :namespace namespace+ :namespaces (cond+ namespace [namespace]+ (premium-features/enable-audit-app?) #{"analytics" nil}+ :else+ #{nil}):shallow false:personal-only personal-only:include-library? true}) collections@@ -210,20 +218,33 @@subtree (below).TODO: for historical reasons this returns Saved Questions AS 'card' AND Models as 'dataset'; we should fix this at- some point in the future."+ some point in the future.++ By default, looks at the `analytics` (if enabled) and regular (`nil`) namespaces. You can optionally pass a+ `namespace` argument, or one or many `namespaces`, to specify the particular collection namespaces you wish to look+ at. For example, `namespaces=analytics&namespaces=` would match the default behavior."[_route-params{:keys [exclude-archived exclude-other-user-collections include-library- namespace shallow collection-id]} :- [:map- [:exclude-archived {:default false} [:maybe :boolean]]- [:exclude-other-user-collections {:default false} [:maybe :boolean]]- [:include-library {:default false} [:maybe :boolean]]- [:namespace {:optional true} [:maybe ms/NonBlankString]]- [:shallow {:default false} [:maybe :boolean]]- [:collection-id {:optional true} [:maybe ms/PositiveInt]]]]+ namespace namespaces shallow collection-id]}+ :- [:map+ [:exclude-archived {:default false} [:maybe :boolean]]+ [:exclude-other-user-collections {:default false} [:maybe :boolean]]+ [:include-library {:default false} [:maybe :boolean]]+ [:namespace {:optional true} [:maybe ms/NonBlankString]]+ [:namespaces {:optional true} [:maybe [:vector {:decode/string (fn [x] (cond (vector? x) x x [x]))} :string]]]+ [:shallow {:default false} [:maybe :boolean]]+ [:collection-id {:optional true} [:maybe ms/PositiveInt]]]]+ (api/check-400+ (not (and namespace (seq namespaces))))(let [archived (if exclude-archived false nil)+ namespaces (cond+ namespace #{namespace}+ (seq namespaces) (into #{} (map not-empty namespaces))+ (premium-features/enable-audit-app?) #{nil "analytics"}+ :else #{nil})collections (-> (select-collections {:archived archived:exclude-other-user-collections exclude-other-user-collections- :namespace namespace+ :namespaces namespaces:shallow shallow:collection-id collection-id:include-library? include-library})@@ -370,9 +391,10 @@(assoc :location (or (when collection(collection/children-location collection))"/"))+ (dissoc :namespace)(update :archived api/bit->boolean)(update :archived_directly api/bit->boolean)))- :can_write :can_restore :can_delete :is_remote_synced))+ :can_write :can_restore :can_delete :is_remote_synced :collection_namespace))(defmethod collection-children-query :document[_ collection {:keys [archived? pinned-state]}]@@ -426,8 +448,8 @@[_ _ _ rows](for [row rows](dissoc row- :description :display :authority_level :moderated_status :icon :personal_owner_id- :collection_preview :dataset_query :table_id :query_type :is_upload)))+ :description :display :authority_level :moderated_status :icon :personal_owner_id :namespace+ :collection_preview :dataset_query :table_id :query_type :is_upload :collection_namespace)))(defenterprise snippets-collection-children-query"Collection children query for snippets on OSS. Returns all snippets regardless of collection, because snippet@@ -456,15 +478,16 @@(for [row rows](dissoc row:description :display :collection_position :authority_level :moderated_status- :collection_preview :dataset_query :table_id :query_type :is_upload)))+ :collection_preview :dataset_query :table_id :query_type :is_upload :namespace)))(defmethod post-process-collection-children :snippet[_ _options _collection rows](for [row rows]- (dissoc row- :description :collection_position :display :authority_level- :moderated_status :icon :personal_owner_id :collection_preview- :dataset_query :table_id :query_type :is_upload)))+ (-> (dissoc row+ :description :collection_position :display :authority_level+ :moderated_status :icon :personal_owner_id :collection_preview+ :dataset_query :table_id :query_type :is_upload :namespace)+ (assoc :collection_namespace "snippets"))))(defn- card-query [card-type collection {:keys [archived? pinned-state show-dashboard-questions?]}](-> {:select (cond->@@ -542,7 +565,7 @@(update :archived_directly api/bit->boolean)))(defn- post-process-card-row-after-hydrate [row]- (-> (dissoc row :authority_level :icon :personal_owner_id :dataset_query :table_id :query_type :is_upload)+ (-> (dissoc row :authority_level :icon :personal_owner_id :dataset_query :table_id :query_type :is_upload :namespace)(update :dashboard #(when % (select-keys % [:id :name :moderation_status])))(assoc :fully_parameterized (queries/fully-parameterized? row))))@@ -553,6 +576,7 @@:can_delete:dashboard_count:is_remote_synced+ :collection_namespace[:dashboard :moderation_status]]include-can-run-adhoc-query (conj :can_run_adhoc_query))](as-> (map post-process-card-row rows) $@@ -615,9 +639,10 @@(assoc :location (or (when parent-collection(collection/children-location parent-collection))"/"))+ (assoc :is_tenant_dashboard (collection/shared-tenant-collection? parent-collection))(update :archived api/bit->boolean)(update :archived_directly api/bit->boolean)- (t2/hydrate :can_write :can_restore :can_delete :is_remote_synced)+ (t2/hydrate :can_write :can_restore :can_delete :is_remote_synced :collection_namespace)(dissoc :display :authority_level :icon :personal_owner_id :collection_preview:dataset_query :table_id :query_type :is_upload)))@@ -664,20 +689,21 @@(collection/effective-children-querycollection{:cte-name :visible_collection_ids}- (if archived?- [:or- [:= :archived true]- [:= :id (collection/trash-collection-id)]]- [:and [:= :archived false] [:not= :id (collection/trash-collection-id)]])- (when collection-type- (if (= collection-type "remote-synced")- [:= :is_remote_synced true]- [:= :type collection-type]))- (when-not include-library?- [:or [:= nil :type]- [:not [:in :type [collection/library-collection-type- collection/library-metrics-collection-type- collection/library-data-collection-type]]]])+ [:and+ (when collection-type+ (if (= collection-type "remote-synced")+ [:= :is_remote_synced true]+ [:= :type collection-type]))+ (when-not include-library?+ [:or [:= nil :type]+ [:not [:in :type [collection/library-collection-type+ collection/library-metrics-collection-type+ collection/library-data-collection-type]]]])+ (if archived?+ [:or+ [:= :archived true]+ [:= :id (collection/trash-collection-id)]]+ [:and [:= :archived false] [:not= :id (collection/trash-collection-id)]])](perms/audit-namespace-clause :namespace (u/qualified-name collection-namespace))(snippets-collection-filter-clause));; We get from the effective-children-query a normal set of columns selected:@@ -691,8 +717,12 @@:personal_owner_id:location:archived_directly+ :namespace+ ;; selected as `type` for compatibility with collection fns that expect it:type[[:case [:= :is_remote_synced nil] [:inline false] :else :is_remote_synced] :is_remote_synced]+ ;; selected as `collection_type` for fast sorting on "when it's a collection, type"+ [:type :collection_type][(h2x/literal "collection") :model]:authority_level]);; the nil indicates that collections are never pinned.@@ -808,7 +838,7 @@collection/maybe-localize-system-collection-name(update :archived api/bit->boolean)(update :is_remote_synced api/bit->boolean)- (t2/hydrate :can_write :effective_location :can_restore :can_delete)+ (t2/hydrate :can_write :effective_location :can_restore :can_delete :is_shared_tenant_collection)(dissoc :collection_position :display :moderated_status :icon:collection_preview :dataset_query :table_id :query_type :is_upload)(assoc :type type-value)@@ -837,7 +867,7 @@(:last_edit_user row) (assoc :last-edit-info (select-as row mapping))))))(defn- remove-unwanted-keys [{:keys [model] :as row}]- (cond-> (dissoc row :model_ranking :archived_directly :total_count)+ (cond-> (dissoc row :model_ranking :archived_directly :total_count :collection_type)(not= model "collection") (dissoc :type)))(defn- model-name->toucan-model [model-name]@@ -892,7 +922,7 @@:model :collection_position :authority_level [:personal_owner_id :integer] :location:last_edit_email :last_edit_first_name :last_edit_last_name :moderated_status :icon[:last_edit_user :integer] [:last_edit_timestamp :timestamp] [:database_id :integer]- :type [:archived :boolean] [:last_used_at :timestamp] [:is_remote_synced :boolean]+ :collection_type :type [:archived :boolean] [:last_used_at :timestamp] [:is_remote_synced :boolean] :namespace;; for determining whether a model is based on a csv-uploaded table[:table_id :integer] [:is_upload :boolean] :query_type])@@ -1035,7 +1065,7 @@reslimit-res)))-(mu/defn- collection-children+(mu/defn collection-children"Fetch a sequence of 'child' objects belonging to a Collection, filtered using `options`."[{collection-namespace :namespace, :as collection} :- collection/CollectionWithLocationAndIDOrRoot{:keys [models], :as options} :- CollectionChildrenOptions]@@ -1269,9 +1299,9 @@{:archived? (boolean archived):include-can-run-adhoc-query include_can_run_adhoc_query:show-dashboard-questions? (boolean show_dashboard_questions)- :collection-type collection_type- :include-library? include_library- :models model-kwds+ :collection-type collection_type+ :include-library? include_library+ :models (if-not (or (nil? namespace) (= namespace "snippets")) #{:collection} model-kwds):pinned-state (keyword pinned_state):sort-info {:sort-column (or (some-> sort_column normalize-sort-choice) :name):sort-direction (or (some-> sort_direction normalize-sort-choice) :asc)@@ -1281,46 +1311,80 @@;;; ----------------------------------------- Creating/Editing a Collection ------------------------------------------+(defn- parent-or-root+ "From a create request return either the parent collection or the root collection"+ [{collection-id :parent_id collection-namespace :namespace}]+ (if collection-id+ (t2/select-one :model/Collection :id collection-id)+ (collection/root-collection-with-ui-details collection-namespace)))+(defn- write-check-collection-or-root-collection"Check that you're allowed to write Collection with `collection-id`; if `collection-id` is `nil`, check that you haveRoot Collection perms."- [collection-id collection-namespace]- (api/write-check (if collection-id- (t2/select-one :model/Collection :id collection-id)- (cond-> collection/root-collection- collection-namespace (assoc :namespace collection-namespace)))))+ [parent-coll]+ (api/write-check parent-coll))-(defn create-collection!- "Create a new collection."- [{:keys [name description parent_id namespace authority_level] :as params}]- ;; To create a new collection, you need write perms for the location you are going to be putting it in...- (write-check-collection-or-root-collection parent_id namespace)- (when (some? authority_level)+(defn- write-check-authority-level+ "Check that a superuser is creating this collection if they are setting the authority level."+ [{authority-level :authority_level :as coll}]+ (when (some? authority-level);; make sure only admin and an EE token is present to be able to create an Official token(premium-features/assert-has-feature :official-collections (tru "Official Collections"))(api/check-superuser))- ;; Get namespace from parent collection if not provided- (let [{remote-synced? :is_remote_synced- :as parent-collection} (when parent_id- (t2/select-one [:model/Collection :location :id :namespace :is_remote_synced] :id parent_id))- effective-namespace (cond- (contains? params :namespace) namespace- parent-collection (:namespace parent-collection)- :else nil)]- ;; Now create the new Collection :)- (u/prog1 (t2/insert-returning-instance!- :model/Collection- (merge- {:name name- :description description- :is_remote_synced (boolean remote-synced?)- :authority_level authority_level- :namespace effective-namespace}- (when parent-collection- {:location (collection/children-location parent-collection)})))- (when config/ee-available?- (events/publish-event! :event/collection-create {:object <> :user-id api/*current-user-id*}))- (events/publish-event! :event/collection-touch {:collection-id (:id <>) :user-id api/*current-user-id*}))))+ coll)++(defenterprise validate-new-tenant-collection!+ "OSS version. Throws API exceptions if the passed collection is an invalid tenant collection, which in OSS+ means 'any tenant collection.'"+ metabase-enterprise.tenants.core+ [collection]+ (when (collection/shared-tenant-collection? collection)+ (throw (ex-info "Cannot create tenant collection on OSS." {:status-code 400})))+ collection)++(def ^:private CreateCollectionArguments+ "The arguments to the `POST /api/collection` endpoint, i.e. what the API needs to create a collection."+ [:map+ [:name ms/NonBlankString]+ [:description {:optional true} [:maybe ms/NonBlankString]]+ [:parent_id {:optional true} [:maybe ms/PositiveInt]]+ [:namespace {:optional true} [:maybe ms/NonBlankString]]+ [:authority_level {:optional true} [:maybe collection/AuthorityLevel]]])++(def ^:private NewCollectionArguments+ "What we use internally to actually create a collection, i.e. what `t2/insert!` needs to create a collection."+ (-> CreateCollectionArguments+ (malli.util/dissoc :parent_id)+ (malli.util/assoc :location [:maybe ms/NonBlankString])+ (malli.util/assoc :namespace [:maybe [:or :keyword ms/NonBlankString]])+ (malli.util/assoc :is_remote_synced [:maybe :boolean])+ (malli.util/optional-keys [:location])+ (malli.util/closed-schema)))++(mu/defn- apply-defaults-to-collection :- NewCollectionArguments+ "Converts `CreateCollectionArguments` into `NewCollectionArguments` - i.e. translates what the API gets into what+ toucan needs to create a collection."+ [coll-data :- CreateCollectionArguments]+ (let [parent-coll (parent-or-root coll-data)]+ (write-check-collection-or-root-collection parent-coll)+ (-> (cond-> coll-data+ (and (:namespace parent-coll)+ (nil? (:namespace coll-data))) (assoc :namespace (:namespace parent-coll))+ parent-coll (assoc :location (collection/children-location parent-coll)))+ (assoc :is_remote_synced (boolean (:is_remote_synced parent-coll)))+ (select-keys (malli.util/keys NewCollectionArguments)))))++(mu/defn create-collection!+ "Create a new collection."+ [coll-data]+ (u/prog1 (t2/insert-returning-instance!+ :model/Collection+ (-> (apply-defaults-to-collection coll-data)+ write-check-authority-level+ validate-new-tenant-collection!))+ (when config/ee-available?+ (events/publish-event! :event/collection-create {:object <> :user-id api/*current-user-id*}))+ (events/publish-event! :event/collection-touch {:collection-id (:id <>) :user-id api/*current-user-id*})));; 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@@ -1356,7 +1420,7 @@(let [orig-location (:location collection-before-update)new-parent-id (:parent_id collection-updates)new-parent (if new-parent-id- (t2/select-one [:model/Collection :location :id] :id new-parent-id)+ (t2/select-one [:model/Collection :location :id :type] :id new-parent-id)collection/root-collection)new-location (collection/children-location new-parent)];; check and make sure we're actually supposed to be moving something@@ -1368,6 +1432,9 @@(perms/set-has-full-permissions-for-set? @api/*current-user-permissions-set*(collection/perms-for-moving collection-before-update new-parent)))+ (api/check+ (not (collection/shared-tenant-collection? new-parent)))+;; ok, we're good to move!(collection/move-collection! collection-before-update new-location(collection/moving-into-remote-synced? (collection/location-path->parent-id orig-location)@@ -1504,12 +1571,12 @@[:id ms/PositiveInt]]_query-params{authority-level :authority_level, :as collection-updates} :- [:map- [:name {:optional true} [:maybe ms/NonBlankString]]- [:description {:optional true} [:maybe ms/NonBlankString]]- [:archived {:default false} [:maybe ms/BooleanValue]]- [:parent_id {:optional true} [:maybe ms/PositiveInt]]- [:type {:optional true} [:maybe CollectionType]]- [:authority_level {:optional true} [:maybe collection/AuthorityLevel]]]]+ [:name {:optional true} [:maybe ms/NonBlankString]]+ [:description {:optional true} [:maybe ms/NonBlankString]]+ [:archived {:default false} [:maybe ms/BooleanValue]]+ [:parent_id {:optional true} [:maybe ms/PositiveInt]]+ [:type {:optional true} [:maybe CollectionType]]+ [:authority_level {:optional true} [:maybe collection/AuthorityLevel]]]];; do we have perms to edit this Collection?(let [collection-before-update (t2/hydrate (api/write-check :model/Collection id) :parent_id)];; if authority_level is changing, make sure we're allowed to do that@@ -1545,7 +1612,7 @@new-children-location (:location collection)](api/check-400 (:archived collection)"Collection must be trashed before deletion.")- (api/check-400 (nil? (:namespace collection))+ (api/check-400 (contains? #{:tenant-specific :shared-tenant-collections nil} (:namespace collection))"Collections in non-nil namespaces cannot be deleted.");; Shouldn't happen, because they can't be archived either... but juuuuust in case.(api/check-400 (nil? (:personal_owner_id collection))diff --git a/src/metabase/events/schema.clj b/src/metabase/events/schema.cljindex c78e1325647..3d420a0c879 100644--- a/src/metabase/events/schema.clj+++ b/src/metabase/events/schema.clj@@ -48,7 +48,7 @@(mr/def ::collection[:map {:closed true}- [:user-id pos-int?]+ [:user-id [:maybe pos-int?]][:object [:fn #(t2/instance-of? :model/Collection %)]]])(mr/def :event/collection-create ::collection)diff --git a/src/metabase/internal_stats/users.clj b/src/metabase/internal_stats/users.cljindex c399fd967eb..96c62bc6091 100644--- a/src/metabase/internal_stats/users.clj+++ b/src/metabase/internal_stats/users.clj@@ -16,6 +16,8 @@[:= :type [:inline "personal"]]]} :distinct_emails]]})))(defn external-users-count- "Number of users with sso-source: JWT as a proxy for external users of embedded views"+ "Number of users with sso-source: JWT as a proxy for tenant users of embedded views"[]- (t2/count :model/User :is_active true :sso_source :jwt :type :personal))+ ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid the `after-select` method on+ ;; users, which calls an EE method that needs ... a token check :|+ (t2/count (t2/table-name :model/User) :is_active true :sso_source "jwt" :type "personal"))diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 07117957472..f411236f3ae 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -94,6 +94,7 @@:model/SupportAccessGrantLog metabase-enterprise.support-access-grants.models.support-access-grant-log:model/Table metabase.warehouse-schema.models.table:model/TaskHistory metabase.task-history.models.task-history+ :model/Tenant metabase-enterprise.tenants.model:model/Timeline metabase.timeline.models.timeline:model/TimelineEvent metabase.timeline.models.timeline-event:model/Transform metabase-enterprise.transforms.models.transformdiff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.cljindex 305d4e26fa2..90fe3312e2c 100644--- a/src/metabase/permissions/core.clj+++ b/src/metabase/permissions/core.clj@@ -13,6 +13,7 @@[metabase.permissions.models.permissions-revision][metabase.permissions.path][metabase.permissions.published-tables]+ [metabase.permissions.settings][metabase.permissions.user][metabase.permissions.util][metabase.permissions.validation]@@ -48,6 +49,7 @@sandboxes-for-userschema-permission-for-userset-database-permission!+ set-external-group-permissions!set-new-database-permissions!set-new-table-permissions!set-table-permission!@@ -81,12 +83,14 @@set-has-full-permissions-for-set?set-has-full-permissions?][metabase.permissions.models.permissions-group- non-magic-groups]+ non-magic-groups+ all-users-magic-group-type][metabase.permissions.models.permissions-group-membershipadd-users-to-groups!add-user-to-groups!add-user-to-group!allow-changing-all-users-group-members+ allow-changing-all-external-users-group-membersfail-to-remove-last-admin-msgremove-user-from-group!remove-user-from-groups!@@ -98,7 +102,8 @@collection-readwrite-pathcollection-path?][metabase.permissions.user- user-permissions-set]+ user-permissions-set+ user->tenant-collection-and-descendant-ids][metabase.permissions.utilPathSchemacheck-revision-numbers@@ -122,11 +127,13 @@user-has-any-published-table-permission?user-has-published-table-permission-for-database?])-;;; import these vars with different names to make their purpose more obvious.+(p/import-vars [metabase.permissions.settings use-tenants])+;;; import these vars with different names to make their purpose more obvious.(p/import-def metabase.permissions.models.permissions-group/all-users all-users-group)(p/import-def metabase.permissions.models.permissions-group/admin admin-group)(p/import-def metabase.permissions.models.application-permissions-revision/latest-id latest-application-permissions-revision-id)(p/import-def metabase.permissions.models.collection-permission-graph-revision/latest-id latest-collection-permissions-revision-id)(p/import-def metabase.permissions.models.permissions-revision/latest-id latest-permissions-revision-id)(p/import-def metabase.permissions.models.data-permissions/least-permissive-value least-permissive-data-perms-value)+(p/import-def metabase.permissions.models.permissions-group/all-external-users all-external-users-group)diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.cljindex 6ab336e9b70..11f90216319 100644--- a/src/metabase/permissions/models/data_permissions.clj+++ b/src/metabase/permissions/models/data_permissions.clj@@ -670,6 +670,12 @@:perms/manage-table-metadata :no:perms/manage-database :no}))+(defn set-external-group-permissions!+ "Sets the appropriate data permissions for a new external group or database - always the minimum possible data permissions."+ [group-or-id db-id]+ (doseq [[perm-type perm-value] (m/map-vals (fn [{:keys [values]}] (last values)) permissions.schema/data-permissions)]+ (set-database-permission! group-or-id db-id perm-type perm-value)))+(defn set-new-group-permissions!"Sets permissions for a newly-added group to their appropriate values for a single database. This is generally basedon the permissions of the All Users group."diff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.cljindex df18d9ead13..b616e18873f 100644--- a/src/metabase/permissions/models/permissions.clj+++ b/src/metabase/permissions/models/permissions.clj@@ -281,8 +281,8 @@(if (or (= read-or-write :read)(remote-sync/collection-editable? (or (:collection instance) (:collection_id instance))))(perms-objects-set-for-parent-collection instance read-or-write)- ;; We need to return a dummy permissions string that cannot possibly be long to a user in- ;; the case where an instance is not syncable due to remote-sync being in ':read-only' mode+ ;; We need to return a dummy permissions string that cannot possibly belong to a user in+ ;; the case where an instance is not syncable due to remote-sync being in ':production' mode#{"___no-remote-sync-access"}))(methodical/defmethod t2/batched-hydrate [:perms/use-parent-collection-perms :can_write]@@ -437,16 +437,22 @@(defn grant-application-permissions!"Grant full permissions for a group to access a Application permisisons."[group-or-id perm-type]- (when (perms-group/is-tenant-group? group-or-id)+ (when (and (perms-group/is-tenant-group? group-or-id)+ (not= perm-type :subscription))(throw (ex-info (tru "Cannot grant application permission to a tenant group.") {})))(grant-permissions! group-or-id (permissions.path/application-perms-path perm-type)))+;; TODO: We really have to figure out a better solution to these circular dependencies than this(defn- is-personal-collection-or-descendant-of-one? [collection]((requiring-resolve 'metabase.collections.models.collection/is-personal-collection-or-descendant-of-one?) collection))(defn- is-trash-or-descendant? [collection]((requiring-resolve 'metabase.collections.models.collection/is-trash-or-descendant?) collection))+(defn- tenant-collection?+ [collection]+ ((requiring-resolve 'metabase.collections.models.collection/shared-tenant-collection?) collection))+(defn- ^:private collection-or-id->collection[collection-or-id](if (map? collection-or-id)@@ -483,16 +489,17 @@[group-or-id :- permissions.path/MapOrID collection-or-id :- permissions.path/MapOrID](check-is-modifiable-collection collection-or-id)(when (perms-group/is-tenant-group? group-or-id)- (throw (ex-info (tru "Tenant Groups cannot have write access to any collections.") {})))+ (throw (ex-info (tru "Tenant groups cannot have write access to any collections.") {})))(grant-permissions! (u/the-id group-or-id) (permissions.path/collection-readwrite-path collection-or-id)))(mu/defn grant-collection-read-permissions!"Grant read access to a Collection, which means a user can view all Cards in the Collection."[group-or-id :- permissions.path/MapOrID collection-or-id :- permissions.path/MapOrID](check-is-modifiable-collection collection-or-id)- (when (and (perms-group/is-tenant-group? group-or-id)- (audit/is-collection-id-audit? (u/the-id collection-or-id)))- (throw (ex-info (tru "Tenant Groups cannot receive any access to the audit collection.") {})))+ (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.") {}))))(grant-permissions! (u/the-id group-or-id) (permissions.path/collection-read-path collection-or-id)))(defenterprise current-user-has-application-permissions?diff --git a/src/metabase/permissions/models/permissions_group.clj b/src/metabase/permissions/models/permissions_group.cljindex 1a510054456..bb103363fd1 100644--- a/src/metabase/permissions/models/permissions_group.clj+++ b/src/metabase/permissions/models/permissions_group.clj@@ -56,27 +56,12 @@(magic-group all-users-magic-group-type))(def all-external-users-magic-group-type- "The magic group type of the \"All External Users\" magic group."+ "The magic group type of the \"All tenant users\" magic group.""all-external-users")-#_(def ^{:arglists '([])} all-external-users- "Fetch the `all-external-users` magic group"- (mdb/memoize-for-application-db- (fn []- ;; Don't use `magic-group` here, because this one might not exist and that's ok.- (t2/select-one [:model/PermissionsGroup :id :name :magic_group_type] :magic_group_type all-external-users-magic-group-type))))--(defn create-all-external-users!- "Creates the \"All External Users\" magic group."- []- (t2/insert! :model/PermissionsGroup {:magic_group_type all-external-users-magic-group-type- :name "All External Users"- :is_tenant_group true}))--(defn delete-all-external-users!- "Deletes the \"All External Users\" magic group."- []- (t2/delete! :model/PermissionsGroup {:magic_group_type all-external-users-magic-group-type}))+(def ^{:arglists '([])} all-external-users+ "Fetch the `All tenant users` permissions group"+ (magic-group all-external-users-magic-group-type))(def admin-magic-group-type"The magic-group type of the \"Administrators\" magic group."@@ -105,6 +90,7 @@[{id :id}]{:pre [(integer? id)]}(doseq [magic-group [(all-users)+ (all-external-users)(admin)]](when (= id (:id magic-group))(throw (ex-info (tru "You cannot edit or delete the ''{0}'' permissions group!" (:name magic-group))@@ -121,7 +107,9 @@[group](t2/with-transaction [_conn](doseq [db-id (t2/select-pks-vec :model/Database)]- (data-perms/set-new-group-permissions! group db-id (u/the-id (all-users))))))+ (if (:is_tenant_group group)+ (data-perms/set-external-group-permissions! group db-id)+ (data-perms/set-new-group-permissions! group db-id (u/the-id (all-users)))))))(t2/define-after-insert :model/PermissionsGroup[group]diff --git a/src/metabase/permissions/models/permissions_group_membership.clj b/src/metabase/permissions/models/permissions_group_membership.cljindex fa4dcf05a12..7a24d8b4865 100644--- a/src/metabase/permissions/models/permissions_group_membership.clj+++ b/src/metabase/permissions/models/permissions_group_membership.clj@@ -24,6 +24,11 @@but enable it when adding or deleting users."false)+(def ^:dynamic *allow-changing-all-external-users-group-members*+ "Should we allow people to be added to or removed from the All tenant users permissions group? By default, this is+ `false`, but enable it when adding or deleting users."+ false)+(defmacro allow-changing-all-users-group-members"Allow people to be added to or removed from the All Users permissions group? By default, this is disallowed."{:style/indent 0}@@ -31,6 +36,13 @@`(binding [*allow-changing-all-users-group-members* true]~@body))+(defmacro allow-changing-all-external-users-group-members+ "Allow users to be added to or removed from the All tenant users permissions group? By default, this is disallowed."+ {:style/indent 0}+ [& body]+ `(binding [*allow-changing-all-external-users-group-members* true]+ ~@body))+(defn- check-not-all-users-group"Throw an Exception if we're trying to add or remove a user to the All Users group."[group-id]@@ -39,6 +51,14 @@(throw (ex-info (tru "You cannot add or remove users to/from the ''All Users'' group."){:status-code 400})))))+(defn- check-not-all-external-users-group+ "Throw an Exception if we're trying to add or remove a user to the All Users group."+ [group-id]+ (when (= group-id (:id (perms-group/all-external-users)))+ (when-not *allow-changing-all-external-users-group-members*+ (throw (ex-info (tru "You cannot add or remove users to/from the ''All tenant users'' group.")+ {:status-code 400})))))+(defn- admin-count"The current number of non-archived admins (superusers)."[]@@ -64,6 +84,7 @@(t2/define-before-delete :model/PermissionsGroupMembership[{:keys [group_id user_id]}](check-not-all-users-group group_id)+ (check-not-all-external-users-group group_id);; Otherwise if this is the Admin group...(when (= group_id (:id (perms-group/admin)));; ...and this is the last membership, throw an exception@@ -149,6 +170,7 @@user-id->tenant? (t2/select-pk->fn (comp (complement nil?) :tenant_id)[:model/User :id :tenant_id]:id [:in user-ids])+bad-user-group-pairs (->> (keys user-id-group-id->is-group-manager?)(keep (fn [[user-id group-id]](when (not= (group-id->tenant? group-id)@@ -158,10 +180,17 @@:user-is-tenant? (user-id->tenant? user-id):group-is-tenant? (group-id->tenant? group-id)}))))_ (doseq [group-id group-ids]- (check-not-all-users-group group-id))+ (check-not-all-users-group group-id)+ (check-not-all-external-users-group group-id))+ _ (doseq [[[user-id group-id] is-group-manager?] user-id-group-id->is-group-manager?]+ (when (and is-group-manager? (user-id->tenant? user-id))+ (throw (ex-info (tru "Tenant users cannot be made group managers")+ {:bad-user-group-pair [user-id group-id]+ :status-code 400}))))_ (when (seq bad-user-group-pairs)(throw (ex-info (tru "Cannot add non-tenant user to tenant-group or vice versa")- {:bad-user-group-pairs bad-user-group-pairs})))+ {:bad-user-group-pairs bad-user-group-pairs+ :status-code 400})))new-admin-ids (->> user-id-group-id->is-group-manager?keysdiff --git a/src/metabase/permissions/settings.clj b/src/metabase/permissions/settings.cljindex 565325f5b74..9d8e5272f8b 100644--- a/src/metabase/permissions/settings.clj+++ b/src/metabase/permissions/settings.clj@@ -2,9 +2,8 @@(:require[java-time.api :as t][metabase.app-db.core :as mdb]- [metabase.permissions.models.permissions-group :as perms-group][metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru tru]]+ [metabase.util.i18n :refer [deferred-tru]][toucan2.core :as t2]));;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;@@ -54,28 +53,24 @@:type :boolean:audit :never)-(defn- turn-off-tenants! []- ;; TODO: when we have `:model/Tenant`, make sure none exist- (when (t2/exists? :model/User :tenant_id [:not= nil])- (throw (ex-info (tru "Tenants cannot be turned off, a tenant user exists") {})))- (perms-group/delete-all-external-users!))--(defn- turn-on-tenants! []- (perms-group/create-all-external-users!))--(defn- -use-tenants! [new-value]- (if new-value- (turn-on-tenants!)- (turn-off-tenants!))- (setting/set-value-of-type! :boolean :use-tenants new-value))+(defn- update-use-tenants! [new-val]+ (when-not new-val+ ;; deactivate all tenants+ (t2/query {:update :tenant+ :set {:is_active false}})+ ;; deactivate all tenant users, so if the tenant is reactivated someday they'll come back too+ (t2/update! :model/User :tenant_id [:not= nil]+ :is_active true+ {:is_active false :deactivated_with_tenant true}))+ (setting/set-value-of-type! :boolean :use-tenants new-val))(defsetting use-tenants(deferred-tru"Turn on the Tenants feature, allowing users to be assigned to a particular Tenant."):type :boolean- :visibility :admin+ :visibility :authenticated:export? false+ :setter update-use-tenants!:default false:feature :tenants- :can-read-from-env? false- :setter #'-use-tenants!)+ :can-read-from-env? false)diff --git a/src/metabase/permissions/user.clj b/src/metabase/permissions/user.cljindex 168d9d6bbf5..03a939a6fe1 100644--- a/src/metabase/permissions/user.clj+++ b/src/metabase/permissions/user.clj@@ -2,8 +2,15 @@(:require[metabase.app-db.core :as app-db][metabase.permissions.path :as permissions.path]+ [metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]))+(defenterprise user->tenant-collection-and-descendant-ids+ "OSS version of user->tenant-collection-and-descendant-ids. Returns an empty vector since tenants are an EE feature."+ metabase-enterprise.tenants.model+ [_user-or-id]+ [])+(defn user-permissions-set"Return a set of all permissions object paths that `user-or-id` has been granted access to. (2 DB Calls)"[user-or-id]@@ -15,6 +22,11 @@(map permissions.path/collection-readwrite-path((requiring-resolve 'metabase.collections.models.collection/user->personal-collection-and-descendant-ids)user-or-id))++ ;; Current User always gets readwrite perms for their Tenant Collection and for its descendants! (3 DB Calls)+ (map permissions.path/collection-readwrite-path+ (user->tenant-collection-and-descendant-ids user-or-id))+;; include the other Perms entries for any Group this User is in (1 DB Call)(map :object (app-db/query {:select [:p.object]:from [[:permissions_group_membership :pgm]]diff --git a/src/metabase/permissions_rest/api.clj b/src/metabase/permissions_rest/api.cljindex de1112866ae..8f1da735755 100644--- a/src/metabase/permissions_rest/api.clj+++ b/src/metabase/permissions_rest/api.clj@@ -13,6 +13,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.request.core :as request]+ [metabase.settings.core :as setting][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]@@ -135,6 +136,26 @@(some? offset) (sql.helpers/offset offset)(some? query) (sql.helpers/where query))))+(defn- maybe-fix-name+ "With Tenants enabled, we refer to the `all-internal-users` group as \"All Internal Users\", but+ if Tenants is disabled we should call it \"All Users\".++ Actually changing the name brings a whole host of problems, and we very rarely actually present the names of+ Permissions Groups to users. (These are the only endpoints that reveal them.) So I think it makes sense to just+ adjust them here."+ [{:keys [magic_group_type] :as group} using-tenants?]+ (update group :name (fn [n]+ (if (and (= magic_group_type perms/all-users-magic-group-type)+ using-tenants?)+ "All Internal Users"+ n))))++(defn- maybe-fix-names+ "See [[maybe-fix-name]] for details."+ [groups]+ (let [using-tenants? (setting/get :use-tenants)]+ (map #(maybe-fix-name % using-tenants?) groups)))+;; 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;;@@ -143,22 +164,41 @@"Fetch all `PermissionsGroups`, including a count of the number of `:members` in that group.This API requires superuser or group manager of more than one group.Group manager is only available if `advanced-permissions` is enabled and returns only groups that user- is manager of."- []+ is manager of.++ Optional query parameter `tenancy` can be used to filter groups:+ - `tenancy=external`: Returns only tenant groups (where `is_tenant_group = true`)+ - `tenancy=internal`: Returns only non-tenant groups (where `is_tenant_group = false`)+ - No `tenancy` parameter: Returns all groups (default behavior)"+ [_route_params+ {:keys [tenancy]} :- [:map+ [:tenancy {:optional true} [:enum "external" "internal"]]]](try(perms/check-group-manager)(catch clojure.lang.ExceptionInfo _e(perms/check-has-application-permission :setting)))- (let [query (when (and (not api/*is-superuser?*)- (premium-features/enable-advanced-permissions?)- api/*is-group-manager?*)- [:in :id {:select [:group_id]- :from [:permissions_group_membership]- :where [:and- [:= :user_id api/*current-user-id*]- [:= :is_group_manager true]]}])]- (-> (ordered-groups (request/limit) (request/offset) query)- (t2/hydrate :member_count))))+ (let [base-where+ [:and+ (when (and (not api/*is-superuser?*)+ (premium-features/enable-advanced-permissions?)+ api/*is-group-manager?*)+ [:in :id {:select [:group_id]+ :from [:permissions_group_membership]+ :where [:and+ [:= :user_id api/*current-user-id*]+ [:= :is_group_manager true]]}])+ (when-not (setting/get :use-tenants)+ [:not :is_tenant_group])]+ where (case tenancy+ "external" (if (setting/get :use-tenants)+ [:and base-where [:= :is_tenant_group true]]+ [:= 1 0]) ; Return no results when tenants disabled but external requested+ "internal" [:and base-where [:or [:= :is_tenant_group false]+ [:= :is_tenant_group nil]]]+ base-where)]+ (-> (ordered-groups (request/limit) (request/offset) where)+ (t2/hydrate :member_count)+ (maybe-fix-names))));; 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@@ -170,8 +210,9 @@[:id ms/PositiveInt]]](perms/check-group-manager id)(api/check-404- (-> (t2/select-one :model/PermissionsGroup :id id)- (t2/hydrate :members))))+ (some-> (t2/select-one :model/PermissionsGroup :id id)+ (t2/hydrate :members)+ (maybe-fix-name (setting/get :use-tenants)))));; 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@@ -181,11 +222,15 @@"Create a new `PermissionsGroup`."[_route-params_query-params- {:keys [name]} :- [:map- [:name ms/NonBlankString]]]+ {:keys [name is_tenant_group]} :- [:map+ [:name ms/NonBlankString]+ [:is_tenant_group {:optional true} [:maybe :boolean]]]](api/check-superuser)+ (when (and is_tenant_group (not (premium-features/enable-tenants?)))+ (throw (premium-features/ee-feature-error (tru "Tenants"))))(u/prog1 (t2/insert-returning-instance! :model/PermissionsGroup- :name name)+ :name name+ :is_tenant_group (boolean is_tenant_group))(events/publish-event! :event/group-create {:object <>:user-id api/*current-user-id*})))diff --git a/src/metabase/permissions_rest/data_permissions/graph.clj b/src/metabase/permissions_rest/data_permissions/graph.cljindex b8923a4e3c3..b9450ba2d31 100644--- a/src/metabase/permissions_rest/data_permissions/graph.clj+++ b/src/metabase/permissions_rest/data_permissions/graph.clj@@ -54,8 +54,7 @@graph)(mu/defn ellide? :- :boolean- "If a table has the least permissive value for a perm type, leave it out,- Unless it's :data perms, in which case, leave it out only if it's no-self-service"+ "If a table has the least permissive value for a perm type, leave it out."[type :- ::permissions.schema/data-permission-typevalue :- ::permissions.schema/data-permission-value](= (perms/least-permissive-data-perms-value type) value))diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.cljindex d4e3a8c64f1..1776765e5de 100644--- a/src/metabase/premium_features/core.clj+++ b/src/metabase/premium_features/core.clj@@ -38,6 +38,7 @@can-disable-password-login?define-premium-featuredevelopment-mode?+ enable-tenants?enable-advanced-permissions?enable-ai-entity-analysis?enable-ai-sql-fixer?diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.cljindex f4789b70a10..b1a75e93c95 100644--- a/src/metabase/premium_features/settings.clj+++ b/src/metabase/premium_features/settings.clj@@ -315,6 +315,10 @@"Should we enable the Data Studio?":data-studio)+(define-premium-feature ^{:added "0.58.0"} enable-tenants?+ "Is this a development instance that should have watermarks?"+ :tenants)+(defn- -token-features []{:advanced_permissions (enable-advanced-permissions?):ai_sql_fixer (enable-ai-sql-fixer?)@@ -363,6 +367,7 @@:sso_saml (enable-sso-saml?):support-users (enable-support-users?):table_data_editing (table-data-editing?)+ :tenants (enable-tenants?):transforms (enable-transforms?):transforms-python (enable-python-transforms?):upload_management (enable-upload-management?)diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.cljindex 8dcd05db71d..0aa28efde43 100644--- a/src/metabase/premium_features/token_check.clj+++ b/src/metabase/premium_features/token_check.clj@@ -73,7 +73,11 @@;; force this to use a new Connection, it seems to be getting called in situations where the Connection;; is from a different thread and is invalid by the time we get to use it(let [result (binding [t2.conn/*current-connectable* nil]- (t2/count :model/User :is_active true :type :personal))]++ ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid+ ;; the `after-select` method on users, which calls an EE method that needs ... a token+ ;; check :|+ (t2/count (t2/table-name :model/User) :is_active true :type "personal"))](log/debug (u/colorize :green "=>") result)result))lock (Object.)]@@ -191,7 +195,9 @@"Checks that, when in an airgap context, the allowed user count is acceptable."[](when-let [max-users (max-users-allowed)]- (when (> (t2/count :model/User :is_active true, :type :personal) max-users)+ ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid the `after-select` method+ ;; on users, which calls an EE method that needs ... a token check :|+ (when (> (t2/count (t2/table-name :model/User) :is_active true, :type "personal") max-users)(throw (Exception. (trs "You have reached the maximum number of users ({0}) for your plan. Please upgrade to add more users." max-users))))))(mu/defn- decode-token* :- TokenStatusdiff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.cljindex 73c0f89e4c0..5e57caf9597 100644--- a/src/metabase/pulse/api/pulse.clj+++ b/src/metabase/pulse/api/pulse.clj@@ -48,17 +48,30 @@(defn- maybe-filter-pulses-recipients"If the current user is sandboxed, remove all Metabase users from the `pulses` recipient lists that are not the user- themselves. Recipients that are plain email addresses are preserved."+ themselves. Recipients that are plain email addresses are preserved.++ If the current user is not a superuser, also filters the list of recipients to remove users from a different tenant."[pulses]- (if (perms/sandboxed-or-impersonated-user?)- (for [pulse pulses]- (assoc pulse :channels- (for [channel (:channels pulse)]- (assoc channel :recipients- (filter (fn [recipient] (or (not (:id recipient))- (= (:id recipient) api/*current-user-id*)))- (:recipients channel))))))- pulses))+ (cond->> pulses+ (perms/sandboxed-or-impersonated-user?)+ (map (fn [pulse]+ (assoc pulse :channels+ (for [channel (:channels pulse)]+ (assoc channel :recipients+ (filter (fn [recipient]+ (or (not (:id recipient))+ (= (:id recipient) api/*current-user-id*)))+ (:recipients channel)))))))++ (not api/*is-superuser?*)+ (map (fn [pulse]+ (assoc pulse :channels+ (for [channel (:channels pulse)]+ (assoc channel :recipients+ (filter (fn [recipient]+ (or (not (:id recipient))+ (= (:tenant_id recipient) (:tenant_id api/*current-user*))))+ (:recipients channel)))))))))(defn- maybe-filter-pulse-recipients[pulse]diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex a34b0cf4eed..dd83693e71b 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -1349,7 +1349,10 @@:bookmark [:model/CardBookmark [:and[:= :bookmark.card_id :this.id][:= :bookmark.user_id :current_user/id]]]- :where [:and [:= :collection.namespace nil] [:= :this.document_id nil]]+ :where [:and [:or [:= :collection.namespace nil]+ [:= :collection.namespace "shared-tenant-collection"]+ [:= :collection.namespace "tenant-specific"]]+ [:= :this.document_id nil]]:joins {:collection [:model/Collection [:= :collection.id :this.collection_id]]:r [:model/Revision [:and[:= :r.model_id :this.id]diff --git a/src/metabase/request/session.clj b/src/metabase/request/session.cljindex dabb253f9fb..002187b3b6c 100644--- a/src/metabase/request/session.clj+++ b/src/metabase/request/session.clj@@ -36,7 +36,7 @@(some-> metabase-user-id perms/user-permissions-set)))(mu/defn do-with-current-user- "Impl for [[with-current-user]]."+ "Impl for [[with-current-user]] and [[metabase.server.middleware.session/with-current-user-for-request]]"[{:keys [metabase-user-id is-superuser? user-locale settings is-group-manager?], :as current-user-info} :- [:maybe ::request.schema/current-user-info]thunk](binding [*current-user-id* metabase-user-iddiff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.cljindex dbf7c70cc4a..91352cfa012 100644--- a/src/metabase/search/in_place/legacy.clj+++ b/src/metabase/search/in_place/legacy.clj@@ -199,11 +199,12 @@[:not :is_published])(search.permissions/permitted-collections-clause search-ctx collection-id-col)]personal-clause (search.filter/personal-collections-where-clause search-ctx collection-id-col)]- (cond-> honeysql-query+ (-> honeysql-query+ (sql.helpers/where permitted-clause)+ (cond->;; add a JOIN against Collection *unless* the source table is already Collection- (not= model "collection") (sql.helpers/left-join [:collection :collection] [:= collection-id-col :collection.id])- true (sql.helpers/where permitted-clause)- personal-clause (sql.helpers/where personal-clause))))+ (not= model "collection") (sql.helpers/left-join [:collection :collection] [:= collection-id-col :collection.id])+ personal-clause (sql.helpers/where personal-clause)))))(mu/defn- replace-select :- :map"Replace a select from query that has alias is `target-alias` with [`with` `target-alias`] column, throw an error ifdiff --git a/src/metabase/search/permissions.clj b/src/metabase/search/permissions.cljindex 8a325f553d5..fb293ef0040 100644--- a/src/metabase/search/permissions.clj+++ b/src/metabase/search/permissions.clj@@ -40,7 +40,13 @@:permission-level (if archived :write :read)}{:current-user-id current-user-id:is-superuser? is-superuser?})- (perms/audit-namespace-clause :collection.namespace nil)])+ ;; This is to allow the set of namespaces indexed by the search spec for appdb-based search to also apply to+ ;; legacy search so it performs the same on MySQL+ ;; TODO(edpaget 2025-12-04): this should be a default value of the search context and then search can be restricted+ ;; to different namespaces via parameters.+ [:or (perms/audit-namespace-clause :collection.namespace nil)+ [:= :collection.namespace "tenant-specific"]+ [:= :collection.namespace "shared-tenant-collection"]]])(mu/defn permitted-tables-clause"Build the WHERE clause corresponding to which tables the given user has access to."diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 075993db0a2..20f19907851 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -28,6 +28,7 @@[metabase.request.core :as request][metabase.request.schema :as request.schema][metabase.session.core :as session]+ [metabase.settings.core :as setting][metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n][metabase.util.log :as log]@@ -94,17 +95,21 @@;; Because this query runs on every single API request it's worth it to optimize it a bit and only compile it to SQL;; once rather than every time-(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions?])} session-with-id-query+(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants?])} session-with-id-query(memoize- (fn [db-type max-age-minutes session-type enable-advanced-permissions?]+ (fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants?](first(t2.pipeline/compile*(cond-> {:select [[:session.user_id :metabase-user-id][:user.is_superuser :is-superuser?][:user.locale :user-locale]]:from [[:core_session :session]]- :left-join [[:core_user :user] [:= :session.user_id :user.id]]+ :left-join [[:core_user :user] [:= :session.user_id :user.id]+ [:tenant] [:= :tenant.id :user.tenant_id]]:where [:and+ (if enable-tenants?+ [:or [:= :tenant.id nil] :tenant.is_active]+ [:= :tenant.id nil])[:= :user.is_active true][:or [:= :session.id [:raw "?"]] [:= :session.key_hashed [:raw "?"]]](let [oldest-allowed (case db-type@@ -174,7 +179,9 @@(let [sql (session-with-id-query (mdb/db-type)(config/config-int :max-session-age)(if (seq anti-csrf-token) :full-app-embed :normal)- (premium-features/enable-advanced-permissions?))+ (premium-features/enable-advanced-permissions?)+ (and (premium-features/enable-tenants?)+ (setting/get :use-tenants)))params (concat [session-key (session/hash-session-key session-key)](when (seq anti-csrf-token)[anti-csrf-token]))]diff --git a/src/metabase/sso/common.clj b/src/metabase/sso/common.cljindex 854d7eaa848..1141aa7a9da 100644--- a/src/metabase/sso/common.clj+++ b/src/metabase/sso/common.clj@@ -10,7 +10,8 @@(defn- excluded-group-ids[]- #{(u/the-id (perms/all-users-group))})+ #{(u/the-id (perms/all-users-group))+ (u/the-id (perms/all-external-users-group))})(defn- sync-group-memberships*![user-or-id to-remove to-add]diff --git a/src/metabase/tenants/core.clj b/src/metabase/tenants/core.cljnew file mode 100644index 00000000000..8589eb71ffd--- /dev/null+++ b/src/metabase/tenants/core.clj@@ -0,0 +1,81 @@+(ns metabase.tenants.core+ "Shim namespace for `metabase-enterprise.tenants.core`"+ (:require+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util.malli :as mu]))++(defenterprise login-attributes+ "OSS version of `login-attributes`"+ metabase-enterprise.tenants.core+ [_user]+ {})++(defenterprise login-attribute-keys+ "OSS version of `login-attribute-keys`"+ metabase-enterprise.tenants.core+ []+ #{})++(defenterprise tenant-is-active?+ "OSS version of `tenant-is-active?`. Returns `true` only if you have no tenant, because no tenants are active on+ OSS."+ metabase-enterprise.tenants.core+ [tenant-id]+ (nil? tenant-id))++(defenterprise create-tenant!+ "Throws an exception in OSS because we can't create tenants there."+ metabase-enterprise.tenants.core+ [_tenant]+ (throw (ex-info "Cannot create tenant in OSS." {})))++(def ^:private SimpleAttributes+ "Basic attributes for users and tenants are a map of string keys to string values."+ [:map-of :string :string])++(def ^:private SystemAttributes+ "Attributes generated from system properties must be prefixed with @."+ [:map-of [:re #"@.*"] :string])++(def ^:private AttributeStatus+ "Describes a possible value of an attribute and where it is sourced from."+ [:map+ [:source [:enum :user :tenant :system]]+ [:frozen boolean?]+ [:value :string]])++(def ^:private CombinedAttributes+ "Map of user attributes to their current value and metadata describing where they are sourced from."+ [:map-of :string+ [:merge AttributeStatus+ [:map+ [:original {:optional true}+ AttributeStatus]]]])++(mu/defn combine :- CombinedAttributes+ "Combines user, tenant, and system attributes. User can override "+ ([user :- [:maybe SimpleAttributes]]+ (combine user nil nil))+ ([user :- [:maybe SimpleAttributes]+ tenant :- [:maybe SimpleAttributes]+ system :- [:maybe SystemAttributes]]+ (letfn [(value-map [s f vs] (into {}+ (for [[k v] vs]+ [k {:source s :frozen f :value v}])))+ (shadow [original new] (if original (assoc new :original original) new))+ (error [original new] (if original+ (throw (ex-info "Cannot clobber"+ {:bad-attribute original+ :attribute new}))+ new))]+ (merge-with error+ (merge-with shadow+ (value-map :tenant false tenant)+ (value-map :user false user))+ (value-map :system true system)))))++(defenterprise user->tenant+ "Get the tenant for a user"+ metabase-enterprise.tenants.core+ [_user]+ nil)diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.cljindex cf35201717b..82c522e136a 100644--- a/src/metabase/users/models/user.clj+++ b/src/metabase/users/models/user.clj@@ -14,6 +14,7 @@[metabase.settings.core :as setting][metabase.setup.core :as setup][metabase.system.core :as system]+ [metabase.tenants.core :as tenants][metabase.users.schema :as users.schema][metabase.util :as u][metabase.util.honey-sql-2 :as h2x]@@ -42,9 +43,27 @@(derive :hook/updated-at-timestamped?)(derive :hook/entity-id))+(defn- stringify-keys-and-values+ "Given a map, convert all the keys and values to strings."+ [m]+ (into {} (map (fn [[k v]] [(u/qualified-name k)+ ;; Preserve nils and don't stringify maps/lists so existing error handling+ ;; catches those+ (cond-> v+ (and (some? v)+ (not (or (vector? v)+ (map? v)))) str)]))+ m))++(def ^:private transform-attributes+ "Transform user attributes, which are maps of strings->strings. There may be some existing values in the database+ which are not, so convert on the way out."+ {:in (comp mi/json-in stringify-keys-and-values)+ :out (comp stringify-keys-and-values mi/json-out-without-keywordization)})+(t2/deftransforms :model/User- {:login_attributes mi/transform-json-no-keywordization- :jwt_attributes mi/transform-json-no-keywordization+ {:login_attributes transform-attributes+ :jwt_attributes transform-attributes:settings mi/transform-encrypted-json:sso_source mi/transform-keyword:type mi/transform-keyword})@@ -237,10 +256,12 @@(when superuser?(log/infof "Adding User %s to All Users permissions group..." user-id))(let [groups (filter some? [(when-not (:tenant_id user) (perms/all-users-group))+ (when (:tenant_id user) (perms/all-external-users-group))(when superuser? (perms/admin-group))])](perms/allow-changing-all-users-group-members- (perms/without-is-superuser-sync-on-add-to-admin-group- (perms/add-user-to-groups! user-id (map u/the-id groups)))))+ (perms/allow-changing-all-external-users-group-members+ (perms/without-is-superuser-sync-on-add-to-admin-group+ (perms/add-user-to-groups! user-id (map u/the-id groups))))))(sync-password-to-auth-identity! user-id)))(t2/define-before-update :model/User@@ -411,6 +432,23 @@(for [user users](assoc user :is_installer (= (:id user) 1)))))+(mi/define-batched-hydration-method add-tenant-collection-id+ :tenant_collection_id+ "Efficiently hydrate the `:tenant_collection_id` property of a sequence of Users. (This is the ID of their Tenant's+ Collection, if they belong to a tenant.)"+ [users]+ (when (seq users)+ ;; efficiently create a map of tenant ID -> tenant collection ID+ (let [users-with-tenant-ids (filter :tenant_id users)+ tenant-ids (set (map :tenant_id users-with-tenant-ids))+ tenant-id->collection-id (when (seq tenant-ids)+ (t2/select-pk->fn :tenant_collection_id :model/Tenant+ :id [:in tenant-ids]))]+ ;; now for each User, try to find the corresponding tenant collection ID+ (for [user users]+ (assoc user :tenant_collection_id (when-let [tenant-id (:tenant_id user)]+ (get tenant-id->collection-id tenant-id)))))))+;;; --------------------------------------------------- Helper Fns ---------------------------------------------------(declare form-password-reset-url)@@ -477,7 +515,7 @@(defn add-attributes"Adds the `:attributes` key to a user."[{:keys [login_attributes jwt_attributes] :as user}]- (assoc user :attributes (merge jwt_attributes login_attributes)))+ (assoc user :attributes (merge {} (tenants/login-attributes user) jwt_attributes login_attributes)));;; Filtering usersdiff --git a/src/metabase/users/schema.clj b/src/metabase/users/schema.cljindex 4c44b1b081e..07e272d47d4 100644--- a/src/metabase/users/schema.clj+++ b/src/metabase/users/schema.clj@@ -6,9 +6,15 @@(def LoginAttributes"Login attributes, currently not collected for LDAP or Google Auth. Will ultimately be stored as JSON."- (mu/with-api-error-message- [:map-of ms/KeywordOrString :any]- (deferred-tru "login attribute keys must be a keyword or string")))+ [:map-of+ [:and+ (mu/with-api-error-message+ ms/KeywordOrString+ (deferred-tru "login attribute keys must be a keyword or string"))+ (mu/with-api-error-message+ [:fn (fn [k] (re-matches #"^(?!@).*" (name k)))]+ (deferred-tru "login attribute keys must not start with `@`"))]+ :any])(def NewUser"Required/optionals parameters needed to create a new user (for any backend)"@@ -21,4 +27,5 @@[:jwt_attributes {:optional true} [:maybe LoginAttributes]][:sso_source {:optional true} [:maybe ms/NonBlankString]][:locale {:optional true} [:maybe ms/KeywordOrString]]- [:type {:optional true} [:maybe ms/KeywordOrString]]])+ [:type {:optional true} [:maybe ms/KeywordOrString]]+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]])diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.cljindex a0440f01a10..5cbc8decf27 100644--- a/src/metabase/users_rest/api.clj+++ b/src/metabase/users_rest/api.clj@@ -12,10 +12,13 @@[metabase.config.core :as config][metabase.events.core :as events][metabase.models.interface :as mi]+ [metabase.notification.core :as notification][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][metabase.request.core :as request]+ [metabase.settings.core :as setting][metabase.sso.core :as sso]+ [metabase.tenants.core :as tenants][metabase.users.models.user :as user][metabase.users.schema :as users.schema][metabase.users.settings :as users.settings]@@ -108,7 +111,7 @@(def ^:private AttributeStatus"Describes a possible value of an attribute and where it is sourced from."[:map- [:source [:enum :user :jwt :system]]+ [:source [:enum :user :jwt :system :tenant]][:frozen boolean?][:value :string]])@@ -122,7 +125,7 @@(def ^:private attribute-merge-order"What order to merge attributes in when used with combine"- [:jwt :user])+ [:jwt :tenant :user])(mu/defn- combine :- CombinedAttributes"Combines user, tenant, and system attributes. User can override "@@ -145,7 +148,13 @@(defn- add-structured-attributes[{:keys [login_attributes jwt_attributes] :as user}]- (assoc user :structured_attributes (combine {:jwt jwt_attributes :user login_attributes} nil)))+ (let [tenant (tenants/user->tenant user)]+ (assoc user :structured_attributes+ (combine {:jwt jwt_attributes+ :user login_attributes+ :tenant (:attributes tenant)}+ (when-let [slug (:slug tenant)]+ {"@tenant.slug" slug})))));;; +----------------------------------------------------------------------------------------------------------------+;;; | Fetching Users -- GET /api/user, GET /api/user/current, GET /api/user/:id |@@ -193,6 +202,7 @@to use `status` for better support and flexibility.If both params are passed, `status` takes precedence.+ - if a `tenant_id` is passed, only users with that tenant_id will be returned.For users with segmented permissions, return only themselves.@@ -202,21 +212,32 @@Also takes `group_id`, which filters on group id."[_route-params- {:keys [status query group_id include_deactivated]}+ {:keys [status query group_id include_deactivated tenant_id tenancy] :as params}:- [:map[:status {:optional true} [:maybe :string]][:query {:optional true} [:maybe :string]][:group_id {:optional true} [:maybe ms/PositiveInt]]- [:include_deactivated {:default false} [:maybe ms/BooleanValue]]]]+ [:include_deactivated {:default false} [:maybe ms/BooleanValue]]+ [:tenancy {:optional true} [:maybe+ [:enum :all :internal :external]]]+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]]](or api/*is-superuser?*(if group_id(perms/check-manager-of-group group_id)(perms/check-group-manager)))+ (api/check-400 (not (every? #(contains? params %) [:tenant_id :tenancy]))+ (tru "You cannot specify both `tenancy` and `tenant_id`"))(let [include_deactivated include_deactivatedgroup-id-clause (when group_id [group_id])- clauses (user/filter-clauses status query group-id-clause include_deactivated- {:limit (request/limit)- :offset (request/offset)})]+ clauses (let [clauses (user/filter-clauses status query group-id-clause include_deactivated+ {:limit (request/limit)+ :offset (request/offset)})]+ (cond+ (not api/*is-superuser?*) (sql.helpers/where clauses [:= :tenant_id (:tenant_id @api/*current-user*)])+ (contains? params :tenant_id) (sql.helpers/where clauses [:= :tenant_id tenant_id])+ (= tenancy :all) clauses+ (= tenancy :external) (sql.helpers/where clauses [:not= :tenant_id nil])+ :else (sql.helpers/where clauses [:= :tenant_id nil])))]{:data (cond-> (t2/select(vec (cons :model/User (user-visible-columns)))(sql.helpers/order-by clauses@@ -225,13 +246,13 @@[:id :asc]));; For admins also include the IDs of Users' Personal Collectionsapi/*is-superuser?*- (t2/hydrate :personal_collection_id)+ (t2/hydrate :personal_collection_id :tenant_collection_id)(or api/*is-superuser?*api/*is-group-manager?*)(t2/hydrate :group_ids);; if there is a group_id clause, make sure the list is deduped in case the same user is in multiple gropus- group-id-clause+ group_iddistinct):total (-> (t2/query(merge {:select [[[:count [:distinct :core_user.id]] :count]]@@ -268,14 +289,17 @@- If user-visibility is :none or the user is sandboxed, include only themselves."[];; defining these functions so the branching logic below can be as clear as possible- (letfn [(all [] (let [clauses (-> (user/filter-clauses nil nil nil nil)- (sql.helpers/order-by [:%lower.last_name :asc] [:%lower.first_name :asc]))]+ (letfn [(all [] (let [clauses (cond-> (user/filter-clauses nil nil nil nil)+ (not api/*is-superuser?*) (sql.helpers/where+ [:= :tenant_id (:tenant_id @api/*current-user*)])+ true (sql.helpers/order-by [:%lower.last_name :asc] [:%lower.first_name :asc]))]{:data (t2/select (vec (cons :model/User (user-visible-columns))) clauses):total (t2/count :model/User (filter-clauses-without-paging clauses)):limit (request/limit):offset (request/offset)}))(within-group [] (let [user-ids (same-groups-user-ids api/*current-user-id*)clauses (cond-> (user/filter-clauses nil nil nil nil)+ (not api/*is-superuser?*) (sql.helpers/where [:= :tenant_id (:tenant_id @api/*current-user*)])(seq user-ids) (sql.helpers/where [:in :core_user.id user-ids])true (sql.helpers/order-by [:%lower.last_name :asc] [:%lower.first_name :asc]))]{:data (t2/select (vec (cons :model/User (user-visible-columns))) clauses)@@ -375,6 +399,19 @@(assoc user:custom_homepage (when valid? {:dashboard_id id}))))+(defn- add-can-write-any-collection+ "Adds a key to the user reflecting whether they have permission to write *any* collection in the instance so that the+ FE can appropriately hide/show elements (e.g., we shouldn't try to let them save a new question if they don't have+ anywhere to save *to*)"+ [user]+ (assoc user :can_write_any_collection+ (or (:is_superuser user)+ (t2/exists? :model/Collection {:where (collection/visible-collection-filter-clause+ :id+ {:include-trash-collection? false+ :include-archived-items :exclude+ :permission-level :write})}))))+;; 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;;@@ -383,13 +420,14 @@"Fetch the current `User`."[](-> (api/check-404 @api/*current-user*)- (t2/hydrate :personal_collection_id :group_ids :is_installer :has_invited_second_user)+ (t2/hydrate :personal_collection_id :group_ids :is_installer :has_invited_second_user :tenant_collection_id)add-has-question-and-dashboardadd-first-loginadd-query-permissionsmaybe-add-advanced-permissionsmaybe-add-sso-source- add-custom-homepage-info))+ add-custom-homepage-info+ add-can-write-any-collection));; 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@@ -417,12 +455,18 @@(api/check-superuser)(api/checkp (not (t2/exists? :model/User :%lower.email (u/lower-case-en email)))"email" (tru "Email address already in use."))+ (api/checkp (not (and (:tenant_id body)+ (not (setting/get :use-tenants))))+ "tenant_id"+ (tru "Cannot create a Tenant User as Tenants are not enabled for this instance."))(t2/with-transaction [_conn]- (let [new-user-id (u/the-id (user/create-and-invite-user!- (u/select-keys-when body- :non-nil [:first_name :last_name :email :password :login_attributes])- @api/*current-user*- (= source "setup")))]+ (let [new-user-id (u/the-id+ (notification/with-skip-sending-notification (boolean (:tenant_id body))+ (user/create-and-invite-user!+ (u/select-keys-when body+ :non-nil [:first_name :last_name :email :password :login_attributes :tenant_id])+ @api/*current-user*+ (= source "setup"))))](maybe-set-user-group-memberships! new-user-id user_group_memberships)(when (= source "setup")(maybe-set-user-permissions-groups! new-user-id [(perms/all-users-group) (perms/admin-group)]))@@ -447,7 +491,8 @@[:email ms/Email][:user_group_memberships {:optional true} [:maybe [:sequential ::user-group-membership]]][:login_attributes {:optional true} [:maybe users.schema/LoginAttributes]]- [:source {:optional true, :default "admin"} [:maybe ms/NonBlankString]]]]+ [:source {:optional true, :default "admin"} [:maybe ms/NonBlankString]]+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]]](invite-user body));;; +----------------------------------------------------------------------------------------------------------------+@@ -475,6 +520,16 @@(= (get user name-key) new-name)(not sso_source)))+(defn- reset-magic-group-membership!+ [user-id tenant-id]+ (perms/allow-changing-all-users-group-members+ (perms/allow-changing-all-external-users-group-members+ (t2/delete! :model/PermissionsGroupMembership :user_id user-id)+ (when tenant-id+ (perms/add-user-to-group! user-id (perms/all-external-users-group)))+ (when (nil? tenant-id)+ (perms/add-user-to-group! user-id (perms/all-users-group))))))+;; 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;;@@ -495,7 +550,8 @@[:is_superuser {:optional true} [:maybe :boolean]][:is_group_manager {:optional true} [:maybe :boolean]][:login_attributes {:optional true} [:maybe users.schema/LoginAttributes]]- [:locale {:optional true} [:maybe ms/ValidLocale]]]]+ [:locale {:optional true} [:maybe ms/ValidLocale]]+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]]](try(check-self-or-superuser id)(catch clojure.lang.ExceptionInfo _e@@ -525,10 +581,14 @@(when-let [changes (not-empty(u/select-keys-when body:present (cond-> #{:first_name :last_name :locale}- api/*is-superuser?* (conj :login_attributes))+ api/*is-superuser?* (conj :login_attributes :tenant_id)):non-nil (cond-> #{:email}api/*is-superuser?* (conj :is_superuser))))](t2/update! :model/User id changes)+ (when (contains? changes :tenant_id)+ (api/check-400 (not (and (:tenant_id changes) (:is_superuser changes)))+ "Superusers cannot be tenant users")+ (reset-magic-group-membership! id (:tenant_id changes)))(events/publish-event! :event/user-update {:object (t2/select-one :model/User :id id):previous-object user-before-update:user-id api/*current-user-id*}))@@ -564,13 +624,15 @@[:id ms/PositiveInt]]](api/check-superuser)(check-not-internal-user id)- (let [user (t2/select-one [:model/User :id :email :first_name :last_name :is_active :sso_source]+ (let [user (t2/select-one [:model/User :id :email :first_name :last_name :is_active :sso_source :tenant_id]:type :personal:id id)](api/check-404 user);; Can only reactivate inactive users(api/check (not (:is_active user))[400 {:message (tru "Not able to reactivate an active user")}])+ (api/check (tenants/tenant-is-active? (:tenant_id user))+ [400 {:message (tru "Not able to reactivate a user in a deactivated tenant")}])(events/publish-event! :event/user-reactivated {:object user :user-id api/*current-user-id*})(reactivate-user! (dissoc user [:email :first_name :last_name]))))diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.cljindex e78f35f1e45..4561c36f0a6 100644--- a/src/metabase/warehouses/models/database.clj+++ b/src/metabase/warehouses/models/database.clj@@ -75,6 +75,9 @@(perms/set-database-permission! (perms/all-users-group) temp-object :perms/view-data :unrestricted)(perms/set-database-permission! (perms/all-users-group) temp-object :perms/create-queries :query-builder-and-native)(perms/set-database-permission! (perms/all-users-group) temp-object :perms/download-results :one-million-rows)+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/view-data :blocked)+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/create-queries :no)+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/download-results :no)(f temp-object)))(defn- should-read-audit-db?@@ -259,17 +262,28 @@(when-not (is-destination? database)(t2/with-transaction [_conn](let [all-users-group (perms/all-users-group)+ all-external-users-group (perms/all-external-users-group)non-magic-groups (perms/non-magic-groups)- non-admin-groups (conj non-magic-groups all-users-group)]+ non-admin-groups (conj non-magic-groups all-users-group all-external-users-group)](if (:is_audit database)(doseq [group non-admin-groups]- (perms/set-database-permission! group database :perms/view-data :unrestricted)- (perms/set-database-permission! group database :perms/create-queries :no)- (perms/set-database-permission! group database :perms/download-results :one-million-rows)- (perms/set-database-permission! group database :perms/manage-table-metadata :no)- (perms/set-database-permission! group database :perms/manage-database :no))+ (if-not (:is_tenant_group group)+ (do+ (perms/set-database-permission! group database :perms/view-data :unrestricted)+ (perms/set-database-permission! group database :perms/create-queries :no)+ (perms/set-database-permission! group database :perms/download-results :one-million-rows)+ (perms/set-database-permission! group database :perms/manage-table-metadata :no)+ (perms/set-database-permission! group database :perms/manage-database :no))+ (do+ (perms/set-database-permission! group database :perms/view-data :no)+ (perms/set-database-permission! group database :perms/create-queries :no)+ (perms/set-database-permission! group database :perms/download-results :no)+ (perms/set-database-permission! group database :perms/manage-table-metadata :no)+ (perms/set-database-permission! group database :perms/manage-database :no))))(doseq [group non-admin-groups]- (perms/set-new-database-permissions! group database)))))))+ (if-not (:is_tenant_group group)+ (perms/set-new-database-permissions! group database)+ (perms/set-external-group-permissions! group database))))))))(t2/define-after-insert :model/Database[database]diff --git a/test/metabase/app_db/custom_migrations_test.clj b/test/metabase/app_db/custom_migrations_test.cljindex ff6e30624fe..6b0dc5c480e 100644--- a/test/metabase/app_db/custom_migrations_test.clj+++ b/test/metabase/app_db/custom_migrations_test.clj@@ -109,6 +109,10 @@:details (json/encode {:channel "general"}):schedule_type "daily":schedule_hour 15})+ :metabase_table (with-timestamped+ {:name (mt/random-name)+ :active true})+ :permissions_group {:name (mt/random-name)}{})))(defn- new-instance-with-default@@ -2696,3 +2700,28 @@(migrate! :down 56);; assert pre conditions(assert-pre-conditions))))))++(deftest escape-existing-at-symbol-user-attributes-test+ (testing "v58.2025-11-18T12:31:49 : rename any existing `@.+` user attrs to add a preceding underscore"+ (impl/test-migrations ["v58.2025-11-18T12:31:49"] [migrate!]+ (let [user-id (:id (new-instance-with-default :core_user {:login_attributes "{\"@foo\": \"bar\"}"}))+ other-user-id (:id (new-instance-with-default :core_user {:login_attributes "{\"@foo\": \"bang\"}"}))+ database-id (:id (new-instance-with-default :metabase_database))+ table-id (:id (new-instance-with-default :metabase_table {:db_id database-id}))+ group-id (:id (new-instance-with-default :permissions_group))+ sandbox-id (:id (new-instance-with-default :sandboxes {:attribute_remappings "{\"@foo\": \"bar\"}"+ :table_id table-id+ :group_id group-id}))+ impersonation-id (:id (new-instance-with-default :connection_impersonations {:attribute "@foo"+ :db_id database-id+ :group_id group-id}))+ db-router-id (:id (new-instance-with-default :db_router {:user_attribute "@foo" :database_id database-id}))]+ (migrate!)+ (is (= {"_@foo" "bar"}+ (json/decode (:attribute_remappings (t2/select-one :sandboxes :id sandbox-id)))))+ (is (= "_@foo" (:attribute (t2/select-one :connection_impersonations impersonation-id))))+ (is (= "_@foo" (:user_attribute (t2/select-one :db_router db-router-id))))+ (is (= {"_@foo" "bar"}+ (json/decode (t2/select-one-fn :login_attributes :core_user :id user-id))))+ (is (= {"_@foo" "bang"}+ (json/decode (t2/select-one-fn :login_attributes :core_user :id other-user-id))))))))diff --git a/test/metabase/app_db/setup_test.clj b/test/metabase/app_db/setup_test.cljindex a79f0d88197..7d0de30f2d0 100644--- a/test/metabase/app_db/setup_test.clj+++ b/test/metabase/app_db/setup_test.clj@@ -32,7 +32,7 @@(letfn [(test* [data-source](is (= :done(mdb.setup/setup-db! :h2 data-source true true)))- (is (= ["Administrators" "All Users"]+ (is (= ["Administrators" "All Users" "All tenant users"](mapv :name (jdbc/query {:datasource data-source}"SELECT name FROM permissions_group ORDER BY name ASC;")))))](let [subname (fn [] (format "mem:%s;DB_CLOSE_DELAY=10" (mt/random-name)))]diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex 08ecfd55210..0702c6a9e32 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -1526,7 +1526,7 @@(mt/with-temp [:model/Collection {collection-id :id} {:namespace "x"}](is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Card can only go in Collections in the \"default\" or :analytics namespace."+ #"A Card can only go in Collections in the \"default\" or :shared-tenant-collection or :tenant-specific or :analytics namespace."(collection/check-collection-namespace :model/Card collection-id)))))(testing "Should throw exception if Collection does not exist"@@ -1821,61 +1821,6 @@(is (set? result)"Should return a set of card IDs")))))-(deftest non-remote-synced-dependencies-different-remote-synced-roots-test- (testing "non-remote-synced-dependencies function behavior with different remote-synced roots"- ;; This test documents the expected behavior when Cards have dependencies- ;; across different remote-synced collection roots. The function should:- ;; 1. NOT flag dependencies within the same remote-synced root hierarchy- ;; 2. FLAG dependencies that cross between different remote-synced roots-- (testing "Setup: Creating remote-synced collection hierarchies"- (mt/with-temp [:model/Collection {root-1 :id} {:name "Remote-Synced Root 1" :is_remote_synced true}- :model/Collection {child-1 :id} {:name "Child of Root 1"- :location (format "/%d/" root-1)- :is_remote_synced true}- :model/Collection {root-2 :id} {:name "Remote-Synced Root 2" :is_remote_synced true}- :model/Collection {child-2 :id} {:name "Child of Root 2"- :location (format "/%d/" root-2)- :is_remote_synced true}]-- ;; Verify the collections are correctly created- (is (true? (:is_remote_synced (t2/select-one :model/Collection :id root-1)))- "Root 1 should be remote-synced type")- (is (true? (:is_remote_synced (t2/select-one :model/Collection :id root-2)))- "Root 2 should be remote-synced type")- (is (= (format "/%d/" root-1) (:location (t2/select-one :model/Collection :id child-1)))- "Child 1 should be nested under Root 1")- (is (= (format "/%d/" root-2) (:location (t2/select-one :model/Collection :id child-2)))- "Child 2 should be nested under Root 2")))-- (testing "Expected behavior documentation (actual dependency tracking requires serdes setup)"- ;; Note: The actual implementation relies on serdes/descendants to track dependencies.- ;; In a real scenario with properly set up dependencies:- ;;- ;; Scenario 1: Card in child-1 depends on Card in root-1 (same hierarchy)- ;; - Both are under remote-synced root-1- ;; - Result: Should return empty set (no non-remote-synced dependencies)- ;;- ;; Scenario 2: Card in root-2 depends on Card in root-1 (different roots)- ;; - They are in different remote-synced roots- ;; - Result: Should return #{card-in-root-1} as non-remote-synced dependency- ;;- ;; Scenario 3: Card in child-2 depends on Card in child-1 (different root hierarchies)- ;; - They are in children of different remote-synced roots- ;; - Result: Should return #{card-in-child-1} as non-remote-synced dependency-- (is (fn? collection/non-remote-synced-dependencies)- "non-remote-synced-dependencies function should exist")-- ;; The function implementation checks:- ;; 1. Gets the collection of the model- ;; 2. Determines the root collection ID (either the collection itself or its root from location)- ;; 3. Traverses dependencies using serdes/descendants- ;; 4. Filters out Cards that are in the same remote-synced root hierarchy- ;; 5. Returns Card IDs that are NOT in the same remote-synced root-- (is true "See implementation in src/metabase/collections/models/collection.clj:1521-1544"))))-(deftest non-remote-synced-dependencies-mixed-locations-test(testing "when model has mixed card dependencies (some in remote-synced, some outside)"(mt/with-temp [:model/Collection {remote-synced-coll-id :id} {:name "Remote-Synced Collection" :is_remote_synced true}@@ -2053,7 +1998,7 @@"Should return true when moving from regular to remote-synced collection"))(testing "when moving from remote-synced collection to remote-synced collection"- (is (true? (collection/moving-into-remote-synced? remote-synced-id other-remote-synced-id))+ (is (false? (collection/moving-into-remote-synced? remote-synced-id other-remote-synced-id))"Should return false when moving from remote-synced collection to remote-synced collection"))(testing "when moving from remote-synced collection to non-remote-synced collection"@@ -2312,7 +2257,7 @@"Should return true when moving from remote-synced collection to regular collection"))(testing "when moving from remote-synced collection to remote-synced collection"- (is (true? (collection/moving-from-remote-synced? remote-synced-id other-remote-synced-id))+ (is (false? (collection/moving-from-remote-synced? remote-synced-id other-remote-synced-id))"Should return false when moving from remote-synced collection to remote-synced collection"))(testing "when moving from non-remote-synced to remote-synced collection"@@ -2342,11 +2287,11 @@(deftest ^:parallel remote-synced-dependents-no-dependents-test(testing "when there are no dependents"- (mt/with-temp [:model/Collection {remote-synced-id :id} {:name "Remote-Synced" :location "/" :is_remote_synced true}+ (mt/with-temp [:model/Collection _ {:name "Remote-Synced" :location "/" :is_remote_synced true}:model/Card {card-id :id} {:name "Test Card":database_id (mt/id):dataset_query (mt/mbql-query venues)}]- (is (= [] (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id card-id})))+ (is (= [] (collection/remote-synced-dependents (t2/instance :model/Card {:id card-id})))"Should return empty seq when card has no dependents"))))(deftest ^:parallel remote-synced-dependents-in-remote-synced-test@@ -2359,7 +2304,7 @@:collection_id remote-synced-id:database_id (mt/id):dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-id)})}]- (let [dependents (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))](is (= 1 (count dependents))"Should find one dependent")(is (= {"Card" dep-card} (first dependents))@@ -2367,7 +2312,7 @@(deftest ^:parallel remote-synced-dependents-outside-remote-synced-test(testing "when dependents are outside remote-synced collection"- (mt/with-temp [:model/Collection {remote-synced-id :id} {:name "Remote-Synced" :is_remote_synced true}+ (mt/with-temp [:model/Collection {_remote-synced-id :id} {:name "Remote-Synced" :is_remote_synced true}:model/Collection {regular-id :id} {:name "Regular"}:model/Card {base-card-id :id} {:name "Base Card":database_id (mt/id)@@ -2376,10 +2321,10 @@:collection_id regular-id:database_id (mt/id):dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-id)})}]- (is (= [] (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id})))+ (is (= [] (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id})))"Should not return dependents outside the remote-synced collection"))))-(deftest ^:parallel remote-synced-dependents-archived-test+(deftest remote-synced-dependents-archived-test(testing "when dependents are archived"(mt/with-temp [:model/Collection {remote-synced-id :id} {:name "Remote-Synced" :is_remote_synced true}:model/Card {base-card-id :id} {:name "Base Card"@@ -2392,14 +2337,14 @@:archived true:dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-id)})}](is (= #{{"Collection" remote-synced-id}}- (set (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))))+ (set (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))))"Should not return archived dependents"))))(deftest ^:parallel remote-synced-dependents-non-card-models-test(testing "for non-card models"- (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}+ (mt/with-temp [:model/Collection {_coll-id :id} {:is_remote_synced true}:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]- (is (= [] (collection/remote-synced-dependents coll-id (t2/instance :model/Dashboard {:id dash-id})))+ (is (= [] (collection/remote-synced-dependents (t2/instance :model/Dashboard {:id dash-id})))"Should return empty seq for dashboard with no deps"))))(deftest ^:parallel remote-synced-dependents-with-parameters-test@@ -2418,7 +2363,7 @@:values_source_config {:card_id base-card-id}}]}];; Create a card with parameters, then update it to have the correct JSON format;; The parameters should be stored as JSON with "card-id" (hyphenated)- (let [dependents (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))](is (= 1 (count dependents))"Should find one dependent using parameters")(is (= dep-card-id (get (first dependents) "Card"))@@ -2426,12 +2371,12 @@(deftest ^:parallel remote-synced-dependents-with-template-tags-test(testing "when card has dependents using template tags"- (mt/with-temp [:model/Collection {remote-synced-id :id} {:name "Remote-Synced" :is_remote_synced true}+ (mt/with-temp [:model/Collection {_remote-synced-id :id} {:name "Remote-Synced" :is_remote_synced true}:model/Card {base-card-id :id} {:name "Base Card":database_id (mt/id):dataset_query (mt/mbql-query venues)}:model/Card {dep-card-id :id} {:name "Dependent Card with Template Tags"- :collection_id remote-synced-id+ :collection_id _remote-synced-id:database_id (mt/id):dataset_query (mt/native-query {:query "SELECT * FROM {{card}}":template-tags {:card {:type "card"@@ -2439,7 +2384,7 @@:card-id base-card-id}}})}];; Create a card with template tags;; The dataset_query should contain "card-id" in the template tags- (let [dependents (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))](is (= 1 (count dependents))"Should find one dependent using template tags")(is (= dep-card-id (get (first dependents) "Card"))@@ -2471,7 +2416,7 @@:template-tags {:card {:type "card":display-name "Card":card-id base-card-id}}})}]- (let [dependents (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))](is (= 3 (count dependents))"Should find all three types of dependents")(is (= #{dep1-id dep2-id dep3-id} (set (mapcat vals dependents)))@@ -2496,7 +2441,7 @@:model/Dashboard {dashboard-id :id} {:collection_id remote-synced-id}:model/DashboardCard _ {:dashboard_id dashboard-id:card_id dep-card-id}]- (let [dependents (collection/remote-synced-dependents remote-synced-id source-coll)]+ (let [dependents (collection/remote-synced-dependents source-coll)](is (= 2 (count dependents))"Should find dependents of cards in the collection")(is (= #{{"Card" dep-card-id} {"Card" dep-card-2-id}} (set dependents))@@ -2505,7 +2450,7 @@(deftest ^:parallel remote-synced-dependents-with-collection-no-cards-test(testing "when a collection with no cards is passed to remote-synced-dependents"(mt/with-temp [:model/Collection {empty-coll-id :id} {:name "Empty Collection" :location "/"}]- (let [dependents (collection/remote-synced-dependents empty-coll-id (t2/instance :model/Collection {:id empty-coll-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Collection {:id empty-coll-id}))](is (= [] dependents)"Should return empty seq for collection with no cards")))))@@ -2531,7 +2476,7 @@:collection_id remote-synced-id:database_id (mt/id):dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-2-id)})}]- (let [dependents (collection/remote-synced-dependents remote-synced-id (t2/instance :model/Collection {:id parent-coll-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Collection {:id parent-coll-id}))](is (= 2 (count dependents))"Should find dependents of cards in parent and child collections")(is (= #{dep-card-1-id dep-card-2-id} (set (mapcat vals dependents)))@@ -2539,12 +2484,12 @@(deftest ^:parallel remote-synced-dependents-with-other-models-test(testing "when other model types are passed to remote-synced-dependents"- (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}+ (mt/with-temp [:model/Collection {_coll-id :id} {:is_remote_synced true}:model/Dashboard {dash-id :id} {:name "Test Dashboard"}:model/Pulse {pulse-id :id} {:name "Test Pulse"}]- (is (= [] (collection/remote-synced-dependents coll-id (t2/instance :model/Dashboard {:id dash-id})))+ (is (= [] (collection/remote-synced-dependents (t2/instance :model/Dashboard {:id dash-id})))"Should return empty seq for Dashboard models")- (is (= [] (collection/remote-synced-dependents coll-id (t2/instance :model/Pulse {:id pulse-id})))+ (is (= [] (collection/remote-synced-dependents (t2/instance :model/Pulse {:id pulse-id})))"Should return empty seq for Pulse models"))))(deftest ^:parallel check-remote-synced-dependents-throws-test@@ -2560,11 +2505,11 @@:dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-id)})}](is (thrown-with-msg? clojure.lang.ExceptionInfo#"Used by remote synced content."- (collection/check-remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id})))+ (collection/check-remote-synced-dependents (t2/instance :model/Card {:id base-card-id})))"Should throw exception when model has remote-synced dependents")(try- (collection/check-remote-synced-dependents remote-synced-id (t2/instance :model/Card {:id base-card-id}))+ (collection/check-remote-synced-dependents (t2/instance :model/Card {:id base-card-id}))(catch clojure.lang.ExceptionInfo e(let [data (ex-data e)](is (= 400 (:status-code data))@@ -2580,7 +2525,7 @@:database_id (mt/id):dataset_query (mt/mbql-query venues)}](let [card (t2/instance :model/Card {:id card-id})- result (collection/check-remote-synced-dependents nil card)]+ result (collection/check-remote-synced-dependents card)](is (= card result)"Should return the same model when no remote-synced dependents")))))@@ -2598,7 +2543,7 @@:dataset_query (mt/mbql-query nil {:source-table (str "card__" base-card-id)})}](is (thrown-with-msg? clojure.lang.ExceptionInfo#"Used by remote synced content."- (collection/check-remote-synced-dependents remote-synced-id (t2/instance :model/Collection {:id source-coll-id})))+ (collection/check-remote-synced-dependents (t2/instance :model/Collection {:id source-coll-id})))"Should throw exception when collection contains cards with remote-synced dependents"))))(deftest ^:parallel remote-synced-dependents-with-dashboard-test@@ -2621,7 +2566,7 @@:size_x 4 :size_y 4}](testing "Returns only dashboards in remote-synced collections"- (let [dependents (collection/remote-synced-dependents remote-synced-coll-id (t2/instance :model/Card {:id remote-synced-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id remote-synced-card-id}))](is (contains? (set dependents) {"Dashboard" remote-synced-dashboard-id "DashboardCard" rs-dashcard-id})"Should include dashboard in remote-synced collection")(is (not (contains? (set dependents) {"Dashboard" regular-dashboard-id "DashboardCard" non-rs-dashcard-id}))@@ -2642,7 +2587,7 @@:size_x 4 :size_y 4}](testing "Returns dashboards from nested remote-synced collections"- (let [dependents (collection/remote-synced-dependents remote-synced-coll-id (t2/instance :model/Card {:id remote-synced-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id remote-synced-card-id}))](is (= #{{"Collection" remote-synced-coll-id} {"Dashboard" nested-dashboard-id "DashboardCard" dashcard-id}}(set dependents))"Should include dashboard in nested remote-synced collection"))))))@@ -2661,7 +2606,7 @@:size_x 4 :size_y 4}](testing "Does not return archived dashboards"- (let [dependents (collection/remote-synced-dependents remote-synced-coll-id (t2/instance :model/Card {:id remote-synced-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id remote-synced-card-id}))](is (= {"Collection" remote-synced-coll-id} (first dependents))"Should not include archived dashboard even if in remote-synced collection"))))))@@ -2683,7 +2628,7 @@:position 0}](testing "Returns dashboards that reference cards through series"- (let [dependents (collection/remote-synced-dependents remote-synced-coll-id (t2/instance :model/Card {:id remote-synced-card-id}))]+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id remote-synced-card-id}))](is (= #{{"Collection" remote-synced-coll-id} {"Dashboard" remote-synced-dashboard-id "DashboardCard" dashcard-id "DashboardCardSeries" series-id}}(set dependents))"Should include dashboard that references card through series"))))))@@ -2704,7 +2649,7 @@:size_x 4 :size_y 4}](testing "Returns both card and dashboard dependencies"- (let [dependents (collection/remote-synced-dependents remote-synced-coll-id (t2/instance :model/Card {:id source-card-id}))+ (let [dependents (collection/remote-synced-dependents (t2/instance :model/Card {:id source-card-id}))dependent-models (mapcat keys dependents)](is (some #(= "Card" %) dependent-models)"Should include dependent cards")@@ -2836,8 +2781,11 @@(is (= (format "/%d/" remote-synced-parent2-id)(:location (t2/select-one :model/Collection :id child-remote-synced-id))))))))-(deftest move-collection!-from-remote-synced-to-remote-synced-disallows-move-test- (testing "move-collection! disallows moving a collection from one remote-synced collection to another remote-synced collection"+(deftest move-collection!-from-remote-synced-to-remote-synced-allows-move-with-dependents-in-source-test+ (testing "move-collection! allows moving a collection between remote-synced roots even when dependents exist in source root"+ ;; With unified remote-sync checking, all remote-synced collections are treated as a single pool,+ ;; so moves between different remote-synced roots no longer trigger dependency/dependent checking.+ ;; This test verifies that a dependent card in the source remote-synced root does NOT block the move.(mt/with-temp [:model/Collection {remote-synced-parent1-id :id} {:name "Remote-Synced Parent 1":location "/":is_remote_synced true}@@ -2853,8 +2801,10 @@:model/Card _ {:name "Dependent Card":collection_id remote-synced-parent1-id:dataset_query (mt/mbql-query nil {:source-table (str "card__" remote-synced-card-id)})}]- (testing "Errors on moves collection from one remote-synced collection to another"- (is (thrown? Exception (collection/move-collection! child-remote-synced-collection (format "/%d/" remote-synced-parent2-id))))))))+ (testing "Allows moving collection from one remote-synced collection to another"+ (collection/move-collection! child-remote-synced-collection (format "/%d/" remote-synced-parent2-id))+ (is (= (format "/%d/" remote-synced-parent2-id)+ (:location (t2/select-one :model/Collection :id child-remote-synced-id))))))))(deftest move-collection!-from-remote-synced-with-nested-dependents-prevents-move-test(testing "move-collection! prevents moving a collection from remote-synced collection when nested collections have dependents"@@ -2972,11 +2922,11 @@"Should return true when moving from regular to remote-synced collection"))(testing "when moving between different remote-synced root collections"- (is (true? (collection/moving-into-remote-synced? remote-synced-root-a remote-synced-root-b))+ (is (false? (collection/moving-into-remote-synced? remote-synced-root-a remote-synced-root-b))"Should return false when moving between different remote-synced root collections"))(testing "when moving from remote-synced child to different remote-synced root"- (is (true? (collection/moving-into-remote-synced? child-of-a remote-synced-root-b))+ (is (false? (collection/moving-into-remote-synced? child-of-a remote-synced-root-b))"Should return false when moving from remote-synced child to different remote-synced root"))(testing "when moving within same remote-synced hierarchy"@@ -3001,12 +2951,12 @@"Should return true when moving from remote-synced collection to regular collection"))(testing "when moving between different remote-synced root collections"- (is (true? (collection/moving-from-remote-synced? remote-synced-root-a remote-synced-root-b))- "Should return true when moving between different remote-synced root collections"))+ (is (false? (collection/moving-from-remote-synced? remote-synced-root-a remote-synced-root-b))+ "Should return false when moving between different remote-synced root collections"))(testing "when moving from remote-synced child to different remote-synced root"- (is (true? (collection/moving-from-remote-synced? child-of-a remote-synced-root-b))- "Should return true when moving from remote-synced child to different remote-synced root"))+ (is (false? (collection/moving-from-remote-synced? child-of-a remote-synced-root-b))+ "Should return false when moving from remote-synced child to different remote-synced root"))(testing "when moving from remote-synced collection to root"(is (true? (collection/moving-from-remote-synced? remote-synced-root-a nil))diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex d7d69f3e000..dfc0490b3ec 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -74,7 +74,7 @@:name "Our analytics":authority_level nil:is_personal false- :is_remote_synced nil+ :is_remote_synced false:id "root":can_restore false:can_delete false}@@ -363,6 +363,7 @@(testing "Make sure we get the expected collections when collection-id is nil"(let [collections (#'api.collection/select-collections {:archived false:exclude-other-user-collections false+ :namespaces #{nil}:shallow true:permissions-set #{"/"}})](is (= #{{:name "A"}@@ -376,6 +377,7 @@(testing "Make sure we get the expected collections when collection-id is an integer"(let [collections (#'api.collection/select-collections {:archived false:exclude-other-user-collections false+ :namespaces #{nil}:shallow true:collection-id (:id a):permissions-set #{"/"}})]@@ -500,6 +502,39 @@(is (= [](collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree?namespace=stamps")))))))))))+(deftest collection-tree-namespaces-parameter-test+ (testing "GET /api/collection/tree"+ (testing "namespaces parameter allows specifying multiple namespaces"+ (mt/with-temp [:model/Collection {normal-id :id} {:name "Normal Collection"}+ :model/Collection {coins-id :id} {:name "Coin Collection", :namespace "currency"}+ :model/Collection {stamps-id :id} {:name "Stamp Collection", :namespace "stamps"}]+ (let [ids [normal-id coins-id stamps-id]]+ (perms/grant-collection-read-permissions! (perms/all-users-group) coins-id)+ (perms/grant-collection-read-permissions! (perms/all-users-group) stamps-id)++ (testing "single namespace via namespaces param"+ (is (= [{:name "Coin Collection", :children []}]+ (collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree?namespaces=currency")))))++ (testing "multiple namespaces via repeated namespaces param"+ (is (= [{:name "Coin Collection", :children []}+ {:name "Stamp Collection", :children []}]+ (collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree" :namespaces ["currency" "stamps"])))))++ (testing "empty string in namespaces matches nil namespace (default collections)"+ (is (= [{:name "Normal Collection", :children []}]+ (collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree?namespaces=")))))++ (testing "combining nil namespace with other namespaces"+ (is (= [{:name "Coin Collection", :children []}+ {:name "Normal Collection", :children []}]+ (collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree" :namespaces ["currency" ""]))+ (collection-tree-view ids (mt/user-http-request :rasta :get 200 "collection/tree" :namespaces ["currency" nil])))))++ (testing "namespace and namespaces params are mutually exclusive"+ (is (= "Invalid Request."+ (mt/user-http-request :rasta :get 400 "collection/tree?namespace=currency&namespaces=stamps")))))))))+(deftest collection-tree-elide-collections-with-no-permissions-test(testing "GET /api/collection/tree"(testing "Tree should elide Collections for which we have no permissions (#14280)"@@ -680,6 +715,7 @@:can_write true:can_delete false:can_restore false+ :collection_namespace nil:id card-id:archived false:location nil@@ -1350,6 +1386,7 @@:id "root":authority_level nil:can_write true+ :is_remote_synced false:is_personal false}]:effective_location "/":parent_id nil@@ -1542,6 +1579,7 @@:name "Our analytics",:id false,:can_write true+ :is_remote_synced false:is_personal false}{:name "Rasta Toucan's Personal Collection",:id true,@@ -1566,6 +1604,7 @@:authority_level nil:parent_id nil:is_personal false+ :is_remote_synced false:can_delete false}(with-some-children-of-collection! nil(mt/user-http-request :crowberto :get 200 "collection/root")))))))@@ -2360,6 +2399,33 @@(is (contains? collection-names "Normal Collection Test"))(is (contains? collection-names "Remote Synced Collection Test")))))))))+(deftest fetch-root-items-shared-tenant-collection-namespace-test+ (testing "GET /api/collection/root/items"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "collections with namespace 'shared-tenant-collection' at root are returned when namespace parameter is set"+ (mt/with-temp [:model/Collection {normal-id :id} {:name "Normal Root Collection"+ :location "/"}+ :model/Collection {tenant-id :id} {:name "Shared Tenant Collection"+ :location "/"+ :namespace "shared-tenant-collection"}]+ (letfn [(collection-names [items]+ (->> (:data items)+ (filter #(and (= (:model %) "collection")+ (#{normal-id tenant-id} (:id %))))+ (map :name)))]+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "should only show collections in the default namespace by default"+ (is (= ["Normal Root Collection"]+ (collection-names (mt/user-http-request :crowberto :get 200 "collection/root/items")))))+ (testing "should show shared-tenant-collection namespace when requested"+ (is (= ["Shared Tenant Collection"]+ (collection-names (mt/user-http-request :crowberto :get 200 "collection/root/items?namespace=shared-tenant-collection"))))))+ (mt/with-temporary-setting-values [use-tenants false]+ (testing "should not show shared tenant collection when setting is off"+ (is (empty?+ (collection-names (mt/user-http-request :crowberto :get 200 "collection/root/items?namespace=shared-tenant-collection")))))))))))))+;;; ----------------------------------- Effective Children, Ancestors, & Location ------------------------------------(defn- api-get-root-collection-children@@ -2538,7 +2604,7 @@:namespace "snippets"}(mt/user-http-request :crowberto :post 200 "collection"{:name collection-name- :descrption "My SQL Snippets"+ :description "My SQL Snippets":namespace "snippets"})))(finally(t2/delete! :model/Collection :name collection-name)))))))@@ -2576,19 +2642,18 @@(deftest create-child-collection-explicit-namespace-fails-test(testing "POST /api/collection"- (testing "Child collection should use explicit namespace when provided (even if nil)"+ (testing "Child collection should use explicit namespace when provided (unless nil)"(mt/with-model-cleanup [:model/Collection](let [;; Create a parent collection with snippets namespaceparent-collection (mt/user-http-request :crowberto :post 200 "collection"{:name "Parent Snippets Collection":namespace "snippets"})parent-id (:id parent-collection)]- ;; Create child collection with explicit nil namespace should use nil (not inherit)(is (= {:errors {:location "Collection must be in the same namespace as its parent"}}(mt/user-http-request :crowberto :post 400 "collection"{:name "Child Collection":parent_id parent-id- :namespace nil}))+ :namespace "not-snippets"}))"Child namespace validation is still enforced"))))))(deftest create-root-collection-namespace-test@@ -2988,7 +3053,7 @@:model/Card card {}](testing "Collections can't be moved to the trash"(mt/user-http-request :crowberto :put 403 (str "collection/" (u/the-id collection)) {:parent_id (collection/trash-collection-id)})- (is (not (t2/exists? :model/Collection :location (collection/trash-path)))))+ (is (not (t2/exists? :model/Collection :id (u/the-id collection) :location (collection/trash-path)))))(testing "Dashboards can't be moved to the trash"(mt/user-http-request :crowberto :put 403 (str "dashboard/" (u/the-id dashboard)) {:collection_id (collection/trash-collection-id)})(is (not (t2/exists? :model/Dashboard :collection_id (collection/trash-collection-id)))))diff --git a/test/metabase/dashboards/models/dashboard_test.clj b/test/metabase/dashboards/models/dashboard_test.cljindex 565625b2654..49d76f81a03 100644--- a/test/metabase/dashboards/models/dashboard_test.clj+++ b/test/metabase/dashboards/models/dashboard_test.clj@@ -211,7 +211,7 @@(try(is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Dashboard can only go in Collections in the \"default\" or :analytics namespace."+ #"A Dashboard can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/insert! :model/Dashboard (assoc (mt/with-temp-defaults :model/Dashboard) :collection_id collection-id, :name dashboard-name))))(finally(t2/delete! :model/Dashboard :name dashboard-name)))))@@ -220,7 +220,7 @@(mt/with-temp [:model/Dashboard {card-id :id}](is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Dashboard can only go in Collections in the \"default\" or :analytics namespace."+ #"A Dashboard can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/update! :model/Dashboard card-id {:collection_id collection-id})))))))(deftest ^:parallel validate-parameters-testdiff --git a/test/metabase/permissions/models/permissions_group_membership_test.clj b/test/metabase/permissions/models/permissions_group_membership_test.cljindex 596d632be56..79e409627ab 100644--- a/test/metabase/permissions/models/permissions_group_membership_test.clj+++ b/test/metabase/permissions/models/permissions_group_membership_test.clj@@ -35,28 +35,6 @@(is (thrown? Exception(t2/delete! :model/PermissionsGroupMembership :user_id id, :group_id (u/the-id (perms-group/admin)))))))))-(deftest tenant-users-and-groups- ;; This will need to get fixed once we have actual tenants - right now the `tenant_id` doesn't actually connect to- ;; anything.- (mt/with-temp [:model/User {tenant-user :id} {:tenant_id 1}- :model/User {normal-user :id} {}- :model/PermissionsGroup {tenant-group :id} {:is_tenant_group true}- :model/PermissionsGroup {normal-group :id} {:is_tenant_group false}]- (testing "A tenant user"- (testing "cannot be added to a normal group"- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Cannot add non-tenant user to tenant-group or vice versa"- (perms/add-user-to-group! tenant-user normal-group))))- (testing "can be added to tenant groups"- (perms/add-user-to-group! tenant-user tenant-group)))- (testing "A normal user"- (testing "cannot be added to a tenant group"- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"Cannot add non-tenant user to tenant-group or vice versa"- (perms/add-user-to-group! normal-user tenant-group))))- (testing "can be added to a normal group"- (perms/add-user-to-group! normal-user normal-group)))))-(deftest permissions-group-membership-audit-add-test(testing "PermissionsGroupMembership audit events"(mt/with-premium-features #{:audit-app}diff --git a/test/metabase/permissions/models/permissions_group_test.clj b/test/metabase/permissions/models/permissions_group_test.cljindex f329e34d14e..7000811fbf5 100644--- a/test/metabase/permissions/models/permissions_group_test.clj+++ b/test/metabase/permissions/models/permissions_group_test.clj@@ -120,7 +120,7 @@(deftest data-graph-for-group-check-all-groups-test(mt/with-temp [:model/PermissionsGroup {} {}:model/Database {} {}]- (doseq [group-id (t2/select-fn-set :id :model/PermissionsGroup)]+ (doseq [group-id (t2/select-fn-set :id :model/PermissionsGroup :is_tenant_group false)](testing (str "testing data-graph-for-group with group-id: [" group-id "].")(let [graph (data-perms.graph/api-graph {:group-id group-id})](is (malli= [:map [:revision :int] [:groups :map]] graph))diff --git a/test/metabase/permissions/models/permissions_test.clj b/test/metabase/permissions/models/permissions_test.cljindex 70a575165ba..6418c4fc735 100644--- a/test/metabase/permissions/models/permissions_test.clj+++ b/test/metabase/permissions/models/permissions_test.clj@@ -227,18 +227,24 @@;; to think about how this works since the collection ID will be `NULL`."/collection/root/" {})))-(deftest cannot-grant-application-permissions-to-tenant-groups+(deftest cannot-grant-non-subscription-application-permissions-to-tenant-groups(mt/with-temp [:model/PermissionsGroup {tenant-group-id :id} {:is_tenant_group true}]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot grant application permission to a tenant group\."- (perms/grant-application-permissions! tenant-group-id :subscription)))))+ (testing "Setting and monitoring permissions should still be blocked"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot grant application permission to a tenant group\."+ (perms/grant-application-permissions! tenant-group-id :setting)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot grant application permission to a tenant group\."+ (perms/grant-application-permissions! tenant-group-id :monitoring))))+ (testing "Subscription permissions should be allowed"+ (is (nil? (perms/grant-application-permissions! tenant-group-id :subscription))))))-(deftest cannot-grant-write-permissions-to-tenant-group+(deftest cannot-grant-collection-permissions-to-tenant-group+ ;; right now, with no tenant collections, you can't grant any permissions on any collection to a tenant group(mt/with-temp [:model/PermissionsGroup {tenant-group-id :id} {:is_tenant_group true}- :model/Collection {coll-id :id} {:location "/"}]- ;; just call grant/revoke to show that nothing here throws- (perms/grant-collection-read-permissions! tenant-group-id coll-id)+ :model/Collection {coll-id :id} {:location "/" :type "tenant-collection"}](perms/revoke-collection-permissions! tenant-group-id coll-id)- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant Groups cannot have write access to any collections\."+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant groups cannot receive access to non-tenant collections\."+ (perms/grant-collection-read-permissions! tenant-group-id coll-id)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant groups cannot have write access to any collections\."(perms/grant-collection-readwrite-permissions! tenant-group-id coll-id)))))(deftest cannot-grant-read-or-write-permissions-on-analytics-to-tenant-group@@ -246,7 +252,7 @@:model/PermissionsGroup {tenant-group-id :id} {:is_tenant_group true}:model/PermissionsGroup {normal-group-id :id} {:is_tenant_group false}](with-redefs [audit.impl/is-collection-id-audit? (constantly true)]- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant Groups cannot receive any access to the audit collection\."+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tenant groups cannot receive access to non-tenant collections\."(perms/grant-collection-read-permissions! tenant-group-id coll-id)));; does not throw - it's not a tenant group(perms/grant-collection-read-permissions! normal-group-id coll-id))))diff --git a/test/metabase/permissions_rest/api_test.clj b/test/metabase/permissions_rest/api_test.cljindex b7d2046fd33..f6ec395ed63 100644--- a/test/metabase/permissions_rest/api_test.clj+++ b/test/metabase/permissions_rest/api_test.clj@@ -25,9 +25,12 @@;; GET /permissions/group;; Should *not* include inactive users in the counts.-(defn- fetch-groups []- (set (mt/user-http-request- :crowberto :get 200 "permissions/group")))+(defn- fetch-groups+ ([]+ (fetch-groups {}))+ ([& query-params]+ (set (apply mt/user-http-request+ :crowberto :get 200 "permissions/group" query-params))))(deftest fetch-groups-test(testing "GET /api/permissions/group"@@ -72,6 +75,60 @@(is (partial= [{:id (:id (perms-group/all-users)), :name "All Users"}](mt/user-http-request :crowberto :get 200 "permissions/group" :limit "1" :offset "1"))))))+(deftest fetch-groups-tenancy-filter-test+ (testing "GET /api/permissions/group with tenancy filter"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/PermissionsGroup regular-group {:name "Regular Group" :is_tenant_group false}+ :model/PermissionsGroup tenant-group {:name "Tenant Group" :is_tenant_group true}]+ (let [all-groups (fetch-groups)+ internal-groups (fetch-groups :tenancy "internal")+ external-groups (fetch-groups :tenancy "external")+ regular-id (:id regular-group)+ tenant-id (:id tenant-group)]++ (testing "default behavior (no tenancy param) returns all groups"+ (is (some #(= regular-id (:id %)) all-groups))+ (is (some #(= tenant-id (:id %)) all-groups)))++ (testing "tenancy=internal returns only non-tenant groups"+ (is (some #(= regular-id (:id %)) internal-groups))+ (is (not (some #(= tenant-id (:id %)) internal-groups))))++ (testing "tenancy=external returns only tenant groups"+ (is (not (some #(= regular-id (:id %)) external-groups)))+ (is (some #(= tenant-id (:id %)) external-groups)))++ (testing "magic groups are handled correctly"+ (let [all-internal-users-id (:id (perms-group/all-users))+ find-group-by-type (fn [groups magic-type]+ (some #(when (= magic-type (:magic_group_type %)) %) groups))]+ (testing "all-internal-users appears in internal filter"+ (is (some #(= all-internal-users-id (:id %)) internal-groups)))+ (testing "all-external-users appears in external filter when available"+ (when-let [external-users-group (find-group-by-type all-groups "all-external-users")]+ (is (some #(= (:id external-users-group) (:id %)) external-groups))))))))))++ (testing "when tenants feature is disabled"+ (mt/with-temporary-setting-values [use-tenants false]+ (mt/with-temp [:model/PermissionsGroup regular-group {:name "Regular Group" :is_tenant_group false}]+ (let [all-groups (fetch-groups)+ internal-groups (fetch-groups :tenancy "internal")+ external-groups (fetch-groups :tenancy "external")+ regular-id (:id regular-group)]++ (testing "default behavior excludes tenant groups when tenants disabled"+ (is (some #(= regular-id (:id %)) all-groups)))++ (testing "tenancy=internal still works when tenants disabled"+ (is (some #(= regular-id (:id %)) internal-groups)))++ (testing "tenancy=external returns empty when tenants disabled"+ (is (empty? external-groups)))))))++ (testing "invalid tenancy value returns 400"+ (:status (mt/user-http-request :crowberto :get 400 "permissions/group" :tenancy "invalid")))))+(deftest fetch-group-test(testing "GET /permissions/group/:id"(let [{:keys [members]} (mt/user-http-request@@ -124,7 +181,35 @@(testing "group name is required"(is (= {:errors {:name "value must be a non-blank string."},:specific-errors {:name ["should be a string, received: nil" "non-blank string, received: nil"]}}- (mt/user-http-request :crowberto :post 400 "permissions/group" {:name nil}))))))+ (mt/user-http-request :crowberto :post 400 "permissions/group" {:name nil}))))++ (testing "creates regular group by default"+ (mt/with-model-cleanup [:model/PermissionsGroup]+ (mt/user-http-request :crowberto :post 200 "permissions/group" {:name "Regular Group"})+ (let [group (t2/select-one :model/PermissionsGroup :name "Regular Group")]+ (is (some? group))+ (is (false? (:is_tenant_group group))))))++ (testing "creates regular group when is_tenant_group is explicitly false"+ (mt/with-model-cleanup [:model/PermissionsGroup]+ (mt/user-http-request :crowberto :post 200 "permissions/group" {:name "Explicit Regular Group" :is_tenant_group false})+ (let [group (t2/select-one :model/PermissionsGroup :name "Explicit Regular Group")]+ (is (some? group))+ (is (false? (:is_tenant_group group))))))++ (testing "creates regular group when is_tenant_group is nil"+ (mt/with-model-cleanup [:model/PermissionsGroup]+ (mt/user-http-request :crowberto :post 200 "permissions/group" {:name "Nil Tenant Group" :is_tenant_group nil})+ (let [group (t2/select-one :model/PermissionsGroup :name "Nil Tenant Group")]+ (is (some? group))+ (is (false? (:is_tenant_group group))))))))++(deftest create-group-test-enterprise-features+ (testing "POST /permissions/group enterprise feature enforcement"+ (testing "throws ee-feature-error when trying to create tenant group without tenants feature"+ (mt/with-premium-features #{}+ (is (=? {:message "Tenants is a paid feature not currently available to your instance. Please upgrade to use it. Learn more at metabase.com/upgrade/"}+ (mt/user-http-request :crowberto :post 402 "permissions/group" {:name "Tenant Group" :is_tenant_group true})))))))(deftest delete-group-test(testing "DELETE /permissions/group/:id"@@ -486,3 +571,27 @@(testing "Delete membership successfully"(mt/user-http-request :crowberto :delete 204 (format "permissions/membership/%d" id))))))++(deftest enabling-tenants-changes-groups+ (let [get-magic-group (fn [group-type]+ (->>+ (mt/user-http-request :crowberto :get 200 "/permissions/group")+ (filter #(= group-type (:magic_group_type %)))+ first))]+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants false]+ (testing "When disabled, 'All Users' is 'All Users'"+ (is (=? {:magic_group_type "all-internal-users"+ :name "All Users"}+ (get-magic-group "all-internal-users"))))+ (testing "When disabled, 'All tenant users' is not visible"+ (is (nil? (get-magic-group "all-external-users")))))+ (mt/with-temporary-setting-values [use-tenants true]+ (testing "When enabled, 'All Users' is 'All Internal Users'"+ (is (=? {:magic_group_type "all-internal-users"+ :name "All Internal Users"}+ (get-magic-group "all-internal-users"))))+ (testing "When enabled, 'All tenant users' is visible"+ (is (=? {:magic_group_type "all-external-users"+ :name "All tenant users"}+ (get-magic-group "all-external-users"))))))))diff --git a/test/metabase/pulse/models/pulse_test.clj b/test/metabase/pulse/models/pulse_test.cljindex de897175d01..ac4662a9985 100644--- a/test/metabase/pulse/models/pulse_test.clj+++ b/test/metabase/pulse/models/pulse_test.clj@@ -437,7 +437,7 @@(try(is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Pulse can only go in Collections in the \"default\" or :analytics namespace."+ #"A Pulse can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/insert! :model/Pulse (assoc (mt/with-temp-defaults :model/Pulse) :collection_id collection-id, :name pulse-name))))(finally(t2/delete! :model/Pulse :name pulse-name)))))@@ -446,7 +446,7 @@(mt/with-temp [:model/Pulse {card-id :id}](is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Pulse can only go in Collections in the \"default\" or :analytics namespace."+ #"A Pulse can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/update! :model/Pulse card-id {:collection_id collection-id})))))));;; +----------------------------------------------------------------------------------------------------------------+diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 7db6c156127..bc8d040b233 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -195,7 +195,7 @@(try(is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Card can only go in Collections in the \"default\" or :analytics namespace."+ #"A Card can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/insert! :model/Card (assoc (mt/with-temp-defaults :model/Card) :collection_id collection-id, :name card-name))))(finally(t2/delete! :model/Card :name card-name)))))))@@ -206,7 +206,7 @@(mt/with-temp [:model/Card {card-id :id}](is (thrown-with-msg?clojure.lang.ExceptionInfo- #"A Card can only go in Collections in the \"default\" or :analytics namespace."+ #"A Card can only go in Collections in the \"default\"(?: or :[a-z\-]+)+ namespace."(t2/update! :model/Card card-id {:collection_id collection-id})))))))(deftest ^:parallel normalize-result-metadata-testdiff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.cljindex f707b620fba..2807d09f41d 100644--- a/test/metabase/search/api_test.clj+++ b/test/metabase/search/api_test.clj@@ -1007,6 +1007,36 @@(filter #(and (= (:model %) "collection")(#{"Normal Collection" "Coin Collection"} (:name %))))))))))+(deftest shared-tenant-collection-search-test+ (testing "Search returns collections with namespace: shared-tenant-collection"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {shared-name :name} {:name "Shared Tenant Test Collection"+ :namespace collection/shared-tenant-ns}+ :model/Collection {normal-name :name} {:name "Normal Test Collection"}]+ (let [results (->> (search-request-data :crowberto :q "Test Collection")+ (filter #(= (:model %) "collection"))+ (map :name)+ set)]+ (testing "shared-tenant-collection namespace collections are returned in search"+ (is (contains? results shared-name))+ (is (contains? results normal-name)))))))))++(deftest shared-tenant-collection-dataset-search-test+ (testing "Search returns datasets (models) from collections in the shared-tenant-collection namespace"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {shared-coll-id :id} {:name "Shared Tenant Collection"+ :namespace collection/shared-tenant-ns}+ :model/Card {model-name :name} {:name "Shared Tenant Model"+ :type :model+ :collection_id shared-coll-id}]+ (let [results (->> (search-request-data :crowberto :q "Shared Tenant Model")+ (filter #(= (:model %) "dataset"))+ first)]+ (testing "datasets in shared-tenant-collection namespace are returned"+ (is (=? {:name model-name} results)))))))))+(deftest no-dashboard-subscription-pulses-test(testing "Pulses used for Dashboard subscriptions should not be returned by search results (#14190)"(letfn [(search-for-pulses [{pulse-id :id}]@@ -1845,7 +1875,7 @@(is (= 1 (count (filter #{:metabase-search/response-ok} @calls))))(is (= 1 (count (filter #{:metabase-search/response-error} @calls))))))))))-(deftest ^:synchronized multiple-limits+(deftest ^:synchronized multiple-limits-test(when (search/supports-index?);; This test is failing with "no index" for some reason, forcing the reindex(mt/user-real-request :crowberto :post 200 "search/force-reindex"))diff --git a/test/metabase/tenants/core_test.clj b/test/metabase/tenants/core_test.cljnew file mode 100644index 00000000000..97d81682c00--- /dev/null+++ b/test/metabase/tenants/core_test.clj@@ -0,0 +1,55 @@+(ns metabase.tenants.core-test+ (:require+ [clojure.test :refer :all]+ [metabase.tenants.core :as tenants]))++(deftest combine-user-attributes-only-test+ (testing "combine function with user attributes only"+ (is (= {"key1" {:source :user :frozen false :value "value1"}+ "key2" {:source :user :frozen false :value "value2"}}+ (tenants/combine {"key1" "value1" "key2" "value2"})))))++(deftest combine-user-and-tenant-attributes-test+ (testing "combine function with user and tenant attributes"+ (is (= {"user-key" {:source :user :frozen false :value "user-value"}+ "tenant-key" {:source :tenant :frozen false :value "tenant-value"}}+ (tenants/combine {"user-key" "user-value"}+ {"tenant-key" "tenant-value"}+ nil)))))++(deftest combine-user-overrides-tenant-attributes-test+ (testing "combine function where user overrides tenant attributes"+ (is (= {"shared-key" {:source :user+ :frozen false+ :value "user-value"+ :original {:source :tenant :frozen false :value "tenant-value"}}}+ (tenants/combine {"shared-key" "user-value"}+ {"shared-key" "tenant-value"}+ nil)))))++(deftest combine-system-attributes-override-everything-test+ (testing "combine function where system attributes in conflict cause it to throw"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Cannot clobber"+ (tenants/combine {"@system-key" "user-value"}+ {"@system-key" "tenant-value"}+ {"@system-key" "system-value"})))))++(deftest combine-empty-inputs-nil-test+ (testing "combine function with nil input"+ (is (= {} (tenants/combine nil)))))++(deftest combine-empty-inputs-all-nil-test+ (testing "combine function with all nil inputs"+ (is (= {} (tenants/combine nil nil nil)))))++(deftest combine-empty-inputs-empty-maps-test+ (testing "combine function with empty maps"+ (is (= {} (tenants/combine {} {} {})))))++(deftest combine-nil-user-with-tenant-and-system-test+ (testing "combine function with nil user but tenant and system attributes"+ (is (= {"tenant-key" {:source :tenant :frozen false :value "tenant-value"}+ "@system-key" {:source :system :frozen true :value "system-value"}}+ (tenants/combine nil+ {"tenant-key" "tenant-value"}+ {"@system-key" "system-value"})))))diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.cljindex 54b6e2acccf..6ffb00cb86e 100644--- a/test/metabase/test/util.clj+++ b/test/metabase/test/util.clj@@ -354,6 +354,11 @@(default-timestamped{:name (str "test-tag-" (u/generate-nano-id))}))+ :model/Tenant+ (fn [_]+ {:slug (u/lower-case-en (u.random/random-name))+ :name (u.random/random-name)})+:model/User(fn [_] {:first_name (u.random/random-name):last_name (u.random/random-name)@@ -1113,7 +1118,9 @@(finally(when (and (:metabase.collections.models.collection.root/is-root? collection)(not (:namespace collection)))- (doseq [group-id (t2/select-pks-set :model/PermissionsGroup :id [:not= (u/the-id (perms/admin-group))])]+ (doseq [group-id (t2/select-pks-set :model/PermissionsGroup+ :id [:not= (u/the-id (perms/admin-group))]+ :is_tenant_group false)](when-not (t2/exists? :model/Permissions :group_id group-id, :object "/collection/root/")(perms/grant-collection-readwrite-permissions! group-id collection/root-collection)))))))diff --git a/test/metabase/users/models/user_test.clj b/test/metabase/users/models/user_test.cljindex cd4b4fc3f42..96df80cd412 100644--- a/test/metabase/users/models/user_test.clj+++ b/test/metabase/users/models/user_test.clj@@ -12,6 +12,7 @@[metabase.request.core :as request][metabase.settings.core :as setting][metabase.sso.ldap-test-util :as ldap.test]+ [metabase.tenants.core :as tenants][metabase.test :as mt][metabase.test.data.users :as test.users][metabase.test.fixtures :as fixtures]@@ -484,47 +485,130 @@(let [deactivated-at (t2/select-one-fn :deactivated_at :model/User user-id)](is (nil? deactivated-at))))))-(deftest add-attributes-test- (testing "add-attributes function"- (testing "should add :attributes key with merged login attributes"+(deftest add-attributes-merges-login-and-jwt-attributes-test+ (testing "add-attributes should add :attributes key with merged login attributes"+ (let [user {:login_attributes {"user_attr" "user_value"}+ :jwt_attributes {"jwt_attr" "jwt_value"}+ :email "[email protected]"}+ result (user/add-attributes user)]+ (is (= {"jwt_attr" "jwt_value"+ "user_attr" "user_value"}+ (:attributes result)))+ (is (= user (dissoc result :attributes))))))++(deftest add-attributes-handles-nil-login-attributes-test+ (testing "add-attributes should handle nil login_attributes"+ (let [user {:email "[email protected]"+ :jwt_attributes {"jwt_attr" "jwt_value"}}+ result (user/add-attributes user)]+ (is (= {"jwt_attr" "jwt_value"}+ (:attributes result))))))++(deftest add-attributes-handles-empty-login-attributes-test+ (testing "add-attributes should handle empty login_attributes"+ (let [user {:login_attributes {}+ :jwt_attributes {"jwt_attr" "jwt_value"}+ :email "[email protected]"}+ result (user/add-attributes user)]+ (is (= {"jwt_attr" "jwt_value"}+ (:attributes result))))))++(deftest add-attributes-user-overrides-jwt-test+ (testing "add-attributes: user attributes should override jwt attributes with same keys"+ (let [user {:login_attributes {"shared_key" "user_value"+ "user_only" "user_val"}+ :jwt_attributes {"shared_key" "jwt_value"+ "jwt_only" "jwt_val"}+ :email "[email protected]"}+ result (user/add-attributes user)]+ (is (= {"shared_key" "user_value"+ "jwt_only" "jwt_val"+ "user_only" "user_val"}+ (:attributes result))))))++(deftest add-attributes-preserves-user-fields-test+ (testing "add-attributes should preserve all other user fields"+ (let [user {:id 123+ :email "[email protected]"+ :first_name "John"+ :last_name "Doe"+ :jwt_attributes {"jwt_attr" "jwt_value"}+ :login_attributes {"user_attr" "user_value"}}+ result (user/add-attributes user)]+ (is (= 123 (:id result)))+ (is (= "[email protected]" (:email result)))+ (is (= "John" (:first_name result)))+ (is (= "Doe" (:last_name result)))+ (is (= {"user_attr" "user_value"} (:login_attributes result)))+ (is (= {"jwt_attr" "jwt_value"+ "user_attr" "user_value"}+ (:attributes result))))))++(deftest add-attributes-merges-tenant-attributes-test+ (testing "add-attributes should merge tenant attributes"+ (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {"user_attr" "user_value"}- :jwt_attributes {"jwt_attr" "jwt_value"}:email "[email protected]"}result (user/add-attributes user)]- (is (= {"jwt_attr" "jwt_value"+ (is (= {"tenant_attr" "tenant_value""user_attr" "user_value"}(:attributes result)))- (is (= user (dissoc result :attributes)))))- (testing "should handle nil login_attributes"- (let [user {:email "[email protected]"- :jwt_attributes {"jwt_attr" "jwt_value"}}+ (is (= user (dissoc result :attributes)))))))++(deftest add-attributes-tenant-handles-nil-login-attributes-test+ (testing "add-attributes with tenant attributes should handle nil login_attributes"+ (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (let [user {:email "[email protected]"}result (user/add-attributes user)]- (is (= {"jwt_attr" "jwt_value"}- (:attributes result)))))- (testing "should handle empty login_attributes"+ (is (= {"tenant_attr" "tenant_value"}+ (:attributes result)))))))++(deftest add-attributes-tenant-handles-empty-login-attributes-test+ (testing "add-attributes with tenant attributes should handle empty login_attributes"+ (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {}- :jwt_attributes {"jwt_attr" "jwt_value"}:email "[email protected]"}result (user/add-attributes user)]- (is (= {"jwt_attr" "jwt_value"}- (:attributes result)))))- (testing "user attributes should override jwt attributes with same keys"+ (is (= {"tenant_attr" "tenant_value"}+ (:attributes result)))))))++(deftest add-attributes-handles-nil-tenant-attributes-test+ (testing "add-attributes should handle nil tenant attributes"+ (with-redefs [tenants/login-attributes (constantly nil)]+ (let [user {:login_attributes {"user_attr" "user_value"}+ :email "[email protected]"}+ result (user/add-attributes user)]+ (is (= {"user_attr" "user_value"}+ (:attributes result)))))))++(deftest add-attributes-handles-both-nil-tenant-and-user-attributes-test+ (testing "add-attributes should handle both nil tenant and user attributes"+ (with-redefs [tenants/login-attributes (constantly nil)]+ (let [user {:email "[email protected]"}+ result (user/add-attributes user)]+ (is (= {}+ (:attributes result)))))))++(deftest add-attributes-user-overrides-tenant-test+ (testing "add-attributes: user attributes should override tenant attributes with same keys"+ (with-redefs [tenants/login-attributes (constantly {"shared_key" "tenant_value"+ "tenant_only" "tenant_val"})](let [user {:login_attributes {"shared_key" "user_value""user_only" "user_val"}- :jwt_attributes {"shared_key" "jwt_value"- "jwt_only" "jwt_val"}:email "[email protected]"}result (user/add-attributes user)](is (= {"shared_key" "user_value"- "jwt_only" "jwt_val"+ "tenant_only" "tenant_val""user_only" "user_val"}- (:attributes result)))))- (testing "should preserve all other user fields"+ (:attributes result)))))))++(deftest add-attributes-tenant-preserves-user-fields-test+ (testing "add-attributes with tenant attributes should preserve all other user fields"+ (with-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:id 123:email "[email protected]":first_name "John":last_name "Doe"- :jwt_attributes {"jwt_attr" "jwt_value"}:login_attributes {"user_attr" "user_value"}}result (user/add-attributes user)](is (= 123 (:id result)))@@ -532,6 +616,6 @@(is (= "John" (:first_name result)))(is (= "Doe" (:last_name result)))(is (= {"user_attr" "user_value"} (:login_attributes result)))- (is (= {"jwt_attr" "jwt_value"+ (is (= {"tenant_attr" "tenant_value""user_attr" "user_value"}(:attributes result)))))))diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.cljindex f7d021ad3fb..a8a3ef666e0 100644--- a/test/metabase/users_rest/api_test.clj+++ b/test/metabase/users_rest/api_test.clj@@ -69,7 +69,7 @@(is (= (set(concatuser/admin-or-self-visible-columns- [:common_name :group_ids :personal_collection_id]))+ [:common_name :group_ids :personal_collection_id :tenant_collection_id]))(->> result first keys set)));; just make sure all users are there by checking the emails(is (= #{"[email protected]"@@ -888,6 +888,23 @@(is (= {:is-superuser? false, :pgm-exists? false}(superuser-and-admin-pgm-info email)))))))+(deftest create-user-must-assign-to-all-users-group+ (testing "POST /api/user"+ (testing "Creating a tenant user automatically assigns them to All tenant users group even when other groups are specified"+ (mt/with-temp [:model/PermissionsGroup group-1 {:name "Custom Group 1"}+ :model/PermissionsGroup group-2 {:name "Custom Group 2"}]+ (let [user-name (mt/random-name)+ email (mt/random-email)]+ (mt/with-model-cleanup [:model/User]+ (mt/with-fake-inbox+ (let [resp (mt/user-http-request :crowberto :post 400 "user"+ {:first_name user-name+ :last_name user-name+ :email email+ :user_group_memberships (group-or-ids->user-group-memberships+ [group-1 group-2])})]+ (is (= "You cannot add or remove users to/from the 'All Users' group." resp))))))))))+(deftest create-user-mixed-case-email(testing "POST /api/user/:id"(testing "can create a new User with a mixed case email and the email is normalized to lower case"@@ -994,6 +1011,90 @@(dissoc :user_group_memberships)mt/boolean-ids-and-timestamps)))))))+(deftest update-login-attributes-with-different-value-types-test+ (testing "PUT /api/user/:id"+ (testing "Non-string attributes are converted to strings"+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test"+ :last_name "User"+ :email "[email protected]"}]+ (let [response (mt/user-http-request :crowberto :put 200 (str "user/" user-id)+ {:login_attributes {:string-attr "hello"+ :number-attr 42+ :float-attr 3.14+ :bool-true true+ :bool-false false}})]+ (is (= {:string-attr "hello"+ :number-attr "42"+ :float-attr "3.14"+ :bool-true "true"+ :bool-false "false"}+ (:login_attributes response)))+ (testing "values are persisted correctly in the database"+ (is (= {"string-attr" "hello"+ "number-attr" "42"+ "float-attr" "3.14"+ "bool-true" "true"+ "bool-false" "false"}+ (t2/select-one-fn :login_attributes :model/User :id user-id)))))))))++(deftest create-user-with-different-attribute-types-test+ (testing "POST /api/user"+ (testing "Non-string attributes are converted to strings"+ (with-temp-user-email! [email]+ (let [response (mt/user-http-request :crowberto :post 200 "user"+ {:first_name "Attribute"+ :last_name "Types"+ :email email+ :login_attributes {:string-val "test-string"+ :integer-val 123+ :decimal-val 45.67+ :boolean-true true+ :boolean-false false}})]+ (is (= {:string-val "test-string"+ :integer-val "123"+ :decimal-val "45.67"+ :boolean-true "true"+ :boolean-false "false"}+ (:login_attributes response)))+ (testing "values are persisted correctly in the database"+ (is (= {"string-val" "test-string"+ "integer-val" "123"+ "decimal-val" "45.67"+ "boolean-true" "true"+ "boolean-false" "false"}+ (t2/select-one-fn :login_attributes :model/User :id (:id response))))))))))++(deftest login-attributes-cannot-start-with-at-symbol+ (testing "PUT /api/user/:id"+ (testing "We can't create login attributes starting with `@`"+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test"+ :last_name "User"+ :email "[email protected]"+ :is_superuser true}]+ (is (= {:specific-errors {:login_attributes {(keyword "@foo") ["login attribute keys must not start with `@`, received: \"@foo\""]}},+ :errors+ {:login_attributes+ {(keyword "@foo")+ "nullable map from <login attribute keys must be a keyword or string, and login attribute keys must not start with `@`> to <anything>"}}}+ (mt/user-http-request :crowberto :put 400 (str "user/" user-id)+ {:email "[email protected]"+ :login_attributes {"@foo" "foo"}}))))))+ (testing "POST /api/user"+ (let [user-name (mt/random-name)+ email (mt/random-email)]+ (mt/with-model-cleanup [:model/User]+ (mt/with-fake-inbox+ (is (= {:specific-errors {:login_attributes {(keyword "@foo") ["login attribute keys must not start with `@`, received: \"@foo\""]}},+ :errors+ {:login_attributes+ {(keyword "@foo")+ "nullable map from <login attribute keys must be a keyword or string, and login attribute keys must not start with `@`> to <anything>"}}}+ (mt/user-http-request :crowberto :post 400 "user"+ {:first_name user-name+ :last_name user-name+ :email email+ :login_attributes {"@foo" "bar"}}))))))))+(deftest ^:parallel updated-user-name-test(testing "Test that `metabase.users-rest.api/updated-user-name` works as intended."(let [names {:first_name "Test" :last_name "User"} ;; in a real user map, `:first_name` and `:last_name` will always be presentdiff --git a/test_resources/saml-test-response-new-user-with-tenant.xml b/test_resources/saml-test-response-new-user-with-tenant.xmlnew file mode 100644index 00000000000..5d971b523d2--- /dev/null+++ b/test_resources/saml-test-response-new-user-with-tenant.xml@@ -0,0 +1,96 @@+<?xml version="1.0"?>+<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_6643ab567200fd4a5c73" InResponseTo="_1" Version="2.0" IssueInstant="2018-07-05T18:02:53Z" Destination="http://localhost:3000/auth/sso">+ <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:saml-metabase-test.auth0.com</saml:Issuer>+ <samlp:Status>+ <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>+ </samlp:Status>+ <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="_vUq3VKutPOwCGartAC4Cbdmql23G3PE2" IssueInstant="2018-07-05T18:02:53.262Z">+ <saml:Issuer>urn:saml-metabase-test.auth0.com</saml:Issuer>+ <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">+ <SignedInfo>+ <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>+ <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>+ <Reference URI="#_vUq3VKutPOwCGartAC4Cbdmql23G3PE2">+ <Transforms>+ <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>+ <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>+ </Transforms>+ <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>+ <DigestValue>4SH+6iSi9cU3PCPqmJDnP6iK+BY=</DigestValue>+ </Reference>+ </SignedInfo>+ <SignatureValue>Dvfajt2ZBDHmHGl0yLETE1trkR99Bv+kVbgVtqNTRBeeb2oUShBY9EQJKmFtdReuamqr1Tn3kjaxZefxpd1XzB4dzsWNKF0duThKP5YTg5njM3PBsN/yXFAIrIHTjedHEOdwuDgPm+endqEtaFm8yQkn0VhYGK86udpPsMvxwPbYdy2eCAWuHXpNFynfWSRJz7rckubIGvXm7Lar/bMbMYiJa5u+wVqmeH53IddjIEQOeZLsQfPyNeZolWGqBv0TzpM/yEejDjQnnj55fMFXpGS3lKJ02vArYLdgtjW2isgB8/m5dY0gjFob0k9ioy+nghdH/rDKFIvqS/Jb8A50zg==</SignatureValue>+ <KeyInfo>+ <X509Data>+ <X509Certificate>MIIDEzCCAfugAwIBAgIJYpjQiNMYxf1GMA0GCSqGSIb3DQEBCwUAMCcxJTAjBgNVBAMTHHNhbWwtbWV0YWJhc2UtdGVzdC5hdXRoMC5jb20wHhcNMTgwNTI5MjEwMDIzWhcNMzIwMjA1MjEwMDIzWjAnMSUwIwYDVQQDExxzYW1sLW1ldGFiYXNlLXRlc3QuYXV0aDAuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzNcrpju4sILZQNe1adwg3beXtAMFGB+Buuc414+FDv2OG7X7b9OSYar/nsYfWwiazZRxEGriagd0Sj5mJ4Qqx+zmB/r4UgX3q/KgocRLlShvvz5gTD99hR7LonDPSWET1E9PD4XE1fRaq+BwftFBl45pKTcCR9QrUAFZJ2R/3g06NPZdhe4bg/lTssY5emCxaZpQEku/v+zzpV2nLF4by0vSj7AHsubrsLgsCfV3JvJyTxCyo1aIOlv4Vrx7h9rOgl9eEmoU5XJAl3D7DuvSTEOy7MyDnKF17m7l5nOPZCVOSzmCWvxSCyysijgsM5DSgAE8DPJyoYezV3gTX2OO2QIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSpB3lvrtbSDuXkB6fhbjeUpFmL2DAOBgNVHQ8BAf8EBAMCAoQwDQYJKoZIhvcNAQELBQADggEBAAEHGIAhR5GPD2JxgLtpNtZMCYiAM4Gr7hoTQMaKiXgVtdQu4iMFfbpEwIr6UVaDU2HKhvSRFIilOjRGmCGrIzvJgR2l+RL1Z3KrZypI1AXKJT5pF5g5FitBsZq+kiUpdRILl2hICzw9Q1M2Le+JSUcHcbHTVgF24xuzOZonxeE56Oc26Ju4CorLpM3Nb5iYaGOlQ+48/GP82cLxlVyi02va8tp7KP03ePSaZeBEKGpFtBtEN/dC3NKO1mmrT9284H0tvete6KLUH+dsS6bDEYGHZM5KGoSLWRr3qYlCB3AmAw+KvuiuSczLg9oYBkdxlhK9zZvkjCgaLCen+0aY67A=</X509Certificate>+ </X509Data>+ </KeyInfo>+ </Signature>+ <saml:Subject>+ <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">auth0|5b0dd0185d7d1617fd8065b5</saml:NameID>+ <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">+ <saml:SubjectConfirmationData NotOnOrAfter="2018-07-05T19:02:53.262Z" Recipient="http://localhost:3000/auth/sso" InResponseTo="_1"/>+ </saml:SubjectConfirmation>+ </saml:Subject>+ <saml:Conditions NotBefore="2018-07-05T18:02:53.262Z" NotOnOrAfter="2018-07-05T19:02:53.262Z">+ <saml:AudienceRestriction>+ <saml:Audience>Metabase</saml:Audience>+ </saml:AudienceRestriction>+ </saml:Conditions>+ <saml:AuthnStatement AuthnInstant="2018-07-05T18:02:53.262Z" SessionIndex="_8vKjURdHz4jghbYbj48khvBkLaEeyEqc">+ <saml:AuthnContext>+ <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>+ </saml:AuthnContext>+ </saml:AuthnStatement>+ <saml:AttributeStatement xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">auth0|5b0dd0185d7d1617fd8065b5</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">[email protected]</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">New</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">User</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">[email protected]</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">[email protected]</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="tenant" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">tenant-mctenantson</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/identities/default/provider" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">auth0</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/identities/default/connection" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">Username-Password-Authentication</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/identities/default/isSocial" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:boolean">false</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/email_verified" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:boolean">true</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/clientID" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">W1R5HozFA9cnbFVbmIT8KPdVmH0pU85k</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/picture" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">https://s.gravatar.com/avatar/9e18d6fcddec348d9131522c3c535646?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fry.png</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/nickname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:string">newuser</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/updated_at" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:anyType">Thu Jul 05 2018 18:02:53 GMT+0000 (UTC)</saml:AttributeValue>+ </saml:Attribute>+ <saml:Attribute Name="http://schemas.auth0.com/created_at" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">+ <saml:AttributeValue xsi:type="xs:anyType">Tue May 29 2018 22:11:36 GMT+0000 (UTC)</saml:AttributeValue>+ </saml:Attribute>+ </saml:AttributeStatement>+ </saml:Assertion>+</samlp:Response>