Преглед изворни кода

fix(ui): force download for non-media types in the media proxy

The media proxy forwarded the upstream Content-Type and always marked
the response as inline. Any URL placed in an <img> tag of a feed gets
a signed proxy link that never expires, so an HTML page could be
shared and rendered from the instance's own domain. The sandbox CSP
blocks scripts and forms, but static phishing pages were still
possible.

Only image, audio and video types are now rendered inline. Any other
type, including a missing or malformed one, is served as
application/octet-stream with Content-Disposition: attachment.

This only changes what happens when a proxy URL is opened directly.
The img, audio and video elements ignore Content-Disposition, so
embedded media is not affected.
Frédéric Guillot пре 1 дан
родитељ
комит
a6cb4b3d86
2 измењених фајлова са 146 додато и 3 уклоњено
  1. 35 3
      internal/ui/proxy.go
  2. 111 0
      internal/ui/proxy_test.go

+ 35 - 3
internal/ui/proxy.go

@@ -9,10 +9,12 @@ import (
 	"encoding/base64"
 	"errors"
 	"log/slog"
+	"mime"
 	"net/http"
 	"net/url"
 	"path"
 	"strconv"
+	"strings"
 	"time"
 
 	"miniflux.app/v2/internal/config"
@@ -142,16 +144,34 @@ func (h *handler) mediaProxy(w http.ResponseWriter, r *http.Request) {
 
 	etag := crypto.HashFromBytes(decodedURL)
 
+	contentType := resp.Header.Get("Content-Type")
+	isInline := isInlineMediaType(contentType)
+	if !isInline {
+		slog.Debug("MediaProxy: Forcing download for non-media content type",
+			slog.String("media_url", mediaURL),
+			slog.String("content_type", contentType),
+		)
+		contentType = "application/octet-stream"
+	}
+
+	filename := path.Base(parsedMediaURL.Path)
+	if filename == "." || filename == "/" {
+		filename = ""
+	}
+
 	response.NewBuilder(w, r).WithCaching(etag, 72*time.Hour, func(b *response.Builder) {
 		b.WithStatus(resp.StatusCode)
 		b.WithHeader("Content-Security-Policy", response.ContentSecurityPolicyForUntrustedContent)
-		b.WithHeader("Content-Type", resp.Header.Get("Content-Type"))
+		b.WithHeader("Content-Type", contentType)
 
-		if filename := path.Base(parsedMediaURL.Path); filename != "" && filename != "." && filename != "/" {
+		switch {
+		case !isInline:
+			b.WithAttachment(filename)
+		case filename != "":
 			b.WithInline(filename)
 		}
 
-		forwardedResponseHeader := [...]string{"Content-Encoding", "Content-Type", "Content-Length", "Accept-Ranges", "Content-Range"}
+		forwardedResponseHeader := [...]string{"Content-Encoding", "Content-Length", "Accept-Ranges", "Content-Range"}
 		for _, responseHeaderName := range forwardedResponseHeader {
 			if resp.Header.Get(responseHeaderName) != "" {
 				b.WithHeader(responseHeaderName, resp.Header.Get(responseHeaderName))
@@ -162,3 +182,15 @@ func (h *handler) mediaProxy(w http.ResponseWriter, r *http.Request) {
 		b.Write()
 	})
 }
+
+// isInlineMediaType reports whether the Content-Type is an image, audio or video type safe to render inline.
+func isInlineMediaType(contentType string) bool {
+	mediaType, _, err := mime.ParseMediaType(contentType)
+	if err != nil {
+		return false
+	}
+
+	return strings.HasPrefix(mediaType, "image/") ||
+		strings.HasPrefix(mediaType, "audio/") ||
+		strings.HasPrefix(mediaType, "video/")
+}

+ 111 - 0
internal/ui/proxy_test.go

@@ -0,0 +1,111 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package ui // import "miniflux.app/v2/internal/ui"
+
+import (
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"miniflux.app/v2/internal/http/response"
+	"miniflux.app/v2/internal/mediaproxy"
+)
+
+func TestIsInlineMediaType(t *testing.T) {
+	scenarios := []struct {
+		contentType string
+		expected    bool
+	}{
+		{"image/png", true},
+		{"image/svg+xml", true},
+		{"IMAGE/JPEG; charset=utf-8", true},
+		{"audio/mpeg", true},
+		{"video/mp4", true},
+		{"text/html", false},
+		{"text/html; charset=utf-8", false},
+		{"application/xhtml+xml", false},
+		{"application/octet-stream", false},
+		{"text/plain", false},
+		{"", false},
+		{";;", false},
+		{"image", false},
+	}
+
+	for _, scenario := range scenarios {
+		if result := isInlineMediaType(scenario.contentType); result != scenario.expected {
+			t.Errorf(`Unexpected result for %q, got %v instead of %v`, scenario.contentType, result, scenario.expected)
+		}
+	}
+}
+
+func TestMediaProxyContentTypeHandling(t *testing.T) {
+	scenarios := []struct {
+		name                       string
+		upstreamPath               string
+		upstreamContentType        string
+		expectedContentType        string
+		expectedContentDisposition string
+	}{
+		{"png image", "/image.png", "image/png", "image/png", "inline; filename=image.png"},
+		{"svg image with parameters", "/image.svg", "IMAGE/SVG+XML; charset=utf-8", "IMAGE/SVG+XML; charset=utf-8", "inline; filename=image.svg"},
+		{"audio", "/episode.mp3", "audio/mpeg", "audio/mpeg", "inline; filename=episode.mp3"},
+		{"video", "/clip.mp4", "video/mp4", "video/mp4", "inline; filename=clip.mp4"},
+		{"image without filename", "/", "image/png", "image/png", ""},
+		{"html page", "/page.html", "text/html; charset=utf-8", "application/octet-stream", "attachment; filename=page.html"},
+		{"xhtml page", "/page.xhtml", "application/xhtml+xml", "application/octet-stream", "attachment; filename=page.xhtml"},
+		{"html page without filename", "/", "text/html", "application/octet-stream", "attachment"},
+		{"missing content type", "/unknown", "", "application/octet-stream", "attachment; filename=unknown"},
+		{"malformed content type", "/broken", ";;", "application/octet-stream", "attachment; filename=broken"},
+	}
+
+	const upstreamBody = "<html><body>upstream body</body></html>"
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			configureTestOptions(t, map[string]string{
+				"MEDIA_PROXY_PRIVATE_KEY":        "test-private-key",
+				"FETCHER_ALLOW_PRIVATE_NETWORKS": "1",
+			})
+
+			upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+				if scenario.upstreamContentType == "" {
+					// Setting the header to nil prevents net/http from sniffing a Content-Type.
+					w.Header()["Content-Type"] = nil
+				} else {
+					w.Header().Set("Content-Type", scenario.upstreamContentType)
+				}
+				io.WriteString(w, upstreamBody)
+			}))
+			t.Cleanup(upstreamServer.Close)
+
+			mux := http.NewServeMux()
+			mux.HandleFunc("GET /proxy/{encodedDigest}/{encodedURL}", (&handler{}).mediaProxy)
+
+			proxyPath := mediaproxy.ProxifyRelativeURL(upstreamServer.URL + scenario.upstreamPath)
+			recorder := httptest.NewRecorder()
+			mux.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, proxyPath, nil))
+
+			if recorder.Code != http.StatusOK {
+				t.Fatalf(`Unexpected status code, got %d instead of %d`, recorder.Code, http.StatusOK)
+			}
+
+			if contentType := recorder.Header().Get("Content-Type"); contentType != scenario.expectedContentType {
+				t.Errorf(`Unexpected Content-Type, got %q instead of %q`, contentType, scenario.expectedContentType)
+			}
+
+			if contentDisposition := recorder.Header().Get("Content-Disposition"); contentDisposition != scenario.expectedContentDisposition {
+				t.Errorf(`Unexpected Content-Disposition, got %q instead of %q`, contentDisposition, scenario.expectedContentDisposition)
+			}
+
+			if csp := recorder.Header().Get("Content-Security-Policy"); csp != response.ContentSecurityPolicyForUntrustedContent {
+				t.Errorf(`Unexpected Content-Security-Policy, got %q`, csp)
+			}
+
+			if body := recorder.Body.String(); body != upstreamBody {
+				t.Errorf(`Unexpected body, got %q instead of %q`, body, upstreamBody)
+			}
+		})
+	}
+}