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 err := fmt.Errorf("no proxy available for cluster %v", remoteID)
52 _, err = filter(nil, err)
55 httpserver.Error(w, err.Error(), http.StatusNotFound)
59 scheme := remote.Scheme
63 saltedReq, err := h.saltAuthToken(req, remoteID)
66 _, err = filter(nil, err)
69 httpserver.Error(w, err.Error(), http.StatusBadRequest)
76 Path: saltedReq.URL.Path,
77 RawPath: saltedReq.URL.RawPath,
78 RawQuery: saltedReq.URL.RawQuery,
80 client := h.secureClient
82 client = h.insecureClient
84 h.proxy.Do(w, saltedReq, urlOut, client, filter)
87 // Buffer request body, parse form parameters in request, and then
88 // replace original body with the buffer so it can be re-read by
89 // downstream proxy steps.
90 func loadParamsFromForm(req *http.Request) error {
91 var postBody *bytes.Buffer
92 if req.Body != nil && req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
94 if req.ContentLength > 0 {
95 cl = req.ContentLength
97 postBody = bytes.NewBuffer(make([]byte, 0, cl))
98 originalBody := req.Body
99 defer originalBody.Close()
100 req.Body = ioutil.NopCloser(io.TeeReader(req.Body, postBody))
103 err := req.ParseForm()
108 if req.Body != nil && postBody != nil {
109 req.Body = ioutil.NopCloser(postBody)
114 type multiClusterQueryResponseCollector struct {
115 responses []map[string]interface{}
121 func (c *multiClusterQueryResponseCollector) collectResponse(resp *http.Response,
122 requestError error) (newResponse *http.Response, err error) {
123 if requestError != nil {
124 c.error = requestError
128 defer resp.Body.Close()
129 var loadInto struct {
130 Kind string `json:"kind"`
131 Items []map[string]interface{} `json:"items"`
132 Errors []string `json:"errors"`
134 err = json.NewDecoder(resp.Body).Decode(&loadInto)
137 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, err)
140 if resp.StatusCode != http.StatusOK {
141 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, loadInto.Errors)
145 c.responses = loadInto.Items
146 c.kind = loadInto.Kind
151 func (h *genericFederatedRequestHandler) remoteQueryUUIDs(w http.ResponseWriter,
153 clusterID string, uuids []string) (rp []map[string]interface{}, kind string, err error) {
155 found := make(map[string]bool)
156 prev_len_uuids := len(uuids) + 1
158 // (1) there are more uuids to query
159 // (2) we're making progress - on each iteration the set of
160 // uuids we are expecting for must shrink.
161 for len(uuids) > 0 && len(uuids) < prev_len_uuids {
162 var remoteReq http.Request
163 remoteReq.Header = req.Header
164 remoteReq.Method = "POST"
165 remoteReq.URL = &url.URL{Path: req.URL.Path}
166 remoteParams := make(url.Values)
167 remoteParams.Set("_method", "GET")
168 remoteParams.Set("count", "none")
169 if req.Form.Get("select") != "" {
170 remoteParams.Set("select", req.Form.Get("select"))
172 content, err := json.Marshal(uuids)
176 remoteParams["filters"] = []string{fmt.Sprintf(`[["uuid", "in", %s]]`, content)}
177 enc := remoteParams.Encode()
178 remoteReq.Body = ioutil.NopCloser(bytes.NewBufferString(enc))
180 rc := multiClusterQueryResponseCollector{clusterID: clusterID}
182 if clusterID == h.handler.Cluster.ClusterID {
183 h.handler.localClusterRequest(w, &remoteReq,
186 h.handler.remoteClusterRequest(clusterID, w, &remoteReq,
190 return nil, "", rc.error
195 if len(rc.responses) == 0 {
196 // We got zero responses, no point in doing
201 rp = append(rp, rc.responses...)
203 // Go through the responses and determine what was
204 // returned. If there are remaining items, loop
205 // around and do another request with just the
207 for _, i := range rc.responses {
208 uuid, ok := i["uuid"].(string)
215 for _, u := range uuids {
220 prev_len_uuids = len(uuids)
227 func (h *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter,
228 req *http.Request, clusterId *string) bool {
230 var filters [][]interface{}
231 err := json.Unmarshal([]byte(req.Form.Get("filters")), &filters)
233 httpserver.Error(w, err.Error(), http.StatusBadRequest)
237 // Split the list of uuids by prefix
238 queryClusters := make(map[string][]string)
240 for _, filter := range filters {
241 if len(filter) != 3 {
245 if lhs, ok := filter[0].(string); !ok || lhs != "uuid" {
249 op, ok := filter[1].(string)
255 if rhs, ok := filter[2].([]interface{}); ok {
256 for _, i := range rhs {
257 if u, ok := i.(string); ok {
259 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
264 } else if op == "=" {
265 if u, ok := filter[2].(string); ok {
267 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
276 if len(queryClusters) <= 1 {
277 // Query does not search for uuids across multiple
283 count := req.Form.Get("count")
284 if count != "" && count != `none` && count != `"none"` {
285 httpserver.Error(w, "Federated multi-object query must have 'count=none'", http.StatusBadRequest)
288 if req.Form.Get("limit") != "" || req.Form.Get("offset") != "" || req.Form.Get("order") != "" {
289 httpserver.Error(w, "Federated multi-object may not provide 'limit', 'offset' or 'order'.", http.StatusBadRequest)
292 if expectCount > h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse() {
293 httpserver.Error(w, fmt.Sprintf("Federated multi-object request for %v objects which is more than max page size %v.",
294 expectCount, h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse()), http.StatusBadRequest)
297 if req.Form.Get("select") != "" {
300 err := json.Unmarshal([]byte(req.Form.Get("select")), &selects)
302 httpserver.Error(w, err.Error(), http.StatusBadRequest)
306 for _, r := range selects {
313 httpserver.Error(w, "Federated multi-object request must include 'uuid' in 'select'", http.StatusBadRequest)
318 // Perform concurrent requests to each cluster
320 // use channel as a semaphore to limit the number of concurrent
321 // requests at a time
322 sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
324 wg := sync.WaitGroup{}
326 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
329 var completeResponses []map[string]interface{}
332 for k, v := range queryClusters {
338 // blocks until it can put a value into the
339 // channel (which has a max queue capacity)
342 go func(k string, v []string) {
343 rp, kn, err := h.remoteQueryUUIDs(w, req, k, v)
346 completeResponses = append(completeResponses, rp...)
349 errors = append(errors, err)
360 for _, e := range errors {
361 strerr = append(strerr, e.Error())
363 httpserver.Errors(w, strerr, http.StatusBadGateway)
367 w.Header().Set("Content-Type", "application/json")
368 w.WriteHeader(http.StatusOK)
369 itemList := make(map[string]interface{})
370 itemList["items"] = completeResponses
371 itemList["kind"] = kind
372 json.NewEncoder(w).Encode(itemList)
377 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
378 m := h.matcher.FindStringSubmatch(req.URL.Path)
381 if len(m) > 0 && m[2] != "" {
385 // Get form parameters from URL and form body (if POST).
386 if err := loadParamsFromForm(req); err != nil {
387 httpserver.Error(w, err.Error(), http.StatusBadRequest)
391 // Check if the parameters have an explicit cluster_id
392 if req.Form.Get("cluster_id") != "" {
393 clusterId = req.Form.Get("cluster_id")
396 // Handle the POST-as-GET special case (workaround for large
397 // GET requests that potentially exceed maximum URL length,
398 // like multi-object queries where the filter has 100s of
400 effectiveMethod := req.Method
401 if req.Method == "POST" && req.Form.Get("_method") != "" {
402 effectiveMethod = req.Form.Get("_method")
405 if effectiveMethod == "GET" &&
407 req.Form.Get("filters") != "" &&
408 h.handleMultiClusterQuery(w, req, &clusterId) {
412 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
413 h.next.ServeHTTP(w, req)
415 h.handler.remoteClusterRequest(clusterId, w, req, nil)
419 type rewriteSignaturesClusterId struct {
424 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
425 if requestError != nil {
426 return resp, requestError
429 if resp.StatusCode != 200 {
433 originalBody := resp.Body
434 defer originalBody.Close()
436 var col arvados.Collection
437 err = json.NewDecoder(resp.Body).Decode(&col)
442 // rewriting signatures will make manifest text 5-10% bigger so calculate
443 // capacity accordingly
444 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
447 mw := io.MultiWriter(hasher, updatedManifest)
450 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
451 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
453 line := scanner.Text()
454 tokens := strings.Split(line, " ")
456 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
459 n, err := mw.Write([]byte(tokens[0]))
461 return nil, fmt.Errorf("Error updating manifest: %v", err)
464 for _, token := range tokens[1:] {
465 n, err = mw.Write([]byte(" "))
467 return nil, fmt.Errorf("Error updating manifest: %v", err)
471 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
473 // Rewrite the block signature to be a remote signature
474 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
476 return nil, fmt.Errorf("Error updating manifest: %v", err)
479 // for hash checking, ignore signatures
480 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
482 return nil, fmt.Errorf("Error updating manifest: %v", err)
486 n, err = mw.Write([]byte(token))
488 return nil, fmt.Errorf("Error updating manifest: %v", err)
493 n, err = mw.Write([]byte("\n"))
495 return nil, fmt.Errorf("Error updating manifest: %v", err)
500 // Check that expected hash is consistent with
501 // portable_data_hash field of the returned record
502 if rw.expectHash == "" {
503 rw.expectHash = col.PortableDataHash
504 } else if rw.expectHash != col.PortableDataHash {
505 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
508 // Certify that the computed hash of the manifest_text matches our expectation
509 sum := hasher.Sum(nil)
510 computedHash := fmt.Sprintf("%x+%v", sum, sz)
511 if computedHash != rw.expectHash {
512 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
515 col.ManifestText = updatedManifest.String()
517 newbody, err := json.Marshal(col)
522 buf := bytes.NewBuffer(newbody)
523 resp.Body = ioutil.NopCloser(buf)
524 resp.ContentLength = int64(buf.Len())
525 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
530 func filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
531 if requestError != nil {
532 return resp, requestError
535 if resp.StatusCode == 404 {
536 // Suppress returning this result, because we want to
537 // search the federation.
543 type searchRemoteClusterForPDH struct {
548 sharedContext *context.Context
554 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
559 // Another request already returned a response
563 if requestError != nil {
564 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
565 // Record the error and suppress response
569 if resp.StatusCode != 200 {
570 // Suppress returning unsuccessful result. Maybe
571 // another request will find it.
572 // TODO collect and return error responses.
573 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
574 if resp.StatusCode != 404 {
575 // Got a non-404 error response, convert into BadGateway
576 *s.statusCode = http.StatusBadGateway
583 // This reads the response body. We don't want to hold the
584 // lock while doing this because other remote requests could
585 // also have made it to this point, and we don't want a
586 // slow response holding the lock to block a faster response
587 // that is waiting on the lock.
588 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
593 // Another request already returned a response
598 // Suppress returning unsuccessful result. Maybe
599 // another request will be successful.
600 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
604 // We have a successful response. Suppress/cancel all the
605 // other requests/responses.
606 *s.sentResponse = true
609 return newResponse, nil
612 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
613 if req.Method != "GET" {
614 // Only handle GET requests right now
615 h.next.ServeHTTP(w, req)
619 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
621 // Not a collection PDH GET request
622 m = collectionRe.FindStringSubmatch(req.URL.Path)
629 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
630 // request for remote collection by uuid
631 h.handler.remoteClusterRequest(clusterId, w, req,
632 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
635 // not a collection UUID request, or it is a request
636 // for a local UUID, either way, continue down the
638 h.next.ServeHTTP(w, req)
642 // Request for collection by PDH. Search the federation.
644 // First, query the local cluster.
645 if h.handler.localClusterRequest(w, req, filterLocalClusterResponse) {
649 sharedContext, cancelFunc := context.WithCancel(req.Context())
651 req = req.WithContext(sharedContext)
653 // Create a goroutine for each cluster in the
654 // RemoteClusters map. The first valid result gets
655 // returned to the client. When that happens, all
656 // other outstanding requests are cancelled or
658 sentResponse := false
660 wg := sync.WaitGroup{}
662 var errorCode int = 404
664 // use channel as a semaphore to limit the number of concurrent
665 // requests at a time
666 sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
668 for remoteID := range h.handler.Cluster.RemoteClusters {
669 if remoteID == h.handler.Cluster.ClusterID {
670 // No need to query local cluster again
673 // blocks until it can put a value into the
674 // channel (which has a max queue capacity)
679 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
680 &sharedContext, cancelFunc, &errors, &errorCode}
683 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
694 // No successful responses, so return the error
695 httpserver.Errors(w, errors, errorCode)
698 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
699 mux := http.NewServeMux()
700 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
701 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
702 mux.Handle("/arvados/v1/containers", &genericFederatedRequestHandler{next, h, containersRe})
703 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
704 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
705 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
706 mux.Handle("/arvados/v1/collections", next)
707 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
708 mux.Handle("/", next)
710 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
711 parts := strings.Split(req.Header.Get("Authorization"), "/")
712 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
715 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
716 // The token is already salted, or this is a
717 // request from another instance of
718 // arvados-controller. In either case, we
719 // don't want to proxy this query, so just
720 // continue down the instance handler stack.
721 next.ServeHTTP(w, req)
725 mux.ServeHTTP(w, req)
731 type CurrentUser struct {
732 Authorization arvados.APIClientAuthorization
736 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
741 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)
744 // Extract the auth token supplied in req, and replace it with a
745 // salted token for the remote cluster.
746 func (h *Handler) saltAuthToken(req *http.Request, remote string) (updatedReq *http.Request, err error) {
747 updatedReq = (&http.Request{
752 ContentLength: req.ContentLength,
754 }).WithContext(req.Context())
756 creds := auth.NewCredentials()
757 creds.LoadTokensFromHTTPRequest(updatedReq)
758 if len(creds.Tokens) == 0 && updatedReq.Header.Get("Content-Type") == "application/x-www-form-encoded" {
759 // Override ParseForm's 10MiB limit by ensuring
760 // req.Body is a *http.maxBytesReader.
761 updatedReq.Body = http.MaxBytesReader(nil, updatedReq.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
762 if err := creds.LoadTokensFromHTTPRequestBody(updatedReq); err != nil {
765 // Replace req.Body with a buffer that re-encodes the
766 // form without api_token, in case we end up
767 // forwarding the request.
768 if updatedReq.PostForm != nil {
769 updatedReq.PostForm.Del("api_token")
771 updatedReq.Body = ioutil.NopCloser(bytes.NewBufferString(updatedReq.PostForm.Encode()))
773 if len(creds.Tokens) == 0 {
774 return updatedReq, nil
777 token, err := auth.SaltToken(creds.Tokens[0], remote)
779 if err == auth.ErrObsoleteToken {
780 // If the token exists in our own database, salt it
781 // for the remote. Otherwise, assume it was issued by
782 // the remote, and pass it through unmodified.
783 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
784 err = h.validateAPItoken(req, ¤tUser)
785 if err == sql.ErrNoRows {
786 // Not ours; pass through unmodified.
787 token = currentUser.Authorization.APIToken
788 } else if err != nil {
791 // Found; make V2 version and salt it.
792 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
797 } else if err != nil {
800 updatedReq.Header = http.Header{}
801 for k, v := range req.Header {
802 if k != "Authorization" {
803 updatedReq.Header[k] = v
806 updatedReq.Header.Set("Authorization", "Bearer "+token)
808 // Remove api_token=... from the the query string, in case we
809 // end up forwarding the request.
810 if values, err := url.ParseQuery(updatedReq.URL.RawQuery); err != nil {
812 } else if _, ok := values["api_token"]; ok {
813 delete(values, "api_token")
814 updatedReq.URL = &url.URL{
815 Scheme: req.URL.Scheme,
818 RawPath: req.URL.RawPath,
819 RawQuery: values.Encode(),
822 return updatedReq, nil