701d53a26c1870d576ad1619bcb880f5a5988c29
[arvados.git] / lib / controller / router / router_test.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         "bytes"
9         "encoding/json"
10         "io"
11         "net/http"
12         "net/http/httptest"
13         "net/url"
14         "os"
15         "strings"
16         "testing"
17         "time"
18
19         "git.curoverse.com/arvados.git/lib/controller/rpc"
20         "git.curoverse.com/arvados.git/sdk/go/arvados"
21         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
22         "github.com/gorilla/mux"
23         check "gopkg.in/check.v1"
24 )
25
26 // Gocheck boilerplate
27 func Test(t *testing.T) {
28         check.TestingT(t)
29 }
30
31 var _ = check.Suite(&RouterSuite{})
32
33 type RouterSuite struct {
34         rtr  *router
35         stub arvadostest.APIStub
36 }
37
38 func (s *RouterSuite) SetUpTest(c *check.C) {
39         s.stub = arvadostest.APIStub{}
40         s.rtr = &router{
41                 mux: mux.NewRouter(),
42                 fed: &s.stub,
43         }
44         s.rtr.addRoutes()
45 }
46
47 func (s *RouterSuite) TestOptions(c *check.C) {
48         token := arvadostest.ActiveToken
49         for _, trial := range []struct {
50                 method       string
51                 path         string
52                 header       http.Header
53                 body         string
54                 shouldStatus int // zero value means 200
55                 shouldCall   string
56                 withOptions  interface{}
57         }{
58                 {
59                         method:      "GET",
60                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
61                         shouldCall:  "CollectionGet",
62                         withOptions: arvados.GetOptions{UUID: arvadostest.FooCollection},
63                 },
64                 {
65                         method:      "PUT",
66                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
67                         shouldCall:  "CollectionUpdate",
68                         withOptions: arvados.UpdateOptions{UUID: arvadostest.FooCollection},
69                 },
70                 {
71                         method:      "PATCH",
72                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
73                         shouldCall:  "CollectionUpdate",
74                         withOptions: arvados.UpdateOptions{UUID: arvadostest.FooCollection},
75                 },
76                 {
77                         method:      "DELETE",
78                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
79                         shouldCall:  "CollectionDelete",
80                         withOptions: arvados.DeleteOptions{UUID: arvadostest.FooCollection},
81                 },
82                 {
83                         method:      "POST",
84                         path:        "/arvados/v1/collections",
85                         shouldCall:  "CollectionCreate",
86                         withOptions: arvados.CreateOptions{},
87                 },
88                 {
89                         method:      "GET",
90                         path:        "/arvados/v1/collections",
91                         shouldCall:  "CollectionList",
92                         withOptions: arvados.ListOptions{Limit: -1},
93                 },
94                 {
95                         method:      "GET",
96                         path:        "/arvados/v1/collections?limit=123&offset=456&include_trash=true&include_old_versions=1",
97                         shouldCall:  "CollectionList",
98                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
99                 },
100                 {
101                         method:      "POST",
102                         path:        "/arvados/v1/collections?limit=123&_method=GET",
103                         body:        `{"offset":456,"include_trash":true,"include_old_versions":true}`,
104                         shouldCall:  "CollectionList",
105                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
106                 },
107                 {
108                         method:      "POST",
109                         path:        "/arvados/v1/collections?limit=123",
110                         body:        `{"offset":456,"include_trash":true,"include_old_versions":true}`,
111                         header:      http.Header{"X-Http-Method-Override": {"GET"}, "Content-Type": {"application/json"}},
112                         shouldCall:  "CollectionList",
113                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
114                 },
115                 {
116                         method:      "POST",
117                         path:        "/arvados/v1/collections?limit=123",
118                         body:        "offset=456&include_trash=true&include_old_versions=1&_method=GET",
119                         header:      http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
120                         shouldCall:  "CollectionList",
121                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
122                 },
123                 {
124                         method:       "PATCH",
125                         path:         "/arvados/v1/collections",
126                         shouldStatus: http.StatusMethodNotAllowed,
127                 },
128                 {
129                         method:       "PUT",
130                         path:         "/arvados/v1/collections",
131                         shouldStatus: http.StatusMethodNotAllowed,
132                 },
133                 {
134                         method:       "DELETE",
135                         path:         "/arvados/v1/collections",
136                         shouldStatus: http.StatusMethodNotAllowed,
137                 },
138         } {
139                 // Reset calls captured in previous trial
140                 s.stub = arvadostest.APIStub{}
141
142                 c.Logf("trial: %#v", trial)
143                 _, rr, _ := doRequest(c, s.rtr, token, trial.method, trial.path, trial.header, bytes.NewBufferString(trial.body))
144                 if trial.shouldStatus == 0 {
145                         c.Check(rr.Code, check.Equals, http.StatusOK)
146                 } else {
147                         c.Check(rr.Code, check.Equals, trial.shouldStatus)
148                 }
149                 calls := s.stub.Calls(nil)
150                 if trial.shouldCall == "" {
151                         c.Check(calls, check.HasLen, 0)
152                 } else if len(calls) != 1 {
153                         c.Check(calls, check.HasLen, 1)
154                 } else {
155                         c.Check(calls[0].Method, isMethodNamed, trial.shouldCall)
156                         c.Check(calls[0].Options, check.DeepEquals, trial.withOptions)
157                 }
158         }
159 }
160
161 var _ = check.Suite(&RouterIntegrationSuite{})
162
163 type RouterIntegrationSuite struct {
164         rtr *router
165 }
166
167 func (s *RouterIntegrationSuite) SetUpTest(c *check.C) {
168         cluster := &arvados.Cluster{}
169         cluster.TLS.Insecure = true
170         arvadostest.SetServiceURL(&cluster.Services.RailsAPI, "https://"+os.Getenv("ARVADOS_TEST_API_HOST"))
171         url, _ := url.Parse("https://" + os.Getenv("ARVADOS_TEST_API_HOST"))
172         s.rtr = New(rpc.NewConn("zzzzz", url, true, rpc.PassthroughTokenProvider))
173 }
174
175 func (s *RouterIntegrationSuite) TearDownSuite(c *check.C) {
176         err := arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil)
177         c.Check(err, check.IsNil)
178 }
179
180 func (s *RouterIntegrationSuite) TestCollectionResponses(c *check.C) {
181         token := arvadostest.ActiveTokenV2
182
183         // Check "get collection" response has "kind" key
184         _, rr, jresp := doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections`, nil, bytes.NewBufferString(`{"include_trash":true}`))
185         c.Check(rr.Code, check.Equals, http.StatusOK)
186         c.Check(jresp["items"], check.FitsTypeOf, []interface{}{})
187         c.Check(jresp["kind"], check.Equals, "arvados#collectionList")
188         c.Check(jresp["items"].([]interface{})[0].(map[string]interface{})["kind"], check.Equals, "arvados#collection")
189
190         // Check items in list response have a "kind" key regardless
191         // of whether a uuid/pdh is selected.
192         for _, selectj := range []string{
193                 ``,
194                 `,"select":["portable_data_hash"]`,
195                 `,"select":["name"]`,
196                 `,"select":["uuid"]`,
197         } {
198                 _, rr, jresp = doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections`, nil, bytes.NewBufferString(`{"where":{"uuid":["`+arvadostest.FooCollection+`"]}`+selectj+`}`))
199                 c.Check(rr.Code, check.Equals, http.StatusOK)
200                 c.Check(jresp["items"], check.FitsTypeOf, []interface{}{})
201                 c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
202                 c.Check(jresp["kind"], check.Equals, "arvados#collectionList")
203                 item0 := jresp["items"].([]interface{})[0].(map[string]interface{})
204                 c.Check(item0["kind"], check.Equals, "arvados#collection")
205                 if selectj == "" || strings.Contains(selectj, "portable_data_hash") {
206                         c.Check(item0["portable_data_hash"], check.Equals, arvadostest.FooCollectionPDH)
207                 } else {
208                         c.Check(item0["portable_data_hash"], check.IsNil)
209                 }
210                 if selectj == "" || strings.Contains(selectj, "name") {
211                         c.Check(item0["name"], check.FitsTypeOf, "")
212                 } else {
213                         c.Check(item0["name"], check.IsNil)
214                 }
215                 if selectj == "" || strings.Contains(selectj, "uuid") {
216                         c.Check(item0["uuid"], check.Equals, arvadostest.FooCollection)
217                 } else {
218                         c.Check(item0["uuid"], check.IsNil)
219                 }
220         }
221
222         // Check "create collection" response has "kind" key
223         _, rr, jresp = doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}, bytes.NewBufferString(`ensure_unique_name=true`))
224         c.Check(rr.Code, check.Equals, http.StatusOK)
225         c.Check(jresp["uuid"], check.FitsTypeOf, "")
226         c.Check(jresp["kind"], check.Equals, "arvados#collection")
227 }
228
229 func (s *RouterIntegrationSuite) TestContainerList(c *check.C) {
230         token := arvadostest.ActiveTokenV2
231
232         _, rr, jresp := doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?limit=0`, nil, nil)
233         c.Check(rr.Code, check.Equals, http.StatusOK)
234         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
235         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
236         c.Check(jresp["items"], check.NotNil)
237         c.Check(jresp["items"], check.HasLen, 0)
238
239         _, rr, jresp = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?filters=[["uuid","in",[]]]`, nil, nil)
240         c.Check(rr.Code, check.Equals, http.StatusOK)
241         c.Check(jresp["items_available"], check.Equals, float64(0))
242         c.Check(jresp["items"], check.NotNil)
243         c.Check(jresp["items"], check.HasLen, 0)
244
245         _, rr, jresp = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?limit=2&select=["uuid","command"]`, nil, nil)
246         c.Check(rr.Code, check.Equals, http.StatusOK)
247         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
248         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
249         c.Check(jresp["items"], check.HasLen, 2)
250         item0 := jresp["items"].([]interface{})[0].(map[string]interface{})
251         c.Check(item0["uuid"], check.HasLen, 27)
252         c.Check(item0["command"], check.FitsTypeOf, []interface{}{})
253         c.Check(item0["command"].([]interface{})[0], check.FitsTypeOf, "")
254         c.Check(item0["mounts"], check.IsNil)
255
256         _, rr, jresp = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers`, nil, nil)
257         c.Check(rr.Code, check.Equals, http.StatusOK)
258         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
259         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
260         avail := int(jresp["items_available"].(float64))
261         c.Check(jresp["items"], check.HasLen, avail)
262         item0 = jresp["items"].([]interface{})[0].(map[string]interface{})
263         c.Check(item0["uuid"], check.HasLen, 27)
264         c.Check(item0["command"], check.FitsTypeOf, []interface{}{})
265         c.Check(item0["command"].([]interface{})[0], check.FitsTypeOf, "")
266         c.Check(item0["mounts"], check.NotNil)
267 }
268
269 func (s *RouterIntegrationSuite) TestContainerLock(c *check.C) {
270         uuid := arvadostest.QueuedContainerUUID
271         token := arvadostest.AdminToken
272         _, rr, jresp := doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/lock", nil, nil)
273         c.Check(rr.Code, check.Equals, http.StatusOK)
274         c.Check(jresp["uuid"], check.HasLen, 27)
275         c.Check(jresp["state"], check.Equals, "Locked")
276         _, rr, jresp = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/lock", nil, nil)
277         c.Check(rr.Code, check.Equals, http.StatusUnprocessableEntity)
278         c.Check(rr.Body.String(), check.Not(check.Matches), `.*"uuid":.*`)
279         _, rr, jresp = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/unlock", nil, nil)
280         c.Check(rr.Code, check.Equals, http.StatusOK)
281         c.Check(jresp["uuid"], check.HasLen, 27)
282         c.Check(jresp["state"], check.Equals, "Queued")
283         c.Check(jresp["environment"], check.IsNil)
284         _, rr, jresp = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/unlock", nil, nil)
285         c.Check(rr.Code, check.Equals, http.StatusUnprocessableEntity)
286         c.Check(jresp["uuid"], check.IsNil)
287 }
288
289 func (s *RouterIntegrationSuite) TestFullTimestampsInResponse(c *check.C) {
290         uuid := arvadostest.CollectionReplicationDesired2Confirmed2UUID
291         token := arvadostest.ActiveTokenV2
292
293         _, rr, jresp := doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections/`+uuid, nil, nil)
294         c.Check(rr.Code, check.Equals, http.StatusOK)
295         c.Check(jresp["uuid"], check.Equals, uuid)
296         expectNS := map[string]int{
297                 "created_at":  596506000, // fixture says 596506247, but truncated by postgresql
298                 "modified_at": 596338000, // fixture says 596338465, but truncated by postgresql
299         }
300         for key, ns := range expectNS {
301                 mt, ok := jresp[key].(string)
302                 c.Logf("jresp[%q] == %q", key, mt)
303                 c.Assert(ok, check.Equals, true)
304                 t, err := time.Parse(time.RFC3339Nano, mt)
305                 c.Check(err, check.IsNil)
306                 c.Check(t.Nanosecond(), check.Equals, ns)
307         }
308 }
309
310 func (s *RouterIntegrationSuite) TestSelectParam(c *check.C) {
311         uuid := arvadostest.QueuedContainerUUID
312         token := arvadostest.ActiveTokenV2
313         for _, sel := range [][]string{
314                 {"uuid", "command"},
315                 {"uuid", "command", "uuid"},
316                 {"", "command", "uuid"},
317         } {
318                 j, err := json.Marshal(sel)
319                 c.Assert(err, check.IsNil)
320                 _, rr, resp := doRequest(c, s.rtr, token, "GET", "/arvados/v1/containers/"+uuid+"?select="+string(j), nil, nil)
321                 c.Check(rr.Code, check.Equals, http.StatusOK)
322
323                 c.Check(resp["kind"], check.Equals, "arvados#container")
324                 c.Check(resp["uuid"], check.HasLen, 27)
325                 c.Check(resp["command"], check.HasLen, 2)
326                 c.Check(resp["mounts"], check.IsNil)
327                 _, hasMounts := resp["mounts"]
328                 c.Check(hasMounts, check.Equals, false)
329         }
330 }
331
332 func (s *RouterIntegrationSuite) TestRouteNotFound(c *check.C) {
333         token := arvadostest.ActiveTokenV2
334         req := (&testReq{
335                 method: "POST",
336                 path:   "arvados/v1/collections/" + arvadostest.FooCollection + "/error404pls",
337                 token:  token,
338         }).Request()
339         rr := httptest.NewRecorder()
340         s.rtr.ServeHTTP(rr, req)
341         c.Check(rr.Code, check.Equals, http.StatusNotFound)
342         c.Logf("body: %q", rr.Body.String())
343         var j map[string]interface{}
344         err := json.Unmarshal(rr.Body.Bytes(), &j)
345         c.Check(err, check.IsNil)
346         c.Logf("decoded: %v", j)
347         c.Assert(j["errors"], check.FitsTypeOf, []interface{}{})
348         c.Check(j["errors"].([]interface{})[0], check.Equals, "API endpoint not found")
349 }
350
351 func (s *RouterIntegrationSuite) TestCORS(c *check.C) {
352         token := arvadostest.ActiveTokenV2
353         req := (&testReq{
354                 method: "OPTIONS",
355                 path:   "arvados/v1/collections/" + arvadostest.FooCollection,
356                 header: http.Header{"Origin": {"https://example.com"}},
357                 token:  token,
358         }).Request()
359         rr := httptest.NewRecorder()
360         s.rtr.ServeHTTP(rr, req)
361         c.Check(rr.Code, check.Equals, http.StatusOK)
362         c.Check(rr.Body.String(), check.HasLen, 0)
363         c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "*")
364         for _, hdr := range []string{"Authorization", "Content-Type"} {
365                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Matches, ".*"+hdr+".*")
366         }
367         for _, method := range []string{"GET", "HEAD", "PUT", "POST", "PATCH", "DELETE"} {
368                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Matches, ".*"+method+".*")
369         }
370
371         for _, unsafe := range []string{"login", "logout", "auth", "auth/foo", "login/?blah"} {
372                 req := (&testReq{
373                         method: "OPTIONS",
374                         path:   unsafe,
375                         header: http.Header{"Origin": {"https://example.com"}},
376                         token:  token,
377                 }).Request()
378                 rr := httptest.NewRecorder()
379                 s.rtr.ServeHTTP(rr, req)
380                 c.Check(rr.Code, check.Equals, http.StatusOK)
381                 c.Check(rr.Body.String(), check.HasLen, 0)
382                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
383                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
384                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
385
386                 req = (&testReq{
387                         method: "POST",
388                         path:   unsafe,
389                         header: http.Header{"Origin": {"https://example.com"}},
390                         token:  token,
391                 }).Request()
392                 rr = httptest.NewRecorder()
393                 s.rtr.ServeHTTP(rr, req)
394                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
395                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
396                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
397         }
398 }
399
400 func doRequest(c *check.C, rtr http.Handler, token, method, path string, hdrs http.Header, body io.Reader) (*http.Request, *httptest.ResponseRecorder, map[string]interface{}) {
401         req := httptest.NewRequest(method, path, body)
402         for k, v := range hdrs {
403                 req.Header[k] = v
404         }
405         req.Header.Set("Authorization", "Bearer "+token)
406         rr := httptest.NewRecorder()
407         rtr.ServeHTTP(rr, req)
408         c.Logf("response body: %s", rr.Body.String())
409         var jresp map[string]interface{}
410         err := json.Unmarshal(rr.Body.Bytes(), &jresp)
411         c.Check(err, check.IsNil)
412         return req, rr, jresp
413 }