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