19889: Serve live logs via webdav.
[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                 backend: &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                 comment      string // unparsed -- only used to help match test failures to trials
51                 method       string
52                 path         string
53                 header       http.Header
54                 body         string
55                 shouldStatus int // zero value means 200
56                 shouldCall   string
57                 withOptions  interface{}
58         }{
59                 {
60                         method:      "GET",
61                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
62                         shouldCall:  "CollectionGet",
63                         withOptions: arvados.GetOptions{UUID: arvadostest.FooCollection},
64                 },
65                 {
66                         method:      "PUT",
67                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
68                         shouldCall:  "CollectionUpdate",
69                         withOptions: arvados.UpdateOptions{UUID: arvadostest.FooCollection},
70                 },
71                 {
72                         method:      "PATCH",
73                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
74                         shouldCall:  "CollectionUpdate",
75                         withOptions: arvados.UpdateOptions{UUID: arvadostest.FooCollection},
76                 },
77                 {
78                         method:      "DELETE",
79                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection,
80                         shouldCall:  "CollectionDelete",
81                         withOptions: arvados.DeleteOptions{UUID: arvadostest.FooCollection},
82                 },
83                 {
84                         method:      "POST",
85                         path:        "/arvados/v1/collections",
86                         shouldCall:  "CollectionCreate",
87                         withOptions: arvados.CreateOptions{},
88                 },
89                 {
90                         method:      "GET",
91                         path:        "/arvados/v1/collections",
92                         shouldCall:  "CollectionList",
93                         withOptions: arvados.ListOptions{Limit: -1},
94                 },
95                 {
96                         method:      "GET",
97                         path:        "/arvados/v1/api_client_authorizations",
98                         shouldCall:  "APIClientAuthorizationList",
99                         withOptions: arvados.ListOptions{Limit: -1},
100                 },
101                 {
102                         method:      "GET",
103                         path:        "/arvados/v1/collections?limit=123&offset=456&include_trash=true&include_old_versions=1",
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&_method=GET",
110                         body:        `{"offset":456,"include_trash":true,"include_old_versions":true}`,
111                         shouldCall:  "CollectionList",
112                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
113                 },
114                 {
115                         method:      "POST",
116                         path:        "/arvados/v1/collections?limit=123",
117                         body:        `{"offset":456,"include_trash":true,"include_old_versions":true}`,
118                         header:      http.Header{"X-Http-Method-Override": {"GET"}, "Content-Type": {"application/json"}},
119                         shouldCall:  "CollectionList",
120                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
121                 },
122                 {
123                         method:      "POST",
124                         path:        "/arvados/v1/collections?limit=123",
125                         body:        "offset=456&include_trash=true&include_old_versions=1&_method=GET",
126                         header:      http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
127                         shouldCall:  "CollectionList",
128                         withOptions: arvados.ListOptions{Limit: 123, Offset: 456, IncludeTrash: true, IncludeOldVersions: true},
129                 },
130                 {
131                         comment:     "form-encoded expression filter in query string",
132                         method:      "GET",
133                         path:        "/arvados/v1/collections?filters=[%22(foo<bar)%22]",
134                         shouldCall:  "CollectionList",
135                         withOptions: arvados.ListOptions{Limit: -1, Filters: []arvados.Filter{{"(foo<bar)", "=", true}}},
136                 },
137                 {
138                         comment:     "form-encoded expression filter in POST body",
139                         method:      "POST",
140                         path:        "/arvados/v1/collections",
141                         body:        "filters=[\"(foo<bar)\"]&_method=GET",
142                         header:      http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
143                         shouldCall:  "CollectionList",
144                         withOptions: arvados.ListOptions{Limit: -1, Filters: []arvados.Filter{{"(foo<bar)", "=", true}}},
145                 },
146                 {
147                         comment:     "json-encoded expression filter in POST body",
148                         method:      "POST",
149                         path:        "/arvados/v1/collections?_method=GET",
150                         body:        `{"filters":["(foo<bar)",["bar","=","baz"]],"limit":2}`,
151                         header:      http.Header{"Content-Type": {"application/json"}},
152                         shouldCall:  "CollectionList",
153                         withOptions: arvados.ListOptions{Limit: 2, Filters: []arvados.Filter{{"(foo<bar)", "=", true}, {"bar", "=", "baz"}}},
154                 },
155                 {
156                         comment:     "json-encoded select param in query string",
157                         method:      "GET",
158                         path:        "/arvados/v1/collections/" + arvadostest.FooCollection + "?select=[%22portable_data_hash%22]",
159                         shouldCall:  "CollectionGet",
160                         withOptions: arvados.GetOptions{UUID: arvadostest.FooCollection, Select: []string{"portable_data_hash"}},
161                 },
162                 {
163                         method:       "PATCH",
164                         path:         "/arvados/v1/collections",
165                         shouldStatus: http.StatusMethodNotAllowed,
166                 },
167                 {
168                         method:       "PUT",
169                         path:         "/arvados/v1/collections",
170                         shouldStatus: http.StatusMethodNotAllowed,
171                 },
172                 {
173                         method:       "DELETE",
174                         path:         "/arvados/v1/collections",
175                         shouldStatus: http.StatusMethodNotAllowed,
176                 },
177                 {
178                         comment:    "container log webdav GET root",
179                         method:     "GET",
180                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log/",
181                         shouldCall: "ContainerLog",
182                         withOptions: arvados.ContainerLogOptions{
183                                 UUID: arvadostest.CompletedContainerUUID,
184                                 WebDAVOptions: arvados.WebDAVOptions{
185                                         Method: "GET",
186                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
187                                         Path:   "/"}},
188                 },
189                 {
190                         comment:    "container log webdav GET root without trailing slash",
191                         method:     "GET",
192                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log",
193                         shouldCall: "ContainerLog",
194                         withOptions: arvados.ContainerLogOptions{
195                                 UUID: arvadostest.CompletedContainerUUID,
196                                 WebDAVOptions: arvados.WebDAVOptions{
197                                         Method: "GET",
198                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
199                                         Path:   ""}},
200                 },
201                 {
202                         comment:    "container log webdav OPTIONS root",
203                         method:     "OPTIONS",
204                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log/",
205                         shouldCall: "ContainerLog",
206                         withOptions: arvados.ContainerLogOptions{
207                                 UUID: arvadostest.CompletedContainerUUID,
208                                 WebDAVOptions: arvados.WebDAVOptions{
209                                         Method: "OPTIONS",
210                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
211                                         Path:   "/"}},
212                 },
213                 {
214                         comment:    "container log webdav OPTIONS root without trailing slash",
215                         method:     "OPTIONS",
216                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log",
217                         shouldCall: "ContainerLog",
218                         withOptions: arvados.ContainerLogOptions{
219                                 UUID: arvadostest.CompletedContainerUUID,
220                                 WebDAVOptions: arvados.WebDAVOptions{
221                                         Method: "OPTIONS",
222                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
223                                         Path:   ""}},
224                 },
225                 {
226                         comment:    "container log webdav PROPFIND root",
227                         method:     "PROPFIND",
228                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log/",
229                         shouldCall: "ContainerLog",
230                         withOptions: arvados.ContainerLogOptions{
231                                 UUID: arvadostest.CompletedContainerUUID,
232                                 WebDAVOptions: arvados.WebDAVOptions{
233                                         Method: "PROPFIND",
234                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
235                                         Path:   "/"}},
236                 },
237                 {
238                         comment:    "container log webdav PROPFIND root without trailing slash",
239                         method:     "PROPFIND",
240                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log",
241                         shouldCall: "ContainerLog",
242                         withOptions: arvados.ContainerLogOptions{
243                                 UUID: arvadostest.CompletedContainerUUID,
244                                 WebDAVOptions: arvados.WebDAVOptions{
245                                         Method: "PROPFIND",
246                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
247                                         Path:   ""}},
248                 },
249                 {
250                         comment:    "container log webdav no_forward=true",
251                         method:     "GET",
252                         path:       "/arvados/v1/containers/" + arvadostest.CompletedContainerUUID + "/log/?no_forward=true",
253                         shouldCall: "ContainerLog",
254                         withOptions: arvados.ContainerLogOptions{
255                                 UUID:      arvadostest.CompletedContainerUUID,
256                                 NoForward: true,
257                                 WebDAVOptions: arvados.WebDAVOptions{
258                                         Method: "GET",
259                                         Header: http.Header{"Authorization": {"Bearer " + arvadostest.ActiveToken}},
260                                         Path:   "/"}},
261                 },
262         } {
263                 // Reset calls captured in previous trial
264                 s.stub = arvadostest.APIStub{}
265
266                 c.Logf("trial: %+v", trial)
267                 comment := check.Commentf("trial comment: %s", trial.comment)
268
269                 _, rr := doRequest(c, s.rtr, token, trial.method, trial.path, trial.header, bytes.NewBufferString(trial.body), nil)
270                 if trial.shouldStatus == 0 {
271                         c.Check(rr.Code, check.Equals, http.StatusOK, comment)
272                 } else {
273                         c.Check(rr.Code, check.Equals, trial.shouldStatus, comment)
274                 }
275                 calls := s.stub.Calls(nil)
276                 if trial.shouldCall == "" {
277                         c.Check(calls, check.HasLen, 0, comment)
278                 } else if len(calls) != 1 {
279                         c.Check(calls, check.HasLen, 1, comment)
280                 } else {
281                         c.Check(calls[0].Method, isMethodNamed, trial.shouldCall, comment)
282                         c.Check(calls[0].Options, check.DeepEquals, trial.withOptions, comment)
283                 }
284         }
285 }
286
287 var _ = check.Suite(&RouterIntegrationSuite{})
288
289 type RouterIntegrationSuite struct {
290         rtr *router
291 }
292
293 func (s *RouterIntegrationSuite) SetUpTest(c *check.C) {
294         cluster := &arvados.Cluster{}
295         cluster.TLS.Insecure = true
296         arvadostest.SetServiceURL(&cluster.Services.RailsAPI, "https://"+os.Getenv("ARVADOS_TEST_API_HOST"))
297         url, _ := url.Parse("https://" + os.Getenv("ARVADOS_TEST_API_HOST"))
298         s.rtr = New(rpc.NewConn("zzzzz", url, true, rpc.PassthroughTokenProvider), Config{})
299 }
300
301 func (s *RouterIntegrationSuite) TearDownSuite(c *check.C) {
302         err := arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil)
303         c.Check(err, check.IsNil)
304 }
305
306 func (s *RouterIntegrationSuite) TestCollectionResponses(c *check.C) {
307         token := arvadostest.ActiveTokenV2
308
309         // Check "get collection" response has "kind" key
310         jresp := map[string]interface{}{}
311         _, rr := doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections`, nil, bytes.NewBufferString(`{"include_trash":true}`), jresp)
312         c.Check(rr.Code, check.Equals, http.StatusOK)
313         c.Check(jresp["items"], check.FitsTypeOf, []interface{}{})
314         c.Check(jresp["kind"], check.Equals, "arvados#collectionList")
315         c.Check(jresp["items"].([]interface{})[0].(map[string]interface{})["kind"], check.Equals, "arvados#collection")
316
317         // Check items in list response have a "kind" key regardless
318         // of whether a uuid/pdh is selected.
319         for _, selectj := range []string{
320                 ``,
321                 `,"select":["portable_data_hash"]`,
322                 `,"select":["name"]`,
323                 `,"select":["uuid"]`,
324         } {
325                 jresp := map[string]interface{}{}
326                 _, rr = doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections`, nil, bytes.NewBufferString(`{"where":{"uuid":["`+arvadostest.FooCollection+`"]}`+selectj+`}`), jresp)
327                 c.Check(rr.Code, check.Equals, http.StatusOK)
328                 c.Check(jresp["items"], check.FitsTypeOf, []interface{}{})
329                 c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
330                 c.Check(jresp["kind"], check.Equals, "arvados#collectionList")
331                 item0 := jresp["items"].([]interface{})[0].(map[string]interface{})
332                 c.Check(item0["kind"], check.Equals, "arvados#collection")
333                 if selectj == "" || strings.Contains(selectj, "portable_data_hash") {
334                         c.Check(item0["portable_data_hash"], check.Equals, arvadostest.FooCollectionPDH)
335                 } else {
336                         c.Check(item0["portable_data_hash"], check.IsNil)
337                 }
338                 if selectj == "" || strings.Contains(selectj, "name") {
339                         c.Check(item0["name"], check.FitsTypeOf, "")
340                 } else {
341                         c.Check(item0["name"], check.IsNil)
342                 }
343                 if selectj == "" || strings.Contains(selectj, "uuid") {
344                         c.Check(item0["uuid"], check.Equals, arvadostest.FooCollection)
345                 } else {
346                         c.Check(item0["uuid"], check.IsNil)
347                 }
348         }
349
350         // Check "create collection" response has "kind" key
351         jresp = map[string]interface{}{}
352         _, rr = doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}, bytes.NewBufferString(`ensure_unique_name=true`), jresp)
353         c.Check(rr.Code, check.Equals, http.StatusOK)
354         c.Check(jresp["uuid"], check.FitsTypeOf, "")
355         c.Check(jresp["kind"], check.Equals, "arvados#collection")
356 }
357
358 func (s *RouterIntegrationSuite) TestMaxRequestSize(c *check.C) {
359         token := arvadostest.ActiveTokenV2
360         for _, maxRequestSize := range []int{
361                 // Ensure 5M limit is enforced.
362                 5000000,
363                 // Ensure 50M limit is enforced, and that a >25M body
364                 // is accepted even though the default Go request size
365                 // limit is 10M.
366                 50000000,
367         } {
368                 s.rtr.config.MaxRequestSize = maxRequestSize
369                 okstr := "a"
370                 for len(okstr) < maxRequestSize/2 {
371                         okstr = okstr + okstr
372                 }
373
374                 hdr := http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}
375
376                 body := bytes.NewBufferString(url.Values{"foo_bar": {okstr}}.Encode())
377                 _, rr := doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, hdr, body, nil)
378                 c.Check(rr.Code, check.Equals, http.StatusOK)
379
380                 body = bytes.NewBufferString(url.Values{"foo_bar": {okstr + okstr}}.Encode())
381                 _, rr = doRequest(c, s.rtr, token, "POST", `/arvados/v1/collections`, hdr, body, nil)
382                 c.Check(rr.Code, check.Equals, http.StatusRequestEntityTooLarge)
383         }
384 }
385
386 func (s *RouterIntegrationSuite) TestContainerList(c *check.C) {
387         token := arvadostest.ActiveTokenV2
388
389         jresp := map[string]interface{}{}
390         _, rr := doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?limit=0`, nil, nil, jresp)
391         c.Check(rr.Code, check.Equals, http.StatusOK)
392         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
393         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
394         c.Check(jresp["items"], check.NotNil)
395         c.Check(jresp["items"], check.HasLen, 0)
396
397         jresp = map[string]interface{}{}
398         _, rr = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?filters=[["uuid","in",[]]]`, nil, nil, jresp)
399         c.Check(rr.Code, check.Equals, http.StatusOK)
400         c.Check(jresp["items_available"], check.Equals, float64(0))
401         c.Check(jresp["items"], check.NotNil)
402         c.Check(jresp["items"], check.HasLen, 0)
403
404         jresp = map[string]interface{}{}
405         _, rr = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers?limit=2&select=["uuid","command"]`, nil, nil, jresp)
406         c.Check(rr.Code, check.Equals, http.StatusOK)
407         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
408         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
409         c.Check(jresp["items"], check.HasLen, 2)
410         item0 := jresp["items"].([]interface{})[0].(map[string]interface{})
411         c.Check(item0["uuid"], check.HasLen, 27)
412         c.Check(item0["command"], check.FitsTypeOf, []interface{}{})
413         c.Check(item0["command"].([]interface{})[0], check.FitsTypeOf, "")
414         c.Check(item0["mounts"], check.IsNil)
415
416         jresp = map[string]interface{}{}
417         _, rr = doRequest(c, s.rtr, token, "GET", `/arvados/v1/containers`, nil, nil, jresp)
418         c.Check(rr.Code, check.Equals, http.StatusOK)
419         c.Check(jresp["items_available"], check.FitsTypeOf, float64(0))
420         c.Check(jresp["items_available"].(float64) > 2, check.Equals, true)
421         avail := int(jresp["items_available"].(float64))
422         c.Check(jresp["items"], check.HasLen, avail)
423         item0 = jresp["items"].([]interface{})[0].(map[string]interface{})
424         c.Check(item0["uuid"], check.HasLen, 27)
425         c.Check(item0["command"], check.FitsTypeOf, []interface{}{})
426         c.Check(item0["command"].([]interface{})[0], check.FitsTypeOf, "")
427         c.Check(item0["mounts"], check.NotNil)
428 }
429
430 func (s *RouterIntegrationSuite) TestContainerLock(c *check.C) {
431         uuid := arvadostest.QueuedContainerUUID
432         token := arvadostest.AdminToken
433
434         jresp := map[string]interface{}{}
435         _, rr := doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/lock", nil, nil, jresp)
436         c.Check(rr.Code, check.Equals, http.StatusOK)
437         c.Check(jresp["uuid"], check.HasLen, 27)
438         c.Check(jresp["state"], check.Equals, "Locked")
439
440         _, rr = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/lock", nil, nil, nil)
441         c.Check(rr.Code, check.Equals, http.StatusUnprocessableEntity)
442         c.Check(rr.Body.String(), check.Not(check.Matches), `.*"uuid":.*`)
443
444         jresp = map[string]interface{}{}
445         _, rr = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/unlock", nil, nil, jresp)
446         c.Check(rr.Code, check.Equals, http.StatusOK)
447         c.Check(jresp["uuid"], check.HasLen, 27)
448         c.Check(jresp["state"], check.Equals, "Queued")
449         c.Check(jresp["environment"], check.IsNil)
450
451         jresp = map[string]interface{}{}
452         _, rr = doRequest(c, s.rtr, token, "POST", "/arvados/v1/containers/"+uuid+"/unlock", nil, nil, jresp)
453         c.Check(rr.Code, check.Equals, http.StatusUnprocessableEntity)
454         c.Check(jresp["uuid"], check.IsNil)
455 }
456
457 func (s *RouterIntegrationSuite) TestWritableBy(c *check.C) {
458         jresp := map[string]interface{}{}
459         _, rr := doRequest(c, s.rtr, arvadostest.ActiveTokenV2, "GET", `/arvados/v1/users/`+arvadostest.ActiveUserUUID, nil, nil, jresp)
460         c.Check(rr.Code, check.Equals, http.StatusOK)
461         c.Check(jresp["writable_by"], check.DeepEquals, []interface{}{"zzzzz-tpzed-000000000000000", "zzzzz-tpzed-xurymjxw79nv3jz", "zzzzz-j7d0g-48foin4vonvc2at"})
462 }
463
464 func (s *RouterIntegrationSuite) TestFullTimestampsInResponse(c *check.C) {
465         uuid := arvadostest.CollectionReplicationDesired2Confirmed2UUID
466         token := arvadostest.ActiveTokenV2
467
468         jresp := map[string]interface{}{}
469         _, rr := doRequest(c, s.rtr, token, "GET", `/arvados/v1/collections/`+uuid, nil, nil, jresp)
470         c.Check(rr.Code, check.Equals, http.StatusOK)
471         c.Check(jresp["uuid"], check.Equals, uuid)
472         expectNS := map[string]int{
473                 "created_at":  596506000, // fixture says 596506247, but truncated by postgresql
474                 "modified_at": 596338000, // fixture says 596338465, but truncated by postgresql
475         }
476         for key, ns := range expectNS {
477                 mt, ok := jresp[key].(string)
478                 c.Logf("jresp[%q] == %q", key, mt)
479                 c.Assert(ok, check.Equals, true)
480                 t, err := time.Parse(time.RFC3339Nano, mt)
481                 c.Check(err, check.IsNil)
482                 c.Check(t.Nanosecond(), check.Equals, ns)
483         }
484 }
485
486 func (s *RouterIntegrationSuite) TestSelectParam(c *check.C) {
487         uuid := arvadostest.QueuedContainerUUID
488         token := arvadostest.ActiveTokenV2
489         // GET
490         for _, sel := range [][]string{
491                 {"uuid", "command"},
492                 {"uuid", "command", "uuid"},
493         } {
494                 j, err := json.Marshal(sel)
495                 c.Assert(err, check.IsNil)
496                 jresp := map[string]interface{}{}
497                 _, rr := doRequest(c, s.rtr, token, "GET", "/arvados/v1/containers/"+uuid+"?select="+string(j), nil, nil, jresp)
498                 c.Check(rr.Code, check.Equals, http.StatusOK)
499
500                 c.Check(jresp["kind"], check.Equals, "arvados#container")
501                 c.Check(jresp["uuid"], check.HasLen, 27)
502                 c.Check(jresp["command"], check.HasLen, 2)
503                 c.Check(jresp["mounts"], check.IsNil)
504                 _, hasMounts := jresp["mounts"]
505                 c.Check(hasMounts, check.Equals, false)
506         }
507         // POST & PUT
508         uuid = arvadostest.FooCollection
509         j, err := json.Marshal([]string{"uuid", "description"})
510         c.Assert(err, check.IsNil)
511         for _, method := range []string{"PUT", "POST"} {
512                 desc := "Today is " + time.Now().String()
513                 reqBody := "{\"description\":\"" + desc + "\"}"
514                 jresp := map[string]interface{}{}
515                 var rr *httptest.ResponseRecorder
516                 if method == "PUT" {
517                         _, rr = doRequest(c, s.rtr, token, method, "/arvados/v1/collections/"+uuid+"?select="+string(j), nil, bytes.NewReader([]byte(reqBody)), jresp)
518                 } else {
519                         _, rr = doRequest(c, s.rtr, token, method, "/arvados/v1/collections?select="+string(j), nil, bytes.NewReader([]byte(reqBody)), jresp)
520                 }
521                 c.Check(rr.Code, check.Equals, http.StatusOK)
522                 c.Check(jresp["kind"], check.Equals, "arvados#collection")
523                 c.Check(jresp["uuid"], check.HasLen, 27)
524                 c.Check(jresp["description"], check.Equals, desc)
525                 c.Check(jresp["manifest_text"], check.IsNil)
526         }
527 }
528
529 func (s *RouterIntegrationSuite) TestHEAD(c *check.C) {
530         _, rr := doRequest(c, s.rtr, arvadostest.ActiveTokenV2, "HEAD", "/arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil, nil, nil)
531         c.Check(rr.Code, check.Equals, http.StatusOK)
532 }
533
534 func (s *RouterIntegrationSuite) TestRouteNotFound(c *check.C) {
535         token := arvadostest.ActiveTokenV2
536         req := (&testReq{
537                 method: "POST",
538                 path:   "arvados/v1/collections/" + arvadostest.FooCollection + "/error404pls",
539                 token:  token,
540         }).Request()
541         rr := httptest.NewRecorder()
542         s.rtr.ServeHTTP(rr, req)
543         c.Check(rr.Code, check.Equals, http.StatusNotFound)
544         c.Logf("body: %q", rr.Body.String())
545         var j map[string]interface{}
546         err := json.Unmarshal(rr.Body.Bytes(), &j)
547         c.Check(err, check.IsNil)
548         c.Logf("decoded: %v", j)
549         c.Assert(j["errors"], check.FitsTypeOf, []interface{}{})
550         c.Check(j["errors"].([]interface{})[0], check.Equals, "API endpoint not found")
551 }
552
553 func (s *RouterIntegrationSuite) TestCORS(c *check.C) {
554         token := arvadostest.ActiveTokenV2
555         req := (&testReq{
556                 method: "OPTIONS",
557                 path:   "arvados/v1/collections/" + arvadostest.FooCollection,
558                 header: http.Header{"Origin": {"https://example.com"}},
559                 token:  token,
560         }).Request()
561         rr := httptest.NewRecorder()
562         s.rtr.ServeHTTP(rr, req)
563         c.Check(rr.Code, check.Equals, http.StatusOK)
564         c.Check(rr.Body.String(), check.HasLen, 0)
565         c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "*")
566         for _, hdr := range []string{"Authorization", "Content-Type"} {
567                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Matches, ".*"+hdr+".*")
568         }
569         for _, method := range []string{"GET", "HEAD", "PUT", "POST", "PATCH", "DELETE"} {
570                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Matches, ".*"+method+".*")
571         }
572
573         for _, unsafe := range []string{"login", "logout", "auth", "auth/foo", "login/?blah"} {
574                 req := (&testReq{
575                         method: "OPTIONS",
576                         path:   unsafe,
577                         header: http.Header{"Origin": {"https://example.com"}},
578                         token:  token,
579                 }).Request()
580                 rr := httptest.NewRecorder()
581                 s.rtr.ServeHTTP(rr, req)
582                 c.Check(rr.Code, check.Equals, http.StatusOK)
583                 c.Check(rr.Body.String(), check.HasLen, 0)
584                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
585                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
586                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
587
588                 req = (&testReq{
589                         method: "POST",
590                         path:   unsafe,
591                         header: http.Header{"Origin": {"https://example.com"}},
592                         token:  token,
593                 }).Request()
594                 rr = httptest.NewRecorder()
595                 s.rtr.ServeHTTP(rr, req)
596                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Origin"), check.Equals, "")
597                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Methods"), check.Equals, "")
598                 c.Check(rr.Result().Header.Get("Access-Control-Allow-Headers"), check.Equals, "")
599         }
600 }
601
602 func doRequest(c *check.C, rtr http.Handler, token, method, path string, hdrs http.Header, body io.Reader, jresp map[string]interface{}) (*http.Request, *httptest.ResponseRecorder) {
603         req := httptest.NewRequest(method, path, body)
604         for k, v := range hdrs {
605                 req.Header[k] = v
606         }
607         req.Header.Set("Authorization", "Bearer "+token)
608         rr := httptest.NewRecorder()
609         rtr.ServeHTTP(rr, req)
610         c.Logf("response body: %s", rr.Body.String())
611         if jresp != nil {
612                 err := json.Unmarshal(rr.Body.Bytes(), &jresp)
613                 c.Check(err, check.IsNil)
614         }
615         return req, rr
616 }