-
Notifications
You must be signed in to change notification settings - Fork 16
/
middleware.go
384 lines (326 loc) · 11.8 KB
/
middleware.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package middleware
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/cors"
"github.com/stellar/go/support/http/mutil"
"github.com/stellar/go/support/log"
"github.com/stellar/stellar-disbursement-platform-backend/internal/data"
"github.com/stellar/stellar-disbursement-platform-backend/internal/monitor"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httperror"
"github.com/stellar/stellar-disbursement-platform-backend/internal/utils"
"github.com/stellar/stellar-disbursement-platform-backend/stellar-auth/pkg/auth"
"github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant"
)
type ContextKey string
const (
TokenContextKey ContextKey = "auth_token"
TenantHeaderKey string = "SDP-Tenant-Name"
)
// RecoverHandler is a middleware that recovers from panics and logs the error.
func RecoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
defer func() {
r := recover()
if r == nil {
return
}
err, ok := r.(error)
if !ok {
err = fmt.Errorf("panic: %v", r)
}
// No need to recover when the client has disconnected:
if errors.Is(err, http.ErrAbortHandler) {
panic(err)
}
ctx := req.Context()
log.Ctx(ctx).WithStack(err).Error(err)
httperror.InternalError(ctx, "", err, nil).Render(rw)
}()
next.ServeHTTP(rw, req)
})
}
// MetricsRequestHandler is a middleware that monitors http requests, and export the data
// to the metrics server
func MetricsRequestHandler(monitorService monitor.MonitorServiceInterface) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
mw := middleware.NewWrapResponseWriter(rw, req.ProtoMajor)
then := time.Now()
next.ServeHTTP(mw, req)
duration := time.Since(then)
labels := monitor.HttpRequestLabels{
Status: fmt.Sprintf("%d", mw.Status()),
Route: utils.GetRoutePattern(req),
Method: req.Method,
}
err := monitorService.MonitorHttpRequestDuration(duration, labels)
if err != nil {
log.Ctx(req.Context()).Errorf("Error trying to monitor request time: %s", err)
}
})
}
}
// AuthenticateMiddleware is a middleware that validates the Authorization header for
// authenticated endpoints.
func AuthenticateMiddleware(authManager auth.AuthManager, tenantManager tenant.ManagerInterface) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
authHeader := req.Header.Get("Authorization")
if authHeader == "" {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
ctx := req.Context()
token := authHeaderParts[1]
userID, err := authManager.GetUserID(ctx, token)
if err != nil {
if !errors.Is(err, auth.ErrInvalidToken) && !errors.Is(err, auth.ErrUserNotFound) {
err = fmt.Errorf("error validating auth token: %w", err)
log.Ctx(ctx).Error(err)
}
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
// Add the token to the request context
ctx = context.WithValue(ctx, TokenContextKey, token)
// Attempt fetching tenant ID from token
tenantID, err := authManager.GetTenantID(ctx, token)
if err == nil && tenantID != "" {
currentTenant, tenantErr := tenantManager.GetTenantByID(ctx, tenantID)
if tenantErr == nil && currentTenant != nil {
ctx = tenant.SaveTenantInContext(ctx, currentTenant)
}
}
// Add the user ID to the request context logger
ctx = log.Set(ctx, log.Ctx(ctx).WithField("user_id", userID))
req = req.WithContext(ctx)
next.ServeHTTP(rw, req)
})
}
}
// AnyRoleMiddleware validates if the user has at least one of the required roles to request
// the current endpoint.
func AnyRoleMiddleware(authManager auth.AuthManager, requiredRoles ...data.UserRole) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
token, ok := ctx.Value(TokenContextKey).(string)
if !ok {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
// Accessible by all users
if len(requiredRoles) == 0 {
next.ServeHTTP(rw, req)
return
}
isValid, err := authManager.AnyRolesInTokenUser(ctx, token, data.FromUserRoleArrayToStringArray(requiredRoles))
if err != nil && !errors.Is(err, auth.ErrInvalidToken) && !errors.Is(err, auth.ErrUserNotFound) {
httperror.InternalError(ctx, "", err, nil).Render(rw)
return
}
if !isValid {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
next.ServeHTTP(rw, req)
})
}
}
func CorsMiddleware(corsAllowedOrigins []string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
cors := cors.New(cors.Options{
AllowedOrigins: corsAllowedOrigins,
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"},
})
return cors.Handler(next)
}
}
type cspItem struct {
ContentType string
Policy []string
}
func (c cspItem) String() string {
return fmt.Sprintf("%s %s;", c.ContentType, strings.Join(c.Policy, " "))
}
// LoggingMiddleware is a middleware that logs requests to the logger.
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
mw := mutil.WrapWriter(rw)
reqCtx := req.Context()
logFields := log.F{
"method": req.Method,
"path": req.URL.String(),
"req": middleware.GetReqID(reqCtx),
}
logCtx := log.Set(reqCtx, log.Ctx(reqCtx).WithFields(logFields))
ctxTenant, err := tenant.GetTenantFromContext(reqCtx)
if err != nil {
// Log for auditing purposes when we cannot derive the tenant from the context in the case of
// tenant-unaware endpoints
log.Ctx(logCtx).Debug("tenant cannot be derived from context")
}
if ctxTenant != nil {
logFields["tenant_name"] = ctxTenant.Name
logFields["tenant_id"] = ctxTenant.ID
logCtx = log.Set(reqCtx, log.Ctx(reqCtx).WithFields(logFields))
}
req = req.WithContext(logCtx)
logRequestStart(req)
started := time.Now()
next.ServeHTTP(mw, req)
ended := time.Since(started)
logRequestEnd(req, mw, ended)
})
}
func logRequestStart(req *http.Request) {
l := log.Ctx(req.Context()).WithFields(
log.F{
"subsys": "http",
"ip": req.RemoteAddr,
"host": req.Host,
"useragent": req.Header.Get("User-Agent"),
},
)
l.Info("starting request")
}
func logRequestEnd(req *http.Request, mw mutil.WriterProxy, duration time.Duration) {
l := log.Ctx(req.Context()).WithFields(log.F{
"subsys": "http",
"status": mw.Status(),
"bytes": mw.BytesWritten(),
"duration": duration,
})
if routeContext := chi.RouteContext(req.Context()); routeContext != nil {
l = l.WithField("route", routeContext.RoutePattern())
}
l.Info("finished request")
}
// CSPMiddleware is the middleware that sets the content security policy, restricting content to only be accessed
// from specified sources in the header.
func CSPMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
selfSrc := "'self'"
recaptchaSrc := "https://www.google.com/recaptcha/"
ipapiSrc := "https://ipapi.co/json"
cspItems := []cspItem{
{"script-src", []string{selfSrc, recaptchaSrc, "https://www.gstatic.com/recaptcha/"}},
{"style-src", []string{selfSrc, recaptchaSrc, "https://fonts.googleapis.com/css2", "'unsafe-inline'"}},
{"connect-src", []string{selfSrc, recaptchaSrc, ipapiSrc}},
{"font-src", []string{selfSrc, "https://fonts.gstatic.com"}},
{"default-src", []string{selfSrc}},
{"frame-src", []string{selfSrc, recaptchaSrc}},
{"frame-ancestors", []string{selfSrc}},
{"form-action", []string{selfSrc}},
}
cspStr := ""
for _, item := range cspItems {
cspStr += fmt.Sprintf("%v", item)
}
rw.Header().Set("Content-Security-Policy", cspStr)
next.ServeHTTP(rw, req)
})
}
}
// ResolveTenantFromRequestMiddleware is a middleware that injects the tenant into the request context, if it can be found in
// the request HEADER, or the hostname prefix.
func ResolveTenantFromRequestMiddleware(tenantManager tenant.ManagerInterface, singleTenantMode bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
var currentTenant *tenant.Tenant
if singleTenantMode {
var err error
currentTenant, err = tenantManager.GetDefault(ctx)
if err != nil {
switch {
case errors.Is(err, tenant.ErrTenantDoesNotExist):
// Log warning and allow the request to continue without a tenant.
log.Ctx(ctx).Warnf(
"No default tenant configured: %v. "+
"use POST /default-tenant to set the default tenant.",
err,
)
next.ServeHTTP(rw, req)
return
case errors.Is(err, tenant.ErrTooManyDefaultTenants):
httperror.InternalError(ctx, "Too many default tenants configured", err, nil).Render(rw)
default:
httperror.InternalError(ctx, "", fmt.Errorf("error getting default tenant: %w", err), nil).Render(rw)
}
return
}
} else {
// Attempt fetching tenant name from request
if tenantName, err := extractTenantNameFromRequest(req); err == nil && tenantName != "" {
currentTenant, _ = tenantManager.GetTenantByName(ctx, tenantName)
}
}
if currentTenant != nil {
ctx = tenant.SaveTenantInContext(ctx, currentTenant)
next.ServeHTTP(rw, req.WithContext(ctx))
} else {
next.ServeHTTP(rw, req)
}
})
}
}
// EnsureTenantMiddleware is a middleware that ensures the tenant is in the request context.
func EnsureTenantMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if _, err := tenant.GetTenantFromContext(ctx); err != nil {
httperror.BadRequest("Tenant not found in context", err, nil).Render(rw)
return
}
next.ServeHTTP(rw, req)
})
}
func BasicAuthMiddleware(adminAccount, adminApiKey string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if adminAccount == "" || adminApiKey == "" {
httperror.InternalError(ctx, "Admin account and API key are not set", nil, nil).Render(rw)
return
}
accountUserName, apiKey, ok := req.BasicAuth()
if !ok {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
// Using constant time comparison to avoid timing attacks
if accountUserName != adminAccount || subtle.ConstantTimeCompare([]byte(apiKey), []byte(adminApiKey)) != 1 {
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
log.Ctx(ctx).Infof("[AdminAuth] - Admin authenticated with account %s", adminAccount)
next.ServeHTTP(rw, req)
})
}
}
// extractTenantNameFromRequest attempts to extract the tenant name from the request HEADER[tenantHeaderKey] or the hostname prefix.
func extractTenantNameFromRequest(r *http.Request) (string, error) {
// 1. Try extracting from the TenantHeaderKey header first
tenantName := r.Header.Get(TenantHeaderKey)
if tenantName != "" {
return tenantName, nil
}
// 2. If header is blank, extract from the hostname prefix
return utils.ExtractTenantNameFromHostName(r.Host)
}