1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/lib/service"
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
22 "git.arvados.org/arvados.git/sdk/go/ctxlog"
23 "git.arvados.org/arvados.git/sdk/go/health"
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
25 "git.arvados.org/arvados.git/sdk/go/keepclient"
26 "git.arvados.org/arvados.git/services/keepstore"
27 "github.com/gorilla/mux"
28 lru "github.com/hashicorp/golang-lru"
29 "github.com/prometheus/client_golang/prometheus"
30 "github.com/sirupsen/logrus"
33 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
35 var Command = service.Command(arvados.ServiceNameKeepproxy, newHandlerOrErrorHandler)
37 func newHandlerOrErrorHandler(ctx context.Context, cluster *arvados.Cluster, token string, reg *prometheus.Registry) service.Handler {
38 client, err := arvados.NewClientFromConfig(cluster)
40 return service.ErrorHandler(ctx, cluster, fmt.Errorf("Error setting up arvados client: %w", err))
42 arv, err := arvadosclient.New(client)
44 return service.ErrorHandler(ctx, cluster, fmt.Errorf("Error setting up arvados client: %w", err))
46 kc, err := keepclient.MakeKeepClient(arv)
48 return service.ErrorHandler(ctx, cluster, fmt.Errorf("Error setting up keep client: %w", err))
50 keepclient.RefreshServiceDiscoveryOnSIGHUP()
51 router, err := newHandler(ctx, kc, time.Duration(keepclient.DefaultProxyRequestTimeout), cluster)
53 return service.ErrorHandler(ctx, cluster, err)
58 type tokenCacheEntry struct {
63 type apiTokenCache struct {
64 tokens *lru.TwoQueueCache
68 // RememberToken caches the token and set an expire time. If the
69 // token is already in the cache, it is not updated.
70 func (cache *apiTokenCache) RememberToken(token string, user *arvados.User) {
71 now := time.Now().Unix()
72 _, ok := cache.tokens.Get(token)
74 cache.tokens.Add(token, tokenCacheEntry{
75 expire: now + cache.expireTime,
81 // RecallToken checks if the cached token is known and still believed to be
83 func (cache *apiTokenCache) RecallToken(token string) (bool, *arvados.User) {
84 val, ok := cache.tokens.Get(token)
89 cacheEntry := val.(tokenCacheEntry)
90 now := time.Now().Unix()
91 if now < cacheEntry.expire {
92 // Token is known and still valid
93 return true, cacheEntry.user
96 cache.tokens.Remove(token)
101 func (h *proxyHandler) Done() <-chan struct{} {
105 func (h *proxyHandler) CheckHealth() error {
109 func (h *proxyHandler) checkAuthorizationHeader(req *http.Request) (pass bool, tok string, user *arvados.User) {
110 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
111 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
112 return false, "", nil
116 // Tokens are validated differently depending on what kind of
117 // operation is being performed. For example, tokens in
118 // collection-sharing links permit GET requests, but not
121 if req.Method == "GET" || req.Method == "HEAD" {
127 if ok, user := h.apiTokenCache.RecallToken(op + ":" + tok); ok {
128 // Valid in the cache, short circuit
129 return true, tok, user
133 arv := *h.KeepClient.Arvados
135 arv.RequestID = req.Header.Get("X-Request-Id")
136 user = &arvados.User{}
137 userCurrentError := arv.Call("GET", "users", "", "current", nil, user)
138 err = userCurrentError
139 if err != nil && op == "read" {
140 apiError, ok := err.(arvadosclient.APIServerError)
141 if ok && apiError.HttpStatusCode == http.StatusForbidden {
142 // If it was a scoped "sharing" token it will
143 // return 403 instead of 401 for the current
144 // user check. If it is a download operation
145 // and they have permission to read the
146 // keep_services table, we can allow it.
147 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
151 ctxlog.FromContext(req.Context()).WithError(err).Info("checkAuthorizationHeader error")
152 return false, "", nil
155 if userCurrentError == nil && user.IsAdmin {
156 // checking userCurrentError is probably redundant,
157 // IsAdmin would be false anyway. But can't hurt.
158 if op == "read" && !h.cluster.Collections.KeepproxyPermission.Admin.Download {
159 return false, "", nil
161 if op == "write" && !h.cluster.Collections.KeepproxyPermission.Admin.Upload {
162 return false, "", nil
165 if op == "read" && !h.cluster.Collections.KeepproxyPermission.User.Download {
166 return false, "", nil
168 if op == "write" && !h.cluster.Collections.KeepproxyPermission.User.Upload {
169 return false, "", nil
173 // Success! Update cache
174 h.apiTokenCache.RememberToken(op+":"+tok, user)
176 return true, tok, user
179 // We can't copy the default http transport because http.Transport has
180 // a mutex field, so we make our own using the values of the exported
182 var defaultTransport = http.Transport{
183 Proxy: http.DefaultTransport.(*http.Transport).Proxy,
184 DialContext: http.DefaultTransport.(*http.Transport).DialContext,
185 ForceAttemptHTTP2: http.DefaultTransport.(*http.Transport).ForceAttemptHTTP2,
186 MaxIdleConns: http.DefaultTransport.(*http.Transport).MaxIdleConns,
187 IdleConnTimeout: http.DefaultTransport.(*http.Transport).IdleConnTimeout,
188 TLSHandshakeTimeout: http.DefaultTransport.(*http.Transport).TLSHandshakeTimeout,
189 ExpectContinueTimeout: http.DefaultTransport.(*http.Transport).ExpectContinueTimeout,
192 type proxyHandler struct {
194 *keepclient.KeepClient
196 timeout time.Duration
197 transport *http.Transport
198 cluster *arvados.Cluster
201 func newHandler(ctx context.Context, kc *keepclient.KeepClient, timeout time.Duration, cluster *arvados.Cluster) (service.Handler, error) {
202 rest := mux.NewRouter()
204 // We can't copy the default http transport because
205 // http.Transport has a mutex field, so we copy the fields
206 // that we know have non-zero values in http.DefaultTransport.
207 transport := &http.Transport{
208 Proxy: http.DefaultTransport.(*http.Transport).Proxy,
209 ForceAttemptHTTP2: http.DefaultTransport.(*http.Transport).ForceAttemptHTTP2,
210 MaxIdleConns: http.DefaultTransport.(*http.Transport).MaxIdleConns,
211 IdleConnTimeout: http.DefaultTransport.(*http.Transport).IdleConnTimeout,
212 ExpectContinueTimeout: http.DefaultTransport.(*http.Transport).ExpectContinueTimeout,
213 DialContext: (&net.Dialer{
214 Timeout: keepclient.DefaultConnectTimeout,
215 KeepAlive: keepclient.DefaultKeepAlive,
218 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
219 TLSHandshakeTimeout: keepclient.DefaultTLSHandshakeTimeout,
222 cacheQ, err := lru.New2Q(500)
224 return nil, fmt.Errorf("Error from lru.New2Q: %v", err)
231 transport: transport,
232 apiTokenCache: &apiTokenCache{
239 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
240 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
243 rest.HandleFunc(`/index`, h.Index).Methods("GET")
245 // List blocks whose hash has the given prefix
246 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
248 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
249 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
250 rest.HandleFunc(`/`, h.Put).Methods("POST")
251 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
252 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
254 rest.Handle("/_health/{check}", &health.Handler{
255 Token: cluster.ManagementToken,
259 rest.NotFoundHandler = invalidPathHandler{}
263 var errLoopDetected = errors.New("loop detected")
265 func (h *proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
266 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
267 ctxlog.FromContext(req.Context()).Printf("proxy loop detected (request has Via: %q): perhaps keepproxy is misidentified by gateway config as an external client, or its keep_services record does not have service_type=proxy?", via)
268 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
269 return errLoopDetected
274 func setCORSHeaders(resp http.ResponseWriter) {
275 keepstore.SetCORSHeaders(resp)
276 acam := "Access-Control-Allow-Methods"
277 resp.Header().Set(acam, resp.Header().Get(acam)+", POST")
280 type invalidPathHandler struct{}
282 func (invalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
283 http.Error(resp, "Bad request", http.StatusBadRequest)
286 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
290 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header, or method not allowed")
291 var errContentLengthMismatch = errors.New("Actual length != expected content length")
292 var errMethodNotSupported = errors.New("Method not supported")
294 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
296 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
297 if err := h.checkLoop(resp, req); err != nil {
301 resp.Header().Set("Via", req.Proto+" "+viaAlias)
303 locator := mux.Vars(req)["locator"]
306 var expectLength, responseLength int64
308 logger := ctxlog.FromContext(req.Context())
310 httpserver.SetResponseLogFields(req.Context(), logrus.Fields{
312 "expectLength": expectLength,
313 "responseLength": responseLength,
316 if status != http.StatusOK {
317 http.Error(resp, err.Error(), status)
321 kc := h.makeKeepClient(req)
322 kc.DiskCacheSize = keepclient.DiskCacheDisabled
326 var user *arvados.User
327 if pass, tok, user = h.checkAuthorizationHeader(req); !pass {
328 status, err = http.StatusForbidden, errBadAuthorizationHeader
331 httpserver.SetResponseLogFields(req.Context(), logrus.Fields{
332 "userUUID": user.UUID,
333 "userFullName": user.FullName,
336 // Copy ArvadosClient struct and use the client's API token
337 arvclient := *kc.Arvados
338 arvclient.ApiToken = tok
339 kc.Arvados = &arvclient
341 var reader io.ReadCloser
343 locator = removeHint.ReplaceAllString(locator, "$1")
347 expectLength, _, err = kc.Ask(locator)
349 reader, expectLength, _, err = kc.Get(locator)
354 status, err = http.StatusNotImplemented, errMethodNotSupported
358 if expectLength == -1 {
359 logger.Warn("Content-Length not provided")
362 switch respErr := err.(type) {
364 status = http.StatusOK
365 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
370 responseLength, err = io.Copy(resp, reader)
371 if err == nil && expectLength > -1 && responseLength != expectLength {
372 err = errContentLengthMismatch
375 case keepclient.Error:
376 if respErr == keepclient.BlockNotFound {
377 status = http.StatusNotFound
378 } else if respErr.Temporary() {
379 status = http.StatusBadGateway
384 status = http.StatusInternalServerError
388 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
389 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
391 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
392 if err := h.checkLoop(resp, req); err != nil {
396 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
398 kc := h.makeKeepClient(req)
401 var expectLength int64
402 var status = http.StatusInternalServerError
403 var wroteReplicas int
404 var locatorOut string = "-"
407 httpserver.SetResponseLogFields(req.Context(), logrus.Fields{
408 "expectLength": expectLength,
409 "wantReplicas": kc.Want_replicas,
410 "wroteReplicas": wroteReplicas,
411 "locator": strings.SplitN(locatorOut, "+A", 2)[0],
414 if status != http.StatusOK {
415 http.Error(resp, err.Error(), status)
419 locatorIn := mux.Vars(req)["locator"]
421 // Check if the client specified storage classes
422 if req.Header.Get(keepclient.XKeepStorageClasses) != "" {
424 for _, sc := range strings.Split(req.Header.Get(keepclient.XKeepStorageClasses), ",") {
425 scl = append(scl, strings.Trim(sc, " "))
427 kc.SetStorageClasses(scl)
430 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
431 if err != nil || expectLength < 0 {
432 err = errLengthRequired
433 status = http.StatusLengthRequired
438 var loc *keepclient.Locator
439 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
440 status = http.StatusBadRequest
442 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
443 err = errLengthMismatch
444 status = http.StatusBadRequest
451 var user *arvados.User
452 if pass, tok, user = h.checkAuthorizationHeader(req); !pass {
453 err = errBadAuthorizationHeader
454 status = http.StatusForbidden
457 httpserver.SetResponseLogFields(req.Context(), logrus.Fields{
458 "userUUID": user.UUID,
459 "userFullName": user.FullName,
462 // Copy ArvadosClient struct and use the client's API token
463 arvclient := *kc.Arvados
464 arvclient.ApiToken = tok
465 kc.Arvados = &arvclient
467 // Check if the client specified the number of replicas
468 if desiredReplicas := req.Header.Get(keepclient.XKeepDesiredReplicas); desiredReplicas != "" {
470 _, err := fmt.Sscanf(desiredReplicas, "%d", &r)
476 // Now try to put the block through
478 bytes, err2 := ioutil.ReadAll(req.Body)
480 err = fmt.Errorf("Error reading request body: %s", err2)
481 status = http.StatusInternalServerError
484 locatorOut, wroteReplicas, err = kc.PutB(bytes)
486 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
489 // Tell the client how many successful PUTs we accomplished
490 resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
494 status = http.StatusOK
495 if len(kc.StorageClasses) > 0 {
496 // A successful PUT request with storage classes means that all
497 // storage classes were fulfilled, so the client will get a
498 // confirmation via the X-Storage-Classes-Confirmed header.
501 for _, sc := range kc.StorageClasses {
503 hdr = fmt.Sprintf("%s=%d", sc, wroteReplicas)
506 hdr += fmt.Sprintf(", %s=%d", sc, wroteReplicas)
509 resp.Header().Set(keepclient.XKeepStorageClassesConfirmed, hdr)
511 _, err = io.WriteString(resp, locatorOut)
512 case keepclient.OversizeBlockError:
514 status = http.StatusRequestEntityTooLarge
515 case keepclient.InsufficientReplicasError:
516 status = http.StatusServiceUnavailable
518 status = http.StatusBadGateway
522 // ServeHTTP implementation for IndexHandler
523 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
524 // For each keep server found in LocalRoots:
525 // - Invokes GetIndex using keepclient
526 // - Expects "complete" response (terminating with blank new line)
527 // - Aborts on any errors
528 // Concatenates responses from all those keep servers and returns
529 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
532 prefix := mux.Vars(req)["prefix"]
537 if status != http.StatusOK {
538 http.Error(resp, err.Error(), status)
542 kc := h.makeKeepClient(req)
543 ok, token, _ := h.checkAuthorizationHeader(req)
545 status, err = http.StatusForbidden, errBadAuthorizationHeader
549 // Copy ArvadosClient struct and use the client's API token
550 arvclient := *kc.Arvados
551 arvclient.ApiToken = token
552 kc.Arvados = &arvclient
554 // Only GET method is supported
555 if req.Method != "GET" {
556 status, err = http.StatusNotImplemented, errMethodNotSupported
560 // Get index from all LocalRoots and write to resp
562 for uuid := range kc.LocalRoots() {
563 reader, err = kc.GetIndex(uuid, prefix)
565 status = http.StatusBadGateway
569 _, err = io.Copy(resp, reader)
571 status = http.StatusBadGateway
576 // Got index from all the keep servers and wrote to resp
577 status = http.StatusOK
578 resp.Write([]byte("\n"))
581 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
582 kc := h.KeepClient.Clone()
583 kc.RequestID = req.Header.Get("X-Request-Id")
584 kc.HTTPClient = &proxyClient{
585 client: &http.Client{
587 Transport: h.transport,