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
Answer conditional requests for static assets (#81937)
Romeo Van Snick4a913252130e
diff --git a/src/metabase/server/lib/etag_cache.clj b/src/metabase/server/lib/etag_cache.cljindex 4e03907e15e..b9ea9b2e8d0 100644--- a/src/metabase/server/lib/etag_cache.clj+++ b/src/metabase/server/lib/etag_cache.clj@@ -3,6 +3,7 @@(:require[clojure.string :as str][metabase.config.core :as config]+ [ring.util.io :as ring.io][ring.util.response :as response]))(set! *warn-on-reflection* true)@@ -12,8 +13,8 @@(format "W/\"%s\"" hash)(format "\"%s\"" hash)))-(defn- current-etag-header [weak?]- {"ETag" (format-etag config/mb-version-hash weak?)})+(defn- current-etag-header [etag weak?]+ {"ETag" (format-etag etag weak?)})(defn- parse-if-none-match [if-none-match](->> (some-> if-none-match (str/split #"\s*,\s*"))@@ -22,10 +23,10 @@(str/replace #"^\"|\"$" "")))set))-(defn- etag-matches? [if-none-match]+(defn- etag-matches? [if-none-match etag](let [normalized-if-none-match (some-> if-none-match str/trim)](or (= "*" normalized-if-none-match)- (contains? (parse-if-none-match normalized-if-none-match) config/mb-version-hash))))+ (contains? (parse-if-none-match normalized-if-none-match) etag))))(def ^:private cacheable-304-headers"Headers that a 304 response MUST echo from the corresponding 200 response@@ -42,13 +43,20 @@cacheable-304-headers))(defn with-etag- "Return 304 + ETag if If-None-Match matches; else 200 base + ETag."- [response request {weak? :weak?}]- (if (etag-matches? (get-in request [:headers "if-none-match"]))- (-> (response/response "")- (response/status 304)- (update :headers merge- (carry-over-304-headers response)- (current-etag-header weak?)))+ "Return 304 + ETag if If-None-Match matches; else 200 base + ETag.++ Validates against the running version's hash unless `:etag` names one. A caller+ that can identify a single representation should pass its own, so that the+ validator tracks the bytes rather than the build."+ [response request {weak? :weak?, etag :etag, :or {etag config/mb-version-hash}}]+ (if (etag-matches? (get-in request [:headers "if-none-match"]) etag)+ (do+ ;; the 304 carries no body, so the one we are dropping has to be released+ (ring.io/close! (:body response))+ (-> (response/response "")+ (response/status 304)+ (update :headers merge+ (carry-over-304-headers response)+ (current-etag-header etag weak?))))(-> response- (update :headers merge (current-etag-header weak?)))))+ (update :headers merge (current-etag-header etag weak?)))))diff --git a/src/metabase/server/routes/static.clj b/src/metabase/server/routes/static.cljindex 8aef804ea77..ac0cadfcd3b 100644--- a/src/metabase/server/routes/static.clj+++ b/src/metabase/server/routes/static.clj@@ -5,11 +5,17 @@instead of compressing on the fly. This avoids CPU overhead at request timeand lets us use higher compression levels during the build."(:require+ [buddy.core.codecs :as codecs]+ [buddy.core.hash :as buddy-hash]+ [clojure.java.io :as io][clojure.set :as set][clojure.string :as str][compojure.core :as compojure]+ [metabase.server.lib.etag-cache :as lib.etag-cache][ring.util.mime-type :as mime]- [ring.util.response :as response]))+ [ring.util.response :as response])+ (:import+ (java.io File)))(def ^:private encoding->extension{:gzip ".gz"@@ -68,6 +74,27 @@[resource-path encoding](str resource-path (encoding->extension encoding)))+(defn- sha256-hex [source]+ (with-open [stream (io/input-stream source)]+ (codecs/bytes->hex (buddy-hash/sha256 stream))))++(def ^:private jar-resource-hash+ "A resource inside the jar cannot change while the process runs, so each is hashed once."+ (memoize (fn [variant-path] (sha256-hex (io/resource variant-path)))))++(defn- content-hash+ "A hash of the bytes of one variant, which is the validator for that representation.++ Each encoding is a separate representation and so needs its own validator,+ which hashing the bytes we actually send gives us for free.++ A file on disk is hashed on every request. In dev a rebuild changes it under+ the running process, and a memoised hash would answer 304 for bytes that moved."+ [{body :body} variant-path]+ (if (instance? File body)+ (sha256-hex body)+ (jar-resource-hash variant-path)))+(defn- compressed-resource"Try to serve a pre-compressed variant of `resource-path`. Returns a Ringresponse map if a compressed variant exists and the client accepts it,@@ -76,10 +103,15 @@If encoding is :identity, we don't compress at all and serve the raw resource."[request resource-path encoding](when (accepts-encoding? request encoding)- (some-> (response/resource-response (compressed-path resource-path encoding))+ (let [variant-path (compressed-path resource-path encoding)]+ ;; `resource-response` returning a response is what proves the path resolves, so only+ ;; a real file is ever hashed or grows the memo.+ (when-let [resource (response/resource-response variant-path)]+ (-> resource(response/content-type (mime/ext-mime-type resource-path))(assoc-in [:headers "Content-Encoding"] (encoding->header encoding))- (assoc-in [:headers "Vary"] "Accept-Encoding"))))+ (assoc-in [:headers "Vary"] "Accept-Encoding")+ (assoc ::content-hash (content-hash resource variant-path)))))))(defn static-resource"Serve a static resource, preferring pre-compressed variants when available."@@ -91,12 +123,38 @@(defn- add-wildcard [path](str path (if (str/ends-with? path "/") "*" "/*")))+(defn- wrap-etag-validation+ "Answers a 304 for a client whose `If-None-Match` names the bytes we would send.++ The validator is the content hash and is compared for equality, so the answer+ holds however the versions move. `If-Modified-Since` is deliberately not+ consulted: it is compared as an ordered date, which also answers 304 when the+ client holds a copy newer than the file on disk, and a downgraded instance+ serves exactly that. The `Last-Modified` header stays on the response because+ dropping it makes the security middleware substitute the time of the response."+ [handler]+ (letfn [(answer [response request]+ (if-let [etag (::content-hash response)]+ (lib.etag-cache/with-etag response request {:etag etag})+ response))]+ (fn+ ([request]+ (answer (handler request) request))+ ([request respond raise]+ (handler request (fn [response] (respond (answer response request))) raise)))))+(defn precompressed-resources"A Ring handler that serves classpath resources from `root`, preferringpre-compressed (.br, .gz) variants when the client supports them.- Drop-in replacement for `compojure.route/resources`."+ Drop-in replacement for `compojure.route/resources`.++ A resource the client already holds is answered with a 304 rather than its+ whole body. Everything under `/app` that carries no content hash is served+ `no-cache, must-revalidate`, which obliges the client to ask every time;+ without this it has to be sent the file every time as well."[path {root :root}]- (compojure/GET (add-wildcard path) request- (let [{{request-path :*} :route-params} request- resource-path (str root "/" request-path)]- (static-resource request resource-path))))+ (wrap-etag-validation+ (compojure/GET (add-wildcard path) request+ (let [{{request-path :*} :route-params} request+ resource-path (str root "/" request-path)]+ (static-resource request resource-path)))))diff --git a/test/metabase/server/routes/static_test.clj b/test/metabase/server/routes/static_test.cljindex afa4cb30e3d..fc7a5f9a43e 100644--- a/test/metabase/server/routes/static_test.clj+++ b/test/metabase/server/routes/static_test.clj@@ -1,8 +1,11 @@(ns metabase.server.routes.static-test(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.server.routes.static :as static]))+(set! *warn-on-reflection* true)+(deftest ^:parallel parse-accept-encoding-nil-header-test(testing "nil header returns identity-only defaults"(is (= {:identity 1.0 :* 0.0}@@ -118,3 +121,77 @@(request-with-encoding "gzip, br")"static_test/app.js")](is (= "Accept-Encoding" (get-in response [:headers "Vary"]))))))++(def ^:private static-handler+ (static/precompressed-resources "/" {:root "frontend_client"}))++(defn- get-static+ ([path] (get-static path nil))+ ([path validators]+ (static-handler {:request-method :get+ :uri path+ :route-params {:* (subs path 1)}+ :headers (or validators {})})))++(defn- etag-of [path]+ (get-in (get-static path) [:headers "ETag"]))++(deftest ^:parallel static-resource-reports-its-own-last-modified-test+ (testing "a static resource carries the time it was modified, not the time it was served"+ (let [response (get-static "/index_template.html")]+ (is (= 200 (:status response)))+ (is (some? (get-in response [:headers "Last-Modified"]))))))++(deftest ^:parallel static-resource-carries-a-strong-content-etag-test+ (testing "a static resource is validated by a strong hash of its bytes"+ (is (re-matches #"\"[0-9a-f]{64}\"" (etag-of "/index_template.html")))))++(deftest ^:parallel static-resource-answers-conditional-request-test+ (testing "a client that already holds the resource is answered without the body"+ (let [response (get-static "/index_template.html"+ {"if-none-match" (etag-of "/index_template.html")})]+ (is (= 304 (:status response)))+ (is (str/blank? (:body response)))))+ (testing "a client holding different bytes is sent the resource"+ (let [response (get-static "/index_template.html" {"if-none-match" "\"not-the-one\""})]+ (is (= 200 (:status response)))+ (is (some? (:body response))))))++(deftest ^:parallel static-resource-never-validates-on-a-date-test+ (testing "a date validator alone is never enough for a 304, whichever way it points"+ (doseq [held ["Tue, 03 Jul 2001 06:00:00 GMT"+ "Fri, 01 Jan 2100 00:00:00 GMT"+ (get-in (get-static "/index_template.html") [:headers "Last-Modified"])]]+ (testing (str "if-modified-since " held)+ (let [response (get-static "/index_template.html" {"if-modified-since" held})]+ (is (= 200 (:status response)))+ (is (some? (:body response))))))))++(deftest ^:parallel each-encoding-is-validated-separately-test+ (testing "every encoding is its own representation, so each carries its own validator"+ (let [gzipped (static/static-resource (request-with-encoding "gzip") "static_test/app.js")+ plain (static/static-resource {} "static_test/app.js")]+ (is (= "gzip" (get-in gzipped [:headers "Content-Encoding"])))+ (is (re-matches #"[0-9a-f]{64}" (::static/content-hash plain)))+ (is (not= (::static/content-hash gzipped)+ (::static/content-hash plain))))))++(deftest ^:parallel file-on-disk-is-hashed-on-every-request-test+ (testing "a file on disk can change under a running dev process, so its hash is never memoised"+ (let [file (doto (java.io.File/createTempFile "static-test" ".js") .deleteOnExit)+ hash #(#'static/content-hash {:body file} "static_test/app.js")]+ (spit file "one")+ (let [before (hash)]+ (spit file "two")+ (is (not= before (hash)))))))++(deftest ^:parallel not-modified-carries-only-cache-headers-test+ (testing "a 304 echoes the headers that guide a cache and drops the metadata of a body it has no room for"+ (let [served (get-static "/index_template.html")+ response (get-static "/index_template.html"+ {"if-none-match" (get-in served [:headers "ETag"])})]+ (is (= 304 (:status response)))+ (is (some? (get-in response [:headers "ETag"])))+ (doseq [header ["Content-Type" "Content-Encoding" "Content-Length"]]+ (testing header+ (is (nil? (get-in response [:headers header]))))))))diff --git a/test/metabase/server/routes_test.clj b/test/metabase/server/routes_test.cljindex a82ece867b3..832707f7198 100644--- a/test/metabase/server/routes_test.clj+++ b/test/metabase/server/routes_test.clj@@ -66,3 +66,60 @@(testing "without the feature it still falls through, so the instance reveals nothing about data apps"(mt/with-premium-features #{}(is (nil? (serve-data-app {:uri "/embed/apps/sales"})))))))++(def ^:private static-asset-path+ "A checked-in asset under `/app` that carries no content hash, so it is served+ `no-cache, must-revalidate` and has to be revalidated on every load."+ "app/assets/img/browserconfig.xml")++(defn- body-text+ "The response body as text. A static resource is served as a `File` from a source+ checkout and as an `InputStream` from a jar, and is absent altogether on a 304."+ [body]+ (cond+ (nil? body) ""+ (string? body) body+ :else (slurp body)))++(defn- get-static-asset+ "Fetches a file under `/app` through the real server, so the security middleware,+ gzip and the validator handling all take part."+ ([] (get-static-asset 200 nil))+ ([expected-status validators]+ (binding [client/*url-prefix* ""]+ (client/client-full-response+ :get expected-status static-asset-path+ {:request-options {:headers (or validators {})}}))))++(deftest static-asset-revalidation-test+ (testing "an unhashed static asset is revalidated rather than cached outright"+ (let [response (get-static-asset)]+ (is (= "max-age=0, no-cache, must-revalidate, proxy-revalidate"+ (get-in response [:headers "Cache-Control"])))+ (testing "and is validated by a strong hash of its bytes"+ (let [etag (get-in response [:headers "ETag"])]+ (is (re-matches #"\"[0-9a-f]{64}\"" etag))+ (testing "which are the bytes on the wire: the gzip middleware leaves a body with a Content-Encoding alone"+ (is (= "identity" (get-in response [:headers "Content-Encoding"]))))+ (testing "so a client that already holds it gets a body-less 304"+ (let [not-modified (get-static-asset 304 {"if-none-match" etag})]+ (is (= 304 (:status not-modified)))+ (is (str/blank? (body-text (:body not-modified))))+ (testing "carrying the validator and the directives a cache needs"+ (is (= etag (get-in not-modified [:headers "ETag"])))+ (is (= "max-age=0, no-cache, must-revalidate, proxy-revalidate"+ (get-in not-modified [:headers "Cache-Control"]))))))+ (testing "while a client holding different bytes is sent the file"+ (let [stale (get-static-asset 200 {"if-none-match" "\"not-the-one\""})]+ (is (= 200 (:status stale)))+ (is (not (str/blank? (body-text (:body stale))))))))))))++(deftest static-asset-is-never-validated-by-date-test+ (testing "a date validator alone never produces a 304, so a downgrade replaces the client's copy"+ (let [served (get-in (get-static-asset) [:headers "Last-Modified"])]+ (is (some? served) "the header stays on the response")+ (doseq [held [served "Fri, 01 Jan 2100 00:00:00 GMT"]]+ (testing (str "if-modified-since " held)+ (let [response (get-static-asset 200 {"if-modified-since" held})]+ (is (= 200 (:status response)))+ (is (not (str/blank? (body-text (:body response)))))))))))