1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/cmd"
23 "git.arvados.org/arvados.git/lib/config"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26 "git.arvados.org/arvados.git/sdk/go/health"
27 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 "git.arvados.org/arvados.git/sdk/go/keepclient"
29 "github.com/coreos/go-systemd/daemon"
30 "github.com/ghodss/yaml"
31 "github.com/gorilla/mux"
32 lru "github.com/hashicorp/golang-lru"
33 log "github.com/sirupsen/logrus"
43 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
45 func configure(logger log.FieldLogger, args []string) (*arvados.Cluster, error) {
47 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
49 dumpConfig := flags.Bool("dump-config", false, "write current configuration to stdout and exit")
50 getVersion := flags.Bool("version", false, "Print version information and exit.")
52 loader := config.NewLoader(os.Stdin, logger)
53 loader.SetupFlags(flags)
54 args = loader.MungeLegacyConfigArgs(logger, args[1:], "-legacy-keepproxy-config")
56 if ok, code := cmd.ParseFlags(flags, prog, args, "", os.Stderr); !ok {
58 } else if *getVersion {
59 fmt.Printf("keepproxy %s\n", version)
63 cfg, err := loader.Load()
67 cluster, err := cfg.GetCluster("")
73 out, err := yaml.Marshal(cfg)
77 if _, err := os.Stdout.Write(out); err != nil {
87 logger.Formatter = &log.JSONFormatter{
88 TimestampFormat: rfc3339NanoFixed,
91 cluster, err := configure(logger, os.Args)
99 log.Printf("keepproxy %s started", version)
101 if err := run(logger, cluster); err != nil {
105 log.Println("shutting down")
108 func run(logger log.FieldLogger, cluster *arvados.Cluster) error {
109 client, err := arvados.NewClientFromConfig(cluster)
113 client.AuthToken = cluster.SystemRootToken
115 arv, err := arvadosclient.New(client)
117 return fmt.Errorf("Error setting up arvados client %v", err)
120 // If a config file is available, use the keepstores defined there
121 // instead of the legacy autodiscover mechanism via the API server
122 for k := range cluster.Services.Keepstore.InternalURLs {
123 arv.KeepServiceURIs = append(arv.KeepServiceURIs, strings.TrimRight(k.String(), "/"))
126 if cluster.SystemLogs.LogLevel == "debug" {
127 keepclient.DebugPrintf = log.Printf
129 kc, err := keepclient.MakeKeepClient(arv)
131 return fmt.Errorf("Error setting up keep client %v", err)
133 keepclient.RefreshServiceDiscoveryOnSIGHUP()
135 if cluster.Collections.DefaultReplication > 0 {
136 kc.Want_replicas = cluster.Collections.DefaultReplication
139 var listen arvados.URL
140 for listen = range cluster.Services.Keepproxy.InternalURLs {
145 listener, lErr = net.Listen("tcp", listen.Host)
147 return fmt.Errorf("listen(%s): %v", listen.Host, lErr)
150 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
151 log.Printf("Error notifying init daemon: %v", err)
153 log.Println("listening at", listener.Addr())
155 // Shut down the server gracefully (by closing the listener)
156 // if SIGTERM is received.
157 term := make(chan os.Signal, 1)
158 go func(sig <-chan os.Signal) {
160 log.Println("caught signal:", s)
163 signal.Notify(term, syscall.SIGTERM)
164 signal.Notify(term, syscall.SIGINT)
166 // Start serving requests.
167 router, err = MakeRESTRouter(kc, time.Duration(keepclient.DefaultProxyRequestTimeout), cluster, logger)
171 return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
174 type TokenCacheEntry struct {
179 type APITokenCache struct {
180 tokens *lru.TwoQueueCache
184 // RememberToken caches the token and set an expire time. If the
185 // token is already in the cache, it is not updated.
186 func (cache *APITokenCache) RememberToken(token string, user *arvados.User) {
187 now := time.Now().Unix()
188 _, ok := cache.tokens.Get(token)
190 cache.tokens.Add(token, TokenCacheEntry{
191 expire: now + cache.expireTime,
197 // RecallToken checks if the cached token is known and still believed to be
199 func (cache *APITokenCache) RecallToken(token string) (bool, *arvados.User) {
200 val, ok := cache.tokens.Get(token)
205 cacheEntry := val.(TokenCacheEntry)
206 now := time.Now().Unix()
207 if now < cacheEntry.expire {
208 // Token is known and still valid
209 return true, cacheEntry.user
212 cache.tokens.Remove(token)
217 // GetRemoteAddress returns a string with the remote address for the request.
218 // If the X-Forwarded-For header is set and has a non-zero length, it returns a
219 // string made from a comma separated list of all the remote addresses,
220 // starting with the one(s) from the X-Forwarded-For header.
221 func GetRemoteAddress(req *http.Request) string {
222 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
223 return xff + "," + req.RemoteAddr
225 return req.RemoteAddr
228 func (h *proxyHandler) CheckAuthorizationHeader(req *http.Request) (pass bool, tok string, user *arvados.User) {
229 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
230 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
231 return false, "", nil
235 // Tokens are validated differently depending on what kind of
236 // operation is being performed. For example, tokens in
237 // collection-sharing links permit GET requests, but not
240 if req.Method == "GET" || req.Method == "HEAD" {
246 if ok, user := h.APITokenCache.RecallToken(op + ":" + tok); ok {
247 // Valid in the cache, short circuit
248 return true, tok, user
252 arv := *h.KeepClient.Arvados
254 arv.RequestID = req.Header.Get("X-Request-Id")
255 user = &arvados.User{}
256 userCurrentError := arv.Call("GET", "users", "", "current", nil, user)
257 err = userCurrentError
258 if err != nil && op == "read" {
259 apiError, ok := err.(arvadosclient.APIServerError)
260 if ok && apiError.HttpStatusCode == http.StatusForbidden {
261 // If it was a scoped "sharing" token it will
262 // return 403 instead of 401 for the current
263 // user check. If it is a download operation
264 // and they have permission to read the
265 // keep_services table, we can allow it.
266 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
270 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
271 return false, "", nil
274 if userCurrentError == nil && user.IsAdmin {
275 // checking userCurrentError is probably redundant,
276 // IsAdmin would be false anyway. But can't hurt.
277 if op == "read" && !h.cluster.Collections.KeepproxyPermission.Admin.Download {
278 return false, "", nil
280 if op == "write" && !h.cluster.Collections.KeepproxyPermission.Admin.Upload {
281 return false, "", nil
284 if op == "read" && !h.cluster.Collections.KeepproxyPermission.User.Download {
285 return false, "", nil
287 if op == "write" && !h.cluster.Collections.KeepproxyPermission.User.Upload {
288 return false, "", nil
292 // Success! Update cache
293 h.APITokenCache.RememberToken(op+":"+tok, user)
295 return true, tok, user
298 // We need to make a private copy of the default http transport early
299 // in initialization, then make copies of our private copy later. It
300 // won't be safe to copy http.DefaultTransport itself later, because
301 // its private mutexes might have already been used. (Without this,
302 // the test suite sometimes panics "concurrent map writes" in
303 // net/http.(*Transport).removeIdleConnLocked().)
304 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
306 type proxyHandler struct {
308 *keepclient.KeepClient
310 timeout time.Duration
311 transport *http.Transport
312 logger log.FieldLogger
313 cluster *arvados.Cluster
316 // MakeRESTRouter returns an http.Handler that passes GET and PUT
317 // requests to the appropriate handlers.
318 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, cluster *arvados.Cluster, logger log.FieldLogger) (http.Handler, error) {
319 rest := mux.NewRouter()
321 transport := defaultTransport
322 transport.DialContext = (&net.Dialer{
323 Timeout: keepclient.DefaultConnectTimeout,
324 KeepAlive: keepclient.DefaultKeepAlive,
327 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
328 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
330 cacheQ, err := lru.New2Q(500)
332 return nil, fmt.Errorf("Error from lru.New2Q: %v", err)
339 transport: &transport,
340 APITokenCache: &APITokenCache{
348 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
349 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
352 rest.HandleFunc(`/index`, h.Index).Methods("GET")
354 // List blocks whose hash has the given prefix
355 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
357 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
358 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
359 rest.HandleFunc(`/`, h.Put).Methods("POST")
360 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
361 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
363 rest.Handle("/_health/{check}", &health.Handler{
364 Token: cluster.ManagementToken,
368 rest.NotFoundHandler = InvalidPathHandler{}
372 var errLoopDetected = errors.New("loop detected")
374 func (h *proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
375 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
376 h.logger.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)
377 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
378 return errLoopDetected
383 func SetCorsHeaders(resp http.ResponseWriter) {
384 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
385 resp.Header().Set("Access-Control-Allow-Origin", "*")
386 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
387 resp.Header().Set("Access-Control-Max-Age", "86486400")
390 type InvalidPathHandler struct{}
392 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
393 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
394 http.Error(resp, "Bad request", http.StatusBadRequest)
397 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
398 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
402 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header, or method not allowed")
403 var errContentLengthMismatch = errors.New("Actual length != expected content length")
404 var errMethodNotSupported = errors.New("Method not supported")
406 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
408 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
409 if err := h.checkLoop(resp, req); err != nil {
413 resp.Header().Set("Via", req.Proto+" "+viaAlias)
415 locator := mux.Vars(req)["locator"]
418 var expectLength, responseLength int64
422 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
423 if status != http.StatusOK {
424 http.Error(resp, err.Error(), status)
428 kc := h.makeKeepClient(req)
432 var user *arvados.User
433 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
434 status, err = http.StatusForbidden, errBadAuthorizationHeader
438 // Copy ArvadosClient struct and use the client's API token
439 arvclient := *kc.Arvados
440 arvclient.ApiToken = tok
441 kc.Arvados = &arvclient
443 var reader io.ReadCloser
445 locator = removeHint.ReplaceAllString(locator, "$1")
448 parts := strings.SplitN(locator, "+", 3)
452 logger = logger.WithField("user_uuid", user.UUID).
453 WithField("user_full_name", user.FullName)
455 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block download")
461 expectLength, proxiedURI, err = kc.Ask(locator)
463 reader, expectLength, proxiedURI, err = kc.Get(locator)
468 status, err = http.StatusNotImplemented, errMethodNotSupported
472 if expectLength == -1 {
473 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
476 switch respErr := err.(type) {
478 status = http.StatusOK
479 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
484 responseLength, err = io.Copy(resp, reader)
485 if err == nil && expectLength > -1 && responseLength != expectLength {
486 err = errContentLengthMismatch
489 case keepclient.Error:
490 if respErr == keepclient.BlockNotFound {
491 status = http.StatusNotFound
492 } else if respErr.Temporary() {
493 status = http.StatusBadGateway
498 status = http.StatusInternalServerError
502 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
503 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
505 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
506 if err := h.checkLoop(resp, req); err != nil {
510 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
512 kc := h.makeKeepClient(req)
515 var expectLength int64
516 var status = http.StatusInternalServerError
517 var wroteReplicas int
518 var locatorOut string = "-"
521 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
522 if status != http.StatusOK {
523 http.Error(resp, err.Error(), status)
527 locatorIn := mux.Vars(req)["locator"]
529 // Check if the client specified storage classes
530 if req.Header.Get("X-Keep-Storage-Classes") != "" {
532 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
533 scl = append(scl, strings.Trim(sc, " "))
535 kc.SetStorageClasses(scl)
538 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
539 if err != nil || expectLength < 0 {
540 err = errLengthRequired
541 status = http.StatusLengthRequired
546 var loc *keepclient.Locator
547 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
548 status = http.StatusBadRequest
550 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
551 err = errLengthMismatch
552 status = http.StatusBadRequest
559 var user *arvados.User
560 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
561 err = errBadAuthorizationHeader
562 status = http.StatusForbidden
566 // Copy ArvadosClient struct and use the client's API token
567 arvclient := *kc.Arvados
568 arvclient.ApiToken = tok
569 kc.Arvados = &arvclient
571 // Check if the client specified the number of replicas
572 if desiredReplicas := req.Header.Get(keepclient.XKeepDesiredReplicas); desiredReplicas != "" {
574 _, err := fmt.Sscanf(desiredReplicas, "%d", &r)
580 // Now try to put the block through
582 bytes, err2 := ioutil.ReadAll(req.Body)
584 err = fmt.Errorf("Error reading request body: %s", err2)
585 status = http.StatusInternalServerError
588 locatorOut, wroteReplicas, err = kc.PutB(bytes)
590 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
593 if locatorOut != "" {
594 parts := strings.SplitN(locatorOut, "+", 3)
598 logger = logger.WithField("user_uuid", user.UUID).
599 WithField("user_full_name", user.FullName)
601 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block upload")
605 // Tell the client how many successful PUTs we accomplished
606 resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
610 status = http.StatusOK
611 if len(kc.StorageClasses) > 0 {
612 // A successful PUT request with storage classes means that all
613 // storage classes were fulfilled, so the client will get a
614 // confirmation via the X-Storage-Classes-Confirmed header.
617 for _, sc := range kc.StorageClasses {
619 hdr = fmt.Sprintf("%s=%d", sc, wroteReplicas)
622 hdr += fmt.Sprintf(", %s=%d", sc, wroteReplicas)
625 resp.Header().Set(keepclient.XKeepStorageClassesConfirmed, hdr)
627 _, err = io.WriteString(resp, locatorOut)
628 case keepclient.OversizeBlockError:
630 status = http.StatusRequestEntityTooLarge
631 case keepclient.InsufficientReplicasError:
632 status = http.StatusServiceUnavailable
634 status = http.StatusBadGateway
638 // ServeHTTP implementation for IndexHandler
639 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
640 // For each keep server found in LocalRoots:
641 // Invokes GetIndex using keepclient
642 // Expects "complete" response (terminating with blank new line)
643 // Aborts on any errors
644 // Concatenates responses from all those keep servers and returns
645 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
648 prefix := mux.Vars(req)["prefix"]
653 if status != http.StatusOK {
654 http.Error(resp, err.Error(), status)
658 kc := h.makeKeepClient(req)
659 ok, token, _ := h.CheckAuthorizationHeader(req)
661 status, err = http.StatusForbidden, errBadAuthorizationHeader
665 // Copy ArvadosClient struct and use the client's API token
666 arvclient := *kc.Arvados
667 arvclient.ApiToken = token
668 kc.Arvados = &arvclient
670 // Only GET method is supported
671 if req.Method != "GET" {
672 status, err = http.StatusNotImplemented, errMethodNotSupported
676 // Get index from all LocalRoots and write to resp
678 for uuid := range kc.LocalRoots() {
679 reader, err = kc.GetIndex(uuid, prefix)
681 status = http.StatusBadGateway
685 _, err = io.Copy(resp, reader)
687 status = http.StatusBadGateway
692 // Got index from all the keep servers and wrote to resp
693 status = http.StatusOK
694 resp.Write([]byte("\n"))
697 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
699 kc.RequestID = req.Header.Get("X-Request-Id")
700 kc.HTTPClient = &proxyClient{
701 client: &http.Client{
703 Transport: h.transport,