Skip to content

Commit cf60f15

Browse files
mromaszewiczclaude
andauthored
Keep the validated request body value and expose it via c.Locals (#56)
Enable openapi3filter.Options.KeepValidatedValue by default, as the other oapi-codegen validation middlewares do, with Options.DiscardValidatedValue as the opt-out. Fiber does not run on net/http, so the validator works on a converted copy of the request and the value it leaves on that copy's body is not reachable from handlers. After validation the middleware now copies the value into the Fiber context under ValidatedBodyLocalsKey ("x-oapi-codegen-validated-body"), readable with ValidatedBody(c). oapi-codegen strict Fiber servers bind that value with exact member-name matching instead of decoding the body a second time, which closes the gap where encoding/json's case-insensitive matching let an unvalidated "ROLE" member bind to `role`. The key is defined independently in the generated code so it does not import this module; keep the two in sync. The body bytes seen by handlers are unchanged. The caller's options struct is copied before the default is applied. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 49def0e commit cf60f15

3 files changed

Lines changed: 122 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,10 @@
44

55
Middleware for the [Fiber web server](https://github.com/gofiber/fiber) for use with [deepmap/oapi-codegen](https://github.com/deepmap/oapi-codegen).
66

7+
## Validated request body
8+
9+
The middleware enables kin-openapi's `openapi3filter.Options.KeepValidatedValue` by default. Fiber does not run on `net/http`, so the validator works on a converted copy of the request; after a request body passes validation, the middleware stores the decoded value that was validated in the Fiber context under `ValidatedBodyLocalsKey` (`x-oapi-codegen-validated-body`), readable with `ValidatedBody(c)`. The body bytes seen by the handler (`c.Body()`) are unchanged. oapi-codegen strict servers that support it bind that value instead of decoding the body a second time, so the handler sees exactly what was validated (for example, `encoding/json`'s case-insensitive member matching can no longer make a request validate as one value but bind as another).
10+
11+
To opt out, for instance to limit memory retention for very large request bodies, set `Options.DiscardValidatedValue = true`. This setting overrides `Options.Options.KeepValidatedValue`.
12+
713
Licensed under the Apache-2.0.

‎oapi_validate.go‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,34 @@ type Options struct {
6060
ParamDecoder openapi3filter.ContentParameterDecoder
6161
UserData interface{}
6262
MultiErrorHandler MultiErrorHandler
63+
// DiscardValidatedValue turns off openapi3filter.Options.KeepValidatedValue,
64+
// which this middleware enables by default. With it enabled, the decoded
65+
// request body value that passed validation is stored in the Fiber context
66+
// under ValidatedBodyLocalsKey, so a handler (for example an oapi-codegen
67+
// strict server) can bind that value instead of decoding the body a second
68+
// time. Set this to drop the decoded value after validation, for instance to
69+
// limit memory retention for very large request bodies.
70+
//
71+
// Options.Options.KeepValidatedValue is overridden by this setting.
72+
DiscardValidatedValue bool
73+
}
74+
75+
// ValidatedBodyLocalsKey is the c.Locals key under which the middleware stores
76+
// the decoded request body value that passed validation (see
77+
// Options.DiscardValidatedValue). The value is what kin-openapi validated:
78+
// nil, bool, string, json.Number, []any or map[string]any.
79+
//
80+
// Strict servers generated by oapi-codegen look the value up under this same
81+
// key, where it is defined independently so generated code does not import
82+
// this module. Keep the two in sync.
83+
const ValidatedBodyLocalsKey = "x-oapi-codegen-validated-body"
84+
85+
// ValidatedBody returns the request body value that passed validation, as
86+
// stored by the middleware under ValidatedBodyLocalsKey, and whether one was
87+
// stored for this request.
88+
func ValidatedBody(c *fiber.Ctx) (any, bool) {
89+
v := c.Locals(ValidatedBodyLocalsKey)
90+
return v, v != nil
6391
}
6492

6593
// OapiRequestValidatorWithOptions creates a validator from a swagger object, with validation options
@@ -124,9 +152,15 @@ func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Op
124152
requestContext := context.WithValue(context.Background(), ctxKeyFiberContext{}, c) //nolint:staticcheck
125153

126154
if options != nil {
127-
requestValidationInput.Options = &options.Options
155+
// Copy the openapi3filter options so the caller's struct is not
156+
// mutated when applying our KeepValidatedValue default.
157+
filterOptions := options.Options
158+
filterOptions.KeepValidatedValue = !options.DiscardValidatedValue
159+
requestValidationInput.Options = &filterOptions
128160
requestValidationInput.ParamDecoder = options.ParamDecoder
129161
requestContext = context.WithValue(requestContext, ctxKeyUserData{}, options.UserData) //nolint:staticcheck
162+
} else {
163+
requestValidationInput.Options = &openapi3filter.Options{KeepValidatedValue: true}
130164
}
131165

132166
err = openapi3filter.ValidateRequest(requestContext, requestValidationInput)
@@ -152,6 +186,13 @@ func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Op
152186
return fmt.Errorf("error validating request: %w", err)
153187
}
154188
}
189+
190+
// The validator ran on a net/http copy of the request, so the validated
191+
// value it left on that copy's body has to be carried over to the Fiber
192+
// context by hand for handlers to reach it.
193+
if vb, ok := r.Body.(interface{ ValidatedValue() any }); ok {
194+
c.Locals(ValidatedBodyLocalsKey, vb.ValidatedValue())
195+
}
155196
return nil
156197
}
157198

