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 wfRe = regexp.MustCompile(`^/arvados/v1/workflows/([0-9a-z]{5})-[^/]+$`)
30 var collectionRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-z]{5})-[^/]+$`)
31 var collectionByPDHRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-fA-F]{32}\+[0-9]+)+$`)
33 type genericFederatedRequestHandler struct {
38 type collectionFederatedRequestHandler struct {
43 func (h *Handler) remoteClusterRequest(remoteID string, w http.ResponseWriter, req *http.Request, filter ResponseFilter) {
44 remote, ok := h.Cluster.RemoteClusters[remoteID]
46 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
49 scheme := remote.Scheme
53 err := h.saltAuthToken(req, remoteID)
55 httpserver.Error(w, err.Error(), http.StatusBadRequest)
62 RawPath: req.URL.RawPath,
63 RawQuery: req.URL.RawQuery,
65 client := h.secureClient
67 client = h.insecureClient
69 h.proxy.Do(w, req, urlOut, client, filter)
72 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
73 m := wfRe.FindStringSubmatch(req.URL.Path)
74 if len(m) < 2 || m[1] == h.handler.Cluster.ClusterID {
75 h.next.ServeHTTP(w, req)
78 h.handler.remoteClusterRequest(m[1], w, req, nil)
81 type rewriteSignaturesClusterId struct {
86 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
87 if requestError != nil {
88 return resp, requestError
91 if resp.StatusCode != 200 {
95 originalBody := resp.Body
96 defer originalBody.Close()
98 var col arvados.Collection
99 err = json.NewDecoder(resp.Body).Decode(&col)
104 // rewriting signatures will make manifest text 5-10% bigger so calculate
105 // capacity accordingly
106 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
109 mw := io.MultiWriter(hasher, updatedManifest)
112 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
113 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
115 line := scanner.Text()
116 tokens := strings.Split(line, " ")
118 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
121 n, err := mw.Write([]byte(tokens[0]))
123 return nil, fmt.Errorf("Error updating manifest: %v", err)
126 for _, token := range tokens[1:] {
127 n, err = mw.Write([]byte(" "))
129 return nil, fmt.Errorf("Error updating manifest: %v", err)
133 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
135 // Rewrite the block signature to be a remote signature
136 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
138 return nil, fmt.Errorf("Error updating manifest: %v", err)
141 // for hash checking, ignore signatures
142 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
144 return nil, fmt.Errorf("Error updating manifest: %v", err)
148 n, err = mw.Write([]byte(token))
150 return nil, fmt.Errorf("Error updating manifest: %v", err)
155 n, err = mw.Write([]byte("\n"))
157 return nil, fmt.Errorf("Error updating manifest: %v", err)
162 // Check that expected hash is consistent with
163 // portable_data_hash field of the returned record
164 if rw.expectHash == "" {
165 rw.expectHash = col.PortableDataHash
166 } else if rw.expectHash != col.PortableDataHash {
167 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
170 // Certify that the computed hash of the manifest_text matches our expectation
171 sum := hasher.Sum(nil)
172 computedHash := fmt.Sprintf("%x+%v", sum, sz)
173 if computedHash != rw.expectHash {
174 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
177 col.ManifestText = updatedManifest.String()
179 newbody, err := json.Marshal(col)
184 buf := bytes.NewBuffer(newbody)
185 resp.Body = ioutil.NopCloser(buf)
186 resp.ContentLength = int64(buf.Len())
187 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
192 type searchLocalClusterForPDH struct {
196 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
197 if requestError != nil {
198 return resp, requestError
201 if resp.StatusCode == 404 {
202 // Suppress returning this result, because we want to
203 // search the federation.
204 s.sentResponse = false
207 s.sentResponse = true
211 type searchRemoteClusterForPDH struct {
216 sharedContext *context.Context
222 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
227 // Another request already returned a response
231 if requestError != nil {
232 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
233 // Record the error and suppress response
237 if resp.StatusCode != 200 {
238 // Suppress returning unsuccessful result. Maybe
239 // another request will find it.
240 // TODO collect and return error responses.
241 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
242 if resp.StatusCode != 404 {
243 // Got a non-404 error response, convert into BadGateway
244 *s.statusCode = http.StatusBadGateway
251 // This reads the response body. We don't want to hold the
252 // lock while doing this because other remote requests could
253 // also have made it to this point, and we don't want a
254 // slow response holding the lock to block a faster response
255 // that is waiting on the lock.
256 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
261 // Another request already returned a response
266 // Suppress returning unsuccessful result. Maybe
267 // another request will be successful.
268 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
272 // We have a successful response. Suppress/cancel all the
273 // other requests/responses.
274 *s.sentResponse = true
277 return newResponse, nil
280 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
281 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
283 // Not a collection PDH request
284 m = collectionRe.FindStringSubmatch(req.URL.Path)
285 if len(m) == 2 && m[1] != h.handler.Cluster.ClusterID {
286 // request for remote collection by uuid
287 h.handler.remoteClusterRequest(m[1], w, req,
288 rewriteSignaturesClusterId{m[1], ""}.rewriteSignatures)
291 // not a collection UUID request, or it is a request
292 // for a local UUID, either way, continue down the
294 h.next.ServeHTTP(w, req)
298 // Request for collection by PDH. Search the federation.
300 // First, query the local cluster.
301 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
303 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
308 Scheme: urlOut.Scheme,
311 RawPath: req.URL.RawPath,
312 RawQuery: req.URL.RawQuery,
314 client := h.handler.secureClient
316 client = h.handler.insecureClient
318 sf := &searchLocalClusterForPDH{}
319 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
324 sharedContext, cancelFunc := context.WithCancel(req.Context())
326 req = req.WithContext(sharedContext)
328 // Create a goroutine for each cluster in the
329 // RemoteClusters map. The first valid result gets
330 // returned to the client. When that happens, all
331 // other outstanding requests are cancelled or
333 sentResponse := false
335 wg := sync.WaitGroup{}
337 var errorCode int = 404
339 // use channel as a semaphore to limit it to 4
340 // parallel requests at a time
341 sem := make(chan bool, 4)
343 for remoteID := range h.handler.Cluster.RemoteClusters {
344 // blocks until it can put a value into the
345 // channel (which has a max queue capacity)
350 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
351 &sharedContext, cancelFunc, &errors, &errorCode}
354 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
365 // No successful responses, so return the error
366 httpserver.Errors(w, errors, errorCode)
369 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
370 mux := http.NewServeMux()
371 mux.Handle("/arvados/v1/workflows", next)
372 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h})
373 mux.Handle("/arvados/v1/collections", next)
374 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
375 mux.Handle("/", next)
377 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
378 parts := strings.Split(req.Header.Get("Authorization"), "/")
379 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
382 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
383 // The token is already salted, or this is a
384 // request from another instance of
385 // arvados-controller. In either case, we
386 // don't want to proxy this query, so just
387 // continue down the instance handler stack.
388 next.ServeHTTP(w, req)
392 mux.ServeHTTP(w, req)
398 type CurrentUser struct {
399 Authorization arvados.APIClientAuthorization
403 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
408 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)
411 // Extract the auth token supplied in req, and replace it with a
412 // salted token for the remote cluster.
413 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
414 creds := auth.NewCredentials()
415 creds.LoadTokensFromHTTPRequest(req)
416 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
417 // Override ParseForm's 10MiB limit by ensuring
418 // req.Body is a *http.maxBytesReader.
419 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
420 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
423 // Replace req.Body with a buffer that re-encodes the
424 // form without api_token, in case we end up
425 // forwarding the request.
426 if req.PostForm != nil {
427 req.PostForm.Del("api_token")
429 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
431 if len(creds.Tokens) == 0 {
434 token, err := auth.SaltToken(creds.Tokens[0], remote)
435 if err == auth.ErrObsoleteToken {
436 // If the token exists in our own database, salt it
437 // for the remote. Otherwise, assume it was issued by
438 // the remote, and pass it through unmodified.
439 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
440 err = h.validateAPItoken(req, ¤tUser)
441 if err == sql.ErrNoRows {
442 // Not ours; pass through unmodified.
443 token = currentUser.Authorization.APIToken
444 } else if err != nil {
447 // Found; make V2 version and salt it.
448 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
453 } else if err != nil {
456 req.Header.Set("Authorization", "Bearer "+token)
458 // Remove api_token=... from the the query string, in case we
459 // end up forwarding the request.
460 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
462 } else if _, ok := values["api_token"]; ok {
463 delete(values, "api_token")
464 req.URL.RawQuery = values.Encode()