Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/karenetheridge/JSON-Schema-Modern

Validate data against a schema using a JSON Schema
https://github.com/karenetheridge/JSON-Schema-Modern

json-schema

Last synced: 3 months ago
JSON representation

Validate data against a schema using a JSON Schema

Awesome Lists containing this project

README

        

=pod

=encoding UTF-8

=for stopwords schema subschema metaschema validator evaluator listref

=head1 NAME

JSON::Schema::Modern - Validate data against a schema using a JSON Schema

=head1 VERSION

version 0.589

=head1 SYNOPSIS

use JSON::Schema::Modern;

$js = JSON::Schema::Modern->new(
specification_version => 'draft2020-12',
output_format => 'flag',
... # other options
);
$result = $js->evaluate($instance_data, $schema_data);

=head1 DESCRIPTION

This module aims to be a fully-compliant L evaluator and
validator, targeting the currently-latest
L
version of the specification.

=head1 CONFIGURATION OPTIONS

These values are all passed as arguments to the constructor.

=head2 specification_version

Indicates which version of the JSON Schema specification is used during evaluation. When not set,
this value is derived from the C<$schema> keyword in the schema used in evaluation, or defaults to
the latest version (currently C).

The use of this option is I encouraged to ensure continued correct operation of your schema.
The current default value will not stay the same over time.

May be one of:

=over 4

=item *

L or C<2020-12>|https://json-schema.org/specification-links.html#2020-12>, corresponding to metaschema C

=item *

L or C<2019-09>|https://json-schema.org/specification-links.html#2019-09-formerly-known-as-draft-8>, corresponding to metaschema C

=item *

L or C<7>|https://json-schema.org/specification-links.html#draft-7>, corresponding to metaschema C

=back

Note that you can also use a C<$schema> keyword in the schema itself, to specify a different metaschema or
specification version.

=head2 output_format

One of: C, C, C, C, C, C. Defaults to C.
C can only be used with C.
Passed to L.

=head2 short_circuit

When true, evaluation will return early in any execution path as soon as the outcome can be
determined, rather than continuing to find all errors or annotations.
This option is safe to use in all circumstances, even in the presence of
C and C keywords: the validation result will not change;
only some errors will be omitted from the result.

Defaults to true when C is C, and false otherwise.

=head2 max_traversal_depth

The maximum number of levels deep a schema traversal may go, before evaluation is halted. This is to
protect against accidental infinite recursion, such as from two subschemas that each reference each
other, or badly-written schemas that could be optimized. Defaults to 50.

=head2 validate_formats

When true, the C keyword will be treated as an assertion, not merely an annotation. Defaults
to true when specification_version is draft7, and false for all other versions, but this may change in the future.

Note that the use of a format that does not have a defined handler will B be interpreted as an
error in this mode; instead, the undefined format will simply be ignored. If you instead want this
to be treated as an evaluation error, you must define a custom schema dialect that uses the
format-assertion vocabulary (available in specification version C) and reference it in
your schema with the C<$schema> keyword.

=head2 format_validations

=for stopwords subref

An optional hashref that allows overriding the validation method for formats, or adding new ones.
Overrides to existing formats (see L)
must be specified in the form of C<< { $format_name => $format_sub } >>, where
the format sub is a subref that takes one argument and returns a boolean result. New formats must
be specified in the form of C<< { $format_name => { type => $type, sub => $format_sub } } >>,
where the type indicates which of the core JSON Schema types (null, object, array, boolean, string,
number, or integer) the instance value must be for the format validation to be considered.

=head2 validate_content_schemas

When true, the C and C keywords are not treated as pure annotations:
C (when present) is used to decode the applied data payload and then
C will be used as the media-type for decoding to produce the data payload which is
then applied to the schema in C for validation. (Note that treating these keywords as
anything beyond simple annotations is contrary to the specification, therefore this option defaults
to false.)

See L and L for adding additional type support.

=for stopwords shhh

Technically only draft7 allows this and drafts 2019-09 and 2020-12 prohibit ever returning the
subschema evaluation results together with their parent schema's results, so shhh. I'm trying to get this
fixed for the next draft.

=head2 collect_annotations

When true, annotations are collected from keywords that produce them, when validation succeeds.
These annotations are available in the returned result (see L).
Not operational when L is C.

Defaults to false.

=head2 scalarref_booleans

