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