Merge branch '17566-max-request-size'
authorTom Clegg <tom@curii.com>
Wed, 21 Apr 2021 20:25:59 +0000 (16:25 -0400)
committerTom Clegg <tom@curii.com>
Wed, 21 Apr 2021 20:25:59 +0000 (16:25 -0400)
fixes #17566

Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tom@curii.com>

lib/controller/federation/federation_test.go
lib/controller/handler.go
lib/controller/router/request.go
lib/controller/router/router.go
lib/controller/router/router_test.go
sdk/go/arvadosclient/arvadosclient_test.go
sdk/python/tests/nginx.conf

index 50f7eea42b3fe162de4282f009d31f162df5cd4f..fdc4d96cfaa90b3e28dd2048c2c5bd0f73bf9dc5 100644 (file)
@@ -86,7 +86,7 @@ func (s *FederationSuite) addDirectRemote(c *check.C, id string, backend backend
 
 func (s *FederationSuite) addHTTPRemote(c *check.C, id string, backend backend) {
        srv := httpserver.Server{Addr: ":"}
-       srv.Handler = router.New(backend, nil)
+       srv.Handler = router.New(backend, router.Config{})
        c.Check(srv.Start(), check.IsNil)
        s.cluster.RemoteClusters[id] = arvados.RemoteCluster{
                Scheme: "http",
index 578bfc7d24bd26b8417a1e1bdcda5b6ab7aafd14..a35d0030194e8bf9e79d1f2f256ff9fab5621fe7 100644 (file)
@@ -92,7 +92,10 @@ func (h *Handler) setup() {
        })
 
        oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
-       rtr := router.New(federation.New(h.Cluster), api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls))
+       rtr := router.New(federation.New(h.Cluster), router.Config{
+               MaxRequestSize: h.Cluster.API.MaxRequestSize,
+               WrapCalls:      api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls),
+       })
        mux.Handle("/arvados/v1/config", rtr)
        mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
        mux.Handle("/arvados/v1/collections", rtr)
