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