15954: Start websocket and keepstore.
[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.arvados.org/arvados.git/lib/controller/rpc"
20         "git.arvados.org/arvados.git/sdk/go/arvados"
21         "git.arvados.org/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) TestWritableBy(c *check.C) {
290         _, rr, jresp := doRequest(c, s.rtr, arvadostest.ActiveTokenV2, "GET", `/arvados/v1/users/`+arvadostest.ActiveUserUUID, nil, nil)
291         c.Check(rr.Code, check.Equals, http.StatusOK)
292         c.Check(jresp["writable_by"], check.DeepEquals, []interface{}{"zzzzz-tpzed-000000000000000", "zzzzz-tpzed-xurymjxw79nv3jz", "zzzzz-j7d0g-48foin4vonvc2at"})
293 }
294
295 func (s *RouterIntegrationSuite) TestFullTimestampsInResponse(c *check.C) {
296         uuid := arvadostest.CollectionReplicationDesired2Confirmed2UUID
297         token := arvadostest.ActiveTokenV2
298
299         _, rr, jresp := doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections/`+uuid, nil, nil)
300         c.Check(rr.Code, check.Equals, http.StatusOK)
301         c.Check(jresp["uuid"], check.Equals, uuid)
302         expectNS := map[string]int{
303                 "created_at":  596506000, // fixture says 596506247, but truncated by postgresql
304                 "modified_at": 596338000, // fixture says 596338465, but truncated by postgresql
305         }
306         for key, ns := range expectNS {
307                 mt, ok := jresp[key].(string)
308                 c.Logf("jresp[%q] == %q", key, mt)
309                 c.Assert(ok, check.Equals, true)
310                 t, err := time.Parse(time.RFC3339Nano, mt)
311                 c.Check(err, check.IsNil)
312                 c.Check(t.Nanosecond(), check.Equals, ns)
313         }
314 }
315
316 func (s *RouterIntegrationSuite) TestSelectParam(c *check.C) {
317         uuid := arvadostest.QueuedContainerUUID
318         token := arvadostest.ActiveTokenV2
319         for _, sel := range [][]string{
320                 {"uuid", "command"},
321                 {"uuid", "command", "uuid"},
322                 {"", "command", "uuid"},
323         } {
324                 j, err := json.Marshal(sel)
325                 c.Assert(err, check.IsNil)
326                 _, rr, resp := doRequest(c, s.rtr, token, "GET", "/arvados/v1/containers/"+uuid+"?select="+string(j), nil, nil)
327                 c.Check(rr.Code, check.Equals, http.StatusOK)
328
329                 c.Check(resp["kind"], check.Equals, "arvados#container")
330                 c.Check(resp["etag"], check.FitsTypeOf, "")
331                 c.Check(resp["etag"], check.Not(check.Equals), "")
332                 c.Check(resp["uuid"], check.HasLen, 27)
333                 c.Check(resp["command"], check.HasLen, 2)
334                 c.Check(resp["mounts"], check.IsNil)
335                 _, hasMounts := resp["mounts"]
336                 c.Check(hasMounts, check.Equals, false)
337         }
338 }
339
340 func (s *RouterIntegrationSuite) TestHEAD(c *check.C) {
341         _, rr, _ := doRequest(c, s.rtr, arvadostest.ActiveTokenV2, "HEAD", "/arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil, nil)
342         c.Check(rr.Code, check.Equals, http.StatusOK)
343 }
344
345 func (s *RouterIntegrationSuite) TestRouteNotFound(c *check.C) {
346         token := arvadostest.ActiveTokenV2
347         req := (&testReq{
348                 method: "POST",
349                 path:   "arvados/v1/collections/" + arvadostest.FooCollection + "/error404pls",
350                 token:  token,
351         }).Request()
352         rr := httptest.NewRecorder()
353         s.rtr.ServeHTTP(rr, req)
354         c.Check(rr.Code, check.Equals, http.StatusNotFound)
355         c.Logf("body: %q", rr.Body.String())
356         var j map[string]interface{}
357         err := json.Unmarshal(rr.Body.Bytes(), &j)
358         c.Check(err, check.IsNil)
359         c.Logf("decoded: %v", j)
360         c.Assert(j["errors"], check.FitsTypeOf, []interface{}{})
361         c.Check(j["errors"].([]interface{})[0], check.Equals, "API endpoint not found")
362 }
363
364 func (s *RouterIntegrationSuite) TestCORS(c *check.C) {
365         token := arvadostest.ActiveTokenV2
366         req := (&testReq{
367                 method: "OPTIONS",
368                 path:   "arvados/v1/collections/" + arvadostest.FooCollection,
369                 header: http.Header{"Origin": {"https://example.com"}},
370                 token:  token,
371         }).Request()
372         rr := httptest.NewRecorder()
373         s.rtr.ServeHTTP(rr, req)
374         c.Check(rr.Code, check.Equals, http.StatusOK)
375         c.Check(rr.Body.String(), check.HasLen, 0)
376         c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "*")
377         for _, hdr := range []string{"Authorization", "Content-Type"} {
378                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Matches, ".*"+hdr+".*")
379         }
380         for _, method := range []string{"GET", "HEAD", "PUT", "POST", "PATCH", "DELETE"} {
381                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Matches, ".*"+method+".*")
382         }
383
384         for _, unsafe := range []string{"login", "logout", "auth", "auth/foo", "login/?blah"} {
385                 req := (&testReq{
386                         method: "OPTIONS",
387                         path:   unsafe,
388                         header: http.Header{"Origin": {"https://example.com"}},
389                         token:  token,
390                 }).Request()
391                 rr := httptest.NewRecorder()
392                 s.rtr.ServeHTTP(rr, req)
393                 c.Check(rr.Code, check.Equals, http.StatusOK)
394                 c.Check(rr.Body.String(), check.HasLen, 0)
395                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
396                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
397                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
398
399                 req = (&testReq{
400                         method: "POST",
401                         path:   unsafe,
402                         header: http.Header{"Origin": {"https://example.com"}},
403                         token:  token,
404                 }).Request()
405                 rr = httptest.NewRecorder()
406                 s.rtr.ServeHTTP(rr, req)
407                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
408                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
409                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
410         }
411 }
412
413 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{}) {
414         req := httptest.NewRequest(method, path, body)
415         for k, v := range hdrs {
416                 req.Header[k] = v
417         }
418         req.Header.Set("Authorization", "Bearer "+token)
419         rr := httptest.NewRecorder()
420         rtr.ServeHTTP(rr, req)
421         c.Logf("response body: %s", rr.Body.String())
422         var jresp map[string]interface{}
423         err := json.Unmarshal(rr.Body.Bytes(), &jresp)
424         c.Check(err, check.IsNil)
425         return req, rr, jresp
426 }