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
Cover DB management permissions with targetted tests (#80594)
Nemanja Glumac4b8fd9848ec8
diff --git a/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts b/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.tsindex a40471eeeb0..f4139581542 100644--- a/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts+++ b/e2e/test/scenarios/admin/database-routing/database-routing-admin.cy.spec.ts@@ -12,6 +12,7 @@ import {BASE_POSTGRES_DESTINATION_DB_INFO,configureDbRoutingViaAPI,createDestinationDatabasesViaAPI,+ grantDatabaseManagementViaAPI,} from "./helpers/e2e-database-routing-helpers";const { H } = cy;@@ -128,7 +129,7 @@ describe("admin > database > database routing", () => {// bulk creation via api (this is how we expect most users to create destination dbs)cy.log("should be able to bulk create destination dbs via API");createDestinationDatabasesViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,databases: _.range(2, 7).map((i) => ({...BASE_POSTGRES_DESTINATION_DB_INFO,name: `Destination DB ${i}`,@@ -209,15 +210,15 @@ describe("admin > database > database routing", () => {it("should not leak destinations databases in the application", () => {cy.log("setup db routing via API");- cy.visit("/admin/databases/2");+ cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);cy.log("disable model actions");cy.findByLabelText("Model actions").click({ force: true });configureDbRoutingViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,user_attribute: "role",});createDestinationDatabasesViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,databases: [BASE_POSTGRES_DESTINATION_DB_INFO],});@@ -331,11 +332,11 @@ describe("admin > database > database routing", () => {it("should highlight that a dabtabase has routing enabled on the permissions pages", () => {cy.log("setup");- cy.request("PUT", "/api/database/2", {+ cy.request("PUT", `/api/database/${WRITABLE_DB_ID}`, {settings: { "database-enable-actions": false },});configureDbRoutingViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,user_attribute: "role",});@@ -346,13 +347,15 @@ describe("admin > database > database routing", () => {.should("exist");cy.log("should highlight on group perms page at table level");- cy.visit(`/admin/permissions/data/group/${ALL_USERS_GROUP}/database/2`);+ cy.visit(+ `/admin/permissions/data/group/${ALL_USERS_GROUP}/database/${WRITABLE_DB_ID}`,+ );cy.findByTestId("permissions-editor-breadcrumbs").findByText("(Database routing enabled)").should("exist");cy.log("should highlight on group perms page at table level");- cy.visit("/admin/permissions/data/database/2");+ cy.visit(`/admin/permissions/data/database/${WRITABLE_DB_ID}`);cy.findByTestId("permissions-editor-breadcrumbs").findByText("(Database routing enabled)").should("exist");@@ -377,77 +380,48 @@ describe("admin > database > database routing", () => {dbRoutingSection().should("not.exist");});- it("should show for users with db management permissions but prevent removal of destination databases", () => {- cy.log("setup - db routing");- cy.visit("/admin/databases/2");- visitDatabaseAdminPage(WRITABLE_DB_ID);- cy.findAllByTestId("database-model-features-section")- .findByLabelText("Model actions")- .click({ force: true });+ it("should let a database manager edit but not remove a destination database", () => {+ cy.log("setup - routing enabled with one destination database");+ disableModelActionsViaApi(WRITABLE_DB_ID);configureDbRoutingViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,user_attribute: "role",});createDestinationDatabasesViaAPI({- router_database_id: 2,+ router_database_id: WRITABLE_DB_ID,databases: [BASE_POSTGRES_DESTINATION_DB_INFO],+ })+ .its("body.0.id")+ .as("destinationDbId");++ cy.log("grant database management permission to all users");+ grantDatabaseManagementViaAPI({+ groupId: ALL_USERS_GROUP,+ databaseId: WRITABLE_DB_ID,});- cy.log("normal user should not see db routing");- cy.signOut();- cy.signInAsNormalUser();- visitDatabaseAdminPage(WRITABLE_DB_ID);- cy.get("main").findByText(- "Sorry, you don’t have permission to see that.",- );-- cy.log("grant db management permissions to all users");- cy.signOut();- cy.signInAsAdmin();- cy.visit(`/admin/permissions/data/group/${ALL_USERS_GROUP}`);- // NOTE: manage db permissions currently do not work in master w/o having create queries permissions- // so we have to grant this permission in addition to db management- const CREATE_QUERIES_PERMISSION_INDEX = 1;- H.modifyPermission(- "Writable Postgres12",- CREATE_QUERIES_PERMISSION_INDEX,- "Query builder and native",- );- const MANAGE_DATABASE_PERMISSION_INDEX = 4;- H.modifyPermission(- "Writable Postgres12",- MANAGE_DATABASE_PERMISSION_INDEX,- "Yes",- );- cy.button("Save changes").click();- H.modal().button("Yes").click();-- cy.log("normal user should see db");cy.signOut();cy.signIn("normal");- visitDatabaseAdminPage(WRITABLE_DB_ID);- dbRoutingSection().should("exist");- dbRoutingSection().within(() => {- cy.log("should not be able to manage db routing settings");- cy.findByLabelText("Enable database routing").should("be.disabled");- cy.findByTestId("db-routing-user-attribute").should("be.disabled");- cy.findByRole("button", { name: /Add/ }).should("not.exist");- });- cy.log("should be able to edit databases");- dbRoutingSection()- .findByTestId("destination-db-list-item")- .icon("ellipsis")- .click();- H.popover().within(() => {- cy.findByText("Remove").should("not.exist");- cy.findByText("Edit").should("exist").click();+ cy.log("editing a destination database is allowed by direct URL");+ cy.get("@destinationDbId").then((destinationDbId) => {+ cy.visit(+ `/admin/databases/${WRITABLE_DB_ID}/destination-databases/${destinationDbId}`,+ );});- H.modal().within(() => {- H.typeAndBlurUsingLabel(/Slug/, "Destination DB 1");- cy.button("Save changes").click();- cy.wait("@databaseUpdate");+ H.modal().findByText("Edit destination database").should("be.visible");++ cy.log("removing a destination database is refused by direct URL");+ cy.get("@destinationDbId").then((destinationDbId) => {+ cy.visit(+ `/admin/databases/${WRITABLE_DB_ID}/destination-databases/${destinationDbId}/remove`,+ );});+ cy.location("pathname").should("eq", "/unauthorized");+ cy.findByRole("status").should(+ "contain.text",+ "Sorry, you don\u2019t have permission to see that.",+ );});});@@ -600,7 +574,7 @@ describe("admin > database > database routing", () => {describe("OSS", { tags: ["@OSS"] }, () => {it("should not show the feature if not enabled in token features", () => {- cy.visit("/admin/databases/2");+ cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);dbConnectionInfoSection().should("exist");dbRoutingSection().should("not.exist");});diff --git a/e2e/test/scenarios/admin/database-routing/helpers/e2e-database-routing-helpers.ts b/e2e/test/scenarios/admin/database-routing/helpers/e2e-database-routing-helpers.tsindex beb8f50c469..d23550e60f3 100644--- a/e2e/test/scenarios/admin/database-routing/helpers/e2e-database-routing-helpers.ts+++ b/e2e/test/scenarios/admin/database-routing/helpers/e2e-database-routing-helpers.ts@@ -4,7 +4,7 @@ import {QA_POSTGRES_PORT,USER_GROUPS,} from "e2e/support/cypress_data";-import type { DatabaseData, User } from "metabase-types/api";+import type { Database, DatabaseData, User } from "metabase-types/api";const { ALL_USERS_GROUP, COLLECTION_GROUP } = USER_GROUPS;@@ -22,6 +22,35 @@ export function configureDbRoutingViaAPI({);}+/**+ * Grants a group database management permission, which the graph API exposes as+ * `details` and stores as `:perms/manage-database`. Permissions that aren't named+ * in the payload are left as they are.+ */+export function grantDatabaseManagementViaAPI({+ groupId,+ databaseId,+}: {+ groupId: number;+ databaseId: number;+}) {+ cy.request("GET", "/api/permissions/graph").then(+ ({ body: { groups, revision } }) => {+ cy.request("PUT", "/api/permissions/graph", {+ revision,+ groups: {+ ...groups,+ [groupId]: {+ ...groups[groupId],+ [databaseId]: { details: "yes" },+ },+ },+ });+ },+ );+}++/** Responds with the created destination databases, in the order they were passed in. */export function createDestinationDatabasesViaAPI({router_database_id,databases,@@ -29,10 +58,14 @@ export function createDestinationDatabasesViaAPI({router_database_id: number;databases: DatabaseData[];}) {- cy.request("POST", "/api/ee/database-routing/destination-database", {- router_database_id,- destinations: databases,- });+ return cy.request<Database[]>(+ "POST",+ "/api/ee/database-routing/destination-database",+ {+ router_database_id,+ destinations: databases,+ },+ );}export const BASE_POSTGRES_DESTINATION_DB_INFO = {diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.cljindex 6a5dd46d4d1..d637c2bab86 100644--- a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj@@ -260,6 +260,26 @@(testing "New group should NOT have permissions for the destination database"(is (not (t2/exists? :model/DataPermissions :group_id group-id :db_id destination-db-id)))))))+(deftest manage-db-user-can-update-destination-database-test+ (testing "PUT /api/database/:id on a routed destination honors manage-database perms held on its router database"+ ;; The permission lives on the router database; the destination itself carries no grant of its own. Without+ ;; `:advanced-permissions`, `current-user-can-write-db?` falls back to the OSS superuser check, so the grant would+ ;; be a no-op and the assertions below would pass for the wrong reason.+ (mt/with-additional-premium-features #{:advanced-permissions}+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/DatabaseRouter _ {:database_id db-id :user_attribute "foo"}+ :model/Database {dest :id} {:router_database_id db-id :name "Destination DB 1"}]+ (mt/with-no-data-perms-for-all-users!+ (testing "without manage-database perms on the router the update is refused"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 (str "database/" dest) {:name "Renamed"})))+ (is (= "Destination DB 1" (t2/select-one-fn :name :model/Database :id dest))))+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/manage-database :yes)+ (testing "with manage-database perms on the router the update succeeds"+ (is (=? {:id dest}+ (mt/user-http-request :rasta :put 200 (str "database/" dest) {:name "Renamed"})))+ (is (= "Renamed" (t2/select-one-fn :name :model/Database :id dest)))))))))+(deftest manage-db-user-cannot-delete-destination-database-test(testing "DELETE /api/database/:id is rejected (403) for a non-superuser with manage-database perms on a routed destination";; NOTE: `DELETE /api/database/:id` calls `api/check-superuser` unconditionally before it ever looks at thediff --git a/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.unit.spec.tsxindex fcb9b048b96..d44b3bbff8d 100644--- a/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/database_routing/DatabaseRoutingSection/DatabaseRoutingSection.unit.spec.tsx@@ -18,16 +18,20 @@ import { DatabaseRoutingSection } from "./DatabaseRoutingSection";interface SetupOpts {database?: Database;+ isAdmin?: boolean;}-const setup = ({ database = createMockDatabase() }: SetupOpts = {}) => {+const setup = ({+ database = createMockDatabase(),+ isAdmin = true,+}: SetupOpts = {}) => {setupUserAttributesEndpoint(["cool_guy", "boss_gal"]);setupDatabasesEndpoints([database]);setupListTransformsEndpoint([]);renderWithProviders(<DatabaseRoutingSection database={database} />, {storeInitialState: {- currentUser: createMockUser({ is_superuser: true }),+ currentUser: createMockUser({ is_superuser: isAdmin }),settings: createMockSettingsState(createMockSettings({engines: createMockEngines({@@ -110,6 +114,40 @@ describe("DatabaseRoutingSection", () => {expect(screen.queryByText("Database routing")).not.toBeInTheDocument();});+ it("should let a non-admin with database management permission view but not change routing settings", async () => {+ setup({+ database: createMockDatabase({+ engine: "postgres",+ features: ["database-routing"],+ router_user_attribute: "cool_guy",+ }),+ isAdmin: false,+ });++ expect(screen.getByText("Database routing")).toBeInTheDocument();+ expect(screen.getByLabelText("Enable database routing")).toBeDisabled();+ expect(+ await screen.findByTestId("db-routing-user-attribute"),+ ).toBeDisabled();+ expect(screen.queryByRole("link", { name: /Add/ })).not.toBeInTheDocument();+ });++ it("should let an admin change routing settings", async () => {+ setup({+ database: createMockDatabase({+ engine: "postgres",+ features: ["database-routing"],+ router_user_attribute: "cool_guy",+ }),+ });++ expect(screen.getByLabelText("Enable database routing")).toBeEnabled();+ expect(+ await screen.findByTestId("db-routing-user-attribute"),+ ).toBeEnabled();+ expect(screen.getByRole("link", { name: /Add/ })).toBeInTheDocument();+ });+it("should show a warning when writable connection is enabled", () => {setup({database: createMockDatabase({diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.unit.spec.tsindex 12e9d896af7..eb3e59a8652 100644--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.unit.spec.ts@@ -1,6 +1,13 @@import { PLUGIN_TRANSFORMS } from "metabase/plugins";+import {+ createMockUser,+ createMockUserPermissions,+} from "metabase-types/api/mocks";-import { getDataColumns } from "./utils";+import {+ databaseManagementPermissionAllowedPathGetter,+ getDataColumns,+} from "./utils";describe("getDataColumns", () => {const originalIsEnabled = PLUGIN_TRANSFORMS.isEnabled;@@ -109,3 +116,31 @@ describe("getDataColumns", () => {});});});++describe("databaseManagementPermissionAllowedPathGetter", () => {+ it("grants the databases admin path when the user has database management permission", () => {+ const user = createMockUser({+ is_superuser: false,+ permissions: createMockUserPermissions({ can_access_db_details: true }),+ });++ expect(databaseManagementPermissionAllowedPathGetter(user)).toEqual([+ "databases",+ ]);+ });++ it("grants no path when the user lacks database management permission", () => {+ const user = createMockUser({+ is_superuser: false,+ permissions: createMockUserPermissions({ can_access_db_details: false }),+ });++ expect(databaseManagementPermissionAllowedPathGetter(user)).toEqual([]);+ });++ it("grants no path when there is no user", () => {+ expect(databaseManagementPermissionAllowedPathGetter(undefined)).toEqual(+ [],+ );+ });+});diff --git a/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsxindex c29cb7289d2..22daf81f608 100644--- a/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx+++ b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx@@ -1,6 +1,9 @@import { mockSettings } from "__support__/settings";-import { renderWithProviders, waitFor } from "__support__/ui";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { AdminPath } from "metabase/redux/store";import {+ createMockAdminAppState,+ createMockAdminState,createMockSettingsState,createMockState,} from "metabase/redux/store/mocks";@@ -9,7 +12,12 @@ import { setBasename } from "metabase/utils/basename";import { replaceLocation } from "metabase/utils/dom";import { createMockUser } from "metabase-types/api/mocks";-import { IsAdmin, IsAuthenticated, IsNotAuthenticated } from "./auth-guards";+import {+ CanAccessSettings,+ IsAdmin,+ IsAuthenticated,+ IsNotAuthenticated,+} from "./auth-guards";jest.mock("metabase/utils/dom", () => ({...jest.requireActual("metabase/utils/dom"),@@ -116,6 +124,50 @@ describe("route-guards", () => {});});+ describe("CanAccessSettings", () => {+ const DATABASES_PATH: AdminPath = {+ name: "Databases",+ path: "/admin/databases",+ key: "databases",+ };++ const setup = (paths: AdminPath[]) =>+ renderWithProviders(+ <>+ <Route element={<CanAccessSettings />}>+ <Route path="/admin/databases" element={<Protected />} />+ </Route>+ <Route path="/unauthorized" element={<Unauthorized />} />+ </>,+ {+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: false }),+ settings: createMockSettingsState({ "has-user-setup": true }),+ admin: createMockAdminState({+ app: createMockAdminAppState({ paths }),+ }),+ }),+ withRouter: true,+ initialRoute: "/admin/databases",+ },+ );++ it("lets a non-admin through when a permission grant left them an admin path", async () => {+ const { router } = setup([DATABASES_PATH]);++ expect(await screen.findByText("protected")).toBeInTheDocument();+ expect(router?.location.pathname).toBe("/admin/databases");+ });++ it("redirects a non-admin with no admin paths to /unauthorized", async () => {+ const { router } = setup([]);++ await waitFor(() => {+ expect(router?.location.pathname).toBe("/unauthorized");+ });+ });+ });+describe("IsNotAuthenticated", () => {it("bounces a logged-in user off /auth/login", async () => {const state = createMockState({