diff --git a/pkg/proxy/pypi/negotiate_test.go b/pkg/proxy/pypi/negotiate_test.go new file mode 100644 index 0000000..da23f34 --- /dev/null +++ b/pkg/proxy/pypi/negotiate_test.go @@ -0,0 +1,32 @@ +package pypi + +import "testing" + +func TestNegotiateFormat(t *testing.T) { + tests := []struct { + name string + accept string + want format + wantOK bool + }{ + {"no header serves html", "", formatHTML, true}, + {"wildcard serves html", "*/*", formatHTML, true}, + {"browser", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", formatHTML, true}, + {"uv", "application/vnd.pypi.simple.v1+json, application/vnd.pypi.simple.v1+html;q=0.2, text/html;q=0.01", formatJSON, true}, + {"pip", "application/vnd.pypi.simple.v1+json, application/vnd.pypi.simple.v1+html; q=0.1, text/html; q=0.01", formatJSON, true}, + {"explicit html", "application/vnd.pypi.simple.v1+html", formatHTML, true}, + {"latest json alias", "application/vnd.pypi.simple.latest+json", formatJSON, true}, + {"html preferred by q", "application/vnd.pypi.simple.v1+json;q=0.1, text/html", formatHTML, true}, + {"json q zero refused", "application/vnd.pypi.simple.v1+json;q=0, text/html;q=0.5", formatHTML, true}, + {"unsupported only", "application/xml", formatHTML, false}, + {"tie prefers json", "text/html, application/vnd.pypi.simple.v1+json", formatJSON, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, ok := negotiateFormat(tt.accept) + if ok != tt.wantOK || (ok && got != tt.want) { + t.Errorf("negotiateFormat(%q) = (%v, %v), want (%v, %v)", tt.accept, got, ok, tt.want, tt.wantOK) + } + }) + } +} diff --git a/pkg/proxy/pypi/pypi.go b/pkg/proxy/pypi/pypi.go index 1035204..2c80a7d 100644 --- a/pkg/proxy/pypi/pypi.go +++ b/pkg/proxy/pypi/pypi.go @@ -80,6 +80,10 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha if len(allowed) == 0 { allowed = defaultAllowedPyPIHosts } + // A private index serves its files from its own host. + if parsed, err := url.Parse(config.Upstream); err == nil && parsed.Hostname() != "" { + allowed = append(append([]string(nil), allowed...), parsed.Hostname()) + } return &Handler{ cache: cacheManager, @@ -156,10 +160,24 @@ func (h *Handler) handleIndex(ctx context.Context, w http.ResponseWriter, r *htt // handlePackagePage handles package page requests func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter, r *http.Request, path string) { + pageFormat, ok := negotiateFormat(r.Header.Get("Accept")) + if !ok { + http.Error(w, "No acceptable simple API representation", http.StatusNotAcceptable) + return + } + url := h.upstream + path packageName := extractPackageName(path) - entry, err := h.cache.Get(ctx, "pypi", packageName, "page", func(ctx context.Context) (*cache.FetchResult, error) { - body, statusCode, err := h.client.Get(ctx, url, nil) + + cacheVersion := "page" + var upstreamHeaders map[string]string + if pageFormat == formatJSON { + cacheVersion = jsonPageVersion + upstreamHeaders = map[string]string{"Accept": contentTypeJSON} + } + + entry, err := h.cache.Get(ctx, "pypi", packageName, cacheVersion, func(ctx context.Context) (*cache.FetchResult, error) { + body, statusCode, err := h.client.Get(ctx, url, upstreamHeaders) if err != nil { return nil, err } @@ -194,10 +212,24 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter, // Rewrite package file URLs to point to our proxy proxyBaseURL := getProxyBaseURL(r) + w.Header().Add("Vary", "Accept") + + if pageFormat == formatJSON { + rewritten, err := rewriteJSONPage(buf.Bytes(), packageName, url, proxyBaseURL) + if err != nil { + log.Error().Err(err).Str("url", url).Msg("Failed to rewrite package page JSON") + http.Error(w, "Failed to parse package page", http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", contentTypeJSON) + _, _ = w.Write(rewritten) // #nosec G104 -- HTTP response write + return + } + modifiedHTML := rewritePackagePageURLs(buf.String(), packageName, proxyBaseURL) - w.Header().Set("Content-Type", "text/html; charset=UTF-8") - _, _ = w.Write([]byte(modifiedHTML)) // #nosec G104 -- Websocket buffer write + w.Header().Set("Content-Type", contentTypeHTML) + _, _ = w.Write([]byte(modifiedHTML)) // #nosec G104 -- HTTP response write } // handlePackageFile handles package file download requests @@ -241,6 +273,13 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter, http.Error(w, "Invalid original_url", http.StatusBadRequest) return } + // The page links the wheel; a PEP 658 sidecar request appends + // ".metadata" to the proxy path, so the upstream URL needs it too. + if strings.HasSuffix(path, metadataSuffix) && !strings.HasSuffix(parsed.Path, metadataSuffix) { + parsed.Path += metadataSuffix + parsed.RawPath = "" + originalURL = parsed.String() + } if !isAllowedPyPIHost(parsed.Host, h.allowedHosts) { log.Warn(). Str("original_url", originalURL). diff --git a/pkg/proxy/pypi/simple_json.go b/pkg/proxy/pypi/simple_json.go new file mode 100644 index 0000000..b185feb --- /dev/null +++ b/pkg/proxy/pypi/simple_json.go @@ -0,0 +1,131 @@ +package pypi + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" +) + +type format int + +const ( + formatHTML format = iota + formatJSON +) + +const ( + // contentTypeJSON is the PEP 691 media type of the JSON simple API. + contentTypeJSON = "application/vnd.pypi.simple.v1+json" + contentTypeHTML = "text/html; charset=UTF-8" + + // jsonPageVersion is the cache version of the upstream JSON page. It is on + // the cache's metadata-entry list, so the page is never security-scanned. + jsonPageVersion = "metadata" + + metadataSuffix = ".metadata" +) + +// negotiateFormat picks the simple-API representation for an Accept header the +// way PyPI does: the highest q wins, JSON wins a tie, and a client that states +// no preference (or only wildcards) gets HTML. ok is false when the client +// accepts none of the supported types. +func negotiateFormat(accept string) (format, bool) { + if strings.TrimSpace(accept) == "" { + return formatHTML, true + } + + bestQ := -1.0 + best := formatHTML + for _, part := range strings.Split(accept, ",") { + mediaType, q := parseMediaRange(part) + if q <= 0 { + continue + } + var candidate format + switch mediaType { + case "application/vnd.pypi.simple.v1+json", "application/vnd.pypi.simple.latest+json": + candidate = formatJSON + case "application/vnd.pypi.simple.v1+html", "application/vnd.pypi.simple.latest+html", + "text/html", "text/*", "*/*": + candidate = formatHTML + default: + continue + } + if q > bestQ || (q == bestQ && candidate == formatJSON) { + bestQ, best = q, candidate + } + } + return best, bestQ > 0 +} + +// parseMediaRange returns the lowercase media type and q-value of one Accept entry. +func parseMediaRange(entry string) (string, float64) { + fields := strings.Split(entry, ";") + mediaType := strings.ToLower(strings.TrimSpace(fields[0])) + q := 1.0 + for _, param := range fields[1:] { + name, value, found := strings.Cut(strings.TrimSpace(param), "=") + if !found || !strings.EqualFold(strings.TrimSpace(name), "q") { + continue + } + if parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64); err == nil { + q = parsed + } + } + return mediaType, q +} + +// rewriteJSONPage points every file URL of a PEP 691 page at the proxy. All +// other fields, including PEP 700 upload-time, pass through untouched. +func rewriteJSONPage(page []byte, packageName, pageURL, proxyBaseURL string) ([]byte, error) { + var doc map[string]json.RawMessage + if err := json.Unmarshal(page, &doc); err != nil { + return nil, fmt.Errorf("parse simple JSON page: %w", err) + } + rawFiles, ok := doc["files"] + if !ok { + return page, nil + } + var files []map[string]json.RawMessage + if err := json.Unmarshal(rawFiles, &files); err != nil { + return nil, fmt.Errorf("parse simple JSON files: %w", err) + } + + base, err := url.Parse(pageURL) + if err != nil { + return nil, fmt.Errorf("parse page URL: %w", err) + } + + for _, file := range files { + var filename, fileURL string + if json.Unmarshal(file["filename"], &filename) != nil || filename == "" { + continue + } + if json.Unmarshal(file["url"], &fileURL) != nil || fileURL == "" { + continue + } + original := fileURL + if ref, parseErr := url.Parse(fileURL); parseErr == nil { + original = base.ResolveReference(ref).String() + } + proxied := fmt.Sprintf("%s/%s/%s?original_url=%s", proxyBaseURL, packageName, url.PathEscape(filename), url.QueryEscape(original)) + encoded, marshalErr := json.Marshal(proxied) + if marshalErr != nil { + return nil, fmt.Errorf("encode file url: %w", marshalErr) + } + file["url"] = encoded + } + + rewrittenFiles, err := json.Marshal(files) + if err != nil { + return nil, fmt.Errorf("encode simple JSON files: %w", err) + } + doc["files"] = rewrittenFiles + out, err := json.Marshal(doc) + if err != nil { + return nil, fmt.Errorf("encode simple JSON page: %w", err) + } + return out, nil +}