Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions docs/swagger/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down
12 changes: 12 additions & 0 deletions docs/swagger/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@
"$ref": "#/definitions/server.ErrorResponse"
}
},
"415": {
"description": "Unsupported Media Type",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
Expand Down Expand Up @@ -439,6 +445,12 @@
"$ref": "#/definitions/server.ErrorResponse"
}
},
"415": {
"description": "Unsupported Media Type",
"schema": {
"$ref": "#/definitions/server.ErrorResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
Expand Down
48 changes: 41 additions & 7 deletions internal/server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
Expand All @@ -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"
)
Expand Down Expand Up @@ -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
Expand All @@ -391,20 +419,23 @@ 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handler and HandleBulkLookup can now answer 415, but the annotations only list 400 and 500. Add // @Failure 415 {object} ErrorResponse to both and regenerate docs/swagger.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in dbd62f6, with docs/swagger regenerated.

// @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
}

if len(req.Packages) == 0 {
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)),
Expand Down Expand Up @@ -437,20 +468,23 @@ 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
}

if len(req.PURLs) == 0 {
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),
Expand Down
101 changes: 101 additions & 0 deletions internal/server/api_limits_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
5 changes: 5 additions & 0 deletions internal/server/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)

Expand All @@ -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)

Expand All @@ -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)

Expand All @@ -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)

Expand Down
13 changes: 1 addition & 12 deletions internal/server/mirror_api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package server

import (
"encoding/json"
"mime"
"net/http"

Expand All @@ -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
}

Expand Down
Loading