18887: it is OK for controller to forward the local anymous token,
[arvados.git] / lib / controller / federation / conn.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package federation
6
7 import (
8         "bytes"
9         "context"
10         "encoding/json"
11         "errors"
12         "fmt"
13         "net/http"
14         "net/url"
15         "regexp"
16         "strings"
17         "time"
18
19         "git.arvados.org/arvados.git/lib/config"
20         "git.arvados.org/arvados.git/lib/controller/localdb"
21         "git.arvados.org/arvados.git/lib/controller/rpc"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "git.arvados.org/arvados.git/sdk/go/auth"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "git.arvados.org/arvados.git/sdk/go/health"
26 )
27
28 type Conn struct {
29         cluster *arvados.Cluster
30         local   backend
31         remotes map[string]backend
32 }
33
34 func New(cluster *arvados.Cluster, healthFuncs *map[string]health.Func) *Conn {
35         local := localdb.NewConn(cluster)
36         remotes := map[string]backend{}
37         for id, remote := range cluster.RemoteClusters {
38                 if !remote.Proxy || id == cluster.ClusterID {
39                         continue
40                 }
41                 conn := rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(cluster, local, id))
42                 // Older versions of controller rely on the Via header
43                 // to detect loops.
44                 conn.SendHeader = http.Header{"Via": {"HTTP/1.1 arvados-controller"}}
45                 remotes[id] = conn
46         }
47
48         if healthFuncs != nil {
49                 hf := map[string]health.Func{"vocabulary": local.LastVocabularyError}
50                 *healthFuncs = hf
51         }
52
53         return &Conn{
54                 cluster: cluster,
55                 local:   local,
56                 remotes: remotes,
57         }
58 }
59
60 // Return a new rpc.TokenProvider that takes the client-provided
61 // tokens from an incoming request context, determines whether they
62 // should (and can) be salted for the given remoteID, and returns the
63 // resulting tokens.
64 func saltedTokenProvider(cluster *arvados.Cluster, local backend, remoteID string) rpc.TokenProvider {
65         return func(ctx context.Context) ([]string, error) {
66                 var tokens []string
67                 incoming, ok := auth.FromContext(ctx)
68                 if !ok {
69                         return nil, errors.New("no token provided")
70                 }
71                 for _, token := range incoming.Tokens {
72                         if strings.HasPrefix(token, "v2/"+cluster.ClusterID+"-") &&
73                                 !strings.HasPrefix(token, "v2/"+cluster.ClusterID+"-gj3su-anonymouspublic/") &&
74                                 remoteID == cluster.Login.LoginCluster {
75                                 // If we did this, the login cluster would call back to us and then
76                                 // reject our response because the user UUID prefix (i.e., the
77                                 // LoginCluster prefix) won't match the token UUID prefix (i.e., our
78                                 // prefix). The anonymous token is OK to forward, because it gets
79                                 // mapped to the local anonymous token automatically on the login
80                                 // cluster.
81                                 return nil, httpErrorf(http.StatusUnauthorized, "cannot use a locally issued token to forward a request to our login cluster (%s)", remoteID)
82                         }
83                         salted, err := auth.SaltToken(token, remoteID)
84                         switch err {
85                         case nil:
86                                 tokens = append(tokens, salted)
87                         case auth.ErrSalted:
88                                 tokens = append(tokens, token)
89                         case auth.ErrTokenFormat:
90                                 // pass through unmodified (assume it's an OIDC access token)
91                                 tokens = append(tokens, token)
92                         case auth.ErrObsoleteToken:
93                                 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
94                                 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
95                                 if errStatus(err) == http.StatusUnauthorized {
96                                         // pass through unmodified
97                                         tokens = append(tokens, token)
98                                         continue
99                                 } else if err != nil {
100                                         return nil, err
101                                 }
102                                 if strings.HasPrefix(aca.UUID, remoteID) {
103                                         // We have it cached here, but
104                                         // the token belongs to the
105                                         // remote target itself, so
106                                         // pass it through unmodified.
107                                         tokens = append(tokens, token)
108                                         continue
109                                 }
110                                 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
111                                 if err != nil {
112                                         return nil, err
113                                 }
114                                 tokens = append(tokens, salted)
115                         default:
116                                 return nil, err
117                         }
118                 }
119                 return tokens, nil
120         }
121 }
122
123 // Return suitable backend for a query about the given cluster ID
124 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
125 func (conn *Conn) chooseBackend(id string) backend {
126         if len(id) == 27 {
127                 id = id[:5]
128         } else if len(id) != 5 {
129                 // PDH or bogus ID
130                 return conn.local
131         }
132         if id == conn.cluster.ClusterID {
133                 return conn.local
134         } else if be, ok := conn.remotes[id]; ok {
135                 return be
136         } else {
137                 // TODO: return an "always error" backend?
138                 return conn.local
139         }
140 }
141
142 func (conn *Conn) localOrLoginCluster() backend {
143         if conn.cluster.Login.LoginCluster != "" {
144                 return conn.chooseBackend(conn.cluster.Login.LoginCluster)
145         }
146         return conn.local
147 }
148
149 // Call fn with the local backend; then, if fn returned 404, call fn
150 // on the available remote backends (possibly concurrently) until one
151 // succeeds.
152 //
153 // The second argument to fn is the cluster ID of the remote backend,
154 // or "" for the local backend.
155 //
156 // A non-nil error means all backends failed.
157 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, forwardedFor string, fn func(context.Context, string, backend) error) error {
158         if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound || forwardedFor != "" {
159                 // Note: forwardedFor != "" means this request came
160                 // from a remote cluster, so we don't take a second
161                 // hop. This avoids cycles, redundant calls to a
162                 // mutually reachable remote, and use of double-salted
163                 // tokens.
164                 return err
165         }
166
167         ctx, cancel := context.WithCancel(ctx)
168         defer cancel()
169         errchan := make(chan error, len(conn.remotes))
170         for remoteID, be := range conn.remotes {
171                 remoteID, be := remoteID, be
172                 go func() {
173                         errchan <- fn(ctx, remoteID, be)
174                 }()
175         }
176         all404 := true
177         var errs []error
178         for i := 0; i < cap(errchan); i++ {
179                 err := <-errchan
180                 if err == nil {
181                         return nil
182                 }
183                 all404 = all404 && errStatus(err) == http.StatusNotFound
184                 errs = append(errs, err)
185         }
186         if all404 {
187                 return notFoundError{}
188         }
189         return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
190 }
191
192 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
193         return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
194 }
195
196 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
197         return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
198 }
199
200 func rewriteManifest(mt, remoteID string) string {
201         return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
202                 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
203         })
204 }
205
206 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
207         var buf bytes.Buffer
208         err := config.ExportJSON(&buf, conn.cluster)
209         return json.RawMessage(buf.Bytes()), err
210 }
211
212 func (conn *Conn) VocabularyGet(ctx context.Context) (arvados.Vocabulary, error) {
213         return conn.chooseBackend(conn.cluster.ClusterID).VocabularyGet(ctx)
214 }
215
216 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
217         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
218                 // defer entire login procedure to designated cluster
219                 remote, ok := conn.remotes[id]
220                 if !ok {
221                         return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
222                 }
223                 baseURL := remote.BaseURL()
224                 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
225                 if err != nil {
226                         return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
227                 }
228                 params := url.Values{
229                         "return_to": []string{options.ReturnTo},
230                 }
231                 if options.Remote != "" {
232                         params.Set("remote", options.Remote)
233                 }
234                 target.RawQuery = params.Encode()
235                 return arvados.LoginResponse{
236                         RedirectLocation: target.String(),
237                 }, nil
238         }
239         return conn.local.Login(ctx, options)
240 }
241
242 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
243         // If the logout request comes with an API token from a known
244         // remote cluster, redirect to that cluster's logout handler
245         // so it has an opportunity to clear sessions, expire tokens,
246         // etc. Otherwise use the local endpoint.
247         reqauth, ok := auth.FromContext(ctx)
248         if !ok || len(reqauth.Tokens) == 0 || len(reqauth.Tokens[0]) < 8 || !strings.HasPrefix(reqauth.Tokens[0], "v2/") {
249                 return conn.local.Logout(ctx, options)
250         }
251         id := reqauth.Tokens[0][3:8]
252         if id == conn.cluster.ClusterID {
253                 return conn.local.Logout(ctx, options)
254         }
255         remote, ok := conn.remotes[id]
256         if !ok {
257                 return conn.local.Logout(ctx, options)
258         }
259         baseURL := remote.BaseURL()
260         target, err := baseURL.Parse(arvados.EndpointLogout.Path)
261         if err != nil {
262                 return arvados.LogoutResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
263         }
264         target.RawQuery = url.Values{"return_to": {options.ReturnTo}}.Encode()
265         return arvados.LogoutResponse{RedirectLocation: target.String()}, nil
266 }
267
268 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
269         if len(options.UUID) == 27 {
270                 // UUID is really a UUID
271                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
272                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
273                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
274                 }
275                 return c, err
276         }
277         // UUID is a PDH
278         first := make(chan arvados.Collection, 1)
279         err := conn.tryLocalThenRemotes(ctx, options.ForwardedFor, func(ctx context.Context, remoteID string, be backend) error {
280                 remoteOpts := options
281                 remoteOpts.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
282                 c, err := be.CollectionGet(ctx, remoteOpts)
283                 if err != nil {
284                         return err
285                 }
286                 haveManifest := true
287                 if options.Select != nil {
288                         haveManifest = false
289                         for _, s := range options.Select {
290                                 if s == "manifest_text" {
291                                         haveManifest = true
292                                         break
293                                 }
294                         }
295                 }
296                 if haveManifest {
297                         pdh := arvados.PortableDataHash(c.ManifestText)
298                         // options.UUID is either hash+size or
299                         // hash+size+hints; only hash+size need to
300                         // match the computed PDH.
301                         if pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
302                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
303                                 ctxlog.FromContext(ctx).Warn(err)
304                                 return err
305                         }
306                 }
307                 if remoteID != "" {
308                         c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
309                 }
310                 select {
311                 case first <- c:
312                         return nil
313                 default:
314                         // lost race, return value doesn't matter
315                         return nil
316                 }
317         })
318         if err != nil {
319                 return arvados.Collection{}, err
320         }
321         return <-first, nil
322 }
323
324 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
325         return conn.generated_CollectionList(ctx, options)
326 }
327
328 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
329         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
330 }
331
332 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
333         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
334 }
335
336 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
337         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
338 }
339
340 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
341         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
342 }
343
344 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
345         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
346 }
347
348 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
349         return conn.generated_ContainerList(ctx, options)
350 }
351
352 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
353         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
354 }
355
356 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
357         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
358 }
359
360 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
361         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
362 }
363
364 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
365         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
366 }
367
368 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
369         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
370 }
371
372 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
373         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
374 }
375
376 func (conn *Conn) ContainerSSH(ctx context.Context, options arvados.ContainerSSHOptions) (arvados.ContainerSSHConnection, error) {
377         return conn.chooseBackend(options.UUID).ContainerSSH(ctx, options)
378 }
379
380 func (conn *Conn) ContainerRequestList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerRequestList, error) {
381         return conn.generated_ContainerRequestList(ctx, options)
382 }
383
384 func (conn *Conn) ContainerRequestCreate(ctx context.Context, options arvados.CreateOptions) (arvados.ContainerRequest, error) {
385         be := conn.chooseBackend(options.ClusterID)
386         if be == conn.local {
387                 return be.ContainerRequestCreate(ctx, options)
388         }
389         if _, ok := options.Attrs["runtime_token"]; !ok {
390                 // If runtime_token is not set, create a new token
391                 aca, err := conn.local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
392                 if err != nil {
393                         // This should probably be StatusUnauthorized
394                         // (need to update test in
395                         // lib/controller/federation_test.go):
396                         // When RoR is out of the picture this should be:
397                         // return arvados.ContainerRequest{}, httpErrorf(http.StatusUnauthorized, "%w", err)
398                         return arvados.ContainerRequest{}, httpErrorf(http.StatusForbidden, "%s", "invalid API token")
399                 }
400                 user, err := conn.local.UserGetCurrent(ctx, arvados.GetOptions{})
401                 if err != nil {
402                         return arvados.ContainerRequest{}, err
403                 }
404                 if len(aca.Scopes) == 0 || aca.Scopes[0] != "all" {
405                         return arvados.ContainerRequest{}, httpErrorf(http.StatusForbidden, "token scope is not [all]")
406                 }
407                 if strings.HasPrefix(aca.UUID, conn.cluster.ClusterID) {
408                         // Local user, submitting to a remote cluster.
409                         // Create a new time-limited token.
410                         local, ok := conn.local.(*localdb.Conn)
411                         if !ok {
412                                 return arvados.ContainerRequest{}, httpErrorf(http.StatusInternalServerError, "bug: local backend is a %T, not a *localdb.Conn", conn.local)
413                         }
414                         aca, err = local.CreateAPIClientAuthorization(ctx, conn.cluster.SystemRootToken, rpc.UserSessionAuthInfo{UserUUID: user.UUID,
415                                 ExpiresAt: time.Now().UTC().Add(conn.cluster.Collections.BlobSigningTTL.Duration())})
416                         if err != nil {
417                                 return arvados.ContainerRequest{}, err
418                         }
419                         options.Attrs["runtime_token"] = aca.TokenV2()
420                 } else {
421                         // Remote user. Container request will use the
422                         // current token, minus the trailing portion
423                         // (optional container uuid).
424                         options.Attrs["runtime_token"] = aca.TokenV2()
425                 }
426         }
427         return be.ContainerRequestCreate(ctx, options)
428 }
429
430 func (conn *Conn) ContainerRequestUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.ContainerRequest, error) {
431         return conn.chooseBackend(options.UUID).ContainerRequestUpdate(ctx, options)
432 }
433
434 func (conn *Conn) ContainerRequestGet(ctx context.Context, options arvados.GetOptions) (arvados.ContainerRequest, error) {
435         return conn.chooseBackend(options.UUID).ContainerRequestGet(ctx, options)
436 }
437
438 func (conn *Conn) ContainerRequestDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.ContainerRequest, error) {
439         return conn.chooseBackend(options.UUID).ContainerRequestDelete(ctx, options)
440 }
441
442 func (conn *Conn) GroupCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Group, error) {
443         return conn.chooseBackend(options.ClusterID).GroupCreate(ctx, options)
444 }
445
446 func (conn *Conn) GroupUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Group, error) {
447         return conn.chooseBackend(options.UUID).GroupUpdate(ctx, options)
448 }
449
450 func (conn *Conn) GroupGet(ctx context.Context, options arvados.GetOptions) (arvados.Group, error) {
451         return conn.chooseBackend(options.UUID).GroupGet(ctx, options)
452 }
453
454 func (conn *Conn) GroupList(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
455         return conn.generated_GroupList(ctx, options)
456 }
457
458 var userUuidRe = regexp.MustCompile(`^[0-9a-z]{5}-tpzed-[0-9a-z]{15}$`)
459
460 func (conn *Conn) GroupContents(ctx context.Context, options arvados.GroupContentsOptions) (arvados.ObjectList, error) {
461         if options.ClusterID != "" {
462                 // explicitly selected cluster
463                 return conn.chooseBackend(options.ClusterID).GroupContents(ctx, options)
464         } else if userUuidRe.MatchString(options.UUID) {
465                 // user, get the things they own on the local cluster
466                 return conn.local.GroupContents(ctx, options)
467         } else {
468                 // a group, potentially want to make federated request
469                 return conn.chooseBackend(options.UUID).GroupContents(ctx, options)
470         }
471 }
472
473 func (conn *Conn) GroupShared(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
474         return conn.chooseBackend(options.ClusterID).GroupShared(ctx, options)
475 }
476
477 func (conn *Conn) GroupDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
478         return conn.chooseBackend(options.UUID).GroupDelete(ctx, options)
479 }
480
481 func (conn *Conn) GroupTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
482         return conn.chooseBackend(options.UUID).GroupTrash(ctx, options)
483 }
484
485 func (conn *Conn) GroupUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Group, error) {
486         return conn.chooseBackend(options.UUID).GroupUntrash(ctx, options)
487 }
488
489 func (conn *Conn) LinkCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Link, error) {
490         return conn.chooseBackend(options.ClusterID).LinkCreate(ctx, options)
491 }
492
493 func (conn *Conn) LinkUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Link, error) {
494         return conn.chooseBackend(options.UUID).LinkUpdate(ctx, options)
495 }
496
497 func (conn *Conn) LinkGet(ctx context.Context, options arvados.GetOptions) (arvados.Link, error) {
498         return conn.chooseBackend(options.UUID).LinkGet(ctx, options)
499 }
500
501 func (conn *Conn) LinkList(ctx context.Context, options arvados.ListOptions) (arvados.LinkList, error) {
502         return conn.generated_LinkList(ctx, options)
503 }
504
505 func (conn *Conn) LinkDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Link, error) {
506         return conn.chooseBackend(options.UUID).LinkDelete(ctx, options)
507 }
508
509 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
510         return conn.generated_SpecimenList(ctx, options)
511 }
512
513 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
514         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
515 }
516
517 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
518         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
519 }
520
521 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
522         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
523 }
524
525 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
526         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
527 }
528
529 func (conn *Conn) SysTrashSweep(ctx context.Context, options struct{}) (struct{}, error) {
530         return conn.local.SysTrashSweep(ctx, options)
531 }
532
533 var userAttrsCachedFromLoginCluster = map[string]bool{
534         "created_at":  true,
535         "email":       true,
536         "first_name":  true,
537         "is_active":   true,
538         "is_admin":    true,
539         "last_name":   true,
540         "modified_at": true,
541         "prefs":       true,
542         "username":    true,
543         "kind":        true,
544
545         "etag":                    false,
546         "full_name":               false,
547         "identity_url":            false,
548         "is_invited":              false,
549         "modified_by_client_uuid": false,
550         "modified_by_user_uuid":   false,
551         "owner_uuid":              false,
552         "uuid":                    false,
553         "writable_by":             false,
554 }
555
556 func (conn *Conn) batchUpdateUsers(ctx context.Context,
557         options arvados.ListOptions,
558         items []arvados.User) (err error) {
559
560         id := conn.cluster.Login.LoginCluster
561         logger := ctxlog.FromContext(ctx)
562         batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
563         for _, user := range items {
564                 if !strings.HasPrefix(user.UUID, id) {
565                         continue
566                 }
567                 logger.Debugf("cache user info for uuid %q", user.UUID)
568
569                 // If the remote cluster has null timestamps
570                 // (e.g., test server with incomplete
571                 // fixtures) use dummy timestamps (instead of
572                 // the zero time, which causes a Rails API
573                 // error "year too big to marshal: 1 UTC").
574                 if user.ModifiedAt.IsZero() {
575                         user.ModifiedAt = time.Now()
576                 }
577                 if user.CreatedAt.IsZero() {
578                         user.CreatedAt = time.Now()
579                 }
580
581                 var allFields map[string]interface{}
582                 buf, err := json.Marshal(user)
583                 if err != nil {
584                         return fmt.Errorf("error encoding user record from remote response: %s", err)
585                 }
586                 err = json.Unmarshal(buf, &allFields)
587                 if err != nil {
588                         return fmt.Errorf("error transcoding user record from remote response: %s", err)
589                 }
590                 updates := allFields
591                 if len(options.Select) > 0 {
592                         updates = map[string]interface{}{}
593                         for _, k := range options.Select {
594                                 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
595                                         updates[k] = v
596                                 }
597                         }
598                 } else {
599                         for k := range updates {
600                                 if !userAttrsCachedFromLoginCluster[k] {
601                                         delete(updates, k)
602                                 }
603                         }
604                 }
605                 batchOpts.Updates[user.UUID] = updates
606         }
607         if len(batchOpts.Updates) > 0 {
608                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
609                 _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
610                 if err != nil {
611                         return fmt.Errorf("error updating local user records: %s", err)
612                 }
613         }
614         return nil
615 }
616
617 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
618         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID && !options.BypassFederation {
619                 resp, err := conn.chooseBackend(id).UserList(ctx, options)
620                 if err != nil {
621                         return resp, err
622                 }
623                 err = conn.batchUpdateUsers(ctx, options, resp.Items)
624                 if err != nil {
625                         return arvados.UserList{}, err
626                 }
627                 return resp, nil
628         }
629         return conn.generated_UserList(ctx, options)
630 }
631
632 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
633         return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
634 }
635
636 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
637         if options.BypassFederation {
638                 return conn.local.UserUpdate(ctx, options)
639         }
640         resp, err := conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
641         if err != nil {
642                 return resp, err
643         }
644         if !strings.HasPrefix(options.UUID, conn.cluster.ClusterID) {
645                 // Copy the updated user record to the local cluster
646                 err = conn.batchUpdateUsers(ctx, arvados.ListOptions{}, []arvados.User{resp})
647                 if err != nil {
648                         return arvados.User{}, err
649                 }
650         }
651         return resp, err
652 }
653
654 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
655         return conn.local.UserMerge(ctx, options)
656 }
657
658 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
659         return conn.localOrLoginCluster().UserActivate(ctx, options)
660 }
661
662 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
663         upstream := conn.localOrLoginCluster()
664         if upstream != conn.local {
665                 // When LoginCluster is in effect, and we're setting
666                 // up a remote user, and we want to give that user
667                 // access to a local VM, we can't include the VM in
668                 // the setup call, because the remote cluster won't
669                 // recognize it.
670
671                 // Similarly, if we want to create a git repo,
672                 // it should be created on the local cluster,
673                 // not the remote one.
674
675                 upstreamOptions := options
676                 upstreamOptions.VMUUID = ""
677                 upstreamOptions.RepoName = ""
678
679                 ret, err := upstream.UserSetup(ctx, upstreamOptions)
680                 if err != nil {
681                         return ret, err
682                 }
683         }
684
685         return conn.local.UserSetup(ctx, options)
686 }
687
688 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
689         return conn.localOrLoginCluster().UserUnsetup(ctx, options)
690 }
691
692 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
693         resp, err := conn.chooseBackend(options.UUID).UserGet(ctx, options)
694         if err != nil {
695                 return resp, err
696         }
697         if options.UUID != resp.UUID {
698                 return arvados.User{}, httpErrorf(http.StatusBadGateway, "Had requested %v but response was for %v", options.UUID, resp.UUID)
699         }
700         if options.UUID[:5] != conn.cluster.ClusterID {
701                 err = conn.batchUpdateUsers(ctx, arvados.ListOptions{Select: options.Select}, []arvados.User{resp})
702                 if err != nil {
703                         return arvados.User{}, err
704                 }
705         }
706         return resp, nil
707 }
708
709 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
710         return conn.local.UserGetCurrent(ctx, options)
711 }
712
713 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
714         return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
715 }
716
717 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
718         return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
719 }
720
721 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
722         return conn.local.UserBatchUpdate(ctx, options)
723 }
724
725 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
726         return conn.local.UserAuthenticate(ctx, options)
727 }
728
729 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
730         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
731 }
732
733 func (conn *Conn) APIClientAuthorizationCreate(ctx context.Context, options arvados.CreateOptions) (arvados.APIClientAuthorization, error) {
734         if conn.cluster.Login.LoginCluster != "" {
735                 return conn.chooseBackend(conn.cluster.Login.LoginCluster).APIClientAuthorizationCreate(ctx, options)
736         }
737         ownerUUID, ok := options.Attrs["owner_uuid"].(string)
738         if ok && ownerUUID != "" {
739                 return conn.chooseBackend(ownerUUID).APIClientAuthorizationCreate(ctx, options)
740         }
741         return conn.local.APIClientAuthorizationCreate(ctx, options)
742 }
743
744 func (conn *Conn) APIClientAuthorizationUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.APIClientAuthorization, error) {
745         if options.BypassFederation {
746                 return conn.local.APIClientAuthorizationUpdate(ctx, options)
747         }
748         return conn.chooseBackend(options.UUID).APIClientAuthorizationUpdate(ctx, options)
749 }
750
751 func (conn *Conn) APIClientAuthorizationDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.APIClientAuthorization, error) {
752         return conn.chooseBackend(options.UUID).APIClientAuthorizationDelete(ctx, options)
753 }
754
755 func (conn *Conn) APIClientAuthorizationList(ctx context.Context, options arvados.ListOptions) (arvados.APIClientAuthorizationList, error) {
756         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID && !options.BypassFederation {
757                 return conn.chooseBackend(conn.cluster.Login.LoginCluster).APIClientAuthorizationList(ctx, options)
758         }
759         return conn.generated_APIClientAuthorizationList(ctx, options)
760 }
761
762 func (conn *Conn) APIClientAuthorizationGet(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
763         return conn.chooseBackend(options.UUID).APIClientAuthorizationGet(ctx, options)
764 }
765
766 type backend interface {
767         arvados.API
768         BaseURL() url.URL
769 }
770
771 type notFoundError struct{}
772
773 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
774 func (notFoundError) Error() string   { return "not found" }
775
776 func errStatus(err error) int {
777         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
778                 return httpErr.HTTPStatus()
779         }
780         return http.StatusInternalServerError
781 }