Documentation
¶
Overview ¶
Package validate compiles OpenAPI 3.1 schemas with santhosh-tekuri/jsonschema and validates decoded requests against them.
A Compiler holds the full OpenAPI document as one resource. Each operation compiles a synthetic schema of the form
{"type":"object","properties":{"path":{...},"query":{...},"header":{...},
"body":{"$ref":"spec.json#/components/schemas/X"}},"required":[...]}
whose $refs point into the document with the "spec.json#/..." prefix.
The Compiler is not safe for concurrent use: compile every operation from a single goroutine, as the api registry does in Ready. A compiled Schema is immutable and safe to use from any number of goroutines.
Validation errors become a single ez.EINVALID error whose message lists the failing fields, at most MaxFields of them: past that many the walk of the violations stops, so a body of many failing values costs about what the validator's own errors cost. Messages never contain the submitted value. Fields returns the same list in structured form.
Index ¶
Constants ¶
const MaxExactNumber = 64
MaxExactNumber is the length of the longest JSON number literal without an exponent (e or E) that the validator is handed as the client wrote it, and the most significant digits of one it is handed the exact value of; any other gets text that compares with the document's numbers as it does (see CanonicalNumber). Bounds are so checked on the value a json.Number or big.Int field receives, not on a rounded one. The validator parses every number with big.Rat, whose cost grows with an exponent (1e-999999 takes milliseconds) and with a length this caps.
const MaxFields = 100
MaxFields is the most fields one error lists. A request can fail on as many fields as it has values, so an uncapped list would make the answer many times the size of the request that caused it.
Variables ¶
This section is empty.
Functions ¶
func CanonicalNumber ¶ added in v1.38.0
CanonicalNumber returns the text the validator is handed for s, a JSON number literal or a base-10 integer with leading zeros. The validator parses every number with big.Rat, whose cost grows with the length of the text and with its exponent, so it gets short text that compares with every number a document states as s does: those are bounds and enum values, each a float64, an int64 or a uint64, so of at most 20 significant digits and less than 10^309 in magnitude. The text is
- s itself, when it has at most MaxExactNumber characters and no exponent;
- else the exact value of s as digits and an exponent, when it has at most MaxExactNumber significant digits, the first of them from the 10^308 place down to the 10^-324 place;
- else, for more significant digits in that span, the first MaxExactNumber of them followed by a 5, and a 5 in the tenths where that alone would make an integer of a number that is not one: no number of MaxExactNumber significant digits or fewer lies between that text and s;
- else 1e309 when s is at least 10^309 in magnitude, past every float64 (or 10^309 and a half, when s is no integer), or 1e-325 when it is under 10^-324, closer to 0 than every float64 but 0, with the sign of s.
The text is an integer exactly when s is. multipleOf gives on it the answer it gives on s for the first two forms and for 1e-325; on the others it cannot for every multipleOf, and a validator from NewRequestCompiler refuses such a number where its schema has multipleOf, unless that is 1, or 1/k and the number an integer (see multipleOfDigits).
func Coerce ¶
Coerce converts raw parameter values to the JSON value the schema expects. Integers become json.Number in canonical text, those past the int64 and uint64 ranges only up to MaxExactNumber characters; numbers within the float64 range become json.Number in the text CanonicalNumber gives them; a number past that range, or that is no JSON literal (+5 or 007, which an integer takes), stays the raw string. Booleans accept exactly "true" and "false", arrays take repeated values or one comma-separated value. A value that does not parse is returned as the raw string so validation reports a type error. No values means absent and returns nil.
func DecodeBytes ¶
DecodeBytes decodes a JSON body into any, keeping numbers as json.Number and rejecting trailing data. An empty body returns nil, nil. Errors are ez.EINVALID and never echo the body. An object that repeats a key keeps only its last value (RejectRepeatedKeys refuses such a body).
func NewFieldsError ¶
func NewFieldsError(fields []FieldError) error
NewFieldsError builds a single ez.EINVALID error from fields, sorted by location (path, query, header, body) then name, a run of digits in a name compared as a number, with duplicates removed. The message joins "<name> <message>" with "; ", prefixing parameter names with their location. Only the first MaxFields are kept: the message then ends with "; and <n> more", and Fields returns the ones kept. Returns nil when fields is empty.
func RejectRepeatedKeys ¶
RejectRepeatedKeys returns an ez.EINVALID error when an object of the JSON text raw repeats a key, at any depth and compared after unescaping. DecodeBytes, and so the validator, keep only the last value of a repeated key, while encoding/json decodes every one into the same struct, map or slice. The error never echoes the key. It holds one entry per open array and object, without recursion, and does not bound how deep they nest: the caller does.
Types ¶
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler compiles operation schemas against one OpenAPI 3.1 document. It is not safe for concurrent use.
func NewCompiler ¶
func NewCompiler(doc json.RawMessage) (*Compiler, error)
NewCompiler loads the OpenAPI 3.1 document as resource "spec.json" and registers the formats compose relies on, email, phone and ip (uuid and date-time are built in; unknown formats such as int64 or double are ignored by santhosh).
func NewRequestCompiler ¶ added in v1.39.0
func NewRequestCompiler(doc json.RawMessage) (*Compiler, error)
NewRequestCompiler is NewCompiler for the requests the api registry validates, whose numbers carry the text CanonicalNumber gives them, which past MaxExactNumber significant digits or 10^309 does not hold all of the number: where a schema has multipleOf, it also refuses a number multipleOf cannot be checked on there (see multipleOfChecks), with the message "has too many digits to be checked as a multiple of <n>". Inside not, if and the oneOf branches after the first match, where santhosh asks only whether a value passes, such a number fails multipleOf like any other failure, so not: {multipleOf: 2} accepts a 70-digit even number. The document is checked against the core, applicator, unevaluated and validation vocabularies only, so an annotation keyword of the wrong type, such as description: 5, which NewCompiler refuses, compiles here.
type FieldError ¶
FieldError is one failing field. In is the request location ("path", "query", "header" or "body"), Name the dotted path inside it ("status", "config.name", "tags.2", or "" for the location itself) and Message the reason, which never contains the submitted value.
func Fields ¶
func Fields(err error) []FieldError
Fields returns the structured field errors carried by err, at most MaxFields of them, or nil.
type Kind ¶
Kind describes the schema type a parameter is coerced to. Type is one of "string", "integer", "number", "boolean" or "array".
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is a compiled operation schema. It is safe for concurrent use.
func (*Schema) Validate ¶
func (s *Schema) Validate(instance any, extra ...FieldError) error
Validate returns nil or an ez.EINVALID error carrying FieldErrors: the schema's violations together with extra, the fields the caller found failing by a check of its own, in one NewFieldsError. It maps violations to fields in the order NewFieldsError sorts them by, but for the cases compareEntries names, and stops past MaxFields: the message then ends with "; and more" instead of a count. Errors that are not schema violations are returned as ez.EINTERNAL, without extra.
A limit the registry's schemas never meet: where the schemas of one location mix an array and an object with additionalProperties (an anyOf, oneOf or allOf of the two, or prefixItems), the map keys of the location are walked as one "*", so a field under a key that looks like an index can be named otherwise than in v1.37.0 ("*.*" where it was "*.0").