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