1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
31 cluster *arvados.Cluster
33 remotes map[string]backend
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 {
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
46 conn.SendHeader = http.Header{"Via": {"HTTP/1.1 arvados-controller"}}
50 if healthFuncs != nil {
51 hf := map[string]health.Func{"vocabulary": local.LastVocabularyError}
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
67 func saltedTokenProvider(cluster *arvados.Cluster, local backend, remoteID string) rpc.TokenProvider {
68 return func(ctx context.Context) ([]string, error) {
70 incoming, ok := auth.FromContext(ctx)
72 return nil, errors.New("no token provided")
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)
88 salted, err := auth.SaltToken(token, remoteID)
91 tokens = append(tokens, salted)
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)
104 } else if err != nil {
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)
115 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
119 tokens = append(tokens, salted)
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 {
133 } else if len(id) != 5 {
137 if id == conn.cluster.ClusterID {
139 } else if be, ok := conn.remotes[id]; ok {
142 // TODO: return an "always error" backend?
147 func (conn *Conn) localOrLoginCluster() backend {
148 if conn.cluster.Login.LoginCluster != "" {
149 return conn.chooseBackend(conn.cluster.Login.LoginCluster)
154 // Call fn with the local backend; then, if fn returned 404, call fn
155 // on the available remote backends (possibly concurrently) until one
158 // The second argument to fn is the cluster ID of the remote backend,
159 // or "" for the local backend.
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
172 ctx, cancel := context.WithCancel(ctx)
174 errchan := make(chan error, len(conn.remotes))
175 for remoteID, be := range conn.remotes {
176 remoteID, be := remoteID, be
178 errchan <- fn(ctx, remoteID, be)
181 returncode := http.StatusNotFound
183 for i := 0; i < cap(errchan); i++ {
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
200 if returncode == http.StatusNotFound {
201 return notFoundError{}
203 return httpErrorf(returncode, "errors: %v", errs)
206 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
207 return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
210 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
211 return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
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)
220 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
222 err := config.ExportJSON(&buf, conn.cluster)
223 return json.RawMessage(buf.Bytes()), err
226 func (conn *Conn) VocabularyGet(ctx context.Context) (arvados.Vocabulary, error) {
227 return conn.chooseBackend(conn.cluster.ClusterID).VocabularyGet(ctx)
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]
235 return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
237 baseURL := remote.BaseURL()
238 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
240 return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
242 params := url.Values{
243 "return_to": []string{options.ReturnTo},
245 if options.Remote != "" {
246 params.Set("remote", options.Remote)
248 target.RawQuery = params.Encode()
249 return arvados.LoginResponse{
250 RedirectLocation: target.String(),
253 return conn.local.Login(ctx, options)
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)
265 id := reqauth.Tokens[0][3:8]
266 if id == conn.cluster.ClusterID {
267 return conn.local.Logout(ctx, options)
269 remote, ok := conn.remotes[id]
271 return conn.local.Logout(ctx, options)
273 baseURL := remote.BaseURL()
274 target, err := baseURL.Parse(arvados.EndpointLogout.Path)
276 return arvados.LogoutResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
278 target.RawQuery = url.Values{"return_to": {options.ReturnTo}}.Encode()
279 return arvados.LogoutResponse{RedirectLocation: target.String()}, nil
282 func (conn *Conn) AuthorizedKeyCreate(ctx context.Context, options arvados.CreateOptions) (arvados.AuthorizedKey, error) {
283 return conn.chooseBackend(options.ClusterID).AuthorizedKeyCreate(ctx, options)
286 func (conn *Conn) AuthorizedKeyUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.AuthorizedKey, error) {
287 return conn.chooseBackend(options.UUID).AuthorizedKeyUpdate(ctx, options)
290 func (conn *Conn) AuthorizedKeyGet(ctx context.Context, options arvados.GetOptions) (arvados.AuthorizedKey, error) {
291 return conn.chooseBackend(options.UUID).AuthorizedKeyGet(ctx, options)
294 func (conn *Conn) AuthorizedKeyList(ctx context.Context, options arvados.ListOptions) (arvados.AuthorizedKeyList, error) {
295 return conn.generated_AuthorizedKeyList(ctx, options)
298 func (conn *Conn) AuthorizedKeyDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.AuthorizedKey, error) {
299 return conn.chooseBackend(options.UUID).AuthorizedKeyDelete(ctx, options)
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])
311 if len(options.UUID) < 34 || options.UUID[32] != '+' {
312 return arvados.Collection{}, httpErrorf(http.StatusNotFound, "invalid UUID or PDH %q", options.UUID)
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)
324 if options.Select != nil {
326 for _, s := range options.Select {
327 if s == "manifest_text" {
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)
345 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
351 // lost race, return value doesn't matter
356 return arvados.Collection{}, err
361 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
362 return conn.generated_CollectionList(ctx, options)
365 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
366 return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
369 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
370 return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
373 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
374 return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
377 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
378 return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
381 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
382 return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
385 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
386 return conn.generated_ContainerList(ctx, options)
389 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
390 return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
393 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
394 return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
397 func (conn *Conn) ContainerPriorityUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
398 return conn.chooseBackend(options.UUID).ContainerPriorityUpdate(ctx, options)
401 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
402 return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
405 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
406 return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
409 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
410 return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
413 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
414 return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
417 func (conn *Conn) ContainerSSH(ctx context.Context, options arvados.ContainerSSHOptions) (arvados.ConnectionResponse, error) {
418 return conn.chooseBackend(options.UUID).ContainerSSH(ctx, options)
421 func (conn *Conn) ContainerGatewayTunnel(ctx context.Context, options arvados.ContainerGatewayTunnelOptions) (arvados.ConnectionResponse, error) {
422 return conn.chooseBackend(options.UUID).ContainerGatewayTunnel(ctx, options)
425 func (conn *Conn) ContainerRequestList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerRequestList, error) {
426 return conn.generated_ContainerRequestList(ctx, options)
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)
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{})
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")
445 user, err := conn.local.UserGetCurrent(ctx, arvados.GetOptions{})
447 return arvados.ContainerRequest{}, err
449 if len(aca.Scopes) == 0 || aca.Scopes[0] != "all" {
450 return arvados.ContainerRequest{}, httpErrorf(http.StatusForbidden, "token scope is not [all]")
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)
457 return arvados.ContainerRequest{}, httpErrorf(http.StatusInternalServerError, "bug: local backend is a %T, not a *localdb.Conn", conn.local)
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())})
462 return arvados.ContainerRequest{}, err
464 options.Attrs["runtime_token"] = aca.TokenV2()
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()
472 return be.ContainerRequestCreate(ctx, options)
475 func (conn *Conn) ContainerRequestUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.ContainerRequest, error) {
476 return conn.chooseBackend(options.UUID).ContainerRequestUpdate(ctx, options)
479 func (conn *Conn) ContainerRequestGet(ctx context.Context, options arvados.GetOptions) (arvados.ContainerRequest, error) {
480 return conn.chooseBackend(options.UUID).ContainerRequestGet(ctx, options)
483 func (conn *Conn) ContainerRequestDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.ContainerRequest, error) {
484 return conn.chooseBackend(options.UUID).ContainerRequestDelete(ctx, options)
487 func (conn *Conn) ContainerRequestLog(ctx context.Context, options arvados.ContainerLogOptions) (http.Handler, error) {
488 return conn.chooseBackend(options.UUID).ContainerRequestLog(ctx, options)
491 func (conn *Conn) GroupCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Group, error) {
492 return conn.chooseBackend(options.ClusterID).GroupCreate(ctx, options)
495 func (conn *Conn) GroupUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Group, error) {
496 return conn.chooseBackend(options.UUID).GroupUpdate(ctx, options)
499 func (conn *Conn) GroupGet(ctx context.Context, options arvados.GetOptions) (arvados.Group, error) {
500 return conn.chooseBackend(options.UUID).GroupGet(ctx, options)
503 func (conn *Conn) GroupList(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
504 return conn.generated_GroupList(ctx, options)
507 var userUuidRe = regexp.MustCompile(`^[0-9a-z]{5}-tpzed-[0-9a-z]{15}$`)
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)
517 // a group, potentially want to make federated request
518 return conn.chooseBackend(options.UUID).GroupContents(ctx, options)
522 func (conn *Conn) GroupShared(ctx context.Context, options arvados.ListOptions) (arvados.GroupList, error) {
523 return conn.chooseBackend(options.ClusterID).GroupShared(ctx, options)
526 func (conn *Conn) GroupDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
527 return conn.chooseBackend(options.UUID).GroupDelete(ctx, options)
530 func (conn *Conn) GroupTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Group, error) {
531 return conn.chooseBackend(options.UUID).GroupTrash(ctx, options)
534 func (conn *Conn) GroupUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Group, error) {
535 return conn.chooseBackend(options.UUID).GroupUntrash(ctx, options)
538 func (conn *Conn) LinkCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Link, error) {
539 return conn.chooseBackend(options.ClusterID).LinkCreate(ctx, options)
542 func (conn *Conn) LinkUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Link, error) {
543 return conn.chooseBackend(options.UUID).LinkUpdate(ctx, options)
546 func (conn *Conn) LinkGet(ctx context.Context, options arvados.GetOptions) (arvados.Link, error) {
547 return conn.chooseBackend(options.UUID).LinkGet(ctx, options)
550 func (conn *Conn) LinkList(ctx context.Context, options arvados.ListOptions) (arvados.LinkList, error) {
551 return conn.generated_LinkList(ctx, options)
554 func (conn *Conn) LinkDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Link, error) {
555 return conn.chooseBackend(options.UUID).LinkDelete(ctx, options)
558 func (conn *Conn) LogCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Log, error) {
559 return conn.chooseBackend(options.ClusterID).LogCreate(ctx, options)
562 func (conn *Conn) LogUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Log, error) {
563 return conn.chooseBackend(options.UUID).LogUpdate(ctx, options)
566 func (conn *Conn) LogGet(ctx context.Context, options arvados.GetOptions) (arvados.Log, error) {
567 return conn.chooseBackend(options.UUID).LogGet(ctx, options)
570 func (conn *Conn) LogList(ctx context.Context, options arvados.ListOptions) (arvados.LogList, error) {
571 return conn.generated_LogList(ctx, options)
574 func (conn *Conn) LogDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Log, error) {
575 return conn.chooseBackend(options.UUID).LogDelete(ctx, options)
578 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
579 return conn.generated_SpecimenList(ctx, options)
582 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
583 return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
586 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
587 return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
590 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
591 return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
594 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
595 return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
598 func (conn *Conn) SysTrashSweep(ctx context.Context, options struct{}) (struct{}, error) {
599 return conn.local.SysTrashSweep(ctx, options)
602 var userAttrsCachedFromLoginCluster = map[string]bool{
616 "identity_url": false,
618 "modified_by_client_uuid": false,
619 "modified_by_user_uuid": false,
622 "writable_by": false,
627 func (conn *Conn) batchUpdateUsers(ctx context.Context,
628 options arvados.ListOptions,
629 items []arvados.User) (err error) {
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) {
638 logger.Debugf("cache user info for uuid %q", user.UUID)
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()
648 if user.CreatedAt.IsZero() {
649 user.CreatedAt = time.Now()
652 var allFields map[string]interface{}
653 buf, err := json.Marshal(user)
655 return fmt.Errorf("error encoding user record from remote response: %s", err)
657 err = json.Unmarshal(buf, &allFields)
659 return fmt.Errorf("error transcoding user record from remote response: %s", err)
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] {
670 for k := range updates {
671 if !userAttrsCachedFromLoginCluster[k] {
676 batchOpts.Updates[user.UUID] = updates
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)
682 return fmt.Errorf("error updating local user records: %s", err)
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)
694 err = conn.batchUpdateUsers(ctx, options, resp.Items)
696 return arvados.UserList{}, err
700 return conn.generated_UserList(ctx, options)
703 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
704 return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
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)
711 resp, err := conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
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})
719 return arvados.User{}, err
725 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
726 return conn.local.UserMerge(ctx, options)
729 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
730 return conn.localOrLoginCluster().UserActivate(ctx, options)
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
742 // Similarly, if we want to create a git repo,
743 // it should be created on the local cluster,
744 // not the remote one.
746 upstreamOptions := options
747 upstreamOptions.VMUUID = ""
748 upstreamOptions.RepoName = ""
750 ret, err := upstream.UserSetup(ctx, upstreamOptions)
756 return conn.local.UserSetup(ctx, options)
759 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
760 return conn.localOrLoginCluster().UserUnsetup(ctx, options)
763 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
764 resp, err := conn.chooseBackend(options.UUID).UserGet(ctx, options)
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)
771 if options.UUID[:5] != conn.cluster.ClusterID {
772 err = conn.batchUpdateUsers(ctx, arvados.ListOptions{Select: options.Select}, []arvados.User{resp})
774 return arvados.User{}, err
780 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
781 return conn.local.UserGetCurrent(ctx, options)
784 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
785 return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
788 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
789 return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
792 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
793 return conn.local.UserBatchUpdate(ctx, options)
796 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
797 return conn.local.UserAuthenticate(ctx, options)
800 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
801 return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
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)
808 ownerUUID, ok := options.Attrs["owner_uuid"].(string)
809 if ok && ownerUUID != "" {
810 return conn.chooseBackend(ownerUUID).APIClientAuthorizationCreate(ctx, options)
812 return conn.local.APIClientAuthorizationCreate(ctx, options)
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)
819 return conn.chooseBackend(options.UUID).APIClientAuthorizationUpdate(ctx, options)
822 func (conn *Conn) APIClientAuthorizationDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.APIClientAuthorization, error) {
823 return conn.chooseBackend(options.UUID).APIClientAuthorizationDelete(ctx, options)
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)
830 return conn.generated_APIClientAuthorizationList(ctx, options)
833 func (conn *Conn) APIClientAuthorizationGet(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
834 return conn.chooseBackend(options.UUID).APIClientAuthorizationGet(ctx, options)
837 type backend interface {
842 type notFoundError struct{}
844 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
845 func (notFoundError) Error() string { return "not found" }
847 func errStatus(err error) int {
848 if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
849 return httpErr.HTTPStatus()
851 return http.StatusInternalServerError