19597: Parse multipart/form-data request body.
[arvados.git] / lib / controller / router / request.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package router
6
7 import (
8         "encoding/json"
9         "fmt"
10         "io"
11         "mime"
12         "net/http"
13         "strconv"
14         "strings"
15
16         "github.com/gorilla/mux"
17 )
18
19 func guessAndParse(k, v string) (interface{}, error) {
20         // All of these form values arrive as strings, so we need some
21         // type-guessing to accept non-string inputs:
22         //
23         // Values for parameters that take ints (limit=1) or bools
24         // (include_trash=1) are parsed accordingly.
25         //
26         // "null" and "" are nil.
27         //
28         // Values that look like JSON objects, arrays, or strings are
29         // parsed as JSON.
30         //
31         // The rest are left as strings.
32         switch {
33         case intParams[k]:
34                 return strconv.ParseInt(v, 10, 64)
35         case boolParams[k]:
36                 return stringToBool(v), nil
37         case v == "null" || v == "":
38                 return nil, nil
39         case strings.HasPrefix(v, "["):
40                 var j []interface{}
41                 err := json.Unmarshal([]byte(v), &j)
42                 return j, err
43         case strings.HasPrefix(v, "{"):
44                 var j map[string]interface{}
45                 err := json.Unmarshal([]byte(v), &j)
46                 return j, err
47         case strings.HasPrefix(v, "\""):
48                 var j string
49                 err := json.Unmarshal([]byte(v), &j)
50                 return j, err
51         default:
52                 return v, nil
53         }
54         // TODO: Need to accept "?foo[]=bar&foo[]=baz" as
55         // foo=["bar","baz"]?
56 }
57
58 // Parse req as an Arvados V1 API request and return the request
59 // parameters.
60 //
61 // If the request has a parameter whose name is attrsKey (e.g.,
62 // "collection"), it is renamed to "attrs".
63 func (rtr *router) loadRequestParams(req *http.Request, attrsKey string) (map[string]interface{}, error) {
64         err := req.ParseForm()
65         if err == nil {
66                 err = req.ParseMultipartForm(int64(rtr.config.MaxRequestSize))
67                 if err == http.ErrNotMultipart {
68                         err = nil
69                 }
70         }
71         if err != nil {
72                 if err.Error() == "http: request body too large" {
73                         return nil, httpError(http.StatusRequestEntityTooLarge, err)
74                 } else {
75                         return nil, httpError(http.StatusBadRequest, err)
76                 }
77         }
78         params := map[string]interface{}{}
79
80         // Load parameters from req.Form, which (after
81         // req.ParseForm()) includes the query string and -- when
82         // Content-Type is application/x-www-form-urlencoded -- the
83         // request body.
84         for k, values := range req.Form {
85                 for _, v := range values {
86                         params[k], err = guessAndParse(k, v)
87                         if err != nil {
88                                 return nil, err
89                         }
90                 }
91         }
92
93         // Decode body as JSON if Content-Type request header is
94         // missing or application/json.
95         mt := req.Header.Get("Content-Type")
96         if ct, _, err := mime.ParseMediaType(mt); err != nil && mt != "" {
97                 return nil, fmt.Errorf("error parsing media type %q: %s", mt, err)
98         } else if (ct == "application/json" || mt == "") && req.ContentLength != 0 {
99                 jsonParams := map[string]interface{}{}
100                 err := json.NewDecoder(req.Body).Decode(&jsonParams)
101                 if err != nil {
102                         return nil, httpError(http.StatusBadRequest, err)
103                 }
104                 for k, v := range jsonParams {
105                         switch v := v.(type) {
106                         case string:
107                                 // The Ruby "arv" cli tool sends a
108                                 // JSON-encode params map with
109                                 // JSON-encoded values.
110                                 dec, err := guessAndParse(k, v)
111                                 if err != nil {
112                                         return nil, err
113                                 }
114                                 jsonParams[k] = dec
115                                 params[k] = dec
116                         default:
117                                 params[k] = v
118                         }
119                 }
120                 if attrsKey != "" && params[attrsKey] == nil {
121                         // Copy top-level parameters from JSON request
122                         // body into params[attrsKey]. Some SDKs rely
123                         // on this Rails API feature; see
124                         // https://api.rubyonrails.org/v5.2.1/classes/ActionController/ParamsWrapper.html
125                         params[attrsKey] = jsonParams
126                 }
127         }
128
129         for k, v := range mux.Vars(req) {
130                 params[k] = v
131         }
132
133         if v, ok := params[attrsKey]; ok && attrsKey != "" {
134                 params["attrs"] = v
135                 delete(params, attrsKey)
136         }
137
138         if order, ok := params["order"].(string); ok {
139                 // We must accept strings ("foo, bar desc") and arrays
140                 // (["foo", "bar desc"]) because RailsAPI does.
141                 // Convert to an array here before trying to unmarshal
142                 // into options structs.
143                 if order == "" {
144                         delete(params, "order")
145                 } else {
146                         params["order"] = strings.Split(order, ",")
147                 }
148         }
149
150         return params, nil
151 }
152
153 // Copy src to dst, using json as an intermediate format in order to
154 // invoke src's json-marshaling and dst's json-unmarshaling behaviors.
155 func (rtr *router) transcode(src interface{}, dst interface{}) error {
156         var errw error
157         pr, pw := io.Pipe()
158         go func() {
159                 defer pw.Close()
160                 errw = json.NewEncoder(pw).Encode(src)
161         }()
162         defer pr.Close()
163         err := json.NewDecoder(pr).Decode(dst)
164         if errw != nil {
165                 return errw
166         }
167         return err
168 }
169
170 var intParams = map[string]bool{
171         "limit":  true,
172         "offset": true,
173 }
174
175 var boolParams = map[string]bool{
176         "distinct":                true,
177         "ensure_unique_name":      true,
178         "include_trash":           true,
179         "include_old_versions":    true,
180         "redirect_to_new_user":    true,
181         "send_notification_email": true,
182         "bypass_federation":       true,
183         "recursive":               true,
184         "exclude_home_project":    true,
185         "no_forward":              true,
186 }
187
188 func stringToBool(s string) bool {
189         switch s {
190         case "", "false", "0":
191                 return false
192         default:
193                 return true
194         }
195 }