forked from QubitProducts/exporter_exporter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
146 lines (127 loc) · 3.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
// 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 (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
)
const (
// Msg 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"
)
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))
r.URL.Path = base.Path
if cfg.HTTP.BasicAuthUsername != "" && cfg.HTTP.BasicAuthPassword != "" {
r.SetBasicAuth(cfg.HTTP.BasicAuthUsername, cfg.HTTP.BasicAuthPassword)
}
}, nil
}
func (cfg moduleConfig) getReverseProxyErrorHandlerFunc() func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, _ *http.Request, err error) {
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.
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)
}
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"))
}