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