From cd67c07b7ed9e71d134f151f23f3bf705357bcdd Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sat, 21 Nov 2026 13:23:52 +0100 Subject: [PATCH 1/2] Cap the entries of an outdated or bulk request and require JSON One request could name about 30,000 packages, each looked up at its registry, and a page on another site could send it through a visitor's browser. --- README.md | 2 + internal/server/api.go | 41 ++++++++++-- internal/server/api_limits_test.go | 100 +++++++++++++++++++++++++++++ internal/server/api_test.go | 5 ++ 4 files changed, 141 insertions(+), 7 deletions(-) create mode 100644 internal/server/api_limits_test.go diff --git a/README.md b/README.md index 961ce67e..a32a13dd 100644 --- a/README.md +++ b/README.md @@ -1475,6 +1475,8 @@ The proxy provides REST endpoints for package metadata enrichment, vulnerability | `POST /api/outdated` | Check multiple packages for outdated versions | | `POST /api/bulk` | Bulk package metadata lookup | +`POST /api/outdated` and `POST /api/bulk` take up to 1000 entries per request and need `Content-Type: application/json`. + #### Get Package Metadata ```bash diff --git a/internal/server/api.go b/internal/server/api.go index 07080aa1..8d5debc3 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "net/http" "strings" "time" @@ -16,7 +17,10 @@ import ( ) const ( - maxBodySize = 1 << 20 // 1 MB + maxBodySize = 1 << 20 // 1 MB + // maxLookupEntries is how many packages one outdated or bulk request + // may name: each is looked up at its registry. + maxLookupEntries = 1000 licenseCategoryUnknown = "unknown" defaultSortBy = "hits" ) @@ -383,6 +387,25 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { writeJSON(w, resp) } +// readLookupRequest decodes the JSON body of a lookup request into req, or +// answers the request and returns false. A browser can only send a JSON +// content type cross-origin after a CORS preflight, which the proxy never +// answers, so requiring it stops other sites from sending lookups through a +// visitor's browser. +func readLookupRequest(w http.ResponseWriter, r *http.Request, req any) bool { + if !isJSONRequest(r) { + writeError(w, http.StatusUnsupportedMediaType, ErrCodeUnsupportedMediaType, + "Content-Type must be application/json") + return false + } + r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) + if err := json.NewDecoder(r.Body).Decode(req); err != nil { + badRequest(w, "invalid request body") + return false + } + return true +} + // HandleOutdated handles POST /api/outdated // @Summary Check outdated packages // @Tags api @@ -394,10 +417,8 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { // @Failure 500 {object} ErrorResponse // @Router /api/outdated [post] func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) var req OutdatedRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - badRequest(w, "invalid request body") + if !readLookupRequest(w, r, &req) { return } @@ -405,6 +426,10 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { badRequest(w, "packages list is required") return } + if len(req.Packages) > maxLookupEntries { + badRequest(w, fmt.Sprintf("at most %d packages per request", maxLookupEntries)) + return + } resp := OutdatedResponse{ Results: make([]OutdatedResult, 0, len(req.Packages)), @@ -440,10 +465,8 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { // @Failure 500 {object} ErrorResponse // @Router /api/bulk [post] func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) var req BulkRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - badRequest(w, "invalid request body") + if !readLookupRequest(w, r, &req) { return } @@ -451,6 +474,10 @@ func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { badRequest(w, "purls list is required") return } + if len(req.PURLs) > maxLookupEntries { + badRequest(w, fmt.Sprintf("at most %d purls per request", maxLookupEntries)) + return + } resp := BulkResponse{ Packages: make(map[string]*PackageResponse), diff --git a/internal/server/api_limits_test.go b/internal/server/api_limits_test.go new file mode 100644 index 00000000..5a63fb50 --- /dev/null +++ b/internal/server/api_limits_test.go @@ -0,0 +1,100 @@ +package server + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/enrichment" +) + +// lookupRequest is a POST to a lookup endpoint whose context is already +// done, so a request that gets as far as its lookups reaches no registry. +func lookupRequest(path, contentType, body string) *http.Request { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)).WithContext(ctx) + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + return req +} + +func outdatedBody(n int) string { + entries := make([]string, n) + for i := range entries { + entries[i] = fmt.Sprintf(`{"ecosystem":"npm","name":"p%d","version":"1.0.0"}`, i) + } + return `{"packages":[` + strings.Join(entries, ",") + `]}` +} + +func bulkBody(n int) string { + entries := make([]string, n) + for i := range entries { + entries[i] = fmt.Sprintf(`"pkg:npm/p%d@1.0.0"`, i) + } + return `{"purls":[` + strings.Join(entries, ",") + `]}` +} + +// One request to a lookup endpoint asks the registries about each entry, so +// the number of entries is capped, and other sites can't send one through a +// visitor's browser. +func TestLookupEndpointsLimitTheirRequests(t *testing.T) { + h := NewAPIHandler(enrichment.New(slog.New(slog.NewTextHandler(os.Stdout, nil))), nil) + endpoints := []struct { + path string + handle http.HandlerFunc + body func(n int) string + }{ + {"/api/outdated", h.HandleOutdated, outdatedBody}, + {"/api/bulk", h.HandleBulkLookup, bulkBody}, + } + for _, e := range endpoints { + for _, tt := range []struct { + name, contentType string + entries, want int + }{ + {"at the limit", "application/json", maxLookupEntries, http.StatusOK}, + {"over the limit", "application/json", maxLookupEntries + 1, http.StatusBadRequest}, + {"with a charset", "application/json; charset=utf-8", 1, http.StatusOK}, + {"no content type", "", 1, http.StatusUnsupportedMediaType}, + {"a form's content type", "text/plain", 1, http.StatusUnsupportedMediaType}, + } { + t.Run(e.path+" "+tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + e.handle(w, lookupRequest(e.path, tt.contentType, e.body(tt.entries))) + if w.Code != tt.want { + t.Fatalf("status = %d, want %d: %s", w.Code, tt.want, w.Body) + } + if tt.want == http.StatusBadRequest && !strings.Contains(w.Body.String(), fmt.Sprint(maxLookupEntries)) { + t.Errorf("body = %s, want it to name the limit of %d", w.Body, maxLookupEntries) + } + }) + } + } +} + +// A body over the size limit is refused even when it is valid JSON naming +// few entries. +func TestLookupEndpointsRefuseALargeBody(t *testing.T) { + h := NewAPIHandler(enrichment.New(slog.New(slog.NewTextHandler(os.Stdout, nil))), nil) + long := strings.Repeat("x", maxBodySize) + for path, e := range map[string]struct { + handle http.HandlerFunc + body string + }{ + "/api/outdated": {h.HandleOutdated, `{"packages":[{"ecosystem":"npm","name":"p","version":"1.0.0"}],"padding":"` + long + `"}`}, + "/api/bulk": {h.HandleBulkLookup, `{"purls":["pkg:npm/p@1.0.0"],"padding":"` + long + `"}`}, + } { + w := httptest.NewRecorder() + e.handle(w, lookupRequest(path, "application/json", e.body)) + if w.Code != http.StatusBadRequest { + t.Errorf("%s: status = %d, want %d", path, w.Code, http.StatusBadRequest) + } + } +} diff --git a/internal/server/api_test.go b/internal/server/api_test.go index 0494b2fd..f8060cef 100644 --- a/internal/server/api_test.go +++ b/internal/server/api_test.go @@ -101,6 +101,7 @@ func TestHandleOutdated_EmptyBody(t *testing.T) { h := NewAPIHandler(svc, nil) req := httptest.NewRequest("POST", "/api/outdated", bytes.NewReader([]byte("{}"))) + req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() h.HandleOutdated(w, req) @@ -120,6 +121,7 @@ func TestHandleOutdated_OversizedBody(t *testing.T) { body[i] = 'x' } req := httptest.NewRequest("POST", "/api/outdated", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() h.HandleOutdated(w, req) @@ -134,6 +136,7 @@ func TestHandleOutdated_InvalidJSON(t *testing.T) { h := NewAPIHandler(svc, nil) req := httptest.NewRequest("POST", "/api/outdated", bytes.NewReader([]byte("not json"))) + req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() h.HandleOutdated(w, req) @@ -148,6 +151,7 @@ func TestHandleBulkLookup_EmptyBody(t *testing.T) { h := NewAPIHandler(svc, nil) req := httptest.NewRequest("POST", "/api/bulk", bytes.NewReader([]byte("{}"))) + req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() h.HandleBulkLookup(w, req) @@ -162,6 +166,7 @@ func TestHandleBulkLookup_InvalidJSON(t *testing.T) { h := NewAPIHandler(svc, nil) req := httptest.NewRequest("POST", "/api/bulk", bytes.NewReader([]byte("not json"))) + req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() h.HandleBulkLookup(w, req) From dbd62f6d73e0c081650208a56db5f96f21c23679 Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sun, 22 Nov 2026 10:43:56 +0100 Subject: [PATCH 2/2] Cap outdated requests at 100 packages and share the JSON reader Outdated looks its packages up one after another, so 1000 of them could run past the default write_timeout. HandleCreate now reads its body with the same helper, and the swagger docs list the 415. --- README.md | 2 +- docs/swagger/docs.go | 12 ++++++++++ docs/swagger/swagger.json | 12 ++++++++++ internal/server/api.go | 37 ++++++++++++++++++------------ internal/server/api_limits_test.go | 13 ++++++----- internal/server/mirror_api.go | 13 +---------- 6 files changed, 55 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index a32a13dd..f079c793 100644 --- a/README.md +++ b/README.md @@ -1475,7 +1475,7 @@ The proxy provides REST endpoints for package metadata enrichment, vulnerability | `POST /api/outdated` | Check multiple packages for outdated versions | | `POST /api/bulk` | Bulk package metadata lookup | -`POST /api/outdated` and `POST /api/bulk` take up to 1000 entries per request and need `Content-Type: application/json`. +`POST /api/outdated` takes up to 100 packages and `POST /api/bulk` up to 1000 PURLs per request; both need `Content-Type: application/json`. #### Get Package Metadata diff --git a/docs/swagger/docs.go b/docs/swagger/docs.go index 22a922dd..a7bfead0 100644 --- a/docs/swagger/docs.go +++ b/docs/swagger/docs.go @@ -106,6 +106,12 @@ const docTemplate = `{ "$ref": "#/definitions/server.ErrorResponse" } }, + "415": { + "description": "Unsupported Media Type", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -446,6 +452,12 @@ const docTemplate = `{ "$ref": "#/definitions/server.ErrorResponse" } }, + "415": { + "description": "Unsupported Media Type", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { diff --git a/docs/swagger/swagger.json b/docs/swagger/swagger.json index 1832c05a..538a8348 100644 --- a/docs/swagger/swagger.json +++ b/docs/swagger/swagger.json @@ -99,6 +99,12 @@ "$ref": "#/definitions/server.ErrorResponse" } }, + "415": { + "description": "Unsupported Media Type", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -439,6 +445,12 @@ "$ref": "#/definitions/server.ErrorResponse" } }, + "415": { + "description": "Unsupported Media Type", + "schema": { + "$ref": "#/definitions/server.ErrorResponse" + } + }, "500": { "description": "Internal Server Error", "schema": { diff --git a/internal/server/api.go b/internal/server/api.go index 8d5debc3..c800670f 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -18,9 +18,14 @@ import ( const ( maxBodySize = 1 << 20 // 1 MB - // maxLookupEntries is how many packages one outdated or bulk request - // may name: each is looked up at its registry. - maxLookupEntries = 1000 + // maxOutdatedPackages is how many packages one outdated request may name. + // They are looked up one after another, so even at 3s each a full request + // finishes inside the default 5m write_timeout. + maxOutdatedPackages = 100 + // maxBulkPURLs is how many PURLs one bulk request may name. They go to + // ecosyste.ms in one request, or to their registries 15 at a time, which + // leaves each of the 67 rounds over 4s. + maxBulkPURLs = 1000 licenseCategoryUnknown = "unknown" defaultSortBy = "hits" ) @@ -387,12 +392,12 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { writeJSON(w, resp) } -// readLookupRequest decodes the JSON body of a lookup request into req, or -// answers the request and returns false. A browser can only send a JSON -// content type cross-origin after a CORS preflight, which the proxy never -// answers, so requiring it stops other sites from sending lookups through a -// visitor's browser. -func readLookupRequest(w http.ResponseWriter, r *http.Request, req any) bool { +// readJSONRequest decodes the JSON body of a request into req, or answers the +// request and returns false. A browser can only send a JSON content type +// cross-origin after a CORS preflight, which the proxy never answers, so +// requiring it stops other sites from sending requests through a visitor's +// browser. +func readJSONRequest(w http.ResponseWriter, r *http.Request, req any) bool { if !isJSONRequest(r) { writeError(w, http.StatusUnsupportedMediaType, ErrCodeUnsupportedMediaType, "Content-Type must be application/json") @@ -414,11 +419,12 @@ func readLookupRequest(w http.ResponseWriter, r *http.Request, req any) bool { // @Param request body OutdatedRequest true "Packages to check" // @Success 200 {object} OutdatedResponse // @Failure 400 {object} ErrorResponse +// @Failure 415 {object} ErrorResponse // @Failure 500 {object} ErrorResponse // @Router /api/outdated [post] func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { var req OutdatedRequest - if !readLookupRequest(w, r, &req) { + if !readJSONRequest(w, r, &req) { return } @@ -426,8 +432,8 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { badRequest(w, "packages list is required") return } - if len(req.Packages) > maxLookupEntries { - badRequest(w, fmt.Sprintf("at most %d packages per request", maxLookupEntries)) + if len(req.Packages) > maxOutdatedPackages { + badRequest(w, fmt.Sprintf("at most %d packages per request", maxOutdatedPackages)) return } @@ -462,11 +468,12 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { // @Param request body BulkRequest true "PURLs" // @Success 200 {object} BulkResponse // @Failure 400 {object} ErrorResponse +// @Failure 415 {object} ErrorResponse // @Failure 500 {object} ErrorResponse // @Router /api/bulk [post] func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { var req BulkRequest - if !readLookupRequest(w, r, &req) { + if !readJSONRequest(w, r, &req) { return } @@ -474,8 +481,8 @@ func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { badRequest(w, "purls list is required") return } - if len(req.PURLs) > maxLookupEntries { - badRequest(w, fmt.Sprintf("at most %d purls per request", maxLookupEntries)) + if len(req.PURLs) > maxBulkPURLs { + badRequest(w, fmt.Sprintf("at most %d purls per request", maxBulkPURLs)) return } diff --git a/internal/server/api_limits_test.go b/internal/server/api_limits_test.go index 5a63fb50..b91936f1 100644 --- a/internal/server/api_limits_test.go +++ b/internal/server/api_limits_test.go @@ -50,17 +50,18 @@ func TestLookupEndpointsLimitTheirRequests(t *testing.T) { path string handle http.HandlerFunc body func(n int) string + limit int }{ - {"/api/outdated", h.HandleOutdated, outdatedBody}, - {"/api/bulk", h.HandleBulkLookup, bulkBody}, + {"/api/outdated", h.HandleOutdated, outdatedBody, 100}, + {"/api/bulk", h.HandleBulkLookup, bulkBody, 1000}, } for _, e := range endpoints { for _, tt := range []struct { name, contentType string entries, want int }{ - {"at the limit", "application/json", maxLookupEntries, http.StatusOK}, - {"over the limit", "application/json", maxLookupEntries + 1, http.StatusBadRequest}, + {"at the limit", "application/json", e.limit, http.StatusOK}, + {"over the limit", "application/json", e.limit + 1, http.StatusBadRequest}, {"with a charset", "application/json; charset=utf-8", 1, http.StatusOK}, {"no content type", "", 1, http.StatusUnsupportedMediaType}, {"a form's content type", "text/plain", 1, http.StatusUnsupportedMediaType}, @@ -71,8 +72,8 @@ func TestLookupEndpointsLimitTheirRequests(t *testing.T) { if w.Code != tt.want { t.Fatalf("status = %d, want %d: %s", w.Code, tt.want, w.Body) } - if tt.want == http.StatusBadRequest && !strings.Contains(w.Body.String(), fmt.Sprint(maxLookupEntries)) { - t.Errorf("body = %s, want it to name the limit of %d", w.Body, maxLookupEntries) + if tt.want == http.StatusBadRequest && !strings.Contains(w.Body.String(), fmt.Sprint(e.limit)) { + t.Errorf("body = %s, want it to name the limit of %d", w.Body, e.limit) } }) } diff --git a/internal/server/mirror_api.go b/internal/server/mirror_api.go index 89de3d56..5047bbbe 100644 --- a/internal/server/mirror_api.go +++ b/internal/server/mirror_api.go @@ -1,7 +1,6 @@ package server import ( - "encoding/json" "mime" "net/http" @@ -21,18 +20,8 @@ func NewMirrorAPIHandler(jobs *mirror.JobStore) *MirrorAPIHandler { // HandleCreate starts a new mirror job. func (h *MirrorAPIHandler) HandleCreate(w http.ResponseWriter, r *http.Request) { - // A browser can only send a JSON content type cross-origin after a CORS - // preflight, which the proxy never answers, so requiring it stops other - // sites from starting mirror jobs through a visitor's browser. - if !isJSONRequest(r) { - writeError(w, http.StatusUnsupportedMediaType, ErrCodeUnsupportedMediaType, - "Content-Type must be application/json") - return - } - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) var req mirror.JobRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - badRequest(w, "invalid request body") + if !readJSONRequest(w, r, &req) { return }