16263: Add local_user_list flag to bypass LoginCluster behavior
[arvados.git] / lib / controller / router / response.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         "net/http"
11         "regexp"
12         "strings"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/arvados"
16         "git.arvados.org/arvados.git/sdk/go/httpserver"
17 )
18
19 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
20
21 type responseOptions struct {
22         Select []string
23         Count  string
24 }
25
26 func (rtr *router) responseOptions(opts interface{}) (responseOptions, error) {
27         var rOpts responseOptions
28         switch opts := opts.(type) {
29         case *arvados.GetOptions:
30                 rOpts.Select = opts.Select
31         case *arvados.ListOptions:
32                 rOpts.Select = opts.Select
33                 rOpts.Count = opts.Count
34         }
35         return rOpts, nil
36 }
37
38 func applySelectParam(selectParam []string, orig map[string]interface{}) map[string]interface{} {
39         if len(selectParam) == 0 {
40                 return orig
41         }
42         selected := map[string]interface{}{}
43         for _, attr := range selectParam {
44                 if v, ok := orig[attr]; ok {
45                         selected[attr] = v
46                 }
47         }
48         // Some keys are always preserved, even if not requested
49         for _, k := range []string{"etag", "kind", "writable_by"} {
50                 if v, ok := orig[k]; ok {
51                         selected[k] = v
52                 }
53         }
54         return selected
55 }
56
57 func (rtr *router) sendResponse(w http.ResponseWriter, req *http.Request, resp interface{}, opts responseOptions) {
58         var tmp map[string]interface{}
59
60         if resp, ok := resp.(http.Handler); ok {
61                 // resp knows how to write its own http response
62                 // header and body.
63                 resp.ServeHTTP(w, req)
64                 return
65         }
66
67         err := rtr.transcode(resp, &tmp)
68         if err != nil {
69                 rtr.sendError(w, err)
70                 return
71         }
72
73         respKind := kind(resp)
74         if respKind != "" {
75                 tmp["kind"] = respKind
76         }
77         defaultItemKind := ""
78         if strings.HasSuffix(respKind, "List") {
79                 defaultItemKind = strings.TrimSuffix(respKind, "List")
80         }
81
82         if items, ok := tmp["items"].([]interface{}); ok {
83                 for i, item := range items {
84                         // Fill in "kind" by inspecting UUID/PDH if
85                         // possible; fall back on assuming each
86                         // Items[] entry in an "arvados#fooList"
87                         // response should have kind="arvados#foo".
88                         item, _ := item.(map[string]interface{})
89                         infix := ""
90                         if uuid, _ := item["uuid"].(string); len(uuid) == 27 {
91                                 infix = uuid[6:11]
92                         }
93                         if k := kind(infixMap[infix]); k != "" {
94                                 item["kind"] = k
95                         } else if pdh, _ := item["portable_data_hash"].(string); pdh != "" {
96                                 item["kind"] = "arvados#collection"
97                         } else if defaultItemKind != "" {
98                                 item["kind"] = defaultItemKind
99                         }
100                         items[i] = applySelectParam(opts.Select, item)
101                 }
102                 if opts.Count == "none" {
103                         delete(tmp, "items_available")
104                 }
105         } else {
106                 tmp = applySelectParam(opts.Select, tmp)
107         }
108
109         // Format non-nil timestamps as rfc3339NanoFixed (by default
110         // they will have been encoded to time.RFC3339Nano, which
111         // omits trailing zeroes).
112         for k, v := range tmp {
113                 if !strings.HasSuffix(k, "_at") {
114                         continue
115                 }
116                 switch tv := v.(type) {
117                 case *time.Time:
118                         if tv == nil {
119                                 break
120                         }
121                         tmp[k] = tv.Format(rfc3339NanoFixed)
122                 case time.Time:
123                         tmp[k] = tv.Format(rfc3339NanoFixed)
124                 case string:
125                         t, err := time.Parse(time.RFC3339Nano, tv)
126                         if err != nil {
127                                 break
128                         }
129                         tmp[k] = t.Format(rfc3339NanoFixed)
130                 }
131         }
132         w.Header().Set("Content-Type", "application/json")
133         enc := json.NewEncoder(w)
134         enc.SetEscapeHTML(false)
135         enc.Encode(tmp)
136 }
137
138 func (rtr *router) sendError(w http.ResponseWriter, err error) {
139         code := http.StatusInternalServerError
140         if err, ok := err.(interface{ HTTPStatus() int }); ok {
141                 code = err.HTTPStatus()
142         }
143         httpserver.Error(w, err.Error(), code)
144 }
145
146 var infixMap = map[string]interface{}{
147         "4zz18": arvados.Collection{},
148         "j7d0g": arvados.Group{},
149 }
150
151 var mungeKind = regexp.MustCompile(`\..`)
152
153 func kind(resp interface{}) string {
154         t := fmt.Sprintf("%T", resp)
155         if !strings.HasPrefix(t, "arvados.") {
156                 return ""
157         }
158         return mungeKind.ReplaceAllStringFunc(t, func(s string) string {
159                 // "arvados.CollectionList" => "arvados#collectionList"
160                 return "#" + strings.ToLower(s[1:])
161         })
162 }