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-)?.*$`
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 (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
77 m := h.matcher.FindStringSubmatch(req.URL.Path)
85 if values, err := url.ParseQuery(req.URL.RawQuery); err == nil {
86 if len(values["cluster_id"]) == 1 {
87 clusterId = values["cluster_id"][0]
92 if clusterId == "" && req.Method == "POST" {
93 var hasClusterId struct {
94 ClusterID string `json:"cluster_id"`
97 if req.ContentLength > 0 {
98 cl = req.ContentLength
100 postBody := bytes.NewBuffer(make([]byte, 0, cl))
101 defer req.Body.Close()
103 rdr := io.TeeReader(req.Body, postBody)
105 err := json.NewDecoder(rdr).Decode(&hasClusterId)
109 req.Body = ioutil.NopCloser(postBody)
111 clusterId = hasClusterId.ClusterID
114 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
115 h.next.ServeHTTP(w, req)
117 h.handler.remoteClusterRequest(clusterId, w, req, nil)
121 type rewriteSignaturesClusterId struct {
126 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
127 if requestError != nil {
128 return resp, requestError
131 if resp.StatusCode != 200 {
135 originalBody := resp.Body
136 defer originalBody.Close()
138 var col arvados.Collection
139 err = json.NewDecoder(resp.Body).Decode(&col)
144 // rewriting signatures will make manifest text 5-10% bigger so calculate
145 // capacity accordingly
146 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
149 mw := io.MultiWriter(hasher, updatedManifest)
152 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
153 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
155 line := scanner.Text()
156 tokens := strings.Split(line, " ")
158 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
161 n, err := mw.Write([]byte(tokens[0]))
163 return nil, fmt.Errorf("Error updating manifest: %v", err)
166 for _, token := range tokens[1:] {
167 n, err = mw.Write([]byte(" "))
169 return nil, fmt.Errorf("Error updating manifest: %v", err)
173 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
175 // Rewrite the block signature to be a remote signature
176 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
178 return nil, fmt.Errorf("Error updating manifest: %v", err)
181 // for hash checking, ignore signatures
182 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
184 return nil, fmt.Errorf("Error updating manifest: %v", err)
188 n, err = mw.Write([]byte(token))
190 return nil, fmt.Errorf("Error updating manifest: %v", err)
195 n, err = mw.Write([]byte("\n"))
197 return nil, fmt.Errorf("Error updating manifest: %v", err)
202 // Check that expected hash is consistent with
203 // portable_data_hash field of the returned record
204 if rw.expectHash == "" {
205 rw.expectHash = col.PortableDataHash
206 } else if rw.expectHash != col.PortableDataHash {
207 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
210 // Certify that the computed hash of the manifest_text matches our expectation
211 sum := hasher.Sum(nil)
212 computedHash := fmt.Sprintf("%x+%v", sum, sz)
213 if computedHash != rw.expectHash {
214 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
217 col.ManifestText = updatedManifest.String()
219 newbody, err := json.Marshal(col)
224 buf := bytes.NewBuffer(newbody)
225 resp.Body = ioutil.NopCloser(buf)
226 resp.ContentLength = int64(buf.Len())
227 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
232 type searchLocalClusterForPDH struct {
236 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
237 if requestError != nil {
238 return resp, requestError
241 if resp.StatusCode == 404 {
242 // Suppress returning this result, because we want to
243 // search the federation.
244 s.sentResponse = false
247 s.sentResponse = true
251 type searchRemoteClusterForPDH struct {
256 sharedContext *context.Context
262 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
267 // Another request already returned a response
271 if requestError != nil {
272 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
273 // Record the error and suppress response
277 if resp.StatusCode != 200 {
278 // Suppress returning unsuccessful result. Maybe
279 // another request will find it.
280 // TODO collect and return error responses.
281 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
282 if resp.StatusCode != 404 {
283 // Got a non-404 error response, convert into BadGateway
284 *s.statusCode = http.StatusBadGateway
291 // This reads the response body. We don't want to hold the
292 // lock while doing this because other remote requests could
293 // also have made it to this point, and we don't want a
294 // slow response holding the lock to block a faster response
295 // that is waiting on the lock.
296 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
301 // Another request already returned a response
306 // Suppress returning unsuccessful result. Maybe
307 // another request will be successful.
308 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
312 // We have a successful response. Suppress/cancel all the
313 // other requests/responses.
314 *s.sentResponse = true
317 return newResponse, nil
320 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
321 if req.Method != "GET" {
322 // Only handle GET requests right now
323 h.next.ServeHTTP(w, req)
327 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
329 // Not a collection PDH GET request
330 m = collectionRe.FindStringSubmatch(req.URL.Path)
337 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
338 // request for remote collection by uuid
339 h.handler.remoteClusterRequest(clusterId, w, req,
340 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
343 // not a collection UUID request, or it is a request
344 // for a local UUID, either way, continue down the
346 h.next.ServeHTTP(w, req)
350 // Request for collection by PDH. Search the federation.
352 // First, query the local cluster.
353 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
355 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
360 Scheme: urlOut.Scheme,
363 RawPath: req.URL.RawPath,
364 RawQuery: req.URL.RawQuery,
366 client := h.handler.secureClient
368 client = h.handler.insecureClient
370 sf := &searchLocalClusterForPDH{}
371 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
376 sharedContext, cancelFunc := context.WithCancel(req.Context())
378 req = req.WithContext(sharedContext)
380 // Create a goroutine for each cluster in the
381 // RemoteClusters map. The first valid result gets
382 // returned to the client. When that happens, all
383 // other outstanding requests are cancelled or
385 sentResponse := false
387 wg := sync.WaitGroup{}
389 var errorCode int = 404
391 // use channel as a semaphore to limit it to 4
392 // parallel requests at a time
393 sem := make(chan bool, 4)
395 for remoteID := range h.handler.Cluster.RemoteClusters {
396 // blocks until it can put a value into the
397 // channel (which has a max queue capacity)
402 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
403 &sharedContext, cancelFunc, &errors, &errorCode}
406 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
417 // No successful responses, so return the error
418 httpserver.Errors(w, errors, errorCode)
421 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
422 mux := http.NewServeMux()
423 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
424 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
425 mux.Handle("/arvados/v1/containers", next)
426 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
427 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
428 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
429 mux.Handle("/arvados/v1/collections", next)
430 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
431 mux.Handle("/", next)
433 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
434 parts := strings.Split(req.Header.Get("Authorization"), "/")
435 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
438 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
439 // The token is already salted, or this is a
440 // request from another instance of
441 // arvados-controller. In either case, we
442 // don't want to proxy this query, so just
443 // continue down the instance handler stack.
444 next.ServeHTTP(w, req)
448 mux.ServeHTTP(w, req)
454 type CurrentUser struct {
455 Authorization arvados.APIClientAuthorization
459 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
464 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)
467 // Extract the auth token supplied in req, and replace it with a
468 // salted token for the remote cluster.
469 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
470 creds := auth.NewCredentials()
471 creds.LoadTokensFromHTTPRequest(req)
472 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
473 // Override ParseForm's 10MiB limit by ensuring
474 // req.Body is a *http.maxBytesReader.
475 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
476 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
479 // Replace req.Body with a buffer that re-encodes the
480 // form without api_token, in case we end up
481 // forwarding the request.
482 if req.PostForm != nil {
483 req.PostForm.Del("api_token")
485 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
487 if len(creds.Tokens) == 0 {
490 token, err := auth.SaltToken(creds.Tokens[0], remote)
491 if err == auth.ErrObsoleteToken {
492 // If the token exists in our own database, salt it
493 // for the remote. Otherwise, assume it was issued by
494 // the remote, and pass it through unmodified.
495 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
496 err = h.validateAPItoken(req, ¤tUser)
497 if err == sql.ErrNoRows {
498 // Not ours; pass through unmodified.
499 token = currentUser.Authorization.APIToken
500 } else if err != nil {
503 // Found; make V2 version and salt it.
504 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
509 } else if err != nil {
512 req.Header.Set("Authorization", "Bearer "+token)
514 // Remove api_token=... from the the query string, in case we
515 // end up forwarding the request.
516 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
518 } else if _, ok := values["api_token"]; ok {
519 delete(values, "api_token")
520 req.URL.RawQuery = values.Encode()