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