The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Better management of database metadata (#79181)
Nathan Voxland7b58c182a3d4
diff --git a/deps.edn b/deps.ednindex 70d6f0ff3eb..81a5d7fd9dc 100644--- a/deps.edn+++ b/deps.edn@@ -353,6 +353,9 @@"-Dmb.jetty.join=false""-Dmb.field.filter.operators.enabled=true""-Dmb.api.key=test-api-key"+ ;; Test warehouses live on localhost, so the network policy has to be off by default or every test+ ;; that creates one breaks.+ "-Dmb.warehouse.allowed.networks=allow-all";; Port 0 tells the OS to assign a random free port, allowing parallel test runs.;; The actual port is read from the running Jetty server via server.instance/server-port."-Dmb.jetty.port=0"]}diff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.mdindex 47ffbb0b8a9..13e494c0b65 100644--- a/docs/developers-guide/driver-changelog.md+++ b/docs/developers-guide/driver-changelog.md@@ -206,6 +206,48 @@ title: Driver interface changelog`:metabase.driver.sql.query-processor.like-escape-char-built-in/like-escape-char-built-in` as a parent of your driver.See `metabase.driver.mysql` for an example of using the abstract driver.+## Metabase 0.58.23++- `metabase.driver/connection-hosts` `[driver details]` -- new multimethod returning the host names pointed to for a set+ of connection details. Where `details` is the connection-details map stored+ on the Database row: the values an admin filled into the "Add a database" form, plus anything Metabase derived from them.+ The default implementation parses hostnames out of `:host` and/or `:hostname`.+ The SSH tunnel host is handled externally and should not be returned here.++ If you cannot work out the hosts -- an unparseable connection URI, say -- throw rather than guessing or returning+ an empty list. Metabase turns a throw into a refusal, which is the safe answer; an empty list reads as "these+ details name no hosts" and lets the connection through unchecked. Return an empty list only when the details really+ do name nowhere, as a file-backed database does.++- `metabase.driver/host-carrying-parameters` `[driver]` -- new multimethod returning possible client parameters+ that can carry a host that the client will connect to: a proxy, a failover partner, a token or authentication+ endpoint, an alternate API endpoint, etc.++ ```clj+ (defmethod driver/host-carrying-parameters :sqlserver+ [_driver]+ ["serverName" "failoverPartner" "enclaveAttestationUrl"])+ ```++ To find possible parameter names, `java.sql.Driver/getPropertyInfo` enumerates every parameter it accepts.++- `metabase.driver/non-host-parameters` `[driver]` -- new multimethod naming the parameters that LOOK+ like they might carry a host but have been checked and do not: a certificate's expected hostname, a Kerberos+ principal, a local bind address, a proxy's port, etc. Nothing reads it at connection time; it records that+ somebody looked, so that `host-carrying-parameters` can be checked for completeness in tests against what+ the client says it accepts. Does NOT have to include all non-host parameters. Just ones that sound like they might+ but actually don't.++- `metabase.driver/connection-parameter-hosts` `[driver details]` -- new multimethod returning the host *values*+ those parameters hold, once the details, `:additional-options`, and any driver-specific rewriting have been folded+ in. The default implementation is almost always valid, but exists as a possible multimethod for special cases+ such as when your connection string is somewhere the default implementation cannot see.++- `metabase.driver/routes-connection-through-ssh-tunnel?` `[driver]` -- new multimethod saying whether the driver+ opens its warehouse connection through the SSH tunnel described by the `:tunnel-*` details.+ Defaults to `false`, and to `true` for `:sql-jdbc` and everything beneath it. A non-`:sql-jdbc`+ driver that opens a tunnel itself must implement this.+## Metabase 0.58.0- Added a `:collate` feature for drivers that support collation settings on text fieldsdiff --git a/e2e/runner/cypress-runner-backend.js b/e2e/runner/cypress-runner-backend.jsindex 351ce44db8c..ad92c856bcb 100755--- a/e2e/runner/cypress-runner-backend.js+++ b/e2e/runner/cypress-runner-backend.js@@ -27,6 +27,13 @@ process.env.MB_ENABLE_TEST_LOCALES = "true";// against the H2 sample data; this defers migrating the tests to SQLite until after the release.process.env.MB_SAMPLE_DATABASE_ENGINE = "h2";+// The warehouses the E2E suite connects to are all on localhost, so the warehouse network policy has to be off.+// It otherwise defaults to `external-only` whenever `is-hosted?` is true, which any spec calling+// `setTokenFeatures("all")` (or activating a cloud token) makes true -- and those specs would then be unable to+// add or sync a test database. Set here rather than in the `:e2e` deps.edn alias because CI runs the uberjar and+// never reads that alias. A spec that wants the policy on can set it through the settings API.+process.env.MB_WAREHOUSE_ALLOWED_NETWORKS = "allow-all";+if (!process.env.CI) {// Use a temporary copy of the sample db so it won't use and lock the db used for local developmentprocess.env.MB_INTERNAL_DO_NOT_USE_SAMPLE_DB_DIR = path.resolve(diff --git a/e2e/runner/embedding-sdk/sample-apps/helpers/get-logs-command.ts b/e2e/runner/embedding-sdk/sample-apps/helpers/get-logs-command.tsindex a28330b61e4..3578ef3e078 100644--- a/e2e/runner/embedding-sdk/sample-apps/helpers/get-logs-command.ts+++ b/e2e/runner/embedding-sdk/sample-apps/helpers/get-logs-command.ts@@ -5,5 +5,8 @@ export const getLogsCommand = (appName: string): string => {);}- return `for container in $(docker ps --filter "name=${appName}-" --format "{{.Names}}"); do docker logs "$container" 2>&1 | sed "s/^/[$container] /"; done`;+ // `-a`, because the only time these logs are wanted is when a container failed -- and a container that died on+ // startup is no longer running, so plain `docker ps` matches nothing and this prints an empty string. That is the+ // difference between "the metabase container exited (1)" and knowing why.+ return `for container in $(docker ps -a --filter "name=${appName}-" --format "{{.Names}}"); do docker logs "$container" 2>&1 | sed "s/^/[$container] /"; done`;};diff --git a/modules/drivers/athena/src/metabase/driver/athena.clj b/modules/drivers/athena/src/metabase/driver/athena.cljindex 1512c4ca2d9..0e13a8a0fef 100644--- a/modules/drivers/athena/src/metabase/driver/athena.clj+++ b/modules/drivers/athena/src/metabase/driver/athena.clj@@ -30,6 +30,17 @@(driver/register! :athena, :parent #{:sql-jdbc})+(defmethod driver/host-carrying-parameters :athena+ [_driver]+ ["AthenaEndpoint" "AthenaStreamingEndpoint" "S3Endpoint" "StsEndpoint" "LakeFormationEndpoint"+ "SsoAdminEndpoint" "SsoOidcEndpoint" "SsoLoginUrl" "IdentityCenterIssuerUrl" "IdpHostName"+ "IdpWellKnownConfigurationUrl" "DataZoneEndpointOverride" "ProxyHost"])++(defmethod driver/non-host-parameters :athena+ [_driver]+ ["DataZoneDomainId" "DataZoneDomainRegion" "OutputLocation" "PingPartnerSpId" "ProxyEnabledForIdP"+ "ProxyExemptHosts" "ProxyPassword" "ProxyPort" "ProxyUsername"])+;;; +----------------------------------------------------------------------------------------------------------------+;;; | metabase.driver method impls |;;; +----------------------------------------------------------------------------------------------------------------+@@ -62,6 +73,14 @@[region](str "//athena." region ".amazonaws.com" (when (str/starts-with? region "cn-") ".cn") ":443"))+(defmethod driver/connection-hosts :athena+ [_driver {:keys [hostname region]}]+ (driver/hosts-from-details+ {:host (if (str/blank? hostname)+ (str "athena." region ".amazonaws.com" (when (str/starts-with? region "cn-") ".cn"))+ hostname)}+ [:host]))+(defmethod sql-jdbc.conn/connection-details->spec :athena[_driver {:keys [region access_key secret_key s3_staging_dir workgroup catalog dbname hostname], :as details}](-> (mergediff --git a/modules/drivers/athena/test/metabase/driver/athena_test.clj b/modules/drivers/athena/test/metabase/driver/athena_test.cljindex 3f12fc396ad..0770e2edd2f 100644--- a/modules/drivers/athena/test/metabase/driver/athena_test.clj+++ b/modules/drivers/athena/test/metabase/driver/athena_test.clj@@ -142,6 +142,17 @@"cn-north-1" "//athena.cn-north-1.amazonaws.com.cn:443""cn-northwest-1" "//athena.cn-northwest-1.amazonaws.com.cn:443")))+(deftest ^:parallel connection-hosts-test+ (are [details expected] (= expected (driver/connection-hosts :athena details))+ {:region "us-east-1"}+ ["athena.us-east-1.amazonaws.com"]++ {:region "cn-north-1"}+ ["athena.cn-north-1.amazonaws.com.cn"]++ {:region "us-east-1" :hostname "athena.internal.example"}+ ["athena.internal.example"]))+(deftest ^:parallel athena-subname-uses-hostname-test(mt/test-driver :athena(doseq [[test-desc details exp-subname]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.cljindex eb388305f3d..7b162d29e59 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@@ -22,9 +22,11 @@[metabase.driver.sql.query-processor.like-escape-char-built-in :as-alias like-escape-char-built-in][metabase.driver.sql.util :as sql.u][metabase.driver.sync :as driver.s]+ [metabase.driver.util :as driver.u][metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.i18n :refer [deferred-tru tru]]+ [metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.performance :refer [mapv some empty? not-empty]]@@ -81,8 +83,33 @@'("https://www.googleapis.com/auth/bigquery""https://www.googleapis.com/auth/drive"))+(def ^:private default-api-host+ "Where `BigQueryOptions` sends API calls when no alternate `:host` is configured."+ "bigquery.googleapis.com")++(def ^:private default-token-uri+ "Where `ServiceAccountCredentials` exchanges the signed JWT when the credentials JSON names no `token_uri`."+ "https://oauth2.googleapis.com/token")++(defn- service-account-token-uri+ "The URI [[bigquery.common/service-account-json->service-account-credential]] will POST a signed assertion to.+ `ServiceAccountCredentials/fromStream` honors a `token_uri` out of the credentials JSON, so this is a destination+ chosen by whoever supplied the credentials rather than a fixed Google endpoint."+ [service-account-json]+ (or (when-not (str/blank? service-account-json)+ (not-empty (get (json/decode service-account-json) "token_uri")))+ default-token-uri))++(defmethod driver/connection-hosts :bigquery-cloud-sdk+ [_driver {:keys [host service-account-json]}]+ (driver/hosts-from-details+ {:api-host (if (str/blank? host) default-api-host host)+ :token-host (service-account-token-uri service-account-json)}+ [:api-host :token-host]))+(mu/defn- database-details->client^BigQuery [details :- :map]+ (driver.u/validate-connection-hosts! :bigquery-cloud-sdk details)(let [base-creds (bigquery.common/database-details->service-account-credential details)creds (.createScoped base-creds bigquery-scopes)mb-version (:tag driver-api/mb-version-info)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.cljindex e8b657eea01..e138d7836b6 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@@ -60,6 +60,44 @@(is (seq (mt/rows(mt/run-mbql-query orders {:limit 1})))))))+(defn- service-account-json+ [& {:as extra}]+ (json/encode (merge {:type "service_account"+ :project_id "test-project"+ :client_email "[email protected]"}+ extra)))++(deftest ^:parallel connection-hosts-test+ (testing "the fixed vendor endpoints are reported even when nothing is configured"+ (is (= #{"bigquery.googleapis.com" "oauth2.googleapis.com"}+ (set (driver/connection-hosts :bigquery-cloud-sdk+ {:service-account-json (service-account-json)})))))+ (testing "the alternate hostname replaces the API endpoint (it is a URL, not a bare host)"+ (is (= #{"bq.internal" "oauth2.googleapis.com"}+ (set (driver/connection-hosts :bigquery-cloud-sdk+ {:host "https://bq.internal:9999"+ :service-account-json (service-account-json)})))))+ (testing "`token_uri` from the service account JSON is fetched by Metabase, so it counts as a connection host"+ ;; `ServiceAccountCredentials/fromStream` honors `token_uri`, so the credentials blob -- not just `:host` --+ ;; decides where Metabase POSTs a signed JWT.+ (is (= #{"bigquery.googleapis.com" "sts.internal"}+ (set (driver/connection-hosts+ :bigquery-cloud-sdk+ {:service-account-json (service-account-json :token_uri "http://sts.internal/token")})))))+ (testing "credentials we cannot read fail closed rather than reporting only the endpoints we can see"+ (is (thrown? Exception+ (driver/connection-hosts :bigquery-cloud-sdk {:service-account-json "{not json"})))))++(deftest client-honors-network-policy-test+ (testing "the network policy is enforced when the client is built, not only when the database is saved"+ ;; BigQuery is not a `:sql-jdbc` driver, so it has no connection pool to re-check the details on the way out.+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Cannot connect to a private or internal network address"+ (#'bigquery/database-details->client {:host "https://169.254.169.254"+ :service-account-json (service-account-json)}))))))+(deftest can-connect?-test(mt/test-driver :bigquery-cloud-sdk(let [db-details (:details (mt/db))diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.cljindex b4bfe48b34e..f82bd4735b2 100644--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj@@ -34,6 +34,14 @@(defmethod driver/display-name :clickhouse [_] "ClickHouse")+;; the connection is made through the proxy when one is set, so it is the host actually contacted.+(defmethod driver/host-carrying-parameters :clickhouse [_driver] ["proxy_host"])++(defmethod driver/non-host-parameters :clickhouse+ [_driver]+ ["proxy_password" "proxy_port" "proxy_type" "proxy_user" "server_time_zone" "server_version"+ "socket_tcp_nodelay" "use_server_time_zone" "use_server_time_zone_for_dates"])+(defn- quote-schema [s] (sql.u/quote-name :clickhouse :schema s))(defmethod driver/prettify-native-form :clickhousediff --git a/modules/drivers/databricks/src/metabase/driver/databricks.clj b/modules/drivers/databricks/src/metabase/driver/databricks.cljindex df5cd8603e7..9ba1c92b972 100644--- a/modules/drivers/databricks/src/metabase/driver/databricks.clj+++ b/modules/drivers/databricks/src/metabase/driver/databricks.clj@@ -42,6 +42,10 @@(driver/register! :databricks, :parent :hive-like)+(defmethod driver/host-carrying-parameters :databricks+ [_driver]+ ["ProxyHost" "OAuth2ConnAuthAuthorizationEndPoint" "OAuth2ConnAuthTokenEndpoint"])+(doseq [[feature supported?] {:basic-aggregations true:binning true:database-routing truediff --git a/modules/drivers/druid-jdbc/src/metabase/driver/druid_jdbc.clj b/modules/drivers/druid-jdbc/src/metabase/driver/druid_jdbc.cljindex 0f7833dd8b1..9e18c74b6a1 100644--- a/modules/drivers/druid-jdbc/src/metabase/driver/druid_jdbc.clj+++ b/modules/drivers/druid-jdbc/src/metabase/driver/druid_jdbc.clj@@ -26,6 +26,14 @@(driver/register! :druid-jdbc :parent #{:sql-jdbc})+(defmethod driver/host-carrying-parameters :druid-jdbc+ [_driver]+ ["url" "LB_URLS"])++(defmethod driver/non-host-parameters :druid-jdbc+ [_driver]+ ["HOSTNAME_VERIFICATION"])+(doseq [[feature supported?] {:set-timezone true:expression-aggregations true:expression-literals truediff --git a/modules/drivers/mongo/src/metabase/driver/mongo.clj b/modules/drivers/mongo/src/metabase/driver/mongo.cljindex 1f72fdd3917..5c1cce02b54 100644--- a/modules/drivers/mongo/src/metabase/driver/mongo.clj+++ b/modules/drivers/mongo/src/metabase/driver/mongo.clj@@ -25,8 +25,10 @@[metabase.util.performance :refer [some mapv empty? get-in]][taoensso.nippy :as nippy])(:import- (com.mongodb MongoCommandException MongoSecurityException)+ (com.mongodb ConnectionString MongoCommandException MongoSecurityException)(com.mongodb.client MongoClient MongoDatabase)+ (com.mongodb.spi.dns DnsClient)+ (javax.naming.directory Attribute Attributes InitialDirContext)(org.bson.types Binary ObjectId)))(set! *warn-on-reflection* true)@@ -48,6 +50,63 @@(driver/register! :mongo)+(def ^DnsClient ^:private no-op-dns-client+ ;; `ConnectionString` resolves TXT records while parsing an SRV URI. Host extraction must be deterministic and+ ;; side-effect free. The actual client performs TXT/SRV discovery later, and every discovered server address+ ;; ultimately goes through the guarded transport resolver.+ (reify DnsClient+ (getResourceRecordData [_ _ _] [])))++(defn- srv-target-hosts+ "Resolve the `_mongodb._tcp.<host>` SRV record that a `mongodb+srv://` connection string expands to, returning the+ target hostnames. `mongodb+srv` puts a layer of caller-controlled DNS indirection in front of the real servers, so+ checking only the SRV name itself would leave the hosts actually connected to unchecked.++ Returns nil when this preflight lookup fails, unlike the parsing in [[driver/connection-hosts]], which fails closed.+ The two differ because this is a live DNS query: it can fail for reasons that have nothing to do with the details+ being validated, and failing closed would make a flaky resolver refuse every `mongodb+srv://` database. Nothing is+ lost by being lenient here -- [[metabase.driver.mongo.connection]] installs an `InetAddressResolver` that checks+ every SRV target against the same policy as the client connects."+ [host]+ (try+ (let [^InitialDirContext context (InitialDirContext.)]+ (try+ (let [^Attributes attrs (.getAttributes context+ ^String (str "dns:/_mongodb._tcp." host)+ ^"[Ljava.lang.String;" (into-array String ["SRV"]))]+ (when-let [^Attribute attr (.get attrs "SRV")]+ (into []+ ;; each record reads "<priority> <weight> <port> <target>."+ (keep #(last (str/split (str (.get attr (int %))) #"\s+")))+ (range (.size attr)))))+ (finally+ (.close context))))+ (catch Throwable _ nil)))++(defmethod driver/routes-connection-through-ssh-tunnel? :mongo [_driver] true)++(defmethod driver/connection-hosts :mongo+ [_driver {:keys [use-conn-uri host] :as details}]+ ;; Mongo takes its hosts from `:host` *or*, when `use-conn-uri` is set, from anywhere inside `:conn-uri` -- and+ ;; either may name several hosts (a replica set). Parsing the connection string the driver itself will use is the+ ;; only way to be sure we see the same hosts it will connect to.+ (if (and (not use-conn-uri) (str/blank? host))+ ;; nothing to parse and nothing to connect to. `:write_data_details` and `:admin_details` are overlays merged on+ ;; top of `:details`, so they arrive here as partial maps; one that carries no host of its own names no hosts,+ ;; which is what the default implementation reports for the same input.+ []+ ;; Parsing failures are left to propagate. It is tempting to fall back to the `:host` field, since a connection+ ;; string this cannot parse is one `db-details->mongo-client-settings` cannot parse either, so it connects+ ;; nowhere -- but that reasoning holds only as long as both keep building the same `ConnectionString`, and the+ ;; fallback would have us validate a host the driver may never use. Better to report that we cannot say what the+ ;; hosts are, which [[metabase.driver.util/validate-connection-hosts!]] turns into a refusal.+ (let [conn-string (mongo.connection/db-details->connection-string details)+ hosts (vec (.getHosts (ConnectionString. conn-string no-op-dns-client)))+ hosts (cond-> hosts+ (str/starts-with? conn-string "mongodb+srv://")+ (into (mapcat srv-target-hosts hosts)))]+ (driver/hosts-from-details {:host (str/join "," hosts)} [:host]))))+(defmethod driver/can-connect? :mongo[_ db-details](trydiff --git a/modules/drivers/mongo/src/metabase/driver/mongo/connection.clj b/modules/drivers/mongo/src/metabase/driver/mongo/connection.cljindex da99d123ac0..53422924e73 100644--- a/modules/drivers/mongo/src/metabase/driver/mongo/connection.clj+++ b/modules/drivers/mongo/src/metabase/driver/mongo/connection.clj@@ -1,6 +1,6 @@(ns metabase.driver.mongo.connection"This namespace contains code responsible for connecting to mongo deployment."- (:refer-clojure :exclude [not-empty])+ (:refer-clojure :exclude [every? not-empty])(:require[clojure.string :as str][metabase.driver-api.core :as driver-api]@@ -12,14 +12,16 @@[metabase.driver.util :as driver.u][metabase.util :as u][metabase.util.log :as log]- [metabase.util.performance :refer [not-empty]])+ [metabase.util.performance :refer [every? not-empty]])(:import(com.mongodbConnectionStringMongoClientSettingsMongoClientSettings$BuilderMongoCredential)- (com.mongodb.connection SslSettings$Builder)))+ (com.mongodb.connection SslSettings$Builder)+ (com.mongodb.spi.dns InetAddressResolver)+ (java.net InetAddress)))(set! *warn-on-reflection* true)@@ -65,18 +67,30 @@(.context ^SslSettings$Builder builder ssl-context)))))builder)))+(defn- warehouse-inet-address-resolver+ "Mongo resolves every seed, SRV target, and topology-discovered server through this resolver. With an SSH tunnel,+ loopback is the intentional local tunnel entrance; other addresses still follow the configured warehouse policy."+ [tunnel-enabled]+ (reify InetAddressResolver+ (lookupByName [_ host]+ (let [addresses (vec (InetAddress/getAllByName ^String host))]+ (when-not (and tunnel-enabled (every? #(.isLoopbackAddress ^InetAddress %) addresses))+ (driver.u/validate-resolved-addresses! addresses))+ addresses))))+(defn db-details->mongo-client-settings"Generate `MongoClientSettings` from `db-details`. `ConnectionString` is generated and applied to`MongoClientSettings$Builder` first. Then credentials are set and ssl context is updated in the `builder` object.Afterwards, `MongoClientSettings` are built using `.build`."^MongoClientSettings- [{:keys [authdb user pass use-conn-uri ssl additional-options] :as db-details}]+ [{:keys [authdb user pass use-conn-uri ssl additional-options tunnel-enabled] :as db-details}](let [connection-string (-> db-detailsdb-details->connection-stringConnectionString.)builder (com.mongodb.MongoClientSettings/builder)](.applicationName builder driver-api/mb-app-id-string)(.applyConnectionString builder connection-string)+ (.inetAddressResolver builder (warehouse-inet-address-resolver tunnel-enabled))(when-not use-conn-uri;; NOTE: authSource connection parameter is the second argument of `createCredential`. We currently set it only;; when some credentials are used (ie. user is not empty), previously we did that in all cases. I'vediff --git a/modules/drivers/mongo/test/metabase/driver/mongo/connection_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo/connection_test.cljindex 1ac4fd17c07..b0abc704ea5 100644--- a/modules/drivers/mongo/test/metabase/driver/mongo/connection_test.clj+++ b/modules/drivers/mongo/test/metabase/driver/mongo/connection_test.clj@@ -11,7 +11,8 @@[metabase.test :as mt])(:import(com.mongodb MongoCredential ServerAddress)- (com.mongodb.client MongoDatabase)))+ (com.mongodb.client MongoDatabase)+ (com.mongodb.spi.dns InetAddressResolver)))(set! *warn-on-reflection* true)@@ -23,6 +24,29 @@:authdb "authdb":use-srv true})+(deftest warehouse-inet-address-resolver-test+ (let [resolver (-> (mongo.connection/db-details->mongo-client-settings {:host "db.example.com"})+ .getInetAddressResolver)]+ (testing "external-only rejects private and loopback topology hosts"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"private or internal network address"+ (.lookupByName ^InetAddressResolver resolver "127.0.0.1")))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"private or internal network address"+ (.lookupByName ^InetAddressResolver resolver "10.0.0.5")))))+ (testing "allow-private permits private addresses but still rejects loopback"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-private"]+ (is (seq (.lookupByName ^InetAddressResolver resolver "10.0.0.5")))+ (is (thrown? clojure.lang.ExceptionInfo+ (.lookupByName ^InetAddressResolver resolver "127.0.0.1"))))))+ (testing "a Mongo connection using an SSH tunnel permits its local tunnel entrance"+ (let [resolver (-> (mongo.connection/db-details->mongo-client-settings+ {:host "localhost" :tunnel-enabled true})+ .getInetAddressResolver)]+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (seq (.lookupByName ^InetAddressResolver resolver "localhost")))))))+(deftest ^:parallel fqdn?-test(testing "test hostname is fqdn"(is (true? (#'mongo.db/fqdn? "db.mongo.com")))diff --git a/modules/drivers/mongo/test/metabase/driver/mongo_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo_test.cljindex adeb04667b0..b403bac2852 100644--- a/modules/drivers/mongo/test/metabase/driver/mongo_test.clj+++ b/modules/drivers/mongo/test/metabase/driver/mongo_test.clj@@ -1341,3 +1341,52 @@(->> (qp.compile/compile-with-inline-parameters query):query(driver/prettify-native-form :mongo))))))))++(deftest ^:parallel connection-hosts-test+ (testing "hosts are read out of the connection string Mongo will actually use, `conn-uri` included"+ (are [details expected] (= expected (driver/connection-hosts :mongo details))+ {:host "db.example.com" :port 27017}+ ["db.example.com"]++ ;; a replica-set list in the plain host field+ {:host "a.example.com,b.example.com"}+ ["a.example.com" "b.example.com"]++ ;; `conn-uri` can smuggle in a host the `:host` field never mentions+ {:host "db.example.com" :use-conn-uri true+ :conn-uri "mongodb://user:[email protected]:27017,internal.corp:27018/db"}+ ["10.0.0.5" "internal.corp"]++ {:use-conn-uri true :conn-uri "mongodb+srv://user:[email protected]/db"}+ ["cluster.example.com"]))+ (testing "a details map naming no host of its own contributes no hosts, as it does for every other driver"+ ;; `write_data_details` and `admin_details` are overlays merged on top of `:details`, so they reach us as partial+ ;; maps; one that only carries credentials repoints nothing, and the map it overlays is validated on its own+ (are [details] (= [] (driver/connection-hosts :mongo details))+ {}+ {:user "admin" :pass "x"}+ {:host "" :user "admin"}))+ (testing "a connection string we cannot parse throws rather than reporting a host the driver may never use"+ (are [details] (thrown? Throwable (driver/connection-hosts :mongo details))+ {:use-conn-uri true :conn-uri "not a connection string"}+ ;; the dangerous shape: a benign `:host` left over from before `use-conn-uri` was turned on+ {:host "db.example.com" :use-conn-uri true :conn-uri "not a connection string"}+ {:use-conn-uri true :conn-uri nil})))++(deftest connection-hosts-are-validated-test+ (testing "a `conn-uri` pointing at a private address is refused"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"private or internal network address"+ (driver.u/validate-connection-hosts!+ :mongo+ {:host "db.example.com" :use-conn-uri true+ :conn-uri "mongodb://10.224.7.141:27017/db"})))))+ (testing "a `conn-uri` we cannot parse is refused, not validated as the `:host` field instead"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"could not apply security policy"+ (driver.u/validate-connection-hosts!+ :mongo+ {:host "db.example.com" :use-conn-uri true+ :conn-uri "not a connection string"}))))))diff --git a/modules/drivers/oracle/src/metabase/driver/oracle.clj b/modules/drivers/oracle/src/metabase/driver/oracle.cljindex 2edada0f016..b6b63ed960a 100644--- a/modules/drivers/oracle/src/metabase/driver/oracle.clj+++ b/modules/drivers/oracle/src/metabase/driver/oracle.clj@@ -50,6 +50,20 @@(driver/register! :oracle, :parent #{:sql-jdbc ::sql.qp.empty-string-is-null/empty-string-is-null})+(defmethod driver/host-carrying-parameters :oracle+ [_driver]+ ["oracle.net.httpsProxyHost" "oracle.net.socksProxyHost" "oracle.jdbc.ociIamUrl"])++(defmethod driver/non-host-parameters :oracle+ [_driver]+ ["oracle.jdbc.DRCPConnectionPurity" "oracle.jdbc.TcpNoDelay" "oracle.jdbc.azureDatabaseApplicationIdUri"+ "oracle.jdbc.enableErrorUrl" "oracle.jdbc.localhostName" "oracle.jdbc.proxyClientName"+ "oracle.jdbc.readOnlyInstanceAllowed" "oracle.jdbc.redirectUri" "oracle.jdbc.tokenLocation"+ "oracle.net.DOWN_HOSTS_TIMEOUT" "oracle.net.httpsProxyPort" "oracle.net.ldap.security.authentication"+ "oracle.net.ldap.security.credentials" "oracle.net.ldap.security.principal" "oracle.net.ldap.ssl.walletLocation"+ "oracle.net.proxyRemoteDNS" "oracle.net.socksProxyPort" "oracle.net.ssl_server_cert_dn"+ "oracle.net.ssl_server_dn_match" "oracle.net.wallet_location" "server"])+(doseq [[feature supported?] {:convert-timezone true:database-routing false:datetime-diff truediff --git a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.cljindex 33c9aab88b1..e3583b163da 100644--- a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj+++ b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj@@ -49,6 +49,14 @@(driver/register! :presto-jdbc, :parent #{:sql-jdbc ::sql-jdbc.legacy/use-legacy-classes-for-read-and-set})+(defmethod driver/host-carrying-parameters :presto-jdbc+ [_driver]+ ["httpProxy" "socksProxy"])++(defmethod driver/non-host-parameters :presto-jdbc+ [_driver]+ ["KerberosUseCanonicalHostname" "externalAuthenticationRedirectHandlers" "hostnameInCertificate"])+(doseq [[feature supported?] {:basic-aggregations true:binning true:database-routing truediff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.cljindex a76788a7f74..898333b561a 100644--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj@@ -43,6 +43,15 @@;; `:postgres` (see `metabase.driver.postgres`).(driver/register! :redshift, :parent :postgres)+(defmethod driver/host-carrying-parameters :redshift+ [_driver]+ ["host" "PGHOST" "endpointurl" "stsendpointurl"])++(defmethod driver/non-host-parameters :redshift+ [_driver]+ ["assumeminserverversion" "hostrecheckseconds" "isserverless" "kerberosservername" "loadbalancehosts"+ "logservererrordetail" "serverlessacctid" "serverlessworkgroup" "sslhostnameverifier" "targetservertype"])+(doseq [[feature supported?] {:atomic-renames true:connection-impersonation true:database-routing truediff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.cljindex 1af32172a5e..045b5b89099 100644--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj@@ -50,6 +50,19 @@(driver/register! :snowflake, :parent #{:sql-jdbc ::sql-jdbc.legacy/use-legacy-classes-for-read-and-set})+(defmethod driver/host-carrying-parameters :snowflake+ [_driver]+ ["proxyHost" "host"])++(defmethod driver/connection-hosts :snowflake+ [_driver {:keys [account host use-hostname]}]+ (driver/hosts-from-details+ {:host (if (and use-hostname (string? host) (not (str/blank? host)))+ host+ (when (string? account)+ (str account ".snowflakecomputing.com")))}+ [:host]))+(doseq [[feature supported?] {:connection-impersonation true:connection-impersonation-requires-role true:rename truediff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 56563b617da..9c4bea84408 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -56,6 +56,17 @@(set! *warn-on-reflection* true)+(deftest ^:parallel connection-hosts-test+ (are [details expected] (= expected (driver/connection-hosts :snowflake details))+ {:account "xy12345.us-east-2.aws"}+ ["xy12345.us-east-2.aws.snowflakecomputing.com"]++ {:account "xy12345" :use-hostname true :host "snowflake.example.com"}+ ["snowflake.example.com"]++ {:account "xy12345" :use-hostname true :host "https://snowflake.example.com:443"}+ ["snowflake.example.com"]))+(defn- query->native! [query](let [check-sql-fn (fn [_ _ sql & _](throw (ex-info "done" {::native-query sql})))]diff --git a/modules/drivers/sparksql/src/metabase/driver/sparksql.clj b/modules/drivers/sparksql/src/metabase/driver/sparksql.cljindex 11b39e8cb27..597a27316aa 100644--- a/modules/drivers/sparksql/src/metabase/driver/sparksql.clj+++ b/modules/drivers/sparksql/src/metabase/driver/sparksql.clj@@ -11,6 +11,7 @@[metabase.driver.hive-like :as hive-like][metabase.driver.hive-like.fixed-hive-connection :as fixed-hive-connection][metabase.driver.sql-jdbc :as sql-jdbc]+ [metabase.driver.sql-jdbc.common :as sql-jdbc.common][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn][metabase.driver.sql-jdbc.execute :as sql-jdbc.execute][metabase.driver.sql-jdbc.sync :as sql-jdbc.sync]@@ -94,18 +95,33 @@(getConnection [_this](fixed-hive-connection/fixed-hive-connection url properties)))+(defn- connection-url+ [{:keys [host port db jdbc-flags dbname]+ :or {host "localhost", port 10000, db "", jdbc-flags ""}}]+ (let [port (cond-> port+ (string? port) Integer/parseInt)+ db (or dbname db)]+ (format "jdbc:hive2://%s:%s/%s%s" host port db jdbc-flags)))+(defmethod sql-jdbc.conn/connection-details->spec :sparksql- [_driver {:keys [host port db jdbc-flags dbname]- :or {host "localhost", port 10000, db "", jdbc-flags ""}- :as opts}]- (let [port (cond-> port- (string? port) Integer/parseInt)- db (or dbname db)- url (format "jdbc:hive2://%s:%s/%s%s" host port db jdbc-flags)- properties (driver-api/map->properties (dissoc opts :host :port :jdbc-flags))- data-source (->SparkSQLDataSource url properties)]+ [_driver opts]+ (let [properties (driver-api/map->properties (dissoc opts :host :port :jdbc-flags))+ data-source (->SparkSQLDataSource (connection-url opts) properties)]{:datasource data-source}))+;; The connection string is built into a `DataSource` rather than left on the spec, so the generic `:sql-jdbc`+;; implementations cannot see it and both of these read it from [[connection-url]] instead. That is also the only+;; place the substituted `localhost` shows up when the details name no host at all.+(defmethod driver/connection-hosts :sparksql+ [_driver details]+ (sql-jdbc.common/connection-string-hosts (connection-url details)))++(defmethod driver/connection-parameter-hosts :sparksql+ [driver details]+ (sql-jdbc.common/connection-parameter-hosts (connection-url details)+ nil+ (driver/host-carrying-parameters driver)))+(defn- dash-to-underscore [s](when s(str/replace s #"-" "_")))diff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.cljindex 6b508814436..a3f0bae0397 100644--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj@@ -48,6 +48,15 @@(driver/register! :sqlserver, :parent #{:sql-jdbc ::like-escape-char-built-in/like-escape-char-built-in})+(defmethod driver/host-carrying-parameters :sqlserver+ [_driver]+ ["serverName" "failoverPartner" "enclaveAttestationUrl"])++(defmethod driver/non-host-parameters :sqlserver+ [_driver]+ ["hostNameInCertificate" "iPAddressPreference" "instanceName" "integratedSecurity" "serverCertificate"+ "serverNameAsACE" "serverPreparedStatementDiscardThreshold" "serverSpn" "trustServerCertificate"])+(doseq [[feature supported?] {:case-sensitivity-string-filter-options false:connection-impersonation true:connection-impersonation-requires-role truediff --git a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.cljindex ac51a773683..69ca0cc3b5b 100644--- a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj+++ b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj@@ -1209,3 +1209,10 @@"column is a doubled-quote identifier")(is (str/includes? stmt "name = N'by\"cat''; DROP TABLE x; --'")"name in the IF NOT EXISTS guard is a doubled-quote N'' string literal"))))++(deftest ^:parallel connection-parameter-hosts-test+ (testing "`serverName` in additional-options overrides the host in the URL, so it counts as a connection host"+ (let [details {:host "real.example.com" :port 1433 :db "db"}+ hosts #(set (driver/connection-parameter-hosts :sqlserver %))]+ (is (contains? (hosts (assoc details :additional-options "serverName=10.0.0.1")) "10.0.0.1"))+ (is (not (contains? (hosts details) "10.0.0.1"))))))diff --git a/modules/drivers/starburst/src/metabase/driver/starburst.clj b/modules/drivers/starburst/src/metabase/driver/starburst.cljindex 3ea6c1d8c33..464b0ad4fe8 100644--- a/modules/drivers/starburst/src/metabase/driver/starburst.clj+++ b/modules/drivers/starburst/src/metabase/driver/starburst.clj@@ -51,6 +51,14 @@(driver/register! :starburst, :parent #{:sql-jdbc ::sql-jdbc.legacy/use-legacy-classes-for-read-and-set})+(defmethod driver/host-carrying-parameters :starburst+ [_driver]+ ["httpProxy" "socksProxy"])++(defmethod driver/non-host-parameters :starburst+ [_driver]+ ["KerberosUseCanonicalHostname" "externalAuthenticationRedirectHandlers" "hostnameInCertificate"])+(set! *warn-on-reflection* true)(prefer-method driver/database-supports? [:starburst :set-timezone] [:sql-jdbc :set-timezone])diff --git a/modules/drivers/vertica/src/metabase/driver/vertica.clj b/modules/drivers/vertica/src/metabase/driver/vertica.cljindex a9edb024bf7..1fa73333ecb 100644--- a/modules/drivers/vertica/src/metabase/driver/vertica.clj+++ b/modules/drivers/vertica/src/metabase/driver/vertica.clj@@ -30,6 +30,13 @@::sql-jdbc.legacy/use-legacy-classes-for-read-and-set::sql.qp.empty-string-is-null/empty-string-is-null})+(defmethod driver/host-carrying-parameters :vertica [_driver] ["backupservernode" "oauthdiscoveryurl"])++(defmethod driver/non-host-parameters :vertica+ [_driver]+ ["failonmultinodeplans" "hostnameverifier" "kerberoshostname" "maxpooledconnectionspernode" "nodedownwaittime"+ "preferredaddressfamily"])+(doseq [[feature supported?] {:convert-timezone true:database-routing false:datetime-diff truediff --git a/src/metabase/driver.clj b/src/metabase/driver.cljindex 06da2d18ca3..c303c2db995 100644--- a/src/metabase/driver.clj+++ b/src/metabase/driver.clj@@ -21,6 +21,7 @@[metabase.lib.schema.metadata :as lib.schema.metadata][metabase.query-processor.error-type :as qp.error-type][metabase.util :as u]+ [metabase.util.http :as u.http][metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.log :as log]@@ -277,6 +278,116 @@(defmethod validate-db-details! :default [_driver _details] nil)+(def default-host-detail-keys+ "Detail keys that hold a warehouse host across the drivers we ship. `:host` is the near-universal one;+ `:hostname` is Athena's."+ [:host :hostname])++(defmulti connection-hosts+ "Return a collection of the hosts (hostnames or IP literals) that Metabase will open a network connection to+ when connecting to a database with `details`.++ The default implementation reads the usual `:host`/`:hostname` detail keys, tolerating values written as a URL, a+ `host:port` pair, a bracketed IPv6 literal, or a comma-separated list. Concrete drivers should implement this+ explicitly so their complete connection behavior remains auditable, including hosts from connection URIs and fixed+ or derived vendor endpoints.++ Returning an empty collection says these details name nowhere at all, which lets the connection through unchecked --+ so return it only when that is true, as it is for a file-backed database. It is not true of details that merely+ leave the host out: a client substitutes a default of its own, which is why the `:sql-jdbc` implementation reads the+ connection string it builds rather than the details alone. When the hosts cannot be worked out, throw; Metabase+ turns that into a refusal."+ {:added "0.58.23" :arglists '([driver details])}+ dispatch-on-initialized-driver-safe-keys+ :hierarchy #'hierarchy)++(defn hosts-from-details+ "Extract and normalize hostnames from the values of `detail-keys` in `details`. Helper for+ [[connection-hosts]] implementations."+ [details detail-keys]+ (into []+ (comp (map details)+ (filter string?)+ (mapcat #(str/split % #","))+ (keep u.http/->hostname))+ detail-keys))++(defmethod connection-hosts :default+ [_driver details]+ (hosts-from-details details default-host-detail-keys))++(defmulti host-carrying-parameters+ "The names of connection parameters that can name a host this driver's client will connect to -- a proxy, a failover+ partner, a token or attestation endpoint, an alternate API endpoint. Defaults to none.++ These are the parameters of the *client*, not Metabase's connection-property names: whatever ends up in the+ connection string or property map, including anything a user writes into `:additional-options`. A client honors a+ host named here in preference to the one it was handed, so what this returns decides which values+ [[connection-parameter-hosts]] resolves.++ To find them, ask the driver: `java.sql.Driver/getPropertyInfo` enumerates every parameter a JDBC client accepts, and+ `metabase.driver.sql-jdbc.connection-parameter-hosts-test` fails on one whose name looks host-ish and appears+ neither here nor in [[non-host-parameters]]. Prefer declaring a parameter you are unsure about."+ {:added "0.58.23" :arglists '([driver])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod host-carrying-parameters :default+ [_driver]+ [])++(defmulti non-host-parameters+ "The names of connection parameters that read as though they might carry a host -- they mention a host, a server, an+ address, an endpoint -- but have been checked and do not name anywhere the client connects: a certificate's expected+ hostname, a Kerberos principal, a local bind address, a proxy's port, a boolean.++ Declaring one is a record that somebody looked, so the next reader does not have to look again, and so a parameter+ that shows up later is not mistaken for one already accounted for. Nothing reads this at connection time; it exists+ so [[host-carrying-parameters]] can be checked for completeness against what the client says it accepts."+ {:added "0.58.23" :arglists '([driver])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod non-host-parameters :default+ [_driver]+ [])++(defmulti connection-parameter-hosts+ "Hosts named by parameters of the connection string or property map the driver hands to its client, once `details`,+ `:additional-options`, and any driver-specific rewriting have been folded in. Defaults to none.++ Separate from [[connection-hosts]] because a client typically honors a host named in its parameters *over* the one+ in the connection string it was given, so these are hosts a connection may open no matter what the details say. An+ SSH tunnel rewrites the host detail but not these, so they are checked even when a tunnel is in use.++ Drivers rarely implement this: the `:sql-jdbc` method builds the connection spec and reads the parameters a driver+ names in [[host-carrying-parameters]] out of it, which is the declaration a driver author writes instead. Implement+ it only when the connection string is somewhere that method cannot see."+ {:added "0.58.23" :arglists '([driver details])}+ dispatch-on-initialized-driver-safe-keys+ :hierarchy #'hierarchy)++(defmethod connection-parameter-hosts :default+ [_driver _details]+ [])++(defmulti routes-connection-through-ssh-tunnel?+ "Whether `driver` opens its warehouse connection through the SSH tunnel described by the `:tunnel-*` details, so that+ Metabase connects to `:tunnel-host` and the tunnel server resolves the warehouse host on the far side.++ Connection details are an open map, so any driver's details can carry `:tunnel-enabled` whether or not the driver+ does anything with it. This says whether it does: for a driver that does not, the `:tunnel-*` details are inert and+ it is [[connection-hosts]] that describes where the connection really goes.++ Defaults to false, and to true for `:sql-jdbc` (whose connection pool opens the tunnel for every driver beneath it).+ A non-`:sql-jdbc` driver that opens a tunnel itself must say so."+ {:added "0.58.23" :arglists '([driver])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod routes-connection-through-ssh-tunnel? :default [_driver] false)+(defmethod routes-connection-through-ssh-tunnel? :sql-jdbc [_driver] true)+(defmulti dbms-version"Return a map containing information that describes the version of the DBMS. This typically includes a`:version` containing the (semantic) version of the DBMS as a string and potentially a `:flavor`diff --git a/src/metabase/driver/h2.clj b/src/metabase/driver/h2.cljindex 54950b7f52f..9385a1a0a0c 100644--- a/src/metabase/driver/h2.clj+++ b/src/metabase/driver/h2.clj@@ -42,6 +42,13 @@(driver/register! :h2, :parent #{:sql-jdbc ::like-escape-char-built-in/like-escape-char-built-in})+(defmethod driver/connection-hosts :h2+ [_driver {:keys [db]}]+ (if (and (string? db)+ (re-find #"(?i)(?:^|:)(?:tcp|ssl)://" db))+ (driver/hosts-from-details {:db db} [:db])+ []))+;;; this will prevent the H2 driver from showing up in the list of options when adding a new Database.(defmethod driver/superseded-by :h2 [_driver] :deprecated)diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.cljindex 795fe88f204..953da0d39c1 100644--- a/src/metabase/driver/mysql.clj+++ b/src/metabase/driver/mysql.clj@@ -52,6 +52,13 @@(driver/register! :mysql, :parent #{:sql-jdbc ::like-escape-char-built-in/like-escape-char-built-in})+(defmethod driver/host-carrying-parameters :mysql [_driver] [])++(defmethod driver/non-host-parameters :mysql+ [_driver]+ ["disableSslHostnameVerification" "localSocketAddress" "serverRsaPublicKeyFile" "serverSslCert" "serverTimezone"+ "tcpNoDelay" "trustServerCertificate" "useServerPrepStmts"])+(def ^:private ^:const min-supported-mysql-version 5.7)(def ^:private ^:const min-supported-mariadb-version 10.2)diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.cljindex 3869f5d096b..e44360c25d9 100644--- a/src/metabase/driver/postgres.clj+++ b/src/metabase/driver/postgres.clj@@ -61,6 +61,13 @@;; `standard_conforming_strings = off` (#73721).(driver/register! :postgres, :parent #{:sql-jdbc ::like-escape-char-built-in/like-escape-char-built-in})+(defmethod driver/host-carrying-parameters :postgres [_driver] ["host" "PGHOST"])++(defmethod driver/non-host-parameters :postgres+ [_driver]+ ["assumeMinServerVersion" "hostRecheckSeconds" "loadBalanceHosts" "logServerErrorDetail" "tcpNoDelay"+ "targetServerType" "localSocketAddress" "kerberosServerName" "sslhostnameverifier"])+(defmethod driver/display-name :postgres [_] "PostgreSQL");; Features that are supported by Postgres and all of its child drivers like Redshiftdiff --git a/src/metabase/driver/settings.clj b/src/metabase/driver/settings.cljindex 1981eae9619..6321cfdb8e4 100644--- a/src/metabase/driver/settings.clj+++ b/src/metabase/driver/settings.clj@@ -3,12 +3,40 @@[java-time.api :as t][metabase.config.core :as config][metabase.events.core :as events]+ [metabase.premium-features.core :as premium-features][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u]- [metabase.util.i18n :refer [deferred-tru]]))+ [metabase.util.i18n :refer [deferred-tru tru]]))(set! *warn-on-reflection* true)+(defsetting warehouse-allowed-networks+ (deferred-tru (str "Controls which networks Metabase may connect to for warehouse connections.\n"+ "Options:\n"+ "- external-only (only globally routable public addresses)\n"+ "- allow-private (external + private networks but NOT loopback or link-local)\n"+ "- allow-all (no restrictions).\n"+ "Defaults to external-only on Metabase Cloud and allow-all when self-hosted.\n"+ "Also covers the SSH tunnel host and the database auth-provider URLs."))+ :type :keyword+ :visibility :internal+ :export? false+ ;; No `:default`, because it depends on where we are running. On Cloud a warehouse is always reached across the+ ;; public internet, so an internal address is somebody reaching for our own infrastructure rather than their+ ;; database. Self-hosted, a warehouse on a private network is the ordinary case, and defaulting to anything+ ;; stricter would break working instances on upgrade.+ :getter (fn []+ (or (setting/get-value-of-type :keyword :warehouse-allowed-networks)+ (if (premium-features/is-hosted?)+ :external-only+ :allow-all)))+ :setter (fn [new-value]+ (when (some? new-value)+ (assert (#{:external-only :allow-private :allow-all} (keyword new-value))+ (tru (str "Invalid warehouse-allowed-networks! Only values of `external-only`, "+ "`allow-private`,` and `allow-all` are allowed."))))+ (setting/set-value-of-type! :keyword :warehouse-allowed-networks new-value)))+(defsetting ssh-heartbeat-interval-sec(deferred-tru "Controls how often the heartbeats are sent when an SSH tunnel is established (in seconds)."):visibility :publicdiff --git a/src/metabase/driver/sql_jdbc/common.clj b/src/metabase/driver/sql_jdbc/common.cljindex 104d2b09dd4..145aa19d3ca 100644--- a/src/metabase/driver/sql_jdbc/common.clj+++ b/src/metabase/driver/sql_jdbc/common.clj@@ -1,7 +1,10 @@(ns metabase.driver.sql-jdbc.common+ (:refer-clojure :exclude [not-empty])(:require[clojure.string :as str]- [metabase.util :as u]))+ [metabase.util :as u]+ [metabase.util.http :as u.http]+ [metabase.util.performance :refer [not-empty]]))(def ^:private valid-separator-styles #{:url :comma :semicolon})@@ -86,3 +89,83 @@[(k-fn k) v]))kvs (map kv-fn pairs)](into {} kvs))))++(def ^:private authority-regex+ "The `//host:port` of a JDBC URL, or the `@host:port` Oracle writes instead. Matched wherever it appears rather than+ anchored at the front, since a driver may put something of its own first."+ #"(?://|@)([^/]*)")++(defn- authority-host+ "The host named by one `host:port` entry of a URL authority, or nil when the entry names none. Unlike+ [[metabase.util.http/->hostname]], which guesses at a string of unknown shape, this reads a value already known to+ be an authority: a colon is always the port separator and an IPv6 literal is always bracketed."+ [entry]+ (let [entry (-> entry str/trim (str/replace #"^.*@" ""))] ; userinfo+ (not-empty+ (cond+ (str/starts-with? entry "[") (subs entry 1 (or (str/index-of entry "]") (count entry)))+ (str/index-of entry ":") (subs entry 0 (str/index-of entry ":"))+ :else entry))))++(defn connection-string-hosts+ "The hosts named by the authority of a JDBC `connection-string` -- the `//host:port` (or Oracle's `@host:port`) that+ precedes the first parameter, and every entry of it when the driver accepts a comma-separated list.++ Reading the string the driver built, rather than the `:host` detail it was built from, is what catches a client that+ supplies a host of its own: every `:sql-jdbc` driver here substitutes `localhost` when the host detail is missing or+ blank, so the details alone name nowhere while the connection still opens somewhere.++ A connection string with no authority at all names no host, which is the honest answer for a file-backed database.+ An authority that is *present but holds no host* throws instead: `//:5439/db` is the same substitution seen from the+ other side, and pgjdbc handed one connects to localhost. [[metabase.driver/connection-hosts]] turns that into a+ refusal."+ [connection-string]+ (let [before-parameters (first (str/split (str connection-string) #"[?;]" 2))]+ (when-let [[_ authority] (re-find authority-regex before-parameters)]+ (let [entries (str/split authority #",")+ hosts (into [] (keep authority-host) entries)]+ (when-not (= (count entries) (count hosts))+ (throw (ex-info "JDBC connection string has an authority that names no host"+ {:connection-string connection-string})))+ hosts))))++(defn- connection-string-parameters+ "The `name=value` pairs in a JDBC `connection-string`, whichever separator style the driver that built it uses. Only+ what follows the first separator is read: the authority (`//host:port/db`) is [[connection-string-hosts]]' business,+ not ours."+ [connection-string]+ (when-let [params (second (str/split (str connection-string) #"[?;,]" 2))]+ (for [pair (str/split params #"[&;,]")+ :let [[k v] (str/split pair #"=" 2)]+ :when (and k v)]+ [(str/trim k) (str/trim v)])))++(defn- parameter-host [declared? backstop? [k v]]+ (when-let [host (u.http/->hostname v)]+ (when (or (declared? (name k))+ ;; A parameter of the connection string that was not declared is read only when its value is already an+ ;; IP address. That covers a declaration that has fallen behind the client it describes without ever+ ;; resolving a value that may not be a host at all -- which would both hand the value to the resolver+ ;; and, for a name that happens to resolve inside the cluster, refuse a database over its username.+ (and backstop? (u.http/ip-literal? host)))+ host)))++(defn connection-parameter-hosts+ "Hosts named by the parameters of `connection-string` and by `extra-parameters` (a map of the connection properties+ passed alongside it, if any), where `host-parameter-names`+ is [[metabase.driver/host-carrying-parameters]] for the driver that built them.++ A JDBC client resolves a host named in its parameters in preference to the one in the URL it was handed -- pgjdbc+ reads `host=`/`PGHOST=`, mssql-jdbc reads `serverName=` and `failoverPartner=` -- so these are hosts a connection+ may really open, whatever the details say.++ The address backstop applies only to `connection-string`, the string the client parses and where a user's+ `:additional-options` end up. `extra-parameters` is Metabase's own spec map, which carries detail keys the client+ never reads -- an inert one holding an internal URL is not a connection."+ [connection-string extra-parameters host-parameter-names]+ (let [declared-names (into #{} (map u/lower-case-en) host-parameter-names)+ declared? (comp declared-names u/lower-case-en)]+ (into []+ cat+ [(keep #(parameter-host declared? true %) (connection-string-parameters connection-string))+ (keep #(parameter-host declared? false %) (filter (comp string? val) extra-parameters))])))diff --git a/src/metabase/driver/sql_jdbc/connection.clj b/src/metabase/driver/sql_jdbc/connection.cljindex 866179aab3c..c93dde05eb9 100644--- a/src/metabase/driver/sql_jdbc/connection.clj+++ b/src/metabase/driver/sql_jdbc/connection.clj@@ -8,6 +8,7 @@[metabase.driver-api.core :as driver-api][metabase.driver.connection :as driver.conn][metabase.driver.settings :as driver.settings]+ [metabase.driver.sql-jdbc.common :as sql-jdbc.common][metabase.driver.sql-jdbc.connection.ssh-tunnel :as ssh][metabase.driver.util :as driver.u][metabase.util :as u]@@ -48,6 +49,49 @@driver/dispatch-on-initialized-driver-safe-keys:hierarchy #'driver/hierarchy)+(def ^:private spec-structural-keys+ "Keys that describe how to reach the JDBC driver rather than what to say to it."+ [:connection-uri :subname :subprotocol :classname :datasource :datasource-class])++(defn- spec-to-inspect+ "The connection spec `details` would produce, or nil when they do not make one. Used to read where a connection would+ go, never to open it.++ A `:write_data_details` or `:admin_details` overlay reaches us as a partial map that may not make a whole spec.+ Details that cannot produce a spec cannot open a connection either, so nil is a safe answer rather than a blind+ spot."+ [driver details]+ (try+ (connection-details->spec driver details)+ (catch Throwable e+ (log/debug e "Could not build a connection spec to check where it would connect")+ nil)))++(defn- spec-connection-string [spec]+ (or (:connection-uri spec) (:subname spec)))++(defmethod driver/connection-hosts :sql-jdbc+ [driver details]+ ;; Read from the connection string as well as the details, because the two disagree in both directions: a client+ ;; substitutes `localhost` for a host detail that is missing or blank, so the string names a host the details do+ ;; not; and a driver that builds its URL somewhere this cannot see (`:datasource`) leaves the details as the only+ ;; account of where it goes.+ (into (vec (driver/hosts-from-details details driver/default-host-detail-keys))+ (some-> (spec-to-inspect driver details)+ spec-connection-string+ sql-jdbc.common/connection-string-hosts)))++(defmethod driver/connection-parameter-hosts :sql-jdbc+ [driver details]+ ;; The parameters are read off the finished spec rather than off `:additional-options`, so that whatever the driver+ ;; folds in on its way there is covered too -- several drivers pass any detail key they do not recognize straight+ ;; through as a connection property.+ (if-let [spec (spec-to-inspect driver details)]+ (sql-jdbc.common/connection-parameter-hosts (spec-connection-string spec)+ (apply dissoc spec spec-structural-keys)+ (driver/host-carrying-parameters driver))+ []))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | Creating Connection Pools |;;; +----------------------------------------------------------------------------------------------------------------+@@ -201,6 +245,10 @@(log/debug (u/format-color :cyan "Creating new connection pool for %s database %s (%s) ..."driver id (driver.conn/connection-telemetry-info)))(let [details (driver.conn/effective-details database)+ ;; before the tunnel is set up, since incorporating it rewrites `:host` to the local tunnel entrance. Checking+ ;; here as well as at connection-test time narrows the DNS-rebinding window and covers databases that never+ ;; went through a connection test (serialization import, config files).+ _ (driver.u/validate-connection-hosts! driver details)details-with-tunnel (driver/incorporate-ssh-tunnel-details ;; If the tunnel is disabled this returned unchangeddriver(update details :port #(or % (default-ssh-tunnel-target-port driver))))diff --git a/src/metabase/driver/util.clj b/src/metabase/driver/util.cljindex f37b5fda736..609aae9f0e8 100644--- a/src/metabase/driver/util.clj+++ b/src/metabase/driver/util.clj@@ -18,6 +18,7 @@[metabase.query-processor.error-type :as qp.error-type]^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store][metabase.util :as u]+ [metabase.util.http :as u.http][metabase.util.i18n :refer [deferred-tru trs]][metabase.util.log :as log][metabase.util.malli :as mu]@@ -120,6 +121,73 @@(or (instance? java.net.ConnectException throwable)(recur (.getCause throwable)))))+(def ^:private auth-provider-url-detail-keys+ "Detail keys holding a URL that Metabase fetches over plain HTTP -- not through the warehouse connection and not+ through the SSH tunnel -- while resolving an auth provider (see [[fetch-and-incorporate-auth-provider-details]])."+ [:http-auth-url :oauth-token-url])++(defn- hosts-metabase-will-connect-to+ "The hosts Metabase itself resolves and connects to for `details`. With an SSH tunnel enabled Metabase connects to+ the tunnel server and the tunnel server resolves the warehouse host on the far side, so `:host` is (legitimately)+ often `localhost` there and only `:tunnel-host` is ours to check. That only holds for a driver that actually routes+ its connection through the tunnel -- details are an open map, and for a driver that ignores the `:tunnel-*` keys+ (BigQuery) believing them would leave the host it really connects to unchecked.++ Eager on purpose: [[validate-connection-hosts!]] turns a failure to extract the hosts into a refusal, which it can+ only do if the failure happens at the call and not later, when a lazy sequence is walked."+ [driver details]+ (into []+ cat+ [(if (and (:tunnel-enabled details)+ (driver/routes-connection-through-ssh-tunnel? driver))+ (driver/hosts-from-details details [:tunnel-host])+ ;; Fail closed if loading the driver or extracting its hosts fails. Falling back to generic keys here could+ ;; turn a bug in a driver's implementation into an unchecked connection.+ (vec (driver/connection-hosts driver details)))+ ;; deliberately outside the tunnel branch: a tunnel rewrites the host detail, but the client still honors a+ ;; host named in its connection parameters, so those are checked either way+ (driver/connection-parameter-hosts driver details)+ (when (:use-auth-provider details)+ (driver/hosts-from-details details auth-provider-url-detail-keys))]))++(defn- blocked-network-address-exception []+ (let [message (str (deferred-tru "Cannot connect to a private or internal network address."))]+ (ex-info message+ {:status-code 400+ :message message+ :errors {:host (str (deferred-tru "check your host settings"))}})))++(defn- unknown-connection-hosts-exception [cause]+ (let [message (str (deferred-tru "Error resolving hosts: could not apply security policy."))]+ (ex-info message+ {:status-code 400+ :message message+ :errors {:host (str (deferred-tru "check your host settings"))}}+ cause)))++(defn validate-resolved-addresses!+ "Throw when any of the already-resolved `addresses` is disallowed by [[driver.settings/warehouse-allowed-networks]].+ Used by connection transports, such as Mongo's `InetAddressResolver`, that can enforce the policy on the exact+ addresses used to open a socket."+ [addresses]+ (let [policy (driver.settings/warehouse-allowed-networks)]+ (when (some #(not (u.http/address-allowed-for-network-policy? policy %)) addresses)+ (throw (blocked-network-address-exception)))))++(defn validate-connection-hosts!+ "Throw a 400 if `details` would have Metabase open a connection to an address disallowed by+ [[driver.settings/warehouse-allowed-networks]]. Returns nil when the details are acceptable."+ [driver details]+ (let [policy (driver.settings/warehouse-allowed-networks)]+ (when (not= policy :allow-all)+ (let [hosts (try+ (hosts-metabase-will-connect-to driver details)+ (catch Throwable e+ (log/error e "Could not determine the hosts a connection to this database would open")+ (throw (unknown-connection-hosts-exception e))))]+ (when (some #(not (u.http/host-allowed-for-network-policy? policy %)) hosts)+ (throw (blocked-network-address-exception)))))))+(defn can-connect-with-details?"Check whether we can connect to a database with `driver` and `details-map` and perform a basic query such as `SELECT1`. Specify optional param `throw-exceptions` if you want to handle any exceptions thrown yourself (e.g., so you@@ -130,27 +198,32 @@^Boolean [driver details-map & [throw-exceptions]]{:pre [(keyword? driver) (map? details-map)]}(if throw-exceptions- (try- (u/with-timeout (driver.settings/db-connection-timeout-ms)- (or (driver/can-connect? driver details-map)- (throw (Exception. "Failed to connect to Database"))))- ;; actually if we are going to `throw-exceptions` we'll rethrow the original but attempt to humanize the message- ;; first- (catch Throwable e- (log/errorf "Failed to connect to Database: %s" (ex-message e))- (throw (if-let [humanized-message (some->> (u/all-ex-messages e)- (driver/humanize-connection-error-message driver))]- (let [error-data (cond- (keyword? humanized-message)- (tr-connection-error-messages humanized-message)-- (connection-error? e)- (tr-connection-error-messages :cannot-connect-check-host-and-port)-- :else- {:message humanized-message})]- (ex-info (str (:message error-data)) error-data e))- e))))+ (do+ ;; deliberately outside the `try` below: this error is already the message we want the caller to see, and+ ;; running it through `humanize-connection-error-message` would let a driver turn it into something more+ ;; revealing. The boolean arity reaches it through its own `try`, so that one still answers `false`.+ (validate-connection-hosts! driver details-map)+ (try+ (u/with-timeout (driver.settings/db-connection-timeout-ms)+ (or (driver/can-connect? driver details-map)+ (throw (Exception. "Failed to connect to Database"))))+ ;; actually if we are going to `throw-exceptions` we'll rethrow the original but attempt to humanize the+ ;; message first+ (catch Throwable e+ (log/errorf "Failed to connect to Database: %s" (ex-message e))+ (throw (if-let [humanized-message (some->> (u/all-ex-messages e)+ (driver/humanize-connection-error-message driver))]+ (let [error-data (cond+ (keyword? humanized-message)+ (tr-connection-error-messages humanized-message)++ (connection-error? e)+ (tr-connection-error-messages :cannot-connect-check-host-and-port)++ :else+ {:message humanized-message})]+ (ex-info (str (:message error-data)) error-data e))+ e)))))(try(can-connect-with-details? driver details-map :throw-exceptions)(catch Throwable ediff --git a/src/metabase/util/http.clj b/src/metabase/util/http.cljindex 9bdfd62bebb..6b24a7c4952 100644--- a/src/metabase/util/http.clj+++ b/src/metabase/util/http.clj@@ -7,7 +7,7 @@(:import(com.google.common.net InetAddresses)(java.io ByteArrayOutputStream InputStream)- (java.net Inet6Address InetAddress URL)+ (java.net Inet6Address InetAddress URI URL)(java.util Locale)(org.apache.http.conn DnsResolver)(org.apache.http.impl.conn SystemDefaultDnsResolver)))@@ -83,9 +83,12 @@(defn public-address?"True only for globally-routable unicast IP addresses (rejects loopback, link-local, site-local,- any-local, multicast, IPv6 unique-local fc00::/7, and IPv4 CGNAT 100.64.0.0/10)."+ any-local, multicast, IPv6 unique-local fc00::/7, IPv4 CGNAT 100.64.0.0/10, IPv4 \"this network\"+ 0.0.0.0/8, and IPv4 reserved 240.0.0.0/4 -- which includes the 255.255.255.255 broadcast address)."[^InetAddress addr]- (let [b (.getAddress addr)]+ (let [b (.getAddress addr)+ ipv4? (= 4 (alength b))+ b0 (bit-and (aget b 0) 0xff)](not (or (.isLoopbackAddress addr)(.isLinkLocalAddress addr)(.isSiteLocalAddress addr)@@ -93,9 +96,93 @@(.isMulticastAddress addr)(and (instance? Inet6Address addr) ; IPv6 unique-local fc00::/7(= 0xfc (bit-and (aget b 0) 0xfe)))- (and (= 4 (alength b)) ; IPv4 CGNAT 100.64.0.0/10- (= 100 (bit-and (aget b 0) 0xff))- (<= 64 (bit-and (aget b 1) 0xff) 127))))))+ (and ipv4? ; IPv4 CGNAT 100.64.0.0/10+ (= 100 b0)+ (<= 64 (bit-and (aget b 1) 0xff) 127))+ (and ipv4? (zero? b0)) ; IPv4 "this network" 0.0.0.0/8+ (and ipv4? (<= 240 b0)))))) ; IPv4 reserved 240.0.0.0/4 + broadcast++(defn- private-address?+ "True for addresses that are private but may be intentionally reachable from a self-hosted deployment."+ [^InetAddress addr]+ (let [b (.getAddress addr)+ ipv4? (= 4 (alength b))]+ (or (.isSiteLocalAddress addr)+ (and (instance? Inet6Address addr) ; IPv6 unique-local fc00::/7+ (= 0xfc (bit-and (aget b 0) 0xfe)))+ (and ipv4? ; IPv4 CGNAT 100.64.0.0/10+ (= 100 (bit-and (aget b 0) 0xff))+ (<= 64 (bit-and (aget b 1) 0xff) 127)))))++(defn address-allowed-for-network-policy?+ "Whether `addr` is allowed by `policy`.++ `:external-only` allows only globally routable public addresses. `:allow-private` additionally allows private,+ unique-local, and carrier-grade NAT addresses, but still rejects loopback, link-local, any-local, multicast, and+ reserved addresses. `:allow-all` imposes no address restriction."+ [policy ^InetAddress addr]+ (case policy+ :external-only (public-address? addr)+ :allow-private (or (public-address? addr) (private-address? addr))+ :allow-all true+ (throw (ex-info (str "Unknown network policy: " (pr-str policy)) {:policy policy}))))++;; one or more scheme segments, so nested schemes (`jdbc:postgresql://...`) are stripped too+(def ^:private scheme-prefix-regex #"(?i)^(?:[a-z][a-z0-9+.-]*:)+//")++(defn ->hostname+ "Best-effort extraction of a hostname from a string that may be a bare hostname (`db.example.com`), a `host:port`+ pair, a bracketed IPv6 literal (`[::1]` / `[::1]:5432`), or a full URL (`https://db.example.com:8443/x`)."+ [s]+ (let [s (str/trim (str s))]+ (when-not (str/blank? s)+ (let [s (cond-> s+ (re-find scheme-prefix-regex s)+ (#(or (try (.getHost (URI. %)) (catch Throwable _ nil))+ ;; not a well-formed URI -- carry on with whatever followed the scheme+ (str/replace % scheme-prefix-regex ""))))+ s (-> (str s)+ (str/replace #"[/?#].*$" "") ; path / query / fragment+ (str/replace #"^.*@" "")) ; userinfo+ s (cond+ (str/starts-with? s "[") (subs s 1 (or (str/index-of s "]") (count s)))+ ;; one colon means `host:port`; several means a bare (unbracketed) IPv6 literal+ (= 1 (count (filter #{\:} s))) (subs s 0 (str/index-of s ":"))+ :else s)]+ (not-empty (str/trim s))))))++(defn ip-literal?+ "Whether `host` is an IP address written out rather than a name that would have to be resolved. Deciding this takes+ no DNS lookup, which is what makes it safe to ask of a value that may not be a host at all."+ [host]+ (boolean (when-let [host (not-empty (str/trim (str host)))]+ (InetAddresses/isInetAddress (str/replace host #"^\[|\]$" "")))))++(defn- host->inet-addresses+ "Resolve `host` to its `InetAddress`es, returning nil if it is blank or cannot be resolved. Strips the brackets+ around an IPv6 literal (`[::1]`), which `InetAddress` accepts but which we may also see already stripped."+ [host]+ (when-not (str/blank? host)+ (let [host (-> (str/trim host) (str/replace #"^\[|\]$" ""))]+ (try+ (seq (InetAddress/getAllByName host))+ (catch Throwable _ nil)))))++(defn host-allowed-for-network-policy?+ "Whether Metabase may open a connection to `host` under `policy`.++ `host` may be written as a bare hostname, an IP literal, a `host:port` pair, or a full URL or `java.net.URL`;+ see [[->hostname]]. Every address it resolves to must satisfy [[address-allowed-for-network-policy?]].+ `:allow-all` short-circuits before any lookup.++ A host that cannot be resolved is **allowed** -- a DNS outage on a legitimate warehouse should surface as the+ connection error it is, not as an accusation that the host is an internal address."+ [policy host]+ (or (= policy :allow-all)+ (boolean+ (when-let [hostname (->hostname host)]+ (every? #(address-allowed-for-network-policy? policy %)+ (host->inet-addresses hostname))))))(def ^DnsResolver ^:private ssrf-safe-dns-resolver"A `DnsResolver` that resolves normally but throws unless *every* resolved address is public.diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.cljindex abca90173d1..62436fd12d8 100644--- a/src/metabase/warehouses/models/database.clj+++ b/src/metabase/warehouses/models/database.clj@@ -501,9 +501,58 @@(throw (ex-info (tru "Cannot change router_database_id; a destination database is established at creation, not by updating an existing database."){:status-code 400}))))+(def ^:private details-keys+ "Every place a Database stores a set of connection details."+ [:details :write_data_details :admin_details])++(defn- exempt-audit-db?+ "Whether `database` is the Audit DB as the analytics installer writes it: a clone of the *application* database+ rather than a warehouse anybody pointed somewhere, carrying no details of its own and reached over the app-db+ connection. There is no user-supplied host in it to police, and checking it anyway refuses the instance's own app+ db -- empty details read as `localhost`, since every `:sql-jdbc` client substitutes that. The refusal lands during+ init, so the instance fails to boot rather than failing a request.++ Narrowed to a database with no details at all, which is the only shape the installer produces+ ([[metabase-enterprise.audit-app.audit/install-database!]] writes none and nothing else adds any). `:is_audit`+ alone would be too much to hang this on: it is not writable through the API, but it is in the Database serdes+ `:copy` set, and serialization import is one of the routes this check exists to cover."+ [database]+ (and (:is_audit database)+ (every? #(empty? (get database %)) details-keys)))++(defn- validate-connection-hosts!+ "Refuse to store details pointing at a private/internal network address. Enforcing this on the model, and not just on+ the endpoints that test a connection, covers the routes that write a Database without ever testing it: serialization+ import, config-file provisioning, and destination databases.++ `keys-to-check` names which of [[details-keys]] to look at. An overlay is checked the way+ [[metabase.driver.connection/effective-details]] resolves it -- merged onto `:details` -- since that, and not the+ overlay by itself, is what a connection is opened with: one holding nothing but credentials repoints nothing.++ The Audit DB is exempt -- see [[exempt-audit-db?]]."+ [engine database keys-to-check]+ (when-not (exempt-audit-db? database)+ (when-let [engine (some-> engine keyword)]+ (doseq [k keys-to-check+ :let [details (get database k)]+ :when (map? details)]+ (driver.u/validate-connection-hosts! engine (cond->> details+ (not= k :details) (merge (:details database))))))))+(t2/define-before-update :model/Database[database](assert-router-database-id-not-mutated! database)+ (let [changes (t2/changes database)+ original (t2/original database)]+ ;; An engine change can make existing detail keys acquire new meaning, so validate every details map under the new+ ;; driver. Otherwise validate only the ones being written, so an unrelated update to a grandfathered database does+ ;; not start failing. Either way the candidate is the merge, since an overlay is resolved against the `:details`+ ;; it accompanies rather than on its own.+ (validate-connection-hosts! (or (:engine changes) (:engine original))+ (merge original changes)+ (if (contains? changes :engine)+ details-keys+ (filterv #(contains? changes %) details-keys))));; Note: the "sample database may not be edited" policy is enforced at the API layer;; ([[metabase.warehouses-rest.api]] PUT /:id), so internally-derived updates - e.g. the sample;; database engine migration in [[metabase.sample-data.impl]] - can change the engine here.@@ -560,7 +609,8 @@(check-and-schedule-tasks-for-db! (t2.realize/realize database)))(t2/define-before-insert :model/Database- [{:keys [details initial_sync_status], :as database}]+ [{:keys [details initial_sync_status engine], :as database}]+ (validate-connection-hosts! engine database details-keys)(-> (merge {:is_full_sync true:is_on_demand false}database)diff --git a/test/metabase/driver/h2_test.clj b/test/metabase/driver/h2_test.cljindex 542591003fb..04a34314ceb 100644--- a/test/metabase/driver/h2_test.clj+++ b/test/metabase/driver/h2_test.clj@@ -27,6 +27,16 @@(set! *warn-on-reflection* true)+(deftest ^:parallel connection-hosts-test+ (testing "local H2 databases have no network host"+ (is (= [] (driver/connection-hosts :h2 {:db "file:./sample.db"})))+ (is (= [] (driver/connection-hosts :h2 {:db "mem:test"}))))+ (testing "remote H2 TCP and SSL connection strings expose their hosts"+ (are [db expected] (= expected (driver/connection-hosts :h2 {:db db}))+ "tcp://10.0.0.5:9092/sample" ["10.0.0.5"]+ "jdbc:h2:tcp://db.example.com/sample" ["db.example.com"]+ "ssl://[::1]:9092/sample" ["::1"])))+(deftest ^:parallel parse-connection-string-test(testing "Check that the functions for exploding a connection string's options work as expected"(is (= ["file:my-file" {"OPTION_1" "TRUE", "OPTION_2" "100", "LOOK_I_INCLUDED_AN_EXTRA_SEMICOLON" "NICE_TRY"}]diff --git a/test/metabase/driver/sql_jdbc/common_test.clj b/test/metabase/driver/sql_jdbc/common_test.cljindex 48acbaa293f..c5ca592ac71 100644--- a/test/metabase/driver/sql_jdbc/common_test.clj+++ b/test/metabase/driver/sql_jdbc/common_test.clj@@ -37,3 +37,61 @@:semicolon]]](testing (format "can parse value for %s separator style from %s" sep-style addl-opts)(is (= exp (sql-jdbc.common/additional-options->map addl-opts sep-style nv-sep)))))))++(deftest ^:parallel connection-parameter-hosts-test+ (testing "a declared parameter is read, whichever separator style the driver that built the string uses"+ (are [conn-str declared expected]+ (= expected (sql-jdbc.common/connection-parameter-hosts conn-str nil declared))+ "jdbc:postgresql://real.example.com:5432/db?host=internal.corp" ["host"] ["internal.corp"]+ "jdbc:postgresql://real.example.com:5432/db?ssl=true&PGHOST=db.corp" ["PGHOST"] ["db.corp"]+ "jdbc:sqlserver://real.example.com:1433;database=x;failoverPartner=db.corp" ["failoverPartner"] ["db.corp"]+ "jdbc:athena://Region=us-east-1;S3Endpoint=https://s3.corp:8443" ["s3endpoint"] ["s3.corp"]))+ (testing "the authority is left to `connection-hosts` -- only the parameters are read here"+ (are [conn-str] (= [] (sql-jdbc.common/connection-parameter-hosts conn-str nil ["host"]))+ "jdbc:postgresql://127.0.0.1:5432/db"+ "jdbc:postgresql://real.example.com:5432/db"))+ (testing "an undeclared parameter is read only when its value is already an address"+ ;; no lookup for a value that may not be a host at all: nothing is handed to the resolver, and a name that+ ;; happens to resolve inside the cluster cannot refuse a database over its username+ (is (= [] (sql-jdbc.common/connection-parameter-hosts+ "jdbc:postgresql://h:5432/db?user=metabase_ro&sslmode=verify-full&ApplicationName=analytics" nil nil)))+ (is (= ["169.254.169.254"]+ (sql-jdbc.common/connection-parameter-hosts+ "jdbc:postgresql://h:5432/db?ApplicationName=169.254.169.254" nil nil)))+ (testing "including inside a URL, and in bracketed IPv6 form"+ (is (= ["10.0.0.1"] (sql-jdbc.common/connection-parameter-hosts+ "jdbc:x://h:1/db?whatever=https://10.0.0.1:8443/path" nil nil)))+ (is (= ["::1"] (sql-jdbc.common/connection-parameter-hosts "jdbc:x://h:1/db?whatever=[::1]" nil nil)))))+ (testing "parameters passed alongside the connection string rather than inside it are read the same way"+ (is (= ["backup.corp"]+ (sql-jdbc.common/connection-parameter-hosts "jdbc:vertica://real.example.com:5433/db"+ {:backupservernode "backup.corp" :loginTimeout 10}+ ["backupservernode"])))))++(deftest ^:parallel connection-string-hosts-test+ (testing "the authority is read whichever shape the driver built it in"+ (are [conn-str expected] (= expected (sql-jdbc.common/connection-string-hosts conn-str))+ "//localhost:5432/db" ["localhost"]+ "//db.example.com" ["db.example.com"] ; SQL Server leaves the port out of the URL+ "@db.example.com:1521:orcl" ["db.example.com"] ; Oracle's SID form+ "@db.example.com:1521/svc" ["db.example.com"] ; Oracle's service-name form+ "//[::1]:5432/db" ["::1"]+ "//user:[email protected]:5432/db" ["10.0.0.1"]+ "//localhost;serverName=db.corp" ["localhost"]+ "jdbc:hive2://localhost:10000/db" ["localhost"]+ "url=http://h.example.com:8082/druid/v2/" ["h.example.com"])) ; Druid buries a whole URL in a parameter+ (testing "every entry of a replica-set style authority is read, not just the first"+ (is (= ["a.example.com" "b.example.com"]+ (sql-jdbc.common/connection-string-hosts "//a.example.com:5432,b.example.com:5432/db"))))+ (testing "a connection string with no authority names no host -- a file-backed database is not a network connection"+ (are [conn-str] (empty? (sql-jdbc.common/connection-string-hosts conn-str))+ "/tmp/sparrow.db"+ "file:./sparrow"+ "mem:sparrow"+ nil))+ (testing "an authority with no host in it throws, because that is a default the client fills in where we cannot see"+ ;; pgjdbc handed `//:5439/db` connects to localhost, exactly as it does for a URL with no authority at all+ (are [conn-str] (thrown? clojure.lang.ExceptionInfo (sql-jdbc.common/connection-string-hosts conn-str))+ "//:5439/db"+ "//:443/;ConnCatalog=c"+ "//a.example.com:5432,:5432/db")))diff --git a/test/metabase/driver/sql_jdbc/connection_parameter_hosts_test.clj b/test/metabase/driver/sql_jdbc/connection_parameter_hosts_test.cljnew file mode 100644index 00000000000..5fcf87fd3a6--- /dev/null+++ b/test/metabase/driver/sql_jdbc/connection_parameter_hosts_test.clj@@ -0,0 +1,120 @@+(ns ^:mb/driver-tests metabase.driver.sql-jdbc.connection-parameter-hosts-test+ "Keeps [[metabase.driver/host-carrying-parameters]] from falling behind the clients it describes.++ A JDBC client enumerates every parameter it accepts through `java.sql.Driver/getPropertyInfo`. This asks each+ driver on the classpath for that list, narrows it to names that could carry a host, and fails on one the driver has+ neither declared in [[metabase.driver/host-carrying-parameters]] nor written off+ in [[metabase.driver/non-host-parameters]] -- so upgrading a JDBC dependency that adds a parameter+ surfaces it here instead of quietly widening what a database's `:additional-options` can reach."+ (:require+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]+ [metabase.util :as u])+ (:import+ (java.sql Driver DriverPropertyInfo)+ (java.util Properties)))++(set! *warn-on-reflection* true)++(def ^:private host-ish+ "Deliberately wider than the set of parameters that really carry a host: this decides only what a human is asked to+ look at. The answer for each one is recorded on the driver itself, in one declaration or the other."+ #"(?i)host|server|address|endpoint|url|uri|proxy|node|target|instance|partner|peer|site|domain|location|redirect")++(def ^:private probe-details+ "Enough detail to get a connection spec out of a driver. Never connected with -- only handed to the JDBC client so+ it will enumerate its parameters."+ {:postgres {:host "h" :port 5432 :dbname "db"}+ :mysql {:host "h" :port 3306 :dbname "db"}+ :h2 {:db "mem:test"}+ :sqlite {:db "/tmp/probe.db"}+ :sqlserver {:host "h" :port 1433 :db "db"}+ :oracle {:host "h" :port 1521 :sid "orcl"}+ :redshift {:host "h" :port 5439 :db "db"}+ :vertica {:host "h" :port 5433 :db "db"}+ :clickhouse {:host "h" :port 8123 :dbname "db"}+ :databricks {:host "h" :http-path "/x" :catalog "c" :schema "s" :token "t"}+ :presto-jdbc {:host "h" :port 8080 :catalog "c" :schema "s" :user "u"}+ :starburst {:host "h" :port 8080 :catalog "c" :schema "s" :user "u"}+ :sparksql {:host "h" :port 10000 :db "db"}+ :druid-jdbc {:host "http://h" :port 8082}+ :athena {:region "us-east-1" :s3_staging_dir "s3://b/p"}+ :snowflake {:account "acct" :db "db"}})++(defn- jdbc-driver-and-url+ "The client for `driver` and the URL it would be handed, or nil when the spec does not name one -- some drivers build+ a `DataSource` themselves, and those declare their parameters from documentation instead."+ [driver details]+ (let [{:keys [connection-uri subprotocol subname classname]} (sql-jdbc.conn/connection-details->spec driver details)]+ (when-let [url (or connection-uri (when (and subprotocol subname) (str "jdbc:" subprotocol ":" subname)))]+ (when classname+ [(-> (Class/forName classname)+ (.getDeclaredConstructor (into-array Class []))+ (.newInstance (object-array 0)))+ url]))))++(defn- host-ish-parameters+ "The parameters of `driver`'s client whose names look like they could carry a host, or nil when the client will not+ say. Not every client answers: some build a `DataSource` instead of a URL, some return nothing, and Oracle's tries+ to open a connection to answer -- for those the declaration comes from documentation and this cannot check it."+ [driver details]+ (try+ (when-let [[^Driver jdbc-driver ^String url] (jdbc-driver-and-url driver details)]+ (not-empty (sort (for [^DriverPropertyInfo info (.getPropertyInfo jdbc-driver url (Properties.))+ :when (re-find host-ish (.-name info))]+ (.-name info)))))+ (catch Throwable _ nil)))++(def ^:private always-on-the-classpath+ "Drivers that ship in the core artifact. A driver missing from a run is normally just one whose module was not on the+ classpath, which is the whole point of checking whatever is present -- but for these that would mean a namespace+ failed to load, and skipping them silently is how this check would come to pass while testing nothing."+ #{:h2 :postgres :mysql :sqlite})++(defn- loaded-driver+ "`driver` with its namespace loaded, so the methods it declares are registered, or nil when it is not on the+ classpath at all."+ [driver]+ (try+ (driver/the-initialized-driver driver)+ (catch Throwable _ nil)))++(deftest ^:parallel host-parameters-are-declared-or-reviewed-test+ (doseq [[driver details] (sort-by key probe-details)]+ (testing driver+ (if-not (loaded-driver driver)+ (is (not (always-on-the-classpath driver))+ (str driver " ships in the core artifact but would not load, so its parameters went unchecked"))+ (if-let [parameters (host-ish-parameters driver details)]+ (let [declared (into #{} (map u/lower-case-en) (driver/host-carrying-parameters driver))+ reviewed (into #{} (map u/lower-case-en) (driver/non-host-parameters driver))+ unaccounted (remove #(or (declared (u/lower-case-en %)) (reviewed (u/lower-case-en %))) parameters)]+ (is (= [] (vec unaccounted))+ (str "Connection parameters of " driver " that could name a host and are neither declared in"+ " `driver/host-carrying-parameters` nor written off in"+ " `driver/non-host-parameters`. Check the client's documentation: if the parameter"+ " names somewhere the client connects, declare it in the first; otherwise record it in the"+ " second, next to the driver's other connection methods.")))+ (testing "does not enumerate its parameters, so its declaration comes from documentation"+ (is (some? (driver/host-carrying-parameters driver)))))))))++(def ^:private opens-no-connection-without-a-host+ "Drivers for which details naming no host really do name nowhere, so reporting no hosts is the honest answer: `:h2`+ and `:sqlite` back onto a file, and `:druid-jdbc` builds `url=:8082/...`, which Avatica rejects as a malformed URI+ rather than filling a host in. Every other client here substitutes `localhost` instead."+ #{:h2 :sqlite :druid-jdbc})++(deftest ^:parallel host-less-details-name-a-host-or-fail-closed-test+ (testing "a client that fills in its own host does not thereby slip past the network policy"+ (doseq [[driver details] (sort-by key probe-details)+ :when (and (not (opens-no-connection-without-a-host driver))+ (loaded-driver driver))]+ (testing driver+ (let [hosts (try+ (not-empty (vec (driver/connection-hosts driver (dissoc details :host))))+ (catch Throwable _ ::refused))]+ (is (some? hosts)+ (str driver " reports no hosts at all for details that name none, which reads as \"this database is"+ " nowhere\" and lets the connection through unchecked -- but its client will substitute a host of"+ " its own and connect. Report where it would really connect, or throw.")))))))diff --git a/test/metabase/driver/util_test.clj b/test/metabase/driver/util_test.cljindex 0c6e5c0c196..5dd87acbd0c 100644--- a/test/metabase/driver/util_test.clj+++ b/test/metabase/driver/util_test.clj@@ -6,6 +6,7 @@[metabase.driver :as driver][metabase.driver.h2 :as h2][metabase.driver.impl :as driver.impl]+ [metabase.driver.settings :as driver.settings][metabase.driver.util :as driver.u][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu]@@ -606,3 +607,235 @@(is (some? group-info))(is (= "Group info message" (:placeholder group-info)))(is (nil? (:getter group-info)) "Getter should be removed"))))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | SSRF: blocking connections to private network addresses |+;;; +----------------------------------------------------------------------------------------------------------------+++(deftest ^:parallel connection-hosts-test+ (testing "the default implementation picks the host out of the usual detail keys"+ (are [details expected] (= expected (set (driver/connection-hosts :sql details)))+ {} #{}+ {:host "db.example.com"} #{"db.example.com"}+ {:host " db.example.com "} #{"db.example.com"}+ {:host ""} #{}+ {:host nil} #{}+ {:hostname "athena.example.com"} #{"athena.example.com"}+ {:host "a.example.com" :hostname "b.example.com"} #{"a.example.com" "b.example.com"}))+ (testing "hosts given as URLs or host:port pairs are normalized (BigQuery, Databricks and Druid all accept these)"+ (are [details expected] (= expected (set (driver/connection-hosts :sql details)))+ {:host "https://db.example.com:8443"} #{"db.example.com"}+ {:host "http://10.0.0.1"} #{"10.0.0.1"}+ {:host "db.example.com:5432"} #{"db.example.com"}+ {:host "[::1]:5432"} #{"::1"}+ {:host "::1"} #{"::1"}+ {:host "https://user:[email protected]:8443/path"} #{"10.0.0.1"}))+ (testing "comma-separated host lists are split (Mongo accepts a replica-set list here)"+ (is (= #{"a.example.com" "b.example.com"}+ (set (driver/connection-hosts :sql {:host "a.example.com,b.example.com"}))))))++(defn- ssrf-error [thunk]+ (try (thunk) nil (catch clojure.lang.ExceptionInfo e (ex-data e))))++(deftest validate-connection-hosts!-hosted-test+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (testing "connections to non-public addresses are refused"+ (doseq [details [{:host "127.0.0.1" :port 5432}+ {:host "localhost" :port 5432}+ {:host "10.224.7.141" :port 5432}+ {:host "169.254.169.254"}+ {:host "https://192.168.0.1:8443"}]]+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres details)))+ (str "should be refused: " (pr-str details)))))+ (testing "the error is the same for every blocked host, so it cannot be used as a reachability oracle"+ (is (= (:message (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"})))+ (:message (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "10.224.7.141"}))))))+ (testing "public and unresolvable hosts are left alone"+ (doseq [details [{:host "8.8.8.8"}+ {:host "metabase-ssrf-test.invalid"}]]+ (is (nil? (driver.u/validate-connection-hosts! :postgres details))+ (str "should be allowed: " (pr-str details)))))+ (testing "a database with no host of its own is refused: the client fills one in and connects anyway"+ ;; every `:sql-jdbc` client substitutes `localhost` for a host detail that is missing or blank, so reading only+ ;; the details would leave every port on the Metabase host reachable -- and an open one distinguishable from a+ ;; closed one -- to anybody who can add a database+ (doseq [details [{}+ {:port 6379 :dbname "db"}+ {:host "" :port 6379 :dbname "db"}+ {:host " " :port 6379 :dbname "db"}+ {:db "/tmp/whatever.db"}]]+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres details)))+ (str "should be refused: " (pr-str details)))))+ (testing "a driver whose database really is a file, rather than a client with a default host, still has no host"+ (is (nil? (driver.u/validate-connection-hosts! :sqlite {:db "/tmp/whatever.db"}))))+ (testing "auth-provider URLs are fetched by Metabase itself, so they are checked too"+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres+ {:host "db.example.com" :use-auth-provider true :auth-provider "oauth"+ :oauth-token-url "http://169.254.169.254/latest/meta-data/"}))))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres+ {:host "db.example.com" :use-auth-provider true :auth-provider "http"+ :http-auth-url "http://127.0.0.1:8080/token"}))))+ (testing "...but a public auth URL is fine, and the keys are ignored when the provider is off"+ (is (nil? (driver.u/validate-connection-hosts!+ :postgres+ {:host "db.example.com" :use-auth-provider true+ :oauth-token-url "https://login.example.com/token"})))+ (is (nil? (driver.u/validate-connection-hosts!+ :postgres+ {:host "db.example.com" :oauth-token-url "http://127.0.0.1:8080/token"})))))+ (testing "with an SSH tunnel the warehouse host is resolved by the tunnel server, so only the tunnel host matters"+ (is (nil? (driver.u/validate-connection-hosts!+ :postgres+ {:tunnel-enabled true :tunnel-host "bastion.example.com" :host "127.0.0.1" :port 5432})))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres+ {:tunnel-enabled true :tunnel-host "127.0.0.1" :host "db.example.com"})))))))++(deftest can-connect-with-details?-refused-host-test+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (let [details {:host "127.0.0.1" :port 5432 :dbname "db"}]+ (testing "the boolean arity keeps its contract and answers `false` rather than throwing"+ ;; sync, the unhidden-table resync task, and the legacy-details migration loop all branch on this answer;+ ;; a throw from here abandons work that used to carry on to the next database or the next candidate details+ (is (false? (driver.u/can-connect-with-details? :postgres details))))+ (testing "the throwing arity reports the refusal, unhumanized"+ ;; a driver's `humanize-connection-error-message` must not get to rewrite this into something more revealing+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"^Cannot connect to a private or internal network address\.$"+ (driver.u/can-connect-with-details? :postgres details :throw-exceptions)))))))++(deftest validate-connection-hosts!-connection-parameters-test+ ;; A JDBC client honors a host named in the connection parameters over the one in the URL it was handed -- pgjdbc+ ;; reads `host=`/`PGHOST=` from the query string -- and `:additional-options` is appended to that string verbatim.+ (testing "a host smuggled through `:additional-options` is checked, not just the `:host` detail"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (doseq [opts ["host=169.254.169.254"+ "PGHOST=127.0.0.1&ssl=false"+ "ssl=false&host=[::1]"]]+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres {:host "db.example.com" :port 5432 :dbname "db"+ :additional-options opts})))+ (str "should be refused: " (pr-str opts))))+ (testing "an SSH tunnel does not exempt them -- it rewrites the host detail, not the parameters"+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres {:host "db.example.com" :port 5432 :dbname "db"+ :tunnel-enabled true :tunnel-host "bastion.example.com"+ :additional-options "host=169.254.169.254"})))))+ (testing "ordinary options are not mistaken for hosts"+ ;; only the parameters a driver declares in `driver/host-carrying-parameters` are resolved, so a value+ ;; that is not a host is never handed to the resolver -- and a name that happens to resolve inside the+ ;; cluster cannot refuse a database over its application name+ (is (nil? (driver.u/validate-connection-hosts!+ :postgres {:host "db.example.com" :port 5432 :dbname "db"+ :additional-options "loginTimeout=1&ApplicationName=localhost&ssl=false"}))))+ (testing "an undeclared parameter is still checked when its value is already an address"+ ;; a declaration that has fallen behind the client it describes is not a free pass; an IP costs no lookup+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ :postgres {:host "db.example.com" :port 5432 :dbname "db"+ :additional-options "ApplicationName=169.254.169.254"}))))))))++(driver/register! ::no-tunnel-driver, :abstract? true)++(deftest validate-connection-hosts!-tunnel-details-do-not-disable-the-check-test+ (testing "a driver that ignores the tunnel details still has its own hosts checked"+ ;; `:tunnel-enabled` is only meaningful to drivers that route the connection through the tunnel. Details are+ ;; stored as an open map, so any driver's details can carry the key -- for one that ignores it (BigQuery), taking+ ;; the caller's word for it would leave the host it really connects to unchecked.+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts!+ ::no-tunnel-driver+ {:tunnel-enabled true :tunnel-host "bastion.example.com" :host "169.254.169.254"}))))+ (testing "and the tunnel host it never contacts is not held against it"+ (is (nil? (driver.u/validate-connection-hosts!+ ::no-tunnel-driver+ {:tunnel-enabled true :tunnel-host "127.0.0.1" :host "db.example.com"}))))))+ (testing "drivers that do route through the tunnel are unaffected"+ (is (true? (driver/routes-connection-through-ssh-tunnel? :postgres)))+ (is (false? (driver/routes-connection-through-ssh-tunnel? ::no-tunnel-driver)))))++(driver/register! ::broken-hosts-driver, :abstract? true)++(defmethod driver/connection-hosts ::broken-hosts-driver+ [_driver _details]+ (throw (ex-info "boom" {:sensitive "should not reach the caller"})))++(deftest validate-connection-hosts!-fails-closed-test+ (testing "a driver that cannot say which hosts it would connect to is refused, not left unchecked"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! ::broken-hosts-driver {:host "8.8.8.8"}))))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"could not apply security policy"+ (driver.u/validate-connection-hosts! ::broken-hosts-driver {:host "8.8.8.8"})))+ (testing "the underlying failure is chained for the logs but kept out of the message"+ (let [e (try (driver.u/validate-connection-hosts! ::broken-hosts-driver {:host "8.8.8.8"})+ (catch clojure.lang.ExceptionInfo e e))]+ (is (= "boom" (ex-message (ex-cause e))))+ (is (not (str/includes? (ex-message e) "boom")))))+ (testing "details the driver multimethod itself refuses to dispatch on fail closed the same way"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"could not apply security policy"+ (driver.u/validate-connection-hosts!+ :postgres+ {:host "8.8.8.8" :connection-uri "jdbc:postgresql://127.0.0.1:5432/db"}))))))+ (testing "with the policy off no hosts are extracted at all, so a broken driver is not an error"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-all"]+ (is (nil? (driver.u/validate-connection-hosts! ::broken-hosts-driver {:host "8.8.8.8"}))))))++(deftest validate-connection-hosts!-allowed-test+ (testing "allow-private permits private networks but still rejects loopback and link-local addresses"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-private"]+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "10.224.7.141"})))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "169.254.169.254"}))))))+ (testing "allow-all permits every network -- the normal self-hosted case"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-all"]+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1" :port 5432})))+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "10.224.7.141"}))))))++(deftest warehouse-allowed-networks-default-test+ (testing "self-hosted, with nothing configured, all networks are allowed"+ ;; a self-hosted warehouse on a private network is the normal case, not an attack+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks nil]+ (mt/with-premium-features #{}+ (is (= :allow-all (driver.settings/warehouse-allowed-networks)))+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))))+ (testing "hosted, with nothing configured, only public addresses are allowed"+ ;; on Metabase Cloud a warehouse is always reached across the public internet, so anything else is somebody+ ;; reaching for our own infrastructure+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks nil]+ (mt/with-premium-features #{:hosting}+ (is (= :external-only (driver.settings/warehouse-allowed-networks)))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "8.8.8.8"}))))))+ (testing "an explicit setting is honored on Cloud too, in either direction"+ (mt/with-premium-features #{:hosting}+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-all"]+ (is (= :allow-all (driver.settings/warehouse-allowed-networks)))+ (is (nil? (driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "allow-private"]+ (is (= :allow-private (driver.settings/warehouse-allowed-networks))))))+ (testing "an explicit setting overrides the default"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (is (= :external-only (driver.settings/warehouse-allowed-networks)))+ (is (=? {:status-code 400}+ (ssrf-error #(driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))))+ (testing "an unrecognized policy fails closed at the point of use rather than quietly allowing everything"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "unknown-policy"]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Unknown network policy"+ (driver.u/validate-connection-hosts! :postgres {:host "127.0.0.1"}))))))diff --git a/test/metabase/util/http_test.clj b/test/metabase/util/http_test.cljindex 5357ed12936..b6317524b16 100644--- a/test/metabase/util/http_test.clj+++ b/test/metabase/util/http_test.clj@@ -32,6 +32,79 @@(is (true? (http/valid-host? :allow-all "http://192.168.1.1")))(is (true? (http/valid-host? :allow-all "http://169.254.1.1")))))+(deftest ^:parallel host-allowed-external-only-test+ (testing "external-only allows only globally-routable addresses"+ (are [host expected] (= expected (http/host-allowed-for-network-policy? :external-only host))+ "https://example.com" true+ "8.8.8.8" true+ "http://localhost" false+ "http://127.0.0.1" false+ "http://192.168.1.1" false+ "http://10.0.0.1" false+ "http://169.254.1.1" false+ ;; the ranges the old `valid-host?` let through: IPv6 unique-local, CGNAT, any-local+ "https://[fd12:3456::1]" false+ "http://100.64.0.1" false+ "http://0.0.0.0" false)))++(deftest ^:parallel host-allowed-allow-private-test+ (testing "allow-private additionally allows private networks, but never loopback or link-local"+ (are [host expected] (= expected (http/host-allowed-for-network-policy? :allow-private host))+ "https://example.com" true+ "http://192.168.1.1" true+ "http://10.0.0.1" true+ "http://172.16.0.1" true+ "http://100.64.0.1" true+ "https://[fd12:3456::1]" true+ "http://localhost" false+ "http://127.0.0.1" false+ "http://169.254.1.1" false+ "http://169.254.169.254" false)))++(deftest ^:parallel host-allowed-allow-all-test+ (testing "allow-all short-circuits before any lookup"+ (are [host] (true? (http/host-allowed-for-network-policy? :allow-all host))+ "https://example.com"+ "http://localhost"+ "http://192.168.1.1"+ "http://169.254.1.1"+ "metadata.google.internal"+ "not-a-url"+ ""))+ (testing "an unknown policy is a programming error, not a silent allow"+ (is (thrown? ExceptionInfo (http/host-allowed-for-network-policy? :allow-everything "http://127.0.0.1")))))++(deftest ^:parallel host-allowed-unresolvable-test+ (testing "a host we cannot resolve is allowed -- a DNS outage on a real warehouse must not be reported as an+ internal address, and a name we cannot resolve is not dialable by the driver either"+ (are [host expected] (= expected (http/host-allowed-for-network-policy? :external-only host))+ "https://metabase-ssrf-test.invalid" true+ "http://127.0.0.1" false+ ;; nothing hostname-like at all is still refused+ "" false+ " " false)))++(deftest ^:parallel host-allowed-host-shapes-test+ (testing "hosts are accepted in any of the shapes `->hostname` understands"+ (are [host expected] (= expected (http/host-allowed-for-network-policy? :external-only host))+ "127.0.0.1" false+ "127.0.0.1:5432" false+ "[::1]:5432" false+ "jdbc:postgresql://10.0.0.1/db" false+ (java.net.URL. "http://10.0.0.1/x") false)))++(deftest ^:parallel host-allowed-alternate-encodings-test+ (testing "alternate encodings of a non-public address are refused, however they resolve"+ (doseq [host ["2130706433" ; decimal form of 127.0.0.1+ "127.1" ; short form of 127.0.0.1+ "0" ; 0.0.0.0+ "[::1]"+ "::1"]]+ (is (false? (http/host-allowed-for-network-policy? :external-only host)) host)))+ (testing "public IP literals are allowed however they are written"+ (doseq [host ["8.8.8.8" "1.1.1.1" "2606:4700:4700::1111" "[2606:4700:4700::1111]"]]+ (is (true? (http/host-allowed-for-network-policy? :external-only host)) host))))+;; --------------------------------------------------------------------------------------------;; SSRF-hardened fetch ([[metabase.util.http/fetch-bytes]] and its helpers). Everything below is;; intentionally network-free -- the URL/address predicates are pure, the DNS resolver is exercised@@ -104,7 +177,13 @@"fe80::1" ; IPv6 link-local"fc00::1" ; IPv6 ULA (fc)"fd12:3456::1" ; IPv6 ULA (fd)- "ff02::1"]) ; IPv6 multicast+ "ff02::1" ; IPv6 multicast+ "0.1.2.3" ; "this network" 0.0.0.0/8+ "0.255.255.255"+ "240.0.0.1" ; reserved 240.0.0.0/4+ "255.255.255.255" ; limited broadcast (inside 240.0.0.0/4)+ "::ffff:127.0.0.1" ; IPv4-mapped loopback+ "::ffff:10.0.0.1"]) ; IPv4-mapped RFC1918(deftest ^:parallel public-address?-test(testing "globally-routable addresses are allowed"@@ -116,6 +195,26 @@(is (false? (boolean (http/public-address? (InetAddress/getByName ip))))(str "should be rejected: " ip)))))+(deftest ^:parallel address-allowed-for-network-policy?-test+ (testing "external-only admits only globally-routable addresses"+ (doseq [ip public-ips]+ (is (true? (http/address-allowed-for-network-policy? :external-only (InetAddress/getByName ip))) ip))+ (doseq [ip non-public-ips]+ (is (false? (http/address-allowed-for-network-policy? :external-only (InetAddress/getByName ip))) ip)))+ (testing "allow-private re-admits exactly the private ranges -- RFC1918, IPv6 ULA and CGNAT"+ (doseq [ip ["10.1.2.3" "172.16.0.1" "172.31.255.255" "192.168.0.1"+ "100.64.0.1" "100.127.255.255" "fc00::1" "fd12:3456::1"]]+ (is (true? (http/address-allowed-for-network-policy? :allow-private (InetAddress/getByName ip))) ip)))+ (testing "allow-private still refuses loopback, link-local, any-local and multicast"+ (doseq [ip ["127.0.0.1" "::1" "169.254.169.254" "fe80::1" "0.0.0.0" "224.0.0.1" "ff02::1"]]+ (is (false? (http/address-allowed-for-network-policy? :allow-private (InetAddress/getByName ip))) ip)))+ (testing "allow-all admits everything"+ (doseq [ip (concat public-ips non-public-ips)]+ (is (true? (http/address-allowed-for-network-policy? :allow-all (InetAddress/getByName ip))) ip)))+ (testing "an unknown policy throws rather than silently allowing"+ (is (thrown? ExceptionInfo+ (http/address-allowed-for-network-policy? :allow-everything (InetAddress/getByName "127.0.0.1"))))))+(deftest ^:parallel ssrf-safe-dns-resolver-test(testing "the validating resolver throws when a host resolves to a non-public address";; `localhost` resolves to loopback (no network needed) -> must be refuseddiff --git a/test/metabase/warehouses/models/database_test.clj b/test/metabase/warehouses/models/database_test.cljindex 6f8db5ebecb..bf9175e286d 100644--- a/test/metabase/warehouses/models/database_test.clj+++ b/test/metabase/warehouses/models/database_test.clj@@ -767,6 +767,70 @@(driver/register! ::test, :abstract? true)+(driver/register! ::host-details-driver, :abstract? true)+(driver/register! ::alternate-details-driver, :abstract? true)++(defmethod driver/connection-hosts ::host-details-driver+ [_driver details]+ (driver/hosts-from-details details [:host]))++(defmethod driver/connection-hosts ::alternate-details-driver+ [_driver details]+ (driver/hosts-from-details details [:alternate-host]))++(deftest engine-change-validates-existing-details-with-new-driver-test+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (mt/with-temp [:model/Database db {:engine (u/qualified-name ::host-details-driver)+ :details {:host "8.8.8.8" :alternate-host "127.0.0.1"}}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/update! :model/Database (:id db) {:engine (u/qualified-name ::alternate-details-driver)}))))))++(deftest overlay-details-are-validated-the-way-they-are-resolved-test+ ;; `:write_data_details` and `:admin_details` are merged onto `:details` by+ ;; [[metabase.driver.connection/effective-details]] rather than used on their own, so that merge is what has to+ ;; satisfy the policy -- an overlay holding nothing but credentials repoints nothing.+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (mt/with-temp [:model/Database db {:engine (u/qualified-name ::host-details-driver)+ :details {:host "8.8.8.8"}}]+ (testing "an overlay carrying only credentials inherits the host it will be merged with"+ (is (pos? (t2/update! :model/Database (:id db) {:write_data_details {:user "hummingbird"}}))))+ (testing "an overlay that repoints the connection at an internal address is refused"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/update! :model/Database (:id db) {:admin_details {:host "127.0.0.1" :user "hummingbird"}})))))))++(deftest audit-db-is-not-subject-to-the-network-policy-test+ ;; The Audit DB is a clone of the *application* database, not a warehouse an admin pointed somewhere: it carries no+ ;; `:details` and is reached over the app-db connection. Under the policy its empty details read as `localhost` --+ ;; every `:sql-jdbc` client substitutes that -- so validating it refuses the instance's own app db.+ ;;+ ;; This has to hold on update as well as insert, because+ ;; [[metabase-enterprise.audit-app.audit/adjust-audit-db-to-source!]] flips `:engine` to "postgres" on every boot+ ;; that installs analytics, and an `:engine` change is what makes `before-update` validate every details map. A+ ;; refusal there is thrown during init, so Metabase fails to start rather than failing a request.+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (testing "the audit db can be created"+ (mt/with-temp [:model/Database db {:is_audit true, :engine :h2, :details {}}]+ (testing "and its engine can be flipped the way installing analytics flips it"+ (is (pos? (t2/update! :model/Database (:id db) {:engine "postgres"}))))))+ (testing "an ordinary database with the same empty details is still refused"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/insert! :model/Database {:name "not the audit db", :engine :postgres, :details {}}))))+ (testing "`is_audit` is not itself a way past the policy -- serdes import can set it, so the exemption is+ narrowed to the detail-less shape the analytics installer actually writes"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/insert! :model/Database {:name "audit-flavored smuggling"+ :is_audit true+ :engine (u/qualified-name ::host-details-driver)+ :details {:host "127.0.0.1"}}))))))+(deftest preserve-driver-namespaces-test(testing "Make sure databases preserve namespaced driver names"(mt/with-temp [:model/Database {db-id :id} {:engine (u/qualified-name ::test)}]diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex c6ad98fbc20..b9fafe4426b 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -1921,6 +1921,37 @@(is (= 1 @call-count))(is (= [true] @ssl-values)))))))+(deftest no-ssrf-via-database-add-test+ (testing "endpoints that test connection details cannot be used to probe the internal network (SEC-556)"+ (mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]+ (let [private-details {:host "10.224.7.141" :port 5432 :dbname "postgres" :user "postgres"}]+ (testing "POST /api/database"+ (let [response (mt/user-http-request :crowberto :post 400 "database"+ {:name "internal" :engine "postgres" :details private-details})]+ (is (=? {:message "Cannot connect to a private or internal network address."} response))+ (is (not (t2/exists? :model/Database :name "internal")))))+ (testing "POST /api/database/validate"+ (is (=? {:valid false, :message "Cannot connect to a private or internal network address."}+ (mt/user-http-request :crowberto :post 200 "database/validate"+ {:details {:engine "postgres" :details private-details}}))))+ (testing "every blocked address gives the same answer, so nothing can be learned about what is behind it"+ (is (apply = (for [host ["10.224.7.141" "127.0.0.1" "169.254.169.254" "192.168.55.55"]]+ (mt/user-http-request :crowberto :post 200 "database/validate"+ {:details {:engine "postgres"+ :details (assoc private-details :host host)}})))))+ (testing "PUT /api/database/:id cannot repoint an existing database at an internal address either"+ (mt/with-temp [:model/Database db {:engine "postgres"+ :details {:host "db.example.com" :port 5432 :dbname "x"}}]+ (is (=? {:message "Cannot connect to a private or internal network address."}+ (mt/user-http-request :crowberto :put 400 (str "database/" (u/the-id db))+ {:details private-details})))))+ (testing "a Database with internal details cannot be written directly (serialization import, config files)"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/insert! :model/Database {:name "internal"+ :engine "postgres"+ :details private-details}))))))))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | GET /api/database/:id/schemas & GET /api/database/:id/schema/:schema |;;; +----------------------------------------------------------------------------------------------------------------+