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