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