Skip to content

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

16.8 KB
Raw Blame
const { H } = cy;
import { SAMPLE_DB_ID, USERS, USER_GROUPS } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
  FIRST_COLLECTION_ID,
  NODATA_USER_ID,
  ORDERS_DASHBOARD_ID,
  ORDERS_QUESTION_ID,
} from "e2e/support/cypress_sample_instance_data";

const { ALL_USERS_GROUP, DATA_GROUP, COLLECTION_GROUP } = USER_GROUPS;
const { PRODUCTS_ID, PEOPLE_ID, PRODUCTS } = SAMPLE_DATABASE;
const { nocollection } = USERS;

const PG_DB_ID = 2;

describe("issue 14873", { tags: "@external" }, () => {
  beforeEach(() => {
    H.restore("postgres-12");
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");

    // Update basic permissions (the same starting "state" as we have for the "Sample Database")
    cy.updatePermissionsGraph({
      [ALL_USERS_GROUP]: {
        [PG_DB_ID]: {
          "view-data": "blocked",
          "create-queries": "no",
        },
      },
      [DATA_GROUP]: {
        [PG_DB_ID]: {
          "view-data": "unrestricted",
          "create-queries": "query-builder-and-native",
        },
      },
      [COLLECTION_GROUP]: {
        [PG_DB_ID]: {
          "view-data": "blocked",
          "create-queries": "no",
        },
      },
    });
  });

  it("should handle the use of `regexExtract` in a sandboxed table (metabase#14873)", () => {
    const CC_NAME = "Firstname";
    // We need ultra-wide screen to avoid scrolling (custom column is rendered at the last position)
    cy.viewport(2200, 1200);

    H.withDatabase(PG_DB_ID, ({ PEOPLE, PEOPLE_ID }) => {
      // Question with a custom column created with `regextract`
      H.createQuestion({
        name: "14873",
        query: {
          "source-table": PEOPLE_ID,
          expressions: {
            [CC_NAME]: [
              "regex-match-first",
              ["field-id", PEOPLE.NAME],
              "^[A-Za-z]+",
            ],
          },
        },
        database: PG_DB_ID,
      }).then(({ body: { id: QUESTION_ID } }) => {
        cy.sandboxTable({
          table_id: PEOPLE_ID,
          attribute_remappings: {
            attr_uid: ["dimension", ["field-id", PEOPLE.ID]],
          },
        });

        cy.signOut();
        cy.signInAsSandboxedUser();

        H.visitQuestion(QUESTION_ID);

        cy.findByText(CC_NAME);
        cy.findByText(/^Hudson$/);
        H.assertQueryBuilderRowCount(1); // test that user is sandboxed - normal users has over 2000 rows
        H.assertDatasetReqIsSandboxed({
          requestAlias: `@cardQuery${QUESTION_ID}`,
        });
      });
    });
  });
});

describe("issue 19603", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    // Archive second collection (nested under the first one)
    cy.request("GET", "/api/collection/").then(({ body }) => {
      const { id } = body.find((c) => c.slug === "second_collection");

      H.archiveCollection(id);
    });
  });

  it("archived subcollection should not show up in permissions (metabase#19603)", () => {
    cy.visit("/admin/permissions/collections");

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("First collection").click();
    cy.url().should(
      "include",
      `/admin/permissions/collections/${FIRST_COLLECTION_ID}`,
    );
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Second collection").should("not.exist");
  });
});

