1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
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]+)+$`)
36 type genericFederatedRequestHandler struct {
39 matcher *regexp.Regexp
42 type collectionFederatedRequestHandler struct {
47 func (h *Handler) remoteClusterRequest(remoteID string, w http.ResponseWriter, req *http.Request, filter ResponseFilter) {
48 remote, ok := h.Cluster.RemoteClusters[remoteID]
50 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
53 scheme := remote.Scheme
57 err := h.saltAuthToken(req, remoteID)
59 httpserver.Error(w, err.Error(), http.StatusBadRequest)
66 RawPath: req.URL.RawPath,
67 RawQuery: req.URL.RawQuery,
69 client := h.secureClient
71 client = h.insecureClient
73 h.proxy.Do(w, req, urlOut, client, filter)
76 func loadParamsFromForm(req *http.Request, params url.Values) error {
77 body, err := ioutil.ReadAll(req.Body)
81 req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
83 if v2, err = url.ParseQuery(string(body)); err != nil {
86 for k, v := range v2 {
87 params[k] = append(params[k], v...)
92 func loadParamsFromJson(req *http.Request, loadInto interface{}) error {
94 if req.ContentLength > 0 {
95 cl = req.ContentLength
97 postBody := bytes.NewBuffer(make([]byte, 0, cl))
98 defer req.Body.Close()
100 rdr := io.TeeReader(req.Body, postBody)
102 err := json.NewDecoder(rdr).Decode(loadInto)
106 req.Body = ioutil.NopCloser(postBody)
110 type responseCollector struct {
112 responses []interface{}
116 func (c *responseCollector) collectResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
117 if requestError != nil {
120 c.errors = append(c.errors, requestError)
123 defer resp.Body.Close()
124 loadInto := make(map[string]interface{})
125 err = json.NewDecoder(resp.Body).Decode(&loadInto)
131 if resp.StatusCode != http.StatusOK {
132 c.errors = append(c.errors, fmt.Errorf("error %v", loadInto["errors"]))
134 c.responses = append(c.responses, loadInto["items"].([]interface{})...)
137 c.errors = append(c.errors, err)
143 func (h *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter, req *http.Request,
144 params url.Values, clusterId *string) bool {
146 var filters [][]interface{}
147 err := json.Unmarshal([]byte(params["filters"][0]), &filters)
149 httpserver.Error(w, err.Error(), http.StatusBadRequest)
152 queryClusters := make(map[string][]string)
153 if len(filters) == 1 && len(filters[0]) == 3 {
155 lhs := f1[0].(string)
157 rhs := f1[2].([]interface{})
158 if lhs == "uuid" && op == "in" {
159 for _, i := range rhs {
162 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
167 if len(queryClusters) <= 1 {
171 wg := sync.WaitGroup{}
172 //var errors []string
173 //var errorCode int = 404
175 // use channel as a semaphore to limit it to 4
176 // parallel requests at a time
177 sem := make(chan bool, 4)
179 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
181 rc := responseCollector{}
182 for k, v := range queryClusters {
183 // blocks until it can put a value into the
184 // channel (which has a max queue capacity)
187 go func(k string, v []string) {
192 var remoteReq http.Request
193 remoteReq.Header = req.Header
194 remoteReq.Method = "POST"
195 remoteReq.URL = &url.URL{Path: req.URL.Path}
196 remoteParams := make(url.Values)
197 remoteParams["_method"] = []string{"GET"}
198 content, err := json.Marshal(v)
201 defer rc.mtx.Unlock()
202 rc.errors = append(rc.errors, err)
205 remoteParams["filters"] = []string{fmt.Sprintf(`[["uuid", "in", %s]]`, content)}
206 enc := remoteParams.Encode()
207 remoteReq.Body = ioutil.NopCloser(bytes.NewBufferString(enc))
209 if k == h.handler.Cluster.ClusterID {
210 h.handler.localClusterRequest(w, &remoteReq,
213 h.handler.remoteClusterRequest(k, w, &remoteReq,
220 if len(rc.errors) > 0 {
223 for _, e := range rc.errors {
224 strerr = append(strerr, e.Error())
226 httpserver.Errors(w, strerr, http.StatusBadGateway)
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 json.NewEncoder(w).Encode(itemList)
238 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
239 m := h.matcher.FindStringSubmatch(req.URL.Path)
242 if len(m) > 0 && m[2] != "" {
246 var params url.Values
248 if params, err = url.ParseQuery(req.URL.RawQuery); err != nil {
249 httpserver.Error(w, err.Error(), http.StatusBadRequest)
253 if req.Method == "POST" && req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
254 if err = loadParamsFromForm(req, params); err != nil {
255 httpserver.Error(w, err.Error(), http.StatusBadRequest)
260 if len(params["cluster_id"]) == 1 {
261 clusterId = params["cluster_id"][0]
264 if clusterId == "" && req.Method == "POST" && req.Header.Get("Content-Type") == "application/json" {
265 var hasClusterId struct {
266 ClusterID string `json:"cluster_id"`
268 if err = loadParamsFromJson(req, &hasClusterId); err != nil {
269 httpserver.Error(w, err.Error(), http.StatusBadRequest)
272 clusterId = hasClusterId.ClusterID
275 effectiveMethod := req.Method
276 if req.Method == "POST" && len(params["_method"]) == 1 {
277 effectiveMethod = params["_method"][0]
280 if effectiveMethod == "GET" && clusterId == "" && len(params["filters"]) == 1 {
281 if h.handleMultiClusterQuery(w, req, params, &clusterId) {
285 //log.Printf("Clusterid is %q", clusterId)
287 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
288 h.next.ServeHTTP(w, req)
290 h.handler.remoteClusterRequest(clusterId, w, req, nil)
294 type rewriteSignaturesClusterId struct {
299 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
300 if requestError != nil {
301 return resp, requestError
304 if resp.StatusCode != 200 {
308 originalBody := resp.Body
309 defer originalBody.Close()
311 var col arvados.Collection
312 err = json.NewDecoder(resp.Body).Decode(&col)
317 // rewriting signatures will make manifest text 5-10% bigger so calculate
318 // capacity accordingly
319 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
322 mw := io.MultiWriter(hasher, updatedManifest)
325 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
326 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
328 line := scanner.Text()
329 tokens := strings.Split(line, " ")
331 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
334 n, err := mw.Write([]byte(tokens[0]))
336 return nil, fmt.Errorf("Error updating manifest: %v", err)
339 for _, token := range tokens[1:] {
340 n, err = mw.Write([]byte(" "))
342 return nil, fmt.Errorf("Error updating manifest: %v", err)
346 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
348 // Rewrite the block signature to be a remote signature
349 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
351 return nil, fmt.Errorf("Error updating manifest: %v", err)
354 // for hash checking, ignore signatures
355 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
357 return nil, fmt.Errorf("Error updating manifest: %v", err)
361 n, err = mw.Write([]byte(token))
363 return nil, fmt.Errorf("Error updating manifest: %v", err)
368 n, err = mw.Write([]byte("\n"))
370 return nil, fmt.Errorf("Error updating manifest: %v", err)
375 // Check that expected hash is consistent with
376 // portable_data_hash field of the returned record
377 if rw.expectHash == "" {
378 rw.expectHash = col.PortableDataHash
379 } else if rw.expectHash != col.PortableDataHash {
380 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
383 // Certify that the computed hash of the manifest_text matches our expectation
384 sum := hasher.Sum(nil)
385 computedHash := fmt.Sprintf("%x+%v", sum, sz)
386 if computedHash != rw.expectHash {
387 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
390 col.ManifestText = updatedManifest.String()
392 newbody, err := json.Marshal(col)
397 buf := bytes.NewBuffer(newbody)
398 resp.Body = ioutil.NopCloser(buf)
399 resp.ContentLength = int64(buf.Len())
400 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
405 func filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
406 if requestError != nil {
407 return resp, requestError
410 if resp.StatusCode == 404 {
411 // Suppress returning this result, because we want to
412 // search the federation.
418 type searchRemoteClusterForPDH struct {
423 sharedContext *context.Context
429 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
434 // Another request already returned a response
438 if requestError != nil {
439 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
440 // Record the error and suppress response
444 if resp.StatusCode != 200 {
445 // Suppress returning unsuccessful result. Maybe
446 // another request will find it.
447 // TODO collect and return error responses.
448 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
449 if resp.StatusCode != 404 {
450 // Got a non-404 error response, convert into BadGateway
451 *s.statusCode = http.StatusBadGateway
458 // This reads the response body. We don't want to hold the
459 // lock while doing this because other remote requests could
460 // also have made it to this point, and we don't want a
461 // slow response holding the lock to block a faster response
462 // that is waiting on the lock.
463 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
468 // Another request already returned a response
473 // Suppress returning unsuccessful result. Maybe
474 // another request will be successful.
475 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
479 // We have a successful response. Suppress/cancel all the
480 // other requests/responses.
481 *s.sentResponse = true
484 return newResponse, nil
487 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
488 if req.Method != "GET" {
489 // Only handle GET requests right now
490 h.next.ServeHTTP(w, req)
494 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
496 // Not a collection PDH GET request
497 m = collectionRe.FindStringSubmatch(req.URL.Path)
504 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
505 // request for remote collection by uuid
506 h.handler.remoteClusterRequest(clusterId, w, req,
507 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
510 // not a collection UUID request, or it is a request
511 // for a local UUID, either way, continue down the
513 h.next.ServeHTTP(w, req)
517 // Request for collection by PDH. Search the federation.
519 // First, query the local cluster.
520 if h.handler.localClusterRequest(w, req, filterLocalClusterResponse) {
524 sharedContext, cancelFunc := context.WithCancel(req.Context())
526 req = req.WithContext(sharedContext)
528 // Create a goroutine for each cluster in the
529 // RemoteClusters map. The first valid result gets
530 // returned to the client. When that happens, all
531 // other outstanding requests are cancelled or
533 sentResponse := false
535 wg := sync.WaitGroup{}
537 var errorCode int = 404
539 // use channel as a semaphore to limit it to 4
540 // parallel requests at a time
541 sem := make(chan bool, 4)
543 for remoteID := range h.handler.Cluster.RemoteClusters {
544 // blocks until it can put a value into the
545 // channel (which has a max queue capacity)
550 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
551 &sharedContext, cancelFunc, &errors, &errorCode}
554 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
565 // No successful responses, so return the error
566 httpserver.Errors(w, errors, errorCode)
569 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
570 mux := http.NewServeMux()
571 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
572 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
573 mux.Handle("/arvados/v1/containers", &genericFederatedRequestHandler{next, h, containersRe})
574 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
575 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
576 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
577 mux.Handle("/arvados/v1/collections", next)
578 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
579 mux.Handle("/", next)
581 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
582 parts := strings.Split(req.Header.Get("Authorization"), "/")
583 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
586 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
587 // The token is already salted, or this is a
588 // request from another instance of
589 // arvados-controller. In either case, we
590 // don't want to proxy this query, so just
591 // continue down the instance handler stack.
592 next.ServeHTTP(w, req)
596 mux.ServeHTTP(w, req)
602 type CurrentUser struct {
603 Authorization arvados.APIClientAuthorization
607 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
612 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)
615 // Extract the auth token supplied in req, and replace it with a
616 // salted token for the remote cluster.
617 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
618 creds := auth.NewCredentials()
619 creds.LoadTokensFromHTTPRequest(req)
620 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
621 // Override ParseForm's 10MiB limit by ensuring
622 // req.Body is a *http.maxBytesReader.
623 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
624 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
627 // Replace req.Body with a buffer that re-encodes the
628 // form without api_token, in case we end up
629 // forwarding the request.
630 if req.PostForm != nil {
631 req.PostForm.Del("api_token")
633 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
635 if len(creds.Tokens) == 0 {
638 token, err := auth.SaltToken(creds.Tokens[0], remote)
639 if err == auth.ErrObsoleteToken {
640 // If the token exists in our own database, salt it
641 // for the remote. Otherwise, assume it was issued by
642 // the remote, and pass it through unmodified.
643 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
644 err = h.validateAPItoken(req, ¤tUser)
645 if err == sql.ErrNoRows {
646 // Not ours; pass through unmodified.
647 token = currentUser.Authorization.APIToken
648 } else if err != nil {
651 // Found; make V2 version and salt it.
652 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
657 } else if err != nil {
660 req.Header.Set("Authorization", "Bearer "+token)
662 // Remove api_token=... from the the query string, in case we
663 // end up forwarding the request.
664 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
666 } else if _, ok := values["api_token"]; ok {
667 delete(values, "api_token")
668 req.URL.RawQuery = values.Encode()