‎oapi_validate_test.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,3 +432,77 @@ func TestOapiRequestValidatorWithOptionsMultiErrorAndCustomHandler(t *testing.T)
432432
called = false
433433
}
434434
}
435+
436+
func TestOapiRequestValidatorKeepValidatedValue(t *testing.T) {
437+
swagger, err := openapi3.NewLoader().LoadFromData(testSchema)
438+
require.NoError(t, err, "Error initializing swagger")
439+
440+
tests := []struct {
441+
name string
442+
options *Options
443+
wantValidated bool
444+
}{
445+
{
446+
name: "nil options keep the validated value",
447+
options: nil,
448+
wantValidated: true,
449+
},
450+
{
451+
name: "empty options keep the validated value",
452+
options: &Options{},
453+
wantValidated: true,
454+
},
455+
{
456+
name: "DiscardValidatedValue drops the validated value",
457+
options: &Options{
458+
DiscardValidatedValue: true,
459+
// DiscardValidatedValue overrides the openapi3filter setting.
460+
Options: openapi3filter.Options{KeepValidatedValue: true},
461+
},
462+
wantValidated: false,
463+
},
464+
{
465+
name: "ExcludeRequestBody skips body validation",
466+
options: &Options{
467+
Options: openapi3filter.Options{ExcludeRequestBody: true},
468+
},
469+
wantValidated: false,
470+
},
471+
}
472+
473+
for _, tt := range tests {
474+
t.Run(tt.name, func(t *testing.T) {
475+
app := fiber.New()
476+
if tt.options == nil {
477+
app.Use(OapiRequestValidator(swagger))
478+
} else {
479+
app.Use(OapiRequestValidatorWithOptions(swagger, tt.options))
480+
}
481+
482+
var got any
483+
var found bool
484+
var rawBody string
485+
app.Post("/resource", func(c *fiber.Ctx) error {
486+
got, found = ValidatedBody(c)
487+
rawBody = string(c.Body())
488+
return c.SendStatus(http.StatusNoContent)
489+
})
490+
491+
body := struct {
492+
Name string `json:"name"`
493+
}{Name: "Marcin"}
494+
res := doPost(t, app, "https://deepmap.ai/resource", body)
495+
require.Equal(t, http.StatusNoContent, res.StatusCode)
496+
// The original body is untouched for the handler either way.
497+
assert.JSONEq(t, `{"name":"Marcin"}`, rawBody)
498+
499+
if !tt.wantValidated {
500+
assert.False(t, found)
501+
assert.Nil(t, got)
502+
return
503+
}
504+
require.True(t, found, "validated value should be stored under ValidatedBodyLocalsKey")
505+
assert.Equal(t, map[string]any{"name": "Marcin"}, got)
506+
})
507+
}
508+
}

0 commit comments

Comments
 (0)