Merge branch '14813-config-cors'
[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/railsproxy"
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 := railsproxy.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         // FIXME: choose appropriate HTTP status
146         return fmt.Errorf("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) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
190         if len(options.UUID) == 27 {
191                 // UUID is really a UUID
192                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
193                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
194                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
195                 }
196                 return c, err
197         } else {
198                 // UUID is a PDH
199                 first := make(chan arvados.Collection, 1)
200                 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
201                         c, err := be.CollectionGet(ctx, options)
202                         if err != nil {
203                                 return err
204                         }
205                         // options.UUID is either hash+size or
206                         // hash+size+hints; only hash+size need to
207                         // match the computed PDH.
208                         if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
209                                 ctxlog.FromContext(ctx).Warnf("bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
210                                 return notFoundError{}
211                         }
212                         if remoteID != "" {
213                                 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
214                         }
215                         select {
216                         case first <- c:
217                                 return nil
218                         default:
219                                 // lost race, return value doesn't matter
220                                 return nil
221                         }
222                 })
223                 if err != nil {
224                         return arvados.Collection{}, err
225                 }
226                 return <-first, nil
227         }
228 }
229
230 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
231         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
232 }
233
234 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
235         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
236 }
237
238 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
239         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
240 }
241
242 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
243         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
244 }
245
246 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
247         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
248 }
249
250 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
251         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
252 }
253
254 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
255         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
256 }
257
258 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
259         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
260 }
261
262 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
263         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
264 }
265
266 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
267         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
268 }
269
270 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
271         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
272 }
273
274 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
275         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
276 }
277
278 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
279         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
280 }
281
282 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
283         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
284 }
285
286 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
287         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
288 }
289
290 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
291         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
292 }
293
294 type backend interface{ arvados.API }
295
296 type notFoundError struct{}
297
298 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
299 func (notFoundError) Error() string   { return "not found" }
300
301 func errStatus(err error) int {
302         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
303                 return httpErr.HTTPStatus()
304         } else {
305                 return http.StatusInternalServerError
306         }
307 }