9d01f1f7c58230c7865688014ab01644bbae2c74
[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
19         "git.curoverse.com/arvados.git/lib/config"
20         "git.curoverse.com/arvados.git/lib/controller/localdb"
21         "git.curoverse.com/arvados.git/lib/controller/rpc"
22         "git.curoverse.com/arvados.git/sdk/go/arvados"
23         "git.curoverse.com/arvados.git/sdk/go/auth"
24         "git.curoverse.com/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 {
38                         continue
39                 }
40                 remotes[id] = rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(local, id))
41         }
42
43         return &Conn{
44                 cluster: cluster,
45                 local:   local,
46                 remotes: remotes,
47         }
48 }
49
50 // Return a new rpc.TokenProvider that takes the client-provided
51 // tokens from an incoming request context, determines whether they
52 // should (and can) be salted for the given remoteID, and returns the
53 // resulting tokens.
54 func saltedTokenProvider(local backend, remoteID string) rpc.TokenProvider {
55         return func(ctx context.Context) ([]string, error) {
56                 var tokens []string
57                 incoming, ok := auth.FromContext(ctx)
58                 if !ok {
59                         return nil, errors.New("no token provided")
60                 }
61                 for _, token := range incoming.Tokens {
62                         salted, err := auth.SaltToken(token, remoteID)
63                         switch err {
64                         case nil:
65                                 tokens = append(tokens, salted)
66                         case auth.ErrSalted:
67                                 tokens = append(tokens, token)
68                         case auth.ErrObsoleteToken:
69                                 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
70                                 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
71                                 if errStatus(err) == http.StatusUnauthorized {
72                                         // pass through unmodified
73                                         tokens = append(tokens, token)
74                                         continue
75                                 } else if err != nil {
76                                         return nil, err
77                                 }
78                                 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
79                                 if err != nil {
80                                         return nil, err
81                                 }
82                                 tokens = append(tokens, salted)
83                         default:
84                                 return nil, err
85                         }
86                 }
87                 return tokens, nil
88         }
89 }
90
91 // Return suitable backend for a query about the given cluster ID
92 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
93 func (conn *Conn) chooseBackend(id string) backend {
94         if len(id) == 27 {
95                 id = id[:5]
96         } else if len(id) != 5 {
97                 // PDH or bogus ID
98                 return conn.local
99         }
100         if id == conn.cluster.ClusterID {
101                 return conn.local
102         } else if be, ok := conn.remotes[id]; ok {
103                 return be
104         } else {
105                 // TODO: return an "always error" backend?
106                 return conn.local
107         }
108 }
109
110 // Call fn with the local backend; then, if fn returned 404, call fn
111 // on the available remote backends (possibly concurrently) until one
112 // succeeds.
113 //
114 // The second argument to fn is the cluster ID of the remote backend,
115 // or "" for the local backend.
116 //
117 // A non-nil error means all backends failed.
118 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, fn func(context.Context, string, backend) error) error {
119         if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound {
120                 return err
121         }
122
123         ctx, cancel := context.WithCancel(ctx)
124         defer cancel()
125         errchan := make(chan error, len(conn.remotes))
126         for remoteID, be := range conn.remotes {
127                 remoteID, be := remoteID, be
128                 go func() {
129                         errchan <- fn(ctx, remoteID, be)
130                 }()
131         }
132         all404 := true
133         var errs []error
134         for i := 0; i < cap(errchan); i++ {
135                 err := <-errchan
136                 if err == nil {
137                         return nil
138                 }
139                 all404 = all404 && errStatus(err) == http.StatusNotFound
140                 errs = append(errs, err)
141         }
142         if all404 {
143                 return notFoundError{}
144         }
145         return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
146 }
147
148 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
149         return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
150 }
151
152 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
153         return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
154 }
155
156 func rewriteManifest(mt, remoteID string) string {
157         return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
158                 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
159         })
160 }
161
162 // this could be in sdk/go/arvados
163 func portableDataHash(mt string) string {
164         h := md5.New()
165         blkRe := regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
166         size := 0
167         _ = regexp.MustCompile(` ?[^ ]*`).ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
168                 if m := blkRe.Find(tok); m != nil {
169                         // write hash+size, ignore remaining block hints
170                         tok = m
171                 }
172                 n, err := h.Write(tok)
173                 if err != nil {
174                         panic(err)
175                 }
176                 size += n
177                 return nil
178         })
179         return fmt.Sprintf("%x+%d", h.Sum(nil), size)
180 }
181
182 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
183         var buf bytes.Buffer
184         err := config.ExportJSON(&buf, conn.cluster)
185         return json.RawMessage(buf.Bytes()), err
186 }
187
188 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
189         if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
190                 // defer entire login procedure to designated cluster
191                 remote, ok := conn.remotes[id]
192                 if !ok {
193                         return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
194                 }
195                 baseURL := remote.BaseURL()
196                 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
197                 if err != nil {
198                         return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
199                 }
200                 target.RawQuery = url.Values{
201                         "return_to": []string{options.ReturnTo},
202                         "remote":    []string{options.Remote},
203                 }.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) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
213         if len(options.UUID) == 27 {
214                 // UUID is really a UUID
215                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
216                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
217                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
218                 }
219                 return c, err
220         } else {
221                 // UUID is a PDH
222                 first := make(chan arvados.Collection, 1)
223                 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
224                         c, err := be.CollectionGet(ctx, options)
225                         if err != nil {
226                                 return err
227                         }
228                         // options.UUID is either hash+size or
229                         // hash+size+hints; only hash+size need to
230                         // match the computed PDH.
231                         if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
232                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
233                                 ctxlog.FromContext(ctx).Warn(err)
234                                 return err
235                         }
236                         if remoteID != "" {
237                                 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
238                         }
239                         select {
240                         case first <- c:
241                                 return nil
242                         default:
243                                 // lost race, return value doesn't matter
244                                 return nil
245                         }
246                 })
247                 if err != nil {
248                         return arvados.Collection{}, err
249                 }
250                 return <-first, nil
251         }
252 }
253
254 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
255         return conn.generated_CollectionList(ctx, options)
256 }
257
258 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
259         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
260 }
261
262 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
263         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
264 }
265
266 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
267         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
268 }
269
270 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
271         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
272 }
273
274 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
275         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
276 }
277
278 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
279         return conn.generated_ContainerList(ctx, options)
280 }
281
282 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
283         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
284 }
285
286 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
287         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
288 }
289
290 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
291         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
292 }
293
294 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
295         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
296 }
297
298 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
299         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
300 }
301
302 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
303         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
304 }
305
306 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
307         return conn.generated_SpecimenList(ctx, options)
308 }
309
310 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
311         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
312 }
313
314 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
315         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
316 }
317
318 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
319         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
320 }
321
322 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
323         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
324 }
325
326 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
327         return conn.generated_UserList(ctx, options)
328 }
329
330 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
331         return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
332 }
333
334 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
335         return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
336 }
337
338 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
339         return conn.chooseBackend(options.UUID).UserUpdateUUID(ctx, options)
340 }
341
342 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
343         return conn.chooseBackend(options.OldUserUUID).UserMerge(ctx, options)
344 }
345
346 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
347         return conn.chooseBackend(options.UUID).UserActivate(ctx, options)
348 }
349
350 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
351         return conn.chooseBackend(options.UUID).UserSetup(ctx, options)
352 }
353
354 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
355         return conn.chooseBackend(options.UUID).UserUnsetup(ctx, options)
356 }
357
358 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
359         return conn.chooseBackend(options.UUID).UserGet(ctx, options)
360 }
361
362 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
363         return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
364 }
365
366 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
367         return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
368 }
369
370 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
371         return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
372 }
373
374 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
375         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
376 }
377
378 type backend interface {
379         arvados.API
380         BaseURL() url.URL
381 }
382
383 type notFoundError struct{}
384
385 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
386 func (notFoundError) Error() string   { return "not found" }
387
388 func errStatus(err error) int {
389         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
390                 return httpErr.HTTPStatus()
391         } else {
392                 return http.StatusInternalServerError
393         }
394 }