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 // Certify that the computed hash of the manifest matches our expectation
163 if rw.expectHash == "" {
164 rw.expectHash = col.PortableDataHash
167 sum := hasher.Sum(nil)
168 computedHash := fmt.Sprintf("%x+%v", sum, sz)
169 if computedHash != rw.expectHash {
170 return nil, fmt.Errorf("Computed hash %q did not match expected hash %q", computedHash, rw.expectHash)
173 col.ManifestText = updatedManifest.String()
175 newbody, err := json.Marshal(col)
180 buf := bytes.NewBuffer(newbody)
181 resp.Body = ioutil.NopCloser(buf)
182 resp.ContentLength = int64(buf.Len())
183 resp.Header.Set("Content-Length", fmt.Sprintf("%v", buf.Len()))
188 type searchLocalClusterForPDH struct {
192 func (s *searchLocalClusterForPDH) filterLocalClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
193 if requestError != nil {
194 return resp, requestError
197 if resp.StatusCode == 404 {
198 // Suppress returning this result, because we want to
199 // search the federation.
200 s.sentResponse = false
203 s.sentResponse = true
207 type searchRemoteClusterForPDH struct {
212 sharedContext *context.Context
218 func (s *searchRemoteClusterForPDH) filterRemoteClusterResponse(resp *http.Response, requestError error) (newResponse *http.Response, err error) {
223 // Another request already returned a response
227 if requestError != nil {
228 *s.errors = append(*s.errors, fmt.Sprintf("Request error contacting %q: %v", s.remoteID, requestError))
229 // Record the error and suppress response
233 if resp.StatusCode != 200 {
234 // Suppress returning unsuccessful result. Maybe
235 // another request will find it.
236 // TODO collect and return error responses.
237 *s.errors = append(*s.errors, fmt.Sprintf("Response from %q: %v", s.remoteID, resp.Status))
238 if resp.StatusCode != 404 {
239 // Got a non-404 error response, convert into BadGateway
240 *s.statusCode = http.StatusBadGateway
247 // This reads the response body. We don't want to hold the
248 // lock while doing this because other remote requests could
249 // also have made it to this point, and we don't want a
250 // slow response holding the lock to block a faster response
251 // that is waiting on the lock.
252 newResponse, err = rewriteSignaturesClusterId{s.remoteID, s.pdh}.rewriteSignatures(resp, nil)
257 // Another request already returned a response
262 // Suppress returning unsuccessful result. Maybe
263 // another request will be successful.
264 *s.errors = append(*s.errors, fmt.Sprintf("Error parsing response from %q: %v", s.remoteID, err))
268 // We have a successful response. Suppress/cancel all the
269 // other requests/responses.
270 *s.sentResponse = true
273 return newResponse, nil
276 func (h *collectionFederatedRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
277 m := collectionByPDHRe.FindStringSubmatch(req.URL.Path)
279 // Not a collection PDH request
280 m = collectionRe.FindStringSubmatch(req.URL.Path)
281 if len(m) == 2 && m[1] != h.handler.Cluster.ClusterID {
282 // request for remote collection by uuid
283 h.handler.remoteClusterRequest(m[1], w, req,
284 rewriteSignaturesClusterId{m[1], ""}.rewriteSignatures)
287 // not a collection UUID request, or it is a request
288 // for a local UUID, either way, continue down the
290 h.next.ServeHTTP(w, req)
294 // Request for collection by PDH. Search the federation.
296 // First, query the local cluster.
297 urlOut, insecure, err := findRailsAPI(h.handler.Cluster, h.handler.NodeProfile)
299 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
304 Scheme: urlOut.Scheme,
307 RawPath: req.URL.RawPath,
308 RawQuery: req.URL.RawQuery,
310 client := h.handler.secureClient
312 client = h.handler.insecureClient
314 sf := &searchLocalClusterForPDH{}
315 h.handler.proxy.Do(w, req, urlOut, client, sf.filterLocalClusterResponse)
320 sharedContext, cancelFunc := context.WithCancel(req.Context())
322 req = req.WithContext(sharedContext)
324 // Create a goroutine for each cluster in the
325 // RemoteClusters map. The first valid result gets
326 // returned to the client. When that happens, all
327 // other outstanding requests are cancelled or
329 sentResponse := false
331 wg := sync.WaitGroup{}
333 var errorCode int = 404
335 // use channel as a semaphore to limit it to 4
336 // parallel requests at a time
337 sem := make(chan bool, 4)
339 for remoteID := range h.handler.Cluster.RemoteClusters {
340 // blocks until it can put a value into the
341 // channel (which has a max queue capacity)
346 search := &searchRemoteClusterForPDH{m[1], remoteID, &mtx, &sentResponse,
347 &sharedContext, cancelFunc, &errors, &errorCode}
350 h.handler.remoteClusterRequest(search.remoteID, w, req, search.filterRemoteClusterResponse)
361 // No successful responses, so return the error
362 httpserver.Errors(w, errors, errorCode)
365 func (h *Handler) setupProxyRemoteCluster(next http.Handler) http.Handler {
366 mux := http.NewServeMux()
367 mux.Handle("/arvados/v1/workflows", next)
368 mux.Handle("/arvados/v1/workflows/", &genericFederatedRequestHandler{next, h})
369 mux.Handle("/arvados/v1/collections", next)
370 mux.Handle("/arvados/v1/collections/", &collectionFederatedRequestHandler{next, h})
371 mux.Handle("/", next)
373 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
374 parts := strings.Split(req.Header.Get("Authorization"), "/")
375 alreadySalted := (len(parts) == 3 && parts[0] == "Bearer v2" && len(parts[2]) == 40)
378 strings.Index(req.Header.Get("Via"), "arvados-controller") != -1 {
379 // The token is already salted, or this is a
380 // request from another instance of
381 // arvados-controller. In either case, we
382 // don't want to proxy this query, so just
383 // continue down the instance handler stack.
384 next.ServeHTTP(w, req)
388 mux.ServeHTTP(w, req)
394 type CurrentUser struct {
395 Authorization arvados.APIClientAuthorization
399 func (h *Handler) validateAPItoken(req *http.Request, user *CurrentUser) error {
404 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)
407 // Extract the auth token supplied in req, and replace it with a
408 // salted token for the remote cluster.
409 func (h *Handler) saltAuthToken(req *http.Request, remote string) error {
410 creds := auth.NewCredentials()
411 creds.LoadTokensFromHTTPRequest(req)
412 if len(creds.Tokens) == 0 && req.Header.Get("Content-Type") == "application/x-www-form-encoded" {
413 // Override ParseForm's 10MiB limit by ensuring
414 // req.Body is a *http.maxBytesReader.
415 req.Body = http.MaxBytesReader(nil, req.Body, 1<<28) // 256MiB. TODO: use MaxRequestSize from discovery doc or config.
416 if err := creds.LoadTokensFromHTTPRequestBody(req); err != nil {
419 // Replace req.Body with a buffer that re-encodes the
420 // form without api_token, in case we end up
421 // forwarding the request.
422 if req.PostForm != nil {
423 req.PostForm.Del("api_token")
425 req.Body = ioutil.NopCloser(bytes.NewBufferString(req.PostForm.Encode()))
427 if len(creds.Tokens) == 0 {
430 token, err := auth.SaltToken(creds.Tokens[0], remote)
431 if err == auth.ErrObsoleteToken {
432 // If the token exists in our own database, salt it
433 // for the remote. Otherwise, assume it was issued by
434 // the remote, and pass it through unmodified.
435 currentUser := CurrentUser{Authorization: arvados.APIClientAuthorization{APIToken: creds.Tokens[0]}}
436 err = h.validateAPItoken(req, ¤tUser)
437 if err == sql.ErrNoRows {
438 // Not ours; pass through unmodified.
439 token = currentUser.Authorization.APIToken
440 } else if err != nil {
443 // Found; make V2 version and salt it.
444 token, err = auth.SaltToken(currentUser.Authorization.TokenV2(), remote)
449 } else if err != nil {
452 req.Header.Set("Authorization", "Bearer "+token)
454 // Remove api_token=... from the the query string, in case we
455 // end up forwarding the request.
456 if values, err := url.ParseQuery(req.URL.RawQuery); err != nil {
458 } else if _, ok := values["api_token"]; ok {
459 delete(values, "api_token")
460 req.URL.RawQuery = values.Encode()