SystemRootToken was missing in the test
[arvados.git] / lib / controller / rpc / conn.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package rpc
6
7 import (
8         "bytes"
9         "context"
10         "crypto/tls"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "log"
16         "net"
17         "net/http"
18         "net/url"
19         "strconv"
20         "strings"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/auth"
25 )
26
27 type TokenProvider func(context.Context) ([]string, error)
28
29 func PassthroughTokenProvider(ctx context.Context) ([]string, error) {
30         incoming, ok := auth.FromContext(ctx)
31         if !ok {
32                 return nil, errors.New("no token provided")
33         }
34         return incoming.Tokens, nil
35 }
36
37 type Conn struct {
38         SendHeader    http.Header
39         clusterID     string
40         httpClient    http.Client
41         baseURL       url.URL
42         tokenProvider TokenProvider
43 }
44
45 func NewConn(clusterID string, url *url.URL, insecure bool, tp TokenProvider) *Conn {
46         transport := http.DefaultTransport
47         if insecure {
48                 // It's not safe to copy *http.DefaultTransport
49                 // because it has a mutex (which might be locked)
50                 // protecting a private map (which might not be nil).
51                 // So we build our own, using the Go 1.12 default
52                 // values, ignoring any changes the application has
53                 // made to http.DefaultTransport.
54                 transport = &http.Transport{
55                         DialContext: (&net.Dialer{
56                                 Timeout:   30 * time.Second,
57                                 KeepAlive: 30 * time.Second,
58                                 DualStack: true,
59                         }).DialContext,
60                         MaxIdleConns:          100,
61                         IdleConnTimeout:       90 * time.Second,
62                         TLSHandshakeTimeout:   10 * time.Second,
63                         ExpectContinueTimeout: 1 * time.Second,
64                         TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
65                 }
66         }
67         return &Conn{
68                 clusterID: clusterID,
69                 httpClient: http.Client{
70                         CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse },
71                         Transport:     transport,
72                 },
73                 baseURL:       *url,
74                 tokenProvider: tp,
75         }
76 }
77
78 func (conn *Conn) requestAndDecode(ctx context.Context, dst interface{}, ep arvados.APIEndpoint, body io.Reader, opts interface{}) error {
79         aClient := arvados.Client{
80                 Client:     &conn.httpClient,
81                 Scheme:     conn.baseURL.Scheme,
82                 APIHost:    conn.baseURL.Host,
83                 SendHeader: conn.SendHeader,
84         }
85         tokens, err := conn.tokenProvider(ctx)
86         if err != nil {
87                 return err
88         } else if len(tokens) > 0 {
89                 ctx = arvados.ContextWithAuthorization(ctx, "Bearer "+tokens[0])
90         } else {
91                 // Use a non-empty auth string to ensure we override
92                 // any default token set on aClient -- and to avoid
93                 // having the remote prompt us to send a token by
94                 // responding 401.
95                 ctx = arvados.ContextWithAuthorization(ctx, "Bearer -")
96         }
97
98         // Encode opts to JSON and decode from there to a
99         // map[string]interface{}, so we can munge the query params
100         // using the JSON key names specified by opts' struct tags.
101         j, err := json.Marshal(opts)
102         if err != nil {
103                 return fmt.Errorf("%T: requestAndDecode: Marshal opts: %s", conn, err)
104         }
105         var params map[string]interface{}
106         dec := json.NewDecoder(bytes.NewBuffer(j))
107         dec.UseNumber()
108         err = dec.Decode(&params)
109         if err != nil {
110                 return fmt.Errorf("%T: requestAndDecode: Decode opts: %s", conn, err)
111         }
112         if attrs, ok := params["attrs"]; ok && ep.AttrsKey != "" {
113                 params[ep.AttrsKey] = attrs
114                 delete(params, "attrs")
115         }
116         if limitStr, ok := params["limit"]; ok {
117                 if limit, err := strconv.ParseInt(string(limitStr.(json.Number)), 10, 64); err == nil && limit < 0 {
118                         // Negative limit means "not specified" here, but some
119                         // servers/versions do not accept that, so we need to
120                         // remove it entirely.
121                         delete(params, "limit")
122                 }
123         }
124         if len(tokens) > 1 {
125                 params["reader_tokens"] = tokens[1:]
126         }
127         path := ep.Path
128         if strings.Contains(ep.Path, "/{uuid}") {
129                 uuid, _ := params["uuid"].(string)
130                 path = strings.Replace(path, "/{uuid}", "/"+uuid, 1)
131                 delete(params, "uuid")
132         }
133         return aClient.RequestAndDecodeContext(ctx, dst, ep.Method, path, body, params)
134 }
135
136 func (conn *Conn) BaseURL() url.URL {
137         return conn.baseURL
138 }
139
140 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
141         ep := arvados.EndpointConfigGet
142         var resp json.RawMessage
143         err := conn.requestAndDecode(ctx, &resp, ep, nil, nil)
144         return resp, err
145 }
146
147 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
148         ep := arvados.EndpointLogin
149         var resp arvados.LoginResponse
150         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
151         resp.RedirectLocation = conn.relativeToBaseURL(resp.RedirectLocation)
152         return resp, err
153 }
154
155 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
156         ep := arvados.EndpointLogout
157         var resp arvados.LogoutResponse
158         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
159         resp.RedirectLocation = conn.relativeToBaseURL(resp.RedirectLocation)
160         return resp, err
161 }
162
163 // If the given location is a valid URL and its origin is the same as
164 // conn.baseURL, return it as a relative URL. Otherwise, return it
165 // unmodified.
166 func (conn *Conn) relativeToBaseURL(location string) string {
167         u, err := url.Parse(location)
168         if err == nil && u.Scheme == conn.baseURL.Scheme && strings.ToLower(u.Host) == strings.ToLower(conn.baseURL.Host) {
169                 u.Opaque = ""
170                 u.Scheme = ""
171                 u.User = nil
172                 u.Host = ""
173                 return u.String()
174         }
175         return location
176 }
177
178 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
179         ep := arvados.EndpointCollectionCreate
180         var resp arvados.Collection
181         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
182         return resp, err
183 }
184
185 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
186         ep := arvados.EndpointCollectionUpdate
187         var resp arvados.Collection
188         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
189         return resp, err
190 }
191
192 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
193         ep := arvados.EndpointCollectionGet
194         var resp arvados.Collection
195         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
196         return resp, err
197 }
198
199 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
200         ep := arvados.EndpointCollectionList
201         var resp arvados.CollectionList
202         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
203         return resp, err
204 }
205
206 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
207         ep := arvados.EndpointCollectionProvenance
208         var resp map[string]interface{}
209         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
210         return resp, err
211 }
212
213 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
214         ep := arvados.EndpointCollectionUsedBy
215         var resp map[string]interface{}
216         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
217         return resp, err
218 }
219
220 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
221         ep := arvados.EndpointCollectionDelete
222         var resp arvados.Collection
223         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
224         return resp, err
225 }
226
227 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
228         ep := arvados.EndpointCollectionTrash
229         var resp arvados.Collection
230         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
231         return resp, err
232 }
233
234 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
235         ep := arvados.EndpointCollectionUntrash
236         var resp arvados.Collection
237         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
238         return resp, err
239 }
240
241 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
242         ep := arvados.EndpointContainerCreate
243         var resp arvados.Container
244         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
245         return resp, err
246 }
247
248 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
249         ep := arvados.EndpointContainerUpdate
250         var resp arvados.Container
251         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
252         return resp, err
253 }
254
255 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
256         ep := arvados.EndpointContainerGet
257         var resp arvados.Container
258         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
259         return resp, err
260 }
261
262 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
263         ep := arvados.EndpointContainerList
264         var resp arvados.ContainerList
265         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
266         return resp, err
267 }
268
269 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
270         ep := arvados.EndpointContainerDelete
271         var resp arvados.Container
272         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
273         return resp, err
274 }
275
276 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
277         ep := arvados.EndpointContainerLock
278         var resp arvados.Container
279         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
280         return resp, err
281 }
282
283 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
284         ep := arvados.EndpointContainerUnlock
285         var resp arvados.Container
286         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
287         return resp, err
288 }
289
290 func (conn *Conn) ContainerRequestCreate(ctx context.Context, options arvados.CreateOptions) (arvados.ContainerRequest, error) {
291         log.Printf("THIS IS rcp.Conn.ContainerRequestCreate() for %s we are %s", options.ClusterID, conn.clusterID)
292         ep := arvados.EndpointContainerRequestCreate
293         var resp arvados.ContainerRequest
294         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
295         return resp, err
296 }
297
298 func (conn *Conn) ContainerRequestUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.ContainerRequest, error) {
299         ep := arvados.EndpointContainerRequestUpdate
300         var resp arvados.ContainerRequest
301         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
302         return resp, err
303 }
304
305 func (conn *Conn) ContainerRequestGet(ctx context.Context, options arvados.GetOptions) (arvados.ContainerRequest, error) {
306         ep := arvados.EndpointContainerRequestGet
307         var resp arvados.ContainerRequest
308         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
309         return resp, err
310 }
311
312 func (conn *Conn) ContainerRequestList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerRequestList, error) {
313         ep := arvados.EndpointContainerRequestList
314         var resp arvados.ContainerRequestList
315         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
316         return resp, err
317 }
318
319 func (conn *Conn) ContainerRequestDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.ContainerRequest, error) {
320         ep := arvados.EndpointContainerRequestDelete
321         var resp arvados.ContainerRequest
322         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
323         return resp, err
324 }
325
326 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
327         ep := arvados.EndpointSpecimenCreate
328         var resp arvados.Specimen
329         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
330         return resp, err
331 }
332
333 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
334         ep := arvados.EndpointSpecimenUpdate
335         var resp arvados.Specimen
336         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
337         return resp, err
338 }
339
340 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
341         ep := arvados.EndpointSpecimenGet
342         var resp arvados.Specimen
343         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
344         return resp, err
345 }
346
347 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
348         ep := arvados.EndpointSpecimenList
349         var resp arvados.SpecimenList
350         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
351         return resp, err
352 }
353
354 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
355         ep := arvados.EndpointSpecimenDelete
356         var resp arvados.Specimen
357         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
358         return resp, err
359 }
360
361 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
362         ep := arvados.EndpointUserCreate
363         var resp arvados.User
364         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
365         return resp, err
366 }
367 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
368         ep := arvados.EndpointUserUpdate
369         var resp arvados.User
370         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
371         return resp, err
372 }
373 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
374         ep := arvados.EndpointUserUpdateUUID
375         var resp arvados.User
376         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
377         return resp, err
378 }
379 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
380         ep := arvados.EndpointUserMerge
381         var resp arvados.User
382         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
383         return resp, err
384 }
385 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
386         ep := arvados.EndpointUserActivate
387         var resp arvados.User
388         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
389         return resp, err
390 }
391 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
392         ep := arvados.EndpointUserSetup
393         var resp map[string]interface{}
394         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
395         return resp, err
396 }
397 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
398         ep := arvados.EndpointUserUnsetup
399         var resp arvados.User
400         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
401         return resp, err
402 }
403 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
404         ep := arvados.EndpointUserGet
405         var resp arvados.User
406         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
407         return resp, err
408 }
409 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
410         ep := arvados.EndpointUserGetCurrent
411         var resp arvados.User
412         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
413         return resp, err
414 }
415 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
416         ep := arvados.EndpointUserGetSystem
417         var resp arvados.User
418         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
419         return resp, err
420 }
421 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
422         ep := arvados.EndpointUserList
423         var resp arvados.UserList
424         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
425         return resp, err
426 }
427 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
428         ep := arvados.EndpointUserDelete
429         var resp arvados.User
430         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
431         return resp, err
432 }
433
434 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
435         ep := arvados.EndpointAPIClientAuthorizationCurrent
436         var resp arvados.APIClientAuthorization
437         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
438         return resp, err
439 }
440
441 type UserSessionAuthInfo struct {
442         UserUUID        string   `json:"user_uuid"`
443         Email           string   `json:"email"`
444         AlternateEmails []string `json:"alternate_emails"`
445         FirstName       string   `json:"first_name"`
446         LastName        string   `json:"last_name"`
447         Username        string   `json:"username"`
448 }
449
450 type UserSessionCreateOptions struct {
451         AuthInfo UserSessionAuthInfo `json:"auth_info"`
452         ReturnTo string              `json:"return_to"`
453 }
454
455 func (conn *Conn) UserSessionCreate(ctx context.Context, options UserSessionCreateOptions) (arvados.LoginResponse, error) {
456         ep := arvados.APIEndpoint{Method: "POST", Path: "auth/controller/callback"}
457         var resp arvados.LoginResponse
458         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
459         return resp, err
460 }
461
462 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
463         ep := arvados.EndpointUserBatchUpdate
464         var resp arvados.UserList
465         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
466         return resp, err
467 }
468
469 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
470         ep := arvados.EndpointUserAuthenticate
471         var resp arvados.APIClientAuthorization
472         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
473         return resp, err
474 }