15851: Merge branch 'master' into 15851-empty-items-array
[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                 params := url.Values{
201                         "return_to": []string{options.ReturnTo},
202                 }
203                 if options.Remote != "" {
204                         params.Set("remote", options.Remote)
205                 }
206                 target.RawQuery = params.Encode()
207                 return arvados.LoginResponse{
208                         RedirectLocation: target.String(),
209                 }, nil
210         } else {
211                 return conn.local.Login(ctx, options)
212         }
213 }
214
215 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
216         if len(options.UUID) == 27 {
217                 // UUID is really a UUID
218                 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
219                 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
220                         c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
221                 }
222                 return c, err
223         } else {
224                 // UUID is a PDH
225                 first := make(chan arvados.Collection, 1)
226                 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
227                         c, err := be.CollectionGet(ctx, options)
228                         if err != nil {
229                                 return err
230                         }
231                         // options.UUID is either hash+size or
232                         // hash+size+hints; only hash+size need to
233                         // match the computed PDH.
234                         if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
235                                 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
236                                 ctxlog.FromContext(ctx).Warn(err)
237                                 return err
238                         }
239                         if remoteID != "" {
240                                 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
241                         }
242                         select {
243                         case first <- c:
244                                 return nil
245                         default:
246                                 // lost race, return value doesn't matter
247                                 return nil
248                         }
249                 })
250                 if err != nil {
251                         return arvados.Collection{}, err
252                 }
253                 return <-first, nil
254         }
255 }
256
257 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
258         return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
259 }
260
261 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
262         return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
263 }
264
265 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
266         return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
267 }
268
269 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
270         return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
271 }
272
273 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
274         return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
275 }
276
277 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
278         return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
279 }
280
281 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
282         return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
283 }
284
285 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
286         return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
287 }
288
289 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
290         return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
291 }
292
293 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
294         return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
295 }
296
297 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
298         return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
299 }
300
301 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
302         return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
303 }
304
305 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
306         return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
307 }
308
309 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
310         return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
311 }
312
313 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
314         return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
315 }
316
317 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
318         return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
319 }
320
321 type backend interface {
322         arvados.API
323         BaseURL() url.URL
324 }
325
326 type notFoundError struct{}
327
328 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
329 func (notFoundError) Error() string   { return "not found" }
330
331 func errStatus(err error) int {
332         if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
333                 return httpErr.HTTPStatus()
334         } else {
335                 return http.StatusInternalServerError
336         }
337 }