Skip to content

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

Backend hardening (#80003)

Nicola Momettoaf35f7f0af72
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 6ea4f1426f5..fa539cf99ff 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -473,6 +473,7 @@
app-db
config
events
+ lib
models
permissions
premium-features
@@ -623,8 +624,7 @@
collections-rest
{:team "UX West"
- :api #{metabase.collections-rest.api
- metabase.collections-rest.init}
+ :api #{metabase.collections-rest.api}
:uses #{api
app-db
collections
@@ -638,7 +638,6 @@
queries
request
revisions
- settings
tracing
transforms
upload
@@ -735,6 +734,7 @@
permissions
public-sharing
queries
+ query-permissions
query-processor
search
settings
@@ -783,17 +783,19 @@
revisions
util
xrays}
- :model-imports #{:model/Card
+ :model-imports #{:model/Action
+ :model/Card
:model/Collection
:model/Dashboard
:model/DashboardCard
+ :model/DashboardCardSeries
:model/DashboardTab
:model/Field
+ :model/ParameterCard
:model/Pulse
:model/PulseChannel
:model/PulseChannelRecipient
:model/Query
- :model/Table
:model/User}}
data-studio
@@ -831,6 +833,7 @@
batch-processing
collections
events
+ lib-be
models
public-sharing
queries
@@ -974,6 +977,7 @@
eid-translation
embedding
events
+ lib
models
notification
parameters
@@ -1224,9 +1228,9 @@
lib-be
{:team "Querying Platform"
- :api #{metabase.lib-be.core
- metabase.lib-be.init}
- :uses #{lib
+ :api #{metabase.lib-be.core metabase.lib-be.init metabase.lib-be.schema}
+ :uses #{legacy-mbql
+ lib
models
settings
util}
@@ -1550,6 +1554,7 @@
driver
embedding
events
+ lib
models
parameters
permissions
@@ -1675,6 +1680,7 @@
:uses #{api
audit-app
events
+ lib
permissions
premium-features
request
@@ -1759,6 +1765,7 @@
api
dashboards
dashboards-rest
+ documents
events
lib
models
@@ -1856,6 +1863,7 @@
view-log
warehouse-schema}
:model-exports #{:model/Card
+ :model/ParameterCard
:model/Query
:model/QueryExecution
:model/QueryTable
@@ -1879,8 +1887,7 @@
queries-rest
{:team "Querying Platform"
:api #{metabase.queries-rest.api}
- :uses #{analyze
- api
+ :uses #{api
collections
eid-translation
embedding
@@ -1917,7 +1924,7 @@
query-processor
request
util}
- :model-imports #{:model/Card :model/Field}}
+ :model-imports #{:model/Card :model/Field :model/Table}}
query-processor
{:team "Querying Platform"
@@ -2030,22 +2037,27 @@
metabase.revisions.core
metabase.revisions.init}
:uses #{api
+ collections
config
dashboards
events
lib
models
+ parameters
queries
query-permissions
util}
:model-exports #{:model/Revision}
:model-imports #{:model/Card
+ :model/Collection
:model/Dashboard
:model/DashboardCard
+ :model/DashboardCardSeries
:model/DashboardTab
:model/Document
:model/Exploration
:model/Measure
+ :model/ParameterCard
:model/Segment
:model/Transform}}
@@ -2163,6 +2175,7 @@
request
session
settings
+ setup
sso
system
tracing
@@ -2496,7 +2509,6 @@
models
permissions
premium-features
- queries
query-processor
remote-sync
revisions
@@ -2801,6 +2813,7 @@
:uses #{analytics
api
app-db
+ collections
database-routing
driver
events
@@ -2817,7 +2830,8 @@
util
warehouse-schema
xrays}
- :model-imports #{:model/Database
+ :model-imports #{:model/Collection
+ :model/Database
:model/Dimension
:model/Field
:model/FieldValues
@@ -2939,8 +2953,7 @@
enterprise/advanced-config
{:team "UX West"
- :api #{metabase-enterprise.advanced-config.api
- metabase-enterprise.advanced-config.api.logs
+ :api #{metabase-enterprise.advanced-config.api.logs
metabase-enterprise.advanced-config.file
metabase-enterprise.advanced-config.init
metabase-enterprise.advanced-config.settings}
@@ -3026,6 +3039,7 @@
app-db
audit-app
classloader
+ config
driver
lib
models
@@ -3107,6 +3121,7 @@
{:team "Cloud"
:api #{metabase-enterprise.cloud-proxy.api}
:uses #{api
+ lib
premium-features
util
enterprise/harbormaster}}
@@ -3583,6 +3598,7 @@
events
legacy-mbql
lib
+ lib-be
models
permissions
premium-features
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.edn
index 607b14a0d1e..de25c512284 100644
--- a/.clj-kondo/ratchets.edn
+++ b/.clj-kondo/ratchets.edn
@@ -7,12 +7,12 @@
{:ignore-counts {:aliased-namespace-symbol 3
:all 49
:case-symbol-test 1
- :clojure-lsp/unused-public-var 9
+ :clojure-lsp/unused-public-var 10
:def-fn 1
:deprecated-namespace 95
:deprecated-var 79
:discouraged-java-method 3
- :discouraged-namespace 79
+ :discouraged-namespace 80
:discouraged-var 107
:equals-true 1
:main-without-gen-class 1
@@ -44,5 +44,5 @@
:unused-binding 9
:unused-excluded-var 2
:unused-namespace 1
- :unused-private-var 8
+ :unused-private-var 9
:unused-value 1}}
diff --git a/deps.edn b/deps.edn
index 0b6fb941914..89bf6a0b49a 100644
--- a/deps.edn
+++ b/deps.edn
@@ -40,7 +40,7 @@
com.github.blagerweij/liquibase-sessionlock {:mvn/version "1.6.9"} ; session lock for liquibase migrations
com.github.jknack/handlebars {:mvn/version "4.5.3"} ; templating engine
com.github.oliyh/martian-clj-http {:mvn/version "0.2.1"} ; openapi client
- com.github.seancorfield/honeysql {:mvn/version "2.7.1350"} ; Honey SQL 2. SQL generation from Clojure data maps
+ com.github.seancorfield/honeysql {:mvn/version "2.7.1437"} ; Honey SQL 2. SQL generation from Clojure data maps. SECURITY FLOOR: >= 2.7.1392 fixes CVE-2026-61620 (unchecked entity names -> SQL injection). Do not drop below 2.7.1392; do not remove this direct pin (Toucan2 pulls a strictly-worse transitive 2.6.1147).
com.github.seancorfield/next.jdbc {:mvn/version "1.3.1070"} ; Talk to JDBC DBs
com.github.steffan-westcott/clj-otel-api {:mvn/version "0.2.10"} ; Telemetry library
com.github.steffan-westcott/clj-otel-exporter-otlp {:mvn/version "0.2.10"} ; OTLP span exporter (gRPC and HTTP)
diff --git a/docs/configuring-metabase/config-template.md b/docs/configuring-metabase/config-template.md
index 06a17ecb47c..0fd4aa9844f 100644
--- a/docs/configuring-metabase/config-template.md
+++ b/docs/configuring-metabase/config-template.md
@@ -107,7 +107,6 @@ config:
bcc-enabled: true
breakout-bin-width: 10.0
breakout-bins-num: 8
- can-run-adhoc-query-check-threshold: 250
check-for-updates: true
config-from-file-sync-databases: true
csp-img-allowed-hosts: ''
diff --git a/docs/configuring-metabase/environment-variables.md b/docs/configuring-metabase/environment-variables.md
index dd5a75a8b20..1f30d02835c 100644
--- a/docs/configuring-metabase/environment-variables.md
+++ b/docs/configuring-metabase/environment-variables.md
@@ -332,13 +332,6 @@ When using the default binning strategy for a field of type Coordinate (such as
When using the default binning strategy and a number of bins is not provided, this number will be used as the default.
-### `MB_CAN_RUN_ADHOC_QUERY_CHECK_THRESHOLD`
-
-- Type: integer
-- Default: `250`
-
-Maximum number of cards to compute can_run_adhoc_query for. When the number of cards exceeds this threshold, can_run_adhoc_query will return true for all cards without computing actual permissions. Set to 0 to always compute permissions. This only affects how cards are displayed in the query builder and does not affect actual permission enforcement.
-
### `MB_CHECK_FOR_UPDATES`
- Type: boolean
diff --git a/e2e/support/helpers/e2e-downloads-helpers.ts b/e2e/support/helpers/e2e-downloads-helpers.ts
index defa99ef6c8..856805dce97 100644
--- a/e2e/support/helpers/e2e-downloads-helpers.ts
+++ b/e2e/support/helpers/e2e-downloads-helpers.ts
@@ -50,7 +50,9 @@ export const exportFromDashcard = (format: string) => {
cy.findByTestId("download-results-button").click();
});
- cy.findByTestId("status-root-container").should("contain", "Downloading");
+ cy.findByTestId("status-root-container")
+ .invoke("text")
+ .should("match", /Downloading|Done/);
};
/**
diff --git a/e2e/support/helpers/e2e-ui-elements-helpers.js b/e2e/support/helpers/e2e-ui-elements-helpers.js
index 74edcc4ca23..1acb4b8dc3a 100644
--- a/e2e/support/helpers/e2e-ui-elements-helpers.js
+++ b/e2e/support/helpers/e2e-ui-elements-helpers.js
@@ -50,10 +50,6 @@ export function miniPickerBrowseAll() {
return miniPicker().findByText("Browse all");
}
-export function miniPickerOurAnalytics() {
- return miniPicker().findByText("Our analytics");
-}
-
export function miniPickerHeader() {
return cy.findByTestId("mini-picker-header");
}
diff --git a/e2e/test/scenarios/admin/databases.cy.spec.js b/e2e/test/scenarios/admin/databases.cy.spec.js
index 79711e62827..36a8cf82020 100644
--- a/e2e/test/scenarios/admin/databases.cy.spec.js
+++ b/e2e/test/scenarios/admin/databases.cy.spec.js
@@ -675,9 +675,12 @@ describe("scenarios > admin > databases > sample database", () => {
name: "Small orders",
description: "All orders with a total under $100.",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
diff --git a/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts b/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
index f762ea7c584..e9bd372269e 100644
--- a/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
+++ b/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
@@ -244,9 +244,12 @@ describe("issues 55617, 55618", () => {
H.createSegment({
name: "My segment",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
}).then(({ body: segment }) => {
cy.wrap(segment.id).as("segmentId");
diff --git a/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js b/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
index effd5cb1865..6f89921bd89 100644
--- a/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
+++ b/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
@@ -637,9 +637,12 @@ describe("issue 24922", () => {
name: "OrdersSegment",
description: "All orders with a total under $100.",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
};
diff --git a/e2e/test/scenarios/custom-column/custom-column-reproductions-2.cy.spec.js b/e2e/test/scenarios/custom-column/custom-column-reproductions-2.cy.spec.js
index 1c60f11ca20..0be654405de 100644
--- a/e2e/test/scenarios/custom-column/custom-column-reproductions-2.cy.spec.js
+++ b/e2e/test/scenarios/custom-column/custom-column-reproductions-2.cy.spec.js
@@ -1,6 +1,7 @@
const { H } = cy;
import { dedent } from "ts-dedent";
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
const { PRODUCTS, PRODUCTS_ID, ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
@@ -306,18 +307,24 @@ describe("issue 55300", () => {
H.createSegment({
name: "now",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
H.createSegment({
name: "Count",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
diff --git a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
index c26e69383d6..42fc360d748 100644
--- a/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard-reproductions.cy.spec.js
@@ -842,9 +842,12 @@ describe("issue 31697", () => {
name: "Orders segment",
description: "All orders with a total under $100.",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
};
diff --git a/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
index 8175bd209f1..a99b570c226 100644
--- a/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
@@ -1090,8 +1090,12 @@ function createSourceTotalAmountMeasure() {
H.createMeasure({
name: "Total amount",
definition: {
- "source-table": sourceTableId,
- aggregation: [["sum", ["field", amountFieldId, null]]],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": sourceTableId,
+ aggregation: [["sum", ["field", amountFieldId, null]]],
+ },
},
}),
),
diff --git a/e2e/test/scenarios/data-studio/measures/measures-queries.cy.spec.ts b/e2e/test/scenarios/data-studio/measures/measures-queries.cy.spec.ts
index 0beaa968329..6a534fb20c3 100644
--- a/e2e/test/scenarios/data-studio/measures/measures-queries.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/measures/measures-queries.cy.spec.ts
@@ -108,8 +108,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createSegment({
name: "TotalSegment",
definition: {
- "source-table": ORDERS_ID,
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
@@ -129,8 +133,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: "TotalMeasure",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -150,8 +158,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: "TotalMeasure",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -171,8 +183,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: "TotalMeasure",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -317,8 +333,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -342,8 +362,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -367,8 +391,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -400,8 +428,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -439,8 +471,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -467,8 +503,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
useMeasureInAdhocQuestion({
@@ -500,8 +540,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
}).then(({ body: measure }) => {
useMeasureInAdhocQuestion();
@@ -520,8 +564,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -542,8 +590,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
},
}).then(({ body: measure }) => {
H.createQuestion({
@@ -579,8 +631,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.updateMeasure({
id: measure.id,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
});
@@ -598,8 +654,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
}).then(({ body: measure }) => {
H.createQuestion(
@@ -644,8 +704,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
}).then(({ body: measure }) => {
H.createQuestion({
@@ -697,8 +761,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ },
},
}).then(({ body: measure }) => {
H.createQuestion({
@@ -751,8 +819,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
},
})
.then(({ body: measure }) => {
@@ -784,8 +856,12 @@ describe("scenarios > data studio > measures > queries", () => {
H.createMeasure({
name: MEASURE_NAME,
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
},
})
.then(({ body: measure }) => {
diff --git a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
index b7dd6687f37..835e209bb59 100644
--- a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
+++ b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
@@ -1101,8 +1101,12 @@ function createTableBasedSegment({ tableId }: { tableId: TableId }) {
name: TABLE_BASED_SEGMENT_NAME,
description: "Segment description",
definition: {
- "source-table": tableId,
- filter: ["=", 1, 1],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ filter: ["=", 1, 1],
+ },
},
});
}
@@ -1118,8 +1122,12 @@ function createSegmentBasedSegment({
name: SEGMENT_BASED_SEGMENT_NAME,
description: "Segment description",
definition: {
- "source-table": tableId,
- filter: ["segment", segmentId],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ filter: ["segment", segmentId],
+ },
},
});
}
@@ -1205,7 +1213,7 @@ function createDocumentWithTableBasedQuestion({
}) {
return H.createDocument({
name: DOCUMENT_NAME,
- document: [],
+ document: { type: "doc", content: [] },
cards: {
"-1": createMockCard({
id: -1,
@@ -1227,8 +1235,12 @@ function createTableBasedMeasure({ tableId }: { tableId: TableId }) {
return H.createMeasure({
name: TABLE_BASED_MEASURE_NAME,
definition: {
- "source-table": tableId,
- aggregation: [["count"]],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ aggregation: [["count"]],
+ },
},
});
}
@@ -1243,8 +1255,12 @@ function createSegmentBaseMeasure({
return H.createMeasure({
name: SEGMENT_BASED_MEASURE_NAME,
definition: {
- "source-table": tableId,
- aggregation: [["count-where", ["segment", segmentId]]],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ aggregation: [["count-where", ["segment", segmentId]]],
+ },
},
});
}
@@ -1338,8 +1354,12 @@ function createMeasureBasedMeasure({
return H.createMeasure({
name: MEASURE_BASED_MEASURE_NAME,
definition: {
- "source-table": tableId,
- aggregation: ["+", 1, ["measure", measureId]],
+ database: WRITABLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ aggregation: ["+", 1, ["measure", measureId]],
+ },
},
});
}
diff --git a/e2e/test/scenarios/dependencies/dependency-unreferenced-list.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-unreferenced-list.cy.spec.ts
index 71faf42ede8..b833890b55f 100644
--- a/e2e/test/scenarios/dependencies/dependency-unreferenced-list.cy.spec.ts
+++ b/e2e/test/scenarios/dependencies/dependency-unreferenced-list.cy.spec.ts
@@ -1,4 +1,4 @@
-import { USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DB_ID, USERS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
ADMIN_PERSONAL_COLLECTION_ID,
@@ -950,8 +950,12 @@ function createSegmentWithTableDataSource({
return H.createSegment({
name,
definition: {
- "source-table": tableId,
- filter: [["=", "A", "A"]],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ filter: ["=", "A", "A"],
+ },
},
});
}
@@ -968,8 +972,12 @@ function createSegmentWithSegmentClause({
return H.createSegment({
name,
definition: {
- "source-table": tableId,
- filter: ["segment", segmentId],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": tableId,
+ filter: ["segment", segmentId],
+ },
},
});
}
diff --git a/e2e/test/scenarios/filters/filter-bulk.cy.spec.js b/e2e/test/scenarios/filters/filter-bulk.cy.spec.js
index fc34e7e9297..60f803a366f 100644
--- a/e2e/test/scenarios/filters/filter-bulk.cy.spec.js
+++ b/e2e/test/scenarios/filters/filter-bulk.cy.spec.js
@@ -255,9 +255,12 @@ describe("scenarios > filters > bulk filtering", () => {
name: SEGMENT_1_NAME,
description: "All orders with a total under $100.",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: ["<", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
@@ -265,9 +268,12 @@ describe("scenarios > filters > bulk filtering", () => {
name: SEGMENT_2_NAME,
description: "All orders with a discount",
definition: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- filter: [">", ["field", ORDERS.DISCOUNT, null], 0],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: [">", ["field", ORDERS.DISCOUNT, null], 0],
+ },
},
});
});
diff --git a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
index e6b4d6acc6b..50acd750e11 100644
--- a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
+++ b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
@@ -2041,8 +2041,12 @@ describe("scenarios > metrics > explorer", () => {
name: SEGMENT_NAME,
description: "Orders with a total over $100",
definition: {
- "source-table": ORDERS_ID,
- filter: [">", ["field", ORDERS.TOTAL, null], 100],
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ filter: [">", ["field", ORDERS.TOTAL, null], 100],
+ },
},
});
diff --git a/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts b/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts
index bb0fb27284d..f3e82b34783 100644
--- a/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts
+++ b/e2e/test/scenarios/question-reproductions/reproductions.cy.spec.ts
@@ -1,6 +1,6 @@
const { H } = cy;
-import { USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
import type {
@@ -761,74 +761,6 @@ describe("issue 64293", () => {
});
});
-describe("issue 13347", () => {
- beforeEach(() => {
- H.restore();
- H.restore("postgres-12");
- cy.signInAsAdmin();
-
- H.createQuestion({
- name: "13347 structured",
- database: WRITABLE_DB_ID,
- query: {
- "source-table": ORDERS_ID,
- },
- });
-
- H.createNativeQuestion({
- name: "13347 native",
- database: WRITABLE_DB_ID,
- native: {
- query: "SELECT * FROM ORDERS",
- },
- });
-
- // The normal user belongs to the data group, which would otherwise get
- // query-builder access to this database by default. Revoke create-queries so
- // the user cannot build new questions on it - the condition this issue is
- // about. (Avoid view-data "blocked", which needs the advanced-permissions
- // token feature this spec doesn't have.)
- cy.updatePermissionsGraph({
- [USER_GROUPS.DATA_GROUP]: {
- [WRITABLE_DB_ID]: {
- "view-data": "unrestricted",
- "create-queries": "no",
- },
- },
- });
-
- cy.signInAsNormalUser();
-
- cy.visit("/");
- });
-
- it("should not display questions in mini data picker that cannot be used for new questions (metabase#13347)", () => {
- H.startNewQuestion();
- H.miniPickerOurAnalytics().click();
-
- H.miniPicker().within(() => {
- cy.findByText("Orders").should("exist");
-
- cy.findByText("13347 structured").should("not.exist");
- cy.findByText("13347 native").should("not.exist");
- });
- });
-
- it("should not display questions in big data picker that cannot be used for new questions (metabase#13347)", () => {
- H.startNewQuestion();
- H.miniPickerBrowseAll().click();
-
- H.entityPickerModalItem(1, "Sample Database").click();
-
- H.entityPickerModalLevel(2).within(() => {
- cy.findByText("Orders").should("exist");
-
- cy.findByText("13347 structured").should("not.exist");
- cy.findByText("13347 native").should("not.exist");
- });
- });
-});
-
describe("issue #47005", () => {
beforeEach(() => {
H.restore();
diff --git a/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts b/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts
index 8a439050f10..5699c5afdb8 100644
--- a/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts
+++ b/e2e/test/scenarios/question/notebook-native-preview-sidebar.cy.spec.ts
@@ -32,7 +32,6 @@ describe("scenarios > question > notebook > native query preview sidebar", () =>
});
it("smoke test: should show the preview sidebar, update it, and close it", () => {
- const defaultRowLimit = 1048575;
const queryLimit = 2;
cy.intercept("POST", "/api/dataset/native").as("nativeDataset");
@@ -62,7 +61,7 @@ describe("scenarios > question > notebook > native query preview sidebar", () =>
H.NativeEditor.get()
.should("be.visible")
.and("contain", "SELECT")
- .and("contain", defaultRowLimit)
+ .and("not.contain", "LIMIT")
.and("not.contain", queryLimit);
cy.log("It should be possible to close the sidebar");
diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/api.clj b/enterprise/backend/src/metabase_enterprise/action_v2/api.clj
index 2a03660d21d..cc413c85d5e 100644
--- a/enterprise/backend/src/metabase_enterprise/action_v2/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/action_v2/api.clj
@@ -8,6 +8,7 @@
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
[metabase.events.core :as events]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]))
@@ -36,6 +37,27 @@
"All the various ways of referring to an action with the v2 APIs."
[:or ::api-action-id ::api-action-expression])
+(mr/def ::action-value
+ "A single value for an action parameter or an input-row cell: a scalar, or a sequence of them like any other
+ parameter value (`POST /api/action/:id/execute` holds its parameters to the same schema -- a query action binds
+ them to native template tags, which take multiple values)."
+ [:ref ::lib.schema.parameter/parameter.value])
+
+(def ^:private strict-action-value-map
+ [:map-of :keyword [:ref ::action-value]])
+
+(mr/def ::action-value-map
+ "A map from parameter name / column name to a value. Keys are keywords: the request decoder keywordizes map keys and
+ the handler reads them via `(keyword ...)`, so the FE never sends anything else.
+
+ Same shape as [[metabase.actions.schema/execute-parameter-values]]. Decoding sees a permissive
+ `[:map-of :keyword :any]` and the values are validated against, rather than decoded through,
+ [[strict-action-value-map]]."
+ [:and
+ [:map-of :keyword :any]
+ [:fn {:error/message "value must be a scalar, or a sequence of scalars"}
+ #(mr/validate strict-action-value-map %)]])
+
(mr/def ::action-expression
"The internal representation used by our APIs, after we've parsed the relevant ids and fetched their configuration."
;; Expected extensions:
@@ -155,8 +177,8 @@
:- [:map
[:action ::api-action-id-or-expression]
[:scope ::types/scope.raw]
- [:params {:optional true} ms/Map]
- [:input {:optional true} ms/Map]]]
+ [:params {:optional true} ::action-value-map]
+ [:input {:optional true} ::action-value-map]]]
;; This check should be redundant in practice with the permission checks within perform-action!
;; Since test coverage is light and the logic is so simple, we've decided to be extra cautious for now.
(api/check-superuser)
@@ -194,8 +216,8 @@
:- [:map
[:action ::api-action-id-or-expression]
[:scope ::types/scope.raw]
- [:inputs [:sequential {:min 1} ms/Map]]
- [:params {:optional true} [:map-of :keyword :any]]]]
+ [:inputs [:sequential {:min 1} ::action-value-map]]
+ [:params {:optional true} ::action-value-map]]]
;; This check should be redundant in practice with the permission checks within perform-action!
;; Since test coverage is light and the logic is so simple, we've decided to be extra cautious for now.
(api/check-superuser)
@@ -216,7 +238,11 @@
[{}
{}
;; TODO support for bulk actions
- {:keys [action scope input]}]
+ {:keys [action scope input]}
+ :- [:map
+ [:action ::api-action-id-or-expression]
+ [:scope ::types/scope.raw]
+ [:input {:optional true} ::action-value-map]]]
:- :metabase-enterprise.action-v2.execute-form/action-description
;; This check should be redundant in practice with the permission checks within perform-action!
;; Since test coverage is light and the logic is so simple, we've decided to be extra cautious for now.
diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj b/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj
index 61b9fdea2a1..ce6def7965f 100644
--- a/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj
+++ b/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj
@@ -42,6 +42,7 @@
;; We may also want to filter based on the type of interaction that caused the change (e.g., grid, workflow, etc)
(t2/select :model/Undo
:batch_num [:in
+ ^:allow-subquery
{:select [[[(if undo? :max :min) :batch_num]]]
:from [(t2/table-name :model/Undo)]
:where [:and
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj
deleted file mode 100644
index 8fabff3653d..00000000000
--- a/enterprise/backend/src/metabase_enterprise/advanced_config/api.clj
+++ /dev/null
@@ -1,47 +0,0 @@
-(ns metabase-enterprise.advanced-config.api
- "HTTP surface for the EE advanced-config module — runtime apply of a
- `config.yml` upload."
- (:require
- [clojure.java.io :as io]
- [metabase-enterprise.advanced-config.file :as advanced-config.file]
- [metabase-enterprise.advanced-config.file.api-keys]
- [metabase-enterprise.advanced-config.file.databases]
- [metabase-enterprise.advanced-config.file.settings]
- [metabase-enterprise.advanced-config.file.users]
- [metabase.api.common :as api]
- [metabase.api.macros :as api.macros]
- [metabase.util.malli.schema :as ms]
- [metabase.util.yaml :as yaml]))
-
-(comment
- metabase-enterprise.advanced-config.file.api-keys/keep-me
- metabase-enterprise.advanced-config.file.databases/keep-me
- metabase-enterprise.advanced-config.file.settings/keep-me
- metabase-enterprise.advanced-config.file.users/keep-me)
-
-(api.macros/defendpoint :post "/" :- :nil
- "Apply an uploaded `config.yml` to this instance. Runs the same per-section
- initializers (`settings`, `databases`, `users`, `api-keys`, ...)
- the boot-time loader runs. Superuser-only.
-
- Unlike the boot-time loader, `{{env VAR}}` templates are NOT expanded — the
- file's values are inserted verbatim, so an admin's upload can't read
- server-side environment variables it didn't intend to."
- {:multipart true}
- [_route-params
- _query-params
- _body
- {{config "config"} :multipart-params, :as _request}
- :- [:map
- [:multipart-params
- [:map
- ["config" [:map
- [:filename :string]
- [:tempfile (ms/InstanceOfClass java.io.File)]]]]]]]
- (api/check-superuser)
- (let [tempfile (:tempfile config)]
- (try
- (advanced-config.file/initialize! (yaml/from-file tempfile))
- (finally
- (io/delete-file tempfile :silently))))
- nil)
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj
index 2a27bca5bea..6cdb88c564f 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj
@@ -23,7 +23,7 @@
month :- ms/PositiveInt]
(let [date-part (fn [part-key part-value]
(if (= (mdb/db-type) :postgres)
- [:= [:date_part [:inline (name part-key)] :started_at] [:inline part-value]]
+ [:= [:date_part ^:allow-raw-sql [:inline (name part-key)] :started_at] [:inline part-value]]
[:= [part-key :started_at] [:inline part-value]]))
results (t2/select :query_execution
{:order-by [[:started_at :desc]]
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/api/application.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/api/application.clj
index 22bfce53a99..9701eb4587e 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/api/application.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/api/application.clj
@@ -50,7 +50,8 @@
[:skip-graph {:default false} [:maybe ms/BooleanValue]]
[:force {:default false} [:maybe ms/BooleanValue]]]
body :- [:map
- [:revision ms/Int]
+ [:revision {:optional true} [:maybe ms/Int]]
+ [:force {:optional true} [:maybe :boolean]]
;; keyed by group id, then by application permission type -- `dejsonify-graph` below turns both back
;; into the int and keyword the graph is stored under
[:groups [:map-of :keyword [:map-of :keyword ms/NonBlankString]]]]]
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj
index 4c6f77c5633..0d00522338f 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj
@@ -19,8 +19,15 @@
(def ^:private ApplicationPermissionsGraph
[:map {:closed true}
[:revision :int]
+ [:force {:optional true} [:maybe :boolean]]
[:groups [:map-of ms/PositiveInt GroupPermissionsGraph]]])
+(def ^:private ApplicationPermissionsGraphUpdate
+ [:map {:closed true}
+ [:revision {:optional true} [:maybe :int]]
+ [:force {:optional true} [:maybe :boolean]]
+ [:groups [:map-of ms/PositiveInt GroupPermissionsGraph]]])
+
;; -------------------------------------------------- Fetch Graph ---------------------------------------------------
(defn- group-id->permissions-set
@@ -73,10 +80,10 @@
"Update the application Permissions graph.
This works just like [[metabase.permissions-rest.data-permissions.graph/update-data-perms-graph!]], but for
Application permissions; refer to that function's extensive documentation to get a sense for how this works."
- ([new-graph :- ApplicationPermissionsGraph]
+ ([new-graph :- ApplicationPermissionsGraphUpdate]
(update-graph! new-graph false))
- ([new-graph :- ApplicationPermissionsGraph
+ ([new-graph :- ApplicationPermissionsGraphUpdate
force? :- :boolean]
(let [old-graph (graph)
old-perms (:groups old-graph)
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index 504a7fc7d66..ea552fcd983 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -6,7 +6,6 @@
`enterprise/backend/README.md` for more details."
(:require
[metabase-enterprise.action-v2.api]
- [metabase-enterprise.advanced-config.api]
[metabase-enterprise.advanced-config.api.logs]
[metabase-enterprise.advanced-permissions.api.routes]
[metabase-enterprise.api.core :as ee.api]
@@ -108,7 +107,6 @@
routes here and follow the convention."
;; Postponing a granular flag for :actions until it's used more widely.
{"/action-v2" (premium-handler metabase-enterprise.action-v2.api/routes :table-data-editing)
- "/advanced-config" (api.macros/ns-handler 'metabase-enterprise.advanced-config.api)
"/advanced-permissions" (premium-handler metabase-enterprise.advanced-permissions.api.routes/routes :advanced-permissions)
"/ai-controls" (premium-handler metabase-enterprise.metabot.api.routes/routes :ai-controls)
"/audit-app" (premium-handler metabase-enterprise.audit-app.api.routes/routes :audit-app)
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj b/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj
index 5aaaf7a0308..dd9289bc47d 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj
@@ -95,19 +95,19 @@
:from [[(t2/table-name :model/Table) :table]]
:where [:and [:= :table.db_id audit-db-id]
;; Exclude DATABASECHANGELOG, DATABASECHANGELOGLOCK, and QRTZ_* tables, they are not metabase managed
- [:not= :table.name [:inline "DATABASECHANGELOG"]]
- [:not= :table.name [:inline "DATABASECHANGELOGLOCK"]] ;; new instances do not get this file, but existing instances may have it
- [:not [:like :table.name [:inline "QRTZ_%"]]]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Table) :self_table]]
- :where [:and
- [:= :self_table.db_id :table.db_id]
- [:or
- [:= :self_table.schema [:lower :table.schema]]
- [:and
- [:= :self_table.schema [:inline "public"]]
- [:= :table.schema nil]]]
- [:= :self_table.name [:lower :table.name]]]}]]]})]
+ [:not= :table.name "DATABASECHANGELOG"]
+ [:not= :table.name "DATABASECHANGELOGLOCK"] ;; new instances do not get this file, but existing instances may have it
+ [:not [:like :table.name "QRTZ_%"]]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/Table) :self_table]]
+ :where [:and
+ [:= :self_table.db_id :table.db_id]
+ [:or
+ [:= :self_table.schema [:lower :table.schema]]
+ [:and
+ [:= :self_table.schema "public"]
+ [:= :table.schema nil]]]
+ [:= :self_table.name [:lower :table.name]]]}]]]})]
(when (seq table-ids-to-update)
(t2/update! :model/Table :id [:in (map :id table-ids-to-update)]
{:schema "public" :name [:lower :name]})))
@@ -116,20 +116,20 @@
:inner-join [[(t2/table-name :model/Table) :table]
[:= :table.id :field.table_id]]
:where [:and [:= :table.db_id audit-db-id]
- [:not= :table.name [:inline "DATABASECHANGELOG"]]
- [:not [:like :table.name [:inline "QRTZ_%"]]]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Field) :self_field]]
- :inner-join [[(t2/table-name :model/Table) :self_table]
- [:= :self_table.id :self_field.table_id]]
- :where [:and
- [:= :self_table.db_id :table.db_id]
- [:or
- [:= :self_table.schema [:lower :table.schema]]
- [:and
- [:= :self_table.schema [:inline "public"]]
- [:= :table.schema nil]]]
- [:= :self_field.name [:lower :field.name]]]}]]]})]
+ [:not= :table.name "DATABASECHANGELOG"]
+ [:not [:like :table.name "QRTZ_%"]]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/Field) :self_field]]
+ :inner-join [[(t2/table-name :model/Table) :self_table]
+ [:= :self_table.id :self_field.table_id]]
+ :where [:and
+ [:= :self_table.db_id :table.db_id]
+ [:or
+ [:= :self_table.schema [:lower :table.schema]]
+ [:and
+ [:= :self_table.schema "public"]
+ [:= :table.schema nil]]]
+ [:= :self_field.name [:lower :field.name]]]}]]]})]
(when (seq field-ids-to-update)
(t2/update! :model/Field :id [:in (map :id field-ids-to-update)]
{:name [:lower :name]})))
@@ -166,9 +166,9 @@
(t2/update! :model/Field
{:table_id
[:in
- {:select [:id]
- :from [(t2/table-name :model/Table)]
- :where [:= :db_id audit-db-id]}]}
+ ^:allow-subquery {:select [:id]
+ :from [(t2/table-name :model/Table)]
+ :where [:= :db_id audit-db-id]}]}
{:name [:upper :name]})
(fix-h2-card-metadata! audit-db-id))
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/interface.clj b/enterprise/backend/src/metabase_enterprise/audit_app/interface.clj
index 2babed84c6c..e80885b80a5 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/interface.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/interface.clj
@@ -28,11 +28,16 @@
(throw (ex-info (str (tru "Unable to run internal query function: cannot resolve {0}" query-type))
{:status-code 400})))
+(def ^:private loadable-namespaces
+ "Namespaces that register [[internal-query]] methods on load, and so may be loaded on demand to resolve an
+ `:internal` query. Add to this when you add an audit page."
+ #{"metabase-enterprise.audit-app.pages.queries"})
+
(defn resolve-internal-query
"Invoke the internal query with `query-type` (invokes the corresponding implementation of [[internal-query]])."
[query-type & args]
(let [query-type (keyword query-type)
ns-str (namespace query-type)]
- (when ns-str
+ (when (contains? loadable-namespaces ns-str)
(classloader/require (symbol ns-str)))
(apply internal-query query-type args)))
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/pages/common.clj b/enterprise/backend/src/metabase_enterprise/audit_app/pages/common.clj
index cdd882d6a81..d1c5d14d65e 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/pages/common.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/pages/common.clj
@@ -189,9 +189,19 @@
(for [field fields-to-search]
[:like (lowercase-field field) query-string]))))))
+(def ^:private sort-directions
+ "The only two directions an audit page may sort in."
+ {"asc" :asc, "desc" :desc})
+
(defn add-sort-clause
"Add an `ORDER BY` clause to `query` on `sort-column` and `sort-direction`.
Most queries will just have explicit default `ORDER BY` clauses"
[query sort-column sort-direction]
- (sql.helpers/order-by query [(keyword sort-column) (keyword sort-direction)]))
+ (let [direction (get sort-directions (u/lower-case-en (if (keyword? sort-direction)
+ (name sort-direction)
+ (str sort-direction))))]
+ (when-not direction
+ (throw (ex-info (tru "Invalid sort direction: {0}" (pr-str sort-direction))
+ {:status-code 400})))
+ (sql.helpers/order-by query [(keyword sort-column) direction])))
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/pages/common/cards.clj b/enterprise/backend/src/metabase_enterprise/audit_app/pages/common/cards.clj
index ccca3f62afd..72a8a8ff6d9 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/pages/common/cards.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/pages/common/cards.clj
@@ -3,34 +3,38 @@
(def latest-qe
"HoneySQL for a CTE to get latest QueryExecution for a Card. Exactly one row per Card."
;; A Card can have several executions sharing its max started_at, so we need to rank them first.
- [:latest_qe {:select [:card_id :error :started_at]
- :from [[{:select [:query_execution.card_id
- :query_execution.error
- :query_execution.started_at
- [[:over [[:row_number]
- {:partition-by [:query_execution.card_id]
- :order-by [[:query_execution.id :desc]]}
- :rn]]]]
- :from [:query_execution]
- ;; Join on BOTH card_id and started_at, because some cards share the same timestamp.
- :join [[{:select [:card_id [:%max.started_at :started_at]]
- :from [:query_execution]
- :group-by [:card_id]} :inner_qe]
- [:and
- [:= :query_execution.card_id :inner_qe.card_id]
- [:= :query_execution.started_at :inner_qe.started_at]]]}
- :ranked_qe]]
- :where [:= :rn [:inline 1]]}])
+ [:latest_qe ^:allow-subquery
+ {:select [:card_id :error :started_at]
+ :from [[^:allow-subquery
+ {:select [:query_execution.card_id
+ :query_execution.error
+ :query_execution.started_at
+ [[:over [[:row_number]
+ ^:allow-subquery
+ {:partition-by [:query_execution.card_id]
+ :order-by [[:query_execution.id :desc]]}
+ :rn]]]]
+ :from [:query_execution]
+ ;; Join on BOTH card_id and started_at, because some cards share the same timestamp.
+ :join [[^:allow-subquery
+ {:select [:card_id [:%max.started_at :started_at]]
+ :from [:query_execution]
+ :group-by [:card_id]} :inner_qe]
+ [:and
+ [:= :query_execution.card_id :inner_qe.card_id]
+ [:= :query_execution.started_at :inner_qe.started_at]]]}
+ :ranked_qe]]
+ :where [:= :rn [:inline 1]]}])
(def query-runs
"HoneySQL for a CTE to include the total number of queries for each Card forever."
- [:query_runs {:select [:card_id
- [:%count.* :count]]
- :from [:query_execution]
- :group-by [:card_id]}])
+ [:query_runs ^:allow-subquery {:select [:card_id
+ [:%count.* :count]]
+ :from [:query_execution]
+ :group-by [:card_id]}])
(def dashboards-count
"HoneySQL for a CTE to enumerate the dashboards for a Card."
- [:dash_card {:select [:card_id [:%count.* :count]]
- :from [:report_dashboardcard]
- :group-by [:card_id]}])
+ [:dash_card ^:allow-subquery {:select [:card_id [:%count.* :count]]
+ :from [:report_dashboardcard]
+ :group-by [:card_id]}])
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj b/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
index f8d79cab651..b477b6c54a1 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
@@ -71,7 +71,7 @@
[(common/user-full-name :u) :user_name]
[:card.updated_at :updated_at]
;; Keep this last: the streaming xform strips it positionally and hoists it to the root.
- [[:over [[:count :*] {} :total_count]]]]
+ [[:over [[:count :*] ^:allow-subquery {} :total_count]]]]
:from [[:report_card :card]]
:left-join [[:collection :coll] [:= :card.collection_id :coll.id]
[:metabase_database :db] [:= :card.database_id :db.id]
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/query_processor/middleware/handle_audit_queries.clj b/enterprise/backend/src/metabase_enterprise/audit_app/query_processor/middleware/handle_audit_queries.clj
index b30f25a1840..fa25aa57f66 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/query_processor/middleware/handle_audit_queries.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/query_processor/middleware/handle_audit_queries.clj
@@ -39,7 +39,9 @@
:xform ...}"
(:require
[clojure.data :as data]
+ [malli.core :as mc]
[metabase-enterprise.audit-app.interface :as audit.i]
+ [metabase.config.core :as config]
[metabase.permissions.core :as perms]
[metabase.premium-features.core :as premium-features :refer [defenterprise]]
[metabase.query-processor.error-type :as qp.error-type]
@@ -47,7 +49,9 @@
[metabase.query-processor.schema :as qp.schema]
[metabase.query-processor.util :as qp.util]
[metabase.util.i18n :refer [tru]]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
(defn- check-results-and-metadata-keys-match
"Primarily for dev and debugging purposes. We can probably take this out when shipping the finished product."
@@ -80,18 +84,36 @@
(def InternalQuery
"Schema for a valid `internal` type query."
- [:map
- [:type [:enum :internal "internal"]]
- [:fn [:and
- :string
- [:fn
- {:error/message "namespace-qualified symbol serialized as a string"}
- (fn [s]
- (try
- (when-let [symb (some-> s symbol)]
- (qualified-symbol? symb))
- (catch Throwable _)))]]]
- [:args {:optional true} [:sequential :any]]])
+ (into [:multi {:dispatch :fn}]
+ (cond-> [["metabase-enterprise.audit-app.pages.queries/bad-table"
+ [:map
+ [:type [:enum :internal "internal"]]
+ [:args {:optional true}
+ [:maybe [:or
+ [:= []]
+ [:tuple
+ [:maybe :string]
+ [:maybe [:enum "card_id" "card_name" "error_substr" "collection_id" "collection_name"
+ "database_id" "database_name" "schema_name" "table_id" "table_name"
+ "last_run_at" "total_runs" "num_dashboards" "user_id" "user_name"
+ "updated_at"]]
+ [:maybe [:enum "asc" "desc"]]]]]]
+ [:limit {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:offset {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]]]]
+ config/is-test?
+ (conj [::mc/default
+ [:map
+ [:type [:enum :internal "internal"]]
+ [:args {:optional true} [:maybe [:sequential :any]]]
+ [:limit {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:offset {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]]]))))
+
+(defn- validate-internal-query
+ [query]
+ (when-not (mr/validate InternalQuery query)
+ (throw (ex-info (tru "Invalid internal query.")
+ {:type qp.error-type/invalid-query
+ :status-code 400}))))
(def ^:dynamic *additional-query-params*
"Additional `internal` query params beyond `type`, `fn`, and `args`. These are bound to this dynamic var which is a
@@ -120,8 +142,9 @@
reduce-legacy-results) rff results))
(mu/defn- process-internal-query
- [{qualified-fn-str :fn, args :args, :as query} :- InternalQuery
- rff :- ::qp.schema/rff]
+ [{qualified-fn-str :fn, args :args, :as query}
+ rff :- ::qp.schema/rff]
+ (validate-internal-query query)
;; Make sure current user is a superuser or has monitoring permissions
(perms/check-has-application-permission :monitoring)
;; Make sure audit app is enabled (currently the only use case for internal queries). We can figure out a way to
diff --git a/enterprise/backend/src/metabase_enterprise/cache/strategies.clj b/enterprise/backend/src/metabase_enterprise/cache/strategies.clj
index 10b63ccf6b6..89ed68763fa 100644
--- a/enterprise/backend/src/metabase_enterprise/cache/strategies.clj
+++ b/enterprise/backend/src/metabase_enterprise/cache/strategies.clj
@@ -46,16 +46,18 @@
[3 "database" (:database_id card)]
[4 "root" 0]]
:when model-id]
+ ^:allow-subquery
{:from [:cache_config]
:select [:id
[[:inline i] :ordering]]
:where [:and
- [:= :model [:inline model]]
+ [:= :model model]
[:= :model_id model-id]]})
- q {:from [[{:union-all qs} :unused_alias]]
- :select [:id]
- :order-by :ordering
- :limit [:inline 1]}
+ q ^:allow-subquery
+ {:from [[^:allow-subquery {:union-all qs} :unused_alias]]
+ :select [:id]
+ :order-by :ordering
+ :limit [:inline 1]}
item (t2/select-one :model/CacheConfig :id q)]
(cache/card-strategy item card)))
diff --git a/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj b/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj
index 175049c2b84..ec8262e42bb 100644
--- a/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj
+++ b/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj
@@ -99,37 +99,37 @@
(let [queries
(for [{:keys [model model_id config]} cache-configs]
(let [rerun-cutoff (duration-ago config)]
- {:nest
- {:select [[:q.query :query]
- [:qc.query_hash :cache-hash]
- [:qe.card_id :card-id]
- [:qe.dashboard_id :dashboard-id]
- [[:count :q.query_hash] :count]]
- :from [[(t2/table-name :model/Query) :q]]
- :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]
- [(t2/table-name :model/QueryCache) :qc] [:= :qc.query_hash :qe.cache_hash]]
- :where [:and
- (case model
- "question" [:= :qe.card_id model_id]
- "dashboard" [:= :qe.dashboard_id model_id])
- [:<= :qc.updated_at rerun-cutoff]
- ;; This is a safety check so that we don't scan all of query_execution -- if a query
- ;; has not been executed at all in the last month (including cache hits) we won't bother
- ;; refreshing it again.
- [:>= :qe.started_at (duration-ago {:duration 30 :unit "days"})]
- [:= :qe.error nil]
- [:= :qe.is_sandboxed false]
- (if parameterized?
- [:and
- [:= :qe.parameterized true]
- ;; Only rerun a parameterized query if it's had a cache hit within the last caching window
- [:= :qe.cache_hit true]
- ;; Don't factor the last cache refresh into whether we should rerun a parameterized query
- [:not= :qe.context (name :cache-refresh)]]
- [:= :qe.parameterized false])]
- :group-by [:q.query_hash :q.query :qc.query_hash :qe.card_id :qe.dashboard_id]}}))]
+ ^:allow-subquery {:nest
+ ^:allow-subquery {:select [[:q.query :query]
+ [:qc.query_hash :cache-hash]
+ [:qe.card_id :card-id]
+ [:qe.dashboard_id :dashboard-id]
+ [[:count :q.query_hash] :count]]
+ :from [[(t2/table-name :model/Query) :q]]
+ :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]
+ [(t2/table-name :model/QueryCache) :qc] [:= :qc.query_hash :qe.cache_hash]]
+ :where [:and
+ (case model
+ "question" [:= :qe.card_id model_id]
+ "dashboard" [:= :qe.dashboard_id model_id])
+ [:<= :qc.updated_at rerun-cutoff]
+ ;; This is a safety check so that we don't scan all of query_execution -- if a query
+ ;; has not been executed at all in the last month (including cache hits) we won't bother
+ ;; refreshing it again.
+ [:>= :qe.started_at (duration-ago {:duration 30 :unit "days"})]
+ [:= :qe.error nil]
+ [:= :qe.is_sandboxed false]
+ (if parameterized?
+ [:and
+ [:= :qe.parameterized true]
+ ;; Only rerun a parameterized query if it's had a cache hit within the last caching window
+ [:= :qe.cache_hit true]
+ ;; Don't factor the last cache refresh into whether we should rerun a parameterized query
+ [:not= :qe.context (name :cache-refresh)]]
+ [:= :qe.parameterized false])]
+ :group-by [:q.query_hash :q.query :qc.query_hash :qe.card_id :qe.dashboard_id]}}))]
{:select [:u.query :u.cache-hash :u.card-id :u.dashboard-id :u.count]
- :from [[{:union queries} :u]]}))
+ :from [[^:allow-subquery {:union queries} :u]]}))
(defn- select-parameterized-queries
"Given a list of parameterized query definitions from the Query table with additional :count and :card-id keys,
diff --git a/enterprise/backend/src/metabase_enterprise/cloud_proxy/api.clj b/enterprise/backend/src/metabase_enterprise/cloud_proxy/api.clj
index 7159c654311..d089eab8218 100644
--- a/enterprise/backend/src/metabase_enterprise/cloud_proxy/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/cloud_proxy/api.clj
@@ -4,6 +4,8 @@
[metabase-enterprise.harbormaster.client :as hm.client]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.premium-features.core :as premium-features]
[metabase.util :as m.util]
[metabase.util.malli.schema :as ms]))
@@ -21,12 +23,12 @@
Parameters are named in kebab-case only, which is both what the FE sends (see
`frontend/src/metabase/api/cloud-proxy.ts`) and what the Store client expects. Callers that spell them
- snake_case (`new_plan_alias`) are normalized by the `:decode/api` hook before validation, so the decoded
- body is forwarded as-is. The parameters span operations rather than being keyed by them because a body
+ snake_case (`new_plan_alias`) are normalized by [[lib.schema.common/normalize-map]] before validation, so the
+ decoded body is forwarded as-is. The parameters span operations rather than being keyed by them because a body
schema cannot dispatch on the `:operation-id` route param, and each is therefore optional -- the operation
itself rejects parameters that don't belong to it, or are missing. Adding an operation to the allowlists
above means adding its parameters here."
- [:map {:decode/api {:enter m.util/deep-kebab-keys}}
+ [:map {:decode/normalize lib.schema.common/normalize-map}
[:plan-alias {:optional true} ms/NonBlankString]
[:new-plan-alias {:optional true} ms/NonBlankString]
[:force-end-trial {:optional true} :boolean]])
@@ -58,4 +60,4 @@
(def routes
"`/api/ee/cloud-proxy` routes."
- (api.macros/ns-handler *ns*))
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj b/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj
index 4d0b4e51bbe..487443eae0d 100644
--- a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj
@@ -65,7 +65,8 @@
(api.macros/defendpoint :post
"/upload-dictionary"
"Upload a CSV of content translations"
- {:multipart true}
+ {:multipart {:max-file-size (long max-content-translation-dictionary-size-bytes)
+ :max-file-count 1}}
[_route_params
_query-params
_body
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
index 654139440d1..41d70f499cb 100644
--- a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
@@ -86,7 +86,7 @@
(defn- table-subquery
"Create a subquery that selects table IDs matching the given WHERE clause."
[where]
- {:select [:id] :from [(t2/table-name :model/Table)] :where where})
+ ^:allow-subquery {:select [:id] :from [(t2/table-name :model/Table)] :where where})
(defn- traverse-graph
"Recursively traverse the remapping graph starting from initial-ids.
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj
index 370a5b7fc43..1bba40503fc 100644
--- a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj
@@ -55,6 +55,7 @@
:feature :library
[table-id-column {:keys [user-id is-superuser?]}]
[:in table-id-column
+ ^:allow-subquery
{:select [:id]
:from [:metabase_table]
:where [:and
@@ -75,6 +76,7 @@
:feature :library
[{:keys [user-id is-superuser?]} perm-types active-only?]
(when (contains? (set perm-types) :perms/create-queries)
+ ^:allow-subquery
{:select [[:mt.id :id]
[(h2x/literal :perms/create-queries) :perm_type]
[(h2x/literal :query-builder) :perm_value]]
diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/api.clj b/enterprise/backend/src/metabase_enterprise/database_routing/api.clj
index fef4a8a77d5..a2a8b745d4c 100644
--- a/enterprise/backend/src/metabase_enterprise/database_routing/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/database_routing/api.clj
@@ -35,7 +35,7 @@
[:sequential
[:map
[:name ms/NonBlankString]
- [:details ms/Map]]]]]]
+ [:details ms/KeywordizedMap]]]]]]
(api/check-400 (t2/exists? :model/DatabaseRouter :database_id router_database_id))
(api/check-400 (not (t2/exists? :model/Database :router_database_id router_database_id :name [:in (map :name destinations)]))
"A destination database with that name already exists.")
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
index 80dc2c5c179..470aae489fa 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
@@ -220,19 +220,20 @@
(when api/*is-superuser?*
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:id] :from [table-name]}]])
+ [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]])
:model/Transform
(cond
api/*is-superuser?*
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:id] :from [table-name]}]]
+ [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]]
api/*is-data-analyst?*
[:and
[:= entity-type-field (name entity-type)]
[:in entity-id-field
+ ^:allow-subquery
{:select [:id]
:from [table-name]
:where [:in :source_database_id
@@ -251,35 +252,39 @@
api/*current-user-id* :perms/create-queries))))
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:id]
- :from [table-name]
- :where [:and
- ;; Filter by collection visibility
- (collection/visible-collection-filter-clause
- (keyword (name table-name) "collection_id")
- {:include-archived-items include-archived-items}
- {:current-user-id api/*current-user-id*
- :is-superuser? api/*is-superuser?*})
- ;; Filter by entity archived status
- (case include-archived-items
- :exclude [:= archived-column false]
- :only [:= archived-column true]
- :all nil)]}]]))
+ [:in entity-id-field
+ ^:allow-subquery
+ {:select [:id]
+ :from [table-name]
+ :where [:and
+ ;; Filter by collection visibility
+ (collection/visible-collection-filter-clause
+ (keyword (name table-name) "collection_id")
+ {:include-archived-items include-archived-items}
+ {:current-user-id api/*current-user-id*
+ :is-superuser? api/*is-superuser?*})
+ ;; Filter by entity archived status
+ (case include-archived-items
+ :exclude [:= archived-column false]
+ :only [:= archived-column true]
+ :all nil)]}]]))
;; Table with visible-filter-clause; inactive/hidden tables are always included
;; so that dependencies broken by dropped tables stay visible
:model/Table
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:id]
- :from [table-name]
- :where [:in id-column
- (perms/visible-table-filter-select
- :id
- {:user-id api/*current-user-id*
- :is-superuser? api/*is-superuser?*}
- {:perms/view-data :unrestricted
- :perms/create-queries :query-builder})]}]]
+ [:in entity-id-field
+ ^:allow-subquery
+ {:select [:id]
+ :from [table-name]
+ :where [:in id-column
+ (perms/visible-table-filter-select
+ :id
+ {:user-id api/*current-user-id*
+ :is-superuser? api/*is-superuser?*}
+ {:perms/view-data :unrestricted
+ :perms/create-queries :query-builder})]}]]
;; Segment/Measure with table permissions and archived filtering
(:model/Segment :model/Measure)
@@ -287,28 +292,31 @@
table-id-column (keyword (name table-name) "table_id")]
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:id]
- :from [table-name]
- :where [:and
- ;; Check that user can see the table this entity belongs to
- [:in table-id-column
- {:select [:metabase_table.id]
- :from [:metabase_table]
- ;; using this clause because we had to change the mi/visible-filter-clause
- ;; to allow returning CTE based filters
- ;; TODO(ed 2025-12-16: support using CTES in filters in dependency graph)
- :where [:in :metabase_table.id
- (perms/visible-table-filter-select
- :id
- {:user-id api/*current-user-id*
- :is-superuser? api/*is-superuser?*}
- {:perms/view-data :unrestricted
- :perms/create-queries :query-builder})]}]
- ;; Filter by archived status
- (case include-archived-items
- :exclude [:= archived-column false]
- :only [:= archived-column true]
- :all nil)]}]])))))
+ [:in entity-id-field
+ ^:allow-subquery
+ {:select [:id]
+ :from [table-name]
+ :where [:and
+ ;; Check that user can see the table this entity belongs to
+ [:in table-id-column
+ ^:allow-subquery
+ {:select [:metabase_table.id]
+ :from [:metabase_table]
+ ;; using this clause because we had to change the mi/visible-filter-clause
+ ;; to allow returning CTE based filters
+ ;; TODO(ed 2025-12-16: support using CTES in filters in dependency graph)
+ :where [:in :metabase_table.id
+ (perms/visible-table-filter-select
+ :id
+ {:user-id api/*current-user-id*
+ :is-superuser? api/*is-superuser?*}
+ {:perms/view-data :unrestricted
+ :perms/create-queries :query-builder})]}]
+ ;; Filter by archived status
+ (case include-archived-items
+ :exclude [:= archived-column false]
+ :only [:= archived-column true]
+ :all nil)]}]])))))
deps.dependency-types/dependency-type->model)))
(defn- broken-entities-filter-clause
@@ -325,11 +333,13 @@
(keep (fn [[entity-type _model]]
[:and
[:= entity-type-field (name entity-type)]
- [:in entity-id-field {:select [:analyzed_entity_id]
- :from [:analysis_finding]
- :where [:and
- [:= :analysis_finding.analyzed_entity_type (name entity-type)]
- [:= :analysis_finding.result false]]}]])
+ [:in entity-id-field
+ ^:allow-subquery
+ {:select [:analyzed_entity_id]
+ :from [:analysis_finding]
+ :where [:and
+ [:= :analysis_finding.analyzed_entity_type (name entity-type)]
+ [:= :analysis_finding.result false]]}]])
deps.dependency-types/dependency-type->model)))
(defn- readable-graph-dependencies
@@ -656,9 +666,9 @@
:card [:case
[:not= :entity.dashboard_id nil] :dashboard.name
[:not= :entity.document_id nil] :document.name
- :else [:coalesce :collection.name [:inline (:name root-collection)]]]
+ :else [:coalesce :collection.name (:name root-collection)]]
:table :database.name
- (:transform :snippet :dashboard :document) [:coalesce :collection.name [:inline (:name root-collection)]]
+ (:transform :snippet :dashboard :document) [:coalesce :collection.name (:name root-collection)]
:sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]
(:segment :measure) :table.display_name)}))
@@ -755,25 +765,27 @@
(case sort-column
:location {:sort-column location-column
:sort-joins (location-joins-for-entity entity-type)}
- :dependents-errors {:sort-column {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))
- [:concat :error_type [:inline "-"] [:coalesce :error_detail [:inline ""]]]
- [:composite :error_type :error_detail])]]]]
- :from [:analysis_finding_error]
- :where [:and
- [:= :source_entity_id :entity.id]
- [:= :source_entity_type (name entity-type)]
- (visible-entities-filter-clause
- :analyzed_entity_type :analyzed_entity_id)]}
+ :dependents-errors {:sort-column ^:allow-subquery
+ {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))
+ [:concat :error_type "-" [:coalesce :error_detail ""]]
+ [:composite :error_type :error_detail])]]]]
+ :from [:analysis_finding_error]
+ :where [:and
+ [:= :source_entity_id :entity.id]
+ [:= :source_entity_type (name entity-type)]
+ (visible-entities-filter-clause
+ :analyzed_entity_type :analyzed_entity_id)]}
:sort-joins #{}}
- :dependents-with-errors {:sort-column {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))
- [:concat :analyzed_entity_id [:inline "-"] :analyzed_entity_type]
- [:composite :analyzed_entity_id :analyzed_entity_type])]]]]
- :from [:analysis_finding_error]
- :where [:and
- [:= :source_entity_id :entity.id]
- [:= :source_entity_type (name entity-type)]
- (visible-entities-filter-clause
- :analyzed_entity_type :analyzed_entity_id)]}
+ :dependents-with-errors {:sort-column ^:allow-subquery
+ {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))
+ [:concat :analyzed_entity_id "-" :analyzed_entity_type]
+ [:composite :analyzed_entity_id :analyzed_entity_type])]]]]
+ :from [:analysis_finding_error]
+ :where [:and
+ [:= :source_entity_id :entity.id]
+ [:= :source_entity_type (name entity-type)]
+ (visible-entities-filter-clause
+ :analyzed_entity_type :analyzed_entity_id)]}
:sort-joins #{}}
{:sort-column name-column
:sort-joins #{}}))
@@ -797,9 +809,10 @@
(when (= query-type :breaking)
{:include-archived-items :all}))
all-required-joins (set/union filter-joins sort-joins)
- select-clause [[[:inline (name entity-type)] :entity_type]
+ select-clause [[^:allow-raw-sql [:inline (name entity-type)] :entity_type]
[:entity.id :entity_id]
[sort-column :sort_key]]]
+ ^:allow-subquery
{(if (= query-type :breaking) :select-distinct :select) select-clause
:from [[table-name :entity]]
:left-join (build-left-joins join all-required-joins)
@@ -868,7 +881,7 @@
:include-personal-collections include-personal-collections
:sort-column sort-column})
selected-types)
- union-query {:union-all union-queries}
+ union-query ^:allow-subquery {:union-all union-queries}
all-ids (->> (t2/query (assoc union-query
:order-by [[:sort_key sort-direction] [:entity_id sort-direction] [:entity_type sort-direction]]
:offset offset
@@ -925,7 +938,7 @@
:include-personal-collections include-personal-collections
:sort-column sort-column})
selected-types)
- union-query {:union-all union-queries}
+ union-query ^:allow-subquery {:union-all union-queries}
all-ids (->> (t2/query (assoc union-query
:order-by [[:sort_key sort-direction] [:entity_id sort-direction] [:entity_type sort-direction]]
:offset offset
@@ -1015,7 +1028,7 @@
{:include-archived-items :exclude})]
dep-types (conj [:in :afe.analyzed_entity_type dep-types])
card-types (conj [:or
- [:!= :afe.analyzed_entity_type [:inline "card"]]
+ [:!= :afe.analyzed_entity_type "card"]
[:in :rc.type card-types]]))
broken-entity-pairs
(t2/query (cond-> {:select-distinct [[:afe.analyzed_entity_type :entity_type]
@@ -1028,7 +1041,7 @@
:where where-clause}
card-types (assoc :left-join [[:report_card :rc]
[:and
- [:= :afe.analyzed_entity_type [:inline "card"]]
+ [:= :afe.analyzed_entity_type "card"]
[:= :rc.id :afe.analyzed_entity_id]]])))
nodes (map (fn [{:keys [entity_type entity_id]}]
[(keyword entity_type) entity_id])
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
index 50288e49890..9e0b1018623 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
@@ -287,19 +287,19 @@
[db-id]
(t2/select-fn-set :table_id :model/AnalysisFinding
{:select [:field_updates/table_id]
- :from [[{:select [[:table/id :table_id]
- [:table/updated_at :last_table_update]
- [[:max :field/updated_at] :last_field_update]]
- :from [[(t2/table-name :model/Table) :table]]
- :left-join [[(t2/table-name :model/Field) :field]
- [:= :field/table_id :table/id]]
- :where [:= :table/db_id db-id]
- :group-by [:table/id
- :table/updated_at]}
+ :from [[^:allow-subquery {:select [[:table/id :table_id]
+ [:table/updated_at :last_table_update]
+ [[:max :field/updated_at] :last_field_update]]
+ :from [[(t2/table-name :model/Table) :table]]
+ :left-join [[(t2/table-name :model/Field) :field]
+ [:= :field/table_id :table/id]]
+ :where [:= :table/db_id db-id]
+ :group-by [:table/id
+ :table/updated_at]}
:field_updates]]
:inner-join [[(t2/table-name :model/Dependency) :dep]
[:and
- [:= :dep/to_entity_type [:inline "table"]]
+ [:= :dep/to_entity_type "table"]
[:= :field_updates/table_id :dep/to_entity_id]]
[(t2/table-name :model/AnalysisFinding) :finding]
[:and
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj
index 6321583628c..0f8163e91e4 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj
@@ -196,6 +196,7 @@
(methodical/defmethod events/publish-event! ::update-card-dependents-metadata
[_ {{:keys [id dataset_query]} :object :keys [previous-object]}]
(when (and (premium-features/has-feature? :dependencies)
+ (seq dataset_query)
(not (lib/any-native-stage? dataset_query)))
(async/submit!
(fn []
diff --git a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
index 4148799e308..6ecdcecd6ac 100644
--- a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
@@ -48,11 +48,12 @@
[:or
[:and
[:!= :collection_id (:id (audit/default-audit-collection))]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Collection) :sample_coll]]
- :where [:and
- [:= :sample_coll.is_sample true]
- [:= :sample_coll.id :report_card.collection_id]]}]]]
+ [:not [:exists ^:allow-subquery
+ {:select [1]
+ :from [[(t2/table-name :model/Collection) :sample_coll]]
+ :where [:and
+ [:= :sample_coll.is_sample true]
+ [:= :sample_coll.id :report_card.collection_id]]}]]]
[:is :collection_id nil]]]}))
(defn- has-user-created-tenants? []
diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj b/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj
index fbce2930e8b..3bd711f9547 100644
--- a/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj
+++ b/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj
@@ -10,6 +10,12 @@
^{:clj-kondo/ignore [:deprecated-namespace :discouraged-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.util.i18n :refer [tru]]))
+(defenterprise remove-impersonation-keys
+ "Pre-processing middleware. Removes the internal `:impersonation/*` keys from the top-level query."
+ :feature :none
+ [query]
+ (dissoc query :impersonation/role :impersonation/admin? :impersonation/allow-write?))
+
(defenterprise apply-impersonation
"Pre-processing middleware. Validates that native queries on impersonated databases are single SELECT statements,
and adds an impersonation role key to the query for non-admin users. Currently used solely for caching."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj
index 016b89bca88..7ded0de1fa2 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj
@@ -17,6 +17,7 @@
scope/all-yes-permissions
(let [stored (t2/select :model/MetabotPermissions
{:where [:in :group_id
+ ^:allow-subquery
{:select [:group_id]
:from [(t2/table-name :model/PermissionsGroupMembership)]
:where [:= :user_id user-id]}]})
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
index fb6f153497f..57389bef7b0 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
@@ -49,17 +49,17 @@
user-id (conj [:= :c.user_id user-id])
(seq date) (conj (date-string->constraints :c.created_at date))
(and group-id (not= group-id (:id (perms/all-users-group))))
- (conj [:exists {:select [1]
- :from [[:permissions_group_membership :pgm]]
- :where [:and
- [:= :pgm.user_id :c.user_id]
- [:= :pgm.group_id group-id]]}])
+ (conj [:exists ^:allow-subquery {:select [1]
+ :from [[:permissions_group_membership :pgm]]
+ :where [:and
+ [:= :pgm.user_id :c.user_id]
+ [:= :pgm.group_id group-id]]}])
tenant-id
- (conj [:exists {:select [1]
- :from [[:core_user :u]]
- :where [:and
- [:= :u.id :c.user_id]
- [:= :u.tenant_id tenant-id]]}]))
+ (conj [:exists ^:allow-subquery {:select [1]
+ :from [[:core_user :u]]
+ :where [:and
+ [:= :u.id :c.user_id]
+ [:= :u.tenant_id tenant-id]]}]))
clauses (remove nil? clauses)]
(when (seq clauses)
(into [:and] clauses))))
@@ -95,13 +95,13 @@
[[:count [:case [:= :m.role "assistant"] 1]] :assistant_message_count]
[[:coalesce [:sum :m.total_tokens] 0] :total_tokens]
[[:max :m.created_at] :last_message_at]
- [{:select [:mm.profile_id]
- :from [[:metabot_message :mm]]
- :where [:and
- [:= :mm.conversation_id :c.id]
- [:= :mm.role "assistant"]]
- :order-by [[:mm.created_at :asc] [:mm.id :asc]]
- :limit 1}
+ [^:allow-subquery {:select [:mm.profile_id]
+ :from [[:metabot_message :mm]]
+ :where [:and
+ [:= :mm.conversation_id :c.id]
+ [:= :mm.role "assistant"]]
+ :order-by [[:mm.created_at :asc] [:mm.id :asc]]
+ :limit 1}
:profile_id]
;; Cache tokens are only recorded per LLM call in `ai_usage_log`
;; (`metabot_message` stores prompt+completion only), so this is a
@@ -109,9 +109,9 @@
;; would fan out against the `metabot_message` join and inflate
;; every aggregate above.
[[:coalesce
- {:select [[[:sum :aul.cache_read_tokens]]]
- :from [[:ai_usage_log :aul]]
- :where [:= :aul.conversation_id :c.id]}
+ ^:allow-subquery {:select [[[:sum :aul.cache_read_tokens]]]
+ :from [[:ai_usage_log :aul]]
+ :where [:= :aul.conversation_id :c.id]}
0]
:cache_read_tokens]]
:from [[:metabot_conversation :c]]
diff --git a/enterprise/backend/src/metabase_enterprise/mfa/management.clj b/enterprise/backend/src/metabase_enterprise/mfa/management.clj
index 9caf65ab737..e8a997c54d5 100644
--- a/enterprise/backend/src/metabase_enterprise/mfa/management.clj
+++ b/enterprise/backend/src/metabase_enterprise/mfa/management.clj
@@ -199,12 +199,12 @@
(def ^:private confirmed-totp-exists
;; enrollment state is the auth_identity.confirmed_at COLUMN (queryable), not the encrypted
;; credentials JSON
- [:exists {:select [1]
- :from [:auth_identity]
- :where [:and
- [:= :auth_identity.user_id :core_user.id]
- [:= :auth_identity.provider "totp"]
- [:not= :auth_identity.confirmed_at nil]]}])
+ [:exists ^:allow-subquery {:select [1]
+ :from [:auth_identity]
+ :where [:and
+ [:= :auth_identity.user_id :core_user.id]
+ [:= :auth_identity.provider "totp"]
+ [:not= :auth_identity.confirmed_at nil]]}])
(def ^:private unenrolled-user-where
;; active personal users without a confirmed TOTP enrollment
@@ -241,11 +241,11 @@
;; a correlated scalar subselect rather than a join: the unique (user_id, provider) constraint
;; guarantees at most one row, and joining would force qualifying every selected column, since
;; auth_identity also has id/created_at/updated_at
- [[{:select [:auth_identity.confirmed_at]
- :from [:auth_identity]
- :where [:and
- [:= :auth_identity.user_id :core_user.id]
- [:= :auth_identity.provider "totp"]]}
+ [[^:allow-subquery {:select [:auth_identity.confirmed_at]
+ :from [:auth_identity]
+ :where [:and
+ [:= :auth_identity.user_id :core_user.id]
+ [:= :auth_identity.provider "totp"]]}
:enrolled_at]])
(defn- search-where
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
index 89f9d6acdb0..e7a23cce83a 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj
@@ -631,12 +631,12 @@
i.e. unsynced local work (an already-synced entity's removal is a normal reconcile, not data loss).
`id-col` is the qualified id column of the model's own table (see [[model-id-column]])."
[model-type id-col]
- [:not [:exists {:select [1]
- :from [:remote_sync_object]
- :where [:and
- [:= :remote_sync_object.model_type model-type]
- [:= :remote_sync_object.model_id id-col]
- [:= :remote_sync_object.status "synced"]]}]])
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [:remote_sync_object]
+ :where [:and
+ [:= :remote_sync_object.model_type model-type]
+ [:= :remote_sync_object.model_id id-col]
+ [:= :remote_sync_object.status "synced"]]}]])
(defn check-deletion-conflicts
"Detects local entities of all-or-nothing models (specs with :all-on-setting-disable) that an import
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
index ff51b6e14e4..d6ddf1769b4 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
@@ -97,9 +97,9 @@
[:card_id {:optional true} [:maybe ms/PositiveInt]]]]
(when card_id
(let [db (t2/select-one :model/Database
- :id {:select [:t.db_id]
- :from [[(t2/table-name :model/Table) :t]]
- :where [:= :t.id table_id]})]
+ :id ^:allow-subquery {:select [:t.db_id]
+ :from [[(t2/table-name :model/Table) :t]]
+ :where [:= :t.id table_id]})]
(when (not (driver.u/supports? (:engine db) :saved-question-sandboxing db))
(throw (ex-info (tru "Sandboxing with a saved question is not enabled for this database.")
{:status-code 400
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
index dde6c0e0bec..ad4013e39be 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
@@ -16,7 +16,8 @@
;; DB-level change (keyword like :unrestricted) → delete all sandboxes for this group+db
(keyword? view-data-changes) true
:else
- (let [schema-changes (get view-data-changes schema)]
+ (let [schema-changes (or (get view-data-changes (or schema ""))
+ (get view-data-changes schema))]
(cond
(nil? schema-changes) false
;; Schema-level change → delete all sandboxes for this group+db+schema
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
index 9684b04398d..4dd2b89988a 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
@@ -11,6 +11,8 @@
[metabase.api.common :as api]
[metabase.audit-app.core :as audit]
[metabase.events.core :as events]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.models.interface :as mi]
@@ -150,24 +152,63 @@
:when table-col]
(check-column-types-match col table-col)))))
+(defn- sandboxing-card-ids
+ "Every Card a sandbox is built out of: the Cards sandboxes name directly, plus every Card those read at any depth."
+ []
+ (let [cards (t2/select :model/Card
+ {:select [:c.id :c.dataset_query :c.database_id :c.card_schema]
+ :from [[(t2/table-name :model/Card) :c]]
+ :where [:exists ^:allow-subquery {:select [[[:inline 1]]]
+ :from [[(t2/table-name :model/Sandbox) :s]]
+ :where [:= :s.card_id :c.id]}]})]
+ (into (into #{} (map :id) cards)
+ (mapcat (fn [{:keys [dataset_query database_id]}]
+ (when (seq dataset_query)
+ (lib/all-source-card-ids-recursive
+ (lib/query (lib-be/application-database-metadata-provider database_id) dataset_query)))))
+ cards)))
+
+(defn- check-non-admin-cannot-affect-sandboxing!
+ "Throws a 403 if `card-id` is a Card a sandbox is built out of and the current user is not an admin. Server-side
+ writes (sync, serdes and the like) run with no user bound, or as a superuser, and are not subject to the check."
+ [card-id]
+ (when (and card-id api/*current-user-id* (not api/*is-superuser?*))
+ (when (contains? (sandboxing-card-ids) card-id)
+ (throw (ex-info (tru "You do not have permissions to modify a question that is used for row and column level security.")
+ {:status-code 403, :card-id card-id})))))
+
+(defn- check-result-metadata-still-matches-sandboxed-tables!
+ "Throws if `new-result-metadata` would stop matching the Tables the sandboxes built out of this Card sandbox: the
+ Card cannot add fields or change types vs. the original Table."
+ [card-id new-result-metadata]
+ (when-let [gtaps-using-this-card (not-empty (t2/select [:model/Sandbox :id :table_id] :card_id card-id))]
+ (let [original-result-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)]
+ (when-not (= original-result-metadata new-result-metadata)
+ (doseq [{table-id :table_id} gtaps-using-this-card]
+ (try
+ (check-columns-match-table table-id new-result-metadata)
+ (catch clojure.lang.ExceptionInfo e
+ (throw (ex-info (str (tru "Cannot update Card: Card is used for Sandboxing, and updates would violate sandbox rules.")
+ " "
+ (.getMessage e))
+ (ex-data e)
+ e)))))))))
+
(defenterprise pre-update-check-sandbox-constraints
"If a Card is updated, and its result metadata changes, check that these changes do not violate the constraints placed
on sandboxes (the Card cannot add fields or change types vs. the original Table)."
:feature :sandboxes
[{new-result-metadata :result_metadata, card-id :id} changes]
+ (when (some #(contains? changes %) [:dataset_query :archived])
+ (check-non-admin-cannot-affect-sandboxing! card-id))
(when (contains? changes :result_metadata)
- (when-let [gtaps-using-this-card (not-empty (t2/select [:model/Sandbox :id :table_id] :card_id card-id))]
- (let [original-result-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)]
- (when-not (= original-result-metadata new-result-metadata)
- (doseq [{table-id :table_id} gtaps-using-this-card]
- (try
- (check-columns-match-table table-id new-result-metadata)
- (catch clojure.lang.ExceptionInfo e
- (throw (ex-info (str (tru "Cannot update Card: Card is used for Sandboxing, and updates would violate sandbox rules.")
- " "
- (.getMessage e))
- (ex-data e)
- e))))))))))
+ (check-result-metadata-still-matches-sandboxed-tables! card-id new-result-metadata)))
+
+(defenterprise pre-delete-check-sandbox-constraints
+ "Checks sandbox constraints when a Card a sandbox is built out of is deleted."
+ :feature :sandboxes
+ [{card-id :id}]
+ (check-non-admin-cannot-affect-sandboxing! card-id))
(defenterprise upsert-sandboxes!
"Create new `sandboxes` or update existing ones. If a sandbox has an `:id` it will be updated, otherwise it will be
diff --git a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
index 6f1a2e8a7c6..b407f9f2456 100644
--- a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj
@@ -13,6 +13,7 @@
[metabase.util :as u]
[metabase.util.i18n :as i18n]
[metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[ring.util.codec :as codec]
[toucan2.core :as t2]))
@@ -61,6 +62,13 @@
[:itemsPerPage ms/IntGreaterThanOrEqualToZero]
[:Resources [:sequential SCIMUser]]])
+(mr/def ::patch-value
+ "A single attribute value in a PATCH operation. The strings clients send for booleans are parsed by the handler."
+ [:or ms/NonBlankString :boolean])
+
+(def ^:private patch-value?
+ (mr/validator ::patch-value))
+
(def UserPatch
"Malli schema for a user patch operation"
[:map
@@ -73,9 +81,11 @@
;; dispatched on shape rather than written as `[:or [:map-of ...] ...]`: request decoding would
;; run the `:map-of` decoder over a scalar value and throw
[:value [:multi {:dispatch #(if (map? %) :map :scalar)}
- [:map [:map-of [:or :keyword :string]
- [:or ms/NonBlankString ms/BooleanValue]]]
- [:scalar [:or ms/NonBlankString ms/BooleanValue]]]]]]]])
+ [:map [:and
+ [:map-of [:or :keyword :string] :any]
+ [:fn {:error/message "attribute value must be a non-blank string or a boolean"}
+ #(every? patch-value? (vals %))]]]
+ [:scalar ::patch-value]]]]]]])
(def SCIMGroup
"Malli schema for a SCIM group."
@@ -303,13 +313,27 @@
:status 400
:status-code 400})))))))))
+(defn- patch->boolean
+ "SCIM sends `active` as a JSON boolean, but clients in the wild send the strings \"true\"/\"false\" too. Anything
+ else is an error rather than a value."
+ [path value]
+ (cond
+ (boolean? value)
+ value
+
+ (and (string? value) (contains? #{"true" "false"} (u/lower-case-en value)))
+ (Boolean/parseBoolean (u/lower-case-en value))
+
+ :else
+ (throw-scim-error 400 (format "Invalid value for %s: %s" path (pr-str value)))))
+
(defn- patch->user-updates
[acc path value]
(if (and (nil? path) (map? value))
(reduce-kv patch->user-updates acc value)
(let [path-str (some-> path name)]
(case path-str
- "active" (assoc acc :is_active (Boolean/valueOf (u/lower-case-en value)))
+ "active" (assoc acc :is_active (patch->boolean path-str value))
"userName" (assoc acc :email value)
"name.givenName" (assoc acc :first_name value)
"name.familyName" (assoc acc :last_name value)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
index 615a857823e..284902e3019 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj
@@ -65,12 +65,12 @@
:where (if schema
[:and
[:= :schemaname [:inline schema]]
- [:<> :tablename [:inline "migration"]]]
+ [:<> :tablename ^:allow-raw-sql [:inline "migration"]]]
;; dedicated mode only ever creates tables in the default
;; schema, so the reset has no business outside it
[:and
- [:= :schemaname [:raw "current_schema()"]]
- [:<> :tablename [:inline "migration"]]])})
+ [:= :schemaname ^:allow-raw-sql [:raw "current_schema()"]]
+ [:<> :tablename ^:allow-raw-sql [:inline "migration"]]])})
{:builder-fn jdbc.rs/as-unqualified-lower-maps})]
;; the sentinel scan reads every table in scope, not just ours: an app db is recognized by tables we
;; would never drop
@@ -194,8 +194,8 @@
model-id-col (semantic.util/column-keyword table-name "model_id")
root-coll-type-col (semantic.util/column-keyword table-name "root_collection_type")
gate-id (semantic.util/column-keyword gate-table "id")
- gate-doc-root [:->> (semantic.util/column-keyword gate-table "document") [:inline "root_collection_type"]]
- composite-gate-id [:|| model-col [:inline "_"] model-id-col]]
+ gate-doc-root [:->> (semantic.util/column-keyword gate-table "document") ^:allow-raw-sql [:inline "root_collection_type"]]
+ composite-gate-id [:|| model-col ^:allow-raw-sql [:inline "_"] model-id-col]]
(execute! {:alter-table [kw-tbl] :add-column [[:root_collection_type :text :if-not-exists]]})
;; Per-row backfill: take whatever the gate document says — authoritative when present.
(execute! {:update kw-tbl
@@ -208,7 +208,7 @@
;; Forest backfill: one UPDATE per distinct root type, filling rows the gate doc missed.
(doseq [[root-type entries] (group-by val root-type-by-coll-id)]
(execute! {:update kw-tbl
- :set {:root_collection_type [:inline root-type]}
+ :set {:root_collection_type ^:allow-raw-sql [:inline root-type]}
:where [:and
[:= :root_collection_type nil]
[:in :collection_id (mapv key entries)]]})))))))
@@ -235,7 +235,7 @@
{:where [:and
[:= :active true]
[:or [:= :is_published true]
- [:= :data_authority [:inline "authoritative"]]]]}))
+ [:= :data_authority ^:allow-raw-sql [:inline "authoritative"]]]]}))
(catch Exception e
(when-not config/is-test?
(throw e))
@@ -276,7 +276,7 @@
(doseq [chunk (partition-all 5000 model-ids)]
(execute! {:update kw-tbl
:set set-map
- :where [:and [:= :model [:inline model]] [:in :model_id (vec chunk)]]})))
+ :where [:and [:= :model ^:allow-raw-sql [:inline model]] [:in :model_id (vec chunk)]]})))
(defn- add-data-authority-and-curated-columns!
"Migration 5: add `data_authority` and the precomputed `curated` flag to index tables.
@@ -309,10 +309,10 @@
;; Non-table rows from index columns (cards accurate; official-only dashboards fixed below).
(execute! {:update kw-tbl
:set {:curated curated-expr}
- :where [:and [:= :curated nil] [:!= :model [:inline "table"]]]})
+ :where [:and [:= :curated nil] [:!= :model ^:allow-raw-sql [:inline "table"]]]})
;; Tables: curated only from the appdb sweep. Authoritative rows also get data_authority.
(update-model-rows-in-batches! execute! kw-tbl "table" authoritative
- {:data_authority [:inline "authoritative"] :curated true})
+ {:data_authority ^:allow-raw-sql [:inline "authoritative"] :curated true})
(update-model-rows-in-batches! execute! kw-tbl "table" published {:curated true})
;; Dashboards: official_collection is new on the spec, so backfill both it and curated for
;; official dashboards (curated alone would leave them scoring as non-official until reindex).
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index 1fbbb173b3f..6d699ac8232 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -702,8 +702,7 @@
:keyword_rank]])
:from [(keyword (:table-name index))]
;; Using a join allows us to share the query expression between our SELECT and WHERE clauses.
- ;; This follows the same secure pattern as metabase.search.appdb.specialization.postgres/base-query
- :join [[[:raw "to_tsquery('" tsv-lang "', " [:lift ts-search-expr] ")"]
+ :join [[[:to_tsquery ^:allow-raw-sql [:inline tsv-lang] [:lift ts-search-expr]]
:query] [:= 1 1]]
:where (let [ts-query-filter [:raw (format "%s @@ query" (name vector-column))]]
(if (seq filters)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
index 0bc217d8461..2db050fb5a6 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
@@ -54,7 +54,7 @@
(defn- view-count-expr [index-table percentile]
(let [views (view-count-percentiles index-table percentile)
cases (for [[sm v] views]
- [[:= :model [:inline (name sm)]] (max (or v 0) 1)])]
+ [[:= :model (name sm)] (max (or v 0) 1)])]
(search.scoring/size :view_count (if (seq cases)
(into [:case] cat cases)
1))))
@@ -158,14 +158,16 @@
(defn- search-doc->select
[{:keys [id model]}]
- {:select [[[:inline (str id)]] [[:inline model]]]})
+ ^:allow-subquery
+ {:select [[^:allow-raw-sql [:inline (str id)]] [^:allow-raw-sql [:inline model]]]})
(defn- search-index-query
[search-results]
- {:with [[[:search_index {:columns [:model_id :model]}]
+ {:with [[[:search_index ^:allow-subquery {:columns [:model_id :model]}]
;; We could use :values here, except MySQL uses a slightly different syntax and I can't seem to get
;; honeysql to generate a valid WITH ... VALUES statement for MySQL, so fallback to UNION + SELECT
;; which works with all supported appdbs. https://dev.mysql.com/doc/refman/8.4/en/values.html
+ ^:allow-subquery
{:union (map search-doc->select search-results)}]]
:select [[[:cast :search_index.model_id (if (= :mysql (mdb/db-type))
:unsigned
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
index 6e3e20c4a8a..2efd42bd00f 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/task/index_cleanup.clj
@@ -78,7 +78,7 @@
:left-join [[(keyword metadata-table-name) :meta]
[:= :meta.table_name stored-name]]
:where [:and
- [:like :t.table_name [:inline like-pattern]]
+ [:like :t.table_name ^:allow-raw-sql [:inline like-pattern]]
[:= :meta.table_name nil]
[:= :t.table_type [:inline "BASE TABLE"]]
[:= :t.table_schema (if schema
@@ -112,7 +112,7 @@
(let [retention-cutoff (t/minus (t/instant) (t/hours (semantic.settings/repair-table-retention-hours)))
repair-tables-sql (-> {:select [:t.table_name]
:from [[:information_schema.tables :t]]
- :where (scope-where-to-schema [:and [:like :t.table_name [:inline "repair_%"]]] schema)}
+ :where (scope-where-to-schema [:and [:like :t.table_name ^:allow-raw-sql [:inline "repair_%"]]] schema)}
(sql/format :quoted true))
all-repair-tables (->> (jdbc/execute! pgvector repair-tables-sql {:builder-fn jdbc.rs/as-unqualified-lower-maps})
(map :table_name))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/api.clj b/enterprise/backend/src/metabase_enterprise/serialization/api.clj
index 3993580d7fe..e873bf02c63 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/api.clj
@@ -192,7 +192,7 @@
:data_model (not (:no-data-model opts))
:settings (not (:no-settings opts))
:field_values (:include-field-values opts)
- :secrets (:include-database-secrets opts)
+ :secrets false
:success (boolean success)
:error_message error-message}))
@@ -214,7 +214,6 @@
[_route-params
{:keys [collection dirname]
include-field-values? :field_values
- include-database-secrets? :database_secrets
all-collections? :all_collections
data-model? :data_model
settings? :settings
@@ -238,7 +237,6 @@
[:settings {:default true} (mu/with ms/BooleanValue {:description "Serialize Metabase settings"})]
[:data_model {:default true} (mu/with ms/BooleanValue {:description "Serialize Metabase data model"})]
[:field_values {:default false} (mu/with ms/BooleanValue {:description "Serialize cached field values"})]
- [:database_secrets {:default false} (mu/with ms/BooleanValue {:description "Serialize details how to connect to each db"})]
[:continue_on_error {:default false} (mu/with ms/BooleanValue {:description "Do not break execution on errors"})]
[:full_stacktrace {:default false} (mu/with ms/BooleanValue {:description "Show full stacktraces in the logs"})]]]
(api/check-superuser)
@@ -249,7 +247,6 @@
:no-data-model (not data-model?)
:no-settings (not settings?)
:include-field-values include-field-values?
- :include-database-secrets include-database-secrets?
:continue-on-error continue-on-error?
:full-stacktrace full-stacktrace?}
export-dirname (or dirname
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj b/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj
index e9beda0981e..87c20ad9d60 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj
@@ -128,7 +128,7 @@
:data_model (not (:no-data-model opts))
:settings (not (:no-settings opts))
:field_values (boolean (:include-field-values opts))
- :secrets (boolean (:include-database-secrets opts))
+ :secrets false
:success (nil? @err)
:error_message (when @err
(u/strip-error @err nil))})
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
index 18079d5be44..ef21d94edfe 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
@@ -8,7 +8,8 @@
[req]
(case (:request-method req)
:get (get-in req [:params :jwt])
- :post (get-in req [:body :jwt])
+ :post (or (get-in req [:body "jwt"])
+ (get-in req [:body :jwt]))
nil))
(defn- select-sso-backend
diff --git a/enterprise/backend/src/metabase_enterprise/stale/api.clj b/enterprise/backend/src/metabase_enterprise/stale/api.clj
index 2587a8dabdc..0bc0858df48 100644
--- a/enterprise/backend/src/metabase_enterprise/stale/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/stale/api.clj
@@ -72,7 +72,8 @@
:dataset_query
:card_schema
:last_used_at
- [{:select [:status]
+ [^:allow-subquery
+ {:select [:status]
:from [:moderation_review]
:where [:and
[:= :moderated_item_type "card"]
diff --git a/enterprise/backend/src/metabase_enterprise/stale/impl.clj b/enterprise/backend/src/metabase_enterprise/stale/impl.clj
index fd42830a6a4..3bed7ffaa07 100644
--- a/enterprise/backend/src/metabase_enterprise/stale/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/stale/impl.clj
@@ -31,7 +31,7 @@
(mu/defn ^:private rows-query [{:keys [limit offset] :as args} :- FindStaleContentArgs]
(cond-> {:select [:id :model]
- :from [[{:union-all (queries args)} :dummy_alias]]
+ :from [[^:allow-subquery {:union-all (queries args)} :dummy_alias]]
:order-by [[(sort-column (:sort-column args))
(:sort-direction args)]]}
(some? limit) ;; limit
@@ -41,7 +41,7 @@
(mu/defn ^:private total-query [args :- FindStaleContentArgs]
{:select [[:%count.* :count]]
- :from [[{:union-all (queries args)} :dummy_alias]]})
+ :from [[^:allow-subquery {:union-all (queries args)} :dummy_alias]]})
(mu/defn find-candidates :- [:map
[:rows [:sequential [:map
diff --git a/enterprise/backend/src/metabase_enterprise/tenants/api.clj b/enterprise/backend/src/metabase_enterprise/tenants/api.clj
index 3853b60b039..c02a750a743 100644
--- a/enterprise/backend/src/metabase_enterprise/tenants/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/tenants/api.clj
@@ -71,7 +71,7 @@
(t2/select :model/Tenant (cond-> {:order-by [[:id :asc]]}
(request/paged?) (assoc :limit (request/limit) :offset (request/offset))
true (assoc :where (case status
- "all" [:inline [:= 1 1]]
+ "all" [:= [:inline 1] [:inline 1]]
"active" [:= :is_active true]
"deactivated" [:= :is_active false])))))})
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/api.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/api.clj
index e404461933a..6a42402a786 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_inspector/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/api.clj
@@ -9,6 +9,7 @@
[metabase.api.routes.common :refer [+auth]]
[metabase.api.util.handlers :as handlers]
[metabase.events.core :as events]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.query-processor.core :as qp]
[metabase.query-processor.middleware.constraints :as qp.constraints]
[metabase.query-processor.pipeline :as qp.pipeline]
@@ -87,7 +88,7 @@
[{:keys [id lens-id]} :- [:map
[:id ms/PositiveInt]
[:lens-id ms/NonBlankString]]
- params :- [:map-of :keyword :any]]
+ params :- ::inspector.schema/lens-params]
(let [transform (api/read-check :model/Transform id)
_ (transforms.core/check-feature-enabled! transform)
result (tracing/with-span :transforms "transforms.inspector.lens"
@@ -121,8 +122,8 @@
_query-params
{query :query, lens-params :lens_params}
:- [:map
- [:query ms/Map]
- [:lens_params {:optional true} [:maybe [:map-of :keyword :any]]]]]
+ [:query ::lib-be.schema/maybe-legacy-query]
+ [:lens_params {:optional true} [:maybe ::inspector.schema/lens-params]]]]
(let [transform (api/read-check :model/Transform id)]
(transforms.core/check-feature-enabled! transform)
(let [info {:executed-by api/*current-user-id*
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj
index 3e24d889a30..0b077850669 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj
@@ -120,7 +120,7 @@
:macaw.ast/literal (let [{:keys [value]} node]
(cond
(nil? value) nil
- :else [:inline value]))
+ :else [:lift value]))
nil))
(defn- macaw-condition->hsql
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/schema.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/schema.clj
index 5e91a9bd9ad..07378d020e2 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_inspector/schema.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/schema.clj
@@ -195,6 +195,11 @@
[:message :string]
[:metadata {:optional true} ::trigger-metadata]])
+(mr/def ::lens-params
+ "Params passed to a drill lens (e.g. `{:join_step 2}`), emitted on drill-lens triggers and echoed back by the FE
+ to the lens endpoints. Scalar values only."
+ [:map-of :keyword [:maybe [:or :string :int :boolean :double]]])
+
(mr/def ::drill-lens-trigger
"Definition for conditional drill lens availability.
FE evaluates condition and shows drill lens option if triggered.
@@ -202,7 +207,7 @@
[:map
[:lens_id :string]
[:condition ::trigger-condition]
- [:params {:optional true} [:map-of :keyword :any]]
+ [:params {:optional true} ::lens-params]
[:reason {:optional true} :string]
[:metadata {:optional true} ::trigger-metadata]])
diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
index a0c8bd9f069..fcc1e3de4a1 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj
@@ -8,6 +8,7 @@
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
[metabase.api.util.handlers :as handlers]
+ [metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
[metabase.transforms-base.util :as transforms-base.u]
[metabase.util.i18n :as i18n]
@@ -67,9 +68,12 @@
[:source_tables [:sequential {:min 1} ::transforms-base.u/source-table-entry]]
[:output_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]]
[:per_input_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]]]]
- (let [db-ids (t2/select-fn-set :db_id [:model/Table :db_id] :id [:in (map :table_id source_tables)])]
+ (let [table-ids (map :table_id source_tables)
+ db-ids (t2/select-fn-set :db_id [:model/Table :db_id] :id [:in table-ids])]
(api/check-400 (= (count db-ids) 1) (i18n/deferred-tru "All source tables must belong to the same database."))
- (api/check-403 (perms/has-db-transforms-permission? api/*current-user-id* (first db-ids))))
+ (api/check-403 (perms/has-db-transforms-permission? api/*current-user-id* (first db-ids)))
+ (doseq [table-id table-ids]
+ (api/check-403 (mi/can-query? :model/Table table-id))))
;; NOTE: we do not test database support, as there is no write target.
(let [result (python-runner/execute-and-read-output!
{:code code
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj
deleted file mode 100644
index fff908d4b6e..00000000000
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/api_test.clj
+++ /dev/null
@@ -1,47 +0,0 @@
-(ns metabase-enterprise.advanced-config.api-test
- (:require
- [clojure.test :refer [deftest is testing use-fixtures]]
- [metabase.driver.util]
- [metabase.test :as mt]
- [metabase.test.fixtures :as fixtures]
- [metabase.util.yaml :as yaml]
- [toucan2.core :as t2]))
-
-(set! *warn-on-reflection* true)
-
-(use-fixtures :once (fixtures/initialize :db))
-
-(defn- yaml-bytes ^bytes [body]
- (.getBytes ^String (yaml/generate-string body) "UTF-8"))
-
-(defn- multipart [bs]
- [{:request-options {:headers {"content-type" "multipart/form-data"}}}
- {:config bs}])
-
-(deftest superuser-only-test
- (testing "POST /api/ee/advanced-config requires superuser"
- (is (= "You don't have permissions to do that."
- (apply mt/user-http-request :rasta :post 403 "ee/advanced-config/"
- (multipart (yaml-bytes {:version 1 :config {}})))))))
-
-(deftest does-not-expand-templates-test
- (testing "POST /api/ee/advanced-config does NOT expand `{{env VAR}}` templates"
- ;; The literal template appears in the inserted database's name; if env
- ;; expansion happened, the row would be created under a different name.
- (let [db-name "advanced-config-literal-{{env SECRET}}"
- payload {:version 1
- :config {:databases [{:name db-name
- :engine "postgres"
- :details {}}]}}]
- (try
- (mt/with-premium-features #{:config-text-file}
- (mt/with-temporary-setting-values [config-from-file-sync-databases false]
- (with-redefs [metabase.driver.util/can-connect-with-details? (constantly true)]
- (mt/user-http-request :crowberto :post 204 "ee/advanced-config/"
- (first (multipart (yaml-bytes payload)))
- (second (multipart (yaml-bytes payload)))))))
- (is (some? (t2/select-one :model/Database :name db-name :engine "postgres"))
- "Database row carries the LITERAL name with templates unexpanded")
- (finally
- (when-let [db-id (t2/select-one-pk :model/Database :name db-name :engine "postgres")]
- (t2/delete! :model/Database db-id)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/application_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/application_test.clj
index b4c8702723a..d80133be443 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/application_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/application_test.clj
@@ -47,6 +47,10 @@
(is (= "Looks like someone else edited the permissions and your data is out of date. Please fetch new data and try again."
(mt/user-http-request :crowberto :put 409 "ee/advanced-permissions/application/graph"
(assoc new-graph :revision (inc (:revision new-graph)))))))
+ (testing "a missing revision is a 409, not a 400 -- the request is well formed, it's just out of date"
+ (is (= "Looks like someone else edited the permissions and your data is out of date. Please fetch new data and try again."
+ (mt/user-http-request :crowberto :put 409 "ee/advanced-permissions/application/graph"
+ (dissoc new-graph :revision)))))
(testing "successfully update application permissions"
(is (partial= {(:id (perms-group/admin))
{:monitoring "yes"
@@ -57,6 +61,11 @@
:setting "yes"
:subscription "no"}}
(:groups (mt/user-http-request :crowberto :put 200 "ee/advanced-permissions/application/graph" new-graph)))))
+ (testing "force=true skips the revision check, so no revision is needed"
+ (is (partial= {group-id {:setting "yes"}}
+ (:groups (mt/user-http-request :crowberto :put 200
+ "ee/advanced-permissions/application/graph?force=true"
+ (dissoc new-graph :revision))))))
(testing "omits graph in response when skip-graph=true"
(let [result (mt/user-http-request :crowberto :put 200 "ee/advanced-permissions/application/graph?skip-graph=true"
(a-perms/graph))]
@@ -71,4 +80,15 @@
{:monitoring "yes"
:setting "yes"
:subscription "no"}}
+ (:groups result)))))
+ (testing "omits revision ID check when body :force is true"
+ (let [result (mt/user-http-request :crowberto :put 200 "ee/advanced-permissions/application/graph"
+ (-> (a-perms/graph)
+ (update :revision dec)
+ (assoc :force true)
+ (assoc-in [:groups group-id :subscription] "yes")))]
+ (is (partial= {group-id
+ {:monitoring "yes"
+ :setting "yes"
+ :subscription "yes"}}
(:groups result))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
index ddc5cf0aef4..4a8d075e977 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
@@ -138,7 +138,7 @@
new-graph (assoc-in current-graph
[:groups group-id (mt/id)]
{:view-data :blocked :create-queries :query-builder-and-native})]
- (is (=? #"Cannot parse permissions graph because it is invalid.*"
+ (is (=? {:specific-errors {:groups [#"Invalid DB permissions: If you have write access for native queries.*"]}}
(mt/with-premium-features #{:advanced-permissions}
(mt/user-http-request :crowberto :put 400 "permissions/graph" new-graph)))))))))
@@ -284,12 +284,15 @@
#"You do not have permissions to run this query"
(mt/rows (process-query-for-card child-card)))
"Even if the user has can-write? on a Card, they should not be able to run it because they are blocked on Card's db"))))
- (testing "view-data = unrestricted is required to allow running the query (#15131)"
+ (testing "view-data alone is not enough: the child reads a Card in a Collection the user cannot read"
(mt/with-restored-data-perms!
(data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
(rasta-view-data-perm= :unrestricted)
- (is (= [[1] [2]] (mt/rows (process-query-for-card child-card)))
- "view-data = unrestricted is sufficient to allow running the query"))))))))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows (process-query-for-card child-card)))
+ "reading the child still requires reading the parent it sources, which is in a blocked Collection"))))))))))
;; Similar to the above test, but with table-level block in place for the nested query
(deftest nested-query-table-level-block-permissions-test
diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/pages_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/pages_test.clj
index 238879d2454..c7019983e1c 100644
--- a/enterprise/backend/test/metabase_enterprise/audit_app/pages_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/audit_app/pages_test.clj
@@ -96,23 +96,27 @@
(for [arglist (query-defmethod-arglists query-type)]
{:type :internal
:fn (u/qualified-name query-type)
- :args (for [arg (mapv keyword (rest arglist))]
- (case arg
- :datetime-unit "day"
- :dashboard-id (u/the-id dash)
- :card-id (u/the-id card)
- :user-id (mt/user->id :crowberto)
- :database-id (u/the-id database)
- :table-id (u/the-id table)
- :model "card"
- :query-hash (codec/base64-encode (qp.util/query-hash {:database 1, :type :native}))
- :query-string "toucans"
- :question-filter "bird sales"
- :search-term "toucans"
- :sort-column "card.id"
- :sort-direction "desc"
- :dashboard-name "wow"
- :card-name "Credit Card"))}))
+ :args (vec
+ (for [arg (mapv keyword (rest arglist))]
+ (case arg
+ :datetime-unit "day"
+ :dashboard-id (u/the-id dash)
+ :card-id (u/the-id card)
+ :user-id (mt/user->id :crowberto)
+ :database-id (u/the-id database)
+ :table-id (u/the-id table)
+ :model "card"
+ :query-hash (codec/base64-encode (qp.util/query-hash {:database 1, :type :native}))
+ :query-string "toucans"
+ :question-filter "bird sales"
+ :collection-filter "coin collection"
+ :error-filter "a"
+ :db-filter "PU"
+ :search-term "toucans"
+ :sort-column "card_id"
+ :sort-direction "desc"
+ :dashboard-name "wow"
+ :card-name "Credit Card")))}))
(defn- do-tests-for-query-type
"Run test(s) for the internal query named by `query-type`. Runs one test for each map returned
diff --git a/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj b/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj
index 517151571e9..2c718ddc3e8 100644
--- a/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj
@@ -17,12 +17,17 @@
(set! *warn-on-reflection* true)
+(def ^:private date-tag-id
+ "The `:id` of the template tag in [[parameterized-native-query]], and so of the parameter the Card declares for it --
+ the id a client sends when giving that parameter a value."
+ "04ae45bd-f8fd-4e8d-9bc6-a9737f231a50")
+
(defn- parameterized-native-query
"A native query with an optional template tag"
[]
{:database (mt/id)
:type :native
- :native {:template-tags {"date" {:id "04ae45bd-f8fd-4e8d-9bc6-a9737f231a50"
+ :native {:template-tags {"date" {:id date-tag-id
:name "date"
:display-name "Check-In Date"
:type :text}}
@@ -110,12 +115,12 @@
(mt/with-temp [:model/Card {card-id :id} {:name "Cached card"
:dataset_query (parameterized-native-query)}]
(let [param-val-1 "2024-12-01"
- params-1 [{:id "_DATE_"
+ params-1 [{:id date-tag-id
:type :text
:target [:variable [:template-tag "date"]]
:value param-val-1}]
param-val-2 "2024-12-02"
- params-2 [{:id "_DATE_"
+ params-2 [{:id date-tag-id
:type :text
:target [:variable [:template-tag "date"]]
:value param-val-2}]
@@ -237,12 +242,12 @@
:refresh_automatically true
:config {:unit "hours" :duration 1}}]
(let [param-val-1 "2024-12-01"
- params-1 [{:id "_DATE_"
+ params-1 [{:id date-tag-id
:type :text
:target [:variable [:template-tag "date"]]
:value param-val-1}]
param-val-2 "2024-12-02"
- params-2 [{:id "_DATE_"
+ params-2 [{:id date-tag-id
:type :text
:target [:variable [:template-tag "date"]]
:value param-val-2}]
@@ -489,7 +494,7 @@
:result [[1000]]}
{:label "parameterized native query"
:query (parameterized-native-query)
- :parameters [{:id "_DATE_"
+ :parameters [{:id date-tag-id
:type :text
:target [:variable [:template-tag "date"]]
:value "2014-05-31"}]
diff --git a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
index 359882e4b6b..e10553ca5f2 100644
--- a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
@@ -1186,10 +1186,8 @@
(is (re-find #"single select statement" (ex-message thrown))))))))
(deftest ^:parallel validate-impersonated-query-keys-on-allow-write-flag-test
- (testing "validate-impersonated-query* derives read-vs-write from :impersonation/allow-write?"
- (let [query (fn [sql allow-write?]
- (cond-> {:stages [{:lib/type :mbql.stage/native :native sql}]}
- allow-write? (assoc :impersonation/allow-write? true)))
+ (testing "validate-impersonated-query* derives read-vs-write from *impersonation-allow-write?*"
+ (let [query (fn [sql] {:stages [{:lib/type :mbql.stage/native :native sql}]})
outcome (fn [q]
(try
(driver.sql/validate-impersonated-query* :postgres q)
@@ -1197,9 +1195,10 @@
(catch clojure.lang.ExceptionInfo _ :rejected)))
select "SELECT 1 AS x"
write "UPDATE t SET x = 1 WHERE id = -1"]
- (testing "without :impersonation/allow-write?: SELECT allowed, write rejected"
- (is (= :ok (outcome (query select false))))
- (is (= :rejected (outcome (query write false)))))
- (testing "with :impersonation/allow-write? true: write allowed, SELECT rejected"
- (is (= :ok (outcome (query write true))))
- (is (= :rejected (outcome (query select true))))))))
+ (testing "unbound: SELECT allowed, write rejected"
+ (is (= :ok (outcome (query select))))
+ (is (= :rejected (outcome (query write)))))
+ (testing "bound true: write allowed, SELECT rejected"
+ (binding [driver.settings/*impersonation-allow-write?* true]
+ (is (= :ok (outcome (query write))))
+ (is (= :rejected (outcome (query select)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
index 3e878968fda..f753474b7a3 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
@@ -490,26 +490,30 @@
(let [task-id (t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})]
(mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :is_remote_synced true :entity_id "test-collection-1xxxx" :location "/"}
:model/Card {card-id :id} {:name "Test Card" :collection_id coll-id :entity_id "test-card-1xxxxxxxxxx"}]
- (t2/insert! :model/RemoteSyncObject
- [{:model_type "Collection" :model_id coll-id :model_name "Test Collection" :status "created" :status_changed_at (t/offset-date-time)}
- {:model_type "Card" :model_id card-id :model_name "Test Card" :status "updated" :status_changed_at (t/offset-date-time)}
- {:model_type "Card" :model_id 999 :model_name "Test Card2" :status "deleted" :status_changed_at (t/offset-date-time)}])
- (is (= 3 (t2/count :model/RemoteSyncObject)))
- (let [test-files {"main" {"collections/main/test_collection/test_collection.yaml"
- (test-helpers/generate-collection-yaml "test-collection-1xxxx" "Test Collection")
- "collections/main/test_collection/test_card.yaml"
- (test-helpers/generate-card-yaml "test-card-1xxxxxxxxxx" "Test Card" "test-collection-1xxxx")}}
- mock-source (test-helpers/create-mock-source :initial-files test-files)
- result (impl/import! (source.p/snapshot mock-source) task-id)]
- (is (= :success (:status result)))
- (let [entries (t2/select :model/RemoteSyncObject)]
- (is (= 2 (count entries)))
- (is (every? #(= "synced" (:status %)) entries))
- (is (some #(and (= "Collection" (:model_type %))
- (= coll-id (:model_id %))) entries))
- (is (some #(and (= "Card" (:model_type %))
- (= card-id (:model_id %))) entries))
- (is (not (some #(= 999 (:model_id %)) entries))))))))))
+ ;; derived rather than hard-coded: `card-id` comes from an auto-increment shared across the whole run, so
+ ;; a literal here is a landmine -- once the sequence reaches it, the "deleted" marker and the real Card are
+ ;; the same id and the prune assertion below fails
+ (let [deleted-card-id (+ card-id 1000000)]
+ (t2/insert! :model/RemoteSyncObject
+ [{:model_type "Collection" :model_id coll-id :model_name "Test Collection" :status "created" :status_changed_at (t/offset-date-time)}
+ {:model_type "Card" :model_id card-id :model_name "Test Card" :status "updated" :status_changed_at (t/offset-date-time)}
+ {:model_type "Card" :model_id deleted-card-id :model_name "Test Card2" :status "deleted" :status_changed_at (t/offset-date-time)}])
+ (is (= 3 (t2/count :model/RemoteSyncObject)))
+ (let [test-files {"main" {"collections/main/test_collection/test_collection.yaml"
+ (test-helpers/generate-collection-yaml "test-collection-1xxxx" "Test Collection")
+ "collections/main/test_collection/test_card.yaml"
+ (test-helpers/generate-card-yaml "test-card-1xxxxxxxxxx" "Test Card" "test-collection-1xxxx")}}
+ mock-source (test-helpers/create-mock-source :initial-files test-files)
+ result (impl/import! (source.p/snapshot mock-source) task-id)]
+ (is (= :success (:status result)))
+ (let [entries (t2/select :model/RemoteSyncObject)]
+ (is (= 2 (count entries)))
+ (is (every? #(= "synced" (:status %)) entries))
+ (is (some #(and (= "Collection" (:model_type %))
+ (= coll-id (:model_id %))) entries))
+ (is (some #(and (= "Card" (:model_type %))
+ (= card-id (:model_id %))) entries))
+ (is (not (some #(= deleted-card-id (:model_id %)) entries)))))))))))
(deftest export!-updates-all-statuses-to-synced-test
(testing "export! updates all RemoteSyncObject entries to synced status"
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
index 45771c8a5db..74a6068282f 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
@@ -333,20 +333,6 @@
;;; ------------------------------------------------- Segment ----------------------------------------------------------
-(deftest segment-upgrade-field-refs!-mbql-query-test
- (testing "should upgrade id-based field refs in a segment with a card source"
- (let [mp (mt/metadata-provider)
- card-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))]
- (mt/with-temp [:model/Card {card-id :id} {:dataset_query card-query}]
- (let [seg-definition (-> (lib/query mp (lib.metadata/card mp card-id))
- (lib/filter (lib/= (lib.metadata/field mp (mt/id :orders :id)) 10)))]
- (mt/with-temp [:model/Segment {segment-id :id} {:table_id (mt/id :orders)
- :definition seg-definition}]
- (replacement.field-refs/upgrade-field-refs! [:segment segment-id])
- (is (=? {:definition {:stages [{:source-card card-id
- :filters [[:= {} [:field {} "ID"] 10]]}]}}
- (t2/select-one :model/Segment segment-id)))))))))
-
(deftest segment-upgrade-field-refs!-broken-query-test
(testing "should not crash or update a segment with a broken definition"
(let [mp (mt/metadata-provider)
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
index 8ad76ea8ba7..5fdf778ce4d 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
@@ -318,7 +318,12 @@
(testing "PUT /api/permissions/graph"
(testing "make sure an error is thrown if the :sandboxes key is included in the request, but the :sandboxes feature
is not enabled"
- (with-redefs [premium-features/enable-sandboxes? (constantly false)]
- (mt/with-temporary-setting-values [premium-embedding-token nil]
- (mt/assert-has-premium-feature-error "Sandboxes" (mt/user-http-request :crowberto :put 402 "permissions/graph"
- (assoc (data-perms.graph/api-graph) :sandboxes [{:card_id 1}]))))))))
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Table {table-id :id} {:db_id (mt/id) :schema "PUBLIC"}]
+ (with-redefs [premium-features/enable-sandboxes? (constantly false)]
+ (mt/with-temporary-setting-values [premium-embedding-token nil]
+ (mt/assert-has-premium-feature-error
+ "Sandboxes"
+ (mt/user-http-request :crowberto :put 402 "permissions/graph"
+ (assoc (data-perms.graph/api-graph)
+ :sandboxes [{:group_id group-id, :table_id table-id, :card_id 1}])))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
index ba04715f513..26d2460866f 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
@@ -41,8 +41,9 @@
(let [new-query (mt/mbql-query categories
{:filter [:and [:> $id 1] [:< $id 4]]})]
(Thread/sleep 1)
- (t2/update! :model/Card card-id {:dataset_query new-query
- :updated_at (t/local-date-time)}))
+ (mt/with-test-user :crowberto
+ (t2/update! :model/Card card-id {:dataset_query new-query
+ :updated_at (t/local-date-time)})))
(params.field-values/get-or-create-field-values!
(t2/select-one :model/Field :id (mt/id :categories :id)))
(is (= [(range 4 6)
diff --git a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
index 25c847e72be..cbfd870738e 100644
--- a/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/scim/v2/api_test.clj
@@ -20,7 +20,8 @@
run."
[thunk]
(mt/with-additional-premium-features #{:scim}
- (mt/with-temporary-setting-values [scim-enabled true]
+ (mt/with-temporary-setting-values [scim-enabled true
+ site-url "http://localhost:3000"]
(let [current-masked-key (-> (t2/select-one :model/ApiKey :scope :scim)
(dissoc :masked_key))
temp-unmasked-key (-> (#'scim/refresh-scim-api-key! (mt/user->id :crowberto))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
index 626463de9fa..a9166a1c2ad 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/api_test.clj
@@ -102,7 +102,7 @@
:model/Card ~card {:collection_id (:id ~coll), :name "frobinate", :type :model
:query_type :native
:dataset_query {:type :native
- :database (t2/select-one-pk :model/Database)
+ :database (t2/select-one-pk :model/Database :is_audit false)
:native {:query "SELECT 1"}}}]
~@body)))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index 170e17a7366..a21b13bacef 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -2007,16 +2007,11 @@
(t2/select-one-fn :details :model/Database)))))))))
(mt/with-temp [:model/Database _ {:name "My Database"
:details {:some "secret"}}]
- (testing "with :include-database-secrets"
+ (testing "connection details are never exported, even when :include-database-secrets is requested"
(let [extracted (vec (serdes.extract/extract {:no-settings true :include-database-secrets true}))
dbs (filterv #(= "Database" (:model (last (serdes/path %)))) extracted)]
(is (= 1 (count dbs)))
- (is (every? :details dbs))
- (ts/with-db dest-db
- (testing "Details are imported if provided"
- (serdes.load/load-metabase! (ingestion-in-memory extracted))
- (is (= (:details (first dbs))
- (t2/select-one-fn :details :model/Database)))))))))))
+ (is (not-any? :details dbs))))))))
(deftest unique-dimensions-test
(ts/with-dbs [source-db dest-db]
diff --git a/frontend/src/metabase-lib/query/limit.ts b/frontend/src/metabase-lib/query/limit.ts
index e8f3cbdf181..8e0d1aba6ce 100644
--- a/frontend/src/metabase-lib/query/limit.ts
+++ b/frontend/src/metabase-lib/query/limit.ts
@@ -14,7 +14,3 @@ export function hasLimit(query: Query, stageIndex: number) {
const limit = currentLimit(query, stageIndex);
return typeof limit === "number" && limit > 0;
}
-
-export function disableDefaultLimit(query: Query): Query {
- return ML.disable_default_limit(query);
-}
diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.ts
index adc17c20b47..8b836a645c3 100644
--- a/frontend/src/metabase-types/api/collection.ts
+++ b/frontend/src/metabase-types/api/collection.ts
@@ -135,7 +135,6 @@ export interface CollectionItem {
can_restore?: boolean;
can_delete?: boolean;
is_library_root?: boolean;
- can_run_adhoc_query?: boolean; // available only for data picker (#60021)
"last-edit-info"?: LastEditInfo;
location?: string | null;
effective_location?: string;
@@ -177,7 +176,6 @@ export type ListCollectionItemsRequest = {
pinned_state?: "all" | "is_pinned" | "is_not_pinned";
namespace?: CollectionNamespace;
collection_type?: CollectionType;
- include_can_run_adhoc_query?: boolean;
show_dashboard_questions?: boolean;
include_library?: boolean;
} & PaginationRequest &
diff --git a/frontend/src/metabase/common/components/Link/BaseLink.tsx b/frontend/src/metabase/common/components/Link/BaseLink.tsx
index 2031e1aad7a..a77a5ff0784 100644
--- a/frontend/src/metabase/common/components/Link/BaseLink.tsx
+++ b/frontend/src/metabase/common/components/Link/BaseLink.tsx
@@ -121,7 +121,7 @@ export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(
// rendered in isolation (common in unit tests) has no router, so fall back
// to a plain anchor with the resolved href. The real app always mounts a
// router, so that path never runs there.
- if (to == null || to === "" || !inRouter) {
+ if (to == null || to === "" || to === "#" || !inRouter) {
const href = to == null || to === "" ? undefined : hrefFor(to);
return (
<a
diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts
index d2f2eb0ffc7..e6c4fbb1d1c 100644
--- a/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/utils.ts
@@ -1,6 +1,5 @@
import { t } from "ttag";
-import { canCollectionCardBeUsed } from "metabase/common/components/Pickers/utils";
import * as Lib from "metabase-lib";
import { getSchemaName } from "metabase-lib/v1/metadata/utils/schema";
import type { DatabaseId, SchemaName } from "metabase-types/api";
@@ -71,7 +70,7 @@ export const shouldDisableItemNotInDb =
}
if (isQuestionItem(item)) {
- return canCollectionCardBeUsed(item) && item.database_id !== databaseId;
+ return item.database_id !== databaseId;
}
return false;
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
index 7f7a2ff7e6a..6084e7a3a6d 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx
@@ -12,10 +12,7 @@ import {
useListDatabasesQuery,
useSearchQuery,
} from "metabase/api";
-import {
- canCollectionCardBeUsed,
- getCollectionItemsOptions,
-} from "metabase/common/components/Pickers/utils";
+import { getCollectionItemsOptions } from "metabase/common/components/Pickers/utils";
import { VirtualizedList } from "metabase/common/components/VirtualizedList";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
import { useGetIcon } from "metabase/hooks/use-icon";
@@ -432,7 +429,7 @@ function CollectionItemList({ parent }: { parent: MiniPickerCollectionItem }) {
});
const allItems: CollectionItem[] = (data?.data ?? []).filter(
- (item) => canCollectionCardBeUsed(item) && !isHidden(item),
+ (item) => !isHidden(item),
);
const typeFilter = parent.childTypeFilter;
const items = typeFilter
diff --git a/frontend/src/metabase/common/components/Pickers/utils.ts b/frontend/src/metabase/common/components/Pickers/utils.ts
index d9d977cb3bf..23e57784662 100644
--- a/frontend/src/metabase/common/components/Pickers/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/utils.ts
@@ -1,27 +1,10 @@
import _ from "underscore";
import { PLUGIN_LIBRARY } from "metabase/plugins";
-import type {
- CollectionId,
- CollectionItem,
- CollectionItemModel,
-} from "metabase-types/api";
+import type { CollectionId, CollectionItemModel } from "metabase-types/api";
import type { OmniPickerCollectionItem, OmniPickerItem } from "./EntityPicker";
-/**
- * check if a card can be used as the starting point for a new query
- */
-export const canCollectionCardBeUsed = (
- item: CollectionItem | OmniPickerItem,
-): boolean => {
- if (item.model === "card") {
- return "can_run_adhoc_query" in item ? !!item.can_run_adhoc_query : true;
- }
-
- return true;
-};
-
/**
* Returns true if the item is the collection itself or a descendant of it.
* Used to prevent circular references when moving or editing collections.
@@ -78,7 +61,6 @@ export const getCollectionItemsOptions = ({
}) => {
return {
models: getValidCollectionItemModels(models),
- include_can_run_adhoc_query: models.includes("table"),
// After a downgrade from EE to OSS, isEnabled is false, and we want to show
// the Library (if it exists) within Our Analytics.
include_library: !PLUGIN_LIBRARY.isEnabled,
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQueryPreviewSidebar/NativeQueryPreviewSidebar.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQueryPreviewSidebar/NativeQueryPreviewSidebar.tsx
index 8505cbf2034..058088b81ef 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQueryPreviewSidebar/NativeQueryPreviewSidebar.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQueryPreviewSidebar/NativeQueryPreviewSidebar.tsx
@@ -15,7 +15,6 @@ type NativeQueryPreviewSidebarProps = {
convertToNativeButtonLabel?: string;
onConvertToNativeClick: (newQuestion: Question) => void;
readOnly?: boolean;
- disableDefaultLimit?: boolean;
};
export function NativeQueryPreviewSidebar({
@@ -24,7 +23,6 @@ export function NativeQueryPreviewSidebar({
convertToNativeButtonLabel,
onConvertToNativeClick,
readOnly,
- disableDefaultLimit,
}: NativeQueryPreviewSidebarProps) {
const { width: windowWidth } = useWindowSize();
const minSidebarWidth = 428;
@@ -47,7 +45,6 @@ export function NativeQueryPreviewSidebar({
buttonTitle={convertToNativeButtonLabel}
onConvertClick={onConvertToNativeClick}
readOnly={readOnly}
- disableDefaultLimit={disableDefaultLimit}
/>
</ResizableBox>
);
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
index ab9d5ae8ef8..2974fa3f5b7 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
@@ -196,7 +196,6 @@ export function QueryEditor({
convertToNativeButtonLabel={uiOptions?.convertToNativeButtonLabel}
onConvertToNativeClick={convertToNative}
readOnly={uiOptions?.readOnly}
- disableDefaultLimit={uiOptions?.disableDefaultLimit}
/>
)}
</Flex>
diff --git a/frontend/src/metabase/querying/editor/types.ts b/frontend/src/metabase/querying/editor/types.ts
index beedbee8d87..5931682270d 100644
--- a/frontend/src/metabase/querying/editor/types.ts
+++ b/frontend/src/metabase/querying/editor/types.ts
@@ -66,7 +66,6 @@ export type QueryEditorUiOptions = {
canConvertToNative?: boolean;
convertToNativeTitle?: string;
convertToNativeButtonLabel?: string;
- disableDefaultLimit?: boolean;
shouldDisableDataPickerItem?: (item: QueryEditorDataPickerItem) => boolean;
getDataPickerItemTooltip?: (
item: QueryEditorDataPickerItem,
diff --git a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
index 2203dc25c62..594f854c1f2 100644
--- a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
+++ b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
@@ -36,7 +36,6 @@ type NotebookNativePreviewProps = {
buttonTitle?: string;
onConvertClick: (newQuestion: Question) => void;
readOnly?: boolean;
- disableDefaultLimit?: boolean;
disableConvert?: boolean;
};
@@ -46,7 +45,6 @@ export const NotebookNativePreview = ({
buttonTitle,
onConvertClick,
readOnly,
- disableDefaultLimit,
disableConvert,
}: NotebookNativePreviewProps) => {
const database = question.database();
@@ -55,10 +53,7 @@ export const NotebookNativePreview = ({
const sourceQuery = question.query();
const canRun = Lib.canRun(sourceQuery, question.type());
- const queryForPayload = disableDefaultLimit
- ? Lib.disableDefaultLimit(sourceQuery)
- : sourceQuery;
- const payload = Lib.toJsQuery(queryForPayload);
+ const payload = Lib.toJsQuery(sourceQuery);
const { data, error, isFetching } = useGetNativeDatasetQuery(payload);
const showLoader = isFetching;
diff --git a/frontend/src/metabase/transforms/components/TransformEditor/utils.ts b/frontend/src/metabase/transforms/components/TransformEditor/utils.ts
index 04f7a0714d7..cd268fbe2c3 100644
--- a/frontend/src/metabase/transforms/components/TransformEditor/utils.ts
+++ b/frontend/src/metabase/transforms/components/TransformEditor/utils.ts
@@ -13,7 +13,6 @@ export function getEditorOptions(
canConvertToNative: true,
convertToNativeTitle: t`SQL for this transform`,
convertToNativeButtonLabel: t`Convert this transform to SQL`,
- disableDefaultLimit: true,
shouldDisableDatabasePickerItem: (item) => {
const database = databases.find((database) => database.id === item.id);
return !doesDatabaseSupportTransforms(database);
diff --git a/frontend/src/metabase/utils/dom.ts b/frontend/src/metabase/utils/dom.ts
index f5ceaee2347..fd6ec7d476a 100644
--- a/frontend/src/metabase/utils/dom.ts
+++ b/frontend/src/metabase/utils/dom.ts
@@ -3,8 +3,6 @@ import _ from "underscore";
import { isWithinIframe } from "metabase/utils/iframe";
import MetabaseSettings from "metabase/utils/settings";
-import { checkNotNull } from "./types";
-
// check whether scrollbars are visible to the user,
// this is off by default on Macs, but can be changed
// Always on on most other non mobile platforms
@@ -59,8 +57,17 @@ export function isObscured(
}
export function getSitePath(): string {
- const siteUrl = checkNotNull(MetabaseSettings.get("site-url"));
- return new URL(siteUrl).pathname.toLowerCase();
+ const siteUrl = MetabaseSettings.get("site-url");
+
+ if (!siteUrl) {
+ return "/";
+ }
+
+ try {
+ return new URL(siteUrl).pathname.toLowerCase();
+ } catch {
+ return "/";
+ }
}
export function getWithSiteUrl(url: string): string {
diff --git a/modules/drivers/athena/src/metabase/driver/athena.clj b/modules/drivers/athena/src/metabase/driver/athena.clj
index 0e13a8a0fef..9434e5cde34 100644
--- a/modules/drivers/athena/src/metabase/driver/athena.clj
+++ b/modules/drivers/athena/src/metabase/driver/athena.clj
@@ -371,7 +371,7 @@
(defmethod sql.qp/->honeysql [:athena :regex-match-first]
[driver [_ _opts arg pattern]]
- [:regexp_extract (sql.qp/->honeysql driver arg) pattern])
+ [:regexp_extract (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver pattern)])
(defn- run-query
"Workaround for avoiding the usage of 'advance' jdbc feature that are not implemented by the driver yet.
diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj
index ab3667898e5..dbcedf1f27e 100644
--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj
+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj
@@ -1413,7 +1413,7 @@
dataset-id (DatasetId/of project-id schema)]
(when-not (.getDataset client dataset-id (u/varargs BigQuery$DatasetOption))
;; Dataset doesn't exist, try to create it
- (let [sql [[(format "CREATE SCHEMA IF NOT EXISTS `%s`;" schema)]]]
+ (let [sql [[(format "CREATE SCHEMA IF NOT EXISTS %s;" (sql.u/quote-name :bigquery-cloud-sdk :table schema))]]]
(driver/execute-raw-queries! driver conn-spec sql)))))
(defmethod driver/schema-exists? :bigquery-cloud-sdk
diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
index 74801bc2a10..6a4c0acf419 100644
--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
@@ -571,8 +571,8 @@
(sql.u/validate-convert-timezone-args timestamptz? target-timezone source-timezone)
(-> (if timestamptz?
hsql-form
- [:timestamp hsql-form (or source-timezone (driver-api/results-timezone-id))])
- (datetime target-timezone)
+ [:timestamp hsql-form (sql.qp/->honeysql driver (or source-timezone (driver-api/results-timezone-id)))])
+ (datetime (sql.qp/->honeysql driver target-timezone))
(with-temporal-type :datetime))))
(defmethod sql.qp/float-dbtype :bigquery-cloud-sdk
@@ -923,8 +923,13 @@
;;; | Other Driver / SQLDriver Method Implementations |
;;; +----------------------------------------------------------------------------------------------------------------+
+(def ^:private bigquery-interval-units
+ #{:microsecond :millisecond :second :minute :hour :day :week :month :quarter :year})
+
(defn- interval [amount unit]
;; todo: can bigquery have an expression here or just a numeric literal?
+ (when-not (contains? bigquery-interval-units unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
[:raw (format "INTERVAL %d %s" (int amount) (name unit))])
;; We can coerce the HoneySQL form this wraps to whatever we want and generate the appropriate SQL.
@@ -1036,9 +1041,18 @@
[driver [_ _opts field]]
[:log (sql.qp/->honeysql driver field) [:inline 10]])
+(sql/register-dialect!
+ ::bigquery
+ (assoc (sql/get-dialect :mysql)
+ :quote (fn [s]
+ (str \` (-> s
+ (str/replace "\\" "\\\\")
+ (str/replace "`" "\\`"))
+ \`))))
+
(defmethod sql.qp/quote-style :bigquery-cloud-sdk
[_driver]
- :mysql)
+ ::bigquery)
(mu/defmethod sql.params.substitution/->replacement-snippet-info [:bigquery-cloud-sdk :metabase.lib.parameters.parse.types/field-filter]
[driver :- :keyword
diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
index 75ee76eb8ca..6d66a83c810 100644
--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
@@ -1637,5 +1637,5 @@
(testing "no clustering index -> no clause"
(is (nil? (#'bigquery/clustering-clause [{:kind :btree :columns [{:name "category"}]}]))))
(testing "a SQL-injection payload in a clustering column is backtick-escaped, so it can only ever be an identifier"
- (is (= "CLUSTER BY `c``; DROP TABLE x; --`"
+ (is (= "CLUSTER BY `c\\`; DROP TABLE x; --`"
(#'bigquery/clustering-clause [{:kind :clustering :columns [{:name "c`; DROP TABLE x; --"}]}])))))
diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
index a98c3462202..4ec50226e79 100644
--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
@@ -31,7 +31,14 @@
[java.util Arrays UUID]))
;; (set! *warn-on-reflection* true) ;; isn't enabled because of Arrays/toString call
-(defmethod sql.qp/quote-style :clickhouse [_] :mysql)
+(sql/register-dialect!
+ ::clickhouse
+ (update (sql/get-dialect :mysql) :quote
+ (fn [mysql-quote]
+ (fn [s]
+ (mysql-quote (str/replace s "\\" "\\\\"))))))
+
+(defmethod sql.qp/quote-style :clickhouse [_] ::clickhouse)
;; without try, there might be test failures when QP is not yet initialized
;; e.g., when a test is preparing the dataset
@@ -213,9 +220,9 @@
expr
[:'toIntervalSecond
[:'minus
- [:'timeZoneOffset [:'toTimeZone expr target-timezone]]
- [:'timeZoneOffset [:'toTimeZone expr source-timezone]]]]]
- [:'toTimeZone expr target-timezone])))
+ [:'timeZoneOffset [:'toTimeZone expr (sql.qp/->honeysql driver target-timezone)]]
+ [:'timeZoneOffset [:'toTimeZone expr (sql.qp/->honeysql driver source-timezone)]]]]]
+ [:'toTimeZone expr (sql.qp/->honeysql driver target-timezone)])))
(defmethod sql.qp/current-datetime-honeysql-form :clickhouse
[_]
@@ -290,13 +297,23 @@
[driver [_ _opts field]]
[:'log10 (sql.qp/->honeysql driver field)])
+(defn- format-quantile
+ [_fn [p field]]
+ (let [[p-sql & p-args] (sql/format-expr p {:nested true})
+ [field-sql & field-args] (sql/format-expr field {:nested true})]
+ (into [(format "quantile(%s)(%s)" p-sql field-sql)]
+ cat
+ [p-args field-args])))
+
+(sql/register-fn! ::quantile #'format-quantile)
+
(defmethod sql.qp/->honeysql [:clickhouse :percentile]
[driver [_ _opts field p]]
- [:raw "quantile(" (sql.qp/->honeysql driver p) ")(" (sql.qp/->honeysql driver field) ")"])
+ [::quantile (sql.qp/->honeysql driver p) (sql.qp/->honeysql driver field)])
(defmethod sql.qp/->honeysql [:clickhouse :regex-match-first]
[driver [_ _opts arg pattern]]
- [:'extract (sql.qp/->honeysql driver arg) pattern])
+ [:'extract (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver pattern)])
(defmethod sql.qp/->honeysql [:clickhouse :split-part]
[driver [_ _opts text divider position]]
@@ -357,6 +374,7 @@
[driver value]
(let [[_ {:keys [base-type]} value] value]
(when (some? value)
+ (sql.qp/check-value-literal driver value)
(condp #(isa? %2 %1) base-type
:type/IPAddress [:'toIPv4 value]
(sql.qp/->honeysql driver value)))))
@@ -450,8 +468,13 @@
(h2x/with-database-type-info (h2x/database-type expr-hsql))))
{::rows-between-unbounded []}))
+(def ^:private clickhouse-interval-units
+ #{:millisecond :second :minute :hour :day :week :month :quarter :year})
+
(defmethod sql.qp/add-interval-honeysql-form :clickhouse
[_ dt amount unit]
+ (when-not (contains? clickhouse-interval-units unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
(let [type-info (h2x/type-info dt)]
(cond-> (h2x/+ dt [:raw (format "INTERVAL %d %s" (int amount) (name unit))])
type-info (h2x/with-type-info type-info))))
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
index ba7643d9eff..560ca8cd7f0 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
@@ -494,6 +494,11 @@ function(bin) {
(or (nil? value) (= value ""))
value
+ (coll? value)
+ (throw (ex-info (tru "Invalid filter value: expected a scalar literal.")
+ {:type driver-api/qp.error-type.invalid-query
+ :value value}))
+
(isa? base-type :type/MongoBSONID)
(ObjectId. (str value))
@@ -875,6 +880,9 @@ function(bin) {
[:>= field min-val]
[:<= field max-val]]))
+(defn- escape-regex-literal [s]
+ (str/replace (str s) #"[.*+?^${}()|\[\]\\]" "\\\\$0"))
+
(defn- str-match-pattern [field options prefix value suffix]
(if (driver-api/is-clause? ::not value)
{$not (str-match-pattern field options prefix (second value) suffix)}
@@ -883,7 +891,7 @@ function(bin) {
"Wrong prefix or suffix value.")
{$regexMatch {"input" (->rvalue field)
"regex" (if (= (first value) :value)
- (str prefix (->rvalue value) suffix)
+ (str prefix (escape-regex-literal (->rvalue value)) suffix)
{$concat (into [] (remove nil?) [(when (some? prefix) {$literal prefix})
(->rvalue value)
(when (some? suffix) {$literal suffix})])})
diff --git a/modules/drivers/oracle/src/metabase/driver/oracle.clj b/modules/drivers/oracle/src/metabase/driver/oracle.clj
index b6b63ed960a..c881db2ff54 100644
--- a/modules/drivers/oracle/src/metabase/driver/oracle.clj
+++ b/modules/drivers/oracle/src/metabase/driver/oracle.clj
@@ -328,7 +328,7 @@
(sql.u/validate-convert-timezone-args has-timezone? target-timezone source-timezone)
(-> (if has-timezone?
expr
- [:from_tz expr (or source-timezone (driver-api/results-timezone-id))])
+ [:from_tz expr (sql.qp/->honeysql driver (or source-timezone (driver-api/results-timezone-id)))])
(h2x/at-time-zone target-timezone)
h2x/->timestamp)))
diff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
index 5ebfaddecc0..fe78f21bc82 100644
--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
@@ -473,6 +473,14 @@
(defmethod sql.qp/unix-timestamp->honeysql [:snowflake :milliseconds] [_ _ expr] [:to_timestamp_tz expr 3])
(defmethod sql.qp/unix-timestamp->honeysql [:snowflake :microseconds] [_ _ expr] [:to_timestamp_tz expr 6])
+(def ^:private snowflake-date-part-units
+ #{:millisecond :second :minute :hour :day :week :month :quarter :year})
+
+(defn- snowflake-date-part [unit]
+ (when-not (contains? snowflake-date-part-units unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
+ (name unit))
+
(defmethod sql.qp/add-interval-honeysql-form :snowflake
[_driver hsql-form amount unit]
;; return type is always the same as expr type, unless expr is a DATE and you're adding something not in a DATE e.g.
@@ -484,7 +492,7 @@
"timestamp_ntz"
db-type)]
(-> [:dateadd
- [:raw (name unit)]
+ [:raw (snowflake-date-part unit)]
[:inline (int amount)]
hsql-form]
(h2x/with-database-type-info return-type))))
@@ -577,7 +585,7 @@
y (if (h2x/is-of-type? y "timestamptz")
[:convert_timezone (driver-api/results-timezone-id) y]
y)]
- [:datediff [:raw (name unit)] x y]))
+ [:datediff [:raw (snowflake-date-part unit)] x y]))
(defn- time-zoned-extract
"Same as `extract` but converts the arg to the results time zone if it's a timestamptz."
@@ -729,9 +737,10 @@
(sql.u/validate-convert-timezone-args timestamptz? target-timezone source-timezone)
(-> (if timestamptz?
[:to_timestamp_ntz
- [:convert_timezone target-timezone hsql-form]]
+ [:convert_timezone (sql.qp/->honeysql driver target-timezone) hsql-form]]
[:to_timestamp_ntz
- [:convert_timezone (or source-timezone (driver-api/results-timezone-id)) target-timezone hsql-form]])
+ [:convert_timezone (sql.qp/->honeysql driver (or source-timezone (driver-api/results-timezone-id)))
+ (sql.qp/->honeysql driver target-timezone) hsql-form]])
(h2x/with-database-type-info "timestampntz"))))
(defmethod sql.qp/->honeysql [:snowflake :relative-datetime]
diff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
index a3f0bae0397..7a224d1da97 100644
--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
@@ -254,18 +254,27 @@
[:inline x]
x))
+(def ^:private allowed-dateparts
+ #{:year :quarter :month :dayofyear :day :week :iso_week :weekday
+ :hour :minute :second :millisecond :microsecond :nanosecond})
+
+(defn- datepart-token [unit]
+ (when-not (contains? allowed-dateparts unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
+ (name unit))
+
;; See https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-ver15
(defn- date-part [unit expr]
- (-> [:datepart [:raw (name unit)] expr]
+ (-> [:datepart [:raw (datepart-token unit)] expr]
(h2x/with-database-type-info "integer")))
(defn- date-add [unit & exprs]
- (into [:dateadd [:raw (name unit)]]
+ (into [:dateadd [:raw (datepart-token unit)]]
(map maybe-inline-number)
exprs))
(defn- date-diff [unit x y]
- [:datediff_big [:raw (name unit)] x y])
+ [:datediff_big [:raw (datepart-token unit)] x y])
;; See https://docs.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql for
;; details on the functions we're using.
@@ -751,6 +760,7 @@
(defmethod sql.qp/escape-like-pattern :sqlserver
[_driver like-pattern]
(-> like-pattern
+ (str/replace "[" "[[]")
(str/replace "\\" "[\\]")
(str/replace "%" "[%]")
(str/replace "_" "[_]")))
@@ -1196,7 +1206,7 @@
[driver conn-spec schema]
(let [sql [[(format "IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = %s) EXEC('CREATE SCHEMA %s;');"
(sql.u/quote-literal schema :ansi)
- (quote-schema schema))]]]
+ (sql.u/escape-sql (quote-schema schema) :ansi))]]]
(driver/execute-raw-queries! driver conn-spec sql)))
(defmethod driver/rename-table! :sqlserver
diff --git a/src/metabase/actions/args.clj b/src/metabase/actions/args.clj
index 98b8bf6442d..ecf00b368a8 100644
--- a/src/metabase/actions/args.clj
+++ b/src/metabase/actions/args.clj
@@ -3,6 +3,7 @@
;; legacy usage, do not use this in new code
^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli.registry :as mr]
@@ -49,7 +50,8 @@
(mr/def ::common
[:map [:database ::lib.schema.id/database]])
-(mr/def ::row [:map-of :string :any])
+(mr/def ::row
+ [:map-of :string [:ref ::lib.schema.parameter/parameter.value]])
;;; Common base schema for all CRUD model row Actions. All CRUD model row Actions at least require
;;;
diff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.clj
index daf40ece3d5..20b0a7d4e0c 100644
--- a/src/metabase/actions/execution.clj
+++ b/src/metabase/actions/execution.clj
@@ -188,47 +188,55 @@
(mu/defn execute-action!
"Execute the given action with the given parameters of shape `{<parameter-id> <value>}."
- [action request-parameters]
- (let [;; if a value is supplied for a hidden parameter, it should raise an error
- field-settings (get-in action [:visualization_settings :fields])
- hidden-param-ids (->> (vals field-settings)
- (filter :hidden)
- (map :id))
- destination-param-ids (set/difference (set (map :id (:parameters action))) (set hidden-param-ids))
- _ (check-no-extra-parameters request-parameters destination-param-ids)
- ;; add default values for missing parameters (including hidden ones)
- all-param-ids (set (map :id (:parameters action)))
- provided-param-ids (set (keys request-parameters))
- missing-param-ids (set/difference all-param-ids provided-param-ids)
- missing-param-defaults (into {}
- (keep (fn [param-id]
- (when-let [default-value (get-in field-settings [param-id :defaultValue])]
- [param-id default-value])))
- missing-param-ids)
- request-parameters (merge missing-param-defaults request-parameters)]
- (case (:type action)
- :implicit
- (execute-implicit-action! action request-parameters)
- (:query :http)
- (execute-custom-action! action request-parameters)
- (throw (ex-info (tru "Unknown action type {0}." (name (:type action :unknown))) action)))))
+ ([action request-parameters]
+ (execute-action! action request-parameters nil))
+ ([action request-parameters {:keys [allow-http-actions?] :or {allow-http-actions? true}}]
+ (when (and (= (:type action) :http) (not allow-http-actions?))
+ (throw (ex-info (tru "HTTP actions cannot be executed from public endpoints.")
+ {:status-code 403})))
+ (let [;; if a value is supplied for a hidden parameter, it should raise an error
+ field-settings (get-in action [:visualization_settings :fields])
+ hidden-param-ids (->> (vals field-settings)
+ (filter :hidden)
+ (map :id))
+ destination-param-ids (set/difference (set (map :id (:parameters action))) (set hidden-param-ids))
+ _ (check-no-extra-parameters request-parameters destination-param-ids)
+ ;; add default values for missing parameters (including hidden ones)
+ all-param-ids (set (map :id (:parameters action)))
+ provided-param-ids (set (keys request-parameters))
+ missing-param-ids (set/difference all-param-ids provided-param-ids)
+ missing-param-defaults (into {}
+ (keep (fn [param-id]
+ (when-let [default-value (get-in field-settings [param-id :defaultValue])]
+ [param-id default-value])))
+ missing-param-ids)
+ request-parameters (merge missing-param-defaults request-parameters)]
+ (case (:type action)
+ :implicit
+ (execute-implicit-action! action request-parameters)
+ (:query :http)
+ (execute-custom-action! action request-parameters)
+ (throw (ex-info (tru "Unknown action type {0}." (name (:type action :unknown))) action))))))
(mu/defn execute-dashcard!
"Execute the given action in the dashboard/dashcard context with the given parameters
of shape `{<parameter-id> <value>}."
- [dashboard-id :- ::lib.schema.id/dashboard
- dashcard-id :- ::lib.schema.id/dashcard
- request-parameters :- [:maybe [:map-of :string :any]]]
- (let [dashcard (api/check-404 (t2/select-one :model/DashboardCard
- :id dashcard-id
- :dashboard_id dashboard-id))
- action (api/check-404 (action/select-action :id (:action_id dashcard)))]
- (analytics/track-event! :snowplow/action
- {:event :action-executed
- :source :dashboard
- :type (:type action)
- :action_id (:id action)})
- (execute-action! action request-parameters)))
+ ([dashboard-id dashcard-id request-parameters]
+ (execute-dashcard! dashboard-id dashcard-id request-parameters nil))
+ ([dashboard-id :- ::lib.schema.id/dashboard
+ dashcard-id :- ::lib.schema.id/dashcard
+ request-parameters :- [:maybe [:map-of :string :any]]
+ opts]
+ (let [dashcard (api/check-404 (t2/select-one :model/DashboardCard
+ :id dashcard-id
+ :dashboard_id dashboard-id))
+ action (api/check-404 (action/select-action :id (:action_id dashcard)))]
+ (analytics/track-event! :snowplow/action
+ {:event :action-executed
+ :source :dashboard
+ :type (:type action)
+ :action_id (:id action)})
+ (execute-action! action request-parameters opts))))
(defn- fetch-implicit-action-values
[action request-parameters]
diff --git a/src/metabase/actions/http_action.clj b/src/metabase/actions/http_action.clj
index 1f6dbfef033..07513c5f1c6 100644
--- a/src/metabase/actions/http_action.clj
+++ b/src/metabase/actions/http_action.clj
@@ -123,6 +123,13 @@
(defn execute-http-action!
"Calls an http endpoint based on action and params"
+ [_action _params->value]
+ (throw (ex-info (tru "HTTP actions are disabled.")
+ {:type :http
+ :status-code 400})))
+
+#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var :unused-private-var]}
+(defn- execute-http-action-impl!
[action params->value]
(try
(let [{:keys [method url body headers]} (:template action)
diff --git a/src/metabase/actions/schema.clj b/src/metabase/actions/schema.clj
index 220575eb4b2..95225f09068 100644
--- a/src/metabase/actions/schema.clj
+++ b/src/metabase/actions/schema.clj
@@ -1,9 +1,12 @@
(ns metabase.actions.schema
(:require
+ [metabase.lib-be.schema :as lib-be.schema]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.parameters.schema :as parameters.schema]
- [metabase.queries.schema :as queries.schema]
[metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.json :as json]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]))
@@ -12,6 +15,57 @@
"Valid Action ID"
pos-int?)
+(def ^:private prefetch-parameter-values-message
+ (deferred-tru "value must be a JSON object mapping parameter ids to scalar values."))
+
+(defn- decode-prefetch-parameter-values
+ [x]
+ (let [parsed (if (string? x)
+ (try
+ (json/decode x)
+ (catch Throwable _
+ (throw (ex-info (str prefetch-parameter-values-message) {:status-code 400}))))
+ x)]
+ (when-not (map? parsed)
+ (throw (ex-info (str prefetch-parameter-values-message) {:status-code 400})))
+ parsed))
+
+(defn- parameter-values-schema
+ [{:keys [decoded-key-schema key-schema value-schema message decode]}]
+ (let [strict [:map-of key-schema value-schema]]
+ [:schema
+ (cond-> {:description message}
+ decode (assoc :decode/api decode))
+ [:and
+ [:map-of decoded-key-schema :any]
+ [:fn {:error/fn (fn [_ _] message)}
+ #(mr/validate strict %)]]]))
+
+(mr/def ::prefetch-parameter-values
+ (parameter-values-schema
+ {:decoded-key-schema :string
+ :key-schema [:ref ::lib.schema.parameter/id]
+ :value-schema [:ref ::lib.schema.parameter/parameter.value.scalar]
+ :message prefetch-parameter-values-message
+ :decode decode-prefetch-parameter-values}))
+
+(def ^:private execute-parameter-values-message
+ (deferred-tru "value must map parameter ids to scalar values."))
+
+(mr/def ::execute-parameter-values
+ (parameter-values-schema
+ {:decoded-key-schema :keyword
+ :key-schema :keyword
+ :value-schema [:ref ::lib.schema.parameter/parameter.value]
+ :message execute-parameter-values-message}))
+
+(mr/def ::execute-parameter-values.string-keys
+ (parameter-values-schema
+ {:decoded-key-schema :string
+ :key-schema [:ref ::lib.schema.parameter/id]
+ :value-schema [:ref ::lib.schema.parameter/parameter.value]
+ :message execute-parameter-values-message}))
+
(mr/def ::type
[:enum
{:decode/normalize keyword
@@ -64,7 +118,7 @@
(def ^:private query-action-entries
[[:database_id {:optional true} [:maybe ::lib.schema.id/database]]
- [:dataset_query {:optional true} [:maybe ::queries.schema/query]]])
+ [:dataset_query {:optional true} [:maybe ::lib-be.schema/maybe-legacy-or-empty-query]]])
(mr/def ::query-action
(into [:map] query-action-entries))
@@ -102,15 +156,15 @@
[:public_uuid {:optional true} [:maybe ms/UUIDString]]
[:made_public_by_id {:optional true} [:maybe ::lib.schema.id/user]]
[:creator_id {:optional true} [:maybe ::lib.schema.id/user]]])])]
- (mu/dispatched-map
- ;; dispatch on the normalized type so a JSON string picks the same branch as a keyword
- (comp keyword :type)
- common
- [[:http http-action-entries]
- [:implicit implicit-action-entries]
- [:query query-action-entries]
+ [:merge
+ (into [:map] common)
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
+ [:http (into [:map] http-action-entries)]
+ [:implicit (into [:map] implicit-action-entries)]
+ [:query (into [:map] query-action-entries)]
;; a partial update need not repeat `:type`; accept every type's keys rather than dropping them
- [nil (into [] cat [http-action-entries implicit-action-entries query-action-entries])]])))
+ [nil (into [:map] cat [http-action-entries implicit-action-entries query-action-entries])]]]))
(mr/def ::action
"An Action as it should appear when we `SELECT` it from the app DB."
diff --git a/src/metabase/actions/types.clj b/src/metabase/actions/types.clj
index 0a9a2f587bf..d8237b62c0b 100644
--- a/src/metabase/actions/types.clj
+++ b/src/metabase/actions/types.clj
@@ -1,5 +1,6 @@
(ns metabase.actions.types
(:require
+ [malli.util :as mut]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]))
@@ -22,7 +23,8 @@
;; Relaxed, as we support it being
(mr/def ::scope.raw
- (into [:or] raw-scope-types))
+ (into [:or] (for [s raw-scope-types]
+ (mut/merge s [:map [:type {:optional true} :keyword]]))))
;; All derivable or unknown data removed, so that this is safe to use as a key.
(mr/def ::scope.normalized
diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.clj
index 5ba649ff060..063b176fac9 100644
--- a/src/metabase/actions_rest/api.clj
+++ b/src/metabase/actions_rest/api.clj
@@ -130,6 +130,9 @@
(throw (ex-info (tru "HTTP actions are not supported.")
{:type :http
:status-code 400})))
+ (when-let [model-id (:model_id action)]
+ (when (not= model-id (:model_id existing-action))
+ (api/write-check :model/Card model-id)))
(actions/update! (assoc action :id id) existing-action))
(let [{:keys [parameters type] :as action} (actions/select-action :id id)]
(analytics/track-event! :snowplow/action
@@ -190,7 +193,7 @@
[:action-id ms/PositiveInt]]
_query-params
{:keys [parameters]} :- [:map
- [:parameters [:map-of :string :any]]]]
+ [:parameters ::actions.schema/prefetch-parameter-values]]]
(actions/check-actions-enabled! action-id)
(-> (actions/select-action :id action-id :archived false)
api/read-check
@@ -232,7 +235,7 @@
[:id [:or ::actions.schema/id ms/NanoIdString]]]
_query-params
{:keys [parameters], :as _body} :- [:maybe [:map
- [:parameters {:optional true} [:maybe [:map-of :keyword any?]]]]]]
+ [:parameters {:optional true} [:maybe ::actions.schema/execute-parameter-values]]]]]
(let [resolved-id (eid-translation/->id-or-404 :action id)
{:keys [type] :as action} (api/read-check (actions/select-action :id resolved-id :archived false))]
(when (= type :http)
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index 837feb843c1..ef11d83952d 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -21,6 +21,7 @@
[metabase.events.core :as events]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.metabot.core :as metabot]
[metabase.metabot.tools.construct :as metabot-construct]
[metabase.metabot.tools.resources :as metabot-resources]
@@ -438,8 +439,8 @@
(-> query
(update-in [:middleware :js-int-to-string?] (fnil identity true))
qp/userland-query-with-default-constraints
- (update :info merge {:executed-by api/*current-user-id*
- :context :agent})))
+ (assoc :info {:executed-by api/*current-user-id*
+ :context :agent})))
(defn- prepare-combined-query
"Apply the tighter row cap used by the combined query endpoint. Each page is bounded
@@ -462,11 +463,12 @@
closed map, so top-level keys it doesn't declare (e.g. the legacy `source_entity` /
`referenced_entities` envelope, or a `:query` sent alongside a `:continuation_token`) are
dropped before the handler runs."
- [:multi {:dispatch (fn [m]
- (cond
- (:continuation_token m) :continuation
- (string? (:query m)) :handle
- :else :fresh))}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (fn [m]
+ (cond
+ (:continuation_token m) :continuation
+ (string? (:query m)) :handle
+ :else :fresh))}
[:continuation [:map {:closed true} [:continuation_token ms/NonBlankString]]]
[:handle [:map {:closed true} [:query ms/NonBlankString]]]
[:fresh ::construct-query-request]])
@@ -928,7 +930,7 @@
[:display {:optional true} [:maybe ::card-display]]
[:description {:optional true} [:maybe :string]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
- [:visualization_settings {:optional true} [:maybe ms/Map]]])
+ [:visualization_settings {:optional true} [:maybe ms/KeywordizedMap]]])
(mr/def ::create-question-response
[:map
@@ -978,7 +980,7 @@
[:display {:optional true} [:maybe ::card-display]]
[:description {:optional true} [:maybe :string]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
- [:visualization_settings {:optional true} [:maybe ms/Map]]])
+ [:visualization_settings {:optional true} [:maybe ms/KeywordizedMap]]])
(mr/def ::create-metric-response
[:map
@@ -1044,7 +1046,7 @@
[:description {:optional true} [:maybe :string]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
[:display {:optional true} [:maybe ::card-display]]
- [:visualization_settings {:optional true} [:maybe ms/Map]]
+ [:visualization_settings {:optional true} [:maybe ms/KeywordizedMap]]
[:archived {:optional true} [:maybe :boolean]]
[:query {:optional true} [:maybe ms/NonBlankString]]])
@@ -1102,7 +1104,7 @@
[:description {:optional true} [:maybe :string]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
[:display {:optional true} [:maybe ::card-display]]
- [:visualization_settings {:optional true} [:maybe ms/Map]]
+ [:visualization_settings {:optional true} [:maybe ms/KeywordizedMap]]
[:archived {:optional true} [:maybe :boolean]]
[:query {:optional true} [:maybe ms/NonBlankString]]])
@@ -1312,7 +1314,8 @@
The add actions take an optional `tab_id` (a tab on this dashboard); omitted, new cards land on
the dashboard's first tab."
- [:multi {:dispatch :action}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch :action}
["add" [:map {:closed true}
[:action [:= "add"]]
[:card_id ms/PositiveInt]
diff --git a/src/metabase/analytics/api/proxy.clj b/src/metabase/analytics/api/proxy.clj
index 2f5b7ecfb36..09fa0f654e6 100644
--- a/src/metabase/analytics/api/proxy.clj
+++ b/src/metabase/analytics/api/proxy.clj
@@ -24,7 +24,7 @@
stringifies every field value, so the values are always strings."
[:map
[:schema ms/NonBlankString]
- [:data [:sequential [:map-of :keyword :string]]]])
+ [:data [:sequential {:max 100} [:map-of :keyword :string]]]])
;; No response schema: the body is an opaque relay of the collector's own response. The tracker drives its retry
;; outbox off the HTTP status, so we forward status + body verbatim; a fabricated schema would be misleading.
diff --git a/src/metabase/api/macros.clj b/src/metabase/api/macros.clj
index 7830c4fded6..2ba61385a7a 100644
--- a/src/metabase/api/macros.clj
+++ b/src/metabase/api/macros.clj
@@ -302,10 +302,21 @@
(str/replace #" " "-")
(str/replace #":" ""))))
+(def ^:private keywordize-declared-map-keys-transformer
+ (mtx/transformer
+ {:name :keywordize-declared-map-keys
+ :decoders {:map {:compile (fn [schema _]
+ (let [keyword-keys (into #{}
+ (comp (filter keyword?)
+ (map u/qualified-name))
+ (malli.util/keys schema))]
+ (mtx/-transform-map-keys keyword-keys mtx/-string->keyword)))}}}))
+
(def ^:private decode-transformer
(mtx/transformer
(mtx/string-transformer)
(mtx/json-transformer)
+ keywordize-declared-map-keys-transformer
(mtx/default-value-transformer)
{:name :api}
{:name :normalize}
@@ -393,7 +404,9 @@
(when (seq path)
(or (malli.util/get-in schema path)
(recur (pop path)))))]
- (assoc-in m error-path (umd/describe nested-schema))))))
+ (assoc-in m error-path (if nested-schema
+ (umd/describe nested-schema)
+ "unexpected key"))))))
{}
(:errors explanation)))
diff --git a/src/metabase/app_db/core.clj b/src/metabase/app_db/core.clj
index 2809ef4242b..1a43d3e396c 100644
--- a/src/metabase/app_db/core.clj
+++ b/src/metabase/app_db/core.clj
@@ -17,6 +17,7 @@
[metabase.app-db.env :as mdb.env]
[metabase.app-db.format]
[metabase.app-db.h2 :as mdb.h2]
+ [metabase.app-db.honeysql-guard]
[metabase.app-db.jdbc-protocols :as mdb.jdbc-protocols]
[metabase.app-db.liquibase :as liquibase]
[metabase.app-db.query]
@@ -29,6 +30,7 @@
(set! *warn-on-reflection* true)
(comment metabase.app-db.format/keep-me
+ metabase.app-db.honeysql-guard/keep-me
metabase.app-db.query/keep-me
metabase.app-db.query-cancelation/keep-me)
diff --git a/src/metabase/app_db/encryption.clj b/src/metabase/app_db/encryption.clj
index d4469bb490e..92ed4719705 100644
--- a/src/metabase/app_db/encryption.clj
+++ b/src/metabase/app_db/encryption.clj
@@ -86,7 +86,7 @@
(doseq [[key value] (t2/select-fn->fn :key :value :model/Setting)]
(case key
"settings-last-updated" (let [current-timestamp-as-string-honeysql (h2x/cast (if (= db-type :mysql) :char :text)
- [:raw "current_timestamp"])]
+ (h2x/current-datetime-honeysql-form db-type))]
(t2/update! :conn conn :setting {:key key} {:value current-timestamp-as-string-honeysql}))
"encryption-check" (t2/update! :conn conn :setting {:key key} {:value (if encrypting? (encrypt-str-fn (str (random-uuid))) "unencrypted")})
(t2/update! :conn conn :setting
diff --git a/src/metabase/app_db/honeysql_guard.clj b/src/metabase/app_db/honeysql_guard.clj
new file mode 100644
index 00000000000..94ac743a57e
--- /dev/null
+++ b/src/metabase/app_db/honeysql_guard.clj
@@ -0,0 +1,104 @@
+(ns metabase.app-db.honeysql-guard
+ (:require
+ [metabase.util.honey-sql-2 :as h2x]
+ [methodical.core :as methodical]
+ [toucan2.pipeline :as t2.pipeline]
+ [toucan2.tools.identity-query :as t2.identity-query])
+ (:import
+ (toucan2.tools.identity_query IdentityQuery)))
+
+(set! *warn-on-reflection* true)
+
+(comment t2.identity-query/keep-me)
+
+(defn- allow-subquery?
+ [x]
+ (boolean (some-> x meta :allow-subquery)))
+
+(defn- raw-honeysql-map?
+ [x]
+ (and (map? x)
+ (contains? x :raw)))
+
+(defn- inline-honeysql-map?
+ [x]
+ (and (map? x)
+ (contains? x :inline)))
+
+(defn- raw-honeysql-form?
+ [x]
+ (and (sequential? x)
+ (= :raw (first x))))
+
+(defn- inline-honeysql-form?
+ [x]
+ (and (sequential? x)
+ (= :inline (first x))))
+
+(defn- allow-raw-sql?
+ [x]
+ (boolean (some-> x meta :allow-raw-sql)))
+
+(defn- safe-inline-value?
+ [x]
+ (cond
+ (coll? x) (every? safe-inline-value? x)
+ :else (or (nil? x) (boolean? x) (number? x))))
+
+(defn- safe-value?
+ [v]
+ (cond
+ (or (raw-honeysql-map? v) (inline-honeysql-map? v))
+ false
+
+ (raw-honeysql-form? v)
+ (allow-raw-sql? v)
+
+ (inline-honeysql-form? v)
+ (and (= 2 (count v))
+ (or (safe-inline-value? (second v))
+ (allow-raw-sql? v)))
+
+ (h2x/typed? v)
+ (safe-value? (second v))
+
+ (map? v)
+ (and (allow-subquery? v) (every? safe-value? (vals v)))
+
+ (coll? v)
+ (every? safe-value? v)
+
+ :else true))
+
+(defn- safe-row?
+ [row]
+ (cond
+ (map? row) (every? safe-value? (vals row))
+ (coll? row) (every? safe-value? row)
+ :else (safe-value? row)))
+
+(defn safe-syntax?
+ "Whether the compiled `query` map contains only allowed HoneySQL forms."
+ [query]
+ (if (map? query)
+ (and (not (or (raw-honeysql-map? query) (inline-honeysql-map? query)))
+ (every? safe-value? (vals (dissoc query :values :set :do-update-set)))
+ (every? safe-row? (:values query))
+ (safe-row? (:set query))
+ (safe-row? (:do-update-set query)))
+ (safe-value? query)))
+
+(methodical/defmethod t2.pipeline/build :around [:toucan.query-type/select.exists :default clojure.lang.IPersistentMap]
+ [query-type model parsed-args resolved-query]
+ (update-in (next-method query-type model parsed-args resolved-query)
+ [:select 0 0 1] vary-meta assoc :allow-subquery true))
+
+(methodical/defmethod t2.pipeline/compile :before :default
+ [_query-type model built-query]
+ (when-not (or (instance? IdentityQuery built-query)
+ (safe-syntax? built-query))
+ (throw (ex-info (str "A forbidden HoneySQL clause reached the app-DB compile step. Mark a deliberate subquery "
+ "with ^:allow-subquery, a deliberate [:raw ...] splice with ^:allow-raw-sql, and use "
+ "[:inline ...] only with a scalar literal.")
+ {:type ::unmarked-nested-map, :model model, :query built-query})))
+ built-query)
diff --git a/src/metabase/audit_app/task/truncate_audit_tables.clj b/src/metabase/audit_app/task/truncate_audit_tables.clj
index f0de7e38164..09b7448c66c 100644
--- a/src/metabase/audit_app/task/truncate_audit_tables.clj
+++ b/src/metabase/audit_app/task/truncate_audit_tables.clj
@@ -25,13 +25,13 @@
{:delete-from (keyword table-name)
:where [:in
:id
- {:select [:id]
- :from (keyword table-name)
- :where [:<=
- (keyword time-column)
- (t/minus (t/offset-date-time) (t/days (audit-app.settings/audit-max-retention-days)))]
- :order-by [[:id :asc]]
- :limit (audit-app.settings/audit-table-truncation-batch-size)}]}
+ ^:allow-subquery {:select [:id]
+ :from (keyword table-name)
+ :where [:<=
+ (keyword time-column)
+ (t/minus (t/offset-date-time) (t/days (audit-app.settings/audit-max-retention-days)))]
+ :order-by [[:id :asc]]
+ :limit (audit-app.settings/audit-table-truncation-batch-size)}]}
(:mysql :mariadb)
{:delete-from (keyword table-name)
diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.clj
index 23f2131dff4..6051bb4d0e2 100644
--- a/src/metabase/auth_identity/provider.clj
+++ b/src/metabase/auth_identity/provider.clj
@@ -58,6 +58,7 @@
[metabase.premium-features.core :refer [defenterprise]]
[metabase.util :as u]
[metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
[methodical.core :as methodical]
@@ -291,14 +292,26 @@
[_provider login-result]
login-result)
+(def ^:private authenticate-owned-keys
+ [:user-id :user_id :user :user-data :auth-identity :provider-id :success? :session
+ :error :message :mfa/pending? :mfa/methods :mfa/first-factor
+ :jwt-data :claims
+ :tenant-slug :tenant-attributes :user-provisioning-enabled?])
+
(methodical/defmethod login! :around ::provider
[provider request]
- (as-> (merge request (authenticate provider request)) $
- (assoc $ :user
- (or (when-let [user-id (:user-id $)]
- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id))
- (when-let [email (get-in $ [:user-data :email])]
- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email)))))
+ (as-> (merge (apply dissoc request authenticate-owned-keys)
+ (authenticate provider request)) $
+ (cond-> $
+ (true? (:success? $))
+ (assoc :user
+ (or (when-let [user-id (:user-id $)]
+ (if (pos-int? user-id)
+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id)
+ (log/errorf "Provider %s returned a non-positive-int :user-id (type %s); refusing to resolve a user."
+ provider (some-> user-id class .getName))))
+ (when-let [email (get-in $ [:user-data :email])]
+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email))))))
(cond-> $
(and (:provider-id $) (:user-data $))
(assoc-in [:user-data :provider-id] (:provider-id $)))
@@ -309,7 +322,7 @@
(next-method provider $))
(apply-mfa-gate provider $)
(cond-> $
- (and (:user $) (not (:mfa/pending? $))) (create-session! provider))
+ (and (true? (:success? $)) (:user $) (not (:mfa/pending? $))) (create-session! provider))
(select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data :claims :oidc-provider-key
:mfa/pending? :mfa/methods :mfa/first-factor])))
@@ -334,7 +347,11 @@
[:provider-id {:optional true} [:maybe :string]]]
provider :- :keyword]
(t2/with-transaction [_]
- (t2/update! :model/User user-id (select-keys user-data (conj (sso-user-fields) :is_active)))
+ (let [reactivating? (and (:is_active user-data)
+ (not (t2/select-one-fn :is_active :model/User :id user-id)))]
+ (t2/update! :model/User user-id
+ (cond-> (select-keys user-data (conj (sso-user-fields) :is_active))
+ reactivating? (assoc :is_superuser false))))
(when-not (t2/exists? :model/AuthIdentity :user_id user-id :provider (name provider))
(t2/insert! :model/AuthIdentity (cond-> {:user_id user-id :provider (name provider)}
(:provider-id user-data) (assoc :provider_id (:provider-id user-data)))))
diff --git a/src/metabase/bookmarks/models/bookmark.clj b/src/metabase/bookmarks/models/bookmark.clj
index b5b521a4995..8449b3a63df 100644
--- a/src/metabase/bookmarks/models/bookmark.clj
+++ b/src/metabase/bookmarks/models/bookmark.clj
@@ -72,57 +72,57 @@
(defn- bookmarks-union-query
[user-id]
(let [as-null (when (= (mdb/db-type) :postgres) (h2x/->integer nil))
- base-queries [{:select [:card_id
- [as-null :dashboard_id]
- [as-null :collection_id]
- [as-null :document_id]
- [as-null :exploration_id]
- [:card_id :item_id]
- [(h2x/literal "card") :type]
- :created_at]
- :from [:card_bookmark]
- :where [:= :user_id user-id]}
- {:select [[as-null :card_id]
- :dashboard_id
- [as-null :collection_id]
- [as-null :document_id]
- [as-null :exploration_id]
- [:dashboard_id :item_id]
- [(h2x/literal "dashboard") :type]
- :created_at]
- :from [:dashboard_bookmark]
- :where [:= :user_id user-id]}
- {:select [[as-null :card_id]
- [as-null :dashboard_id]
- :collection_id
- [as-null :document_id]
- [as-null :exploration_id]
- [:collection_id :item_id]
- [(h2x/literal "collection") :type]
- :created_at]
- :from [:collection_bookmark]
- :where [:= :user_id user-id]}
- {:select [[as-null :card_id]
- [as-null :dashboard_id]
- [as-null :collection_id]
- :document_id
- [as-null :exploration_id]
- [:document_id :item_id]
- [(h2x/literal "document") :type]
- :created_at]
- :from [:document_bookmark]
- :where [:= :user_id user-id]}]]
+ base-queries [^:allow-subquery {:select [:card_id
+ [as-null :dashboard_id]
+ [as-null :collection_id]
+ [as-null :document_id]
+ [as-null :exploration_id]
+ [:card_id :item_id]
+ [(h2x/literal "card") :type]
+ :created_at]
+ :from [:card_bookmark]
+ :where [:= :user_id user-id]}
+ ^:allow-subquery {:select [[as-null :card_id]
+ :dashboard_id
+ [as-null :collection_id]
+ [as-null :document_id]
+ [as-null :exploration_id]
+ [:dashboard_id :item_id]
+ [(h2x/literal "dashboard") :type]
+ :created_at]
+ :from [:dashboard_bookmark]
+ :where [:= :user_id user-id]}
+ ^:allow-subquery {:select [[as-null :card_id]
+ [as-null :dashboard_id]
+ :collection_id
+ [as-null :document_id]
+ [as-null :exploration_id]
+ [:collection_id :item_id]
+ [(h2x/literal "collection") :type]
+ :created_at]
+ :from [:collection_bookmark]
+ :where [:= :user_id user-id]}
+ ^:allow-subquery {:select [[as-null :card_id]
+ [as-null :dashboard_id]
+ [as-null :collection_id]
+ :document_id
+ [as-null :exploration_id]
+ [:document_id :item_id]
+ [(h2x/literal "document") :type]
+ :created_at]
+ :from [:document_bookmark]
+ :where [:= :user_id user-id]}]]
{:union-all (conj base-queries
- {:select [[as-null :card_id]
- [as-null :dashboard_id]
- [as-null :collection_id]
- [as-null :document_id]
- :exploration_id
- [:exploration_id :item_id]
- [(h2x/literal "exploration") :type]
- :created_at]
- :from [:exploration_bookmark]
- :where [:= :user_id user-id]})}))
+ ^:allow-subquery {:select [[as-null :card_id]
+ [as-null :dashboard_id]
+ [as-null :collection_id]
+ [as-null :document_id]
+ :exploration_id
+ [:exploration_id :item_id]
+ [(h2x/literal "exploration") :type]
+ :created_at]
+ :from [:exploration_bookmark]
+ :where [:= :user_id user-id]})}))
(mu/defn bookmarks-for-user :- [:sequential BookmarkResult]
"Get all bookmarks for a user. Each bookmark will have a string id made of the model and model-id, a type, and
diff --git a/src/metabase/cache/api.clj b/src/metabase/cache/api.clj
index b0455deb43c..fe1cee18559 100644
--- a/src/metabase/cache/api.clj
+++ b/src/metabase/cache/api.clj
@@ -4,6 +4,7 @@
[metabase.api.macros :as api.macros]
[metabase.cache.models.cache-config :as cache-config]
[metabase.config.core :as config]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.models.interface :as mi]
[metabase.premium-features.core :as premium-features]
[metabase.request.core :as request]
@@ -43,8 +44,9 @@
(mr/def ::cache-strategy.oss
"Schema for a caching strategy (OSS)"
- [:multi {:description (deferred-tru "cache strategy :type must be one of :nocache, :ttl")
- :dispatch cache-strategy-dispatch
+ [:multi {:description (deferred-tru "cache strategy :type must be one of :nocache, :ttl")
+ :decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch cache-strategy-dispatch
:error/fn (fn [{:keys [value]} _]
(tru "invalid cache strategy :type {0}, must be one of :nocache, :ttl"
(pr-str (:type value))))}
@@ -69,8 +71,9 @@
;;; the optional `:invalidated-at` keys
(mr/def ::cache-strategy.ee
"Schema for a caching strategy in EE when we have an premium token with `:cache-granular-controls`."
- [:multi {:description (deferred-tru "cache strategy :type must be one of :nocache, :ttl, :duration, :schedule")
- :dispatch cache-strategy-dispatch
+ [:multi {:description (deferred-tru "cache strategy :type must be one of :nocache, :ttl, :duration, :schedule")
+ :decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch cache-strategy-dispatch
:error/fn (fn [{:keys [value]} _]
(tru "invalid cache strategy :type {0}, must be one of :nocache, :ttl, :duration, :schedule"
(pr-str (:type value))))}
diff --git a/src/metabase/cache/models/cache_config.clj b/src/metabase/cache/models/cache_config.clj
index c1160ec09b0..1d381c4d493 100644
--- a/src/metabase/cache/models/cache_config.clj
+++ b/src/metabase/cache/models/cache_config.clj
@@ -165,12 +165,12 @@
[:collection.type :collection_type]]
:from [:cache_config]
:left-join [:report_card [:and
- [:= :model [:inline "question"]]
+ [:= :model "question"]
[:= :model_id :report_card.id]
(when collection
[:= :report_card.collection_id collection])]
:report_dashboard [:and
- [:= :model [:inline "dashboard"]]
+ [:= :model "dashboard"]
[:= :model_id :report_dashboard.id]
(when collection
[:= :report_dashboard.collection_id collection])]
@@ -180,8 +180,8 @@
:where [:and
[:in :model models]
[:case
- [:= :model [:inline "question"]] [:!= :report_card.id nil]
- [:= :model [:inline "dashboard"]] [:!= :report_dashboard.id nil]
+ [:= :model "question"] [:!= :report_card.id nil]
+ [:= :model "dashboard"] [:!= :report_dashboard.id nil]
:else true]]}))
(mu/defn get-list
diff --git a/src/metabase/channel/api/channel.clj b/src/metabase/channel/api/channel.clj
index 7b79638aef8..eb199494954 100644
--- a/src/metabase/channel/api/channel.clj
+++ b/src/metabase/channel/api/channel.clj
@@ -6,12 +6,18 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.channel.core :as channel]
+ [metabase.channel.impl.email :as channel.email]
+ [metabase.channel.impl.http :as channel.http]
+ [metabase.channel.impl.slack :as channel.slack]
+ [metabase.config.core :as config]
[metabase.events.core :as events]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
[metabase.util :as u]
- [metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.i18n :refer [deferred-tru tru]]
[metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -44,6 +50,48 @@
#(= "channel" (namespace (keyword %)))]
(deferred-tru "Must be a namespaced channel. E.g: channel/http")))
+(def ^:private TestChannelDetails
+ [:map
+ [:return-type [:enum "return-value" "throw"]]
+ [:return-value {:optional true} :any]])
+
+(defn- channel-body-schema
+ [common-entries & {:keys [details-optional?]}]
+ (let [details-entry (fn [schema]
+ (if details-optional?
+ [:details {:optional true} [:maybe schema]]
+ [:details schema]))]
+ [:merge
+ (into [:map] common-entries)
+ (into [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (fn [m]
+ (let [channel-type (some-> (:type m) keyword)]
+ (when (and channel-type (= "channel" (namespace channel-type)))
+ channel-type)))}]
+ (concat
+ [[:channel/http [:map (details-entry channel.http/HTTPDetails)]]
+ [:channel/email [:map [:details {:optional true} [:maybe channel.email/EmailDetails]]]]
+ [:channel/slack [:map (details-entry channel.slack/SlackDetails)]]]
+ (when config/is-test?
+ [[:channel/metabase-test [:map (details-entry TestChannelDetails)]]])
+ [[nil [:map [:details {:optional true}
+ [:maybe (into [:or]
+ (concat
+ (when config/is-test?
+ [TestChannelDetails])
+ [channel.slack/SlackDetails
+ channel.http/HTTPDetails
+ channel.email/EmailDetails]))]]]]]))]))
+
+(defn- details-schema-for-type
+ [channel-type]
+ (condp = channel-type
+ :channel/http channel.http/HTTPDetails
+ :channel/email channel.email/EmailDetails
+ :channel/slack channel.slack/SlackDetails
+ :channel/metabase-test (when config/is-test? TestChannelDetails)
+ nil))
+
;; 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
;;
@@ -52,12 +100,11 @@
"Create a channel"
[_route-params
_query-params
- {channel-name :name, :as body} :- [:map
- [:name ms/NonBlankString]
- [:description {:optional true} [:maybe ms/NonBlankString]]
- [:type ChannelType]
- [:details ms/Map]
- [:active {:optional true} [:maybe {:default true} :boolean]]]]
+ {channel-name :name, :as body} :- (channel-body-schema
+ [[:name ms/NonBlankString]
+ [:description {:optional true} [:maybe ms/NonBlankString]]
+ [:type ChannelType]
+ [:active {:optional true} [:maybe {:default true} :boolean]]])]
(perms/check-has-application-permission :setting)
(when (t2/exists? :model/Channel :name channel-name)
(throw (ex-info "Channel with that name already exists" {:status-code 409
@@ -84,13 +131,17 @@
[{:keys [id]} :- [:map
[:id ms/PositiveInt]]
_query-params
- body :- [:map
- [:name {:optional true} [:maybe ms/NonBlankString]]
- [:description {:optional true} [:maybe ms/NonBlankString]]
- [:type {:optional true} [:maybe ChannelType]]
- [:details {:optional true} [:maybe ms/Map]]
- [:active {:optional true} [:maybe :boolean]]]]
+ body :- (channel-body-schema
+ [[:name {:optional true} [:maybe ms/NonBlankString]]
+ [:description {:optional true} [:maybe ms/NonBlankString]]
+ [:type {:optional true} [:maybe ChannelType]]
+ [:active {:optional true} [:maybe :boolean]]]
+ :details-optional? true)]
(let [channel-before-update (api/write-check (t2/select-one :model/Channel id))]
+ (when (and (:details body) (nil? (:type body)))
+ (when-let [schema (details-schema-for-type (:type channel-before-update))]
+ (when-not (mr/validate schema (:details body))
+ (throw (ex-info (tru "Invalid channel details") {:status-code 400})))))
(t2/update! :model/Channel id body)
(u/prog1 (t2/select-one :model/Channel id)
(events/publish-event! :event/channel-update {:object <>
@@ -120,8 +171,7 @@
"Test a channel connection"
[_route-params
_query-params
- {:keys [type details]} :- [:map
- [:type ChannelType]
- [:details ms/Map]]]
+ {:keys [type details]} :- (channel-body-schema
+ [[:type ChannelType]])]
(perms/check-has-application-permission :setting)
(test-channel-connection! type details))
diff --git a/src/metabase/channel/email/messages.clj b/src/metabase/channel/email/messages.clj
index 0bed31e534f..3c61fff5279 100644
--- a/src/metabase/channel/email/messages.clj
+++ b/src/metabase/channel/email/messages.clj
@@ -258,11 +258,12 @@
:from [[:permissions_group_membership :pgm]]
:join [[:permissions_group :pg] [:= :pgm.group_id :pg.id]]
:where [:and
- [:exists {:select [1]
- :from [[:permissions :p]]
- :where [:and
- [:= :p.group_id :pg.id]
- [:= :p.object monitoring]]}]]
+ [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:permissions :p]]
+ :where [:and
+ [:= :p.group_id :pg.id]
+ [:= :p.object monitoring]]}]]
:group-by [:pgm.user_id]}
app-db/query
(mapv :user_id)))
diff --git a/src/metabase/channel/impl/email.clj b/src/metabase/channel/impl/email.clj
index 9c85dded7af..9a50692299c 100644
--- a/src/metabase/channel/impl/email.clj
+++ b/src/metabase/channel/impl/email.clj
@@ -43,6 +43,10 @@
{:template-type template-type
:channel-type :channel/email}))
+(def EmailDetails
+ "Schema for the connection `:details` of a `:channel/email` channel."
+ [:map {:closed true}])
+
(def ^:private EmailMessage
[:map
[:subject :string]
diff --git a/src/metabase/channel/impl/http.clj b/src/metabase/channel/impl/http.clj
index 23a8ba28425..7092cb57d0c 100644
--- a/src/metabase/channel/impl/http.clj
+++ b/src/metabase/channel/impl/http.clj
@@ -19,14 +19,12 @@
many columns) is truncated."
1200)
-(def ^:private string-or-keyword
- [:or :string :keyword])
-
-(def ^:private HTTPDetails
+(def HTTPDetails
+ "Schema for the connection `:details` of a `:channel/http` channel."
[:map {:closed true}
[:url ms/Url]
[:auth-method [:enum "none" "header" "query-param" "request-body"]]
- [:auth-info {:optional true} [:map-of string-or-keyword :any]]
+ [:auth-info {:optional true} ms/KeywordizedMap]
;; used by the frontend to display the auth info properly
[:fe-form-type {:optional true} [:enum "api-key" "bearer" "basic" "none"]]
;; request method
diff --git a/src/metabase/channel/impl/slack.clj b/src/metabase/channel/impl/slack.clj
index bacd169cda7..92fd366a04b 100644
--- a/src/metabase/channel/impl/slack.clj
+++ b/src/metabase/channel/impl/slack.clj
@@ -16,6 +16,11 @@
[metabase.util.malli :as mu]
[metabase.util.markdown :as markdown]))
+(def SlackDetails
+ "Schema for the connection `:details` of a `:channel/slack` channel."
+ [:map {:closed true}
+ [:channel :string]])
+
(defn- notification-recipient->channel
"Returns the Slack channel target for a raw-value notification recipient.
Prefers the immutable `:channel_id` (e.g. \"C0ABC123\") over the display `:value`
diff --git a/src/metabase/channel/models/channel.clj b/src/metabase/channel/models/channel.clj
index 8150d098f13..1ebd6155447 100644
--- a/src/metabase/channel/models/channel.clj
+++ b/src/metabase/channel/models/channel.clj
@@ -5,6 +5,7 @@
[metabase.analytics.core :as analytics.core]
[metabase.api.common :as api]
[metabase.channel.template.handlebars :as handlebars]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
[metabase.permissions.core :as perms]
@@ -105,7 +106,8 @@
[:type (apply ms/enum-keywords-and-strings channel-template-details-type)]
[:subject string?]
[:recipient-type {:optional true} (ms/enum-keywords-and-strings :cc :bcc)]]
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:email/handlebars-resource
[:map
[:path [:and
@@ -124,12 +126,12 @@
(mr/def ::ChannelTemplate
"Channel Template schema."
- (mu/dispatched-map
- ;; keywordize: the raw JSON body has `:channel_type` as a string, which would match no branch
- (comp keyword :channel_type)
- channel-template-entries
- [[:channel/email [[:details ::ChannelTemplateEmailDetails]]]
- [::mc/default []]]))
+ [:merge
+ (into [:map] channel-template-entries)
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :channel_type)}
+ [:channel/email [:map [:details ::ChannelTemplateEmailDetails]]]
+ [::mc/default [:map]]]])
(mr/def ::ChannelTemplateEmailDetailsUserProvided
"Email template details schema for API-provided templates. Only handlebars-text is allowed;
@@ -142,12 +144,12 @@
(mr/def ::ChannelTemplateUserProvided
"Channel Template schema for API-provided templates. Does not allow handlebars-resource."
- (mu/dispatched-map
- ;; keywordize: the raw JSON body has `:channel_type` as a string, which would match no branch
- (comp keyword :channel_type)
- channel-template-entries
- [[:channel/email [[:details ::ChannelTemplateEmailDetailsUserProvided]]]
- [::mc/default []]]))
+ [:merge
+ (into [:map] channel-template-entries)
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :channel_type)}
+ [:channel/email [:map [:details ::ChannelTemplateEmailDetailsUserProvided]]]
+ [::mc/default [:map]]]])
(defn- check-valid-channel-template
[channel-template]
diff --git a/src/metabase/cmd/core.clj b/src/metabase/cmd/core.clj
index b507f9103dd..6fe08f88ca0 100644
--- a/src/metabase/cmd/core.clj
+++ b/src/metabase/cmd/core.clj
@@ -202,7 +202,6 @@
["-S" "--no-settings" "Do not export settings.yaml"]
["-D" "--no-data-model" "Do not export any data model entities; useful for subsequent exports."]
["-f" "--include-field-values" "Include field values along with field metadata."]
- ["-s" "--include-database-secrets" "Include database connection details (in plain text; use caution)."]
["-e" "--continue-on-error" "Do not break execution on errors."]
["" "--full-stacktrace" "Output full stacktraces on errors."]]}
[path & options]
diff --git a/src/metabase/collections/curation.clj b/src/metabase/collections/curation.clj
index d1fe603be18..04c1f46fa31 100644
--- a/src/metabase/collections/curation.clj
+++ b/src/metabase/collections/curation.clj
@@ -70,7 +70,7 @@
[:and
[:or [:is (col :is_published) true]
[:in (col :root_collection_type) (vec library-root-collection-types)]]
- [:or [:not= (col :model) [:inline "table"]]
- [:= (col :data_layer) [:inline "final"]]]]
- [:= (col :data_authority) [:inline "authoritative"]]]
+ [:or [:not= (col :model) "table"]
+ [:= (col :data_layer) "final"]]]
+ [:= (col :data_authority) "authoritative"]]
false])
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 3e2937724a9..fda83b0021c 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -857,69 +857,69 @@
;; - archive operation id (when we archive a collection and subcollections together, we mark the whole archived
;; tree so you can look at it in isolation)
;; - effective child (if you're only interested in things that are an effective child of another collection, we can do that)
- {:select :id
- ;; the `FROM` clause is where we limit the collections to the ones we have permissions on. For a superuser,
- ;; that's all of them. For regular users, it's:
- ;; a) the collections they have permission in the DB for,
- ;; b) the trash collection, and
- ;; c) their personal collection and its descendants
- :from [(if is-superuser?
- [:collection :c]
- [{:union-all (keep identity [{:select visible-union-columns
- :from [[:collection :c]]
- :where [:and [:exists {:select [1]
- :from [[:permissions :p]]
- :inner-join [[:permissions_group_membership :pgm] [:= :p.group_id :pgm.group_id]]
- :where [:and
- [:= :pgm.user_id [:inline current-user-id]]
- [:= :c.id :p.collection_id]
- [:= :p.perm_type (h2x/literal "perms/collection-access")]
- [:or
- [:= :p.perm_value (h2x/literal "read-and-write")]
- (when (= :read (:permission-level visibility-config))
- [:= :p.perm_value (h2x/literal "read")])]]}]]}
- {:select visible-union-columns
- :from [[:collection :c]]
- :where [:= :type (h2x/literal trash-collection-type)]}
- (when-let [personal-collection-and-descendant-ids
- (seq (user->personal-collection-and-descendant-ids current-user-id))]
- {:select visible-union-columns
- :from [[:collection :c]]
- :where [:in :id [:inline personal-collection-and-descendant-ids]]})
- (when-let [tenant-collection-and-descendant-ids (seq (perms/user->tenant-collection-and-descendant-ids current-user-id))]
- {:select visible-union-columns
- :from [[:collection :c]]
- :where [:in :id [:inline tenant-collection-and-descendant-ids]]})
- (when (perms/is-data-analyst? current-user-id)
- {:select visible-union-columns
- :from [[:collection :c]]
- :where [:= :namespace [:inline "transforms"]]})])}
- :c])]
- ;; The `WHERE` clause is where we apply the other criteria we were given:
- :where [:and
- ;; hiding the trash collection when desired...
- (when-not (:include-trash-collection? visibility-config)
- [:not= [:inline (trash-collection-id)] :c.id])
- ;; hiding archived items when desired...
- (when (= :exclude (:include-archived-items visibility-config))
- [:= :c.archived false])
- ;; (or showing them, if that's what you want)
- (when (= :only (:include-archived-items visibility-config))
- [:or
- [:= :c.archived true]
- ;; the trash collection is included when viewing archived-only
- [:= :id [:inline (trash-collection-id)]]])
- (when-not (perms/use-tenants)
- [:not [:exists {:select [1]
- :from [[:collection :sub_c]]
- :where [:and [:= :c.id :sub_c.id]
- [:= :sub_c.namespace [:inline "shared-tenant-collection"]]]}]])
- ;; excluding things outside of the `archive_operation_id` you wanted...
- (when-let [op-id (:archive-operation-id visibility-config)]
- [:or
- [:= :c.archive_operation_id [:inline op-id]]
- ;; the trash collection is part of every `archive_operation`
- [:= :id (trash-collection-id)]])]}))
+ ^:allow-subquery {:select :id
+ ;; the `FROM` clause is where we limit the collections to the ones we have permissions on. For a superuser,
+ ;; that's all of them. For regular users, it's:
+ ;; a) the collections they have permission in the DB for,
+ ;; b) the trash collection, and
+ ;; c) their personal collection and its descendants
+ :from [(if is-superuser?
+ [:collection :c]
+ [^:allow-subquery {:union-all (keep identity [^:allow-subquery {:select visible-union-columns
+ :from [[:collection :c]]
+ :where [:and [:exists ^:allow-subquery {:select [1]
+ :from [[:permissions :p]]
+ :inner-join [[:permissions_group_membership :pgm] [:= :p.group_id :pgm.group_id]]
+ :where [:and
+ [:= :pgm.user_id [:inline current-user-id]]
+ [:= :c.id :p.collection_id]
+ [:= :p.perm_type (h2x/literal "perms/collection-access")]
+ [:or
+ [:= :p.perm_value (h2x/literal "read-and-write")]
+ (when (= :read (:permission-level visibility-config))
+ [:= :p.perm_value (h2x/literal "read")])]]}]]}
+ ^:allow-subquery {:select visible-union-columns
+ :from [[:collection :c]]
+ :where [:= :type (h2x/literal trash-collection-type)]}
+ (when-let [personal-collection-and-descendant-ids
+ (seq (user->personal-collection-and-descendant-ids current-user-id))]
+ ^:allow-subquery {:select visible-union-columns
+ :from [[:collection :c]]
+ :where [:in :id [:inline personal-collection-and-descendant-ids]]})
+ (when-let [tenant-collection-and-descendant-ids (seq (perms/user->tenant-collection-and-descendant-ids current-user-id))]
+ ^:allow-subquery {:select visible-union-columns
+ :from [[:collection :c]]
+ :where [:in :id [:inline tenant-collection-and-descendant-ids]]})
+ (when (perms/is-data-analyst? current-user-id)
+ ^:allow-subquery {:select visible-union-columns
+ :from [[:collection :c]]
+ :where [:= :namespace ^:allow-raw-sql [:inline "transforms"]]})])}
+ :c])]
+ ;; The `WHERE` clause is where we apply the other criteria we were given:
+ :where [:and
+ ;; hiding the trash collection when desired...
+ (when-not (:include-trash-collection? visibility-config)
+ [:not= [:inline (trash-collection-id)] :c.id])
+ ;; hiding archived items when desired...
+ (when (= :exclude (:include-archived-items visibility-config))
+ [:= :c.archived false])
+ ;; (or showing them, if that's what you want)
+ (when (= :only (:include-archived-items visibility-config))
+ [:or
+ [:= :c.archived true]
+ ;; the trash collection is included when viewing archived-only
+ [:= :id [:inline (trash-collection-id)]]])
+ (when-not (perms/use-tenants)
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[:collection :sub_c]]
+ :where [:and [:= :c.id :sub_c.id]
+ [:= :sub_c.namespace ^:allow-raw-sql [:inline "shared-tenant-collection"]]]}]])
+ ;; excluding things outside of the `archive_operation_id` you wanted...
+ (when-let [op-id (:archive-operation-id visibility-config)]
+ [:or
+ [:= :c.archive_operation_id op-id]
+ ;; the trash collection is part of every `archive_operation`
+ [:= :id (trash-collection-id)]])]}))
(mu/defn visible-collection-filter-clause
"Given a `CollectionVisibilityConfig`, return a HoneySQL filter clause ready for use in queries. Takes an optional
@@ -946,7 +946,7 @@
[:in
collection-id-field
(if cte-name
- {:select :id :from cte-name}
+ ^:allow-subquery {:select :id :from cte-name}
(visible-collection-query visibility-config user-scope))]])))
(defn- effective-child-of-filter-clause
@@ -963,13 +963,13 @@
;; an effective child is a descendant of the parent collection
[:like (->col "location") (str (children-location parent-coll) "%")]
;; but NOT a child of any OTHER visible collection.
- [:not [:exists {:select 1
- :from [[:collection :c2]]
- :where [:and
- (visible-collection-filter-clause :c2.id visibility-config)
- [:= (->col "location") [:concat :c2.location :c2.id (h2x/literal "/")]]
- (when-not (collection.root/is-root-collection? parent-coll)
- [:not= :c2.id [:inline (u/the-id parent-coll)]])]}]]])]))
+ [:not [:exists ^:allow-subquery {:select 1
+ :from [[:collection :c2]]
+ :where [:and
+ (visible-collection-filter-clause :c2.id visibility-config)
+ [:= (->col "location") [:concat :c2.location :c2.id (h2x/literal "/")]]
+ (when-not (collection.root/is-root-collection? parent-coll)
+ [:not= :c2.id [:inline (u/the-id parent-coll)]])]}]]])]))
(defn visible-collection-id?
"Whether the current user can see the Collection with `collection-id`, at `:read` (the default) or `:write` level.
@@ -1238,9 +1238,9 @@
[collection :- CollectionWithLocationAndIDOrRoot
visibility-config :- CollectionVisibilityConfig
& additional-honeysql-where-clauses]
- {:select [:id :name :description :type]
- :from [[:collection :col]]
- :where (apply effective-children-where-clause collection :col visibility-config additional-honeysql-where-clauses)})
+ ^:allow-subquery {:select [:id :name :description :type]
+ :from [[:collection :col]]
+ :where (apply effective-children-where-clause collection :col visibility-config additional-honeysql-where-clauses)})
(mu/defn- effective-children* :- [:set (ms/InstanceOf :model/Collection)]
[collection :- CollectionWithLocationAndIDOrRoot & additional-honeysql-where-clauses]
@@ -2078,10 +2078,10 @@
[:and
[:or [:= (maybe-alias :type) nil]
[:and
- [:not= (maybe-alias :type) [:inline instance-analytics-collection-type]]
- [:not= (maybe-alias :type) [:inline trash-collection-type]]]]
+ [:not= (maybe-alias :type) instance-analytics-collection-type]
+ [:not= (maybe-alias :type) trash-collection-type]]]
[:or [:= (maybe-alias :namespace) nil]
- [:not= (maybe-alias :namespace) [:inline "analytics"]]]
+ [:not= (maybe-alias :namespace) ^:allow-raw-sql [:inline "analytics"]]]
[:not (maybe-alias :is_sample)]]))
(defmethod serdes/extract-query "Collection" [_model {:keys [collection-set where skip-archived]}]
diff --git a/src/metabase/collections/util.clj b/src/metabase/collections/util.clj
index 08f94c487ce..2dc226031c8 100644
--- a/src/metabase/collections/util.clj
+++ b/src/metabase/collections/util.clj
@@ -12,11 +12,11 @@
:where [:and
[:= :archived false]
[:in :dashboard_id dashboard-ids]
- [:exists {:select 1
- :from :report_dashboardcard
- :where [:and
- [:= :report_dashboardcard.card_id :report_card.id]
- [:= :report_dashboardcard.dashboard_id :report_card.dashboard_id]]}]]}))
+ [:exists ^:allow-subquery {:select 1
+ :from :report_dashboardcard
+ :where [:and
+ [:= :report_dashboardcard.card_id :report_card.id]
+ [:= :report_dashboardcard.dashboard_id :report_card.dashboard_id]]}]]}))
(map :dashboard_id)
(into #{}))]
(for [dashboard dashboards]
diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.clj
index 1b5b14b25ab..bfe78528f3e 100644
--- a/src/metabase/collections_rest/api.clj
+++ b/src/metabase/collections_rest/api.clj
@@ -13,7 +13,6 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.app-db.core :as mdb]
- [metabase.collections-rest.settings :as collections-rest.settings]
[metabase.collections.core :as collections]
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection.root :as collection.root]
@@ -34,7 +33,6 @@
[metabase.util :as u]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [tru]]
- [metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
@@ -486,18 +484,19 @@
(def ^:private exploration-recent-edits-subquery
;; Per-exploration latest edit, from the Exploration's own metadata revisions.
;; `rn = 1` picks the winner.
+ ^:allow-subquery
{:select [:exploration_id
:timestamp
:user_id
- [[:over [[:row_number] {:partition-by [:exploration_id]
- :order-by [[:timestamp :desc]]}]] :rn]]
- :from [[{:select [[:r.model_id :exploration_id]
- [:r.timestamp :timestamp]
- [:r.user_id :user_id]]
- :from [[:revision :r]]
- :where [:and
- [:= :r.model (h2x/literal "Exploration")]
- [:= :r.most_recent true]]}
+ [[:over [[:row_number] ^:allow-subquery {:partition-by [:exploration_id]
+ :order-by [[:timestamp :desc]]}]] :rn]]
+ :from [[^:allow-subquery {:select [[:r.model_id :exploration_id]
+ [:r.timestamp :timestamp]
+ [:r.user_id :user_id]]
+ :from [[:revision :r]]
+ :where [:and
+ [:= :r.model (h2x/literal "Exploration")]
+ [:= :r.most_recent true]]}
:all_edits]]})
(defmethod collection-children-query :exploration
@@ -691,29 +690,18 @@
(assoc :fully_parameterized (queries/fully-parameterized? row))))
(defn- post-process-card-like
- [{:keys [include-can-run-adhoc-query hydrate-based-on-upload]} rows]
- (let [threshold (collections-rest.settings/can-run-adhoc-query-check-threshold)
- card-count (count rows)
- skip-adhoc-hydration? (u/prog1 (and include-can-run-adhoc-query
- (pos? threshold)
- (> card-count threshold))
- (when <>
- (log/warnf "Skipping can_run_adhoc_query hydration for %d cards (threshold: %d)"
- card-count threshold)))
- hydration (cond-> [:can_write
- :can_restore
- :can_delete
- :dashboard_count
- :is_remote_synced
- :collection_namespace
- [:dashboard :moderation_status]]
- (and include-can-run-adhoc-query
- (not skip-adhoc-hydration?)) (conj :can_run_adhoc_query))]
+ [{:keys [hydrate-based-on-upload]} rows]
+ (let [hydration [:can_write
+ :can_restore
+ :can_delete
+ :dashboard_count
+ :is_remote_synced
+ :collection_namespace
+ [:dashboard :moderation_status]]]
(as-> (map post-process-card-row rows) $
(apply t2/hydrate $ hydration)
(cond-> $
- hydrate-based-on-upload upload/model-hydrate-based-on-upload
- skip-adhoc-hydration? (->> (map #(assoc % :can_run_adhoc_query true))))
+ hydrate-based-on-upload upload/model-hydrate-based-on-upload)
(map post-process-card-row-after-hydrate $))))
(defmethod post-process-collection-children :card
@@ -1197,8 +1185,8 @@
:include-trash-collection? archived?}
search-clause (search-text-clause search-text)
rows-query (cond-> {:with [[:visible_collection_ids (collection/visible-collection-query viz-config)]]
- :select [:* [[:over [[:count :*] {} :total_count]]]]
- :from [[{:union-all queries} :dummy_alias]]
+ :select [:* [[:over [[:count :*] ^:allow-subquery {} :total_count]]]]
+ :from [[^:allow-subquery {:union-all queries} :dummy_alias]]
:order-by sql-order}
search-clause
(sql.helpers/where search-clause))
@@ -1493,11 +1481,10 @@
changed, that should too."
[_route-params
{:keys [models archived namespace pinned_state sort_column sort_direction official_collections_first
- include_can_run_adhoc_query include_library collection_type
+ include_library collection_type
show_dashboard_questions q include_available_models]} :- [:map
[:models {:optional true} [:maybe Models]]
[:collection_type {:optional true} CollectionType]
- [:include_can_run_adhoc_query {:default false} [:maybe ms/BooleanValue]]
[:archived {:default false} [:maybe ms/BooleanValue]]
[:namespace {:optional true} [:maybe ms/NonBlankString]]
[:include_library {:default false} [:maybe ms/BooleanValue]]
@@ -1517,7 +1504,6 @@
(not (mi/can-read? root-collection)))
#{:collection})
options {:archived? (boolean archived)
- :include-can-run-adhoc-query include_can_run_adhoc_query
:show-dashboard-questions? (boolean show_dashboard_questions)
:collection-type collection_type
:include-library? include_library
@@ -1729,7 +1715,6 @@
[:description {:optional true} [:maybe ms/NonBlankString]]
[:archived {:default false} [:maybe ms/BooleanValue]]
[:parent_id {:optional true} [:maybe ms/PositiveInt]]
- [:type {:optional true} [:maybe CollectionType]]
[:authority_level {:optional true} [:maybe collection/AuthorityLevel]]]]
;; do we have perms to edit this Collection?
(let [collection-before-update (t2/hydrate (api/write-check :model/Collection id) :parent_id)]
@@ -1743,7 +1728,7 @@
(api/check-403 api/*is-superuser?*))
;; ok, go ahead and update it! Only update keys that were specified in the `body`. But not `parent_id` since
;; that's not actually a property of Collection, and since we handle moving a Collection separately below.
- (let [updates (u/select-keys-when collection-updates :present [:name :description :authority_level :type])]
+ (let [updates (u/select-keys-when collection-updates :present [:name :description :authority_level])]
(when (seq updates)
(t2/update! :model/Collection id updates)))
;; if we're trying to move or archive the Collection, go ahead and do that
@@ -1798,7 +1783,6 @@
* `pinned_state` - when `is_pinned`, return pinned objects only.
when `is_not_pinned`, return non pinned objects only.
when `all`, return everything. By default returns everything.
- * `include_can_run_adhoc_query` - when this is true hydrates the `can_run_adhoc_query` flag on card models
* `q` - filter items by name or last editor. Blank or whitespace-only values are ignored.
* `include_available_models` - include the models that have at least one visible item in the requested scope.
@@ -1807,11 +1791,9 @@
[{:keys [id]} :- [:map
[:id [:or ms/PositiveInt ms/NanoIdString]]]
{:keys [models archived pinned_state sort_column sort_direction official_collections_first
- include_can_run_adhoc_query
show_dashboard_questions q include_available_models]} :- [:map
[:models {:optional true} [:maybe Models]]
[:archived {:default false} [:maybe ms/BooleanValue]]
- [:include_can_run_adhoc_query {:default false} [:maybe ms/BooleanValue]]
[:pinned_state {:optional true} [:maybe (into [:enum] valid-pinned-state-values)]]
[:sort_column {:optional true} [:maybe (into [:enum] valid-sort-columns)]]
[:sort_direction {:optional true} [:maybe (into [:enum] valid-sort-directions)]]
@@ -1827,7 +1809,6 @@
:include-library? true
:archived? (or archived (:archived collection) (collection/is-trash? collection))
:pinned-state (keyword pinned_state)
- :include-can-run-adhoc-query include_can_run_adhoc_query
:search-text q
:sort-info {:sort-column (or (some-> sort_column normalize-sort-choice) :name)
:sort-direction (or (some-> sort_direction normalize-sort-choice) :asc)
diff --git a/src/metabase/collections_rest/init.clj b/src/metabase/collections_rest/init.clj
deleted file mode 100644
index c9dcac0e9a3..00000000000
--- a/src/metabase/collections_rest/init.clj
+++ /dev/null
@@ -1,3 +0,0 @@
-(ns metabase.collections-rest.init
- (:require
- [metabase.collections-rest.settings]))
diff --git a/src/metabase/collections_rest/settings.clj b/src/metabase/collections_rest/settings.clj
deleted file mode 100644
index a68aa018f64..00000000000
--- a/src/metabase/collections_rest/settings.clj
+++ /dev/null
@@ -1,14 +0,0 @@
-(ns metabase.collections-rest.settings
- (:require
- [metabase.settings.core :refer [defsetting]]
- [metabase.util.i18n :as i18n]))
-
-(defsetting can-run-adhoc-query-check-threshold
- (i18n/deferred-tru (str "Maximum number of cards to compute can_run_adhoc_query for. When the number of cards exceeds "
- "this threshold, can_run_adhoc_query will return true for all cards without computing actual "
- "permissions. Set to 0 to always compute permissions. This only affects how cards are displayed"
- " in the query builder and does not affect actual permission enforcement."))
- :type :integer
- :export? false
- :default 250
- :visibility :internal)
diff --git a/src/metabase/comments/api.clj b/src/metabase/comments/api.clj
index 68df84aa4f4..42afd1be4b5 100644
--- a/src/metabase/comments/api.clj
+++ b/src/metabase/comments/api.clj
@@ -150,11 +150,11 @@
parent (when parent_comment_id
(t2/select-one :model/Comment :id parent_comment_id))}}]]
(let [clause (if parent_comment_id
- {:where [:in :id {:from [:comment]
- :select [:creator_id]
- :where [:or
- [:= :id parent_comment_id]
- [:= :parent_comment_id parent_comment_id]]}]}
+ {:where [:in :id ^:allow-subquery {:from [:comment]
+ :select [:creator_id]
+ :where [:or
+ [:= :id parent_comment_id]
+ [:= :parent_comment_id parent_comment_id]]}]}
;; TODO: when we expand to more entity types, add dispatch here if not everyone has `creator_id`
{:where [:= :id (:creator_id entity)]})
mentions (comment/mentions (:content comment))
diff --git a/src/metabase/comments/models/comment.clj b/src/metabase/comments/models/comment.clj
index 144f437df5f..e9f33f343d4 100644
--- a/src/metabase/comments/models/comment.clj
+++ b/src/metabase/comments/models/comment.clj
@@ -86,7 +86,10 @@
(defn mentions
"Find mentioned users inside of a comment content"
[content]
- (->> (tree-seq :content :content content)
- (filter #(and (= "smartLink" (-> % :type))
- (= "user" (-> % :attrs :model))))
- (mapv #(-> % :attrs :entityId))))
+ (into []
+ (comp (filter #(and (= "smartLink" (:type %))
+ (= "user" (-> % :attrs :model))))
+ (keep #(let [entity-id (-> % :attrs :entityId)]
+ (when (pos-int? entity-id)
+ entity-id))))
+ (tree-seq :content :content content)))
diff --git a/src/metabase/comments/render.clj b/src/metabase/comments/render.clj
index cbfc31ec4bb..f03d2548bea 100644
--- a/src/metabase/comments/render.clj
+++ b/src/metabase/comments/render.clj
@@ -73,7 +73,8 @@
display-text (or label
(when (= model "user") (str "@" entityId))
(str model " " entityId))
- url-fn (model->url-fn model)]
+ url-fn (when (pos-int? entityId)
+ (model->url-fn model))]
(if url-fn
[:a {:href (url-fn entityId)} display-text]
;; Unknown model or user mention — render as escaped plain text
diff --git a/src/metabase/core/init.clj b/src/metabase/core/init.clj
index d90c5baca1b..0af6411b25e 100644
--- a/src/metabase/core/init.clj
+++ b/src/metabase/core/init.clj
@@ -23,7 +23,6 @@
[metabase.channel.init]
[metabase.classloader.init]
[metabase.cloud-migration.init]
- [metabase.collections-rest.init]
[metabase.comments.init]
[metabase.config.core :as config]
[metabase.content-verification.init]
diff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.clj
index 931c81c6226..6bb52e18828 100644
--- a/src/metabase/dashboards/models/dashboard.clj
+++ b/src/metabase/dashboards/models/dashboard.clj
@@ -22,6 +22,7 @@
[metabase.permissions.core :as perms]
[metabase.public-sharing.core :as public-sharing]
[metabase.queries.core :as queries]
+ [metabase.query-permissions.core :as query-perms]
[metabase.query-processor.metadata :as qp.metadata]
[metabase.search.core :as search]
[metabase.settings.core :as setting]
@@ -310,24 +311,45 @@
(cond
;; If this is a pre-existing card, just return it
(and (integer? (:id card)) (t2/select-one :model/Card :id (:id card)))
- card
+ (do
+ (api/read-check :model/Card (:id card))
+ card)
;; Don't save text cards
(-> card :dataset_query not-empty)
- (let [card (first (t2/insert-returning-instances!
+ (let [_ (query-perms/check-run-permissions-for-query (:dataset_query card))
+ card (first (t2/insert-returning-instances!
:model/Card
(-> card
(update :result_metadata #(or % (-> card
:dataset_query
legacy-result-metadata-for-query)))
- ;; Xrays populate this in their transient cards
- (dissoc :id :can_run_adhoc_query))))]
+ (dissoc :id
+ :public_uuid :made_public_by_id
+ :enable_embedding :embedding_params)
+ (assoc :creator_id api/*current-user-id*))))]
(events/publish-event! :event/card-create {:object card :user-id (:creator_id card)})
- (t2/hydrate card :creator :dashboard_count :can_write :can_run_adhoc_query :collection))))
+ (t2/hydrate card :creator :dashboard_count :can_write :collection))))
+
+(defn- check-dashcard-parameter-mapping-permissions
+ [dashcards]
+ (let [mappings (for [{:keys [card_id parameter_mappings]} dashcards
+ mapping parameter_mappings]
+ (assoc mapping ::card-id (or (:card_id mapping) card_id)))
+ card-ids (into #{} (keep ::card-id) mappings)
+ card-id->query (when (seq card-ids)
+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))
+ field-ids (into []
+ (keep (fn [{:keys [target] ::keys [card-id]}]
+ (when target
+ (params/param-target->field-id target {:dataset_query (card-id->query card-id)}))))
+ mappings)]
+ (query-perms/check-parameter-field-permissions field-ids)))
(defn save-transient-dashboard!
"Save a denormalized description of `dashboard`."
[dashboard parent-collection-id]
+ (queries/check-parameter-source-card-permissions (:parameters dashboard))
(t2/with-transaction [_conn]
(let [{dashcards :dashcards
tabs :tabs
@@ -336,30 +358,34 @@
:model/Dashboard
(-> dashboard
(dissoc :dashcards :tabs :rule :related
- :transient_name :transient_filters :param_fields :more)
+ :transient_name :transient_filters :param_fields :more
+ :public_uuid :made_public_by_id
+ :enable_embedding :embedding_params)
(assoc :description description
- :collection_id parent-collection-id))))
- {:keys [old->new-tab-id]} (dashboard-tab/do-update-tabs! (:id dashboard) nil tabs)]
- (add-dashcards! dashboard
- (for [dashcard dashcards]
- (let [card (some-> dashcard :card
- (assoc :dashboard_id (:id dashboard)
- :collection_id parent-collection-id)
- save-card!)
- series (some->> dashcard
- :series
- (mapv (fn [card]
- (-> card
- (assoc :collection_id parent-collection-id)
- save-card!))))
- dashcard (-> dashcard
- (dissoc :card :id :creator_id)
- (update :parameter_mappings
- (partial map #(assoc % :card_id (:id card))))
- (assoc :series series)
- (update :dashboard_tab_id (or old->new-tab-id {}))
- (assoc :card_id (:id card)))]
- dashcard)))
+ :collection_id parent-collection-id
+ :creator_id api/*current-user-id*))))
+ {:keys [old->new-tab-id]} (dashboard-tab/do-update-tabs! (:id dashboard) nil tabs)
+ dashcards-to-add (for [dashcard dashcards]
+ (let [card (some-> dashcard :card
+ (assoc :dashboard_id (:id dashboard)
+ :collection_id parent-collection-id)
+ save-card!)
+ series (some->> dashcard
+ :series
+ (mapv (fn [card]
+ (-> card
+ (assoc :collection_id parent-collection-id)
+ save-card!))))
+ dashcard (-> dashcard
+ (dissoc :card :id :creator_id)
+ (update :parameter_mappings
+ (partial map #(assoc % :card_id (:id card))))
+ (assoc :series series)
+ (update :dashboard_tab_id (or old->new-tab-id {}))
+ (assoc :card_id (:id card)))]
+ dashcard))]
+ (check-dashcard-parameter-mapping-permissions dashcards-to-add)
+ (add-dashcards! dashboard dashcards-to-add)
(cond-> dashboard
(collections/remote-synced-collection? parent-collection-id) collections/check-non-remote-synced-dependencies))))
@@ -548,32 +574,32 @@
(defmethod staleness/find-stale-query :model/Dashboard
[_model args]
- {:select [:report_dashboard.id
- [(h2x/literal "Dashboard") :model]
- [:report_dashboard.name :name]
- [:last_viewed_at :last_used_at]]
- :from :report_dashboard
- :left-join [:pulse [:and
- [:= :pulse.archived false]
- [:= :pulse.dashboard_id :report_dashboard.id]]
- :collection [:= :collection.id :report_dashboard.collection_id]
- :moderation_review [:and
- [:= :moderation_review.moderated_item_id :report_dashboard.id]
- [:= :moderation_review.moderated_item_type (h2x/literal "dashboard")]
- [:= :moderation_review.most_recent true]
- [:= :moderation_review.status (h2x/literal "verified")]]]
- :where [:and
- [:= :pulse.id nil]
- [:= :moderation_review.id nil]
- [:= :report_dashboard.archived false]
- [:<= :report_dashboard.last_viewed_at (-> args :cutoff-date)]
- ;; find things only in regular collections, not the `instance-analytics` collection.
- [:= :collection.type nil]
- (when (embed.settings/some-embedding-enabled?)
- [:= :report_dashboard.enable_embedding false])
- (when (setting/get :enable-public-sharing)
- [:= :report_dashboard.public_uuid nil])
- [:or
- (when (contains? (:collection-ids args) nil)
- [:is :report_dashboard.collection_id nil])
- [:in :report_dashboard.collection_id (-> args :collection-ids)]]]})
+ ^:allow-subquery {:select [:report_dashboard.id
+ [(h2x/literal "Dashboard") :model]
+ [:report_dashboard.name :name]
+ [:last_viewed_at :last_used_at]]
+ :from :report_dashboard
+ :left-join [:pulse [:and
+ [:= :pulse.archived false]
+ [:= :pulse.dashboard_id :report_dashboard.id]]
+ :collection [:= :collection.id :report_dashboard.collection_id]
+ :moderation_review [:and
+ [:= :moderation_review.moderated_item_id :report_dashboard.id]
+ [:= :moderation_review.moderated_item_type (h2x/literal "dashboard")]
+ [:= :moderation_review.most_recent true]
+ [:= :moderation_review.status (h2x/literal "verified")]]]
+ :where [:and
+ [:= :pulse.id nil]
+ [:= :moderation_review.id nil]
+ [:= :report_dashboard.archived false]
+ [:<= :report_dashboard.last_viewed_at (-> args :cutoff-date)]
+ ;; find things only in regular collections, not the `instance-analytics` collection.
+ [:= :collection.type nil]
+ (when (embed.settings/some-embedding-enabled?)
+ [:= :report_dashboard.enable_embedding false])
+ (when (setting/get :enable-public-sharing)
+ [:= :report_dashboard.public_uuid nil])
+ [:or
+ (when (contains? (:collection-ids args) nil)
+ [:is :report_dashboard.collection_id nil])
+ [:in :report_dashboard.collection_id (-> args :collection-ids)]]]})
diff --git a/src/metabase/dashboards/models/dashboard_card.clj b/src/metabase/dashboards/models/dashboard_card.clj
index c627adc0448..f22455858e4 100644
--- a/src/metabase/dashboards/models/dashboard_card.clj
+++ b/src/metabase/dashboards/models/dashboard_card.clj
@@ -324,21 +324,28 @@
(def ^:private link-card-models
(set (keys serdes/link-card-model->toucan-model)))
+(defn- ensure-integer-link-card-id
+ [id]
+ (when-not (integer? id)
+ (throw (ex-info "Link card entity id must be an integer"
+ {:status-code 400, :id id})))
+ id)
+
(defn link-card-info-query-for-model
"Return a honeysql query that is used to fetch info for a linkcard."
[model id-or-ids]
- {:select (select-clause-for-link-card-model model)
- :from (t2/table-name (serdes/link-card-model->toucan-model model))
- :where (if (coll? id-or-ids)
- [:in :id id-or-ids]
- [:= :id id-or-ids])})
+ ^:allow-subquery {:select (select-clause-for-link-card-model model)
+ :from (t2/table-name (serdes/link-card-model->toucan-model model))
+ :where (if (coll? id-or-ids)
+ [:in :id (mapv ensure-integer-link-card-id id-or-ids)]
+ [:= :id (ensure-integer-link-card-id id-or-ids)])})
(defn- link-card-info-query
[link-card-model->ids]
(if (= 1 (count link-card-model->ids))
(apply link-card-info-query-for-model (first link-card-model->ids))
{:select [:*]
- :from [[{:union-all (map #(apply link-card-info-query-for-model %) link-card-model->ids)}
+ :from [[^:allow-subquery {:union-all (map #(apply link-card-info-query-for-model %) link-card-model->ids)}
:alias_is_required_by_sql_but_not_needed_here]]}))
(mi/define-batched-hydration-method dashcard-linkcard-info
diff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.clj
index 87a2f24e15a..259afe87cea 100644
--- a/src/metabase/dashboards_rest/api.clj
+++ b/src/metabase/dashboards_rest/api.clj
@@ -6,6 +6,7 @@
[clojure.set :as set]
[medley.core :as m]
[metabase.actions.core :as actions]
+ [metabase.actions.schema :as actions.schema]
[metabase.analytics.core :as analytics]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
@@ -24,6 +25,7 @@
[metabase.embedding.validation :as embedding.validation]
[metabase.events.core :as events]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.models.interface :as mi]
[metabase.parameters.chain-filter :as chain-filter]
@@ -94,6 +96,16 @@
dashboard)))
dashboards)))
+(defn- remove-unreadable-actions
+ [dashboard]
+ (m/update-existing dashboard :dashcards
+ (fn [dashcards]
+ (mapv (fn [dashcard]
+ (cond-> dashcard
+ (and (:action dashcard) (not (mi/can-read? (:action dashcard))))
+ (dissoc :action)))
+ dashcards))))
+
(defn- hydrate-dashboard-details
"Get dashboard details for the complete dashboard, including tabs, dashcards, params, etc."
[{dashboard-id :id :as dashboard}]
@@ -105,9 +117,8 @@
:attributes {:dashboard/id dashboard-id}}
(binding [params/*field-id-context* (atom params/empty-field-id-context)]
(cond->> [[:dashcards
- ;; disabled :can_run_adhoc_query for performance reasons in 50 release
- [:card :can_write #_:can_run_adhoc_query [:moderation_reviews :moderator_details]]
- [:series :can_write #_:can_run_adhoc_query]
+ [:card :can_write [:moderation_reviews :moderator_details]]
+ [:series :can_write]
:dashcard/action
:dashcard/linkcard-info]
:can_restore
@@ -121,7 +132,43 @@
[:moderation_reviews :moderator_details]
[:collection :is_personal :effective_location]]
(dashboards.settings/dashboards-save-last-used-parameters) (cons :last_used_param_values)
- true (apply t2/hydrate dashboard)))))
+ true (apply t2/hydrate dashboard)
+ true remove-unreadable-actions))))
+
+(defn- dashcard-card-ids [dashcard]
+ (concat (when-let [card-id (:card_id dashcard)]
+ [card-id])
+ (keep :id (:series dashcard))))
+
+(defn- references
+ [{:keys [dashcards parameters]}]
+ {:cards (into (set (queries/values-source-card-ids parameters))
+ (comp (mapcat dashcard-card-ids) (filter pos-int?))
+ dashcards)
+ :actions (into #{} (keep :action_id) dashcards)})
+
+(defn- stored-references
+ [dashboard-id]
+ {:cards (into (set (t2/select-fn-vec :card_id :model/ParameterCard
+ :parameterized_object_type "dashboard"
+ :parameterized_object_id dashboard-id))
+ (concat (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id dashboard-id)
+ (t2/select-fn-vec :card_id :model/DashboardCardSeries
+ {:where [:in :dashboardcard_id
+ ^:allow-subquery {:select [:id]
+ :from [(t2/table-name :model/DashboardCard)]
+ :where [:= :dashboard_id dashboard-id]}]})))
+ :actions (set (t2/select-fn-vec :action_id :model/DashboardCard :dashboard_id dashboard-id))})
+
+(def ^:private no-references {:cards #{} :actions #{}})
+
+(defn- check-new-references
+ [stored dashboard]
+ (let [new-references (references dashboard)]
+ (doseq [card-id (set/difference (:cards new-references) (:cards stored))]
+ (api/read-check :model/Card card-id))
+ (doseq [action-id (set/difference (:actions new-references) (:actions stored))]
+ (api/read-check :model/Action action-id))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
@@ -141,6 +188,7 @@
[:collection_position {:optional true} [:maybe ms/PositiveInt]]]]
;; if we're trying to save the new dashboard in a Collection make sure we have permissions to do that
(api/create-check :model/Dashboard {:collection_id collection_id})
+ (check-new-references no-references {:parameters parameters})
(let [dashboard-data {:name name
:description description
:parameters (or parameters [])
@@ -692,23 +740,23 @@
:c.dashboard_id
[nil :location]
[(h2x/literal "card") :model]
- [{:select [:status]
- :from [:moderation_review]
- :where [:and
- [:= :moderated_item_type "card"]
- [:= :moderated_item_id :c.id]
- [:= :most_recent true]]
- ;; limit 1 to ensure that there is only one result but this invariant should hold true, just
- ;; protecting against potential bugs
- :order-by [[:id :desc]]
- :limit 1}
+ [^:allow-subquery {:select [:status]
+ :from [:moderation_review]
+ :where [:and
+ [:= :moderated_item_type "card"]
+ [:= :moderated_item_id :c.id]
+ [:= :most_recent true]]
+ ;; limit 1 to ensure that there is only one result but this invariant should hold true, just
+ ;; protecting against potential bugs
+ :order-by [[:id :desc]]
+ :limit 1}
:moderated_status]]
:from [[:report_card :c]]
:where [:and
[:= :c.dashboard_id id]
- [:exists {:select 1
- :from [[:report_dashboardcard :dc]]
- :where [:and [:= :c.id :dc.card_id] [:= :c.dashboard_id :dc.dashboard_id]]}]
+ [:exists ^:allow-subquery {:select 1
+ :from [[:report_dashboardcard :dc]]
+ :where [:and [:= :c.id :dc.card_id] [:= :c.dashboard_id :dc.dashboard_id]]}]
[:= :c.archived false]]}
(when (request/paged?)
{:limit (request/limit)
@@ -757,39 +805,21 @@
{:added "0.41.0"}
[parameter-mappings :- [:sequential ::parameters.schema/parameter-mapping]]
(when (seq parameter-mappings)
- ;; calculate a set of all Field IDs referenced by parameter mappings; then from those Field IDs calculate a set of
- ;; all Table IDs to which those Fields belong. This is done in a batched fashion so we can avoid N+1 query issues
- ;; if there happen to be a lot of parameters
- (let [card-ids (into #{}
- (comp (map :card-id)
- (remove nil?))
- parameter-mappings)]
- (when (seq card-ids)
- (let [card-id->query (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids])
- field-ids (set (for [{:keys [target card-id]} parameter-mappings
- :when card-id
- :let [query (or (card-id->query card-id)
- (throw (ex-info (tru "Card {0} does not exist or does not have a valid query."
- card-id)
- {:status-code 404
- :card-id card-id})))
- field-id (param-target->field-id target query)]
- :when field-id]
- field-id))
- table-ids (when (seq field-ids)
- (t2/select-fn-set :table_id :model/Field :id [:in field-ids]))
- table-id->database-id (when (seq table-ids)
- (t2/select-pk->fn :db_id :model/Table :id [:in table-ids]))]
- (doseq [table-id table-ids
- :let [database-id (table-id->database-id table-id)]]
- ;; check whether we'd actually be able to query this Table (do we have ad-hoc data perms for it?)
- (when-not (query-perms/can-query-table? database-id table-id)
- (throw (ex-info (tru "You must have data permissions to add a parameter referencing the Table {0}."
- (pr-str (t2/select-one-fn :name :model/Table :id table-id)))
- {:status-code 403
- :database-id database-id
- :table-id table-id
- :actual-permissions @api/*current-user-permissions-set*})))))))))
+ (let [card-ids (into #{} (keep :card-id) parameter-mappings)
+ card-id->query (when (seq card-ids)
+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))
+ field-ids (into []
+ (keep (fn [{:keys [target card-id]}]
+ (when target
+ (let [query (when card-id
+ (or (card-id->query card-id)
+ (throw (ex-info (tru "Card {0} does not exist or does not have a valid query."
+ card-id)
+ {:status-code 404
+ :card-id card-id}))))]
+ (param-target->field-id target query)))))
+ parameter-mappings)]
+ (query-perms/check-parameter-field-permissions field-ids))))
(defn- existing-parameter-mappings
"Returns a map of DashboardCard ID -> parameter mappings for a Dashboard of the form
@@ -826,9 +856,8 @@
(defn- create-dashcards!
[dashboard dashcards]
- (doseq [{:keys [card_id]} dashcards
- :when (pos-int? card_id)]
- (api/check-not-archived (api/read-check :model/Card card_id)))
+ (doseq [card-id (into #{} (comp (mapcat dashcard-card-ids) (filter pos-int?)) dashcards)]
+ (api/check-not-archived (t2/select-one :model/Card :id card-id)))
(check-parameter-mapping-permissions (for [{:keys [card_id parameter_mappings]} dashcards
mapping parameter_mappings]
(assoc mapping :card-id card_id)))
@@ -846,11 +875,6 @@
(dashboard-card/delete-dashboard-cards! dashcard-ids)
dashboard-cards))
-(defn- dashcard-card-ids [dashcard]
- (concat (when-let [card-id (:card_id dashcard)]
- [card-id])
- (keep :id (:series dashcard))))
-
(defn- assert-dashcards-are-not-internal-to-other-dashboards
"Reject `new-dashcards` that newly reference a question internal to another dashboard. Card ids the
dashboard already references (as a dashcard's card or series, per `existing-dashboard`'s hydrated
@@ -894,7 +918,7 @@
[:parameter_mappings {:optional true} [:maybe [:ref ::parameters.schema/parameter-mappings]]]
[:visualization_settings {:optional true} [:maybe ms/Map]]
[:inline_parameters {:optional true} [:maybe [:sequential ms/NonBlankString]]]
- [:series {:optional true} [:maybe [:sequential ms/Map]]]])
+ [:series {:optional true} [:maybe [:sequential [:map [:id ms/PositiveInt]]]]]])
(def ^:private UpdatedDashboardTab
[:map
@@ -1030,6 +1054,7 @@
(span/with-span!
{:name "update-dashboard"
:attributes {:dashboard/id id}}
+ (check-new-references (stored-references id) dash-updates)
(let [current-dash (api/write-check :model/Dashboard id)
;; If there are parameters in the update, we want the old params so that we can do a check to see if any of
;; the notifications were broken by the update.
@@ -1262,6 +1287,37 @@
;;; ---------------------------------------------- Transient dashboards ----------------------------------------------
+(def ^:private TransientCard
+ [:map
+ [:id {:optional true} [:maybe [:or ms/PositiveInt ms/NonBlankString]]]
+ [:name {:optional true} [:maybe ms/NonBlankString]]
+ [:description {:optional true} [:maybe :string]]
+ [:display {:optional true} [:maybe ms/NonBlankString]]
+ [:dataset_query {:optional true} [:maybe ::lib-be.schema/maybe-legacy-or-empty-query]]
+ [:visualization_settings {:optional true} [:maybe ms/Map]]])
+
+(def ^:private TransientDashboardCard
+ [:map
+ [:card {:optional true} [:maybe TransientCard]]
+ [:series {:optional true} [:maybe [:sequential TransientCard]]]
+ [:row {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:col {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:size_x {:optional true} [:maybe ms/PositiveInt]]
+ [:size_y {:optional true} [:maybe ms/PositiveInt]]
+ [:dashboard_tab_id {:optional true} [:maybe ms/Int]]
+ [:parameter_mappings {:optional true} [:maybe [:ref ::parameters.schema/parameter-mappings]]]
+ [:visualization_settings {:optional true} [:maybe ms/Map]]])
+
+(def ^:private TransientDashboard
+ [:map
+ [:name {:optional true} [:maybe ms/NonBlankString]]
+ [:description {:optional true} [:maybe :string]]
+ [:parameters {:optional true} [:maybe [:ref ::parameters.schema/parameters]]]
+ [:auto_apply_filters {:optional true} [:maybe :boolean]]
+ [:width {:optional true} [:maybe [:enum "fixed" "full"]]]
+ [:dashcards {:optional true} [:maybe [:sequential TransientDashboardCard]]]
+ [:tabs {:optional true} [:maybe [:sequential UpdatedDashboardTab]]]])
+
;; 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
;;
@@ -1271,7 +1327,7 @@
[{:keys [parent-collection-id]} :- [:map
[:parent-collection-id ms/PositiveInt]]
_query-params
- dashboard]
+ dashboard :- TransientDashboard]
(api/create-check :model/Dashboard {:collection_id parent-collection-id})
(let [dashboard (dashboard/save-transient-dashboard! dashboard parent-collection-id)]
(events/publish-event! :event/dashboard-create {:object dashboard :user-id api/*current-user-id*})
@@ -1285,13 +1341,13 @@
"Save a denormalized description of dashboard."
[_route-params
_query-params
- dashboard]
+ dashboard :- TransientDashboard]
(let [parent-collection-id (:id (xrays/get-or-create-container-collection
(if api/*is-superuser?*
"/"
(collection/children-location
(t2/select-one :model/Collection :personal_owner_id api/*current-user-id*)))))
- dashboard (dashboard/save-transient-dashboard! (assoc dashboard :creator_id api/*current-user-id*) parent-collection-id)]
+ dashboard (dashboard/save-transient-dashboard! dashboard parent-collection-id)]
(events/publish-event! :event/dashboard-create {:object dashboard :user-id api/*current-user-id*})
dashboard))
@@ -1404,11 +1460,14 @@
[:dashcard-id ms/PositiveInt]]
_query-params
{:keys [parameters]} :- [:map
- [:parameters {:optional true} [:maybe [:map-of :string :any]]]]]
+ [:parameters {:optional true} ::actions.schema/prefetch-parameter-values]]]
(api/read-check :model/Dashboard dashboard-id)
- (actions/fetch-values
- (api/check-404 (actions/dashcard->action dashcard-id))
- parameters))
+ (let [dashcard (api/check-404 (t2/select-one :model/DashboardCard
+ :id dashcard-id
+ :dashboard_id dashboard-id))]
+ (actions/fetch-values
+ (api/check-404 (actions/dashcard->action dashcard))
+ parameters)))
;; 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
@@ -1424,9 +1483,9 @@
[:dashcard-id ms/PositiveInt]]
_query-params
{:keys [parameters]} :- [:map
- [:parameters {:optional true} [:maybe [:map-of :string :any]]]]]
+ [:parameters {:optional true}
+ [:maybe ::actions.schema/execute-parameter-values.string-keys]]]]
(api/read-check :model/Dashboard dashboard-id)
- ;; Undo middleware string->keyword coercion
(actions/execute-dashcard! dashboard-id dashcard-id parameters))
;;; ---------------------------------- Running the query associated with a Dashcard ----------------------------------
diff --git a/src/metabase/data_studio/api/table.clj b/src/metabase/data_studio/api/table.clj
index 8f6269a233a..27f6f18b180 100644
--- a/src/metabase/data_studio/api/table.clj
+++ b/src/metabase/data_studio/api/table.clj
@@ -89,6 +89,7 @@
(defn- table-subquery
"Create a subquery that selects table IDs matching the given WHERE clause."
[where]
+ ^:allow-subquery
{:select [:id] :from [(t2/table-name :model/Table)] :where where})
(defn- traverse-graph
@@ -277,9 +278,10 @@
body :- ::table-selectors]
(api/check-data-analyst)
(let [tables (t2/select :model/Table {:where (table-selectors->filter body), :order-by [[:id]]})]
- (let [field-ids-to-delete-q {:select [:id]
- :from [(t2/table-name :model/Field)]
- :where [:in :table_id (map :id tables)]}]
+ (let [field-ids-to-delete-q ^:allow-subquery
+ {:select [:id]
+ :from [(t2/table-name :model/Field)]
+ :where [:in :table_id (map :id tables)]}]
(t2/delete! (t2/table-name :model/FieldValues) :field_id [:in field-ids-to-delete-q]))
nil))
diff --git a/src/metabase/documents/api/document.clj b/src/metabase/documents/api/document.clj
index c342bec1fb2..7d8439efca2 100644
--- a/src/metabase/documents/api/document.clj
+++ b/src/metabase/documents/api/document.clj
@@ -10,6 +10,7 @@
[metabase.documents.prose-mirror :as prose-mirror]
[metabase.documents.schema :as documents.schema]
[metabase.events.core :as events]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.public-sharing.validation :as public-sharing.validation]
[metabase.queries.core :as card]
[metabase.query-permissions.core :as query-perms]
@@ -19,7 +20,6 @@
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.malli :as mu]
- [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -27,7 +27,7 @@
"Schema for creating a new card - simplified version to avoid circular dependencies"
[:map
[:name ms/NonBlankString]
- [:dataset_query ms/Map]
+ [:dataset_query ::lib-be.schema/maybe-legacy-query]
[:entity_id {:optional true} [:maybe ms/NonBlankString]]
[:parameters {:optional true} [:maybe [:sequential ms/Map]]]
[:parameter_mappings {:optional true} [:maybe [:sequential ms/Map]]]
@@ -45,16 +45,19 @@
saved without it. Decoding therefore sees a permissive `[:map-of :int :any]` — enough to turn the JSON string keys
into ints — and the `:fn` re-checks the strict shape afterwards, so a bad card is a 400."
[key-schema]
- (let [strict [:map-of key-schema CardCreateSchema]]
- [:and
- [:map-of :int :any]
- [:fn {:error/message "value must map a card placeholder id to a card"}
- #(mr/validate strict %)]]))
+ [:schema
+ {:decode/normalize (fn [cards]
+ (cond-> cards
+ (map? cards)
+ (-> (update-keys #(api.macros/decode-and-validate-params
+ :body key-schema (cond-> % (keyword? %) u/qualified-name)))
+ (update-vals #(api.macros/decode-and-validate-params :body CardCreateSchema %)))))}
+ [:map-of key-schema CardCreateSchema]])
(def ^:private DocumentCreateOptions
[:map
[:name m.document/DocumentName]
- [:document :any]
+ [:document ::prose-mirror/ast]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
[:collection_position {:optional true} [:maybe ms/PositiveInt]]
[:cards {:optional true} [:maybe (cards-to-create-schema [:int {:max -1}])]]])
@@ -62,7 +65,7 @@
(def ^:private DocumentUpdateOptions
[:map
[:name {:optional true} m.document/DocumentName]
- [:document {:optional true} :any]
+ [:document {:optional true} [:maybe ::prose-mirror/ast]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
[:collection_position {:optional true} [:maybe ms/PositiveInt]]
[:cards {:optional true} [:maybe (cards-to-create-schema :int)]]
@@ -72,6 +75,7 @@
"Checks that the query is runnable by the current user then saves"
[{query :dataset_query :as card} creator]
(query-perms/check-run-permissions-for-query (dissoc query :query-permissions/perms))
+ (card/check-parameter-source-card-permissions (:parameters card))
(card/create-card! (assoc card :type :question :dashboard_id nil) creator))
(mu/defn- update-cards-in-ast :- [:map [:document :any]
@@ -449,7 +453,8 @@
[document-id card-id]
(let [document (api/check-404 (t2/select-one :model/Document :id document-id :archived false))]
(api/read-check document)
- (api/check-404 (t2/exists? :model/Card :id card-id :document_id document-id :archived false))))
+ (api/check-404 (and (contains? (set (prose-mirror/card-ids document)) card-id)
+ (t2/exists? :model/Card :id card-id :document_id document-id :archived false)))))
;; 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
diff --git a/src/metabase/documents/prose_mirror.clj b/src/metabase/documents/prose_mirror.clj
index a8d6f6b7c3d..08876693d82 100644
--- a/src/metabase/documents/prose_mirror.clj
+++ b/src/metabase/documents/prose_mirror.clj
@@ -2,7 +2,17 @@
"Manipulate the prose mirror ast for documents"
(:require
[clojure.string :as str]
- [clojure.walk :as walk]))
+ [clojure.walk :as walk]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::ast
+ "Schema for a prose-mirror document AST as it arrives at the API."
+ [:map
+ {:decode/normalize (fn [ast]
+ (cond-> ast
+ (map? ast) walk/keywordize-keys))
+ :closed false}
+ [:type :string]])
(def card-embed-type
"Type of a card-embed node"
diff --git a/src/metabase/documents/revisions/impl.clj b/src/metabase/documents/revisions/impl.clj
index eab88da5b0e..6efd40fda6d 100644
--- a/src/metabase/documents/revisions/impl.clj
+++ b/src/metabase/documents/revisions/impl.clj
@@ -20,8 +20,15 @@
:view_count
:last_viewed_at
:collection_id
- :collection_position})
+ :collection_position
+ :public_uuid
+ :made_public_by_id})
(defmethod revisions/serialize-instance :model/Document
[_model _id instance]
(apply dissoc instance excluded-columns-for-document-revision))
+
+(defmethod revisions/revert-to-revision! :model/Document
+ [model id user-id serialized-document]
+ ((get-method revisions/revert-to-revision! :default)
+ model id user-id (apply dissoc serialized-document excluded-columns-for-document-revision)))
diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.clj
index 953da0d39c1..0512a06e85e 100644
--- a/src/metabase/driver/mysql.clj
+++ b/src/metabase/driver/mysql.clj
@@ -564,9 +564,9 @@
(defn- temporal-cast [type expr]
;; mysql does not allow casting to timestamp
- (if (= "timestamp" (u/lower-case-en type))
- (h2x/maybe-cast "datetime" expr)
- (h2x/maybe-cast type expr)))
+ (if (= "date" (u/lower-case-en type))
+ (h2x/maybe-cast "date" expr)
+ (h2x/maybe-cast "datetime" expr)))
(defmethod sql.qp/date [:mysql :day]
[_ _ expr]
@@ -618,7 +618,9 @@
(h2x/is-of-type? expr "timestamp"))]
(sql.u/validate-convert-timezone-args timestamp? target-timezone source-timezone)
(h2x/with-database-type-info
- [:convert_tz expr (or source-timezone (driver-api/results-timezone-id)) target-timezone]
+ [:convert_tz expr
+ (sql.qp/->honeysql driver (or source-timezone (driver-api/results-timezone-id)))
+ (sql.qp/->honeysql driver target-timezone)]
"datetime")))
(defn- timestampdiff-dates [unit x y]
diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.clj
index e44360c25d9..0148a29c72a 100644
--- a/src/metabase/driver/postgres.clj
+++ b/src/metabase/driver/postgres.clj
@@ -597,9 +597,22 @@
(sql.qp/adjust-start-of-week :postgres (partial date-trunc :week) expr))
(mu/defn- quoted? [database-type :- driver-api/schema.common.non-blank-string]
- (and (str/starts-with? database-type "\"")
+ (and (>= (count database-type) 2)
+ (str/starts-with? database-type "\"")
(str/ends-with? database-type "\"")))
+(mu/defn- enum-type-components :- [:sequential {:min 1} :string]
+ [database-type :- driver-api/schema.common.non-blank-string]
+ (if (quoted? database-type)
+ (str/split (subs database-type 1 (dec (count database-type))) #"\"\.\"" -1)
+ [database-type]))
+
+(mu/defn- enum-cast
+ [database-type :- driver-api/schema.common.non-blank-string
+ raw-value]
+ (-> [:cast raw-value (apply h2x/identifier :type-name (enum-type-components database-type))]
+ (h2x/with-database-type-info database-type)))
+
(defmethod sql.qp/date [:postgres :day]
[_ _ expr]
(h2x/maybe-cast (h2x/database-type expr) (h2x/->date expr)))
@@ -620,12 +633,11 @@
(defmethod sql.qp/->honeysql [:postgres :value]
[driver [_ {:keys [base-type database-type] :as opts} raw-value]]
(when (some? raw-value)
+ (sql.qp/check-value-literal driver raw-value)
(condp #(isa? %2 %1) base-type
:type/PostgresBitString (h2x/cast :varbit raw-value)
:type/IPAddress (h2x/cast :inet raw-value)
- :type/PostgresEnum (if (quoted? database-type)
- (h2x/cast database-type raw-value)
- (h2x/quoted-cast database-type raw-value))
+ :type/PostgresEnum (enum-cast database-type raw-value)
((get-method sql.qp/->honeysql [:sql :value])
driver [:value opts raw-value]))))
@@ -687,7 +699,7 @@
(defmethod sql.qp/->honeysql [:postgres :regex-match-first]
[driver [_ _opts arg pattern]]
(let [identifier (sql.qp/->honeysql driver arg)]
- [::regex-match-first identifier pattern]))
+ [::regex-match-first identifier (sql.qp/->honeysql driver pattern)]))
(defmethod sql.qp/->honeysql [:postgres :split-part]
[driver [_ _opts text divider position]]
diff --git a/src/metabase/driver/settings.clj b/src/metabase/driver/settings.clj
index 6321cfdb8e4..60a7952bbaa 100644
--- a/src/metabase/driver/settings.clj
+++ b/src/metabase/driver/settings.clj
@@ -204,6 +204,10 @@
(or (config/config-bool :mb-dangerous-unsafe-enable-testing-h2-connections-do-not-enable)
false))
+(def ^:dynamic *impersonation-allow-write?*
+ "Whether write-back operations are permitted while connection impersonation is active. Normally `false`."
+ false)
+
(def ^:dynamic *allow-testing-sqlite-connections*
"Whether to allow testing new SQLite connections. Normally disabled on hosted Metabase, which effectively prevents
users from creating new SQLite databases from the API. Internal flows that need to test connections to the bundled
diff --git a/src/metabase/driver/sql.clj b/src/metabase/driver/sql.clj
index 40cebcec641..fa9a36b7f84 100644
--- a/src/metabase/driver/sql.clj
+++ b/src/metabase/driver/sql.clj
@@ -5,6 +5,7 @@
[clojure.set :as set]
[metabase.driver :as driver]
[metabase.driver-api.core :as driver-api]
+ [metabase.driver.settings :as driver.settings]
[metabase.driver.sql.normalize]
[metabase.driver.sql.parameters.substitute :as sql.params.substitute]
[metabase.driver.sql.parameters.substitution]
@@ -350,7 +351,7 @@
(fn [stages]
(mapv (fn [stage]
(if (lib.util/native-stage? stage)
- (let [[stmt-type allowed-stmts] (if (:impersonation/allow-write? query)
+ (let [[stmt-type allowed-stmts] (if driver.settings/*impersonation-allow-write?*
["write" (tru "insert, update, or delete")]
["read" (tru "select")])
{:keys [is-single-stmt? allowed-stmt-type? sql error]}
diff --git a/src/metabase/driver/sql/normalize.clj b/src/metabase/driver/sql/normalize.clj
index fde7437e2de..414f57a78fc 100644
--- a/src/metabase/driver/sql/normalize.clj
+++ b/src/metabase/driver/sql/normalize.clj
@@ -1,6 +1,7 @@
(ns metabase.driver.sql.normalize
(:require
[clojure.string :as str]
+ [honey.sql :as sql]
[metabase.driver :as driver]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.util :as u]))
@@ -19,8 +20,8 @@
"Normalizes the (primarily table/column) name passed in.
Should return a value that matches the name listed in the appdb."
[driver name-str]
- (let [quote-style (sql.qp/quote-style driver)
- quote-char (if (= quote-style :mysql) \` \")]
+ (let [quote-char (when-let [quote-fn (:quote (sql/get-dialect (sql.qp/quote-style driver)))]
+ (first (quote-fn "")))]
(if (and (= (first name-str) quote-char)
(= (last name-str) quote-char))
(let [quote-quote (str quote-char quote-char)
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index 0c6c3494b26..8c1f51eb6dd 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -476,6 +476,15 @@
driver/dispatch-on-initialized-driver
:hierarchy #'driver/hierarchy)
+(defn check-interval-unit
+ "Return `unit` when it is a supported temporal interval unit, otherwise throw an invalid-query error."
+ [unit]
+ (when-not (contains? driver-api/datetime-interval-units unit)
+ (throw (ex-info (tru "Invalid temporal unit: {0}" (pr-str unit))
+ {:type driver-api/qp.error-type.invalid-query
+ :unit unit})))
+ unit)
+
(mu/defn adjust-start-of-week
"Truncate to the day the week starts on.
@@ -720,13 +729,26 @@
[_driver this]
this)
+(defmethod ->honeysql [:sql clojure.lang.IPersistentMap]
+ [driver _this]
+ (throw (ex-info "Unexpected ->honeysql call on a map"
+ {:driver driver, :type driver-api/qp.error-type.invalid-query})))
+
(defmethod ->honeysql [:sql Number]
[_driver n]
(inline-num n))
+(defn check-value-literal
+ "Throw an invalid-query error unless `value` is a scalar literal usable in a `:value` clause for `driver`."
+ [driver value]
+ (when (coll? value)
+ (throw (ex-info "Unexpected collection in a :value clause"
+ {:driver driver, :type driver-api/qp.error-type.invalid-query}))))
+
(defmethod ->honeysql [:sql :value]
[driver [_ {:keys [base-type effective-type]} value]]
(when (some? value)
+ (check-value-literal driver value)
(condp #(isa? %2 %1) (or effective-type base-type)
;; When we are dealing with a uuid type we should try to convert to a real UUID
;; If that fails,, we will add a fallback cast to "text"
@@ -1243,7 +1265,7 @@
(if (some interval? args)
(if-let [[field intervals] (u/pick-first (complement interval?) args)]
(reduce (fn [hsql-form [_ _opts amount unit]]
- (add-interval-honeysql-form driver hsql-form amount unit))
+ (add-interval-honeysql-form driver hsql-form amount (check-interval-unit unit)))
(->honeysql driver field)
intervals)
(throw (ex-info "Summing intervals is not supported" {:args args})))
@@ -1265,7 +1287,7 @@
(if (interval? (first other-args))
(reduce (fn [hsql-form [_ _opts amount unit]]
;; We are adding negative amount. Inspired by `->honeysql [:sql :datetime-subtract]`.
- (add-interval-honeysql-form driver hsql-form (- amount) unit))
+ (add-interval-honeysql-form driver hsql-form (- amount) (check-interval-unit unit)))
(->honeysql driver first-arg)
other-args)
(into [:-]
@@ -1459,11 +1481,11 @@
(defmethod ->honeysql [:sql :datetime-add]
[driver [_ _opts arg amount unit]]
- (add-interval-honeysql-form driver (->honeysql driver arg) amount unit))
+ (add-interval-honeysql-form driver (->honeysql driver arg) amount (check-interval-unit unit)))
(defmethod ->honeysql [:sql :datetime-subtract]
[driver [_ _opts arg amount unit]]
- (add-interval-honeysql-form driver (->honeysql driver arg) (- amount) unit))
+ (add-interval-honeysql-form driver (->honeysql driver arg) (- amount) (check-interval-unit unit)))
(defn datetime-diff-check-args
"This util function is used by SQL implementations of ->honeysql for the `:datetime-diff` clause.
diff --git a/src/metabase/driver/sql_jdbc/actions.clj b/src/metabase/driver/sql_jdbc/actions.clj
index 0265342f05e..307e788260f 100644
--- a/src/metabase/driver/sql_jdbc/actions.clj
+++ b/src/metabase/driver/sql_jdbc/actions.clj
@@ -99,7 +99,7 @@
driver/dispatch-on-initialized-driver
:hierarchy #'driver/hierarchy)
-(mu/defn- cast-values :- driver-api/schema.actions.row
+(mu/defn- cast-values :- [:map-of :string :any]
"Certain value types need to have their honeysql form updated to work properly during update/creation. This function
uses honeysql casting to wrap values in the map that need to be cast with their column's type, and passes through
types that do not need casting like integer or string."
diff --git a/src/metabase/driver/sql_jdbc/connection/ssh_tunnel.clj b/src/metabase/driver/sql_jdbc/connection/ssh_tunnel.clj
index 1a86ba2b7ce..4641385658d 100644
--- a/src/metabase/driver/sql_jdbc/connection/ssh_tunnel.clj
+++ b/src/metabase/driver/sql_jdbc/connection/ssh_tunnel.clj
@@ -99,7 +99,7 @@
hb-sec)
(.. auth (verify default-ssh-timeout no-cancel-options)))
tracker (.createLocalPortForwardingTracker session
- (SshdSocketAddress. "" 0)
+ SshdSocketAddress/LOCALHOST_ADDRESS
(SshdSocketAddress. host port))
input-port (.. tracker getBoundAddress getPort)]
(log/trace (u/format-color 'cyan "creating ssh tunnel (heartbeating every %d seconds) %s:%s -L %s:%s:%s"
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index ef16fd0085b..cc609050dad 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -101,6 +101,7 @@
lib.metadata/transforms
lib.schema.common/instance-of-class
lib.schema.temporal-bucketing/date-bucketing-units
+ lib.schema.temporal-bucketing/datetime-interval-units
lib.types.isa/temporal?
match/match-one
match/match-many
diff --git a/src/metabase/eid_translation/util.clj b/src/metabase/eid_translation/util.clj
index eab7b214ffb..e5ad5ccad0b 100644
--- a/src/metabase/eid_translation/util.clj
+++ b/src/metabase/eid_translation/util.clj
@@ -6,6 +6,7 @@
[metabase.eid-translation.impl :as eid-translation]
[metabase.eid-translation.settings :as eid-translation.settings]
[metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[toucan2.core :as t2]))
@@ -135,9 +136,16 @@
(mu/defn ->id :- :int
"Translates a single entity_id -> id. This reuses the batched version: [[model->entity-ids->ids]].
- Please use that if you have to do man lookups at once."
+ Please use that if you have to do man lookups at once.
+
+ The non-string branch is a runtime guard, not the `:-`/argument schemas: those are `mu/defn`
+ schemas, which are compiled out of production builds, so they cannot be relied on to keep a
+ non-scalar value (e.g. a keyword-keyed map decoded from a JWT claim) out of the query built from
+ the return value. A map returned here reaches a Toucan2 value position and is compiled as HoneySQL
+ query structure rather than bound as a parameter."
[api-name-or-model :- [:or ApiName ApiModel] id :- [:or #_id :int #_entity-id :string]]
- (if (string? id)
+ (cond
+ (string? id)
(let [model (->model api-name-or-model)
[[_ {:keys [status] :as info}]] (entity-ids->id-for-model api-name-or-model [id])]
(update-translation-count! [status])
@@ -148,7 +156,12 @@
:id id
:status status}))
(:id info)))
- id))
+
+ (pos-int? id)
+ id
+
+ :else
+ (throw (ex-info (tru "Invalid ID.") {:status-code 400}))))
(mu/defn ->id-or-404 :- :int
"Translates a single entity_id -> id, throwing a 404 error if not found.
diff --git a/src/metabase/embedding/models/theme.clj b/src/metabase/embedding/models/theme.clj
index 60c70dde2a0..0ff5aecda12 100644
--- a/src/metabase/embedding/models/theme.clj
+++ b/src/metabase/embedding/models/theme.clj
@@ -18,7 +18,7 @@
;;;; transforms
(t2/deftransforms :model/EmbeddingTheme
- {:settings mi/transform-json})
+ {:settings mi/transform-json-no-keywordization})
;;;; serialization
diff --git a/src/metabase/embedding_rest/api/common.clj b/src/metabase/embedding_rest/api/common.clj
index 4847417e0ec..b7b12eb1731 100644
--- a/src/metabase/embedding_rest/api/common.clj
+++ b/src/metabase/embedding_rest/api/common.clj
@@ -9,6 +9,7 @@
[metabase.eid-translation.core :as eid-translation]
[metabase.embedding.jwt :as embed]
[metabase.embedding.validation :as embedding.validation]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.models.resolution :as models.resolution]
[metabase.notification.payload.core :as notification.payload]
[metabase.parameters.dashboard :as parameters.dashboard]
@@ -25,6 +26,7 @@
[metabase.util.json :as json]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -48,6 +50,10 @@
as keywords (e.g. slugs starting with a digit) arrive as strings (see [[normalize-query-params]])."
[:map-of [:or :keyword :string] [:maybe [:or :string [:sequential :string]]]])
+(def ParsedQueryParams
+ "Schema for [[QueryParams]] after the `:parameters` JSON blob has been decoded into real JSON scalars."
+ [:map-of [:or :keyword :string] [:maybe [:ref ::lib.schema.parameter/parameter.value]]])
+
(comment
;; load dynamic model resolution code... should already be loaded by [[metabase.core.init]] so this is mostly here for
;; the benefit of tests
@@ -156,13 +162,15 @@
contains serialized JSON with parameter values. If this object cannot be found or parsed, we fallback to plain query
string parameters."
[query-params]
- (or (try
- (when-let [parameters (:parameters query-params)]
- (json/decode+kw parameters))
- (catch Throwable _
- nil))
- query-params
- {}))
+ (let [parsed (when-let [parameters (:parameters query-params)]
+ (try
+ (json/decode+kw parameters)
+ (catch Throwable _
+ nil)))]
+ (when (and (some? parsed)
+ (not (mr/validate ParsedQueryParams parsed)))
+ (throw (ex-info (tru "Invalid parameter values") {:status-code 400})))
+ (or parsed query-params {})))
(mu/defn normalize-query-params :- [:map-of :keyword :any]
"Take a map of `query-params` and make sure they're in the right format for the rest of our code. Our
@@ -357,6 +365,35 @@
:qp qp
options))))
+(defn- tile-slug->value
+ [object-parameters parameter-values]
+ (let [id->slug (into {} (map (juxt :id :slug)) object-parameters)]
+ (into {}
+ (map (fn [{:keys [id value]}]
+ [(keyword (or (get id->slug id)
+ (throw (ex-info (tru "Invalid query params: could not determine slug for parameter with ID {0}"
+ (pr-str id))
+ {:status-code 400}))))
+ value]))
+ parameter-values)))
+
+(defn tile-parameters-for-card
+ "The parameters an embedded Card's map tile should run with."
+ [card token-params parameter-values]
+ (let [parameters (resolve-card-parameters card)]
+ (apply-slug->value parameters
+ (validate-and-merge-params (:embedding_params card)
+ token-params
+ (tile-slug->value parameters parameter-values)))))
+
+(defn tile-parameters-for-dashboard
+ "The parameters an embedded Dashboard's map tile should run with."
+ [dashboard token-params parameter-values]
+ (resolve-dashboard-parameters dashboard
+ (validate-and-merge-params (:embedding_params dashboard)
+ token-params
+ (tile-slug->value (:parameters dashboard) parameter-values))))
+
(defn process-tiles-query-for-card
"Like [[metabase.tiles.api/process-tiles-query-for-card]], but takes a pre-loaded Card entity and runs with database
routing off (see above). Used by the embed tiles endpoints. Returns a Ring response."
diff --git a/src/metabase/embedding_rest/api/embed.clj b/src/metabase/embedding_rest/api/embed.clj
index 56c385dc43b..a7c7219ee78 100644
--- a/src/metabase/embedding_rest/api/embed.clj
+++ b/src/metabase/embedding_rest/api/embed.clj
@@ -412,7 +412,11 @@
lon-field (json/decode+kw lonField)]
(api.embed.common/check-embedding-enabled-for-card card)
(request/as-admin
- (api.embed.common/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))))
+ (api.embed.common/process-tiles-query-for-card
+ card
+ (api.embed.common/tile-parameters-for-card
+ card (embedding.jwt/get-in-unsigned-token-or-throw unsigned [:params]) parameters)
+ zoom x y lat-field lon-field))))
;; 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
@@ -443,4 +447,8 @@
lon-field (json/decode+kw lonField)]
(api.embed.common/check-embedding-enabled-for-dashboard dashboard)
(request/as-admin
- (api.embed.common/process-tiles-query-for-dashcard dashboard dashcard card parameters zoom x y lat-field lon-field))))
+ (api.embed.common/process-tiles-query-for-dashcard
+ dashboard dashcard card
+ (api.embed.common/tile-parameters-for-dashboard
+ dashboard (embedding.jwt/get-in-unsigned-token-or-throw unsigned [:params]) parameters)
+ zoom x y lat-field lon-field))))
diff --git a/src/metabase/embedding_rest/api/preview_embed.clj b/src/metabase/embedding_rest/api/preview_embed.clj
index 8f68bf9561f..5f354ec06f4 100644
--- a/src/metabase/embedding_rest/api/preview_embed.clj
+++ b/src/metabase/embedding_rest/api/preview_embed.clj
@@ -116,6 +116,7 @@
[:token api.embed.common/EncodedToken]
[:param-key ms/NonBlankString]]
query-params]
+ (check-and-unsign token)
(api.embed.common/dashboard-param-values token
param-key
nil
@@ -130,6 +131,7 @@
"Embedded version of chain filter search endpoint."
[{:keys [token param-key prefix]} :- api.embed.common/SearchParams
query-params]
+ (check-and-unsign token)
(api.embed.common/dashboard-param-values token
param-key
prefix
@@ -146,6 +148,7 @@
[:token api.embed.common/EncodedToken]
[:param-key ms/NonBlankString]]
{:keys [value]}]
+ (check-and-unsign token)
(api.embed.common/dashboard-param-remapped-value token param-key (codec/url-decode value) {:preview true}))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
@@ -247,7 +250,11 @@
lat-field (json/decode+kw latField)
lon-field (json/decode+kw lonField)]
(request/as-admin
- (api.embed.common/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))))
+ (api.embed.common/process-tiles-query-for-card
+ card
+ (api.embed.common/tile-parameters-for-card
+ card (embed/get-in-unsigned-token-or-throw unsigned-token [:params]) parameters)
+ zoom x y lat-field lon-field))))
;; 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
@@ -277,4 +284,8 @@
lat-field (json/decode+kw latField)
lon-field (json/decode+kw lonField)]
(request/as-admin
- (api.embed.common/process-tiles-query-for-dashcard dashboard dashcard card parameters zoom x y lat-field lon-field))))
+ (api.embed.common/process-tiles-query-for-dashcard
+ dashboard dashcard card
+ (api.embed.common/tile-parameters-for-dashboard
+ dashboard (embed/get-in-unsigned-token-or-throw unsigned-token [:params]) parameters)
+ zoom x y lat-field lon-field))))
diff --git a/src/metabase/explorations/api.clj b/src/metabase/explorations/api.clj
index b50caaaee84..20af658530e 100644
--- a/src/metabase/explorations/api.clj
+++ b/src/metabase/explorations/api.clj
@@ -281,11 +281,11 @@
:where [:and
[:= :id thread-id]
[:not= :completed_at nil]
- [:not-exists {:select [1]
- :from [:exploration_query]
- :where [:and
- [:= :exploration_thread_id thread-id]
- [:= :status "running"]]}]]}))
+ [:not-exists ^:allow-subquery {:select [1]
+ :from [:exploration_query]
+ :where [:and
+ [:= :exploration_thread_id thread-id]
+ [:= :status "running"]]}]]}))
(t2/delete! :model/ExplorationQuery :exploration_thread_id thread-id)
;; Enqueue planning inside the reset transaction so the plan message publishes iff the reset
;; commits (:queue/exploration-plan is :transactional :require).
@@ -332,6 +332,9 @@
;;; ----------------------------------------- schemas -----------------------------------------
+(def ^:private ExploreFilterScalar
+ [:maybe [:or :string number? :boolean]])
+
(def ^:private ExploreFilterSpec
"One segment filter stamped onto a block metric selection's `:explore_filters` vector.
`:display_value` is required — the FE formats it at click time and both the thread name
@@ -341,14 +344,14 @@
[:map
[:operator [:= "="]]
[:field_ref [:sequential :any]]
- [:value :any]
+ [:value ExploreFilterScalar]
[:display_value ms/NonBlankString]
[:dimension_name {:optional true} [:maybe :string]]]]
["between"
[:map
[:operator [:= "between"]]
[:field_ref [:sequential :any]]
- [:values [:tuple :any :any]]
+ [:values [:tuple ExploreFilterScalar ExploreFilterScalar]]
[:display_value ms/NonBlankString]
[:dimension_name {:optional true} [:maybe :string]]]]])
@@ -776,22 +779,26 @@
`current_user_last_touched_at` is non-null on every row. `limit`/`offset` are appended only when
paged."
[user-id limit offset]
- (let [my-touches {:union-all
- [{:select [[:model_id :eid] [:timestamp :ts]]
- :from [:revision]
- :where [:and [:= :model "Exploration"] [:= :user_id user-id]]}
- {:select [[:id :eid] [:created_at :ts]]
- :from [:exploration]
- :where [:= :creator_id user-id]}]}
+ (let [my-touches ^:allow-subquery
+ {:union-all
+ [^:allow-subquery
+ {:select [[:model_id :eid] [:timestamp :ts]]
+ :from [:revision]
+ :where [:and [:= :model "Exploration"] [:= :user_id user-id]]}
+ ^:allow-subquery
+ {:select [[:id :eid] [:created_at :ts]]
+ :from [:exploration]
+ :where [:= :creator_id user-id]}]}
;; MAX rather than GREATEST — the latter's NULL semantics differ across app DBs. And
;; `my-touches` is a derived table here rather than a sibling CTE: a second `:with` binding
;; that selects from the first silently returns no rows under our HoneySQL/H2 stack.
- agg {:select [:eid [[:max :ts] :max_ts]]
- :from [[my-touches :my_touches]]
- :group-by [:eid]}]
+ agg ^:allow-subquery
+ {:select [:eid [[:max :ts] :max_ts]]
+ :from [[my-touches :my_touches]]
+ :group-by [:eid]}]
(cond-> {:select [:exploration.*
[:agg.max_ts :current_user_last_touched_at]
- [[:over [[:count :*] {} :total_count]]]]
+ [[:over [[:count :*] ^:allow-subquery {} :total_count]]]]
:from [:exploration]
:join [[agg :agg] [:= :agg.eid :exploration.id]]
:where [:and
diff --git a/src/metabase/explorations/runner.clj b/src/metabase/explorations/runner.clj
index b41bfde837d..242ee50d11b 100644
--- a/src/metabase/explorations/runner.clj
+++ b/src/metabase/explorations/runner.clj
@@ -185,11 +185,11 @@
[:= :id thread-id]
[:= :analysis_started_at nil]
[:= :canceled_at nil]
- [:not-exists {:select [1]
- :from [:exploration_query]
- :where [:and
- [:= :exploration_thread_id thread-id]
- [:= :status "pending"]]}]]})))
+ [:not-exists ^:allow-subquery {:select [1]
+ :from [:exploration_query]
+ :where [:and
+ [:= :exploration_thread_id thread-id]
+ [:= :status "pending"]]}]]})))
(defn maybe-complete-thread!
"Invoke after any state transition that could be the last unit of work for `thread-id`
diff --git a/src/metabase/explorations/task/collect_orphaned_results.clj b/src/metabase/explorations/task/collect_orphaned_results.clj
index 8ba6d2382c6..e765e1f4cb8 100644
--- a/src/metabase/explorations/task/collect_orphaned_results.clj
+++ b/src/metabase/explorations/task/collect_orphaned_results.clj
@@ -52,9 +52,9 @@
{:select [:sr.id]
:from [[:stored_result :sr]]
:where [:and
- [:not [:exists {:select [1]
- :from [[:exploration_query_result :eqr]]
- :where [:= :eqr.stored_result_id :sr.id]}]]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[:exploration_query_result :eqr]]
+ :where [:= :eqr.stored_result_id :sr.id]}]]
[:< :sr.created_at (t/minus (t/offset-date-time)
(t/minutes grace-period-minutes))]]
:order-by [[:sr.id :asc]]
diff --git a/src/metabase/internal_stats/questions.clj b/src/metabase/internal_stats/questions.clj
index 455f1d6d671..0a881f5bf05 100644
--- a/src/metabase/internal_stats/questions.clj
+++ b/src/metabase/internal_stats/questions.clj
@@ -17,23 +17,24 @@
(condp = (db/db-type)
:mysql [:json_contains_path
:dataset_query
- [:inline "one"]
- [:inline "$.native.\"template-tags\".*"]]
+ ^:allow-raw-sql [:inline "one"]
+ ^:allow-raw-sql [:inline "$.native.\"template-tags\".*"]]
:postgres [:jsonb_path_exists
[:cast :dataset_query :jsonb]
- [:inline "$.native.\"template-tags\" ? (exists(@.*))"]]))
+ ^:allow-raw-sql [:inline "$.native.\"template-tags\" ? (exists(@.*))"]]))
(defn- contains-embedding-param
[param]
(condp = (db/db-type)
:mysql [:!= [:json_search
:embedding_params
- [:inline "one"]
- [:inline param]]
+ ^:allow-raw-sql [:inline "one"]
+ param]
nil]
:postgres [:jsonb_path_exists
[:cast :embedding_params :jsonb]
- [:inline (str "$.* ? (@ == \"" param "\")")]]))
+ ^:allow-raw-sql [:inline "$.* ? (@ == $val)"]
+ [:jsonb_build_object ^:allow-raw-sql [:inline "val"] param]]))
(def ^:private embedding-on [:= :enable_embedding [:inline true]])
@@ -43,9 +44,9 @@
(let [json-supported? (contains? #{:mysql :mariadb :postgres} (db/db-type))]
(t2/select-one (cond-> [:model/Card
[:%count.* :total]
- [(u/count-case [:= [:inline "native"] :query_type])
+ [(u/count-case [:= "native" :query_type])
:native]
- [(u/count-case [:!= [:inline "native"] :query_type])
+ [(u/count-case [:!= "native" :query_type])
:gui]
[(u/count-case [:!= :dashboard_id nil])
:is_dashboard_question]
diff --git a/src/metabase/internal_stats/users.clj b/src/metabase/internal_stats/users.clj
index bdec21eda9e..2b39d547f87 100644
--- a/src/metabase/internal_stats/users.clj
+++ b/src/metabase/internal_stats/users.clj
@@ -7,13 +7,14 @@
"Count all unique normalized domains found in active user emails"
[]
(:count (t2/query-one {:select [[:%count.* :count]]
- :from [[{:select-distinct (condp contains? (db/db-type)
- #{:postgres} [[[:split_part :email [:inline "@"] [:inline 2]]]]
+ :from [[^:allow-subquery
+ {:select-distinct (condp contains? (db/db-type)
+ #{:postgres} [[[:split_part :email "@" [:inline 2]]]]
#{:h2 :mysql} [[[:substring :email [:locate "@" :email]]]])
:from [:core_user]
:where [:and
[:= :is_active true]
- [:= :type [:inline "personal"]]]} :distinct_emails]]})))
+ [:= :type "personal"]]} :distinct_emails]]})))
(defn external-users-count
"Number of users with sso-source: JWT as a proxy for tenant users of embedded views"
@@ -36,5 +37,5 @@
:from [(t2/table-name :model/User)]
:where [:and
[:= :is_active true]
- [:= :type [:inline "personal"]]
+ [:= :type "personal"]
[:not= :tenant_id nil]]})))
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index 23618956909..63a73605300 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -274,7 +274,7 @@
;;
;; :value clauses are also used to wrap top-level literal values in expression clauses.
(defclause value
- value :any
+ value [:ref ::lib.schema.literal/value.value]
type-info [:maybe ::ValueTypeInfo])
(defmethod options-style-method :value [_tag] ::options-style.last-always.snake_case)
@@ -362,7 +362,10 @@
::raw-int [:field x nil]
:field-id (let [[_tag id] x]
;; sometimes the old FE code was dumb and passed in `:field-literal` wrapped inside` `:field-id`
- (if (sequential? id)
+ (if (and (sequential? id)
+ (contains? #{"field-literal" "field" "field-id" "datetime-field" "binning-strategy"
+ :field-literal :field :field-id :datetime-field :binning-strategy}
+ (first id)))
(normalize-field id)
[:field id nil]))
:field-literal (let [[_tag field-name base-type] x]
@@ -1545,7 +1548,7 @@
[:map
[:field-id ::lib.schema.id/field]
[:op (into [:enum] lib.schema.template-tag/allowed-source-filter-ops)]
- [:value :any]])
+ [:value [:ref ::lib.schema.parameter/parameter.value]]])
;; Example:
;;
@@ -1571,7 +1574,7 @@
::TemplateTag.Common
[:map
;; default value for this parameter
- [:default {:optional true} :any]
+ [:default {:optional true} [:ref ::lib.schema.parameter/parameter.value]]
;; whether or not a value for this parameter is required in order to run the query
[:required {:optional true} :boolean]]])
@@ -1851,22 +1854,35 @@
[:base_type {:default :type/*} ::lib.schema.common/base-type]
[:display_name :string]
[:name :string]
+ [:active {:optional true} :boolean]
[:description {:optional true} [:maybe :string]]
[:binning_info {:optional true} [:maybe [:ref ::legacy-column-metadata.binning-info]]]
+ [:coercion_strategy {:optional true} [:maybe ::lib.schema.common/coercion-strategy]]
+ [:database_type {:optional true} [:maybe :string]]
[:effective_type {:optional true} ::lib.schema.common/base-type]
[:converted_timezone {:optional true} [:maybe [:ref ::lib.schema.expression.temporal/timezone-id]]]
[:field_ref {:optional true} [:maybe [:ref ::Reference]]]
;; implicit-join provenance -- the FE renders "Orders → Category" from these, and drill-thru needs them to
;; rebuild the `:source-field` option
[:fk_field_id {:optional true} [:maybe ::lib.schema.id/field]]
+ [:fk_field_name {:optional true} [:maybe :string]]
+ [:fk_join_alias {:optional true} [:maybe [:ref ::lib.schema.join/alias]]]
[:fk_target_field_id {:optional true} [:maybe ::lib.schema.id/field]]
;; Fingerprint is required in order to use BINNING
[:fingerprint {:optional true} [:maybe [:ref ::lib.schema.metadata.fingerprint/fingerprint]]]
+ [:has_field_values {:optional true} [:maybe [:ref ::lib.schema.metadata/column.has-field-values]]]
[:id {:optional true} [:maybe ::lib.schema.id/field]]
+ [:inherited_temporal_unit {:optional true} [:maybe [:ref ::lib.schema.temporal-bucketing/unit]]]
+ [:nfc_path {:optional true} [:maybe [:sequential :string]]]
+ [:position {:optional true} [:maybe :int]]
+ [:remapped_from {:optional true} [:maybe :string]]
+ [:remapped_to {:optional true} [:maybe :string]]
+ [:selected? {:optional true} :boolean]
;; name is allowed to be empty in some databases like SQL Server.
[:semantic_type {:optional true} [:maybe ::lib.schema.common/semantic-or-relation-type]]
[:settings {:optional true} [:maybe [:map {:closed false}]]]
[:source {:optional true} [:maybe [:ref ::lib.schema.metadata/column.legacy-source]]]
+ [:table_id {:optional true} [:maybe [:ref ::SourceTable]]]
[:unit {:optional true} [:maybe [:ref ::lib.schema.temporal-bucketing/unit]]]
[:visibility_type {:optional true} [:maybe [:ref ::lib.schema.metadata/column.visibility-type]]]]
[:ref ::legacy-column-metadata.qualified-keys]]
diff --git a/src/metabase/legacy_mbql/schema/helpers.cljc b/src/metabase/legacy_mbql/schema/helpers.cljc
index 4303fd06db9..30d163987ae 100644
--- a/src/metabase/legacy_mbql/schema/helpers.cljc
+++ b/src/metabase/legacy_mbql/schema/helpers.cljc
@@ -15,6 +15,11 @@
[clause-name]
(keyword "metabase.legacy-mbql.schema" (name clause-name)))
+(defn known-clause-tag?
+ "Whether `k` names a registered legacy-MBQL clause."
+ [k]
+ (some? (mr/registered-schema (clause-registry-name k))))
+
(defn defclause
"Impl for [[defclause*]]."
[clause-name schema]
@@ -82,9 +87,11 @@
[:fn
{:error/message (str "must be a `" tag "` clause")
:decode/normalize (fn [x]
- (when (and (sequential? x)
- ((some-fn simple-keyword? string?) (first x)))
- (update (vec x) 0 normalize-keyword)))}
+ (if (and (sequential? x)
+ ((some-fn simple-keyword? string?) (first x))
+ (known-clause-tag? (normalize-keyword (first x))))
+ (update (vec x) 0 normalize-keyword)
+ x))}
(partial is-clause? tag)]
(into
[:catn
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index ace299ef6ca..f0f329e7188 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -1660,6 +1660,7 @@
all-measure-ids
all-segment-ids
all-source-card-ids
+ all-source-card-ids-recursive
all-source-table-ids
all-template-tag-field-ids
all-template-tag-snippet-ids
diff --git a/src/metabase/lib/limit.cljc b/src/metabase/lib/limit.cljc
index a2f74ab086a..5d550b53def 100644
--- a/src/metabase/lib/limit.cljc
+++ b/src/metabase/lib/limit.cljc
@@ -34,7 +34,7 @@
stage-number :- :int]
(:limit (lib.util/query-stage query stage-number))))
-(defn ^:export disable-default-limit
+(defn disable-default-limit
"Sets the `disable-max-results?` middleware option on `query`, which disables the default limit on
query results. Used by transforms to allow unlimited result rows."
[query]
diff --git a/src/metabase/lib/query/test_spec.cljc b/src/metabase/lib/query/test_spec.cljc
index 84e29ff994d..b4414f9266d 100644
--- a/src/metabase/lib/query/test_spec.cljc
+++ b/src/metabase/lib/query/test_spec.cljc
@@ -350,6 +350,7 @@
(mtx/transformer
mtx/json-transformer
(mtx/key-transformer {:decode #(-> % u/->kebab-case-en keyword)})
+ {:name :normalize}
mtx/strip-extra-keys-transformer
mtx/default-value-transformer)))
diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljc
index 03c77659f63..926897aee3a 100644
--- a/src/metabase/lib/schema.cljc
+++ b/src/metabase/lib/schema.cljc
@@ -549,6 +549,18 @@
[:settings {:optional true} [:ref ::lib.schema.settings/settings]]
[:constraints {:optional true} [:ref ::lib.schema.constraints/constraints]]
[:middleware {:optional true} [:ref ::lib.schema.middleware-options/middleware-options]]
+ [:was-pivot
+ {:optional true
+ :description
+ "Whether this query was originally run as a pivot query. Stamped into the saved `json_query` by
+ `metabase.query-processor.middleware.process-userland-query` and sent back by clients re-downloading pivot query
+ results."}
+ [:maybe :boolean]]
+ [:pivot-rows {:optional true} [:maybe [:sequential [:int {:min 0}]]]]
+ [:pivot-cols {:optional true} [:maybe [:sequential [:int {:min 0}]]]]
+ [:pivot-measures {:optional true} [:maybe [:sequential [:int {:min 0}]]]]
+ [:show-row-totals {:optional true} [:maybe :boolean]]
+ [:show-column-totals {:optional true} [:maybe :boolean]]
;; TODO -- `:viz-settings` ?
;;
;; INFO
diff --git a/src/metabase/lib/schema/common.cljc b/src/metabase/lib/schema/common.cljc
index 5d88ea51918..fdef21acf94 100644
--- a/src/metabase/lib/schema/common.cljc
+++ b/src/metabase/lib/schema/common.cljc
@@ -187,6 +187,19 @@
(str "Not a valid base type: " (pr-str value)))}
base-type?]])
+(defn- coercion-strategy? [x]
+ (isa? x :Coercion/*))
+
+(mr/def ::coercion-strategy
+ [:and
+ [:keyword
+ {:decode/normalize #'normalize-keyword}]
+ [:fn
+ {:error/message "valid coercion strategy"
+ :error/fn (fn [{:keys [value]} _]
+ (str "Not a valid coercion strategy: " (pr-str value)))}
+ coercion-strategy?]])
+
(defn normalize-options-map
"Basic normalization behavior for an MBQL clause options map."
[m]
diff --git a/src/metabase/lib/schema/literal.cljc b/src/metabase/lib/schema/literal.cljc
index b45b7036ec3..66f2e038349 100644
--- a/src/metabase/lib/schema/literal.cljc
+++ b/src/metabase/lib/schema/literal.cljc
@@ -152,6 +152,12 @@
[:effective-type ::common/base-type]
[:unit {:optional true} [:maybe ::temporal-bucketing/unit]]]])
+(mr/def ::value.value
+ "The value slot of a `:value` clause: a single literal that is not a Clojure collection."
+ [:fn
+ {:error/message "value must be a literal, not a Clojure collection"}
+ (complement coll?)])
+
;;; [:value <opts> <value>] clauses are mostly used internally by the query processor to add type information to
;;; literals, to make it easier for drivers to process queries; see
;;; the [[metabase.query-processor.middleware.wrap-value-literals]] middleware. It is also used to differentiate `nil`
@@ -166,7 +172,7 @@
{:error/message "Value :value clause"}
#_tag [:= {:decode/normalize common/normalize-keyword} :value]
#_opts [:ref ::value.options]
- #_value any?])
+ #_value [:ref ::value.value]])
(mr/def ::literal
[:or
diff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljc
index b556b5502b0..e51591a1020 100644
--- a/src/metabase/lib/schema/metadata.cljc
+++ b/src/metabase/lib/schema/metadata.cljc
@@ -535,7 +535,7 @@
;; `:coercion-strategy`, along with `:qp/native-sandbox-column.propagate-coercion? true` (see below). Lib will
;; propagate the coercion strategy through *exactly one* stage boundary, so it can get from the SQL first stage to
;; the earliest MBQL stage, where the coercion will get applied correctly. See QUE2-376 or #69867 for more details.
- [:qp/native-sandbox-column.force-coercion-strategy {:optional true} :keyword]
+ [:qp/native-sandbox-column.force-coercion-strategy {:optional true} [:ref ::lib.schema.common/coercion-strategy]]
;;
;; See above about `:qp/native-sandbox-column.force-coercion-strategy`.
[:qp/native-sandbox-column.propagate-coercion? {:optional true} :boolean]]
diff --git a/src/metabase/lib/schema/middleware_options.cljc b/src/metabase/lib/schema/middleware_options.cljc
index aa6cc2b16c6..892d5938b86 100644
--- a/src/metabase/lib/schema/middleware_options.cljc
+++ b/src/metabase/lib/schema/middleware_options.cljc
@@ -59,5 +59,17 @@
:description
"Whether to process a question's visualization settings and include them in the result metadata so that they can
incorporated into an export. Used by `metabase.query-processor.middleware.visualization-settings`; default
+ `false`."}
+ [:maybe :boolean]]
+ [:js-int-to-string?
+ {:optional true
+ :description
+ "Whether to convert bigint values in results to strings so that they can be parsed losslessly by JavaScript
+ clients. Used by `metabase.query-processor.middleware.large-int`; default `false`."}
+ [:maybe :boolean]]
+ [:ignore-cached-results?
+ {:optional true
+ :description
+ "Whether to ignore any cached results and re-run the query. Used by the query results cache middleware; default
`false`."}
[:maybe :boolean]]])
diff --git a/src/metabase/lib/schema/parameter.cljc b/src/metabase/lib/schema/parameter.cljc
index ed36a27a368..94f32ee87cc 100644
--- a/src/metabase/lib/schema/parameter.cljc
+++ b/src/metabase/lib/schema/parameter.cljc
@@ -21,7 +21,7 @@
currently still allowed for backwards-compatibility purposes -- currently the FE client will just parrot back the
`:widget-type` in some cases. In these cases, the backend is just supposed to infer the actual type of the parameter
value."
- (:refer-clojure :exclude [get-in])
+ (:refer-clojure :exclude [get-in mapv])
(:require
#?@(:clj
([flatland.ordered.map :as ordered-map]))
@@ -30,7 +30,7 @@
[metabase.util :as u]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
- [metabase.util.performance :refer [get-in]]))
+ [metabase.util.performance :refer [get-in mapv]]))
(defn- variadic-opts-first
"Some clauses, like `:contains`, have optional `options` last in their binary form, and required options first in
@@ -352,10 +352,28 @@
(vec (sort-by str param-value))
param-value))
+(mr/def ::parameter.value.scalar
+ "A single scalar parameter value."
+ [:fn
+ {:error/message "Valid parameter value (cannot be a collection)"}
+ (complement coll?)])
+
+(defn- normalize-parameter-value
+ [x]
+ (letfn [(normalize-scalar-parameter-value [x]
+ (when-not (coll? x)
+ x))]
+ (if (sequential? x)
+ (mapv normalize-scalar-parameter-value x)
+ (normalize-scalar-parameter-value x))))
+
(mr/def ::parameter.value
[:schema
{:encode/for-hashing #'sort-parameter-values}
- :any])
+ [:or
+ {:decode/normalize normalize-parameter-value}
+ [:ref ::parameter.value.scalar]
+ [:sequential [:ref ::parameter.value.scalar]]]])
(mr/def ::parameter.options
"Options the frontend attaches to a parameter value."
diff --git a/src/metabase/lib/schema/template_tag.cljc b/src/metabase/lib/schema/template_tag.cljc
index 323353fbe22..0fb63b47eaf 100644
--- a/src/metabase/lib/schema/template_tag.cljc
+++ b/src/metabase/lib/schema/template_tag.cljc
@@ -44,7 +44,7 @@
[:ref ::common]
[:map
;; default value for this parameter
- [:default {:optional true} any?]
+ [:default {:optional true} [:ref ::lib.schema.parameter/parameter.value]]
;; whether or not a value for this parameter is required in order to run the query
[:required {:optional true} :boolean]]])
@@ -56,7 +56,7 @@
;; :display-name "Unit"}
(mr/def ::temporal-unit
[:merge
- [:ref ::common]
+ [:ref ::value.common]
[:map
[:type [:= :temporal-unit]]
;; an optional alias to use in place of the normal field ref
@@ -144,7 +144,7 @@
[:map
[:field-id ::id/field]
[:op (into [:enum] allowed-source-filter-ops)]
- [:value :any]])
+ [:value [:ref ::lib.schema.parameter/parameter.value]]])
;; Example:
;;
diff --git a/src/metabase/lib/schema/test_spec.cljc b/src/metabase/lib/schema/test_spec.cljc
index d0dffa622b9..c96ba5f3322 100644
--- a/src/metabase/lib/schema/test_spec.cljc
+++ b/src/metabase/lib/schema/test_spec.cljc
@@ -23,7 +23,8 @@
[:id [:ref ::lib.schema.id/card]]])
(mr/def ::test-source-spec
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:table ::test-table-source-spec]
[:card ::test-card-source-spec]])
@@ -84,7 +85,8 @@
[:args {:default []} [:sequential [:ref ::test-expression-spec]]]])
(mr/def ::test-expression-spec
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:column [:ref ::test-column-spec]]
[:literal [:ref ::test-literal-expression-spec]]
[:operator [:ref ::test-operator-expression-spec]]])
@@ -116,7 +118,8 @@
[:conditions {:optional true} [:maybe [:sequential ::test-join-condition-spec]]]])
(mr/def ::test-join-source-spec
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:column [:ref ::test-column-with-binning-spec]]
[:literal [:ref ::test-literal-expression-spec]]
[:operator [:ref ::test-operator-expression-spec]]])
@@ -192,7 +195,8 @@
(mr/def ::test-template-tag-spec
[:map
[:type ::lib.schema.template-tag/type]]
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:temporal-unit [:ref ::test-temporal-unit-spec]]
[:dimension [:ref ::test-field-filter-spec]]
[:snippet [:ref ::test-snippet-spec]]
diff --git a/src/metabase/lib/walk/util.cljc b/src/metabase/lib/walk/util.cljc
index 0b5973eff8f..6ef81e66c7d 100644
--- a/src/metabase/lib/walk/util.cljc
+++ b/src/metabase/lib/walk/util.cljc
@@ -14,7 +14,7 @@
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.match :as match]
- [metabase.util.performance :refer [not-empty]]))
+ [metabase.util.performance :as perf :refer [not-empty]]))
(defn- transduce-stages
([rf query]
@@ -129,6 +129,25 @@
(all-metric-ids query)
(all-template-tag-card-ids query))))
+(mu/defn all-source-card-ids-recursive :- [:maybe [:set {:min 1} ::lib.schema.id/card]]
+ "Like [[all-source-card-ids]], but follows each source Card into its own query, returning every Card the query reads
+ at any depth."
+ [query :- ::lib.schema/query]
+ (loop [seen #{}, layer (set (all-source-card-ids query))]
+ (let [layer (set/difference layer seen)]
+ (if (perf/empty? layer)
+ (not-empty seen)
+ (do
+ (lib.metadata/bulk-metadata query :metadata/card layer)
+ (recur (set/union seen layer)
+ (into #{}
+ (mapcat (fn [card-id]
+ (some-> (lib.metadata/card query card-id)
+ :dataset-query
+ not-empty
+ all-source-card-ids)))
+ layer)))))))
+
(mu/defn any-native-stage?
"Returns true if any stage of this query is native."
[query :- ::lib.schema/query]
diff --git a/src/metabase/lib_be/metadata/bootstrap.clj b/src/metabase/lib_be/metadata/bootstrap.clj
index a5ea89f5556..74e3b34f2e1 100644
--- a/src/metabase/lib_be/metadata/bootstrap.clj
+++ b/src/metabase/lib_be/metadata/bootstrap.clj
@@ -1,6 +1,5 @@
(ns metabase.lib-be.metadata.bootstrap
(:require
- [clojure.set :as set]
[metabase.lib.core :as lib]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
[metabase.lib.schema.id :as lib.schema.id]
@@ -120,13 +119,10 @@
[:or
::empty-map
[:map
- [:database ::maybe-unresolved-database-id]]
- [:map
- ["database" ::maybe-unresolved-database-id]]]]]
+ [:database ::maybe-unresolved-database-id]]]]]
(when (seq query)
(if (pos-int? (:database query))
query
- (let [query (set/rename-keys query {"database" :database})
- database-id (resolved-database-id metadata-provider query)]
+ (let [database-id (resolved-database-id metadata-provider query)]
(cond-> query
database-id (assoc :database database-id)))))))
diff --git a/src/metabase/lib_be/metadata/jvm.clj b/src/metabase/lib_be/metadata/jvm.clj
index e70f86880b3..053f64f2c0b 100644
--- a/src/metabase/lib_be/metadata/jvm.clj
+++ b/src/metabase/lib_be/metadata/jvm.clj
@@ -181,11 +181,11 @@
[(t2/table-name :model/Dimension) :dimension]
[:and
[:= :dimension/field_id :field/id]
- [:inline [:in :dimension/type ["external" "internal"]]]]
+ [:in :dimension/type ["external" "internal"]]]
[(t2/table-name :model/FieldValues) :values]
[:and
[:= :values/field_id :field/id]
- [:= :values/type [:inline "full"]]]]}))
+ [:= :values/type "full"]]]}))
(t2/define-after-select :metadata/column
[field]
@@ -484,7 +484,7 @@
[:= :active true]
[:or
[:= :visibility_type nil]
- [:not-in :visibility_type [:inline ["hidden" "technical" "cruft"]]]]]
+ [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]
:metadata/column
(let [excluded-visibility-types (cond-> ["retired"]
@@ -493,7 +493,7 @@
[:= :field/active true]
[:or
[:= :field/visibility_type nil]
- [:not-in :field/visibility_type [:inline excluded-visibility-types]]]])
+ [:not-in :field/visibility_type excluded-visibility-types]]])
:metadata/card
[:= :card/archived false]
@@ -526,7 +526,7 @@
table-ids (conj [:in (table-id-key metadata-type) table-ids])
card-ids (conj [:in (card-id-key metadata-type) card-ids])
active-only? (conj (active-only-honeysql-filter metadata-type {:include-sensitive? include-sensitive?}))
- metric? (conj [:= :type [:inline "metric"]])
+ metric? (conj [:= :type "metric"])
(and metric? table-ids) (conj [:= :source_card_id nil]))]
(reduce
sql.helpers/where
diff --git a/src/metabase/lib_be/models/transforms.clj b/src/metabase/lib_be/models/transforms.clj
index 0ffb4a73137..d50e83e1997 100644
--- a/src/metabase/lib_be/models/transforms.clj
+++ b/src/metabase/lib_be/models/transforms.clj
@@ -1,26 +1,27 @@
(ns metabase.lib-be.models.transforms
- (:refer-clojure :exclude [some empty?])
+ (:refer-clojure :exclude [empty?])
(:require
+ ^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize]
[metabase.lib-be.metadata.bootstrap :as lib-be.bootstrap]
[metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
[metabase.lib.schema :as lib.schema]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.util :as lib.util]
[metabase.models.interface :as mi]
- [metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
- [metabase.util.performance :refer [some empty?]]))
+ [metabase.util.performance :refer [empty?]]))
(set! *warn-on-reflection* true)
-(defn- has-normalized-key? [m k]
- (or (get m k)
- (get m (u/qualified-name k))))
-
-(defn- has-any-of-these-normalized-keys? [m ks]
- (some (partial has-normalized-key? m) ks))
+(defn- normalize-mbql
+ [query]
+ (case (lib/normalized-query-type query)
+ :mbql/query (lib.schema.common/normalize-map-no-kebab-case query)
+ (:query :native) (mbql.normalize/normalize query)
+ (lib.schema.common/normalize-map-no-kebab-case query)))
(mu/defn normalize-query :- [:maybe
[:multi {:dispatch (comp boolean empty?)}
@@ -50,29 +51,31 @@
(empty? query)
{}
- (not (has-normalized-key? query :database))
- (throw (ex-info "Query must include :database" {:query query}))
-
- (not (has-any-of-these-normalized-keys? query #{:lib/type :type}))
- (throw (ex-info "Query must include :lib/type or :type" {:query query}))
-
- (and (has-normalized-key? query :lib/type)
- (has-any-of-these-normalized-keys? query #{:type :query :native}))
+ (and (:lib/type query)
+ (or (:type query) (:query query) (:native query)))
(throw (ex-info "MBQL 4 keys like :type, :query, or :native are not allowed in MBQL 5 queries with :lib/type"
{:query query}))
- (and (has-normalized-key? query :type)
- (has-normalized-key? query :stages))
+ (and (:type query) (:stages query))
(throw (ex-info "MBQL 5 :stages is not allowed in an MBQL 4 query with :type" {:query query}))
- (lib/cached-metadata-provider-with-cache? (:lib/metadata query))
- (lib/normalize ::lib.schema/query query)
-
:else
- (->> query
- (lib-be.bootstrap/resolve-database (when (lib/metadata-provider? metadata-providerable)
- metadata-providerable))
- (lib/query metadata-providerable)))))
+ (let [query (normalize-mbql query)]
+ (cond
+ (not (or (:lib/type query) (:type query)))
+ (throw (ex-info "Query must include :lib/type or :type" {:query query}))
+
+ (not (:database query))
+ (throw (ex-info "Query must include :database" {:query query}))
+
+ (lib/cached-metadata-provider-with-cache? (:lib/metadata query))
+ (lib/normalize ::lib.schema/query query)
+
+ :else
+ (->> query
+ (lib-be.bootstrap/resolve-database (when (lib/metadata-provider? metadata-providerable)
+ metadata-providerable))
+ (lib/query metadata-providerable)))))))
;; Normalization failed. Degrade to {} so bad stored data can't break callers,
;; but in strict mode (saving) rethrow rather than persist a query we couldn't parse.
(fn [e]
diff --git a/src/metabase/lib_be/schema.clj b/src/metabase/lib_be/schema.clj
new file mode 100644
index 00000000000..8bc10c3c2e9
--- /dev/null
+++ b/src/metabase/lib_be/schema.clj
@@ -0,0 +1,50 @@
+(ns metabase.lib-be.schema
+ (:refer-clojure :exclude [empty?])
+ (:require
+ [metabase.lib-be.models.transforms :as lib-be.transforms]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.util :as lib.util]
+ [metabase.util.i18n :refer [deferred-tru tru]]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.performance :refer [empty?]]))
+
+(set! *warn-on-reflection* true)
+
+(mr/def ::empty-query
+ [:= {} {}])
+
+(defn- normalize-query
+ [query message]
+ (if (map? query)
+ (try
+ (lib-be.transforms/normalize-query nil query {:strict? true})
+ (catch Exception e
+ (throw (ex-info (ex-message e)
+ {:status-code (or (:status-code (ex-data e)) 400)}))))
+ (throw (ex-info message {:status-code 400}))))
+
+(mr/def ::maybe-legacy-query
+ [:schema
+ {:description (deferred-tru "value must be a valid MBQL query.")
+ :decode/normalize #(normalize-query % (tru "value must be a valid MBQL query."))}
+ [:ref ::lib.schema/query]])
+
+(mr/def ::internal-query
+ [:map
+ [:type [:= {:decode/normalize keyword} :internal]]
+ [:fn :string]
+ [:args {:optional true} [:maybe [:sequential :any]]]
+ [:limit {:optional true} [:maybe :int]]
+ [:offset {:optional true} [:maybe :int]]])
+
+(mr/def ::maybe-legacy-or-internal-query
+ [:multi {:dispatch (fn [query] (and (map? query) (= (lib.util/normalized-query-type query) :internal)))
+ :description (deferred-tru "value must be a valid MBQL query, or an internal audit query.")}
+ [true ::internal-query]
+ [false ::maybe-legacy-query]])
+
+(mr/def ::maybe-legacy-or-empty-query
+ [:multi {:dispatch (fn [query] (boolean (and (map? query) (empty? query))))
+ :description (deferred-tru "value must be a valid MBQL query, or an empty query.")}
+ [true ::empty-query]
+ [false ::maybe-legacy-query]])
diff --git a/src/metabase/lib_metric/metadata/jvm.clj b/src/metabase/lib_metric/metadata/jvm.clj
index 6034dd4dbf1..6726b113818 100644
--- a/src/metabase/lib_metric/metadata/jvm.clj
+++ b/src/metabase/lib_metric/metadata/jvm.clj
@@ -32,7 +32,7 @@
Metrics are Cards with type='metric' - not scoped to any database."
[{id-set :id, name-set :name, :keys [table-ids card-ids], :as _metadata-spec}]
(let [active-only? (not (or id-set name-set))
- where-clauses (cond-> [[:= :type [:inline "metric"]]]
+ where-clauses (cond-> [[:= :type "metric"]]
id-set (conj [:in :id id-set])
name-set (conj [:in :name name-set])
table-ids (conj [:in :table_id table-ids])
diff --git a/src/metabase/login_history/models/login_history.clj b/src/metabase/login_history/models/login_history.clj
index 9efe0a6cca4..c5ce9a5a8da 100644
--- a/src/metabase/login_history/models/login_history.clj
+++ b/src/metabase/login_history/models/login_history.clj
@@ -93,6 +93,7 @@
[:= :user_id user-id]
[:> :timestamp cutoff]
[:not [:exists
+ ^:allow-subquery
{:select [1]
:from [[:login_history :lh2]]
:where [:and
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index f3671ecedb6..93721eb07ef 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -4,6 +4,7 @@
(:require
[clojure.core.async :as a]
[clojure.string :as str]
+ [clojure.walk :as walk]
[compojure.response :as compojure.response]
[metabase.ai-tracing.core :as ait]
[metabase.api.common :as api]
@@ -264,7 +265,7 @@
(defn- handle-post
"Handle a POST request containing one or more JSON-RPC messages."
[user-id request]
- (let [body (:body request)
+ (let [body (walk/keywordize-keys (:body request))
session-id (get-in request [:headers "mcp-session-id"])
eval-session-id (eval-session-override request)
batch? (sequential? body)]
diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.clj
index a08ed1a4ab0..ac4969a4cb5 100644
--- a/src/metabase/mcp/session.clj
+++ b/src/metabase/mcp/session.clj
@@ -236,6 +236,12 @@
[session-id]
(some? (session-parts session-id)))
+(defn- assert-session-id!
+ [session-id]
+ (when-not (valid-id? session-id)
+ (throw (ex-info "Invalid MCP session id" {:session-id session-id})))
+ session-id)
+
(defn create!
"Create a new MCP session. Returns a session id string.
No database row is written — the session is just an opaque correlator until
@@ -321,6 +327,7 @@
([mcp-session-id user-id encoded-query]
(store-handle! mcp-session-id user-id encoded-query nil))
([mcp-session-id user-id encoded-query prompt]
+ (assert-session-id! mcp-session-id)
;; Materializing a core_session here serves two purposes: its FK is what makes handles
;; cascade-delete when the session row is reaped, and its user_id is what find-handle-row
;; filters on for cross-session ownership.
@@ -334,6 +341,11 @@
prompt (assoc :prompt prompt)))
handle-id)))
+(defn- handle-id?
+ [handle-id]
+ (and (string? handle-id)
+ (some? (parse-uuid handle-id))))
+
(defn- find-handle-row
"Look up the handle row by `handle-id`, scoped to `user-id`.
Handle ids are globally unique UUIDs, so the join's `WHERE mqh.id = handle-id` returns at most one
@@ -341,7 +353,7 @@
on the row only so harnesses that rotate MCP sessions between calls (e.g. ChatGPT) can be logged as
cross-session resolutions for telemetry."
[mcp-session-id user-id handle-id]
- (when (and user-id handle-id)
+ (when (and user-id (handle-id? handle-id))
;; Single round-trip: join `mcp_query_handle` to `core_session` and filter on
;; `core_session.user_id`, so ownership is enforced in the WHERE clause.
(let [row (t2/select-one :model/McpQueryHandle
@@ -379,6 +391,7 @@
`core_session_id` was never set — e.g. handles for regular query payloads that
aren't backed by an MCP iframe and so never materialize a `core_session`."
[session-id user-id]
+ (assert-session-id! session-id)
(let [key-hashed (session/hash-session-key (derive-embedding-session-key session-id))]
(t2/query {:delete-from :core_session
:where [:and
diff --git a/src/metabase/measures/api.clj b/src/metabase/measures/api.clj
index c04819dd305..b7d60798f64 100644
--- a/src/metabase/measures/api.clj
+++ b/src/metabase/measures/api.clj
@@ -4,8 +4,8 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.events.core :as events]
- [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.measures.schema :as measures.schema]
[metabase.metrics.core :as metrics]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
@@ -34,29 +34,6 @@
[:dimension_mappings {:optional true} [:maybe [:sequential :map]]]
[:result_column_name {:optional true} [:maybe :string]]])
-(defn- normalize-input-definition
- "Normalize measure definition from API input to MBQL5.
- Accepts MBQL4 definitions for Cypress e2e test support:
- - MBQL5 full queries (passed through)
- - MBQL4 full queries (converted to MBQL5)
- - MBQL4 fragments (wrapped in full query, then converted to MBQL5); the fragment must
- include `:source-table` so the table can be derived"
- [definition]
- (if (seq definition)
- (-> (case (lib/normalized-mbql-version definition)
- (:mbql-version/mbql5 :mbql-version/legacy)
- definition
- ;; default: MBQL4 fragment - wrap it in a full query
- (let [table-id (:source-table definition)
- _ (api/check-400 (pos-int? table-id)
- (tru "Measure definition must specify a source table."))
- database-id (t2/select-one-fn :db_id :model/Table :id table-id)]
- {:database database-id
- :type :query
- :query definition}))
- lib-be/normalize-query)
- {}))
-
(defn- definition-table-id
"Derive the source table ID from a normalized measure definition, or throw a 400 if it has none."
[normalized-definition]
@@ -70,17 +47,16 @@
_query-params
{:keys [name description definition], :as body} :- [:map
[:name ms/NonBlankString]
- [:definition ms/Map]
+ [:definition ::measures.schema/definition]
[:description {:optional true} [:maybe :string]]]]
- (let [normalized-definition (normalize-input-definition definition)
- table-id (definition-table-id normalized-definition)]
+ (let [table-id (definition-table-id definition)]
(api/create-check :model/Measure (assoc body :table_id table-id))
(let [measure (api/check-500
(first (t2/insert-returning-instances! :model/Measure
:creator_id api/*current-user-id*
:name name
:description description
- :definition normalized-definition)))]
+ :definition definition)))]
(events/publish-event! :event/measure-create {:object measure :user-id api/*current-user-id*})
(t2/hydrate measure :creator))))
@@ -131,17 +107,13 @@
clean-body (u/select-keys-when body
:present #{:description}
:non-nil #{:archived :definition :name})
- new-def (when-let [def (:definition clean-body)]
- (normalize-input-definition def))
- new-body (merge
- (dissoc clean-body :revision_message)
- (when new-def {:definition new-def}))
+ new-body (dissoc clean-body :revision_message)
changes (when-not (= new-body existing)
new-body)]
;; An updated definition must still specify a source table; if it implicitly moves the Measure to a different
;; table, the write-check above checked the old table, so also make sure the user could create a Measure on the
;; new one.
- (when new-def
+ (when-let [new-def (:definition clean-body)]
(let [new-table-id (definition-table-id new-def)]
(when (not= new-table-id (:table_id existing))
(api/create-check :model/Measure {:table_id new-table-id}))))
@@ -158,7 +130,7 @@
_query-params
body :- [:map
[:name {:optional true} [:maybe ms/NonBlankString]]
- [:definition {:optional true} [:maybe ms/Map]]
+ [:definition {:optional true} [:maybe ::measures.schema/definition]]
[:revision_message ms/NonBlankString]
[:archived {:optional true} [:maybe :boolean]]
[:description {:optional true} [:maybe :string]]]]
diff --git a/src/metabase/measures/models/measure.clj b/src/metabase/measures/models/measure.clj
index 2d3442084dc..1f825f2e4a9 100644
--- a/src/metabase/measures/models/measure.clj
+++ b/src/metabase/measures/models/measure.clj
@@ -6,6 +6,7 @@
[metabase.api.common :as api]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
[metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.measure :as lib.schema.measure]
[metabase.metrics.core :as metrics]
@@ -40,7 +41,7 @@
"Transform for measure definitions. Handles JSON serialization/deserialization.
Validation happens in before-insert and before-update hooks."
{:in mi/json-in
- :out mi/json-out-with-keywordization})
+ :out mi/json-out-without-keywordization})
(t2/deftransforms :model/Measure
{:definition transform-measure-definition
@@ -159,7 +160,8 @@
[{:keys [definition] :as measure}]
(if (seq definition)
(try
- (assoc measure :definition (lib-be/normalize-query definition))
+ (assoc measure :definition (-> (lib/normalize ::lib.schema/query definition)
+ lib-be/normalize-query))
(catch Throwable e
(log/errorf "Error normalizing measure definition: %s" (ex-message e))
measure))
diff --git a/src/metabase/measures/schema.clj b/src/metabase/measures/schema.clj
new file mode 100644
index 00000000000..f232d3da611
--- /dev/null
+++ b/src/metabase/measures/schema.clj
@@ -0,0 +1,18 @@
+(ns metabase.measures.schema
+ (:require
+ [metabase.lib-be.schema :as lib-be.schema]
+ [metabase.lib.core :as lib]
+ [metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.malli.registry :as mr]))
+
+(set! *warn-on-reflection* true)
+
+(mr/def ::definition
+ "Schema for a measure's `:definition`; accepts a full MBQL query, converting legacy MBQL on decode."
+ [:schema
+ {:description (deferred-tru "value must be a valid MBQL query with a source table.")}
+ [:and
+ ::lib-be.schema/maybe-legacy-query
+ [:fn
+ {:error/message (deferred-tru "measure definition must have a source table")}
+ #(some? (lib/primary-source-table-id %))]]])
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.clj
index 1b466eb3568..94cd831e9b2 100644
--- a/src/metabase/metabot/agent/core.clj
+++ b/src/metabase/metabot/agent/core.clj
@@ -13,6 +13,7 @@
[metabase.metabot.agent.messages :as messages]
[metabase.metabot.agent.profiles :as profiles]
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.metadata-perms :as metabot.perms]
[metabase.metabot.provider-util :as provider-util]
[metabase.metabot.schema :as metabot.schema]
[metabase.metabot.scope :as scope]
@@ -672,7 +673,8 @@
scope/*current-user-scope* scopes
scope/*current-user-metabot-permissions* perms
scope/*current-user-capabilities* (get-in opts [:context :capabilities] #{})
- scope/*current-loadable-skill-ids* (atom #{})]
+ scope/*current-loadable-skill-ids* (atom #{})
+ metabot.perms/*cache* (atom {})]
(try
;; `with-eval-session` establishes the eval capture (gated by MB_AI_EVAL_CAPTURE,
;; inherited when an in-process `capture-reducible` already bound one). Spans stream
diff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.clj
index de825dd8811..cd091c15469 100644
--- a/src/metabase/metabot/agent/user_context.clj
+++ b/src/metabase/metabot/agent/user_context.clj
@@ -7,6 +7,8 @@
[clojure.string :as str]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.metabot.metadata-perms :as metabot.perms]
+ [metabase.metabot.query-analyzer :as query-analyzer]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
@@ -135,8 +137,14 @@
(te/lines preamble (format-fn structured-output))
(format-simple-entity entity)))
(catch Exception e
- (log/error "Error fetching entity details for viewing context" {:type (:type entity) :id (:id entity)} (ex-message e))
- (format-simple-entity entity))))
+ (if (= 403 (:status-code (ex-data e)))
+ (do (log/debugf "Omitting viewing-context entity the current user cannot read: %s %s"
+ (:type entity) (:id entity))
+ nil)
+ (do (log/error "Error fetching entity details for viewing context"
+ {:type (:type entity) :id (:id entity)}
+ (ex-message e))
+ (format-simple-entity entity))))))
(defmethod format-entity "table"
[entity]
@@ -249,11 +257,92 @@
(map format-entity)
te/lines)))))
+(def ^:private exported-table-id-keys
+ [:source-table :source_table])
+
+(def ^:private exported-card-id-keys
+ [:source-card :source_card :card-id :card_id])
+
+(def ^:private exported-field-id-keys
+ [:source-field :metabase.models.visualization-settings/param-mapping-source])
+
+(defn- exported-entity-ids
+ [normalized]
+ (let [ids (fn [ks node] (into #{} (comp (map #(get node %)) (filter pos-int?)) ks))]
+ (reduce
+ (fn [acc node]
+ (cond
+ (map? node)
+ (-> acc
+ (update :table into (ids exported-table-id-keys node))
+ (update :card into (ids exported-card-id-keys node))
+ (update :field into (ids exported-field-id-keys node)))
+
+ (and (vector? node) (not (map-entry? node)))
+ (case (keyword (first node))
+ (:field :field-id) (update acc :field into (filter pos-int?) [(nth node 1 nil) (nth node 2 nil)])
+ :metric (update acc :card into (filter pos-int?) [(nth node 1 nil) (nth node 2 nil)])
+ acc)
+
+ :else acc))
+ {:table #{} :card #{} :field #{}}
+ (tree-seq coll? seq normalized))))
+
+(defn- native-stage?
+ [normalized]
+ (boolean (some #(and (map? %) (= :mbql.stage/native (:lib/type %)))
+ (tree-seq coll? seq normalized))))
+
+(defn- native-sql-table-ids
+ [normalized]
+ (try
+ (into #{}
+ (comp (keep #(or (:table-id %) (:id %))) (filter pos-int?))
+ (:tables (query-analyzer/tables-for-native normalized :all-drivers-trusted? true)))
+ (catch Exception e
+ (log/debugf "Could not analyze a viewing-context native query for permission gating: %s"
+ (ex-message e))
+ #{})))
+
+(defn- sandbox-visible-fields?
+ [field-id->table-id]
+ (let [restricted (metabot.perms/sandbox-restricted-fields (set (vals field-id->table-id)))]
+ (every? (fn [[field-id table-id]]
+ (if-let [allowed (get restricted table-id)]
+ (contains? allowed field-id)
+ true))
+ field-id->table-id)))
+
+(defn- queryable-normalized-query
+ [query]
+ (let [raw-database-id (and (map? query) (:database query))]
+ (when (pos-int? raw-database-id)
+ (try
+ (let [normalized (lib-be/normalize-query query)
+ database-id (:database normalized)]
+ (when (and (pos-int? database-id)
+ (mi/can-query? :model/Database database-id))
+ (let [{:keys [table card field]} (exported-entity-ids normalized)
+ field-table (metabot.perms/field-id->table-id field)
+ table-ids (cond-> (into (set table) (vals field-table))
+ (native-stage? normalized) (into (native-sql-table-ids normalized)))]
+ (when (and (= table-ids (metabot.perms/queryable-table-ids table-ids))
+ (sandbox-visible-fields? field-table)
+ (every? #(mi/can-read? :model/Card %) card))
+ [normalized (lib-be/application-database-metadata-provider database-id)]))))
+ (catch Exception e
+ (log/debugf "Omitting a viewing-context query that could not be permission-checked: %s"
+ (ex-message e))
+ nil)))))
+
(defn- transform-query-source-text
"Format a transform's `:query` source for the LLM; the rendering and fallback contract
lives in [[llm-shape/export-query-for-llm]]."
[source]
- (llm-shape/export-query-for-llm (:query source)))
+ (let [query (:query source)]
+ (when (or (not (and (map? query) (:database query)))
+ (queryable-normalized-query query))
+ (llm-shape/export-query-for-llm query))))
(defn- transform-source-type
[source]
diff --git a/src/metabase/metabot/api/conversations.clj b/src/metabase/metabot/api/conversations.clj
index bb6d7024700..15ad31ebba1 100644
--- a/src/metabase/metabot/api/conversations.clj
+++ b/src/metabase/metabot/api/conversations.clj
@@ -120,17 +120,18 @@
New rows participate via `metabot_message.user_id`; legacy rows created before
message authors were stamped fall back to the conversation originator."
[user-id]
- (let [participation-exists [:exists {:select [[[:inline 1]]]
- :from [[:metabot_message :participation_message]]
- :where [:and
- [:= :participation_message.conversation_id :c.id]
- [:= :participation_message.user_id user-id]]}]]
+ (let [participation-exists [:exists ^:allow-subquery {:select [[[:inline 1]]]
+ :from [[:metabot_message :participation_message]]
+ :where [:and
+ [:= :participation_message.conversation_id :c.id]
+ [:= :participation_message.user_id user-id]]}]]
[:or
[:= :c.user_id user-id]
participation-exists]))
(defn- last-live-message-profile-id-subquery
[]
+ ^:allow-subquery
{:select [:last_message.profile_id]
:from [[:metabot_message :last_message]]
:where [:and
@@ -141,6 +142,7 @@
(defn- live-message-count-subquery
[]
+ ^:allow-subquery
{:select [[[:count :*]]]
:from [[:metabot_message :counted_message]]
:where [:and
@@ -149,6 +151,7 @@
(defn- last-live-message-at-subquery
[]
+ ^:allow-subquery
{:select [[[:max :recent_message.created_at]]]
:from [[:metabot_message :recent_message]]
:where [:and
diff --git a/src/metabase/metabot/api/metabot.clj b/src/metabase/metabot/api/metabot.clj
index 35312d3be62..9c008c278f7 100644
--- a/src/metabase/metabot/api/metabot.clj
+++ b/src/metabase/metabot/api/metabot.clj
@@ -103,9 +103,9 @@
rand-fn (case (mdb/db-type)
:postgres :random
:rand)
- base-query (cond-> {:join [[{:select [:id :name :type]
- :from [[(metabot.tools.u/metabot-metrics-and-models-query id)
- :scope]]}
+ base-query (cond-> {:join [[^:allow-subquery {:select [:id :name :type]
+ :from [[(metabot.tools.u/metabot-metrics-and-models-query id)
+ :scope]]}
:card]
[:and
[:= :card.id :metabot_prompt.card_id]]]
diff --git a/src/metabase/metabot/context.clj b/src/metabase/metabot/context.clj
index 80ad5554390..fb6862fbb07 100644
--- a/src/metabase/metabot/context.clj
+++ b/src/metabase/metabot/context.clj
@@ -10,6 +10,7 @@
[metabase.lib.core :as lib]
[metabase.metabot.config :as metabot.config]
[metabase.metabot.curation :as curation]
+ [metabase.metabot.metadata-perms :as metabot.perms]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.table-utils :as table-utils]
[metabase.transforms-base.util :as transforms-base.u]
@@ -201,13 +202,15 @@
which is too restrictive for MBQL viewing context enrichment."
[[database-id table-ids]]
(try
- (let [raw-tables (t2/select [:model/Table :id :name :schema :description]
- :db_id database-id
- :id [:in table-ids]
- :active true
- :visibility_type nil)]
+ (let [raw-tables (t2/select [:model/Table :id :name :schema :description]
+ :db_id database-id
+ :id [:in table-ids]
+ :active true
+ :visibility_type nil)
+ queryable-ids (metabot.perms/queryable-table-ids (map :id raw-tables))]
(into []
- (comp (m/distinct-by :id)
+ (comp (filter (comp queryable-ids :id))
+ (m/distinct-by :id)
(map table-stub))
raw-tables))
(catch Exception e
@@ -338,8 +341,9 @@
(create-context context nil))
([context :- ::context
opts :- [:maybe [:map-of :keyword :any]]]
- (-> context
- enhance-context-with-schema
- annotate-transform-source-types
- (add-recent-views (or opts {}))
- (set-user-time opts))))
+ (metabot.perms/with-cache
+ (-> context
+ enhance-context-with-schema
+ annotate-transform-source-types
+ (add-recent-views (or opts {}))
+ (set-user-time opts)))))
diff --git a/src/metabase/metabot/metadata_perms.clj b/src/metabase/metabot/metadata_perms.clj
new file mode 100644
index 00000000000..b9cc27ba0c0
--- /dev/null
+++ b/src/metabase/metabot/metadata_perms.clj
@@ -0,0 +1,82 @@
+(ns metabase.metabot.metadata-perms
+ (:require
+ [metabase.api.common :as api]
+ [metabase.metrics.core :as metrics]
+ [metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:dynamic *cache*
+ "Cache atom bound by [[with-cache]], or nil to read through to the app DB on every call."
+ nil)
+
+(defmacro with-cache
+ "Memoize this namespace's lookups for the duration of `body`. Nesting reuses the enclosing cache."
+ {:style/indent 0}
+ [& body]
+ `(binding [*cache* (or *cache* (atom {}))]
+ ~@body))
+
+(defn- memoized
+ [k ids compute absent]
+ (let [ids (set ids)
+ cache *cache*
+ k [api/*current-user-id* api/*is-superuser?* k]
+ known (if cache (get @cache k {}) {})
+ missing (into #{} (remove #(contains? known %)) ids)
+ fresh (when (seq missing)
+ (let [computed (compute missing)]
+ (into {} (map (fn [id] [id (get computed id absent)])) missing)))]
+ (when (and cache (seq fresh))
+ (swap! cache update k merge fresh))
+ (select-keys (merge known fresh) ids)))
+
+(defn- table-rows
+ [table-ids]
+ (memoized :table-row table-ids
+ (fn [ids] (t2/select-fn->fn :id identity :model/Table :id [:in ids]))
+ nil))
+
+(defn- permitted-table-ids
+ [k pred table-ids]
+ (->> (memoized k table-ids
+ (fn [ids]
+ (let [tables (into [] (keep (table-rows ids)) ids)]
+ (perms/prime-table-perms-cache {:table-ids (into #{} (map :id) tables)})
+ (into {} (comp (filter pred) (map (juxt :id (constantly true)))) tables)))
+ false)
+ (into #{} (keep (fn [[id permitted?]] (when permitted? id))))))
+
+(defn queryable-table-ids
+ "Returns the subset of `table-ids` the current user may run queries against."
+ [table-ids]
+ (permitted-table-ids :queryable-table mi/can-query? table-ids))
+
+(defn- data-accessible?
+ [table]
+ (perms/user-has-permission-for-table? api/*current-user-id*
+ :perms/view-data :unrestricted
+ (:db_id table) (:id table)))
+
+(defn data-accessible-table-ids
+ "Returns the subset of `table-ids` the current user has unrestricted view-data access to."
+ [table-ids]
+ (permitted-table-ids :data-accessible-table data-accessible? table-ids))
+
+(defn sandbox-restricted-fields
+ "Returns `{table-id #{allowed-field-id}}` for the column-sandboxed subset of `table-ids`."
+ [table-ids]
+ (->> (memoized :sandbox-fields table-ids
+ #(metrics/sandbox-restricted-fields (set %))
+ ::unrestricted)
+ (into {} (remove #(= ::unrestricted (val %))))))
+
+(defn field-id->table-id
+ "Returns a `{field-id table-id}` map for the given `field-ids`."
+ [field-ids]
+ (->> (memoized :field-table field-ids
+ (fn [ids] (t2/select-fn->fn :id :table_id [:model/Field :id :table_id] :id [:in ids]))
+ nil)
+ (into {} (remove #(nil? (val %))))))
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index ed6a5740ca0..ea2105327a4 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -113,15 +113,16 @@
;;; ---------------------------------------- Source resolution ----------------------------------------
+(defn- portable-table-fk
+ [x]
+ (when (and (vector? x) (= 3 (count x)) (string? (nth x 0)))
+ x))
+
(defn- first-stage-source-table-fk
"Pull the portable `[db schema table]` FK out of `stages[0].source-table`, or `nil`
if not present / wrong shape."
[parsed-query]
- (let [fk (get-in parsed-query ["stages" 0 "source-table"])]
- (when (and (vector? fk)
- (= 3 (count fk))
- (string? (nth fk 0)))
- fk)))
+ (portable-table-fk (get-in parsed-query ["stages" 0 "source-table"])))
(def ^:private metabase-uri-source-table-pattern
"Matches values the LLM sometimes writes into `source-table:` by confusing the Metabase
@@ -183,19 +184,64 @@
ContentStore methods. The unchecked underlying store rejects non-NanoID entity-id values."
shared.content-store/default-store)
-(defn- check-first-stage-source-table-query-permissions!
- "Ensure the current user can query the table named by `stages[0].source-table`.
-
- The metadata provider intentionally exposes database metadata without applying user data
- permissions. Before any repair pass can inspect fields/FKs on the requested source table,
- resolve the portable table FK and run the normal API query permission check."
- [metadata-provider parsed-query]
- (when-let [table-fk (first-stage-source-table-fk parsed-query)]
- (let [resolver (resolve.mp/import-resolver metadata-provider permission-aware-content-store)
- table-id (serdes.resolve/import-table-fk resolver table-fk)]
- (api/query-check :model/Table table-id)
+(defn- portable-field-fk-table
+ [x]
+ (when (and (vector? x)
+ (>= (count x) 4)
+ (string? (nth x 0))
+ (let [schema (nth x 1)] (or (nil? schema) (string? schema)))
+ (string? (nth x 2)))
+ (subvec x 0 3)))
+
+(defn- node-table-fks
+ [node]
+ (cond
+ (map? node)
+ (keep identity [(portable-table-fk (get node "source-table"))
+ (portable-field-fk-table (get node "source-field"))])
+
+ (and (vector? node)
+ (not (map-entry? node))
+ (= "field" (nth node 0 nil)))
+ (keep identity [(or (portable-field-fk-table (nth node 2 nil))
+ (portable-field-fk-table (nth node 1 nil)))])))
+
+(defn- referenced-table-fks
+ [parsed-query]
+ (into []
+ (comp (mapcat node-table-fks) (distinct))
+ (tree-seq coll? seq parsed-query)))
+
+(def ^:private unresolved-table-fk-errors
+ #{:unknown-table :ambiguous-table})
+
+(defn- resolve-table-fk
+ [resolver table-fk]
+ (try
+ (serdes.resolve/import-table-fk resolver table-fk)
+ (catch clojure.lang.ExceptionInfo e
+ (when-not (contains? unresolved-table-fk-errors (:error (ex-data e)))
+ (throw e))
nil)))
+(defn- check-source-table-query-permissions!
+ ([metadata-provider portable-query]
+ (check-source-table-query-permissions! metadata-provider portable-query #{}))
+
+ ([metadata-provider portable-query already-checked]
+ (if-let [table-fks (not-empty (referenced-table-fks portable-query))]
+ (let [resolver (resolve.mp/import-resolver metadata-provider permission-aware-content-store)]
+ (reduce (fn [checked table-fk]
+ (if-let [table-id (resolve-table-fk resolver table-fk)]
+ (if (contains? checked table-id)
+ checked
+ (do (api/query-check :model/Table table-id)
+ (conj checked table-id)))
+ checked))
+ already-checked
+ table-fks))
+ already-checked)))
+
(defn resolve-database-id-from-first-stage
"Resolve the application database id from the first stage's source.
@@ -348,16 +394,17 @@
(catch clojure.lang.ExceptionInfo e
(throw (as-agent-input-error e))))
database-id (resolve-database-id-from-first-stage parsed)
- mp (lib-be/application-database-metadata-provider database-id)]
- ;; Permission checks happen before repair/resolve so the metadata-provider-backed pipeline
- ;; never inspects table/card metadata that the current user cannot use.
- (check-first-stage-source-table-query-permissions! mp parsed)
+ mp (lib-be/application-database-metadata-provider database-id)
+ ;; Permission checks happen before repair/resolve so the metadata-provider-backed pipeline
+ ;; never inspects table/card metadata that the current user cannot use.
+ checked (check-source-table-query-permissions! mp parsed)]
;; Everything after the MP is built can surface LLM-input errors (lib.schema validation
;; in resolve, missing-column complaints from lib/query in `result-columns-for-query`,
;; etc.). Wrap the whole rest of the pipeline in a single `:agent-error?` relay so any of
;; them reach the tool wrapper with the flag set.
(try
(let [repaired (repr.repair/repair mp parsed permission-aware-content-store)
+ _perms (check-source-table-query-permissions! mp repaired checked)
_validated (repr/validate-query repaired)
pmbql-query (repr.resolve/resolve-query mp repaired permission-aware-content-store)
_runnable (when-let [why (query-not-runnable-explanation pmbql-query)]
diff --git a/src/metabase/metabot/tools/entity_details.clj b/src/metabase/metabot/tools/entity_details.clj
index 87132bde4d4..72cd5e3ebd3 100644
--- a/src/metabase/metabot/tools/entity_details.clj
+++ b/src/metabase/metabot/tools/entity_details.clj
@@ -9,12 +9,11 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.types.isa :as lib.types.isa]
[metabase.metabot.config :as metabot.config]
+ [metabase.metabot.metadata-perms :as metabot.perms]
[metabase.metabot.tools.shared.content-store :as shared.content-store]
[metabase.metabot.tools.util :as metabot.tools.u]
- [metabase.metrics.core :as metrics]
[metabase.models.interface :as mi]
[metabase.parameters.field-values :as params.field-values]
- [metabase.permissions.core :as perms]
[metabase.util :as u]
[metabase.util.humanization :as u.humanization]
[metabase.util.i18n :as i18n]
@@ -120,6 +119,9 @@
(defn get-dashboard-details
"Get information about the dashboard with ID `dashboard-id`."
[{:keys [dashboard-id]}]
+ (when-not (int? dashboard-id)
+ (throw (ex-info "Invalid dashboard_id format"
+ {:agent-error? true :status-code 400})))
(if-let [dashboard (t2/select-one [:model/Dashboard :id :description :name :collection_id] dashboard-id)]
(do (api/read-check dashboard)
{:structured-output
@@ -149,47 +151,51 @@
(defn- permission-filter-columns
"Remove columns hidden by Table or sandbox permissions and hide inaccessible FK targets on retained columns."
- [columns]
- (let [columns (vec columns)
- referenced-field-ids (into #{}
- (comp (mapcat (juxt :fk-field-id :fk-target-field-id))
- (filter some?))
- columns)
- referenced-fields (when (seq referenced-field-ids)
- (t2/select [:model/Field :id :table_id]
- :id [:in referenced-field-ids]))
- field-id->field (m/index-by :id referenced-fields)
- table-ids (into #{}
+ ([columns] (permission-filter-columns columns nil))
+ ([columns {:keys [explicit-joins-caller-performed?]}]
+ (let [columns (vec columns)
+ referenced-field-ids (into #{}
+ (comp (mapcat (juxt :fk-field-id :fk-target-field-id))
+ (filter some?))
+ columns)
+ referenced-field-table (when (seq referenced-field-ids)
+ (metabot.perms/field-id->table-id referenced-field-ids))
+ table-ids (into #{}
(filter pos-int?)
(concat (keep :table-id columns)
- (keep :table_id referenced-fields)))
- _ (perms/prime-table-perms-cache {:table-ids (set table-ids)})
- readable-table-ids (->> (t2/select :model/Table :id [:in table-ids])
- (filter mi/can-read?)
- (map :id)
- set)
- sandbox-restricted-ids (metrics/sandbox-restricted-fields table-ids)
- field-readable? (fn [table-id field]
- (and (contains? readable-table-ids table-id)
+ (vals referenced-field-table)))
+ queryable-table-ids (metabot.perms/queryable-table-ids table-ids)
+ accessible-table-ids (metabot.perms/data-accessible-table-ids table-ids)
+ sandbox-restricted-ids (metabot.perms/sandbox-restricted-fields table-ids)
+ field-visible? (fn [visible-table-ids table-id field-id]
+ (and (contains? visible-table-ids table-id)
(if-let [allowed-field-ids (get sandbox-restricted-ids table-id)]
- (contains? allowed-field-ids (u/id field))
+ (contains? allowed-field-ids field-id)
true)))
- referenced-field-readable?
- (fn [field-id]
- (when-let [field (get field-id->field field-id)]
- (field-readable? (:table_id field) field)))
- column-readable? (fn [{:keys [fk-field-id table-id] :as column}]
+ caller-joined? (fn [column]
+ (or (= :source/implicitly-joinable (:lib/source column))
+ (and explicit-joins-caller-performed?
+ (= :source/joins (:lib/source column)))))
+ referenced-field-visible?
+ (fn [visible-table-ids field-id]
+ (when-let [table-id (get referenced-field-table field-id)]
+ (field-visible? visible-table-ids table-id field-id)))
+ column-visible? (fn [{:keys [fk-field-id table-id] :as column}]
(and (or (not (pos-int? table-id))
- (field-readable? table-id column))
+ (field-visible? (if (caller-joined? column)
+ queryable-table-ids
+ accessible-table-ids)
+ table-id
+ (u/id column)))
(or (nil? fk-field-id)
- (referenced-field-readable? fk-field-id))))]
- (->> columns
- (filter column-readable?)
- (mapv (fn [{:keys [fk-target-field-id] :as column}]
- (cond-> column
- (and fk-target-field-id
- (not (referenced-field-readable? fk-target-field-id)))
- (dissoc :fk-target-field-id)))))))
+ (referenced-field-visible? accessible-table-ids fk-field-id))))]
+ (->> columns
+ (filter column-visible?)
+ (mapv (fn [{:keys [fk-target-field-id] :as column}]
+ (cond-> column
+ (and fk-target-field-id
+ (not (referenced-field-visible? queryable-table-ids fk-target-field-id)))
+ (dissoc :fk-target-field-id))))))))
(defn- strip-lib-uuids
"Recursively drop volatile `\"lib/uuid\"` keys from a portable clause so the LLM copies a clean,
@@ -250,13 +256,14 @@
;; collection-based and says nothing about the join target's Table/sandbox permissions,
;; so filter here too or we would leak columns the user cannot read. A wholly
;; unreadable target table yields no dims, which drops the join entry (fail closed).
- def-cols (permission-filter-columns (lib/filterable-columns defq))
+ def-cols (permission-filter-columns (lib/filterable-columns defq)
+ {:explicit-joins-caller-performed? true})
;; Both `explicit-joins` and the export are keyed off the aggregation stage: `lib/joins`
;; reads stage -1 and we read the exported LAST stage's joins, so their aliases line up
;; for multi-stage definitions too (a stage whose join fails to export drops, closed).
portable-by-alias (into {}
(map (juxt #(get % "alias") strip-lib-uuids))
- (-> (repr.resolve/try-export-query metadata-provider defq)
+ (-> (repr.resolve/try-export-query metadata-provider defq shared.content-store/default-store)
(get "stages") last (get "joins")))]
(not-empty
(into []
@@ -323,7 +330,7 @@
;; reveal metadata for this physical Table.
source-table-id (or (:table-id card) (:table_id card))
source-table (when (and source-table-id
- (mi/can-read? :model/Table source-table-id))
+ (mi/can-query? :model/Table source-table-id))
(lib.metadata/table metadata-provider source-table-id))
base-table-portable-fk (when (and database-name source-table)
[database-name (:schema source-table) (:name source-table)])
@@ -463,6 +470,7 @@
(lib/query mp (lib.metadata/table mp id)))
cols (when with-fields?
(->> (lib/visible-columns table-query -1 {:include-implicitly-joinable? false})
+ permission-filter-columns
field-values-fn
(map #(metabot.tools.u/add-table-reference table-query %))))
related (when with-related-tables?
@@ -504,9 +512,10 @@
expand [[max-related-tables]] of them (metabase#76493). Instead we read the source table's own FK columns and do a
single bulk lookup of just the target fields (not their sibling columns) to map each FK to its table."
[query]
- (let [source-cols (lib/visible-columns query -1 {:include-implicitly-joinable? false})
- existing-table-ids (into #{} (keep :table-id) source-cols)
- fk-cols (filter (every-pred :fk-target-field-id (comp number? :id)) source-cols)
+ (let [all-cols (lib/visible-columns query -1 {:include-implicitly-joinable? false})
+ existing-table-ids (into #{} (keep :table-id) all-cols)
+ fk-cols (filter (every-pred :fk-target-field-id (comp number? :id))
+ (permission-filter-columns all-cols))
id->target-field (m/index-by :id (lib.metadata/bulk-metadata
query :metadata/column (into #{} (map :fk-target-field-id) fk-cols)))]
(->> fk-cols
diff --git a/src/metabase/metabot/tools/field_stats.clj b/src/metabase/metabot/tools/field_stats.clj
index 4b610167e72..8e3f0e9ea01 100644
--- a/src/metabase/metabot/tools/field_stats.clj
+++ b/src/metabase/metabot/tools/field_stats.clj
@@ -1,7 +1,9 @@
(ns metabase.metabot.tools.field-stats
(:require
[clojure.set :as set]
+ [metabase.api.common :as api]
[metabase.lib.core :as lib]
+ [metabase.metabot.metadata-perms :as metabot.perms]
[metabase.metabot.tools.util :as metabot.tools.u]
[metabase.parameters.field-values :as params.field-values]
[metabase.request.core :as request]
@@ -43,6 +45,19 @@
(select-keys (metabot.tools.u/->result-column query col)
[:portable_fk :table_reference]))})
+(defn- check-column-table-perms!
+ [col]
+ (let [table-id (:table-id col)
+ field-id (:id col)]
+ (when (int? table-id)
+ (api/check-403
+ (contains? (if (= :source/implicitly-joinable (:lib/source col))
+ (metabot.perms/queryable-table-ids #{table-id})
+ (metabot.perms/data-accessible-table-ids #{table-id}))
+ table-id))
+ (when-let [allowed (get (metabot.perms/sandbox-restricted-fields #{table-id}) table-id)]
+ (api/check-403 (contains? allowed field-id))))))
+
(defn- table-field-stats
[table-id field-id limit]
(try
@@ -51,6 +66,7 @@
{:agent-error? true :status-code 404})))
visible-cols (lib/visible-columns query)
col (metabot.tools.u/find-column-by-field-id field-id visible-cols)]
+ (check-column-table-perms! col)
(field-metadata-output query col field-id limit))
(catch Exception ex
(metabot.tools.u/handle-agent-error ex))))
@@ -63,6 +79,7 @@
{:agent-error? true :status-code 404})))
visible-cols (lib/visible-columns query)
col (metabot.tools.u/find-column-by-field-id field-id visible-cols)]
+ (check-column-table-perms! col)
(field-metadata-output query col field-id limit))
(catch Exception ex
(metabot.tools.u/handle-agent-error ex))))
@@ -75,6 +92,7 @@
{:agent-error? true :status-code 404})))
filterable-cols (lib/filterable-columns query)
col (metabot.tools.u/find-column-by-field-id field-id filterable-cols)]
+ (check-column-table-perms! col)
(field-metadata-output query col field-id limit))
(catch Exception ex
(metabot.tools.u/handle-agent-error ex))))
diff --git a/src/metabase/metabot/tools/util.clj b/src/metabase/metabot/tools/util.clj
index 39a2fa0237b..7b9331baecd 100644
--- a/src/metabase/metabot/tools/util.clj
+++ b/src/metabase/metabot/tools/util.clj
@@ -218,8 +218,8 @@
;; Mirror collections.curation/curated? for card scope: verified, official-collection, or
;; library-published (under a Library root). Each disjunct is gated on its feature.
curated-conds (cond-> []
- verified? (conj [:= :mr.status [:inline "verified"]])
- official? (conj [:= :collection.authority_level [:inline "official"]])
+ verified? (conj [:= :mr.status "verified"])
+ official? (conj [:= :collection.authority_level "official"])
(seq library-coll-ids) (conj [:in :report_card.collection_id (vec library-coll-ids)]))
;; Columns are qualified with report_card because the official-collections branch joins
;; `collection`, which shares column names (type, archived, id) — unqualified refs would be ambiguous.
@@ -228,20 +228,20 @@
collection-ids (conj (collection/descendant-ids collection) metabot-collection-id)]
[:in :report_card.collection_id collection-ids])
[:and true])
- base-query {:select [:report_card.*]
- :from [[:report_card]]
- :where [:and
- [:!= :report_card.database_id audit-app/audit-db-id]
- collection-filter
- [:in :report_card.type [:inline ["metric" "model"]]]
- [:= :report_card.archived false]
- (when api/*current-user-id*
- (collection/visible-collection-filter-clause :report_card.collection_id))]}]
+ base-query ^:allow-subquery {:select [:report_card.*]
+ :from [[:report_card]]
+ :where [:and
+ [:!= :report_card.database_id audit-app/audit-db-id]
+ collection-filter
+ [:in :report_card.type ["metric" "model"]]
+ [:= :report_card.archived false]
+ (when api/*current-user-id*
+ (collection/visible-collection-filter-clause :report_card.collection_id))]}]
(cond-> base-query
verified?
(update :left-join (fnil into []) [[:moderation_review :mr] [:and
[:= :mr.moderated_item_id :report_card.id]
- [:= :mr.moderated_item_type [:inline "card"]]
+ [:= :mr.moderated_item_type "card"]
[:= :mr.most_recent true]]])
official?
diff --git a/src/metabase/metrics/api.clj b/src/metabase/metrics/api.clj
index 7c193811ef2..f4a59487229 100644
--- a/src/metabase/metrics/api.clj
+++ b/src/metabase/metrics/api.clj
@@ -45,7 +45,7 @@
[:map
[:dimensions [:sequential ::metrics.dimension/dimension]]
[:dimension_mappings [:sequential ::metrics.dimension/dimension-mapping]]
- [:dataset_query {:optional true} ms/Map]
+ [:dataset_query {:optional true} [:maybe ms/Map]]
[:database_id {:optional true} [:maybe ms/PositiveInt]]
[:result_column_name {:optional true} [:maybe :string]]]])
diff --git a/src/metabase/model_persistence/api.clj b/src/metabase/model_persistence/api.clj
index 03518d38271..4017057874c 100644
--- a/src/metabase/model_persistence/api.clj
+++ b/src/metabase/model_persistence/api.clj
@@ -99,6 +99,7 @@
[{:keys [persisted-info-id]} :- [:map
[:persisted-info-id ms/PositiveInt]]]
(api/let-404 [persisted-info (first (fetch-persisted-info {:persisted-info-id persisted-info-id} nil nil))]
+ (api/read-check :model/Card (:card_id persisted-info))
(api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))
persisted-info))
@@ -111,6 +112,7 @@
[{:keys [card-id]} :- [:map
[:card-id ms/PositiveInt]]]
(api/let-404 [persisted-info (first (fetch-persisted-info {:card-id card-id} nil nil))]
+ (api/read-check :model/Card card-id)
(api/read-check (t2/select-one :model/Database :id (:database_id persisted-info)))
persisted-info))
@@ -204,6 +206,7 @@
[:card-id ms/PositiveInt]]]
(premium-features/assert-has-feature :cache-granular-controls (tru "Granular cache controls"))
(api/let-404 [{:keys [database_id] :as card} (t2/select-one :model/Card :id card-id)]
+ (api/write-check card)
(let [database (t2/select-one :model/Database :id database_id)]
(api/write-check database)
(when-not (driver.u/supports? (:engine database) :persist-models database)
@@ -234,6 +237,7 @@
(throw (ex-info (trs "Cannot refresh a non-model question") {:status-code 400})))
(when (:archived card)
(throw (ex-info (trs "Cannot refresh an archived model") {:status-code 400})))
+ (api/write-check card)
(api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))
(task.persist-refresh/schedule-refresh-for-individual! persisted-info)
api/generic-204-no-content))
@@ -248,7 +252,8 @@
[{:keys [card-id]} :- [:map
[:card-id ms/PositiveInt]]]
(premium-features/assert-has-feature :cache-granular-controls (tru "Granular cache controls"))
- (api/let-404 [_card (t2/select-one :model/Card :id card-id)]
+ (api/let-404 [card (t2/select-one :model/Card :id card-id)]
+ (api/write-check card)
(when-let [persisted-info (t2/select-one :model/PersistedInfo :card_id card-id)]
(api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))
(persisted-info/mark-for-pruning! {:id (:id persisted-info)} "off"))
diff --git a/src/metabase/model_persistence/models/persisted_info.clj b/src/metabase/model_persistence/models/persisted_info.clj
index 21d4d8746df..66000d7443b 100644
--- a/src/metabase/model_persistence/models/persisted_info.clj
+++ b/src/metabase/model_persistence/models/persisted_info.clj
@@ -164,9 +164,10 @@
{:where [:and
[:= :database_id database-id]
[:= :type "model"]
- [:not [:exists {:select [1]
- :from [:persisted_info]
- :where [:= :persisted_info.card_id :report_card.id]}]]]})]
+ [:not [:exists ^:allow-subquery
+ {:select [1]
+ :from [:persisted_info]
+ :where [:= :persisted_info.card_id :report_card.id]}]]]})]
(t2/insert! :model/PersistedInfo (map #(create-row nil %) cards))))
(defn turn-on-model!
diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.clj
index a841da1a5b0..fc8bdcb2a0f 100644
--- a/src/metabase/models/serialization.clj
+++ b/src/metabase/models/serialization.clj
@@ -1010,13 +1010,13 @@
[id]
(reverse
(t2/select :model/Field
- {:with-recursive [[[:parents {:columns [:id :name :parent_id :table_id]}]
- {:union-all [{:from [[:metabase_field :mf]]
- :select [:mf.id :mf.name :mf.parent_id :mf.table_id]
- :where [:= :id id]}
- {:from [[:metabase_field :pf]]
- :select [:pf.id :pf.name :pf.parent_id :pf.table_id]
- :join [[:parents :p] [:= :p.parent_id :pf.id]]}]}]]
+ {:with-recursive [[[:parents ^:allow-subquery {:columns [:id :name :parent_id :table_id]}]
+ ^:allow-subquery {:union-all [^:allow-subquery {:from [[:metabase_field :mf]]
+ :select [:mf.id :mf.name :mf.parent_id :mf.table_id]
+ :where [:= :id id]}
+ ^:allow-subquery {:from [[:metabase_field :pf]]
+ :select [:pf.id :pf.name :pf.parent_id :pf.table_id]
+ :join [[:parents :p] [:= :p.parent_id :pf.id]]}]}]]
:from [:parents]
:select [:name :table_id]})))
@@ -1026,12 +1026,12 @@
`(recursively-find-field-q 1 [\"inner\" \"outer\"])`"
[table-id [field & rest]]
(when field
- {:from [:metabase_field]
- :select [:id]
- :where [:and
- [:= :table_id table-id]
- [:= :name field]
- [:= :parent_id (recursively-find-field-q table-id rest)]]}))
+ ^:allow-subquery {:from [:metabase_field]
+ :select [:id]
+ :where [:and
+ [:= :table_id table-id]
+ [:= :name field]
+ [:= :parent_id (recursively-find-field-q table-id rest)]]}))
;; NOTE: field lookups are intentionally NOT routed through the cached resolver, unlike the
;; database and table exporters above. Fields are unbounded in number (millions on large
diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.clj
index ff29e223864..ca728405281 100644
--- a/src/metabase/models/serialization/resolve/mp.clj
+++ b/src/metabase/models/serialization/resolve/mp.clj
@@ -332,7 +332,7 @@
(when (resolve/entity-id? entity-id)
(serdes/lookup-by-id 'Segment entity-id)))
(card-by-id [_ card-id]
- (when card-id
+ (when (int? card-id)
;; `api/read-check` for Cards needs only the parent collection. Avoid loading and
;; transforming the entire dataset_query just to export one stable identifier.
;; `:card_schema` must ride along: selecting `:database_id` makes the after-select
diff --git a/src/metabase/notification/api/admin.clj b/src/metabase/notification/api/admin.clj
index 7892f508521..a91908b70ad 100644
--- a/src/metabase/notification/api/admin.clj
+++ b/src/metabase/notification/api/admin.clj
@@ -185,9 +185,12 @@
e.g. created before that column existed). Uses
`ROW_NUMBER() OVER (PARTITION BY notification_id ORDER BY started_at DESC)`."
[]
+ ^:allow-subquery
{:select [:id :notification_id :status :started_at :ended_at]
- :from [[{:select [:id :notification_id :status :started_at :ended_at
+ :from [[^:allow-subquery
+ {:select [:id :notification_id :status :started_at :ended_at
[[:over [[:row_number]
+ ^:allow-subquery
{:partition-by [:notification_id]
:order-by [[:started_at :desc]]}]]
:rn]]
@@ -213,6 +216,7 @@
- `:has_failure` — true if any channel-send in the tick failed"
[]
(let [lookback (lookback-cutoff)]
+ ^:allow-subquery
{:select [:lr.notification_id
[:lr.run_id :id]
[:lr.tick_started_at :started_at]
@@ -220,19 +224,22 @@
;; `metabase.search.in-place.legacy/bookmark-col`. `has-failure?` runs it through
;; `bit->boolean` to absorb the MySQL/MariaDB bit-vs-boolean JDBC quirk.
[[:case
- [:exists {:select [[1]]
- :from [[:task_history :tf]]
- :where [:and
- [:= :tf.run_id :lr.run_id]
- [:= :tf.task task-channel-send]
- [:= :tf.status "failed"]]}]
+ [:exists ^:allow-subquery
+ {:select [[1]]
+ :from [[:task_history :tf]]
+ :where [:and
+ [:= :tf.run_id :lr.run_id]
+ [:= :tf.task task-channel-send]
+ [:= :tf.status "failed"]]}]
true
:else false]
:has_failure]]
- :from [[{:select [:tr2.notification_id
+ :from [[^:allow-subquery
+ {:select [:tr2.notification_id
[:tr2.id :run_id]
[:tr2.started_at :tick_started_at]
[[:over [[:row_number]
+ ^:allow-subquery
{:partition-by [:tr2.notification_id]
:order-by [[:tr2.started_at :desc]]}]]
:rn]]
@@ -243,11 +250,12 @@
[:in :tr2.status terminal-statuses]
[:> :tr2.started_at lookback]
;; only keep runs that actually had channel-send rows
- [:exists {:select [[1]]
- :from [[:task_history :tx]]
- :where [:and
- [:= :tx.run_id :tr2.id]
- [:= :tx.task task-channel-send]]}]]}
+ [:exists ^:allow-subquery
+ {:select [[1]]
+ :from [[:task_history :tx]]
+ :where [:and
+ [:= :tx.run_id :tr2.id]
+ [:= :tx.task task-channel-send]]}]]}
:lr]]
:where [:= :lr.rn 1]}))
@@ -271,6 +279,7 @@
[channels]
(let [channels (if (sequential? channels) channels [channels])]
[:exists
+ ^:allow-subquery
{:select [[1]]
:from [(t2/table-name :model/NotificationHandler)]
:where [:and
@@ -437,8 +446,10 @@
(when (seq run-ids)
(->> (t2/select :model/TaskHistory
{:select [:run_id :task_details]
- :from [[{:select [:run_id :task_details
+ :from [[^:allow-subquery
+ {:select [:run_id :task_details
[[:over [[:row_number]
+ ^:allow-subquery
{:partition-by [:run_id]
:order-by [[[:case
[:= :task task-notification-send] 0
diff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.clj
index 37544115ddc..86dc7858f4d 100644
--- a/src/metabase/notification/api/notification.clj
+++ b/src/metabase/notification/api/notification.clj
@@ -23,16 +23,30 @@
(set! *warn-on-reflection* true)
+(defn- handler-api-input
+ [handler-schema recipient-schema]
+ [:merge
+ handler-schema
+ [:map
+ [:template {:optional true} [:multi {:dispatch map?}
+ [true ::models.channel/ChannelTemplateUserProvided]
+ [false :nil]]]
+ [:channel {:optional true} [:maybe ::models.channel/Channel]]
+ [:recipients {:optional true} [:sequential recipient-schema]]]])
+
(mr/def ::NotificationApiInput
"Notification schema for API input. Like FullyHydratedNotification but restricts templates
to user-provided types only (no handlebars-resource)."
(models.notification/hydrated-notification-schema
- [:merge
- ::models.notification/NotificationHandler
- [:map
- [:template {:optional true} [:maybe ::models.channel/ChannelTemplateUserProvided]]
- [:channel {:optional true} [:maybe ::models.channel/Channel]]
- [:recipients {:optional true} [:sequential ::models.notification/NotificationRecipient]]]]))
+ (handler-api-input ::models.notification/NotificationHandler
+ ::models.notification/NotificationRecipient)))
+
+(mr/def ::CreateNotificationParams
+ "Notification schema for a create request."
+ (models.notification/hydrated-notification-schema
+ (handler-api-input ::models.notification/CreateNotificationHandlerParams
+ ::models.notification/CreateNotificationRecipientParams)
+ {:with-id? false}))
(defn- check-no-resource-templates!
"Validate that no handler uses handlebars-resource templates. That type is internal only."
@@ -185,7 +199,7 @@
(api.macros/defendpoint :post "/" :- ::models.notification/FullyHydratedNotification
"Create a new notification, return the created notification."
- [_route _query body :- ::NotificationApiInput request]
+ [_route _query body :- ::CreateNotificationParams request]
(check-no-resource-templates! (:handlers body))
(create-notification!
(-> body
diff --git a/src/metabase/notification/api/unsubscribe.clj b/src/metabase/notification/api/unsubscribe.clj
index 6d650410d4e..b2e4f66f926 100644
--- a/src/metabase/notification/api/unsubscribe.clj
+++ b/src/metabase/notification/api/unsubscribe.clj
@@ -27,9 +27,9 @@
(defn- notification-name-by-handler-id
[notification-handler-id]
(let [notification (t2/hydrate (t2/select-one :model/Notification
- :id [:in {:select [:notification_id]
- :from :notification_handler
- :where [:= :id notification-handler-id]}])
+ :id [:in ^:allow-subquery {:select [:notification_id]
+ :from :notification_handler
+ :where [:= :id notification-handler-id]}])
:payload)]
(case (:payload_type notification)
;; use the card name
diff --git a/src/metabase/notification/models.clj b/src/metabase/notification/models.clj
index d88c4cf47f7..21ef3443449 100644
--- a/src/metabase/notification/models.clj
+++ b/src/metabase/notification/models.clj
@@ -7,6 +7,7 @@
[malli.core :as mc]
[medley.core :as m]
[metabase.channel.models.channel :as models.channel]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.models.interface :as mi]
[metabase.models.util.spec-update :as models.u.spec-update]
[metabase.permissions.core :as perms]
@@ -98,23 +99,26 @@
:id
{:default []}))
-(def ^:private notification-entries
+(defn- notification-entries
"Entries every notification map has, whatever its `:payload_type`."
- [[:payload_type (ms/enum-decode-keyword notification-types)]
- [:id {:optional true} ms/PositiveInt]
- [:active {:optional true} [:maybe :boolean]]])
+ [{:keys [with-id?]}]
+ (cond->> [[:payload_type (ms/enum-decode-keyword notification-types)]
+ [:active {:optional true} [:maybe :boolean]]]
+ with-id? (into [[:id {:optional true} ms/PositiveInt]])))
(mr/def ::Notification
- (mu/dispatched-map
- (comp keyword :payload_type)
- notification-entries
- [[:notification/system-event
- [[:payload_id {:optional true} nil?]]]
+ [:merge
+ (into [:map] (notification-entries {:with-id? true}))
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :payload_type)}
+ [:notification/system-event
+ [:map [:payload_id {:optional true} nil?]]]
[:notification/card
;; both optional during creation
- [[:payload_id {:optional true} int?]
+ [:map
+ [:payload_id {:optional true} int?]
[:creator_id {:optional true} int?]]]
- [:notification/testing :any]]))
+ [:notification/testing :any]]])
(defn- validate-notification
[notification]
@@ -189,22 +193,32 @@
:event_name (mi/transform-validator mi/transform-keyword (partial mi/assert-namespaced "event"))
:ui_display_type (mi/transform-validator mi/transform-keyword (partial mi/assert-enum subscription-ui-display-types))})
-(mr/def ::NotificationSubscription
- "Schema for :model/NotificationSubscription."
- (mu/dispatched-map
- (comp keyword :type)
- [[:type (ms/enum-decode-keyword subscription-types)]
- ;; the API sends a negative id for a subscription that is being added
- [:id {:optional true} :int]
- [:notification_id {:optional true} ms/PositiveInt]]
- [[:notification-subscription/system-event
- [[:event_name [:or :keyword :string]]
+(defn- notification-subscription-schema
+ [{:keys [with-id?]}]
+ [:merge
+ (into [:map] (cond->> [[:type (ms/enum-decode-keyword subscription-types)]
+ [:notification_id {:optional true} ms/PositiveInt]]
+ with-id? (into [[:id {:optional true} :int]])))
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
+ [:notification-subscription/system-event
+ [:map
+ [:event_name [:or :keyword :string]]
[:cron_schedule {:optional true} nil?]]]
[:notification-subscription/cron
- [[:cron_schedule :string]
+ [:map
+ [:cron_schedule :string]
[:event_name {:optional true} nil?]
;; enum values can change depending on UI
- [:ui_display_type {:optional true} [:maybe (into [:enum] subscription-ui-display-types)]]]]]))
+ [:ui_display_type {:optional true} [:maybe (into [:enum] subscription-ui-display-types)]]]]]])
+
+(mr/def ::NotificationSubscription
+ "Schema for :model/NotificationSubscription."
+ (notification-subscription-schema {:with-id? true}))
+
+(mr/def ::CreateNotificationSubscriptionParams
+ "Schema for :model/NotificationSubscription on a create request."
+ (notification-subscription-schema {:with-id? false}))
(defn- validate-subscription
"Validate a NotificationSubscription."
@@ -304,15 +318,23 @@
:channel-type channel-type
:template-type template-type}))))))
+(defn- notification-handler-schema
+ [{:keys [with-id?]}]
+ (into [:map]
+ (cond->> [;; optional during insertion
+ [:notification_id {:optional true} ms/PositiveInt]
+ [:channel_type {:decode/json keyword} [:fn #(= "channel" (-> % keyword namespace))]]
+ [:channel_id {:optional true} [:maybe ms/PositiveInt]]
+ [:template_id {:optional true} [:maybe ms/PositiveInt]]
+ [:active {:optional true} [:maybe :boolean]]]
+ with-id? (into [[:id {:optional true} ms/PositiveInt]]))))
+
(mr/def ::NotificationHandler
- [:map
- ;; optional during insertion
- [:id {:optional true} ms/PositiveInt]
- [:notification_id {:optional true} ms/PositiveInt]
- [:channel_type {:decode/json keyword} [:fn #(= "channel" (-> % keyword namespace))]]
- [:channel_id {:optional true} [:maybe ms/PositiveInt]]
- [:template_id {:optional true} [:maybe ms/PositiveInt]]
- [:active {:optional true} [:maybe :boolean]]])
+ (notification-handler-schema {:with-id? true}))
+
+(mr/def ::CreateNotificationHandlerParams
+ "Schema for :model/NotificationHandler on a create request."
+ (notification-handler-schema {:with-id? false}))
(defn- validate-notification-handler
[notification-handler]
@@ -345,33 +367,46 @@
{:type (mi/transform-validator mi/transform-keyword (partial mi/assert-enum notification-recipient-types))
:details mi/transform-json})
-(mr/def ::NotificationRecipient
- "Schema for :model/NotificationRecipient."
- (mu/dispatched-map
- (comp keyword :type)
- [[:type (ms/enum-decode-keyword notification-recipient-types)]
- [:id {:optional true} ms/PositiveInt]
- [:notification_handler_id {:optional true} ms/PositiveInt]]
- [[:notification-recipient/user
- [[:user_id ms/PositiveInt]
+(defn- notification-recipient-schema
+ [{:keys [with-id?]}]
+ [:merge
+ (into [:map] (cond->> [[:type (ms/enum-decode-keyword notification-recipient-types)]
+ [:notification_handler_id {:optional true} ms/PositiveInt]]
+ with-id? (into [[:id {:optional true} ms/PositiveInt]])))
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
+ [:notification-recipient/user
+ [:map
+ [:user_id ms/PositiveInt]
[:permissions_group_id {:optional true} [:fn nil?]]
[:details {:optional true} [:fn empty?]]]]
[:notification-recipient/group
- [[:permissions_group_id ms/PositiveInt]
+ [:map
+ [:permissions_group_id ms/PositiveInt]
[:user_id {:optional true} [:fn nil?]]
[:details {:optional true} [:fn empty?]]]]
[:notification-recipient/raw-value
- [[:details [:map {:closed true}
+ [:map
+ [:details [:map {:closed true}
[:value :any]
[:channel_id {:optional true} [:maybe :string]]]]
[:user_id {:optional true} [:fn nil?]]
[:permissions_group_id {:optional true} [:fn nil?]]]]
[:notification-recipient/template
- [[:details [:map {:closed true}
+ [:map
+ [:details [:map {:closed true}
[:pattern :string]
[:is_optional {:optional true} :boolean]]]
[:user_id {:optional true} [:fn nil?]]
- [:permissions_group_id {:optional true} [:fn nil?]]]]]))
+ [:permissions_group_id {:optional true} [:fn nil?]]]]]])
+
+(mr/def ::NotificationRecipient
+ "Schema for :model/NotificationRecipient."
+ (notification-recipient-schema {:with-id? true}))
+
+(mr/def ::CreateNotificationRecipientParams
+ "Schema for :model/NotificationRecipient on a create request."
+ (notification-recipient-schema {:with-id? false}))
(defn- check-valid-recipient
[recipient]
@@ -410,17 +445,25 @@
(t2/deftransforms :model/NotificationCard
{:send_condition (mi/transform-validator mi/transform-keyword (partial mi/assert-enum card-subscription-send-conditions))})
+(defn- notification-card-schema
+ [{:keys [with-id?]}]
+ (into [:map]
+ (cond->> [[:card_id ms/PositiveInt]
+ [:notification_id {:optional true} [:maybe ms/PositiveInt]]
+ ;; the hydrated Card, echoed back by clients on update; nothing here reads it
+ [:card {:optional true} [:maybe ms/Map]]
+ [:send_condition {:optional true} (ms/enum-decode-keyword card-subscription-send-conditions)]
+ [:send_once {:optional true} :boolean]]
+ ;; nil on an unsaved notification, e.g. the one POST /api/pulse/test builds to send a test alert
+ with-id? (into [[:id {:optional true} [:maybe ms/PositiveInt]]]))))
+
(mr/def ::NotificationCard
"Schema for :model/NotificationCard."
- [:map
- [:card_id ms/PositiveInt]
- ;; nil on an unsaved notification, e.g. the one POST /api/pulse/test builds to send a test alert
- [:id {:optional true} [:maybe ms/PositiveInt]]
- [:notification_id {:optional true} [:maybe ms/PositiveInt]]
- ;; the hydrated Card, echoed back by clients on update; nothing here reads it
- [:card {:optional true} [:maybe ms/Map]]
- [:send_condition {:optional true} (ms/enum-decode-keyword card-subscription-send-conditions)]
- [:send_once {:optional true} :boolean]])
+ (notification-card-schema {:with-id? true}))
+
+(mr/def ::CreateNotificationCardParams
+ "Schema for :model/NotificationCard on a create request."
+ (notification-card-schema {:with-id? false}))
(t2/define-before-insert :model/NotificationCard
[instance]
@@ -507,7 +550,8 @@
(or
(not (premium-features/has-feature? :advanced-permissions))
(perms/current-user-has-application-permissions? :subscription))
- (current-user-can-read-payload? instance)))))
+ (current-user-can-read-payload? instance)
+ (current-user-can-read-payload? (merge instance changes))))))
;; ------------------------------------------------------------------------------------------------;;
;; Public APIs ;;
@@ -517,19 +561,26 @@
"Schema for a notification hydrated with its creator, subscriptions and handlers, where each handler matches
`handler-schema`. Callers supply the handler schema because API input accepts a narrower set of templates than what
we hand back out."
- [handler-schema]
- (let [entries (into notification-entries
- [;; the hydrated User, echoed back by clients on update; `:creator_id` is what gets read
- [:creator {:optional true} [:maybe ms/Map]]
- [:creator_id {:optional true} [:maybe int?]]
- [:payload_id {:optional true} [:maybe int?]]
- [:subscriptions {:optional true} [:sequential [:ref ::NotificationSubscription]]]
- [:handlers {:optional true} [:sequential handler-schema]]])]
- (mu/dispatched-map
- (comp keyword :payload_type)
- entries
- [[:notification/card [[:payload [:ref ::NotificationCard]]]]
- [::mc/default []]])))
+ ([handler-schema]
+ (hydrated-notification-schema handler-schema {:with-id? true}))
+ ([handler-schema {:keys [with-id?] :as opts}]
+ (let [entries (into (notification-entries opts)
+ [;; the hydrated User, echoed back by clients on update; `:creator_id` is what gets read
+ [:creator {:optional true} [:maybe ms/Map]]
+ [:creator_id {:optional true} [:maybe int?]]
+ [:payload_id {:optional true} [:maybe int?]]
+ [:subscriptions {:optional true} [:sequential [:ref (if with-id?
+ ::NotificationSubscription
+ ::CreateNotificationSubscriptionParams)]]]
+ [:handlers {:optional true} [:sequential handler-schema]]])]
+ [:merge
+ (into [:map] entries)
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :payload_type)}
+ [:notification/card [:map [:payload [:ref (if with-id?
+ ::NotificationCard
+ ::CreateNotificationCardParams)]]]]
+ [::mc/default [:map]]]])))
(mr/def ::FullyHydratedNotification
"Fully hydrated notification."
@@ -556,9 +607,9 @@
(hydrate-notification (t2/select :model/Notification
:active true
:payload_type :notification/card
- :payload_id [:in {:select [:id]
- :from [:notification_card]
- :where [:= :card_id card-id]}])))
+ :payload_id [:in ^:allow-subquery {:select [:id]
+ :from [:notification_card]
+ :where [:= :card_id card-id]}])))
(defn notifications-for-event
"Find all active notifications for a given event."
@@ -642,6 +693,6 @@
[notification-id user-id]
(t2/delete! :model/NotificationRecipient
:user_id user-id
- :notification_handler_id [:in {:select [:id]
- :from [:notification_handler]
- :where [:= :notification_id notification-id]}]))
+ :notification_handler_id [:in ^:allow-subquery {:select [:id]
+ :from [:notification_handler]
+ :where [:= :notification_id notification-id]}]))
diff --git a/src/metabase/osi/ai_context/api.clj b/src/metabase/osi/ai_context/api.clj
index d33b779f2c4..7b2a46de099 100644
--- a/src/metabase/osi/ai_context/api.clj
+++ b/src/metabase/osi/ai_context/api.clj
@@ -31,7 +31,7 @@
"OSI ai_context blob. All fields optional; extra keys tolerated for forward-compat with the OSI spec.
String and list lengths are capped so a single curated entity can't bloat the index, its embeddings, or
the agent prompt."
- [:map
+ [:map {:closed false}
[:instructions {:optional true} [:maybe [:string {:max entity-retrieval/max-instructions-len}]]]
[:synonyms {:optional true} [:sequential {:max max-list-len} [:string {:max max-item-len}]]]
[:examples {:optional true} [:sequential {:max max-list-len} [:string {:max max-item-len}]]]])
diff --git a/src/metabase/parameters/chain_filter.clj b/src/metabase/parameters/chain_filter.clj
index 8eb72a623e6..a888a116b95 100644
--- a/src/metabase/parameters/chain_filter.clj
+++ b/src/metabase/parameters/chain_filter.clj
@@ -559,7 +559,8 @@
(defn- implicit-pk->name-mapping-query
[field-id mapping-type]
- {:select [[:dest.id :id] [[:inline mapping-type] :mapping_type]]
+ ^:allow-subquery
+ {:select [[:dest.id :id] [^:allow-raw-sql [:inline mapping-type] :mapping_type]]
:from [[:metabase_field :source]]
:left-join [[:metabase_table :table] [:= :source.table_id :table.id]
[:metabase_field :dest] [:= :dest.table_id :table.id]]
@@ -577,8 +578,10 @@
(defn- remapped-field-id-query [field-id]
{:select [[:mapping.id :id] [:mapping.mapping_type :mapping_type]]
- :from [[{::union (into [;; Explicit FK Field->Field remapping
- {:select [[:dimension.human_readable_field_id :id] [[:inline "fk->field"] :mapping_type]]
+ :from [[^:allow-subquery
+ {::union (into [;; Explicit FK Field->Field remapping
+ ^:allow-subquery
+ {:select [[:dimension.human_readable_field_id :id] [^:allow-raw-sql [:inline "fk->field"] :mapping_type]]
:from [[:dimension :dimension]]
:where [:and
[:= :dimension.field_id field-id]
@@ -587,6 +590,7 @@
(when *allow-implicit-uuid-field-remapping*
[;; Implicit FK Field -> PK Field -> [Name] Field remapping
(implicit-pk->name-mapping-query
+ ^:allow-subquery
{:select [:fk_target_field_id]
:from [:metabase_field]
:where [:and
diff --git a/src/metabase/permissions/models/collection/graph.clj b/src/metabase/permissions/models/collection/graph.clj
index 32e4bfa9c3e..10a2a5653a8 100644
--- a/src/metabase/permissions/models/collection/graph.clj
+++ b/src/metabase/permissions/models/collection/graph.clj
@@ -84,58 +84,63 @@
accum
(t2/reducible-query
{:with [[:eligible_collections
+ ^:allow-subquery
{:select [:id]
:from [:collection]
:where [:and
- [:or [:= :type nil] [:not= :type [:inline "trash"]]]
+ [:or [:= :type nil] [:not= :type "trash"]]
(perms/namespace-clause
:namespace (u/qualified-name collection-namespace))
[:not :archived]
[:= :personal_owner_id nil]
(when (seq ids-without-root)
[:in :id ids-without-root])
- [:not [:exists {:select [1]
- :from [[:collection :pc]]
- :where [:and
- [:not= :pc.personal_owner_id nil]
- [:like :collection.location
- [:concat "/" :pc.id "/%"]]]}]]]}]
+ [:not [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:collection :pc]]
+ :where [:and
+ [:not= :pc.personal_owner_id nil]
+ [:like :collection.location
+ [:concat "/" :pc.id "/%"]]]}]]]}]
[:relevant_permissions
+ ^:allow-subquery
{:select [:group_id :collection_id :perm_value]
:from [:permissions]
:where (into [:and
- [:= :perm_type [:inline "perms/collection-access"]]
+ [:= :perm_type "perms/collection-access"]
[:not= :collection_id nil]]
(when (seq group-ids)
[[:in :group_id group-ids]]))}]]
:union-all
[;; Query 1: Root collection permissions, exclude this query if collection-ids are supplied
;; and :root is not present in that collection
+ ^:allow-subquery
{:select [[:pg.id :group_id]
[nil :collection_id]
- [[:max [:case [:= :p.object [:inline root-object]]
+ [[:max [:case [:= :p.object root-object]
[:inline 1]
:else [:inline 0]]] :writable]
- [[:max [:case [:= :p.object [:inline (str root-object "read/")]]
+ [[:max [:case [:= :p.object (str root-object "read/")]
[:inline 1]
:else [:inline 0]]] :readable]]
:from [[:permissions_group :pg]]
:join [[:permissions :p] [:and
[:= :p.group_id :pg.id]
- [:or [:= :p.object [:inline root-object]]
- [:= :p.object [:inline (str root-object "read/")]]]]]
+ [:or [:= :p.object root-object]
+ [:= :p.object (str root-object "read/")]]]]
:where (into [:and [:inline include-root?]]
(when (seq group-ids)
[[:in :pg.id group-ids]]))
:group-by [:pg.id]}
;; Query 2: Regular collection permissions
+ ^:allow-subquery
{:select [[:pg.id :group_id]
[:c.id :collection_id]
- [[:max [:case [:= :p.perm_value [:inline "read-and-write"]]
+ [[:max [:case [:= :p.perm_value "read-and-write"]
[:inline 1]
:else [:inline 0]]] :writable]
- [[:max [:case [:or [:= :p.perm_value [:inline "read-and-write"]]
- [:= :p.perm_value [:inline "read"]]]
+ [[:max [:case [:or [:= :p.perm_value "read-and-write"]
+ [:= :p.perm_value "read"]]
[:inline 1]
:else [:inline 0]]] :readable]]
:from [[:permissions_group :pg]]
@@ -145,6 +150,7 @@
:group-by [:pg.id :c.id]}
;; Query 3: The Administrators group has write access to all collections
;; but does not have any explicit permissions.
+ ^:allow-subquery
{:select [[(u/the-id (perms-group/admin)) :group_id]
[:c.id :collection_id]
[[:inline 1] :writable]
@@ -270,12 +276,13 @@
[:and
[:in :id id-set]
[:or [:not= :personal_owner_id nil]
- [:exists {:select [1]
- :from [[:collection :pc]]
- :where [:and
- [:not= :pc.personal_owner_id nil]
- [:like :collection.location
- [:concat "/" :pc.id "/%"]]]}]]]))))
+ [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:collection :pc]]
+ :where [:and
+ [:not= :pc.personal_owner_id nil]
+ [:like :collection.location
+ [:concat "/" :pc.id "/%"]]]}]]]))))
(defn- remove-personal-collections-from-graph
"Remove any personal collection IDs from the graph. Personal collections cannot be edited via the graph API."
diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.clj
index 81440bc32ee..155e0619be0 100644
--- a/src/metabase/permissions/models/data_permissions.clj
+++ b/src/metabase/permissions/models/data_permissions.clj
@@ -206,17 +206,17 @@
for deactivated tables. All caches must select from this same row set so they can never answer the same permission
question differently — change the row set here, not in one of the queries. `db-ids` of nil means every database."
[user-id db-ids]
- {:from [[(t2/table-name :model/PermissionsGroupMembership) :pgm]]
- :join [[(t2/table-name :model/PermissionsGroup) :pg] [:= :pg.id :pgm.group_id]
- [(t2/table-name :model/DataPermissions) :p] [:= :p.group_id :pg.id]]
- :left-join [[(t2/table-name :model/Table) :mt] [:= :mt.id :p.table_id]]
- :where [:and
- [:= :pgm.user_id user-id]
- (when (seq db-ids)
- [:in :p.db_id db-ids])
- [:or
- [:= :p.table_id nil]
- [:= :mt.active true]]]})
+ ^:allow-subquery {:from [[(t2/table-name :model/PermissionsGroupMembership) :pgm]]
+ :join [[(t2/table-name :model/PermissionsGroup) :pg] [:= :pg.id :pgm.group_id]
+ [(t2/table-name :model/DataPermissions) :p] [:= :p.group_id :pg.id]]
+ :left-join [[(t2/table-name :model/Table) :mt] [:= :mt.id :p.table_id]]
+ :where [:and
+ [:= :pgm.user_id user-id]
+ (when (seq db-ids)
+ [:in :p.db_id db-ids])
+ [:or
+ [:= :p.table_id nil]
+ [:= :mt.active true]]]})
(def ^:private value-rank-case
"A HoneySQL CASE expression mapping a data_permissions row's (perm_type, perm_value) to the value's rank in its
@@ -1451,11 +1451,11 @@
:where [:and
[:in :group_id group-ids]
[:in :perm_type ["perms/create-queries" "perms/download-results"]]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Database) :audit_db]]
- :where [:and
- [:= :audit_db.is_audit true]
- [:= :audit_db.id :data_permissions.db_id]]}]]]}))
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/Database) :audit_db]]
+ :where [:and
+ [:= :audit_db.is_audit true]
+ [:= :audit_db.id :data_permissions.db_id]]}]]]}))
;; Group by (group_id, perm_type) → set of values
perms-by-grp (when all-perms
(reduce (fn [acc {:keys [group_id perm_type perm_value]}]
diff --git a/src/metabase/permissions/models/data_permissions/sql.clj b/src/metabase/permissions/models/data_permissions/sql.clj
index 40c5a93b9d8..6cb3f7e865a 100644
--- a/src/metabase/permissions/models/data_permissions/sql.clj
+++ b/src/metabase/permissions/models/data_permissions/sql.clj
@@ -44,9 +44,9 @@
;; blocked has a higher 'prioirty' than legacy-no-self-service when determining what permission level the user has
(let [minimum-perm-value [:min
[:case
- [:= column [:inline "unrestricted"]] [:inline 0]
- [:= column [:inline "blocked"]] [:inline 1]
- [:= column [:inline "legacy-no-self-service"]] [:inline 2]]]]
+ [:= column "unrestricted"] [:inline 0]
+ [:= column "blocked"] [:inline 1]
+ [:= column "legacy-no-self-service"] [:inline 2]]]]
;; but when we compare it against the required level it should still be compared by its index value
[:case
[:= minimum-perm-value [:inline 0]] [:inline 0]
@@ -80,9 +80,10 @@
"Returns a simple IN clause to check if dp.group_id is in the user's groups.
This is more efficient than nested EXISTS subqueries."
[user-id :- pos-int?]
- [:in :dp.group_id {:select [:group_id]
- :from [:permissions_group_membership]
- :where [:= :user_id [:inline user-id]]}])
+ [:in :dp.group_id ^:allow-subquery
+ {:select [:group_id]
+ :from [:permissions_group_membership]
+ :where [:= :user_id [:inline user-id]]}])
(mu/defn- has-perms-for-table-as-honey-sql?
"Builds an EXIST (SELECT ...) half-join to filter tables that a user has the required permissions for. It builds the subselect by as a
@@ -92,17 +93,18 @@
perm-type :- :keyword
required-level :- :keyword
& [most-or-least :- [:maybe [:enum :most :least]]]]
- [:exists {:select [1]
- :from [[:data_permissions :dp]]
- :where [:and
- [:= :dp.perm_type (h2x/literal perm-type)]
- [:or
- [:and [:= :mt.db_id :dp.db_id]
- [:= :dp.table_id nil]]
- [:= :mt.id :dp.table_id]]
- (user-in-group-clause user-id)]
- :group-by [:mt.id]
- :having [(perm-condition perm-type required-level (or most-or-least :least))]}])
+ [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:data_permissions :dp]]
+ :where [:and
+ [:= :dp.perm_type (h2x/literal perm-type)]
+ [:or
+ [:and [:= :mt.db_id :dp.db_id]
+ [:= :dp.table_id nil]]
+ [:= :mt.id :dp.table_id]]
+ (user-in-group-clause user-id)]
+ :group-by [:mt.id]
+ :having [(perm-condition perm-type required-level (or most-or-least :least))]}])
(def UserInfo
"The user-id to use in the visibility query and their superuser status."
@@ -129,6 +131,7 @@
{:keys [user-id is-superuser? is-data-analyst?]} :- UserInfo
permission-mapping :- PermissionMapping
& [{:keys [active-only?] :or {active-only? false}}]]
+ ^:allow-subquery
{:select [(case select-column
:id :mt.id
:db_id :mt.db_id)]
@@ -167,9 +170,9 @@
[:case
[:= :dp.perm_type (h2x/literal perm-type)]
[:case
- [:= :dp.perm_value [:inline "unrestricted"]] [:inline 0]
- [:= :dp.perm_value [:inline "blocked"]] [:inline 1]
- [:= :dp.perm_value [:inline "legacy-no-self-service"]] [:inline 2]]]]]
+ [:= :dp.perm_value "unrestricted"] [:inline 0]
+ [:= :dp.perm_value "blocked"] [:inline 1]
+ [:= :dp.perm_value "legacy-no-self-service"] [:inline 2]]]]]
[:case
[:= minimum-perm-value [:inline 0]] [:inline 0]
[:= minimum-perm-value [:inline 1]] [:inline 2]
@@ -221,6 +224,7 @@
user-info perm-types active-only?))
active-clause (when active-only? [:= :mt.active true])
permission-branches (cond-> [;; Table-level permissions (direct grant to table)
+ ^:allow-subquery
{:select [:mt.id :dp.perm_type :dp.perm_value]
:from [[:data_permissions :dp]]
:join [[:metabase_table :mt] [:= :mt.id :dp.table_id]]
@@ -230,6 +234,7 @@
perm-type-filter]
(when active-clause [active-clause]))}
;; Database-level permissions (applies to all tables in db)
+ ^:allow-subquery
{:select [:mt.id :dp.perm_type :dp.perm_value]
:from [[:data_permissions :dp]]
:join [[:metabase_table :mt] [:= :mt.db_id :dp.db_id]]
@@ -240,20 +245,22 @@
(when active-clause [active-clause]))}]
published-grant-rows (conj published-grant-rows))]
{:with [;; First CTE: collect all permission grants that apply to each table
- [:table_permissions {:union-all permission-branches}]
+ [:table_permissions ^:allow-subquery {:union-all permission-branches}]
;; Second CTE: aggregate and filter by permission requirements
[:permitted_tables
+ ^:allow-subquery
{:select [:dp.id]
:from [[:table_permissions :dp]]
:group-by [:dp.id]
:having having-conditions}]]
- :clause [:in column-or-exp {:select [:id] :from [:permitted_tables]}]})))
+ :clause [:in column-or-exp ^:allow-subquery {:select [:id] :from [:permitted_tables]}]})))
(mu/defn select-tables-and-groups-granting-perm
"Selects table.id and the group.id of all permissions groups that give the provided user the provided permission level or a
permission level either more or less restrictive than the supplied level."
[{:keys [user-id is-superuser?]} :- UserInfo
permission-mapping :- PermissionMapping]
+ ^:allow-subquery
{:select [:mt.id :dp.group_id :dp.perm_type :dp.perm_value]
:from [[:metabase_table :mt]]
:join [[:data_permissions :dp] [:or
@@ -287,20 +294,22 @@
perm-type :- :keyword
required-level :- :keyword
& [most-or-least :- [:maybe [:enum :most :least]]]]
- [:exists {:select [1]
- :from [[:data_permissions :dp]]
- :where [:and
- [:= :dp.perm_type (h2x/literal perm-type)]
- [:= :md.id :dp.db_id]
- (user-in-group-clause user-id)]
- :group-by [:md.id]
- :having [(perm-condition perm-type required-level (or most-or-least :least))]}])
+ [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:data_permissions :dp]]
+ :where [:and
+ [:= :dp.perm_type (h2x/literal perm-type)]
+ [:= :md.id :dp.db_id]
+ (user-in-group-clause user-id)]
+ :group-by [:md.id]
+ :having [(perm-condition perm-type required-level (or most-or-least :least))]}])
(mu/defn visible-database-filter-select
"Selects database IDs that are visible to the provided user given a mapping of permission types to the required value.
Similar to visible-table-filter-select but for databases."
[{:keys [user-id is-superuser? is-data-analyst?]} :- UserInfo
permission-mapping :- PermissionMapping]
+ ^:allow-subquery
{:select [:md.id]
:from [[:metabase_database :md]]
;; Superusers see all databases. Data analysts see all databases when checking manage-table-metadata.
diff --git a/src/metabase/permissions/models/permissions_group_membership.clj b/src/metabase/permissions/models/permissions_group_membership.clj
index b123348746d..257d0961b3a 100644
--- a/src/metabase/permissions/models/permissions_group_membership.clj
+++ b/src/metabase/permissions/models/permissions_group_membership.clj
@@ -127,6 +127,7 @@
:boolean]]
(when (seq user-id-group-id->is-group-manager?)
{:insert-into [[:permissions_group_membership [:group_id :user_id :is_group_manager]]
+ ^:allow-subquery
{:select [:g.id :u.id [(into [:case]
(mapcat (fn [[[user-id group-id] is-group-manager?]]
[[[:and
diff --git a/src/metabase/permissions_rest/api.clj b/src/metabase/permissions_rest/api.clj
index da501559dab..f088238f907 100644
--- a/src/metabase/permissions_rest/api.clj
+++ b/src/metabase/permissions_rest/api.clj
@@ -3,8 +3,6 @@
(:require
[clojure.data :as data]
[honey.sql.helpers :as sql.helpers]
- [malli.core :as mc]
- [malli.transform :as mtx]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.events.core :as events]
@@ -16,8 +14,6 @@
[metabase.settings.core :as setting]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
- [metabase.util.malli :as mu]
- [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
@@ -89,64 +85,30 @@
{:keys [skip-graph force]} :- [:map
[:skip-graph {:default false} [:maybe ms/BooleanValue]]
[:force {:default false} [:maybe ms/BooleanValue]]]
- body :- [:map
- ;; keyed by group id, then by database id -- `::permissions-rest.schema/strict-api-permissions-graph`
- ;; below turns both back into the ints the graph is stored under, and checks the per-database
- ;; permissions, so the value stays open here
- [:groups [:map-of :keyword [:maybe ms/Map]]]
- [:revision {:optional true} [:maybe ms/Int]]
- [:force {:optional true} [:maybe :boolean]]
- ;; sandboxes without an `:id` are created, ones with an `:id` are updated -- and only in the keys the
- ;; request actually carries, so `:card_id`/`:attribute_remappings` have to keep their present/absent
- ;; distinction
- [:sandboxes {:optional true}
- [:maybe [:sequential
- [:map
- [:id {:optional true} ms/PositiveInt]
- [:group_id {:optional true} ms/PositiveInt]
- [:table_id {:optional true} ms/PositiveInt]
- [:card_id {:optional true} [:maybe ms/PositiveInt]]
- ;; user attribute name -> the parameter target it is remapped to
- [:attribute_remappings {:optional true} [:maybe ms/Map]]
- [:permission_id {:optional true} [:maybe ms/PositiveInt]]]]]]
- [:impersonations {:optional true}
- [:maybe [:sequential
- [:map
- [:group_id ms/PositiveInt]
- [:db_id ms/PositiveInt]
- [:attribute ms/NonBlankString]]]]]]]
+ new-graph :- ::permissions-rest.schema/graph-update-request]
(api/check-superuser)
- (let [new-graph (mc/decode ::permissions-rest.schema/strict-api-permissions-graph
- body
- (mtx/transformer
- mtx/string-transformer
- (mtx/transformer {:name :perm-graph})))]
- (when-not (mr/validate ::permissions-rest.schema/data-permissions-graph new-graph)
- (let [explained (mu/explain ::permissions-rest.schema/data-permissions-graph new-graph)]
- (throw (ex-info (tru "Cannot parse permissions graph because it is invalid: {0}" (pr-str explained))
- {:status-code 400}))))
- (t2/with-transaction [_conn]
- (let [group-ids (-> new-graph :groups keys)
- old-graph (data-perms.graph/api-graph {:group-ids group-ids})
- [old new] (data/diff (:groups old-graph)
- (:groups new-graph))
- old (or old {})
- new (or new {})]
- (perms/log-permissions-changes old new)
- (when-not force (perms/check-revision-numbers old-graph new-graph))
- (data-perms.graph/update-data-perms-graph! {:groups new})
- (perms/save-perms-revision! :model/PermissionsRevision (:revision old-graph) old new)
- (let [sandbox-updates (:sandboxes new-graph)
- sandboxes (when sandbox-updates
- (upsert-sandboxes! sandbox-updates))
- impersonation-updates (:impersonations new-graph)
- impersonations (when impersonation-updates
- (insert-impersonations! impersonation-updates))
- group-ids (-> new-graph :groups keys)]
- (merge {:revision (perms/latest-permissions-revision-id)}
- (when-not skip-graph {:groups (:groups (data-perms.graph/api-graph {:group-ids group-ids}))})
- (when sandboxes {:sandboxes sandboxes})
- (when impersonations {:impersonations impersonations})))))))
+ (t2/with-transaction [_conn]
+ (let [group-ids (-> new-graph :groups keys)
+ old-graph (data-perms.graph/api-graph {:group-ids group-ids})
+ [old new] (data/diff (:groups old-graph)
+ (:groups new-graph))
+ old (or old {})
+ new (or new {})]
+ (perms/log-permissions-changes old new)
+ (when-not force (perms/check-revision-numbers old-graph new-graph))
+ (data-perms.graph/update-data-perms-graph! {:groups new})
+ (perms/save-perms-revision! :model/PermissionsRevision (:revision old-graph) old new)
+ (let [sandbox-updates (:sandboxes new-graph)
+ sandboxes (when sandbox-updates
+ (upsert-sandboxes! sandbox-updates))
+ impersonation-updates (:impersonations new-graph)
+ impersonations (when impersonation-updates
+ (insert-impersonations! impersonation-updates))
+ group-ids (-> new-graph :groups keys)]
+ (merge {:revision (perms/latest-permissions-revision-id)}
+ (when-not skip-graph {:groups (:groups (data-perms.graph/api-graph {:group-ids group-ids}))})
+ (when sandboxes {:sandboxes sandboxes})
+ (when impersonations {:impersonations impersonations}))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PERMISSIONS GROUP ENDPOINTS |
@@ -207,11 +169,11 @@
(when (and (not api/*is-superuser?*)
(premium-features/enable-advanced-permissions?)
api/*is-group-manager?*)
- [:in :id {:select [:group_id]
- :from [:permissions_group_membership]
- :where [:and
- [:= :user_id api/*current-user-id*]
- [:= :is_group_manager true]]}])
+ [:in :id ^:allow-subquery {:select [:group_id]
+ :from [:permissions_group_membership]
+ :where [:and
+ [:= :user_id api/*current-user-id*]
+ [:= :is_group_manager true]]}])
(when-not (setting/get :use-tenants)
[:not :is_tenant_group])
(when-not (premium-features/enable-advanced-permissions?)
@@ -339,11 +301,11 @@
(and (not api/*is-superuser?*)
api/*is-group-manager?*)
(sql.helpers/where
- [:in :group_id {:select [:group_id]
- :from [:permissions_group_membership]
- :where [:and
- [:= :user_id api/*current-user-id*]
- [:= :is_group_manager true]]}])
+ [:in :group_id ^:allow-subquery {:select [:group_id]
+ :from [:permissions_group_membership]
+ :where [:and
+ [:= :user_id api/*current-user-id*]
+ [:= :is_group_manager true]]}])
(not (premium-features/enable-advanced-permissions?))
(sql.helpers/where [:not= :group_id (u/the-id (perms/data-analyst-group))])))))
diff --git a/src/metabase/permissions_rest/data_permissions/graph.clj b/src/metabase/permissions_rest/data_permissions/graph.clj
index 0f6dd347d5b..06764158aba 100644
--- a/src/metabase/permissions_rest/data_permissions/graph.clj
+++ b/src/metabase/permissions_rest/data_permissions/graph.clj
@@ -233,11 +233,11 @@
(when group-id [:= :group_id group-id])
(when group-ids [:in :group_id group-ids])
(when-not audit? [:not= :db_id audit/audit-db-id])
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Database) :router_db]]
- :where [:and
- [:not= :router_db.router_database_id nil]
- [:= :router_db.id :db_id]]}]]]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/Database) :router_db]]
+ :where [:and
+ [:not= :router_db.router_database_id nil]
+ [:= :router_db.id :db_id]]}]]]
:order-by [:group_id :db_id]})))
(defn- add-perm
diff --git a/src/metabase/permissions_rest/schema.clj b/src/metabase/permissions_rest/schema.clj
index 6c826d2af3b..333afdc2d6a 100644
--- a/src/metabase/permissions_rest/schema.clj
+++ b/src/metabase/permissions_rest/schema.clj
@@ -1,16 +1,23 @@
(ns metabase.permissions-rest.schema
(:require
- [metabase.util.i18n :refer [trs]]
- [metabase.util.malli.registry :as mr]))
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [trs tru]]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
-(defn- kw-int->int-decoder [kw-int]
- (if (int? kw-int)
- kw-int
- (parse-long (name kw-int))))
+(defn- kw-int->int-decoder
+ [kw-int]
+ (cond
+ (int? kw-int) kw-int
+ (or (keyword? kw-int) (string? kw-int)) (parse-long (name kw-int))
+ :else kw-int))
(mr/def ::decodable-keyword-int
"Integer malli schema that knows how to decode itself from the :123 sort of shape used in perm-graphs"
- [:int {:decode/perm-graph kw-int->int-decoder}])
+ [:schema {:decode/api kw-int->int-decoder} ms/PositiveInt])
(mr/def ::id ::decodable-keyword-int)
(mr/def ::group-id ::decodable-keyword-int)
@@ -34,41 +41,55 @@
:segmented
:unrestricted])
+(defn- named-or-granular
+ [granular-schema]
+ [:multi {:dispatch map?}
+ [true granular-schema]
+ [false [:ref ::perms]]])
+
(mr/def ::table-perms
- [:or
- [:ref ::perms]
+ (named-or-granular
[:map
[:read {:optional true} [:enum :all :none]]
- [:query {:optional true} [:enum :all :none :segmented]]]])
+ [:query {:optional true} [:enum :all :none :segmented]]]))
(mr/def ::schema-perms
- [:or
- [:ref ::perms]
- [:map-of [:ref ::id] [:ref ::table-perms]]])
+ (named-or-granular
+ [:map-of
+ [:or [:ref ::id]
+ (mu/refuse #(tru "Invalid DB permissions: permissions for a schema must be keyed by table id."))]
+ [:or [:ref ::table-perms]
+ (mu/refuse #(tru "Invalid DB permissions: unrecognized permissions for a table."))]]))
+
+(defn- kw->name-decoder
+ [schema-name]
+ (cond-> schema-name
+ (keyword? schema-name) name))
(mr/def ::schema-graph
[:map-of
- [:string {:decode/perm-graph name}]
- [:ref ::schema-perms]])
+ [:string {:decode/api kw->name-decoder}]
+ [:or [:ref ::schema-perms]
+ (mu/refuse #(tru "Invalid DB permissions: unrecognized permissions for a schema."))]])
(mr/def ::schemas
- [:or
- [:enum
- :all
- :segmented
- :none
- :block
- :blocked
- :full
- :limited
- :impersonated
- :unrestricted
- :sandboxed
- :legacy-no-self-service
- :query-builder-and-native
- :query-builder
- :no]
- [:ref ::schema-graph]])
+ [:multi {:dispatch map?}
+ [true [:ref ::schema-graph]]
+ [false [:enum
+ :all
+ :segmented
+ :none
+ :block
+ :blocked
+ :full
+ :limited
+ :impersonated
+ :unrestricted
+ :sandboxed
+ :legacy-no-self-service
+ :query-builder-and-native
+ :query-builder
+ :no]]])
(mr/def ::data-perms
[:map
@@ -84,33 +105,102 @@
(fn [{:keys [native schemas]}]
(not (and (= native :write) schemas (not (#{:all :impersonated} schemas)))))]])
+(mr/def ::db-perms
+ "the permissions one group has on one database"
+ [:map {:closed true}
+ [:view-data {:optional true} [:ref ::schemas]]
+ [:create-queries {:optional true} [:ref ::schemas]]
+ [:data {:optional true} [:ref ::strict-data-perms]]
+ [:download {:optional true} [:ref ::strict-data-perms]]
+ [:data-model {:optional true} [:ref ::strict-data-perms]]
+ [:details {:optional true} [:enum :yes :no]]
+ [:transforms {:optional true} [:enum :yes :no]]])
+
+(defn- valid-db-perms?
+ [{:keys [create-queries view-data]}]
+ (not (and (= create-queries :query-builder-and-native) (= view-data :blocked))))
+
(mr/def ::strict-db-graph
"like db-graph, but with added validations:
- Ensures 'view-data' is not 'blocked' if 'create-queries' is 'query-builder-and-native'."
[:map-of
[:ref ::id]
[:and
- [:map
- [:view-data {:optional true} [:ref ::schemas]]
- [:create-queries {:optional true} [:ref ::schemas]]
- [:data {:optional true} [:ref ::strict-data-perms]]
- [:download {:optional true} [:ref ::strict-data-perms]]
- [:data-model {:optional true} [:ref ::strict-data-perms]]
- [:details {:optional true} [:enum :yes :no]]
- [:transforms {:optional true} [:enum :yes :no]]]
+ [:ref ::db-perms]
[:fn {:error/fn (fn [_ _] (trs "Invalid DB permissions: If you have write access for native queries, you must have data access to all schemas."))}
- (fn [db-entry]
- (let [{:keys [create-queries view-data]} db-entry]
- (not (and (= create-queries :query-builder-and-native) (= view-data :blocked)))))]]])
+ valid-db-perms?]]])
(mr/def ::data-permissions-graph
"Used to transform, and verify data permissions graph"
[:map
[:groups [:map-of [:ref ::group-id] [:maybe [:ref ::strict-db-graph]]]]])
-(mr/def ::strict-api-permissions-graph
- "Top level strict data graph schema expected over the API. Includes revision ID for avoiding concurrent updates."
+(mr/def ::attribute-name
+ "a user attribute name"
+ [:schema {:decode/normalize (fn [attribute]
+ (cond-> attribute
+ (keyword? attribute) u/qualified-name))}
+ ms/NonBlankString])
+
+(mr/def ::attribute-remapping
+ "a field name, a field id, or a parameter target"
+ [:orn
+ [:field-name ms/NonBlankString]
+ [:field-id ::lib.schema.id/field]
+ [:parameter-target [:ref ::lib.schema.parameter/target]]])
+
+(mr/def ::attribute-remappings
+ "a map of user attribute name -> the field or parameter target it is remapped onto"
+ [:map-of
+ [:or [:ref ::attribute-name]
+ (mu/refuse #(tru "Invalid attribute remappings: a user attribute name must be a non-blank string."))]
+ [:or [:ref ::attribute-remapping]
+ (mu/refuse #(tru "Invalid attribute remappings: a user attribute must be remapped onto a field name, a field id, or a parameter target."))]])
+
+(mr/def ::sandbox-update
+ "a sandbox to write alongside a permissions graph update"
+ [:and
+ [:map
+ [:id {:optional true} ms/PositiveInt]
+ [:group_id {:optional true} ms/PositiveInt]
+ [:table_id {:optional true} ms/PositiveInt]
+ [:card_id {:optional true} [:maybe ms/PositiveInt]]
+ [:attribute_remappings {:optional true} [:maybe [:ref ::attribute-remappings]]]
+ [:permission_id {:optional true} [:maybe ms/PositiveInt]]]
+ [:fn {:error/fn (fn [_ _] (trs "Invalid sandbox: an update needs an id, and a new sandbox needs a group_id and a table_id."))}
+ (fn [{:keys [id group_id table_id]}]
+ (boolean (or id (and group_id table_id))))]])
+
+(mr/def ::impersonation-update
+ "a connection impersonation policy to write alongside a permissions graph update"
+ [:map
+ [:group_id ms/PositiveInt]
+ [:db_id ms/PositiveInt]
+ [:attribute ms/NonBlankString]])
+
+(mr/def ::graph-update-request
+ "the permissions graph, plus the sandboxes and connection impersonations to write with it"
[:map
- [:revision {:optional true} [:maybe int?]]
- [:force {:optional true} [:maybe boolean?]]
- [:groups [:map-of [:ref ::group-id] [:maybe [:ref ::strict-db-graph]]]]])
+ [:groups [:and
+ [:multi {:dispatch map?}
+ [true [:map-of
+ [:or [:ref ::group-id]
+ (mu/refuse #(tru "Invalid permissions graph: it must be keyed by group id."))]
+ [:multi {:dispatch map?}
+ [true [:map-of
+ [:or [:ref ::id]
+ (mu/refuse #(tru "Invalid permissions graph: permissions for a group must be keyed by database id."))]
+ [:or [:ref ::db-perms]
+ (mu/refuse #(tru "Invalid DB permissions: unrecognized permissions for a database."))]]]
+ [false [:or :nil
+ (mu/refuse #(tru "Invalid permissions graph: permissions for a group must be keyed by database id."))]]]]]
+ [false (mu/refuse #(tru "Invalid permissions graph: it must be keyed by group id, then by database id."))]]
+ [:fn {:error/fn (fn [_ _] (trs "Invalid DB permissions: If you have write access for native queries, you must have data access to all schemas."))}
+ (fn [groups]
+ (or (not (map? groups))
+ (every? (fn [db-graph] (every? valid-db-perms? (vals db-graph)))
+ (vals groups))))]]]
+ [:revision {:optional true} [:maybe ms/Int]]
+ [:force {:optional true} [:maybe :boolean]]
+ [:sandboxes {:optional true} [:maybe [:sequential [:ref ::sandbox-update]]]]
+ [:impersonations {:optional true} [:maybe [:sequential [:ref ::impersonation-update]]]]])
diff --git a/src/metabase/public_sharing_rest/api.clj b/src/metabase/public_sharing_rest/api.clj
index 3dbd9b67d2f..129e11d0ddf 100644
--- a/src/metabase/public_sharing_rest/api.clj
+++ b/src/metabase/public_sharing_rest/api.clj
@@ -4,11 +4,13 @@
[hiccup.core :as hiccup]
[medley.core :as m]
[metabase.actions.core :as actions]
+ [metabase.actions.schema :as actions.schema]
[metabase.analytics.core :as analytics]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.dashboards-rest.api :as api.dashboard]
[metabase.dashboards.schema :as dashboards.schema]
+ [metabase.documents.prose-mirror :as prose-mirror]
[metabase.events.core :as events]
[metabase.lib.schema.info :as lib.schema.info]
[metabase.models.interface :as mi]
@@ -393,12 +395,6 @@
:format-rows? format_rows
:pivot? pivot_results}))))
-(def ^:private ActionParameterValue
- "A value submitted for an action execution parameter, keyed by parameter id. The FE types these as
- `string | number | boolean | null` (`ParametersForActionExecution` in `metabase-types/api/actions.ts`); dates and
- other rich types are submitted in their string form."
- [:maybe [:or :string number? :boolean]])
-
(api.macros/defendpoint :post "/dashboard/:uuid/dashcard/:dashcard-id/execute/values" :- [:map-of :string :any]
"Fetches the values for filling in execution parameters. Pass PK parameters and values to select.
@@ -408,7 +404,7 @@
[:dashcard-id ms/PositiveInt]]
_query-params
{:keys [parameters]} :- [:map
- [:parameters [:map-of :string ActionParameterValue]]]]
+ [:parameters ::actions.schema/prefetch-parameter-values]]]
(public-sharing.validation/check-public-sharing-enabled)
(let [dashboard-id (api/check-404 (t2/select-one-pk :model/Dashboard :public_uuid uuid :archived false))]
(api/check-404 (t2/select-one-pk :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))
@@ -431,7 +427,7 @@
[:dashcard-id ms/PositiveInt]]
_query-params
{:keys [parameters], :as _body} :- [:map
- [:parameters {:optional true} [:maybe [:map-of :keyword ActionParameterValue]]]
+ [:parameters {:optional true} [:maybe ::actions.schema/execute-parameter-values]]
[:modelId {:optional true} [:maybe ms/PositiveInt]]]]
(let [throttle-message (try
(throttle/check dashcard-execution-throttle dashcard-id)
@@ -452,7 +448,8 @@
;; you're by definition allowed to run it without a perms check anyway
(request/as-admin
;; Undo middleware string->keyword coercion
- (actions/execute-dashcard! dashboard-id dashcard-id (update-keys parameters name))))))))
+ (actions/execute-dashcard! dashboard-id dashcard-id (update-keys parameters name)
+ {:allow-http-actions? false})))))))
(defn- iframe
"Return an `<iframe>` HTML fragment to embed a public page."
@@ -669,7 +666,7 @@
[:uuid ms/UUIDString]]
_query-params
{:keys [parameters], :as _body} :- [:map
- [:parameters {:optional true} [:maybe [:map-of :keyword any?]]]]]
+ [:parameters {:optional true} [:maybe ::actions.schema/execute-parameter-values]]]]
(let [throttle-message (try
(throttle/check action-execution-throttle uuid)
nil
@@ -695,7 +692,8 @@
:type (:type action)
:action_id (:id action)})
;; Undo middleware string->keyword coercion
- (actions/execute-action! action (update-keys parameters name))))))))
+ (actions/execute-action! action (update-keys parameters name)
+ {:allow-http-actions? false})))))))
;;; ----------------------------------------------------- Map Tiles --------------------------------------------------
@@ -775,13 +773,15 @@
once before exposing them to unauthenticated users. The document and all cards must not be archived to be
accessible publicly."
[& conditions]
- (let [document (-> (api/check-404 (apply t2/select-one [:model/Document :id :name :document :content_type :created_at :updated_at]
- :archived false, conditions))
- ;; Hydrate cards via Toucan batched hydration to avoid N+1 queries
- (t2/hydrate :cards))]
+ (let [document (-> (api/check-404 (apply t2/select-one [:model/Document :id :name :document :content_type :created_at :updated_at]
+ :archived false, conditions))
+ ;; Hydrate cards via Toucan batched hydration to avoid N+1 queries
+ (t2/hydrate :cards))
+ embedded-ids (set (prose-mirror/card-ids document))]
(-> document
;; Filter sensitive fields from all cards before exposing publicly
- (update :cards #(update-vals % remove-card-non-public-columns))
+ (update :cards #(-> (select-keys % embedded-ids)
+ (update-vals remove-card-non-public-columns)))
(dissoc :content_type)
remove-document-non-public-columns)))
@@ -794,8 +794,10 @@
Returns the loaded `:model/Card` entity so the caller can thread it downstream without re-selecting it."
[uuid card-id]
- (let [document-id (api/check-404 (t2/select-one-pk :model/Document :public_uuid uuid :archived false))]
- (api/check-404 (t2/select-one :model/Card :id card-id :document_id document-id :archived false))))
+ (let [document (api/check-404 (t2/select-one [:model/Document :id :document :content_type]
+ :public_uuid uuid :archived false))]
+ (api/check-404 (when (contains? (set (prose-mirror/card-ids document)) card-id)
+ (t2/select-one :model/Card :id card-id :document_id (:id document) :archived false)))))
;; 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
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index b29f4c52aa9..2dc436555bc 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -146,20 +146,49 @@
(events/publish-event! :event/pulse-create {:object pulse :user-id api/*current-user-id*})
pulse)))
+(def ^:private PulseChannelType
+ [:enum "email" "slack" "http"])
+
+(def ^:private PulseScheduleType
+ [:enum "hourly" "daily" "weekly" "monthly"])
+
+(def ^:private PulseScheduleDay
+ [:enum "sun" "mon" "tue" "wed" "thu" "fri" "sat"])
+
+(def ^:private PulseScheduleFrame
+ [:enum "first" "mid" "last"])
+
+(def ^:private PulseScheduleHour
+ [:int {:min 0 :max 23}])
+
+(def ^:private PulseChannelRecipient
+ [:map
+ [:id {:optional true} [:maybe ms/PositiveInt]]
+ [:email {:optional true} [:maybe ms/Email]]])
+
+(def ^:private PulseChannelDetails
+ [:map
+ [:attachment_only {:optional true} [:maybe :boolean]]
+ [:include_pdf {:optional true} [:maybe :boolean]]
+ [:channel {:optional true} [:maybe :string]]
+ [:channels {:optional true} [:maybe :string]]
+ [:channel_id {:optional true} [:maybe :string]]
+ [:emails {:optional true} [:maybe [:sequential ms/Email]]]])
+
(def ^:private PulseChannel
"The fields [[metabase.pulse.models.pulse-channel/create-pulse-channel!]] reads off a channel."
[:map
- [:id {:optional true} :any]
- [:channel_type :any]
- [:enabled {:optional true} :any]
- [:pulse_id {:optional true} :any]
- [:channel_id {:optional true} :any]
- [:details {:optional true} ms/Map]
- [:recipients {:optional true} [:sequential ms/Map]]
- [:schedule_type {:optional true} :any]
- [:schedule_day {:optional true} :any]
- [:schedule_hour {:optional true} :any]
- [:schedule_frame {:optional true} :any]])
+ [:id {:optional true} [:maybe ms/PositiveInt]]
+ [:channel_type PulseChannelType]
+ [:enabled {:optional true} [:maybe :boolean]]
+ [:pulse_id {:optional true} [:maybe ms/PositiveInt]]
+ [:channel_id {:optional true} [:maybe ms/PositiveInt]]
+ [:details {:optional true} [:maybe PulseChannelDetails]]
+ [:recipients {:optional true} [:sequential PulseChannelRecipient]]
+ [:schedule_type {:optional true} [:maybe PulseScheduleType]]
+ [:schedule_day {:optional true} [:maybe PulseScheduleDay]]
+ [:schedule_hour {:optional true} [:maybe PulseScheduleHour]]
+ [:schedule_frame {:optional true} [:maybe PulseScheduleFrame]]])
;; 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
diff --git a/src/metabase/pulse/task/send_pulses.clj b/src/metabase/pulse/task/send_pulses.clj
index 5c8d9346c1f..d5ddf7fa879 100644
--- a/src/metabase/pulse/task/send_pulses.clj
+++ b/src/metabase/pulse/task/send_pulses.clj
@@ -112,10 +112,11 @@
(for [channel (t2/select [:model/PulseChannel :id :details :channel_id :channel_type]
{:where [:and
[:= :pulse_id pulse-id]
- [:not [:exists {:select [1]
- :from [:pulse_channel_recipient]
- :where [:= :pulse_channel_recipient.pulse_channel_id
- :pulse_channel.id]}]]]})
+ [:not [:exists ^:allow-subquery
+ {:select [1]
+ :from [:pulse_channel_recipient]
+ :where [:= :pulse_channel_recipient.pulse_channel_id
+ :pulse_channel.id]}]]]})
:when (case (:channel_type channel)
:email
(empty? (get-in channel [:details :emails]))
diff --git a/src/metabase/queries/core.clj b/src/metabase/queries/core.clj
index f2865059a99..d0a690187b3 100644
--- a/src/metabase/queries/core.clj
+++ b/src/metabase/queries/core.clj
@@ -34,20 +34,22 @@
batch-fetch-query-metadata]
[metabase.queries.models.card
fully-parameterized?
+ maybe-unverify!
model-supports-implicit-actions?
model?
sole-dashboard-id
starting-card-schema-version
update-card!
- visible-metric-cards-where-clause
- ;; TODO -- not convinced whether this belongs here or in `permissions`
- with-can-run-adhoc-query]
+ visible-metric-cards-where-clause]
[metabase.queries.models.card.metadata
infer-metadata
maybe-async-result-metadata
refresh-metadata
save-metadata-async!]
- [metabase.queries.models.parameter-card]
+ [metabase.queries.models.parameter-card
+ check-new-parameter-source-card-permissions
+ check-parameter-source-card-permissions
+ values-source-card-ids]
[metabase.queries.models.query
average-execution-time-ms
query->database-and-table-ids
diff --git a/src/metabase/queries/metadata.clj b/src/metabase/queries/metadata.clj
index e92f366c8f8..e71a41d10b6 100644
--- a/src/metabase/queries/metadata.clj
+++ b/src/metabase/queries/metadata.clj
@@ -3,6 +3,7 @@
[clojure.set :as set]
[metabase.api.common :as api]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.schema :as lib.schema]
@@ -229,7 +230,7 @@
[:map
[:card {:optional true} [:maybe ::queries.schema/card]]
[:series {:optional true} [:maybe [:sequential [:map
- [:dataset_query ::queries.schema/query]]]]]]]]]]]
+ [:dataset_query ::lib-be.schema/maybe-legacy-or-empty-query]]]]]]]]]]]
(let [dashcards (mapcat :dashcards dashboards)
cards (for [{:keys [card series]} dashcards
:let [all (conj series card)]
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index a0e7674f9ca..9977b93a372 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -19,8 +19,8 @@
[metabase.events.core :as events]
[metabase.graph.core :as graph]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
- [metabase.lib.metadata.protocols :as lib.metadata.protocols]
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
@@ -39,7 +39,6 @@
[metabase.queries.models.parameter-card :as parameter-card]
[metabase.queries.models.query :as query]
[metabase.queries.schema :as queries.schema]
- [metabase.query-permissions.core :as query-perms]
[metabase.search.core :as search]
[metabase.settings.core :as setting]
[metabase.staleness.core :as staleness]
@@ -192,32 +191,32 @@
(fn []
(let [card-ids (map u/the-id cards)
all-dashboards (t2/query {:union-all [;; First get dashboards from direct card connections
- {:nest
- {:select [[:dc.card_id :card_id]
- :d.name
- :d.collection_id
- :d.description
- :d.id
- :d.archived
- :d.enable_embedding]
- :from [[:report_dashboardcard :dc]]
- :join [[:report_dashboard :d] [:= :dc.dashboard_id :d.id]]
- :where [:in :dc.card_id [:inline card-ids]]
- :order-by [[:d.id :asc]]}}
+ ^:allow-subquery {:nest
+ ^:allow-subquery {:select [[:dc.card_id :card_id]
+ :d.name
+ :d.collection_id
+ :d.description
+ :d.id
+ :d.archived
+ :d.enable_embedding]
+ :from [[:report_dashboardcard :dc]]
+ :join [[:report_dashboard :d] [:= :dc.dashboard_id :d.id]]
+ :where [:in :dc.card_id [:inline card-ids]]
+ :order-by [[:d.id :asc]]}}
;; Then get dashboards from series
- {:nest
- {:select [[:dcs.card_id :card_id]
- :d.name
- :d.collection_id
- :d.description
- :d.id
- :d.archived
- :d.enable_embedding]
- :from [[:dashboardcard_series :dcs]]
- :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]
- [:report_dashboard :d] [:= :d.id :dc.dashboard_id]]
- :where [:in :dcs.card_id [:inline card-ids]]
- :order-by [[:d.id :asc]]}}]})]
+ ^:allow-subquery {:nest
+ ^:allow-subquery {:select [[:dcs.card_id :card_id]
+ :d.name
+ :d.collection_id
+ :d.description
+ :d.id
+ :d.archived
+ :d.enable_embedding]
+ :from [[:dashboardcard_series :dcs]]
+ :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]
+ [:report_dashboard :d] [:= :d.id :dc.dashboard_id]]
+ :where [:in :dcs.card_id [:inline card-ids]]
+ :order-by [[:d.id :asc]]}}]})]
(update-vals
(group-by :card_id all-dashboards)
(fn [dashes]
@@ -230,71 +229,9 @@
{:default []}))
(mu/defn- source-card-id :- [:maybe ::lib.schema.id/card]
- [query :- [:maybe ::queries.schema/query]]
+ [query :- [:maybe [:or ::lib.schema/query ::lib-be.schema/empty-query]]]
(some-> query not-empty lib/primary-source-card-id))
-(mu/defn- card->integer-table-ids :- [:maybe [:set {:min 1} ::lib.schema.id/table]]
- "Return integer source table ids for card's :dataset_query."
- [card :- [:maybe ::queries.schema/card]]
- (some-> card :dataset_query not-empty lib/all-source-table-ids))
-
-(mu/defn- prefetch-tables-for-cards!
- "Collect tables from `dataset-cards` and prefetch metadata. Should be used only with metadata provider caching
- enabled, as per https://github.com/metabase/metabase/pull/45050. Returns `nil`."
- [cards-with-non-empty-queries :- [:maybe
- [:sequential
- [:merge
- ::queries.schema/card
- [:map
- [:dataset_query ::lib.schema/query]]]]]]
- (let [db-id->table-ids (-> (group-by :database_id cards-with-non-empty-queries)
- (update-vals (partial into #{} (comp (mapcat card->integer-table-ids)
- (remove nil?)))))]
- (doseq [[db-id table-ids] db-id->table-ids
- :let [mp (lib-be/application-database-metadata-provider db-id)]
- :when (seq table-ids)]
- (lib.metadata.protocols/metadatas mp {:lib/type :metadata/table, :id (set table-ids)}))))
-
-(mu/defn with-can-run-adhoc-query
- "Adds `:can_run_adhoc_query` to each card."
- [cards :- [:maybe [:sequential ::queries.schema/card]]]
- ;; TODO: for metrics, we can get (some-fn :source_model_id :source_question_id)
- (let [cards-with-non-empty-queries (filter (comp seq :dataset_query) cards)
- source-card-ids (into #{}
- (keep (comp source-card-id :dataset_query))
- cards-with-non-empty-queries)]
- ;; Warming caches must not change the outcome of the permission checks below, so nothing here propagates: finding
- ;; a query's tables means walking it, and a malformed one throws.
- (try
- (when (lib-be/metadata-provider-cache)
- (prefetch-tables-for-cards! cards-with-non-empty-queries))
- ;; Only the tables the queries name directly: a source Card is reached through its collection's permissions,
- ;; not its tables', so it contributes none of its own.
- (perms/prime-table-perms-cache
- {:table-ids (into #{} (mapcat card->integer-table-ids) cards-with-non-empty-queries)})
- (catch Throwable t
- (log/errorf "Failed prefetching cards `%s`: %s" (pr-str (map :id cards-with-non-empty-queries)) (ex-message t))))
- (query-perms/with-card-instances (when (seq source-card-ids)
- (t2/select-fn->fn :id identity [:model/Card :id :collection_id :card_schema]
- :id [:in source-card-ids]))
- (mi/instances-with-hydrated-data
- cards :can_run_adhoc_query
- (fn []
- (into {}
- (map
- (fn [{card-id :id :keys [dataset_query]}]
- [card-id (query-perms/can-run-query? dataset_query)]))
- cards-with-non-empty-queries))
- :id
- {:default false}))))
-
-(methodical/defmethod t2/batched-hydrate [:model/Card :can_run_adhoc_query]
- "Hydrate can_run_adhoc_query onto cards"
- [_model _k cards]
- (with-can-run-adhoc-query cards))
-
-;; note: perms lookup here in the course of fetching a card/model should hit a cache pre-warmed by
-;; the `:can_run_adhoc_query` above
(methodical/defmethod t2/batched-hydrate [:model/Card :can_manage_db]
"Hydrate can_manage_db onto cards. Indicates whether the current user has access to the database admin page for the
database powering this card."
@@ -411,9 +348,11 @@
(for [{tag-type :type, widget-type :widget-type, :as tag} (some-> card :dataset_query not-empty lib/all-template-tags)
:when (and tag-type
(or (contains? lib.schema.template-tag/raw-value-template-tag-types tag-type)
+ (= tag-type :temporal-unit)
(and (= tag-type :dimension) widget-type (not= widget-type :none))))]
{:id (:id tag)
:type (or widget-type (case tag-type
+ :temporal-unit :temporal-unit
:date :date/single
:text :string/=
:number :number/=
@@ -421,7 +360,7 @@
;; fallback; should be unreachable since :when filters
;; to raw-value-template-tag-types
:string/=))
- :target (if (= tag-type :dimension)
+ :target (if (contains? #{:dimension :temporal-unit} tag-type)
[:dimension [:template-tag (:name tag)]]
[:variable [:template-tag (:name tag)]])
:name (:display-name tag)
@@ -476,6 +415,15 @@
{:status-code 400})))))
nil)
+(mu/defn- assert-not-native-audit-db-query
+ [{query :dataset_query, :as _card} :- [:maybe ::queries.schema/card]]
+ (when (and (seq query)
+ (= (:database query) audit/audit-db-id)
+ (lib/any-native-stage? query))
+ (throw (ex-info (tru "You cannot save a native query that targets the audit database.")
+ {:status-code 400})))
+ nil)
+
(defn- dashboard-internal-card? [card]
(boolean (:dashboard_id card)))
@@ -550,6 +498,7 @@
(check-field-filter-fields-are-from-correct-database card)
;; TODO: add a check to see if all id in :parameter_mappings are in :parameters (#40013)
(assert-valid-type card)
+ (assert-not-native-audit-db-query card)
(params/assert-valid-parameters card)
(params/assert-valid-parameter-mappings card)
(collection/check-collection-namespace :model/Card (:collection_id card)))))
@@ -559,6 +508,11 @@
metabase-enterprise.sandbox.models.sandbox
[_ _])
+(defenterprise pre-delete-check-sandbox-constraints
+ "Checks additional sandboxing constraints for Metabase Enterprise Edition. The OSS implementation is a no-op."
+ metabase-enterprise.sandbox.models.sandbox
+ [_])
+
(defn- value-field-gone?
[metadata-columns value-field]
(or (nil? value-field)
@@ -641,6 +595,8 @@
;; TODO - don't we need to be doing the same permissions check we do in `pre-insert` if the query gets changed? Or
;; does that happen in the `PUT` endpoint? (#40013)
(u/prog1 card
+ (when (:dataset_query changes)
+ (assert-not-native-audit-db-query changes))
(let [;; Fetch old card data if necessary, and share the data between multiple checks.
old-card-info (when (or (contains? changes :type)
(:dataset_query changes)
@@ -921,7 +877,8 @@
;; Cards don't normally get deleted (they get archived instead) so this mostly affects tests
(t2/define-before-delete :model/Card
- [{:keys [id] :as _card}]
+ [{:keys [id] :as card}]
+ (pre-delete-check-sandbox-constraints card)
;; delete any ParameterCard that the parameters on this card linked to
(parameter-card/delete-all-for-parameterized-object! "card" id)
;; delete any ParameterCard linked to this card
@@ -933,9 +890,9 @@
;; return empty by the time the actual DELETE executes.
(when-let [notification-ids (seq (t2/select-pks-set :model/Notification
:payload_type :notification/card
- :payload_id [:in {:select [:id]
- :from [:notification_card]
- :where [:= :card_id id]}]))]
+ :payload_id [:in ^:allow-subquery {:select [:id]
+ :from [:notification_card]
+ :where [:= :card_id id]}]))]
(t2/delete! :model/Notification :id [:in notification-ids])))
(defmethod mi/exclude-internal-content-hsql :model/Card
@@ -1155,6 +1112,19 @@
:query_type ;; these first three may not even be changeable
:dataset_query})
+(defn maybe-unverify!
+ "Remove `card`'s verification review when `updates` change something important about its query."
+ [card updates actor]
+ (when (and (card-is-verified? card)
+ (changed? card (select-keys updates card-compare-keys)))
+ ;; this is an enterprise feature but we don't care if enterprise is enabled here. If there is a review we need
+ ;; to remove it regardless if enterprise edition is present at the moment.
+ (moderation/create-review! {:moderated_item_id (:id card)
+ :moderated_item_type "card"
+ :moderator_id (:id actor)
+ :status nil
+ :text (tru "Unverified due to edit")})))
+
(mu/defn- mbql-clause->identifier-for-parameter-updates
"Get the unique key used to power the parameter mapping update stuff added in #49308. Key is an MBQL-5-style clause
but with an empty options clause."
@@ -1297,15 +1267,7 @@
:enable_embedding :type :parameters :parameter_mappings :embedding_params
:result_metadata :collection_preview :verified-result-metadata?})]
(assert-is-valid-dashboard-internal-update card-updates card-before-update)
- (when (and (card-is-verified? card-before-update)
- (changed? card-before-update (select-keys updated-fields card-compare-keys)))
- ;; this is an enterprise feature but we don't care if enterprise is enabled here. If there is a review we need
- ;; to remove it regardless if enterprise edition is present at the moment.
- (moderation/create-review! {:moderated_item_id (:id card-before-update)
- :moderated_item_type "card"
- :moderator_id (:id actor)
- :status nil
- :text (tru "Unverified due to edit")}))
+ (maybe-unverify! card-before-update updated-fields actor)
;; Invalidate the cache for card
(cache/invalidate-config! {:questions [(:id card-before-update)]
:with-overrides? true})
@@ -1346,7 +1308,7 @@
(mu/defn fully-parameterized?
"Given a Card, returns `true` if its query is fully parameterized."
[{query :dataset_query, :as _card} :- [:map
- [:dataset_query [:maybe ::queries.schema/query]]]]
+ [:dataset_query [:maybe [:or ::lib.schema/query ::lib-be.schema/empty-query]]]]]
(if (empty? query)
true
(lib/fully-parameterized-query? query)))
@@ -1548,9 +1510,9 @@
:collection-id true
:creator-id true
:dashboard-id true
- :dashboardcard-count {:select [:%count.*]
- :from [:report_dashboardcard]
- :where [:= :report_dashboardcard.card_id :this.id]}
+ :dashboardcard-count ^:allow-subquery {:select [:%count.*]
+ :from [:report_dashboardcard]
+ :where [:= :report_dashboardcard.card_id :this.id]}
:database-id true
:last-viewed-at :last_used_at
:native-query {:fn maybe-extract-native-query
@@ -1612,35 +1574,35 @@
(defmethod staleness/find-stale-query :model/Card
[_model args]
- {:select [:report_card.id
- [(h2x/literal "Card") :model]
- [:report_card.name :name]
- :last_used_at]
- :from :report_card
- :left-join [:moderation_review [:and
- [:= :moderation_review.moderated_item_id :report_card.id]
- [:= :moderation_review.moderated_item_type (h2x/literal "card")]
- [:= :moderation_review.most_recent true]
- [:= :moderation_review.status (h2x/literal "verified")]]
- :pulse_card [:= :pulse_card.card_id :report_card.id]
- :pulse [:and
- [:= :pulse_card.pulse_id :pulse.id]
- [:= :pulse.archived false]]
- :sandboxes [:= :sandboxes.card_id :report_card.id]
- :collection [:= :collection.id :report_card.collection_id]]
- :where [:and
- [:= :sandboxes.id nil]
- [:= :pulse.id nil]
- [:= :moderation_review.id nil]
- [:= :report_card.archived false]
- [:<= :report_card.last_used_at (-> args :cutoff-date)]
- ;; find things only in regular collections, not the `instance-analytics` collection.
- [:= :collection.type nil]
- (when (embed.settings/some-embedding-enabled?)
- [:= :report_card.enable_embedding false])
- (when (setting/get :enable-public-sharing)
- [:= :report_card.public_uuid nil])
- [:or
- (when (contains? (:collection-ids args) nil)
- [:is :report_card.collection_id nil])
- [:in :report_card.collection_id (-> args :collection-ids)]]]})
+ ^:allow-subquery {:select [:report_card.id
+ [(h2x/literal "Card") :model]
+ [:report_card.name :name]
+ :last_used_at]
+ :from :report_card
+ :left-join [:moderation_review [:and
+ [:= :moderation_review.moderated_item_id :report_card.id]
+ [:= :moderation_review.moderated_item_type (h2x/literal "card")]
+ [:= :moderation_review.most_recent true]
+ [:= :moderation_review.status (h2x/literal "verified")]]
+ :pulse_card [:= :pulse_card.card_id :report_card.id]
+ :pulse [:and
+ [:= :pulse_card.pulse_id :pulse.id]
+ [:= :pulse.archived false]]
+ :sandboxes [:= :sandboxes.card_id :report_card.id]
+ :collection [:= :collection.id :report_card.collection_id]]
+ :where [:and
+ [:= :sandboxes.id nil]
+ [:= :pulse.id nil]
+ [:= :moderation_review.id nil]
+ [:= :report_card.archived false]
+ [:<= :report_card.last_used_at (-> args :cutoff-date)]
+ ;; find things only in regular collections, not the `instance-analytics` collection.
+ [:= :collection.type nil]
+ (when (embed.settings/some-embedding-enabled?)
+ [:= :report_card.enable_embedding false])
+ (when (setting/get :enable-public-sharing)
+ [:= :report_card.public_uuid nil])
+ [:or
+ (when (contains? (:collection-ids args) nil)
+ [:is :report_card.collection_id nil])
+ [:in :report_card.collection_id (-> args :collection-ids)]]]})
diff --git a/src/metabase/queries/models/parameter_card.clj b/src/metabase/queries/models/parameter_card.clj
index a6c017003cf..ff054ee2e3f 100644
--- a/src/metabase/queries/models/parameter_card.clj
+++ b/src/metabase/queries/models/parameter_card.clj
@@ -1,12 +1,13 @@
(ns metabase.queries.models.parameter-card
(:require
[medley.core :as m]
+ [metabase.api.common :as api]
[metabase.models.interface :as mi]
[metabase.parameters.schema :as parameters.schema]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
- [metabase.util.malli.schema :as ms]
+ [metabase.util.malli.registry :as mr]
[methodical.core :as methodical]
[toucan2.core :as t2]))
@@ -24,6 +25,9 @@
"Set of valid parameterized_object_type for a ParameterCard"
#{"dashboard" "card"})
+(mr/def ::parameterized-object-type
+ (into [:enum] (sort valid-parameterized-object-type)))
+
(defn- validate-parameterized-object-type
[{:keys [parameterized_object_type] :as _parameter-card}]
(when-not (valid-parameterized-object-type parameterized_object_type)
@@ -67,11 +71,40 @@
(t2/update! :model/ParameterCard conditions {:card_id card-id})
(t2/insert! :model/ParameterCard (merge conditions {:card_id card-id}))))))
+(defn values-source-card-ids
+ "Returns the ids of the Cards `parameters` draw their values from."
+ [parameters]
+ (into #{}
+ (keep (fn [{:keys [values_source_type values_source_config]}]
+ (when (= (keyword values_source_type) :card)
+ (:card_id values_source_config))))
+ parameters))
+
+(mu/defn check-parameter-source-card-permissions
+ "Read-check the Cards `parameters` draw their values from."
+ [parameters :- [:maybe [:sequential :map]]]
+ (doseq [card-id (values-source-card-ids parameters)]
+ (api/read-check :model/Card card-id)))
+
+(mu/defn check-new-parameter-source-card-permissions
+ "Read-check the source Cards newly referenced by `parameters` that are not already stored for this object."
+ [parameterized-object-type :- ::parameterized-object-type
+ parameterized-object-id :- pos-int?
+ parameters :- [:maybe [:sequential ::parameters.schema/parameter]]]
+ (when-not mi/*deserializing?*
+ (when-let [wanted (not-empty (values-source-card-ids parameters))]
+ (let [existing (t2/select-fn-set :card_id :model/ParameterCard
+ :parameterized_object_type parameterized-object-type
+ :parameterized_object_id parameterized-object-id)]
+ (doseq [card-id wanted
+ :when (not (contains? existing card-id))]
+ (api/read-check :model/Card card-id))))))
+
(mu/defn upsert-or-delete-from-parameters!
"From a parameters list on card or dashboard, create, update,
or delete appropriate ParameterCards for each parameter in the dashboard"
- [parameterized-object-type :- ms/NonBlankString ; TODO (Cam 9/25/25) -- change this to take `:model/Dashboard` or `:model/Card` instead of ANY STRING
- parameterized-object-id :- ms/PositiveInt
+ [parameterized-object-type :- ::parameterized-object-type ; TODO (Cam 9/25/25) -- change this to take `:model/Dashboard` or `:model/Card` instead of ANY STRING
+ parameterized-object-id :- pos-int?
parameters :- [:maybe [:sequential ::parameters.schema/parameter]]]
(let [upsertable? (fn [{:keys [values_source_type values_source_config id]}]
(and values_source_type id (:card_id values_source_config)
diff --git a/src/metabase/queries/models/query.clj b/src/metabase/queries/models/query.clj
index 1e2bd5e1a40..fedcd7231a8 100644
--- a/src/metabase/queries/models/query.clj
+++ b/src/metabase/queries/models/query.clj
@@ -2,11 +2,12 @@
"Functions related to the 'Query' model, which records stuff such as average query execution time."
(:require
[metabase.app-db.core :as mdb]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.models.interface :as mi]
- [metabase.queries.schema :as queries.schema]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -193,7 +194,7 @@
"Return a map with `:database-id` and source `:table-id` that should be saved for a Card.
Expects MBQL 5 queries."
- [{database-id :database, :as query} :- ::queries.schema/query]
+ [{database-id :database, :as query} :- [:or ::lib.schema/query ::lib-be.schema/empty-query]]
(when (seq query)
(if-let [source-card-id (lib/primary-source-card-id query)]
(let [card (or (lib.metadata/card query source-card-id)
@@ -207,5 +208,5 @@
(mu/defn query-is-native? :- :boolean
"Whether this query (MBQL 5 or legacy) has a `:native` first stage. Queries with source Cards are considered to be MBQL
regardless of whether the Card has a native query or not."
- [query :- [:maybe ::queries.schema/query]]
+ [query :- [:maybe [:or ::lib.schema/query ::lib-be.schema/empty-query]]]
(boolean (some-> query not-empty lib/native-only-query?)))
diff --git a/src/metabase/queries/schema.clj b/src/metabase/queries/schema.clj
index 59b184724d9..f2e5fbdf655 100644
--- a/src/metabase/queries/schema.clj
+++ b/src/metabase/queries/schema.clj
@@ -1,9 +1,8 @@
(ns metabase.queries.schema
(:require
[metabase.documents.schema :as documents.schema]
- [metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
- [metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.parameters.schema :as parameters.schema]
@@ -19,25 +18,6 @@
(mr/def ::card-type
::lib.schema.metadata/card.type)
-(mr/def ::empty-map
- "An empty map, allowed for Card.dataset_query for historic purposes."
- [:= {} {}])
-
-(mr/def ::query
- "Schema for Card.dataset_query. Cards are for some wacko reason allowed to be saved with empty queries (`{}`), but not
- `NULL` ones, because the column is non-null. This sorta seems like an oversight but fixing all the tests that save
- Cards with empty queries is too much to attempt at this point. So a Card either has an empty query or a valid MBQL 5
- query."
- [:multi {:dispatch (comp boolean empty?)}
- [true ::empty-map]
- [false [:schema
- {:decode/normalize lib-be/normalize-query}
- [:merge
- [:ref ::lib.schema/query]
- ;; Card query is guaranteed to have a metadata provider
- [:map
- [:lib/metadata ::lib.schema.metadata/metadata-provider]]]]]])
-
(mr/def ::card.result-metadata
[:and
[:sequential ::lib.schema.metadata/lib-or-legacy-column]
@@ -68,7 +48,7 @@
[:dashboard_id {:optional true} [:maybe ::lib.schema.id/dashboard]]
[:database_id {:optional true} [:maybe ::lib.schema.id/database]]
[:document_id {:optional true} [:maybe ::documents.schema/document.id]]
- [:dataset_query {:optional true} [:maybe ::query]]
+ [:dataset_query {:optional true} [:maybe ::lib-be.schema/maybe-legacy-or-empty-query]]
[:description {:optional true} [:maybe :string]]
[:name {:optional true} [:maybe :string]]
[:parameters {:optional true} [:maybe [:ref ::parameters.schema/parameters]]]
diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.clj
index 9ced165f1c3..dba2650efcd 100644
--- a/src/metabase/queries_rest/api/card.clj
+++ b/src/metabase/queries_rest/api/card.clj
@@ -1,8 +1,6 @@
(ns metabase.queries-rest.api.card
"/api/card endpoints."
(:require
- [medley.core :as m]
- [metabase.analyze.core :as analyze]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.collections.models.collection :as collection]
@@ -11,11 +9,14 @@
[metabase.embedding.validation :as embedding.validation]
[metabase.events.core :as events]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.lib.types.isa :as lib.types.isa]
[metabase.models.interface :as mi]
+ [metabase.parameters.params :as params]
[metabase.parameters.schema :as parameters.schema]
[metabase.permissions.core :as perms]
[metabase.public-sharing.validation :as public-sharing.validation]
@@ -205,7 +206,6 @@
(t2/hydrate :based_on_upload
:creator
:can_write
- :can_run_adhoc_query
:dashboard_count
[:dashboard :moderation_status]
:average_query_time
@@ -485,7 +485,7 @@
;;; ------------------------------------------------- Creating Cards -------------------------------------------------
(mu/defn- check-if-card-can-be-saved
- [dataset-query :- [:maybe ::queries.schema/query]
+ [dataset-query :- [:maybe ::lib-be.schema/maybe-legacy-query]
card-type :- [:maybe ::queries.schema/card-type]]
(when (and (seq dataset-query) (= card-type :metric))
(when-not (lib/can-save? dataset-query card-type)
@@ -525,7 +525,7 @@
[:map
[:name ms/NonBlankString]
[:type {:optional true} [:maybe ::queries.schema/card-type]]
- [:dataset_query ms/Map]
+ [:dataset_query ::lib-be.schema/maybe-legacy-query]
;; TODO: Make entity_id a NanoID regex schema?
[:entity_id {:optional true} [:maybe ms/NonBlankString]]
[:parameters {:optional true} [:maybe ::parameters.schema/parameters]]
@@ -535,7 +535,7 @@
[:visualization_settings ms/Map]
[:collection_id {:optional true} [:maybe [:or ms/PositiveInt ms/NanoIdString]]]
[:collection_position {:optional true} [:maybe ms/PositiveInt]]
- [:result_metadata {:optional true} [:maybe analyze/ResultsMetadata]]
+ [:result_metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/card.result-metadata]]]
[:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
[:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
[:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]
@@ -543,14 +543,15 @@
[:size_x ms/PositiveInt]
[:size_y ms/PositiveInt]]]]])
-(defn- normalize-dataset-query-or-400
- "Strictly normalize an incoming `:dataset_query` from an API request, converting any normalization
- failure into a 400 Bad Request."
- [query]
- (try
- (lib-be/normalize-query nil query {:strict? true})
- (catch Throwable e
- (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400) e)))))
+(defn- check-parameter-permissions
+ [parameters query]
+ (queries/check-parameter-source-card-permissions parameters)
+ (query-perms/check-parameter-field-permissions
+ (into []
+ (keep (fn [{:keys [target]}]
+ (when target
+ (params/param-target->field-id target {:dataset_query query}))))
+ parameters)))
;; 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
@@ -561,14 +562,12 @@
[_route-params
_query-params
{card-type :type, collection-id :collection_id, :as card} :- CardCreateSchema]
- (let [card (-> card
- (update :dataset_query normalize-dataset-query-or-400)
- (cond-> (some? collection-id)
- ;; Strict check to prevent a malformed query (coerced to `{}` by [[lib-be/normalize-query]])
- ;; from being written into the DB (#74615).
- (update :collection_id #(eid-translation/->id-or-404 :collection %))))
+ (let [card (cond-> card
+ (some? collection-id)
+ (update :collection_id #(eid-translation/->id-or-404 :collection %)))
query (:dataset_query card)]
(check-if-card-can-be-saved query card-type)
+ (check-parameter-permissions (:parameters card) query)
;; check that we have permissions to run the query that we're trying to save.
;; Strip :query-permissions/perms first -- it is populated internally by the QP
;; middleware, so any value already on the incoming query is dropped here.
@@ -601,6 +600,7 @@
(let [orig-card (api/read-check :model/Card id)
new-name (trs "Copy of {0}" (:name orig-card))
new-card (assoc orig-card :name new-name)]
+ (api/create-check :model/Card new-card)
(-> (queries/create-card! new-card @api/*current-user*)
hydrate-card-details
(assoc :last-edit-info (revisions/edit-information-for-user @api/*current-user*)))))
@@ -645,7 +645,7 @@
[:name {:optional true} [:maybe ms/NonBlankString]]
[:parameters {:optional true} [:maybe ::parameters.schema/parameters]]
[:parameter_mappings {:optional true} [:maybe ::parameters.schema/parameter-mappings]]
- [:dataset_query {:optional true} [:maybe ms/Map]]
+ [:dataset_query {:optional true} [:maybe ::lib-be.schema/maybe-legacy-query]]
[:type {:optional true} [:maybe ::queries.schema/card-type]]
[:display {:optional true} [:maybe ms/NonBlankString]]
[:description {:optional true} [:maybe :string]]
@@ -656,7 +656,7 @@
[:embedding_params {:optional true} [:maybe ms/EmbeddingParams]]
[:collection_id {:optional true} [:maybe ms/PositiveInt]]
[:collection_position {:optional true} [:maybe ms/PositiveInt]]
- [:result_metadata {:optional true} [:maybe analyze/ResultsMetadata]]
+ [:result_metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/card.result-metadata]]]
[:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
[:collection_preview {:optional true} [:maybe :boolean]]
[:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
@@ -680,11 +680,10 @@
[id :- ::lib.schema.id/card
{metadata :result_metadata, card-type :type, :as card-updates} :- CardUpdateSchema
delete-old-dashcards? :- :boolean]
- ;; Strict check to prevent a malformed query (coerced to `{}` by [[lib-be/normalize-query]])
- ;; from being written into the DB (#74615).
- (let [card-updates (m/update-existing card-updates :dataset_query normalize-dataset-query-or-400)
- query (:dataset_query card-updates)]
+ (let [query (:dataset_query card-updates)]
(check-if-card-can-be-saved query card-type)
+ (check-parameter-permissions (:parameters card-updates)
+ (or query (t2/select-one-fn :dataset_query :model/Card :id id)))
(when-some [query (:dataset_query card-updates)]
(try
(lib/check-card-overwrite id query)
@@ -996,7 +995,7 @@
be enabled."
[{:keys [card-id]} :- [:map
[:card-id ms/PositiveInt]]]
- (perms/check-has-application-permission :setting)
+ (api/check-superuser)
(public-sharing.validation/check-public-sharing-enabled)
(api/check-not-archived (api/read-check :model/Card card-id))
(let [{existing-public-uuid :public_uuid} (t2/select-one [:model/Card :public_uuid :card_schema] :id card-id)
diff --git a/src/metabase/query_permissions/core.clj b/src/metabase/query_permissions/core.clj
index 37f1959291f..20524566f83 100644
--- a/src/metabase/query_permissions/core.clj
+++ b/src/metabase/query_permissions/core.clj
@@ -9,6 +9,7 @@
(p/import-vars
[metabase.query-permissions.impl
can-query-table?
+ check-parameter-field-permissions
can-run-query?
check-card-read-perms
check-card-result-metadata-data-perms
diff --git a/src/metabase/query_permissions/impl.clj b/src/metabase/query_permissions/impl.clj
index acaa9ff1276..77cd2fe0338 100644
--- a/src/metabase/query_permissions/impl.clj
+++ b/src/metabase/query_permissions/impl.clj
@@ -130,8 +130,7 @@
(match/match-many query
(:and m {:qp/stage-is-from-source-card (id :guard identity)})
(merge-with merge-source-ids
- (when-not parent-source-card-id
- {:card-ids #{id}})
+ {:card-ids #{id}}
(query->source-ids (dissoc m :qp/stage-is-from-source-card) id in-sandbox?))
(:and m {:query-permissions/sandboxed-table (id :guard identity)})
@@ -248,10 +247,11 @@
{:perms/create-queries :query-builder-and-native
:perms/view-data :unrestricted}
(when-let [card-ids (referenced-card-ids query)]
- {:paths (into #{}
- (mapcat (fn [card-id]
- (mi/perms-objects-set (card-instance card-id) :read)))
- card-ids)})))
+ {:card-ids card-ids
+ :paths (into #{}
+ (mapcat (fn [card-id]
+ (mi/perms-objects-set (card-instance card-id) :read)))
+ card-ids)})))
(defn- legacy-mbql-required-perms
([query options]
@@ -276,7 +276,7 @@
(not already-preprocessed?) preprocess-query)
{:keys [table-ids table-query-ids card-ids native?]} (query->source-ids query)]
(merge
- (when (seq card-ids)
+ (when-let [card-ids (not-empty (into (set card-ids) (referenced-card-ids query)))]
{:card-ids card-ids})
(when (seq table-ids)
{:perms/view-data (zipmap table-ids (repeat :unrestricted))})
@@ -431,16 +431,20 @@
(mu/defn can-run-query?
"Return `true` if the current user has sufficient permissions to run `query`, and `false` otherwise."
- [{database-id :database :as query} :- :map]
- (try
- (let [required-perms (required-perms-for-query query)]
- (check-data-perms query required-perms)
- ;; Check card read permissions for any cards referenced in subqueries!
- (doseq [card-id (:card-ids required-perms)]
- (check-card-read-perms database-id card-id))
- true)
- (catch clojure.lang.ExceptionInfo _e
- false)))
+ ([query]
+ (can-run-query? query false))
+
+ ([{database-id :database :as query} :- :map
+ already-preprocessed? :- :boolean]
+ (try
+ (let [required-perms (required-perms-for-query query :already-preprocessed? already-preprocessed?)]
+ (check-data-perms query required-perms)
+ ;; Check card read permissions for any cards referenced in subqueries!
+ (doseq [card-id (:card-ids required-perms)]
+ (check-card-read-perms database-id card-id))
+ true)
+ (catch clojure.lang.ExceptionInfo _e
+ false))))
(mu/defn can-query-table?
"Does the current user have permissions to run an ad-hoc query against the Table with `table-id`?"
@@ -450,15 +454,40 @@
:type :query
:query {:source-table table-id}}))
+(mu/defn check-parameter-field-permissions
+ "Throw a 403 unless the current user could run an ad-hoc query against the Tables the Fields with `field-ids` belong
+ to."
+ [field-ids :- [:maybe [:sequential ::lib.schema.id/field]]]
+ (when (seq field-ids)
+ (let [table-ids (t2/select-fn-set :table_id :model/Field :id [:in (set field-ids)])
+ table-id->database-id (when (seq table-ids)
+ (t2/select-pk->fn :db_id :model/Table :id [:in table-ids]))]
+ (perms/prime-table-perms-cache {:table-ids table-ids})
+ (doseq [table-id table-ids
+ :let [database-id (table-id->database-id table-id)]]
+ (when-not (can-query-table? database-id table-id)
+ (throw (ex-info (tru "You must have data permissions to add a parameter referencing the Table {0}."
+ (pr-str (t2/select-one-fn :name :model/Table :id table-id)))
+ {:status-code 403
+ :database-id database-id
+ :table-id table-id
+ :actual-permissions @api/*current-user-permissions-set*})))))))
+
(mu/defn check-run-permissions-for-query
"Make sure the Current User has the appropriate permissions to run `query`. We don't want Users saving Cards with
queries they wouldn't be allowed to run!"
[query :- :map]
{:pre [(map? query)]}
- (let [query (dissoc query :query-permissions/perms)]
- (when-not (can-run-query? query)
+ (let [query (dissoc query :query-permissions/perms)
+ expanded (try
+ (preprocess-query query)
+ (catch Throwable _
+ nil))
+ query (or expanded query)
+ expanded? (some? expanded)]
+ (when-not (can-run-query? query expanded?)
(let [required-perms (try
- (required-perms-for-query query :throw-exceptions? true)
+ (required-perms-for-query query :already-preprocessed? expanded? :throw-exceptions? true)
(catch Throwable e
e))]
(throw (ex-info (tru "You cannot save this Question because you do not have permissions to run its query.")
diff --git a/src/metabase/query_processor.clj b/src/metabase/query_processor.clj
index 35bb3b0fa78..f9370c6beb1 100644
--- a/src/metabase/query_processor.clj
+++ b/src/metabase/query_processor.clj
@@ -6,7 +6,9 @@
Various REST API endpoints, such as `POST /api/dataset`, return the results of queries; they usually
use [[userland-query]] or [[userland-query-with-default-constraints]] (see below)."
+ (:refer-clojure :exclude [select-keys])
(:require
+ [medley.core :as m]
[metabase.lib.schema.info :as lib.schema.info]
[metabase.query-processor.compile :as qp.compile]
[metabase.query-processor.debug :as qp.debug]
@@ -21,7 +23,8 @@
[metabase.query-processor.setup :as qp.setup]
[metabase.tracing.core :as tracing]
[metabase.util.log :as log]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.performance :refer [select-keys]]))
(def around-middleware
"Middleware that goes AROUND [[process-query]]. Does extra stuff like handling `:internal` Audit v1 queries or saving
@@ -105,7 +108,10 @@
info :- [:maybe ::lib.schema.info/info]]
(-> query
(assoc-in [:middleware :userland-query?] true)
- (update :info merge info))))
+ (cond-> info (update :info merge info)))))
+
+(def ^:private userland-query-middleware-options
+ #{:js-int-to-string? :ignore-cached-results?})
(mu/defn userland-query-with-default-constraints :- ::qp.schema/any-query
"Add middleware options and `:info` to a `query` so it is ran as a 'userland' query. QP behavior changes are the same
@@ -119,6 +125,8 @@
([query :- ::qp.schema/any-query
info :- [:maybe ::lib.schema.info/info]]
(-> query
+ (dissoc :constraints)
+ (m/update-existing :middleware select-keys userland-query-middleware-options)
(userland-query info)
(assoc-in [:middleware :add-default-userland-constraints?] true))))
;; test
diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.clj
index 867b521d3e1..291fcb831b6 100644
--- a/src/metabase/query_processor/api.clj
+++ b/src/metabase/query_processor/api.clj
@@ -1,6 +1,6 @@
(ns metabase.query-processor.api
"/api/dataset endpoints."
- (:refer-clojure :exclude [not-empty get-in])
+ (:refer-clojure :exclude [get-in select-keys])
(:require
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
@@ -8,7 +8,9 @@
[metabase.driver.util :as driver.u]
[metabase.events.core :as events]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.info :as lib.schema.info]
[metabase.model-persistence.core :as model-persistence]
@@ -33,7 +35,7 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.util.malli.schema :as ms]
- [metabase.util.performance :refer [not-empty get-in]]
+ [metabase.util.performance :refer [get-in select-keys]]
[steffan-westcott.clj-otel.api.trace.span :as span]
^{:clj-kondo/ignore [:discouraged-namespace]} [toucan2.core :as t2]))
@@ -45,31 +47,27 @@
is a wrapper for the function of the same name in the QP util namespace; it adds additional permissions checking as
well."
[query]
- (when-let [source-card-id (and ((complement #{:internal "internal"}) (:type query))
- (some-> query not-empty lib-be/normalize-query lib/primary-source-card-id))]
+ (when-let [source-card-id (lib/primary-source-card-id query)]
(log/infof "Source query for this query is Card %s" (pr-str source-card-id))
(api/read-check :model/Card source-card-id)
source-card-id))
(mu/defn- run-streaming-query :- (ms/InstanceOfClass metabase.server.streaming_response.StreamingResponse)
- [{:keys [database], :as query}
+ [query :- [:or ::lib.schema/query ::lib-be.schema/internal-query]
& {:keys [context export-format was-pivot]
:or {context :ad-hoc
export-format :api}}]
(span/with-span!
{:name "run-query-async"}
- (when (and (not= (:type query) "internal")
- (not= database lib.schema.id/saved-questions-virtual-database-id))
- (when-not database
- (throw (ex-info (tru "`database` is required for all queries whose type is not `internal`.")
- {:status-code 400, :query query}))))
;; store table id trivially iff we get a query with simple source-table
- (let [table-id (get-in query [:query :source-table])]
+ (let [table-id (when (= (lib/normalized-query-type query) :mbql/query)
+ (lib/primary-source-table-id query))]
(when (int? table-id)
(events/publish-event! :event/table-read {:object (t2/select-one :model/Table :id table-id)
:user-id api/*current-user-id*})))
;; add sensible constraints for results limits on our query
- (let [source-card-id (query->source-card-id query) ; This is only set for direct :source-table "card__..."
+ (let [source-card-id (when (= (lib/normalized-query-type query) :mbql/query)
+ (query->source-card-id query))
source-card (when source-card-id
(t2/select-one [:model/Card :entity_id :result_metadata :type :card_schema] :id source-card-id))
info (cond-> {:executed-by api/*current-user-id*
@@ -97,8 +95,7 @@
"Execute a query and retrieve the results in the usual format. The query will not use the cache."
[_route-params
_query-params
- query :- [:map {:closed false}
- [:database {:optional true} [:maybe :int]]]]
+ query :- ::lib-be.schema/maybe-legacy-or-internal-query]
(run-streaming-query
(-> query
(update-in [:middleware :js-int-to-string?] (fnil identity true))
@@ -138,11 +135,11 @@
;; Support JSON-encoded query and viz settings for backwards compatibility for when downloads used to be triggered by
;; `<form>` submissions... see https://metaboat.slack.com/archives/C010L1Z4F9S/p1738003606875659
:- [:map
- [:query [:map
- {:closed false
- :decode/api (fn [x]
+ [:query [:schema
+ {:decode/api (fn [x]
(cond-> x
- (string? x) json/decode+kw))}]]
+ (string? x) json/decode))}
+ ::lib-be.schema/maybe-legacy-or-internal-query]]
[:visualization_settings {:default {}} [:map
{:closed false
:decode/api (fn [x]
@@ -155,10 +152,10 @@
mi/normalize-visualization-settings
mb.viz/norm->db)
query (-> query
- (assoc :viz-settings viz-settings)
(dissoc :constraints)
+ (assoc :viz-settings viz-settings)
(update :middleware #(-> %
- (dissoc :add-default-userland-constraints? :js-int-to-string?)
+ (select-keys [:ignore-cached-results?])
(assoc :format-rows? (or format-rows false)
:pivot? (or pivot-results false)
:csv-include-bom? (if (some? csv-include-bom) csv-include-bom false)
@@ -186,13 +183,10 @@
visibility_type :sensitive in the response."
[_route-params
_query-params
- query :- [:map {:closed false}
- [:database ms/PositiveInt]
- [:settings {:optional true} [:maybe [:map
- [:include_sensitive_fields {:optional true} :boolean]]]]]]
+ query :- ::lib-be.schema/maybe-legacy-query]
(queries/batch-fetch-query-metadata
[query]
- (when-some [include-sensitive-fields (get-in query [:settings :include_sensitive_fields])]
+ (when-some [include-sensitive-fields (get-in query [:settings :include-sensitive-fields])]
{:include-sensitive-fields? include-sensitive-fields})))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
@@ -207,25 +201,27 @@
[:database ms/PositiveInt]
[:pretty {:default true} [:maybe :boolean]]]]
(model-persistence/with-persisted-substituion-disabled
- (qp.perms/check-current-user-has-adhoc-native-query-perms query)
- (let [driver (driver.u/database->driver database)
- prettify (partial driver/prettify-native-form driver)
- compiled (qp.compile/compile-with-inline-parameters query)]
- (cond-> compiled
- pretty (update :query prettify)))))
+ (let [query (lib-be/normalize-query (dissoc query :pretty))]
+ (qp.perms/check-current-user-has-adhoc-native-query-perms query)
+ (let [driver (driver.u/database->driver database)
+ prettify (partial driver/prettify-native-form driver)
+ compiled (qp.compile/compile-with-inline-parameters (-> query
+ (dissoc :constraints :middleware)
+ lib/disable-default-limit))]
+ (cond-> compiled
+ pretty (update :query prettify))))))
(api.macros/defendpoint :post "/pivot"
:- (server/streaming-response-schema ::qp.schema/query-result)
"Generate a pivoted dataset for an ad-hoc query"
[_route-params
_query-params
- {:keys [database] :as query} :- [:map {:closed false}
- [:database ms/PositiveInt]]]
+ {:keys [database] :as query} :- ::lib-be.schema/maybe-legacy-query]
(api/read-check :model/Database database)
(let [info {:executed-by api/*current-user-id*
:context :ad-hoc}]
(qp.streaming/streaming-response [rff :api]
- (qp.pivot/run-pivot-query (assoc query
+ (qp.pivot/run-pivot-query (assoc (update query :middleware select-keys [:js-int-to-string? :ignore-cached-results?])
:constraints (qp.constraints/default-query-constraints)
:info info)
rff)
diff --git a/src/metabase/query_processor/card.clj b/src/metabase/query_processor/card.clj
index de8944d1b57..72b64e71c5e 100644
--- a/src/metabase/query_processor/card.clj
+++ b/src/metabase/query_processor/card.clj
@@ -116,8 +116,7 @@
filter-stage-added?))
lib/append-stage)
query (-> query
- ;; don't want default constraints overriding anything that's already there
- (m/dissoc-in [:middleware :add-default-userland-constraints?])
+ (dissoc :constraints :middleware)
(m/assoc-some :constraints (not-empty constraints)
:parameters (not-empty (cond-> parameters
filter-stage-added? add-stage-to-temporal-unit-parameters))
@@ -207,6 +206,15 @@
[:template-tag tag-name]
(name tag-name))))
+(defn- target-template-tag-name
+ [tag-id->name target]
+ (match/match-one target
+ [:template-tag (tag-name :guard string?)]
+ tag-name
+
+ [:template-tag (tag-ref :guard map?)]
+ (get tag-id->name (:id tag-ref))))
+
(mu/defn- validate-card-parameters
"Unless [[*allow-arbitrary-mbql-parameters*]] is truthy, check to make all supplied `parameters` actually match up
with template tags in `dataset-query` (the query for the Card with `card-id`)."
@@ -214,9 +222,12 @@
dataset-query :- [:maybe ::lib.schema/query]
parameters :- [:maybe [:ref ::lib.schema.parameter/parameters]]]
(when-not *allow-arbitrary-mbql-parameters*
- (let [template-tags (card-template-tag-parameters dataset-query)]
+ (let [template-tags (card-template-tag-parameters dataset-query)
+ tag-id->name (into {} (map (fn [[nm tag]] [(:id tag) nm]))
+ (lib/all-template-tags-map dataset-query))]
(doseq [request-parameter parameters
- :let [parameter-name (infer-parameter-name request-parameter)]]
+ :let [parameter-name (or (target-template-tag-name tag-id->name (:target request-parameter))
+ (infer-parameter-name request-parameter))]]
(let [matching-widget-type (or (get template-tags parameter-name)
(throw (ex-info (tru "Invalid parameter: Card {0} does not have a template tag named {1}."
card-id
@@ -275,7 +286,18 @@
(let [id->card-param (->> card-parameters
(map #(select-keys % [:id :type :target]))
(m/index-by :id))]
- (mapv #(merge (-> % :id id->card-param) %) parameters)))
+ (into []
+ (keep (fn [parameter]
+ (let [card-param (get id->card-param (:id parameter))
+ enriched (merge card-param parameter)
+ target (:target card-param)]
+ (if *allow-arbitrary-mbql-parameters*
+ enriched
+ (when (or target (not (:target parameter)))
+ (-> enriched
+ (dissoc :target)
+ (m/assoc-some :target target)))))))
+ parameters)))
(defn- card-read-context
"The context to use for tracking the view. Return nil if the view should not be tracked"
diff --git a/src/metabase/query_processor/middleware/fetch_source_query.clj b/src/metabase/query_processor/middleware/fetch_source_query.clj
index 27cb177c729..a8ddfcdd68c 100644
--- a/src/metabase/query_processor/middleware/fetch_source_query.clj
+++ b/src/metabase/query_processor/middleware/fetch_source_query.clj
@@ -42,6 +42,13 @@
:query x}))))]
(cons first-stage more)))
+(def ^:private qp-owned-stage-keys
+ [:persisted-info/native
+ :qp/stage-is-from-source-card
+ :qp/stage-had-source-card
+ :source-query/model?
+ :source-query/native-model?])
+
(mu/defn normalize-card-query :- ::lib.schema.metadata/card
"Convert Card's query (`:dataset-query`) to MBQL 5 as needed; splice in stage metadata and some extra keys."
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
@@ -53,7 +60,11 @@
card-id
(ddl.i/schema-name {:id (:database-id card)} (system/site-uuid))
(:table-name persisted-info)))
- (letfn [(update-stages [stages]
+ (letfn [(clear-qp-owned-keys [query]
+ (lib.walk/walk query
+ (fn [_query _path-type _path stage-or-join]
+ (apply dissoc stage-or-join qp-owned-stage-keys))))
+ (update-stages [stages]
(let [stages (fix-mongodb-first-stage stages)
stages (for [stage stages]
;; This is for detecting circular refs below, and is later used as part of
@@ -80,6 +91,7 @@
;; a card getting joined twice creates duplicate UUID errors!
;; This safely re-rolls all the `:lib/uuid`s on the card's query so they won't collide.
lib.util/fresh-uuids-preserving-aggregation-refs
+ clear-qp-owned-keys
(update :stages update-stages)))]
(update card :dataset-query update-query))))
diff --git a/src/metabase/query_processor/middleware/permissions.clj b/src/metabase/query_processor/middleware/permissions.clj
index 49f71f12e1a..37a26a1d991 100644
--- a/src/metabase/query_processor/middleware/permissions.clj
+++ b/src/metabase/query_processor/middleware/permissions.clj
@@ -5,6 +5,7 @@
[metabase.audit-app.core :as audit]
[metabase.lib.core :as lib]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
+ [metabase.lib.options :as lib.options]
[metabase.lib.schema :as lib.schema]
[metabase.lib.walk :as lib.walk]
[metabase.permissions.core :as perms]
@@ -12,6 +13,8 @@
[metabase.query-permissions.core :as query-perms]
[metabase.query-processor.schema :as qp.schema]
^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
+ [metabase.query-processor.util :as qp.util]
+ [metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -71,6 +74,12 @@
[query]
(dissoc query :query-permissions/perms))
+(defenterprise remove-impersonation-keys
+ "OSS implementation of `remove-impersonation-keys`. Connection impersonation is EE-only, so there is nothing to strip."
+ metabase-enterprise.impersonation.middleware
+ [query]
+ query)
+
(defn remove-source-card-keys
"Pre-processing middleware. Removes any instances of the `:qp/stage-is-from-source-card` key which is added by the
fetch-source-query middleware when source cards are resolved in a query. Since we rely on this for permission enforcement,
@@ -81,15 +90,51 @@
(fn [_query _path-type _path stage-or-join]
(dissoc stage-or-join :qp/stage-is-from-source-card))))
-(defn remove-sandboxed-table-keys
- "Pre-processing middleware. Removes any instances of the `:query-permissions/sandboxed-table` key which is added by the
- row-level-restriction middleware when sandboxes are resolved in a query. Since we rely on this for permission
- enforcement, we want to disallow users from passing it in themselves (like the functions above)."
+(def ^:private allowed-stage-keys
+ #{:persisted-info/native
+ :qp/stage-is-from-source-card
+ :qp/stage-had-source-card
+ :source-query/model?
+ :source-query/native-model?
+ :query-permissions/referenced-card-ids})
+
+(defn- allowed-clause-key?
+ [k]
+ (case (namespace k)
+ (nil "lib") true
+ false))
+
+(defn- allowed-stage-key?
+ [k]
+ (or (allowed-clause-key? k)
+ (contains? allowed-stage-keys k)))
+
+(defn- remove-keys
+ [m allowed?]
+ (reduce-kv (fn [m k _v]
+ (cond-> m
+ (not (allowed? k)) (dissoc k)))
+ m
+ m))
+
+(defn remove-namespaced-options
+ "Pre-processing middleware. Strip namespaced keys that are not in the allow-list from every stage, join, and clause
+ options map in `query`."
[query]
- (lib.walk/walk
- query
- (fn [_query _path-type _path stage-or-join]
- (dissoc stage-or-join :query-permissions/sandboxed-table))))
+ (-> query
+ (lib.walk/walk
+ (fn [_query _path-type _path stage-or-join]
+ (remove-keys stage-or-join allowed-stage-key?)))
+ (lib.walk/walk-clauses
+ (fn [_query _path-type _path clause]
+ (when-let [options (lib.options/options clause)]
+ (lib.options/with-options clause (remove-keys options allowed-clause-key?)))))))
+
+(mu/defn record-referenced-card-ids :- ::lib.schema/query
+ "Pre-processing middleware. Record the source-card IDs referenced by `query` under the
+ `:query-permissions/referenced-card-ids` key."
+ [query :- ::lib.schema/query]
+ (u/assoc-dissoc query :query-permissions/referenced-card-ids (lib/all-source-card-ids-recursive query)))
(defn remove-persisted-info-native-keys
"Pre-processing middleware. Removes any `:persisted-info/native` keys from the query. This key is populated later by
@@ -107,11 +152,14 @@
(if (:lib/type query)
(recur (lib/->legacy-MBQL query))
(let [{database-id :database :as outer-query} query]
+ (when (and (= audit/audit-db-id database-id)
+ (or (qp.util/userland-query? outer-query)
+ *param-values-query*
+ *current-user-id*))
+ (check-audit-db-permissions outer-query))
(when *current-user-id*
(log/tracef "Checking query permissions. Current user permissions = %s"
(pr-str (perms/permissions-for-user *current-user-id*)))
- (when (= audit/audit-db-id database-id)
- (check-audit-db-permissions outer-query))
(check-query-does-not-access-inactive-tables outer-query)
(let [required-perms (query-perms/required-perms-for-query outer-query :already-preprocessed? true)
source-card-ids (:card-ids required-perms)]
@@ -123,7 +171,13 @@
;; check that the user has permission to read this card
*card-id*
(do (query-perms/check-card-read-perms database-id *card-id*)
- (query-perms/check-card-result-metadata-data-perms database-id *card-id*))
+ (query-perms/check-card-result-metadata-data-perms database-id *card-id*)
+ (when-not (query-perms/has-perm-for-query? outer-query :perms/view-data required-perms)
+ (throw (query-perms/perms-exception required-perms)))
+ (doseq [card-id source-card-ids
+ :when (not= card-id *card-id*)]
+ (query-perms/check-card-read-perms database-id card-id)
+ (query-perms/check-card-result-metadata-data-perms database-id card-id)))
;; set when querying for field values of dashboard filters, which only require
;; collection perms for the dashboard and not ad-hoc query perms
diff --git a/src/metabase/query_processor/middleware/process_userland_query.clj b/src/metabase/query_processor/middleware/process_userland_query.clj
index 9c1b64c60f5..a2e25fbbd6b 100644
--- a/src/metabase/query_processor/middleware/process_userland_query.clj
+++ b/src/metabase/query_processor/middleware/process_userland_query.clj
@@ -15,6 +15,7 @@
[metabase.batch-processing.core :as grouper]
[metabase.events.core :as events]
[metabase.lib.computed :as lib.computed]
+ [metabase.lib.core :as lib]
[metabase.queries.models.query :as query]
[metabase.query-processor.middleware.enterprise :as qp.middleware.enterprise]
[metabase.query-processor.schema :as qp.schema]
@@ -156,34 +157,37 @@
parameters :parameters
:as query} :- ::qp.schema/any-query]
{:pre [(bytes? query-hash)]}
- (let [json-query (if original-query
- (-> original-query
- (dissoc :info)
- (assoc :was-pivot true))
- (cond-> (dissoc query :info)
- (empty? (:parameters query)) (dissoc :parameters)))]
- {:database_id database-id
- :executor_id executed-by
- :action_id action-id
- :card_id card-id
- :dashboard_id dashboard-id
- :transform_id transform-id
- :lens_id lens-id
- :lens_params lens-params
- :pulse_id pulse-id
- :context context
- :hash query-hash
- :parameterized (and (boolean (seq parameters))
- (every? #(some? (:value %)) parameters))
- :native (= (keyword query-type) :native)
- :json_query json-query
- :tenant_id (:tenant_id @api/*current-user*)
- :parameters (when (and (seq parameters) (analytics.settings/analytics-pii-retention-enabled))
- (json/encode parameters))
- :started_at (t/zoned-date-time)
- :running_time 0
- :result_rows 0
- :start_time_millis (System/currentTimeMillis)}))
+ (letfn [(->json-query [q]
+ (cond-> (dissoc q :info)
+ (= (lib/normalized-query-type q) :mbql/query) lib/prepare-for-serialization
+ (seq (:parameters q)) (assoc :parameters (:parameters q))
+ (empty? (:parameters q)) (dissoc :parameters)))]
+ (let [json-query (if original-query
+ (assoc (->json-query original-query) :was-pivot true)
+ (->json-query query))]
+ {:database_id database-id
+ :executor_id executed-by
+ :action_id action-id
+ :card_id card-id
+ :dashboard_id dashboard-id
+ :transform_id transform-id
+ :lens_id lens-id
+ :lens_params lens-params
+ :pulse_id pulse-id
+ :context context
+ :hash query-hash
+ :parameterized (and (boolean (seq parameters))
+ (every? #(some? (:value %)) parameters))
+ :native (or (= (keyword query-type) :native)
+ (lib/native-only-query? query))
+ :json_query json-query
+ :tenant_id (:tenant_id @api/*current-user*)
+ :parameters (when (and (seq parameters) (analytics.settings/analytics-pii-retention-enabled))
+ (json/encode parameters))
+ :started_at (t/zoned-date-time)
+ :running_time 0
+ :result_rows 0
+ :start_time_millis (System/currentTimeMillis)})))
(defn- snapshot-execution-context
"Reads the postprocessing-middleware dynamic vars (`*impersonation-role*`, `*destination-database-id*`) and
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index 3b7c282a3bd..811e2ead705 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -61,9 +61,10 @@
;; ↓↓↓ PRE-PROCESSING ↓↓↓ happens from TOP TO BOTTOM
[#'normalize/normalize-preprocessing-middleware
#'qp.perms/remove-permissions-key
+ #'qp.perms/remove-impersonation-keys
#'qp.perms/remove-source-card-keys
- #'qp.perms/remove-sandboxed-table-keys
#'qp.perms/remove-persisted-info-native-keys
+ #'qp.perms/record-referenced-card-ids
#'qp.constraints/maybe-add-default-userland-constraints
#'validate/validate-query
#'prefetch-metadata/prefetch-metadata
@@ -75,6 +76,7 @@
#'expand-macros/expand-macros
#'nest-for-pivot/nest-for-pivot
#'qp.resolve-referenced/resolve-referenced-card-resources
+ #'qp.perms/remove-namespaced-options
#'parameters/substitute-parameters
#'qp.resolve-source-table/resolve-source-tables
#'qp.auto-bucket-datetimes/auto-bucket-datetimes
@@ -85,7 +87,6 @@
;; and picks up model-level column overrides (display_name, semantic_type). #79060
#'qp.add-implicit-clauses/add-implicit-clauses
#'qp.middleware.enterprise/apply-sandboxing
- #'qp.persistence/substitute-persisted-query
#'qp.add-implicit-clauses/add-implicit-clauses ; #61398
;; this needs to be done twice, once before adding remaps (since we want to add remaps inside joins) and then again
;; after adding any implicit joins. Implicit joins do not need to get remaps since we only use them for fetching
@@ -104,6 +105,7 @@
#'qp.remove-inactive-field-refs/remove-inactive-field-refs
;; yes, this is called a second time, because we need to handle any joins that got added
#'qp.middleware.enterprise/apply-sandboxing
+ #'qp.persistence/substitute-persisted-query
#'qp.cumulative-aggregations/rewrite-cumulative-aggregations
#'qp.wrap-value-literals/wrap-value-literals
#'auto-parse-filter-values/auto-parse-filter-values
diff --git a/src/metabase/query_processor/util/relative_datetime.clj b/src/metabase/query_processor/util/relative_datetime.clj
index 21f8704145f..f18d3f2197a 100644
--- a/src/metabase/query_processor/util/relative_datetime.clj
+++ b/src/metabase/query_processor/util/relative_datetime.clj
@@ -40,7 +40,7 @@
:or {base-type :type/DateTimeWithTZ
database-type "timestamp"}}]
(if (use-server-side-relative-datetime? unit)
- (h2x/cast database-type (relative-datetime-sql-str unit amount (or effective-type base-type)))
+ (h2x/maybe-cast database-type (relative-datetime-sql-str unit amount (or effective-type base-type)))
((-> 'metabase.driver.sql.query-processor/->honeysql
requiring-resolve
var-get
diff --git a/src/metabase/query_processor/writeback.clj b/src/metabase/query_processor/writeback.clj
index b018b5badf0..341eafc86f1 100644
--- a/src/metabase/query_processor/writeback.clj
+++ b/src/metabase/query_processor/writeback.clj
@@ -2,6 +2,7 @@
"Code for executing writeback queries."
(:require
[metabase.driver :as driver]
+ [metabase.driver.settings :as driver.settings]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.schema :as lib.schema]
@@ -53,13 +54,14 @@
(mu/defn execute-write-query!
"Execute an writeback query (which currently has to be an MBQL 4 native query) from an action."
[query :- ::lib.schema/native-only-query]
- (qp.setup/with-qp-setup [query (assoc query :impersonation/allow-write? true)]
- (let [query (qp.preprocess/preprocess query)]
- ;; make sure this is a native query.
- (when-not (lib/native-only-query? query)
- (throw (ex-info (tru "Only native queries can be executed as write queries.")
- {:type qp.error-type/invalid-query, :status-code 400, :query query})))
- ((writeback-qp) query (constantly conj)))))
+ (binding [driver.settings/*impersonation-allow-write?* true]
+ (qp.setup/with-qp-setup [query query]
+ (let [query (qp.preprocess/preprocess query)]
+ ;; make sure this is a native query.
+ (when-not (lib/native-only-query? query)
+ (throw (ex-info (tru "Only native queries can be executed as write queries.")
+ {:type qp.error-type/invalid-query, :status-code 400, :query query})))
+ ((writeback-qp) query (constantly conj))))))
(mu/defn execute-write-sql!
"Execute a write query in SQL against a database given by `db-id`."
diff --git a/src/metabase/request/cookies.clj b/src/metabase/request/cookies.clj
index 2ea3edb76b0..a1a0586246a 100644
--- a/src/metabase/request/cookies.clj
+++ b/src/metabase/request/cookies.clj
@@ -127,7 +127,10 @@
;; Disallow permanent cookies if MB_SESSION_COOKIES is set
false
;; Otherwise check whether the user selected "remember me" during login
- (get-in request [:body :remember])))
+ (let [body (:body request)]
+ (if (map? body)
+ (or (get body "remember") (get body :remember))
+ false))))
(mu/defn set-session-cookies
"Add the appropriate cookies to the `response` for the Session."
diff --git a/src/metabase/request/current.clj b/src/metabase/request/current.clj
index 38e420426f1..2f83eef2f6d 100644
--- a/src/metabase/request/current.clj
+++ b/src/metabase/request/current.clj
@@ -77,9 +77,7 @@
remote-addr
header-ip-address)]
(some-> source-address
- ;; first IP (if there are multiple) is the actual client -- see
- ;; https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
(str/split #"\s*,\s*")
- first
+ last
;; strip out non-ip-address characters like square brackets which we get sometimes
(str/replace #"[^0-9a-fA-F.:]" ""))))
diff --git a/src/metabase/revisions/api.clj b/src/metabase/revisions/api.clj
index 5e1509aa4dd..f16968c6b1c 100644
--- a/src/metabase/revisions/api.clj
+++ b/src/metabase/revisions/api.clj
@@ -1,7 +1,12 @@
(ns metabase.revisions.api
(:require
+ [clojure.set :as set]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
+ [metabase.parameters.params :as params]
+ [metabase.queries.core :as queries]
[metabase.query-permissions.core :as query-perms]
[metabase.revisions.models.revision :as revision]
[metabase.util.malli.schema :as ms]
@@ -30,6 +35,12 @@
(t2.model/resolve-model model)
[model (t2/select-one model :id id)]))
+(defn- visible-revisions
+ [model instance revisions]
+ (if (= model :model/Transform)
+ (filter #(mi/can-read? (merge instance (:object %))) revisions)
+ revisions))
+
;; 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
;;
@@ -42,7 +53,65 @@
[:entity Entity]]]
(let [[model instance] (model-and-instance entity id)]
(when (api/read-check instance)
- (revision/revisions+details model id))))
+ (visible-revisions model instance (revision/revisions+details model id)))))
+
+(defn- dashcard-card-ids
+ [dashcard]
+ (cons (:card_id dashcard) (:series dashcard)))
+
+(defn- revision-card-references
+ [revision]
+ (let [{:keys [cards parameters]} (:object revision)]
+ (into (set (queries/values-source-card-ids parameters))
+ (comp (mapcat dashcard-card-ids) (filter pos-int?))
+ cards)))
+
+(defn- stored-card-references
+ [model id]
+ (let [parameter-cards (set (t2/select-fn-vec :card_id :model/ParameterCard
+ :parameterized_object_type (if (= model :model/Dashboard)
+ "dashboard"
+ "card")
+ :parameterized_object_id id))]
+ (if (= model :model/Dashboard)
+ (into parameter-cards
+ (concat (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id id)
+ (t2/select-fn-vec :card_id :model/DashboardCardSeries
+ {:where [:in :dashboardcard_id
+ ^:allow-subquery {:select [:id]
+ :from [(t2/table-name :model/DashboardCard)]
+ :where [:= :dashboard_id id]}]})))
+ parameter-cards)))
+
+(defn- revision-parameter-field-ids
+ [model revision]
+ (let [{:keys [cards parameters dataset_query]} (:object revision)
+ resolve-target (fn [target query]
+ (when target
+ (params/param-target->field-id target {:dataset_query query})))]
+ (case model
+ :model/Card
+ (into [] (keep #(resolve-target (:target %) dataset_query)) parameters)
+
+ :model/Dashboard
+ (let [mappings (for [dashcard cards
+ mapping (:parameter_mappings dashcard)]
+ mapping)
+ card-ids (into #{} (keep :card_id) mappings)
+ card-id->query (when (seq card-ids)
+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))]
+ (into [] (keep (fn [{:keys [target card_id]}]
+ (resolve-target target (card-id->query card_id))))
+ mappings))
+
+ nil)))
+
+(defn- check-new-revision-card-references
+ [model id revision]
+ (doseq [card-id (set/difference (revision-card-references revision)
+ (stored-card-references model id))]
+ (api/read-check :model/Card card-id))
+ (query-perms/check-parameter-field-permissions (revision-parameter-field-ids model revision)))
;; 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
@@ -64,6 +133,15 @@
;; TODO -- we should be using something like `api/read-check` for this, but unfortunately the impl for Cards
;; doesn't actually check important stuff like this.
(query-perms/check-run-permissions-for-query (dissoc (get-in revision [:object :dataset_query]) :query-permissions/perms)))
+ (when (contains? #{:model/Transform :model/Segment :model/Measure} model)
+ (api/check-403 (mi/can-write? (merge instance (:object revision)))))
+ (when (contains? #{:model/Dashboard :model/Card} model)
+ (collection/check-allowed-to-change-collection instance (:object revision))
+ (when (api/column-will-change? :dashboard_id instance (:object revision))
+ (doseq [dashboard-id (keep identity [(:dashboard_id instance)
+ (:dashboard_id (:object revision))])]
+ (api/write-check :model/Dashboard dashboard-id)))
+ (check-new-revision-card-references model id revision))
;; ok, we're g2g
(revision/revert!
{:entity model
@@ -84,5 +162,5 @@
(assert (keyword? model))
;; Ensure the model namespace is loaded before using it
(t2.model/resolve-model model)
- (api/read-check model id)
- (revision/revisions+details model id)))
+ (let [instance (api/read-check model id)]
+ (visible-revisions model instance (revision/revisions+details model id)))))
diff --git a/src/metabase/revisions/impl/card.clj b/src/metabase/revisions/impl/card.clj
index 0ad5a76644c..9f38c0a1fc3 100644
--- a/src/metabase/revisions/impl/card.clj
+++ b/src/metabase/revisions/impl/card.clj
@@ -1,11 +1,15 @@
(ns metabase.revisions.impl.card
(:require
[metabase.queries.core :as queries]
- [metabase.revisions.models.revision :as revision]))
+ [metabase.revisions.models.revision :as revision]
+ [toucan2.core :as t2]))
(def ^:private excluded-columns-for-card-revision
#{:cache_invalidated_at
:created_at
+ :embedding_params
+ :embedding_type
+ :enable_embedding
:creator_id
:dimension_mappings
:dimensions
@@ -33,8 +37,14 @@
(contains? serialized-card :dataset) (-> (dissoc :dataset)
(assoc :type (if (:dataset serialized-card) :model :question)))
;; Add the default `:card_schema` if it's missing.
- (not (:card_schema serialized-card)) (assoc :card_schema queries/starting-card-schema-version))]
- ((get-method revision/revert-to-revision! :default) model id user-id serialized-card)))
+ (not (:card_schema serialized-card)) (assoc :card_schema queries/starting-card-schema-version))
+ restored (apply dissoc serialized-card excluded-columns-for-card-revision)]
+ (queries/check-new-parameter-source-card-permissions "card" id (:parameters restored))
+ (queries/maybe-unverify! (t2/hydrate (t2/select-one :model/Card :id id)
+ [:moderation_reviews :moderator_details])
+ restored
+ {:id user-id})
+ ((get-method revision/revert-to-revision! :default) model id user-id restored)))
(defn- model?
"Returns true if `card` is a model."
diff --git a/src/metabase/revisions/impl/dashboard.clj b/src/metabase/revisions/impl/dashboard.clj
index 43293d25f84..9f33c020471 100644
--- a/src/metabase/revisions/impl/dashboard.clj
+++ b/src/metabase/revisions/impl/dashboard.clj
@@ -6,6 +6,7 @@
[metabase.dashboards.models.dashboard :as dashboard]
[metabase.dashboards.models.dashboard-card :as dashboard-card]
[metabase.dashboards.models.dashboard-tab :as dashboard-tab]
+ [metabase.queries.core :as queries]
[metabase.revisions.models.revision :as revision]
[metabase.util :as u]
[metabase.util.i18n :refer [deferred-tru deferred-trun]]
@@ -18,7 +19,7 @@
;; > The position this Dashboard should appear in the Dashboards list,
;; lower-numbered positions appearing before higher numbered ones.
;; TODO: querying on stats we don't have any dashboard that has a position, maybe we could just drop it?
- :public_uuid :made_public_by_id
+ :public_uuid :made_public_by_id :enable_embedding :embedding_params :embedding_type
:position :initially_published_at :view_count
:last_viewed_at})
@@ -46,9 +47,11 @@
(defn- revert-dashcards
[dashboard-id serialized-cards]
- (let [current-cards (t2/select-fn-vec #(apply dissoc (t2.realize/realize %) excluded-columns-for-dashcard-revision)
- :model/DashboardCard
- :dashboard_id dashboard-id)
+ (let [current-cards (->> (t2/hydrate (t2/select :model/DashboardCard :dashboard_id dashboard-id) :series)
+ (mapv (fn [dashcard]
+ (-> (apply dissoc (t2.realize/realize dashcard)
+ excluded-columns-for-dashcard-revision)
+ (assoc :series (mapv :id (:series dashcard)))))))
id->current-card (zipmap (map :id current-cards) current-cards)
{:keys [to-create to-update to-delete]} (u/row-diff current-cards serialized-cards)]
(when (seq to-delete)
@@ -101,8 +104,10 @@
;; Clean invalid parameter card references before reverting (cards may have been deleted since the revision)
(let [cleaned-parameters (clean-invalid-parameter-card-references (or (:parameters serialized-dashboard) []))
serialized-dashboard (assoc serialized-dashboard :parameters cleaned-parameters)]
+ (queries/check-new-parameter-source-card-permissions "dashboard" dashboard-id cleaned-parameters)
;; Update the dashboard description / name / permissions
- ((get-method revision/revert-to-revision! :default) model dashboard-id user-id (dissoc serialized-dashboard :cards :tabs))
+ ((get-method revision/revert-to-revision! :default) model dashboard-id user-id
+ (apply dissoc serialized-dashboard :cards :tabs excluded-columns-for-dashboard-revision))
;; Now update the tabs and cards as needed
(let [serialized-dashcards (:cards serialized-dashboard)
current-tabs (t2/select-fn-vec #(dissoc (t2.realize/realize %) :created_at :updated_at :entity_id :dashboard_id)
diff --git a/src/metabase/revisions/models/revision.clj b/src/metabase/revisions/models/revision.clj
index 872a115a952..d4d39b86c6c 100644
--- a/src/metabase/revisions/models/revision.clj
+++ b/src/metabase/revisions/models/revision.clj
@@ -239,15 +239,20 @@
model-name (name entity)
serialized-instance (t2/select-one-fn :object :model/Revision :model model-name :model_id id :id revision-id)]
(t2/with-transaction [_conn]
- ;; Do the reversion of the object
- (revert-to-revision! entity id user-id serialized-instance)
- ;; Push a new revision to record this change
- (let [last-revision (t2/select-one :model/Revision :model model-name, :model_id id, {:order-by [[:id :desc]]})
- new-revision (first (t2/insert-returning-instances! :model/Revision
- :model model-name
- :model_id id
- :user_id user-id
- :object serialized-instance
- :is_creation false
- :is_reversion true))]
- (add-revision-details entity new-revision last-revision)))))
+ (let [already-in-target-state? (= serialized-instance
+ (t2/select-one-fn :object :model/Revision
+ :model model-name :model_id id {:order-by [[:id :desc]]}))]
+ ;; Do the reversion of the object
+ (revert-to-revision! entity id user-id serialized-instance)
+ ;; Push a new revision to record this change
+ (let [last-revision (t2/select-one :model/Revision :model model-name, :model_id id, {:order-by [[:id :desc]]})]
+ (if already-in-target-state?
+ last-revision
+ (let [new-revision (first (t2/insert-returning-instances! :model/Revision
+ :model model-name
+ :model_id id
+ :user_id user-id
+ :object serialized-instance
+ :is_creation false
+ :is_reversion true))]
+ (add-revision-details entity new-revision last-revision))))))))
diff --git a/src/metabase/revisions/models/revision/diff.clj b/src/metabase/revisions/models/revision/diff.clj
index b666c87506e..08272c27964 100644
--- a/src/metabase/revisions/models/revision/diff.clj
+++ b/src/metabase/revisions/models/revision/diff.clj
@@ -1,10 +1,18 @@
(ns metabase.revisions.models.revision.diff
(:require
[clojure.data :as data]
+ [metabase.models.interface :as mi]
[metabase.util.i18n :refer [deferred-tru]]
[metabase.util.match :as match]
[toucan2.core :as t2]))
+(defn- readable-name
+ [model id]
+ (when id
+ (when-let [instance (t2/select-one model :id id)]
+ (when (mi/can-read? instance)
+ (:name instance)))))
+
(defn- match-1 [k v1 v2 identifier]
(match/match-one [k v1 v2]
[:name _ _]
@@ -58,17 +66,17 @@
[:collection_id nil coll-id]
(deferred-tru "moved {0} to {1}" identifier (if coll-id
- (or (t2/select-one-fn :name 'Collection coll-id)
+ (or (readable-name :model/Collection coll-id)
(str "#" coll-id))
(deferred-tru "Our analytics")))
[:collection_id (prev-coll-id :guard int?) coll-id]
(deferred-tru "moved {0} from {1} to {2}"
identifier
- (or (t2/select-one-fn :name 'Collection prev-coll-id)
+ (or (readable-name :model/Collection prev-coll-id)
(str "#" prev-coll-id))
(if coll-id
- (or (t2/select-one-fn :name 'Collection coll-id)
+ (or (readable-name :model/Collection coll-id)
(str "#" coll-id))
(deferred-tru "Our analytics")))
@@ -103,12 +111,12 @@
[:dashboard_id v1 v2]
(cond
(and v1 v2) (deferred-tru "moved from dashboard {0} to {1}"
- (t2/select-one-fn :name :model/Dashboard :id v1)
- (t2/select-one-fn :name :model/Dashboard :id v2))
+ (readable-name :model/Dashboard v1)
+ (readable-name :model/Dashboard v2))
(nil? v1) (deferred-tru "moved this question into {0}"
- (t2/select-one-fn :name :model/Dashboard :id v2))
+ (readable-name :model/Dashboard v2))
(nil? v2) (deferred-tru "moved this question from {0}"
- (t2/select-one-fn :name :model/Dashboard :id v1)))
+ (readable-name :model/Dashboard v1)))
[:width v1 v2]
(if (and v1 v2)
diff --git a/src/metabase/search/appdb/core.clj b/src/metabase/search/appdb/core.clj
index bff578c4fc6..b23f5370344 100644
--- a/src/metabase/search/appdb/core.clj
+++ b/src/metabase/search/appdb/core.clj
@@ -84,9 +84,9 @@
true (sql.helpers/where
[:or
[:= :search_index.model nil]
- [:!= :search_index.model [:inline "table"]]
+ [:!= :search_index.model "table"]
[:and
- [:= :search_index.model [:inline "table"]]
+ [:= :search_index.model "table"]
clause]]))))
(defn add-collection-join-and-where-clauses
diff --git a/src/metabase/search/appdb/index.clj b/src/metabase/search/appdb/index.clj
index d7e27b0dc01..6cb2bcfc473 100644
--- a/src/metabase/search/appdb/index.clj
+++ b/src/metabase/search/appdb/index.clj
@@ -122,17 +122,17 @@
:where [:and
[:= :ist.table_schema :%current_schema]
[:or
- [:like [:lower :ist.table_name] [:inline "search\\_index\\_\\_%"]]
+ [:like [:lower :ist.table_name] "search\\_index\\_\\_%"]
;; legacy table names
[:in [:lower :ist.table_name]
- (mapv #(vector :inline %) ["search_index" "search_index_next" "search_index_retired"])]]
+ ["search_index" "search_index_next" "search_index_retired"]]]
;; Exclude temp tables — they are managed by with-temp-index-table
- [:not-like [:lower :ist.table_name] [:inline "%\\_temp"]]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/SearchIndexMetadata) :sim]]
- :where [:and
- [:= :sim.engine [:inline "appdb"]]
- [:= [:lower :sim.index_name] [:lower :ist.table_name]]]}]]]})))
+ [:not-like [:lower :ist.table_name] "%\\_temp"]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/SearchIndexMetadata) :sim]]
+ :where [:and
+ [:= :sim.engine "appdb"]
+ [:= [:lower :sim.index_name] [:lower :ist.table_name]]]}]]]})))
(defn- delete-obsolete-tables! []
;; Delete metadata around indexes that are no longer needed.
@@ -173,7 +173,7 @@
[:legacy_input :text :not-null]
;; useful for tracking the speed and age of the index
[:created_at :timestamp-with-time-zone
- [:default [:raw "CURRENT_TIMESTAMP"]]
+ [:default ^:allow-raw-sql [:raw "CURRENT_TIMESTAMP"]]
:not-null]
[:updated_at :timestamp-with-time-zone :not-null]]
(keep (fn [[k t]]
diff --git a/src/metabase/search/appdb/scoring.clj b/src/metabase/search/appdb/scoring.clj
index e6f0311f0f6..712d6529c51 100644
--- a/src/metabase/search/appdb/scoring.clj
+++ b/src/metabase/search/appdb/scoring.clj
@@ -34,7 +34,7 @@
(defn- view-count-expr [percentile]
(let [views (view-count-percentiles percentile)
cases (for [[sm v] views]
- [[:= :search_index.model [:inline (name sm)]] (max (or v 0) 1)])]
+ [[:= :search_index.model (name sm)] (max (or v 0) 1)])]
(search.scoring/size :view_count (if (seq cases)
(into [:case] cat cases)
1))))
diff --git a/src/metabase/search/appdb/specialization/postgres.clj b/src/metabase/search/appdb/specialization/postgres.clj
index 2aa6eb2e353..5d61a52ac93 100644
--- a/src/metabase/search/appdb/specialization/postgres.clj
+++ b/src/metabase/search/appdb/specialization/postgres.clj
@@ -3,10 +3,11 @@
[clojure.string :as str]
[metabase.search.appdb.specialization.api :as specialization]
[metabase.search.util :as search.util]
+ [metabase.util.honey-sql-2 :as h2x]
[toucan2.core :as t2]))
(defmethod specialization/table-schema :postgres [base-schema]
- (into [[:id :bigint [:primary-key] [:raw "GENERATED BY DEFAULT AS IDENTITY"]]
+ (into [[:id :bigint [:primary-key] ^:allow-raw-sql [:raw "GENERATED BY DEFAULT AS IDENTITY"]]
[:search_vector :tsvector :not-null]
[:with_native_query_vector :tsvector :not-null]]
base-schema))
@@ -41,12 +42,12 @@
{:select select-items
:from [[active-table :search_index]]
;; Using a join allows us to share the query expression between our SELECT and WHERE clauses.
- :join [[[:raw "to_tsquery('"
- (search.util/tsv-language) "', "
- [:lift (search.util/to-tsquery-expr search-term)] ")"]
+ :join [[[:to_tsquery ^:allow-raw-sql [:inline (search.util/tsv-language)]
+ [:lift (search.util/to-tsquery-expr search-term)]]
:query] [:= 1 1]]
:where (if (str/blank? search-term)
[:= [:inline 1] [:inline 1]]
+ ^:allow-raw-sql
[:raw
(str
(if (:search-native-query search-ctx)
@@ -89,11 +90,11 @@
(defmethod specialization/text-score :postgres
[]
- [:ts_rank [:inline ts-rank-weights] :search_vector :query [:inline ts-rank-normalization]])
+ [:ts_rank ^:allow-raw-sql [:inline ts-rank-weights] :search_vector :query [:inline ts-rank-normalization]])
(defmethod specialization/view-count-percentile-query :postgres
[index-table p-value]
- (let [expr [:raw "percentile_cont(" [:lift p-value] ") WITHIN GROUP (ORDER BY view_count)"]]
+ (let [expr [::h2x/percentile-cont :view_count p-value]]
{:select [:search_index.model [expr :vcp]]
:from [[index-table :search_index]]
:group-by [:search_index.model]
diff --git a/src/metabase/search/filter.clj b/src/metabase/search/filter.clj
index 35012dafa68..1a4a3c2285f 100644
--- a/src/metabase/search/filter.clj
+++ b/src/metabase/search/filter.clj
@@ -18,7 +18,10 @@
(defn- remove-if-falsey [m k]
(if (m k) m (dissoc m k)))
-(defn- visible-to? [search-ctx {:keys [visibility] :as _spec}]
+(defn visible-to?
+ "Whether the search-model described by `spec` may be returned to the user described by `search-ctx`, per the spec's
+ `:visibility`."
+ [search-ctx {:keys [visibility] :as _spec}]
(case visibility
:all true
:app-user (not (search.permissions/sandboxed-or-impersonated-user? search-ctx))
@@ -117,7 +120,7 @@
(if (premium-features/has-feature? :library)
collection-filter
[:and
- [:not= :search_index.model [:inline "table"]]
+ [:not= :search_index.model "table"]
collection-filter])))
(defn personal-collections-where-clause
@@ -145,13 +148,13 @@
;; query on instances with many users.
;; Correlated subquery: assumes the outer query has `:collection` as FROM or LEFT JOIN.
(let [descendant-of-personal-collection
- [:exists {:select [[[:inline 1]]]
- :from [[:collection :pc]]
- :where [:and
- [:not= :pc.personal_owner_id nil]
- [:= :pc.location "/"]
- [:like :collection.location
- [:concat (h2x/literal "/") :pc.id (h2x/literal "/%")]]]}]]
+ [:exists ^:allow-subquery {:select [[[:inline 1]]]
+ :from [[:collection :pc]]
+ :where [:and
+ [:not= :pc.personal_owner_id nil]
+ [:= :pc.location "/"]
+ [:like :collection.location
+ [:concat (h2x/literal "/") :pc.id (h2x/literal "/%")]]]}]]
(case filter-type
"only"
[:or
@@ -180,7 +183,7 @@
[:= [:inline 0] [:inline 1]])))
([search-context model-col source-type-col]
[:or
- [:!= model-col [:inline "transform"]]
+ [:!= model-col "transform"]
(transform-source-type-where-clause search-context source-type-col)]))
(defn filter-clauses
diff --git a/src/metabase/search/in_place/filter.clj b/src/metabase/search/in_place/filter.clj
index af667729ed2..27b5c35badb 100644
--- a/src/metabase/search/in_place/filter.clj
+++ b/src/metabase/search/in_place/filter.clj
@@ -21,14 +21,15 @@
[metabase.search.filter :as search.filter]
[metabase.search.in-place.util :as search.util]
[metabase.search.permissions :as search.permissions]
+ [metabase.search.spec :as search.spec]
[metabase.util.date-2 :as u.date]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu])
(:import
(java.time LocalDate)))
-(def ^:private true-clause [:inline [:= 1 1]])
-(def ^:private false-clause [:inline [:= 0 1]])
+(def ^:private true-clause [:= [:inline 1] [:inline 1]])
+(def ^:private false-clause [:= [:inline 0] [:inline 1]])
(def ^:private max-document-search-length
"Cap the number of characters of a document's prose-mirror body that the legacy engine LIKE-scans.
@@ -395,8 +396,12 @@
display-type
is-superuser?]} search-context
enabled-types (:enabled-transform-source-types search-context)
- feature->supported-models (feature->supported-models)]
+ feature->supported-models (feature->supported-models)
+ hidden-by-visibility (into #{}
+ (remove #(search.filter/visible-to? search-context (search.spec/spec %)))
+ models)]
(cond-> models
+ (seq hidden-by-visibility) (set/difference hidden-by-visibility)
(not is-superuser?) (disj "transform")
(empty? enabled-types) (disj "transform")
(some? collection) (set/intersection (:collection feature->supported-models))
diff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.clj
index a2b38d67e54..52d9088a21c 100644
--- a/src/metabase/search/in_place/legacy.clj
+++ b/src/metabase/search/in_place/legacy.clj
@@ -184,9 +184,9 @@
"table" clause
"search-index" [:or
[:= :search_index.model nil]
- [:!= :search_index.model [:inline "table"]]
+ [:!= :search_index.model "table"]
[:and
- [:= :search_index.model [:inline "table"]]
+ [:= :search_index.model "table"]
clause]])))))
(mu/defn add-collection-join-and-where-clauses
@@ -373,9 +373,9 @@
(def ^:private dashboardcard-count-col
"Subselect to get the count of associated DashboardCards"
- [{:select [:%count.*]
- :from [:report_dashboardcard]
- :where [:= :report_dashboardcard.card_id :card.id]}
+ [^:allow-subquery {:select [:%count.*]
+ :from [:report_dashboardcard]
+ :where [:= :report_dashboardcard.card_id :card.id]}
:dashboardcard_count])
(def ^:private table-columns
@@ -497,7 +497,7 @@
[:table.description :table_description]
[:table.collection_id :collection_id]
[[:case [:and [:= :table.collection_id nil] [:= :table.is_published true]]
- [:inline "Our analytics"]
+ "Our analytics"
:else
:collection.name] :collection_name]
[:collection.authority_level :collection_authority_level]
@@ -555,9 +555,9 @@
;; from the collection picker or when browsing, so it shouldn't be visible in search either.
(when (:include-dashboard-questions? search-ctx)
[:exists
- {:select 1
- :from [:report_dashboardcard]
- :where [:= :card_id :card.id]}])])
+ ^:allow-subquery {:select 1
+ :from [:report_dashboardcard]
+ :where [:= :card_id :card.id]}])])
(add-collection-join-and-where-clauses "card" search-ctx)
(add-card-db-id-clause (:table-db-id search-ctx))
(with-last-editing-info "card")
@@ -693,10 +693,12 @@
(assoc search-ctx :models search.config/all-models))]
(search-query-for-model model search-ctx)))
{:keys [ctes queries]} (extract-and-hoist-ctes raw-queries)
- nested-queries (mapv #(hash-map :nest (sql.helpers/limit % 1)) queries)
+ nested-queries (mapv #(vary-meta (hash-map :nest (vary-meta (sql.helpers/limit % 1) assoc :allow-subquery true))
+ assoc :allow-subquery true)
+ queries)
query (when (pos-int? (count nested-queries))
(cond-> {:select [:*]
- :from [[{:union-all nested-queries} :dummy_alias]]}
+ :from [[^:allow-subquery {:union-all nested-queries} :dummy_alias]]}
(seq ctes) (assoc :with ctes)))]
(into #{} (map :model) (some-> query mdb/query))))
@@ -719,9 +721,10 @@
:let [query (search-query-for-model model search-ctx)]
:when (seq query)]
query))
- {:keys [ctes queries]} (extract-and-hoist-ctes model-queries)]
+ {:keys [ctes queries]} (extract-and-hoist-ctes model-queries)
+ queries (mapv #(vary-meta % assoc :allow-subquery true) queries)]
(cond-> {:select [:*]
- :from [[{:union-all queries} :alias_is_required_by_sql_but_not_needed_here]]
+ :from [[^:allow-subquery {:union-all queries} :alias_is_required_by_sql_but_not_needed_here]]
:order-by order-clause
:limit search.config/*db-max-results*}
(seq ctes) (assoc :with ctes))))))
diff --git a/src/metabase/search/ingestion.clj b/src/metabase/search/ingestion.clj
index 2785c75af43..c2910acc309 100644
--- a/src/metabase/search/ingestion.clj
+++ b/src/metabase/search/ingestion.clj
@@ -177,7 +177,7 @@
[:attrs :render-terms])
fn-selects))
:from [[(t2/table-name (:model spec)) :this]]
- :where (:where spec [:inline [:= 1 1]])
+ :where (:where spec [:= [:inline 1] [:inline 1]])
:left-join (when (:joins spec)
(into []
cat
diff --git a/src/metabase/search/scoring.clj b/src/metabase/search/scoring.clj
index b30880adb16..f11a755a32d 100644
--- a/src/metabase/search/scoring.clj
+++ b/src/metabase/search/scoring.clj
@@ -35,10 +35,10 @@
([expr] (normalize-text-expr (mdb/db-type) expr))
([db-type expr]
;; Replace commas with a space, not nothing, so `a,b` doesn't collapse into `ab`.
- (let [stripped [:replace [:lower expr] [:inline ","] [:inline " "]]
+ (let [stripped [:replace [:lower expr] "," " "]
collapsed (case db-type
- :postgres [:regexp_replace stripped [:inline "\\s+"] [:inline " "] [:inline "g"]]
- :h2 [:regexp_replace stripped [:inline "\\s+"] [:inline " "]])]
+ :postgres [:regexp_replace stripped "\\s+" " " "g"]
+ :h2 [:regexp_replace stripped "\\s+" " "])]
[:trim collapsed])))
(defn normalize-text
@@ -74,9 +74,9 @@
;; Use seconds for granularity in the fraction.
(if (= :mysql db-type)
[:coalesce
- [[:timestampdiff [:raw "SECOND"] from-column to-column]]
+ [[:timestampdiff ^:allow-raw-sql [:raw "SECOND"] from-column to-column]]
[:* ceiling (double seconds-in-a-day)]]
- [[:raw "EXTRACT(epoch FROM (" [:- to-column from-column] [:raw "))"]]])
+ [[::h2x/extract :epoch [:- to-column from-column]]])
[:inline (double seconds-in-a-day)]]]
[:inline 0]]
ceiling])))
@@ -91,9 +91,10 @@
"Expression to select the `:user-recency` timestamp for the `current-user-id`."
[{:keys [current-user-id]}]
(let [one-day-ago (h2x/add-interval-honeysql-form (mdb/db-type) :%now -1 :day)]
+ ^:allow-subquery
{:select [[[:case
;; Transforms get a hardcoded 1-day last_viewed_at because we don't track views on them
- [:= :search_index.model [:inline "transform"]]
+ [:= :search_index.model "transform"]
one-day-ago
:else
[:max :recent_views.timestamp]]
@@ -104,8 +105,8 @@
[:= (cast-to-text :recent_views.model_id) :search_index.model_id]
[:= :recent_views.model
[:case
- [:= :search_index.model [:inline "dataset"]] [:inline "card"]
- [:= :search_index.model [:inline "metric"]] [:inline "card"]
+ [:= :search_index.model "dataset"] "card"
+ [:= :search_index.model "metric"] "card"
:else :search_index.model]]]}))
(defn library-score-expr
@@ -116,7 +117,7 @@
[:case
(into [:or]
(for [t (sort collection/library-collection-types)]
- [:= :root_collection_type [:inline t]]))
+ [:= :root_collection_type t]))
[:inline 1]
:else [:inline 0]])
@@ -126,9 +127,9 @@
[search-ctx]
(let [tier-weight #(or (search.config/scorer-param search-ctx :data-layer %) 0)]
[:case
- [:= :data_layer [:inline "final"]] [:inline (tier-weight :final)]
- [:= :data_layer [:inline "internal"]] [:inline (tier-weight :internal)]
- [:= :data_layer [:inline "hidden"]] [:inline (tier-weight :hidden)]
+ [:= :data_layer "final"] [:inline (tier-weight :final)]
+ [:= :data_layer "internal"] [:inline (tier-weight :internal)]
+ [:= :data_layer "hidden"] [:inline (tier-weight :hidden)]
:else [:inline 0]]))
(defn model-rank-expr
@@ -158,8 +159,8 @@
"Score an item based on whether it has been bookmarked."
(let [match-clause (fn [m] [[:and
(if-let [sms (bookmarked-sub-models (keyword m))]
- [:in :search_index.model (mapv (fn [k] [:inline (name k)]) sms)]
- [:= :search_index.model [:inline m]])
+ [:in :search_index.model (mapv name sms)]
+ [:= :search_index.model m])
[:!= nil (keyword (str m "_bookmark." m "_id"))]]
[:inline 1]])]
(into [:case] (concat (mapcat (comp match-clause name) bookmarked-models) [:else [:inline 0]]))))
@@ -170,8 +171,8 @@
[(keyword table-name)
[:and
(if-let [sms (bookmarked-sub-models model)]
- [:in :search_index.model (mapv (fn [m] [:inline (name m)]) sms)]
- [:= :search_index.model [:inline model-name]])
+ [:in :search_index.model (mapv name sms)]
+ [:= :search_index.model model-name])
[:= (keyword (str table-name ".user_id")) user-id]
[:= :search_index.model_id (cast-to-text (keyword (str table-name "." model-name "_id")))]]]))
diff --git a/src/metabase/search/util.clj b/src/metabase/search/util.clj
index 86bff5dd947..dabe0025228 100644
--- a/src/metabase/search/util.clj
+++ b/src/metabase/search/util.clj
@@ -157,4 +157,4 @@
(weighted-tsvector weight text (tsv-language)))
([weight text lang]
;; tsvector has a max value size of 1048575 bytes, limit to less than that because the multiple values get concatenated together
- [:setweight [:to_tsvector [:inline lang] [:cast (u.str/limit-bytes text search.ingestion/max-searchable-value-length) :text]] [:inline weight]]))
+ [:setweight [:to_tsvector ^:allow-raw-sql [:inline lang] [:cast (u.str/limit-bytes text search.ingestion/max-searchable-value-length) :text]] ^:allow-raw-sql [:inline weight]]))
diff --git a/src/metabase/segments/api.clj b/src/metabase/segments/api.clj
index b7351f66d45..bb458e601fd 100644
--- a/src/metabase/segments/api.clj
+++ b/src/metabase/segments/api.clj
@@ -8,6 +8,7 @@
[metabase.lib.core :as lib]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
+ [metabase.segments.schema :as segments.schema]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
@@ -40,7 +41,7 @@
_query-params
{:keys [name description definition], :as body} :- [:map
[:name ms/NonBlankString]
- [:definition ms/Map]
+ [:definition ::segments.schema/definition]
[:description {:optional true} [:maybe :string]]]]
;; TODO - why can't we set other properties like `show_in_getting_started` when we create the Segment?
(let [table-id (definition-table-id definition)]
@@ -121,7 +122,7 @@
_query-params
body :- [:map
[:name {:optional true} [:maybe ms/NonBlankString]]
- [:definition {:optional true} [:maybe ms/Map]]
+ [:definition {:optional true} [:maybe ::segments.schema/definition]]
[:revision_message ms/NonBlankString]
[:archived {:optional true} [:maybe :boolean]]
[:caveats {:optional true} [:maybe :string]]
diff --git a/src/metabase/segments/models/segment.clj b/src/metabase/segments/models/segment.clj
index 118201c0258..29ac062c55b 100644
--- a/src/metabase/segments/models/segment.clj
+++ b/src/metabase/segments/models/segment.clj
@@ -6,6 +6,7 @@
[metabase.api.common :as api]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
[metabase.lib.schema.common :as lib.schema.common]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
@@ -29,7 +30,7 @@
"Validate that an MBQL 5 segment definition has the correct structure."
[definition]
(when (seq definition)
- (mu/validate-throw ::segments.schema/segment definition)
+ (mu/validate-throw ::segments.schema/definition definition)
definition))
(defn- normalize-segment-definition
@@ -42,10 +43,14 @@
[definition table-id database-id]
(if (seq definition)
(u/prog1 (-> (case (lib/normalized-mbql-version definition)
- (:mbql-version/mbql5 :mbql-version/legacy)
+ :mbql-version/mbql5
+ (lib/normalize ::lib.schema/query definition)
+
+ :mbql-version/legacy
definition
;; default MBQL4 fragment
- (let [definition
+ (let [definition (update-keys definition keyword)
+ definition
(if (:aggregation definition)
(do
(log/warn "Stripping :aggregation from MBQL4 segment definition during migration")
@@ -62,7 +67,7 @@
"Transform for segment definitions. Only handles JSON serialization/deserialization.
Normalization and validation happen in before-insert and after-select hooks."
{:in mi/json-in
- :out mi/json-out-with-keywordization})
+ :out mi/json-out-without-keywordization})
(t2/deftransforms :model/Segment
{:definition transform-segment-definition})
diff --git a/src/metabase/segments/schema.clj b/src/metabase/segments/schema.clj
index 37bdbeb0a92..81dfbd5144d 100644
--- a/src/metabase/segments/schema.clj
+++ b/src/metabase/segments/schema.clj
@@ -1,36 +1,25 @@
(ns metabase.segments.schema
(:require
- [metabase.lib.schema :as lib.schema]
- [metabase.lib.schema.common :as common]
+ [metabase.lib-be.schema :as lib-be.schema]
+ [metabase.lib.core :as lib]
+ [metabase.util.i18n :refer [deferred-tru]]
[metabase.util.malli.registry :as mr]))
-(mr/def ::stage.segment
- [:and
- ::lib.schema/stage.mbql
- [:fn
- {:error/message "A segment stage must have exactly one of :source-table or :source-card"}
- #(= (count (select-keys % [:source-table :source-card])) 1)]
- [:fn
- {:error/message "A segment stage must have filters"}
- #(contains? % :filters)]
- (common/disallowed-keys
- {:joins "Segments cannot use :joins"
- :expressions "Segments cannot use :expressions"
- :breakout "Segments cannot use :breakout"
- :aggregation "Segments cannot use :aggregation"
- :fields "Segments cannot use :fields"
- :order-by "Segments cannot use :order-by"
- :page "Segments cannot use :page"
- :limit "Segments cannot use :limit"})])
-
-(mr/def ::segment
- [:and
- ::lib.schema/query
- [:fn
- {:error/message "A segment must have exactly one stage"}
- #(= (-> % :stages count) 1)]
- ;; checked with `:fn` rather than a `[:map [:stages ...]]` conjunct: a map conjunct declares only the keys it names,
- ;; so it would strip every other key of the query before the sibling `::lib.schema/query` saw it
- [:fn
- {:error/message "A segment's stages must be segment stages"}
- #(mr/validate [:sequential [:ref ::stage.segment]] (:stages %))]])
+(mr/def ::definition
+ "Schema for a segment's `:definition`; accepts a full MBQL query, converting legacy MBQL on decode."
+ [:schema
+ {:description (deferred-tru "value must be a valid MBQL query with a source table and filters.")}
+ [:and
+ ::lib-be.schema/maybe-legacy-query
+ [:fn
+ {:error/message (deferred-tru "a segment definition must be a single-stage query with a source table and filters, and without joins, expressions, breakouts, aggregations, fields, order by, or limit")}
+ (fn [query]
+ (and (= (lib/stage-count query) 1)
+ (some? (lib/primary-source-table-id query))
+ (seq (lib/filters query))
+ (empty? (lib/joins query))
+ (empty? (lib/expressions query))
+ (empty? (lib/breakouts query))
+ (empty? (lib/aggregations query))
+ (empty? (lib/order-bys query))
+ (nil? (lib/current-limit query))))]]])
diff --git a/src/metabase/server/middleware/misc.clj b/src/metabase/server/middleware/misc.clj
index e4f1f198e91..0e422fe340f 100644
--- a/src/metabase/server/middleware/misc.clj
+++ b/src/metabase/server/middleware/misc.clj
@@ -6,6 +6,7 @@
[metabase.config.core :as config]
[metabase.request.core :as request]
[metabase.server.streaming-response]
+ [metabase.setup.core :as setup]
[metabase.system.core :as system]
[metabase.util :as u]
[metabase.util.log :as log])
@@ -72,10 +73,12 @@
(when-let [ssl (or x-forwarded-ssl front-end-https)]
(when (= "on" (u/lower-case-en ssl)) "https"))))
-(defn- maybe-set-site-url* [{headers :headers, uri :uri}]
+(defn- maybe-set-site-url* [{headers :headers, uri :uri, superuser? :is-superuser?}]
(let [{:strs [origin x-forwarded-host host user-agent]} headers]
(when (and (mdb/db-is-set-up?)
(not (system/site-url))
+ (or (not (setup/has-user-setup))
+ superuser?)
(not (#{"/api/health" "/livez" "/readyz"} uri))
(or (nil? user-agent) ((complement str/includes?) user-agent "HealthChecker")))
;; `origin` already carries a scheme; the `*-host` headers normally don't, so prepend the scheme the proxy
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index 6ed17be4595..2710bf96eba 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -103,14 +103,13 @@
(defn- oldest-allowed-expr
"Build a database-specific expression for `NOW() - interval`."
[db-type amount unit]
- (case db-type
- :postgres [:- [:raw "current_timestamp"]
- [:raw (format "INTERVAL '%d %s'" amount (name unit))]]
- :h2 [:dateadd (h2x/literal (name unit))
- [:inline (- amount)]
- :%now]
- :mysql [:date_add :%now
- [:raw (format "INTERVAL -%d %s" amount (name unit))]]))
+ (let [now (h2x/current-datetime-honeysql-form db-type)]
+ (case db-type
+ :postgres [:- now [::h2x/postgres-interval amount unit]]
+ :h2 [:dateadd (h2x/literal (name unit))
+ [:inline (- amount)]
+ now]
+ :mysql [:- now [::h2x/mysql-interval amount unit]])))
(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds])} session-with-id-query
(memoize
@@ -131,11 +130,11 @@
[:or [:= :tenant.id nil] :tenant.is_active]
[:= :tenant.id nil])
[:= :user.is_active true]
- [:or [:= :session.id [:raw "?"]] [:= :session.key_hashed [:raw "?"]]]
+ [:or [:= :session.id ^:allow-raw-sql [:raw "?"]] [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]]]
[:> :session.created_at (oldest-allowed-expr db-type max-age-minutes :minute)]
[:= :session.anti_csrf_token (case session-type
:normal nil
- :full-app-embed [:raw "?"])]]
+ :full-app-embed ^:allow-raw-sql [:raw "?"])]]
(when session-timeout-seconds
[[:> [:coalesce :session.last_active_at :session.created_at]
(oldest-allowed-expr db-type session-timeout-seconds :second)]]))
@@ -165,7 +164,7 @@
:left-join [[:core_user :user] [:= :api_key.user_id :user.id]]
:where [:and
[:= :user.is_active true]
- [:= :api_key.key_prefix [:raw "?"]]]
+ [:= :api_key.key_prefix ^:allow-raw-sql [:raw "?"]]]
:limit [:inline 1]}
enable-advanced-permissions?
(->
@@ -190,7 +189,7 @@
:from [[:core_user :user]]
:where [:and
[:= :user.is_active true]
- [:= :user.id [:raw "?"]]]
+ [:= :user.id ^:allow-raw-sql [:raw "?"]]]
:limit [:inline 1]}
enable-advanced-permissions?
(->
diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.clj
index 4f3577fd854..b381c688ce6 100644
--- a/src/metabase/session/api.clj
+++ b/src/metabase/session/api.clj
@@ -207,7 +207,7 @@
(do-login)
(http-401-on-error
(throttle/with-throttling [(login-throttlers :ip-address) ip-address
- (login-throttlers :username) username]
+ (login-throttlers :username) (u/lower-case-en username)]
(do-login))))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
@@ -232,7 +232,7 @@
;; There's also no need to salt the token because it's already random <3
(def ^:private forgot-password-throttlers
- {:email (throttle/make-throttler :email :attempts-threshold 3 :attempt-ttl-ms 1000)
+ {:email (throttle/make-throttler :email :attempts-threshold 3 :attempt-ttl-ms (* 1000 60 60))
:ip-address (throttle/make-throttler :email :attempts-threshold 50)})
(defn- sso-password-reset-disabled?
@@ -339,7 +339,7 @@
"Reset password with a reset token."
[_route-params
_query-params
- request-body :- [:map
+ request-body :- [:map {:closed true}
[:token ms/NonBlankString]
[:password ms/ValidPassword]]
request]
@@ -348,7 +348,7 @@
(let [auth-result (auth-identity/with-fallback auth-identity/login!
[:provider/support-access-grant
:provider/emailed-secret-password-reset]
- request-body)]
+ (select-keys request-body [:token :password]))]
(cond
(not (:success? auth-result))
(api/throw-invalid-param-exception :password (tru "Invalid reset token"))
diff --git a/src/metabase/session/task/session_cleanup.clj b/src/metabase/session/task/session_cleanup.clj
index 6e89be89fd4..fbd125d5321 100644
--- a/src/metabase/session/task/session_cleanup.clj
+++ b/src/metabase/session/task/session_cleanup.clj
@@ -18,16 +18,16 @@
"Deletes sessions from the database which are no longer valid. Removes sessions that exceed MAX_SESSION_AGE
(absolute lifetime) and also sessions that have been idle longer than the session-timeout setting (if configured)."
[]
- (let [oldest-allowed [:inline (h2x/add-interval-honeysql-form (mdb/db-type)
- :%now
- (- (config/config-int :max-session-age))
- :minute)]
+ (let [oldest-allowed (h2x/add-interval-honeysql-form (mdb/db-type)
+ :%now
+ (- (config/config-int :max-session-age))
+ :minute)
timeout-seconds (request/enabled-session-timeout-seconds)
timeout-oldest (when timeout-seconds
- [:inline (h2x/add-interval-honeysql-form (mdb/db-type)
- :%now
- (- timeout-seconds)
- :second)])
+ (h2x/add-interval-honeysql-form (mdb/db-type)
+ :%now
+ (- timeout-seconds)
+ :second))
where-clause (if timeout-oldest
[:or
[:< :created_at oldest-allowed]
diff --git a/src/metabase/settings/models/setting.clj b/src/metabase/settings/models/setting.clj
index 2bde790638d..0dfbf2aed68 100644
--- a/src/metabase/settings/models/setting.clj
+++ b/src/metabase/settings/models/setting.clj
@@ -5,6 +5,7 @@
[clojure.data :as data]
[clojure.data.csv :as csv]
[clojure.string :as str]
+ [clojure.walk :as walk]
[environ.core :as env]
[malli.core :as mc]
[medley.core :as m]
@@ -408,7 +409,7 @@
;; Non-admin setting managers can only access settings that are not marked as admin-only
(not api/*is-superuser?*)
(has-advanced-setting-access?)
- (not= (:visibility setting) :admin))
+ (contains? #{:public :authenticated :settings-manager} (:visibility setting)))
(and
;; Non-admins can only access user-local settings not marked as admin-only
(allows-user-local-values? setting)
@@ -1037,7 +1038,10 @@
This method will throw an exception if trying to update a read-only setting, unless `:bypass-read-only?` is set."
[setting-definition-or-name new-value & {:keys [bypass-read-only?]}]
- (let [{:keys [cache?] :as setting} (resolve-setting setting-definition-or-name)]
+ (let [{:keys [cache?] :as setting} (resolve-setting setting-definition-or-name)
+ new-value (cond-> new-value
+ (and (= (:type setting) :json) (coll? new-value))
+ walk/keywordize-keys)]
(validate-settable! setting bypass-read-only?)
(binding [config/*disable-setting-cache* (not cache?)]
(set-with-audit-logging! setting new-value bypass-read-only?))))
diff --git a/src/metabase/settings/models/setting/cache.clj b/src/metabase/settings/models/setting/cache.clj
index 4ad87941ecc..eaae0856f41 100644
--- a/src/metabase/settings/models/setting/cache.clj
+++ b/src/metabase/settings/models/setting/cache.clj
@@ -74,7 +74,7 @@
(log/debug "Updating value of settings-last-updated in DB...")
;; for MySQL, cast(current_timestamp AS char); for H2 & Postgres, cast(current_timestamp AS text)
(let [current-timestamp-as-string-honeysql (h2x/cast (if (= (mdb/db-type) :mysql) :char :text)
- [:raw "current_timestamp"])]
+ (h2x/current-datetime-honeysql-form (mdb/db-type)))]
;; attempt to UPDATE the existing row. If no row exists, `t2/update!` will return 0...
(or (pos? (t2/update! :setting {:key settings-last-updated-key} {:value current-timestamp-as-string-honeysql}))
;; ...at which point we will try to INSERT a new row. Note that it is entirely possible two instances can both
diff --git a/src/metabase/slackbot/api.clj b/src/metabase/slackbot/api.clj
index 7c72afaeb29..4c1bf6d609b 100644
--- a/src/metabase/slackbot/api.clj
+++ b/src/metabase/slackbot/api.clj
@@ -7,6 +7,7 @@
[metabase.analytics.core :as analytics.core]
[metabase.api.macros :as api.macros]
[metabase.channel.settings :as channel.settings]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.metabot.feedback :as metabot.feedback]
[metabase.permissions.core :as perms]
[metabase.request.core :as request]
@@ -431,7 +432,8 @@
"Respond to activities in Slack"
[_route-params
_query-params
- body :- [:multi {:dispatch :type}
+ body :- [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch :type}
["url_verification" slackbot.events/SlackUrlVerificationEvent]
["event_callback" slackbot.events/SlackEventCallbackEvent]
[::mc/default [:map [:type :string]]]]
diff --git a/src/metabase/slackbot/events.clj b/src/metabase/slackbot/events.clj
index 0124f00cc55..c48460f6196 100644
--- a/src/metabase/slackbot/events.clj
+++ b/src/metabase/slackbot/events.clj
@@ -1,8 +1,7 @@
(ns metabase.slackbot.events
"Event definitions for slackbot."
(:require
- [clojure.string :as str]
- [malli.core :as mc]))
+ [clojure.string :as str]))
(def SlackEventsResponse
"Malli schema for Slack events API response"
@@ -53,11 +52,28 @@
"Malli schema for Slack event_callback event"
[:map
[:type [:= "event_callback"]]
+ [:event_id {:optional true} :string]
+ [:team_id {:optional true} :string]
[:event [:map
- [:type :string]
- [:event_ts :string]
- [::mc/default [:map-of :keyword :any]]]]
- [::mc/default [:map-of :keyword :any]]])
+ [:type :string]
+ [:event_ts :string]
+ [:user {:optional true} :string]
+ [:channel {:optional true} :string]
+ [:channel_type {:optional true} :string]
+ [:subtype {:optional true} :string]
+ [:ts {:optional true} :string]
+ [:thread_ts {:optional true} [:maybe :string]]
+ [:text {:optional true} [:maybe :string]]
+ [:bot_id {:optional true} [:maybe :string]]
+ [:reaction {:optional true} :string]
+ [:edited {:optional true} [:map
+ [:user {:optional true} :string]
+ [:ts {:optional true} :string]]]
+ [:files {:optional true} [:sequential SlackFile]]
+ [:item {:optional true} [:map
+ [:type {:optional true} :string]
+ [:channel {:optional true} :string]
+ [:ts {:optional true} :string]]]]]])
(defn user-message?
"Check if event is from a user (not a bot)."
diff --git a/src/metabase/sql_tools/common.clj b/src/metabase/sql_tools/common.clj
index 93969eb03d0..cf933c28b81 100644
--- a/src/metabase/sql_tools/common.clj
+++ b/src/metabase/sql_tools/common.clj
@@ -49,7 +49,7 @@
[:= :active true]
[:or
[:= :visibility_type nil]
- [:not-in :visibility_type [:inline ["hidden" "technical" "cruft"]]]]]}))
+ [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]}))
#{}))
(defn find-table-or-transform
diff --git a/src/metabase/sync/analyze.clj b/src/metabase/sync/analyze.clj
index b6fdb725e8c..b313710c636 100644
--- a/src/metabase/sync/analyze.clj
+++ b/src/metabase/sync/analyze.clj
@@ -65,9 +65,10 @@
[database :- i/DatabaseInstance]
(t2/update! :model/Field
(merge (sync.fingerprint/incomplete-analysis-kvs)
- {:table_id [:in {:select [:id]
- :from [(t2/table-name :model/Table)]
- :where [:and sync-util/sync-tables-clause [:= :db_id (:id database)]]}]})
+ {:table_id [:in ^:allow-subquery
+ {:select [:id]
+ :from [(t2/table-name :model/Table)]
+ :where [:and sync-util/sync-tables-clause [:= :db_id (:id database)]]}]})
{:last_analyzed :%now}))
(mu/defn analyze-table!
diff --git a/src/metabase/sync/analyze/interestingness.clj b/src/metabase/sync/analyze/interestingness.clj
index 47292344c76..4e864173635 100644
--- a/src/metabase/sync/analyze/interestingness.clj
+++ b/src/metabase/sync/analyze/interestingness.clj
@@ -85,9 +85,9 @@
[:= :active true]
[:= :dimension_interestingness nil]
[:not-in :visibility_type ["sensitive" "retired"]]
- [:in :table_id {:select [:id]
- :from [(t2/table-name :model/Table)]
- :where [:= :db_id (u/the-id database)]}]]})))
+ [:in :table_id ^:allow-subquery {:select [:id]
+ :from [(t2/table-name :model/Table)]
+ :where [:= :db_id (u/the-id database)]}]]})))
(mu/defn score-fields-for-db!
"Score interestingness for all qualifying Fields in `database`."
diff --git a/src/metabase/sync/sync_metadata/fks.clj b/src/metabase/sync/sync_metadata/fks.clj
index 4df3a4d8c78..db883a6a7a8 100644
--- a/src/metabase/sync/sync_metadata/fks.clj
+++ b/src/metabase/sync/sync_metadata/fks.clj
@@ -22,6 +22,7 @@
pk-table-schema
pk-column-name]}]
(let [field-id-query (fn [db-id table-schema table-name column-name]
+ ^:allow-subquery
{:select [[[:min :f.id] :id]]
;; Cal 2024-03-04: We use `min` to limit this subquery to one result (limit 1 isn't allowed
;; in subqueries in MySQL) because it's possible for schema, table, or column names to be
diff --git a/src/metabase/sync/sync_metadata/indexes.clj b/src/metabase/sync/sync_metadata/indexes.clj
index ee8dfb43900..66433def462 100644
--- a/src/metabase/sync/sync_metadata/indexes.clj
+++ b/src/metabase/sync/sync_metadata/indexes.clj
@@ -85,9 +85,10 @@
database-id (:id database)
indexed-field-ids (all-indexes->field-ids database-id indexes)
existing-indexed-field-ids (t2/select-pks-set :model/Field
- :table_id [:in {:select [[:t.id]]
- :from [[(t2/table-name :model/Table) :t]]
- :where [:= :t.db_id database-id]}]
+ :table_id [:in ^:allow-subquery
+ {:select [[:t.id]]
+ :from [[(t2/table-name :model/Table) :t]]
+ :where [:= :t.db_id database-id]}]
:parent_id nil
:database_indexed true)
[removing adding] (data/diff existing-indexed-field-ids indexed-field-ids)
diff --git a/src/metabase/sync/util.clj b/src/metabase/sync/util.clj
index 62fadf30fc8..fc19de8f9dd 100644
--- a/src/metabase/sync/util.clj
+++ b/src/metabase/sync/util.clj
@@ -503,10 +503,10 @@
(t2/reducible-select :model/Table
{:select [:t.*]
:from [[(t2/table-name :model/Table) :t]]
- :left-join [[{:select [:table_id
- [[:min :last_analyzed] :earliest_last_analyzed]]
- :from [(t2/table-name :model/Field)]
- :group-by [:table_id]} :sub]
+ :left-join [[^:allow-subquery {:select [:table_id
+ [[:min :last_analyzed] :earliest_last_analyzed]]
+ :from [(t2/table-name :model/Field)]
+ :group-by [:table_id]} :sub]
[:= :t.id :sub.table_id]]
:where [:and sync-tables-clause [:= :t.db_id (u/the-id database-or-id)]]
:order-by [[:sub.earliest_last_analyzed :asc]]})))
diff --git a/src/metabase/task_history/api.clj b/src/metabase/task_history/api.clj
index 21bc33cd1d7..50edfbd20f4 100644
--- a/src/metabase/task_history/api.clj
+++ b/src/metabase/task_history/api.clj
@@ -10,6 +10,7 @@
[metabase.task-history.models.task-run :as task-run]
[metabase.task.core :as task]
[metabase.util.date-2 :as u.date]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
@@ -157,10 +158,8 @@
(let [run-ids (map :id runs)
counts (t2/query {:select [:run_id
[[:count :id] :task_count]
- [[:raw "SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END)"]
- :success_count]
- [[:raw "SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END)"]
- :failed_count]]
+ [[:sum [:case [:= :status [::h2x/literal "success"]] [:inline 1] :else [:inline 0]]] :success_count]
+ [[:sum [:case [:= :status [::h2x/literal "failed"]] [:inline 1] :else [:inline 0]]] :failed_count]]
:from :task_history
:where [:in :run_id run-ids]
:group-by [:run_id]})
@@ -226,9 +225,9 @@
:task_count
{:select [:task_run.*]
- :left-join [[{:select [:run_id [[:count :*] :task_count]]
- :from [:task_history]
- :group-by [:run_id]}
+ :left-join [[^:allow-subquery {:select [:run_id [[:count :*] :task_count]]
+ :from [:task_history]
+ :group-by [:run_id]}
:sort_tc]
[:= :sort_tc.run_id :task_run.id]]
:order-by [[[:coalesce :sort_tc.task_count [:inline 0]] dir] secondary]}
diff --git a/src/metabase/tiles/api.clj b/src/metabase/tiles/api.clj
index 631b2220796..b5bf65b7296 100644
--- a/src/metabase/tiles/api.clj
+++ b/src/metabase/tiles/api.clj
@@ -230,8 +230,9 @@
[:lonField ::legacy-ref]]]
(let [updated-query (tiles-query query zoom x y lat-field lon-field)
result (qp/process-query
- (qp/userland-query updated-query {:executed-by api/*current-user-id*
- :context :map-tiles}))
+ (qp/userland-query
+ (assoc updated-query :info {:executed-by api/*current-user-id*
+ :context :map-tiles})))
points (result->points result lat-field lon-field)]
(tiles-response result zoom points)))
diff --git a/src/metabase/timeline/api/timeline_event.clj b/src/metabase/timeline/api/timeline_event.clj
index 719c257f3cd..7408642a928 100644
--- a/src/metabase/timeline/api/timeline_event.clj
+++ b/src/metabase/timeline/api/timeline_event.clj
@@ -90,6 +90,8 @@
timeline-event-updates (cond-> timeline-event-updates
(boolean timestamp) (update :timestamp u.date/parse))]
(collection/check-allowed-to-change-collection existing timeline-event-updates)
+ (when (api/column-will-change? :timeline_id existing timeline-event-updates)
+ (api/write-check :model/Timeline (:timeline_id timeline-event-updates)))
;; todo: if we accept a new timestamp, must we require a timezone? gut says yes?
(t2/update! :model/TimelineEvent id
(u/select-keys-when timeline-event-updates
diff --git a/src/metabase/transforms/jobs.clj b/src/metabase/transforms/jobs.clj
index 4d48e88b467..bf7b4d10ea8 100644
--- a/src/metabase/transforms/jobs.clj
+++ b/src/metabase/transforms/jobs.clj
@@ -3,6 +3,7 @@
[clojure.set :as set]
[clojure.string :as str]
[flatland.ordered.set :as ordered-set]
+ [metabase.app-db.core :as mdb]
[metabase.channel.urls :as urls]
[metabase.events.core :as events]
[metabase.revisions.core :as revisions]
@@ -23,6 +24,7 @@
[metabase.transforms.usage :as transforms.usage]
[metabase.transforms.util :as transforms.u]
[metabase.util :as u]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :as i18n]
[metabase.util.log :as log]
[toucan2.core :as t2]))
@@ -335,7 +337,7 @@
(defn- app-db-now
[]
- (:now (t2/query-one {:select [[[:raw "current_timestamp"] :now]]})))
+ (:now (t2/query-one {:select [[(h2x/current-datetime-honeysql-form (mdb/db-type)) :now]]})))
(defn run-transforms!
"Run the transforms of `plan`, honoring the DAG.
diff --git a/src/metabase/transforms/models/job_run.clj b/src/metabase/transforms/models/job_run.clj
index 263afdfbb6b..305d1e0c030 100644
--- a/src/metabase/transforms/models/job_run.clj
+++ b/src/metabase/transforms/models/job_run.clj
@@ -20,8 +20,9 @@
(defn- latest-runs-query [job-ids]
{:with [[:ranked_runs
+ ^:allow-subquery
{:select [:*
- [[:over [[:row_number] {:partition-by :job_id, :order-by [[:start_time :desc]]}]] :rn]]
+ [[:over [[:row_number] ^:allow-subquery {:partition-by :job_id, :order-by [[:start_time :desc]]}]] :rn]]
:from [:transform_job_run]
:where [:in :job_id job-ids]}]]
:select [:*]
diff --git a/src/metabase/transforms/models/transform.clj b/src/metabase/transforms/models/transform.clj
index 2aae58ad1ac..3d20d9e82af 100644
--- a/src/metabase/transforms/models/transform.clj
+++ b/src/metabase/transforms/models/transform.clj
@@ -48,6 +48,13 @@
(= :query-builder-and-native
(perms/full-database-permission-for-user api/*current-user-id* :perms/create-queries source-db-id)))))
+(defn- transform-database-permissions?
+ [instance]
+ (let [source-db-id (or (transforms-base.i/source-db-id instance) (:source_database_id instance))
+ target-db-id (transforms-base.i/target-db-id instance)]
+ (every? #(perms/has-db-transforms-permission? api/*current-user-id* %)
+ (distinct (keep identity [source-db-id target-db-id])))))
+
(defn- transform-writable?
"Whether the current user can write `instance`. Any extra `args` (an optional `models-cache`) are
passed through to the source-readability check, as in `transform-readable?`."
@@ -56,7 +63,7 @@
(transforms.u/check-feature-enabled instance)
(or api/*is-superuser?*
(and (apply transform-readable? instance args)
- (perms/has-db-transforms-permission? api/*current-user-id* (:source_database_id instance))
+ (transform-database-permissions? instance)
(native-transform-write-allowed? instance (:source_database_id instance))))))
(defmethod mi/can-read? :model/Transform
@@ -91,7 +98,7 @@
(let [source-db-id (or (:source_database_id instance) (transforms-base.i/source-db-id instance))]
(and api/*is-data-analyst?*
(transforms.u/source-tables-readable? instance)
- (perms/has-db-transforms-permission? api/*current-user-id* source-db-id)
+ (transform-database-permissions? instance)
(native-transform-write-allowed? instance source-db-id))))))
(defn- orphan-query?
diff --git a/src/metabase/transforms/models/transform_run.clj b/src/metabase/transforms/models/transform_run.clj
index e0b7491134c..9edea26d4f2 100644
--- a/src/metabase/transforms/models/transform_run.clj
+++ b/src/metabase/transforms/models/transform_run.clj
@@ -42,9 +42,10 @@
([] (latest-run-cte nil))
([where]
[[:latest_runs
- (-> {:select [:*
- [[:over [[:row_number] {:partition-by :transform_id, :order-by [[:start_time :desc]]}]] :rn]]
- :from [:transform_run]}
+ (-> ^:allow-subquery
+ {:select [:*
+ [[:over [[:row_number] ^:allow-subquery {:partition-by :transform_id, :order-by [[:start_time :desc]]}]] :rn]]
+ :from [:transform_run]}
(m/assoc-some :where where))]]))
(defn- latest-runs-query [transform-ids]
@@ -244,7 +245,7 @@
{:select [:transform_id [[:max :end_time] :last_success]]
:where [:and
[:in :transform_id transform-ids]
- [:= :status [:inline "succeeded"]]]
+ [:= :status "succeeded"]]
:group-by [:transform_id]}))))
(defn- paged-runs-join-clause
@@ -271,9 +272,10 @@
(conj [:in :transform_id transform-ids])
(seq transform-tag-ids)
- (conj [:in :transform_id {:select [:transform_id]
- :from [:transform_transform_tag]
- :where [:in :tag_id transform-tag-ids]}])
+ (conj [:in :transform_id ^:allow-subquery
+ {:select [:transform_id]
+ :from [:transform_transform_tag]
+ :where [:in :tag_id transform-tag-ids]}])
(seq statuses)
(conj [:in :status (set statuses)])
@@ -324,14 +326,16 @@
"Returns a correlated subquery that selects the translated name of the first tag
(by minimum position) assigned to the transform for a transform run."
[]
+ ^:allow-subquery
{:select [[(translate-tag-name-clause :tt.name :tt.built_in_type) :tag_name]]
:from [[:transform_transform_tag :ttt]]
:join [[:transform_tag :tt] [:= :ttt.tag_id :tt.id]]
:where [:and
[:= :ttt.transform_id :transform_run.transform_id]
- [:= :ttt.position {:select [[[:min :ttt2.position]]]
- :from [[:transform_transform_tag :ttt2]]
- :where [:= :ttt2.transform_id :transform_run.transform_id]}]]})
+ [:= :ttt.position ^:allow-subquery
+ {:select [[[:min :ttt2.position]]]
+ :from [[:transform_transform_tag :ttt2]]
+ :where [:= :ttt2.transform_id :transform_run.transform_id]}]]})
(defn- paged-runs-order-by-clause
"Builds a HoneySQL `:order-by` clause for transform runs, translating display values for sortable columns."
diff --git a/src/metabase/transforms/models/transform_run_cancelation.clj b/src/metabase/transforms/models/transform_run_cancelation.clj
index 731e12f99c3..3467c86c9b3 100644
--- a/src/metabase/transforms/models/transform_run_cancelation.clj
+++ b/src/metabase/transforms/models/transform_run_cancelation.clj
@@ -40,11 +40,12 @@
(defn- no-active-run-clause
[]
- [:not [:exists {:select [1]
- :from [[:transform_run :wr]]
- :where [:and
- [:= :wr.id :transform_run_cancelation.run_id]
- :wr.is_active]}]])
+ [:not [:exists ^:allow-subquery
+ {:select [1]
+ :from [[:transform_run :wr]]
+ :where [:and
+ [:= :wr.id :transform_run_cancelation.run_id]
+ :wr.is_active]}]])
(defn delete-cancelation!
"Delete a cancelation once it has been handled."
diff --git a/src/metabase/transforms/run_listing.clj b/src/metabase/transforms/run_listing.clj
index 756c4ce34c6..e72a22826ae 100644
--- a/src/metabase/transforms/run_listing.clj
+++ b/src/metabase/transforms/run_listing.clj
@@ -26,7 +26,8 @@
;; `[nil :col]` fills in columns a table lacks.
(defn- job-run-subquery [transform-ids]
- {:select [[[:inline "job"] :run_type]
+ ^:allow-subquery
+ {:select [[^:allow-raw-sql [:inline "job"] :run_type]
:id
[:job_id :entity_id]
[:job_name :entity_name]
@@ -38,34 +39,36 @@
:from [:transform_job_run]
:where (if (seq transform-ids)
;; only job runs that actually ran one of these transforms
- [:exists {:select [[[:inline 1]]]
- :from [[:transform_run :member]]
- :where [:and
- [:= :member.job_run_id :transform_job_run.id]
- [:in :member.transform_id transform-ids]]}]
+ [:exists ^:allow-subquery {:select [[[:inline 1]]]
+ :from [[:transform_run :member]]
+ :where [:and
+ [:= :member.job_run_id :transform_job_run.id]
+ [:in :member.transform_id transform-ids]]}]
true)})
(defn- dag-run-subquery [transform-ids]
- {:select [[[:inline "dag"] :run_type]
+ ^:allow-subquery
+ {:select [[^:allow-raw-sql [:inline "dag"] :run_type]
:id
[:source_transform_id :entity_id]
[:source_transform_name :entity_name]
:direction
:transform_count
- [[:inline "manual"] :run_method]
+ [^:allow-raw-sql [:inline "manual"] :run_method]
:status :is_active :start_time :end_time :message
:user_id]
:from [:transform_dag_run]
:where (if (seq transform-ids)
- [:exists {:select [[[:inline 1]]]
- :from [[:transform_run :member]]
- :where [:and
- [:= :member.dag_run_id :transform_dag_run.id]
- [:in :member.transform_id transform-ids]]}]
+ [:exists ^:allow-subquery {:select [[[:inline 1]]]
+ :from [[:transform_run :member]]
+ :where [:and
+ [:= :member.dag_run_id :transform_dag_run.id]
+ [:in :member.transform_id transform-ids]]}]
true)})
(defn- transform-run-subquery [transform-ids]
- {:select [[[:inline "transform"] :run_type]
+ ^:allow-subquery
+ {:select [[^:allow-raw-sql [:inline "transform"] :run_type]
:id
[:transform_id :entity_id]
[:transform_name :entity_name]
@@ -86,6 +89,7 @@
narrowed to runs touching one of `transform-ids`."
[types transform-ids]
(let [types (set (or (seq types) run-types))]
+ ^:allow-subquery
{:union-all (cond-> []
(:job types) (conj (job-run-subquery transform-ids))
(:dag types) (conj (dag-run-subquery transform-ids))
diff --git a/src/metabase/transforms/schema.clj b/src/metabase/transforms/schema.clj
index 7b93e4a5346..2e3906e5a44 100644
--- a/src/metabase/transforms/schema.clj
+++ b/src/metabase/transforms/schema.clj
@@ -1,8 +1,8 @@
(ns metabase.transforms.schema
(:require
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.id :as lib.schema.id]
- [metabase.queries.schema :as queries.schema]
[metabase.transforms-base.util :as transforms-base.u]
[metabase.util.date-2 :as u.date]
[metabase.util.malli.registry :as mr]
@@ -23,15 +23,17 @@
[:lookback {:optional true} [:maybe ::lookback]]])
(mr/def ::source-incremental-strategy
- [:multi {:dispatch :type}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch :type}
["checkpoint" ::checkpoint-strategy]])
(mr/def ::transform-source
- [:multi {:dispatch (comp keyword :type)}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
[:query
[:map
[:type {:decode/normalize lib.schema.common/normalize-keyword} [:= :query]]
- [:query ::queries.schema/query]
+ [:query ::lib-be.schema/maybe-legacy-query]
[:source-incremental-strategy {:optional true} ::source-incremental-strategy]]]
[:python
[:map
@@ -58,7 +60,8 @@
[:unique-key [:sequential ::merge-key-column]]])
(mr/def ::target-incremental-strategy
- [:multi {:dispatch :type}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch :type}
["append" ::append-config]
["merge" ::merge-config]])
@@ -78,7 +81,8 @@
[:target-incremental-strategy ::target-incremental-strategy]])
(mr/def ::transform-target
- [:multi {:dispatch :type}
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch :type}
["table" ::table-target]
["table-incremental" ::table-incremental-target]])
diff --git a/src/metabase/upload/impl.clj b/src/metabase/upload/impl.clj
index 97209071c1e..a88b00b4e25 100644
--- a/src/metabase/upload/impl.clj
+++ b/src/metabase/upload/impl.clj
@@ -900,7 +900,7 @@
(ex-info (tru "The table must be an uploaded table.")
{:status-code 422})
- (not (mi/can-read? table))
+ (not (mi/can-query? table))
(ex-info (tru "You don''t have permissions to do that.")
{:status-code 403}))))
@@ -918,13 +918,17 @@
(defn- can-delete-error
"Returns an ExceptionInfo object if the user cannot delete the given upload. Returns nil otherwise."
[table database]
- (when-not (:is_attached_dwh database) ;; gsheets uploads: deletable, but we cannot write + they aren't is_upload
+ (if (:is_attached_dwh database)
+ ;; gsheets uploads: deletable, but we cannot write + they aren't is_upload
+ (when-not api/*is-superuser?*
+ (ex-info (tru "You don''t have permissions to do that.")
+ {:status-code 403}))
(cond
(not (:is_upload table))
(ex-info (tru "The table must be an uploaded table.")
{:status-code 422})
- (not (mi/can-write? table))
+ (not (and (mi/can-query? table) (mi/can-write? table)))
(ex-info (tru "You don''t have permissions to do that.")
{:status-code 403}))))
diff --git a/src/metabase/user_key_value/api.clj b/src/metabase/user_key_value/api.clj
index 194d81df1ab..ed55465d9a2 100644
--- a/src/metabase/user_key_value/api.clj
+++ b/src/metabase/user_key_value/api.clj
@@ -30,6 +30,7 @@
:value v
:expires-at expires-at}
(mtx/transformer
+ (mtx/key-transformer {:decode keyword})
(mtx/default-value-transformer)
(mett/time-transformer)
{:name :api-request})))
diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.clj
index 9e1cc948a8d..78b3ec1d748 100644
--- a/src/metabase/users/models/user.clj
+++ b/src/metabase/users/models/user.clj
@@ -373,7 +373,7 @@
(defmethod mi/exclude-internal-content-hsql :model/User
[_model & {:keys [table-alias]}]
- [:and [:not= (h2x/identifier :field table-alias :type) [:inline "internal"]]])
+ [:and [:not= (h2x/identifier :field table-alias :type) "internal"]])
;;; --------------------------------------------------- Hydration ----------------------------------------------------
@@ -549,13 +549,13 @@
"EXISTS clause, correlated to :core_user.id, testing whether the user is in a group that grants
manage-table-metadata."
[]
- [:exists {:select [1]
- :from [[:permissions_group_membership :pgm]]
- :join [[:data_permissions :p] [:= :p.group_id :pgm.group_id]]
- :where [:and
- [:= :pgm.user_id :core_user.id]
- [:= :p.perm_type "perms/manage-table-metadata"]
- [:= :p.perm_value "yes"]]}])
+ [:exists ^:allow-subquery {:select [1]
+ :from [[:permissions_group_membership :pgm]]
+ :join [[:data_permissions :p] [:= :p.group_id :pgm.group_id]]
+ :where [:and
+ [:= :pgm.user_id :core_user.id]
+ [:= :p.perm_type "perms/manage-table-metadata"]
+ [:= :p.perm_value "yes"]]}])
(defn filter-clauses
"Honeysql clauses for filtering on users.
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index c106268196d..7afc92ccccd 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -242,6 +242,7 @@
:from [:permissions_group_membership]
:where [:in :permissions_group_membership.group_id
;; get all the groups ids that the current user is in
+ ^:allow-subquery
{:select-distinct [:permissions_group_membership.group_id]
:from [:permissions_group_membership]
:where [:and [:= :permissions_group_membership.user_id user-id]
diff --git a/src/metabase/util/honey_sql_2.clj b/src/metabase/util/honey_sql_2.clj
index 133aa29c612..7dc0a730f9a 100644
--- a/src/metabase/util/honey_sql_2.clj
+++ b/src/metabase/util/honey_sql_2.clj
@@ -100,6 +100,16 @@
(sql/register-fn! ::percentile-cont #'format-percentile-cont)
+(defn- format-collate
+ [_fn [expr collation]]
+ (when-not (re-matches #"\w+" (name collation))
+ (throw (ex-info (str "Invalid collation: " (pr-str collation)) {:collation collation})))
+ (let [[expr-sql & expr-args] (sql/format-expr expr)]
+ (into [(clojure.core/format "%s COLLATE %s" expr-sql (name collation))]
+ expr-args)))
+
+(sql/register-fn! ::collate #'format-collate)
+
(def IdentifierType
"Malli schema for valid [[identifier]] types."
[:enum
@@ -172,7 +182,7 @@
(defn- escape-and-quote-literal [s]
(as-> s s
- (str/replace s #"(?<![\\'])'(?![\\'])" "''")
+ (str/replace s "'" "''")
(str \' s \')))
(defn- format-literal [_tag [s]]
@@ -245,7 +255,9 @@
(:database-type type-info)
(update :database-type (comp u/lower-case-en name))))
-(defn- typed? [x]
+(defn typed?
+ "Whether `x` is a typed Honey SQL form, i.e. a `[::typed <expr> <type-info>]` vector."
+ [x]
(and (vector? x)
(= (first x) ::typed)))
@@ -342,21 +354,15 @@
(def ^:private TypedExpression
[:fn {:error/message "::h2x/typed Honey SQL form"} typed?])
+(def ^:private raw-cast-type-name-re
+ #"(?i)[a-z][a-z0-9_ ]*(?:\(\d+(?:, ?\d+)?\))?")
+
(mu/defn cast :- TypedExpression
"Generate a statement like `cast(expr AS sql-type)`. Returns a typed HoneySQL form."
- [db-type expr]
- (-> [:cast expr [:raw (name db-type)]]
- (with-database-type-info db-type)))
-
-(mu/defn quoted-cast :- TypedExpression
- "Generate a statement like `cast(expr AS \"sql-type\")`.
-
- Like `cast` but quotes `sql-type`. This is useful for cases where we deal with user-defined types or other types
- that may have a space in the name, for example Postgres enum types.
-
- Returns a typed HoneySQL form."
- [sql-type :- ms/NonBlankString expr]
- (-> [:cast expr (identifier :type-name sql-type)]
+ [sql-type expr]
+ (-> (if (re-matches raw-cast-type-name-re (name sql-type))
+ [:cast expr ^:allow-raw-sql [:raw (name sql-type)]]
+ [:cast expr (identifier :type-name (name sql-type))])
(with-database-type-info sql-type)))
(mu/defn maybe-cast :- TypedExpression
@@ -505,12 +511,30 @@
(-> (+ hsql-form (pg-interval amount unit))
(with-type-info (type-info hsql-form))))))
+(def ^:private mysql-interval-units
+ #{:second :minute :hour :day :week :month :quarter :year})
+
+(defn- format-mysql-interval
+ [_fn [amount unit]]
+ (when-not (number? amount)
+ (throw (ex-info "Invalid interval amount" {:amount amount})))
+ (when-not (contains? mysql-interval-units unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
+ [(clojure.core/format "INTERVAL %s %s" (num amount) (name unit))])
+
+(sql/register-fn! ::mysql-interval #'format-mysql-interval)
+
(defmethod add-interval-honeysql-form :mysql
[db-type hsql-form amount unit]
;; MySQL doesn't support `:millisecond` as an option, but does support fractional seconds
(if (= unit :millisecond)
(recur db-type hsql-form (clojure.core// amount 1000.0) :second)
- [:date_add hsql-form [:raw (clojure.core/format "INTERVAL %s %s" amount (name unit))]]))
+ (do
+ (when-not (contains? mysql-interval-units unit)
+ (throw (ex-info (str "Invalid temporal unit: " (pr-str unit)) {:unit unit})))
+ (when-not (number? amount)
+ (throw (ex-info "Invalid interval amount" {:amount amount})))
+ [:date_add hsql-form [::mysql-interval amount unit]])))
(defn- dateadd-h2 [unit amount expr]
(let [expr (cast-unless-type-in "datetime" #{"datetime" "timestamp" "timestamp with time zone" "date"} expr)]
@@ -571,7 +595,7 @@
(defmethod calculate-interval-honeysql-form :mysql
[_db-type end-form start-form]
- [:timestampdiff [:raw "MICROSECOND"] start-form end-form])
+ [:timestampdiff ^:allow-raw-sql [:raw "MICROSECOND"] start-form end-form])
(defmethod calculate-interval-honeysql-form :h2
[_db-type end-form start-form]
diff --git a/src/metabase/util/malli.cljc b/src/metabase/util/malli.cljc
index 2f29fd7b051..b3f78873a71 100644
--- a/src/metabase/util/malli.cljc
+++ b/src/metabase/util/malli.cljc
@@ -151,16 +151,9 @@
:and (some map-schema-keys (mc/children schema))
nil)))
-(core/defn dispatched-map
- "A `:multi` schema on `dispatch` whose every branch declares `common-entries` on top of its own entries.
-
- This is what `[:merge [:map common-entries] [:multi ...]]` looks like it does, but does not: `:merge` pushes itself
- inside each branch, nesting a second dispatch there instead of adding the common keys to it. A branch given
- anything other than a vector of entries is used as its own schema."
- [dispatch common-entries branches]
- (into [:multi {:dispatch dispatch}]
- (map (core/fn [[dispatch-value entries]]
- [dispatch-value (if (vector? entries)
- (into (into [:map] common-entries) entries)
- entries)]))
- branches))
+(core/defn refuse
+ "A schema that never validates; its `:decode/api` throws a 400 with `(message-fn)`. Intended as the last branch of
+ an `[:or ...]`."
+ [message-fn]
+ [:fn {:decode/api (core/fn [_] (throw (ex-info (message-fn) {:status-code 400})))}
+ (constantly false)])
diff --git a/src/metabase/util/malli/schema.clj b/src/metabase/util/malli/schema.clj
index adb237bb5ae..73558ddd937 100644
--- a/src/metabase/util/malli/schema.clj
+++ b/src/metabase/util/malli/schema.clj
@@ -4,6 +4,7 @@
For example the PositiveInt can be defined as (mr/def ::positive-int pos-int?)"
(:require
[clojure.string :as str]
+ [clojure.walk :as walk]
[malli.util :as mut]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
@@ -220,6 +221,15 @@
[:map {:closed false}]
(deferred-tru "Value must be a map.")))
+(def KeywordizedMap
+ "Schema for an open map whose incoming string keys are normalized to keywords on API decode."
+ (mu/with-api-error-message
+ [:map {:closed false
+ :decode/api (fn [m]
+ (cond-> m
+ (map? m) walk/keywordize-keys))}]
+ (deferred-tru "Value must be a map.")))
+
(def Email
"Schema for a valid email string."
(mu/with-api-error-message
diff --git a/src/metabase/util/time/impl_common.cljc b/src/metabase/util/time/impl_common.cljc
index 1713e472900..f4d6e368c64 100644
--- a/src/metabase/util/time/impl_common.cljc
+++ b/src/metabase/util/time/impl_common.cljc
@@ -64,7 +64,7 @@
(def zone-offset-part-regex
"Regex for a zone-offset string."
- (re-pattern offset-part))
+ (re-pattern (str \^ offset-part \$)))
(def ^:const local-date-regex
"Regex for a local-date string."
diff --git a/src/metabase/warehouse_schema/models/field.clj b/src/metabase/warehouse_schema/models/field.clj
index bcabcce9418..d3ecf82ebe8 100644
--- a/src/metabase/warehouse_schema/models/field.clj
+++ b/src/metabase/warehouse_schema/models/field.clj
@@ -166,9 +166,9 @@
:from [:metabase_field]
:where [:and
[:= :fk_target_field_id (:id field)]
- [:not [:exists {:select [1]
- :from [:metabase_field_user_settings]
- :where [:= :metabase_field_user_settings.field_id :metabase_field.id]}]]]}
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [:metabase_field_user_settings]
+ :where [:= :metabase_field_user_settings.field_id :metabase_field.id]}]]]}
sql (sql/format q :dialect (mdb/quoting-style (mdb/db-type)))]
(t2/insert! :model/FieldUserSettings
(map (fn [{:keys [id]}] {:field_id id})
diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.clj
index d2850cbd4c7..b42516e8d2e 100644
--- a/src/metabase/warehouse_schema/models/table.clj
+++ b/src/metabase/warehouse_schema/models/table.clj
@@ -682,7 +682,7 @@
:collection-name [:coalesce :collection.name
[:case
[:and :this.is_published
- [:= :this.collection_id nil]] [:inline "Our analytics"]
+ [:= :this.collection_id nil]] "Our analytics"
:else nil]]}
:where [:and
:active
diff --git a/src/metabase/warehouse_schema/table.clj b/src/metabase/warehouse_schema/table.clj
index 9a160eb4fda..ea7406fc238 100644
--- a/src/metabase/warehouse_schema/table.clj
+++ b/src/metabase/warehouse_schema/table.clj
@@ -242,13 +242,13 @@
:c.source_card_id :c.created_at :c.entity_id :c.card_schema
[:r.status :moderated_status]]
:from [[:report_card :c]]
- :left-join [[{:select [:moderated_item_id :status]
- :from [:moderation_review]
- :where [:and
- [:= :moderated_item_type "card"]
- [:= :most_recent true]]
- :order-by [[:id :desc]]
- :limit 1} :r]
+ :left-join [[^:allow-subquery {:select [:moderated_item_id :status]
+ :from [:moderation_review]
+ :where [:and
+ [:= :moderated_item_type "card"]
+ [:= :most_recent true]]
+ :order-by [[:id :desc]]
+ :limit 1} :r]
[:= :r.moderated_item_id :c.id]]
:where [:in :c.id ids]})
dbs (if (seq cards)
diff --git a/src/metabase/warehouse_schema_rest/api/field.clj b/src/metabase/warehouse_schema_rest/api/field.clj
index ffd4d62a6ad..aab539ea042 100644
--- a/src/metabase/warehouse_schema_rest/api/field.clj
+++ b/src/metabase/warehouse_schema_rest/api/field.clj
@@ -80,6 +80,13 @@
(api/checkp (= (:source_db_id result) (:target_db_id result))
param-name "Target field must belong to the same database")))
+(defn- check-can-point-at-field!
+ [source-field-id target-field-id current-target-field-id param-name]
+ (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))))
+
(defn- clear-dimension-on-fk-change! [{:keys [dimensions], :as _field}]
(doseq [{dimension-id :id, dimension-type :type} dimensions]
(when (and dimension-id (= :external dimension-type))
@@ -178,8 +185,7 @@
removed-fk? (removed-fk-semantic-type? (:semantic_type field) new-semantic-type)
fk-target-field-id (get body :fk_target_field_id (:fk_target_field_id field))]
;; validate that fk_target_field_id is a valid Field in the same database
- (when fk-target-field-id
- (check-field-in-same-database! id fk-target-field-id :fk_target_field_id))
+ (check-can-point-at-field! id fk-target-field-id (:fk_target_field_id field) :fk_target_field_id)
(when (and display-name
(not removed-fk?)
(not= (:display_name field) display-name))
@@ -249,18 +255,20 @@
(and (= dimension-type "external")
human-readable-field-id))
[400 "Foreign key based remappings require a human readable field id"])
- (when human-readable-field-id
- (check-field-in-same-database! id human-readable-field-id :human_readable_field_id))
- (if-let [dimension (t2/select-one :model/Dimension :field_id id)]
- (t2/update! :model/Dimension (u/the-id dimension)
- {:type dimension-type
- :name dimension-name
- :human_readable_field_id human-readable-field-id})
- (t2/insert! :model/Dimension
- {:field_id id
- :type dimension-type
- :name dimension-name
- :human_readable_field_id human-readable-field-id}))
+ (let [existing-dimension (t2/select-one :model/Dimension :field_id id)]
+ (check-can-point-at-field! id human-readable-field-id
+ (:human_readable_field_id existing-dimension)
+ :human_readable_field_id)
+ (if-let [dimension existing-dimension]
+ (t2/update! :model/Dimension (u/the-id dimension)
+ {:type dimension-type
+ :name dimension-name
+ :human_readable_field_id human-readable-field-id})
+ (t2/insert! :model/Dimension
+ {:field_id id
+ :type dimension-type
+ :name dimension-name
+ :human_readable_field_id human-readable-field-id})))
(t2/select-one :model/Dimension :field_id id))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.clj
index 1fc475199c1..5fe3340b97b 100644
--- a/src/metabase/warehouse_schema_rest/api/table.clj
+++ b/src/metabase/warehouse_schema_rest/api/table.clj
@@ -7,6 +7,7 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.app-db.core :as app-db]
+ [metabase.collections.core :as collections]
[metabase.database-routing.core :as database-routing]
[metabase.driver.settings :as driver.settings]
[metabase.driver.util :as driver.u]
@@ -26,6 +27,7 @@
[metabase.sync.core :as sync]
[metabase.upload.core :as upload]
[metabase.util :as u]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [deferred-tru tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -91,7 +93,7 @@
(let [like (fn [field pattern]
(case (app-db/db-type)
(:h2 :postgres) [:ilike field pattern]
- [:raw [:like field pattern] " COLLATE " [:inline "utf8mb4_unicode_ci"]]))
+ [::h2x/collate [:like field pattern] "utf8mb4_unicode_ci"]))
pattern (some-> term
(str/replace "\\" "\\\\")
(str/replace "_" "\\_")
@@ -114,11 +116,11 @@
orphan-only (conj [:and [:= :owner_email nil] [:= :owner_user_id nil]])
published-only (conj [:= :is_published true])
(and unused-only (premium-features/has-feature? :dependencies))
- (conj [:not-exists {:select [:*]
- :from [[:dependency :d]]
- :where [:and
- [:= :d.to_entity_id :metabase_table.id]
- [:= :d.to_entity_type "table"]]}]))
+ (conj [:not-exists ^:allow-subquery {:select [:*]
+ :from [[:dependency :d]]
+ :where [:and
+ [:= :d.to_entity_id :metabase_table.id]
+ [:= :d.to_entity_type "table"]]}]))
query {:where where, :order-by [[:name :asc]]}
hydrations (cond-> [:db]
(premium-features/any-transforms-enabled?) (conj :transform))]
@@ -233,11 +235,21 @@
(log/warn (u/format-color :red "Cannot connect to database %s in order to sync unhidden tables"
(:id database))))))))))
+(defn- check-can-publish-tables-to-collection!
+ [tables collection-id]
+ (api/check-data-analyst)
+ (let [collection (api/check-404 (t2/select-one :model/Collection :id collection-id))]
+ (api/check-400 (= (:type collection) collections/library-data-collection-type)
+ (tru "Tables can only be published to Library/Data collections."))
+ (api/check-403 (every? mi/can-query? tables))))
+
(defn- update-tables!
- [ids {:keys [visibility_type] :as body}]
+ [ids {:keys [collection_id visibility_type] :as body}]
(let [existing-tables (t2/select :model/Table :id [:in ids])]
(api/check-404 (= (count existing-tables) (count ids)))
(run! api/write-check existing-tables)
+ (when collection_id
+ (check-can-publish-tables-to-collection! existing-tables collection_id))
(let [updated-tables (t2/with-transaction [_conn] (mapv #(update-table!* % body) existing-tables))
newly-unhidden (when (and (contains? body :visibility_type) (nil? visibility_type))
(into [] (filter (comp some? :visibility_type)) existing-tables))]
@@ -368,9 +380,10 @@
(api/read-check :model/Table id)
(when-let [field-ids (seq (t2/select-pks-set :model/Field, :table_id id, :visibility_type [:not= "retired"], :active true))]
(for [origin-field (t2/select :model/Field, :fk_target_field_id [:in field-ids], :active true)
- :let [origin-field (-> (t2/hydrate origin-field [:table :db])
- (update :table schema.table/present-table))]
- :when (-> origin-field :table :active)]
+ :let [origin-field (t2/hydrate origin-field [:table :db])]
+ :when (and (-> origin-field :table :active)
+ (mi/can-read? origin-field))
+ :let [origin-field (update origin-field :table schema.table/present-table)]]
;; it's silly to be hydrating some of these tables/dbs
{:relationship :Mt1
:origin_id (:id origin-field)
diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.clj
index 62436fd12d8..b1291e77d92 100644
--- a/src/metabase/warehouses/models/database.clj
+++ b/src/metabase/warehouses/models/database.clj
@@ -424,9 +424,9 @@
{:pre [(pos-int? database-id)]}
;; Field has `define-before-delete` deleting children, but we'll delete them all at once because they refer same
;; database - iteratively, deleting those that no one depends on first
- (let [table-ids-query {:from [(t2/table-name :model/Table)]
- :select [:id]
- :where [:= :db_id database-id]}]
+ (let [table-ids-query ^:allow-subquery {:from [(t2/table-name :model/Table)]
+ :select [:id]
+ :where [:= :db_id database-id]}]
;; Avoid issuing the DELETE when no Fields exist. Keep this check non-locking: locking an empty range on MySQL
;; recreates the contention this guard avoids. A concurrent sync can race this check, but the foreign keys preserve
;; integrity by rejecting the Database deletion if it introduces nested Fields after the transaction snapshot.
@@ -434,16 +434,16 @@
(let [no-children-clause (if (= (mdb/db-type) :mysql)
;; double-wrapped subquery to work around the MySQL restriction on selecting from the
;; DELETE target
- [:not-in :id {:select [:parent_id]
- :from [[{:select [:parent_id]
- :from [(t2/table-name :model/Field)]
- :where [:and
- [:not= :parent_id nil]
- [:in :table_id table-ids-query]]}
- :parent_fields]]}]
- [:not [:exists {:select [1]
- :from [[(t2/table-name :model/Field) :child_field]]
- :where [:= :child_field.parent_id :metabase_field.id]}]])]
+ [:not-in :id ^:allow-subquery {:select [:parent_id]
+ :from [[^:allow-subquery {:select [:parent_id]
+ :from [(t2/table-name :model/Field)]
+ :where [:and
+ [:not= :parent_id nil]
+ [:in :table_id table-ids-query]]}
+ :parent_fields]]}]
+ [:not [:exists ^:allow-subquery {:select [1]
+ :from [[(t2/table-name :model/Field) :child_field]]
+ :where [:= :child_field.parent_id :metabase_field.id]}]])]
(loop []
(let [deleted (t2/query-one
{:delete-from (t2/table-name :model/Field)
@@ -717,14 +717,9 @@
;;; ------------------------------------------------ Serialization ----------------------------------------------------
(defmethod serdes/make-spec "Database"
- [_model-name {:keys [include-database-secrets]}]
- ;; Export only when secrets are explicitly included AND the database isn't an attached DWH.
- ;; Import is unconditional.
- (let [details-transform {:export-with-context (fn [current _ details]
- (if (and include-database-secrets
- (not (:is_attached_dwh current)))
- details
- ::serdes/skip))
+ [_model-name _opts]
+ ;; Connection details are never exported. Import is unconditional.
+ (let [details-transform {:export-with-context (fn [_current _ _details] ::serdes/skip)
:import identity}]
{:copy [:auto_run_queries :cache_field_values_schedule :caveats :dbms_version
:description :engine :is_audit :is_attached_dwh :is_full_sync :is_on_demand :is_sample :is_stub
diff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.clj
index 27e87776baa..52b52dfa929 100644
--- a/src/metabase/warehouses_rest/api.clj
+++ b/src/metabase/warehouses_rest/api.clj
@@ -17,6 +17,7 @@
[metabase.driver.util :as driver.u]
[metabase.events.core :as events]
[metabase.lib-be.core :as lib-be]
+ [metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.schema.id :as lib.schema.id]
@@ -190,7 +191,7 @@
with those aggregations as source queries. This function determines whether `card` is using one of those queries so
we can filter it out in Clojure-land."
[{query :dataset_query, :as _card} :- [:map
- [:dataset_query ::queries.schema/query]]]
+ [:dataset_query ::lib-be.schema/maybe-legacy-or-empty-query]]]
(match/match-one (lib/aggregations query) [#{:cum-count :cum-sum} & _] true))
(defn card-can-be-used-as-source-query?
@@ -223,14 +224,14 @@
[]
(t2/reducible-query {:select [:name :description :database_id :dataset_query :id :collection_id
:result_metadata :type :source_card_id :card_schema
- [{:select [:status]
- :from [:moderation_review]
- :where [:and
- [:= :moderated_item_type "card"]
- [:= :moderated_item_id :report_card.id]
- [:= :most_recent true]]
- :order-by [[:id :desc]]
- :limit 1}
+ [^:allow-subquery {:select [:status]
+ :from [:moderation_review]
+ :where [:and
+ [:= :moderated_item_type "card"]
+ [:= :moderated_item_id :report_card.id]
+ [:= :most_recent true]]
+ :order-by [[:id :desc]]
+ :limit 1}
:moderated_status]]
:from [:report_card]
:where (into [:and
@@ -556,11 +557,11 @@
(defn- card-query
[db-id model type-str]
- {:select [[:%count.* model]]
- :from [:report_card]
- :where [:and
- [:= :database_id db-id]
- [:= :type type-str]]})
+ ^:allow-subquery {:select [[:%count.* model]]
+ :from [:report_card]
+ :where [:and
+ [:= :database_id db-id]
+ [:= :type type-str]]})
(defmethod database-usage-query :question
[_ db-id]
@@ -576,19 +577,19 @@
(defmethod database-usage-query :segment
[_ db-id]
- {:select [[:%count.* :segment]]
- :from [:segment]
- :where [:in :table_id {:select [:id]
- :from [:metabase_table]
- :where [:= :db_id db-id]}]})
+ ^:allow-subquery {:select [[:%count.* :segment]]
+ :from [:segment]
+ :where [:in :table_id ^:allow-subquery {:select [:id]
+ :from [:metabase_table]
+ :where [:= :db_id db-id]}]})
(defmethod database-usage-query :transform
[_ db-id]
- {:select [[:%count.* :transform]]
- :from [:transform]
- :where [:or
- [:= :source_database_id db-id]
- [:= :target_db_id db-id]]})
+ ^:allow-subquery {:select [[:%count.* :transform]]
+ :from [:transform]
+ :where [:or
+ [:= :source_database_id db-id]
+ [:= :target_db_id db-id]]})
;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
;;
@@ -920,14 +921,15 @@
:- [:map
[:name ms/NonBlankString]
[:engine DBEngineString]
- [:details ms/Map]
+ [:details ms/KeywordizedMap]
[:is_full_sync {:default true} [:maybe ms/BooleanValue]]
[:is_on_demand {:default false} [:maybe ms/BooleanValue]]
[:schedules {:optional true} [:maybe sync.schedules/ExpandedSchedulesMap]]
[:auto_run_queries {:optional true} [:maybe :boolean]]
[:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
[:connection_source {:default :admin} [:maybe [:enum :admin :setup]]]
- [:provider_name {:optional true} [:maybe :string]]]]
+ [:provider_name {:optional true} [:maybe :string]]
+ [:is_stub {:optional true} [:maybe :boolean]]]]
(api/check-superuser)
(when (true? (:is_stub body))
(throw (ex-info (tru "is_stub may not be set via the API")
@@ -984,7 +986,7 @@
{{:keys [engine details]} :details} :- [:map
[:details [:map
[:engine DBEngineString]
- [:details ms/Map]]]]]
+ [:details ms/KeywordizedMap]]]]]
(api/check-superuser)
(let [details-or-error (warehouses/test-connection-details engine details)]
;; details that come back without a `:valid` key at all are... valid!
@@ -1080,8 +1082,8 @@
[:name {:optional true} [:maybe ms/NonBlankString]]
[:engine {:optional true} [:maybe DBEngineString]]
[:refingerprint {:optional true} [:maybe :boolean]]
- [:details {:optional true} [:maybe ms/Map]]
- [:write_data_details {:optional true} [:maybe ms/Map]]
+ [:details {:optional true} [:maybe ms/KeywordizedMap]]
+ [:write_data_details {:optional true} [:maybe ms/KeywordizedMap]]
[:schedules {:optional true} [:maybe sync.schedules/ExpandedSchedulesMap]]
[:is_full_sync {:optional true} [:maybe ms/BooleanValue]]
[:is_on_demand {:optional true} [:maybe ms/BooleanValue]]
@@ -1091,7 +1093,8 @@
[:auto_run_queries {:optional true} [:maybe :boolean]]
[:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
[:provider_name {:optional true} [:maybe :string]]
- [:settings {:optional true} [:maybe ms/Map]]]]
+ [:settings {:optional true} [:maybe ms/KeywordizedMap]]
+ [:is_stub {:optional true} [:maybe :boolean]]]]
(when (true? (:is_stub body))
(throw (ex-info (tru "is_stub may not be set via the API")
{:status-code 400})))
@@ -1328,10 +1331,10 @@
(defn- delete-all-field-values-for-database! [database-or-id]
(t2/query-one {:delete-from :metabase_fieldvalues
:where [:in :field_id
- {:select [:f.id]
- :from [[:metabase_field :f]]
- :right-join [[:metabase_table :t] [:= :f.table_id :t.id]]
- :where [:= :t.db_id (u/the-id database-or-id)]}]}))
+ ^:allow-subquery {:select [:f.id]
+ :from [[:metabase_field :f]]
+ :right-join [[:metabase_table :t] [:= :f.table_id :t.id]]
+ :where [:= :t.db_id (u/the-id database-or-id)]}]}))
;; TODO - should this be something like DELETE /api/database/:id/field_values instead?
;;
@@ -1621,7 +1624,8 @@
"Reports whether the database can currently connect"
[{:keys [id]} :- [:map [:id ms/PositiveInt]]
{:keys [connection-type]} :- [:map [:connection-type {:optional true} ::driver.conn/connection-type]]]
- (let [{:as database :keys [engine]} (t2/select-one :model/Database :id id)
+ (api/check-superuser)
+ (let [{:as database :keys [engine]} (api/check-404 (t2/select-one :model/Database :id id))
connection-type (or connection-type :default)
connection-details (driver.conn/details-for-exact-type database connection-type)]
(api/check-400 connection-details (tru "No {0} connection configured for this database" (name connection-type)))
diff --git a/src/metabase/xrays/api/automagic_dashboards.clj b/src/metabase/xrays/api/automagic_dashboards.clj
index 6d58eb96d4c..2bcbac765b1 100644
--- a/src/metabase/xrays/api/automagic_dashboards.clj
+++ b/src/metabase/xrays/api/automagic_dashboards.clj
@@ -8,6 +8,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.queries.core :as queries]
[metabase.query-permissions.core :as query-perms]
[metabase.util :as u]
@@ -248,11 +249,12 @@
"Identify the pk field of the model with `pk_ref`, and then find any fks that have that pk as a target."
[{{field-ref :pk_ref} :model-index {rsmd :result_metadata} :model}]
(when-let [field-id (:id (some #(when ((comp #{field-ref} :field_ref) %) %) rsmd))]
- (map
- (fn [{:keys [table_id id]}]
- {:linked-table-id table_id
- :linked-field-id id})
- (t2/select :model/Field :fk_target_field_id field-id))))
+ (let [fields (t2/hydrate (t2/select :model/Field :fk_target_field_id field-id) :table)]
+ (perms/prime-table-perms-cache {:table-ids (into #{} (map :table_id) fields)})
+ (for [{:keys [table_id id] :as field} fields
+ :when (mi/can-read? field)]
+ {:linked-table-id table_id
+ :linked-field-id id}))))
(defn- add-source-model-link
"Insert a source model link card into the sequence of passed in cards."
diff --git a/src/metabase/xrays/automagic_dashboards/core.clj b/src/metabase/xrays/automagic_dashboards/core.clj
index 997118f4a9e..63450365826 100644
--- a/src/metabase/xrays/automagic_dashboards/core.clj
+++ b/src/metabase/xrays/automagic_dashboards/core.clj
@@ -197,7 +197,7 @@
:dashboard-templates-prefix ["table"]})
(mu/defmethod ->root :model/Segment :- ::ads/root
- [segment :- [:map [:definition ::segments.schema/segment]]]
+ [segment :- [:map [:definition ::segments.schema/definition]]]
(let [table (->> segment :table_id (t2/select-one :model/Table :id))]
{:entity segment
:full-name (tru "{0} in the {1} segment" (:display_name table) (:name segment))
@@ -406,13 +406,15 @@
If there are multiple FKs pointing to the same table, multiple entries will
be returned."
[table]
- (for [{:keys [id target]} (field/with-targets
- (t2/select :model/Field
- :table_id (u/the-id table)
- :fk_target_field_id [:not= nil]
- :active true))
- :when (some-> target mi/can-read?)]
- (-> target field/table (assoc :link id))))
+ (let [fields (field/with-targets
+ (t2/select :model/Field
+ :table_id (u/the-id table)
+ :fk_target_field_id [:not= nil]
+ :active true))]
+ (perms/prime-table-perms-cache {:table-ids (into #{} (keep (comp :table_id :target)) fields)})
+ (for [{:keys [id target]} fields
+ :when (some-> target mi/can-read?)]
+ (-> target field/table (assoc :link id)))))
(defn- source->db [source]
(let [db-id (or ((some-fn :db_id :database_id) source)
@@ -767,7 +769,7 @@
(automagic-dashboard (merge (->root table) opts)))
(mu/defmethod automagic-analysis-method :model/Segment
- [segment :- [:map [:definition ::segments.schema/segment]]
+ [segment :- [:map [:definition ::segments.schema/definition]]
opts]
(automagic-dashboard (merge (->root segment) opts)))
@@ -938,18 +940,18 @@
[[:and
[:>= :ts.count 2]
[:= :ts.count_non_pks 1]] :list-like?]]
- {:inner-join [[{:select [:f.table_id
- [:%count.* "count"]
- [[:count [:case [:or [:not= :semantic_type "type/PK"]
- [:= :f.semantic_type nil]]
- [:inline 1] :else [:inline nil]]]
- :count_non_pks]
- [[:count [:case [:in :f.semantic_type ["type/PK" "type/FK"]]
- [:inline 1] :else [:inline nil]]]
- :count_pks_and_fks]]
- :from [[:metabase_field :f]]
- :where [:= :f.active true]
- :group-by [:f.table_id]} :ts]
+ {:inner-join [[^:allow-subquery {:select [:f.table_id
+ [:%count.* "count"]
+ [[:count [:case [:or [:not= :semantic_type "type/PK"]
+ [:= :f.semantic_type nil]]
+ [:inline 1] :else [:inline nil]]]
+ :count_non_pks]
+ [[:count [:case [:in :f.semantic_type ["type/PK" "type/FK"]]
+ [:inline 1] :else [:inline nil]]]
+ :count_pks_and_fks]]
+ :from [[:metabase_field :f]]
+ :where [:= :f.active true]
+ :group-by [:f.table_id]} :ts]
[:and [:= :ts.table_id :id]
[:> :ts.count 0]
[:!= :ts.count :ts.count_pks_and_fks]]]
diff --git a/src/metabase/xrays/automagic_dashboards/populate.clj b/src/metabase/xrays/automagic_dashboards/populate.clj
index ac9157b048f..2c754874700 100644
--- a/src/metabase/xrays/automagic_dashboards/populate.clj
+++ b/src/metabase/xrays/automagic_dashboards/populate.clj
@@ -1,7 +1,6 @@
(ns metabase.xrays.automagic-dashboards.populate
"Create and save models that make up automagic dashboards."
(:require
- [clojure.set :as set]
[clojure.string :as str]
[medley.core :as m]
[metabase.api.common :as api]
@@ -11,7 +10,6 @@
[metabase.lib.schema :as lib.schema]
[metabase.queries.core :as queries]
[metabase.query-processor.util :as qp.util]
- [metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
@@ -319,28 +317,6 @@
(let [g (group-by f coll)]
(access key-order g))))
-(mu/defn- create-dashboard-populate-dashcards :- [:sequential ::ads/dashcard]
- [dashcards :- [:maybe [:sequential ::ads/card-template]]]
- ;; disable ref validation because X-Rays does stuff in a wacko manner, it adds a bunch of filters and whatever that
- ;; use columns from joins before adding the joins themselves (same with expressions), which is technically invalid
- ;; at the time it happens but ends up resulting in a valid query at the end of the day. Maybe one day we can rework
- ;; this code to be saner
- (let [card-id->can-run-adhoc-query (binding [lib.schema/*HACK-disable-ref-validation* true]
- (into {}
- (map (juxt ::id :can_run_adhoc_query))
- (queries/with-can-run-adhoc-query
- (for [{:keys [card]} dashcards
- :when (and (:id card)
- (:dataset_query card))]
- (-> card
- (update :dataset_query lib-be/normalize-query)
- (set/rename-keys {:id ::id}))))))]
- (for [dashcard dashcards
- :let [card (:card dashcard)
- card (when (seq card)
- (assoc card :can_run_adhoc_query (get card-id->can-run-adhoc-query (:id card))))]]
- (u/assoc-dissoc dashcard :card card))))
-
(mu/defn create-dashboard :- ::ads/dashboard
"Create dashboard and populate it with cards."
([dashboard] (create-dashboard dashboard :all))
@@ -367,8 +343,7 @@
[dashboard
;; Height doesn't need to be precise, just some
;; safe upper bound.
- (make-grid grid-width (* n grid-width))]))
- dashboard (update dashboard :dashcards create-dashboard-populate-dashcards)]
+ (make-grid grid-width (* n grid-width))]))]
(log/debugf "Adding %s cards to dashboard" (count cards))
(cond-> (update dashboard :dashcards (partial sort-by (juxt :row :col)))
(not-empty filters) (filters/add-filters filters max-filters)))))
diff --git a/src/metabase/xrays/related.clj b/src/metabase/xrays/related.clj
index 54b810acefe..9d344530f01 100644
--- a/src/metabase/xrays/related.clj
+++ b/src/metabase/xrays/related.clj
@@ -53,7 +53,7 @@
((juxt lib/breakouts lib/aggregations lib/expressions lib/fields))))
(mu/defmethod definition :model/Segment
- [segment :- [:map [:definition ::segments.schema/segment]]]
+ [segment :- [:map [:definition ::segments.schema/definition]]]
(-> segment :definition :stages first :filters not-empty))
(defmethod definition :model/Field
diff --git a/test/metabase/channel/impl/http_test.clj b/test/metabase/channel/impl/http_test.clj
index aa99757228d..37151528491 100644
--- a/test/metabase/channel/impl/http_test.clj
+++ b/test/metabase/channel/impl/http_test.clj
@@ -4,6 +4,7 @@
[clj-http.client :as http]
[clojure.string :as str]
[clojure.test :refer :all]
+ [clojure.walk :as walk]
[compojure.core :as compojure]
[compojure.route :as compojure.route]
[metabase.channel.core :as channel]
@@ -51,7 +52,13 @@
handler
middlewares))
-(def middlewares [mw.json/wrap-json-body
+(defn- wrap-keywordize-json-body
+ [handler]
+ (fn [req]
+ (handler (update req :body #(cond-> % (map? %) walk/keywordize-keys)))))
+
+(def middlewares [wrap-keywordize-json-body
+ mw.json/wrap-json-body
mw.json/wrap-streamed-json-response
wrap-params])
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index 8b5a98b61a0..875bd37650c 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -6,7 +6,6 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.collections-rest.api :as api.collection]
- [metabase.collections-rest.settings :as collections-rest.settings]
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection-test :as collection-test]
[metabase.collections.test-utils :refer [with-library-not-synced without-library]]
@@ -1504,101 +1503,6 @@
(into #{} (map #(select-keys % [:name :authority_level]))
items))))))))
-(deftest collection-items-include-can-run-adhoc-query-test
- (testing "GET /api/collection/:id/items and GET /api/collection/root/items"
- (testing "include_can_run_adhoc_query parameter controls hydration of can_run_adhoc_query flag"
- (mt/with-temp [:model/Collection {collection-id :id} {}
- :model/Card {card-id :id} {:collection_id collection-id}
- :model/Card {root-card-id :id} {:collection_id nil}]
- (testing "When include_can_run_adhoc_query=false (default), can_run_adhoc_query is not included"
- (let [collection-items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")))
- root-items (:data (mt/user-http-request :rasta :get 200 "collection/root/items"))]
- (is (not (contains? (first collection-items) :can_run_adhoc_query)))
- (is (not (some #(contains? % :can_run_adhoc_query) root-items)))))
- (testing "When include_can_run_adhoc_query=true, can_run_adhoc_query is included for cards"
- (let [collection-items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")
- :include_can_run_adhoc_query true))
- root-items (:data (mt/user-http-request :rasta :get 200 "collection/root/items"
- :include_can_run_adhoc_query true))
- card-item (first (filter #(= (:id %) card-id) collection-items))
- root-card-item (first (filter #(= (:id %) root-card-id) root-items))]
- (is (contains? card-item :can_run_adhoc_query))
- (is (boolean? (:can_run_adhoc_query card-item)))
- (is (contains? root-card-item :can_run_adhoc_query))
- (is (boolean? (:can_run_adhoc_query root-card-item)))))
- (testing "can_run_adhoc_query is only added to card-like models (card, dataset, metric)"
- (mt/with-temp [:model/Dashboard {dashboard-id :id} {:collection_id collection-id}
- :model/Collection {subcoll-id :id} {:location (collection/children-location
- (t2/select-one :model/Collection :id collection-id))}]
- (let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")
- :include_can_run_adhoc_query true))
- dashboard-item (first (filter #(= (:id %) dashboard-id) items))
- collection-item (first (filter #(= (:id %) subcoll-id) items))]
- (is (not (contains? dashboard-item :can_run_adhoc_query)))
- (is (not (contains? collection-item :can_run_adhoc_query))))))))))
-
-(deftest can-run-adhoc-query-threshold-exceeded-test
- (testing "GET /api/collection/:id/items with include_can_run_adhoc_query=true"
- (testing "When card count exceeds threshold, can_run_adhoc_query returns true (skips permission check)"
- (let [card-query {:database (mt/id)
- :type :query
- :query {:source-table (mt/id :venues)}}]
- (mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection {collection-id :id} {}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}]
- (mt/with-temporary-setting-values [collections-rest.settings/can-run-adhoc-query-check-threshold 2]
- (let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")
- :include_can_run_adhoc_query true))]
- ;; With 3 cards and threshold of 2, all cards should have can_run_adhoc_query=true
- ;; even though user doesn't have data permissions (computation was skipped)
- (is (= 3 (count items)))
- (is (every? #(true? (:can_run_adhoc_query %)) items))))))))))
-
-(deftest can-run-adhoc-query-threshold-not-exceeded-test
- (testing "GET /api/collection/:id/items with include_can_run_adhoc_query=true"
- (testing "When card count is at or below threshold, normal hydration occurs (returns false without perms)"
- (let [card-query {:database (mt/id)
- :type :query
- :query {:source-table (mt/id :venues)}}]
- (mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection {collection-id :id} {}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}]
- (mt/with-temporary-setting-values [collections-rest.settings/can-run-adhoc-query-check-threshold 5]
- (let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")
- :include_can_run_adhoc_query true))]
- ;; With 2 cards and threshold of 5, actual permission check occurs
- ;; User doesn't have data permissions, so all should be false
- (is (= 2 (count items)))
- (is (every? #(false? (:can_run_adhoc_query %)) items))))))))))
-
-(deftest can-run-adhoc-query-threshold-disabled-test
- (testing "GET /api/collection/:id/items with include_can_run_adhoc_query=true"
- (testing "When threshold is 0, always compute permissions regardless of card count"
- (let [card-query {:database (mt/id)
- :type :query
- :query {:source-table (mt/id :venues)}}]
- (mt/with-no-data-perms-for-all-users!
- (mt/with-temp [:model/Collection {collection-id :id} {}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}
- :model/Card _ {:collection_id collection-id :dataset_query card-query}]
- (mt/with-temporary-setting-values [collections-rest.settings/can-run-adhoc-query-check-threshold 0]
- (let [items (:data (mt/user-http-request :rasta :get 200
- (str "collection/" collection-id "/items")
- :include_can_run_adhoc_query true))]
- ;; With threshold of 0, hydration should always occur
- ;; User doesn't have data permissions, so all should be false
- (is (= 3 (count items)))
- (is (every? #(false? (:can_run_adhoc_query %)) items))))))))))
-
(deftest collection-items-include-datasets-test
(testing "GET /api/collection/:id/items"
(testing "Includes datasets"
diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.clj
index 2cb40bdbfe7..2013c85e8d2 100644
--- a/test/metabase/dashboards_rest/api_test.clj
+++ b/test/metabase/dashboards_rest/api_test.clj
@@ -141,6 +141,11 @@
(defmacro ^:private with-dashboards-in-writeable-collection! [dashboards-or-ids & body]
`(do-with-dashboards-in-a-collection! perms/grant-collection-readwrite-permissions! ~dashboards-or-ids (fn [] ~@body)))
+(defn- move-cards-to-dashboard-collection!
+ [dashboard-or-id card-ids]
+ (t2/update! :model/Card {:id [:in card-ids]}
+ {:collection_id (t2/select-one-fn :collection_id :model/Dashboard :id (u/the-id dashboard-or-id))}))
+
(defn- implicit-fk-column-ref
"The legacy `[:field id {:source-field fk-id}]` ref for the column with `target-field-id`, as reached implicitly via
an FK from `from-table-key` (e.g. `products.category` reached via `orders.product_id`)."
@@ -2459,6 +2464,7 @@
:model/DashboardCard {dashcard-id-2 :id} {:dashboard_id dashboard-id, :card_id card-id}
:model/Card {series-id-1 :id} {:name "Series Card"}]
(with-dashboards-in-writeable-collection! [dashboard-id]
+ (move-cards-to-dashboard-collection! dashboard-id [card-id series-id-1])
(is (= {:size_x 4
:size_y 4
:col 0
@@ -2558,6 +2564,7 @@
:card_id model-id}
:model/DashboardCard question-card {:dashboard_id dashboard-id, :card_id model-id}]
(with-dashboards-in-writeable-collection! [dashboard-id]
+ (move-cards-to-dashboard-collection! dashboard-id [model-id model-id-2])
;; TODO adds test for return
;; Update **both** cards to use the new card id
(mt/user-http-request :rasta :put 200 (format "dashboard/%d" dashboard-id)
@@ -2600,6 +2607,7 @@
:model/DashboardCardSeries _ {:dashboardcard_id dashcard-id-1, :card_id series-id-2, :position 1}
:model/DashboardCardSeries _ {:dashboardcard_id dashcard-id-3, :card_id series-id-1, :position 0}]
(with-dashboards-in-writeable-collection! [dashboard-id]
+ (move-cards-to-dashboard-collection! dashboard-id [card-id series-id-1 series-id-2])
(is (= 3
(count (t2/select-pks-set :model/DashboardCard, :dashboard_id dashboard-id))))
(is (=? {:dashcards [{:id dashcard-id-3
@@ -3804,7 +3812,7 @@
(deftest dashboard-card-query-metric-sourced-from-inaccessible-model-test
(testing "POST /api/dashboard/:dashboard-id/dashcard/:dashcard-id/card/:card-id/query with a metric sourced from a model"
- (testing "runs for a user without collection access to the source model"
+ (testing "is refused for a caller without collection access to the source model"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp [:model/Collection model-coll {}
:model/Collection dash-coll {}
@@ -3821,10 +3829,10 @@
:model/DashboardCard dashcard {:dashboard_id (u/the-id dashboard)
:card_id (u/the-id metric)}]
(perms/grant-collection-read-permissions! (perms-group/all-users) dash-coll)
- (is (= [[18760]]
- (mt/rows (mt/user-http-request :rasta :post 202
- (dashboard-card-query-url
- (u/the-id dashboard) (u/the-id metric) (u/the-id dashcard)))))))))
+ (is (re-find #"You do not have permissions to view Card"
+ (str (mt/user-http-request :rasta :post 403
+ (dashboard-card-query-url
+ (u/the-id dashboard) (u/the-id metric) (u/the-id dashcard)))))))))
(testing "runs for a user without query-building data perms"
(mt/with-temp [:model/Collection coll {}
:model/Card model {:type :model
@@ -5123,8 +5131,6 @@
(mt/user-http-request :crowberto :get 200
(format "dashboard/%d/query_metadata?dashboard_load_id=%s" (:id d) load-id))))
(testing "Call count for :metadata/table is smaller with caching in place"
- ;; with disabled can_run_adhoc_query these numbers might now match. Without disabled it was 5, with disabling
- ;; it is 1
(is (<= @cached-calls-count @uncached-calls-count)))
;; If we need more for _some reason_, this test should be updated accordingly.
(testing "At most 1 db call should be executed for :metadata/tables"
@@ -5456,6 +5462,7 @@
:values_source_type "static-list"
:values_source_config {:values ["A" "B" "C"]}}]}]
(with-dashboards-in-writeable-collection! [dashboard-id]
+ (move-cards-to-dashboard-collection! dashboard-id [source-card-id])
(testing "Initial parameter cards are created for card-sourced parameters only"
(is (= 1 (t2/count :model/ParameterCard :parameterized_object_type "dashboard"
:parameterized_object_id dashboard-id))))
@@ -5515,6 +5522,7 @@
:values_source_type "card"
:values_source_config {:card_id source-card-id-1}}]}]
(with-dashboards-in-writeable-collection! [dashboard-id]
+ (move-cards-to-dashboard-collection! dashboard-id [source-card-id-1 source-card-id-2])
(testing "Initial parameter cards are created"
(is (= 2 (t2/count :model/ParameterCard :parameterized_object_type "dashboard"
:parameterized_object_id dashboard-id))))
@@ -6223,22 +6231,6 @@
(is (=? [{:target target}]
(t2/select-one-fn :parameter_mappings :model/DashboardCard :id dc-id))))))))
-(deftest swap-dashcard-card-id-requires-no-card-permission-test
- (testing "PUT /api/dashboard/:id swapping a dashcard's card_id needs no data/read perms on the new card"
- (mt/with-non-admin-groups-no-root-collection-perms
- (let [mp (mt/metadata-provider)]
- (mt/with-temp [:model/Collection {coll-id :id} {}
- :model/Dashboard {dash-id :id} {:collection_id coll-id}
- :model/Card {c1-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
- :model/Card {c2-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
- :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id c1-id}]
- (perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll-id)
- (mt/with-no-data-perms-for-all-users!
- (is (=? [{:card_id c2-id}]
- (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" dash-id)
- {:dashcards [{:id dc-id :card_id c2-id :row 0 :col 0 :size_x 4 :size_y 4}]
- :tabs []}))))))))))
-
(deftest update-card-id-preserves-mismatched-stale-parameter-mappings-test
(testing "PUT /api/dashboard/:id changing a dashcard's card_id does not validate/prune stale parameter_mappings"
(let [mp (mt/metadata-provider)]
diff --git a/test/metabase/documents/api/document_test.clj b/test/metabase/documents/api/document_test.clj
index b64a2529832..a98ba4cd2ba 100644
--- a/test/metabase/documents/api/document_test.clj
+++ b/test/metabase/documents/api/document_test.clj
@@ -496,7 +496,7 @@
:display :table
:visualization_settings {}}}]
(mt/user-http-request :crowberto
- :post 403 "document/"
+ :post 400 "document/"
{:name "Document That Should Rollback"
:document (documents.test-util/text->prose-mirror-ast "Doc that should rollback")
:cards invalid-cards})
@@ -514,7 +514,7 @@
:display :table
:visualization_settings {}}}]
(mt/user-http-request :crowberto
- :put 403 (format "document/%s" document-id)
+ :put 400 (format "document/%s" document-id)
{:name "Document That Should Rollback"
:document (documents.test-util/text->prose-mirror-ast "Doc that should rollback")
:cards invalid-cards})
diff --git a/test/metabase/documents/revisions/impl_test.clj b/test/metabase/documents/revisions/impl_test.clj
index e87b51cd18c..50422c82650 100644
--- a/test/metabase/documents/revisions/impl_test.clj
+++ b/test/metabase/documents/revisions/impl_test.clj
@@ -98,4 +98,4 @@
(is (contains? excluded-columns :updated_at))
(is (contains? excluded-columns :collection_id))
(is (contains? excluded-columns :collection_position))
- (is (= 8 (count excluded-columns)) "Should exclude exactly 5 metadata fields"))))
+ (is (= 10 (count excluded-columns)) "Should exclude exactly 10 metadata fields"))))
diff --git a/test/metabase/documents/test_util.clj b/test/metabase/documents/test_util.clj
index b463dcf2fda..eb3856eef74 100644
--- a/test/metabase/documents/test_util.clj
+++ b/test/metabase/documents/test_util.clj
@@ -10,3 +10,9 @@
:content [{:type "paragraph"
:content [{:type "text"
:text text}]}]}))
+
+(defn cards->prose-mirror-ast
+ "Build a ProseMirror document AST that embeds each id in `card-ids` as a `cardEmbed` node."
+ [card-ids]
+ {:type "doc"
+ :content (mapv (fn [id] {:type "cardEmbed" :attrs {:id id :name nil}}) card-ids)})
diff --git a/test/metabase/driver/sql_jdbc/actions_test.clj b/test/metabase/driver/sql_jdbc/actions_test.clj
index ed4e3399cb3..787747f71d7 100644
--- a/test/metabase/driver/sql_jdbc/actions_test.clj
+++ b/test/metabase/driver/sql_jdbc/actions_test.clj
@@ -23,7 +23,7 @@
(mt/with-test-user :rasta
(thunk))))
-(mu/defn- cast-values :- ::actions.args/row
+(mu/defn- cast-values :- [:map-of :string :any]
[driver :- :keyword
column->value :- ::actions.args/row
table-id :- ::lib.schema.id/table]
diff --git a/test/metabase/embedding_rest/api/preview_embed_test.clj b/test/metabase/embedding_rest/api/preview_embed_test.clj
index 7747ace173e..9e93579cfc2 100644
--- a/test/metabase/embedding_rest/api/preview_embed_test.clj
+++ b/test/metabase/embedding_rest/api/preview_embed_test.clj
@@ -524,7 +524,7 @@
`(do-with-new-secret-key! (fn [] ~@body)))
(defmacro with-embedding-enabled-and-new-secret-key! {:style/indent 0} [& body]
- `(mt/with-temporary-setting-values [~'enable-embedding true]
+ `(mt/with-temporary-setting-values [~'enable-embedding-static true]
(with-new-secret-key!
~@body)))
@@ -569,7 +569,7 @@
(testing "\nGET /api/preview_embed/dashboard/:token/params/:param-key/values"
(is (= {:values [["African"] ["American"] ["Asian"]]
:has_more_values false}
- (mt/user-http-request :rasta :get 200 url))))))))))
+ (mt/user-http-request :crowberto :get 200 url))))))))))
(deftest preview-locked-linked-chain-filter-values-test
(testing "GET /api/preview_embed/dashboard/:token/params/:key/values constrains a linked enabled param by a locked param (#41635)"
diff --git a/test/metabase/lib/fe_util_test.cljc b/test/metabase/lib/fe_util_test.cljc
index c9df628a706..ac68bcb8103 100644
--- a/test/metabase/lib/fe_util_test.cljc
+++ b/test/metabase/lib/fe_util_test.cljc
@@ -219,9 +219,7 @@
(lib/expression expression-name
(lib/* (lib.tu/field-clause :venues :price {:base-type :type/Integer}) 2))
(lib/expression other-expression-name
- [:expression {:base-type :type/Integer} expression-name]))
- ;;
-
+ [:expression {:base-type :type/Integer, :lib/uuid (str (random-uuid))} expression-name]))
stage-number -1]
(testing "expression references"
(mu/disable-enforcement
diff --git a/test/metabase/measures/api_test.clj b/test/metabase/measures/api_test.clj
index 19f1d4fecbc..36fff189aee 100644
--- a/test/metabase/measures/api_test.clj
+++ b/test/metabase/measures/api_test.clj
@@ -57,18 +57,16 @@
(testing "POST /api/measure"
(is (=? {:errors {:name "value must be a non-blank string."}}
(mt/user-http-request :crowberto :post 400 "measure" {})))
- (is (=? {:errors {:definition "Value must be a map."}}
+ (is (=? {:errors {:definition "value must be a valid MBQL query with a source table."}}
(mt/user-http-request :crowberto :post 400 "measure" {:name "abc"})))
- (is (=? {:errors {:definition "Value must be a map."}}
- (mt/user-http-request :crowberto :post 400 "measure" {:name "abc"
- :definition "foobar"})))
- (testing "definition must specify a source table"
- (is (= "Measure definition must specify a source table."
- (mt/user-http-request :crowberto :post 400 "measure" {:name "abc"
- :definition {}})))
- (is (= "Measure definition must specify a source table."
- (mt/user-http-request :crowberto :post 400 "measure" {:name "abc"
- :definition {:aggregation [[:count]]}}))))))
+ (testing "a non-map definition is rejected while decoding, so the body is the message rather than :errors"
+ (is (=? "value must be a valid MBQL query."
+ (mt/user-http-request :crowberto :post 400 "measure" {:name "abc"
+ :definition "foobar"}))))
+ (testing "a definition that isn't a full MBQL query (e.g. a bare MBQL4 fragment) is rejected"
+ (is (=? "Query must include :lib/type or :type"
+ (mt/user-http-request :crowberto :post 400 "measure" {:name "abc"
+ :definition {:aggregation [[:count]]}}))))))
(deftest create-measure-test
(testing "POST /api/measure"
@@ -97,7 +95,7 @@
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "measure/" (:id measure))
{:name "abc"
- :definition {}
+ :definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))
:revision_message "something different"})))))))
(deftest update-input-validation-test
@@ -109,20 +107,20 @@
(is (=? {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request :crowberto :put 400 "measure/1" {:name "abc"
:revision_message ""})))
- (is (=? {:errors {:definition "nullable Value must be a map."}}
+ (is (=? "value must be a valid MBQL query."
(mt/user-http-request :crowberto :put 400 "measure/1" {:name "abc"
:revision_message "123"
:definition "foobar"})))))
(deftest update-definition-table-test
(testing "PUT /api/measure/:id"
- (testing "an updated definition must still specify a source table"
+ (testing "an updated definition must still be a valid MBQL query with a source table"
(mt/with-temp [:model/Measure {:keys [id]} {:table_id (mt/id :venues)
:definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))}]
- (is (= "Measure definition must specify a source table."
- (mt/user-http-request :crowberto :put 400 (str "measure/" id)
- {:revision_message "no more source table"
- :definition {}})))))
+ (is (=? {:errors {:definition some?}}
+ (mt/user-http-request :crowberto :put 400 (str "measure/" id)
+ {:revision_message "no more source table"
+ :definition {}})))))
(testing "a definition that moves the Measure to another table keeps table_id in sync"
(mt/with-temp [:model/Measure {:keys [id]} {:table_id (mt/id :venues)
:definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))}]
@@ -354,14 +352,12 @@
(deftest api-accepts-mbql4-on-post-test
(testing "POST /api/measure accepts MBQL4 definitions and returns MBQL5"
(mt/with-model-cleanup [:model/Measure]
- (testing "MBQL4 fragment format"
- (let [response (mt/user-http-request
- :crowberto :post 200 "measure"
- {:name "Fragment Measure"
- :definition (mbql4-fragment-definition (mt/id :venues) [[:count]])})]
- (is (some? (:id response)))
- (is (mbql5-definition? (:definition response))
- "Returned definition should be MBQL5")))
+ (testing "an MBQL4 fragment is rejected with the specific normalization error"
+ (is (= "Query must include :lib/type or :type"
+ (mt/user-http-request
+ :crowberto :post 400 "measure"
+ {:name "Fragment Measure"
+ :definition (mbql4-fragment-definition (mt/id :venues) [[:count]])}))))
(testing "MBQL4 full query format"
(let [response (mt/user-http-request
:crowberto :post 200 "measure"
@@ -375,14 +371,12 @@
(testing "PUT /api/measure/:id accepts MBQL4 definitions and returns MBQL5"
(mt/with-temp [:model/Measure {measure-id :id} {:table_id (mt/id :venues)
:definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))}]
- (testing "MBQL4 fragment format"
- (let [response (mt/user-http-request
- :crowberto :put 200 (str "measure/" measure-id)
- {:revision_message "Update with fragment"
- :definition (mbql4-fragment-definition (mt/id :venues) [[:count]])})]
- (is (= measure-id (:id response)))
- (is (mbql5-definition? (:definition response))
- "Returned definition should be MBQL5")))
+ (testing "an MBQL4 fragment is rejected -- see `api-accepts-mbql4-on-post-test`"
+ (is (= "Query must include :lib/type or :type"
+ (mt/user-http-request
+ :crowberto :put 400 (str "measure/" measure-id)
+ {:revision_message "Update with fragment"
+ :definition (mbql4-fragment-definition (mt/id :venues) [[:count]])}))))
(testing "MBQL4 full query format"
(let [response (mt/user-http-request
:crowberto :put 200 (str "measure/" measure-id)
@@ -398,7 +392,7 @@
(let [{measure-id :id} (mt/user-http-request
:crowberto :post 200 "measure"
{:name "Venue Count"
- :definition (mbql4-fragment-definition (mt/id :venues) [[:count]])})
+ :definition (legacy-mbql-measure-definition (mt/id) (mt/id :venues) [[:count]])})
measure-query (mt/mbql-query venues {:aggregation [[:measure measure-id]]})
direct-query (mt/mbql-query venues {:aggregation [[:count]]})]
(is (= (mt/rows (qp/process-query direct-query))
diff --git a/test/metabase/metabot/agent/user_context_test.clj b/test/metabase/metabot/agent/user_context_test.clj
index 722cd2b7bd6..6b9cf0ed89f 100644
--- a/test/metabase/metabot/agent/user_context_test.clj
+++ b/test/metabase/metabot/agent/user_context_test.clj
@@ -211,7 +211,7 @@
(deftest ^:parallel format-viewing-context-test-2h
(testing "handles multiple viewing items"
- (let [context {:user_is_viewing [{:type "table" :id 1 :name "users"}
+ (let [context {:user_is_viewing [{:type "table" :id 321 :name "users"}
{:type "question" :id 2 :name "Top Users"}]}
result (user-context/format-viewing-context context)]
(is (some? result))
diff --git a/test/metabase/metabot/tools/construct_representations_test.clj b/test/metabase/metabot/tools/construct_representations_test.clj
index 1dd2b3ed1ed..2a2814cc9b9 100644
--- a/test/metabase/metabot/tools/construct_representations_test.clj
+++ b/test/metabase/metabot/tools/construct_representations_test.clj
@@ -1173,12 +1173,15 @@
"Valid 21-char NanoID so `import-mbql` picks up the `[:metric …]` branch."
"Metric123_456DefGhI78")
+(def ^:private mock-db-id
+ Integer/MAX_VALUE)
+
(def ^:private mp-metric-base
"ORDERS(10) and CAMPAIGNS(30) with NO foreign key between them."
(lib.tu/mock-metadata-provider
- {:database {:id 1 :name "Sample"}
- :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
- {:id 30 :name "CAMPAIGNS" :schema "PUBLIC" :db-id 1}]
+ {:database {:id mock-db-id :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id mock-db-id}
+ {:id 30 :name "CAMPAIGNS" :schema "PUBLIC" :db-id mock-db-id}]
:fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
{:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
{:id 102 :name "CAMPAIGN_ID" :table-id 10 :base-type :type/Integer} ;; NO :fk-target-field-id
@@ -1197,14 +1200,14 @@
(def ^:private mp-metric
(lib.tu/mock-metadata-provider
mp-metric-base
- {:cards [{:id 700 :name "Order Count by Campaign" :type :metric :database-id 1 :table-id 10
+ {:cards [{:id 700 :name "Order Count by Campaign" :type :metric :database-id mock-db-id :table-id 10
:entity-id metric-eid :dataset-query metric-definition}]}))
(defn- with-joined-metric-mp-and-stubs! [f]
(with-redefs [lib-be/application-database-metadata-provider (fn [_] mp-metric)
- construct/resolve-database-id-from-first-stage (fn [_] 1)
+ construct/resolve-database-id-from-first-stage (fn [_] mock-db-id)
construct/permission-aware-content-store (stub-content-store
- {:id 700 :database_id 1 :entity_id metric-eid})
+ {:id 700 :database_id mock-db-id :entity_id metric-eid})
api/read-check allow-read-check
api/query-check allow-read-check
;; `metric-details` gates its base table and every surfaced column on app-db
@@ -1213,7 +1216,8 @@
;; app-DB-free (see the fixture note above). That the surfaced dimensions ARE
;; permission-filtered is covered against real tables in entity-details-test.
mi/can-read? (constantly true)
- entity-details/permission-filter-columns identity
+ mi/can-query? (constantly true)
+ entity-details/permission-filter-columns (fn [cols & _] cols)
entity-details/verified-review? (constantly false)]
(f)))
diff --git a/test/metabase/permissions_rest/api_test.clj b/test/metabase/permissions_rest/api_test.clj
index 3a3bff0023e..2df0a28d723 100644
--- a/test/metabase/permissions_rest/api_test.clj
+++ b/test/metabase/permissions_rest/api_test.clj
@@ -516,9 +516,14 @@
(deftest update-perms-graph-error-test
(testing "PUT /api/permissions/graph"
(testing "make sure an error is thrown if the :sandboxes key is included in an OSS request"
- (mt/with-premium-features #{}
- (mt/assert-has-premium-feature-error "Sandboxes" (mt/user-http-request :crowberto :put 402 "permissions/graph"
- (assoc (data-perms.graph/api-graph) :sandboxes [{:card_id 1}])))))))
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Table {table-id :id} {:db_id (mt/id) :schema "PUBLIC"}]
+ (mt/with-premium-features #{}
+ (mt/assert-has-premium-feature-error
+ "Sandboxes"
+ (mt/user-http-request :crowberto :put 402 "permissions/graph"
+ (assoc (data-perms.graph/api-graph)
+ :sandboxes [{:group_id group-id, :table_id table-id, :card_id 1}]))))))))
(deftest update-perms-graph-blocked-view-data-test
(testing "PUT /api/permissions/graph"
diff --git a/test/metabase/public_sharing_rest/api_documents_test.clj b/test/metabase/public_sharing_rest/api_documents_test.clj
index 3d66d73a207..d17070f82ce 100644
--- a/test/metabase/public_sharing_rest/api_documents_test.clj
+++ b/test/metabase/public_sharing_rest/api_documents_test.clj
@@ -72,6 +72,8 @@
:model/Card {card2-id :id} {:name "Card 2"
:dataset_query (mt/mbql-query venues {:limit 10})
:document_id (:id document)}]
+ (t2/update! :model/Document (:id document)
+ {:document (documents.test-util/cards->prose-mirror-ast [card1-id card2-id])})
(let [result (mt/client :get 200 (str "public/document/" (:public_uuid document)))]
(testing "response includes cards field"
(is (contains? result :cards)))
@@ -132,6 +134,8 @@
:model/Card card {:name "Test Card"
:dataset_query (mt/mbql-query venues {:limit 5})
:document_id (:id document)}]
+ (t2/update! :model/Document (:id document)
+ {:document (documents.test-util/cards->prose-mirror-ast [(:id card)])})
(let [result (mt/client :get 202 (format "public/document/%s/card/%d" (:public_uuid document) (:id card)))]
(is (some? result))
(is (= "completed" (:status result)))))))))
@@ -154,6 +158,8 @@
:model/Card card {:name "Export Test Card"
:dataset_query (mt/mbql-query venues {:limit 5})
:document_id (:id document)}]
+ (t2/update! :model/Document (:id document)
+ {:document (documents.test-util/cards->prose-mirror-ast [(:id card)])})
(testing "Can export card results as CSV"
(let [response (mt/client-full-response :post (format "public/document/%s/card/%d/csv"
(:public_uuid document)
diff --git a/test/metabase/public_sharing_rest/api_test.clj b/test/metabase/public_sharing_rest/api_test.clj
index fbd24453a9c..8406f39b06c 100644
--- a/test/metabase/public_sharing_rest/api_test.clj
+++ b/test/metabase/public_sharing_rest/api_test.clj
@@ -476,7 +476,7 @@
:parameters (json/encode [{:type "category"
:value "456"
:target ["variable" ["template-tag" "foo"]]
- :id "ed1fd39e-2e35-636f-ec44-8bf226cca5b0"}])))))))))
+ :id "abc123"}])))))))))
(deftest execute-public-card-with-default-parameters-test
(testing "GET /api/public/card/:uuid/query with parameters with default values"
diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.clj
index 6e2fa951f06..5dbee49b53b 100644
--- a/test/metabase/pulse/dashboard_subscription_test.clj
+++ b/test/metabase/pulse/dashboard_subscription_test.clj
@@ -902,28 +902,29 @@
card-id
model-id
dashboard-id]}]
- (let [site-url (system/site-url)]
- (testing "should returns all link cards and name are newly fetched"
- (doseq [[model id] [[:model/Card card-id]
- [:model/Table table-id]
- [:model/Database database-id]
- [:model/Dashboard dashboard-id]
- [:model/Collection collection-id]
- [:model/Card model-id]]]
- (t2/update! model id {:name (format "New %s name" (name model))}))
- (is (=? [{:text (format "### [New Collection name](%s/collection/%d)\nLinked collection desc" site-url collection-id)}
- {:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
- {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
- {:text (format "### [New Dashboard name](%s/dashboard/%d)\nLinked Dashboard desc" site-url dashboard-id)}
- {:text (format "### [New Card name](%s/question/%d)\nLinked card desc" site-url card-id)}
- {:text (format "### [New Card name](%s/question/%d)\nLinked model desc" site-url model-id)}
- {:text "### [https://metabase.com](https://metabase.com)"}]
- (execute-dashboard (:id dashboard) collection-owner-id nil))))
- (testing "it should filter out models that current users does not have permission to read"
- (is (=? [{:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
- {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
- {:text "### [https://metabase.com](https://metabase.com)"}]
- (execute-dashboard (:id dashboard) (mt/user->id :lucky) nil)))))))))
+ (mt/with-temporary-setting-values [site-url "https://testmb.com"]
+ (let [site-url (system/site-url)]
+ (testing "should returns all link cards and name are newly fetched"
+ (doseq [[model id] [[:model/Card card-id]
+ [:model/Table table-id]
+ [:model/Database database-id]
+ [:model/Dashboard dashboard-id]
+ [:model/Collection collection-id]
+ [:model/Card model-id]]]
+ (t2/update! model id {:name (format "New %s name" (name model))}))
+ (is (=? [{:text (format "### [New Collection name](%s/collection/%d)\nLinked collection desc" site-url collection-id)}
+ {:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
+ {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
+ {:text (format "### [New Dashboard name](%s/dashboard/%d)\nLinked Dashboard desc" site-url dashboard-id)}
+ {:text (format "### [New Card name](%s/question/%d)\nLinked card desc" site-url card-id)}
+ {:text (format "### [New Card name](%s/question/%d)\nLinked model desc" site-url model-id)}
+ {:text "### [https://metabase.com](https://metabase.com)"}]
+ (execute-dashboard (:id dashboard) collection-owner-id nil))))
+ (testing "it should filter out models that current users does not have permission to read"
+ (is (=? [{:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
+ {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
+ {:text "### [https://metabase.com](https://metabase.com)"}]
+ (execute-dashboard (:id dashboard) (mt/user->id :lucky) nil))))))))))
(deftest iframe-cards-are-skipped-test
(testing "iframe cards should be filtered out"
@@ -952,28 +953,29 @@
card-id
model-id
dashboard-id]}]
- (let [site-url (system/site-url)]
- (testing "should returns all link cards and name are newly fetched"
- (doseq [[model id] [[:model/Card card-id]
- [:model/Table table-id]
- [:model/Database database-id]
- [:model/Dashboard dashboard-id]
- [:model/Collection collection-id]
- [:model/Card model-id]]]
- (t2/update! model id {:name (format "New %s name" (name model))}))
- (is (=? [{:text (format "### [New Collection name](%s/collection/%d)\nLinked collection desc" site-url collection-id)}
- {:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
- {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
- {:text (format "### [New Dashboard name](%s/dashboard/%d)\nLinked Dashboard desc" site-url dashboard-id)}
- {:text (format "### [New Card name](%s/question/%d)\nLinked card desc" site-url card-id)}
- {:text (format "### [New Card name](%s/question/%d)\nLinked model desc" site-url model-id)}
- {:text "### [https://metabase.com](https://metabase.com)"}]
- (execute-dashboard (:id dashboard) collection-owner-id nil))))
- (testing "it should filter out models that current users does not have permission to read"
- (is (=? [{:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
- {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
- {:text "### [https://metabase.com](https://metabase.com)"}]
- (execute-dashboard (:id dashboard) (mt/user->id :lucky) nil)))))))))
+ (mt/with-temporary-setting-values [site-url "https://testmb.com"]
+ (let [site-url (system/site-url)]
+ (testing "should returns all link cards and name are newly fetched"
+ (doseq [[model id] [[:model/Card card-id]
+ [:model/Table table-id]
+ [:model/Database database-id]
+ [:model/Dashboard dashboard-id]
+ [:model/Collection collection-id]
+ [:model/Card model-id]]]
+ (t2/update! model id {:name (format "New %s name" (name model))}))
+ (is (=? [{:text (format "### [New Collection name](%s/collection/%d)\nLinked collection desc" site-url collection-id)}
+ {:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
+ {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
+ {:text (format "### [New Dashboard name](%s/dashboard/%d)\nLinked Dashboard desc" site-url dashboard-id)}
+ {:text (format "### [New Card name](%s/question/%d)\nLinked card desc" site-url card-id)}
+ {:text (format "### [New Card name](%s/question/%d)\nLinked model desc" site-url model-id)}
+ {:text "### [https://metabase.com](https://metabase.com)"}]
+ (execute-dashboard (:id dashboard) collection-owner-id nil))))
+ (testing "it should filter out models that current users does not have permission to read"
+ (is (=? [{:text (format "### [New Database name](%s/browse/%d)\nLinked database desc" site-url database-id)}
+ {:text (format "### [Linked table dname](%s/question?db=%d&table=%d)\nLinked table desc" site-url database-id table-id)}
+ {:text "### [https://metabase.com](https://metabase.com)"}]
+ (execute-dashboard (:id dashboard) (mt/user->id :lucky) nil))))))))))
(deftest execute-dashboard-with-tabs-test
(mt/with-temp
diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.clj
index 0fe398b7cbe..6b94f19e605 100644
--- a/test/metabase/queries/models/card_test.clj
+++ b/test/metabase/queries/models/card_test.clj
@@ -13,8 +13,6 @@
[metabase.lib.test-util.notebook-helpers :as notebook-helpers]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
- [metabase.permissions.models.data-permissions :as data-perms]
- [metabase.permissions.models.permissions-group :as perms-group]
[metabase.queries.models.card :as card]
[metabase.queries.models.parameter-card :as parameter-card]
[metabase.queries.schema :as queries.schema]
@@ -969,35 +967,6 @@
:database_id (mt/id)}
(t2/select-one :model/Card :id (u/the-id card))))))))))
-(deftest ^:parallel can-run-adhoc-query-test
- (let [metadata-provider (mt/metadata-provider)
- venues (lib.metadata/table metadata-provider (mt/id :venues))
- query (lib/query metadata-provider venues)]
- (mt/with-current-user (mt/user->id :crowberto)
- (mt/with-temp [:model/Card card {:dataset_query query}
- :model/Card no-query {}]
- (is (=? {:can_run_adhoc_query true}
- (t2/hydrate card :can_run_adhoc_query)))
- (is (=? {:can_run_adhoc_query false}
- (t2/hydrate no-query :can_run_adhoc_query)))))))
-
-(deftest can-run-adhoc-query-respects-create-queries-perm-test
- (testing "can_run_adhoc_query reflects a non-admin's create-queries permission on the card's table (#13347)"
- (let [mp (mt/metadata-provider)
- venues (lib.metadata/table mp (mt/id :venues))
- query (lib/query mp venues)]
- (mt/with-temp [:model/Card card {:dataset_query query}]
- (mt/with-no-data-perms-for-all-users!
- (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
- (data-perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :no)
- (mt/with-current-user (mt/user->id :rasta)
- (is (=? {:can_run_adhoc_query false}
- (t2/hydrate (t2/select-one :model/Card :id (:id card)) :can_run_adhoc_query))))
- (data-perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :query-builder)
- (mt/with-current-user (mt/user->id :rasta)
- (is (=? {:can_run_adhoc_query true}
- (t2/hydrate (t2/select-one :model/Card :id (:id card)) :can_run_adhoc_query)))))))))
-
(deftest audit-card-permissions-test
(testing "Cards in audit collections are not readable or writable on OSS, even if they exist (#42645)"
;; Here we're testing the specific scenario where an EE instance is downgraded to OSS, but still has the audit
diff --git a/test/metabase/queries/schema_test.clj b/test/metabase/queries/schema_test.clj
index e273d6d727b..6be152229a1 100644
--- a/test/metabase/queries/schema_test.clj
+++ b/test/metabase/queries/schema_test.clj
@@ -7,8 +7,7 @@
[metabase.util.malli.registry :as mr]))
(deftest ^:parallel validate-query-test
- (is (= {:dataset_query {:lib/metadata ["missing required key"]
- :stages [["Initial MBQL stage must have either :source-table or :source-card (but not both)"]]}}
+ (is (= {:dataset_query {:stages [["Initial MBQL stage must have either :source-table or :source-card (but not both)"]]}}
(me/humanize (mr/explain ::queries.schema/card
{:dataset_query {:lib/type :mbql/query, :database 2378, :stages [{:lib/type :mbql.stage/mbql}]}})))))
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index e09de78e1f8..cdbfc820835 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -196,7 +196,7 @@
:data {:rows [[8]]}}
(mt/user-http-request
:rasta :post 202 (format "card/%d/query" card-id)
- {:parameters [{:id "_CATEGORY_"
+ {:parameters [{:id "_CATEGORY_ID_"
:type :number
:target [:variable [:template-tag :category]]
:value 2}]})))))))
@@ -782,7 +782,7 @@
(is (=? {:oneOf [{:$ref "#/components/schemas/metabase.queries.schema.card-type"} {:type :null}]}
type-schema)))
(testing 'result_metadata
- (is (=? {:oneOf [{:$ref "#/components/schemas/metabase.analyze.query-results.ResultsMetadata"} {:type :null}]}
+ (is (=? {:oneOf [{:$ref "#/components/schemas/metabase.lib.schema.metadata..card.result-metadata"} {:type :null}]}
result-metadata-schema))))))
(deftest create-a-card
@@ -865,7 +865,7 @@
(deftest ^:parallel create-card-validation-test
(testing "POST /api/card"
(is (=? {:errors {:name "value must be a non-blank string."
- :dataset_query "Value must be a map."
+ :dataset_query "value must be a valid MBQL query."
:display "value must be a non-blank string."
:visualization_settings "Value must be a map."}
:specific-errors {:name ["missing required key, received: nil"]
@@ -877,7 +877,7 @@
(deftest ^:parallel create-card-validation-test-1b
(testing "POST /api/card"
(is (=? {:errors {:name "value must be a non-blank string."
- :dataset_query "Value must be a map."
+ :dataset_query "value must be a valid MBQL query."
:parameters "nullable sequence of parameter must be a map with :id and :type keys"
:display "value must be a non-blank string."}
:specific-errors {:name ["missing required key, received: nil"]
@@ -904,20 +904,22 @@
(mt/id :orders :created_at)]}}}})
(deftest ^:parallel post-card-with-malformed-dataset-query-returns-400-test
- (testing "POST /api/card with structurally malformed :dataset_query returns 400, not 500 (#74615)"
- (is (=? {:cause #"(?si).*(normaliz|mbql).*"}
- (mt/user-http-request
- :crowberto :post 400 "card"
- (assoc (card-with-name-and-query)
- :dataset_query (malformed-native-dataset-query)))))))
+ (testing "POST /api/card with structurally malformed :dataset_query returns 400 with the specific error, not 500 (#74615)"
+ (let [response (mt/user-http-request
+ :crowberto :post 400 "card"
+ (assoc (card-with-name-and-query)
+ :dataset_query (malformed-native-dataset-query)))]
+ (is (string? response))
+ (is (not (str/blank? response))))))
(deftest ^:parallel put-card-with-malformed-dataset-query-returns-400-test
(testing "PUT /api/card/:id with structurally malformed :dataset_query returns 400, not 200 with silent data loss (#74615)"
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mbql-count-query)}]
- (is (=? {:cause #"(?si).*(normaliz|mbql).*"}
- (mt/user-http-request
- :crowberto :put 400 (str "card/" card-id)
- {:dataset_query (malformed-native-dataset-query)})))
+ (let [response (mt/user-http-request
+ :crowberto :put 400 (str "card/" card-id)
+ {:dataset_query (malformed-native-dataset-query)})]
+ (is (string? response))
+ (is (not (str/blank? response))))
(testing "the existing dataset_query is preserved (not silently coerced to {})"
(is (= :mbql/query
(:lib/type (t2/select-one-fn :dataset_query :model/Card :id card-id))))))))
@@ -2377,7 +2379,7 @@
;;; Test GET /api/card/:id/query/csv & GET /api/card/:id/json & GET /api/card/:id/query/xlsx **WITH PARAMETERS**
(def ^:private test-params
- [{:id "_CATEGORY_"
+ [{:id "_CATEGORY_ID_"
:type :number
:target [:variable [:template-tag :category]]
:value 2}])
@@ -3282,7 +3284,7 @@
:row_count 1}
(mt/user-http-request
:rasta :post 202 (format "card/pivot/%d/query" card-id)
- {:parameters [{:id "_CATEGORY_"
+ {:parameters [{:id "_CATEGORY_ID_"
:type :number
:target [:variable [:template-tag :category]]
:value 2}]})))))))
@@ -3980,17 +3982,6 @@
(mt/user-http-request :crowberto :put 200 (str "collection/" (u/the-id collection-a)) {:archived true})
(is (false? (:can_restore (mt/user-http-request :crowberto :get 200 (str "card/" card-id)))))))
-(deftest ^:parallel can-run-adhoc-query-test
- (let [metadata-provider (mt/metadata-provider)
- venues (lib.metadata/table metadata-provider (mt/id :venues))
- query (lib/query metadata-provider venues)]
- (mt/with-temp [:model/Card card {:dataset_query query}
- :model/Card no-query {}]
- (is (=? {:can_run_adhoc_query true}
- (mt/user-http-request :crowberto :get 200 (str "card/" (:id card)))))
- (is (=? {:can_run_adhoc_query false}
- (mt/user-http-request :crowberto :get 200 (str "card/" (:id no-query))))))))
-
(deftest can-manage-db-test
(mt/with-temp [:model/Card card {:type :model}]
(mt/with-no-data-perms-for-all-users!
@@ -5120,19 +5111,6 @@
resp (mt/user-http-request :rasta :post 202 (format "card/%d/query" (:id card)))]
(is (= 3 (count (get-in resp [:data :rows]))))))))))
-(deftest can-run-adhoc-query-nested-card-source-test
- (testing "can_run_adhoc_query for a card sourced from another card matches the collection-perms model (#23857)"
- (let [mp (mt/metadata-provider)
- source-query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]
- (mt/with-temp [:model/Card source {:dataset_query source-query}]
- (let [nested-query (lib/query mp (lib.metadata/card mp (:id source)))]
- (mt/with-temp [:model/Card nested {:dataset_query nested-query}]
- (mt/with-no-data-perms-for-all-users!
- (is (=? {:can_run_adhoc_query true}
- (mt/user-http-request :rasta :get 200 (str "card/" (:id nested)))))
- (is (=? {:can_run_adhoc_query false}
- (mt/user-http-request :rasta :get 200 (str "card/" (:id source))))))))))))
-
(deftest ^:parallel reduced-fields-propagate-to-downstream-card-test
(testing "A card with reduced :fields only exposes those columns to a card sourced from it (#30610)"
(let [mp (mt/metadata-provider)
@@ -5308,8 +5286,8 @@
(is (not (some #{(str "card__" (u/the-id card))}
(tree-seq coll? seq (:dataset_query newcard)))))))))
-(deftest can-fetch-and-query-metric-sourced-from-inaccessible-model-test
- (testing "GET/POST card endpoints don't require collection-read on nested source cards they reference"
+(deftest cannot-query-metric-sourced-from-inaccessible-model-test
+ (testing "GET does not require collection-read on nested source cards, but running the query does"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp [:model/Collection model-coll {}
:model/Collection metric-coll {}
@@ -5326,8 +5304,8 @@
(perms/grant-collection-read-permissions! (perms-group/all-users) metric-coll)
(is (=? {:id (u/the-id metric)}
(mt/user-http-request :rasta :get 200 (str "card/" (u/the-id metric)))))
- (is (=? {:status "completed"}
- (mt/user-http-request :rasta :post (str "card/" (u/the-id metric) "/query"))))))))
+ (is (re-find #"You do not have permissions to view Card"
+ (str (mt/user-http-request :rasta :post 403 (str "card/" (u/the-id metric) "/query")))))))))
(deftest native-card-ref-runs-with-no-data-perms-test
(testing "A native card referencing another native card via {{#id}} runs for a user with no query-building data perms (#216)"
diff --git a/test/metabase/query_permissions/impl_test.clj b/test/metabase/query_permissions/impl_test.clj
index 776ec738264..45833779cd0 100644
--- a/test/metabase/query_permissions/impl_test.clj
+++ b/test/metabase/query_permissions/impl_test.clj
@@ -316,6 +316,7 @@
(testing "native query"
(is (= {:perms/create-queries :query-builder-and-native
:perms/view-data :unrestricted
+ :card-ids #{card-1-id card-2-id}
:paths #{(format "/collection/%d/read/" collection-1-id)
(format "/collection/%d/read/" collection-2-id)}}
(query-perms/required-perms-for-query
@@ -334,12 +335,14 @@
:condition [:= true false]}]}}]
(is (= {:perms/create-queries :query-builder-and-native
:perms/view-data :unrestricted
+ :card-ids #{card-1-id card-2-id}
:paths #{(format "/collection/%d/read/" collection-1-id)
(format "/collection/%d/read/" collection-2-id)}}
(query-perms/required-perms-for-query native-query)))
(testing "MBQL 5 query"
(is (= {:perms/create-queries :query-builder-and-native
:perms/view-data :unrestricted
+ :card-ids #{card-1-id card-2-id}
:paths #{(format "/collection/%d/read/" collection-1-id)
(format "/collection/%d/read/" collection-2-id)}}
(query-perms/required-perms-for-query
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index 4f04f3340ab..c997881669c 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -77,10 +77,6 @@
(Thread/sleep 100)
(recur (dec retries)))))))
-(def ^:private query-defaults
- {:middleware {:add-default-userland-constraints? true
- :js-int-to-string? true}})
-
(deftest basic-query-test
(testing "POST /api/dataset"
(testing "\nJust a basic sanity check to make sure Query Processor endpoint is still working correctly."
@@ -97,11 +93,13 @@
:row_count 1
:status "completed"
:context "ad-hoc"
- :json_query (-> (mt/mbql-query checkins
- {:aggregation [[:count]]})
- (assoc-in [:query :aggregation] [["count"]])
- (assoc :type "query")
- (merge query-defaults))
+ :json_query {:lib/type "mbql/query"
+ :database (mt/id)
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table (mt/id :checkins)
+ :aggregation [["count" {:lib/uuid string?}]]}]
+ :middleware {:add-default-userland-constraints? true
+ :js-int-to-string? true}}
:started_at true
:running_time true
:average_execution_time nil
@@ -171,9 +169,10 @@
[:error #"Syntax error in SQL statement"]
[:json_query [:map
[:database [:= (mt/id)]]
- [:type [:= "native"]]
- [:native [:map
- [:query [:= "foobar"]]]]
+ [:lib/type [:= "mbql/query"]]
+ [:stages [:sequential [:map
+ [:lib/type [:= "mbql.stage/native"]]
+ [:native [:= "foobar"]]]]]
[:middleware [:map
[:add-default-userland-constraints? [:= true]]
[:js-int-to-string? [:= true]]]]]]
@@ -314,7 +313,12 @@
:row_count 5
:status "completed"
:context "ad-hoc"
- :json_query (merge query-defaults card-query)
+ :json_query {:lib/type "mbql/query"
+ :database (mt/id)
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-card (u/the-id card)}]
+ :middleware {:add-default-userland-constraints? true
+ :js-int-to-string? true}}
:database_id (mt/id)}
(-> (mt/user-http-request :crowberto :post 202 "dataset" card-query)
(update-in [:data :native_form :query]
@@ -582,8 +586,7 @@
(testing "POST /api/dataset/native"
(testing "\nCan we fetch a native version of an MBQL query?"
(is (= {:query (str "SELECT \"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", \"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\" "
- "FROM \"PUBLIC\".\"VENUES\" "
- "LIMIT 1048575")
+ "FROM \"PUBLIC\".\"VENUES\"")
:params nil}
(mt/user-http-request :crowberto :post 200 "dataset/native"
(assoc (mt/mbql-query venues {:fields [$id $name]})
@@ -608,9 +611,7 @@
"FROM"
" \"PUBLIC\".\"CHECKINS\""
"WHERE"
- " \"PUBLIC\".\"CHECKINS\".\"DATE\" = date '2015-11-13'"
- "LIMIT"
- " 1048575"]
+ " \"PUBLIC\".\"CHECKINS\".\"DATE\" = date '2015-11-13'"]
:params nil}
(-> (mt/user-http-request :crowberto :post 200 "dataset/native"
(assoc (mt/mbql-query checkins
@@ -644,9 +645,7 @@
" \"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\",\n"
" \"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\"\n"
"FROM\n"
- " \"PUBLIC\".\"VENUES\"\n"
- "LIMIT\n"
- " 1048575")
+ " \"PUBLIC\".\"VENUES\"")
:params nil}
(mt/user-http-request :crowberto :post 200 "dataset/native"
(assoc
@@ -661,9 +660,7 @@
" \"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\",\n"
" \"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\"\n"
"FROM\n"
- " \"PUBLIC\".\"VENUES\"\n"
- "LIMIT\n"
- " 1048575")
+ " \"PUBLIC\".\"VENUES\"")
:params nil}
(mt/user-http-request :crowberto :post 200 "dataset/native"
(mt/mbql-query venues {:fields [$id $name]}))))))))
@@ -1031,13 +1028,12 @@
(deftest ^:parallel mbql5-query-convert-to-native-disable-default-limit-test
(testing "POST /api/dataset/native"
- (testing "MBQL 5 query with disable-default-limit should compile to SQL without a LIMIT clause"
+ (testing "MBQL 5 query should compile to SQL without a LIMIT clause"
(let [metadata-provider (mt/metadata-provider)
venues (lib.metadata/table metadata-provider (mt/id :venues))
- query (-> (lib/query metadata-provider venues)
- lib/disable-default-limit)]
+ query (lib/query metadata-provider venues)]
(is (not (re-find #"(?i)\bLIMIT\b" (:query (mt/user-http-request :crowberto :post 200 "dataset/native" query))))
- "Expected no LIMIT in SQL for query with disable-default-limit")))))
+ "Expected no LIMIT in SQL")))))
(deftest ^:parallel format-export-middleware-test
(testing "The `:format-export?` query processor middleware has the intended effect on file exports."
diff --git a/test/metabase/query_processor/card_test.clj b/test/metabase/query_processor/card_test.clj
index 8351d0073cc..6ae2128612b 100644
--- a/test/metabase/query_processor/card_test.clj
+++ b/test/metabase/query_processor/card_test.clj
@@ -234,7 +234,7 @@
(is (= [[100]] (mt/formatted-rows [int] result))))))))
(deftest nested-query-permissions-test
- (testing "Should be able to run a Card with another Card as its source query with just perms for the former (#15131)"
+ (testing "Reading a Card is not enough to run it when its source query is a Card we cannot read"
(mt/with-no-data-perms-for-all-users!
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp [:model/Collection allowed-collection {}
@@ -266,12 +266,14 @@
clojure.lang.ExceptionInfo
#"\QYou don't have permissions to do that.\E"
(process-query-for-card parent-card))))
- (testing "Should be able to run the child Card (#15131)"
+ (testing "Should not be able to run the child Card either, since it reads the parent"
(is (not (mi/can-read? parent-card)))
(is (mi/can-read? allowed-collection))
(is (mi/can-read? child-card))
- (is (= [[1] [2]]
- (mt/rows (process-query-for-card child-card))))))))))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows (process-query-for-card child-card))))))))))))
(deftest ^:parallel archived-source-card-still-queryable-test
(testing "a card whose source is an archived card can still be run (#52071)"
diff --git a/test/metabase/query_processor/constraints_test.clj b/test/metabase/query_processor/constraints_test.clj
index a6b9c1b42af..41819dc022f 100644
--- a/test/metabase/query_processor/constraints_test.clj
+++ b/test/metabase/query_processor/constraints_test.clj
@@ -40,12 +40,11 @@
["Brite Spot Family Restaurant"]]
(mt/rows
(qp/process-query
- (qp/userland-query-with-default-constraints
- {:database (mt/id)
- :type :native
- :native (native-query)
- :constraints {:max-results 5}}
- {:context :question}))))))))
+ (-> {:database (mt/id)
+ :type :native
+ :native (native-query)}
+ (qp/userland-query-with-default-constraints {:context :question})
+ (assoc :constraints {:max-results 5})))))))))
(deftest ^:parallel override-limit-test
(mt/test-drivers (mt/normal-drivers)
diff --git a/test/metabase/query_processor/middleware/parameters_test.clj b/test/metabase/query_processor/middleware/parameters_test.clj
index 128efb63958..5d7581640b3 100644
--- a/test/metabase/query_processor/middleware/parameters_test.clj
+++ b/test/metabase/query_processor/middleware/parameters_test.clj
@@ -15,7 +15,10 @@
[metabase.lib.test-util.macros :as lib.tu.macros]
[metabase.query-processor.middleware.parameters :as parameters]
[metabase.query-processor.preprocess :as qp.preprocess]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db))
(defn- substitute-params
([query]
diff --git a/test/metabase/query_processor/middleware/permissions_test.clj b/test/metabase/query_processor/middleware/permissions_test.clj
index 6b24916509f..466a34a88a3 100644
--- a/test/metabase/query_processor/middleware/permissions_test.clj
+++ b/test/metabase/query_processor/middleware/permissions_test.clj
@@ -494,8 +494,8 @@
{:source-table (format "card__%d" (u/the-id card-2))}))))))))))))))))))))
(deftest e2e-nested-source-card-no-permissions-mbql-mbql-test
- (testing "Make sure permissions are calculated correctly for Card 2 -> Card 1 -> Source Query when a user has access to Card 2,
- but not Card 1 - MBQL Card 1, MBQL Card 2"
+ (testing "Reading Card 2 does not stand in for reading Card 1, which it reads in turn: Card 2 -> Card 1 -> Source
+ Query, with access to Card 2 but not Card 1 - MBQL Card 1, MBQL Card 2"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -514,8 +514,7 @@
(mt/with-temp [:model/Card card-2 {:collection_id collection-2-id
:dataset_query card-2-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 4 10.0646 -165.374 3]
- [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2]]]
+ (do
(testing "Should not be able to run Card 1 directly"
(binding [qp.perms/*card-id* (u/the-id card-1)]
(is (thrown-with-msg?
@@ -523,11 +522,13 @@
#"You do not have permissions to view Card"
(mt/rows
(qp/process-query (:dataset_query card-1)))))))
- (testing "Should be able to run Card 2 directly [Card 2 -> Card 1 -> Source Query]"
+ (testing "Should not be able to run Card 2 either [Card 2 -> Card 1 -> Source Query]"
(binding [qp.perms/*card-id* (u/the-id card-2)]
- (is (= expected
- (mt/rows
- (qp/process-query (:dataset_query card-2)))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query (:dataset_query card-2)))))))
(testing "Should not be able to run ad-hoc query with Card 1 as source query [Ad-hoc -> Card 1 -> Source Query]"
(is (thrown-with-msg?
ExceptionInfo
@@ -535,17 +536,19 @@
(mt/rows
(qp/process-query (mt/mbql-query nil
{:source-table (format "card__%d" card-1-id)}))))))
- (testing "Should be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
- (is (= expected
- (mt/rows
- (qp/process-query
- (qp/userland-query
- (mt/mbql-query nil
- {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
+ (testing "Should not be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query
+ (qp/userland-query
+ (mt/mbql-query nil
+ {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
(deftest e2e-nested-source-card-no-permissions-mbql-native-test
- (testing "Make sure permissions are calculated correctly for Card 2 -> Card 1 -> Source Query when a user has access to Card 2,
- but not Card 1 - MBQL Card 1, native Card 2"
+ (testing "Reading Card 2 does not stand in for reading Card 1, which it reads in turn: Card 2 -> Card 1 -> Source
+ Query, with access to Card 2 but not Card 1 - MBQL Card 1, native Card 2"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -568,8 +571,7 @@
(mt/with-temp [:model/Card card-2 {:collection_id collection-2-id
:dataset_query card-2-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 4 10.0646 -165.374 3]
- [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2]]]
+ (do
(testing "Should not be able to run Card 1 directly"
(binding [qp.perms/*card-id* (u/the-id card-1)]
(is (thrown-with-msg?
@@ -577,11 +579,13 @@
#"You do not have permissions to view Card"
(mt/rows
(qp/process-query (:dataset_query card-1)))))))
- (testing "Should be able to run Card 2 directly [Card 2 -> Card 1 -> Source Query]"
+ (testing "Should not be able to run Card 2 either [Card 2 -> Card 1 -> Source Query]"
(binding [qp.perms/*card-id* (u/the-id card-2)]
- (is (= expected
- (mt/rows
- (qp/process-query (:dataset_query card-2)))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query (:dataset_query card-2)))))))
(testing "Should not be able to run ad-hoc query with Card 1 as source query [Ad-hoc -> Card 1 -> Source Query]"
(is (thrown-with-msg?
ExceptionInfo
@@ -589,17 +593,19 @@
(mt/rows
(qp/process-query (mt/mbql-query nil
{:source-table (format "card__%d" card-1-id)}))))))
- (testing "Should be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
- (is (= expected
- (mt/rows
- (qp/process-query
- (qp/userland-query
- (mt/mbql-query nil
- {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
+ (testing "Should not be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query
+ (qp/userland-query
+ (mt/mbql-query nil
+ {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
(deftest e2e-nested-source-card-no-permissions-native-mbql-test
- (testing "Make sure permissions are calculated correctly for Card 2 -> Card 1 -> Source Query when a user has access to Card 2,
- but not Card 1 - native Card 1, MBQL Card 2"
+ (testing "Reading Card 2 does not stand in for reading Card 1, which it reads in turn: Card 2 -> Card 1 -> Source
+ Query, with access to Card 2 but not Card 1 - native Card 1, MBQL Card 2"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -621,8 +627,7 @@
(mt/with-temp [:model/Card card-2 {:collection_id collection-2-id
:dataset_query card-2-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 4 10.0646 -165.374 3]
- [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2]]]
+ (do
(testing "Should not be able to run Card 1 directly"
(binding [qp.perms/*card-id* (u/the-id card-1)]
(is (thrown-with-msg?
@@ -630,11 +635,13 @@
#"You do not have permissions to view Card"
(mt/rows
(qp/process-query (:dataset_query card-1)))))))
- (testing "Should be able to run Card 2 directly [Card 2 -> Card 1 -> Source Query]"
+ (testing "Should not be able to run Card 2 either [Card 2 -> Card 1 -> Source Query]"
(binding [qp.perms/*card-id* (u/the-id card-2)]
- (is (= expected
- (mt/rows
- (qp/process-query (:dataset_query card-2)))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query (:dataset_query card-2)))))))
(testing "Should not be able to run ad-hoc query with Card 1 as source query [Ad-hoc -> Card 1 -> Source Query]"
(is (thrown-with-msg?
ExceptionInfo
@@ -642,17 +649,19 @@
(mt/rows
(qp/process-query (mt/mbql-query nil
{:source-table (format "card__%d" card-1-id)}))))))
- (testing "Should be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
- (is (= expected
- (mt/rows
- (qp/process-query
- (qp/userland-query
- (mt/mbql-query nil
- {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
+ (testing "Should not be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query
+ (qp/userland-query
+ (mt/mbql-query nil
+ {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
(deftest e2e-nested-source-card-no-permissions-native-native-test
- (testing "Make sure permissions are calculated correctly for Card 2 -> Card 1 -> Source Query when a user has access to Card 2,
- but not Card 1 - native Card 1, native Card 2"
+ (testing "Reading Card 2 does not stand in for reading Card 1, which it reads in turn: Card 2 -> Card 1 -> Source
+ Query, with access to Card 2 but not Card 1 - native Card 1, native Card 2"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -678,8 +687,7 @@
(mt/with-temp [:model/Card card-2 {:collection_id collection-2-id
:dataset_query card-2-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 4 10.0646 -165.374 3]
- [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2]]]
+ (do
(testing "Should not be able to run Card 1 directly"
(binding [qp.perms/*card-id* (u/the-id card-1)]
(is (thrown-with-msg?
@@ -687,11 +695,13 @@
#"You do not have permissions to view Card"
(mt/rows
(qp/process-query (:dataset_query card-1)))))))
- (testing "Should be able to run Card 2 directly [Card 2 -> Card 1 -> Source Query]"
+ (testing "Should not be able to run Card 2 either [Card 2 -> Card 1 -> Source Query]"
(binding [qp.perms/*card-id* (u/the-id card-2)]
- (is (= expected
- (mt/rows
- (qp/process-query (:dataset_query card-2)))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query (:dataset_query card-2)))))))
(testing "Should not be able to run ad-hoc query with Card 1 as source query [Ad-hoc -> Card 1 -> Source Query]"
(is (thrown-with-msg?
ExceptionInfo
@@ -699,13 +709,15 @@
(mt/rows
(qp/process-query (mt/mbql-query nil
{:source-table (format "card__%d" card-1-id)}))))))
- (testing "Should be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
- (is (= expected
- (mt/rows
- (qp/process-query
- (qp/userland-query
- (mt/mbql-query nil
- {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
+ (testing "Should not be able to run ad-hoc query with Card 2 as source query [Ad-hoc -> Card 2 -> Card 1 -> Source Query]"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query
+ (qp/userland-query
+ (mt/mbql-query nil
+ {:source-table (format "card__%d" (u/the-id card-2))})))))))))))))))))))
(deftest e2e-ignore-user-supplied-card-ids-test
(testing "You shouldn't be able to bypass security restrictions by passing `[:info :card-id]` in the query."
@@ -1353,7 +1365,7 @@
{:source-table (format "card__%d" card-4-id)})))))))))))))))))))))))
(deftest e2e-four-level-nested-mixed-permissions-scenario-1-test
- (testing "Four levels of nesting where user has no access to Card 2 but access to Cards 1, 3, and 4"
+ (testing "Four levels of nesting where the user has no access to Card 2: the Cards built on it are refused too"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -1391,7 +1403,7 @@
(mt/with-temp [:model/Card {card-4-id :id} {:collection_id accessible-coll-2
:dataset_query card-4-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 3]]]
+ (let [_expected [[1 "Red Medicine" 3]]]
(testing "Should be able to run Card 1 directly"
(binding [qp.perms/*card-id* card-1-id]
(is (= [[1 "Red Medicine" 3]
@@ -1403,14 +1415,18 @@
ExceptionInfo
#"You do not have permissions to view Card"
(qp/process-query card-2-query)))))
- (testing "Should be able to run Card 3 directly (despite Card 2 in chain)"
+ (testing "Should NOT be able to run Card 3 directly, since Card 2 is in the chain"
(binding [qp.perms/*card-id* card-3-id]
- (is (= expected
- (mt/rows (qp/process-query card-3-query))))))
- (testing "Should be able to run Card 4 directly (despite Card 2 in chain)"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (qp/process-query card-3-query)))))
+ (testing "Should NOT be able to run Card 4 directly, since Card 2 is in the chain"
(binding [qp.perms/*card-id* card-4-id]
- (is (= expected
- (mt/rows (qp/process-query card-4-query))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (qp/process-query card-4-query)))))
(testing "Should NOT be able to run ad-hoc query with Card 2 as source"
(is (thrown-with-msg?
ExceptionInfo
@@ -1462,11 +1478,16 @@
#"You do not have permissions to view Card"
(binding [qp.perms/*card-id* card-2-id]
(mt/rows (qp/process-query card-2-query))))))
- (testing "Should be able to run Card 3 in grandchild collection"
+ (testing "Should not be able to run Card 3, which reads Card 2 in turn"
(binding [qp.perms/*card-id* card-3-id]
- (is (seq (mt/rows (qp/process-query card-3-query))))))
- (testing "Should be able to run ad-hoc query chaining all cards"
- (is (seq
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (qp/process-query card-3-query)))))
+ (testing "Should not be able to run an ad-hoc query chaining all the cards either"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
(mt/rows
(qp/process-query
(qp/userland-query
@@ -1474,7 +1495,7 @@
{:source-table (format "card__%d" card-3-id)}))))))))))))))))))))
(deftest e2e-nested-mixed-query-types-permissions-test
- (testing "Mixed MBQL and native queries in deep nesting with varying permissions"
+ (testing "Mixed MBQL and native queries in deep nesting: a restricted Card anywhere in the chain refuses the query"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp-copy-of-db
(mt/with-no-data-perms-for-all-users!
@@ -1511,7 +1532,7 @@
(mt/with-temp [:model/Card {card-3-id :id} {:collection_id coll-3
:dataset_query card-3-query}]
(mt/with-test-user :rasta
- (let [expected [[1 "Red Medicine" 4 3]]]
+ (let [_expected [[1 "Red Medicine" 4 3]]]
(testing "Should be able to run Card 1 (native, accessible)"
(binding [qp.perms/*card-id* card-1-id]
(is (= 2 (count (mt/rows (qp/process-query card-1-query)))))))
@@ -1521,17 +1542,21 @@
ExceptionInfo
#"You do not have permissions to view Card"
(qp/process-query card-2-query)))))
- (testing "Should be able to run Card 3 (references restricted Card 2 via template tag)"
+ (testing "Should NOT be able to run Card 3, which references restricted Card 2 via a template tag"
(binding [qp.perms/*card-id* card-3-id]
- (is (= expected
- (mt/rows (qp/process-query card-3-query))))))
- (testing "Should be able to use Card 3 as source in ad-hoc query"
- (is (= expected
- (mt/rows
- (qp/process-query
- (qp/userland-query
- (mt/mbql-query nil
- {:source-table (format "card__%d" card-3-id)})))))))))))))))))))))
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows (qp/process-query card-3-query))))))
+ (testing "Should NOT be able to use Card 3 as source in an ad-hoc query either"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"You do not have permissions to view Card"
+ (mt/rows
+ (qp/process-query
+ (qp/userland-query
+ (mt/mbql-query nil
+ {:source-table (format "card__%d" card-3-id)})))))))))))))))))))))
(deftest e2e-expression-referencing-restricted-fields-test
(testing "Queries with custom expressions that reference fields from restricted tables"
diff --git a/test/metabase/query_processor/middleware/wrap_value_literals_test.clj b/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
index e148a1ba38b..100caeebbef 100644
--- a/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
+++ b/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
@@ -12,7 +12,10 @@
[metabase.query-processor.preprocess :as qp.preprocess]
^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.query-processor.timezone :as qp.timezone]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db))
(driver/register! ::tz-driver, :abstract? true)
diff --git a/test/metabase/query_processor/parameters_test.clj b/test/metabase/query_processor/parameters_test.clj
index 1d5ad86d28a..724db5f1678 100644
--- a/test/metabase/query_processor/parameters_test.clj
+++ b/test/metabase/query_processor/parameters_test.clj
@@ -708,7 +708,7 @@
(testing "SHOULD NOT be able to run native query with Card ID template tag"
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
- #"\QYou do not have permissions to run this query.\E"
+ #"You do not have permissions to view Card"
(qp/process-query query))))
(testing "Exception should NOT include the compiled native query"
(try
@@ -723,17 +723,16 @@
(is (not (re-find #"SELECT" form))))
form)
data)))))
- (testing (str "If we have permissions for Card 2's Collection (but not Card 1's) we should be able to"
- " run a native query referencing Card 2, even tho it references Card 1 (#15131)")
+ (testing (str "Permissions for Card 2's Collection are not enough to run a native query referencing"
+ " Card 2 while it references Card 1, which we still cannot read")
(perms/grant-collection-read-permissions! (perms-group/all-users) collection-2-id)
;; need to call [[mt/with-test-user]] again so [[metabase.api.common/*current-user-permissions-set*]]
;; gets rebound with the updated permissions. This will be fixed in #45001
(mt/with-test-user :rasta
- (is (= [[1 "Red Medicine"]
- [2 "Stout Burgers & Beers"]]
- (mt/formatted-rows
- [int str]
- (qp/process-query query))))))))))))))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"You do not have permissions to view Card"
+ (qp/process-query query)))))))))))))
;;; TODO (Cam 9/9/25) -- I added this in #61114 but I don't remember exactly what I was testing... I think this is a
;;; port of one of the Cypress e2e tests but I don't remember which one. Give this a better name.
diff --git a/test/metabase/query_processor/streaming_test.clj b/test/metabase/query_processor/streaming_test.clj
index 31593a2f90e..7d2566795b0 100644
--- a/test/metabase/query_processor/streaming_test.clj
+++ b/test/metabase/query_processor/streaming_test.clj
@@ -323,8 +323,6 @@
[message {:keys [query viz-settings assertions endpoints user expected-status]}]
(testing message
(let [expected-status (or expected-status 200)
- query-json (json/encode query)
- viz-settings-json (some-> viz-settings json/encode)
public-uuid (str (random-uuid))
card-defaults {:dataset_query query, :public_uuid public-uuid, :enable_embedding true}
user (or user :rasta)]
@@ -346,9 +344,9 @@
(let [results (mt/user-http-request user :post expected-status
(format "dataset/%s" (name export-format))
{:request-options {:as (if (= export-format :xlsx) :byte-array :string)}}
- {:format_rows true
- :query query-json
- :visualization_settings viz-settings-json})]
+ (cond-> {:format_rows true
+ :query query}
+ viz-settings (assoc :visualization_settings viz-settings)))]
((-> assertions export-format) results))
:card
diff --git a/test/metabase/query_processor/util/add_alias_info_test.clj b/test/metabase/query_processor/util/add_alias_info_test.clj
index 90af38e9535..7ffd381dbb2 100644
--- a/test/metabase/query_processor/util/add_alias_info_test.clj
+++ b/test/metabase/query_processor/util/add_alias_info_test.clj
@@ -1078,7 +1078,7 @@
;;; in the future when we remove all the roundtripping that happens inside of the QP then we can remove this test
;;; entirely.
-(deftest ^:parallel additional-keys-should-survive-preprocessing-test
+(deftest ^:parallel additional-keys-do-not-survive-preprocessing-test
(driver/with-driver :h2
(let [query (lib/query
meta/metadata-provider
@@ -1096,12 +1096,12 @@
:alias "PRODUCTS__via__PRODUCT_ID"
:fk-field-id %product-id
:condition [:= $product-id &PRODUCTS__via__PRODUCT_ID.products.id]}]}))]
- (is (=? [[:expression {::add/source-table ::add/none, ::add/desired-alias "pivot-grouping"} "pivot-grouping"]
- [:expression {::add/source-table ::add/none, ::add/desired-alias "pivot-grouping"} "pivot-grouping"]]
- (match/match-many (-> query
- add/add-alias-info
- qp.preprocess/preprocess)
- [:expression & _] &match))))))
+ (is (= [nil nil]
+ (map (fn [[_tag opts]] (not-empty (select-keys opts [::add/source-table ::add/desired-alias])))
+ (match/match-many (-> query
+ add/add-alias-info
+ qp.preprocess/preprocess)
+ [:expression & _] &match)))))))
(deftest ^:parallel remapped-columns-in-joined-source-queries-test
(testing "Make sure remapped columns are given correct aliases and escaped correctly for drivers like Oracle"
diff --git a/test/metabase/request/util_test.clj b/test/metabase/request/util_test.clj
index 003f8b69f31..e1ac0b30872 100644
--- a/test/metabase/request/util_test.clj
+++ b/test/metabase/request/util_test.clj
@@ -110,10 +110,10 @@
(ring.mock/header "X-Forwarded-For" "5.6.7.8"))]
(is (= "5.6.7.8"
(request.current/ip-address mock-request))))
- (testing "multiple IP addresses"
+ (testing "multiple IP addresses -- takes the last (proxy-appended, trusted) entry, not the first"
(let [mock-request (-> (ring.mock/request :get "api/session")
(ring.mock/header "X-Forwarded-For" "1.2.3.4, 5.6.7.8"))]
- (is (= "1.2.3.4"
+ (is (= "5.6.7.8"
(request.current/ip-address mock-request)))))
(testing "different header than default X-Forwarded-For"
(mt/with-temporary-setting-values [source-address-header "X-ProxyUser-Ip"]
diff --git a/test/metabase/revisions/api_test.clj b/test/metabase/revisions/api_test.clj
index a68fd71debc..259547484ee 100644
--- a/test/metabase/revisions/api_test.clj
+++ b/test/metabase/revisions/api_test.clj
@@ -277,7 +277,7 @@
(t2/update! :model/Dashboard :id dashboard-id {:collection_id coll-id})
(create-dashboard-revision! dashboard-id false :crowberto)
;; 7. revert to an earlier revision
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Dashboard :id dashboard-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= [{:description "reverted to an earlier version."
:has_multiple_changes false}
@@ -347,7 +347,7 @@
(t2/update! :model/Card :id card-id {:collection_id coll-id})
(create-card-revision! card-id false :crowberto)
;; 6. revert to an earlier revision
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Card :id card-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= [{:description "reverted to an earlier version.",
:has_multiple_changes false}
@@ -391,7 +391,7 @@
(t2/update! :model/Card :id card-id {:collection_id coll-id})
(create-card-revision! card-id false :crowberto)
;; 5. revert to an earlier revision
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Card :id card-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= [{:description "reverted to an earlier version.",
:has_multiple_changes false}
@@ -431,7 +431,7 @@
:name "New name"})
(create-card-revision! card-id false :crowberto)
;; 2. revert to an earlier revision
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Card :id card-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= [{:description "est revenu à une version antérieure."
:has_multiple_changes false}
@@ -461,7 +461,7 @@
:col 1
:row 1}])
(create-dashboard-revision! dashboard-id false :crowberto)
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Dashboard :id dashboard-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= [{:description "reverted to an earlier version."
:has_multiple_changes false}
@@ -487,7 +487,7 @@
;; Update the card to a new version
(t2/update! :model/Card {:name "A card with a new name"})
;; Revert to the saved revision and check that the revert succeeded despite the extra field
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Card :id card-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= "A card" (t2/select-one-fn :name :model/Card :id card-id))))
(testing "Reverting a dashboard..."
@@ -501,7 +501,7 @@
;; Update the dashboard to a new version
(t2/update! :model/Dashboard {:name "A dashboard with a new name"})
;; Revert to the saved revision and check that the revert succeeded despite the extra field
- (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:timestamp :desc]]})]
+ (let [earlier-revision-id (t2/select-one-pk :model/Revision :model "Dashboard" :model_id dashboard-id {:order-by [[:id :asc]]})]
(revision/revert! {:entity :model/Dashboard :id dashboard-id :user-id (mt/user->id :crowberto) :revision-id earlier-revision-id}))
(is (= "A dashboard" (t2/select-one-fn :name :model/Dashboard :id dashboard-id)))))))
diff --git a/test/metabase/revisions/events_test.clj b/test/metabase/revisions/events_test.clj
index ba00c35df4d..4cc512c15a4 100644
--- a/test/metabase/revisions/events_test.clj
+++ b/test/metabase/revisions/events_test.clj
@@ -27,8 +27,6 @@
:type :question
:description nil
:display :table
- :enable_embedding false
- :embedding_params nil
:name (:name card)
:parameters []
:parameter_mappings []
@@ -49,9 +47,6 @@
:cards []
:archived false
:collection_position nil
- :enable_embedding false
- :embedding_params nil
- :embedding_type nil
:parameters []
:archived_directly (:archived_directly dashboard)})
diff --git a/test/metabase/revisions/impl/card_test.clj b/test/metabase/revisions/impl/card_test.clj
index 5673bad2d05..2de23dc2c5c 100644
--- a/test/metabase/revisions/impl/card_test.clj
+++ b/test/metabase/revisions/impl/card_test.clj
@@ -60,25 +60,26 @@
(mt/with-temp
[:model/Collection {coll-id-1 :id} {:name "Old collection"}
:model/Collection {coll-id-2 :id} {:name "New collection"}]
- (are [x y expected] (= expected
- (u/build-sentence (revision/diff-strings :model/Card x y)))
-
- {:name "Apple"}
- {:name "Apple"
- :collection_id coll-id-2}
- "moved this Card to New collection."
-
- {:name "Diff Test"
- :description nil}
- {:name "Diff Test changed"
- :description "New description"}
- "added a description and renamed it from \"Diff Test\" to \"Diff Test changed\"."
-
- {:name "Apple"
- :collection_id coll-id-1}
- {:name "Apple"
- :collection_id coll-id-2}
- "moved this Card from Old collection to New collection.")))
+ (mt/with-test-user :crowberto
+ (are [x y expected] (= expected
+ (u/build-sentence (revision/diff-strings :model/Card x y)))
+
+ {:name "Apple"}
+ {:name "Apple"
+ :collection_id coll-id-2}
+ "moved this Card to New collection."
+
+ {:name "Diff Test"
+ :description nil}
+ {:name "Diff Test changed"
+ :description "New description"}
+ "added a description and renamed it from \"Diff Test\" to \"Diff Test changed\"."
+
+ {:name "Apple"
+ :collection_id coll-id-1}
+ {:name "Apple"
+ :collection_id coll-id-2}
+ "moved this Card from Old collection to New collection."))))
(defn- create-card-revision!
"Fetch the latest version of a Dashboard and save a revision entry for it. Returns the fetched Dashboard."
diff --git a/test/metabase/revisions/impl/dashboard_test.clj b/test/metabase/revisions/impl/dashboard_test.clj
index e72c4afa37c..2007bf48f18 100644
--- a/test/metabase/revisions/impl/dashboard_test.clj
+++ b/test/metabase/revisions/impl/dashboard_test.clj
@@ -41,9 +41,6 @@
:tabs []
:archived false
:collection_position nil
- :enable_embedding false
- :embedding_type nil
- :embedding_params nil
:parameters []
:width "fixed"}
(update (revision/serialize-instance :model/Dashboard (:id dashboard) dashboard)
@@ -177,24 +174,26 @@
:collection_id nil}))))
(mt/with-temp
[:model/Collection {coll-id :id} {:name "New collection"}]
- (is (= "moved this Dashboard to New collection."
- (u/build-sentence
- (revision/diff-strings
- :model/Dashboard
- {:name "Apple"}
- {:name "Apple"
- :collection_id coll-id})))))
+ (mt/with-test-user :crowberto
+ (is (= "moved this Dashboard to New collection."
+ (u/build-sentence
+ (revision/diff-strings
+ :model/Dashboard
+ {:name "Apple"}
+ {:name "Apple"
+ :collection_id coll-id}))))))
(mt/with-temp
[:model/Collection {coll-id-1 :id} {:name "Old collection"}
:model/Collection {coll-id-2 :id} {:name "New collection"}]
- (is (= "moved this Dashboard from Old collection to New collection."
- (u/build-sentence
- (revision/diff-strings
- :model/Dashboard
- {:name "Apple"
- :collection_id coll-id-1}
- {:name "Apple"
- :collection_id coll-id-2})))))))
+ (mt/with-test-user :crowberto
+ (is (= "moved this Dashboard from Old collection to New collection."
+ (u/build-sentence
+ (revision/diff-strings
+ :model/Dashboard
+ {:name "Apple"
+ :collection_id coll-id-1}
+ {:name "Apple"
+ :collection_id coll-id-2}))))))))
(deftest ^:parallel diff-dashboards-str-update-tabs-test
(testing "update tabs"
@@ -366,9 +365,6 @@
:tabs []
:archived false
:collection_position nil
- :enable_embedding false
- :embedding_type nil
- :embedding_params nil
:parameters []
:width "fixed"}
serialized-dashboard (revision/serialize-instance :model/Dashboard (:id dashboard) dashboard)]
@@ -395,9 +391,6 @@
:tabs []
:archived false
:collection_position nil
- :enable_embedding false
- :embedding_type nil
- :embedding_params nil
:parameters []
:width "fixed"}
(update serialized-dashboard :cards check-ids))))
@@ -435,9 +428,6 @@
:tabs []
:archived false
:collection_position nil
- :enable_embedding false
- :embedding_type nil
- :embedding_params nil
:parameters []
:width "fixed"}
(update (revision/serialize-instance :model/Dashboard dashboard-id (t2/select-one :model/Dashboard :id dashboard-id))
@@ -468,7 +458,8 @@
(let [ids (t2/select-pks-vec :model/Revision :model (name model) :model_id model-id {:order-by [[:id :desc]]
:limit n})]
(assert (= n (count ids)), "There are less revisions than required to revert")
- (revision/revert! {:entity model :id model-id :user-id (mt/user->id :crowberto) :revision-id (last ids)})))
+ (mt/with-test-user :crowberto
+ (revision/revert! {:entity model :id model-id :user-id (mt/user->id :crowberto) :revision-id (last ids)}))))
(deftest revert-dashboard-with-tabs-basic-test
(testing "revert adding tabs"
diff --git a/test/metabase/search/filter_test.clj b/test/metabase/search/filter_test.clj
index 659505b5e73..a497a47f3fa 100644
--- a/test/metabase/search/filter_test.clj
+++ b/test/metabase/search/filter_test.clj
@@ -124,7 +124,7 @@
#{[:in :search_index.last_editor_id [321]]
[:in :search_index.creator_id [123]]
[:or [:= :search_index.collection_id 5] [:like :collection.location "%/5/%"]]
- [:not= :search_index.model [:inline "table"]]
+ [:not= :search_index.model "table"]
[:= :search_index.archived true]
[:= :search_index.curated true]
[:in :search_index.model ["card" "dataset" "metric" "dashboard" "action"]]
diff --git a/test/metabase/search/in_place/filter_test.clj b/test/metabase/search/in_place/filter_test.clj
index 6a21d194022..fe2bb56f173 100644
--- a/test/metabase/search/in_place/filter_test.clj
+++ b/test/metabase/search/in_place/filter_test.clj
@@ -17,6 +17,8 @@
:is-data-analyst? false
:current-user-perms #{"/"}
:calculate-available-models? false
+ :is-sandboxed-user? false
+ :is-impersonated-user? false
:enabled-transform-source-types #{"mbql"}})
(deftest ^:parallel ->applicable-models-test
@@ -353,7 +355,7 @@
base-search-query
{:where [:and
[:= :card.archived false]
- [:inline [:= 0 1]]]})
+ [:= [:inline 0] [:inline 1]]]})
(search.filter/build-filters
base-search-query "card"
(merge default-search-ctx {:verified true}))))))))
@@ -366,7 +368,7 @@
base-search-query
{:where [:and
[:= :card.archived false]
- [:inline [:= 0 1]]]})
+ [:= [:inline 0] [:inline 1]]]})
(search.filter/build-filters
base-search-query "dataset"
(merge default-search-ctx {:verified true}))))))))
@@ -387,7 +389,7 @@
(mt/with-dynamic-fn-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly false)]
(is (= [:and
[:or [:like [:lower :model-index-value.name] "%foo%"]]
- [:inline [:= 1 1]]]
+ [:= [:inline 1] [:inline 1]]]
(:where (search.filter/build-filters
base-search-query
"indexed-entity"
@@ -398,7 +400,7 @@
(mt/with-dynamic-fn-redefs [search.permissions/sandboxed-or-impersonated-user? (constantly true)]
(is (= [:and
[:or [:= 0 1]]
- [:inline [:= 1 1]]]
+ [:= [:inline 1] [:inline 1]]]
(:where (search.filter/build-filters
base-search-query
"indexed-entity"
@@ -464,5 +466,5 @@
(let [result (search.filter/build-filters
base-search-query model
(merge default-search-ctx {:collection 1}))]
- (is (some #{[:inline [:= 0 1]]}
+ (is (some #{[:= [:inline 0] [:inline 1]]}
(tree-seq sequential? seq (:where result)))))))))
diff --git a/test/metabase/segments/api_test.clj b/test/metabase/segments/api_test.clj
index 728b7c98cb5..aa5ad5b10d2 100644
--- a/test/metabase/segments/api_test.clj
+++ b/test/metabase/segments/api_test.clj
@@ -32,8 +32,10 @@
(defn- mbql4-segment-definition
"Create a legacy MBQL4 segment definition"
[table-id field-id value]
- {:source-table table-id
- :filter [:= [:field field-id nil] value]})
+ {:database (t2/select-one-fn :db_id :model/Table :id table-id)
+ :type :query
+ :query {:source-table table-id
+ :filter [:= [:field field-id nil] value]}})
(defn- mbql5-segment-definition
"Create an MBQL5 segment definition"
@@ -68,18 +70,12 @@
(testing "POST /api/segment"
(is (=? {:errors {:name "value must be a non-blank string."}}
(mt/user-http-request :crowberto :post 400 "segment" {})))
- (is (=? {:errors {:definition "Value must be a map."}}
+ (is (=? {:errors {:definition "value must be a valid MBQL query with a source table and filters."}}
(mt/user-http-request :crowberto :post 400 "segment" {:name "abc"})))
- (is (=? {:errors {:definition "Value must be a map."}}
- (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"
- :definition "foobar"})))
- (testing "definition must specify a source table"
- (is (= "Segment definition must specify a source table."
- (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"
- :definition {}})))
- (is (= "Segment definition must specify a source table."
- (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"
- :definition {:filter [:> [:field (mt/id :users :id) nil] 0]}}))))))
+ (testing "a non-map definition is rejected while decoding, so the body is the message rather than :errors"
+ (is (=? "value must be a valid MBQL query."
+ (mt/user-http-request :crowberto :post 400 "segment" {:name "abc"
+ :definition "foobar"}))))))
(deftest create-segment-test
(doseq [[format-name definition-fn] {"MBQL4" (partial mbql4-segment-definition (mt/id :users))
@@ -125,7 +121,7 @@
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "segment/" (:id segment))
{:name "abc"
- :definition {}
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")
:revision_message "something different"})))))))
(deftest update-input-validation-test
@@ -137,20 +133,20 @@
(is (=? {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc"
:revision_message ""})))
- (is (=? {:errors {:definition "nullable Value must be a map."}}
+ (is (=? "value must be a valid MBQL query."
(mt/user-http-request :crowberto :put 400 "segment/1" {:name "abc"
:revision_message "123"
:definition "foobar"})))))
(deftest update-definition-table-test
(testing "PUT /api/segment/:id"
- (testing "an updated definition must still specify a source table"
+ (testing "an updated definition must still be a valid MBQL query with a source table (enforced by the schema)"
(mt/with-temp [:model/Segment {:keys [id]} {:table_id (mt/id :users)
:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
- (is (= "Segment definition must specify a source table."
- (mt/user-http-request :crowberto :put 400 (str "segment/" id)
- {:revision_message "no more source table"
- :definition {}})))))
+ (is (=? {:errors {:definition {:stages string?}}}
+ (mt/user-http-request :crowberto :put 400 (str "segment/" id)
+ {:revision_message "no more source table"
+ :definition {}})))))
(testing "a definition that moves the Segment to another table keeps table_id in sync"
(mt/with-temp [:model/Segment {:keys [id]} {:table_id (mt/id :users)
:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
diff --git a/test/metabase/server/middleware/misc_test.clj b/test/metabase/server/middleware/misc_test.clj
index 1e1a6694213..9bc17e4ec2a 100644
--- a/test/metabase/server/middleware/misc_test.clj
+++ b/test/metabase/server/middleware/misc_test.clj
@@ -15,6 +15,11 @@
identity
(fn [e] (throw e))))
+(defmacro ^:private with-fresh-instance!
+ [& body]
+ `(mt/with-temporary-setting-values [~'has-user-setup false]
+ ~@body))
+
(defn- mock-request
[uri origin-header x-forwarded-host-header host-header]
(cond-> (m/dissoc-in (ring.mock/request :get uri) [:headers "host"])
@@ -23,72 +28,74 @@
host-header (ring.mock/header "Host" host-header)))
(deftest maybe-set-site-url-test
- (testing "Make sure `maybe-set-site-url` middleware looks at the correct headers in the correct order (#12528)"
- (doseq [origin-header ["https://mb1.example.com" nil]
- x-forwarded-host-header ["https://mb2.example.com" nil]
- host-header ["https://mb3.example.com" nil]
- :let [request (mock-request "/" origin-header x-forwarded-host-header host-header)]]
- (testing (format "headers = %s" (pr-str (:headers request)))
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url request)
- (is (= (or origin-header x-forwarded-host-header host-header)
- (system/site-url)))))))
- (testing "Site URL should not be inferred from healthcheck requests"
- (mt/with-temporary-setting-values [site-url nil]
- (doseq [uri ["/api/health" "/livez" "/readyz"]]
- (let [request (mock-request uri "https://mb1.example.com" nil nil)]
- (maybe-set-site-url request)
- (is (nil? (system/site-url)))))))
- (testing "Site URL should not be inferred if already set in DB"
- (mt/with-temporary-setting-values [site-url "https://mb1.example.com"]
- (let [request (mock-request "/" "https://mb2.example.com" nil nil)]
- (maybe-set-site-url request)
- (is (= "https://mb1.example.com" (system/site-url))))))
- (testing "Site URL should not be inferred if already set by env variable"
- (mt/with-temporary-setting-values [site-url nil]
- (mt/with-temp-env-var-value! [mb-site-url "https://mb1.example.com"]
+ (with-fresh-instance!
+ (testing "Make sure `maybe-set-site-url` middleware looks at the correct headers in the correct order (#12528)"
+ (doseq [origin-header ["https://mb1.example.com" nil]
+ x-forwarded-host-header ["https://mb2.example.com" nil]
+ host-header ["https://mb3.example.com" nil]
+ :let [request (mock-request "/" origin-header x-forwarded-host-header host-header)]]
+ (testing (format "headers = %s" (pr-str (:headers request)))
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url request)
+ (is (= (or origin-header x-forwarded-host-header host-header)
+ (system/site-url)))))))
+ (testing "Site URL should not be inferred from healthcheck requests"
+ (mt/with-temporary-setting-values [site-url nil]
+ (doseq [uri ["/api/health" "/livez" "/readyz"]]
+ (let [request (mock-request uri "https://mb1.example.com" nil nil)]
+ (maybe-set-site-url request)
+ (is (nil? (system/site-url)))))))
+ (testing "Site URL should not be inferred if already set in DB"
+ (mt/with-temporary-setting-values [site-url "https://mb1.example.com"]
(let [request (mock-request "/" "https://mb2.example.com" nil nil)]
(maybe-set-site-url request)
- (is (= "https://mb1.example.com" (system/site-url))))))))
+ (is (= "https://mb1.example.com" (system/site-url))))))
+ (testing "Site URL should not be inferred if already set by env variable"
+ (mt/with-temporary-setting-values [site-url nil]
+ (mt/with-temp-env-var-value! [mb-site-url "https://mb1.example.com"]
+ (let [request (mock-request "/" "https://mb2.example.com" nil nil)]
+ (maybe-set-site-url request)
+ (is (= "https://mb1.example.com" (system/site-url)))))))))
(deftest maybe-set-site-url-forwarded-proto-test
- (testing "scheme-less `*-host` headers get the scheme from `X-Forwarded-Proto` (BOT-1617)"
- (doseq [host-header ["X-Forwarded-Host" "Host"]]
- (testing host-header
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (-> (m/dissoc-in (ring.mock/request :get "/") [:headers "host"])
- (ring.mock/header host-header "mb.example.com")
- (ring.mock/header "X-Forwarded-Proto" "https")))
- (is (= "https://mb.example.com" (system/site-url)))))))
- (testing "`X-Forwarded-Proto` is matched case-insensitively (RFC 3986)"
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
- (ring.mock/header "X-Forwarded-Proto" "HTTPS")))
- (is (= "https://mb.example.com" (system/site-url)))))
- (testing "the first hop wins when `X-Forwarded-Proto` is a comma-separated chain"
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
- (ring.mock/header "X-Forwarded-Proto" "https, http")))
- (is (= "https://mb.example.com" (system/site-url)))))
- (testing "the alternate HTTPS-indicator headers `u/https?` recognizes also seed the scheme"
- (doseq [[header value] [["X-Forwarded-Protocol" "https"]
- ["X-URL-Scheme" "https"]
- ["X-Forwarded-Ssl" "on"]
- ["Front-End-Https" "on"]]]
- (testing header
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
- (ring.mock/header header value)))
- (is (= "https://mb.example.com" (system/site-url)))))))
- (testing "without `X-Forwarded-Proto`, a scheme-less host falls back to http:// (unchanged behavior)"
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (mock-request "/" nil "mb.example.com" nil))
- (is (= "http://mb.example.com" (system/site-url)))))
- (testing "a scheme-bearing host header is left untouched, even alongside `X-Forwarded-Proto` (no double scheme)"
- (mt/with-temporary-setting-values [site-url nil]
- (maybe-set-site-url (-> (mock-request "/" nil "https://mb.example.com" nil)
- (ring.mock/header "X-Forwarded-Proto" "https")))
- (is (= "https://mb.example.com" (system/site-url))))))
+ (with-fresh-instance!
+ (testing "scheme-less `*-host` headers get the scheme from `X-Forwarded-Proto` (BOT-1617)"
+ (doseq [host-header ["X-Forwarded-Host" "Host"]]
+ (testing host-header
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (-> (m/dissoc-in (ring.mock/request :get "/") [:headers "host"])
+ (ring.mock/header host-header "mb.example.com")
+ (ring.mock/header "X-Forwarded-Proto" "https")))
+ (is (= "https://mb.example.com" (system/site-url)))))))
+ (testing "`X-Forwarded-Proto` is matched case-insensitively (RFC 3986)"
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
+ (ring.mock/header "X-Forwarded-Proto" "HTTPS")))
+ (is (= "https://mb.example.com" (system/site-url)))))
+ (testing "the first hop wins when `X-Forwarded-Proto` is a comma-separated chain"
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
+ (ring.mock/header "X-Forwarded-Proto" "https, http")))
+ (is (= "https://mb.example.com" (system/site-url)))))
+ (testing "the alternate HTTPS-indicator headers `u/https?` recognizes also seed the scheme"
+ (doseq [[header value] [["X-Forwarded-Protocol" "https"]
+ ["X-URL-Scheme" "https"]
+ ["X-Forwarded-Ssl" "on"]
+ ["Front-End-Https" "on"]]]
+ (testing header
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (-> (mock-request "/" nil "mb.example.com" nil)
+ (ring.mock/header header value)))
+ (is (= "https://mb.example.com" (system/site-url)))))))
+ (testing "without `X-Forwarded-Proto`, a scheme-less host falls back to http:// (unchanged behavior)"
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (mock-request "/" nil "mb.example.com" nil))
+ (is (= "http://mb.example.com" (system/site-url)))))
+ (testing "a scheme-bearing host header is left untouched, even alongside `X-Forwarded-Proto` (no double scheme)"
+ (mt/with-temporary-setting-values [site-url nil]
+ (maybe-set-site-url (-> (mock-request "/" nil "https://mb.example.com" nil)
+ (ring.mock/header "X-Forwarded-Proto" "https")))
+ (is (= "https://mb.example.com" (system/site-url)))))))
(deftest add-version-header-test
(testing "x-metabase-version is only added on API calls"
diff --git a/test/metabase/server/streaming_response_test.clj b/test/metabase/server/streaming_response_test.clj
index 6bdc7cd6bea..6490d3156ea 100644
--- a/test/metabase/server/streaming_response_test.clj
+++ b/test/metabase/server/streaming_response_test.clj
@@ -3,6 +3,7 @@
[clj-http.client :as http]
[clojure.core.async :as a]
[clojure.test :refer :all]
+ [clojure.walk :as walk]
[compojure.response]
[malli.error :as me]
[metabase.driver :as driver]
@@ -72,23 +73,25 @@
(reset! start-execution-chan nil)))))
(defmethod driver/execute-reducible-query ::test-driver
- [_driver {{{:keys [sleep]} :query} :native, database-id :database} _context respond]
- {:pre [(integer? sleep) (integer? database-id)]}
- (let [futur (future
- (try
- (when-let [chan @start-execution-chan]
- (a/>!! chan ::started))
- (Thread/sleep (long sleep))
- (respond {:cols [{:name "Sleep", :base_type :type/Integer}]} [[sleep]])
- (catch InterruptedException e
- (reset! canceled? ::interrupted-exception)
- (throw e))))]
- (when-let [canceled-chan qp.pipeline/*canceled-chan*]
- (a/go
- (when (a/<! canceled-chan)
- (reset! canceled? ::canceled-chan-message)
- (future-cancel futur))))
- (u/deref-with-timeout futur 5000)))
+ [_driver {{native-query :query} :native, database-id :database} _context respond]
+ (let [{:keys [sleep]} (walk/keywordize-keys native-query)]
+ (assert (integer? sleep))
+ (assert (integer? database-id))
+ (let [futur (future
+ (try
+ (when-let [chan @start-execution-chan]
+ (a/>!! chan ::started))
+ (Thread/sleep (long sleep))
+ (respond {:cols [{:name "Sleep", :base_type :type/Integer}]} [[sleep]])
+ (catch InterruptedException e
+ (reset! canceled? ::interrupted-exception)
+ (throw e))))]
+ (when-let [canceled-chan qp.pipeline/*canceled-chan*]
+ (a/go
+ (when (a/<! canceled-chan)
+ (reset! canceled? ::canceled-chan-message)
+ (future-cancel futur))))
+ (u/deref-with-timeout futur 5000))))
(defmethod driver/connection-properties ::test-driver
[& _]
diff --git a/test/metabase/settings/models/setting/cache_test.clj b/test/metabase/settings/models/setting/cache_test.clj
index 444243cbe20..af29e773904 100644
--- a/test/metabase/settings/models/setting/cache_test.clj
+++ b/test/metabase/settings/models/setting/cache_test.clj
@@ -26,12 +26,12 @@
updating our locally cached value.."
[]
(t2/update! :model/Setting {:key setting.cache/settings-last-updated-key}
- {:value [:raw (case (mdb/db-type)
- ;; make it one second in the future so we don't end up getting an exact match when we try to test
- ;; to see if things update below
- :h2 "cast(dateadd('second', 1, current_timestamp) AS text)"
- :mysql "cast((current_timestamp + interval 1 second) AS char)"
- :postgres "cast((current_timestamp + interval '1 second') AS text)")]}))
+ {:value ^:allow-raw-sql [:raw (case (mdb/db-type)
+ ;; make it one second in the future so we don't end up getting an exact match when we try to test
+ ;; to see if things update below
+ :h2 "cast(dateadd('second', 1, current_timestamp) AS text)"
+ :mysql "cast((current_timestamp + interval 1 second) AS char)"
+ :postgres "cast((current_timestamp + interval '1 second') AS text)")]}))
(defn- simulate-another-instance-updating-setting! [setting-name new-value]
(if new-value
diff --git a/test/metabase/slackbot/api_test.clj b/test/metabase/slackbot/api_test.clj
index 152455b5c71..cf756944f96 100644
--- a/test/metabase/slackbot/api_test.clj
+++ b/test/metabase/slackbot/api_test.clj
@@ -964,8 +964,8 @@
(is (nil? result) "handler returns nil and does not schedule async work")
(is (zero? (t2/count :model/MetabotFeedback :user_id rasta-id
{:where [:in :message_id
- {:select [:id] :from [:metabot_message]
- :where [:= :external_id "nothing-to-match"]}]}))
+ ^:allow-subquery {:select [:id] :from [:metabot_message]
+ :where [:= :external_id "nothing-to-match"]}]}))
"no feedback row written for unresolvable submissions"))))
(deftest handle-feedback-modal-submission-lurker-test
diff --git a/test/metabase/transforms/test_util.clj b/test/metabase/transforms/test_util.clj
index e578ed9e9b9..60c91fe4d6c 100644
--- a/test/metabase/transforms/test_util.clj
+++ b/test/metabase/transforms/test_util.clj
@@ -46,15 +46,15 @@
(t2/select-one-pk :model/Table
:db_id (mt/id)
:active true
- :id [:in {:select [:table_id]
- :from [(t2/table-name :model/Field)]
- ;; Mirror the QP's queryable-column filter (active-column-pred):
- ;; active, and visibility not sensitive/retired, else the picked
- ;; table still yields no implicit fields.
- :where [:and
- [:= :active true]
- [:or [:= :visibility_type nil]
- [:not-in :visibility_type ["sensitive" "retired"]]]]}]
+ :id [:in ^:allow-subquery {:select [:table_id]
+ :from [(t2/table-name :model/Field)]
+ ;; Mirror the QP's queryable-column filter (active-column-pred):
+ ;; active, and visibility not sensitive/retired, else the picked
+ ;; table still yields no implicit fields.
+ :where [:and
+ [:= :active true]
+ [:or [:= :visibility_type nil]
+ [:not-in :visibility_type ["sensitive" "retired"]]]]}]
{:order-by [[:id :asc]]}))))
(defn drop-target!
diff --git a/test/metabase/util/honey_sql_2_test.clj b/test/metabase/util/honey_sql_2_test.clj
index e25946535cb..a0147c2bfab 100644
--- a/test/metabase/util/honey_sql_2_test.clj
+++ b/test/metabase/util/honey_sql_2_test.clj
@@ -63,12 +63,11 @@
(is (= ["WHERE name = 'Cam''s'"]
(sql/format {:where [:= :name (h2x/literal "Cam's")]}
{:quoted false}))))
- (testing "`literal` should only escape single quotes that aren't already escaped -- with two single quotes..."
- (is (= ["WHERE name = 'Cam''s'"]
+ (testing "`literal` escapes every single quote unconditionally -- no \"already escaped\" exception"
+ (is (= ["WHERE name = 'Cam''''s'"]
(sql/format {:where [:= :name (h2x/literal "Cam''s")]}
- {:quoted false}))))
- (testing "...or with a slash"
- (is (= ["WHERE name = 'Cam\\'s'"]
+ {:quoted false})))
+ (is (= ["WHERE name = 'Cam\\''s'"]
(sql/format {:where [:= :name (h2x/literal "Cam\\'s")]}
{:quoted false}))))
(testing "`literal` should escape strings that start with a single quote"
@@ -149,9 +148,14 @@
:mysql 0.1M)}]
(app-db/query {:select [[(/ 1 10) :one_tenth]]})))))
-(deftest ^:parallel quoted-cast-test
- (is (= ["SELECT CAST(? AS \"bird type\")" "toucan"]
- (sql/format {:select [[(h2x/quoted-cast "bird type" "toucan")]]} {:quoted true, :dialect :ansi}))))
+(deftest ^:parallel cast-test
+ (testing "a sane bare type-name token is emitted raw, since most dialects reject a quoted type name in a CAST"
+ (is (= ["SELECT CAST(? AS date)" "toucan"]
+ (sql/format {:select [[(h2x/cast "date" "toucan")]]} {:quoted true, :dialect :ansi}))))
+ (testing "a type name that isn't a bare token is quoted, so a hostile type cannot inject SQL"
+ (is (= ["SELECT CAST(? AS \"date) UNION SELECT 1 --\")" "toucan"]
+ (sql/format {:select [[(h2x/cast "date) UNION SELECT 1 --" "toucan")]]}
+ {:quoted true, :dialect :ansi})))))
(defn- ->sql [expr]
(sql/format {:select [[expr]]} {:quoted false}))
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index 1763e3b768f..0ae3d70422f 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -626,23 +626,24 @@
(let [curr-db (t2/select-one [:model/Database :cache_ttl], :id db-id)]
(is (= nil (:cache_ttl curr-db))))))))))
-(deftest ignore-is-stub-in-create-test
- (testing "POST /api/database ignores :is_stub in the request body (advanced-config only path)"
+(deftest reject-is-stub-in-create-test
+ (testing "POST /api/database returns a 400 when :is_stub=true is in the request body (advanced-config only path)"
(mt/with-model-cleanup [:model/Database]
(with-redefs [driver/available? (constantly true)
driver/can-connect? (constantly true)]
- (let [{:keys [id]} (mt/user-http-request :crowberto :post 200 "database"
- {:name (mt/random-name)
- :engine (u/qualified-name ::test-driver)
- :details {:db "my_db"}
- :is_stub true})]
- (is (false? (t2/select-one-fn :is_stub :model/Database :id id))))))))
-
-(deftest ignore-is-stub-in-update-test
- (testing "PUT /api/database/:id ignores :is_stub=true in the request body"
+ (is (= "is_stub may not be set via the API"
+ (mt/user-http-request :crowberto :post 400 "database"
+ {:name (mt/random-name)
+ :engine (u/qualified-name ::test-driver)
+ :details {:db "my_db"}
+ :is_stub true})))))))
+
+(deftest reject-is-stub-in-update-test
+ (testing "PUT /api/database/:id returns a 400 when :is_stub=true is in the request body"
(mt/with-temp [:model/Database {db-id :id} {:engine ::test-driver}]
- (mt/user-http-request :crowberto :put 200 (format "database/%d" db-id)
- {:is_stub true})
+ (is (= "is_stub may not be set via the API"
+ (mt/user-http-request :crowberto :put 400 (format "database/%d" db-id)
+ {:is_stub true})))
(testing "the row is unchanged"
(is (false? (t2/select-one-fn :is_stub :model/Database :id db-id))))))
(testing "PUT /api/database/:id passes when :is_stub=false is in the body (no-op, matches default)"
diff --git a/test/metabase/xrays/api/automagic_dashboards_test.clj b/test/metabase/xrays/api/automagic_dashboards_test.clj
index a52f7cd3888..e4cee6ed87c 100644
--- a/test/metabase/xrays/api/automagic_dashboards_test.clj
+++ b/test/metabase/xrays/api/automagic_dashboards_test.clj
@@ -305,13 +305,6 @@
:dataset_query
qp/process-query))))))))))))
-(deftest cards-have-can-run-adhoc-query-test
- (api-call! "table/%s" [(mt/id :venues)]
- (constantly true)
- (fn [dashboard]
- (is (every? #(get-in % [:card :can_run_adhoc_query])
- (filter :card (:dashcards dashboard)))))))
-
;;; ------------------- Index Entities Xrays -------------------
(deftest add-source-model-link-auto-width-test