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