Skip to content

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

21.1 KB
Raw Blame
import _ from "underscore";

import {
  QA_POSTGRES_PORT,
  SAMPLE_DB_ID,
  USER_GROUPS,
  WRITABLE_DB_ID,
} from "e2e/support/cypress_data";
import type { DatabaseId } from "metabase-types/api";

import {
  BASE_POSTGRES_DESTINATION_DB_INFO,
  configureDbRoutingViaAPI,
  createDestinationDatabasesViaAPI,
  grantDatabaseManagementViaAPI,
} from "./helpers/e2e-database-routing-helpers";

const { H } = cy;
const { ALL_USERS_GROUP } = USER_GROUPS;

describe("admin > database > database routing", () => {
  beforeEach(() => {
    H.restore("postgres-writable");
    cy.signInAsAdmin();

    cy.intercept(
      "POST",
      "/api/ee/database-routing/destination-database?check_connection_details=true",
    ).as("createDestinationDatabase");
    cy.intercept("PUT", "/api/database/*").as("databaseUpdate");
    cy.intercept("DELETE", "/api/database/*").as("deleteDatabase");
  });

  describe("EE", () => {
    beforeEach(() => {
      H.activateToken("pro-self-hosted");
    });

    it("should be able to configure db routing and manage destination databases", () => {
      // setup
      visitDatabaseAdminPage(WRITABLE_DB_ID);
      cy.log("disable data actions");
      cy.findByLabelText("Data actions").click({ force: true });

      // enabling
      cy.log("should be able to turn the feature on");
      cy.findByLabelText("Enable database routing")
        .should("not.be.checked")
        .click({ force: true }); // mantine toggle hides the real input
      cy.findByRole("button", { name: /Add/ }).should("be.disabled");
      cy.findByTestId("db-routing-user-attribute").click();
      H.popover().findByText("attr_uid").click();
      H.undoToast().within(() => {
        cy.findByText("Database routing enabled").should("exist");
        cy.icon("close").click();
      });

      // configuring
      cy.log("should be able to change the user attribute routed on");
      cy.findByTestId("db-routing-user-attribute").click();
      H.popover().findByText("role").click();
      H.undoToast().within(() => {
        cy.findByText("Database routing updated").should("exist");
        cy.icon("close").click();
      });

      // database creation
      cy.log("should be able to create a destination databases");
      dbRoutingSection().findByText("No destination databases added yet");
      cy.findByRole("link", { name: /Add/ }).click();

      H.modal().within(() => {
        cy.log("should not allow changing engine");
        cy.findByLabelText("Database type").should("not.exist");

        H.typeAndBlurUsingLabel(/Slug/, "Destination DB 1");
        H.typeAndBlurUsingLabel(/Host/, "localhost");
        H.typeAndBlurUsingLabel(/Port/, QA_POSTGRES_PORT);
        H.typeAndBlurUsingLabel(/Database name/, "sample");
        H.typeAndBlurUsingLabel(/Username/, "metabase");
        H.typeAndBlurUsingLabel(/Password/, "metasample123");

        cy.button("Save").click();
        cy.wait("@createDestinationDatabase");
      });
      H.undoToast().within(() => {
        cy.findByText("Destination database created successfully").should(
          "exist",
        );
        cy.icon("close").click();
      });
      dbRoutingSection().within(() => {
        cy.findByText("Destination DB 1");
        cy.findByTestId("database-connection-health-info").realHover();
      });
      H.tooltip().should("contain.text", "Connected");

      cy.log("should validate destination db creation");
      cy.findByRole("link", { name: /Add/ }).click();

      H.modal().within(() => {
        cy.log("should prevent adding a db with the same name");
        H.typeAndBlurUsingLabel(/Slug/, "Destination DB 1");
        H.typeAndBlurUsingLabel(/Host/, "localhost");
        H.typeAndBlurUsingLabel(/Port/, QA_POSTGRES_PORT);
        H.typeAndBlurUsingLabel(/Database name/, "sample");
        H.typeAndBlurUsingLabel(/Username/, "metabase");
        H.typeAndBlurUsingLabel(/Password/, "metasample123");

        cy.button("Save").click();
        cy.wait("@createDestinationDatabase");
        cy.findByText("A destination database with that name already exists.");

        cy.log("should prevent adding with incorrect connection info");
        H.typeAndBlurUsingLabel(/Slug/, "Unique Destination DB Name");
        H.typeAndBlurUsingLabel(/Password/, "metasample124");
        cy.button(/(Failed|Save)/).click();
        cy.wait("@createDestinationDatabase");
        cy.findByText("Looks like your Password is incorrect.");

        cy.button("Cancel").click();
      });
      cy.findByTestId("leave-confirmation")
        .should("exist")
        .findByRole("button", { name: "Discard changes" })
        .click();
      H.modal().should("not.exist");

      // 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: WRITABLE_DB_ID,
        databases: _.range(2, 7).map((i) => ({
          ...BASE_POSTGRES_DESTINATION_DB_INFO,
          name: `Destination DB ${i}`,
        })),
      });
      cy.reload();
      dbRoutingSection().within(() => {
        cy.findByText("Destination DB 5").should("exist");
        cy.findByText("Destination DB 6").should("not.exist");
      });

      // view all destination databases
      cy.log("should be able to see full list of destination databases");
      dbRoutingSection().findByText("View all 6").click();
      H.modal().within(() => {
        cy.findByText("Destination DB 6").should("exist");
        cy.button("Close").click();
      });

      // update destination database
      dbRoutingSection()
        .findAllByTestId("destination-db-list-item")
        .first()
        .icon("ellipsis")
        .click();
      H.popover().findByText("Edit").click();
      H.modal().within(() => {
        H.typeAndBlurUsingLabel(/Slug/, " Destination DB 1 Updated");
        cy.button("Save changes").click();
        cy.wait("@databaseUpdate");
      });
      H.undoToast().within(() => {
        cy.findByText("Destination database updated successfully").should(
          "exist",
        );
        cy.icon("close").click();
      });

      // remove a database
      cy.log("should be able to remove a routed database");
      dbRoutingSection()
        .findAllByTestId("destination-db-list-item")
        .first()
        .icon("ellipsis")
        .click();
      H.popover().findByText("Remove").click();
      H.modal().within(() => {
        cy.findByTestId("database-name-confirmation-input").type(
          "Destination DB 1 Updated",
        );
        cy.button("Delete").click();
        cy.wait("@deleteDatabase");
      });
      dbRoutingSection()
        .findByText("Destination DB 1 Updated")
        .should("not.exist");

      // turn off routing
      cy.log("should be able to turn the feature off");
      cy.findByLabelText("Enable database routing")
        .should("be.checked")
        .click({ force: true }); // mantine toggle hides the real input
      cy.findByLabelText("Enable database routing").should("not.be.checked");
      H.undoToast().within(() => {
        cy.findByText("Database routing disabled").should("exist");
        cy.icon("close").click();
      });

      cy.log(
        "should not remove destination databases when turning the feature off",
      );
      expandDbRouting();
      dbRoutingSection().within(() => {
        cy.findByText("Destination DB 2").should("exist");
        cy.findByText("No destination databases added yet").should("not.exist");
      });
    });

    it("should not leak destinations databases in the application", () => {
      cy.log("setup db routing via API");
      cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);
      cy.log("disable data actions");
      cy.findByLabelText("Data actions").click({ force: true });
      configureDbRoutingViaAPI({
        router_database_id: WRITABLE_DB_ID,
        user_attribute: "role",
      });
      createDestinationDatabasesViaAPI({
        router_database_id: WRITABLE_DB_ID,
        databases: [BASE_POSTGRES_DESTINATION_DB_INFO],
      });

      cy.log("validate setup was successful");
      cy.reload();
      cy.findByLabelText("Enable database routing").should("be.checked");
      dbRoutingSection()
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("exist");

      cy.log("should not see destination databases in admin list of database");
      cy.visit("/admin/databases");
      cy.findAllByTestId("database-list")
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("not.exist");

      cy.log("should not see destination databases in database browser");
      cy.visit("/browse/databases");
      cy.findAllByTestId("database-browser")
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("not.exist");

      cy.log("should not see destination databases in search");
      H.commandPaletteSearch(BASE_POSTGRES_DESTINATION_DB_INFO.name, false);
      H.commandPalette()
        .findByText("No results for “DestinationDB”")
        .should("exist");

      cy.log("should not see database in table metadata db list");
      H.DataModel.visit();

      H.DataModel.TablePicker.getDatabase(
        BASE_POSTGRES_DESTINATION_DB_INFO.name,
      ).should("not.exist");

      cy.log("should not see database in permissions pages");
      cy.visit("/admin/permissions/data/database");
      cy.get("aside")
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("not.exist");

      cy.log("should not see database in data picker");
      cy.visit("/question/notebook");
      H.miniPicker()
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("not.exist");
      H.miniPickerBrowseAll().click();
      H.entityPickerModal().within(() => {
        cy.findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name).should(
          "not.exist",
        );
      });

      cy.log("shoudl not see database in data reference");
      H.startNewNativeQuestion();
      cy.findByTestId("sidebar-header").icon("chevronleft").click();
      cy.findByTestId("sidebar-header-title").should(
        "have.text",
        "Data Reference",
      );
      cy.findByTestId("sidebar-header-title")
        .findByText(BASE_POSTGRES_DESTINATION_DB_INFO.name)
        .should("not.exist");
    });

    it("should not allow turning on db routing if other conflicting features are enabled", () => {
      cy.log("setup");
      setupModelPersistence();
      visitDatabaseAdminPage(WRITABLE_DB_ID);

      cy.log("should be disabled if data actions is enabled");
      cy.findByLabelText("Data actions").should("be.checked");
      assertDbRoutingDisabled(
        "Database routing can't be enabled if data actions are enabled.",
      );

      cy.findByLabelText("Data actions").parent("label").click();

      assertDbRoutingNotDisabled();

      cy.log("should be disabled if model persistence is enabled");
      cy.findByLabelText("Model persistence")
        .should("not.be.checked")
        .parent("label")
        .click();

      assertDbRoutingDisabled(
        "Database routing can't be enabled if model persistence is enabled.",
      );
      cy.findAllByTestId("database-model-persistence-section")
        .findByLabelText("Model persistence")
        .should("be.checked")
        .parent("label")
        .click();
      assertDbRoutingNotDisabled();

      cy.log("should be disabled if table editing is enabled");
      // Table editing must be the only active conflict here: the routing
      // section shows a single message, and data actions, model persistence,
      // and uploads all take precedence over table editing.
      tableEditingSection()
        .findByLabelText("Editable tables")
        .should("not.be.checked")
        .click({ force: true });
      assertDbRoutingDisabled(
        "Database routing can't be enabled when table editing is enabled.",
      );
      tableEditingSection()
        .findByLabelText("Editable tables")
        .should("be.checked")
        .click({ force: true });
      assertDbRoutingNotDisabled();

      cy.log("should be disabled if uploads are enabled for the database");
      cy.visit("/admin/settings/uploads");
      cy.findByLabelText("Upload Settings Form")
        .findByPlaceholderText("Select a database")
        .click();
      H.popover().findByText("Writable Postgres12").click();
      cy.findByLabelText("Upload Settings Form")
        .findByPlaceholderText("Select a schema")
        .click();

      H.popover().findByText("public").click();
      cy.findByLabelText("Upload Settings Form")
        .button("Enable uploads")
        .click();

      visitDatabaseAdminPage(WRITABLE_DB_ID);
      assertDbRoutingDisabled(
        "Database routing can't be enabled if uploads are enabled for this database.",
      );
    });

    it("should highlight that a dabtabase has routing enabled on the permissions pages", () => {
      cy.log("setup");
      cy.request("PUT", `/api/database/${WRITABLE_DB_ID}`, {
        settings: { "database-enable-actions": false },
      });
      configureDbRoutingViaAPI({
        router_database_id: WRITABLE_DB_ID,
        user_attribute: "role",
      });

      cy.log("should highlight on group perms page at db level");
      cy.visit(`/admin/permissions/data/group/${ALL_USERS_GROUP}`);
      cy.findByTestId("permission-table")
        .findByText("(Database routing enabled)")
        .should("exist");

      cy.log("should highlight on group perms page at table level");
      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/${WRITABLE_DB_ID}`);
      cy.findByTestId("permissions-editor-breadcrumbs")
        .findByText("(Database routing enabled)")
        .should("exist");
    });

    describe("feature visibility", () => {
      it("should only show db routing for valid database types", () => {
        cy.log("should not show for sample databases");
        visitDatabaseAdminPage(SAMPLE_DB_ID);
        dbConnectionInfoSection().should("exist");
        dbRoutingSection().should("not.exist");

        cy.log("should not show for attached data warehouses");
        cy.intercept("GET", `/api/database/${SAMPLE_DB_ID}`, (req) => {
          req.reply((res) => {
            res.body.is_attached_dwh = true;
            res.body.is_sample = false;
          });
        }).as("loadDatabase");
        cy.reload();
        dbConnectionInfoSection().should("exist");
        dbRoutingSection().should("not.exist");
      });

      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: WRITABLE_DB_ID,
          user_attribute: "role",
        });
        createDestinationDatabasesViaAPI({
          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.signOut();
        cy.signIn("normal");

        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().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.",
        );
      });
    });

    describe("feature compatibility", () => {
      beforeEach(() => {
        // disable data actions since it is enabled by default for this db
        disableModelActionsViaApi(WRITABLE_DB_ID);
      });

      it("should not be possible to enable model persistence, data actions, table editing, or uploads when database routing is enabled", () => {
        cy.log("setup");
        enableGlobalModelPersistence();
        configureDbRoutingViaAPI({
          router_database_id: WRITABLE_DB_ID,
          user_attribute: "role",
        });

        visitDatabaseAdminPage(WRITABLE_DB_ID);

        cy.log(
          "should not be possible to enable model persistence when database routing is enabled",
        );
        modelPersistenceSection().within(() => {
          cy.findByLabelText("Model persistence").should("be.disabled");
          cy.findByText(
            "Model persistence can't be enabled when database routing is enabled.",
          )
            .scrollIntoView()
            .should("be.visible");
        });

        cy.log(
          "should not be possible to enable data actions when database routing is enabled",
        );
        dataActionsSection().within(() => {
          cy.findByLabelText("Data actions").should("be.disabled");
          cy.findByText(
            "Data actions can't be enabled when database routing is enabled.",
          )
            .scrollIntoView()
            .should("be.visible");
        });

        cy.log(
          "should not be possible to enable table editing when database routing is enabled",
        );
        tableEditingSection().within(() => {
          cy.findByLabelText("Editable tables").should("be.disabled");
          cy.findByText(
            "Table editing can't be enabled when database routing is enabled.",
          )
            .scrollIntoView()
            .should("be.visible");
        });

        cy.log(
          "should not be possible to enable uploads when database routing is enabled",
        );
        // Keep this step last: it navigates away from the database page.
        visitUploadSettingsPage();

        cy.findByLabelText("Database to use for uploads").click();
        H.popover()
          .findByText("Writable Postgres12 (DB Routing Enabled)")
          .should("be.visible");
      });
    });
  });

  describe("OSS", { tags: ["@OSS"] }, () => {
    it("should not show the feature if not enabled in token features", () => {
      cy.visit(`/admin/databases/${WRITABLE_DB_ID}`);
      dbConnectionInfoSection().should("exist");
      dbRoutingSection().should("not.exist");
    });
  });
});

function dbConnectionInfoSection() {
  return cy.findByTestId("database-connection-info-section");
}

function dbRoutingSection() {
  return cy.findByTestId("database-routing-section");
}

function expandDbRouting() {
  dbRoutingSection().within(() => {
    cy.icon("chevrondown").click();
  });
}

function assertDbRoutingNotDisabled() {
  dbRoutingSection().within(() => {
    cy.findByLabelText("Enable database routing")
      .should("not.be.disabled")
      .realHover();
  });
  H.tooltip().should("not.contain", /Database routing can't be enabled if/);
}

function assertDbRoutingDisabled(message: string) {
  dbRoutingSection().within(() => {
    cy.findByLabelText("Enable database routing")
      .should("not.be.checked")
      .should("be.disabled");
    cy.findByText(message).scrollIntoView().should("be.visible");
  });
  // Use cy.trigger("mouseenter") instead of realHover() because Chrome v122+
  // headless hit-tests CDP mouse events to the disabled <input> inside the
  // Mantine Switch, which suppresses boundary events and prevents the Tooltip
  // from appearing. cy.trigger() dispatches the event directly on the Box
  // wrapper, bypassing Chrome's hit-testing.
  dbRoutingSection()
    .findByTestId("database-routing-toggle-wrapper")
    .trigger("mouseenter");
  H.tooltip().findByText(message).should("exist");
}

function setupModelPersistence() {
  cy.intercept("POST", "/api/persist/enable").as("enablePersistence");
  cy.visit("/admin/performance/models");
  cy.findByTestId("admin-layout-content").findByLabelText("Disabled").click();
  cy.wait("@enablePersistence");
}

function visitDatabaseAdminPage(databaseId: DatabaseId) {
  cy.visit(`/admin/databases/${databaseId}`);
}

function modelPersistenceSection() {
  return cy.findByTestId("database-model-persistence-section");
}

function dataActionsSection() {
  return cy.findByTestId("database-data-actions-section");
}

function disableModelActionsViaApi(databaseId: DatabaseId) {
  cy.request("PUT", `/api/database/${databaseId}`, {
    settings: { "database-enable-actions": false },
  });
}

function enableGlobalModelPersistence() {
  cy.visit("/admin/performance/models");
  cy.findByLabelText("Disabled").click();
}

function tableEditingSection() {
  return cy.findByTestId("database-table-editing-section");
}

function visitUploadSettingsPage() {
  cy.visit("/admin/settings/uploads");
}