/
httputil.go
344 lines (304 loc) · 9.18 KB
/
httputil.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
package api
import (
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/carlmjohnson/resperr"
"github.com/getsentry/sentry-go"
"github.com/spotlightpa/almanack/internal/netlifyid"
"github.com/spotlightpa/almanack/internal/stringx"
"github.com/spotlightpa/almanack/layouts"
"github.com/spotlightpa/almanack/pkg/almanack"
"github.com/spotlightpa/almanack/pkg/almlog"
)
func (app *appEnv) replyJSON(statusCode int, w http.ResponseWriter, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
enc := json.NewEncoder(w)
if err := enc.Encode(data); err != nil {
// TODO: Log to Sentry
almlog.Logger.Error("replyJSON", "err", err)
}
}
func (app *appEnv) replyErr(w http.ResponseWriter, r *http.Request, err error) {
app.logErr(r.Context(), err)
code := resperr.StatusCode(err)
details := url.Values{"message": []string{resperr.UserMessage(err)}}
if v := resperr.ValidationErrors(err); len(v) != 0 {
details = v
}
app.replyJSON(code, w, struct {
Status int `json:"status"`
Details url.Values `json:"details"`
}{
code,
details,
})
}
func (app *appEnv) replyNewErr(code int, w http.ResponseWriter, r *http.Request, format string, v ...any) {
app.replyErr(w, r, resperr.New(code, format, v...))
}
func (app *appEnv) logErr(ctx context.Context, err error) {
l := almlog.FromContext(ctx)
if hub := sentry.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
userinfo := netlifyid.FromContext(ctx)
scope.SetTag("username", cmp.Or(userinfo.Username(), "anonymous"))
scope.SetTag("email", cmp.Or(userinfo.Email(), "not set"))
hub.CaptureException(err)
})
} else {
l.Warn("sentry not in context")
}
l.ErrorContext(ctx, "logErr", "err", err)
}
func (app *appEnv) tryReadJSON(w http.ResponseWriter, r *http.Request, dst any) error {
// Thanks to https://www.alexedwards.net/blog/how-to-properly-parse-a-json-request-body
if ct := r.Header.Get("Content-Type"); ct != "" {
value, _, _ := mime.ParseMediaType(ct)
if value != "application/json" {
return resperr.New(http.StatusUnsupportedMediaType,
"request Content-Type must be application/json; got %s",
ct)
}
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err := dec.Decode(&dst)
if err != nil {
var (
syntaxError *json.SyntaxError
unmarshalTypeError *json.UnmarshalTypeError
maxBytesError *http.MaxBytesError
)
switch {
case errors.As(err, &syntaxError):
return resperr.WithUserMessagef(err,
"Request body contains badly-formed JSON (at position %d)",
syntaxError.Offset)
case errors.Is(err, io.ErrUnexpectedEOF):
return resperr.WithUserMessage(err,
"Request body contains badly-formed JSON")
case errors.As(err, &unmarshalTypeError):
return resperr.WithUserMessagef(err,
"Request body contains an invalid value for the %q field (at position %d)",
unmarshalTypeError.Field, unmarshalTypeError.Offset)
case strings.HasPrefix(err.Error(), "json: unknown field "):
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
return resperr.WithUserMessagef(err,
"Request body contains unknown field %s", fieldName)
case errors.Is(err, io.EOF):
return resperr.WithUserMessage(nil,
"Request body must not be empty")
case errors.As(err, &maxBytesError):
return resperr.New(http.StatusRequestEntityTooLarge,
"request body exceeds max size %d: %w",
maxBytesError.Limit, err)
default:
return resperr.New(http.StatusBadRequest, "tryReadJSON: %w", err)
}
}
var discard any
if err := dec.Decode(&discard); !errors.Is(err, io.EOF) {
return resperr.WithUserMessagef(nil,
"Request body must only contain a single JSON object")
}
return nil
}
func (app *appEnv) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
if err := app.tryReadJSON(w, r, dst); err != nil {
app.replyErr(w, r, err)
return false
}
return true
}
func (app *appEnv) versionMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Almanack-App-Version", almanack.BuildVersion)
h.ServeHTTP(w, r)
})
}
func (app *appEnv) authHeaderMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r2, err := app.auth.AuthFromHeader(r)
if err != nil {
app.replyErr(w, r, err)
return
}
h.ServeHTTP(w, r2)
})
}
func (app *appEnv) authCookieMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r2, err := app.auth.AuthFromCookie(r)
if err != nil {
app.replyErr(w, r, err)
return
}
h.ServeHTTP(w, r2)
})
}
func (app *appEnv) hasRoleMiddleware(role string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := app.auth.HasRole(r, role); err != nil {
app.replyErr(w, r, err)
return
}
next.ServeHTTP(w, r)
})
}
}
func (app *appEnv) maxSizeMiddleware(next http.Handler) http.Handler {
const (
megabyte = 1 << 20
maxSize = 5 * megabyte
)
return http.MaxBytesHandler(next, maxSize)
}
func intParam[Int int | int32 | int64](r *http.Request, param string, p *Int) error {
pstr := r.PathValue(param)
if pstr == "" {
return fmt.Errorf("parameter %q not set", param)
}
if err := intFromString(pstr, p); err != nil {
return resperr.WithUserMessagef(
err, "Bad integer parameter for %s", param)
}
return nil
}
func intFromQuery[Int int | int32 | int64](r *http.Request, param string, p *Int) bool {
s := r.URL.Query().Get(param)
err := intFromString(s, p)
return err == nil
}
func intFromString[Int int | int32 | int64](s string, p *Int) error {
bitsize := 0
switch any(p).(type) {
case *int:
case *int32:
bitsize = 32
case *int64:
bitsize = 64
default:
panic("unreachable")
}
n, err := strconv.ParseInt(s, 10, bitsize)
if err != nil {
return err
}
*p = Int(n)
return nil
}
func boolFromQuery(r *http.Request, param string) (val bool, err error) {
if !r.URL.Query().Has(param) {
return
}
s := r.URL.Query().Get(param)
val, err = strconv.ParseBool(s)
if err != nil {
err = resperr.WithUserMessagef(err,
"Could not interpret %s=%q", param, s)
}
return
}
func (app *appEnv) replyHTML(w http.ResponseWriter, r *http.Request, t *template.Template, data any) {
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
app.logErr(r.Context(), err)
app.replyHTMLErr(w, r, err)
return
}
w.Header().Set("Content-Type", "text/html")
if _, err := buf.WriteTo(w); err != nil {
app.logErr(r.Context(), err)
return
}
}
func (app *appEnv) replyHTMLErr(w http.ResponseWriter, r *http.Request, err error) {
app.logErr(r.Context(), err)
code := resperr.StatusCode(err)
var buf bytes.Buffer
if err := layouts.Error.Execute(&buf, struct {
Status string
StatusCode int
Message string
}{
Status: http.StatusText(code),
StatusCode: code,
Message: resperr.UserMessage(err),
}); err != nil {
app.logErr(r.Context(), err)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(code)
if _, err := buf.WriteTo(w); err != nil {
app.logErr(r.Context(), err)
return
}
}
func (app *appEnv) logStart(r *http.Request, args ...any) {
pc, file, line, ok := runtime.Caller(1)
route := "unknown"
if ok {
f := runtime.FuncForPC(pc)
file = filepath.Base(file)
_, name, _ := stringx.LastCut(f.Name(), ".")
route = fmt.Sprintf("%s(%s:%d)", name, file, line)
}
l := almlog.FromContext(r.Context())
l.With(args...).InfoContext(r.Context(), "logStart", "route", route)
}
func (app *appEnv) jsonErr(err error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyErr(w, r, err)
})
}
func (app *appEnv) jsonNewErr(code int, format string, args ...any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyErr(w, r, resperr.New(code, format, args...))
})
}
func (app *appEnv) jsonBadRequest(err error, format string, args ...any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyErr(w, r, resperr.WithUserMessagef(err, format, args...))
})
}
func (app *appEnv) jsonOK(v any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyJSON(http.StatusOK, w, v)
})
}
func (app *appEnv) jsonAccepted(v any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyJSON(http.StatusAccepted, w, v)
})
}
func (app *appEnv) htmlOK(t *template.Template, data any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyHTML(w, r, t, data)
})
}
func (app *appEnv) htmlErr(err error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyHTMLErr(w, r, err)
})
}
func (app *appEnv) htmlBadRequest(err error, format string, args ...any) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.replyHTMLErr(w, r, resperr.WithUserMessagef(err, format, args...))
})
}