index eae9e0a8cebc974dca813bba3dfa8f03381bbf2e..06141b1033e3f0034e003eab07da11c17153496e 100644 (file)
@@ -63,7 +63,11 @@ func guessAndParse(k, v string) (interface{}, error) {
 func (rtr *router) loadRequestParams(req *http.Request, attrsKey string) (map[string]interface{}, error) {
        err := req.ParseForm()
        if err != nil {
-               return nil, httpError(http.StatusBadRequest, err)
+               if err.Error() == "http: request body too large" {
+                       return nil, httpError(http.StatusRequestEntityTooLarge, err)
+               } else {
+                       return nil, httpError(http.StatusBadRequest, err)
+               }
        }
        params := map[string]interface{}{}
 
index a313ebc8bed94c5b5b7e32b6c086644b4faae77f..5ceabbfb1d56fab171d8d4a8dfabca585f1362f6 100644 (file)
@@ -7,6 +7,7 @@ package router
 import (
        "context"
        "fmt"
+       "math"
        "net/http"
        "strings"
 
@@ -20,24 +21,32 @@ import (
 )
 
 type router struct {
-       mux       *mux.Router
-       backend   arvados.API
-       wrapCalls func(api.RoutableFunc) api.RoutableFunc
+       mux     *mux.Router
+       backend arvados.API
+       config  Config
+}
+
+type Config struct {
+       // Return an error if request body exceeds this size. 0 means
+       // unlimited.
+       MaxRequestSize int
+
+       // If wrapCalls is not nil, it is called once for each API
+       // method, and the returned method is used in its place. This
+       // can be used to install hooks before and after each API call
+       // and alter responses; see localdb.WrapCallsInTransaction for
+       // an example.
+       WrapCalls func(api.RoutableFunc) api.RoutableFunc
 }
 
 // New returns a new router (which implements the http.Handler
 // interface) that serves requests by calling Arvados API methods on
 // the given backend.
-//
-// If wrapCalls is not nil, it is called once for each API method, and
-// the returned method is used in its place. This can be used to
-// install hooks before and after each API call and alter responses;
-// see localdb.WrapCallsInTransaction for an example.
-func New(backend arvados.API, wrapCalls func(api.RoutableFunc) api.RoutableFunc) *router {
+func New(backend arvados.API, config Config) *router {
        rtr := &router{
-               mux:       mux.NewRouter(),
-               backend:   backend,
-               wrapCalls: wrapCalls,
+               mux:     mux.NewRouter(),
+               backend: backend,
+               config:  config,
        }
        rtr.addRoutes()
        return rtr
@@ -433,8 +442,8 @@ func (rtr *router) addRoutes() {
                },
        } {
                exec := route.exec
-               if rtr.wrapCalls != nil {
-                       exec = rtr.wrapCalls(exec)
+               if rtr.config.WrapCalls != nil {
+                       exec = rtr.config.WrapCalls(exec)
                }
                rtr.addRoute(route.endpoint, route.defaultOpts, exec)
        }
@@ -524,8 +533,26 @@ func (rtr *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        if r.Method == "OPTIONS" {
                return
        }
+       if r.Body != nil {
+               // Wrap r.Body in a http.MaxBytesReader(), otherwise
+               // r.ParseForm() uses a default max request body size
+               // of 10 megabytes. Note we rely on the Nginx
+               // configuration to enforce the real max body size.
+               max := int64(rtr.config.MaxRequestSize)
+               if max < 1 {
+                       max = math.MaxInt64 - 1
+               }
+               r.Body = http.MaxBytesReader(w, r.Body, max)
+       }
        if r.Method == "POST" {
-               r.ParseForm()
+               err := r.ParseForm()
+               if err != nil {
+                       if err.Error() == "http: request body too large" {
+                               err = httpError(http.StatusRequestEntityTooLarge, err)
+                       }
+                       rtr.sendError(w, err)
+                       return
+               }
                if m := r.FormValue("_method"); m != "" {
                        r2 := *r
                        r = &r2
index 18fff7c9cc4f5d4a10f347c3da55ab79ca1bf38d..0330ec4252c9ad3ee8f461faf9ce7508c17bd3fc 100644 (file)
@@ -169,7 +169,7 @@ func (s *RouterIntegrationSuite) SetUpTest(c *check.C) {
        cluster.TLS.Insecure = true
        arvadostest.SetServiceURL(&cluster.Services.RailsAPI, "https://"+os.Getenv("ARVADOS_TEST_API_HOST"))
        url, _ := url.Parse("https://" + os.Getenv("ARVADOS_TEST_API_HOST"))
-       s.rtr = New(rpc.NewConn("zzzzz", url, true, rpc.PassthroughTokenProvider), nil)
+       s.rtr = New(rpc.NewConn("zzzzz", url, true, rpc.PassthroughTokenProvider), Config{})
 }
 
 func (s *RouterIntegrationSuite) TearDownSuite(c *check.C) {
@@ -226,6 +226,34 @@ func (s *RouterIntegrationSuite) TestCollectionResponses(c *check.C) {
        c.Check(jresp["kind"], check.Equals, "arvados#collection")
 }
 
+func (s *RouterIntegrationSuite) TestMaxRequestSize(c *check.C) {
+       token := arvadostest.ActiveTokenV2
+       for _, maxRequestSize := range []int{
+               // Ensure 5M limit is enforced.
+               5000000,
+               // Ensure 50M limit is enforced, and that a >25M body
+               // is accepted even though the default Go request size
+               // limit is 10M.
+               50000000,
+       } {
+               s.rtr.config.MaxRequestSize = maxRequestSize
+               okstr := "a"
+               for len(okstr) < maxRequestSize/2 {
+                       okstr = okstr + okstr
+               }
+
+               hdr := http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}
+
+               body := bytes.NewBufferString(url.Values{"foo_bar": {okstr}}.Encode())
+               _, rr, _ := doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, hdr, body)
+               c.Check(rr.Code, check.Equals, http.StatusOK)
+
+               body = bytes.NewBufferString(url.Values{"foo_bar": {okstr + okstr}}.Encode())
+               _, rr, _ = doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, hdr, body)
+               c.Check(rr.Code, check.Equals, http.StatusRequestEntityTooLarge)
+       }
+}
+
 func (s *RouterIntegrationSuite) TestContainerList(c *check.C) {
        token := arvadostest.ActiveTokenV2
 
index fc686ad63739e51340d5e254f8f68d65ac4db3e7..9d6e4fe7e8f7e702287db4865c348715c104a4ff 100644 (file)
@@ -10,7 +10,9 @@ import (
        "net/http"
        "os"
        "testing"
+       "time"
 
+       "git.arvados.org/arvados.git/sdk/go/arvados"
        "git.arvados.org/arvados.git/sdk/go/arvadostest"
        . "gopkg.in/check.v1"
 )
@@ -28,14 +30,12 @@ var _ = Suite(&MockArvadosServerSuite{})
 type ServerRequiredSuite struct{}
 
 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
-       arvadostest.StartAPI()
        arvadostest.StartKeep(2, false)
        RetryDelay = 0
 }
 
 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
        arvadostest.StopKeep(2)
-       arvadostest.StopAPI()
 }
 
 func (s *ServerRequiredSuite) SetUpTest(c *C) {
@@ -158,6 +158,32 @@ func (s *ServerRequiredSuite) TestAPIDiscovery_Get_noSuchParameter(c *C) {
        c.Assert(value, IsNil)
 }
 
+func (s *ServerRequiredSuite) TestCreateLarge(c *C) {
+       arv, err := MakeArvadosClient()
+       c.Assert(err, IsNil)
+
+       txt := arvados.SignLocator("d41d8cd98f00b204e9800998ecf8427e+0", arv.ApiToken, time.Now().Add(time.Minute), time.Minute, []byte(arvadostest.SystemRootToken))
+       // Ensure our request body is bigger than the Go http server's
+       // default max size, 10 MB.
+       for len(txt) < 12000000 {
+               txt = txt + " " + txt
+       }
+       txt = ". " + txt + " 0:0:foo\n"
+
+       resp := Dict{}
+       err = arv.Create("collections", Dict{
+               "ensure_unique_name": true,
+               "collection": Dict{
+                       "is_trashed":    true,
+                       "name":          "test",
+                       "manifest_text": txt,
+               },
+       }, &resp)
+       c.Check(err, IsNil)
+       c.Check(resp["portable_data_hash"], Not(Equals), "")
+       c.Check(resp["portable_data_hash"], Not(Equals), "d41d8cd98f00b204e9800998ecf8427e+0")
+}
+
 type UnitSuite struct{}
 
 func (s *UnitSuite) TestUUIDMatch(c *C) {
index a4336049f2447bd18cf396cbec0b76e7cdf69356..35b780071a356f5bb7ab38e053798908b0dafe6b 100644 (file)
@@ -24,6 +24,7 @@ http {
     server_name controller ~.*;
     ssl_certificate "{{SSLCERT}}";
     ssl_certificate_key "{{SSLKEY}}";
+    client_max_body_size 0;
     location  / {
       proxy_pass http://controller;
       proxy_set_header Host $http_host;