Debian Codegraph @

debian/go/src/github.com/google/jsonschema-go/jsonschema/resolve.go

raw symbols SCIP
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 // This file deals with preparing a schema for validation, including various checks,
6 // optimizations, and the resolution of cross-schema references.
7
8 package jsonschema
9
10 import (
11 "errors"
12 "fmt"
13 "net/url"
14 "reflect"
15 "regexp"
16 "strings"
17 )
18
19 // A Resolved consists of a [Schema] along with associated information needed to
20 // validate documents against it.
21 // A Resolved has been validated against its meta-schema, and all its references
22 // (the $ref and $dynamicRef keywords) have been resolved to their referenced Schemas.
23 // Call [Schema.Resolve] to obtain a Resolved from a Schema.
24 type Resolved struct {
25 root *Schema
26 // map from $ids to their schemas
27 resolvedURIs map[string]*Schema
28 // map from schemas to additional info computed during resolution
29 resolvedInfos map[*Schema]*resolvedInfo
30 }
31
32 func newResolved(s *Schema) *Resolved {
33 return &Resolved{
34 root: s,
35 resolvedURIs: map[string]*Schema{},
36 resolvedInfos: map[*Schema]*resolvedInfo{},
37 }
38 }
39
40 // resolvedInfo holds information specific to a schema that is computed by [Schema.Resolve].
41 type resolvedInfo struct {
42 s *Schema
43 // The JSON Pointer path from the root schema to here.
44 // Used in errors.
45 path string
46 // The schema's base schema.
47 // If the schema is the root or has an ID, its base is itself.
48 // Otherwise, its base is the innermost enclosing schema whose base
49 // is itself.
50 // Intuitively, a base schema is one that can be referred to with a
51 // fragmentless URI.
52 base *Schema
53 // The URI for the schema, if it is the root or has an ID.
54 // Otherwise nil.
55 // Invariants:
56 // s.base.uri != nil.
57 // s.base == s <=> s.uri != nil
58 uri *url.URL
59 // The schema to which Ref refers.
60 resolvedRef *Schema
61
62 // If the schema has a dynamic ref, exactly one of the next two fields
63 // will be non-zero after successful resolution.
64 // The schema to which the dynamic ref refers when it acts lexically.
65 resolvedDynamicRef *Schema
66 // The anchor to look up on the stack when the dynamic ref acts dynamically.
67 dynamicRefAnchor string
68
69 // The following fields are independent of arguments to Schema.Resolved,
70 // so they could live on the Schema. We put them here for simplicity.
71
72 // The set of required properties.
73 isRequired map[string]bool
74
75 // Compiled regexps.
76 pattern *regexp.Regexp
77 patternProperties map[*regexp.Regexp]*Schema
78
79 // Map from anchors to subschemas.
80 anchors map[string]anchorInfo
81 }
82
83 // Schema returns the schema that was resolved.
84 // It must not be modified.
85 func (r *Resolved) Schema() *Schema { return r.root }
86
87 // schemaString returns a short string describing the schema.
88 func (r *Resolved) schemaString(s *Schema) string {
89 if s.ID != "" {
90 return s.ID
91 }
92 info := r.resolvedInfos[s]
93 if info.path != "" {
94 return info.path
95 }
96 return "<anonymous schema>"
97 }
98
99 // A Loader reads and unmarshals the schema at uri, if any.
100 type Loader func(uri *url.URL) (*Schema, error)
101
102 // ResolveOptions are options for [Schema.Resolve].
103 type ResolveOptions struct {
104 // BaseURI is the URI relative to which the root schema should be resolved.
105 // If non-empty, must be an absolute URI (one that starts with a scheme).
106 // It is resolved (in the URI sense; see [url.ResolveReference]) with root's
107 // $id property.
108 // If the resulting URI is not absolute, then the schema cannot contain
109 // relative URI references.
110 BaseURI string
111 // Loader loads schemas that are referred to by a $ref but are not under the
112 // root schema (remote references).
113 // If nil, resolving a remote reference will return an error.
114 Loader Loader
115 // ValidateDefaults determines whether to validate values of "default" keywords
116 // against their schemas.
117 // The [JSON Schema specification] does not require this, but it is recommended
118 // if defaults will be used.
119 //
120 // [JSON Schema specification]: https://json-schema.org/understanding-json-schema/reference/annotations
121 ValidateDefaults bool
122 }
123
124 // Resolve resolves all references within the schema and performs other tasks that
125 // prepare the schema for validation.
126 // If opts is nil, the default values are used.
127 // The schema must not be changed after Resolve is called.
128 // The same schema may be resolved multiple times.
129 func (root *Schema) Resolve(opts *ResolveOptions) (*Resolved, error) {
130 // There are up to five steps required to prepare a schema to validate.
131 // 1. Load: read the schema from somewhere and unmarshal it.
132 // This schema (root) may have been loaded or created in memory, but other schemas that
133 // come into the picture in step 4 will be loaded by the given loader.
134 // 2. Check: validate the schema against a meta-schema, and perform other well-formedness checks.
135 // Precompute some values along the way.
136 // 3. Resolve URIs: determine the base URI of the root and all its subschemas, and
137 // resolve (in the URI sense) all identifiers and anchors with their bases. This step results
138 // in a map from URIs to schemas within root.
139 // 4. Resolve references: all refs in the schemas are replaced with the schema they refer to.
140 // 5. (Optional.) If opts.ValidateDefaults is true, validate the defaults.
141 r := &resolver{loaded: map[string]*Resolved{}}
142 if opts != nil {
143 r.opts = *opts
144 }
145 var base *url.URL
146 if r.opts.BaseURI == "" {
147 base = &url.URL{} // so we can call ResolveReference on it
148 } else {
149 var err error
150 base, err = url.Parse(r.opts.BaseURI)
151 if err != nil {
152 return nil, fmt.Errorf("parsing base URI: %w", err)
153 }
154 }
155
156 if r.opts.Loader == nil {
157 r.opts.Loader = func(uri *url.URL) (*Schema, error) {
158 return nil, errors.New("cannot resolve remote schemas: no loader passed to Schema.Resolve")
159 }
160 }
161
162 resolved, err := r.resolve(root, base)
163 if err != nil {
164 return nil, err
165 }
166 if r.opts.ValidateDefaults {
167 if err := resolved.validateDefaults(); err != nil {
168 return nil, err
169 }
170 }
171 // TODO: before we return, throw away anything we don't need for validation.
172 return resolved, nil
173 }
174
175 // A resolver holds the state for resolution.
176 type resolver struct {
177 opts ResolveOptions
178 // A cache of loaded and partly resolved schemas. (They may not have had their
179 // refs resolved.) The cache ensures that the loader will never be called more
180 // than once with the same URI, and that reference cycles are handled properly.
181 loaded map[string]*Resolved
182 }
183
184 func (r *resolver) resolve(s *Schema, baseURI *url.URL) (*Resolved, error) {
185 if baseURI.Fragment != "" {
186 return nil, fmt.Errorf("base URI %s must not have a fragment", baseURI)
187 }
188 rs := newResolved(s)
189
190 if err := s.check(rs.resolvedInfos); err != nil {
191 return nil, err
192 }
193
194 if err := resolveURIs(rs, baseURI); err != nil {
195 return nil, err
196 }
197
198 // Remember the schema by both the URI we loaded it from and its canonical name,
199 // which may differ if the schema has an $id.
200 // We must set the map before calling resolveRefs, or ref cycles will cause unbounded recursion.
201 r.loaded[baseURI.String()] = rs
202 r.loaded[rs.resolvedInfos[s].uri.String()] = rs
203
204 if err := r.resolveRefs(rs); err != nil {
205 return nil, err
206 }
207 return rs, nil
208 }
209
210 func (root *Schema) check(infos map[*Schema]*resolvedInfo) error {
211 // Check for structural validity. Do this first and fail fast:
212 // bad structure will cause other code to panic.
213 if err := root.checkStructure(infos); err != nil {
214 return err
215 }
216
217 var errs []error
218 report := func(err error) { errs = append(errs, err) }
219
220 for ss := range root.all() {
221 ss.checkLocal(report, infos)
222 }
223 return errors.Join(errs...)
224 }
225
226 // checkStructure verifies that root and its subschemas form a tree.
227 // It also assigns each schema a unique path, to improve error messages.
228 func (root *Schema) checkStructure(infos map[*Schema]*resolvedInfo) error {
229 assert(len(infos) == 0, "non-empty infos")
230
231 var check func(reflect.Value, []byte) error
232 check = func(v reflect.Value, path []byte) error {
233 // For the purpose of error messages, the root schema has path "root"
234 // and other schemas' paths are their JSON Pointer from the root.
235 p := "root"
236 if len(path) > 0 {
237 p = string(path)
238 }
239 s := v.Interface().(*Schema)
240 if s == nil {
241 return fmt.Errorf("jsonschema: schema at %s is nil", p)
242 }
243 if info, ok := infos[s]; ok {
244 // We've seen s before.
245 // The schema graph at root is not a tree, but it needs to
246 // be because a schema's base must be unique.
247 // A cycle would also put Schema.all into an infinite recursion.
248 return fmt.Errorf("jsonschema: schemas at %s do not form a tree; %s appears more than once (also at %s)",
249 root, info.path, p)
250 }
251 infos[s] = &resolvedInfo{s: s, path: p}
252
253 for _, info := range schemaFieldInfos {
254 fv := v.Elem().FieldByIndex(info.sf.Index)
255 switch info.sf.Type {
256 case schemaType:
257 // A field that contains an individual schema.
258 // A nil is valid: it just means the field isn't present.
259 if !fv.IsNil() {
260 if err := check(fv, fmt.Appendf(path, "/%s", info.jsonName)); err != nil {
261 return err
262 }
263 }
264
265 case schemaSliceType:
266 for i := range fv.Len() {
267 if err := check(fv.Index(i), fmt.Appendf(path, "/%s/%d", info.jsonName, i)); err != nil {
268 return err
269 }
270 }
271
272 case schemaMapType:
273 iter := fv.MapRange()
274 for iter.Next() {
275 key := escapeJSONPointerSegment(iter.Key().String())
276 if err := check(iter.Value(), fmt.Appendf(path, "/%s/%s", info.jsonName, key)); err != nil {
277 return err
278 }
279 }
280 }
281
282 }
283 return nil
284 }
285
286 return check(reflect.ValueOf(root), make([]byte, 0, 256))
287 }
288
289 // checkLocal checks s for validity, independently of other schemas it may refer to.
290 // Since checking a regexp involves compiling it, checkLocal saves those compiled regexps
291 // in the schema for later use.
292 // It appends the errors it finds to errs.
293 func (s *Schema) checkLocal(report func(error), infos map[*Schema]*resolvedInfo) {
294 addf := func(format string, args ...any) {
295 msg := fmt.Sprintf(format, args...)
296 report(fmt.Errorf("jsonschema.Schema: %s: %s", s, msg))
297 }
298
299 if s == nil {
300 addf("nil subschema")
301 return
302 }
303 if err := s.basicChecks(); err != nil {
304 report(err)
305 return
306 }
307
308 // TODO: validate the schema's properties,
309 // ideally by jsonschema-validating it against the meta-schema.
310
311 // Some properties are present so that Schemas can round-trip, but we do not
312 // validate them.
313 // Currently, it's just the $vocabulary property.
314 // As a special case, we can validate the 2020-12 meta-schema.
315 if s.Vocabulary != nil && s.Schema != draft202012 {
316 addf("cannot validate a schema with $vocabulary")
317 }
318
319 info := infos[s]
320
321 // Check and compile regexps.
322 if s.Pattern != "" {
323 re, err := regexp.Compile(s.Pattern)
324 if err != nil {
325 addf("pattern: %v", err)
326 } else {
327 info.pattern = re
328 }
329 }
330 if len(s.PatternProperties) > 0 {
331 info.patternProperties = map[*regexp.Regexp]*Schema{}
332 for reString, subschema := range s.PatternProperties {
333 re, err := regexp.Compile(reString)
334 if err != nil {
335 addf("patternProperties[%q]: %v", reString, err)
336 continue
337 }
338 info.patternProperties[re] = subschema
339 }
340 }
341
342 // Build a set of required properties, to avoid quadratic behavior when validating
343 // a struct.
344 if len(s.Required) > 0 {
345 info.isRequired = map[string]bool{}
346 for _, r := range s.Required {
347 info.isRequired[r] = true
348 }
349 }
350 }
351
352 // resolveURIs resolves the ids and anchors in all the schemas of root, relative
353 // to baseURI.
354 // See https://json-schema.org/draft/2020-12/json-schema-core#section-8.2, section
355 // 8.2.1.
356 //
357 // Every schema has a base URI and a parent base URI.
358 //
359 // The parent base URI is the base URI of the lexically enclosing schema, or for
360 // a root schema, the URI it was loaded from or the one supplied to [Schema.Resolve].
361 //
362 // If the schema has no $id property, the base URI of a schema is that of its parent.
363 // If the schema does have an $id, it must be a URI, possibly relative. The schema's
364 // base URI is the $id resolved (in the sense of [url.URL.ResolveReference]) against
365 // the parent base.
366 //
367 // As an example, consider this schema loaded from http://a.com/root.json (quotes omitted):
368 //
369 // {
370 // allOf: [
371 // {$id: "sub1.json", minLength: 5},
372 // {$id: "http://b.com", minimum: 10},
373 // {not: {maximum: 20}}
374 // ]
375 // }
376 //
377 // The base URIs are as follows. Schema locations are expressed in the JSON Pointer notation.
378 //
379 // schema base URI
380 // root http://a.com/root.json
381 // allOf/0 http://a.com/sub1.json
382 // allOf/1 http://b.com (absolute $id; doesn't matter that it's not under the loaded URI)
383 // allOf/2 http://a.com/root.json (inherited from parent)
384 // allOf/2/not http://a.com/root.json (inherited from parent)
385 func resolveURIs(rs *Resolved, baseURI *url.URL) error {
386 var resolve func(s, base *Schema) error
387 resolve = func(s, base *Schema) error {
388 info := rs.resolvedInfos[s]
389 baseInfo := rs.resolvedInfos[base]
390
391 // ids are scoped to the root.
392 if s.ID != "" {
393 // A non-empty ID establishes a new base.
394 idURI, err := url.Parse(s.ID)
395 if err != nil {
396 return err
397 }
398 if idURI.Fragment != "" {
399 return fmt.Errorf("$id %s must not have a fragment", s.ID)
400 }
401 // The base URI for this schema is its $id resolved against the parent base.
402 info.uri = baseInfo.uri.ResolveReference(idURI)
403 if !info.uri.IsAbs() {
404 return fmt.Errorf("$id %s does not resolve to an absolute URI (base is %q)", s.ID, baseInfo.uri)
405 }
406 rs.resolvedURIs[info.uri.String()] = s
407 base = s // needed for anchors
408 baseInfo = rs.resolvedInfos[base]
409 }
410 info.base = base
411
412 // Anchors and dynamic anchors are URI fragments that are scoped to their base.
413 // We treat them as keys in a map stored within the schema.
414 setAnchor := func(anchor string, dynamic bool) error {
415 if anchor != "" {
416 if _, ok := baseInfo.anchors[anchor]; ok {
417 return fmt.Errorf("duplicate anchor %q in %s", anchor, baseInfo.uri)
418 }
419 if baseInfo.anchors == nil {
420 baseInfo.anchors = map[string]anchorInfo{}
421 }
422 baseInfo.anchors[anchor] = anchorInfo{s, dynamic}
423 }
424 return nil
425 }
426
427 setAnchor(s.Anchor, false)
428 setAnchor(s.DynamicAnchor, true)
429
430 for c := range s.children() {
431 if err := resolve(c, base); err != nil {
432 return err
433 }
434 }
435 return nil
436 }
437
438 // Set the root URI to the base for now. If the root has an $id, this will change.
439 rs.resolvedInfos[rs.root].uri = baseURI
440 // The original base, even if changed, is still a valid way to refer to the root.
441 rs.resolvedURIs[baseURI.String()] = rs.root
442
443 return resolve(rs.root, rs.root)
444 }
445
446 // resolveRefs replaces every ref in the schemas with the schema it refers to.
447 // A reference that doesn't resolve within the schema may refer to some other schema
448 // that needs to be loaded.
449 func (r *resolver) resolveRefs(rs *Resolved) error {
450 for s := range rs.root.all() {
451 info := rs.resolvedInfos[s]
452 if s.Ref != "" {
453 refSchema, _, err := r.resolveRef(rs, s, s.Ref)
454 if err != nil {
455 return err
456 }
457 // Whether or not the anchor referred to by $ref fragment is dynamic,
458 // the ref still treats it lexically.
459 info.resolvedRef = refSchema
460 }
461 if s.DynamicRef != "" {
462 refSchema, frag, err := r.resolveRef(rs, s, s.DynamicRef)
463 if err != nil {
464 return err
465 }
466 if frag != "" {
467 // The dynamic ref's fragment points to a dynamic anchor.
468 // We must resolve the fragment at validation time.
469 info.dynamicRefAnchor = frag
470 } else {
471 // There is no dynamic anchor in the lexically referenced schema,
472 // so the dynamic ref behaves like a lexical ref.
473 info.resolvedDynamicRef = refSchema
474 }
475 }
476 }
477 return nil
478 }
479
480 // resolveRef resolves the reference ref, which is either s.Ref or s.DynamicRef.
481 func (r *resolver) resolveRef(rs *Resolved, s *Schema, ref string) (_ *Schema, dynamicFragment string, err error) {
482 refURI, err := url.Parse(ref)
483 if err != nil {
484 return nil, "", err
485 }
486 // URI-resolve the ref against the current base URI to get a complete URI.
487 base := rs.resolvedInfos[s].base
488 refURI = rs.resolvedInfos[base].uri.ResolveReference(refURI)
489 // The non-fragment part of a ref URI refers to the base URI of some schema.
490 // This part is the same for dynamic refs too: their non-fragment part resolves
491 // lexically.
492 u := *refURI
493 u.Fragment = ""
494 fraglessRefURI := &u
495 // Look it up locally.
496 referencedSchema := rs.resolvedURIs[fraglessRefURI.String()]
497 if referencedSchema == nil {
498 // The schema is remote. Maybe we've already loaded it.
499 // We assume that the non-fragment part of refURI refers to a top-level schema
500 // document. That is, we don't support the case exemplified by
501 // http://foo.com/bar.json/baz, where the document is in bar.json and
502 // the reference points to a subschema within it.
503 // TODO: support that case.
504 if lrs := r.loaded[fraglessRefURI.String()]; lrs != nil {
505 referencedSchema = lrs.root
506 } else {
507 // Try to load the schema.
508 ls, err := r.opts.Loader(fraglessRefURI)
509 if err != nil {
510 return nil, "", fmt.Errorf("loading %s: %w", fraglessRefURI, err)
511 }
512 lrs, err := r.resolve(ls, fraglessRefURI)
513 if err != nil {
514 return nil, "", err
515 }
516 referencedSchema = lrs.root
517 assert(referencedSchema != nil, "nil referenced schema")
518 // Copy the resolvedInfos from lrs into rs, without overwriting
519 // (hence we can't use maps.Insert).
520 for s, i := range lrs.resolvedInfos {
521 if rs.resolvedInfos[s] == nil {
522 rs.resolvedInfos[s] = i
523 }
524 }
525 }
526 }
527
528 frag := refURI.Fragment
529 // Look up frag in refSchema.
530 // frag is either a JSON Pointer or the name of an anchor.
531 // A JSON Pointer is either the empty string or begins with a '/',
532 // whereas anchors are always non-empty strings that don't contain slashes.
533 if frag != "" && !strings.HasPrefix(frag, "/") {
534 resInfo := rs.resolvedInfos[referencedSchema]
535 info, found := resInfo.anchors[frag]
536
537 if !found {
538 return nil, "", fmt.Errorf("no anchor %q in %s", frag, s)
539 }
540 if info.dynamic {
541 dynamicFragment = frag
542 }
543 return info.schema, dynamicFragment, nil
544 }
545 // frag is a JSON Pointer.
546 s, err = dereferenceJSONPointer(referencedSchema, frag)
547 return s, "", err
548 }