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