14259: Test updates & additions related to keep client HEAD requests
[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-[0-9a-z]{15})?(.*)$`
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 // Buffer request body, parse form parameters in request, and then
77 // replace original body with the buffer so it can be re-read by
78 // downstream proxy steps.
79 func loadParamsFromForm(req *http.Request) error {
80         var postBody *bytes.Buffer
81         if req.Body != nil && req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
82                 var cl int64
83                 if req.ContentLength > 0 {
84                         cl = req.ContentLength
85                 }
86                 postBody = bytes.NewBuffer(make([]byte, 0, cl))
87                 originalBody := req.Body
88                 defer originalBody.Close()
89                 req.Body = ioutil.NopCloser(io.TeeReader(req.Body, postBody))
90         }
91
92         err := req.ParseForm()
93         if err != nil {
94                 return err
95         }
96
97         if req.Body != nil && postBody != nil {
98                 req.Body = ioutil.NopCloser(postBody)
99         }
100         return nil
101 }
102
103 type multiClusterQueryResponseCollector struct {
104         responses []map[string]interface{}
105         error     error
106         kind      string
107         clusterID string
108 }
109
110 func (c *multiClusterQueryResponseCollector) collectResponse(resp *http.Response,
111         requestError error) (newResponse *http.Response, err error) {
112         if requestError != nil {
113                 c.error = requestError
114                 return nil, nil
115         }
116
117         defer resp.Body.Close()
118         var loadInto struct {
119                 Kind   string                   `json:"kind"`
120                 Items  []map[string]interface{} `json:"items"`
121                 Errors []string                 `json:"errors"`
122         }
123         err = json.NewDecoder(resp.Body).Decode(&loadInto)
124
125         if err != nil {
126                 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, err)
127                 return nil, nil
128         }
129         if resp.StatusCode != http.StatusOK {
130                 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, loadInto.Errors)
131                 return nil, nil
132         }
133
134         c.responses = loadInto.Items
135         c.kind = loadInto.Kind
136
137         return nil, nil
138 }
139
140 func (h *genericFederatedRequestHandler) remoteQueryUUIDs(w http.ResponseWriter,
141         req *http.Request,
142         clusterID string, uuids []string) (rp []map[string]interface{}, kind string, err error) {
143
144         found := make(map[string]bool)
145         prev_len_uuids := len(uuids) + 1
146         // Loop while
147         // (1) there are more uuids to query
148         // (2) we're making progress - on each iteration the set of
149         // uuids we are expecting for must shrink.
150         for len(uuids) > 0 && len(uuids) < prev_len_uuids {
151                 var remoteReq http.Request
152                 remoteReq.Header = req.Header
153                 remoteReq.Method = "POST"
154                 remoteReq.URL = &url.URL{Path: req.URL.Path}
155                 remoteParams := make(url.Values)
156                 remoteParams.Set("_method", "GET")
157                 remoteParams.Set("count", "none")
158                 if req.Form.Get("select") != "" {
159                         remoteParams.Set("select", req.Form.Get("select"))
160                 }
161                 content, err := json.Marshal(uuids)
162                 if err != nil {
163                         return nil, "", err
164                 }
165                 remoteParams["filters"] = []string{fmt.Sprintf(`[["uuid", "in", %s]]`, content)}
166                 enc := remoteParams.Encode()
167                 remoteReq.Body = ioutil.NopCloser(bytes.NewBufferString(enc))
168
169                 rc := multiClusterQueryResponseCollector{clusterID: clusterID}
170
171                 if clusterID == h.handler.Cluster.ClusterID {
172                         h.handler.localClusterRequest(w, &remoteReq,
173                                 rc.collectResponse)
174                 } else {
175                         h.handler.remoteClusterRequest(clusterID, w, &remoteReq,
176                                 rc.collectResponse)
177                 }
178                 if rc.error != nil {
179                         return nil, "", rc.error
180                 }
181
182                 kind = rc.kind
183
184                 if len(rc.responses) == 0 {
185                         // We got zero responses, no point in doing
186                         // another query.
187                         return rp, kind, nil
188                 }
189
190                 rp = append(rp, rc.responses...)
191
192                 // Go through the responses and determine what was
193                 // returned.  If there are remaining items, loop
194                 // around and do another request with just the
195                 // stragglers.
196                 for _, i := range rc.responses {
197                         uuid, ok := i["uuid"].(string)
198                         if ok {
199                                 found[uuid] = true
200                         }
201                 }
202
203                 l := []string{}
204                 for _, u := range uuids {
205                         if !found[u] {
206                                 l = append(l, u)
207                         }
208                 }
209                 prev_len_uuids = len(uuids)
210                 uuids = l
211         }
212
213         return rp, kind, nil
214 }
215
216 func (h *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter,
217         req *http.Request, clusterId *string) bool {
218
219         var filters [][]interface{}
220         err := json.Unmarshal([]byte(req.Form.Get("filters")), &filters)
221         if err != nil {
222                 httpserver.Error(w, err.Error(), http.StatusBadRequest)
223                 return true
224         }
225
226         // Split the list of uuids by prefix
227         queryClusters := make(map[string][]string)
228         expectCount := 0
229         for _, filter := range filters {
230                 if len(filter) != 3 {
231                         return false
232                 }
233
234                 if lhs, ok := filter[0].(string); !ok || lhs != "uuid" {
235                         return false
236                 }
237
238                 op, ok := filter[1].(string)
239                 if !ok {
240                         return false
241                 }
242
243                 if op == "in" {
244                         if rhs, ok := filter[2].([]interface{}); ok {
245                                 for _, i := range rhs {
246                                         if u, ok := i.(string); ok {
247                                                 *clusterId = u[0:5]
248                                                 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
249                                                 expectCount += 1
250                                         }
251                                 }
252                         }
253                 } else if op == "=" {
254                         if u, ok := filter[2].(string); ok {
255                                 *clusterId = u[0:5]
256                                 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
257                                 expectCount += 1
258                         }
259                 } else {
260                         return false
261                 }
262
263         }
264
265         if len(queryClusters) <= 1 {
266                 // Query does not search for uuids across multiple
267                 // clusters.
268                 return false
269         }
270
271         // Validations
272         count := req.Form.Get("count")
273         if count != "" && count != `none` && count != `"none"` {
274                 httpserver.Error(w, "Federated multi-object query must have 'count=none'", http.StatusBadRequest)
275                 return true
276         }
277         if req.Form.Get("limit") != "" || req.Form.Get("offset") != "" || req.Form.Get("order") != "" {
278                 httpserver.Error(w, "Federated multi-object may not provide 'limit', 'offset' or 'order'.", http.StatusBadRequest)
279                 return true
280         }
281         if expectCount > h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse() {
282                 httpserver.Error(w, fmt.Sprintf("Federated multi-object request for %v objects which is more than max page size %v.",
283                         expectCount, h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse()), http.StatusBadRequest)
284                 return true
285         }
286         if req.Form.Get("select") != "" {
287                 foundUUID := false
288                 var selects []string
289                 err := json.Unmarshal([]byte(req.Form.Get("select")), &selects)
290                 if err != nil {
291                         httpserver.Error(w, err.Error(), http.StatusBadRequest)
292                         return true
293                 }
294
295                 for _, r := range selects {
296                         if r == "uuid" {
297                                 foundUUID = true
298                                 break
299                         }
300                 }
301                 if !foundUUID {
302                         httpserver.Error(w, "Federated multi-object request must include 'uuid' in 'select'", http.StatusBadRequest)
303                         return true
304                 }
305         }
306
307         // Perform concurrent requests to each cluster
308
309         // use channel as a semaphore to limit the number of concurrent
310         // requests at a time
311         sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
312         defer close(sem)
313         wg := sync.WaitGroup{}
314
315         req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
316         mtx := sync.Mutex{}
317         errors := []error{}
318         var completeResponses []map[string]interface{}
319         var kind string
320
321         for k, v := range queryClusters {
322                 if len(v) == 0 {
323                         // Nothing to query
324                         continue
325                 }
326
327                 // blocks until it can put a value into the
328                 // channel (which has a max queue capacity)
329                 sem <- true
330                 wg.Add(1)
331                 go func(k string, v []string) {
332                         rp, kn, err := h.remoteQueryUUIDs(w, req, k, v)
333                         mtx.Lock()
334                         if err == nil {
335                                 completeResponses = append(completeResponses, rp...)
336                                 kind = kn
337                         } else {
338                                 errors = append(errors, err)
339                         }
340                         mtx.Unlock()
341                         wg.Done()
342                         <-sem
343                 }(k, v)
344         }
345         wg.Wait()
346
347         if len(errors) > 0 {
348                 var strerr []string
349                 for _, e := range errors {
350                         strerr = append(strerr, e.Error())
351                 }
352                 httpserver.Errors(w, strerr, http.StatusBadGateway)
353                 return true
354         }
355
356         w.Header().Set("Content-Type", "application/json")
357         w.WriteHeader(http.StatusOK)
358         itemList := make(map[string]interface{})
359         itemList["items"] = completeResponses
360         itemList["kind"] = kind
361         json.NewEncoder(w).Encode(itemList)
362
363         return true
364 }
365
366 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
367         m := h.matcher.FindStringSubmatch(req.URL.Path)
368         clusterId := ""
369
370         if len(m) > 0 && m[2] != "" {
371                 clusterId = m[2]
372         }
373
374         // Get form parameters from URL and form body (if POST).
375         if err := loadParamsFromForm(req); err != nil {
376                 httpserver.Error(w, err.Error(), http.StatusBadRequest)
377                 return
378         }
379
380         // Check if the parameters have an explicit cluster_id
381         if req.Form.Get("cluster_id") != "" {
382                 clusterId = req.Form.Get("cluster_id")
383         }
384
385         // Handle the POST-as-GET special case (workaround for large
386         // GET requests that potentially exceed maximum URL length,
387         // like multi-object queries where the filter has 100s of
388         // items)
389         effectiveMethod := req.Method
390         if req.Method == "POST" && req.Form.Get("_method") != "" {
391                 effectiveMethod = req.Form.Get("_method")
392         }
393
394         if effectiveMethod == "GET" &&
395                 clusterId == "" &&
396                 req.Form.Get("filters") != "" &&
397                 h.handleMultiClusterQuery(w, req, &clusterId) {
398                 return
399         }
400
401         if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
402                 h.next.ServeHTTP(w, req)
403         } else {
404                 h.handler.remoteClusterRequest(clusterId, w, req, nil)
405         }
406 }
407
408 type rewriteSignaturesClusterId struct {
409         clusterID  string
410         expectHash string
411 }
412
413 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
414         if requestError != nil {
415                 return resp, requestError
416         }
417
418         if resp.StatusCode != 200 {
419                 return resp, nil
420         }
421
422         originalBody := resp.Body
423         defer originalBody.Close()
424
425         var col arvados.Collection
426         err = json.NewDecoder(resp.Body).Decode(&col)
427         if err != nil {
428                 return nil, err
429         }
430
431         // rewriting signatures will make manifest text 5-10% bigger so calculate
432         // capacity accordingly
433         updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
434
435         hasher := md5.New()
436         mw := io.MultiWriter(hasher, updatedManifest)
437         sz := 0
438
439         scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
440         scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
441         for scanner.Scan() {
442                 line := scanner.Text()
443                 tokens := strings.Split(line, " ")
444                 if len(tokens) < 3 {
445                         return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
446                 }
447
448                 n, err := mw.Write([]byte(tokens[0]))
449                 if err != nil {
450                         return nil, fmt.Errorf("Error updating manifest: %v", err)
451                 }
452                 sz += n
453                 for _, token := range tokens[1:] {
454                         n, err = mw.Write([]byte(" "))
455                         if err != nil {
456                                 return nil, fmt.Errorf("Error updating manifest: %v", err)
457                         }
458                         sz += n
459
460                         m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
461                         if m != nil {
462                                 // Rewrite the block signature to be a remote signature
463                                 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
464                                 if err != nil {
465                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
466                                 }
467
468                                 // for hash checking, ignore signatures
469                                 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
470                                 if err != nil {
471                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
472                                 }
473                                 sz += n
474                         } else {
475                                 n, err = mw.Write([]byte(token))
476                                 if err != nil {
477                                         return nil, fmt.Errorf("Error updating manifest: %v", err)
478                                 }
479                                 sz += n
480                         }
481                 }
482                 n, err = mw.Write([]byte("\n"))
483                 if err != nil {
484                         return nil, fmt.Errorf("Error updating manifest: %v", err)
485                 }
486                 sz += n
487         }
488
489         // Check that expected hash is consistent with
490         // portable_data_hash field of the returned record
491         if rw.expectHash == "" {
492                 rw.expectHash = col.PortableDataHash
493         } else if rw.expectHash != col.PortableDataHash {
494                 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
495         }
496
497         // Certify that the computed hash of the manifest_text matches our expectation
498         sum := hasher.Sum(nil)
499         computedHash := fmt.Sprintf("%x+%v", sum, sz)
500         if computedHash != rw.expectHash {
501                 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
502         }
503
504         col.ManifestText = updatedManifest.String()
505
506         newbody, err := json.Marshal(col)
507         if err != nil {
508                 return nil, err
509         }
510
511         buf := bytes.NewBuffer(newbody)
512         resp.Body = ioutil.NopCloser(buf)
513         resp.ContentLength = int64(buf.Len())
514         resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
515
516         return resp, nil
517 }
518
519 func filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
520         if requestError != nil {
521                 return resp, requestError
522         }
523
524         if resp.StatusCode == 404 {
525                 // Suppress returning this result, because we want to
526                 // search the federation.
527                 return nil, nil
528         }
529         return resp, nil
530 }
531
532 type searchRemoteClusterForPDH struct {
533         pdh           string
534         remoteID      string
535         mtx           *sync.Mutex
536         sentResponse  *bool
537         sharedContext *context.Context
538         cancelFunc    func()
539         errors        *[]string
540         statusCode    *int
541 }
542
543 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
544         s.mtx.Lock()
545         defer s.mtx.Unlock()
546
547         if *s.sentResponse {
548                 // Another request already returned a response
549                 return nil, nil
550         }
551
552         if requestError != nil {
553                 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
554                 // Record the error and suppress response
555                 return nil, nil
556         }
557
558         if resp.StatusCode != 200 {
559                 // Suppress returning unsuccessful result.  Maybe
560                 // another request will find it.
561                 // TODO collect and return error responses.
562                 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
563                 if resp.StatusCode != 404 {
564                         // Got a non-404 error response, convert into BadGateway
565                         *s.statusCode = http.StatusBadGateway
566                 }
567                 return nil, nil
568         }
569
570         s.mtx.Unlock()
571
572         // This reads the response body.  We don't want to hold the
573         // lock while doing this because other remote requests could
574         // also have made it to this point, and we don't want a
575         // slow response holding the lock to block a faster response
576         // that is waiting on the lock.
577         newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
578
579         s.mtx.Lock()
580
581         if *s.sentResponse {
582                 // Another request already returned a response
583                 return nil, nil
584         }
585
586         if err != nil {
587                 // Suppress returning unsuccessful result.  Maybe
588                 // another request will be successful.
589                 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
590                 return nil, nil
591         }
592
593         // We have a successful response.  Suppress/cancel all the
594         // other requests/responses.
595         *s.sentResponse = true
596         s.cancelFunc()
597
598         return newResponse, nil
599 }
600
601 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
602         if req.Method != "GET" {
603                 // Only handle GET requests right now
604                 h.next.ServeHTTP(w, req)
605                 return
606         }
607
608         m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
609         if len(m) != 2 {
610                 // Not a collection PDH GET request
611                 m = collectionRe.FindStringSubmatch(req.URL.Path)
612                 clusterId := ""
613
614                 if len(m) > 0 {
615                         clusterId = m[2]
616                 }
617
618                 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
619                         // request for remote collection by uuid
620                         h.handler.remoteClusterRequest(clusterId, w, req,
621                                 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
622                         return
623                 }
624                 // not a collection UUID request, or it is a request
625                 // for a local UUID, either way, continue down the
626                 // handler stack.
627                 h.next.ServeHTTP(w, req)
628                 return
629         }
630
631         // Request for collection by PDH.  Search the federation.
632
633         // First, query the local cluster.
634         if h.handler.localClusterRequest(w, req, filterLocalClusterResponse) {
635                 return
636         }
637
638         sharedContext, cancelFunc := context.WithCancel(req.Context())
639         defer cancelFunc()
640         req = req.WithContext(sharedContext)
641
642         // Create a goroutine for each cluster in the
643         // RemoteClusters map.  The first valid result gets
644         // returned to the client.  When that happens, all
645         // other outstanding requests are cancelled or
646         // suppressed.
647         sentResponse := false
648         mtx := sync.Mutex{}
649         wg := sync.WaitGroup{}
650         var errors []string
651         var errorCode int = 404
652
653         // use channel as a semaphore to limit the number of concurrent
654         // requests at a time
655         sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
656         defer close(sem)
657         for remoteID := range h.handler.Cluster.RemoteClusters {
658                 // blocks until it can put a value into the
659                 // channel (which has a max queue capacity)
660                 sem <- true
661                 if sentResponse {
662                         break
663                 }
664                 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
665                         &sharedContext, cancelFunc, &errors, &errorCode}
666                 wg.Add(1)
667                 go func() {
668                         h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
669                         wg.Done()
670                         <-sem
671                 }()
672         }
673         wg.Wait()
674
675         if sentResponse {
676                 return
677         }
678
679         // No successful responses, so return the error
680         httpserver.Errors(w, errors, errorCode)
681 }
682
683 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
684         mux := http.NewServeMux()
685         mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
686         mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
687         mux.Handle("/arvados/v1/containers", &genericFederatedRequestHandler{next, h, containersRe})
688         mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
689         mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
690         mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
691         mux.Handle("/arvados/v1/collections", next)
692         mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
693         mux.Handle("/", next)
694
695         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
696                 parts := strings.Split(req.Header.Get("Authorization"), "/")
697                 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
698
699                 if alreadySalted ||
700                         strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
701                         // The token is already salted, or this is a
702                         // request from another instance of
703                         // arvados-controller.  In either case, we
704                         // don't want to proxy this query, so just
705                         // continue down the instance handler stack.
706                         next.ServeHTTP(w, req)
707                         return
708                 }
709
710                 mux.ServeHTTP(w, req)
711         })
712
713         return mux
714 }
715
716 type CurrentUser struct {
717         Authorization arvados.APIClientAuthorization
718         UUID          string
719 }
720
721 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
722         db, err := h.db(req)
723         if err != nil {
724                 return err
725         }
726         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)
727 }
728
729 // Extract the auth token supplied in req, and replace it with a
730 // salted token for the remote cluster.
731 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
732         creds := auth.NewCredentials()
733         creds.LoadTokensFromHTTPRequest(req)
734         if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
735                 // Override ParseForm's 10MiB limit by ensuring
736                 // req.Body is a *http.maxBytesReader.
737                 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
738                 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
739                         return err
740                 }
741                 // Replace req.Body with a buffer that re-encodes the
742                 // form without api_token, in case we end up
743                 // forwarding the request.
744                 if req.PostForm != nil {
745                         req.PostForm.Del("api_token")
746                 }
747                 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
748         }
749         if len(creds.Tokens) == 0 {
750                 return nil
751         }
752         token, err := auth.SaltToken(creds.Tokens[0], remote)
753         if err == auth.ErrObsoleteToken {
754                 // If the token exists in our own database, salt it
755                 // for the remote. Otherwise, assume it was issued by
756                 // the remote, and pass it through unmodified.
757                 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
758                 err = h.validateAPItoken(req, &currentUser)
759                 if err == sql.ErrNoRows {
760                         // Not ours; pass through unmodified.
761                         token = currentUser.Authorization.APIToken
762                 } else if err != nil {
763                         return err
764                 } else {
765                         // Found; make V2 version and salt it.
766                         token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
767                         if err != nil {
768                                 return err
769                         }
770                 }
771         } else if err != nil {
772                 return err
773         }
774         req.Header.Set("Authorization", "Bearer "+token)
775
776         // Remove api_token=... from the the query string, in case we
777         // end up forwarding the request.
778         if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
779                 return err
780         } else if _, ok := values["api_token"]; ok {
781                 delete(values, "api_token")
782                 req.URL.RawQuery = values.Encode()
783         }
784         return nil
785 }