/
middlewares.go
305 lines (262 loc) · 8.72 KB
/
middlewares.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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/go-chi/jwtauth/v5"
"github.com/go-chi/render"
"github.com/jackc/pgx/v4"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/matoous/go-nanoid/v2"
"github.com/rhpds/sandbox/internal/api/v1"
"github.com/rhpds/sandbox/internal/log"
)
// AllowContentType enforces a whitelist of request Content-Types otherwise responds
// with a 415 Unsupported Media Type status.
func AllowContentType(contentTypes ...string) func(next http.Handler) http.Handler {
allowedContentTypes := make(map[string]struct{}, len(contentTypes))
for _, ctype := range contentTypes {
allowedContentTypes[strings.TrimSpace(strings.ToLower(ctype))] = struct{}{}
}
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength == 0 {
// skip check for empty content body
next.ServeHTTP(w, r)
return
}
s := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Type")))
if i := strings.Index(s, ";"); i > -1 {
s = s[0:i]
}
if _, ok := allowedContentTypes[s]; ok {
next.ServeHTTP(w, r)
return
}
w.WriteHeader(http.StatusUnsupportedMediaType)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnsupportedMediaType,
Message: fmt.Sprintf("Unsupported Media Type '%s'. Allowed: %s", s, strings.Join(contentTypes, ", ")),
})
}
return http.HandlerFunc(fn)
}
}
func (h *BaseHandler) OpenAPIValidation(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
route, pathParams, err := h.oaRouter.FindRoute(r)
if err != nil {
log.Logger.Error("Error finding route", "error", err)
w.WriteHeader(http.StatusBadRequest)
enc.Encode(v1.Error{
HTTPStatusCode: http.StatusBadRequest,
Message: "Error finding route",
})
return
}
requestValidationInput := &openapi3filter.RequestValidationInput{
Request: r,
PathParams: pathParams,
Route: route,
Options: &openapi3filter.Options{
MultiError: true,
},
}
err = openapi3filter.ValidateRequest(context.Background(), requestValidationInput)
if err != nil {
log.Logger.Error("Error validating request", "error", err)
errs := strings.Split(err.Error(), "\n")
w.WriteHeader(http.StatusBadRequest)
enc.Encode(v1.Error{
HTTPStatusCode: http.StatusBadRequest,
Message: "Bad request: payload doesn't pass OpenAPI spec",
ErrorMultiline: errs,
})
return
}
next.ServeHTTP(w, r)
})
}
// AuthenticatorAdmin is a admin authentication middleware to enforce access from the
// Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
// response for any unverified tokens and passes the good ones through.
// It looks at the role and make sure it is admin.
func AuthenticatorAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
log.Logger.Info("Error authenticating request", "error", err, "token", token, "claims", claims)
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: err.Error(),
})
return
}
if token == nil || jwt.Validate(token) != nil {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
})
return
}
if claims["kind"] != "access" {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: "Wrong token kind, access token required",
})
return
}
if claims["role"] != "admin" {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
})
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
// AuthenticatorLogin is a authentication middleware to enforce access from the
// Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
// response for any unverified tokens and passes the good ones through.
// It looks at the kind and make sure it is a login token.
func (h *BaseHandler) AuthenticatorLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
log.Logger.Info("Error authenticating request", "error", err, "token", token, "claims", claims)
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: err.Error(),
})
return
}
if token == nil || jwt.Validate(token) != nil {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
})
return
}
if claims["kind"] != "login" {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: "Wrong token kind, login token required",
})
return
}
jti := token.JwtID()
var id int
err = h.dbpool.QueryRow(context.Background(),
"SELECT id FROM tokens WHERE id = $1 AND valid = true AND kind = 'login'",
jti).Scan(&id)
if err != nil {
if err == pgx.ErrNoRows {
log.Logger.Error("Error checking token", "error", err)
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: "Token not found or invalid",
})
return
}
log.Logger.Error("Error checking token", "error", err)
w.WriteHeader(http.StatusInternalServerError)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusInternalServerError,
Message: "Error checking token",
})
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
// AuthenticatorAccess is a default authentication middleware to enforce access from the
// Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
// response for any unverified tokens and passes the good ones through. It's just fine
func AuthenticatorAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token, claims, err := jwtauth.FromContext(ctx)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: err.Error(),
})
return
}
if token == nil || jwt.Validate(token) != nil {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: http.StatusText(http.StatusUnauthorized),
})
return
}
if claims["kind"] != "access" {
w.WriteHeader(http.StatusUnauthorized)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusUnauthorized,
Message: "Wrong token kind, access token required",
})
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}
// RequestID
var RequestIDHeader = "X-Request-Id"
// Key to use when setting the request ID.
type ctxKeyRequestID int
// RequestIDKey is the key that holds the unique request ID in a request context.
const RequestIDKey ctxKeyRequestID = 0
// GetReqID returns a request ID from the given context if one is present.
// Returns the empty string if a request ID cannot be found.
func GetReqID(ctx context.Context) string {
if ctx == nil {
return ""
}
if reqID, ok := ctx.Value(RequestIDKey).(string); ok {
return reqID
}
return ""
}
// ShortRequestID is a middleware that injects a Short request ID into the context of each request.
func ShortRequestID(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
requestID := r.Header.Get(RequestIDHeader)
if requestID == "" {
var err error
requestID, err = gonanoid.New()
if err != nil {
log.Logger.Error("Error generating request ID", "error", err)
w.WriteHeader(http.StatusInternalServerError)
render.Render(w, r, &v1.Error{
HTTPStatusCode: http.StatusInternalServerError,
Message: "Error generating request ID",
})
return
}
}
ctx = context.WithValue(ctx, RequestIDKey, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}