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