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