diff --git a/README.md b/README.md index 961ce67e..f079c793 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` takes up to 100 packages and `POST /api/bulk` up to 1000 PURLs per request; both need `Content-Type: application/json`. + #### Get Package Metadata ```bash 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 07080aa1..c800670f 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,15 @@ import ( ) const ( - maxBodySize = 1 << 20 // 1 MB + maxBodySize = 1 << 20 // 1 MB + // 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" ) @@ -383,6 +392,25 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { writeJSON(w, resp) } +// 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") + 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 @@ -391,13 +419,12 @@ func (h *APIHandler) HandleVulnsPath(w http.ResponseWriter, r *http.Request) { // @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) { - 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 !readJSONRequest(w, r, &req) { return } @@ -405,6 +432,10 @@ func (h *APIHandler) HandleOutdated(w http.ResponseWriter, r *http.Request) { badRequest(w, "packages list is required") return } + if len(req.Packages) > maxOutdatedPackages { + badRequest(w, fmt.Sprintf("at most %d packages per request", maxOutdatedPackages)) + return + } resp := OutdatedResponse{ Results: make([]OutdatedResult, 0, len(req.Packages)), @@ -437,13 +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) { - 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 !readJSONRequest(w, r, &req) { return } @@ -451,6 +481,10 @@ func (h *APIHandler) HandleBulkLookup(w http.ResponseWriter, r *http.Request) { badRequest(w, "purls list is required") return } + if len(req.PURLs) > maxBulkPURLs { + badRequest(w, fmt.Sprintf("at most %d purls per request", maxBulkPURLs)) + 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..b91936f1 --- /dev/null +++ b/internal/server/api_limits_test.go @@ -0,0 +1,101 @@ +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 + limit int + }{ + {"/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", 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}, + } { + 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(e.limit)) { + t.Errorf("body = %s, want it to name the limit of %d", w.Body, e.limit) + } + }) + } + } +} + +// 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) 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 }