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