forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse_proxy.go
175 lines (146 loc) · 4.69 KB
/
reverse_proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package proxyutil
import (
"context"
"errors"
"log"
"net/http"
"net/http/httputil"
"strings"
"time"
glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/middleware/requestmeta"
"github.com/grafana/grafana/pkg/services/contexthandler"
)
// StatusClientClosedRequest A non-standard status code introduced by nginx
// for the case when a client closes the connection while nginx is processing
// the request.
// https://httpstatus.in/499/
const StatusClientClosedRequest = 499
// ReverseProxyOption reverse proxy option to configure a httputil.ReverseProxy.
type ReverseProxyOption func(*httputil.ReverseProxy)
// NewReverseProxy creates a new httputil.ReverseProxy with sane default configuration.
func NewReverseProxy(logger glog.Logger, director func(*http.Request), opts ...ReverseProxyOption) *httputil.ReverseProxy {
if logger == nil {
panic("logger cannot be nil")
}
if director == nil {
panic("director cannot be nil")
}
p := &httputil.ReverseProxy{
FlushInterval: time.Millisecond * 200,
ErrorHandler: errorHandler(logger),
ErrorLog: log.New(&logWrapper{logger: logger}, "", 0),
Director: director,
}
for _, opt := range opts {
opt(p)
}
origDirector := p.Director
p.Director = wrapDirector(origDirector)
if p.ModifyResponse == nil {
// nolint:bodyclose
p.ModifyResponse = modifyResponse(logger)
} else {
modResponse := p.ModifyResponse
p.ModifyResponse = func(resp *http.Response) error {
if err := modResponse(resp); err != nil {
return err
}
// nolint:bodyclose
return modifyResponse(logger)(resp)
}
}
return p
}
// wrapDirector wraps a director and adds additional functionality.
func wrapDirector(d func(*http.Request)) func(req *http.Request) {
return func(req *http.Request) {
list := contexthandler.AuthHTTPHeaderListFromContext(req.Context())
if list != nil {
for _, name := range list.Items {
req.Header.Del(name)
}
}
d(req)
PrepareProxyRequest(req)
}
}
// deletedHeaders lists a number of headers that we don't want to
// pass-through from the upstream when using a reverse proxy.
//
// These are related to the connection between Grafana and the proxy
// or instructions that would alter how a browser will interact with
// future requests to Grafana (such as enabling Strict Transport
// Security)
var deletedHeaders = []string{
"Alt-Svc",
"Close",
"Server",
"Set-Cookie",
"Strict-Transport-Security",
}
// modifyResponse enforces certain constraints on http.Response.
func modifyResponse(logger glog.Logger) func(resp *http.Response) error {
return func(resp *http.Response) error {
for _, header := range deletedHeaders {
resp.Header.Del(header)
}
SetProxyResponseHeaders(resp.Header)
SetViaHeader(resp.Header, resp.ProtoMajor, resp.ProtoMinor)
requestmeta.WithStatusSource(resp.Request.Context(), resp.StatusCode)
return nil
}
}
type timeoutError interface {
error
Timeout() bool
}
// errorHandler handles any errors happening while proxying a request and enforces
// certain HTTP status based on the kind of error.
// If client cancel/close the request we return 499 StatusClientClosedRequest.
// If timeout happens while communicating with upstream server we return http.StatusGatewayTimeout.
// If any other error we return http.StatusBadGateway.
func errorHandler(logger glog.Logger) func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, r *http.Request, err error) {
ctxLogger := logger.FromContext(r.Context())
requestmeta.WithDownstreamStatusSource(r.Context())
if errors.Is(err, context.Canceled) {
ctxLogger.Debug("Proxy request cancelled by client")
w.WriteHeader(StatusClientClosedRequest)
return
}
// nolint:errorlint
if timeoutErr, ok := err.(timeoutError); ok && timeoutErr.Timeout() {
ctxLogger.Error("Proxy request timed out", "err", err)
w.WriteHeader(http.StatusGatewayTimeout)
return
}
ctxLogger.Error("Proxy request failed", "err", err)
w.WriteHeader(http.StatusBadGateway)
}
}
type logWrapper struct {
logger glog.Logger
}
// Write writes log messages as bytes from proxy.
func (lw *logWrapper) Write(p []byte) (n int, err error) {
withoutNewline := strings.TrimSuffix(string(p), "\n")
lw.logger.Error("Proxy request error", "error", withoutNewline)
return len(p), nil
}
func WithTransport(transport http.RoundTripper) ReverseProxyOption {
if transport == nil {
panic("transport cannot be nil")
}
return ReverseProxyOption(func(rp *httputil.ReverseProxy) {
rp.Transport = transport
})
}
func WithModifyResponse(fn func(*http.Response) error) ReverseProxyOption {
if fn == nil {
panic("fn cannot be nil")
}
return ReverseProxyOption(func(rp *httputil.ReverseProxy) {
rp.ModifyResponse = fn
})
}