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
Take host-part credentials off the pgvector URL (#83010)
Chris Truter9e27bdf31fdd
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.cljindex 50bca8e0e34..150fdf693dd 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/datasource.clj@@ -94,7 +94,11 @@(into #{} (map #(.getName ^PGProperty %)) (PGProperty/values)))(defn- url-decode ^String [^String s]- (URLDecoder/decode s StandardCharsets/UTF_8))+ (try+ (URLDecoder/decode s StandardCharsets/UTF_8)+ (catch IllegalArgumentException _+ ;; the decoder's own message quotes part of the value, which may be a password+ (throw (ex-info "Malformed %-escape in MB_PGVECTOR_DB_URL" {})))))(defn- split-query"Split a JDBC URL into [base pairs], where pairs is a seq of raw [key value] strings.@@ -108,17 +112,57 @@:let [[k v] (str/split pair #"=" 2)]][k (or v "")])]))+(defn- split-userinfo+ "Split `user:password@` out of a JDBC URL's host part, returning [url credentials].+ The credentials are a map of the decoded :user and :password, empty when the URL has none."+ [^String base]+ ;; The host part runs from `//` to the next `/`.+ ;; Split it at its last `@`, not the first as libpq does, so an unencoded `@` in the password can't leave+ ;; part of it on the URL.+ ;; Any scheme matches, so a misspelt one, which DriverManager quotes, can't carry the credentials either.+ (if-let [[_ scheme userinfo more] (re-matches #"([^/]*//)([^/]*)@(.*)" base)]+ ;; decode %-escapes only, as libpq does: a `+` here is a literal plus, not a space as in a query string+ (let [decode #(url-decode (str/replace % "+" "%2B"))+ [user password] (str/split userinfo #":" 2)+ credentials (cond-> {:user (decode user)}+ password (assoc :password (decode password)))]+ [(str scheme more) credentials])+ [base {}]))++(defn- check-no-stray-at!+ "Throw if an `@` is left in `url` or `pairs` once the credentials are off, without quoting either."+ [^String url pairs]+ ;; An `@` left on `url` means a password with an unencoded `/`, or an `@` that pgjdbc requires encoded anyway.+ ;; An unencoded `?` in a password ends the host part early, before the `/` pgjdbc requires after a host, and+ ;; moves the `@` into `pairs`.+ ;; Any other `@` in `pairs` is a plain value that pgjdbc accepts, such as Azure's `user=name@server`.+ ;; Refuse a stray `@` before an error or the URL can quote the part of the password it may hold.+ (when (or (str/includes? url "@")+ (and (re-matches #"[^/]*//[^/]+" url)+ (some (fn [[k v]] (str/includes? (str k v) "@")) pairs)))+ (throw (ex-info (str "MB_PGVECTOR_DB_URL has an unencoded @ outside its credentials. "+ "Percent-encode reserved characters, e.g. @ as %40, / as %2F and ? as %3F.")+ {}))))+(defn- parse-db-url- "Parse a pgvector JDBC URL into {:jdbc-url ... :credentials ... :pool-props ...}, or throw if it carries an- unrecognized parameter."+ "Parse a pgvector JDBC URL into {:jdbc-url ... :credentials ... :pool-props ...}, or throw if it is+ malformed or carries an unrecognized parameter.+ Credentials come off the URL whether they're written as params or before the host."[^String url]- (let [[base pairs] (split-query url)- default-pool (merge fixed-pool-props- (update-vals tunable-pool-props first))+ (let [[base pairs] (split-query url)+ [base-url host-credentials] (split-userinfo base)+ _ (check-no-stray-at! base-url pairs)+ default-pool (merge fixed-pool-props+ (update-vals tunable-pool-props first)){:keys [pool conn credentials]}(reduce(fn [acc [k raw-v]](cond+ ;; also set before the host: Postgres clients disagree on which wins, so refuse to pick one+ (contains? host-credentials (keyword k))+ (throw (ex-info (format "The pgvector URL sets %s both before the host and as a parameter" k)+ {:param k}))+;; credentials: passed to pgjdbc as connection properties, off the URL, because the URL gets;; printed -- pgjdbc logs it at DEBUG on every connection, and DriverManager quotes it in its;; "No suitable driver" error@@ -144,9 +188,9 @@"(%s) or a Postgres connection property.")k (str/join ", " (sort (keys tunable-pool-props)))){:param k}))))- {:pool default-pool, :conn [], :credentials {}}+ {:pool default-pool, :conn [], :credentials host-credentials}pairs)]- {:jdbc-url (cond-> base (seq conn) (str "?" (str/join "&" conn)))+ {:jdbc-url (cond-> base-url (seq conn) (str "?" (str/join "&" conn))):credentials credentials:pool-props pool}))diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.cljindex 81d4ae26b54..4ea2aa893b5 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/db_test.clj@@ -108,6 +108,11 @@(def ^:private base-url "jdbc:postgresql://localhost:5432/mb_semantic_search")+(defn- userinfo-url+ "[[base-url]] with `userinfo` written before the host."+ [userinfo]+ (str "jdbc:postgresql://" userinfo "@localhost:5432/mb_semantic_search"))+(deftest probe-jdbc-url-test(testing "the probe URL fills in the fail-fast timeouts the one-shot datasource would otherwise lack";; db-url is a value, not a fn, so with-dynamic-fn-redefs can't bind it@@ -169,7 +174,32 @@:sslpassword "k3y@pass"}}(select-keys (parse-db-url (str base-url "?user=postgres&password=p%26ss%3Dword&tcpKeepAlive=true""&sslpassword=k3y%40pass"))- [:jdbc-url :credentials])))))+ [:jdbc-url :credentials]))))+ (testing "credentials in the host part come off the URL too, with %-escapes decoded and a `+` kept as is"+ (is (= {:jdbc-url (str base-url "?tcpKeepAlive=true")+ :credentials {:user "postgres", :password "p@ss:w+rd"}}+ (select-keys (parse-db-url (str (userinfo-url "postgres:p%40ss:w+rd") "?tcpKeepAlive=true"))+ [:jdbc-url :credentials]))))+ (testing "an unencoded `@` in a host-part password still leaves the whole password off the URL"+ (is (=? {:jdbc-url base-url, :credentials {:user "postgres", :password "p@ss"}}+ (parse-db-url (userinfo-url "postgres:p@ss")))))+ (testing "host-part credentials come off whatever the scheme, even one no driver accepts"+ ;; CI spells the scheme `jdbc:postgres:`, and `jdbc:postgresq:` is a typo DriverManager would quote+ (doseq [scheme ["jdbc:postgres://" "jdbc:postgresq://"]]+ (is (=? {:jdbc-url (str scheme "localhost:5432/mb_semantic_search")+ :credentials {:user "postgres", :password "secret"}}+ (parse-db-url (str scheme "postgres:secret@localhost:5432/mb_semantic_search"))))))+ (testing "a credential set both in the host part and in the query throws, without quoting either value"+ (let [e (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"The pgvector URL sets password both before the host and as a parameter"+ (parse-db-url (str (userinfo-url "postgres:secret") "?password=other"))))]+ (is (not (re-find #"secret|other" (str (ex-message e) (ex-data e)))))))+ (testing "an unencoded `@` in a query value passes through, as pgjdbc accepts it"+ (doseq [url [(str base-url "?user=mylogin@srv&password=p@ss")+ "jdbc:postgresql://?service=pgvector&user=mylogin@srv&password=p@ss"]]+ (is (=? {:credentials {:user "mylogin@srv", :password "p@ss"}}+ (parse-db-url url))))))(deftest parse-db-url-validation-test(testing "an unrecognized param throws rather than being silently ignored by pgjdbc"@@ -181,7 +211,23 @@(is (thrown-with-msg?clojure.lang.ExceptionInfo#"Invalid value for pgvector pool parameter maxPoolSize"- (parse-db-url (str base-url "?maxPoolSize=lots"))))))+ (parse-db-url (str base-url "?maxPoolSize=lots")))))+ (testing "an `@` outside the host part throws without quoting the URL"+ (doseq [url ["jdbc:postgresql://alice:se/cret@db/mb" ; `/` in the password+ "jdbc:postgresql://alice:se?cret@db/mb" ; `?` in the password+ "jdbc:postgresql://alice:se?service=cret@db/mb" ; `?`, putting the `@` in a param+ "jdbc:postgresql://alice:s@e?cret@db/mb" ; `@` and then `?` in the password+ "jdbc:postgresql://alice:secret@db/mb@elsewhere"]] ; `@` in the database name+ (let [e (is (thrown? clojure.lang.ExceptionInfo (parse-db-url url)))]+ (is (=? {:message (str "MB_PGVECTOR_DB_URL has an unencoded @ outside its credentials. "+ "Percent-encode reserved characters, e.g. @ as %40, / as %2F and ? as %3F.")+ :data {}}+ {:message (ex-message e), :data (ex-data e)}))+ (is (not (re-find #"cret|elsewhere" (str (ex-message e) (ex-data e))))))))+ (testing "a malformed %-escape in a credential throws without quoting any of the value"+ (let [e (is (thrown? clojure.lang.ExceptionInfo (parse-db-url (str base-url "?password=hunter%zz"))))]+ (is (=? {:message "Malformed %-escape in MB_PGVECTOR_DB_URL", :data {}, :cause nil}+ {:message (ex-message e), :data (ex-data e), :cause (ex-cause e)})))))(deftest pool-props-applied-by-c3p0-test(testing "c3p0 actually understands and applies every pool property name we set"