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" && req.Header.Get("Content-Type") == "application/json" {
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)
107 httpserver.Error(w, err.Error(), http.StatusBadRequest)
110 req.Body = ioutil.NopCloser(postBody)
112 clusterId = hasClusterId.ClusterID
115 if clusterId == "" || clusterId == h.handler.Cluster.ClusterID {
116 h.next.ServeHTTP(w, req)
118 h.handler.remoteClusterRequest(clusterId, w, req, nil)
122 type rewriteSignaturesClusterId struct {
127 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
128 if requestError != nil {
129 return resp, requestError
132 if resp.StatusCode != 200 {
136 originalBody := resp.Body
137 defer originalBody.Close()
139 var col arvados.Collection
140 err = json.NewDecoder(resp.Body).Decode(&col)
145 // rewriting signatures will make manifest text 5-10% bigger so calculate
146 // capacity accordingly
147 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
150 mw := io.MultiWriter(hasher, updatedManifest)
153 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
154 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
156 line := scanner.Text()
157 tokens := strings.Split(line, " ")
159 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
162 n, err := mw.Write([]byte(tokens[0]))
164 return nil, fmt.Errorf("Error updating manifest: %v", err)
167 for _, token := range tokens[1:] {
168 n, err = mw.Write([]byte(" "))
170 return nil, fmt.Errorf("Error updating manifest: %v", err)
174 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
176 // Rewrite the block signature to be a remote signature
177 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
179 return nil, fmt.Errorf("Error updating manifest: %v", err)
182 // for hash checking, ignore signatures
183 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
185 return nil, fmt.Errorf("Error updating manifest: %v", err)
189 n, err = mw.Write([]byte(token))
191 return nil, fmt.Errorf("Error updating manifest: %v", err)
196 n, err = mw.Write([]byte("\n"))
198 return nil, fmt.Errorf("Error updating manifest: %v", err)
203 // Check that expected hash is consistent with
204 // portable_data_hash field of the returned record
205 if rw.expectHash == "" {
206 rw.expectHash = col.PortableDataHash
207 } else if rw.expectHash != col.PortableDataHash {
208 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
211 // Certify that the computed hash of the manifest_text matches our expectation
212 sum := hasher.Sum(nil)
213 computedHash := fmt.Sprintf("%x+%v", sum, sz)
214 if computedHash != rw.expectHash {
215 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
218 col.ManifestText = updatedManifest.String()
220 newbody, err := json.Marshal(col)
225 buf := bytes.NewBuffer(newbody)
226 resp.Body = ioutil.NopCloser(buf)
227 resp.ContentLength = int64(buf.Len())
228 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
233 type searchLocalClusterForPDH struct {
237 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
238 if requestError != nil {
239 return resp, requestError
242 if resp.StatusCode == 404 {
243 // Suppress returning this result, because we want to
244 // search the federation.
245 s.sentResponse = false
248 s.sentResponse = true
252 type searchRemoteClusterForPDH struct {
257 sharedContext *context.Context
263 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
268 // Another request already returned a response
272 if requestError != nil {
273 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
274 // Record the error and suppress response
278 if resp.StatusCode != 200 {
279 // Suppress returning unsuccessful result. Maybe
280 // another request will find it.
281 // TODO collect and return error responses.
282 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
283 if resp.StatusCode != 404 {
284 // Got a non-404 error response, convert into BadGateway
285 *s.statusCode = http.StatusBadGateway
292 // This reads the response body. We don't want to hold the
293 // lock while doing this because other remote requests could
294 // also have made it to this point, and we don't want a
295 // slow response holding the lock to block a faster response
296 // that is waiting on the lock.
297 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
302 // Another request already returned a response
307 // Suppress returning unsuccessful result. Maybe
308 // another request will be successful.
309 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
313 // We have a successful response. Suppress/cancel all the
314 // other requests/responses.
315 *s.sentResponse = true
318 return newResponse, nil
321 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
322 if req.Method != "GET" {
323 // Only handle GET requests right now
324 h.next.ServeHTTP(w, req)
328 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
330 // Not a collection PDH GET request
331 m = collectionRe.FindStringSubmatch(req.URL.Path)
338 if clusterId != "" && clusterId != h.handler.Cluster.ClusterID {
339 // request for remote collection by uuid
340 h.handler.remoteClusterRequest(clusterId, w, req,
341 rewriteSignaturesClusterId{clusterId, ""}.rewriteSignatures)
344 // not a collection UUID request, or it is a request
345 // for a local UUID, either way, continue down the
347 h.next.ServeHTTP(w, req)
351 // Request for collection by PDH. Search the federation.
353 // First, query the local cluster.
354 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
356 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
361 Scheme: urlOut.Scheme,
364 RawPath: req.URL.RawPath,
365 RawQuery: req.URL.RawQuery,
367 client := h.handler.secureClient
369 client = h.handler.insecureClient
371 sf := &searchLocalClusterForPDH{}
372 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
377 sharedContext, cancelFunc := context.WithCancel(req.Context())
379 req = req.WithContext(sharedContext)
381 // Create a goroutine for each cluster in the
382 // RemoteClusters map. The first valid result gets
383 // returned to the client. When that happens, all
384 // other outstanding requests are cancelled or
386 sentResponse := false
388 wg := sync.WaitGroup{}
390 var errorCode int = 404
392 // use channel as a semaphore to limit it to 4
393 // parallel requests at a time
394 sem := make(chan bool, 4)
396 for remoteID := range h.handler.Cluster.RemoteClusters {
397 // blocks until it can put a value into the
398 // channel (which has a max queue capacity)
403 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
404 &sharedContext, cancelFunc, &errors, &errorCode}
407 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
418 // No successful responses, so return the error
419 httpserver.Errors(w, errors, errorCode)
422 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
423 mux := http.NewServeMux()
424 mux.Handle("/arvados/v1/workflows", &genericFederatedRequestHandler{next, h, wfRe})
425 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
426 mux.Handle("/arvados/v1/containers", next)
427 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
428 mux.Handle("/arvados/v1/container_requests", &genericFederatedRequestHandler{next, h, containerRequestsRe})
429 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
430 mux.Handle("/arvados/v1/collections", next)
431 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
432 mux.Handle("/", next)
434 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
435 parts := strings.Split(req.Header.Get("Authorization"), "/")
436 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
439 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
440 // The token is already salted, or this is a
441 // request from another instance of
442 // arvados-controller. In either case, we
443 // don't want to proxy this query, so just
444 // continue down the instance handler stack.
445 next.ServeHTTP(w, req)
449 mux.ServeHTTP(w, req)
455 type CurrentUser struct {
456 Authorization arvados.APIClientAuthorization
460 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
465 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)
468 // Extract the auth token supplied in req, and replace it with a
469 // salted token for the remote cluster.
470 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
471 creds := auth.NewCredentials()
472 creds.LoadTokensFromHTTPRequest(req)
473 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
474 // Override ParseForm's 10MiB limit by ensuring
475 // req.Body is a *http.maxBytesReader.
476 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
477 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
480 // Replace req.Body with a buffer that re-encodes the
481 // form without api_token, in case we end up
482 // forwarding the request.
483 if req.PostForm != nil {
484 req.PostForm.Del("api_token")
486 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
488 if len(creds.Tokens) == 0 {
491 token, err := auth.SaltToken(creds.Tokens[0], remote)
492 if err == auth.ErrObsoleteToken {
493 // If the token exists in our own database, salt it
494 // for the remote. Otherwise, assume it was issued by
495 // the remote, and pass it through unmodified.
496 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
497 err = h.validateAPItoken(req, ¤tUser)
498 if err == sql.ErrNoRows {
499 // Not ours; pass through unmodified.
500 token = currentUser.Authorization.APIToken
501 } else if err != nil {
504 // Found; make V2 version and salt it.
505 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
510 } else if err != nil {
513 req.Header.Set("Authorization", "Bearer "+token)
515 // Remove api_token=... from the the query string, in case we
516 // end up forwarding the request.
517 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
519 } else if _, ok := values["api_token"]; ok {
520 delete(values, "api_token")
521 req.URL.RawQuery = values.Encode()