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