1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
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]+)+$`)
37 type genericFederatedRequestHandler struct {
40 matcher *regexp.Regexp
43 type collectionFederatedRequestHandler struct {
48 func (h *Handler) remoteClusterRequest(remoteID string, w http.ResponseWriter, req *http.Request, filter ResponseFilter) {
49 remote, ok := h.Cluster.RemoteClusters[remoteID]
51 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
54 scheme := remote.Scheme
58 err := h.saltAuthToken(req, remoteID)
60 httpserver.Error(w, err.Error(), http.StatusBadRequest)
67 RawPath: req.URL.RawPath,
68 RawQuery: req.URL.RawQuery,
70 client := h.secureClient
72 client = h.insecureClient
74 h.proxy.Do(w, req, urlOut, client, filter)
77 func loadParamsFromForm(req *http.Request, params url.Values) error {
78 body, err := ioutil.ReadAll(req.Body)
82 req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
84 if v2, err = url.ParseQuery(string(body)); err != nil {
87 for k, v := range v2 {
88 params[k] = append(params[k], v...)
93 func loadParamsFromJson(req *http.Request, loadInto interface{}) error {
95 if req.ContentLength > 0 {
96 cl = req.ContentLength
98 postBody := bytes.NewBuffer(make([]byte, 0, cl))
99 defer req.Body.Close()
101 rdr := io.TeeReader(req.Body, postBody)
103 err := json.NewDecoder(rdr).Decode(loadInto)
107 req.Body = ioutil.NopCloser(postBody)
111 type responseCollector struct {
113 responses []interface{}
117 func (c *responseCollector) collectResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
118 if requestError != nil {
121 c.errors = append(c.errors, requestError)
124 defer resp.Body.Close()
125 loadInto := make(map[string]interface{})
126 err = json.NewDecoder(resp.Body).Decode(&loadInto)
132 c.responses = append(c.responses, loadInto["items"].([]interface{})...)
134 c.errors = append(c.errors, err)
140 func (h *genericFederatedRequestHandler) handleMultiClusterQuery(w http.ResponseWriter, req *http.Request,
141 params url.Values, clusterId *string) bool {
143 var filters [][]interface{}
144 err := json.Unmarshal([]byte(params["filters"][0]), &filters)
146 httpserver.Error(w, err.Error(), http.StatusBadRequest)
149 queryClusters := make(map[string][]string)
150 if len(filters) == 1 && len(filters[0]) == 3 {
152 lhs := f1[0].(string)
154 rhs := f1[2].([]interface{})
155 if lhs == "uuid" && op == "in" {
156 for _, i := range rhs {
159 queryClusters[u[0:5]] = append(queryClusters[u[0:5]], u)
164 if len(queryClusters) <= 1 {
168 wg := sync.WaitGroup{}
169 //var errors []string
170 //var errorCode int = 404
172 // use channel as a semaphore to limit it to 4
173 // parallel requests at a time
174 sem := make(chan bool, 4)
176 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
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)
184 go func(k string, v []string) {
190 remoteReq.Method = "POST"
191 remoteReq.URL = &url.URL{
193 RawPath: req.URL.RawPath,
195 remoteParams := make(url.Values)
196 remoteParams["_method"] = []string{"GET"}
197 content, err := json.Marshal(v)
200 rc.errors = append(rc.errors, err)
204 remoteParams["filters"] = []string{fmt.Sprintf(`[["uuid", "in", %s]]`, content)}
205 enc := remoteParams.Encode()
206 remoteReq.Body = ioutil.NopCloser(bytes.NewBufferString(enc))
208 if k == h.handler.Cluster.ClusterID {
209 h.handler.proxy.Do(w, &remoteReq, remoteReq.URL,
210 h.handler.secureClient, rc.collectResponse)
212 h.handler.remoteClusterRequest(k, w, &remoteReq,
219 if len(rc.errors) > 0 {
222 for _, e := range rc.errors {
223 strerr = append(strerr, e.Error())
225 httpserver.Errors(w, strerr, http.StatusBadRequest)
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)
241 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
242 m := h.matcher.FindStringSubmatch(req.URL.Path)
245 if len(m) > 0 && m[2] != "" {
249 var params url.Values
251 if params, err = url.ParseQuery(req.URL.RawQuery); err != nil {
252 httpserver.Error(w, err.Error(), http.StatusBadRequest)
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)
263 if len(params["cluster_id"]) == 1 {
264 clusterId = params["cluster_id"][0]
267 if clusterId == "" && req.Method == "POST" && req.Header.Get("Content-Type") == "application/json" {
268 var hasClusterId struct {
269 ClusterID string `json:"cluster_id"`
271 if err = loadParamsFromJson(req, &hasClusterId); err != nil {
272 httpserver.Error(w, err.Error(), http.StatusBadRequest)
275 clusterId = hasClusterId.ClusterID
278 effectiveMethod := req.Method
279 if req.Method == "POST" && len(params["_method"]) == 1 {
280 effectiveMethod = params["_method"][0]
283 if effectiveMethod == "GET" && clusterId == "" && len(params["filters"]) == 1 {
284 if h.handleMultiClusterQuery(w, req, params, &clusterId) {
288 log.Printf("Clusterid is %q", clusterId)
290 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
291 h.next.ServeHTTP(w, req)
293 h.handler.remoteClusterRequest(clusterId, w, req, nil)
297 type rewriteSignaturesClusterId struct {
302 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
303 if requestError != nil {
304 return resp, requestError
307 if resp.StatusCode != 200 {
311 originalBody := resp.Body
312 defer originalBody.Close()
314 var col arvados.Collection
315 err = json.NewDecoder(resp.Body).Decode(&col)
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)))
325 mw := io.MultiWriter(hasher, updatedManifest)
328 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
329 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
331 line := scanner.Text()
332 tokens := strings.Split(line, " ")
334 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
337 n, err := mw.Write([]byte(tokens[0]))
339 return nil, fmt.Errorf("Error updating manifest: %v", err)
342 for _, token := range tokens[1:] {
343 n, err = mw.Write([]byte(" "))
345 return nil, fmt.Errorf("Error updating manifest: %v", err)
349 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
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])
354 return nil, fmt.Errorf("Error updating manifest: %v", err)
357 // for hash checking, ignore signatures
358 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
360 return nil, fmt.Errorf("Error updating manifest: %v", err)
364 n, err = mw.Write([]byte(token))
366 return nil, fmt.Errorf("Error updating manifest: %v", err)
371 n, err = mw.Write([]byte("\n"))
373 return nil, fmt.Errorf("Error updating manifest: %v", err)
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)
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)
393 col.ManifestText = updatedManifest.String()
395 newbody, err := json.Marshal(col)
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()))
408 type searchLocalClusterForPDH struct {
412 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
413 if requestError != nil {
414 return resp, requestError
417 if resp.StatusCode == 404 {
418 // Suppress returning this result, because we want to
419 // search the federation.
420 s.sentResponse = false
423 s.sentResponse = true
427 type searchRemoteClusterForPDH struct {
432 sharedContext *context.Context
438 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
443 // Another request already returned a response
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
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
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)
477 // Another request already returned a response
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))
488 // We have a successful response. Suppress/cancel all the
489 // other requests/responses.
490 *s.sentResponse = true
493 return newResponse, nil
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)
503 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
505 // Not a collection PDH GET request
506 m = collectionRe.FindStringSubmatch(req.URL.Path)
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)
519 // not a collection UUID request, or it is a request
520 // for a local UUID, either way, continue down the
522 h.next.ServeHTTP(w, req)
526 // Request for collection by PDH. Search the federation.
528 // First, query the local cluster.
529 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
531 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
536 Scheme: urlOut.Scheme,
539 RawPath: req.URL.RawPath,
540 RawQuery: req.URL.RawQuery,
542 client := h.handler.secureClient
544 client = h.handler.insecureClient
546 sf := &searchLocalClusterForPDH{}
547 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
552 sharedContext, cancelFunc := context.WithCancel(req.Context())
554 req = req.WithContext(sharedContext)
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
561 sentResponse := false
563 wg := sync.WaitGroup{}
565 var errorCode int = 404
567 // use channel as a semaphore to limit it to 4
568 // parallel requests at a time
569 sem := make(chan bool, 4)
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)
578 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
579 &sharedContext, cancelFunc, &errors, &errorCode}
582 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
593 // No successful responses, so return the error
594 httpserver.Errors(w, errors, errorCode)
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)
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)
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)
624 mux.ServeHTTP(w, req)
630 type CurrentUser struct {
631 Authorization arvados.APIClientAuthorization
635 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
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)
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 {
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")
661 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
663 if len(creds.Tokens) == 0 {
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, ¤tUser)
673 if err == sql.ErrNoRows {
674 // Not ours; pass through unmodified.
675 token = currentUser.Authorization.APIToken
676 } else if err != nil {
679 // Found; make V2 version and salt it.
680 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
685 } else if err != nil {
688 req.Header.Set("Authorization", "Bearer "+token)
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 {
694 } else if _, ok := values["api_token"]; ok {
695 delete(values, "api_token")
696 req.URL.RawQuery = values.Encode()