20690: Merge branch 'main' into 20690-remove-wb1
[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.chooseBackend(conn.cluster.ClusterID).VocabularyGet(ctx)
229 }
230
231 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
232         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
233                 // defer entire login procedure to designated cluster
234                 remote, ok := conn.remotes[id]
235                 if !ok {
236                         return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
237                 }
238                 baseURL := remote.BaseURL()
239                 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
240                 if err != nil {
241                         return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
242                 }
243                 params := url.Values{
244                         "return_to": []string{options.ReturnTo},
245                 }
246                 if options.Remote != "" {
247                         params.Set("remote", options.Remote)
248                 }
249                 target.RawQuery = params.Encode()
250                 return arvados.LoginResponse{
251                         RedirectLocation: target.String(),
252                 }, nil
253         }
254         return conn.local.Login(ctx, options)
255 }
256
257 var v2TokenRegexp = regexp.MustCompile(`^v2/[a-z0-9]{5}-gj3su-[a-z0-9]{15}/`)
258
259 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
260         // If the token was issued by another cluster, we want to issue a logout
261         // request to the issuing instance to invalidate the token federation-wide.
262         // If this federation has a login cluster, that's always considered the
263         // issuing cluster.
264         // Otherwise, if this is a v2 token, use the UUID to find the issuing
265         // cluster.
266         // Note that remoteBE may still be conn.local even *after* one of these
267         // conditions is true.
268         var remoteBE backend = conn.local
269         if conn.cluster.Login.LoginCluster != "" {
270                 remoteBE = conn.chooseBackend(conn.cluster.Login.LoginCluster)
271         } else {
272                 reqauth, ok := auth.FromContext(ctx)
273                 if ok && len(reqauth.Tokens) > 0 && v2TokenRegexp.MatchString(reqauth.Tokens[0]) {
274                         remoteBE = conn.chooseBackend(reqauth.Tokens[0][3:8])
275                 }
276         }
277
278         // We always want to invalidate the token locally. Start that process.
279         var localResponse arvados.LogoutResponse
280         var localErr error
281         wg := sync.WaitGroup{}
282         wg.Add(1)
283         go func() {
284                 localResponse, localErr = conn.local.Logout(ctx, options)
285                 wg.Done()
286         }()
287
288         // If the token was issued by another cluster, log out there too.
289         if remoteBE != conn.local {
290                 response, err := remoteBE.Logout(ctx, options)
291                 // If the issuing cluster returns a redirect or error, that's more
292                 // important to return to the user than anything that happens locally.
293                 if response.RedirectLocation != "" || err != nil {
294                         return response, err
295                 }
296         }
297
298         // Either the local cluster is the issuing cluster, or the issuing cluster's
299         // response was uninteresting.
300         wg.Wait()
301         return localResponse, localErr
302 }
303
304 func (conn *Conn) AuthorizedKeyCreate(ctx context.Context, options arvados.CreateOptions) (arvados.AuthorizedKey, error) {
305         return conn.chooseBackend(options.ClusterID).AuthorizedKeyCreate(ctx, options)
306 }
307
308 func (conn *Conn) AuthorizedKeyUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.AuthorizedKey, error) {
309         return conn.chooseBackend(options.UUID).AuthorizedKeyUpdate(ctx, options)
310 }
311
312 func (conn *Conn) AuthorizedKeyGet(ctx context.Context, options arvados.GetOptions) (arvados.AuthorizedKey, error) {
313         return conn.chooseBackend(options.UUID).AuthorizedKeyGet(ctx, options)
314 }
315
316 func (conn *Conn) AuthorizedKeyList(ctx context.Context, options arvados.ListOptions) (arvados.AuthorizedKeyList, error) {
317         return conn.generated_AuthorizedKeyList(ctx, options)
318 }
319
320 func (conn *Conn) AuthorizedKeyDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.AuthorizedKey, error) {
321         return conn.chooseBackend(options.UUID).AuthorizedKeyDelete(ctx, options)
322 }
323
324 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
325         if len(options.UUID) == 27 {
326                 // UUID is really a UUID
327                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
328                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
329                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
330                 }
331                 return c, err
332         }
333         if len(options.UUID) < 34 || options.UUID[32] != '+' {
334                 return arvados.Collection{}, httpErrorf(http.StatusNotFound, "invalid UUID or PDH %q", options.UUID)
335         }
336         // UUID is a PDH
337         first := make(chan arvados.Collection, 1)
338         err := conn.tryLocalThenRemotes(ctx, options.ForwardedFor, func(ctx context.Context, remoteID string, be backend) error {
339                 remoteOpts := options
340                 remoteOpts.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
341                 c, err := be.CollectionGet(ctx, remoteOpts)
342                 if err != nil {
343                         return err
344                 }
345                 haveManifest := true
346                 if options.Select != nil {
347                         haveManifest = false
348                         for _, s := range options.Select {
349                                 if s == "manifest_text" {
350                                         haveManifest = true
351                                         break
352                                 }
353                         }
354                 }
355                 if haveManifest {
356                         pdh := arvados.PortableDataHash(c.ManifestText)
357                         // options.UUID is either hash+size or
358                         // hash+size+hints; only hash+size need to
359                         // match the computed PDH.
360                         if pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
361                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
362                                 ctxlog.FromContext(ctx).Warn(err)
363                                 return err
364                         }
365                 }
366                 if remoteID != "" {
367                         c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
368                 }
369                 select {
370                 case first <- c:
371                         return nil
372                 default:
373                         // lost race, return value doesn't matter
374                         return nil
375                 }
376         })
377         if err != nil {
378                 return arvados.Collection{}, err
379         }
380         return <-first, nil
381 }
382
383 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
384         return conn.generated_CollectionList(ctx, options)
385 }
386
387 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
388         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
389 }
390
391 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
392         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
393 }
394
395 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
396         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
397 }
398
399 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
400         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
401 }
402
403 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
404         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
405 }
406
407 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
408         return conn.generated_ContainerList(ctx, options)
409 }
410
411 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
412         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
413 }
414
415 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
416         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
417 }
418
419 func (conn *Conn) ContainerPriorityUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
420         return conn.chooseBackend(options.UUID).ContainerPriorityUpdate(ctx, options)
421 }
422
423 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
424         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
425 }
426
427 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
428         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
429 }
430
431 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
432         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
433 }
434
435 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
436         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
437 }
438
439 func (conn *Conn) ContainerSSH(ctx context.Context, options arvados.ContainerSSHOptions) (arvados.ConnectionResponse, error) {
440         return conn.chooseBackend(options.UUID).ContainerSSH(ctx, options)
441 }
442
443 func (conn *Conn) ContainerGatewayTunnel(ctx context.Context, options arvados.ContainerGatewayTunnelOptions) (arvados.ConnectionResponse, error) {
444         return conn.chooseBackend(options.UUID).ContainerGatewayTunnel(ctx, options)
445 }
446
447 func (conn *Conn) ContainerRequestList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerRequestList, error) {
448         return conn.generated_ContainerRequestList(ctx, options)
449 }
450
451 func (conn *Conn) ContainerRequestCreate(ctx context.Context, options arvados.CreateOptions) (arvados.ContainerRequest, error) {
452         be := conn.chooseBackend(options.ClusterID)
453         if be == conn.local {
454                 return be.ContainerRequestCreate(ctx, options)
455         }
456         if _, ok := options.Attrs["runtime_token"]; !ok {
457                 // If runtime_token is not set, create a new token
458                 aca, err := conn.local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
459                 if err != nil {
460                         // This should probably be StatusUnauthorized
461                         // (need to update test in
462                         // lib/controller/federation_test.go):
463                         // When RoR is out of the picture this should be:
464                         // return arvados.ContainerRequest{}, httpErrorf(http.StatusUnauthorized, "%w", err)
465                         return arvados.ContainerRequest{}, httpErrorf(http.StatusForbidden, "%s", "invalid API token")
466                 }
467                 user, err := conn.local.UserGetCurrent(ctx, arvados.GetOptions{})
468                 if err != nil {
469                         return arvados.ContainerRequest{}, err
470                 }
471                 if len(aca.Scopes) == 0 || aca.Scopes[0] != "all" {
472                         return arvados.ContainerRequest{}, httpErrorf(http.StatusForbidden, "token scope is not [all]")
473                 }
474                 if strings.HasPrefix(aca.UUID, conn.cluster.ClusterID) {
475                         // Local user, submitting to a remote cluster.
476                         // Create a new time-limited token.
477                         local, ok := conn.local.(*localdb.Conn)
478                         if !ok {
479                                 return arvados.ContainerRequest{}, httpErrorf(http.StatusInternalServerError, "bug: local backend is a %T, not a *localdb.Conn", conn.local)
480                         }
481                         aca, err = local.CreateAPIClientAuthorization(ctx, conn.cluster.SystemRootToken, rpc.UserSessionAuthInfo{UserUUID: user.UUID,
482                                 ExpiresAt: time.Now().UTC().Add(conn.cluster.Collections.BlobSigningTTL.Duration())})
483                         if err != nil {
484                                 return arvados.ContainerRequest{}, err
485                         }
486                         options.Attrs["runtime_token"] = aca.TokenV2()
487                 } else {
488                         // Remote user. Container request will use the
489                         // current token, minus the trailing portion
490                         // (optional container uuid).
491                         options.Attrs["runtime_token"] = aca.TokenV2()
492                 }
493         }
494         return be.ContainerRequestCreate(ctx, options)
495 }
496
497 func (conn *Conn) ContainerRequestUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.ContainerRequest, error) {
498         return conn.chooseBackend(options.UUID).ContainerRequestUpdate(ctx, options)
499 }
500
501 func (conn *Conn) ContainerRequestGet(ctx context.Context, options arvados.GetOptions) (arvados.ContainerRequest, error) {
502         return conn.chooseBackend(options.UUID).ContainerRequestGet(ctx, options)
503 }
504
505 func (conn *Conn) ContainerRequestDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.ContainerRequest, error) {
506         return conn.chooseBackend(options.UUID).ContainerRequestDelete(ctx, options)
507 }
508
509 func (conn *Conn) ContainerRequestLog(ctx context.Context, options arvados.ContainerLogOptions) (http.Handler, error) {
510         return conn.chooseBackend(options.UUID).ContainerRequestLog(ctx, options)
511 }
512
513 func (conn *Conn) GroupCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Group, error) {
514         return conn.chooseBackend(options.ClusterID).GroupCreate(ctx, options)
515 }
516
517 func (conn *Conn) GroupUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Group, error) {
518         return conn.chooseBackend(options.UUID).GroupUpdate(ctx, options)
519 }
520
521 func (conn *Conn) GroupGet(ctx context.Context, options arvados.GetOptions) (arvados.Group, error) {
522         return conn.chooseBackend(options.UUID).GroupGet(ctx, options)
523 }
524
525 func (conn *Conn) GroupList(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
526         return conn.generated_GroupList(ctx, options)
527 }
528
529 var userUuidRe = regexp.MustCompile(`^[0-9a-z]{5}-tpzed-[0-9a-z]{15}$`)
530
531 func (conn *Conn) GroupContents(ctx context.Context, options arvados.GroupContentsOptions) (arvados.ObjectList, error) {
532         if options.ClusterID != "" {
533                 // explicitly selected cluster
534                 return conn.chooseBackend(options.ClusterID).GroupContents(ctx, options)
535         } else if userUuidRe.MatchString(options.UUID) {
536                 // user, get the things they own on the local cluster
537                 return conn.local.GroupContents(ctx, options)
538         } else {
539                 // a group, potentially want to make federated request
540                 return conn.chooseBackend(options.UUID).GroupContents(ctx, options)
541         }
542 }
543
544 func (conn *Conn) GroupShared(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
545         return conn.chooseBackend(options.ClusterID).GroupShared(ctx, options)
546 }
547
548 func (conn *Conn) GroupDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
549         return conn.chooseBackend(options.UUID).GroupDelete(ctx, options)
550 }
551
552 func (conn *Conn) GroupTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
553         return conn.chooseBackend(options.UUID).GroupTrash(ctx, options)
554 }
555
556 func (conn *Conn) GroupUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Group, error) {
557         return conn.chooseBackend(options.UUID).GroupUntrash(ctx, options)
558 }
559
560 func (conn *Conn) LinkCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Link, error) {
561         return conn.chooseBackend(options.ClusterID).LinkCreate(ctx, options)
562 }
563
564 func (conn *Conn) LinkUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Link, error) {
565         return conn.chooseBackend(options.UUID).LinkUpdate(ctx, options)
566 }
567
568 func (conn *Conn) LinkGet(ctx context.Context, options arvados.GetOptions) (arvados.Link, error) {
569         return conn.chooseBackend(options.UUID).LinkGet(ctx, options)
570 }
571
572 func (conn *Conn) LinkList(ctx context.Context, options arvados.ListOptions) (arvados.LinkList, error) {
573         return conn.generated_LinkList(ctx, options)
574 }
575
576 func (conn *Conn) LinkDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Link, error) {
577         return conn.chooseBackend(options.UUID).LinkDelete(ctx, options)
578 }
579
580 func (conn *Conn) LogCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Log, error) {
581         return conn.chooseBackend(options.ClusterID).LogCreate(ctx, options)
582 }
583
584 func (conn *Conn) LogUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Log, error) {
585         return conn.chooseBackend(options.UUID).LogUpdate(ctx, options)
586 }
587
588 func (conn *Conn) LogGet(ctx context.Context, options arvados.GetOptions) (arvados.Log, error) {
589         return conn.chooseBackend(options.UUID).LogGet(ctx, options)
590 }
591
592 func (conn *Conn) LogList(ctx context.Context, options arvados.ListOptions) (arvados.LogList, error) {
593         return conn.generated_LogList(ctx, options)
594 }
595
596 func (conn *Conn) LogDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Log, error) {
597         return conn.chooseBackend(options.UUID).LogDelete(ctx, options)
598 }
599
600 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
601         return conn.generated_SpecimenList(ctx, options)
602 }
603
604 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
605         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
606 }
607
608 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
609         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
610 }
611
612 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
613         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
614 }
615
616 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
617         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
618 }
619
620 func (conn *Conn) SysTrashSweep(ctx context.Context, options struct{}) (struct{}, error) {
621         return conn.local.SysTrashSweep(ctx, options)
622 }
623
624 var userAttrsCachedFromLoginCluster = map[string]bool{
625         "created_at":  true,
626         "email":       true,
627         "first_name":  true,
628         "is_active":   true,
629         "is_admin":    true,
630         "last_name":   true,
631         "modified_at": true,
632         "prefs":       true,
633         "username":    true,
634         "kind":        true,
635
636         "etag":                    false,
637         "full_name":               false,
638         "identity_url":            false,
639         "is_invited":              false,
640         "modified_by_client_uuid": false,
641         "modified_by_user_uuid":   false,
642         "owner_uuid":              false,
643         "uuid":                    false,
644         "writable_by":             false,
645         "can_write":               false,
646         "can_manage":              false,
647 }
648
649 func (conn *Conn) batchUpdateUsers(ctx context.Context,
650         options arvados.ListOptions,
651         items []arvados.User) (err error) {
652
653         id := conn.cluster.Login.LoginCluster
654         logger := ctxlog.FromContext(ctx)
655         batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
656         for _, user := range items {
657                 if !strings.HasPrefix(user.UUID, id) {
658                         continue
659                 }
660                 logger.Debugf("cache user info for uuid %q", user.UUID)
661
662                 // If the remote cluster has null timestamps
663                 // (e.g., test server with incomplete
664                 // fixtures) use dummy timestamps (instead of
665                 // the zero time, which causes a Rails API
666                 // error "year too big to marshal: 1 UTC").
667                 if user.ModifiedAt.IsZero() {
668                         user.ModifiedAt = time.Now()
669                 }
670                 if user.CreatedAt.IsZero() {
671                         user.CreatedAt = time.Now()
672                 }
673
674                 var allFields map[string]interface{}
675                 buf, err := json.Marshal(user)
676                 if err != nil {
677                         return fmt.Errorf("error encoding user record from remote response: %s", err)
678                 }
679                 err = json.Unmarshal(buf, &allFields)
680                 if err != nil {
681                         return fmt.Errorf("error transcoding user record from remote response: %s", err)
682                 }
683                 updates := allFields
684                 if len(options.Select) > 0 {
685                         updates = map[string]interface{}{}
686                         for _, k := range options.Select {
687                                 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
688                                         updates[k] = v
689                                 }
690                         }
691                 } else {
692                         for k := range updates {
693                                 if !userAttrsCachedFromLoginCluster[k] {
694                                         delete(updates, k)
695                                 }
696                         }
697                 }
698                 batchOpts.Updates[user.UUID] = updates
699         }
700         if len(batchOpts.Updates) > 0 {
701                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
702                 _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
703                 if err != nil {
704                         return fmt.Errorf("error updating local user records: %s", err)
705                 }
706         }
707         return nil
708 }
709
710 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
711         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID && !options.BypassFederation {
712                 resp, err := conn.chooseBackend(id).UserList(ctx, options)
713                 if err != nil {
714                         return resp, err
715                 }
716                 err = conn.batchUpdateUsers(ctx, options, resp.Items)
717                 if err != nil {
718                         return arvados.UserList{}, err
719                 }
720                 return resp, nil
721         }
722         return conn.generated_UserList(ctx, options)
723 }
724
725 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
726         return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
727 }
728
729 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
730         if options.BypassFederation {
731                 return conn.local.UserUpdate(ctx, options)
732         }
733         resp, err := conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
734         if err != nil {
735                 return resp, err
736         }
737         if !strings.HasPrefix(options.UUID, conn.cluster.ClusterID) {
738                 // Copy the updated user record to the local cluster
739                 err = conn.batchUpdateUsers(ctx, arvados.ListOptions{}, []arvados.User{resp})
740                 if err != nil {
741                         return arvados.User{}, err
742                 }
743         }
744         return resp, err
745 }
746
747 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
748         return conn.local.UserMerge(ctx, options)
749 }
750
751 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
752         return conn.localOrLoginCluster().UserActivate(ctx, options)
753 }
754
755 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
756         upstream := conn.localOrLoginCluster()
757         if upstream != conn.local {
758                 // When LoginCluster is in effect, and we're setting
759                 // up a remote user, and we want to give that user
760                 // access to a local VM, we can't include the VM in
761                 // the setup call, because the remote cluster won't
762                 // recognize it.
763
764                 // Similarly, if we want to create a git repo,
765                 // it should be created on the local cluster,
766                 // not the remote one.
767
768                 upstreamOptions := options
769                 upstreamOptions.VMUUID = ""
770                 upstreamOptions.RepoName = ""
771
772                 ret, err := upstream.UserSetup(ctx, upstreamOptions)
773                 if err != nil {
774                         return ret, err
775                 }
776         }
777
778         return conn.local.UserSetup(ctx, options)
779 }
780
781 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
782         return conn.localOrLoginCluster().UserUnsetup(ctx, options)
783 }
784
785 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
786         resp, err := conn.chooseBackend(options.UUID).UserGet(ctx, options)
787         if err != nil {
788                 return resp, err
789         }
790         if options.UUID != resp.UUID {
791                 return arvados.User{}, httpErrorf(http.StatusBadGateway, "Had requested %v but response was for %v", options.UUID, resp.UUID)
792         }
793         if options.UUID[:5] != conn.cluster.ClusterID {
794                 err = conn.batchUpdateUsers(ctx, arvados.ListOptions{Select: options.Select}, []arvados.User{resp})
795                 if err != nil {
796                         return arvados.User{}, err
797                 }
798         }
799         return resp, nil
800 }
801
802 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
803         return conn.local.UserGetCurrent(ctx, options)
804 }
805
806 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
807         return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
808 }
809
810 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
811         return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
812 }
813
814 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
815         return conn.local.UserBatchUpdate(ctx, options)
816 }
817
818 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
819         return conn.local.UserAuthenticate(ctx, options)
820 }
821
822 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
823         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
824 }
825
826 func (conn *Conn) APIClientAuthorizationCreate(ctx context.Context, options arvados.CreateOptions) (arvados.APIClientAuthorization, error) {
827         if conn.cluster.Login.LoginCluster != "" {
828                 return conn.chooseBackend(conn.cluster.Login.LoginCluster).APIClientAuthorizationCreate(ctx, options)
829         }
830         ownerUUID, ok := options.Attrs["owner_uuid"].(string)
831         if ok && ownerUUID != "" {
832                 return conn.chooseBackend(ownerUUID).APIClientAuthorizationCreate(ctx, options)
833         }
834         return conn.local.APIClientAuthorizationCreate(ctx, options)
835 }
836
837 func (conn *Conn) APIClientAuthorizationUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.APIClientAuthorization, error) {
838         if options.BypassFederation {
839                 return conn.local.APIClientAuthorizationUpdate(ctx, options)
840         }
841         return conn.chooseBackend(options.UUID).APIClientAuthorizationUpdate(ctx, options)
842 }
843
844 func (conn *Conn) APIClientAuthorizationDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.APIClientAuthorization, error) {
845         return conn.chooseBackend(options.UUID).APIClientAuthorizationDelete(ctx, options)
846 }
847
848 func (conn *Conn) APIClientAuthorizationList(ctx context.Context, options arvados.ListOptions) (arvados.APIClientAuthorizationList, error) {
849         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID && !options.BypassFederation {
850                 return conn.chooseBackend(conn.cluster.Login.LoginCluster).APIClientAuthorizationList(ctx, options)
851         }
852         return conn.generated_APIClientAuthorizationList(ctx, options)
853 }
854
855 func (conn *Conn) APIClientAuthorizationGet(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
856         return conn.chooseBackend(options.UUID).APIClientAuthorizationGet(ctx, options)
857 }
858
859 type backend interface {
860         arvados.API
861         BaseURL() url.URL
862 }
863
864 type notFoundError struct{}
865
866 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
867 func (notFoundError) Error() string   { return "not found" }
868
869 func errStatus(err error) int {
870         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
871                 return httpErr.HTTPStatus()
872         }
873         return http.StatusInternalServerError
874 }