4d4141ffd6a04b7b3fe793607959c678fe4a25b9
[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, fn func(context.Context, string, backend) error) error {
124         if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound {
125                 return err
126         }
127
128         ctx, cancel := context.WithCancel(ctx)
129         defer cancel()
130         errchan := make(chan error, len(conn.remotes))
131         for remoteID, be := range conn.remotes {
132                 remoteID, be := remoteID, be
133                 go func() {
134                         errchan <- fn(ctx, remoteID, be)
135                 }()
136         }
137         all404 := true
138         var errs []error
139         for i := 0; i < cap(errchan); i++ {
140                 err := <-errchan
141                 if err == nil {
142                         return nil
143                 }
144                 all404 = all404 && errStatus(err) == http.StatusNotFound
145                 errs = append(errs, err)
146         }
147         if all404 {
148                 return notFoundError{}
149         }
150         return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
151 }
152
153 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
154         return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
155 }
156
157 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
158         return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
159 }
160
161 func rewriteManifest(mt, remoteID string) string {
162         return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
163                 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
164         })
165 }
166
167 // this could be in sdk/go/arvados
168 func portableDataHash(mt string) string {
169         h := md5.New()
170         blkRe := regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
171         size := 0
172         _ = regexp.MustCompile(` ?[^ ]*`).ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
173                 if m := blkRe.Find(tok); m != nil {
174                         // write hash+size, ignore remaining block hints
175                         tok = m
176                 }
177                 n, err := h.Write(tok)
178                 if err != nil {
179                         panic(err)
180                 }
181                 size += n
182                 return nil
183         })
184         return fmt.Sprintf("%x+%d", h.Sum(nil), size)
185 }
186
187 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
188         var buf bytes.Buffer
189         err := config.ExportJSON(&buf, conn.cluster)
190         return json.RawMessage(buf.Bytes()), err
191 }
192
193 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
194         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
195                 // defer entire login procedure to designated cluster
196                 remote, ok := conn.remotes[id]
197                 if !ok {
198                         return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
199                 }
200                 baseURL := remote.BaseURL()
201                 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
202                 if err != nil {
203                         return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
204                 }
205                 params := url.Values{
206                         "return_to": []string{options.ReturnTo},
207                 }
208                 if options.Remote != "" {
209                         params.Set("remote", options.Remote)
210                 }
211                 target.RawQuery = params.Encode()
212                 return arvados.LoginResponse{
213                         RedirectLocation: target.String(),
214                 }, nil
215         } else {
216                 return conn.local.Login(ctx, options)
217         }
218 }
219
220 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
221         downstream := options.ForwardedFor
222         options.ForwardedFor = conn.cluster.ClusterID + "-" + downstream
223         if len(options.UUID) == 27 {
224                 // UUID is really a UUID
225                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
226                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
227                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
228                 }
229                 return c, err
230         } else {
231                 // UUID is a PDH
232                 first := make(chan arvados.Collection, 1)
233                 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
234                         if remoteID != "" && strings.Contains(downstream, remoteID) {
235                                 return notFoundError{}
236                         }
237                         c, err := be.CollectionGet(ctx, options)
238                         if err != nil {
239                                 return err
240                         }
241                         // options.UUID is either hash+size or
242                         // hash+size+hints; only hash+size need to
243                         // match the computed PDH.
244                         if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
245                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
246                                 ctxlog.FromContext(ctx).Warn(err)
247                                 return err
248                         }
249                         if remoteID != "" {
250                                 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
251                         }
252                         select {
253                         case first <- c:
254                                 return nil
255                         default:
256                                 // lost race, return value doesn't matter
257                                 return nil
258                         }
259                 })
260                 if err != nil {
261                         return arvados.Collection{}, err
262                 }
263                 return <-first, nil
264         }
265 }
266
267 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
268         return conn.generated_CollectionList(ctx, options)
269 }
270
271 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
272         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
273 }
274
275 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
276         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
277 }
278
279 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
280         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
281 }
282
283 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
284         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
285 }
286
287 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
288         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
289 }
290
291 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
292         return conn.generated_ContainerList(ctx, options)
293 }
294
295 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
296         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
297 }
298
299 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
300         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
301 }
302
303 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
304         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
305 }
306
307 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
308         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
309 }
310
311 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
312         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
313 }
314
315 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
316         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
317 }
318
319 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
320         return conn.generated_SpecimenList(ctx, options)
321 }
322
323 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
324         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
325 }
326
327 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
328         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
329 }
330
331 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
332         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
333 }
334
335 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
336         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
337 }
338
339 var userAttrsCachedFromLoginCluster = map[string]bool{
340         "created_at":              true,
341         "email":                   true,
342         "first_name":              true,
343         "is_active":               true,
344         "is_admin":                true,
345         "last_name":               true,
346         "modified_at":             true,
347         "modified_by_client_uuid": true,
348         "modified_by_user_uuid":   true,
349         "prefs":                   true,
350         "username":                true,
351
352         "etag":         false,
353         "full_name":    false,
354         "identity_url": false,
355         "is_invited":   false,
356         "owner_uuid":   false,
357         "uuid":         false,
358         "writable_by":  false,
359 }
360
361 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
362         logger := ctxlog.FromContext(ctx)
363         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
364                 resp, err := conn.chooseBackend(id).UserList(ctx, options)
365                 if err != nil {
366                         return resp, err
367                 }
368                 batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
369                 for _, user := range resp.Items {
370                         if !strings.HasPrefix(user.UUID, id) {
371                                 continue
372                         }
373                         logger.Debugf("cache user info for uuid %q", user.UUID)
374
375                         // If the remote cluster has null timestamps
376                         // (e.g., test server with incomplete
377                         // fixtures) use dummy timestamps (instead of
378                         // the zero time, which causes a Rails API
379                         // error "year too big to marshal: 1 UTC").
380                         if user.ModifiedAt.IsZero() {
381                                 user.ModifiedAt = time.Now()
382                         }
383                         if user.CreatedAt.IsZero() {
384                                 user.CreatedAt = time.Now()
385                         }
386
387                         var allFields map[string]interface{}
388                         buf, err := json.Marshal(user)
389                         if err != nil {
390                                 return arvados.UserList{}, fmt.Errorf("error encoding user record from remote response: %s", err)
391                         }
392                         err = json.Unmarshal(buf, &allFields)
393                         if err != nil {
394                                 return arvados.UserList{}, fmt.Errorf("error transcoding user record from remote response: %s", err)
395                         }
396                         updates := allFields
397                         if len(options.Select) > 0 {
398                                 updates = map[string]interface{}{}
399                                 for _, k := range options.Select {
400                                         if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
401                                                 updates[k] = v
402                                         }
403                                 }
404                         } else {
405                                 for k := range updates {
406                                         if !userAttrsCachedFromLoginCluster[k] {
407                                                 delete(updates, k)
408                                         }
409                                 }
410                         }
411                         batchOpts.Updates[user.UUID] = updates
412                 }
413                 if len(batchOpts.Updates) > 0 {
414                         ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
415                         _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
416                         if err != nil {
417                                 return arvados.UserList{}, fmt.Errorf("error updating local user records: %s", err)
418                         }
419                 }
420                 return resp, nil
421         } else {
422                 return conn.generated_UserList(ctx, options)
423         }
424 }
425
426 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
427         return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
428 }
429
430 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
431         return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
432 }
433
434 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
435         return conn.chooseBackend(options.UUID).UserUpdateUUID(ctx, options)
436 }
437
438 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
439         return conn.chooseBackend(options.OldUserUUID).UserMerge(ctx, options)
440 }
441
442 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
443         return conn.chooseBackend(options.UUID).UserActivate(ctx, options)
444 }
445
446 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
447         return conn.chooseBackend(options.UUID).UserSetup(ctx, options)
448 }
449
450 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
451         return conn.chooseBackend(options.UUID).UserUnsetup(ctx, options)
452 }
453
454 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
455         return conn.chooseBackend(options.UUID).UserGet(ctx, options)
456 }
457
458 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
459         return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
460 }
461
462 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
463         return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
464 }
465
466 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
467         return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
468 }
469
470 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
471         return conn.local.UserBatchUpdate(ctx, options)
472 }
473
474 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
475         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
476 }
477
478 type backend interface {
479         arvados.API
480         BaseURL() url.URL
481 }
482
483 type notFoundError struct{}
484
485 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
486 func (notFoundError) Error() string   { return "not found" }
487
488 func errStatus(err error) int {
489         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
490                 return httpErr.HTTPStatus()
491         } else {
492                 return http.StatusInternalServerError
493         }
494 }