1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "git.curoverse.com/arvados.git/sdk/go/health"
19 "git.curoverse.com/arvados.git/sdk/go/httpserver"
23 Cluster *arvados.Cluster
24 Node *arvados.SystemNode
27 handlerStack http.Handler
28 proxyClient *arvados.Client
31 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
32 h.setupOnce.Do(h.setup)
33 h.handlerStack.ServeHTTP(w, req)
36 func (h *Handler) setup() {
37 mux := http.NewServeMux()
38 mux.Handle("/_health/", &health.Handler{
39 Token: h.Cluster.ManagementToken,
42 mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
46 // headers that shouldn't be forwarded when proxying. See
47 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
48 var dropHeaders = map[string]bool{
51 "Proxy-Authenticate": true,
52 "Proxy-Authorization": true,
55 "Transfer-Encoding": true,
59 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
60 urlOut, err := findRailsAPI(h.Cluster, h.Node)
62 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
66 Scheme: urlOut.Scheme,
69 RawPath: reqIn.URL.RawPath,
70 RawQuery: reqIn.URL.RawQuery,
73 // Copy headers from incoming request, then add/replace proxy
74 // headers like Via and X-Forwarded-For.
75 hdrOut := http.Header{}
76 for k, v := range reqIn.Header {
81 xff := reqIn.RemoteAddr
82 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
83 xff = xffIn + "," + xff
85 hdrOut.Set("X-Forwarded-For", xff)
86 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
88 ctx := reqIn.Context()
89 if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
90 var cancel context.CancelFunc
91 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
95 reqOut := (&http.Request{
101 resp, err := arvados.InsecureHTTPClient.Do(reqOut)
103 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
106 for k, v := range resp.Header {
107 for _, v := range v {
111 w.WriteHeader(resp.StatusCode)
112 n, err := io.Copy(w, resp.Body)
114 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
118 // For now, findRailsAPI always uses the rails API running on this
120 func findRailsAPI(cluster *arvados.Cluster, node *arvados.SystemNode) (*url.URL, error) {
121 hostport := node.RailsAPI.Listen
122 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
123 // ":12345" => connect to indicated port on localhost
124 hostport = "localhost" + hostport
125 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
126 // "[::1]:12345" => connect to indicated address & port
131 if node.RailsAPI.TLS {
134 return url.Parse(proto + "://" + hostport)