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