13497: Don't propagate connection-oriented headers when proxying.
[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         Node    *arvados.SystemNode
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) setup() {
37         mux := http.NewServeMux()
38         mux.Handle("/_health/", &health.Handler{
39                 Token:  h.Cluster.ManagementToken,
40                 Prefix: "/_health/",
41         })
42         mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
43         h.handlerStack = mux
44 }
45
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{
49         "Connection":          true,
50         "Keep-Alive":          true,
51         "Proxy-Authenticate":  true,
52         "Proxy-Authorization": true,
53         "TE":                true,
54         "Trailer":           true,
55         "Transfer-Encoding": true,
56         "Upgrade":           true,
57 }
58
59 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
60         urlOut, err := findRailsAPI(h.Cluster, h.Node)
61         if err != nil {
62                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
63                 return
64         }
65         urlOut = &url.URL{
66                 Scheme:   urlOut.Scheme,
67                 Host:     urlOut.Host,
68                 Path:     reqIn.URL.Path,
69                 RawPath:  reqIn.URL.RawPath,
70                 RawQuery: reqIn.URL.RawQuery,
71         }
72
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 {
77                 if !dropHeaders[k] {
78                         hdrOut[k] = v
79                 }
80         }
81         xff := reqIn.RemoteAddr
82         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
83                 xff = xffIn + "," + xff
84         }
85         hdrOut.Set("X-Forwarded-For", xff)
86         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
87
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)))
92                 defer cancel()
93         }
94
95         reqOut := (&http.Request{
96                 Method: reqIn.Method,
97                 URL:    urlOut,
98                 Header: hdrOut,
99                 Body:   reqIn.Body,
100         }).WithContext(ctx)
101         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
102         if err != nil {
103                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
104                 return
105         }
106         for k, v := range resp.Header {
107                 for _, v := range v {
108                         w.Header().Add(k, v)
109                 }
110         }
111         w.WriteHeader(resp.StatusCode)
112         n, err := io.Copy(w, resp.Body)
113         if err != nil {
114                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
115         }
116 }
117
118 // For now, findRailsAPI always uses the rails API running on this
119 // node.
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
127         } else {
128                 return nil, err
129         }
130         proto := "http"
131         if node.RailsAPI.TLS {
132                 proto = "https"
133         }
134         return url.Parse(proto + "://" + hostport)
135 }