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