Merge branch 'master' into 15803-unsetup
[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 // Parse req as an Arvados V1 API request and return the request
20 // parameters.
21 //
22 // If the request has a parameter whose name is attrsKey (e.g.,
23 // "collection"), it is renamed to "attrs".
24 func (rtr *router) loadRequestParams(req *http.Request, attrsKey string) (map[string]interface{}, error) {
25         err := req.ParseForm()
26         if err != nil {
27                 return nil, httpError(http.StatusBadRequest, err)
28         }
29         params := map[string]interface{}{}
30
31         // Load parameters from req.Form, which (after
32         // req.ParseForm()) includes the query string and -- when
33         // Content-Type is application/x-www-form-urlencoded -- the
34         // request body.
35         for k, values := range req.Form {
36                 // All of these form values arrive as strings, so we
37                 // need some type-guessing to accept non-string
38                 // inputs:
39                 //
40                 // Values for parameters that take ints (limit=1) or
41                 // bools (include_trash=1) are parsed accordingly.
42                 //
43                 // "null" and "" are nil.
44                 //
45                 // Values that look like JSON objects, arrays, or
46                 // strings are parsed as JSON.
47                 //
48                 // The rest are left as strings.
49                 for _, v := range values {
50                         switch {
51                         case intParams[k]:
52                                 params[k], err = strconv.ParseInt(v, 10, 64)
53                                 if err != nil {
54                                         return nil, err
55                                 }
56                         case boolParams[k]:
57                                 params[k] = stringToBool(v)
58                         case v == "null" || v == "":
59                                 params[k] = nil
60                         case strings.HasPrefix(v, "["):
61                                 var j []interface{}
62                                 err := json.Unmarshal([]byte(v), &j)
63                                 if err != nil {
64                                         return nil, err
65                                 }
66                                 params[k] = j
67                         case strings.HasPrefix(v, "{"):
68                                 var j map[string]interface{}
69                                 err := json.Unmarshal([]byte(v), &j)
70                                 if err != nil {
71                                         return nil, err
72                                 }
73                                 params[k] = j
74                         case strings.HasPrefix(v, "\""):
75                                 var j string
76                                 err := json.Unmarshal([]byte(v), &j)
77                                 if err != nil {
78                                         return nil, err
79                                 }
80                                 params[k] = j
81                         default:
82                                 params[k] = v
83                         }
84                         // TODO: Need to accept "?foo[]=bar&foo[]=baz"
85                         // as foo=["bar","baz"]?
86                 }
87         }
88
89         // Decode body as JSON if Content-Type request header is
90         // missing or application/json.
91         mt := req.Header.Get("Content-Type")
92         if ct, _, err := mime.ParseMediaType(mt); err != nil && mt != "" {
93                 return nil, fmt.Errorf("error parsing media type %q: %s", mt, err)
94         } else if (ct == "application/json" || mt == "") && req.ContentLength != 0 {
95                 jsonParams := map[string]interface{}{}
96                 err := json.NewDecoder(req.Body).Decode(&jsonParams)
97                 if err != nil {
98                         return nil, httpError(http.StatusBadRequest, err)
99                 }
100                 for k, v := range jsonParams {
101                         params[k] = v
102                 }
103                 if attrsKey != "" && params[attrsKey] == nil {
104                         // Copy top-level parameters from JSON request
105                         // body into params[attrsKey]. Some SDKs rely
106                         // on this Rails API feature; see
107                         // https://api.rubyonrails.org/v5.2.1/classes/ActionController/ParamsWrapper.html
108                         params[attrsKey] = jsonParams
109                 }
110         }
111
112         for k, v := range mux.Vars(req) {
113                 params[k] = v
114         }
115
116         if v, ok := params[attrsKey]; ok && attrsKey != "" {
117                 params["attrs"] = v
118                 delete(params, attrsKey)
119         }
120
121         if order, ok := params["order"].(string); ok {
122                 // We must accept strings ("foo, bar desc") and arrays
123                 // (["foo", "bar desc"]) because RailsAPI does.
124                 // Convert to an array here before trying to unmarshal
125                 // into options structs.
126                 if order == "" {
127                         delete(params, "order")
128                 } else {
129                         params["order"] = strings.Split(order, ",")
130                 }
131         }
132
133         return params, nil
134 }
135
136 // Copy src to dst, using json as an intermediate format in order to
137 // invoke src's json-marshaling and dst's json-unmarshaling behaviors.
138 func (rtr *router) transcode(src interface{}, dst interface{}) error {
139         var errw error
140         pr, pw := io.Pipe()
141         go func() {
142                 defer pw.Close()
143                 errw = json.NewEncoder(pw).Encode(src)
144         }()
145         defer pr.Close()
146         err := json.NewDecoder(pr).Decode(dst)
147         if errw != nil {
148                 return errw
149         }
150         return err
151 }
152
153 var intParams = map[string]bool{
154         "limit":  true,
155         "offset": true,
156 }
157
158 var boolParams = map[string]bool{
159         "distinct":             true,
160         "ensure_unique_name":   true,
161         "include_trash":        true,
162         "include_old_versions": true,
163 }
164
165 func stringToBool(s string) bool {
166         switch s {
167         case "", "false", "0":
168                 return false
169         default:
170                 return true
171         }
172 }