-
Notifications
You must be signed in to change notification settings - Fork 55
/
http.go
220 lines (191 loc) · 5.96 KB
/
http.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Copyright 2016 Qubit Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
log "github.com/sirupsen/logrus"
)
const (
// VerificationErrorMsg to send in response body when verification of proxied server
// response is failed
VerificationErrorMsg = "Internal Server Error: " +
"Response from proxied server failed verification. " +
"See server logs for details"
)
// VerifyError is an error type that supports reporting verification errors
type VerifyError struct {
msg string
cause error
}
func (e *VerifyError) Error() string { return e.msg + ": " + e.cause.Error() }
func (e *VerifyError) Unwrap() error { return e.cause }
func (cfg moduleConfig) getReverseProxyDirectorFunc() (func(*http.Request), error) {
base, err := url.Parse(cfg.HTTP.Path)
if err != nil {
return nil, fmt.Errorf("http configuration path should be a valid URL path with options, %w", err)
}
cvs := base.Query()
return func(r *http.Request) {
qvs := r.URL.Query()
for k, vs := range cvs {
for _, v := range vs {
qvs.Add(k, v)
}
}
qvs["module"] = qvs["module"][1:]
r.URL.RawQuery = qvs.Encode()
for k, v := range cfg.HTTP.Headers {
r.Header.Add(k, v)
}
r.URL.Scheme = cfg.HTTP.Scheme
r.URL.Host = net.JoinHostPort(cfg.HTTP.Address, strconv.Itoa(cfg.HTTP.Port))
if _, ok := cfg.HTTP.Headers["host"]; ok {
r.Host = cfg.HTTP.Headers["host"]
}
r.URL.Path = base.Path
if cfg.HTTP.BasicAuthUsername != "" && cfg.HTTP.BasicAuthPassword != "" {
r.SetBasicAuth(cfg.HTTP.BasicAuthUsername, cfg.HTTP.BasicAuthPassword)
}
}, nil
}
func (cfg moduleConfig) getReverseProxyModifyResponseFunc() func(*http.Response) error {
return func(resp *http.Response) error {
if resp.StatusCode != 200 {
return nil
}
var (
err error
body bytes.Buffer
oldBody = resp.Body
)
defer oldBody.Close()
if _, err = body.ReadFrom(oldBody); err != nil {
return &VerifyError{"Failed to read body from proxied server", err}
}
resp.Body = io.NopCloser(bytes.NewReader(body.Bytes()))
var bodyReader io.ReadCloser
if resp.Header.Get("Content-Encoding") == "gzip" {
bodyReader, err = gzip.NewReader(bytes.NewReader(body.Bytes()))
if err != nil {
return &VerifyError{"Failed to decode gzipped response", err}
}
} else {
bodyReader = io.NopCloser(bytes.NewReader(body.Bytes()))
}
defer bodyReader.Close()
dec := expfmt.NewDecoder(bodyReader, expfmt.ResponseFormat(resp.Header))
for {
mf := dto.MetricFamily{}
err := dec.Decode(&mf)
if err == io.EOF {
break
}
if err != nil {
proxyMalformedCount.WithLabelValues(cfg.name).Inc()
return &VerifyError{"Failed to decode metrics from proxied server", err}
}
}
return nil
}
}
func (cfg moduleConfig) getReverseProxyErrorHandlerFunc() func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, _ *http.Request, err error) {
var verifyError *VerifyError
if errors.As(err, &verifyError) {
log.Errorf("Verification for module '%s' failed: %v", cfg.name, err)
http.Error(w, VerificationErrorMsg, http.StatusInternalServerError)
return
}
if errors.Is(err, context.DeadlineExceeded) {
log.Errorf("Request time out for module '%s'", cfg.name)
http.Error(w, http.StatusText(http.StatusGatewayTimeout), http.StatusGatewayTimeout)
return
}
log.Errorf("Proxy error for module '%s': %v", cfg.name, err)
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
}
}
// BearerAuthMiddleware checks an Authorization: Berarer header for a known
// token
type BearerAuthMiddleware struct {
http.Handler
Token string
}
func (b BearerAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Authorization header is missing"))
return
}
ss := strings.SplitN(authHeader, " ", 2)
if !(len(ss) == 2 && ss[0] == "Bearer") {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Authorization header not of Bearer type"))
return
}
if ss[1] != b.Token {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Invalid Bearer Token"))
return
}
b.Handler.ServeHTTP(w, r)
}
// IPAddressAuthMiddleware matches all incoming requests to a known
// set of remote net.IPNet networks
type IPAddressAuthMiddleware struct {
http.Handler
ACL []net.IPNet
}
func (m IPAddressAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Errorf("Failed to parse host form remote address '%s'", r.RemoteAddr)
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Failed to determine client IP address"))
return
}
addr := net.ParseIP(host)
if addr == nil {
log.Errorf(
"Failed to determine client IP address from '%s' (originally '%s')",
host, r.RemoteAddr,
)
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Failed to determine client IP address"))
return
}
for _, network := range m.ACL {
// client is in access list
if network.Contains(addr) {
m.Handler.ServeHTTP(w, r)
return
}
}
// client is not in access list
log.Infof("Access forbidden for %q", addr)
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("Forbidden"))
}