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