14197: Verify manifest text matches portable data hash that was requested
[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         // Certify that the computed hash of the manifest matches our expectation
163         if rw.expectHash == "" {
164                 rw.expectHash = col.PortableDataHash
165         }
166
167         sum := hasher.Sum(nil)
168         computedHash := fmt.Sprintf("%x+%v", sum, sz)
169         if computedHash != rw.expectHash {
170                 return nil, fmt.Errorf("Computed hash %q did not match expected hash %q", computedHash, rw.expectHash)
171         }
172
173         col.ManifestText = updatedManifest.String()
174
175         newbody, err := json.Marshal(col)
176         if err != nil {
177                 return nil, err
178         }
179
180         buf := bytes.NewBuffer(newbody)
181         resp.Body = ioutil.NopCloser(buf)
182         resp.ContentLength = int64(buf.Len())
183         resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
184
185         return resp, nil
186 }
187
188 type searchLocalClusterForPDH struct {
189         sentResponse bool
190 }
191
192 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
193         if requestError != nil {
194                 return resp, requestError
195         }
196
197         if resp.StatusCode == 404 {
198                 // Suppress returning this result, because we want to
199                 // search the federation.
200                 s.sentResponse = false
201                 return nil, nil
202         }
203         s.sentResponse = true
204         return resp, nil
205 }
206
207 type searchRemoteClusterForPDH struct {
208         pdh           string
209         remoteID      string
210         mtx           *sync.Mutex
211         sentResponse  *bool
212         sharedContext *context.Context
213         cancelFunc    func()
214         errors        *[]string
215         statusCode    *int
216 }
217
218 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
219         s.mtx.Lock()
220         defer s.mtx.Unlock()
221
222         if *s.sentResponse {
223                 // Another request already returned a response
224                 return nil, nil
225         }
226
227         if requestError != nil {
228                 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
229                 // Record the error and suppress response
230                 return nil, nil
231         }
232
233         if resp.StatusCode != 200 {
234                 // Suppress returning unsuccessful result.  Maybe
235                 // another request will find it.
236                 // TODO collect and return error responses.
237                 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
238                 if resp.StatusCode != 404 {
239                         // Got a non-404 error response, convert into BadGateway
240                         *s.statusCode = http.StatusBadGateway
241                 }
242                 return nil, nil
243         }
244
245         s.mtx.Unlock()
246
247         // This reads the response body.  We don't want to hold the
248         // lock while doing this because other remote requests could
249         // also have made it to this point, and we don't want a
250         // slow response holding the lock to block a faster response
251         // that is waiting on the lock.
252         newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
253
254         s.mtx.Lock()
255
256         if *s.sentResponse {
257                 // Another request already returned a response
258                 return nil, nil
259         }
260
261         if err != nil {
262                 // Suppress returning unsuccessful result.  Maybe
263                 // another request will be successful.
264                 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
265                 return nil, nil
266         }
267
268         // We have a successful response.  Suppress/cancel all the
269         // other requests/responses.
270         *s.sentResponse = true
271         s.cancelFunc()
272
273         return newResponse, nil
274 }
275
276 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
277         m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
278         if len(m) != 2 {
279                 // Not a collection PDH request
280                 m = collectionRe.FindStringSubmatch(req.URL.Path)
281                 if len(m) == 2 && m[1] != h.handler.Cluster.ClusterID {
282                         // request for remote collection by uuid
283                         h.handler.remoteClusterRequest(m[1], w, req,
284                                 rewriteSignaturesClusterId{m[1], ""}.rewriteSignatures)
285                         return
286                 }
287                 // not a collection UUID request, or it is a request
288                 // for a local UUID, either way, continue down the
289                 // handler stack.
290                 h.next.ServeHTTP(w, req)
291                 return
292         }
293
294         // Request for collection by PDH.  Search the federation.
295
296         // First, query the local cluster.
297         urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
298         if err != nil {
299                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
300                 return
301         }
302
303         urlOut = &url.URL{
304                 Scheme:   urlOut.Scheme,
305                 Host:     urlOut.Host,
306                 Path:     req.URL.Path,
307                 RawPath:  req.URL.RawPath,
308                 RawQuery: req.URL.RawQuery,
309         }
310         client := h.handler.secureClient
311         if insecure {
312                 client = h.handler.insecureClient
313         }
314         sf := &searchLocalClusterForPDH{}
315         h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
316         if sf.sentResponse {
317                 return
318         }
319
320         sharedContext, cancelFunc := context.WithCancel(req.Context())
321         defer cancelFunc()
322         req = req.WithContext(sharedContext)
323
324         // Create a goroutine for each cluster in the
325         // RemoteClusters map.  The first valid result gets
326         // returned to the client.  When that happens, all
327         // other outstanding requests are cancelled or
328         // suppressed.
329         sentResponse := false
330         mtx := sync.Mutex{}
331         wg := sync.WaitGroup{}
332         var errors []string
333         var errorCode int = 404
334
335         // use channel as a semaphore to limit it to 4
336         // parallel requests at a time
337         sem := make(chan bool, 4)
338         defer close(sem)
339         for remoteID := range h.handler.Cluster.RemoteClusters {
340                 // blocks until it can put a value into the
341                 // channel (which has a max queue capacity)
342                 sem <- true
343                 if sentResponse {
344                         break
345                 }
346                 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
347                         &sharedContext, cancelFunc, &errors, &errorCode}
348                 wg.Add(1)
349                 go func() {
350                         h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
351                         wg.Done()
352                         <-sem
353                 }()
354         }
355         wg.Wait()
356
357         if sentResponse {
358                 return
359         }
360
361         // No successful responses, so return the error
362         httpserver.Errors(w, errors, errorCode)
363 }
364
365 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
366         mux := http.NewServeMux()
367         mux.Handle("/arvados/v1/workflows", next)
368         mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h})
369         mux.Handle("/arvados/v1/collections", next)
370         mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
371         mux.Handle("/", next)
372
373         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
374                 parts := strings.Split(req.Header.Get("Authorization"), "/")
375                 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
376
377                 if alreadySalted ||
378                         strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
379                         // The token is already salted, or this is a
380                         // request from another instance of
381                         // arvados-controller.  In either case, we
382                         // don't want to proxy this query, so just
383                         // continue down the instance handler stack.
384                         next.ServeHTTP(w, req)
385                         return
386                 }
387
388                 mux.ServeHTTP(w, req)
389         })
390
391         return mux
392 }
393
394 type CurrentUser struct {
395         Authorization arvados.APIClientAuthorization
396         UUID          string
397 }
398
399 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
400         db, err := h.db(req)
401         if err != nil {
402                 return err
403         }
404         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)
405 }
406
407 // Extract the auth token supplied in req, and replace it with a
408 // salted token for the remote cluster.
409 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
410         creds := auth.NewCredentials()
411         creds.LoadTokensFromHTTPRequest(req)
412         if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
413                 // Override ParseForm's 10MiB limit by ensuring
414                 // req.Body is a *http.maxBytesReader.
415                 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
416                 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
417                         return err
418                 }
419                 // Replace req.Body with a buffer that re-encodes the
420                 // form without api_token, in case we end up
421                 // forwarding the request.
422                 if req.PostForm != nil {
423                         req.PostForm.Del("api_token")
424                 }
425                 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
426         }
427         if len(creds.Tokens) == 0 {
428                 return nil
429         }
430         token, err := auth.SaltToken(creds.Tokens[0], remote)
431         if err == auth.ErrObsoleteToken {
432                 // If the token exists in our own database, salt it
433                 // for the remote. Otherwise, assume it was issued by
434                 // the remote, and pass it through unmodified.
435                 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
436                 err = h.validateAPItoken(req, &currentUser)
437                 if err == sql.ErrNoRows {
438                         // Not ours; pass through unmodified.
439                         token = currentUser.Authorization.APIToken
440                 } else if err != nil {
441                         return err
442                 } else {
443                         // Found; make V2 version and salt it.
444                         token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
445                         if err != nil {
446                                 return err
447                         }
448                 }
449         } else if err != nil {
450                 return err
451         }
452         req.Header.Set("Authorization", "Bearer "+token)
453
454         // Remove api_token=... from the the query string, in case we
455         // end up forwarding the request.
456         if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
457                 return err
458         } else if _, ok := values["api_token"]; ok {
459                 delete(values, "api_token")
460                 req.URL.RawQuery = values.Encode()
461         }
462         return nil
463 }