16811: Add a test that system users/groups can't be deleted.
[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 )
26
27 type Conn struct {
28         cluster *arvados.Cluster
29         local   backend
30         remotes map[string]backend
31 }
32
33 func New(cluster *arvados.Cluster) *Conn {
34         local := localdb.NewConn(cluster)
35         remotes := map[string]backend{}
36         for id, remote := range cluster.RemoteClusters {
37                 if !remote.Proxy || id == cluster.ClusterID {
38                         continue
39                 }
40                 conn := rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(local, id))
41                 // Older versions of controller rely on the Via header
42                 // to detect loops.
43                 conn.SendHeader = http.Header{"Via": {"HTTP/1.1 arvados-controller"}}
44                 remotes[id] = conn
45         }
46
47         return &Conn{
48                 cluster: cluster,
49                 local:   local,
50                 remotes: remotes,
51         }
52 }
53
54 // Return a new rpc.TokenProvider that takes the client-provided
55 // tokens from an incoming request context, determines whether they
56 // should (and can) be salted for the given remoteID, and returns the
57 // resulting tokens.
58 func saltedTokenProvider(local backend, remoteID string) rpc.TokenProvider {
59         return func(ctx context.Context) ([]string, error) {
60                 var tokens []string
61                 incoming, ok := auth.FromContext(ctx)
62                 if !ok {
63                         return nil, errors.New("no token provided")
64                 }
65                 for _, token := range incoming.Tokens {
66                         salted, err := auth.SaltToken(token, remoteID)
67                         switch err {
68                         case nil:
69                                 tokens = append(tokens, salted)
70                         case auth.ErrSalted:
71                                 tokens = append(tokens, token)
72                         case auth.ErrObsoleteToken:
73                                 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
74                                 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
75                                 if errStatus(err) == http.StatusUnauthorized {
76                                         // pass through unmodified
77                                         tokens = append(tokens, token)
78                                         continue
79                                 } else if err != nil {
80                                         return nil, err
81                                 }
82                                 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
83                                 if err != nil {
84                                         return nil, err
85                                 }
86                                 tokens = append(tokens, salted)
87                         default:
88                                 return nil, err
89                         }
90                 }
91                 return tokens, nil
92         }
93 }
94
95 // Return suitable backend for a query about the given cluster ID
96 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
97 func (conn *Conn) chooseBackend(id string) backend {
98         if len(id) == 27 {
99                 id = id[:5]
100         } else if len(id) != 5 {
101                 // PDH or bogus ID
102                 return conn.local
103         }
104         if id == conn.cluster.ClusterID {
105                 return conn.local
106         } else if be, ok := conn.remotes[id]; ok {
107                 return be
108         } else {
109                 // TODO: return an "always error" backend?
110                 return conn.local
111         }
112 }
113
114 func (conn *Conn) localOrLoginCluster() backend {
115         if conn.cluster.Login.LoginCluster != "" {
116                 return conn.chooseBackend(conn.cluster.Login.LoginCluster)
117         } else {
118                 return conn.local
119         }
120 }
121
122 // Call fn with the local backend; then, if fn returned 404, call fn
123 // on the available remote backends (possibly concurrently) until one
124 // succeeds.
125 //
126 // The second argument to fn is the cluster ID of the remote backend,
127 // or "" for the local backend.
128 //
129 // A non-nil error means all backends failed.
130 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, forwardedFor string, fn func(context.Context, string, backend) error) error {
131         if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound || forwardedFor != "" {
132                 // Note: forwardedFor != "" means this request came
133                 // from a remote cluster, so we don't take a second
134                 // hop. This avoids cycles, redundant calls to a
135                 // mutually reachable remote, and use of double-salted
136                 // tokens.
137                 return err
138         }
139
140         ctx, cancel := context.WithCancel(ctx)
141         defer cancel()
142         errchan := make(chan error, len(conn.remotes))
143         for remoteID, be := range conn.remotes {
144                 remoteID, be := remoteID, be
145                 go func() {
146                         errchan <- fn(ctx, remoteID, be)
147                 }()
148         }
149         all404 := true
150         var errs []error
151         for i := 0; i < cap(errchan); i++ {
152                 err := <-errchan
153                 if err == nil {
154                         return nil
155                 }
156                 all404 = all404 && errStatus(err) == http.StatusNotFound
157                 errs = append(errs, err)
158         }
159         if all404 {
160                 return notFoundError{}
161         }
162         return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
163 }
164
165 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
166         return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
167 }
168
169 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
170         return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
171 }
172
173 func rewriteManifest(mt, remoteID string) string {
174         return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
175                 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
176         })
177 }
178
179 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
180         var buf bytes.Buffer
181         err := config.ExportJSON(&buf, conn.cluster)
182         return json.RawMessage(buf.Bytes()), err
183 }
184
185 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
186         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
187                 // defer entire login procedure to designated cluster
188                 remote, ok := conn.remotes[id]
189                 if !ok {
190                         return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
191                 }
192                 baseURL := remote.BaseURL()
193                 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
194                 if err != nil {
195                         return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
196                 }
197                 params := url.Values{
198                         "return_to": []string{options.ReturnTo},
199                 }
200                 if options.Remote != "" {
201                         params.Set("remote", options.Remote)
202                 }
203                 target.RawQuery = params.Encode()
204                 return arvados.LoginResponse{
205                         RedirectLocation: target.String(),
206                 }, nil
207         } else {
208                 return conn.local.Login(ctx, options)
209         }
210 }
211
212 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
213         // If the logout request comes with an API token from a known
214         // remote cluster, redirect to that cluster's logout handler
215         // so it has an opportunity to clear sessions, expire tokens,
216         // etc. Otherwise use the local endpoint.
217         reqauth, ok := auth.FromContext(ctx)
218         if !ok || len(reqauth.Tokens) == 0 || len(reqauth.Tokens[0]) < 8 || !strings.HasPrefix(reqauth.Tokens[0], "v2/") {
219                 return conn.local.Logout(ctx, options)
220         }
221         id := reqauth.Tokens[0][3:8]
222         if id == conn.cluster.ClusterID {
223                 return conn.local.Logout(ctx, options)
224         }
225         remote, ok := conn.remotes[id]
226         if !ok {
227                 return conn.local.Logout(ctx, options)
228         }
229         baseURL := remote.BaseURL()
230         target, err := baseURL.Parse(arvados.EndpointLogout.Path)
231         if err != nil {
232                 return arvados.LogoutResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
233         }
234         target.RawQuery = url.Values{"return_to": {options.ReturnTo}}.Encode()
235         return arvados.LogoutResponse{RedirectLocation: target.String()}, nil
236 }
237
238 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
239         if len(options.UUID) == 27 {
240                 // UUID is really a UUID
241                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
242                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
243                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
244                 }
245                 return c, err
246         } else {
247                 // UUID is a PDH
248                 first := make(chan arvados.Collection, 1)
249                 err := conn.tryLocalThenRemotes(ctx, options.ForwardedFor, func(ctx context.Context, remoteID string, be backend) error {
250                         remoteOpts := options
251                         remoteOpts.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
252                         c, err := be.CollectionGet(ctx, remoteOpts)
253                         if err != nil {
254                                 return err
255                         }
256                         // options.UUID is either hash+size or
257                         // hash+size+hints; only hash+size need to
258                         // match the computed PDH.
259                         if pdh := arvados.PortableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
260                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
261                                 ctxlog.FromContext(ctx).Warn(err)
262                                 return err
263                         }
264                         if remoteID != "" {
265                                 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
266                         }
267                         select {
268                         case first <- c:
269                                 return nil
270                         default:
271                                 // lost race, return value doesn't matter
272                                 return nil
273                         }
274                 })
275                 if err != nil {
276                         return arvados.Collection{}, err
277                 }
278                 return <-first, nil
279         }
280 }
281
282 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
283         return conn.generated_CollectionList(ctx, options)
284 }
285
286 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
287         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
288 }
289
290 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
291         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
292 }
293
294 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
295         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
296 }
297
298 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
299         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
300 }
301
302 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
303         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
304 }
305
306 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
307         return conn.generated_ContainerList(ctx, options)
308 }
309
310 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
311         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
312 }
313
314 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
315         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
316 }
317
318 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
319         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
320 }
321
322 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
323         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
324 }
325
326 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
327         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
328 }
329
330 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
331         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
332 }
333
334 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
335         return conn.generated_SpecimenList(ctx, options)
336 }
337
338 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
339         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
340 }
341
342 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
343         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
344 }
345
346 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
347         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
348 }
349
350 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
351         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
352 }
353
354 var userAttrsCachedFromLoginCluster = map[string]bool{
355         "created_at":  true,
356         "email":       true,
357         "first_name":  true,
358         "is_active":   true,
359         "is_admin":    true,
360         "last_name":   true,
361         "modified_at": true,
362         "prefs":       true,
363         "username":    true,
364
365         "etag":                    false,
366         "full_name":               false,
367         "identity_url":            false,
368         "is_invited":              false,
369         "modified_by_client_uuid": false,
370         "modified_by_user_uuid":   false,
371         "owner_uuid":              false,
372         "uuid":                    false,
373         "writable_by":             false,
374 }
375
376 func (conn *Conn) batchUpdateUsers(ctx context.Context,
377         options arvados.ListOptions,
378         items []arvados.User) (err error) {
379
380         id := conn.cluster.Login.LoginCluster
381         logger := ctxlog.FromContext(ctx)
382         batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
383         for _, user := range items {
384                 if !strings.HasPrefix(user.UUID, id) {
385                         continue
386                 }
387                 logger.Debugf("cache user info for uuid %q", user.UUID)
388
389                 // If the remote cluster has null timestamps
390                 // (e.g., test server with incomplete
391                 // fixtures) use dummy timestamps (instead of
392                 // the zero time, which causes a Rails API
393                 // error "year too big to marshal: 1 UTC").
394                 if user.ModifiedAt.IsZero() {
395                         user.ModifiedAt = time.Now()
396                 }
397                 if user.CreatedAt.IsZero() {
398                         user.CreatedAt = time.Now()
399                 }
400
401                 var allFields map[string]interface{}
402                 buf, err := json.Marshal(user)
403                 if err != nil {
404                         return fmt.Errorf("error encoding user record from remote response: %s", err)
405                 }
406                 err = json.Unmarshal(buf, &allFields)
407                 if err != nil {
408                         return fmt.Errorf("error transcoding user record from remote response: %s", err)
409                 }
410                 updates := allFields
411                 if len(options.Select) > 0 {
412                         updates = map[string]interface{}{}
413                         for _, k := range options.Select {
414                                 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
415                                         updates[k] = v
416                                 }
417                         }
418                 } else {
419                         for k := range updates {
420                                 if !userAttrsCachedFromLoginCluster[k] {
421                                         delete(updates, k)
422                                 }
423                         }
424                 }
425                 batchOpts.Updates[user.UUID] = updates
426         }
427         if len(batchOpts.Updates) > 0 {
428                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
429                 _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
430                 if err != nil {
431                         return fmt.Errorf("error updating local user records: %s", err)
432                 }
433         }
434         return nil
435 }
436
437 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
438         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID && !options.BypassFederation {
439                 resp, err := conn.chooseBackend(id).UserList(ctx, options)
440                 if err != nil {
441                         return resp, err
442                 }
443                 err = conn.batchUpdateUsers(ctx, options, resp.Items)
444                 if err != nil {
445                         return arvados.UserList{}, err
446                 }
447                 return resp, nil
448         } else {
449                 return conn.generated_UserList(ctx, options)
450         }
451 }
452
453 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
454         return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
455 }
456
457 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
458         if options.BypassFederation {
459                 return conn.local.UserUpdate(ctx, options)
460         }
461         return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
462 }
463
464 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
465         return conn.local.UserUpdateUUID(ctx, options)
466 }
467
468 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
469         return conn.local.UserMerge(ctx, options)
470 }
471
472 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
473         return conn.localOrLoginCluster().UserActivate(ctx, options)
474 }
475
476 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
477         upstream := conn.localOrLoginCluster()
478         if upstream != conn.local {
479                 // When LoginCluster is in effect, and we're setting
480                 // up a remote user, and we want to give that user
481                 // access to a local VM, we can't include the VM in
482                 // the setup call, because the remote cluster won't
483                 // recognize it.
484
485                 // Similarly, if we want to create a git repo,
486                 // it should be created on the local cluster,
487                 // not the remote one.
488
489                 upstreamOptions := options
490                 upstreamOptions.VMUUID = ""
491                 upstreamOptions.RepoName = ""
492
493                 ret, err := upstream.UserSetup(ctx, upstreamOptions)
494                 if err != nil {
495                         return ret, err
496                 }
497         }
498
499         return conn.local.UserSetup(ctx, options)
500 }
501
502 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
503         return conn.localOrLoginCluster().UserUnsetup(ctx, options)
504 }
505
506 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
507         return conn.chooseBackend(options.UUID).UserGet(ctx, options)
508 }
509
510 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
511         return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
512 }
513
514 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
515         return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
516 }
517
518 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
519         return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
520 }
521
522 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
523         return conn.local.UserBatchUpdate(ctx, options)
524 }
525
526 func (conn *Conn) UserAuthenticate(ctx context.Context, options arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
527         return conn.local.UserAuthenticate(ctx, options)
528 }
529
530 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
531         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
532 }
533
534 type backend interface {
535         arvados.API
536         BaseURL() url.URL
537 }
538
539 type notFoundError struct{}
540
541 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
542 func (notFoundError) Error() string   { return "not found" }
543
544 func errStatus(err error) int {
545         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
546                 return httpErr.HTTPStatus()
547         } else {
548                 return http.StatusInternalServerError
549         }
550 }