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