Debian Codegraph @

lib/JSON/Schema/Modern/Vocabulary/Core.pm

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern::Vocabulary::Core;
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Implementation of the JSON Schema Core vocabulary
6
7 our $VERSION = '0.650';
8
9 use 5.020;
10 use Moo;
11 use strictures 2;
12 use stable 0.031 'postderef';
13 use experimental 'signatures';
14 no autovivification warn => qw(fetch store exists delete);
15 use if "$]" >= 5.022, experimental => 're_strict';
16 no if "$]" >= 5.031009, feature => 'indirect';
17 no if "$]" >= 5.033001, feature => 'multidimensional';
18 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
19 no if "$]" >= 5.041009, feature => 'smartmatch';
20 no feature 'switch';
21 use JSON::Schema::Modern::Utilities qw(is_type abort assert_keyword_type canonical_uri E assert_uri_reference assert_uri jsonp);
22 use namespace::clean;
23
24 with 'JSON::Schema::Modern::Vocabulary';
25
26 sub vocabulary ($class) {
27 'https://json-schema.org/draft/2019-09/vocab/core' => 'draft2019-09',
28 'https://json-schema.org/draft/2020-12/vocab/core' => 'draft2020-12';
29 }
30
31 sub evaluation_order ($class) { 0 }
32
33 sub keywords ($class, $spec_version) {
34 return (
35 '$schema', # must be first to ensure we use the correct Core keywords and subsequent vocabularies
36 $spec_version eq 'draft4' ? 'id' : '$id',
37 $spec_version !~ /^draft[467]\z/ ? '$anchor' : (),
38 $spec_version eq 'draft2019-09' ? '$recursiveAnchor' : (),
39 $spec_version !~ /^draft(?:[467]|2019-09)\z/ ? '$dynamicAnchor' : (),
40 '$ref',
41 $spec_version eq 'draft2019-09' ? '$recursiveRef' : (),
42 $spec_version !~ /^draft(?:[467]|2019-09)\z/ ? '$dynamicRef' : (),
43 $spec_version !~ /^draft[467]\z/ ? '$vocabulary' : (),
44 $spec_version =~ /^draft[467]\z/ ? 'definitions' : '$defs',
45 $spec_version !~ /^draft[46]\z/ ? '$comment' : (),
46 );
47 }
48
49 # adds the following keys to $state during traversal:
50 # - identifiers: an arrayref of tuples:
51 # $uri => { path => $path_to_identifier, canonical_uri => Mojo::URL (absolute when possible) }
52 # this is used by the Document constructor to build its resource_index.
53
54 sub _traverse_keyword_id ($class, $schema, $state) {
55 return if not assert_keyword_type($state, $schema, 'string')
56 or not assert_uri_reference($state, $schema);
57
58 my $uri = Mojo::URL->new($schema->{$state->{keyword}});
59
60 if (length $uri->fragment) {
61 return E($state, '%s value "%s" cannot have a non-empty fragment', $state->{keyword}, $schema->{$state->{keyword}})
62 if $state->{specification_version} !~ /^draft[467]\z/;
63
64 if (length(my $base = $uri->clone->fragment(undef))) {
65 return E($state, '$id cannot change the base uri at the same time as declaring an anchor')
66 if $state->{specification_version} =~ /^draft[67]\z/;
67
68 # only permitted in draft4: add an id and an anchor via the single 'id' keyword
69 return if not $class->__create_identifier($base, $state);
70 }
71
72 return $class->_traverse_keyword_anchor({ %$schema, id => '#'.$uri->fragment }, $state);
73 }
74
75 return if not $class->__create_identifier($uri, $state);
76 return 1;
77 }
78
79 sub __create_identifier ($class, $uri, $state) {
80 $uri->fragment(undef);
81 return E($state, '%s cannot be empty', $state->{keyword}) if not length $uri;
82
83 $uri = $uri->to_abs($state->{initial_schema_uri}) if not $uri->is_abs;
84
85 return E($state, 'duplicate canonical uri "%s" found (original at path "%s")',
86 $uri, $state->{identifiers}{$uri}{path})
87 if exists $state->{identifiers}{$uri};
88
89 $state->{initial_schema_uri} = $uri;
90 $state->{traversed_keyword_path} = $state->{traversed_keyword_path}.$state->{keyword_path};
91 $state->{keyword_path} = '';
92
93 # Note that since '$schema' is considered ahead of '$id' in the keyword list, the dialect
94 # (specification_version and vocabularies) is known to be correct.
95
96 $state->{identifiers}{$uri} = {
97 path => $state->{traversed_keyword_path},
98 canonical_uri => $uri,
99 $state->%{qw(specification_version vocabularies)},
100 };
101
102 return 1;
103 }
104
105 sub _eval_keyword_id ($class, $, $schema, $state) {
106 # we already indexed the anchor uri, so there is nothing more to do at evaluation time.
107 # we explicitly do NOT set $state->{initial_schema_uri} or change any other $state values.
108 return 1
109 if $state->{specification_version} =~ /^draft[467]\z/ and $schema->{$state->{keyword}} =~ /^#/;
110
111 my $schema_info = $state->{evaluator}->_fetch_from_uri($state->{initial_schema_uri}->clone->fragment($state->{keyword_path}));
112
113 # this should never happen, if the pre-evaluation traversal was performed correctly
114 abort($state, 'failed to resolve "%s" to canonical uri', $state->{keyword}) if not $schema_info;
115
116 # $state->{document} is set by evaluate() and does not change unless following a reference
117 abort($state, 'EXCEPTION: mismatched document when processing %s "%s"',
118 $state->{keyword}, $schema->{$state->{keyword}})
119 if $schema_info->{document} != $state->{document};
120
121 # these will all be set when we are at the document root, or if we are here via a $ref,
122 # but not if we are organically passing through this subschema.
123 $state->{initial_schema_uri} = $schema_info->{canonical_uri};
124 $state->{traversed_keyword_path} = $state->{traversed_keyword_path}.$state->{keyword_path};
125 $state->{keyword_path} = '';
126 $state->@{qw(specification_version vocabularies)} = $schema_info->@{qw(specification_version vocabularies)};
127
128 push $state->{dynamic_scope}->@*, $state->{initial_schema_uri}
129 if $state->{dynamic_scope}->[-1] ne $schema_info->{canonical_uri};
130
131 return 1;
132 }
133
134 sub _traverse_keyword_schema ($class, $schema, $state) {
135 # Note that this sub is sometimes called with $state->{keyword} undefined, in order to change
136 # error locations
137
138 # Note that because this keyword is parsed ahead of "id"/"$id", location information may not
139 # be correct if an error occurs when parsing this keyword.
140 return E($state, '$schema value is not a string') if not is_type('string', $schema->{'$schema'});
141 return if not assert_uri($state, $schema, $schema->{'$schema'});
142
143 my ($spec_version, $vocabularies);
144
145 if (my $metaschema_info = $state->{evaluator}->_get_metaschema_vocabulary_classes($schema->{'$schema'})) {
146 ($spec_version, $vocabularies) = @$metaschema_info;
147 }
148 else {
149 my $schema_info = $state->{evaluator}->_fetch_from_uri($schema->{'$schema'});
150 return E($state, 'EXCEPTION: unable to find resource "%s"', $schema->{'$schema'}) if not $schema_info;
151 # this cannot happen unless there are other entity types in the index
152 return E($state, 'EXCEPTION: bad reference to $schema "%s": not a schema', $schema_info->{canonical_uri})
153 if $schema_info->{document}->get_entity_at_location($schema_info->{document_path}) ne 'schema';
154
155 if (ref $schema_info->{schema} ne 'HASH') {
156 ()= E($state, 'metaschemas must be objects');
157 }
158 else {
159 ($spec_version, $vocabularies) = $state->{evaluator}->_fetch_vocabulary_data({ %$state,
160 keyword => '$vocabulary', initial_schema_uri => Mojo::URL->new($schema->{'$schema'}),
161 traversed_keyword_path => jsonp($state->{traversed_keyword_path}.$state->{keyword_path}, $state->{keyword}//()) },
162 $schema_info);
163 }
164 }
165
166 return E($state, '"%s" is not a valid metaschema', $schema->{'$schema'})
167 if not $vocabularies or not @$vocabularies;
168
169 # "A JSON Schema resource is a schema which is canonically identified by an absolute URI."
170 # "A resource's root schema is its top-level schema object."
171 # note: we need not be at the document root, but simply adjacent to an $id (or be the at the
172 # document root)
173 return E($state, '$schema can only appear at the schema resource root')
174 if not exists $schema->{$spec_version eq 'draft4' ? 'id' : '$id'}
175 and length($state->{keyword_path});
176
177 # This is a bit of a chicken-and-egg situation. If we start off at draft2020-12, then all
178 # keywords are valid, so we inspect and process the $schema keyword; this switches us to draft7
179 # but now only the $ref keyword is respected and everything else should be ignored, so the
180 # $schema keyword never happened, so now we're back to draft2020-12 again, and...?!
181 # The only winning move is not to play.
182 return E($state, '$schema and $ref cannot be used together in older drafts')
183 if exists $schema->{'$ref'} and $spec_version =~ /^draft[467]\z/;
184
185 $state->{evaluator}->_set_metaschema_vocabulary_classes($schema->{'$schema'}, [ $spec_version, $vocabularies ]);
186 $state->@{qw(specification_version vocabularies metaschema_uri)} = ($spec_version, $vocabularies, $schema->{'$schema'} =~ s/#\z//r);
187 return 1;
188 }
189
190 sub _eval_keyword_schema ($class, $, $schema, $state) {
191 # the dialect can change at any time, even in the middle of a document, where subsequent keywords
192 # and vocabularies can change; however if we came to this schema via a $ref it will already be
193 # set correctly
194 $state->@{qw(specification_version vocabularies)} = $state->{evaluator}->_get_metaschema_vocabulary_classes($schema->{'$schema'})->@*;
195 return 1;
196 }
197
198 sub _traverse_keyword_anchor ($class, $schema, $state) {
199 return if not assert_keyword_type($state, $schema, 'string');
200
201 my $anchor = $schema->{$state->{keyword}};
202 return E($state, '%s value "%s" does not match required syntax', $state->{keyword}, $anchor)
203 if $state->{specification_version} =~ /^draft[467]\z/ and $anchor !~ /^#[A-Za-z][A-Za-z0-9_:.-]*\z/
204 or $state->{specification_version} eq 'draft2019-09' and $anchor !~ /^[A-Za-z][A-Za-z0-9_:.-]*\z/
205 or $state->{specification_version} eq 'draft2020-12' and $anchor !~ /^[A-Za-z_][A-Za-z0-9._-]*\z/;
206
207 my $canonical_uri = canonical_uri($state);
208
209 $anchor =~ s/^#// if $state->{specification_version} =~ /^draft[467]\z/;
210 my $uri = Mojo::URL->new->to_abs($canonical_uri)->fragment($anchor);
211 my $base_uri = $canonical_uri->clone->fragment(undef);
212
213 if (exists $state->{identifiers}{$base_uri}) {
214 return E($state, 'duplicate anchor uri "%s" found (original at path "%s")',
215 $uri, $state->{identifiers}{$base_uri}{anchors}{$anchor}{path})
216 if exists(($state->{identifiers}{$base_uri}{anchors}//{})->{$anchor});
217
218 use autovivification 'store';
219 $state->{identifiers}{$base_uri}{anchors}{$anchor} = {
220 canonical_uri => $canonical_uri,
221 path => $state->{traversed_keyword_path}.$state->{keyword_path},
222 };
223 }
224 # we need not be at the root of the resource schema, and we need not even have an entry
225 # in 'identifiers' for our current base uri (if there was no $id at the root, or if
226 # initial_schema_uri was overridden in the call to traverse())
227 else {
228 my $base_path = '';
229 if (my $fragment = $canonical_uri->fragment) {
230 # this shouldn't happen, as we also check this at the start of traverse
231 return E($state, 'something is wrong; "%s" is not the suffix of "%s"', $fragment, $state->{traversed_keyword_path}.$state->{keyword_path})
232 if substr($state->{traversed_keyword_path}.$state->{keyword_path}, -length($fragment))
233 ne $fragment;
234 $base_path = substr($state->{traversed_keyword_path}.$state->{keyword_path}, 0, -length($fragment));
235 }
236
237 $state->{identifiers}{$base_uri} = {
238 # We didn't see an $id keyword at this position or above us, so a resource entry hasn't been
239 # made yet for this identifier. However, we have all the information we need to infer its
240 # data. If this entry is being created in a subschema (below the document root), another one
241 # just like it may be created by another subschema using the same base canonical uri, so that
242 # caller will need to merge the entries together before providing them to the Document's
243 # resource index.
244 canonical_uri => $base_uri,
245 path => $base_path,
246 $state->%{qw(specification_version vocabularies)},
247 anchors => {
248 $anchor => {
249 canonical_uri => $canonical_uri,
250 path => $state->{traversed_keyword_path}.$state->{keyword_path},
251 },
252 },
253 };
254 }
255
256 return 1;
257 }
258
259 # we already indexed the $anchor uri, so there is nothing more to do at evaluation time.
260 # we explicitly do NOT set $state->{initial_schema_uri}.
261
262 sub _traverse_keyword_recursiveAnchor ($class, $schema, $state) {
263 return if not assert_keyword_type($state, $schema, 'boolean');
264
265 # this is required because the location is used as the base URI for future resolution
266 # of $recursiveRef, and the fragment would be disregarded in the base
267 return E($state, '"$recursiveAnchor" keyword used without "$id"')
268 if length($state->{keyword_path});
269 return 1;
270 }
271
272 sub _eval_keyword_recursiveAnchor ($class, $, $schema, $state) {
273 return 1 if not $schema->{'$recursiveAnchor'} or exists $state->{recursive_anchor_uri};
274
275 # record the canonical location of the current position, to be used against future resolution
276 # of a $recursiveRef uri -- as if it was the current location when we encounter a $ref.
277 $state->{recursive_anchor_uri} = canonical_uri($state);
278 return 1;
279 }
280
281 sub _traverse_keyword_dynamicAnchor ($class, $schema, $state) {
282 return if not $class->_traverse_keyword_anchor($schema, $state);
283 $state->{identifiers}{$state->{initial_schema_uri}}{anchors}{$schema->{'$dynamicAnchor'}}{dynamic} = 1;
284 }
285
286 # we already indexed the $dynamicAnchor uri, so there is nothing more to do at evaluation time.
287 # we explicitly do NOT set $state->{initial_schema_uri}.
288
289 sub _traverse_keyword_ref ($class, $schema, $state) {
290 return if not assert_keyword_type($state, $schema, 'string')
291 or not assert_uri_reference($state, $schema);
292
293 push $state->{references}->@*, [
294 $state->{keyword},
295 ($state->{traversed_keyword_path}//'').$state->{keyword_path},
296 Mojo::URL->new($schema->{$state->{keyword}})->to_abs($state->{initial_schema_uri}//()),
297 'schema',
298 ] if $state->{references};
299
300 return 1;
301 }
302
303 sub _eval_keyword_ref ($class, $data, $schema, $state) {
304 my $uri = Mojo::URL->new($schema->{'$ref'})->to_abs($state->{initial_schema_uri});
305 $class->eval_subschema_at_uri($data, $schema, $state, $uri);
306 }
307
308 *_traverse_keyword_recursiveRef = \&_traverse_keyword_ref;
309
310 sub _eval_keyword_recursiveRef ($class, $data, $schema, $state) {
311 my $uri = Mojo::URL->new($schema->{'$recursiveRef'})->to_abs($state->{initial_schema_uri});
312 my $schema_info = $state->{evaluator}->_fetch_from_uri($uri);
313 abort($state, 'EXCEPTION: unable to find resource "%s"', $uri) if not $schema_info;
314 abort($state, 'EXCEPTION: bad reference to "%s": not a schema', $schema_info->{canonical_uri})
315 if $schema_info->{document}->get_entity_at_location($schema_info->{document_path}) ne 'schema';
316
317 if (ref $schema_info->{schema} eq 'HASH'
318 and is_type('boolean', $schema_info->{schema}{'$recursiveAnchor'})
319 and $schema_info->{schema}{'$recursiveAnchor'}) {
320 $uri = Mojo::URL->new($schema->{'$recursiveRef'})
321 ->to_abs($state->{recursive_anchor_uri} // $state->{initial_schema_uri});
322 }
323
324 return $class->eval_subschema_at_uri($data, $schema, $state, $uri);
325 }
326
327 *_traverse_keyword_dynamicRef = \&_traverse_keyword_ref;
328
329 sub __resolve_dynamicRef ($class, $uri, $state) {
330 $uri = Mojo::URL->new($uri)->to_abs($state->{initial_schema_uri});
331 my $schema_info = $state->{evaluator}->_fetch_from_uri($uri);
332 abort($state, 'EXCEPTION: unable to find resource "%s"', $uri) if not $schema_info;
333 abort($state, 'EXCEPTION: bad reference to "%s": not a schema', $schema_info->{canonical_uri})
334 if $schema_info->{document}->get_entity_at_location($schema_info->{document_path}) ne 'schema';
335
336 # If the initially resolved starting point URI includes a fragment that was created by the
337 # "$dynamicAnchor" keyword, ...
338 if (length $uri->fragment
339 and ref $schema_info->{schema} eq 'HASH'
340 and exists $schema_info->{schema}{'$dynamicAnchor'}
341 and $uri->fragment eq (my $anchor = $schema_info->{schema}{'$dynamicAnchor'})) {
342 # ...the initial URI MUST be replaced by the URI (including the fragment) for the outermost
343 # schema resource in the dynamic scope that defines an identically named fragment with
344 # "$dynamicAnchor".
345 foreach my $scope_uri ($state->{dynamic_scope}->@*) {
346 my $resource = $state->{evaluator}->_get_or_load_resource($scope_uri);
347 die 'bad dynamic scope uri: ', $scope_uri if not $resource;
348 if (exists(($resource->{anchors}//{})->{$anchor}) and $resource->{anchors}{$anchor}{dynamic}) {
349 $uri = Mojo::URL->new($scope_uri)->fragment($anchor);
350 last;
351 }
352 }
353 }
354
355 return $uri;
356 }
357
358 sub _eval_keyword_dynamicRef ($class, $data, $schema, $state) {
359 my $uri = $class->__resolve_dynamicRef($schema->{'$dynamicRef'}, $state);
360 return $class->eval_subschema_at_uri($data, $schema, $state, $uri);
361 }
362
363 sub _traverse_keyword_vocabulary ($class, $schema, $state) {
364 return if not assert_keyword_type($state, $schema, 'object');
365
366 return E($state, '$vocabulary can only appear at the schema resource root')
367 if length($state->{keyword_path});
368
369 my $valid = 1;
370
371 my @vocabulary_classes;
372 foreach my $uri (sort keys $schema->{'$vocabulary'}->%*) {
373 if (not is_type('boolean', $schema->{'$vocabulary'}{$uri})) {
374 ()= E({ %$state, _keyword_path_suffix => $uri }, '$vocabulary value at "%s" is not a boolean', $uri);
375 $valid = 0;
376 next;
377 }
378
379 $valid = 0 if not assert_uri({ %$state, _keyword_path_suffix => $uri }, undef, $uri);
380 }
381
382 # we cannot return an error here for invalid or incomplete vocabulary lists, because
383 # - the specification vocabulary schemas themselves don't list Core,
384 # - it is possible for a metaschema to $ref to another metaschema that uses an unrecognized
385 # vocabulary uri while still validating those vocabulary keywords (e.g.
386 # https://spec.openapis.org/oas/3.1/schema-base/2021-05-20)
387 # Instead, we will verify these constraints when we actually use the metaschema, in
388 # _traverse_keyword_schema -> _fetch_vocabulary_data
389
390 return $valid;
391 }
392
393 # we do nothing with $vocabulary yet at evaluation time. When we know we are in a metaschema,
394 # we can scan the URIs included here and either abort if a vocabulary is enabled that we do not
395 # understand, or turn on and off certain keyword behaviours based on the boolean values seen.
396
397 sub _traverse_keyword_comment ($class, $schema, $state) {
398 return if not assert_keyword_type($state, $schema, 'string');
399 return 1;
400 }
401
402 # we do nothing with $comment at evaluation time, including not collecting its value for annotations.
403
404 sub _traverse_keyword_definitions { shift->traverse_object_schemas(@_) }
405 sub _traverse_keyword_defs { shift->traverse_object_schemas(@_) }
406
407 # we do nothing directly with $defs at evaluation time, including not collecting its value for
408 # annotations.
409
410 1;
411
412 __END__
413
414 =pod
415
416 =encoding UTF-8
417
418 =head1 NAME
419
420 JSON::Schema::Modern::Vocabulary::Core - Implementation of the JSON Schema Core vocabulary
421
422 =head1 VERSION
423
424 version 0.650
425
426 I use a linearly-increasing version numbering scheme. No meaning should be
427 presumed or inferred from the version being less than 1.0.
428
429 =head1 DESCRIPTION
430
431 =for Pod::Coverage vocabulary evaluation_order keywords
432
433 =for stopwords metaschema
434
435 Implementation of the JSON Schema Draft 2020-12 "Core" vocabulary, indicated in metaschemas
436 with the URI C<https://json-schema.org/draft/2020-12/vocab/core> and formally specified in
437 L<https://json-schema.org/draft/2020-12/json-schema-core.html#section-8>.
438
439 Support is also provided for
440
441 =over 4
442
443 =item *
444
445 the equivalent Draft 2019-09 keywords, indicated in metaschemas with the URI C<https://json-schema.org/draft/2019-09/vocab/core> and formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-02#section-8>.
446
447 =item *
448
449 the equivalent Draft 7 keywords that correspond to this vocabulary and are formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01>.
450
451 =item *
452
453 the equivalent Draft 6 keywords that correspond to this vocabulary and are formally specified in L<https://json-schema.org/draft-06/draft-wright-json-schema-01>.
454
455 =item *
456
457 the equivalent Draft 4 keywords that correspond to this vocabulary and are formally specified in L<https://json-schema.org/draft-04/draft-zyp-json-schema-04>.
458
459 =back
460
461 =head1 GIVING THANKS
462
463 =for stopwords MetaCPAN GitHub
464
465 If you found this module to be useful, please show your appreciation by
466 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
467 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
468
469 =head1 SUPPORT
470
471 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
472
473 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
474
475 =for stopwords OpenAPI
476
477 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
478 server|https://open-api.slack.com>, which are also great resources for finding help.
479
480 =head1 AUTHOR
481
482 Karen Etheridge <[email protected]>
483
484 =head1 COPYRIGHT AND LICENCE
485
486 This software is copyright (c) 2020 by Karen Etheridge.
487
488 This is free software; you can redistribute it and/or modify it under
489 the same terms as the Perl 5 programming language system itself.
490
491 Some schema files have their own licence, in share/LICENSE.
492
493 =cut