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 *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter,
217 req *http.Request, clusterId *string) bool {
219 var filters [][]interface{}
220 err := json.Unmarshal([]byte(req.Form.Get("filters")), &filters)
222 httpserver.Error(w, err.Error(), http.StatusBadRequest)
226 // Split the list of uuids by prefix
227 queryClusters := make(map[string][]string)
229 for _, filter := range filters {
230 if len(filter) != 3 {
234 if lhs, ok := filter[0].(string); !ok || lhs != "uuid" {
238 op, ok := filter[1].(string)
244 if rhs, ok := filter[2].([]interface{}); ok {
245 for _, i := range rhs {
246 if u, ok := i.(string); ok {
248 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
253 } else if op == "=" {
254 if u, ok := filter[2].(string); ok {
256 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
265 if len(queryClusters) <= 1 {
266 // Query does not search for uuids across multiple
272 count := req.Form.Get("count")
273 if count != "" && count != `none` && count != `"none"` {
274 httpserver.Error(w, "Federated multi-object query must have 'count=none'", http.StatusBadRequest)
277 if req.Form.Get("limit") != "" || req.Form.Get("offset") != "" || req.Form.Get("order") != "" {
278 httpserver.Error(w, "Federated multi-object may not provide 'limit', 'offset' or 'order'.", http.StatusBadRequest)
281 if expectCount > h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse() {
282 httpserver.Error(w, fmt.Sprintf("Federated multi-object request for %v objects which is more than max page size %v.",
283 expectCount, h.handler.Cluster.RequestLimits.GetMaxItemsPerResponse()), http.StatusBadRequest)
286 if req.Form.Get("select") != "" {
289 err := json.Unmarshal([]byte(req.Form.Get("select")), &selects)
291 httpserver.Error(w, err.Error(), http.StatusBadRequest)
295 for _, r := range selects {
302 httpserver.Error(w, "Federated multi-object request must include 'uuid' in 'select'", http.StatusBadRequest)
307 // Perform concurrent requests to each cluster
309 // use channel as a semaphore to limit the number of concurrent
310 // requests at a time
311 sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
313 wg := sync.WaitGroup{}
315 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
318 var completeResponses []map[string]interface{}
321 for k, v := range queryClusters {
327 // blocks until it can put a value into the
328 // channel (which has a max queue capacity)
331 go func(k string, v []string) {
332 rp, kn, err := h.remoteQueryUUIDs(w, req, k, v)
335 completeResponses = append(completeResponses, rp...)
338 errors = append(errors, err)
349 for _, e := range errors {
350 strerr = append(strerr, e.Error())
352 httpserver.Errors(w, strerr, http.StatusBadGateway)
356 w.Header().Set("Content-Type", "application/json")
357 w.WriteHeader(http.StatusOK)
358 itemList := make(map[string]interface{})
359 itemList["items"] = completeResponses
360 itemList["kind"] = kind
361 json.NewEncoder(w).Encode(itemList)
366 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
367 m := h.matcher.FindStringSubmatch(req.URL.Path)
370 if len(m) > 0 && m[2] != "" {
374 // Get form parameters from URL and form body (if POST).
375 if err := loadParamsFromForm(req); err != nil {
376 httpserver.Error(w, err.Error(), http.StatusBadRequest)
380 // Check if the parameters have an explicit cluster_id
381 if req.Form.Get("cluster_id") != "" {
382 clusterId = req.Form.Get("cluster_id")
385 // Handle the POST-as-GET special case (workaround for large
386 // GET requests that potentially exceed maximum URL length,
387 // like multi-object queries where the filter has 100s of
389 effectiveMethod := req.Method
390 if req.Method == "POST" && req.Form.Get("_method") != "" {
391 effectiveMethod = req.Form.Get("_method")
394 if effectiveMethod == "GET" &&
396 req.Form.Get("filters") != "" &&
397 h.handleMultiClusterQuery(w, req, &clusterId) {
401 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
402 h.next.ServeHTTP(w, req)
404 h.handler.remoteClusterRequest(clusterId, w, req, nil)
408 type rewriteSignaturesClusterId struct {
413 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
414 if requestError != nil {
415 return resp, requestError
418 if resp.StatusCode != 200 {
422 originalBody := resp.Body
423 defer originalBody.Close()
425 var col arvados.Collection
426 err = json.NewDecoder(resp.Body).Decode(&col)
431 // rewriting signatures will make manifest text 5-10% bigger so calculate
432 // capacity accordingly
433 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
436 mw := io.MultiWriter(hasher, updatedManifest)
439 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
440 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
442 line := scanner.Text()
443 tokens := strings.Split(line, " ")
445 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
448 n, err := mw.Write([]byte(tokens[0]))
450 return nil, fmt.Errorf("Error updating manifest: %v", err)
453 for _, token := range tokens[1:] {
454 n, err = mw.Write([]byte(" "))
456 return nil, fmt.Errorf("Error updating manifest: %v", err)
460 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
462 // Rewrite the block signature to be a remote signature
463 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
465 return nil, fmt.Errorf("Error updating manifest: %v", err)
468 // for hash checking, ignore signatures
469 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
471 return nil, fmt.Errorf("Error updating manifest: %v", err)
475 n, err = mw.Write([]byte(token))
477 return nil, fmt.Errorf("Error updating manifest: %v", err)
482 n, err = mw.Write([]byte("\n"))
484 return nil, fmt.Errorf("Error updating manifest: %v", err)
489 // Check that expected hash is consistent with
490 // portable_data_hash field of the returned record
491 if rw.expectHash == "" {
492 rw.expectHash = col.PortableDataHash
493 } else if rw.expectHash != col.PortableDataHash {
494 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
497 // Certify that the computed hash of the manifest_text matches our expectation
498 sum := hasher.Sum(nil)
499 computedHash := fmt.Sprintf("%x+%v", sum, sz)
500 if computedHash != rw.expectHash {
501 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
504 col.ManifestText = updatedManifest.String()
506 newbody, err := json.Marshal(col)
511 buf := bytes.NewBuffer(newbody)
512 resp.Body = ioutil.NopCloser(buf)
513 resp.ContentLength = int64(buf.Len())
514 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
519 func filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
520 if requestError != nil {
521 return resp, requestError
524 if resp.StatusCode == 404 {
525 // Suppress returning this result, because we want to
526 // search the federation.
532 type searchRemoteClusterForPDH struct {
537 sharedContext *context.Context
543 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
548 // Another request already returned a response
552 if requestError != nil {
553 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
554 // Record the error and suppress response
558 if resp.StatusCode != 200 {
559 // Suppress returning unsuccessful result. Maybe
560 // another request will find it.
561 // TODO collect and return error responses.
562 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
563 if resp.StatusCode != 404 {
564 // Got a non-404 error response, convert into BadGateway
565 *s.statusCode = http.StatusBadGateway
572 // This reads the response body. We don't want to hold the
573 // lock while doing this because other remote requests could
574 // also have made it to this point, and we don't want a
575 // slow response holding the lock to block a faster response
576 // that is waiting on the lock.
577 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
582 // Another request already returned a response
587 // Suppress returning unsuccessful result. Maybe
588 // another request will be successful.
589 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
593 // We have a successful response. Suppress/cancel all the
594 // other requests/responses.
595 *s.sentResponse = true
598 return newResponse, nil
601 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
602 if req.Method != "GET" {
603 // Only handle GET requests right now
604 h.next.ServeHTTP(w, req)
608 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
610 // Not a collection PDH GET request
611 m = collectionRe.FindStringSubmatch(req.URL.Path)
618 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
619 // request for remote collection by uuid
620 h.handler.remoteClusterRequest(clusterId, w, req,
621 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
624 // not a collection UUID request, or it is a request
625 // for a local UUID, either way, continue down the
627 h.next.ServeHTTP(w, req)
631 // Request for collection by PDH. Search the federation.
633 // First, query the local cluster.
634 if h.handler.localClusterRequest(w, req, filterLocalClusterResponse) {
638 sharedContext, cancelFunc := context.WithCancel(req.Context())
640 req = req.WithContext(sharedContext)
642 // Create a goroutine for each cluster in the
643 // RemoteClusters map. The first valid result gets
644 // returned to the client. When that happens, all
645 // other outstanding requests are cancelled or
647 sentResponse := false
649 wg := sync.WaitGroup{}
651 var errorCode int = 404
653 // use channel as a semaphore to limit the number of concurrent
654 // requests at a time
655 sem := make(chan bool, h.handler.Cluster.RequestLimits.GetMultiClusterRequestConcurrency())
657 for remoteID := range h.handler.Cluster.RemoteClusters {
658 // blocks until it can put a value into the
659 // channel (which has a max queue capacity)
664 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
665 &sharedContext, cancelFunc, &errors, &errorCode}
668 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
679 // No successful responses, so return the error
680 httpserver.Errors(w, errors, errorCode)
683 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
684 mux := http.NewServeMux()
685 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
686 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
687 mux.Handle("/arvados/v1/containers", &genericFederatedRequestHandler{next, h, containersRe})
688 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
689 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
690 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
691 mux.Handle("/arvados/v1/collections", next)
692 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
693 mux.Handle("/", next)
695 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
696 parts := strings.Split(req.Header.Get("Authorization"), "/")
697 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
700 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
701 // The token is already salted, or this is a
702 // request from another instance of
703 // arvados-controller. In either case, we
704 // don't want to proxy this query, so just
705 // continue down the instance handler stack.
706 next.ServeHTTP(w, req)
710 mux.ServeHTTP(w, req)
716 type CurrentUser struct {
717 Authorization arvados.APIClientAuthorization
721 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
726 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)
729 // Extract the auth token supplied in req, and replace it with a
730 // salted token for the remote cluster.
731 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
732 creds := auth.NewCredentials()
733 creds.LoadTokensFromHTTPRequest(req)
734 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
735 // Override ParseForm's 10MiB limit by ensuring
736 // req.Body is a *http.maxBytesReader.
737 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
738 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
741 // Replace req.Body with a buffer that re-encodes the
742 // form without api_token, in case we end up
743 // forwarding the request.
744 if req.PostForm != nil {
745 req.PostForm.Del("api_token")
747 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
749 if len(creds.Tokens) == 0 {
752 token, err := auth.SaltToken(creds.Tokens[0], remote)
753 if err == auth.ErrObsoleteToken {
754 // If the token exists in our own database, salt it
755 // for the remote. Otherwise, assume it was issued by
756 // the remote, and pass it through unmodified.
757 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
758 err = h.validateAPItoken(req, ¤tUser)
759 if err == sql.ErrNoRows {
760 // Not ours; pass through unmodified.
761 token = currentUser.Authorization.APIToken
762 } else if err != nil {
765 // Found; make V2 version and salt it.
766 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
771 } else if err != nil {
774 req.Header.Set("Authorization", "Bearer "+token)
776 // Remove api_token=... from the the query string, in case we
777 // end up forwarding the request.
778 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
780 } else if _, ok := values["api_token"]; ok {
781 delete(values, "api_token")
782 req.URL.RawQuery = values.Encode()