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
Fix data model page 403s for read-only remote-synced tables (#84910)
Alexander Polyankin20791369dd3a
diff --git a/docs/developers-guide/api-changelog.md b/docs/developers-guide/api-changelog.mdindex f4b16e0a04d..3d7bacd21f9 100644--- a/docs/developers-guide/api-changelog.md+++ b/docs/developers-guide/api-changelog.md@@ -4,6 +4,18 @@ title: API changelog# Breaking changes to the API interface+## Metabase 0.66.0++- The `can-write-metadata` query parameter of `GET /api/database`, `GET /api/database/:id/schemas`,+ `GET /api/database/:id/schema/:schema` and `GET /api/database/:id/schema/`, and the `can-write` query parameter of+ `GET /api/table`, have been removed and are ignored. To list only what the current user can edit the data model of,+ pass `include_editable_data_model=true` to the database endpoints and `include-editable-data-model=true` to+ `GET /api/table` instead.++- `GET /api/database/:id/metadata?include_hidden=true` no longer returns fields whose visibility is "Do not include"+ (`sensitive`). Pass the new `include_sensitive_fields=true` to get them, for tables whose data model the current user+ can edit, as with `GET /api/table/:id/query_metadata`.+## Metabase 0.65.0- `POST /api/transform` and `PUT /api/transform/:id` answer a target table that already exists withdiff --git a/e2e/support/assets/example_synced_library/collections/main/library/dashboards.yaml b/e2e/support/assets/example_synced_library/collections/main/library/dashboards.yamlnew file mode 100644index 00000000000..850daefd268--- /dev/null+++ b/e2e/support/assets/example_synced_library/collections/main/library/dashboards.yaml@@ -0,0 +1,11 @@+name: Dashboards+entity_id: librarylibrarydashbrd+slug: dashboards+created_at: '2026-09-11T00:00:00Z'+type: library-dashboards+parent_id: librarylibrarylibrary+serdes/meta:+- id: librarylibrarydashbrd+ label: dashboards+ model: Collection+is_remote_synced: truediff --git a/e2e/support/helpers/e2e-datamodel-helpers.ts b/e2e/support/helpers/e2e-datamodel-helpers.tsindex 61b8a4bc670..3109ad9497b 100644--- a/e2e/support/helpers/e2e-datamodel-helpers.ts+++ b/e2e/support/helpers/e2e-datamodel-helpers.ts@@ -177,7 +177,9 @@ function visit({basePath?: string;} = {}) {const normalizedBasePath = getNormalizedBasePath(basePath);- cy.intercept("GET", "/api/database").as("datamodel/visit/databases");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as(+ "datamodel/visit/databases",+ );cy.intercept("GET", "/api/database/*").as("datamodel/visit/database");cy.intercept("GET", "/api/table/*/query_metadata*").as("datamodel/visit/metadata",@@ -945,15 +947,12 @@ function getInterceptsForArea(area: Area) {cy.intercept("PUT", "/api/table").as("updateTables");cy.intercept("PUT", "/api/table/*").as("updateTable");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as("databases");+if (area === "admin") {- cy.intercept("GET", "/api/database?*").as("databases");cy.intercept("GET", "/api/field/*/values").as("fieldValues");cy.intercept("PUT", "/api/table/*").as("updateTable");}-- if (area === "data studio") {- cy.intercept("GET", "/api/database").as("databases");- }}/** source replacement helpers */diff --git a/e2e/test/scenarios/admin/datamodel/datamodel.cy.spec.ts b/e2e/test/scenarios/admin/datamodel/datamodel.cy.spec.tsindex 36f89932f14..36ca67a22ba 100644--- a/e2e/test/scenarios/admin/datamodel/datamodel.cy.spec.ts+++ b/e2e/test/scenarios/admin/datamodel/datamodel.cy.spec.ts@@ -22,7 +22,7 @@ describe("scenarios > admin > datamodel", () => {H.restore();cy.signInAsAdmin();- cy.intercept("GET", "/api/database?*").as("databases");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as("databases");cy.intercept("GET", "/api/database/*/schemas?*").as("schemas");cy.intercept("GET", "/api/table/*/query_metadata*").as("metadata");cy.intercept("GET", "/api/database/*/schema/*").as("schema");diff --git a/e2e/test/scenarios/data-model/data-model-shared-2.cy.spec.ts b/e2e/test/scenarios/data-model/data-model-shared-2.cy.spec.tsindex b7c7d92602a..c8735fe6a5c 100644--- a/e2e/test/scenarios/data-model/data-model-shared-2.cy.spec.ts+++ b/e2e/test/scenarios/data-model/data-model-shared-2.cy.spec.ts@@ -49,15 +49,14 @@ areas.forEach((area) => {cy.intercept("PUT", "/api/table").as("updateTables");cy.intercept("PUT", "/api/table/*").as("updateTable");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as(+ "databases",+ );+if (area === "admin") {- cy.intercept("GET", "/api/database?*").as("databases");cy.intercept("GET", "/api/field/*/values").as("fieldValues");cy.intercept("PUT", "/api/table/*").as("updateTable");}-- if (area === "data studio") {- cy.intercept("GET", "/api/database").as("databases");- }});describe("Field section", () => {diff --git a/e2e/test/scenarios/data-model/data-model-shared-3.cy.spec.ts b/e2e/test/scenarios/data-model/data-model-shared-3.cy.spec.tsindex 814a63045aa..03d05737833 100644--- a/e2e/test/scenarios/data-model/data-model-shared-3.cy.spec.ts+++ b/e2e/test/scenarios/data-model/data-model-shared-3.cy.spec.ts@@ -46,15 +46,14 @@ areas.forEach((area) => {cy.intercept("PUT", "/api/table").as("updateTables");cy.intercept("PUT", "/api/table/*").as("updateTable");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as(+ "databases",+ );+if (area === "admin") {- cy.intercept("GET", "/api/database?*").as("databases");cy.intercept("GET", "/api/field/*/values").as("fieldValues");cy.intercept("PUT", "/api/table/*").as("updateTable");}-- if (area === "data studio") {- cy.intercept("GET", "/api/database").as("databases");- }});describe("Field section", () => {diff --git a/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts b/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.tsindex 76094bc121e..8c841bfaa4c 100644--- a/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts+++ b/e2e/test/scenarios/data-model/data-model-shared-4.cy.spec.ts@@ -37,15 +37,14 @@ areas.forEach((area) => {cy.intercept("PUT", "/api/table").as("updateTables");cy.intercept("PUT", "/api/table/*").as("updateTable");+ cy.intercept({ method: "GET", pathname: "/api/database" }).as(+ "databases",+ );+if (area === "admin") {- cy.intercept("GET", "/api/database?*").as("databases");cy.intercept("GET", "/api/field/*/values").as("fieldValues");cy.intercept("PUT", "/api/table/*").as("updateTable");}-- if (area === "data studio") {- cy.intercept("GET", "/api/database").as("databases");- }});describe("Undos", { tags: "@external" }, () => {diff --git a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.tsindex 47f0ae5d57f..54a2327ee27 100644--- a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts@@ -10,7 +10,8 @@ import type { TableId } from "metabase-types/api";const { H } = cy;const { TablePicker, TableSection, FieldSection, PreviewSection } = H.DataModel;-const { ORDERS, ORDERS_ID, PRODUCTS_ID, REVIEWS, REVIEWS_ID } = SAMPLE_DATABASE;+const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID, REVIEWS, REVIEWS_ID } =+ SAMPLE_DATABASE;describe("scenarios > data studio > datamodel", () => {beforeEach(() => {@@ -745,6 +746,97 @@ describe("scenarios > data studio > datamodel", () => {.should("be.visible");H.main().findByText("Something’s gone wrong").should("not.exist");});++ describe("read-only remote sync", () => {+ function verifyTableIsNotWritable(tableId: TableId) {+ cy.request("GET", `/api/table/${tableId}/query_metadata`)+ .its("body.can_write")+ .should("eq", false);+ }++ function verifyReadOnlyTablePage({ hasTabs }: { hasTabs: boolean }) {+ cy.log("table picker and table");+ TablePicker.getTable("Orders").should("be.visible");+ TablePicker.getTable("Products").should("be.visible");+ TableSection.getNameInput().should("have.value", "Orders");+ if (hasTabs) {+ TableSection.clickFieldsTab();+ }++ cy.log("field metadata, FK target and remapping");+ TableSection.clickField("Product ID");+ FieldSection.getNameInput().should("have.value", "Product ID");+ FieldSection.getSemanticTypeFkTarget().should(+ "have.value",+ "Products → ID",+ );+ FieldSection.getDisplayValuesInput().should(+ "have.value",+ "Use foreign key",+ );+ FieldSection.getDisplayValuesFkTargetInput().should(+ "have.value",+ "Title",+ );++ cy.log("preview");+ FieldSection.getPreviewButton().click();+ PreviewSection.get().findByText("Product ID").should("be.visible");+ PreviewSection.getPreviewTypeInput().findByText("Detail").click();+ PreviewSection.get().findByText("Product ID").should("be.visible");+ PreviewSection.get()+ .findByText("Sorry, you don’t have permission to see that.")+ .should("not.exist");++ cy.log("field values");+ TablePicker.getTable("Products").click();+ TableSection.getNameInput().should("have.value", "Products");+ if (hasTabs) {+ TableSection.clickFieldsTab();+ }+ TableSection.clickField("Category");+ FieldSection.getNameInput().should("have.value", "Category");+ PreviewSection.getPreviewTypeInput().findByText("Filtering").click();+ PreviewSection.get().findByText("Doohickey").should("be.visible");+ }++ beforeEach(() => {+ H.remapDisplayValueToFK({+ display_value: ORDERS.PRODUCT_ID,+ name: "Product ID",+ fk: PRODUCTS.TITLE,+ });+ H.setupGitSync();+ H.createLibrary();+ H.copySyncedLibraryFixture();+ H.commitToRepo();+ H.configureGitAndPullChanges("read-write");+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });+ cy.request("POST", "/api/ee/remote-sync/export", { branch: "main" });+ H.pollForTask({ taskName: "export" });+ H.configureGitAndPullChanges("read-only");++ [ORDERS_ID, PRODUCTS_ID].forEach(verifyTableIsNotWritable);+ });++ it("should show a published table in the data studio data model", () => {+ H.DataModel.visitDataStudio({+ databaseId: SAMPLE_DB_ID,+ schemaId: SAMPLE_DB_SCHEMA_ID,+ tableId: ORDERS_ID,+ });+ verifyReadOnlyTablePage({ hasTabs: true });+ });++ it("should show a published table in the admin data model", () => {+ H.DataModel.visit({+ databaseId: SAMPLE_DB_ID,+ schemaId: SAMPLE_DB_SCHEMA_ID,+ tableId: ORDERS_ID,+ });+ verifyReadOnlyTablePage({ hasTabs: false });+ });+ });});describe(diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.cljindex 2d43eb1d039..ebef4c0ec07 100644--- a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj+++ b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj@@ -173,6 +173,7 @@(let [target-collection (api/check-404 (data-studio.db/collection (:collection_id body)))_ (api/check-400 (= (:type target-collection) collection/library-data-collection-type)(tru "Tables can only be published to Semantic layer/Data collections."))+ _ (api/write-check target-collection)selectors (body->table-selectors body)upstream-ids (all-upstream-table-ids selectors);; Don't move already-published upstream tables; only publish unpublished ones. Get table IDs before update@@ -200,6 +201,8 @@table-ids-to-update (data-studio.db/table-ids-matching-selectors selectors downstream-ids :any)](api/check-403 (can-publish-all-tables? table-ids-to-update))(when (seq table-ids-to-update)+ (run! (comp api/write-check data-studio.db/collection)+ (into #{} (keep :collection_id) (data-studio.db/tables table-ids-to-update)))(data-studio.db/unpublish-tables! table-ids-to-update);; Publish events for audit log and remote sync tracking(let [updated-tables (data-studio.db/tables table-ids-to-update)]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.cljindex 779a7273c28..8d0406bf8ff 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj@@ -46,7 +46,8 @@(defenterprise batch-fetch-table-query-metadatas"Returns the query metadata used to power the Query Builder for the tables specified by`ids`.Options:- - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive (default false)"+ - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive for tables the current+ user can edit the data model of (default false)":feature :sandboxes[ids opts](for [table (schema.table/batch-fetch-query-metadatas* ids opts)]diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.cljindex 05aa6041efc..bdd9d5c1e9d 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj@@ -532,69 +532,6 @@(mt/user-http-request :rasta :get 200 (format "database/%d/schemas" db-id):include_editable_data_model true))))))))-;;; +----------------------------------------------------------------------------------------------------------------+-;;; | can-query and can-write-metadata filter tests |-;;; +----------------------------------------------------------------------------------------------------------------+--(deftest list-databases-can-write-metadata-filter-test- (testing "GET /api/database with can-write-metadata=true filters to only databases with editable tables"- (mt/with-temp [:model/Database {db-1-id :id} {:name "Editable DB"}- :model/Database {db-2-id :id} {:name "Not Editable DB"}- :model/Table t1 {:db_id db-1-id :name "table1" :active true}- :model/Table _ {:db_id db-2-id :name "table2" :active true}]- (mt/with-all-users-data-perms-graph! {db-1-id {:view-data :unrestricted- :create-queries :query-builder- :data-model {:schemas {"" {(u/the-id t1) :all}}}}- db-2-id {:view-data :unrestricted- :create-queries :query-builder- :data-model {:schemas :none}}}- (let [response (->> (mt/user-http-request :rasta :get 200 "database" :can-write-metadata true)- :data- (filter #(#{db-1-id db-2-id} (:id %))))]- (is (= 1 (count response)))- (is (= "Editable DB" (-> response first :name))))))))--(deftest list-databases-with-tables-can-write-metadata-filter-test- (testing "GET /api/database?include=tables&can-write-metadata=true filters tables within databases"- (mt/with-temp [:model/Database {db-id :id} {:name "Test DB"}- :model/Table t1 {:db_id db-id :name "editable_table" :active true}- :model/Table t2 {:db_id db-id :name "not_editable_table" :active true}]- (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted- :create-queries :query-builder- :data-model {:schemas {"" {(u/the-id t1) :all- (u/the-id t2) :none}}}}}- (let [response (->> (mt/user-http-request :rasta :get 200 "database" :include "tables" :can-write-metadata true)- :data- (filter #(= (:id %) db-id))- first)]- (is (= 1 (count (:tables response))))- (is (= "editable_table" (-> response :tables first :name))))))))--(deftest list-schemas-can-write-metadata-filter-test- (testing "GET /api/database/:id/schemas with can-write-metadata=true filters to only schemas with editable tables"- (mt/with-temp [:model/Database {db-id :id} {}- :model/Table t1 {:db_id db-id :schema "editable_schema" :name "t1" :active true}- :model/Table _ {:db_id db-id :schema "not_editable_schema" :name "t2" :active true}]- (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted- :create-queries :query-builder- :data-model {:schemas {"editable_schema" {(u/the-id t1) :all}- "not_editable_schema" :none}}}}- (is (= ["editable_schema"]- (mt/user-http-request :rasta :get 200 (format "database/%d/schemas" db-id) :can-write-metadata true)))))))--(deftest list-schema-tables-can-write-metadata-filter-test- (testing "GET /api/database/:id/schema/:schema with can-write-metadata=true filters to only editable tables"- (mt/with-temp [:model/Database {db-id :id} {}- :model/Table t1 {:db_id db-id :schema "test_schema" :name "editable_table" :active true}- :model/Table t2 {:db_id db-id :schema "test_schema" :name "not_editable_table" :active true}]- (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted- :create-queries :query-builder- :data-model {:schemas {"test_schema" {(u/the-id t1) :all- (u/the-id t2) :none}}}}}- (let [response (mt/user-http-request :rasta :get 200 (format "database/%d/schema/%s" db-id "test_schema") :can-write-metadata true)]- (is (= 1 (count response)))- (is (= "editable_table" (-> response first :name))))))))-(deftest get-field-hydrated-target-with-advanced-perms-test(testing "GET /api/field/:id"(mt/with-temp [:model/Database {db-id :id} {}diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.cljindex 4b01920311f..210a577da30 100644--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj@@ -220,6 +220,22 @@(is (nil? (mt/user-http-request analyst-id :post 204 "ee/data-studio/table/unpublish-tables"{:table_ids [table-id]})))))))))+(deftest unpublish-tables-requires-collection-write-test+ (mt/with-premium-features #{:library :advanced-permissions}+ (testing "users without write access to the collection of a table cannot unpublish it"+ (let [data-analyst-group (perms-group/data-analyst)]+ (mt/with-temp [:model/User {analyst-id :id} {:is_data_analyst true}+ :model/PermissionsGroupMembership _ {:user_id analyst-id :group_id (:id data-analyst-group)}+ :model/Table {table-id :id} {:db_id (mt/id)}+ :model/Collection {collection-id :id} {:type collection/library-data-collection-type}]+ (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"+ {:table_ids [table-id] :collection_id collection-id})+ (mt/with-non-admin-groups-no-collection-perms collection-id+ (perms/grant-collection-read-permissions! data-analyst-group collection-id)+ (mt/user-http-request analyst-id :post 403 "ee/data-studio/table/unpublish-tables"+ {:table_ids [table-id]})+ (is (true? (user-table-fn :is_published table-id)))))))))+(deftest regular-user-cannot-access-data-studio-test(mt/with-premium-features #{:library}(testing "Regular users (not in Data Analysts group) cannot access library endpoints"diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.cljindex f1ff5f45952..50546272606 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj@@ -6,6 +6,7 @@[metabase.collections.models.collection :as collections][metabase.collections.test-utils :as collections.tu][metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.models.interface :as mi][metabase.remote-sync.test-util :as remote-sync.tu][metabase.test :as mt]@@ -437,6 +438,146 @@{:is_published false:collection_id nil})))))))))))+(deftest table-data-model-read-only-test+ (doseq [features [#{} #{:advanced-permissions}]]+ (testing (str "features: " features)+ (mt/with-premium-features features+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}]+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:is_published true :collection_id coll-id}+ (mt/with-temp-vals-in-db :model/Field (mt/id :venues :name) {:visibility_type :sensitive}+ (testing "published tables in remote-synced collections are not writable when remote-sync-type is read-only"+ (is (false? (mi/can-write? (t2/select-one :model/Table (mt/id :venues)))))+ (is (false? (:can_write (mt/user-http-request :crowberto :get 200+ (str "table/" (mt/id :venues) "/query_metadata")+ :include_editable_data_model true)))))+ (testing "admins can read the table"+ (is (= (mt/id :venues)+ (:id (mt/user-http-request :crowberto :get 200 (str "table/" (mt/id :venues))+ :include_editable_data_model true)))))+ (testing "admins get sensitive fields in the table metadata"+ (is (contains? (into #{} (map :id)+ (:fields (mt/user-http-request :crowberto :get 200+ (str "table/" (mt/id :venues) "/query_metadata")+ :include_sensitive_fields true+ :include_editable_data_model true)))+ (mt/id :venues :name))))+ (testing "admins can read the table's fields"+ (is (= (mt/id :venues :name)+ (:id (mt/user-http-request :crowberto :get 200 (str "field/" (mt/id :venues :name))+ :include_editable_data_model true)))))+ (testing "FK targets in the table are returned"+ (is (= (mt/id :venues :id)+ (get-in (mt/user-http-request :crowberto :get 200 (str "field/" (mt/id :checkins :venue_id))+ :include_editable_data_model true)+ [:target :id]))))+ (testing "users without data model permissions cannot read the table's data model"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 (str "table/" (mt/id :venues))+ :include_editable_data_model true))))))))))))++(defn- field-ids+ [fields]+ (into #{} (map :id) fields))++(deftest table-data-model-read-only-permissions-test+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}]+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:is_published true :collection_id coll-id}+ (mt/with-temp-vals-in-db :model/Field (mt/id :venues :name) {:visibility_type :sensitive}+ (let [batch-metadata (fn [user]+ (->> (mt/user-http-request user :post 200 "dataset/query_metadata"+ (assoc (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))+ :settings {:include-sensitive-fields true}))+ :tables+ (some #(when (= (mt/id :venues) (:id %)) %))+ :fields+ field-ids))]+ (testing "admins get sensitive fields of read-only tables from batch query metadata"+ (is (contains? (batch-metadata :crowberto) (mt/id :venues :name))))+ (mt/with-premium-features #{:advanced-permissions}+ (testing "metadata editors can read the data model of read-only tables"+ (mt/with-all-users-data-perms-graph! {(mt/id) {:view-data :unrestricted+ :create-queries :query-builder+ :data-model {:schemas :all}}}+ (is (= (mt/id :venues)+ (:id (mt/user-http-request :rasta :get 200 (str "table/" (mt/id :venues))+ :include_editable_data_model true))))+ (is (contains? (field-ids (:fields (mt/user-http-request :rasta :get 200+ (str "table/" (mt/id :venues) "/query_metadata")+ :include_sensitive_fields true+ :include_editable_data_model true)))+ (mt/id :venues :name)))))+ (testing "users without data model permissions cannot read the data model or sensitive fields"+ (mt/with-all-users-data-perms-graph! {(mt/id) {:view-data :unrestricted+ :create-queries :query-builder+ :data-model {:schemas :none}}}+ (mt/user-http-request :rasta :get 403 (str "table/" (mt/id :venues) "/query_metadata")+ :include_editable_data_model true)+ (mt/user-http-request :rasta :get 403 (str "field/" (mt/id :venues :name))+ :include_editable_data_model true)+ (is (not (contains? (field-ids (:fields (mt/user-http-request :rasta :get 200+ (str "table/" (mt/id :venues) "/query_metadata")+ :include_sensitive_fields true)))+ (mt/id :venues :name))))+ (is (not (contains? (batch-metadata :rasta) (mt/id :venues :name)))))))))))))++(deftest fk-to-read-only-table-test+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}+ :model/Table {pk-table-id :id} {:db_id (mt/id) :is_published true :collection_id coll-id}+ :model/Field {pk-id :id} {:table_id pk-table-id :base_type :type/Integer :semantic_type :type/PK}+ :model/Table {fk-table-id :id} {:db_id (mt/id)}+ :model/Field {fk-id :id} {:table_id fk-table-id :base_type :type/Integer :semantic_type :type/FK+ :fk_target_field_id pk-id}+ :model/Field {other-id :id} {:table_id fk-table-id :base_type :type/Integer}]+ (testing "updating an FK field returns its target in a read-only table"+ (is (= pk-id+ (get-in (mt/user-http-request :crowberto :put 200 (str "field/" fk-id) {:description "FK"})+ [:target :id]))))+ (testing "a writable table can point an FK at a read-only table"+ (is (= pk-id+ (:fk_target_field_id (mt/user-http-request :crowberto :put 200 (str "field/" other-id)+ {:semantic_type :type/FK :fk_target_field_id pk-id}))))))))++(deftest idfields-data-model-read-only-test+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true}]+ (mt/with-temp-vals-in-db :model/Table (mt/id :venues) {:is_published true :collection_id coll-id}+ (doseq [features [#{} #{:advanced-permissions}]]+ (mt/with-premium-features features+ (testing (str "admins see primary keys of read-only tables, features: " features)+ (is (contains? (field-ids (mt/user-http-request :crowberto :get 200 (str "database/" (mt/id) "/idfields")+ :include_editable_data_model true))+ (mt/id :venues :id))))))+ (mt/with-premium-features #{:advanced-permissions}+ (testing "users see primary keys only of tables they can edit the data model of"+ (mt/with-all-users-data-perms-graph! {(mt/id) {:view-data :unrestricted+ :create-queries :query-builder+ :data-model {:schemas {"PUBLIC" {(mt/id :venues) :none+ (mt/id :users) :all}}}}}+ (is (= #{(mt/id :users :id)}+ (field-ids (mt/user-http-request :rasta :get 200 (str "database/" (mt/id) "/idfields")+ :include_editable_data_model true)))))))))))++(deftest publish-tables-read-only-test+ (mt/with-premium-features #{:library}+ (collections.tu/without-library+ (mt/with-temp [:model/Collection {coll-id :id} {:type collections/library-data-collection-type+ :is_remote_synced true}+ :model/Table {table-id :id} {:db_id (mt/id)}]+ (testing "tables cannot be published into a remote-synced collection when remote-sync-type is read-only"+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-only]+ (mt/user-http-request :crowberto :post 403 "ee/data-studio/table/publish-tables"+ {:table_ids [table-id] :collection_id coll-id})+ (is (false? (:is_published (mt/user-http-request :crowberto :get 200 (str "table/" table-id)))))))+ (testing "tables can be published into a remote-synced collection when remote-sync-type is read-write"+ (mt/with-temporary-setting-values [settings/remote-sync-type :read-write]+ (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"+ {:table_ids [table-id] :collection_id coll-id})+ (is (true? (:is_published (mt/user-http-request :crowberto :get 200 (str "table/" table-id)))))))))))+;;; ------------------------------------------------ Field Remote Sync Tests ------------------------------------------------(deftest field-remote-synced-permissions-read-only-testdiff --git a/frontend/src/metabase-types/api/database.ts b/frontend/src/metabase-types/api/database.tsindex 5d785fb3f54..dc10a8362d0 100644--- a/frontend/src/metabase-types/api/database.ts+++ b/frontend/src/metabase-types/api/database.ts@@ -169,7 +169,6 @@ export type ListDatabasesRequest = {include_stubs?: boolean;router_database_id?: DatabaseId;"can-query"?: boolean;- "can-write-metadata"?: boolean;};export interface ListDatabasesResponse {@@ -187,7 +186,6 @@ export interface ListDatabaseSchemasRequest {include_hidden?: boolean;include_editable_data_model?: boolean;"can-query"?: boolean;- "can-write-metadata"?: boolean;}export interface ListDatabaseSchemaTablesRequest {@@ -196,7 +194,6 @@ export interface ListDatabaseSchemaTablesRequest {include_hidden?: boolean;include_editable_data_model?: boolean;"can-query"?: boolean;- "can-write-metadata"?: boolean;include_measures?: boolean;}@@ -208,6 +205,7 @@ export interface ListVirtualDatabaseTablesRequest {export interface GetDatabaseMetadataRequest {id: DatabaseId;include_hidden?: boolean;+ include_sensitive_fields?: boolean;include_editable_data_model?: boolean;remove_inactive?: boolean;skip_fields: true; // make sure we don't get every field of every tablediff --git a/frontend/src/metabase-types/api/table.ts b/frontend/src/metabase-types/api/table.tsindex e1800aa56f0..082d598d486 100644--- a/frontend/src/metabase-types/api/table.ts+++ b/frontend/src/metabase-types/api/table.ts@@ -81,6 +81,7 @@ export type Table = {collection_id: CollectionId | null;is_published: boolean;collection?: Collection;+ can_write?: boolean;};export type TableOwner = Pick<diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.tsxindex 290a9b54eaf..07536869688 100644--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.tsx+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.tsx@@ -24,7 +24,10 @@ import {} from "metabase/metadata/components";import { getTableMetadataQuery } from "metabase/metadata/pages/shared/utils";import { getRawTableFieldId } from "metabase/metadata/utils/field";-import { PLUGIN_LIBRARY } from "metabase/plugins";+import {+ PLUGIN_FEATURE_LEVEL_PERMISSIONS,+ PLUGIN_LIBRARY,+} from "metabase/plugins";import { useParams } from "metabase/router";import {ActionIcon,@@ -79,7 +82,9 @@ function DataModelContent() {data: databasesData,error: databasesError,isLoading: isLoadingDatabases,- } = useListDatabasesQuery();+ } = useListDatabasesQuery(+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,+ );const databaseExists = databasesData?.data?.some((database) => database.id === databaseId,);diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TablePicker/hooks.ts b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TablePicker/hooks.tsindex 267eb5d53a1..bc3a6eefcdd 100644--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TablePicker/hooks.ts+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TablePicker/hooks.ts@@ -9,6 +9,7 @@ import {useLazyListDatabasesQuery,useSearchQuery,} from "metabase/api";+import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";import { isSyncCompleted } from "metabase/utils/syncing";import { UNNAMED_SCHEMA_NAME } from "metabase-lib/v1/metadata/utils/schema";import type { DatabaseId, SchemaName } from "metabase-types/api";@@ -173,7 +174,10 @@ export function useTableLoader() {const [isInitialLoading, setIsInitialLoading] = useState(true);const getDatabases = useCallback(async () => {- const response = await fetchDatabases({}, true);+ const response = await fetchDatabases(+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,+ true,+ );if (databasesRef.current.isError) {// Do not refetch when this call failed previously.// This is to prevent infinite data-loading loop as RTK query does not cache error responses.@@ -204,6 +208,7 @@ export function useTableLoader() {id: databaseId,schema: schemaName,include_hidden: true,+ ...PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,};if (@@ -244,6 +249,7 @@ export function useTableLoader() {const newArgs = {id: databaseId,include_hidden: true,+ ...PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,};if (diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsxindex 47ab6556e96..445da06d64e 100644--- a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx+++ b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx@@ -9,6 +9,7 @@ import {} from "metabase/api";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { getRawTableFieldId } from "metabase/metadata/utils/field";+import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";import { Outlet, useLocation, useParams } from "metabase/router";import { Box, Flex, Stack, rem } from "metabase/ui";import * as Urls from "metabase/urls";@@ -37,7 +38,7 @@ export const DataModelV1 = () => {const parsedParams = parseRouteParams(params);const { databaseId, fieldId, schemaName, tableId } = parsedParams;const { data: databasesData, isLoading: isLoadingDatabases } =- useListDatabasesQuery({ "can-write-metadata": true });+ useListDatabasesQuery(PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps);const databaseExists = databasesData?.data?.some((database) => database.id === databaseId,);diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/hooks/useTableLoader.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/hooks/useTableLoader.tsindex a97352f2f36..15b322cd9c5 100644--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/hooks/useTableLoader.ts+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/hooks/useTableLoader.ts@@ -7,6 +7,7 @@ import {useLazyListDatabaseSchemasQuery,useLazyListDatabasesQuery,} from "metabase/api";+import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";import { isSyncCompleted } from "metabase/utils/syncing";import { UNNAMED_SCHEMA_NAME } from "metabase-lib/v1/metadata/utils/schema";import type { DatabaseId, SchemaName } from "metabase-types/api";@@ -42,7 +43,10 @@ export function useTableLoader(path: TreePath) {const [tree, setTree] = useState<TreeNode>(rootNode());const getDatabases = useCallback(async () => {- const response = await fetchDatabases({ "can-write-metadata": true }, true);+ const response = await fetchDatabases(+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,+ true,+ );if (databasesRef.current.isError) {// Do not refetch when this call failed previously.@@ -74,7 +78,7 @@ export function useTableLoader(path: TreePath) {id: databaseId,schema: schemaName,include_hidden: true,- "can-write-metadata": true,+ ...PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,};if (@@ -112,7 +116,7 @@ export function useTableLoader(path: TreePath) {const newArgs = {id: databaseId,include_hidden: true,- "can-write-metadata": true,+ ...PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,};if (diff --git a/frontend/src/metabase/plugins/oss/permissions.ts b/frontend/src/metabase/plugins/oss/permissions.tsindex fb61e02cadf..36a95589947 100644--- a/frontend/src/metabase/plugins/oss/permissions.ts+++ b/frontend/src/metabase/plugins/oss/permissions.ts@@ -22,6 +22,12 @@ import { DataPermissionValue } from "metabase-types/api";import { definePluginSlot } from "../slot";import type { PluginGroupManagersType } from "../types";+type DataModelQueryProps = {+ include_editable_data_model?: boolean;+};++const DEFAULT_DATA_MODEL_QUERY_PROPS: DataModelQueryProps = {};+// These describe the entries EE plugins contribute to the admin permissions// editor. They live here (not in metabase/admin) because shared plugin code// cannot import from feature modules; metabase/admin/permissions/types@@ -246,8 +252,7 @@ const getDefaultFeatureLevelPermissions = () => ({}) => [] as any,getDownloadWidgetMessageOverride: (_result: Dataset): string | null => null,canDownloadResults: (_result: Dataset): boolean => true,- // Unjustified type cast. FIXME- dataModelQueryProps: {} as any,+ dataModelQueryProps: DEFAULT_DATA_MODEL_QUERY_PROPS,// Unjustified type cast. FIXMEdatabaseDetailsQueryProps: {} as any,});diff --git a/src/metabase/queries/metadata.clj b/src/metabase/queries/metadata.cljindex a34adebcde9..58671fbd70b 100644--- a/src/metabase/queries/metadata.clj+++ b/src/metabase/queries/metadata.clj@@ -98,7 +98,8 @@(mu/defn- batch-fetch-query-metadata*"Fetch dependent metadata for ad-hoc queries.Options:- - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive (default false)"+ - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive in the `:tables` the+ current user can edit the data model of (default false)"[queries :- [:maybe [:sequential ::lib.schema/query]]opts :- [:maybe [:map {:closed true} [:include-sensitive-fields? {:optional true} :boolean]]]](let [source-table-ids (into #{}@@ -147,7 +148,8 @@(defn batch-fetch-query-metadata"Fetch dependent metadata for ad-hoc queries.Options:- - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive (default false)"+ - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive in the `:tables` the+ current user can edit the data model of (default false)"([queries](batch-fetch-query-metadata queries nil))([queries opts]diff --git a/src/metabase/warehouse_schema/field.clj b/src/metabase/warehouse_schema/field.cljindex b3e3539ade4..ae96456c842 100644--- a/src/metabase/warehouse_schema/field.clj+++ b/src/metabase/warehouse_schema/field.clj@@ -5,16 +5,27 @@[metabase.permissions.core :as perms][metabase.util :as u][metabase.warehouse-schema.db :as warehouse-schema.db]- [metabase.warehouse-schema.models.field :as field]+ [metabase.warehouse-schema.table :as schema.table][toucan2.core :as t2]))+(defn hydrate-target-with-data-model-perms+ "Hydrate the FK target of `field` as `:target`, or nil when `field` is not an FK or the current user cannot edit the+ data model of the target's table."+ [field]+ (let [target-field-id (when (isa? (:semantic_type field) :type/FK)+ (:fk_target_field_id field))+ target-field (when-let [target-field (and target-field-id (warehouse-schema.db/field target-field-id))]+ (when (seq (schema.table/filter-tables-by-data-model-perms [(:table (t2/hydrate target-field :table))]))+ target-field))]+ (assoc field :target target-field)))+(defn get-field"Get `Field` with ID."[id {:keys [include-editable-data-model?]}](let [field (-> (api/check-404 (warehouse-schema.db/field id))(t2/hydrate [:table :db] :has_field_values :dimensions :name_field))field (if include-editable-data-model?- (field/hydrate-target-with-write-perms field)+ (hydrate-target-with-data-model-perms field)(t2/hydrate field :target))];; Normal read perms = normal access.;;@@ -25,7 +36,7 @@;;;; Check for permissions and throw 403 if we don't have them...(if include-editable-data-model?- (api/write-check :model/Table (:table_id field))+ (schema.table/check-data-model-perms (:table field))(api/check-403 (mi/can-read? field)));; ...but if we do, return the Field <3field))diff --git a/src/metabase/warehouse_schema/models/field.clj b/src/metabase/warehouse_schema/models/field.cljindex c48f62a0c28..fe88f7c2fdd 100644--- a/src/metabase/warehouse_schema/models/field.clj+++ b/src/metabase/warehouse_schema/models/field.clj@@ -386,16 +386,6 @@:let [target-id (:fk_target_field_id field)]](assoc field :target (id->target-field target-id)))))-(defn hydrate-target-with-write-perms- "Hydrates :target on field, but if the `:fk_target_field_id` field is not writable, `:target` will be nil."- [field]- (let [target-field-id (when (isa? (:semantic_type field) :type/FK)- (:fk_target_field_id field))- target-field (when-let [target-field (and target-field-id (warehouse-schema.db/field target-field-id))]- (when (mi/can-write? (t2/hydrate target-field :table))- target-field))]- (assoc field :target target-field)))-(defn qualified-name-components"Return the pieces that represent a path to `field`, of the form `[table-name parent-fields-name* field-name]`."[{field-name :name, table-id :table_id, parent-id :parent_id}]diff --git a/src/metabase/warehouse_schema/table.clj b/src/metabase/warehouse_schema/table.cljindex 58347b4736e..fa06df20c3d 100644--- a/src/metabase/warehouse_schema/table.clj+++ b/src/metabase/warehouse_schema/table.clj@@ -34,6 +34,19 @@(update field :values field-values/field-values->pairs)field)))))+(defenterprise filter-tables-by-data-model-perms+ "Given a list of tables, removes the ones for which the current user does not have data model editing permissions.+ Admin-only without the advanced-permissions feature. Data model reads, sensitive fields and FK targets rely on this+ filter alone, so it must keep nothing the user cannot edit."+ metabase-enterprise.advanced-permissions.common+ [tables]+ (if (mi/superuser?) tables (empty tables)))++(defn check-data-model-perms+ "Return `table`, or throw a 403 unless the current user has data model editing permissions for it."+ [table]+ (api/check-403 (first (filter-tables-by-data-model-perms [table]))))+(defn- can-access-table-for-query-metadata?"Returns true if the current user can access this table for query metadata.Uses can-read? which checks data permissions, metadata management permissions,@@ -41,10 +54,13 @@[table](mi/can-read? table))-(defn- include-sensitive-fields-for?- "Sensitive fields are hidden from querying, so only list them for users who can edit the table's metadata."- [include-sensitive-fields? table]- (boolean (and include-sensitive-fields? (mi/can-write? table))))+(defn sensitive-fields-table-ids+ "IDs of the `tables` whose sensitive fields to list: none unless `include-sensitive-fields?`, and then only those the+ current user can edit the data model of."+ [include-sensitive-fields? tables]+ (if include-sensitive-fields?+ (into #{} (map :id) (filter-tables-by-data-model-perms tables))+ #{}))(defn fetch-query-metadata*"Returns the query metadata used to power the Query Builder for the given `table`. `include-sensitive-fields?`,@@ -52,11 +68,12 @@[table {:keys [include-sensitive-fields? include-hidden-fields? include-editable-data-model?]}](api/check-404 table)(if include-editable-data-model?- (api/write-check table)+ (check-data-model-perms table)(api/check-403 (can-access-table-for-query-metadata? table)))- (let [include-sensitive-fields? (include-sensitive-fields-for? include-sensitive-fields? table)+ (let [include-sensitive-fields? (contains? (sensitive-fields-table-ids include-sensitive-fields? [table]) (:id table))hydration-keys (cond-> [:db [:fields [:target :has_field_values] :has_field_values :dimensions :name_field]- [:segments :definition_description] [:measures :definition_description] :metrics :collection]+ [:segments :definition_description] [:measures :definition_description] :metrics :collection+ :can_write](premium-features/any-transforms-enabled?) (conj :transform))](-> table(update :collection nil-if-unreadable)@@ -74,7 +91,7 @@"Returns the query metadata used to power the Query Builder for the `table`s specified by `ids`.Options:- `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive for tables the current- user can write (default false)"+ user can edit the data model of (default false)"([ids](batch-fetch-query-metadatas* ids nil))([ids {:keys [include-sensitive-fields?]}]@@ -83,10 +100,11 @@_ (perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables):table-ids (into #{} (map :id) tables)})tables (filter can-access-table-for-query-metadata? tables)+ sensitive-table-ids (sensitive-fields-table-ids include-sensitive-fields? tables)tables (t2/hydrate tables [:fields [:target :has_field_values] :has_field_values :dimensions :name_field] :segments :measures :metrics)](for [table tables:let [excluded-visibility-types (cond-> #{:hidden}- (not (include-sensitive-fields-for? include-sensitive-fields? table))+ (not (contains? sensitive-table-ids (:id table)))(conj :sensitive))]](-> table(m/dissoc-in [:db :details])@@ -104,7 +122,8 @@(defenterprise batch-fetch-table-query-metadatas"Returns the query metadatas used to power the Query Builder for the tables specified by `ids`.Options:- - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive (default false)"+ - `include-sensitive-fields?` - if true, includes fields with visibility_type :sensitive for tables the current+ user can edit the data model of (default false)"metabase-enterprise.sandbox.api.table[ids opts](batch-fetch-query-metadatas* ids opts))@@ -130,36 +149,19 @@[_db-id _schema-name](mi/superuser?))-(defn- admins-only- "OSS fallback for the data-model-perms filters below: editing the data model is admin-only without the- advanced-permissions feature (see [[current-user-can-manage-schema-metadata?]]), so a non-admin keeps nothing.-- These filters must fail closed. `include_editable_data_model=true` means \"skip my query-access check, run my- data-model check instead\", and callers do skip `api/read-check` when it is set, so returning `xs` unfiltered- would switch off the only check the request gets."- [xs]- (if (mi/superuser?) xs (empty xs)))--(defenterprise filter-tables-by-data-model-perms- "Given a list of tables, removes the ones for which the current user does not have data model editing permissions.- Admin-only on OSS."- metabase-enterprise.advanced-permissions.common- [tables]- (admins-only tables))-(defenterprise filter-schema-by-data-model-perms"Given a list of `{:db_id ... :schema ...}` maps, removes the ones for which the current user does not have datamodel editing permissions. Admin-only on OSS."metabase-enterprise.advanced-permissions.common[schemas]- (admins-only schemas))+ (if (mi/superuser?) schemas (empty schemas)))(defenterprise filter-databases-by-data-model-perms"Given a list of databases, removes the ones for which the current user has no data model editing permissions. Ifthe databases are hydrated with their tables, also removes the tables the user cannot edit. Admin-only on OSS."metabase-enterprise.advanced-permissions.common[dbs]- (admins-only dbs))+ (if (mi/superuser?) dbs (empty dbs)))(defn can-read-schema?"Does the current user have permissions to know the schema with `schema-name` exists? (Do they have permissions to see@@ -196,7 +198,7 @@(defn database-schemas"Returns a list of all the schemas with tables found for the database `id`. Excludes schemas with no tables."- [id {:keys [include-editable-data-model? include-hidden? can-query? can-write-metadata?]}]+ [id {:keys [include-editable-data-model? include-hidden? can-query?]}](let [filter-schemas (fn [schemas](if include-editable-data-model?(->> schemas@@ -204,14 +206,11 @@filter-schema-by-data-model-perms(map :schema))(filter (partial can-read-schema? id) schemas)))- ;; For can-query? and can-write-metadata?, we need to filter based on tables in each schemafilter-schemas-by-tables (fn [schemas]- (if (or can-query? can-write-metadata?)+ (if can-query?(let [tables (warehouse-schema.db/active-tables-for-database id)_ (perms/prime-table-perms-cache {:db-ids #{id}})- filtered-tables (cond->> tables- can-query? (filter mi/can-query?)- can-write-metadata? (filter mi/can-write?))+ filtered-tables (filter mi/can-query? tables)allowed-schemas (set (map :schema filtered-tables))](filter #(contains? allowed-schemas %) schemas))schemas))]@@ -230,7 +229,7 @@`include-editable-data-model?` routes the filtering through data-model permissions instead."([db-id schema](schema-tables-list db-id schema {}))- ([db-id schema {:keys [include-hidden? include-editable-data-model? can-query? can-write-metadata? include-measures?]}]+ ([db-id schema {:keys [include-hidden? include-editable-data-model? can-query? include-measures?]}](when-not include-editable-data-model?(api/read-check :model/Database db-id)(api/check-403 (can-read-schema? db-id schema)))@@ -241,8 +240,7 @@filtered-tables (cond->> (if include-editable-data-model?(filter-tables-by-data-model-perms candidate-tables)(filter mi/can-read? candidate-tables))- can-query? (filter mi/can-query?)- can-write-metadata? (filter mi/can-write?))+ can-query? (filter mi/can-query?))hydration-keys (cond-> [](premium-features/any-transforms-enabled?) (conj :transform)include-measures? (conj :measures))]diff --git a/src/metabase/warehouse_schema_rest/api/field.clj b/src/metabase/warehouse_schema_rest/api/field.cljindex cfab0448a90..33e5b8d4043 100644--- a/src/metabase/warehouse_schema_rest/api/field.clj+++ b/src/metabase/warehouse_schema_rest/api/field.clj@@ -21,6 +21,7 @@[metabase.warehouse-schema.models.field :as field][metabase.warehouse-schema.models.field-user-settings :as schema.field-user-settings][metabase.warehouse-schema.models.field-values :as field-values]+ [metabase.warehouse-schema.table :as schema.table][metabase.xrays.core :as xrays][toucan2.core :as t2]))@@ -85,7 +86,10 @@(when target-field-id(check-field-in-same-database! source-field-id target-field-id param-name)(when (not= target-field-id current-target-field-id)- (api/write-check :model/Field target-field-id))))+ (-> (warehouse-schema-rest.db/field target-field-id)+ :table_id+ warehouse-schema-rest.db/table+ schema.table/check-data-model-perms))))(defn- clear-dimension-on-fk-change! [{:keys [dimensions], :as _field}](doseq [{dimension-id :id, dimension-type :type} dimensions]@@ -211,7 +215,7 @@(let [updated (warehouse-schema-rest.db/field id)](u/prog1 (-> updated(t2/hydrate :dimensions :has_field_values)- (field/hydrate-target-with-write-perms))+ (schema.field/hydrate-target-with-data-model-perms))(events/publish-event! :event/field-update {:object <> :user-id api/*current-user-id*})(when (not= effective-type (:effective_type field))(analytics/track-event! :snowplow/simple_event {:event "field_effective_type_change" :target_id id})diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.cljindex 1d635ffbc76..3a3f293cc46 100644--- a/src/metabase/warehouse_schema_rest/api/table.clj+++ b/src/metabase/warehouse_schema_rest/api/table.clj@@ -78,10 +78,11 @@Optional filters:- `can-query=true` - filter to only tables the user can execute queries against- - `can-write=true` - filter to only tables the user can edit metadata for"+ - `include-editable-data-model=true` - filter to only tables the user can edit the data model of, instead of the+ tables the user can read"[_{:keys [term visibility-type data-layer data-source owner-user-id owner-email orphan-only unused-only- published-only can-query can-write include-transform-targets]}+ published-only can-query include-editable-data-model include-transform-targets]}:- [:map {:closed true}[:term {:optional true} :string][:visibility-type {:optional true} :string]@@ -93,7 +94,7 @@[:unused-only {:optional true} [:maybe ms/BooleanValue]][:published-only {:optional true} [:maybe ms/BooleanValue]][:can-query {:optional true} [:maybe ms/BooleanValue]]- [:can-write {:optional true} [:maybe ms/BooleanValue]]+ [:include-editable-data-model {:optional true} [:maybe ms/BooleanValue]][:include-transform-targets {:optional true} [:maybe ms/BooleanValue]]]](let [hydrations (cond-> [:db](premium-features/any-transforms-enabled?) (conj :transform))]@@ -113,9 +114,10 @@(do (perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables):table-ids (into #{} (map :id) tables)})tables)- (into [] (comp (filter mi/can-read?)- (if can-query (filter mi/can-query?) identity)- (if can-write (filter mi/can-write?) identity)+ (if include-editable-data-model+ (schema.table/filter-tables-by-data-model-perms tables)+ (filter mi/can-read? tables))+ (into [] (comp (if can-query (filter mi/can-query?) identity)(map schema.table/present-table))tables))))@@ -139,7 +141,7 @@:- [:map {:closed false}[:data_authority ::data-authority-read]](let [api-perm-check-fn (if include_editable_data_model- api/write-check+ schema.table/check-data-model-permsapi/read-check)](-> (api/check-404 (warehouse-schema-rest.db/table id))api-perm-check-fn@@ -317,13 +319,17 @@"Get metadata about a `Table` useful for running queries.Returns DB, fields, field FKs, and field values.- Passing `include_hidden_fields=true` will include any hidden `Fields` in the response. Defaults to `false`- Passing `include_sensitive_fields=true` will include any sensitive `Fields` in the response. Defaults to `false`.+ Passing `include_hidden_fields=true` will include any hidden `Fields` in the response. Defaults to `false`.+ Passing `include_sensitive_fields=true` will include any sensitive `Fields` in the response if the current user has+ data model editing permissions for the table. Defaults to `false`.- Passing `include_editable_data_model=true` will check that the current user has write permissions for the table's- data model, while `false` checks that they have data access perms for the table. Defaults to `false`.+ Passing `include_editable_data_model=true` will check that the current user has data model editing permissions for+ the table, even when Remote Sync makes the table read-only, while `false` checks that they can read the table.+ Defaults to `false`.- These options are provided for use in the Admin Edit Metadata page."+ The response includes `can_write`, which is false when the user cannot edit the table's metadata right now.++ These options are provided for use in the data model pages."{:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]diff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex 4d1ef753dee..dfeeb194aea 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -63,14 +63,12 @@;;; ----------------------------------------------- GET /api/database ------------------------------------------------(defn- add-tables- "Hydrate tables for each database. Optional `can-query?` and `can-write-metadata?` filters- can be applied to filter tables by permission level."- [dbs & {:keys [can-query? can-write-metadata?]}]+ "Hydrate tables for each database. An optional `can-query?` filter keeps only the tables the user can query."+ [dbs & {:keys [can-query?]}](let [all-tables (warehouses-rest.db/active-visible-tables-for-databases (map :id dbs))_ (perms/prime-table-perms-cache {:db-ids (into #{} (map :id) dbs)})filtered-tables (cond->> (filter mi/can-read? all-tables)- can-query? (filter mi/can-query?)- can-write-metadata? (filter mi/can-write?))+ can-query? (filter mi/can-query?))db-id->tables (group-by :db_id filtered-tables)](for [db dbs](assoc db :tables (get db-id->tables (:id db) [])))))@@ -293,8 +291,7 @@exclude-uneditable-details?include-only-uploadable?router-database-id- can-query?- can-write-metadata?]}]+ can-query?]}](let [filter-on-router-database-id (when (some->> router-database-id(perms/user-has-permission-for-database? api/*current-user-id* :perms/manage-database :yes))router-database-id)@@ -307,7 +304,7 @@;; everything below walks the list one database at a time_ (perms/prime-database-perms-cache {:db-ids (into #{} (map :id) dbs)})](cond-> (-> dbs add-native-perms-info add-transforms-perms-info)- include-tables? (add-tables :can-query? can-query? :can-write-metadata? can-write-metadata?)+ include-tables? (add-tables :can-query? can-query?)include-schemas? add-schemascan-query? (#(filter mi/can-query? %))true add-can-upload-to-dbs@@ -351,9 +348,6 @@* `can-query` will only include DBs for which the current user has query permissions. Default: `false`.- * `can-write-metadata` will only include DBs for which the current user has data model editing permissions- for at least one table in the database. Default: `false`.-Independently of these flags, the implementation of [[metabase.models.interface/to-json]] for `:model/Database` in[[metabase.warehouses.models.database]] uses the implementation of [[metabase.models.interface/can-write?]] for`:model/Database` in [[metabase.warehouses.models.database]] to exclude the `details` field, if the requesting user@@ -361,7 +355,7 @@{:scope api-scope/data-app}[_route-params{:keys [include saved include_editable_data_model exclude_uneditable_details include_only_uploadable include_analytics- include_stubs router_database_id can-query can-write-metadata]}+ include_stubs router_database_id can-query]}:- [:map {:closed true}[:include {:optional true} (mu/with-api-error-message[:maybe [:enum "tables" "schemas"]]@@ -373,31 +367,23 @@[:exclude_uneditable_details {:default false} [:maybe :boolean]][:include_only_uploadable {:default false} [:maybe :boolean]][:router_database_id {:optional true} [:maybe ms/PositiveInt]]- [:can-query {:optional true} [:maybe :boolean]]- [:can-write-metadata {:optional true} [:maybe :boolean]]]]+ [:can-query {:optional true} [:maybe :boolean]]]](let [include-tables? (= include "tables")include-schemas? (= include "schemas")include-saved-questions-tables? (and saved include-tables?)only-editable? (or include_only_uploadable exclude_uneditable_details)- has-table-metadata-perms? (fn [{db-id :id}]- (= :yes (perms/most-permissive-database-permission-for-user- api/*current-user-id*- :perms/manage-table-metadata- db-id)))- db-list-res (cond->> (or (dbs-list :include-tables? include-tables?- :include-schemas? include-schemas?- :include-saved-questions-db? saved- :include-saved-questions-tables? include-saved-questions-tables?- :include-editable-data-model? include_editable_data_model- :exclude-uneditable-details? only-editable?- :include-analytics? include_analytics- :include-stubs? include_stubs- :include-only-uploadable? include_only_uploadable- :router-database-id router_database_id- :can-query? can-query- :can-write-metadata? can-write-metadata)- [])- can-write-metadata (filter has-table-metadata-perms?))]+ db-list-res (or (dbs-list :include-tables? include-tables?+ :include-schemas? include-schemas?+ :include-saved-questions-db? saved+ :include-saved-questions-tables? include-saved-questions-tables?+ :include-editable-data-model? include_editable_data_model+ :exclude-uneditable-details? only-editable?+ :include-analytics? include_analytics+ :include-stubs? include_stubs+ :include-only-uploadable? include_only_uploadable+ :router-database-id router_database_id+ :can-query? can-query)+ [])]{:data db-list-res:total (count db-list-res)}))@@ -537,7 +523,7 @@[](saved-cards-virtual-db-metadata :question :include-tables? true, :include-fields? true))-(defn- db-metadata [id include-hidden? include-editable-data-model? remove_inactive? skip-fields?]+(defn- db-metadata [id include-hidden? include-sensitive-fields? include-editable-data-model? remove_inactive? skip-fields?](let [db (-> (warehouses/get-database id {:include-editable-data-model? include-editable-data-model?})((if skip-fields?#(t2/hydrate % [:tables :segments :metrics])@@ -554,12 +540,12 @@db(update db :tables apply-sandbox-column-filter))](-> db- (update :tables (if include-hidden?- identity- (fn [tables]- (->> tables- (remove :visibility_type)- (map #(m/update-existing % :fields filter-sensitive-fields))))))+ (update :tables (if include-hidden? identity (partial remove :visibility_type)))+ (update :tables (fn [tables]+ (let [sensitive-table-ids (schema.table/sensitive-fields-table-ids include-sensitive-fields? tables)]+ (for [table tables]+ (cond-> table+ (not (sensitive-table-ids (:id table))) (m/update-existing :fields filter-sensitive-fields))))))(update :tables (fn [tables](if-not include-editable-data-model?;; If we're filtering by data model perms, table perm checks were already done by@@ -587,7 +573,10 @@:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id/metadata""Get metadata about a `Database`, including all of its `Tables` and `Fields`. Returns DB, fields, and field values.- By default only non-hidden tables and fields are returned. Passing include_hidden=true includes them.+ By default only non-hidden tables are returned. Passing include_hidden=true includes them.++ Passing include_sensitive_fields=true includes fields with visibility_type sensitive, for tables whose data model the+ current user can edit.Passing include_editable_data_model will only return tables for which the current user has data model editingpermissions. Granting data model permissions to non-admins requires Enterprise Edition code and a token with the@@ -595,14 +584,16 @@DB (aka block permissions), it will return only the DB name, ID and tables, with no additional metadata."[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]- {:keys [include_hidden include_editable_data_model remove_inactive skip_fields]}+ {:keys [include_hidden include_sensitive_fields include_editable_data_model remove_inactive skip_fields]}:- [:map {:closed true}[:include_hidden {:default false} [:maybe ms/BooleanValue]]+ [:include_sensitive_fields {:default false} [:maybe ms/BooleanValue]][:include_editable_data_model {:default false} [:maybe ms/BooleanValue]][:remove_inactive {:default false} [:maybe ms/BooleanValue]][:skip_fields {:default false} [:maybe ms/BooleanValue]]]](db-metadata idinclude_hidden+ include_sensitive_fieldsinclude_editable_data_modelremove_inactiveskip_fields))@@ -754,13 +745,16 @@[:id ms/PositiveInt]]{:keys [include_editable_data_model]} :- [:map {:closed true}[:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]]]- (let [[db-perm-check field-perm-check] (if include_editable_data_model- [check-db-data-model-perms mi/can-write?]- [api/read-check mi/can-read?])]- (db-perm-check (warehouses/get-database id {:include-editable-data-model? true}))- (sort-by (comp u/lower-case-en :name :table)- (filter field-perm-check (-> (database/pk-fields {:id id})- (t2/hydrate :table))))))+ (let [db-perm-check (if include_editable_data_model check-db-data-model-perms api/read-check)+ _ (db-perm-check (warehouses/get-database id {:include-editable-data-model? true}))+ fields (-> (database/pk-fields {:id id})+ (t2/hydrate :table))+ fields (if include_editable_data_model+ (let [table-ids (into #{} (map :id) (schema.table/filter-tables-by-data-model-perms+ (distinct (map :table fields))))]+ (filter (comp table-ids :table_id) fields))+ (filter mi/can-read? fields))]+ (sort-by (comp u/lower-case-en :name :table) fields)));;; ----------------------------------------------- POST /api/database -----------------------------------------------@@ -1274,23 +1268,19 @@"Returns a list of all the schemas with tables found for the database `id`. Excludes schemas with no tables.Optional filters:- - `can-query=true` - filter to only schemas containing tables the user can query- - `can-write-metadata=true` - filter to only schemas containing tables the user can edit metadata for"+ - `can-query=true` - filter to only schemas containing tables the user can query"{:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]{:keys [include_editable_data_modelinclude_hidden- can-query- can-write-metadata]} :- [:map {:closed true}- [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]- [:include_hidden {:default false} [:maybe ms/BooleanValue]]- [:can-query {:optional true} [:maybe :boolean]]- [:can-write-metadata {:optional true} [:maybe :boolean]]]]+ can-query]} :- [:map {:closed true}+ [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]+ [:include_hidden {:default false} [:maybe ms/BooleanValue]]+ [:can-query {:optional true} [:maybe :boolean]]]](schema.table/database-schemas id {:include-editable-data-model? include_editable_data_model:include-hidden? include_hidden- :can-query? can-query- :can-write-metadata? can-write-metadata}))+ :can-query? can-query}));; 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@@ -1338,25 +1328,22 @@instead (#77353).Optional filters:- - `can-query=true` - filter to only tables the user can query- - `can-write-metadata=true` - filter to only tables the user can edit metadata for"+ - `can-query=true` - filter to only tables the user can query"{:scope api-scope/data-app}[{:keys [id schema]} :- [:map {:closed true}[:id ms/PositiveInt][:schema ms/NonBlankString]]- {:keys [include_hidden include_editable_data_model can-query can-write-metadata include_measures]} :- [:map {:closed true}- [:include_hidden {:default false} [:maybe ms/BooleanValue]]- [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]- [:can-query {:optional true} [:maybe :boolean]]- [:can-write-metadata {:optional true} [:maybe :boolean]]- [:include_measures {:optional true} [:maybe :boolean]]]]+ {:keys [include_hidden include_editable_data_model can-query include_measures]} :- [:map {:closed true}+ [:include_hidden {:default false} [:maybe ms/BooleanValue]]+ [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]+ [:can-query {:optional true} [:maybe :boolean]]+ [:include_measures {:optional true} [:maybe :boolean]]]](api/check-404 (seq (schema.table/schema-tables-listidschema{:include-hidden? include_hidden:include-editable-data-model? include_editable_data_model:can-query? can-query- :can-write-metadata? can-write-metadata:include-measures? include_measures}))));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest@@ -1374,25 +1361,22 @@the URL path (#77353).Optional filters:- - `can-query=true` - filter to only tables the user can query- - `can-write-metadata=true` - filter to only tables the user can edit metadata for"+ - `can-query=true` - filter to only tables the user can query";; Tagged for the same reason as the `/:id/schema/:schema` sibling, and it is this route the SDK;; usually reaches: `GET /:id/schemas` reports a nil schema as "", and the sibling's `NonBlankString`;; route regex cannot match an empty segment, so every schemaless warehouse lands here.{:scope api-scope/data-app}[{:keys [id]} :- [:map {:closed true}[:id ms/PositiveInt]]- {:keys [schema include_hidden include_editable_data_model can-query can-write-metadata include_measures]} :- [:map {:closed true}- [:schema {:optional true} [:maybe :string]]- [:include_hidden {:default false} [:maybe ms/BooleanValue]]- [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]- [:can-query {:optional true} [:maybe :boolean]]- [:can-write-metadata {:optional true} [:maybe :boolean]]- [:include_measures {:optional true} [:maybe :boolean]]]]+ {:keys [schema include_hidden include_editable_data_model can-query include_measures]} :- [:map {:closed true}+ [:schema {:optional true} [:maybe :string]]+ [:include_hidden {:default false} [:maybe ms/BooleanValue]]+ [:include_editable_data_model {:default false} [:maybe ms/BooleanValue]]+ [:can-query {:optional true} [:maybe :boolean]]+ [:include_measures {:optional true} [:maybe :boolean]]]](let [opts {:include-hidden? include_hidden:include-editable-data-model? include_editable_data_model:can-query? can-query- :can-write-metadata? can-write-metadata:include-measures? include_measures}](api/check-404 (seq (if (str/blank? schema)(concat (schema.table/schema-tables-list id nil opts)diff --git a/test/metabase/warehouse_schema_rest/api/table_test.clj b/test/metabase/warehouse_schema_rest/api/table_test.cljindex 2df05877702..725622d195c 100644--- a/test/metabase/warehouse_schema_rest/api/table_test.clj+++ b/test/metabase/warehouse_schema_rest/api/table_test.clj@@ -265,6 +265,7 @@:id (mt/id :users)):collection){:schema "PUBLIC"+ :can_write true:name "USERS":display_name "Users":entity_type "entity/UserTable"@@ -358,6 +359,7 @@:id (mt/id :users)):collection){:schema "PUBLIC"+ :can_write false:name "USERS":display_name "Users":entity_type "entity/UserTable"@@ -701,6 +703,7 @@(t2/hydrate (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status] :id (mt/id :categories)):collection){:schema "PUBLIC"+ :can_write false:name "CATEGORIES":display_name "Categories":fields [(merge@@ -1536,7 +1539,7 @@(sync/sync-database! db {:scan :schema})(is (= () (mt/user-http-request :rasta :get 200 (format "table/%d/fks" (mt/id :continent)))))))))-;;; ---------------------------------------- can-query and can-write filter tests ----------------------------------------+;;; -------------------------------------------- can-query filter tests --------------------------------------------(deftest list-tables-can-query-filter-returns-only-queryable-tables-test(testing "can-query=true filters to only queryable tables"@@ -1559,26 +1562,16 @@(is (= 1 (count response)))(is (= "queryable_table" (-> response first :name)))))))-(deftest list-tables-can-write-filter-returns-only-editable-tables-test- (testing "can-write=true filters to only editable tables"- (mt/with-temp [:model/Database {db-id :id} {}- :model/Table {table-1-id :id} {:db_id db-id :name "editable_table" :active true}- :model/Table _ {:db_id db-id :name "not_editable_table" :active true}- :model/PermissionsGroup {pg-id :id :as pg} {}- :model/PermissionsGroupMembership _ {:user_id (mt/user->id :crowberto) :group_id pg-id}]- (t2/delete! :model/DataPermissions :db_id db-id)- ;; Block database-level access- (data-perms/set-database-permission! pg db-id :perms/view-data :unrestricted)- (data-perms/set-database-permission! pg db-id :perms/create-queries :query-builder)- ;; Grant manage-table-metadata to table-1 only (editable)- (data-perms/set-table-permission! pg table-1-id :perms/manage-table-metadata :yes)- ;; table-2 gets no manage-table-metadata (not editable)-- (let [response (->> (mt/user-http-request :crowberto :get 200 "table" :can-write true)- (filter #(= (:db_id %) db-id)))]- ;; crowberto is an admin, so should see all tables when they have manage-table-metadata- (is (>= (count response) 1))- (is (contains? (set (map :name response)) "editable_table"))))))+(deftest list-tables-include-editable-data-model-filter-test+ (testing "include-editable-data-model=true filters to only tables the user can edit the data model of"+ (mt/with-premium-features #{}+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id :active true}]+ (let [table-ids (fn [user]+ (into #{} (comp (filter #(= db-id (:db_id %))) (map :id))+ (mt/user-http-request user :get 200 "table" :include-editable-data-model true)))]+ (is (= #{table-id} (table-ids :crowberto)))+ (is (= #{} (table-ids :rasta))))))));;; ---------------------------------------- /data endpoint permission tests ----------------------------------------diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex 582f21d28da..ebed0ad3e1b 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -994,26 +994,30 @@;; NOTE: test for the exclude_uneditable parameter lives in metabase-enterprise.advanced-permissions.common-test(mt/with-temp-vals-in-db :model/Table (mt/id :categories) {:visibility_type "hidden"}(mt/with-temp-vals-in-db :model/Field (mt/id :venues :price) {:visibility_type "sensitive"}- (testing "GET /api/database/:id/metadata?include_hidden=true"- (let [tables (->> (mt/user-http-request :rasta :get 200 (format "database/%d/metadata?include_hidden=true" (mt/id)))- :tables)]- (is (some (partial = "CATEGORIES") (map :name tables)))- (is (->> tables- (filter #(= "VENUES" (:name %)))- first- :fields- (map :name)- (some (partial = "PRICE"))))))- (testing "GET /api/database/:id/metadata"- (let [tables (->> (mt/user-http-request :rasta :get 200 (format "database/%d/metadata" (mt/id)))- :tables)]- (is (not (some (partial = "CATEGORIES") (map :name tables))))- (is (not (->> tables- (filter #(= "VENUES" (:name %)))- first- :fields- (map :name)- (some (partial = "PRICE"))))))))))+ (let [metadata (fn [user & params]+ (apply mt/user-http-request user :get 200 (format "database/%d/metadata" (mt/id)) params))+ table-names (fn [{:keys [tables]}]+ (set (map :name tables)))+ venues-field-names (fn [{:keys [tables]}]+ (->> tables+ (filter #(= "VENUES" (:name %)))+ first+ :fields+ (map :name)+ set))]+ (testing "GET /api/database/:id/metadata excludes hidden tables and sensitive fields"+ (let [response (metadata :rasta)]+ (is (not (contains? (table-names response) "CATEGORIES")))+ (is (not (contains? (venues-field-names response) "PRICE")))))+ (testing "GET /api/database/:id/metadata?include_hidden=true includes hidden tables but not sensitive fields"+ (let [response (metadata :crowberto :include_hidden true)]+ (is (contains? (table-names response) "CATEGORIES"))+ (is (not (contains? (venues-field-names response) "PRICE")))))+ (testing "GET /api/database/:id/metadata?include_sensitive_fields=true"+ (testing "includes sensitive fields for users who can edit the data model"+ (is (contains? (venues-field-names (metadata :crowberto :include_sensitive_fields true)) "PRICE")))+ (testing "does not include sensitive fields for other users"+ (is (not (contains? (venues-field-names (metadata :rasta :include_sensitive_fields true)) "PRICE")))))))))(deftest fetch-database-metadata-remove-inactive-test(mt/with-temp [:model/Database {db-id :id} {}@@ -3136,8 +3140,6 @@;;; +----------------------------------------------------------------------------------------------------------------+;;; | can-query filter tests |;;; +----------------------------------------------------------------------------------------------------------------+-;; Note: can-write-metadata tests are in metabase-enterprise.advanced-permissions.common-test since they require-;; enterprise features (:perms/manage-table-metadata permission)(deftest list-databases-can-query-filter-test(testing "GET /api/database with can-query=true filters to only queryable databases"