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