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