10181: Merge branch 'master' into 10181-incremental-log
[arvados.git] / lib / controller / federation.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "bufio"
9         "bytes"
10         "context"
11         "crypto/md5"
12         "database/sql"
13         "encoding/json"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "net/http"
18         "net/url"
19         "regexp"
20         "strings"
21         "sync"
22
23         "git.curoverse.com/arvados.git/sdk/go/arvados"
24         "git.curoverse.com/arvados.git/sdk/go/auth"
25         "git.curoverse.com/arvados.git/sdk/go/httpserver"
26         "git.curoverse.com/arvados.git/sdk/go/keepclient"
27 )
28
29 var pathPattern = `^/arvados/v1/%s(/([0-9a-z]{5})-%s-)?.*$`
30 var wfRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "workflows", "7fd4e"))
31 var containersRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "containers", "dz642"))
32 var containerRequestsRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "container_requests", "xvhdp"))
33 var collectionRe = regexp.MustCompile(fmt.Sprintf(pathPattern, "collections", "4zz18"))
34 var collectionByPDHRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-fA-F]{32}\+[0-9]+)+$`)
35
36 type genericFederatedRequestHandler struct {
37         next    http.Handler
38         handler *Handler
39         matcher *regexp.Regexp
40 }
41
42 type collectionFederatedRequestHandler struct {
43         next    http.Handler
44         handler *Handler
45 }
46
47 func (h *Handler) remoteClusterRequest(remoteID string, w http.ResponseWriter, req *http.Request, filter ResponseFilter) {
48         remote, ok := h.Cluster.RemoteClusters[remoteID]
49         if !ok {
50                 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
51                 return
52         }
53         scheme := remote.Scheme
54         if scheme == "" {
55                 scheme = "https"
56         }
57         err := h.saltAuthToken(req, remoteID)
58         if err != nil {
59                 httpserver.Error(w, err.Error(), http.StatusBadRequest)
60                 return
61         }
62         urlOut := &url.URL{
63                 Scheme:   scheme,
64                 Host:     remote.Host,
65                 Path:     req.URL.Path,
66                 RawPath:  req.URL.RawPath,
67                 RawQuery: req.URL.RawQuery,
68         }
69         client := h.secureClient
70         if remote.Insecure {
71                 client = h.insecureClient
72         }
73         h.proxy.Do(w, req, urlOut, client, filter)
74 }
75
76 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
77         m := h.matcher.FindStringSubmatch(req.URL.Path)
78         clusterId := ""
79
80         if len(m) == 3 {
81                 clusterId = m[2]
82         }
83
84         if clusterId == "" {
85                 if values, err := url.ParseQuery(req.URL.RawQuery); err == nil {
86                         if len(values["cluster_id"]) == 1 {
87                                 clusterId = values["cluster_id"][0]
88                         }
89                 }
90         }
91
92         if clusterId == "" && req.Method == "POST" && req.Header.Get("Content-Type") == "application/json" {
93                 var hasClusterId struct {
94                         ClusterID string `json:"cluster_id"`
95                 }
96                 var cl int64
97                 if req.ContentLength > 0 {
98                         cl = req.ContentLength
99                 }
100                 postBody := bytes.NewBuffer(make([]byte, 0, cl))
101                 defer req.Body.Close()
102
103                 rdr := io.TeeReader(req.Body, postBody)
104
105                 err := json.NewDecoder(rdr).Decode(&hasClusterId)
106                 if err != nil {
107                         httpserver.Error(w, err.Error(), http.StatusBadRequest)
108                         return
109                 }
110                 req.Body = ioutil.NopCloser(postBody)
111
112                 clusterId = hasClusterId.ClusterID
113         }
114
115         if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
116                 h.next.ServeHTTP(w, req)
117         } else {
118                 h.handler.remoteClusterRequest(clusterId, w, req, nil)
119         }
120 }
121
122 type rewriteSignaturesClusterId struct {
123         clusterID  string
124         expectHash string
125 }
126
127 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
128         if requestError != nil {
129                 return resp, requestError
130         }
131
132         if resp.StatusCode != 200 {
133                 return resp, nil
134         }
135
136         originalBody := resp.Body
137         defer originalBody.Close()
138
139         var col arvados.Collection
140         err = json.NewDecoder(resp.Body).Decode(&col)
141         if err != nil {
142                 return nil, err
143         }
144
145         // rewriting signatures will make manifest text 5-10% bigger so calculate
146         // capacity accordingly
147         updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
148
149         hasher := md5.New()
150         mw := io.MultiWriter(hasher, updatedManifest)
151         sz := 0
152
153         scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
154         scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
155         for scanner.Scan() {
156                 line := scanner.Text()
157                 tokens := strings.Split(line, " ")
158                 if len(tokens) < 3 {
159                         return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
160                 }
161
162                 n, err := mw.Write([]byte(tokens[0]))
163                 if err != nil {
164                         return nil, fmt.Errorf("Error updating manifest: %v", err)
165                 }
166                 sz += n
167                 for _, token := range tokens[1:] {
168                         n, err = mw.Write([]byte(" "))
169                         if err != nil {
170                                 return nil, fmt.Errorf("Error updating manifest: %v", err)
171                         }
172                         sz += n
173
174                         m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
175                         if m != nil {
176                                 // Rewrite the block signature to be a remote signature
177                                 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
178                                 if err != nil {
179                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
180                                 }
181
182                                 // for hash checking, ignore signatures
183                                 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
184                                 if err != nil {
185                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
186                                 }
187                                 sz += n
188                         } else {
189                                 n, err = mw.Write([]byte(token))
190                                 if err != nil {
191                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
192                                 }
193                                 sz += n
194                         }
195                 }
196                 n, err = mw.Write([]byte("\n"))
197                 if err != nil {
198                         return nil, fmt.Errorf("Error updating manifest: %v", err)
199                 }
200                 sz += n
201         }
202
203         // Check that expected hash is consistent with
204         // portable_data_hash field of the returned record
205         if rw.expectHash == "" {
206                 rw.expectHash = col.PortableDataHash
207         } else if rw.expectHash != col.PortableDataHash {
208                 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
209         }
210
211         // Certify that the computed hash of the manifest_text matches our expectation
212         sum := hasher.Sum(nil)
213         computedHash := fmt.Sprintf("%x+%v", sum, sz)
214         if computedHash != rw.expectHash {
215                 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
216         }
217
218         col.ManifestText = updatedManifest.String()
219
220         newbody, err := json.Marshal(col)
221         if err != nil {
222                 return nil, err
223         }
224
225         buf := bytes.NewBuffer(newbody)
226         resp.Body = ioutil.NopCloser(buf)
227         resp.ContentLength = int64(buf.Len())
228         resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
229
230         return resp, nil
231 }
232
233 type searchLocalClusterForPDH struct {
234         sentResponse bool
235 }
236
237 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
238         if requestError != nil {
239                 return resp, requestError
240         }
241
242         if resp.StatusCode == 404 {
243                 // Suppress returning this result, because we want to
244                 // search the federation.
245                 s.sentResponse = false
246                 return nil, nil
247         }
248         s.sentResponse = true
249         return resp, nil
250 }
251
252 type searchRemoteClusterForPDH struct {
253         pdh           string
254         remoteID      string
255         mtx           *sync.Mutex
256         sentResponse  *bool
257         sharedContext *context.Context
258         cancelFunc    func()
259         errors        *[]string
260         statusCode    *int
261 }
262
263 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
264         s.mtx.Lock()
265         defer s.mtx.Unlock()
266
267         if *s.sentResponse {
268                 // Another request already returned a response
269                 return nil, nil
270         }
271
272         if requestError != nil {
273                 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
274                 // Record the error and suppress response
275                 return nil, nil
276         }
277
278         if resp.StatusCode != 200 {
279                 // Suppress returning unsuccessful result.  Maybe
280                 // another request will find it.
281                 // TODO collect and return error responses.
282                 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
283                 if resp.StatusCode != 404 {
284                         // Got a non-404 error response, convert into BadGateway
285                         *s.statusCode = http.StatusBadGateway
286                 }
287                 return nil, nil
288         }
289
290         s.mtx.Unlock()
291
292         // This reads the response body.  We don't want to hold the
293         // lock while doing this because other remote requests could
294         // also have made it to this point, and we don't want a
295         // slow response holding the lock to block a faster response
296         // that is waiting on the lock.
297         newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
298
299         s.mtx.Lock()
300
301         if *s.sentResponse {
302                 // Another request already returned a response
303                 return nil, nil
304         }
305
306         if err != nil {
307                 // Suppress returning unsuccessful result.  Maybe
308                 // another request will be successful.
309                 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
310                 return nil, nil
311         }
312
313         // We have a successful response.  Suppress/cancel all the
314         // other requests/responses.
315         *s.sentResponse = true
316         s.cancelFunc()
317
318         return newResponse, nil
319 }
320
321 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
322         if req.Method != "GET" {
323                 // Only handle GET requests right now
324                 h.next.ServeHTTP(w, req)
325                 return
326         }
327
328         m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
329         if len(m) != 2 {
330                 // Not a collection PDH GET request
331                 m = collectionRe.FindStringSubmatch(req.URL.Path)
332                 clusterId := ""
333
334                 if len(m) == 3 {
335                         clusterId = m[2]
336                 }
337
338                 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
339                         // request for remote collection by uuid
340                         h.handler.remoteClusterRequest(clusterId, w, req,
341                                 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
342                         return
343                 }
344                 // not a collection UUID request, or it is a request
345                 // for a local UUID, either way, continue down the
346                 // handler stack.
347                 h.next.ServeHTTP(w, req)
348                 return
349         }
350
351         // Request for collection by PDH.  Search the federation.
352
353         // First, query the local cluster.
354         urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
355         if err != nil {
356                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
357                 return
358         }
359
360         urlOut = &url.URL{
361                 Scheme:   urlOut.Scheme,
362                 Host:     urlOut.Host,
363                 Path:     req.URL.Path,
364                 RawPath:  req.URL.RawPath,
365                 RawQuery: req.URL.RawQuery,
366         }
367         client := h.handler.secureClient
368         if insecure {
369                 client = h.handler.insecureClient
370         }
371         sf := &searchLocalClusterForPDH{}
372         h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
373         if sf.sentResponse {
374                 return
375         }
376
377         sharedContext, cancelFunc := context.WithCancel(req.Context())
378         defer cancelFunc()
379         req = req.WithContext(sharedContext)
380
381         // Create a goroutine for each cluster in the
382         // RemoteClusters map.  The first valid result gets
383         // returned to the client.  When that happens, all
384         // other outstanding requests are cancelled or
385         // suppressed.
386         sentResponse := false
387         mtx := sync.Mutex{}
388         wg := sync.WaitGroup{}
389         var errors []string
390         var errorCode int = 404
391
392         // use channel as a semaphore to limit it to 4
393         // parallel requests at a time
394         sem := make(chan bool, 4)
395         defer close(sem)
396         for remoteID := range h.handler.Cluster.RemoteClusters {
397                 // blocks until it can put a value into the
398                 // channel (which has a max queue capacity)
399                 sem <- true
400                 if sentResponse {
401                         break
402                 }
403                 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
404                         &sharedContext, cancelFunc, &errors, &errorCode}
405                 wg.Add(1)
406                 go func() {
407                         h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
408                         wg.Done()
409                         <-sem
410                 }()
411         }
412         wg.Wait()
413
414         if sentResponse {
415                 return
416         }
417
418         // No successful responses, so return the error
419         httpserver.Errors(w, errors, errorCode)
420 }
421
422 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
423         mux := http.NewServeMux()
424         mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
425         mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
426         mux.Handle("/arvados/v1/containers", next)
427         mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
428         mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
429         mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
430         mux.Handle("/arvados/v1/collections", next)
431         mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
432         mux.Handle("/", next)
433
434         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
435                 parts := strings.Split(req.Header.Get("Authorization"), "/")
436                 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
437
438                 if alreadySalted ||
439                         strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
440                         // The token is already salted, or this is a
441                         // request from another instance of
442                         // arvados-controller.  In either case, we
443                         // don't want to proxy this query, so just
444                         // continue down the instance handler stack.
445                         next.ServeHTTP(w, req)
446                         return
447                 }
448
449                 mux.ServeHTTP(w, req)
450         })
451
452         return mux
453 }
454
455 type CurrentUser struct {
456         Authorization arvados.APIClientAuthorization
457         UUID          string
458 }
459
460 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
461         db, err := h.db(req)
462         if err != nil {
463                 return err
464         }
465         return db.QueryRowContext(req.Context(), `SELECT api_client_authorizations.uuid, users.uuid FROM api_client_authorizations JOIN users on api_client_authorizations.user_id=users.id WHERE api_token=$1 AND (expires_at IS NULL OR expires_at > current_timestamp) LIMIT 1`, user.Authorization.APIToken).Scan(&user.Authorization.UUID, &user.UUID)
466 }
467
468 // Extract the auth token supplied in req, and replace it with a
469 // salted token for the remote cluster.
470 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
471         creds := auth.NewCredentials()
472         creds.LoadTokensFromHTTPRequest(req)
473         if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
474                 // Override ParseForm's 10MiB limit by ensuring
475                 // req.Body is a *http.maxBytesReader.
476                 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
477                 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
478                         return err
479                 }
480                 // Replace req.Body with a buffer that re-encodes the
481                 // form without api_token, in case we end up
482                 // forwarding the request.
483                 if req.PostForm != nil {
484                         req.PostForm.Del("api_token")
485                 }
486                 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
487         }
488         if len(creds.Tokens) == 0 {
489                 return nil
490         }
491         token, err := auth.SaltToken(creds.Tokens[0], remote)
492         if err == auth.ErrObsoleteToken {
493                 // If the token exists in our own database, salt it
494                 // for the remote. Otherwise, assume it was issued by
495                 // the remote, and pass it through unmodified.
496                 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
497                 err = h.validateAPItoken(req, &currentUser)
498                 if err == sql.ErrNoRows {
499                         // Not ours; pass through unmodified.
500                         token = currentUser.Authorization.APIToken
501                 } else if err != nil {
502                         return err
503                 } else {
504                         // Found; make V2 version and salt it.
505                         token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
506                         if err != nil {
507                                 return err
508                         }
509                 }
510         } else if err != nil {
511                 return err
512         }
513         req.Header.Set("Authorization", "Bearer "+token)
514
515         // Remove api_token=... from the the query string, in case we
516         // end up forwarding the request.
517         if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
518                 return err
519         } else if _, ok := values["api_token"]; ok {
520                 delete(values, "api_token")
521                 req.URL.RawQuery = values.Encode()
522         }
523         return nil
524 }