13497: Fix Rails redirect targets.
[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         if hdrOut.Get("X-Forwarded-Proto") == "" {
98                 hdrOut.Set("X-Forwarded-Proto", reqIn.URL.Scheme)
99         }
100         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
101
102         ctx := reqIn.Context()
103         if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
104                 var cancel context.CancelFunc
105                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
106                 defer cancel()
107         }
108
109         reqOut := (&http.Request{
110                 Method: reqIn.Method,
111                 URL:    urlOut,
112                 Host:   reqIn.Host,
113                 Header: hdrOut,
114                 Body:   reqIn.Body,
115         }).WithContext(ctx)
116         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
117         if err != nil {
118                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
119                 return
120         }
121         for k, v := range resp.Header {
122                 for _, v := range v {
123                         w.Header().Add(k, v)
124                 }
125         }
126         w.WriteHeader(resp.StatusCode)
127         n, err := io.Copy(w, resp.Body)
128         if err != nil {
129                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
130         }
131 }
132
133 // For now, findRailsAPI always uses the rails API running on this
134 // node.
135 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, error) {
136         hostport := np.RailsAPI.Listen
137         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
138                 // ":12345" => connect to indicated port on localhost
139                 hostport = "localhost" + hostport
140         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
141                 // "[::1]:12345" => connect to indicated address & port
142         } else {
143                 return nil, err
144         }
145         proto := "http"
146         if np.RailsAPI.TLS {
147                 proto = "https"
148         }
149         return url.Parse(proto + "://" + hostport)
150 }