-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathhttp.go
227 lines (198 loc) · 6.01 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
221
222
223
224
225
226
227
package internal
import (
"crypto/subtle"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type BasicAuthErrorFunc func(rw http.ResponseWriter)
// JWTAuthHandler returns a http handler that requires the HTTP bearer auth
// token to be valid and match the given user.
func JWTAuthHandler(secret, username string, onError BasicAuthErrorFunc) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return &jwtAuthHandler{
secret: []byte(secret),
username: []byte(username),
onError: onError,
next: h,
}
}
}
type jwtAuthHandler struct {
secret []byte
username []byte
onError BasicAuthErrorFunc
next http.Handler
}
func (h *jwtAuthHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
authHeader := req.Header.Get("Authentication")
if !strings.HasPrefix(authHeader, "Bearer ") {
h.onError(rw)
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
bearer := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(bearer, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Method)
}
return h.secret, nil
})
if err != nil || !token.Valid {
h.onError(rw)
if err != nil && errors.Is(err, jwt.ErrTokenExpired) {
http.Error(rw, "token expired", http.StatusUnauthorized)
} else if err != nil {
http.Error(rw, "invalid token: "+err.Error(), http.StatusUnauthorized)
} else {
http.Error(rw, "invalid token", http.StatusUnauthorized)
}
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
h.onError(rw)
http.Error(rw, "problem authenticating token", http.StatusInternalServerError)
return
}
username, ok := claims["username"].(string)
if !ok || username == "" {
h.onError(rw)
http.Error(rw, "token must contain a string username", http.StatusUnauthorized)
return
}
if subtle.ConstantTimeCompare([]byte(username), h.username) != 1 {
h.onError(rw)
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
h.next.ServeHTTP(rw, req)
}
// BasicAuthHandler returns a http handler that requires HTTP basic auth
// credentials to match the given username and password.
func BasicAuthHandler(username, password, realm string, onError BasicAuthErrorFunc) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return &basicAuthHandler{
username: username,
password: password,
realm: realm,
onError: onError,
next: h,
}
}
}
type basicAuthHandler struct {
username string
password string
realm string
onError BasicAuthErrorFunc
next http.Handler
}
func (h *basicAuthHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if h.username == "" && h.password == "" {
h.next.ServeHTTP(rw, req)
return
}
var reqUsername, reqPassword string
var ok bool
authHeader := req.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Token ") {
token := strings.TrimPrefix(authHeader, "Token ")
reqUsername, reqPassword, ok = strings.Cut(token, ":")
} else {
reqUsername, reqPassword, ok = req.BasicAuth()
}
if !ok ||
subtle.ConstantTimeCompare([]byte(reqUsername), []byte(h.username)) != 1 ||
subtle.ConstantTimeCompare([]byte(reqPassword), []byte(h.password)) != 1 {
rw.Header().Set("WWW-Authenticate", "Basic realm=\""+h.realm+"\"")
h.onError(rw)
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
h.next.ServeHTTP(rw, req)
}
type GenericAuthErrorFunc func(rw http.ResponseWriter)
// GenericAuthHandler returns a http handler that requires `Authorization: <credentials>`
func GenericAuthHandler(credentials string, onError GenericAuthErrorFunc) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return &genericAuthHandler{
credentials: credentials,
onError: onError,
next: h,
}
}
}
// Generic auth scheme handler - exact match on `Authorization: <credentials>`
type genericAuthHandler struct {
credentials string
onError GenericAuthErrorFunc
next http.Handler
}
func (h *genericAuthHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if h.credentials != "" {
// Scheme checking
authorization := req.Header.Get("Authorization")
if subtle.ConstantTimeCompare([]byte(authorization), []byte(h.credentials)) != 1 {
h.onError(rw)
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
}
h.next.ServeHTTP(rw, req)
}
// ErrorFunc is a callback for writing an error response.
type ErrorFunc func(rw http.ResponseWriter, code int)
// IPRangeHandler returns a http handler that requires the remote address to be
// in the specified network.
func IPRangeHandler(networks []*net.IPNet, onError ErrorFunc) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return &ipRangeHandler{
networks: networks,
onError: onError,
next: h,
}
}
}
type ipRangeHandler struct {
networks []*net.IPNet
onError ErrorFunc
next http.Handler
}
func (h *ipRangeHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if len(h.networks) == 0 {
h.next.ServeHTTP(rw, req)
return
}
remoteIPString, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
h.onError(rw, http.StatusForbidden)
return
}
remoteIP := net.ParseIP(remoteIPString)
if remoteIP == nil {
h.onError(rw, http.StatusForbidden)
return
}
for _, network := range h.networks {
if network.Contains(remoteIP) {
h.next.ServeHTTP(rw, req)
return
}
}
h.onError(rw, http.StatusForbidden)
}
func OnClientError(client *http.Client, err error) {
// Close connection after a timeout error. If this is a HTTP2
// connection this ensures that next interval a new connection will be
// used and name lookup will be performed.
// https://github.com/golang/go/issues/36026
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr.Timeout() {
client.CloseIdleConnections()
}
}