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 // Buffer request body, parse form parameters in request, and then
77 // replace original body with the buffer so it can be re-read by
78 // downstream proxy steps.
79 func loadParamsFromForm(req *http.Request) error {
80 var postBody *bytes.Buffer
81 if req.Body != nil && req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
83 if req.ContentLength > 0 {
84 cl = req.ContentLength
86 postBody = bytes.NewBuffer(make([]byte, 0, cl))
87 originalBody := req.Body
88 defer originalBody.Close()
89 req.Body = ioutil.NopCloser(io.TeeReader(req.Body, postBody))
92 err := req.ParseForm()
97 if req.Body != nil && postBody != nil {
98 req.Body = ioutil.NopCloser(postBody)
103 type multiClusterQueryResponseCollector struct {
104 responses []map[string]interface{}
110 func (c *multiClusterQueryResponseCollector) collectResponse(resp *http.Response,
111 requestError error) (newResponse *http.Response, err error) {
112 if requestError != nil {
113 c.error = requestError
117 defer resp.Body.Close()
118 var loadInto struct {
119 Kind string `json:"kind"`
120 Items []map[string]interface{} `json:"items"`
121 Errors []string `json:"errors"`
123 err = json.NewDecoder(resp.Body).Decode(&loadInto)
126 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, err)
129 if resp.StatusCode != http.StatusOK {
130 c.error = fmt.Errorf("error fetching from %v (%v): %v", c.clusterID, resp.Status, loadInto.Errors)
134 c.responses = loadInto.Items
135 c.kind = loadInto.Kind
140 func (h *genericFederatedRequestHandler) remoteQueryUUIDs(w http.ResponseWriter,
142 clusterID string, uuids []string) (rp []map[string]interface{}, kind string, err error) {
144 found := make(map[string]bool)
145 prev_len_uuids := len(uuids) + 1
147 // (1) there are more uuids to query
148 // (2) we're making progress - on each iteration the set of
149 // uuids we are expecting for must shrink.
150 for len(uuids) > 0 && len(uuids) < prev_len_uuids {
151 var remoteReq http.Request
152 remoteReq.Header = req.Header
153 remoteReq.Method = "POST"
154 remoteReq.URL = &url.URL{Path: req.URL.Path}
155 remoteParams := make(url.Values)
156 remoteParams.Set("_method", "GET")
157 remoteParams.Set("count", "none")
158 if req.Form.Get("select") != "" {
159 remoteParams.Set("select", req.Form.Get("select"))
161 content, err := json.Marshal(uuids)
165 remoteParams["filters"] = []string{fmt.Sprintf(`[["uuid", "in", %s]]`, content)}
166 enc := remoteParams.Encode()
167 remoteReq.Body = ioutil.NopCloser(bytes.NewBufferString(enc))
169 rc := multiClusterQueryResponseCollector{clusterID: clusterID}
171 if clusterID == h.handler.Cluster.ClusterID {
172 h.handler.localClusterRequest(w, &remoteReq,
175 h.handler.remoteClusterRequest(clusterID, w, &remoteReq,
179 return nil, "", rc.error
184 if len(rc.responses) == 0 {
185 // We got zero responses, no point in doing
190 rp = append(rp, rc.responses...)
192 // Go through the responses and determine what was
193 // returned. If there are remaining items, loop
194 // around and do another request with just the
196 for _, i := range rc.responses {
197 uuid, ok := i["uuid"].(string)
204 for _, u := range uuids {
209 prev_len_uuids = len(uuids)
216 func (h *Handler) FederatedRequestConcurrency() int {
217 if h.Cluster.FederatedRequestConcurrency == 0 {
220 return h.Cluster.FederatedRequestConcurrency
223 func (h *Handler) MaxItemsPerResponse() int {
224 if h.Cluster.MaxItemsPerResponse == 0 {
227 return h.Cluster.MaxItemsPerResponse
230 func (h *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter,
231 req *http.Request, clusterId *string) bool {
233 var filters [][]interface{}
234 err := json.Unmarshal([]byte(req.Form.Get("filters")), &filters)
236 httpserver.Error(w, err.Error(), http.StatusBadRequest)
240 // Split the list of uuids by prefix
241 queryClusters := make(map[string][]string)
243 for _, filter := range filters {
244 if len(filter) != 3 {
248 if lhs, ok := filter[0].(string); !ok || lhs != "uuid" {
252 op, ok := filter[1].(string)
258 if rhs, ok := filter[2].([]interface{}); ok {
259 for _, i := range rhs {
260 if u, ok := i.(string); ok {
262 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
267 } else if op == "=" {
268 if u, ok := filter[2].(string); ok {
270 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
279 if len(queryClusters) <= 1 {
280 // Query does not search for uuids across multiple
286 count := req.Form.Get("count")
287 if count != "" && count != `none` && count != `"none"` {
288 httpserver.Error(w, "Federated multi-object query must have 'count=none'", http.StatusBadRequest)
291 if req.Form.Get("limit") != "" || req.Form.Get("offset") != "" || req.Form.Get("order") != "" {
292 httpserver.Error(w, "Federated multi-object may not provide 'limit', 'offset' or 'order'.", http.StatusBadRequest)
295 if expectCount > h.handler.MaxItemsPerResponse() {
296 httpserver.Error(w, fmt.Sprintf("Federated multi-object request for %v objects which is more than max page size %v.",
297 expectCount, h.handler.MaxItemsPerResponse()), http.StatusBadRequest)
300 if req.Form.Get("select") != "" {
303 err := json.Unmarshal([]byte(req.Form.Get("select")), &selects)
305 httpserver.Error(w, err.Error(), http.StatusBadRequest)
309 for _, r := range selects {
316 httpserver.Error(w, "Federated multi-object request must include 'uuid' in 'select'", http.StatusBadRequest)
321 // Perform concurrent requests to each cluster
323 // use channel as a semaphore to limit the number of concurrent
324 // requests at a time
325 sem := make(chan bool, h.handler.FederatedRequestConcurrency())
327 wg := sync.WaitGroup{}
329 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
332 var completeResponses []map[string]interface{}
335 for k, v := range queryClusters {
341 // blocks until it can put a value into the
342 // channel (which has a max queue capacity)
345 go func(k string, v []string) {
346 rp, kn, err := h.remoteQueryUUIDs(w, req, k, v)
349 completeResponses = append(completeResponses, rp...)
352 errors = append(errors, err)
363 for _, e := range errors {
364 strerr = append(strerr, e.Error())
366 httpserver.Errors(w, strerr, http.StatusBadGateway)
370 w.Header().Set("Content-Type", "application/json")
371 w.WriteHeader(http.StatusOK)
372 itemList := make(map[string]interface{})
373 itemList["items"] = completeResponses
374 itemList["kind"] = kind
375 json.NewEncoder(w).Encode(itemList)
380 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
381 m := h.matcher.FindStringSubmatch(req.URL.Path)
384 if len(m) > 0 && m[2] != "" {
388 // Get form parameters from URL and form body (if POST).
389 if err := loadParamsFromForm(req); err != nil {
390 httpserver.Error(w, err.Error(), http.StatusBadRequest)
394 // Check if the parameters have an explicit cluster_id
395 if req.Form.Get("cluster_id") != "" {
396 clusterId = req.Form.Get("cluster_id")
399 // Handle the POST-as-GET special case (workaround for large
400 // GET requests that potentially exceed maximum URL length,
401 // like multi-object queries where the filter has 100s of
403 effectiveMethod := req.Method
404 if req.Method == "POST" && req.Form.Get("_method") != "" {
405 effectiveMethod = req.Form.Get("_method")
408 if effectiveMethod == "GET" &&
410 req.Form.Get("filters") != "" &&
411 h.handleMultiClusterQuery(w, req, &clusterId) {
415 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
416 h.next.ServeHTTP(w, req)
418 h.handler.remoteClusterRequest(clusterId, w, req, nil)
422 type rewriteSignaturesClusterId struct {
427 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
428 if requestError != nil {
429 return resp, requestError
432 if resp.StatusCode != 200 {
436 originalBody := resp.Body
437 defer originalBody.Close()
439 var col arvados.Collection
440 err = json.NewDecoder(resp.Body).Decode(&col)
445 // rewriting signatures will make manifest text 5-10% bigger so calculate
446 // capacity accordingly
447 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
450 mw := io.MultiWriter(hasher, updatedManifest)
453 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
454 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
456 line := scanner.Text()
457 tokens := strings.Split(line, " ")
459 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
462 n, err := mw.Write([]byte(tokens[0]))
464 return nil, fmt.Errorf("Error updating manifest: %v", err)
467 for _, token := range tokens[1:] {
468 n, err = mw.Write([]byte(" "))
470 return nil, fmt.Errorf("Error updating manifest: %v", err)
474 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
476 // Rewrite the block signature to be a remote signature
477 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
479 return nil, fmt.Errorf("Error updating manifest: %v", err)
482 // for hash checking, ignore signatures
483 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
485 return nil, fmt.Errorf("Error updating manifest: %v", err)
489 n, err = mw.Write([]byte(token))
491 return nil, fmt.Errorf("Error updating manifest: %v", err)
496 n, err = mw.Write([]byte("\n"))
498 return nil, fmt.Errorf("Error updating manifest: %v", err)
503 // Check that expected hash is consistent with
504 // portable_data_hash field of the returned record
505 if rw.expectHash == "" {
506 rw.expectHash = col.PortableDataHash
507 } else if rw.expectHash != col.PortableDataHash {
508 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
511 // Certify that the computed hash of the manifest_text matches our expectation
512 sum := hasher.Sum(nil)
513 computedHash := fmt.Sprintf("%x+%v", sum, sz)
514 if computedHash != rw.expectHash {
515 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
518 col.ManifestText = updatedManifest.String()
520 newbody, err := json.Marshal(col)
525 buf := bytes.NewBuffer(newbody)
526 resp.Body = ioutil.NopCloser(buf)
527 resp.ContentLength = int64(buf.Len())
528 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
533 func filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
534 if requestError != nil {
535 return resp, requestError
538 if resp.StatusCode == 404 {
539 // Suppress returning this result, because we want to
540 // search the federation.
546 type searchRemoteClusterForPDH struct {
551 sharedContext *context.Context
557 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
562 // Another request already returned a response
566 if requestError != nil {
567 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
568 // Record the error and suppress response
572 if resp.StatusCode != 200 {
573 // Suppress returning unsuccessful result. Maybe
574 // another request will find it.
575 // TODO collect and return error responses.
576 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
577 if resp.StatusCode != 404 {
578 // Got a non-404 error response, convert into BadGateway
579 *s.statusCode = http.StatusBadGateway
586 // This reads the response body. We don't want to hold the
587 // lock while doing this because other remote requests could
588 // also have made it to this point, and we don't want a
589 // slow response holding the lock to block a faster response
590 // that is waiting on the lock.
591 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
596 // Another request already returned a response
601 // Suppress returning unsuccessful result. Maybe
602 // another request will be successful.
603 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
607 // We have a successful response. Suppress/cancel all the
608 // other requests/responses.
609 *s.sentResponse = true
612 return newResponse, nil
615 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
616 if req.Method != "GET" {
617 // Only handle GET requests right now
618 h.next.ServeHTTP(w, req)
622 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
624 // Not a collection PDH GET request
625 m = collectionRe.FindStringSubmatch(req.URL.Path)
632 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
633 // request for remote collection by uuid
634 h.handler.remoteClusterRequest(clusterId, w, req,
635 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
638 // not a collection UUID request, or it is a request
639 // for a local UUID, either way, continue down the
641 h.next.ServeHTTP(w, req)
645 // Request for collection by PDH. Search the federation.
647 // First, query the local cluster.
648 if h.handler.localClusterRequest(w, req, filterLocalClusterResponse) {
652 sharedContext, cancelFunc := context.WithCancel(req.Context())
654 req = req.WithContext(sharedContext)
656 // Create a goroutine for each cluster in the
657 // RemoteClusters map. The first valid result gets
658 // returned to the client. When that happens, all
659 // other outstanding requests are cancelled or
661 sentResponse := false
663 wg := sync.WaitGroup{}
665 var errorCode int = 404
667 // use channel as a semaphore to limit the number of concurrent
668 // requests at a time
669 sem := make(chan bool, h.handler.FederatedRequestConcurrency())
671 for remoteID := range h.handler.Cluster.RemoteClusters {
672 // blocks until it can put a value into the
673 // channel (which has a max queue capacity)
678 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
679 &sharedContext, cancelFunc, &errors, &errorCode}
682 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
693 // No successful responses, so return the error
694 httpserver.Errors(w, errors, errorCode)
697 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
698 mux := http.NewServeMux()
699 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
700 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
701 mux.Handle("/arvados/v1/containers", &genericFederatedRequestHandler{next, h, containersRe})
702 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
703 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
704 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
705 mux.Handle("/arvados/v1/collections", next)
706 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
707 mux.Handle("/", next)
709 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
710 parts := strings.Split(req.Header.Get("Authorization"), "/")
711 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
714 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
715 // The token is already salted, or this is a
716 // request from another instance of
717 // arvados-controller. In either case, we
718 // don't want to proxy this query, so just
719 // continue down the instance handler stack.
720 next.ServeHTTP(w, req)
724 mux.ServeHTTP(w, req)
730 type CurrentUser struct {
731 Authorization arvados.APIClientAuthorization
735 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
740 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)
743 // Extract the auth token supplied in req, and replace it with a
744 // salted token for the remote cluster.
745 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
746 creds := auth.NewCredentials()
747 creds.LoadTokensFromHTTPRequest(req)
748 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
749 // Override ParseForm's 10MiB limit by ensuring
750 // req.Body is a *http.maxBytesReader.
751 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
752 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
755 // Replace req.Body with a buffer that re-encodes the
756 // form without api_token, in case we end up
757 // forwarding the request.
758 if req.PostForm != nil {
759 req.PostForm.Del("api_token")
761 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
763 if len(creds.Tokens) == 0 {
766 token, err := auth.SaltToken(creds.Tokens[0], remote)
767 if err == auth.ErrObsoleteToken {
768 // If the token exists in our own database, salt it
769 // for the remote. Otherwise, assume it was issued by
770 // the remote, and pass it through unmodified.
771 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
772 err = h.validateAPItoken(req, ¤tUser)
773 if err == sql.ErrNoRows {
774 // Not ours; pass through unmodified.
775 token = currentUser.Authorization.APIToken
776 } else if err != nil {
779 // Found; make V2 version and salt it.
780 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
785 } else if err != nil {
788 req.Header.Set("Authorization", "Bearer "+token)
790 // Remove api_token=... from the the query string, in case we
791 // end up forwarding the request.
792 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
794 } else if _, ok := values["api_token"]; ok {
795 delete(values, "api_token")
796 req.URL.RawQuery = values.Encode()