Skip to content

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

Improve geojson and http requests (#80111)

Nathan Voxlanddbe9a0acc14a
diff --git a/deps.edn b/deps.edn
index 55e6b5b0b33..32f3061e115 100644
--- a/deps.edn
+++ b/deps.edn
@@ -350,7 +350,6 @@
:exec-fn metabase.test-runner/find-and-run-tests-cli
:exec-args {}
:jvm-opts ["-Dmb.run.mode=test"
- "-Dmb.warehouse.allowed.networks=allow-all"
"-Dmacaw.run.mode=test"
"-Dmb.db.in.memory=true"
"-Dmb.jetty.join=false"
diff --git a/src/metabase/channel/impl/http.clj b/src/metabase/channel/impl/http.clj
index 1bb876e9c3e..c2a940b587c 100644
--- a/src/metabase/channel/impl/http.clj
+++ b/src/metabase/channel/impl/http.clj
@@ -1,6 +1,7 @@
(ns metabase.channel.impl.http
(:require
[clj-http.client :as http]
+ [clojure.java.io :as io]
[clojure.string :as str]
[java-time.api :as t]
[metabase.channel.core :as channel]
@@ -9,6 +10,7 @@
[metabase.channel.shared :as channel.shared]
[metabase.channel.urls :as urls]
[metabase.util :as u]
+ [metabase.util.http :as u.http]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.malli :as mu]
@@ -36,37 +38,43 @@
[:details HTTPDetails]])
(defn- check-url!
- [url]
+ [strategy url]
(when (str/blank? url)
(throw (ex-info (tru "No URL is configured for this webhook.") {:status-code 400})))
- (when-not (try
- (u/valid-host? (channel.settings/http-channel-host-strategy) url)
+ (let [url (try
+ (io/as-url url)
(catch Exception e
(throw (ex-info (tru "Invalid webhook URL: {0}" (ex-message e))
{:status-code 400
:url url}
- e))))
- (throw (ex-info (tru "URLs referring to hosts that supply internal hosting metadata are prohibited.")
- {:status-code 400}))))
+ e))))]
+ (when-not (u.http/host-allowed-for-network-policy? strategy url)
+ (throw (ex-info (tru "URLs referring to hosts that supply internal hosting metadata are prohibited.")
+ {:status-code 400})))))
(mu/defmethod channel/send! :channel/http
[{{:keys [url method auth-method auth-info]} :details} :- HTTPChannel
request]
- (check-url! url)
- (let [req (merge
- {:accept :json
- :content-type :json
- :method :post
- :url url}
- (when method
- {:method (keyword method)})
- (cond-> request
- (= "request-body" auth-method) (update :body merge auth-info)
- (= "header" auth-method) (update :headers merge auth-info)
- (= "query-param" auth-method) (update :query-params merge auth-info)))]
- (http/request (cond-> req
- (or (map? (:body req))
- (sequential? (:body req))) (update :body json/encode)))))
+ (let [strategy (channel.settings/http-channel-host-strategy)
+ resolver (u.http/network-policy-dns-resolver strategy)]
+ (check-url! strategy url)
+ (let [req (-> (merge
+ {:accept :json
+ :content-type :json
+ :method :post}
+ (when method
+ {:method (keyword method)})
+ (cond-> request
+ (= "request-body" auth-method) (update :body merge auth-info)
+ (= "header" auth-method) (update :headers merge auth-info)
+ (= "query-param" auth-method) (update :query-params merge auth-info)))
+ (assoc :url url)
+ ;; Remove an incoming resolver under :allow-all; rendered requests must not control
+ ;; DNS resolution.
+ (u/assoc-dissoc :dns-resolver resolver))]
+ (http/request (cond-> req
+ (or (map? (:body req))
+ (sequential? (:body req))) (update :body json/encode))))))
(defn- maybe-parse-json
[x]
diff --git a/src/metabase/geojson/api.clj b/src/metabase/geojson/api.clj
index 35c3aab2b72..2fd5c22ef7b 100644
--- a/src/metabase/geojson/api.clj
+++ b/src/metabase/geojson/api.clj
@@ -8,6 +8,7 @@
[metabase.geojson.settings :as geojson.settings]
[metabase.permissions.core :as perms]
[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]
@@ -16,27 +17,12 @@
[ring.util.response :as response])
(:import
(java.io BufferedReader)
- (java.net InetAddress)
- (org.apache.commons.io.input ReaderInputStream)
- (org.apache.http.conn DnsResolver)
- (org.apache.http.impl.conn SystemDefaultDnsResolver)))
+ (org.apache.commons.io.input ReaderInputStream)))
(set! *warn-on-reflection* true)
(def ^:private connection-timeout-ms 8000)
-(def ^DnsResolver ^:private ^:dynamic *system-dns-resolver* (SystemDefaultDnsResolver.))
-
-(def ^:private non-link-local-dns-resolver
- (reify
- DnsResolver
- (^"[Ljava.net.InetAddress;" resolve [_ ^String host]
- (let [addresses (.resolve *system-dns-resolver* host)]
- (if (some #(.isLinkLocalAddress ^InetAddress %) addresses)
- (throw (ex-info (geojson.settings/invalid-location-msg) {:status-code 400
- :link-local true}))
- addresses)))))
-
(defn- url->geojson
[url]
(let [resp (try (http/get url {:as :reader
@@ -44,10 +30,10 @@
:socket-timeout connection-timeout-ms
:connection-timeout connection-timeout-ms
:throw-exceptions false
- :dns-resolver non-link-local-dns-resolver})
+ :dns-resolver (u.http/network-policy-dns-resolver :external-only)})
(catch Throwable e
- (if (:link-local (ex-data e))
- (throw (ex-info (ex-message e) (dissoc (ex-data e) :link-local) e))
+ (if (:ssrf (ex-data e))
+ (throw (ex-info (geojson.settings/invalid-location-msg) {:status-code 400} e))
(throw (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))))
;; only 2xx is a real success — a 3xx redirect isn't followed (`:redirect-strategy :none`, for SSRF
;; protection), so its (empty) body must be treated as a failed load rather than streamed as GeoJSON.
diff --git a/src/metabase/geojson/settings.clj b/src/metabase/geojson/settings.clj
index f9f4c2a9de8..24ac7a01461 100644
--- a/src/metabase/geojson/settings.clj
+++ b/src/metabase/geojson/settings.clj
@@ -73,12 +73,23 @@
[^URL url]
(#{"http" "https"} (.getProtocol url)))
+(defn- external-host?
+ "True only when `url`'s host resolves and *every* resolved address is a public, externally-routable
+ unicast address (see [[metabase.util.http/address-allowed-for-network-policy?]]). Unlike
+ [[metabase.util.http/host-allowed-for-network-policy?]] this rejects a host that does not resolve,
+ matching geojson's stricter set-time validation -- a bad URL should fail to save.
+ The fetch itself will still re-check the security at each request to handle changes in settings."
+ [^URL url]
+ (boolean
+ (when-let [addrs (http/host->inet-addresses (.getHost url))]
+ (every? #(http/address-allowed-for-network-policy? :external-only %) addrs))))
+
(defn- valid-url?
[url-string]
(try
(let [url (.toURL (URI. url-string))]
(and (valid-protocol? url)
- (http/valid-host? :external-only url)))
+ (external-host? url)))
(catch Throwable _ false)))
(defn valid-geojson-resource-path?
diff --git a/src/metabase/sso/oidc/discovery.clj b/src/metabase/sso/oidc/discovery.clj
index 43400f5b3d2..08854872524 100644
--- a/src/metabase/sso/oidc/discovery.clj
+++ b/src/metabase/sso/oidc/discovery.clj
@@ -109,7 +109,7 @@
[config discovery-key manual-key]
(when-let [url (or (get-in config [:discovery-document discovery-key])
(get config manual-key))]
- (when-not (u.http/valid-host? (sso.settings/oidc-allowed-networks) url)
+ (when-not (u.http/host-allowed-for-network-policy? (sso.settings/oidc-allowed-networks) url)
(throw (ex-info "OIDC endpoint blocked: address not allowed by network restrictions"
{:url url :endpoint-key discovery-key})))
url))
diff --git a/src/metabase/sso/oidc/http.clj b/src/metabase/sso/oidc/http.clj
index d5be7d851aa..c65d8ad3b0c 100644
--- a/src/metabase/sso/oidc/http.clj
+++ b/src/metabase/sso/oidc/http.clj
@@ -21,12 +21,21 @@
"Validate that a URL is allowed by the current `oidc-allowed-networks` setting.
Throws `ex-info` if the URL is blocked."
[url]
- (when-not (u.http/valid-host? (sso.settings/oidc-allowed-networks) url)
+ (when-not (u.http/host-allowed-for-network-policy? (sso.settings/oidc-allowed-networks) url)
(log/warnf "OIDC request to %s blocked by network restrictions (oidc-allowed-networks = %s)"
url (sso.settings/oidc-allowed-networks))
(throw (ex-info "OIDC request blocked: address not allowed by network restrictions"
{:url url}))))
+(defn- request-opts
+ "Merge caller `opts` over the defaults, adding the connection-time SSRF `:dns-resolver` for the current
+ `oidc-allowed-networks` policy so a host that rebinds to an internal address between validation and
+ connection is still rejected. Omitted for `:allow-all`, which imposes no restriction."
+ [opts]
+ (let [resolver (u.http/network-policy-dns-resolver (sso.settings/oidc-allowed-networks))]
+ (cond-> (merge default-opts opts)
+ resolver (assoc :dns-resolver resolver))))
+
(defn oidc-get
"Perform a validated GET request for OIDC operations.
Validates the URL against `oidc-allowed-networks` before making the request."
@@ -34,7 +43,7 @@
(oidc-get url {}))
([url opts]
(validate-url! url)
- (http/get url (merge default-opts opts))))
+ (http/get url (request-opts opts))))
(defn oidc-post
"Perform a validated POST request for OIDC operations.
@@ -43,4 +52,4 @@
(oidc-post url {}))
([url opts]
(validate-url! url)
- (http/post url (merge default-opts opts))))
+ (http/post url (request-opts opts))))
diff --git a/src/metabase/util.cljc b/src/metabase/util.cljc
index 896c1236e9a..26b4ff99a20 100644
--- a/src/metabase/util.cljc
+++ b/src/metabase/util.cljc
@@ -10,7 +10,6 @@
[clojure.pprint :as pprint]
^{:clj-kondo/ignore [:discouraged-namespace]}
[metabase.util.jvm :as u.jvm]
- [metabase.util.http :as u.http]
[metabase.util.string :as u.str]
[potemkin :as p]
[puget.printer]
@@ -83,9 +82,7 @@
with-timeout
with-us-locale]
[u.str
- build-sentence]
- [u.http
- valid-host?]))
+ build-sentence]))
(defmacro or-with
"Like or, but determines truthiness with `pred`."
diff --git a/src/metabase/util/http.clj b/src/metabase/util/http.clj
index 6b24a7c4952..c66e0abab61 100644
--- a/src/metabase/util/http.clj
+++ b/src/metabase/util/http.clj
@@ -29,29 +29,6 @@
response (http/get url (m/assoc-some {:as :json} :headers headers))]
(:body response)))
-(def ^:private invalid-hosts
- #{"metadata.google.internal"}) ; internal metadata for GCP
-
-(defn valid-host?
- "Check whether url is valid based on the given strategy:
- :external-only - only external hosts
- :allow-private - external + private networks but not localhost/loopback
- :allow-all - no restrictions"
- [strategy url]
- (case strategy
- :allow-all true
- ;; For both :external-only and :allow-private, we need to check the host
- (let [^URL url (if (string? url) (URL. url) url)
- host (.getHost url)
- host-name (InetAddress/getByName host)]
- (and
- (not (contains? invalid-hosts host))
- (not (.isLinkLocalAddress host-name))
- (not (.isLoopbackAddress host-name))
- ;; Only block site-local (private) addresses for :external-only
- (or (= strategy :allow-private)
- (not (.isSiteLocalAddress host-name)))))))
-
;; --------------------------------------------------------------------------------------------
;; SSRF-hardened fetch of an untrusted (user-provided) URL.
;;
@@ -64,14 +41,6 @@
;; - No redirects (a 3xx would be a bypass vector; here it just fails).
;; - No cookies/credentials (a fresh clj-http GET carries no Metabase session).
;; - Cap the download bytes and (optionally) restrict to an allowlist of content-types.
-;;
-;; TODO (bshepherdson 2026-06-09) -- this hardened fetch (rebinding-safe [[ssrf-safe-dns-resolver]]
-;; + [[public-address?]] + size/content-type caps) supersedes the weaker [[valid-host?]] above,
-;; which validates only a single up-front DNS resolution (a TOCTOU/DNS-rebinding gap) and misses
-;; IPv6 ULA, IPv4 CGNAT, any-local, multicast, and IP-literal hosts. Migrate the existing
-;; `valid-host?` callers -- `metabase.geojson`, `metabase.sso.oidc.http`,
-;; `metabase.channel.impl.http` -- onto this, and add SSRF validation to
-;; `metabase.actions.http-action` (which currently has none).
;; --------------------------------------------------------------------------------------------
(def ^:private fetch-default-timeout-ms 8000)
@@ -158,7 +127,7 @@
(boolean (when-let [host (not-empty (str/trim (str host)))]
(InetAddresses/isInetAddress (str/replace host #"^\[|\]$" "")))))
-(defn- host->inet-addresses
+(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]
@@ -184,17 +153,31 @@
(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.
- Used as clj-http's `:dns-resolver` so the check runs inside the connection actually opened,
- closing the DNS-rebinding TOCTOU gap (validating up front then re-resolving would not)."
- (let [system (SystemDefaultDnsResolver.)]
+(def ^DnsResolver ^:dynamic *system-dns-resolver*
+ "The underlying system DNS resolver. Exposed as a dynamic var so tests can inject a fake
+ host->address mapping"
+ (SystemDefaultDnsResolver.))
+
+(defn network-policy-dns-resolver
+ "A clj-http `:dns-resolver` that resolves `host` normally but throws unless *every* resolved address is
+ permitted by `policy`.
+
+ Returns nil for `:allow-all`, which restricts nothing: callers should omit `:dns-resolver` in that case
+ and let clj-http use its default resolver."
+ ^DnsResolver [policy]
+ (when-not (= policy :allow-all)
(reify DnsResolver
(^"[Ljava.net.InetAddress;" resolve [_ ^String host]
- (let [addrs (.resolve system host)]
- (if (every? public-address? addrs)
+ (let [addrs (.resolve *system-dns-resolver* host)]
+ (if (every? #(address-allowed-for-network-policy? policy %) addrs)
addrs
- (throw (ex-info "Refusing to fetch from a non-public address" {:ssrf true}))))))))
+ (throw (ex-info "Refusing to connect to a non-permitted network address"
+ {:ssrf true :policy policy :host host}))))))))
+
+(def ^DnsResolver ^:private ssrf-safe-dns-resolver
+ "The strict `:external-only` resolver (public addresses only) used by [[fetch-bytes]].
+ See [[network-policy-dns-resolver]]."
+ (network-policy-dns-resolver :external-only))
(defn safe-url?
"True if `url` is safe to fetch from untrusted input: HTTPS scheme, no userinfo, and a real DNS
diff --git a/test/metabase/channel/impl/http_test.clj b/test/metabase/channel/impl/http_test.clj
index 37151528491..44cc372fa27 100644
--- a/test/metabase/channel/impl/http_test.clj
+++ b/test/metabase/channel/impl/http_test.clj
@@ -344,6 +344,41 @@
:details {:url "not-a-url" :auth-method "none"}}
nil)))))))
+(deftest send!-rejects-any-local-ula-cgnat-test
+ (testing "under :external-only, hosts the old valid-host? let through -- any-local (0.0.0.0 / [::]),
+ IPv6 ULA, IPv4 CGNAT -- are rejected up front"
+ (mt/with-temporary-setting-values [http-channel-host-strategy :external-only]
+ (doseq [host ["0.0.0.0" "[::]" "[fc00::1]" "100.64.0.1"]]
+ (testing host
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo #"internal hosting metadata are prohibited"
+ (channel/send! {:type :channel/http
+ :details {:url (str "http://" host ":80/") :auth-method "none"}}
+ {}))))))))
+
+(deftest send!-attaches-dns-resolver-test
+ (testing "a connection-time SSRF :dns-resolver is attached for restrictive policies, but not for :allow-all"
+ ;; 8.8.8.8 is a public IP literal, so the up-front check needs no DNS lookup
+ (doseq [[strategy resolver?] [[:allow-all false]
+ [:allow-private true]
+ [:external-only true]]]
+ (with-captured-http-requests [requests]
+ (mt/with-temporary-setting-values [http-channel-host-strategy strategy]
+ (channel/send! {:type :channel/http
+ :details {:url "https://8.8.8.8"
+ :auth-method "none"
+ :method "get"}}
+ {:url "http://127.0.0.1/"
+ :dns-resolver ::caller-supplied}))
+ ;; unrelated background http/request calls can land in the atom too (Clojure conveys the
+ ;; `binding` into async tasks), so pick out our request by URL rather than assuming it is first
+ (let [req (first (filter #(= "https://8.8.8.8" (:url %)) @requests))]
+ (is (some? req) "the rendered request cannot override the configured webhook URL")
+ (is (= resolver? (some? (:dns-resolver req)))
+ (str strategy " controls whether the policy DNS resolver is present"))
+ (is (not= ::caller-supplied (:dns-resolver req))
+ "the rendered request cannot override the policy DNS resolver"))))))
+
(deftest alert-http-channel-e2e-test
(mt/with-temporary-setting-values [http-channel-host-strategy :allow-all]
(let [received-message (atom nil)
diff --git a/test/metabase/geojson/api_test.clj b/test/metabase/geojson/api_test.clj
index 0a819a966a1..88b13227e07 100644
--- a/test/metabase/geojson/api_test.clj
+++ b/test/metabase/geojson/api_test.clj
@@ -8,6 +8,7 @@
[metabase.test :as mt]
[metabase.test.http-client :as client]
[metabase.util :as u]
+ [metabase.util.http :as u.http]
[ring.adapter.jetty :as ring-jetty])
(:import
(java.net InetAddress)
@@ -154,19 +155,20 @@
(-port [_] (.. server getURI getPort)))))
(deftest url-proxy-endpoint-non-responding-server-test
- (testing "error is returned if URL server never responds (#28752)"
+ (testing "a loopback URL is refused by the connection-time SSRF resolver, returning a good error
+ immediately instead of hanging on a server that accepts a connection but never responds"
(with-redefs [api.geojson/connection-timeout-ms 200]
- ;; use a webserver which accepts a connection and never responds. The geojson endpoint opens a reader to the url
- ;; and responds with it. And if there are never any bytes going across, the whole thing just sits there. Our
- ;; test flakes after 45 seconds with `mt/user-http-request` times out. And presumably other clients have similar
- ;; issues. This ensures we give a good error message in this case.
+ ;; a webserver which accepts a connection and never responds -- the case that used to hang for 45s.
+ ;; We never even connect now: `localhost` resolves to loopback, which the resolver refuses.
(with-open [server (non-responding-server)]
+ ;; bypass the up-front check so we exercise the connection-time resolver specifically
(mt/with-dynamic-fn-redefs [geojson.settings/valid-geojson-url? (constantly true)]
(let [never-responds-url (str "http://localhost:" (-port server))]
- (testing "error is returned if URL connection fails"
- (is (= "GeoJSON URL failed to load"
- (mt/user-http-request :crowberto :get 400 "geojson"
- :url never-responds-url))))))))))
+ (is (= (str "Invalid GeoJSON file location: must start with http:// or https://. "
+ "URLs referring to hosts that supply internal hosting metadata are "
+ "prohibited.")
+ (mt/user-http-request :crowberto :get 400 "geojson"
+ :url never-responds-url)))))))))
(deftest key-proxy-endpoint-test
(with-geojson-mocks
@@ -225,13 +227,24 @@
(is (= "Invalid custom GeoJSON key: us_states"
(mt/user-real-request :crowberto :get 400 "geojson/us_states"))))))
-(deftest resolver-disallows-link-local-geojson-attack
- (testing "Should block link local dns resolution"
- (binding [api.geojson/*system-dns-resolver* (doto (InMemoryDnsResolver.)
- (.add "metabase.com"
- (into-array [(InetAddress/getByAddress (byte-array [1 1 1 1]))
- (InetAddress/getByAddress (byte-array [169 254 169 254]))])))]
+(deftest resolver-disallows-non-public-geojson-attack
+ (testing "the connection-time resolver blocks a host that resolves to a non-public address at connect
+ time even though it passed the up-front check (DNS rebinding / multiple A records)"
+ (binding [u.http/*system-dns-resolver* (doto (InMemoryDnsResolver.)
+ (.add "metabase.com"
+ (into-array [(InetAddress/getByAddress (byte-array [1 1 1 1]))
+ (InetAddress/getByAddress (byte-array [169 254 169 254]))])))]
(is (= (str "Invalid GeoJSON file location: must start with http:// or https://. "
"URLs referring to hosts that supply internal hosting metadata are "
"prohibited.")
(mt/user-http-request :crowberto :get 400 "geojson" :url test-geojson-url))))))
+
+(deftest url-proxy-rejects-any-local-ula-cgnat-test
+ (testing "hosts the old valid-host? let through -- any-local (0.0.0.0 / [::]), IPv6 ULA, IPv4 CGNAT --
+ are rejected up front, before any fetch"
+ (doseq [host ["0.0.0.0" "[::]" "100.64.0.1" "[fc00::1]"]]
+ (testing host
+ (is (= (str "Invalid GeoJSON file location: must start with http:// or https://. "
+ "URLs referring to hosts that supply internal hosting metadata are "
+ "prohibited.")
+ (mt/user-http-request :crowberto :get 400 "geojson" :url (str "http://" host "/x.json"))))))))
diff --git a/test/metabase/geojson/settings_test.clj b/test/metabase/geojson/settings_test.clj
index 5f7a02461fb..bdfee4ccd5b 100644
--- a/test/metabase/geojson/settings_test.clj
+++ b/test/metabase/geojson/settings_test.clj
@@ -49,6 +49,10 @@
"http://fe80::" false
"169.254.169.254" false
"http://169.254.169.254/secret-stuff.json" false
+ "http://0.0.0.0" false
+ "http://[::]" false
+ "http://100.64.0.1" false
+ "http://[fc00::1]" false
;; alternate IPv4 encodings (hex, octal, integer)
"http://0xa9fea9fe" false
"https://0xa9fea9fe" false
diff --git a/test/metabase/util/http_test.clj b/test/metabase/util/http_test.clj
index b6317524b16..af4b2904dd2 100644
--- a/test/metabase/util/http_test.clj
+++ b/test/metabase/util/http_test.clj
@@ -5,33 +5,12 @@
(:import
(clojure.lang ExceptionInfo)
(java.io ByteArrayInputStream)
- (java.net InetAddress)))
+ (java.net InetAddress)
+ (org.apache.http.conn DnsResolver)
+ (org.apache.http.impl.conn InMemoryDnsResolver)))
(set! *warn-on-reflection* true)
-(deftest valid-host?-test
- (testing "external-only strategy (default)"
- (is (true? (http/valid-host? :external-only "https://example.com")))
- (is (false? (http/valid-host? :external-only "http://localhost")))
- (is (false? (http/valid-host? :external-only "http://192.168.1.1"))))
- (testing "external-only strategy explicitly"
- (is (true? (http/valid-host? :external-only "https://example.com")))
- (is (false? (http/valid-host? :external-only "http://localhost")))
- (is (false? (http/valid-host? :external-only "http://192.168.1.1"))))
- (testing "allow-private strategy allows private networks but not localhost"
- (is (true? (http/valid-host? :allow-private "https://example.com")))
- (is (true? (http/valid-host? :allow-private "http://192.168.1.1")))
- (is (true? (http/valid-host? :allow-private "http://10.0.0.1")))
- (is (true? (http/valid-host? :allow-private "http://172.16.0.1")))
- (is (false? (http/valid-host? :allow-private "http://localhost")))
- (is (false? (http/valid-host? :allow-private "http://127.0.0.1")))
- (is (false? (http/valid-host? :allow-private "http://169.254.1.1"))))
- (testing "allow-all strategy allows everything"
- (is (true? (http/valid-host? :allow-all "https://example.com")))
- (is (true? (http/valid-host? :allow-all "http://localhost")))
- (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))
@@ -219,7 +198,26 @@
(testing "the validating resolver throws when a host resolves to a non-public address"
;; `localhost` resolves to loopback (no network needed) -> must be refused
(is (thrown? ExceptionInfo
- (.resolve ^org.apache.http.conn.DnsResolver @#'http/ssrf-safe-dns-resolver "localhost")))))
+ (.resolve ^DnsResolver @#'http/ssrf-safe-dns-resolver "localhost")))))
+
+(deftest ^:parallel network-policy-dns-resolver-test
+ (testing ":allow-all imposes no restriction, so there is no resolver (clj-http uses its default)"
+ (is (nil? (http/network-policy-dns-resolver :allow-all))))
+ (testing "the resolver refuses a host that resolves to a disallowed address"
+ ;; `localhost` resolves to loopback with no network IO; loopback is denied by both policies
+ (doseq [policy [:external-only :allow-private]]
+ (is (thrown-with-msg? ExceptionInfo #"non-permitted"
+ (.resolve ^DnsResolver (http/network-policy-dns-resolver policy) "localhost"))
+ (str policy))))
+ (testing "the resolver honors the policy: an injected private address passes :allow-private but not :external-only,
+ closing the DNS-rebinding gap that up-front-only validation leaves open"
+ (binding [http/*system-dns-resolver* (doto (InMemoryDnsResolver.)
+ (.add "rebind.example"
+ (into-array [(InetAddress/getByName "10.0.0.1")])))]
+ (is (thrown-with-msg? ExceptionInfo #"non-permitted"
+ (.resolve ^DnsResolver (http/network-policy-dns-resolver :external-only) "rebind.example")))
+ (is (= 1 (alength ^"[Ljava.net.InetAddress;"
+ (.resolve ^DnsResolver (http/network-policy-dns-resolver :allow-private) "rebind.example")))))))
(deftest ^:parallel fetch-bytes-blocks-without-network-test
(testing "blocked URLs return nil at the validation gate, never reaching the network"