describe("issue 20436", () => {
  const url = `/admin/permissions/data/group/${ALL_USERS_GROUP}`;
  const CREATE_QUERIES_PERMISSION_INDEX = 1;

  function changePermissions(from, to) {
    cy.findAllByText(from).first().click();

    H.popover().contains(to).click();
  }

  function saveChanges() {
    cy.button("Save changes").click();
    cy.button("Yes").click();
  }

  beforeEach(() => {
    cy.intercept("PUT", "/api/permissions/graph").as("updatePermissions");

    H.restore();
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");

    cy.updatePermissionsGraph({
      [ALL_USERS_GROUP]: {
        1: {
          "view-data": "unrestricted",
          "create-queries": "query-builder",
        },
      },
    });
  });

  it("should display correct permissions on the database level after changes on the table level (metabase#20436)", () => {
    cy.visit(url);

    cy.findByTestId("permission-table").within(() => {
      cy.findByText("Query builder only").click();
    });

    H.popover().within(() => {
      cy.findByText("Granular").click();
    });

    // Change the permission levels for ANY of the tables - it doesn't matter which one
    changePermissions("Query builder only", "No");

    saveChanges();
    cy.wait("@updatePermissions");

    // Now turn it back to previous value
    changePermissions("No", "Query builder only");

    saveChanges();
    cy.wait("@updatePermissions");

    cy.visit(url);
    H.assertPermissionForItem(
      "Sample Database",
      CREATE_QUERIES_PERMISSION_INDEX,
      "Query builder only",
    );
  });
});

describe("UI elements that make no sense for users without data permissions (metabase#22447, metabase#22449, metabase#22450)", () => {
  beforeEach(() => {
    H.restore();
  });

  it("should let users without data permissions view but not save questions, and hide visualization settings when data is blocked", () => {
    cy.signIn("nodata");

    H.visitQuestion(ORDERS_QUESTION_ID);
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("February 11, 2028, 9:40 PM"); // check that the data loads

    cy.findByTestId("viz-settings-button");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Visualization").click();

    cy.findByTestId("display-options-sensible");
    H.leftSidebar().within(() => {
      cy.findByTestId("more-charts-toggle").click();
      cy.icon("line").click();
      cy.findByTestId("Line-button").realHover();
      cy.findByTestId("Line-container").within(() => {
        cy.icon("gear").click();
      });
    });

    cy.findByTextEnsureVisible("Line options");
    cy.findByTestId("qb-save-button")
      .as("saveButton")
      .should("have.attr", "data-disabled");

    cy.get("@saveButton").realHover();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("You don't have permission to save this question.");

    cy.findByTestId("qb-header-action-panel").within(() => {
      cy.icon("refresh").should("not.exist");
    });

    H.newButton().click();
    H.popover().should("contain", "Dashboard").and("not.contain", "Question");

    cy.log("blocked data permissions");
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");
    cy.updatePermissionsGraph({
      [ALL_USERS_GROUP]: {
        [SAMPLE_DB_ID]: { "view-data": "blocked" },
      },
      [COLLECTION_GROUP]: {
        [SAMPLE_DB_ID]: { "view-data": "blocked" },
      },
    });

    cy.signIn("nodata");

    H.visitQuestion(ORDERS_QUESTION_ID);

    H.queryBuilderMain()
      .findByText("Sorry, you don't have permission to run this query.")
      .should("be.visible");

    H.queryBuilderFooter()
      .findByTestId("viz-settings-button")
      .should("not.exist");
    H.queryBuilderFooter().findByText("Visualization").should("not.exist");

    cy.findByTestId("qb-header-action-panel").within(() => {
      cy.icon("refresh").should("not.exist");
    });

    H.newButton().click();
    H.popover().should("contain", "Dashboard").and("not.contain", "Question");

    H.visitDashboard(ORDERS_DASHBOARD_ID);
    H.getDashboardCard()
      .findByText("Sorry, you don't have permission to see this card.")
      .should("be.visible");
  });
});

describe("issue 22473", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.setupSMTP();
  });

  it("nocollection user should be able to view and unsubscribe themselves from a subscription", () => {
    cy.visit(`/dashboard/${ORDERS_DASHBOARD_ID}`);
    H.toggleDashboardSubscriptionsSidebar();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Email it").click();
    cy.findByPlaceholderText("Enter user names or email addresses")
      .click()
      .type(`${nocollection.first_name} ${nocollection.last_name}{enter}`)
      .blur();
    H.sidebar().within(() => {
      cy.button("Done").click();
    });

    cy.signIn("nocollection");
    cy.visit("/account/notifications");

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Orders in a dashboard").should("exist");
    cy.findByTestId("notifications-list").within(() => {
      cy.findByLabelText("close icon").click();
    });
    H.modal().within(() => {
      cy.button("Unsubscribe").click();
    });
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Orders in a dashboard").should("not.exist");
  });
});

