This repository has been archived by the owner on Feb 23, 2022. It is now read-only.
forked from danielgtaylor/huma
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolver.go
498 lines (441 loc) · 12.9 KB
/
resolver.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package huma
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/istreamlabs/huma/schema"
"github.com/xeipuuv/gojsonschema"
)
// Locations for input parameters. These are used in struct field tags to
// specify the location from which the parameter value gets set. It is also
// used to generate JSON Path locations for error reporting. For example,
// `path.id` or `body.foo.bar[0].baz` might have validation errors.
const (
locationPath = string(inPath)
locationQuery = string(inQuery)
locationHeader = string(inHeader)
locationBody = "body"
)
var timeType = reflect.TypeOf(time.Time{})
var readerType = reflect.TypeOf((*io.Reader)(nil)).Elem()
// Resolver provides a way to resolve input values from a request or to post-
// process input values in some way, including additional validation beyond
// what is possible with JSON Schema alone. If any errors are added to the
// context, then the client will get a 400 Bad Request response.
type Resolver interface {
Resolve(ctx Context, r *http.Request)
}
// Checks if data validates against the given schema. Returns false on failure.
func validAgainstSchema(ctx *hcontext, label string, schema *schema.Schema, data []byte) bool {
defer func() {
// Catch panics from the `gojsonschema` library.
if err := recover(); err != nil {
ctx.AddError(&ErrorDetail{
Message: fmt.Errorf("unable to validate against schema: %w", err.(error)).Error(),
Location: label,
Value: string(data),
})
// TODO: log error?
}
}()
// TODO: load and pre-cache schemas once per operation
loader := gojsonschema.NewGoLoader(schema)
doc := gojsonschema.NewBytesLoader(data)
s, err := gojsonschema.NewSchema(loader)
if err != nil {
panic(err)
}
result, err := s.Validate(doc)
if err != nil {
panic(err)
}
if !result.Valid() {
for _, desc := range result.Errors() {
// Note: some descriptions start with the context location so we trim
// those off to prevent duplicating data. (e.g. see the enum error)
ctx.AddError(&ErrorDetail{
Message: strings.TrimPrefix(desc.Description(), desc.Context().String()+" "),
Location: label + strings.TrimPrefix(desc.Field(), "(root)"),
Value: desc.Value(),
})
}
return false
}
return true
}
// parseParamValue parses and returns a value from its string representation
// based on the given type/format info.
func parseParamValue(ctx Context, location string, name string, typ reflect.Type, timeFormat string, pstr string) interface{} {
var pv interface{}
switch typ.Kind() {
case reflect.Bool:
converted, err := strconv.ParseBool(pstr)
if err != nil {
ctx.AddError(&ErrorDetail{
Message: "cannot parse boolean",
Location: location + "." + name,
Value: pstr,
})
return nil
}
pv = converted
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
converted, err := strconv.Atoi(pstr)
if err != nil {
ctx.AddError(&ErrorDetail{
Message: "cannot parse integer",
Location: location + "." + name,
Value: pstr,
})
return nil
}
pv = reflect.ValueOf(converted).Convert(typ).Interface()
case reflect.Float32:
converted, err := strconv.ParseFloat(pstr, 32)
if err != nil {
ctx.AddError(&ErrorDetail{
Message: "cannot parse float",
Location: location + "." + name,
Value: pstr,
})
return nil
}
pv = float32(converted)
case reflect.Float64:
converted, err := strconv.ParseFloat(pstr, 64)
if err != nil {
ctx.AddError(&ErrorDetail{
Message: "cannot parse float",
Location: location + "." + name,
Value: pstr,
})
return nil
}
pv = converted
case reflect.Slice:
if len(pstr) > 1 && pstr[0] == '[' {
pstr = pstr[1 : len(pstr)-1]
}
slice := reflect.MakeSlice(typ, 0, 0)
for i, item := range strings.Split(pstr, ",") {
if itemValue := parseParamValue(ctx, fmt.Sprintf("%s[%d]", location, i), name, typ.Elem(), timeFormat, item); itemValue != nil {
slice = reflect.Append(slice, reflect.ValueOf(itemValue))
} else {
// Keep going to check other array items for vailidity.
continue
}
}
pv = slice.Interface()
default:
if typ == timeType {
dt, err := time.Parse(timeFormat, pstr)
if err != nil {
ctx.AddError(&ErrorDetail{
Message: "cannot parse time",
Location: location + "." + name,
Value: pstr,
})
return nil
}
pv = dt
} else {
pv = pstr
}
}
return pv
}
func setFields(ctx *hcontext, req *http.Request, input reflect.Value, t reflect.Type) {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if input.Kind() == reflect.Ptr {
input = input.Elem()
}
if t.Kind() != reflect.Struct {
panic("not a struct")
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
inField := input.Field(i)
if f.Anonymous {
// Embedded struct
setFields(ctx, req, inField, f.Type)
continue
}
if _, ok := f.Tag.Lookup(locationBody); ok || f.Name == strings.Title(locationBody) {
// Special case: body field is a reader for streaming
if f.Type == readerType {
inField.Set(reflect.ValueOf(req.Body))
continue
}
// Check if a content-length has been sent. If it's too big then there
// is no need to waste time reading.
if length := req.Header.Get("Content-Length"); length != "" {
if l, err := strconv.ParseInt(length, 10, 64); err == nil {
if l > ctx.op.maxBodyBytes {
ctx.AddError(&ErrorDetail{
Message: fmt.Sprintf("Request body too large, limit = %d bytes", ctx.op.maxBodyBytes),
Location: locationBody,
Value: length,
})
continue
}
}
}
// Load the body (read/unmarshal).
data, err := ioutil.ReadAll(req.Body)
if err != nil {
if strings.Contains(err.Error(), "request body too large") {
ctx.AddError(&ErrorDetail{
Message: fmt.Sprintf("Request body too large, limit = %d bytes", ctx.op.maxBodyBytes),
Location: locationBody,
})
} else if e, ok := err.(net.Error); ok && e.Timeout() {
ctx.AddError(&ErrorDetail{
Message: fmt.Sprintf("Request body took too long to read: timed out after %v", ctx.op.bodyReadTimeout),
Location: locationBody,
})
} else {
panic(err)
}
continue
}
if ctx.op.requestSchema != nil && ctx.op.requestSchema.HasValidation() {
if !validAgainstSchema(ctx, locationBody+".", ctx.op.requestSchema, data) {
continue
}
}
err = json.Unmarshal(data, inField.Addr().Interface())
if err != nil {
panic(err)
}
continue
}
var pv string
var pname string
var location string
timeFormat := time.RFC3339Nano
if v, ok := f.Tag.Lookup("default"); ok {
pv = v
}
if name, ok := f.Tag.Lookup(locationPath); ok {
pname = name
location = locationPath
if v := chi.URLParam(req, name); v != "" {
pv = v
}
}
if name, ok := f.Tag.Lookup(locationQuery); ok {
pname = name
location = locationQuery
if v := req.URL.Query().Get(name); v != "" {
pv = v
}
}
if name, ok := f.Tag.Lookup(locationHeader); ok {
pname = name
location = locationHeader
// TODO: get combined rather than first header?
if v := req.Header.Get(name); v != "" {
pv = v
}
// Some headers have special time formats that aren't ISO8601/RFC3339.
lowerName := strings.ToLower(name)
if lowerName == "if-modified-since" || lowerName == "if-unmodified-since" {
timeFormat = http.TimeFormat
}
}
if pv != "" {
// Parse value into the right type.
parsed := parseParamValue(ctx, location, pname, f.Type, timeFormat, pv)
if parsed == nil {
// At least one error, just keep going trying to parse other fields.
continue
}
if oap, ok := ctx.op.params[pname]; ok {
s := oap.Schema
if s.HasValidation() {
data := pv
if s.Type == "string" && !strings.HasPrefix(data, `"`) {
// Strings are special in that we don't expect users to provide them
// with quotes, so wrap them here for the parser that does the
// validation step below.
data = `"` + data + `"`
} else if s.Type == "array" {
// Array type needs to have `[` and `]` added.
if s.Items.Type == "string" {
// Same as above, quote each item.
parts := strings.Split(data, ",")
for i, part := range parts {
if !strings.HasPrefix(part, `"`) {
parts[i] = `"` + part + `"`
}
}
data = strings.Join(parts, ",")
}
if len(data) > 0 && data[0] != '[' {
data = "[" + data + "]"
}
}
if !validAgainstSchema(ctx, location+"."+pname, s, []byte(data)) {
continue
}
}
}
inField.Set(reflect.ValueOf(parsed))
}
}
}
// A smart join for JSONPath
func pathJoin(prefix string, parts ...string) string {
joined := prefix
if joined != "" {
joined += "."
}
return joined + strings.Join(parts, ".")
}
// ctxLocationWrapper wraps a context so that the error detail `location` field
// gets sets appropriately for resolver errors. I.e. the resolver doesn't know
// when it runs whether it is the body or deeply nested within the body of an
// incoming request. We prefix it so the errors make sense to the end-user.
type ctxLocationWrapper struct {
*hcontext
location string
}
func (c ctxLocationWrapper) AddError(err error) {
if e, ok := err.(*ErrorDetail); ok {
e.Location = pathJoin(c.location, e.Location)
}
c.hcontext.AddError(err)
}
// resolveFields recursively crawls the input struct and calls Resolve on
// any structs it finds as fields, within slices, and as values in maps. This
// should be called *after* all other fields are set so the resolver code can
// use their values. It processes depth-first so structs have access to the
// resolved fields of any contained structs when their resolver runs.
func resolveFields(ctx *hcontext, path string, input reflect.Value) {
if input.Kind() == reflect.Ptr {
resolveFields(ctx, path, input.Elem())
return
}
if input.Kind() == reflect.Invalid {
// Some internal stuff can return invalid, e.g. time.Time fields. We just
// ignore those.
return
}
// First, handle any nested stuff (depth-first search)
switch input.Kind() {
case reflect.Slice:
for i := 0; i < input.Len(); i++ {
resolveFields(ctx, fmt.Sprintf("%s[%d]", path, i), input.Index(i))
}
case reflect.Map:
keys := input.MapKeys()
for i := 0; i < input.Len(); i++ {
resolveFields(ctx, pathJoin(path, keys[i].String()), input.MapIndex(keys[i]))
}
case reflect.Struct:
for i := 0; i < input.NumField(); i++ {
f := input.Type().Field(i)
n := strings.ToLower(f.Name)
if j, ok := f.Tag.Lookup("json"); ok {
parts := strings.Split(j, ",")
if parts[0] != "" {
n = parts[0]
}
}
if path == "" {
// Check what kind of top-level path there should be, if any. This
// will get errors where the location is e.g. query.search or
// header.authorization so you know where to look.
for _, tag := range []string{locationPath, locationQuery, locationHeader} {
if v, ok := f.Tag.Lookup(tag); ok {
n = v
path = tag
}
}
}
resolveFields(ctx, pathJoin(path, n), input.Field(i))
}
}
// Once all nested stuff has been handled, handle the resolver method if
// it exists.
if input.CanInterface() && input.CanAddr() {
if resolver, ok := input.Addr().Interface().(Resolver); ok {
wrapper := ctxLocationWrapper{
hcontext: ctx,
location: path,
}
resolver.Resolve(wrapper, ctx.r)
}
}
}
// getParamInfo recursively gets info about params from an input struct. It
// returns a map of parameter name => parameter object.
func getParamInfo(t reflect.Type) map[string]oaParam {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
panic("not a struct")
}
params := map[string]oaParam{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous {
// Embedded struct
for k, v := range getParamInfo(f.Type) {
params[k] = v
}
continue
}
p := oaParam{}
if name, ok := f.Tag.Lookup(locationPath); ok {
p.Name = name
p.In = inPath
p.Required = true
}
if name, ok := f.Tag.Lookup(locationQuery); ok {
p.Name = name
p.In = inQuery
p.Explode = new(bool)
}
if name, ok := f.Tag.Lookup(locationHeader); ok {
p.Name = name
p.In = inHeader
}
if p.Name == "" {
// This is not a known param. May be filled in later by a resolver so
// we shouldn't touch it. Skip!
continue
}
if doc, ok := f.Tag.Lookup("doc"); ok {
p.Description = doc
}
if deprecated, ok := f.Tag.Lookup("deprecated"); ok {
p.Deprecated = deprecated == "true"
}
if internal, ok := f.Tag.Lookup("internal"); ok {
p.Internal = internal == "true"
}
if cliName, ok := f.Tag.Lookup("cliName"); ok {
p.CLIName = cliName
}
_, _, s, err := schema.GenerateFromField(f, schema.ModeRead)
if err != nil {
panic(err)
}
p.Schema = s
params[p.Name] = p
}
return params
}