Debian Codegraph @

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

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern::Vocabulary::FormatAssertion;
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Implementation of the JSON Schema Format-Assertion 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 use if "$]" < 5.026, experimental => 'lexical_subs';
17 no if "$]" >= 5.031009, feature => 'indirect';
18 no if "$]" >= 5.033001, feature => 'multidimensional';
19 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
20 no if "$]" >= 5.041009, feature => 'smartmatch';
21 no feature 'switch';
22 use JSON::Schema::Modern::Utilities qw(get_type E A assert_keyword_type abort);
23 use Feature::Compat::Try;
24 use if "$]" < 5.041010, 'List::Util' => 'any';
25 use if "$]" >= 5.041010, experimental => 'keyword_any';
26 use Scalar::Util 'looks_like_number';
27 use namespace::clean;
28
29 with 'JSON::Schema::Modern::Vocabulary';
30
31 sub vocabulary ($class) {
32 'https://json-schema.org/draft/2020-12/vocab/format-assertion' => 'draft2020-12';
33 }
34
35 sub evaluation_order ($class) { 2 }
36
37 sub keywords ($class, $spec_version) {
38 return (
39 $spec_version !~ /^draft(?:[467]|2019-09)\z/ ? qw(format) : (),
40 );
41 }
42
43 # these definitions are shared with the FormatAnnotation vocabulary
44 {
45 # for now, all built-in formats are constrained to the 'string' type
46
47 my $is_email = sub { # email, idn-email
48 require Email::Address::XS; Email::Address::XS->VERSION(1.04);
49 Email::Address::XS->parse_bare_address($_[0])->is_valid;
50 };
51 my $is_hostname = sub { # hostname, idn-hostname
52 # A dotted quad (such as 127.0.0.1) is not considered a domain, but the use of
53 # domain_disable_tld_validation results in a valid result anyway.
54 # see https://github.com/houseabsolute/Data-Validate-Domain/pull/15
55 return 0 if $_[0] =~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\z/;
56
57 # FIXME: draft7 hostname uses RFC1034, draft2019-09+ hostname uses RFC1123
58 require Data::Validate::Domain; Data::Validate::Domain->VERSION(0.13);
59
60 Data::Validate::Domain::is_domain($_[0],
61 { domain_disable_tld_validation => 1, domain_allow_single_label => 1 });
62 };
63 my $idn_decode = sub { # idn-hostname
64 require Net::IDN::Encode;
65 try { return Net::IDN::Encode::domain_to_ascii($_[0]) } catch ($e) { return $_[0]; }
66 };
67 my $is_ipv4 = sub { # ipv4, ipv6
68 my @o = split(/\./, $_[0], 5);
69 @o == 4 && (grep /^(?:0|[1-9][0-9]{0,2})\z/, @o) == 4 && (grep $_ < 256, @o) == 4;
70 };
71 # https://datatracker.ietf.org/doc/html/rfc3339#appendix-A
72 # Changes in the 2000 version as defined in https://en.wikipedia.org/wiki/ISO_8601#Durations
73 # (that allow fractional numbers) are NOT included
74 my $duration_re = do { # duration
75 my $num = '[0-9]+';
76 my $second = "${num}S";
77 my $minute = "${num}M(?:$second)?";
78 my $hour = "${num}H(?:$minute)?";
79 my $time = "T(?:$hour|$minute|$second)";
80 my $day = "${num}D";
81 my $month = "${num}M(?:$day)?";
82 my $year = "${num}Y(?:$month)?";
83 my $week = "${num}W";
84 my $date = "(?:$year|$month|$day)(?:$time)?";
85 qr{^P(?:$week|$date|$time)\z};
86 };
87
88 state sub days_in_month ($month) {
89 $month == 2 ? 28
90 : $month == 4 || $month == 6 || $month == 9 || $month == 11 ? 30
91 : 31;
92 }
93
94 my $formats = +{
95 'date-time' => sub {
96 # https://www.rfc-editor.org/rfc/rfc3339.html#section-5.6
97 $_[0] =~ m/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:Z|([+-]\d\d):(\d\d))\z/ia
98 && $2 >= 1 && $2 <= 12 # date-month
99 && $3 >= 1 && $3 <= 31 # date-mday
100 && $4 <= 23 # time-hour
101 && $5 <= 59 # time-minute
102 && $6 <= 60 # time-second
103 && (!defined $7 || abs($7) <= 23) # time-hour in time-numoffset
104 && (!defined $8 || $8 <= 59) # time-minute in time-numoffset
105 && ($3 <= days_in_month($2)
106 || ($2 == 2 && $3 == 29 && $1 % 4 == 0 && ($1 % 100 != 0 || $1 % 400 == 0)))
107 && ($6 < 60 || do {
108 my ($year, $month, $day, $hour, $minute) = ($1, $2, $3, $4, $5);
109
110 if (defined $7 && ($7 != 0 || $8 != 0)) {
111 my $mult = ($7 < 0 ? 1 : -1); # if offset is negative, we ADD; if positive, we SUBTRACT
112 $hour += $mult * abs($7);
113 $minute += $mult * $8;
114
115 $minute += 60, $hour -= 1 if $minute < 0;
116 $minute -= 60, $hour += 1 if $minute >= 60;
117
118 $hour += 24, $day -= 1 if $hour < 0;
119 $hour -= 24, $day += 1 if $hour >= 24;
120
121 $day += days_in_month(($month + 11) % 12), $month -= 1 if $day < 1;
122 $day -= days_in_month($month), $month += 1 if $day > days_in_month($month);
123
124 $month += 12, $year -= 1 if $month < 1;
125 $month -= 12, $year += 1 if $month > 12;
126 }
127
128 # a leap second can appear only as 23:59:60 UTC, and only on June 30 or December 31
129 $hour == 23 && $minute == 59
130 && (($month == 6 && $day == 30) || ($month == 12 && $day == 31));
131 }
132 );
133 },
134 date => sub {
135 # https://www.rfc-editor.org/rfc/rfc3339.html#section-5.6 full-date
136 $_[0] =~ m/^(\d{4})-(\d\d)-(\d\d)\z/a
137 && $2 >= 1 && $2 <= 12 # date-month
138 && $3 >= 1 && $3 <= 31 # date-mday
139 && ($3 <= days_in_month($2)
140 || ($2 == 2 && $3 == 29 && $1 % 4 == 0 && ($1 % 100 != 0 || $1 % 400 == 0)));
141 },
142 time => sub {
143 # https://www.rfc-editor.org/rfc/rfc3339.html#section-5.6 full-time
144 $_[0] =~ m/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:Z|([+-]\d\d):(\d\d))\z/ia
145 && $1 <= 23 # time-hour
146 && $2 <= 59 # time-minute
147 && $3 <= 60 # time-second
148 && (!defined $4 || abs($4) <= 23) # time-hour in time-numoffset
149 && (!defined $5 || $5 <= 59) # time-minute in time-numoffset
150 && ($3 < 60 || do {
151 my ($hour, $minute) = ($1, $2);
152 if (defined $4 && ($4 != 0 || $5 != 0)) {
153 my $mult = ($4 < 0 ? 1 : -1); # if offset is negative, we ADD; if positive, we SUBTRACT
154 $hour += $mult * abs($4);
155 $minute += $mult * $5;
156
157 $minute += 60, $hour -= 1 if $minute < 0;
158 $minute -= 60, $hour += 1 if $minute >= 60; # this line not really needed; always invalid
159 }
160
161 # a leap second can appear only as 23:59:60 UTC
162 $hour % 24 == 23 && $minute == 59;
163 }
164 );
165 },
166 duration => sub { $_[0] =~ $duration_re && $_[0] !~ m{[.,][0-9]+[A-Z].} },
167 email => sub { $is_email->($_[0]) && $_[0] !~ /[^[:ascii:]]/ },
168 'idn-email' => $is_email,
169 hostname => $is_hostname,
170 'idn-hostname' => sub { $is_hostname->($idn_decode->($_[0])) },
171 ipv4 => $is_ipv4,
172 ipv6 => sub {
173 ($_[0] =~ /^(?:[[:xdigit:]]{0,4}:){0,8}[[:xdigit:]]{0,4}\z/a
174 || $_[0] =~ /^(?:[[:xdigit:]]{0,4}:){1,7}((?:[0-9]{1,3}\.){3}[0-9]{1,3})\z/a
175 && $is_ipv4->($1))
176 && $_[0] !~ /:::/
177 && $_[0] !~ /^:[^:]/
178 && $_[0] !~ /[^:]:\z/
179 && do {
180 my $double_colons = ()= ($_[0] =~ /::/g);
181 my $colon_components = grep length, split(/:+/, $_[0], -1);
182 ($double_colons == 1
183 && ((!defined $1 && $colon_components < 8) || (defined $1 && $colon_components < 7)))
184 ||
185 ($double_colons == 0
186 && ((!defined $1 && $colon_components == 8) || (defined $1 && $colon_components == 7)));
187 };
188 },
189 uri => sub {
190 return if $_[0] =~ /%.?\z/ or $_[0] =~ /%[^[:xdigit:]]/a or $_[0] =~ /%.[^[:xdigit:]]/a;
191 return if $_[0] =~ /[^[:ascii:]]/;
192 my $uri = Mojo::URL->new($_[0]);
193 return if not fc($uri->to_unsafe_string) eq fc($_[0]) && $uri->is_abs;
194 require Data::Validate::URI;
195 return Data::Validate::URI::is_uri($_[0]);
196 },
197 'uri-reference' => sub {
198 return if $_[0] =~ /%.?\z/ or $_[0] =~ /%[^[:xdigit:]]/a or $_[0] =~ /%.[^[:xdigit:]]/a;
199 return if $_[0] =~ /[^[:ascii:]]/;
200 fc(Mojo::URL->new($_[0])->to_unsafe_string) eq fc($_[0]);
201 },
202 iri => sub {
203 return if $_[0] =~ /%.?\z/ or $_[0] =~ /%[^[:xdigit:]]/a or $_[0] =~ /%.[^[:xdigit:]]/a;
204 Mojo::URL->new($_[0])->is_abs;
205 },
206 'iri-reference' => sub {
207 return if $_[0] =~ /%.?\z/ or $_[0] =~ /%[^[:xdigit:]]/a or $_[0] =~ /%.[^[:xdigit:]]/a;
208 return 1;
209 },
210 uuid => sub { $_[0] =~ /^[[:xdigit:]]{8}-(?:[[:xdigit:]]{4}-){3}[[:xdigit:]]{12}\z/a },
211 'json-pointer' => sub { (!length($_[0]) || $_[0] =~ m{^/}) && $_[0] !~ m{~(?![01])} },
212 'relative-json-pointer' => sub { $_[0] =~ m{^(?:0|[1-9][0-9]*)(?:#\z|\z|/)} && $_[0] !~ m{~(?![01])} },
213 regex => sub {
214 local $SIG{__WARN__} = sub { die @_ };
215 eval { qr/$_[0]/; 1 };
216 },
217 # uri-template is not implemented, but user can add a custom definition
218 };
219
220 my %formats_by_spec_version = (
221 draft4 => [qw(
222 date-time
223 email
224 hostname
225 ipv4
226 ipv6
227 uri
228 )],
229 );
230 $formats_by_spec_version{draft6} = [$formats_by_spec_version{draft4}->@*, qw(
231 uri-reference
232 uri-template
233 json-pointer
234 )];
235 $formats_by_spec_version{draft7} = [$formats_by_spec_version{draft6}->@*, qw(
236 iri
237 iri-reference
238 idn-email
239 idn-hostname
240 relative-json-pointer
241 regex
242 date
243 time
244 )];
245 $formats_by_spec_version{'draft2019-09'} =
246 $formats_by_spec_version{'draft2020-12'} = [$formats_by_spec_version{draft7}->@*, qw(duration uuid)];
247
248 sub _get_default_format_validation ($class, $state, $format) {
249 # all core formats are of type string (so far)
250 return { type => 'string', sub => $formats->{$format} }
251 if grep $format eq $_, $formats_by_spec_version{$state->{specification_version}}->@*
252 and $formats->{$format};
253 }
254 }
255
256 my $warnings = {
257 email => sub { require Email::Address::XS; Email::Address::XS->VERSION(1.04); 1 },
258 hostname => sub { require Data::Validate::Domain; Data::Validate::Domain->VERSION(0.13); 1 },
259 'idn-hostname' => sub { require Data::Validate::Domain; Data::Validate::Domain->VERSION(0.13); require Net::IDN::Encode; 1 },
260 uri => sub { require Data::Validate::URI; 1 },
261 };
262 $warnings->{'idn-email'} = $warnings->{email};
263
264 sub _traverse_keyword_format ($class, $schema, $state) {
265 return if not assert_keyword_type($state, $schema, 'string');
266
267 # warn when prereq is missing for a format implementation
268 if (my $warn_sub = $warnings->{$schema->{format}}) {
269 try { $warn_sub->() } catch ($e) { warn $e }
270 }
271
272 # §7.2.2 (draft2020-12) "When the Format-Assertion vocabulary is declared with a value of true,
273 # implementations MUST provide full validation support for all of the formats defined by this
274 # specification. Implementations that cannot provide full validation support MUST refuse to
275 # process the schema."
276 return E($state, 'unimplemented core format "%s"', $schema->{format})
277 if $schema->{format} eq 'uri-template'
278 and not $state->{evaluator}->_get_format_validation($schema->{format});
279
280 # unimplemented custom formats are detected at runtime, only if actually evaluated
281
282 return 1;
283 }
284
285 # Note that this method is only callable in draft2020-12 and later, because this vocabulary does not
286 # exist in previous versions
287 sub _eval_keyword_format ($class, $data, $schema, $state) {
288 A($state, $schema->{format});
289
290 # unimplemented core formats were already detected in the traverse phase
291
292 my $spec = $state->{evaluator}->_get_format_validation($schema->{format})
293 // $class->_get_default_format_validation($state, $schema->{format});
294
295 # §7.2.3 (draft2020-12) "When the Format-Assertion vocabulary is specified, implementations MUST
296 # fail upon encountering unknown formats."
297 abort($state, 'unimplemented custom format "%s"', $schema->{format}) if not $spec;
298
299 my $type = get_type($data);
300 $type = 'number' if $type eq 'integer';
301
302 return 1 if
303 not ref $spec->{type} eq 'ARRAY' ? any { $type eq $_ } $spec->{type}->@* : $type eq $spec->{type}
304 and not ($state->{stringy_numbers} and $type eq 'string'
305 and ref $spec->{type} eq 'ARRAY' ? any { $_ eq 'number' } $spec->{type}->@* : $spec->{type} eq 'number'
306 and looks_like_number($data));
307
308 return E($state, 'not a valid %s %s', $schema->{format},
309 ref $spec->{type} eq 'ARRAY' ? join(', ', $spec->{type}->@*) : $spec->{type})
310 if not $spec->{sub}->($data);
311
312 return 1;
313 }
314
315 1;
316
317 __END__
318
319 =pod
320
321 =encoding UTF-8
322
323 =head1 NAME
324
325 JSON::Schema::Modern::Vocabulary::FormatAssertion - Implementation of the JSON Schema Format-Assertion vocabulary
326
327 =head1 VERSION
328
329 version 0.650
330
331 I use a linearly-increasing version numbering scheme. No meaning should be
332 presumed or inferred from the version being less than 1.0.
333
334 =head1 DESCRIPTION
335
336 =for Pod::Coverage vocabulary evaluation_order keywords
337
338 =for stopwords metaschema
339
340 Implementation of the JSON Schema Draft 2020-12 "Format-Assertion" vocabulary, indicated in metaschemas
341 with the URI C<https://json-schema.org/draft/2020-12/vocab/format-assertion> and formally specified in
342 L<https://json-schema.org/draft/2020-12/json-schema-validation.html#section-7>.
343
344 Support is also provided for
345
346 =over 4
347
348 =item *
349
350 the equivalent Draft 2019-09 keyword, indicated in metaschemas with the URI C<https://json-schema.org/draft/2019-09/vocab/format> and formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-7>.
351
352 =item *
353
354 the equivalent Draft 7 keyword, as formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-7>.
355
356 =item *
357
358 the equivalent Draft 6 keyword, as formally specified in L<https://json-schema.org/draft-06/draft-wright-json-schema-validation-01#rfc.section.8>.
359
360 =item *
361
362 the equivalent Draft 4 keyword, as formally specified in L<https://json-schema.org/draft-04/draft-fge-json-schema-validation-00#rfc.section.7>.
363
364 =back
365
366 Assertion behaviour can be enabled by
367 L<https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.8.1.2/referencing this vocabulary explicitly>
368 in a metaschema's C<$vocabulary> keyword, or by toggling the
369 L<JSON::Schema::Modern/validate_formats> option.
370
371 When the Format-Annotation vocabulary is specified (which is the default for the draft2020-12
372 metaschema) and combined with the C<validate_formats> option set to true, unimplemented formats will
373 silently validate, but implemented formats will validate completely. Note that some formats require
374 optional module dependencies, and the lack of these modules will generate an error.
375
376 When this vocabulary (the Format-Assertion vocabulary) is specified, unimplemented formats will
377 generate an error on use.
378
379 Overrides to particular format implementations, or additions of new ones, can be done through
380 L<JSON::Schema::Modern/format_validations>.
381
382 Format C<uri-template> is not yet implemented.
383 Use of this format will always result in an error.
384
385 =head1 SEE ALSO
386
387 =over 4
388
389 =item *
390
391 L<JSON::Schema::Modern/Format Validation>
392
393 =item *
394
395 L<JSON::Schema::Modern::Vocabulary::FormatAnnotation>
396
397 =back
398
399 =head1 GIVING THANKS
400
401 =for stopwords MetaCPAN GitHub
402
403 If you found this module to be useful, please show your appreciation by
404 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
405 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
406
407 =head1 SUPPORT
408
409 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
410
411 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
412
413 =for stopwords OpenAPI
414
415 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
416 server|https://open-api.slack.com>, which are also great resources for finding help.
417
418 =head1 AUTHOR
419
420 Karen Etheridge <[email protected]>
421
422 =head1 COPYRIGHT AND LICENCE
423
424 This software is copyright (c) 2020 by Karen Etheridge.
425
426 This is free software; you can redistribute it and/or modify it under
427 the same terms as the Perl 5 programming language system itself.
428
429 Some schema files have their own licence, in share/LICENSE.
430
431 =cut