describe("issue 22695 ", () => {
  function assert() {
    cy.visit("/");

    H.commandPaletteSearch("S");
    cy.wait("@searchResults");

    cy.findAllByTestId("search-result-item-name")
      .should("have.length.above", 0)
      .and("not.contain", "Sample Database");
  }

  beforeEach(() => {
    cy.intercept("GET", "/api/search?*").as("searchResults");

    H.restore();
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");

    cy.updatePermissionsGraph({
      [ALL_USERS_GROUP]: {
        [SAMPLE_DB_ID]: { "view-data": "blocked" },
      },
      [DATA_GROUP]: {
        [SAMPLE_DB_ID]: { "view-data": "blocked" },
      },
    });
  });

  // https://github.com/metabase/metaboat/issues/159
  it("should not expose database names to which the user has no access permissions (metabase#22695)", () => {
    // Nocollection user belongs to a "data" group which we blocked for this repro,
    // but they have access to data otherwise (as name suggests)
    cy.signIn("nocollection");
    assert();

    cy.signOut();

    // Nodata user belongs to the group that has access to collections,
    // but has no-self-service data permissions
    cy.signIn("nodata");
    assert();
  });
});

describe("issues 22726 and 22727", () => {
  beforeEach(() => {
    cy.intercept("POST", "/api/dataset").as("dataset");
    cy.intercept("POST", "/api/card").as("createCard");

    H.restore();
    cy.signInAsAdmin();

    // Let's give all users a read only access to "Our analytics"
    cy.updateCollectionGraph({
      [ALL_USERS_GROUP]: { root: "read" },
    });

    cy.signIn("nocollection");
  });

  it("should not offer to save a question in a view-only collection, but should offer to duplicate it (metabase#22727, metabase#20717, metabase#22726)", () => {
    // It is important to start from a saved question and to alter it.
    // We already have a reproduction that makes sure "Our analytics" is not offered when starting from an ad-hoc question (table).
    H.visitQuestion(ORDERS_QUESTION_ID);

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("31.44").click();
    H.popover().contains("=").click();
    cy.wait("@dataset");

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Save").click();

    cy.findByTestId("save-question-modal").within(() => {
      // This part is an actual repro for https://github.com/metabase/metabase/issues/22727
      cy.findByLabelText(/Where do you want to save this/)
        .should("contain.text", "Personal Collection")
        .and("not.contain.text", "Our analytics");

      // This part reproduces https://github.com/metabase/metabase/issues/20717
      cy.findByText(/^Replace original question/).should("not.exist");
    });

    cy.log("metabase#22726");
    H.visitQuestion(ORDERS_QUESTION_ID);

    H.openQuestionActions();
    H.popover().findByText("Duplicate").click();
    cy.findByTextEnsureVisible(
      `${H.getFullName(nocollection)}'s Personal Collection`,
    );

    cy.button("Duplicate").click();
    cy.wait("@createCard").its("response.statusCode").should("eq", 200);
  });
});

describe("issue 23981", () => {
  beforeEach(() => {
    cy.intercept("POST", "/api/dataset").as("dataset");

    H.restore();
    cy.signInAsAdmin();

    // Let's revoke access to "Our analytics" from "All users"
    cy.updateCollectionGraph({
      [ALL_USERS_GROUP]: { root: "none" },
    });

    cy.signIn("nocollection");
  });

  it("should not show the root collection name in breadcrumbs if the user does not have access to it (metabase#23981)", () => {
    H.visitQuestionAdhoc({
      name: "23981",
      dataset_query: {
        database: SAMPLE_DB_ID,
        type: "query",
        query: {
          "source-table": PEOPLE_ID,
        },
      },
    });

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Save").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText(
      `${H.getFullName(nocollection)}'s Personal Collection`,
    ).click();

    H.entityPickerModal().within(() => {
      cy.findByText("Collections").should("be.visible");
      cy.findByText("Our analytics").should("not.exist");
      cy.log('ensure that "Collections" is not selectable');
      cy.findByText("Collections").click();
      cy.button("Select this collection").should("be.disabled");
    });
  });
});

