| 1 | // Copyright 2025 The JSON Schema Go Project Authors. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package jsonschema |
| 6 | |
| 7 | import ( |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "hash/maphash" |
| 12 | "iter" |
| 13 | "math" |
| 14 | "math/big" |
| 15 | "reflect" |
| 16 | "slices" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "unicode/utf8" |
| 20 | ) |
| 21 | |
| 22 | // The value of the "$schema" keyword for the version that we can validate. |
| 23 | const draft202012 = "https://json-schema.org/draft/2020-12/schema" |
| 24 | |
| 25 | // Validate validates the instance, which must be a JSON value, against the schema. |
| 26 | // It returns nil if validation is successful or an error if it is not. |
| 27 | // If the schema type is "object", instance can be a map[string]any or a struct. |
| 28 | func (rs *Resolved) Validate(instance any) error { |
| 29 | if s := rs.root.Schema; s != "" && s != draft202012 { |
| 30 | return fmt.Errorf("cannot validate version %s, only %s", s, draft202012) |
| 31 | } |
| 32 | st := &state{rs: rs} |
| 33 | return st.validate(reflect.ValueOf(instance), st.rs.root, nil) |
| 34 | } |
| 35 | |
| 36 | // validateDefaults walks the schema tree. If it finds a default, it validates it |
| 37 | // against the schema containing it. |
| 38 | // |
| 39 | // TODO(jba): account for dynamic refs. This algorithm simple-mindedly |
| 40 | // treats each schema with a default as its own root. |
| 41 | func (rs *Resolved) validateDefaults() error { |
| 42 | if s := rs.root.Schema; s != "" && s != draft202012 { |
| 43 | return fmt.Errorf("cannot validate version %s, only %s", s, draft202012) |
| 44 | } |
| 45 | st := &state{rs: rs} |
| 46 | for s := range rs.root.all() { |
| 47 | // We checked for nil schemas in [Schema.Resolve]. |
| 48 | assert(s != nil, "nil schema") |
| 49 | if s.DynamicRef != "" { |
| 50 | return fmt.Errorf("jsonschema: %s: validateDefaults does not support dynamic refs", rs.schemaString(s)) |
| 51 | } |
| 52 | if s.Default != nil { |
| 53 | var d any |
| 54 | if err := json.Unmarshal(s.Default, &d); err != nil { |
| 55 | return fmt.Errorf("unmarshaling default value of schema %s: %w", rs.schemaString(s), err) |
| 56 | } |
| 57 | if err := st.validate(reflect.ValueOf(d), s, nil); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | // state is the state of single call to ResolvedSchema.Validate. |
| 66 | type state struct { |
| 67 | rs *Resolved |
| 68 | // stack holds the schemas from recursive calls to validate. |
| 69 | // These are the "dynamic scopes" used to resolve dynamic references. |
| 70 | // https://json-schema.org/draft/2020-12/json-schema-core#scopes |
| 71 | stack []*Schema |
| 72 | } |
| 73 | |
| 74 | // validate validates the reflected value of the instance. |
| 75 | func (st *state) validate(instance reflect.Value, schema *Schema, callerAnns *annotations) (err error) { |
| 76 | defer wrapf(&err, "validating %s", st.rs.schemaString(schema)) |
| 77 | |
| 78 | // Maintain a stack for dynamic schema resolution. |
| 79 | st.stack = append(st.stack, schema) // push |
| 80 | defer func() { |
| 81 | st.stack = st.stack[:len(st.stack)-1] // pop |
| 82 | }() |
| 83 | |
| 84 | // We checked for nil schemas in [Schema.Resolve]. |
| 85 | assert(schema != nil, "nil schema") |
| 86 | |
| 87 | // Step through interfaces and pointers. |
| 88 | for instance.Kind() == reflect.Pointer || instance.Kind() == reflect.Interface { |
| 89 | instance = instance.Elem() |
| 90 | } |
| 91 | |
| 92 | schemaInfo := st.rs.resolvedInfos[schema] |
| 93 | |
| 94 | // type: https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.1.1 |
| 95 | if schema.Type != "" || schema.Types != nil { |
| 96 | gotType, ok := jsonType(instance) |
| 97 | if !ok { |
| 98 | return fmt.Errorf("type: %v of type %[1]T is not a valid JSON value", instance) |
| 99 | } |
| 100 | if schema.Type != "" { |
| 101 | // "number" subsumes integers |
| 102 | if !(gotType == schema.Type || |
| 103 | gotType == "integer" && schema.Type == "number") { |
| 104 | return fmt.Errorf("type: %v has type %q, want %q", instance, gotType, schema.Type) |
| 105 | } |
| 106 | } else { |
| 107 | if !(slices.Contains(schema.Types, gotType) || (gotType == "integer" && slices.Contains(schema.Types, "number"))) { |
| 108 | return fmt.Errorf("type: %v has type %q, want one of %q", |
| 109 | instance, gotType, strings.Join(schema.Types, ", ")) |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | // enum: https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.1.2 |
| 114 | if schema.Enum != nil { |
| 115 | ok := false |
| 116 | for _, e := range schema.Enum { |
| 117 | if equalValue(reflect.ValueOf(e), instance) { |
| 118 | ok = true |
| 119 | break |
| 120 | } |
| 121 | } |
| 122 | if !ok { |
| 123 | return fmt.Errorf("enum: %v does not equal any of: %v", instance, schema.Enum) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // const: https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.1.3 |
| 128 | if schema.Const != nil { |
| 129 | if !equalValue(reflect.ValueOf(*schema.Const), instance) { |
| 130 | return fmt.Errorf("const: %v does not equal %v", instance, *schema.Const) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // numbers: https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.2 |
| 135 | if schema.MultipleOf != nil || schema.Minimum != nil || schema.Maximum != nil || schema.ExclusiveMinimum != nil || schema.ExclusiveMaximum != nil { |
| 136 | n, ok := jsonNumber(instance) |
| 137 | if ok { // these keywords don't apply to non-numbers |
| 138 | if schema.MultipleOf != nil { |
| 139 | // TODO: validate MultipleOf as non-zero. |
| 140 | // The test suite assumes floats. |
| 141 | nf, _ := n.Float64() // don't care if it's exact or not |
| 142 | if _, f := math.Modf(nf / *schema.MultipleOf); f != 0 { |
| 143 | return fmt.Errorf("multipleOf: %s is not a multiple of %f", n, *schema.MultipleOf) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | m := new(big.Rat) // reuse for all of the following |
| 148 | cmp := func(f float64) int { return n.Cmp(m.SetFloat64(f)) } |
| 149 | |
| 150 | if schema.Minimum != nil && cmp(*schema.Minimum) < 0 { |
| 151 | return fmt.Errorf("minimum: %s is less than %f", n, *schema.Minimum) |
| 152 | } |
| 153 | if schema.Maximum != nil && cmp(*schema.Maximum) > 0 { |
| 154 | return fmt.Errorf("maximum: %s is greater than %f", n, *schema.Maximum) |
| 155 | } |
| 156 | if schema.ExclusiveMinimum != nil && cmp(*schema.ExclusiveMinimum) <= 0 { |
| 157 | return fmt.Errorf("exclusiveMinimum: %s is less than or equal to %f", n, *schema.ExclusiveMinimum) |
| 158 | } |
| 159 | if schema.ExclusiveMaximum != nil && cmp(*schema.ExclusiveMaximum) >= 0 { |
| 160 | return fmt.Errorf("exclusiveMaximum: %s is greater than or equal to %f", n, *schema.ExclusiveMaximum) |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // strings: https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.3 |
| 166 | if instance.Kind() == reflect.String && (schema.MinLength != nil || schema.MaxLength != nil || schema.Pattern != "") { |
| 167 | str := instance.String() |
| 168 | n := utf8.RuneCountInString(str) |
| 169 | if schema.MinLength != nil { |
| 170 | if m := *schema.MinLength; n < m { |
| 171 | return fmt.Errorf("minLength: %q contains %d Unicode code points, fewer than %d", str, n, m) |
| 172 | } |
| 173 | } |
| 174 | if schema.MaxLength != nil { |
| 175 | if m := *schema.MaxLength; n > m { |
| 176 | return fmt.Errorf("maxLength: %q contains %d Unicode code points, more than %d", str, n, m) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | if schema.Pattern != "" && !schemaInfo.pattern.MatchString(str) { |
| 181 | return fmt.Errorf("pattern: %q does not match regular expression %q", str, schema.Pattern) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | var anns annotations // all the annotations for this call and child calls |
| 186 | |
| 187 | // $ref: https://json-schema.org/draft/2020-12/json-schema-core#section-8.2.3.1 |
| 188 | if schema.Ref != "" { |
| 189 | if err := st.validate(instance, schemaInfo.resolvedRef, &anns); err != nil { |
| 190 | return err |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // $dynamicRef: https://json-schema.org/draft/2020-12/json-schema-core#section-8.2.3.2 |
| 195 | if schema.DynamicRef != "" { |
| 196 | // The ref behaves lexically or dynamically, but not both. |
| 197 | assert((schemaInfo.resolvedDynamicRef == nil) != (schemaInfo.dynamicRefAnchor == ""), |
| 198 | "DynamicRef not resolved properly") |
| 199 | if schemaInfo.resolvedDynamicRef != nil { |
| 200 | // Same as $ref. |
| 201 | if err := st.validate(instance, schemaInfo.resolvedDynamicRef, &anns); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | } else { |
| 205 | // Dynamic behavior. |
| 206 | // Look for the base of the outermost schema on the stack with this dynamic |
| 207 | // anchor. (Yes, outermost: the one farthest from here. This the opposite |
| 208 | // of how ordinary dynamic variables behave.) |
| 209 | // Why the base of the schema being validated and not the schema itself? |
| 210 | // Because the base is the scope for anchors. In fact it's possible to |
| 211 | // refer to a schema that is not on the stack, but a child of some base |
| 212 | // on the stack. |
| 213 | // For an example, search for "detached" in testdata/draft2020-12/dynamicRef.json. |
| 214 | var dynamicSchema *Schema |
| 215 | for _, s := range st.stack { |
| 216 | base := st.rs.resolvedInfos[s].base |
| 217 | info, ok := st.rs.resolvedInfos[base].anchors[schemaInfo.dynamicRefAnchor] |
| 218 | if ok && info.dynamic { |
| 219 | dynamicSchema = info.schema |
| 220 | break |
| 221 | } |
| 222 | } |
| 223 | if dynamicSchema == nil { |
| 224 | return fmt.Errorf("missing dynamic anchor %q", schemaInfo.dynamicRefAnchor) |
| 225 | } |
| 226 | if err := st.validate(instance, dynamicSchema, &anns); err != nil { |
| 227 | return err |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // logic |
| 233 | // https://json-schema.org/draft/2020-12/json-schema-core#section-10.2 |
| 234 | // These must happen before arrays and objects because if they evaluate an item or property, |
| 235 | // then the unevaluatedItems/Properties schemas don't apply to it. |
| 236 | // See https://json-schema.org/draft/2020-12/json-schema-core#section-11.2, paragraph 4. |
| 237 | // |
| 238 | // If any of these fail, then validation fails, even if there is an unevaluatedXXX |
| 239 | // keyword in the schema. The spec is unclear about this, but that is the intention. |
| 240 | |
| 241 | valid := func(s *Schema, anns *annotations) bool { return st.validate(instance, s, anns) == nil } |
| 242 | |
| 243 | if schema.AllOf != nil { |
| 244 | for _, ss := range schema.AllOf { |
| 245 | if err := st.validate(instance, ss, &anns); err != nil { |
| 246 | return err |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | if schema.AnyOf != nil { |
| 251 | // We must visit them all, to collect annotations. |
| 252 | ok := false |
| 253 | for _, ss := range schema.AnyOf { |
| 254 | if valid(ss, &anns) { |
| 255 | ok = true |
| 256 | } |
| 257 | } |
| 258 | if !ok { |
| 259 | return fmt.Errorf("anyOf: did not validate against any of %v", schema.AnyOf) |
| 260 | } |
| 261 | } |
| 262 | if schema.OneOf != nil { |
| 263 | // Exactly one. |
| 264 | var okSchema *Schema |
| 265 | for _, ss := range schema.OneOf { |
| 266 | if valid(ss, &anns) { |
| 267 | if okSchema != nil { |
| 268 | return fmt.Errorf("oneOf: validated against both %v and %v", okSchema, ss) |
| 269 | } |
| 270 | okSchema = ss |
| 271 | } |
| 272 | } |
| 273 | if okSchema == nil { |
| 274 | return fmt.Errorf("oneOf: did not validate against any of %v", schema.OneOf) |
| 275 | } |
| 276 | } |
| 277 | if schema.Not != nil { |
| 278 | // Ignore annotations from "not". |
| 279 | if valid(schema.Not, nil) { |
| 280 | return fmt.Errorf("not: validated against %v", schema.Not) |
| 281 | } |
| 282 | } |
| 283 | if schema.If != nil { |
| 284 | var ss *Schema |
| 285 | if valid(schema.If, &anns) { |
| 286 | ss = schema.Then |
| 287 | } else { |
| 288 | ss = schema.Else |
| 289 | } |
| 290 | if ss != nil { |
| 291 | if err := st.validate(instance, ss, &anns); err != nil { |
| 292 | return err |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // arrays |
| 298 | // TODO(jba): consider arrays of structs. |
| 299 | if instance.Kind() == reflect.Array || instance.Kind() == reflect.Slice { |
| 300 | // https://json-schema.org/draft/2020-12/json-schema-core#section-10.3.1 |
| 301 | // This validate call doesn't collect annotations for the items of the instance; they are separate |
| 302 | // instances in their own right. |
| 303 | // TODO(jba): if the test suite doesn't cover this case, add a test. For example, nested arrays. |
| 304 | for i, ischema := range schema.PrefixItems { |
| 305 | if i >= instance.Len() { |
| 306 | break // shorter is OK |
| 307 | } |
| 308 | if err := st.validate(instance.Index(i), ischema, nil); err != nil { |
| 309 | return err |
| 310 | } |
| 311 | } |
| 312 | anns.noteEndIndex(min(len(schema.PrefixItems), instance.Len())) |
| 313 | |
| 314 | if schema.Items != nil { |
| 315 | for i := len(schema.PrefixItems); i < instance.Len(); i++ { |
| 316 | if err := st.validate(instance.Index(i), schema.Items, nil); err != nil { |
| 317 | return err |
| 318 | } |
| 319 | } |
| 320 | // Note that all the items in this array have been validated. |
| 321 | anns.allItems = true |
| 322 | } |
| 323 | |
| 324 | nContains := 0 |
| 325 | if schema.Contains != nil { |
| 326 | for i := range instance.Len() { |
| 327 | if err := st.validate(instance.Index(i), schema.Contains, nil); err == nil { |
| 328 | nContains++ |
| 329 | anns.noteIndex(i) |
| 330 | } |
| 331 | } |
| 332 | if nContains == 0 && (schema.MinContains == nil || *schema.MinContains > 0) { |
| 333 | return fmt.Errorf("contains: %s does not have an item matching %s", instance, schema.Contains) |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.4 |
| 338 | // TODO(jba): check that these next four keywords' values are integers. |
| 339 | if schema.MinContains != nil && schema.Contains != nil { |
| 340 | if m := *schema.MinContains; nContains < m { |
| 341 | return fmt.Errorf("minContains: contains validated %d items, less than %d", nContains, m) |
| 342 | } |
| 343 | } |
| 344 | if schema.MaxContains != nil && schema.Contains != nil { |
| 345 | if m := *schema.MaxContains; nContains > m { |
| 346 | return fmt.Errorf("maxContains: contains validated %d items, greater than %d", nContains, m) |
| 347 | } |
| 348 | } |
| 349 | if schema.MinItems != nil { |
| 350 | if m := *schema.MinItems; instance.Len() < m { |
| 351 | return fmt.Errorf("minItems: array length %d is less than %d", instance.Len(), m) |
| 352 | } |
| 353 | } |
| 354 | if schema.MaxItems != nil { |
| 355 | if m := *schema.MaxItems; instance.Len() > m { |
| 356 | return fmt.Errorf("maxItems: array length %d is greater than %d", instance.Len(), m) |
| 357 | } |
| 358 | } |
| 359 | if schema.UniqueItems { |
| 360 | if instance.Len() > 1 { |
| 361 | // Hash each item and compare the hashes. |
| 362 | // If two hashes differ, the items differ. |
| 363 | // If two hashes are the same, compare the collisions for equality. |
| 364 | // (The same logic as hash table lookup.) |
| 365 | // TODO(jba): Use container/hash.Map when it becomes available (https://go.dev/issue/69559), |
| 366 | hashes := map[uint64][]int{} // from hash to indices |
| 367 | seed := maphash.MakeSeed() |
| 368 | for i := range instance.Len() { |
| 369 | item := instance.Index(i) |
| 370 | var h maphash.Hash |
| 371 | h.SetSeed(seed) |
| 372 | hashValue(&h, item) |
| 373 | hv := h.Sum64() |
| 374 | if sames := hashes[hv]; len(sames) > 0 { |
| 375 | for _, j := range sames { |
| 376 | if equalValue(item, instance.Index(j)) { |
| 377 | return fmt.Errorf("uniqueItems: array items %d and %d are equal", i, j) |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | hashes[hv] = append(hashes[hv], i) |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | // https://json-schema.org/draft/2020-12/json-schema-core#section-11.2 |
| 387 | if schema.UnevaluatedItems != nil && !anns.allItems { |
| 388 | // Apply this subschema to all items in the array that haven't been successfully validated. |
| 389 | // That includes validations by subschemas on the same instance, like allOf. |
| 390 | for i := anns.endIndex; i < instance.Len(); i++ { |
| 391 | if !anns.evaluatedIndexes[i] { |
| 392 | if err := st.validate(instance.Index(i), schema.UnevaluatedItems, nil); err != nil { |
| 393 | return err |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | anns.allItems = true |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // objects |
| 402 | // https://json-schema.org/draft/2020-12/json-schema-core#section-10.3.2 |
| 403 | // Validating structs is problematic. See https://github.com/google/jsonschema-go/issues/23. |
| 404 | if instance.Kind() == reflect.Struct { |
| 405 | return errors.New("cannot validate against a struct; see https://github.com/google/jsonschema-go/issues/23 for details") |
| 406 | } |
| 407 | if instance.Kind() == reflect.Map { |
| 408 | if kt := instance.Type().Key(); kt.Kind() != reflect.String { |
| 409 | return fmt.Errorf("map key type %s is not a string", kt) |
| 410 | } |
| 411 | // Track the evaluated properties for just this schema, to support additionalProperties. |
| 412 | // If we used anns here, then we'd be including properties evaluated in subschemas |
| 413 | // from allOf, etc., which additionalProperties shouldn't observe. |
| 414 | evalProps := map[string]bool{} |
| 415 | for prop, subschema := range schema.Properties { |
| 416 | val := property(instance, prop) |
| 417 | if !val.IsValid() { |
| 418 | // It's OK if the instance doesn't have the property. |
| 419 | continue |
| 420 | } |
| 421 | // If the instance is a struct and an optional property has the zero |
| 422 | // value, then we could interpret it as present or missing. Be generous: |
| 423 | // assume it's missing, and thus always validates successfully. |
| 424 | if instance.Kind() == reflect.Struct && val.IsZero() && !schemaInfo.isRequired[prop] { |
| 425 | continue |
| 426 | } |
| 427 | if err := st.validate(val, subschema, nil); err != nil { |
| 428 | return err |
| 429 | } |
| 430 | evalProps[prop] = true |
| 431 | } |
| 432 | if len(schema.PatternProperties) > 0 { |
| 433 | for prop, val := range properties(instance) { |
| 434 | // Check every matching pattern. |
| 435 | for re, schema := range schemaInfo.patternProperties { |
| 436 | if re.MatchString(prop) { |
| 437 | if err := st.validate(val, schema, nil); err != nil { |
| 438 | return err |
| 439 | } |
| 440 | evalProps[prop] = true |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | if schema.AdditionalProperties != nil { |
| 446 | // Special case for a better error message when additional properties is |
| 447 | // 'falsy' |
| 448 | // |
| 449 | // If additionalProperties is {"not":{}} (which is how we |
| 450 | // unmarshal "false"), we can produce a better error message that |
| 451 | // summarizes all the extra properties. Otherwise, we fall back to the |
| 452 | // default validation. |
| 453 | // |
| 454 | // Note: this is much faster than comparing with falseSchema using Equal. |
| 455 | isFalsy := schema.AdditionalProperties.Not != nil && reflect.ValueOf(*schema.AdditionalProperties.Not).IsZero() |
| 456 | if isFalsy { |
| 457 | var disallowed []string |
| 458 | for prop := range properties(instance) { |
| 459 | if !evalProps[prop] { |
| 460 | disallowed = append(disallowed, prop) |
| 461 | } |
| 462 | } |
| 463 | if len(disallowed) > 0 { |
| 464 | return fmt.Errorf("unexpected additional properties %q", disallowed) |
| 465 | } |
| 466 | } else { |
| 467 | // Apply to all properties not handled above. |
| 468 | for prop, val := range properties(instance) { |
| 469 | if !evalProps[prop] { |
| 470 | if err := st.validate(val, schema.AdditionalProperties, nil); err != nil { |
| 471 | return err |
| 472 | } |
| 473 | evalProps[prop] = true |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | anns.noteProperties(evalProps) |
| 479 | if schema.PropertyNames != nil { |
| 480 | // Note: properties unnecessarily fetches each value. We could define a propertyNames function |
| 481 | // if performance ever matters. |
| 482 | for prop := range properties(instance) { |
| 483 | if err := st.validate(reflect.ValueOf(prop), schema.PropertyNames, nil); err != nil { |
| 484 | return err |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.5 |
| 490 | var min, max int |
| 491 | if schema.MinProperties != nil || schema.MaxProperties != nil { |
| 492 | min, max = numPropertiesBounds(instance, schemaInfo.isRequired) |
| 493 | } |
| 494 | if schema.MinProperties != nil { |
| 495 | if n, m := max, *schema.MinProperties; n < m { |
| 496 | return fmt.Errorf("minProperties: object has %d properties, less than %d", n, m) |
| 497 | } |
| 498 | } |
| 499 | if schema.MaxProperties != nil { |
| 500 | if n, m := min, *schema.MaxProperties; n > m { |
| 501 | return fmt.Errorf("maxProperties: object has %d properties, greater than %d", n, m) |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | hasProperty := func(prop string) bool { |
| 506 | return property(instance, prop).IsValid() |
| 507 | } |
| 508 | |
| 509 | missingProperties := func(props []string) []string { |
| 510 | var missing []string |
| 511 | for _, p := range props { |
| 512 | if !hasProperty(p) { |
| 513 | missing = append(missing, p) |
| 514 | } |
| 515 | } |
| 516 | return missing |
| 517 | } |
| 518 | |
| 519 | if schema.Required != nil { |
| 520 | if m := missingProperties(schema.Required); len(m) > 0 { |
| 521 | return fmt.Errorf("required: missing properties: %q", m) |
| 522 | } |
| 523 | } |
| 524 | if schema.DependentRequired != nil { |
| 525 | // "Validation succeeds if, for each name that appears in both the instance |
| 526 | // and as a name within this keyword's value, every item in the corresponding |
| 527 | // array is also the name of a property in the instance." §6.5.4 |
| 528 | for dprop, reqs := range schema.DependentRequired { |
| 529 | if hasProperty(dprop) { |
| 530 | if m := missingProperties(reqs); len(m) > 0 { |
| 531 | return fmt.Errorf("dependentRequired[%q]: missing properties %q", dprop, m) |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | // https://json-schema.org/draft/2020-12/json-schema-core#section-10.2.2.4 |
| 538 | if schema.DependentSchemas != nil { |
| 539 | // This does not collect annotations, although it seems like it should. |
| 540 | for dprop, ss := range schema.DependentSchemas { |
| 541 | if hasProperty(dprop) { |
| 542 | // TODO: include dependentSchemas[dprop] in the errors. |
| 543 | err := st.validate(instance, ss, &anns) |
| 544 | if err != nil { |
| 545 | return err |
| 546 | } |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | if schema.UnevaluatedProperties != nil && !anns.allProperties { |
| 551 | // This looks a lot like AdditionalProperties, but depends on in-place keywords like allOf |
| 552 | // in addition to sibling keywords. |
| 553 | for prop, val := range properties(instance) { |
| 554 | if !anns.evaluatedProperties[prop] { |
| 555 | if err := st.validate(val, schema.UnevaluatedProperties, nil); err != nil { |
| 556 | return err |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | // The spec says the annotation should be the set of evaluated properties, but we can optimize |
| 561 | // by setting a single boolean, since after this succeeds all properties will be validated. |
| 562 | // See https://json-schema.slack.com/archives/CT7FF623C/p1745592564381459. |
| 563 | anns.allProperties = true |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | if callerAnns != nil { |
| 568 | // Our caller wants to know what we've validated. |
| 569 | callerAnns.merge(&anns) |
| 570 | } |
| 571 | return nil |
| 572 | } |
| 573 | |
| 574 | // resolveDynamicRef returns the schema referred to by the argument schema's |
| 575 | // $dynamicRef value. |
| 576 | // It returns an error if the dynamic reference has no referent. |
| 577 | // If there is no $dynamicRef, resolveDynamicRef returns nil, nil. |
| 578 | // See https://json-schema.org/draft/2020-12/json-schema-core#section-8.2.3.2. |
| 579 | func (st *state) resolveDynamicRef(schema *Schema) (*Schema, error) { |
| 580 | if schema.DynamicRef == "" { |
| 581 | return nil, nil |
| 582 | } |
| 583 | info := st.rs.resolvedInfos[schema] |
| 584 | // The ref behaves lexically or dynamically, but not both. |
| 585 | assert((info.resolvedDynamicRef == nil) != (info.dynamicRefAnchor == ""), |
| 586 | "DynamicRef not statically resolved properly") |
| 587 | if r := info.resolvedDynamicRef; r != nil { |
| 588 | // Same as $ref. |
| 589 | return r, nil |
| 590 | } |
| 591 | // Dynamic behavior. |
| 592 | // Look for the base of the outermost schema on the stack with this dynamic |
| 593 | // anchor. (Yes, outermost: the one farthest from here. This the opposite |
| 594 | // of how ordinary dynamic variables behave.) |
| 595 | // Why the base of the schema being validated and not the schema itself? |
| 596 | // Because the base is the scope for anchors. In fact it's possible to |
| 597 | // refer to a schema that is not on the stack, but a child of some base |
| 598 | // on the stack. |
| 599 | // For an example, search for "detached" in testdata/draft2020-12/dynamicRef.json. |
| 600 | for _, s := range st.stack { |
| 601 | base := st.rs.resolvedInfos[s].base |
| 602 | info, ok := st.rs.resolvedInfos[base].anchors[info.dynamicRefAnchor] |
| 603 | if ok && info.dynamic { |
| 604 | return info.schema, nil |
| 605 | } |
| 606 | } |
| 607 | return nil, fmt.Errorf("missing dynamic anchor %q", info.dynamicRefAnchor) |
| 608 | } |
| 609 | |
| 610 | // ApplyDefaults modifies an instance by applying the schema's defaults to it. If |
| 611 | // a schema or sub-schema has a default, then a corresponding zero instance value |
| 612 | // is set to the default. |
| 613 | // |
| 614 | // The JSON Schema specification does not describe how defaults should be interpreted. |
| 615 | // This method honors defaults only on properties, and only those that are not required. |
| 616 | // If the instance is a map and the property is missing, the property is added to |
| 617 | // the map with the default. |
| 618 | // If the instance is a struct, the field corresponding to the property exists, and |
| 619 | // its value is zero, the field is set to the default. |
| 620 | // ApplyDefaults can panic if a default cannot be assigned to a field. |
| 621 | // |
| 622 | // The argument must be a pointer to the instance. |
| 623 | // (In case we decide that top-level defaults are meaningful.) |
| 624 | // |
| 625 | // It is recommended to first call Resolve with a ValidateDefaults option of true, |
| 626 | // then call this method, and lastly call Validate. |
| 627 | func (rs *Resolved) ApplyDefaults(instancep any) error { |
| 628 | // TODO(jba): consider what defaults on top-level or array instances might mean. |
| 629 | // TODO(jba): follow $ref and $dynamicRef |
| 630 | // TODO(jba): apply defaults on sub-schemas to corresponding sub-instances. |
| 631 | st := &state{rs: rs} |
| 632 | return st.applyDefaults(reflect.ValueOf(instancep), rs.root) |
| 633 | } |
| 634 | |
| 635 | // Leave this as a potentially recursive helper function, because we'll surely want |
| 636 | // to apply defaults on sub-schemas someday. |
| 637 | func (st *state) applyDefaults(instancep reflect.Value, schema *Schema) (err error) { |
| 638 | defer wrapf(&err, "applyDefaults: schema %s, instance %v", st.rs.schemaString(schema), instancep) |
| 639 | |
| 640 | schemaInfo := st.rs.resolvedInfos[schema] |
| 641 | instance := instancep.Elem() |
| 642 | if instance.Kind() == reflect.Interface && instance.IsValid() { |
| 643 | // If we unmarshalled into 'any', the default object unmarshalling will be map[string]any. |
| 644 | instance = instance.Elem() |
| 645 | } |
| 646 | if instance.Kind() == reflect.Map || instance.Kind() == reflect.Struct { |
| 647 | if instance.Kind() == reflect.Map { |
| 648 | if kt := instance.Type().Key(); kt.Kind() != reflect.String { |
| 649 | return fmt.Errorf("map key type %s is not a string", kt) |
| 650 | } |
| 651 | } |
| 652 | for prop, subschema := range schema.Properties { |
| 653 | // Ignore defaults on required properties. (A required property shouldn't have a default.) |
| 654 | if schemaInfo.isRequired[prop] { |
| 655 | continue |
| 656 | } |
| 657 | val := property(instance, prop) |
| 658 | switch instance.Kind() { |
| 659 | case reflect.Map: |
| 660 | // If there is a default for this property, and the map key is missing, |
| 661 | // set the map value to the default. |
| 662 | if subschema.Default != nil && !val.IsValid() { |
| 663 | // Create an lvalue, since map values aren't addressable. |
| 664 | lvalue := reflect.New(instance.Type().Elem()) |
| 665 | if err := json.Unmarshal(subschema.Default, lvalue.Interface()); err != nil { |
| 666 | return err |
| 667 | } |
| 668 | instance.SetMapIndex(reflect.ValueOf(prop), lvalue.Elem()) |
| 669 | } |
| 670 | case reflect.Struct: |
| 671 | // If there is a default for this property, and the field exists but is zero, |
| 672 | // set the field to the default. |
| 673 | if subschema.Default != nil && val.IsValid() && val.IsZero() { |
| 674 | if err := json.Unmarshal(subschema.Default, val.Addr().Interface()); err != nil { |
| 675 | return err |
| 676 | } |
| 677 | } |
| 678 | default: |
| 679 | panic(fmt.Sprintf("applyDefaults: property %s: bad value %s of kind %s", |
| 680 | prop, instance, instance.Kind())) |
| 681 | } |
| 682 | } |
| 683 | } |
| 684 | return nil |
| 685 | } |
| 686 | |
| 687 | // property returns the value of the property of v with the given name, or the invalid |
| 688 | // reflect.Value if there is none. |
| 689 | // If v is a map, the property is the value of the map whose key is name. |
| 690 | // If v is a struct, the property is the value of the field with the given name according |
| 691 | // to the encoding/json package (see [jsonName]). |
| 692 | // If v is anything else, property panics. |
| 693 | func property(v reflect.Value, name string) reflect.Value { |
| 694 | switch v.Kind() { |
| 695 | case reflect.Map: |
| 696 | return v.MapIndex(reflect.ValueOf(name)) |
| 697 | case reflect.Struct: |
| 698 | props := structPropertiesOf(v.Type()) |
| 699 | // Ignore nonexistent properties. |
| 700 | if sf, ok := props[name]; ok { |
| 701 | return v.FieldByIndex(sf.Index) |
| 702 | } |
| 703 | return reflect.Value{} |
| 704 | default: |
| 705 | panic(fmt.Sprintf("property(%q): bad value %s of kind %s", name, v, v.Kind())) |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | // properties returns an iterator over the names and values of all properties |
| 710 | // in v, which must be a map or a struct. |
| 711 | // If a struct, zero-valued properties that are marked omitempty or omitzero |
| 712 | // are excluded. |
| 713 | func properties(v reflect.Value) iter.Seq2[string, reflect.Value] { |
| 714 | return func(yield func(string, reflect.Value) bool) { |
| 715 | switch v.Kind() { |
| 716 | case reflect.Map: |
| 717 | for k, e := range v.Seq2() { |
| 718 | if !yield(k.String(), e) { |
| 719 | return |
| 720 | } |
| 721 | } |
| 722 | case reflect.Struct: |
| 723 | for name, sf := range structPropertiesOf(v.Type()) { |
| 724 | val := v.FieldByIndex(sf.Index) |
| 725 | if val.IsZero() { |
| 726 | info := fieldJSONInfo(sf) |
| 727 | if info.settings["omitempty"] || info.settings["omitzero"] { |
| 728 | continue |
| 729 | } |
| 730 | } |
| 731 | if !yield(name, val) { |
| 732 | return |
| 733 | } |
| 734 | } |
| 735 | default: |
| 736 | panic(fmt.Sprintf("bad value %s of kind %s", v, v.Kind())) |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | // numPropertiesBounds returns bounds on the number of v's properties. |
| 742 | // v must be a map or a struct. |
| 743 | // If v is a map, both bounds are the map's size. |
| 744 | // If v is a struct, the max is the number of struct properties. |
| 745 | // But since we don't know whether a zero value indicates a missing optional property |
| 746 | // or not, be generous and use the number of non-zero properties as the min. |
| 747 | func numPropertiesBounds(v reflect.Value, isRequired map[string]bool) (int, int) { |
| 748 | switch v.Kind() { |
| 749 | case reflect.Map: |
| 750 | return v.Len(), v.Len() |
| 751 | case reflect.Struct: |
| 752 | sp := structPropertiesOf(v.Type()) |
| 753 | min := 0 |
| 754 | for prop, sf := range sp { |
| 755 | if !v.FieldByIndex(sf.Index).IsZero() || isRequired[prop] { |
| 756 | min++ |
| 757 | } |
| 758 | } |
| 759 | return min, len(sp) |
| 760 | default: |
| 761 | panic(fmt.Sprintf("properties: bad value: %s of kind %s", v, v.Kind())) |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | // A propertyMap is a map from property name to struct field index. |
| 766 | type propertyMap = map[string]reflect.StructField |
| 767 | |
| 768 | var structProperties sync.Map // from reflect.Type to propertyMap |
| 769 | |
| 770 | // structPropertiesOf returns the JSON Schema properties for the struct type t. |
| 771 | // The caller must not mutate the result. |
| 772 | func structPropertiesOf(t reflect.Type) propertyMap { |
| 773 | // Mutex not necessary: at worst we'll recompute the same value. |
| 774 | if props, ok := structProperties.Load(t); ok { |
| 775 | return props.(propertyMap) |
| 776 | } |
| 777 | props := map[string]reflect.StructField{} |
| 778 | for _, sf := range reflect.VisibleFields(t) { |
| 779 | if sf.Anonymous { |
| 780 | continue |
| 781 | } |
| 782 | info := fieldJSONInfo(sf) |
| 783 | if !info.omit { |
| 784 | props[info.name] = sf |
| 785 | } |
| 786 | } |
| 787 | structProperties.Store(t, props) |
| 788 | return props |
| 789 | } |