When true, any value that is expected to be a boolean B may also be expressed
as the scalar references C<\0> or C<\1> (which are serialized as booleans by JSON backends).

Defaults to false.

=head2 stringy_numbers

When true, any value that is expected to be a number or integer B may also be
expressed as a string. This applies only to the following keywords:

=over 4

=item *

C (where both C and C (and possibly C) are considered valid)

=item *

C and C (where the string C<"1"> will match with C<"const": 1>)

=item *

C (where strings and numbers are compared numerically to each other, if either or both are numeric)

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C (for formats defined to validate numbers)

=back

This allows you to write a schema like this (which validates a string representing an integer):

type: string
pattern: ^[0-9]$
multipleOf: 4
minimum: 16
maximum: 256

Such keywords are only applied if the value looks like a number, and do not generate a failure
otherwise. Values are determined to be numbers via L.
This option is only intended to be used for evaluating data from sources that can only be strings,
such as the extracted value of an HTTP header or query parameter.

Defaults to false.

=head2 strict

When true, unrecognized keywords are disallowed in schemas (they will cause an immediate abort
in L or L).

Defaults to false.

=head1 METHODS

=for Pod::Coverage BUILDARGS FREEZE THAW

=head2 evaluate_json_string

$result = $js->evaluate_json_string($data_as_json_string, $schema);
$result = $js->evaluate_json_string($data_as_json_string, $schema, { collect_annotations => 1});

Evaluates the provided instance data against the known schema document.

The data is in the form of a JSON-encoded string (in accordance with
L). B

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation,

=item *

a L object,

=item *

or a URI string indicating the location where such a schema is located.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L, L, L,
L, L, L, and/or L
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C: adjusts the effective path of the data instance as of the start of evaluation

=item *

C: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C: adjusts the recorded absolute keyword location as of the start of evaluation

=item *

C: locations in errors and annotations are resolved against this URI

=back

The return value is a L object, which can also be used as a boolean.

=head2 evaluate

$result = $js->evaluate($instance_data, $schema);
$result = $js->evaluate($instance_data, $schema, { short_circuit => 0 });

Evaluates the provided instance data against the known schema document.

The data is in the form of an unblessed nested Perl data structure representing any type that JSON
allows: null, boolean, string, number, object, array. (See L below.)

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation,

=item *

a L object,

=item *

or a URI string indicating the location where such a schema is located.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L, L, L,
L, L, L, and/or L
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C: adjusts the effective path of the data instance as of the start of evaluation

=item *

C: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C: adjusts the recorded absolute keyword location as of the start of evaluation

=item *

C: locations in errors and annotations are resolved against this URI

=back

You can pass a series of callback subs to this method corresponding to keywords, which is useful for
identifying various data that are not exposed by annotations.
This feature is highly experimental and may change in the future.

For example, to find the locations where all C<$ref> keywords are applied B:

my @used_ref_at;
$js->evaluate($data, $schema_or_uri, {
callbacks => {
'$ref' => sub ($data, $schema, $state) {
push @used_ref_at, $state->{data_path};
}
},
});

The return value is a L object, which can also be used as a boolean.
Callbacks are not compatible with L mode.

=head2 validate_schema

$result = $js->validate_schema($schema);
$result = $js->validate_schema($schema, $config_override);

Evaluates the provided schema as instance data against its metaschema. Accepts C<$schema> and
C<$config_override> parameters in the same form as L.

=head2 traverse

$result = $js->traverse($schema);
$result = $js->traverse($schema, { initial_schema_uri => 'http://example.com' });

Traverses the provided schema without evaluating it against any instance data. Returns the
internal state object accumulated during the traversal, including any identifiers found therein, and
any errors found during parsing. For internal purposes only.

Optionally, a hashref can be passed as a second parameter which alters some
behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C: adjusts the recorded absolute keyword location as of the start of evaluation

=item *

C: use the indicated URI as the metaschema

=back

You can pass a series of callback subs to this method corresponding to keywords, which is useful for
extracting data from within schemas and skipping properties that may look like keywords but actually
are not (for example C<{"const": {"$ref": "this is not actually a $ref"}}>). This feature is highly
experimental and is highly likely to change in the future.

For example, to find the resolved targets of all C<$ref> keywords in a schema document:

my @refs;
JSON::Schema::Modern->new->traverse($schema, {
callbacks => {
'$ref' => sub ($schema, $state) {
push @refs, Mojo::URL->new($schema->{'$ref'})
->to_abs(JSON::Schema::Modern::Utilities::canonical_uri($state));
}
},
});

