Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add feature to limit HTTP request body length to process #1334

Merged
merged 1 commit into from
Mar 4, 2023
Merged
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 cmd/rekor-server/app/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ Memory and file-based signers should only be used for testing.`)

rootCmd.PersistentFlags().StringSlice("enabled_api_endpoints", operationIds, "list of API endpoints to enable using operationId from openapi.yaml")

rootCmd.PersistentFlags().Uint64("max_request_body_size", 0, "maximum size for HTTP request body, in bytes; set to 0 for unlimited")
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you want to set a default limit rather than unlimited?

Copy link
Member Author

Choose a reason for hiding this comment

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

For backward compatibility I didn't want to change behavior.

Copy link
Contributor

Choose a reason for hiding this comment

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

makes sense! maybe update the description to include a suggestion of a max value?


if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
log.Logger.Fatal(err)
}
Expand Down
23 changes: 23 additions & 0 deletions cmd/rekor-server/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path/filepath"
Expand Down Expand Up @@ -358,3 +361,23 @@ func TestSearchQueryMalformedEntry(t *testing.T) {
t.Fatalf("expected status 400, got %d instead", resp.StatusCode)
}
}

func TestHTTPMaxRequestBodySize(t *testing.T) {
// default value is 32Mb so let's try to propose something bigger
pipeR, pipeW := io.Pipe()
go func() {
_, _ = io.CopyN(base64.NewEncoder(base64.StdEncoding, pipeW), rand.New(rand.NewSource(123)), 33*1024768)
pipeW.Close()
}()
// json parsing will hit first so we need to make sure this is valid JSON
bodyReader := io.MultiReader(strings.NewReader("{ \"key\": \""), pipeR, strings.NewReader("\"}"))
resp, err := http.Post(fmt.Sprintf("%s/api/v1/log/entries/retrieve", rekorServer()),
"application/json",
bodyReader)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("expected status %d, got %d instead", http.StatusRequestEntityTooLarge, resp.StatusCode)
}
}
1 change: 1 addition & 0 deletions docker-compose.test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ services:
"--enable_attestation_storage",
"--attestation_storage_bucket=file:///var/run/attestations",
"--enable_killswitch",
"--max_request_body_size=32792576",
]
ports:
- "3000:3000"
Expand Down
27 changes: 26 additions & 1 deletion pkg/generated/restapi/configure_rekor_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package restapi
import (
"context"
"crypto/tls"
go_errors "errors"
"fmt"
"net/http"
"net/http/httputil"
Expand Down Expand Up @@ -251,6 +252,10 @@ func (l *logFormatter) NewLogEntry(r *http.Request) middleware.LogEntry {
// So this is a good place to plug in a panic handling middleware, logging and metrics
func setupGlobalMiddleware(handler http.Handler) http.Handler {
returnHandler := recoverer(handler)
maxReqBodySize := viper.GetInt64("max_request_body_size")
if maxReqBodySize > 0 {
returnHandler = maxBodySize(maxReqBodySize, returnHandler)
}
middleware.DefaultLogger = middleware.RequestLogger(&logFormatter{})
returnHandler = middleware.Logger(returnHandler)
returnHandler = middleware.Heartbeat("/ping")(returnHandler)
Expand Down Expand Up @@ -339,8 +344,18 @@ func logAndServeError(w http.ResponseWriter, r *http.Request, err error) {
} else {
log.ContextLogger(ctx).Error(err)
}
if compErr, ok := err.(*errors.CompositeError); ok {
// iterate over composite error looking for something more specific
for _, embeddedErr := range compErr.Errors {
var maxBytesError *http.MaxBytesError
if parseErr, ok := embeddedErr.(*errors.ParseError); ok && go_errors.As(parseErr.Reason, &maxBytesError) {
err = errors.New(http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge))
break
}
}
}
requestFields := map[string]interface{}{}
if err := mapstructure.Decode(r, &requestFields); err == nil {
if decodeErr := mapstructure.Decode(r, &requestFields); decodeErr == nil {
log.ContextLogger(ctx).Debug(requestFields)
}
errors.ServeError(w, r, err)
Expand Down Expand Up @@ -386,3 +401,13 @@ func recoverer(next http.Handler) http.Handler {

return http.HandlerFunc(fn)
}

// maxBodySize limits the request body
func maxBodySize(maxLength int64, next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxLength)
next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}