describe("issue 24966", () => {
  const sandboxingQuestion = {
    name: "geadsfasd",
    native: {
      query:
        "select products.category,PRODUCTS.title from PRODUCTS where true [[AND products.CATEGORY = {{category}}]]",
      "template-tags": {
        category: {
          id: "411b40bb-1374-9787-6ffb-20604df56d73",
          name: "category",
          "display-name": "Category",
          type: "text",
        },
      },
    },
    parameters: [
      {
        id: "411b40bb-1374-9787-6ffb-20604df56d73",
        type: "category",
        target: ["variable", ["template-tag", "category"]],
        name: "Category",
        slug: "category",
      },
    ],
  };

  const dashboardFilter = {
    name: "Text",
    slug: "text",
    id: "ec00b255",
    type: "string/=",
    sectionId: "string",
  };

  const dashboardDetails = { parameters: [dashboardFilter] };

  const allCategories = ["Doohickey", "Gadget", "Gizmo", "Widget"];

  function verifyCategoryList(visibleCategories) {
    H.popover().within(() => {
      visibleCategories.forEach((value) => {
        cy.findByText(value).should("be.visible");
      });
      allCategories
        .filter((value) => !visibleCategories.includes(value))
        .forEach((value) => {
          cy.findByText(value).should("not.exist");
        });
    });
  }

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
    H.activateToken("pro-self-hosted");
    H.blockUserGroupPermissions(USER_GROUPS.ALL_USERS_GROUP);

    // Add user attribute to existing user
    cy.request("PUT", `/api/user/${NODATA_USER_ID}`, {
      login_attributes: { attr_cat: "Gizmo" },
    });

    H.createNativeQuestion(sandboxingQuestion).then(({ body: { id } }) => {
      H.visitQuestion(id);

      cy.sandboxTable({
        table_id: PRODUCTS_ID,
        card_id: id,
        attribute_remappings: {
          attr_cat: ["variable", ["template-tag", "category"]],
        },
      });
    });

    // Add the saved products table to the dashboard
    H.createQuestionAndDashboard({
      questionDetails: {
        query: {
          "source-table": PRODUCTS_ID,
          limit: 10,
        },
      },
      dashboardDetails,
    }).then(({ body: { id, card_id, dashboard_id } }) => {
      cy.wrap(dashboard_id).as("dashboardId");
      cy.wrap(id).as("dashcardId");

      // Connect the filter to the card
      cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
        dashcards: [
          {
            id,
            card_id,
            col: 0,
            row: 0,
            size_x: 16,
            size_y: 8,
            parameter_mappings: [
              {
                parameter_id: dashboardFilter.id,
                card_id,
                target: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
              },
            ],
          },
        ],
      });
    });
  });

  it("should correctly fetch field values for a filter when native question is used for sandboxing (metabase#24966)", () => {
    cy.signIn("nodata");
    H.visitDashboard("@dashboardId");
    H.filterWidget().click();
    verifyCategoryList(["Gizmo"]);
    cy.findByLabelText("Gizmo").click();
    cy.button("Add filter").click();
    cy.location("search").should("eq", "?text=Gizmo");

    cy.signInAsSandboxedUser();
    H.visitDashboard("@dashboardId");
    H.filterWidget().click();
    verifyCategoryList(["Widget"]);
    cy.findByLabelText("Widget").click();
    cy.button("Add filter").click();
    cy.location("search").should("eq", "?text=Widget");
    cy.get("@dashcardId").then((id) => {
      H.assertDatasetReqIsSandboxed({ requestAlias: `@dashcardQuery${id}` });
    });
  });
});