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