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