← Index
NYTProf Performance Profile   « line view »
For ../prof.pl
  Run on Thu Dec 15 15:23:56 2022
Reported on Thu Dec 15 15:27:01 2022

Filename/Users/ether/.perlbrew/libs/36.0@std/lib/perl5/OpenAPI/Modern.pm
StatementsExecuted 74 statements in 18.5ms
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
1116.26ms537msOpenAPI::Modern::::BEGIN@26OpenAPI::Modern::BEGIN@26
1114.77ms15.6msOpenAPI::Modern::::BEGIN@28OpenAPI::Modern::BEGIN@28
1113.25ms34.2msOpenAPI::Modern::::BEGIN@11OpenAPI::Modern::BEGIN@11
1113.06ms7.63msOpenAPI::Modern::::BEGIN@20OpenAPI::Modern::BEGIN@20
1112.81ms35.6msOpenAPI::Modern::::BEGIN@24OpenAPI::Modern::BEGIN@24
1112.17ms2.85msOpenAPI::Modern::::BEGIN@12OpenAPI::Modern::BEGIN@12
1112.00ms2.09msOpenAPI::Modern::::BEGIN@25OpenAPI::Modern::BEGIN@25
1111.83ms3.54msOpenAPI::Modern::::BEGIN@23OpenAPI::Modern::BEGIN@23
1111.55ms3.87msOpenAPI::Modern::::BEGIN@19OpenAPI::Modern::BEGIN@19
1111.53ms7.44msOpenAPI::Modern::::BEGIN@13OpenAPI::Modern::BEGIN@13
1111.04ms1.10msOpenAPI::Modern::::BEGIN@14OpenAPI::Modern::BEGIN@14
111500µs70.7sOpenAPI::Modern::::__ANON__[:79]OpenAPI::Modern::__ANON__[:79]
11123µs26µsmain::::BEGIN@1.2 main::BEGIN@1.2
11119µs19µsOpenAPI::Modern::::BEGIN@10OpenAPI::Modern::BEGIN@10
11112µs80µsOpenAPI::Modern::::BEGIN@27OpenAPI::Modern::BEGIN@27
11112µs352µsOpenAPI::Modern::::BEGIN@30OpenAPI::Modern::BEGIN@30
11110µs29µsOpenAPI::Modern::::BEGIN@15OpenAPI::Modern::BEGIN@15
11110µs63µsOpenAPI::Modern::::BEGIN@21OpenAPI::Modern::BEGIN@21
11110µs49µsOpenAPI::Modern::::BEGIN@32OpenAPI::Modern::BEGIN@32
1117µs17µsOpenAPI::Modern::::BEGIN@16OpenAPI::Modern::BEGIN@16
1116µs16µsOpenAPI::Modern::::BEGIN@17OpenAPI::Modern::BEGIN@17
1116µs59µsOpenAPI::Modern::::BEGIN@29OpenAPI::Modern::BEGIN@29
1116µs315µsOpenAPI::Modern::::BEGIN@31OpenAPI::Modern::BEGIN@31
1116µs287µsOpenAPI::Modern::::BEGIN@33OpenAPI::Modern::BEGIN@33
1115µs14µsOpenAPI::Modern::::BEGIN@22OpenAPI::Modern::BEGIN@22
1114µs29µsmain::::BEGIN@2.3 main::BEGIN@2.3
1113µs32µsOpenAPI::Modern::::BEGIN@18OpenAPI::Modern::BEGIN@18
1110s0sOpenAPI::Modern::::__ANON__OpenAPI::Modern::__ANON__ (xsub)
0000s0sOpenAPI::Modern::::__ANON__[:206]OpenAPI::Modern::__ANON__[:206]
0000s0sOpenAPI::Modern::::__ANON__[:488]OpenAPI::Modern::__ANON__[:488]
0000s0sOpenAPI::Modern::::__ANON__[:489]OpenAPI::Modern::__ANON__[:489]
0000s0sOpenAPI::Modern::::__ANON__[:528]OpenAPI::Modern::__ANON__[:528]
0000s0sOpenAPI::Modern::::_body_sizeOpenAPI::Modern::_body_size
0000s0sOpenAPI::Modern::::_content_charsetOpenAPI::Modern::_content_charset
0000s0sOpenAPI::Modern::::_content_refOpenAPI::Modern::_content_ref
0000s0sOpenAPI::Modern::::_content_typeOpenAPI::Modern::_content_type
0000s0sOpenAPI::Modern::::_evaluate_subschemaOpenAPI::Modern::_evaluate_subschema
0000s0sOpenAPI::Modern::::_headerOpenAPI::Modern::_header
0000s0sOpenAPI::Modern::::_query_pairsOpenAPI::Modern::_query_pairs
0000s0sOpenAPI::Modern::::_request_uriOpenAPI::Modern::_request_uri
0000s0sOpenAPI::Modern::::_resolve_refOpenAPI::Modern::_resolve_ref
0000s0sOpenAPI::Modern::::_resultOpenAPI::Modern::_result
0000s0sOpenAPI::Modern::::_validate_body_contentOpenAPI::Modern::_validate_body_content
0000s0sOpenAPI::Modern::::_validate_cookie_parameterOpenAPI::Modern::_validate_cookie_parameter
0000s0sOpenAPI::Modern::::_validate_header_parameterOpenAPI::Modern::_validate_header_parameter
0000s0sOpenAPI::Modern::::_validate_parameter_contentOpenAPI::Modern::_validate_parameter_content
0000s0sOpenAPI::Modern::::_validate_path_parameterOpenAPI::Modern::_validate_path_parameter
0000s0sOpenAPI::Modern::::_validate_query_parameterOpenAPI::Modern::_validate_query_parameter
0000s0sOpenAPI::Modern::::find_pathOpenAPI::Modern::find_path
0000s0sOpenAPI::Modern::::validate_requestOpenAPI::Modern::validate_request
0000s0sOpenAPI::Modern::::validate_responseOpenAPI::Modern::validate_response
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1226µs229µs
# spent 26µs (23+3) within main::BEGIN@1.2 which was called: # once (23µs+3µs) by main::BEGIN@2 at line 1
use strict;
# spent 26µs making 1 call to main::BEGIN@1.2 # spent 3µs making 1 call to strict::import
2231µs254µs
# spent 29µs (4+25) within main::BEGIN@2.3 which was called: # once (4µs+25µs) by main::BEGIN@2 at line 2
use warnings;
# spent 29µs making 1 call to main::BEGIN@2.3 # spent 25µs making 1 call to warnings::import
3package OpenAPI::Modern; # git description: v0.036-2-g96d001a
4# vim: set ts=8 sts=2 sw=2 tw=100 et :
5# ABSTRACT: Validate HTTP requests and responses against an OpenAPI document
6# KEYWORDS: validation evaluation JSON Schema OpenAPI Swagger HTTP request response
7
810sour $VERSION = '0.037';
9
10239µs119µs
# spent 19µs within OpenAPI::Modern::BEGIN@10 which was called: # once (19µs+0s) by main::BEGIN@2 at line 10
use 5.020;
# spent 19µs making 1 call to OpenAPI::Modern::BEGIN@10
1121.33ms235.3ms
# spent 34.2ms (3.25+31.0) within OpenAPI::Modern::BEGIN@11 which was called: # once (3.25ms+31.0ms) by main::BEGIN@2 at line 11
use Moo;
# spent 34.2ms making 1 call to OpenAPI::Modern::BEGIN@11 # spent 1.05ms making 1 call to Moo::import
1231.37ms33.47ms
# spent 2.85ms (2.17+681µs) within OpenAPI::Modern::BEGIN@12 which was called: # once (2.17ms+681µs) by main::BEGIN@2 at line 12
use strictures 2;
# spent 2.85ms making 1 call to OpenAPI::Modern::BEGIN@12 # spent 603µs making 1 call to strictures::import # spent 19µs making 1 call to strictures::VERSION
132574µs27.59ms
# spent 7.44ms (1.53+5.91) within OpenAPI::Modern::BEGIN@13 which was called: # once (1.53ms+5.91ms) by main::BEGIN@2 at line 13
use experimental qw(signatures postderef);
# spent 7.44ms making 1 call to OpenAPI::Modern::BEGIN@13 # spent 153µs making 1 call to experimental::import
142913µs21.11ms
# spent 1.10ms (1.04+59µs) within OpenAPI::Modern::BEGIN@14 which was called: # once (1.04ms+59µs) by main::BEGIN@2 at line 14
use if "$]" >= 5.022, experimental => 're_strict';
# spent 1.10ms making 1 call to OpenAPI::Modern::BEGIN@14 # spent 3µs making 1 call to if::import
15220µs229µs
# spent 29µs (10+19) within OpenAPI::Modern::BEGIN@15 which was called: # once (10µs+19µs) by main::BEGIN@2 at line 15
no if "$]" >= 5.031009, feature => 'indirect';
# spent 29µs making 1 call to OpenAPI::Modern::BEGIN@15 # spent 0s making 1 call to if::unimport
16216µs217µs
# spent 17µs (7+10) within OpenAPI::Modern::BEGIN@16 which was called: # once (7µs+10µs) by main::BEGIN@2 at line 16
no if "$]" >= 5.033001, feature => 'multidimensional';
# spent 17µs making 1 call to OpenAPI::Modern::BEGIN@16 # spent 0s making 1 call to if::unimport
17214µs216µs
# spent 16µs (6+10) within OpenAPI::Modern::BEGIN@17 which was called: # once (6µs+10µs) by main::BEGIN@2 at line 17
no if "$]" >= 5.033006, feature => 'bareword_filehandles';
# spent 16µs making 1 call to OpenAPI::Modern::BEGIN@17 # spent 0s making 1 call to if::unimport
18214µs261µs
# spent 32µs (3+29) within OpenAPI::Modern::BEGIN@18 which was called: # once (3µs+29µs) by main::BEGIN@2 at line 18
use Carp 'croak';
# spent 32µs making 1 call to OpenAPI::Modern::BEGIN@18 # spent 29µs making 1 call to Exporter::import
1921.31ms26.10ms
# spent 3.87ms (1.55+2.32) within OpenAPI::Modern::BEGIN@19 which was called: # once (1.55ms+2.32ms) by main::BEGIN@2 at line 19
use Safe::Isa;
# spent 3.87ms making 1 call to OpenAPI::Modern::BEGIN@19 # spent 2.23ms making 1 call to Exporter::import
2021.76ms27.70ms
# spent 7.63ms (3.06+4.57) within OpenAPI::Modern::BEGIN@20 which was called: # once (3.06ms+4.57ms) by main::BEGIN@2 at line 20
use Ref::Util qw(is_plain_hashref is_plain_arrayref is_ref);
# spent 7.63ms making 1 call to OpenAPI::Modern::BEGIN@20 # spent 70µs making 1 call to Exporter::import
21219µs270µs
# spent 63µs (10+53) within OpenAPI::Modern::BEGIN@21 which was called: # once (10µs+53µs) by main::BEGIN@2 at line 21
use List::Util 'first';
# spent 63µs making 1 call to OpenAPI::Modern::BEGIN@21 # spent 7µs making 1 call to List::Util::import
22214µs223µs
# spent 14µs (5+9) within OpenAPI::Modern::BEGIN@22 which was called: # once (5µs+9µs) by main::BEGIN@2 at line 22
use Scalar::Util 'looks_like_number';
# spent 14µs making 1 call to OpenAPI::Modern::BEGIN@22 # spent 9µs making 1 call to Exporter::import
2321.68ms23.57ms
# spent 3.54ms (1.83+1.71) within OpenAPI::Modern::BEGIN@23 which was called: # once (1.83ms+1.71ms) by main::BEGIN@2 at line 23
use Feature::Compat::Try;
# spent 3.54ms making 1 call to OpenAPI::Modern::BEGIN@23 # spent 33µs making 1 call to Feature::Compat::Try::import
243548µs335.7ms
# spent 35.6ms (2.81+32.8) within OpenAPI::Modern::BEGIN@24 which was called: # once (2.81ms+32.8ms) by main::BEGIN@2 at line 24
use Encode 2.89;
# spent 35.6ms making 1 call to OpenAPI::Modern::BEGIN@24 # spent 36µs making 1 call to Exporter::import # spent 7µs making 1 call to UNIVERSAL::VERSION
2521.32ms12.09ms
# spent 2.09ms (2.00+84µs) within OpenAPI::Modern::BEGIN@25 which was called: # once (2.00ms+84µs) by main::BEGIN@2 at line 25
use URI::Escape ();
# spent 2.09ms making 1 call to OpenAPI::Modern::BEGIN@25
263160µs3537ms
# spent 537ms (6.26+531) within OpenAPI::Modern::BEGIN@26 which was called: # once (6.26ms+531ms) by main::BEGIN@2 at line 26
use JSON::Schema::Modern 0.557;
# spent 537ms making 1 call to OpenAPI::Modern::BEGIN@26 # spent 8µs making 1 call to UNIVERSAL::VERSION # spent 0s making 1 call to OpenAPI::Modern::__ANON__
27330µs3148µs
# spent 80µs (12+68) within OpenAPI::Modern::BEGIN@27 which was called: # once (12µs+68µs) by main::BEGIN@2 at line 27
use JSON::Schema::Modern::Utilities 0.531 qw(jsonp unjsonp canonical_uri E abort is_equal is_elements_unique);
# spent 80µs making 1 call to OpenAPI::Modern::BEGIN@27 # spent 64µs making 1 call to Exporter::import # spent 4µs making 1 call to UNIVERSAL::VERSION
2823.09ms215.6ms
# spent 15.6ms (4.77+10.8) within OpenAPI::Modern::BEGIN@28 which was called: # once (4.77ms+10.8ms) by main::BEGIN@2 at line 28
use JSON::Schema::Modern::Document::OpenAPI;
# spent 15.6ms making 1 call to OpenAPI::Modern::BEGIN@28 # spent 4µs making 1 call to Mojo::Base::import
29222µs2112µs
# spent 59µs (6+53) within OpenAPI::Modern::BEGIN@29 which was called: # once (6µs+53µs) by main::BEGIN@2 at line 29
use MooX::HandlesVia;
# spent 59µs making 1 call to OpenAPI::Modern::BEGIN@29 # spent 53µs making 1 call to MooX::HandlesVia::import
30336µs3692µs
# spent 352µs (12+340) within OpenAPI::Modern::BEGIN@30 which was called: # once (12µs+340µs) by main::BEGIN@2 at line 30
use MooX::TypeTiny 0.002002;
# spent 352µs making 1 call to OpenAPI::Modern::BEGIN@30 # spent 332µs making 1 call to MooX::TypeTiny::import # spent 8µs making 1 call to UNIVERSAL::VERSION
31232µs2624µs
# spent 315µs (6+309) within OpenAPI::Modern::BEGIN@31 which was called: # once (6µs+309µs) by main::BEGIN@2 at line 31
use Types::Standard 'InstanceOf';
# spent 315µs making 1 call to OpenAPI::Modern::BEGIN@31 # spent 309µs making 1 call to Exporter::Tiny::import
32222µs488µs
# spent 49µs (10+39) within OpenAPI::Modern::BEGIN@32 which was called: # once (10µs+39µs) by main::BEGIN@2 at line 32
use constant { true => JSON::PP::true, false => JSON::PP::false };
# spent 49µs making 1 call to OpenAPI::Modern::BEGIN@32 # spent 36µs making 1 call to constant::import # spent 2µs making 1 call to JSON::PP::true # spent 1µs making 1 call to JSON::PP::false
3323.53ms2568µs
# spent 287µs (6+281) within OpenAPI::Modern::BEGIN@33 which was called: # once (6µs+281µs) by main::BEGIN@2 at line 33
use namespace::clean;
# spent 287µs making 1 call to OpenAPI::Modern::BEGIN@33 # spent 281µs making 1 call to namespace::clean::import
34
3516µs22.30mshas openapi_document => (
# spent 1.91ms making 1 call to OpenAPI::Modern::has # spent 391µs making 1 call to Types::Standard::InstanceOf
36 is => 'ro',
37 isa => InstanceOf['JSON::Schema::Modern::Document::OpenAPI'],
38 required => 1,
39 handles => {
40 openapi_uri => 'canonical_uri', # Mojo::URL
41 openapi_schema => 'schema', # hashref
42 document_get => 'get', # data access using a json pointer
43 },
44);
45
46# held separately because $document->evaluator is a weak ref
4714µs2979µshas evaluator => (
# spent 921µs making 1 call to OpenAPI::Modern::has # spent 58µs making 1 call to Types::Standard::InstanceOf
48 is => 'ro',
49 isa => InstanceOf['JSON::Schema::Modern'],
50 required => 1,
51 handles => [ qw(get_media_type add_media_type) ],
52);
53
5448µs
# spent 70.7s (500µs+70.7) within OpenAPI::Modern::__ANON__[/Users/ether/.perlbrew/libs/36.0@std/lib/perl5/OpenAPI/Modern.pm:79] which was called: # once (500µs+70.7s) by OpenAPI::Modern::__ANON__[(eval 415)[/Users/ether/.perlbrew/libs/36.0@std/lib/perl5/Class/Method/Modifiers.pm:89]:1] at line 1 of (eval 415)[Class/Method/Modifiers.pm:89]
around BUILDARGS => sub ($orig, $class, @args) {
5513µs15µs my $args = $class->$orig(@args);
# spent 5µs making 1 call to Moo::Object::BUILDARGS
56
5711µs if (exists $args->{openapi_document}) {
58 $args->{evaluator} = $args->{openapi_document}->evaluator;
59 }
60 else {
61 # construct document out of openapi_uri, openapi_schema, evaluator, if provided.
62 croak 'missing required constructor arguments: either openapi_document, or openapi_uri'
6310s if not exists $args->{openapi_uri};
64 croak 'missing required constructor arguments: either openapi_document, or openapi_schema'
6510s if not exists $args->{openapi_schema};
66
6715µs19.67ms $args->{evaluator} //= JSON::Schema::Modern->new(validate_formats => 1, max_traversal_depth => 80);
# spent 9.67ms making 1 call to JSON::Schema::Modern::new
68 $args->{openapi_document} = JSON::Schema::Modern::Document::OpenAPI->new(
69 canonical_uri => $args->{openapi_uri},
70 schema => $args->{openapi_schema},
71 evaluator => $args->{evaluator},
72112µs13.30ms );
# spent 3.30ms making 1 call to JSON::Schema::Modern::Document::OpenAPI::new
73
74 # if there were errors, this will die with a JSON::Schema::Modern::Result object
751396µs110.5ms $args->{evaluator}->add_schema($args->{openapi_document});
# spent 10.5ms making 1 call to JSON::Schema::Modern::add_schema
76 }
77
78152µs return $args;
7913µs1152µs};
# spent 152µs making 1 call to Moo::around
80
81sub validate_request ($self, $request, $options = {}) {
82 my $state = {
83 data_path => '/request',
84 initial_schema_uri => $self->openapi_uri, # the canonical URI as of the start or last $id, or the last traversed $ref
85 traversed_schema_path => '', # the accumulated traversal path as of the start, or last $id, or up to the last traversed $ref
86 schema_path => '', # the rest of the path, since the last $id or the last traversed $ref
87 effective_base_uri => Mojo::URL->new->host(scalar _header($request, 'Host'))->scheme('https'),
88 annotations => [],
89 };
90
91 try {
92 my $path_ok = $self->find_path($request, $options);
93 $state->{errors} = delete $options->{errors};
94 return $self->_result($state, 1) if not $path_ok;
95
96 my ($path_template, $path_captures) = $options->@{qw(path_template path_captures)};
97 my $path_item = $self->openapi_document->schema->{paths}{$path_template};
98 my $method = lc $request->method;
99 my $operation = $path_item->{$method};
100
101 $state->{schema_path} = jsonp('/paths', $path_template);
102
103 # PARAMETERS
104 # { $in => { $name => 'path-item'|$method } } as we process each one.
105 my $request_parameters_processed;
106
107 # first, consider parameters at the operation level.
108 # parameters at the path-item level are also considered, if not already seen at the operation level
109 foreach my $section ($method, 'path-item') {
110 foreach my $idx (0 .. (($section eq $method ? $operation : $path_item)->{parameters}//[])->$#*) {
111 my $state = { %$state, schema_path => jsonp($state->{schema_path},
112 ($section eq $method ? $method : ()), 'parameters', $idx) };
113 my $param_obj = ($section eq $method ? $operation : $path_item)->{parameters}[$idx];
114 while (my $ref = $param_obj->{'$ref'}) {
115 $param_obj = $self->_resolve_ref($ref, $state);
116 }
117
118 my $fc_name = $param_obj->{in} eq 'header' ? fc($param_obj->{name}) : $param_obj->{name};
119
120 abort($state, 'duplicate %s parameter "%s"', $param_obj->{in}, $param_obj->{name})
121 if ($request_parameters_processed->{$param_obj->{in}}{$fc_name} // '') eq $section;
122 next if exists $request_parameters_processed->{$param_obj->{in}}{$fc_name};
123 $request_parameters_processed->{$param_obj->{in}}{$fc_name} = $section;
124
125 $state->{data_path} = jsonp($state->{data_path},
126 ((grep $param_obj->{in} eq $_, qw(path query)) ? 'uri' : ()), $param_obj->{in},
127 $param_obj->{name});
128 my $valid =
129 $param_obj->{in} eq 'path' ? $self->_validate_path_parameter($state, $param_obj, $path_captures)
130 : $param_obj->{in} eq 'query' ? $self->_validate_query_parameter($state, $param_obj, _request_uri($request))
131 : $param_obj->{in} eq 'header' ? $self->_validate_header_parameter($state, $param_obj->{name}, $param_obj, [ _header($request, $param_obj->{name}) ])
132 : $param_obj->{in} eq 'cookie' ? $self->_validate_cookie_parameter($state, $param_obj, $request)
133 : abort($state, 'unrecognized "in" value "%s"', $param_obj->{in});
134 }
135 }
136
137 # 3.2 "Each template expression in the path MUST correspond to a path parameter that is included in
138 # the Path Item itself and/or in each of the Path Item’s Operations."
139 foreach my $path_name (sort keys $path_captures->%*) {
140 abort({ %$state, data_path => jsonp($state->{data_path}, qw(uri path), $path_name) },
141 'missing path parameter specification for "%s"', $path_name)
142 if not exists $request_parameters_processed->{path}{$path_name};
143 }
144
145 $state->{data_path} = jsonp($state->{data_path}, 'body');
146 $state->{schema_path} = jsonp($state->{schema_path}, $method);
147
148 if (my $body_obj = $operation->{requestBody}) {
149 $state->{schema_path} = jsonp($state->{schema_path}, 'requestBody');
150
151 while (my $ref = $body_obj->{'$ref'}) {
152 $body_obj = $self->_resolve_ref($ref, $state);
153 }
154
155 if (_body_size($request)) {
156 $self->_validate_body_content($state, $body_obj->{content}, $request);
157 }
158 elsif ($body_obj->{required}) {
159 ()= E({ %$state, keyword => 'required' }, 'request body is required but missing');
160 }
161 }
162 else {
163 ()= E($state, 'unspecified body is present in %s request', uc $method)
164 if ($method eq 'get' or $method eq 'head') and _body_size($request);
165 }
166 }
167 catch ($e) {
168 if ($e->$_isa('JSON::Schema::Modern::Result')) {
169 return $e;
170 }
171 elsif ($e->$_isa('JSON::Schema::Modern::Error')) {
172 push @{$state->{errors}}, $e;
173 }
174 else {
175 ()= E($state, 'EXCEPTION: '.$e);
176 }
177 }
178
179 return $self->_result($state);
180}
181
182sub validate_response ($self, $response, $options = {}) {
183 my $state = {
184 data_path => '/response',
185 initial_schema_uri => $self->openapi_uri, # the canonical URI as of the start or last $id, or the last traversed $ref
186 traversed_schema_path => '', # the accumulated traversal path as of the start, or last $id, or up to the last traversed $ref
187 schema_path => '', # the rest of the path, since the last $id or the last traversed $ref
188 annotations => [],
189 };
190
191 try {
192 my $path_ok = $self->find_path($response->$_call_if_can('request') // $options->{request}, $options);
193 $state->{errors} = delete $options->{errors};
194 return $self->_result($state, 1) if not $path_ok;
195
196 my ($path_template, $path_captures) = $options->@{qw(path_template path_captures)};
197 my $method = lc $options->{method};
198 my $operation = $self->openapi_document->schema->{paths}{$path_template}{$method};
199
200 return $self->_result($state) if not exists $operation->{responses};
201
202 $state->{effective_base_uri} = Mojo::URL->new->host(scalar _header($options->{request}, 'Host'))->scheme('https')
203 if $options->{request};
204 $state->{schema_path} = jsonp('/paths', $path_template, $method);
205
206 my $response_name = first { exists $operation->{responses}{$_} }
207 $response->code, substr(sprintf('%03s', $response->code), 0, -2).'XX', 'default';
208
209 if (not $response_name) {
210 ()= E({ %$state, keyword => 'responses' }, 'no response object found for code %s', $response->code);
211 return $self->_result($state);
212 }
213
214 my $response_obj = $operation->{responses}{$response_name};
215 $state->{schema_path} = jsonp($state->{schema_path}, 'responses', $response_name);
216 while (my $ref = $response_obj->{'$ref'}) {
217 $response_obj = $self->_resolve_ref($ref, $state);
218 }
219
220 foreach my $header_name (sort keys(($response_obj->{headers}//{})->%*)) {
221 next if fc $header_name eq fc 'Content-Type';
222 my $state = { %$state, schema_path => jsonp($state->{schema_path}, 'headers', $header_name) };
223 my $header_obj = $response_obj->{headers}{$header_name};
224 while (my $ref = $header_obj->{'$ref'}) {
225 $header_obj = $self->_resolve_ref($ref, $state);
226 }
227
228 ()= $self->_validate_header_parameter({ %$state,
229 data_path => jsonp($state->{data_path}, 'header', $header_name) },
230 $header_name, $header_obj, [ _header($response, $header_name) ]);
231 }
232
233 $self->_validate_body_content({ %$state, data_path => jsonp($state->{data_path}, 'body') },
234 $response_obj->{content}, $response)
235 if exists $response_obj->{content} and _body_size($response);
236 }
237 catch ($e) {
238 if ($e->$_isa('JSON::Schema::Modern::Result')) {
239 return $e;
240 }
241 elsif ($e->$_isa('JSON::Schema::Modern::Error')) {
242 push @{$state->{errors}}, $e;
243 }
244 else {
245 ()= E($state, 'EXCEPTION: '.$e);
246 }
247 }
248
249 return $self->_result($state);
250}
251
252sub find_path ($self, $request, $options) {
253 my $state = {
254 data_path => '/request/uri/path',
255 initial_schema_uri => $self->openapi_uri, # the canonical URI as of the start or last $id, or the last traversed $ref
256 traversed_schema_path => '', # the accumulated traversal path as of the start, or last $id, or up to the last traversed $ref
257 schema_path => '', # the rest of the path, since the last $id or the last traversed $ref
258 errors => $options->{errors} //= [],
259 $request ? ( effective_base_uri => Mojo::URL->new->host(scalar _header($request, 'Host'))->scheme('https') ) : (),
260 };
261
262 my ($method, $path_template);
263
264 # method from options
265 if (exists $options->{method}) {
266 $method = lc $options->{method};
267 return E({ %$state, data_path => '/request/method' }, 'wrong HTTP method %s', $request->method)
268 if $request and lc $request->method ne $method;
269 }
270 elsif ($request) {
271 $method = $options->{method} = lc $request->method;
272 }
273
274 # path_template and method from operation_id from options
275 if (exists $options->{operation_id}) {
276 my $operation_path = $self->openapi_document->get_operationId_path($options->{operation_id});
277 return E({ %$state, keyword => 'paths' }, 'unknown operation_id "%s"', $options->{operation_id})
278 if not $operation_path;
279 return E({ %$state, schema_path => $operation_path, keyword => 'operationId' },
280 'operation id does not have an associated path') if $operation_path !~ m{^/paths/};
281 (undef, undef, $path_template, $method) = unjsonp($operation_path);
282
283 return E({ %$state, schema_path => jsonp('/paths', $path_template) },
284 'operation does not match provided path_template')
285 if exists $options->{path_template} and $options->{path_template} ne $path_template;
286
287 return E({ %$state, data_path => '/request/method', schema_path => $operation_path },
288 'wrong HTTP method %s', $options->{method})
289 if $options->{method} and lc $options->{method} ne $method;
290
291 $options->{operation_path} = $operation_path;
292 $options->{method} = lc $method;
293 }
294
295 croak 'at least one of request, $options->{method} and $options->{operation_id} must be provided'
296 if not $method;
297
298 # path_template from options
299 if (exists $options->{path_template}) {
300 $path_template = $options->{path_template};
301
302 my $path_item = $self->openapi_document->schema->{paths}{$path_template};
303 return E({ %$state, keyword => 'paths' }, 'missing path-item "%s"', $path_template) if not $path_item;
304
305 return E({ %$state, data_path => '/request/method', schema_path => jsonp('/paths', $path_template), keyword => $method },
306 'missing operation for HTTP method "%s"', $method)
307 if not $path_item->{$method};
308 }
309
310 # path_template from request URI
311 if (not $path_template and $request and my $uri_path = _request_uri($request)->path) {
312 my $schema = $self->openapi_document->schema;
313 croak 'servers not yet supported when matching request URIs'
314 if exists $schema->{servers} and $schema->{servers}->@*;
315
316 # sorting (ascii-wise) gives us the desired results that concrete path components sort ahead of
317 # templated components, except when the concrete component is a non-ascii character or matches [|}~].
318 foreach $path_template (sort keys $schema->{paths}->%*) {
319 my $path_pattern = $path_template =~ s!\{[^/}]+\}!([^/?#]*)!gr;
320 next if $uri_path !~ m/^$path_pattern$/;
321
322 $options->{path_template} = $path_template;
323
324 # perldoc perlvar, @-: $n coincides with "substr $_, $-[n], $+[n] - $-[n]" if "$-[n]" is defined
325 my @capture_values = map
326 Encode::decode('UTF-8', URI::Escape::uri_unescape(substr($uri_path, $-[$_], $+[$_]-$-[$_]))), 1 .. $#-;
327 my @capture_names = ($path_template =~ m!\{([^/?#}]+)\}!g);
328 my %path_captures; @path_captures{@capture_names} = @capture_values;
329
330 my $indexes = [];
331 return E({ %$state, keyword => 'paths' }, 'duplicate path capture name %s', $capture_names[$indexes->[0]])
332 if not is_elements_unique(\@capture_names, $indexes);
333
334 return E({ %$state, keyword => 'paths' }, 'provided path_captures values do not match request URI')
335 if $options->{path_captures} and not is_equal($options->{path_captures}, \%path_captures);
336
337 $options->{path_captures} = \%path_captures;
338 return E({ %$state, data_path => '/request/method', schema_path => jsonp('/paths', $path_template), keyword => $method },
339 'missing operation for HTTP method "%s"', $method)
340 if not exists $schema->{paths}{$path_template}{$method};
341
342 $options->{operation_id} = $self->openapi_document->schema->{paths}{$path_template}{$method}{operationId};
343 delete $options->{operation_id} if not defined $options->{operation_id};
344 $options->{operation_path} = jsonp('/paths', $path_template, $method);
345 return 1;
346 }
347
348 return E({ %$state, keyword => 'paths' }, 'no match found for URI path "%s"', $uri_path);
349 }
350
351 croak 'at least one of request, $options->{path_template} and $options->{operation_id} must be provided'
352 if not $path_template;
353
354 $options->{operation_path} = jsonp('/paths', $path_template, $method);
355
356 # note: we aren't doing anything special with escaped slashes. this bit of the spec is hazy.
357 my @capture_names = ($path_template =~ m!\{([^/}]+)\}!g);
358 return E({ %$state, keyword => 'paths', _schema_path_suffix => $path_template },
359 'provided path_captures names do not match path template "%s"', $path_template)
360 if exists $options->{path_captures}
361 and not is_equal([ sort keys $options->{path_captures}->%* ], [ sort @capture_names ]);
362
363 if (not $request) {
364 $options->@{qw(path_template operation_id)} =
365 ($path_template, $self->openapi_document->schema->{paths}{$path_template}{$method}{operationId});
366 delete $options->{operation_id} if not defined $options->{operation_id};
367 return 1;
368 }
369
370 # if we're still here, we were passed path_template in options or we calculated it from
371 # operation_id, and now we verify it against path_captures and the request URI.
372 my $uri_path = _request_uri($request)->path;
373
374 # 3.2: "The value for these path parameters MUST NOT contain any unescaped “generic syntax”
375 # characters described by [RFC3986]: forward slashes (/), question marks (?), or hashes (#)."
376 my $path_pattern = $path_template =~ s!\{[^/}]+\}!([^/?#]*)!gr;
377 return E({ %$state, keyword => 'paths', _schema_path_suffix => $path_template },
378 'provided %s does not match request URI', exists $options->{path_template} ? 'path_template' : 'operation_id')
379 if $uri_path !~ m/^$path_pattern$/;
380
381 # perldoc perlvar, @-: $n coincides with "substr $_, $-[n], $+[n] - $-[n]" if "$-[n]" is defined
382 my @capture_values = map
383 Encode::decode('UTF-8', URI::Escape::uri_unescape(substr($uri_path, $-[$_], $+[$_]-$-[$_]))), 1 .. $#-;
384 return E({ %$state, keyword => 'paths', _schema_path_suffix => $path_template },
385 'provided path_captures values do not match request URI')
386 if exists $options->{path_captures}
387 and not is_equal([ map $_.'', $options->{path_captures}->@{@capture_names} ], \@capture_values);
388
389 my %path_captures; @path_captures{@capture_names} = @capture_values;
390 $options->@{qw(path_template path_captures operation_id)} =
391 ($path_template, \%path_captures, $self->openapi_document->schema->{paths}{$path_template}{$method}{operationId});
392 delete $options->{operation_id} if not defined $options->{operation_id};
393 $options->{operation_path} = jsonp('/paths', $path_template, $method);
394 return 1;
395}
396
397######## NO PUBLIC INTERFACES FOLLOW THIS POINT ########
398
399sub _validate_path_parameter ($self, $state, $param_obj, $path_captures) {
400 # 'required' is always true for path parameters
401 return E({ %$state, keyword => 'required' }, 'missing path parameter: %s', $param_obj->{name})
402 if not exists $path_captures->{$param_obj->{name}};
403
404 $self->_validate_parameter_content($state, $param_obj, \ $path_captures->{$param_obj->{name}});
405}
406
407sub _validate_query_parameter ($self, $state, $param_obj, $uri) {
408 # parse the query parameters out of uri
409 my $query_params = { _query_pairs($uri) };
410
411 # TODO: support different styles.
412 # for now, we only support style=form and do not allow for multiple values per
413 # property (i.e. 'explode' is not checked at all.)
414 # (other possible style values: spaceDelimited, pipeDelimited, deepObject)
415
416 if (not exists $query_params->{$param_obj->{name}}) {
417 return E({ %$state, keyword => 'required' }, 'missing query parameter: %s', $param_obj->{name})
418 if $param_obj->{required};
419 return 1;
420 }
421
422 # TODO: check 'allowReserved': if true, do not use percent-decoding
423 return E({ %$state, keyword => 'allowReserved' }, 'allowReserved: true is not yet supported')
424 if $param_obj->{allowReserved} // 0;
425
426 $self->_validate_parameter_content($state, $param_obj, \ $query_params->{$param_obj->{name}});
427}
428
429# validates a header, from either the request or the response
430sub _validate_header_parameter ($self, $state, $header_name, $header_obj, $headers) {
431 return 1 if grep fc $header_name eq fc $_, qw(Accept Content-Type Authorization);
432
433 # NOTE: for now, we will only support a single header value.
434 @$headers = map s/^\s*//r =~ s/\s*$//r, @$headers;
435
436 if (not @$headers) {
437 return E({ %$state, keyword => 'required' }, 'missing header: %s', $header_name)
438 if $header_obj->{required};
439 return 1;
440 }
441
442 $self->_validate_parameter_content($state, $header_obj, \ $headers->[0]);
443}
444
445sub _validate_cookie_parameter ($self, $state, $param_obj, $request) {
446 return E($state, 'cookie parameters not yet supported');
447}
448
449sub _validate_parameter_content ($self, $state, $param_obj, $content_ref) {
450 if (exists $param_obj->{content}) {
451 abort({ %$state, keyword => 'content' }, 'more than one media type entry present')
452 if keys $param_obj->{content}->%* > 1; # TODO: remove, when the spec schema is updated
453 my ($media_type) = keys $param_obj->{content}->%*; # there can only be one key
454 my $schema = $param_obj->{content}{$media_type}{schema};
455
456 my $media_type_decoder = $self->get_media_type($media_type); # case-insensitive, wildcard lookup
457 if (not $media_type_decoder) {
458 # don't fail if the schema would pass on any input
459 return if is_plain_hashref($schema) ? !keys %$schema : $schema;
460
461 abort({ %$state, keyword => 'content', _schema_path_suffix => $media_type},
462 'EXCEPTION: unsupported media type "%s": add support with $openapi->add_media_type(...)', $media_type)
463 }
464
465 try {
466 $content_ref = $media_type_decoder->($content_ref);
467 }
468 catch ($e) {
469 return E({ %$state, keyword => 'content', _schema_path_suffix => $media_type },
470 'could not decode content as %s: %s', $media_type, $e =~ s/^(.*)\n/$1/r);
471 }
472
473 $state = { %$state, schema_path => jsonp($state->{schema_path}, 'content', $media_type, 'schema') };
474 return $self->_evaluate_subschema($content_ref->$*, $schema, $state);
475 }
476
477 $state = { %$state, schema_path => jsonp($state->{schema_path}, 'schema') };
478 $self->_evaluate_subschema($content_ref->$*, $param_obj->{schema}, $state);
479}
480
481sub _validate_body_content ($self, $state, $content_obj, $message) {
482 my $content_type = _content_type($message); # does not include charset
483
484 return E({ %$state, data_path => $state->{data_path} =~ s{body}{header/Content-Type}r, keyword => 'content' },
485 'missing header: Content-Type')
486 if not length $content_type;
487
488 my $media_type = (first { $content_type eq fc } keys $content_obj->%*)
489 // (first { m{([^/]+)/\*$} && fc($content_type) =~ m{^\F\Q$1\E/[^/]+$} } keys $content_obj->%*);
490 $media_type = '*/*' if not defined $media_type and exists $content_obj->{'*/*'};
491 return E({ %$state, keyword => 'content' }, 'incorrect Content-Type "%s"', $content_type)
492 if not defined $media_type;
493
494 if (exists $content_obj->{$media_type}{encoding}) {
495 my $state = { %$state, schema_path => jsonp($state->{schema_path}, 'content', $media_type) };
496 # 4.8.14.1 "The key, being the property name, MUST exist in the schema as a property."
497 foreach my $property (sort keys $content_obj->{$media_type}{encoding}->%*) {
498 ()= E({ $state, schema_path => jsonp($state->{schema_path}, 'schema', 'properties', $property) },
499 'encoding property "%s" requires a matching property definition in the schema')
500 if not exists(($content_obj->{$media_type}{schema}{properties}//{})->{$property});
501 }
502
503 # 4.8.14.1 "The encoding object SHALL only apply to requestBody objects when the media type is
504 # multipart or application/x-www-form-urlencoded."
505 return E({ %$state, keyword => 'encoding' }, 'encoding not yet supported')
506 if $content_type =~ m{^multipart/} or $content_type eq 'application/x-www-form-urlencoded';
507 }
508
509 # TODO: handle Content-Encoding header; https://github.com/OAI/OpenAPI-Specification/issues/2868
510 my $content_ref = _content_ref($message);
511
512 # decode the charset, for text content
513 if ($content_type =~ m{^text/} and my $charset = _content_charset($message)) {
514 try {
515 $content_ref = \ Encode::decode($charset, $content_ref->$*, Encode::FB_CROAK | Encode::LEAVE_SRC);
516 }
517 catch ($e) {
518 return E({ %$state, keyword => 'content', _schema_path_suffix => $media_type },
519 'could not decode content as %s: %s', $charset, $e =~ s/^(.*)\n/$1/r);
520 }
521 }
522
523 my $schema = $content_obj->{$media_type}{schema};
524
525 # use the original Content-Type, NOT the possibly wildcard media type from the openapi document
526 # lookup is case-insensitive and falls back to wildcard definitions
527 my $media_type_decoder = $self->get_media_type($content_type);
528 $media_type_decoder = sub ($content_ref) { $content_ref } if $media_type eq '*/*';
529 if (not $media_type_decoder) {
530 # don't fail if the schema would pass on any input
531 return if not defined $schema or is_plain_hashref($schema) ? !keys %$schema : $schema;
532
533 abort({ %$state, keyword => 'content', _schema_path_suffix => $media_type },
534 'EXCEPTION: unsupported Content-Type "%s": add support with $openapi->add_media_type(...)', $content_type)
535 }
536
537 try {
538 $content_ref = $media_type_decoder->($content_ref);
539 }
540 catch ($e) {
541 return E({ %$state, keyword => 'content', _schema_path_suffix => $media_type },
542 'could not decode content as %s: %s', $media_type, $e =~ s/^(.*)\n/$1/r);
543 }
544
545 return if not defined $schema;
546
547 $state = { %$state, schema_path => jsonp($state->{schema_path}, 'content', $media_type, 'schema') };
548 $self->_evaluate_subschema($content_ref->$*, $schema, $state);
549}
550
551# wrap a result object around the errors
552sub _result ($self, $state, $exception = 0) {
553 return JSON::Schema::Modern::Result->new(
554 output_format => $self->evaluator->output_format,
555 formatted_annotations => 0,
556 valid => !$state->{errors}->@*,
557 $exception ? ( exception => 1 ) : (),
558 !$state->{errors}->@*
559 ? (annotations => $state->{annotations}//[])
560 : (errors => $state->{errors}),
561 );
562}
563
564sub _resolve_ref ($self, $ref, $state) {
565 my $uri = Mojo::URL->new($ref)->to_abs($state->{initial_schema_uri});
566 my $schema_info = $self->evaluator->_fetch_from_uri($uri);
567 abort({ %$state, keyword => '$ref' }, 'EXCEPTION: unable to find resource %s', $uri)
568 if not $schema_info;
569
570 abort($state, 'EXCEPTION: maximum evaluation depth exceeded')
571 if $state->{depth}++ > $self->evaluator->max_traversal_depth;
572
573 $state->{initial_schema_uri} = $schema_info->{canonical_uri};
574 $state->{traversed_schema_path} = $state->{traversed_schema_path}.$state->{schema_path}.jsonp('/$ref');
575 $state->{schema_path} = '';
576
577 return $schema_info->{schema};
578}
579
580# evaluates data against the subschema at the current state location
581sub _evaluate_subschema ($self, $data, $schema, $state) {
582 # boolean schema
583 if (not is_plain_hashref($schema)) {
584 return 1 if $schema;
585
586 my @location = unjsonp($state->{data_path});
587 my $location =
588 $location[-1] eq 'body' ? join(' ', @location[-2..-1])
589 : $location[-2] eq 'query' ? 'query parameter'
590 : $location[-2] eq 'path' ? 'path parameter' # this should never happen
591 : $location[-2] eq 'header' ? join(' ', @location[-3..-2])
592 : $location[-2]; # cookie
593 return E($state, '%s not permitted', $location);
594 }
595
596 return 1 if !keys(%$schema); # schema is {}
597
598 # treat numeric-looking data as a string, unless "type" explicitly requests number or integer.
599 if (is_plain_hashref($schema) and exists $schema->{type} and not is_plain_arrayref($schema->{type})
600 and grep $schema->{type} eq $_, qw(number integer) and looks_like_number($data)) {
601 $data = $data+0;
602 }
603 elsif (defined $data and not is_ref($data)) {
604 $data = $data.'';
605 }
606
607 # TODO: also handle multi-valued elements like headers and query parameters, when type=array requested
608 # (and possibly coerce their numeric-looking elements as well)
609
610 my $result = $self->evaluator->evaluate(
611 $data, canonical_uri($state),
612 {
613 data_path => $state->{data_path},
614 traversed_schema_path => $state->{traversed_schema_path}.$state->{schema_path},
615 effective_base_uri => $state->{effective_base_uri},
616 collect_annotations => 1,
617 },
618 );
619
620 push $state->{errors}->@*, $result->errors;
621 push $state->{annotations}->@*, $result->annotations;
622
623 return $result;
624}
625
626# returned object supports ->path
627sub _request_uri ($request) {
628 $request->isa('HTTP::Request') ? $request->uri
629 : $request->isa('Mojo::Message::Request') ? $request->url
630 : croak 'unknown type '.ref($request);
631}
632
633# returns a list of key-value pairs (beware of treating as a hash!)
634sub _query_pairs ($uri) {
635 $uri->isa('URI') ? $uri->query_form
636 : $uri->isa('Mojo::URL') ? $uri->query->pairs->@*
637 : croak 'unknown type '.ref($uri);
638}
639
640# note: this assumes that the header values were already normalized on creation,
641# as sanitizing on read is bypassed
642# beware: the lwp version is list/scalar-context-sensitive
643sub _header ($message, $header_name) {
644 $message->isa('HTTP::Message') ? $message->headers->header($header_name)
645 : $message->isa('Mojo::Message') ? $message->content->headers->header($header_name) // ()
646 : croak 'unknown type '.ref($message);
647}
648
649# normalized, with extensions stripped
650sub _content_type ($message) {
651 $message->isa('HTTP::Message') ? fc $message->headers->content_type
652 : $message->isa('Mojo::Message') ? fc((split(/;/, $message->headers->content_type//'', 2))[0] // '')
653 : croak 'unknown type '.ref($message);
654}
655
656sub _content_charset ($message) {
657 $message->isa('HTTP::Message') ? $message->headers->content_type_charset
658 : $message->isa('Mojo::Message') ? $message->content->charset
659 : croak 'unknown type '.ref($message);
660}
661
662sub _body_size ($message) {
663 $message->isa('HTTP::Message') ? $message->headers->content_length // length $message->content_ref->$*
664 : $message->isa('Mojo::Message') ? $message->headers->content_length // $message->body_size
665 : croak 'unknown type '.ref($message);
666}
667
668sub _content_ref ($message) {
669 $message->isa('HTTP::Message') ? $message->content_ref
670 : $message->isa('Mojo::Message') ? \$message->body
671 : croak 'unknown type '.ref($message);
672}
673
674# wrappers that aren't needed (yet), because they are the same across all supported classes:
675# $request->method
676# $response->code
677# $uri->path
678
67919µs1;
680
681143µs1640µs__END__
 
# spent 0s within OpenAPI::Modern::__ANON__ which was called: # once (0s+0s) by OpenAPI::Modern::BEGIN@26 at line 26
sub OpenAPI::Modern::__ANON__; # xsub