13497: 13779: Forward Host header, and don't follow redirects.
[arvados.git] / lib / controller / handler.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "context"
9         "io"
10         "net"
11         "net/http"
12         "net/url"
13         "strings"
14         "sync"
15         "time"
16
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"
20 )
21
22 type Handler struct {
23         Cluster     *arvados.Cluster
24         NodeProfile *arvados.NodeProfile
25
26         setupOnce    sync.Once
27         handlerStack http.Handler
28         proxyClient  *arvados.Client
29 }
30
31 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
32         h.setupOnce.Do(h.setup)
33         h.handlerStack.ServeHTTP(w, req)
34 }
35
36 func (h *Handler) CheckHealth() error {
37         h.setupOnce.Do(h.setup)
38         _, err := findRailsAPI(h.Cluster, h.NodeProfile)
39         return err
40 }
41
42 func (h *Handler) setup() {
43         mux := http.NewServeMux()
44         mux.Handle("/_health/", &health.Handler{
45                 Token:  h.Cluster.ManagementToken,
46                 Prefix: "/_health/",
47         })
48         mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
49         h.handlerStack = mux
50
51         // Changing the global isn't the right way to do this, but a
52         // proper solution would conflict with an impending 13493
53         // merge anyway, so this will do for now.
54         arvados.InsecureHTTPClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
55 }
56
57 // headers that shouldn't be forwarded when proxying. See
58 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
59 var dropHeaders = map[string]bool{
60         "Connection":          true,
61         "Keep-Alive":          true,
62         "Proxy-Authenticate":  true,
63         "Proxy-Authorization": true,
64         "TE":                true,
65         "Trailer":           true,
66         "Transfer-Encoding": true,
67         "Upgrade":           true,
68 }
69
70 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
71         urlOut, err := findRailsAPI(h.Cluster, h.NodeProfile)
72         if err != nil {
73                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
74                 return
75         }
76         urlOut = &url.URL{
77                 Scheme:   urlOut.Scheme,
78                 Host:     urlOut.Host,
79                 Path:     reqIn.URL.Path,
80                 RawPath:  reqIn.URL.RawPath,
81                 RawQuery: reqIn.URL.RawQuery,
82         }
83
84         // Copy headers from incoming request, then add/replace proxy
85         // headers like Via and X-Forwarded-For.
86         hdrOut := http.Header{}
87         for k, v := range reqIn.Header {
88                 if !dropHeaders[k] {
89                         hdrOut[k] = v
90                 }
91         }
92         xff := reqIn.RemoteAddr
93         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
94                 xff = xffIn + "," + xff
95         }
96         hdrOut.Set("X-Forwarded-For", xff)
97         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
98
99         ctx := reqIn.Context()
100         if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
101                 var cancel context.CancelFunc
102                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
103                 defer cancel()
104         }
105
106         reqOut := (&http.Request{
107                 Method: reqIn.Method,
108                 URL:    urlOut,
109                 Host:   reqIn.Host,
110                 Header: hdrOut,
111                 Body:   reqIn.Body,
112         }).WithContext(ctx)
113         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
114         if err != nil {
115                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
116                 return
117         }
118         for k, v := range resp.Header {
119                 for _, v := range v {
120                         w.Header().Add(k, v)
121                 }
122         }
123         w.WriteHeader(resp.StatusCode)
124         n, err := io.Copy(w, resp.Body)
125         if err != nil {
126                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
127         }
128 }
129
130 // For now, findRailsAPI always uses the rails API running on this
131 // node.
132 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, error) {
133         hostport := np.RailsAPI.Listen
134         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
135                 // ":12345" => connect to indicated port on localhost
136                 hostport = "localhost" + hostport
137         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
138                 // "[::1]:12345" => connect to indicated address & port
139         } else {
140                 return nil, err
141         }
142         proto := "http"
143         if np.RailsAPI.TLS {
144                 proto = "https"
145         }
146         return url.Parse(proto + "://" + hostport)
147 }