=head2 add_schema

$js->add_schema($uri => $schema);
$js->add_schema($uri => $document);
$js->add_schema($schema);
$js->add_schema($document);

Introduces the (unblessed, nested) Perl data structure or L
object, representing a JSON Schema, to the implementation, registering it under the indicated URI if
provided (and if not, C<''> will be used if no other identifier can be found within).

You B call C for any external resources that a schema may reference via C<$ref>
before calling L, other than the standard metaschemas which are loaded from a local cache
as needed.

Returns C if the resource could not be found;
if there were errors in the document, will die with these errors;
otherwise returns the L that contains the added schema.

=head2 add_format_validation

$js->add_format_validation(all_lc => sub ($value) { lc($value) eq $value });

=for comment we are the nine Eleven Deniers

or

$js->add_format_validation(no_nines => { type => 'number', sub => sub ($value) { $value =~ m/^[0-8]+$/ });

$js->add_format_validation(8bits => { type => 'string', sub => sub ($value) { $value =~ m/^[\x00-\xFF]+$/ });

Adds support for a custom format. If not supplied, the data type(s) that this format applies to
defaults to string; all values of any other type will automatically be deemed to be valid, and will
not be passed to the subref.

Additionally, you can redefine the definition for any core format (see L), but
the data type(s) supported by that format may not be changed.

Be careful to not mutate the type of the value while checking it -- for example, if it is a string,
do not apply arithmetic operators to it -- or subsequent type checks on this value may fail.

See L for a registry of known and useful formats; for
compatibility reasons, avoid defining a format listed here with different semantics.

=head2 add_vocabulary

$js->add_vocabulary('My::Custom::Vocabulary::Class');

Makes a custom vocabulary class available to metaschemas that make use of this vocabulary.
as described in the specification at
L<"Meta-Schemas and Vocabularies"|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.8.1>.

The class must compose the L role and implement the
L and
L methods, as well as
C<< _traverse_keyword_ >> methods for each keyword. C<< _eval_keyword_ >>
methods are optional; when not provided, evaluation will always return a true result.

=head2 add_media_type

$js->add_media_type('application/furble' => sub ($content_ref) {
return ...; # data representing the deserialized text for Content-Type: application/furble
});

Takes a media-type name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which might contain wide characters (i.e. not octets), especially when used
in conjunction with L below. Must return B (which is
then dereferenced for the C keyword).

These media types are already known:

=over 4

=item *

C - see L

=item *

C - see L

=item *

C - see L

=item *

C - passes strings through unchanged

=item *

C

=item *

C - see L

=item *

C - passes strings through unchanged

=back

=head2 get_media_type

Fetches a decoder sub for the indicated media type. Lookups are performed B.

=for stopwords thusly

You can use it thusly:

$js->add_media_type('application/furble' => sub { ... }); # as above
my $decoder = $self->get_media_type('application/furble') or die 'cannot find media type decoder';
my $content_ref = $decoder->(\$content_string);

=head2 add_encoding

$js->add_encoding('bloop' => sub ($content_ref) {
return \ ...; # data representing the deserialized content for Content-Transfer-Encoding: bloop
});

Takes an encoding name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which SHOULD be a 7-bit or 8-bit string. Result values MUST be a scalar-reference
to a string (which is then dereferenced for the C keyword).

=for stopwords natively

Encodings handled natively are:

=over 4

=item *

C - passes strings through unchanged

=item *

C - see L

=item *

C - see L

=back

See also L.

=head2 get_encoding

Fetches a decoder sub for the indicated encoding. Incoming values MUST be a reference to an octet
string. Result values will be a scalar-reference to a string, which might be passed to a media_type
decoder (see above).

You can use it thusly:

my $decoder = $self->get_encoding('base64') or die 'cannot find encoding decoder';
my $content_ref = $decoder->(\$content_string);

=head2 get

my $schema = $js->get($uri);
my ($schema, $canonical_uri) = $js->get($uri);

Fetches the Perl data structure representing the JSON Schema at the indicated identifier (uri or
uri-reference). When called in list context, the canonical URI of that location is also returned, as
a L. Returns C if the schema with that URI has not been loaded (or cached).

=head2 get_document

my $document = $js->get_document($uri_reference);

Fetches the L object that contains the provided identifier (uri or
uri-reference). C if the schema with that URI has not been loaded (or cached).

=head1 CACHING

=for stopwords preforking

Very large documents, particularly those used by L, may take a noticeable time to be
loaded and parsed. You can reduce the impact to your preforking application by loading all necessary
documents at startup, and impact can be further reduced by saving objects to cache and then
reloading them (perhaps by using a timestamp or checksum to determine if a fresh reload is needed).

Custom L, L or
L are not serialized, as they are represented by subroutine references, and
will need to be manually added after thawing.

sub get_evaluator (...) {
my $serialized_file = Path::Tiny::path($filename);
my $schema_file = Path::Tiny::path($schema_filename);
my $js;
if ($serialized_file->stat->mtime < $schema_file->stat->mtime)) {
$js = JSON::Schema::Modern->new;
$js->add_schema(decode_json($schema_file->slurp_raw)); # your application schema
my $frozen = Sereal::Encoder->new({ freeze_callbacks => 1 })->encode($js);
$serialized_file->spew_raw($frozen);
}
else {
my $frozen = $serialized_file->slurp_raw;
$js = Sereal::Decoder->new->decode($frozen);
}

# add custom format validations, media types and encodings here
$js->add_media_type(...);

return $js;
}

See also L.

=head1 LIMITATIONS

=head2 Types

Perl is a more loosely-typed language than JSON. This module delves into a value's internal
representation in an attempt to derive the true "intended" type of the value. However, if a value is
used in another context (for example, a numeric value is concatenated into a string, or a numeric
string is used in an arithmetic operation), additional flags can be added onto the variable causing
it to resemble the other type. This should not be an issue if data validation is occurring
immediately after decoding a JSON payload, or if the JSON string itself is passed to this module.
If you are still having difficulties, make sure you are using Perl's fastest and most trusted and
reliable JSON decoder, L.
Other JSON decoders are known to produce data with incorrect data types.

For more information, see L.

=head2 Format Validation

By default (and unless you specify a custom metaschema with the C<$schema> keyword or
L),
formats are treated only as annotations, not assertions. When L is
true, strings are also checked against the format as specified in the schema. At present the
following formats are supported (use of any other formats than these will always evaluate as true,
but remember you can always supply custom format handlers; see L above):

=over 4

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=item *

C

=back

A few optional prerequisites are needed for some of these (if the prerequisite is missing,
validation will always succeed):

=over 4

=item *

C, C, and C

=item *

C and C require L version 1.04 (or higher)

=item *

C and C require L

=item *

C requires L

=back

=head2 Specification Compliance

This implementation is now fully specification-compliant (for versions draft7, draft2019-09,
draft2020-12), but until version 1.000 is released, it is
still deemed to be missing some optional but quite useful features, such as:

=for stopwords Mojolicious

=over 4

=item *

loading schema documents from disk

=item *

loading schema documents from the network

=item *

loading schema documents from a local web application (e.g. L)

=item *

additional output formats beyond C, C, and C (L)

=back

=head1 SECURITY CONSIDERATIONS

The C and C keywords evaluate regular expressions from the schema,
the C format validator evaluates regular expressions from the data, and some keywords
in the Validation vocabulary perform floating point operations on potentially-very large numbers.
No effort is taken (at this time) to sanitize the regular expressions for embedded code or
detect potentially pathological constructs that may pose a security risk, either via denial of
service or by allowing exposure to the internals of your application. B

(In particular, see vulnerability
L,
which is closed in Perl releases 5.34.3, 5.36.3 and 5.38.1.)

=head1 SEE ALSO

=for stopwords OpenAPI

=over 4

=item *

L

=item *

L

=item *

L

=item *

L

=item *

L: contains the official JSON Schema test suite

=item *

L: a more stripped-down implementation of the specification, with fewer dependencies and faster evaluation

=item *

L

=item *

L

=item *

L

=item *

L: tutorial-focused documentation

=item *

L: a parser and evaluator for OpenAPI v3.1 documents

=item *

L: a Mojolicious plugin providing OpenAPI functionality

=item *

L: test your Mojolicious application's OpenAPI compliance

=back

=head1 SUPPORT

Bugs may be submitted through L.

I am also usually active on irc, as 'ether' at C and C.

=for stopwords OpenAPI

You can also find me on the L and L, which are also great resources for finding help.

=head1 AUTHOR

Karen Etheridge

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2020 by Karen Etheridge.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut