From 4bbc12e3b2f418576b3feaa2387c8ca165d4c62b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Guillot?= Date: Mon, 19 Aug 2024 20:12:42 -0700 Subject: [PATCH] fix: use root URL to generate absolute proxy URL When using `BASE_URL` with a subfolder, the root URL must be used to avoid base folder appearing twice in the generated URL. --- internal/mediaproxy/media_proxy_test.go | 17 +++++++++++++---- internal/mediaproxy/url.go | 4 ++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/internal/mediaproxy/media_proxy_test.go b/internal/mediaproxy/media_proxy_test.go index 8c544af6..27043194 100644 --- a/internal/mediaproxy/media_proxy_test.go +++ b/internal/mediaproxy/media_proxy_test.go @@ -182,7 +182,7 @@ func TestAbsoluteProxyFilterWithHttpsAlways(t *testing.T) { } } -func TestAbsoluteProxyFilterWithCustomPortInBaseURL(t *testing.T) { +func TestAbsoluteProxyFilterWithCustomPortAndSubfolderInBaseURL(t *testing.T) { os.Clearenv() os.Setenv("BASE_URL", "http://example.org:88/folder/") os.Setenv("MEDIA_PROXY_PRIVATE_KEY", "test") @@ -198,11 +198,20 @@ func TestAbsoluteProxyFilterWithCustomPortInBaseURL(t *testing.T) { t.Fatalf(`Unexpected base URL, got "%s"`, config.Opts.BaseURL()) } - r := mux.NewRouter() - r.HandleFunc("/proxy/{encodedDigest}/{encodedURL}", func(w http.ResponseWriter, r *http.Request) {}).Name("proxy") + if config.Opts.RootURL() != "http://example.org:88" { + t.Fatalf(`Unexpected root URL, got "%s"`, config.Opts.RootURL()) + } + + router := mux.NewRouter() + + if config.Opts.BasePath() != "" { + router = router.PathPrefix(config.Opts.BasePath()).Subrouter() + } + + router.HandleFunc("/proxy/{encodedDigest}/{encodedURL}", func(w http.ResponseWriter, r *http.Request) {}).Name("proxy") input := `

Test

` - output := RewriteDocumentWithAbsoluteProxyURL(r, input) + output := RewriteDocumentWithAbsoluteProxyURL(router, input) expected := `

Test

` if expected != output { diff --git a/internal/mediaproxy/url.go b/internal/mediaproxy/url.go index 6eb17989..2b9ded03 100644 --- a/internal/mediaproxy/url.go +++ b/internal/mediaproxy/url.go @@ -40,9 +40,9 @@ func ProxifyAbsoluteURL(router *mux.Router, mediaURL string) string { return proxifyURLWithCustomProxy(mediaURL, customProxyURL) } + // Note that the proxyified URL is relative to the root URL. proxifiedUrl := ProxifyRelativeURL(router, mediaURL) - - absoluteURL, err := url.JoinPath(config.Opts.BaseURL(), proxifiedUrl) + absoluteURL, err := url.JoinPath(config.Opts.RootURL(), proxifiedUrl) if err != nil { return mediaURL }