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 containersRe = regexp.MustCompile(`^/arvados/v1/containers/([0-9a-z]{5})-[^/]+$`)
31 var containerRequestsRe = regexp.MustCompile(`^/arvados/v1/container_requests/([0-9a-z]{5})-[^/]+$`)
32 var collectionRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-z]{5})-[^/]+$`)
33 var collectionByPDHRe = regexp.MustCompile(`^/arvados/v1/collections/([0-9a-fA-F]{32}\+[0-9]+)+$`)
35 type genericFederatedRequestHandler struct {
38 matcher *regexp.Regexp
41 type collectionFederatedRequestHandler struct {
46 func (h *Handler) remoteClusterRequest(remoteID string, w http.ResponseWriter, req *http.Request, filter ResponseFilter) {
47 remote, ok := h.Cluster.RemoteClusters[remoteID]
49 httpserver.Error(w, "no proxy available for cluster "+remoteID, http.StatusNotFound)
52 scheme := remote.Scheme
56 err := h.saltAuthToken(req, remoteID)
58 httpserver.Error(w, err.Error(), http.StatusBadRequest)
65 RawPath: req.URL.RawPath,
66 RawQuery: req.URL.RawQuery,
68 client := h.secureClient
70 client = h.insecureClient
72 h.proxy.Do(w, req, urlOut, client, filter)
75 func (h *genericFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
76 m := h.matcher.FindStringSubmatch(req.URL.Path)
77 if len(m) < 2 || m[1] == h.handler.Cluster.ClusterID {
78 h.next.ServeHTTP(w, req)
81 h.handler.remoteClusterRequest(m[1], w, req, nil)
84 type rewriteSignaturesClusterId struct {
89 func (rw rewriteSignaturesClusterId) rewriteSignatures(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
90 if requestError != nil {
91 return resp, requestError
94 if resp.StatusCode != 200 {
98 originalBody := resp.Body
99 defer originalBody.Close()
101 var col arvados.Collection
102 err = json.NewDecoder(resp.Body).Decode(&col)
107 // rewriting signatures will make manifest text 5-10% bigger so calculate
108 // capacity accordingly
109 updatedManifest := bytes.NewBuffer(make([]byte, 0, int(float64(len(col.ManifestText))*1.1)))
112 mw := io.MultiWriter(hasher, updatedManifest)
115 scanner := bufio.NewScanner(strings.NewReader(col.ManifestText))
116 scanner.Buffer(make([]byte, 1048576), len(col.ManifestText))
118 line := scanner.Text()
119 tokens := strings.Split(line, " ")
121 return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
124 n, err := mw.Write([]byte(tokens[0]))
126 return nil, fmt.Errorf("Error updating manifest: %v", err)
129 for _, token := range tokens[1:] {
130 n, err = mw.Write([]byte(" "))
132 return nil, fmt.Errorf("Error updating manifest: %v", err)
136 m := keepclient.SignedLocatorRe.FindStringSubmatch(token)
138 // Rewrite the block signature to be a remote signature
139 _, err = fmt.Fprintf(updatedManifest, "%s%s%s+R%s-%s%s", m[1], m[2], m[3], rw.clusterID, m[5][2:], m[8])
141 return nil, fmt.Errorf("Error updating manifest: %v", err)
144 // for hash checking, ignore signatures
145 n, err = fmt.Fprintf(hasher, "%s%s", m[1], m[2])
147 return nil, fmt.Errorf("Error updating manifest: %v", err)
151 n, err = mw.Write([]byte(token))
153 return nil, fmt.Errorf("Error updating manifest: %v", err)
158 n, err = mw.Write([]byte("\n"))
160 return nil, fmt.Errorf("Error updating manifest: %v", err)
165 // Check that expected hash is consistent with
166 // portable_data_hash field of the returned record
167 if rw.expectHash == "" {
168 rw.expectHash = col.PortableDataHash
169 } else if rw.expectHash != col.PortableDataHash {
170 return nil, fmt.Errorf("portable_data_hash %q on returned record did not match expected hash %q ", rw.expectHash, col.PortableDataHash)
173 // Certify that the computed hash of the manifest_text matches our expectation
174 sum := hasher.Sum(nil)
175 computedHash := fmt.Sprintf("%x+%v", sum, sz)
176 if computedHash != rw.expectHash {
177 return nil, fmt.Errorf("Computed manifest_text hash %q did not match expected hash %q", computedHash, rw.expectHash)
180 col.ManifestText = updatedManifest.String()
182 newbody, err := json.Marshal(col)
187 buf := bytes.NewBuffer(newbody)
188 resp.Body = ioutil.NopCloser(buf)
189 resp.ContentLength = int64(buf.Len())
190 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
195 type searchLocalClusterForPDH struct {
199 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
200 if requestError != nil {
201 return resp, requestError
204 if resp.StatusCode == 404 {
205 // Suppress returning this result, because we want to
206 // search the federation.
207 s.sentResponse = false
210 s.sentResponse = true
214 type searchRemoteClusterForPDH struct {
219 sharedContext *context.Context
225 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
230 // Another request already returned a response
234 if requestError != nil {
235 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
236 // Record the error and suppress response
240 if resp.StatusCode != 200 {
241 // Suppress returning unsuccessful result. Maybe
242 // another request will find it.
243 // TODO collect and return error responses.
244 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
245 if resp.StatusCode != 404 {
246 // Got a non-404 error response, convert into BadGateway
247 *s.statusCode = http.StatusBadGateway
254 // This reads the response body. We don't want to hold the
255 // lock while doing this because other remote requests could
256 // also have made it to this point, and we don't want a
257 // slow response holding the lock to block a faster response
258 // that is waiting on the lock.
259 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
264 // Another request already returned a response
269 // Suppress returning unsuccessful result. Maybe
270 // another request will be successful.
271 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
275 // We have a successful response. Suppress/cancel all the
276 // other requests/responses.
277 *s.sentResponse = true
280 return newResponse, nil
283 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
284 if req.Method != "GET" {
285 // Only handle GET requests right now
286 h.next.ServeHTTP(w, req)
290 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
292 // Not a collection PDH GET request
293 m = collectionRe.FindStringSubmatch(req.URL.Path)
294 if len(m) == 2 && m[1] != h.handler.Cluster.ClusterID {
295 // request for remote collection by uuid
296 h.handler.remoteClusterRequest(m[1], w, req,
297 rewriteSignaturesClusterId{m[1], ""}.rewriteSignatures)
300 // not a collection UUID request, or it is a request
301 // for a local UUID, either way, continue down the
303 h.next.ServeHTTP(w, req)
307 // Request for collection by PDH. Search the federation.
309 // First, query the local cluster.
310 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
312 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
317 Scheme: urlOut.Scheme,
320 RawPath: req.URL.RawPath,
321 RawQuery: req.URL.RawQuery,
323 client := h.handler.secureClient
325 client = h.handler.insecureClient
327 sf := &searchLocalClusterForPDH{}
328 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
333 sharedContext, cancelFunc := context.WithCancel(req.Context())
335 req = req.WithContext(sharedContext)
337 // Create a goroutine for each cluster in the
338 // RemoteClusters map. The first valid result gets
339 // returned to the client. When that happens, all
340 // other outstanding requests are cancelled or
342 sentResponse := false
344 wg := sync.WaitGroup{}
346 var errorCode int = 404
348 // use channel as a semaphore to limit it to 4
349 // parallel requests at a time
350 sem := make(chan bool, 4)
352 for remoteID := range h.handler.Cluster.RemoteClusters {
353 // blocks until it can put a value into the
354 // channel (which has a max queue capacity)
359 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
360 &sharedContext, cancelFunc, &errors, &errorCode}
363 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
374 // No successful responses, so return the error
375 httpserver.Errors(w, errors, errorCode)
378 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
379 mux := http.NewServeMux()
381 mux.Handle("/arvados/v1/workflows", next)
382 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h, wfRe})
383 mux.Handle("/arvados/v1/containers", next)
384 mux.Handle("/arvados/v1/containers/", &genericFederatedRequestHandler{next, h, containersRe})
385 mux.Handle("/arvados/v1/container_requests", next)
386 mux.Handle("/arvados/v1/container_requests/", &genericFederatedRequestHandler{next, h, containerRequestsRe})
387 mux.Handle("/arvados/v1/collections", next)
388 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
389 mux.Handle("/", next)
391 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
392 parts := strings.Split(req.Header.Get("Authorization"), "/")
393 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
396 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
397 // The token is already salted, or this is a
398 // request from another instance of
399 // arvados-controller. In either case, we
400 // don't want to proxy this query, so just
401 // continue down the instance handler stack.
402 next.ServeHTTP(w, req)
406 mux.ServeHTTP(w, req)
412 type CurrentUser struct {
413 Authorization arvados.APIClientAuthorization
417 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
422 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)
425 // Extract the auth token supplied in req, and replace it with a
426 // salted token for the remote cluster.
427 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
428 creds := auth.NewCredentials()
429 creds.LoadTokensFromHTTPRequest(req)
430 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
431 // Override ParseForm's 10MiB limit by ensuring
432 // req.Body is a *http.maxBytesReader.
433 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
434 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
437 // Replace req.Body with a buffer that re-encodes the
438 // form without api_token, in case we end up
439 // forwarding the request.
440 if req.PostForm != nil {
441 req.PostForm.Del("api_token")
443 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
445 if len(creds.Tokens) == 0 {
448 token, err := auth.SaltToken(creds.Tokens[0], remote)
449 if err == auth.ErrObsoleteToken {
450 // If the token exists in our own database, salt it
451 // for the remote. Otherwise, assume it was issued by
452 // the remote, and pass it through unmodified.
453 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
454 err = h.validateAPItoken(req, ¤tUser)
455 if err == sql.ErrNoRows {
456 // Not ours; pass through unmodified.
457 token = currentUser.Authorization.APIToken
458 } else if err != nil {
461 // Found; make V2 version and salt it.
462 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
467 } else if err != nil {
470 req.Header.Set("Authorization", "Bearer "+token)
472 // Remove api_token=... from the the query string, in case we
473 // end up forwarding the request.
474 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
476 } else if _, ok := values["api_token"]; ok {
477 delete(values, "api_token")
478 req.URL.RawQuery = values.Encode()