CORS.pm

filter: Statementstmt 93.8% 167 / 178 Branchbran 88.5% 62 / 70 Conditioncond 73.6% 14 / 19 MC/DCmcdc 41.6% 5 / 12 Subroutinesub 100% 18 / 18 Podpod n/a totaltotal 89.5% 266 / 297 CC 45 SCAR 30.3
CC
45
Cov
91%
_handle
35.3
_prefl_handle
5.1
_add_rule
5.0
CRAP 20.6
↑ Summary CORS/Sharing.pm »
1 package Dancer::Plugin::CORS;
2  
3 11 ▶use Modern::Perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use Dancer::Plugin::CORS::Sharing;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 =head1 NAME
7  
8 Dancer::Plugin::CORS - A plugin for using cross origin resource sharing
9  
10 =head1 VERSION
11  
12 Version 0.11
13  
14 =cut
15  
16 11 our $VERSION = '0.11';
17  
18 =head1 DESCRIPTION
19  
20 Cross origin resource sharing is a feature used by modern web browser to bypass cross site scripting restrictions. A webservice can provide those rules from which origin a client is allowed to make cross-site requests. This module helps you to setup such rules.
21  
22 =head1 SYNOPSIS
23  
24 use Dancer::Plugin::CORS;
25  
26 get '/foo' => sub { ... };
27 share '/foo' =>
28 origin => 'http://localhost/',
29 credentials => 1,
30 expose => [qw[ Content-Type ]],
31 method => 'GET',
32 headers => [qw[ X-Requested-With ]],
33 maxage => 7200,
34 timing => 1,
35 ;
36  
37 =cut
38  
39 11 ▶use Carp qw(croak confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
40 11 ▶use Dancer ':syntax';
Subroutine BEGIN: called CC=1 SCAR=0.0
41 11 ▶use Dancer::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 11 ▶use Sub::Name;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 11 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
44 11 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 11 ▶use constant DEBUG => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 11 my $routes = {};
49  
50 sub _isin($@) {
51 14 ▶ shift ~~ \@_;
Subroutine _isin: called CC=1 SCAR=0.0
52 }
53  
54 sub _isuri(_) {
55 48 ▶ shift =~ m|(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?|
Subroutine _isuri: called CC=1 SCAR=0.0
56 }
57  
58 sub _handle;
59 11 my $current_route;
60  
61 sub _prefl_handle {
62 30 ▶ debug "[CORS] entered preflight request main subroutine" if DEBUG;
Subroutine _prefl_handle: called CC=5 SCAR=16.3
63 30 ▶ unless (defined $current_route) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $current_route) 0 30 30
64 0 warning "[CORS] current route not defined!";
65 0 return;
66 }
67 30 ▶ unless(_handle($current_route)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_handle($current_route)) 22 8 30
68 22 my $request = Dancer::SharedData->request;
69 22 ▶ while ($current_route = $current_route->next) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_route = $current_route->next) 18 6 24
70 18 ▶ if ($current_route->match($request)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_route->match($request)) 16 2 18
71 16 debug "[CORS] going to next handler" if DEBUG;
72 16 pass;
73 }
74 }
75 6 debug "[CORS] no more rules." if DEBUG;
76 }
77 14 $current_route = undef;
78 }
79  
80 sub _add_rule($%) {
81 30 ▶ my ($route, %options) = @_;
Subroutine _add_rule: called CC=5 SCAR=16.1
82
83 30 ▶ if (blessed $route and $route->isa('Dancer::Route')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($route) and $route->isa("Dancer::Route")) 22 8 30
Condition66%2/3
builtin::blessed($route) and $route->isa("Dancer::Route")
!ll&&!rl&&r
8022
MC/DC50%1/2
builtin::blessed($route) and $route->isa("Dancer::Route")
builtin::blessed($route) $route->isa("Dancer::Route")
Truth table66%2/3
A and B
A= builtin::blessed($route)B= $route->isa("Dancer::Route")
ABresult
0X0
100
111
84 22 my $prefl = Dancer::App->current->registry->add_route(Dancer::Route->new(
85 method => 'options',
86 code => \&_prefl_handle,
87 options => $route->options,
88 pattern => $route->pattern
89 ));
90 22 $options{method} = uc($route->method);
91 22 $routes->{$prefl} = [{ %options }];
92 22 debug "registered preflight route handler for ".$route->method." pattern: ".$route->pattern."\n" if DEBUG;
93 }
94
95 30 ▶ unless (exists $routes->{$route}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $routes->{$route}) 25 5 30
96 25 $routes->{$route} = [];
97 25 ▶ unless (ref $route) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $route) 8 17 25
98 8 debug "registered preflight route handler for any pattern: $route\n" if DEBUG;
99 8 options $route => \&_prefl_handle;
100 }
101 }
102 30 push @{ $routes->{$route} } => \%options;
103 }
104  
105 sub _handle {
106 52 ▶ my $route = shift;
Subroutine _handle: called CC=34 SCAR=35.7
107 52 my $request = Dancer::SharedData->request;
108 52 my $path = $request->path_info;
109
110 52 ▶ unless (exists $routes->{$path} or exists $routes->{$route}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $routes->{$path} or exists $routes->{$route}) 0 52 52
Condition66%2/3
exists $routes->{$path} or exists $routes->{$route}
l!l&&r!l&&!r
13390
MC/DC0%0/2
exists $routes->{$path} or exists $routes->{$route}
exists $routes->{$path} exists $routes->{$route}
Truth table66%2/3
A or B
A= exists $routes->{$path}B= exists $routes->{$route}
ABresult
1X1
011
000
111 0 debug "[CORS] path $path or route $route did not no matched any rule" if DEBUG;
112 }
113
114 52 my $preflight = uc $request->method eq 'OPTIONS';
115
116 52 debug "[CORS] preflight request" if DEBUG and $preflight;
117
118 52 my $origin = scalar($request->header('Origin'));
119
120 52 ▶ unless (defined $origin) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $origin) 4 48 52
121 4 debug "[CORS] no origin header present in request" if DEBUG;
122 4 return;
123 }
124  
125 48 ▶ unless (_isuri($origin)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&_isuri($origin)) 0 48 48
126 0 debug "[CORS] origin '$origin' is not a URI" if DEBUG;
127 0 return;
128 }
129
130 48 ▶ my $requested_method = $preflight
Branch: 1 branch
BranchTrueFalseTotal
$preflight ? : 28 20 48
131 ? scalar($request->header('Access-Control-Request-Method'))
132 : $request->method
133 ;
134 48 ▶ unless (defined $requested_method) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $requested_method) 0 48 48
135 0 debug "[CORS] no request method defined" if DEBUG;
136 }
137  
138 48 ▶ my @requested_headers = map { s{\s+}{}g; $_ } split /,+/, (scalar($request->header('Access-Control-Request-Headers')) || '');
Condition100%2/2
scalar $request->header('Access-Control-Request-Headers') || ''
l!l
147
MC/DC100%1/1
scalar $request->header('Access-Control-Request-Headers') || ''
scalar $request->header('Access-Control-Request-Headers')
Truth table100%2/2
A
A= scalar $request->header('Access-Control-Request-Headers')
Aresult
11
00
139
140 48 my ($ok, $i) = (0, 0);
141 48 my ($headers, $xoptions);
142
143 48 ▶ if (exists $routes->{$route}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $routes->{$route}) { } 37 11 48
144 37 $path = "$route";
145 37 debug "[CORS] dynamic route" if DEBUG;
146 } else {
147 11 debug "[CORS] static route" if DEBUG;
148 }
149
150 48 my $n = scalar @{$routes->{$path}};
151
152 48 RULE: foreach my $options (@{$routes->{$path}}) {
153 49 debug "[CORS] testing rule ".++$i." of $n" if DEBUG;
154 49 if (DEBUG) {
155 11 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
156 debug Dumper($options);
157 }
158 49 $headers = {};
159 49 ▶ if (exists $options->{origin}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{'origin'}) { } 46 3 49
160 46 given (ref $options->{origin}) {
161 46 when ('CODE') {
162 5 ▶ if (!$options->{origin}->(URI->new($origin))) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $options->{"origin"}->("URI"->new($origin))) 3 2 5
163 3 debug "[CORS] origin $origin did not matched against coderef" if DEBUG;
164 3 next RULE;
165 }
166 }
167 41 when ('ARRAY') {
168 2 ▶ unless (_isin($origin => @{ $options->{origin} })) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&_isin($origin, @{$$options{"origin"};})) 1 1 2
169 1 debug "[CORS] origin $origin is not in array" if DEBUG;
170 1 next RULE;
171 }
172 }
173 39 when ('Regexp') {
174 2 ▶ unless ($origin =~ $options->{origin}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($origin =~ /$options->{"origin"}/u) 1 1 2
175 1 debug "[CORS] origin $origin did not matched against regexp" if DEBUG;
176 1 next RULE;
177 }
178 }
179 37 when ('') {
180 37 ▶ unless ($options->{origin} eq $origin) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"origin"} eq $origin) 5 32 37
181 5 debug "[CORS] origin $origin did not matched against static string" if DEBUG;
182 5 next RULE;
183 }
184 }
185 0 default {
186 0 confess("unknown origin type: $_");
187 }
188 }
189 } else {
190 3 $origin = '*';
191 }
192 39 $headers->{'Access-Control-Allow-Origin'} = $origin;
193 39 ▶ $headers->{'Vary'} = 'Origin' if $origin ne '*';
Branch: 1 branch
BranchTrueFalseTotal
if $origin ne "*" 36 3 39
194
195 39 ▶ if (exists $options->{timing}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"timing"}) 3 36 39
196 3 ▶ if (defined $options->{timing} and $options->{timing} eq '1') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{'timing'} and $options->{'timing'} eq '1') { } 2 1 3
Condition66%2/3
defined $options->{"timing"} and $options->{"timing"} eq 1
!ll&&!rl&&r
102
MC/DC50%1/2
defined $options->{"timing"} and $options->{"timing"} eq 1
defined $options->{"timing"} $options->{"timing"} eq 1
Truth table66%2/3
A and B
A= defined $options->{"timing"}B= $options->{"timing"} eq 1
ABresult
0X0
100
111
197 2 $headers->{'Timing-Allow-Origin'} = $headers->{'Access-Control-Allow-Origin'};
198 } else {
199 1 $headers->{'Timing-Allow-Origin'} = 'null';
200 }
201 }
202
203 39 ▶ if (exists $options->{credentials}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"credentials"}) 2 37 39
204 2 ▶ if (!!$options->{credentials}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (not $options->{"credentials"}) 2 0 2
205 2 ▶ if ($origin eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($origin eq "*") 1 1 2
206 1 warning('For a resource that supports credentials a origin matcher must be specified.');
207 1 next RULE;
208 }
209 1 $headers->{'Access-Control-Allow-Credentials'} = 'true' ;
210 }
211 }
212
213 38 ▶ if (exists $options->{expose}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"expose"}) 2 36 38
214 2 $headers->{'Access-Control-Expose-Headers'} = $options->{expose};
215 }
216
217 38 ▶ if (exists $options->{methods}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $options->{'methods'}) { } 10 28 38
elsif (exists $options->{'method'}) { } 28 0 28
218 10 ▶ unless (_isin(lc $requested_method => map lc, @{ $options->{methods} })) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&_isin(lc $requested_method, map(lc($_), @{$$options{"methods"};}))) 7 3 10
219 7 debug "[CORS] request method not allowed" if DEBUG;
220 7 next RULE;
221 }
222 3 $headers->{'Access-Control-Allow-Methods'} = join ', ' => map uc, @{ $options->{methods} };
223 } elsif (exists $options->{method}) {
224 28 ▶ unless ($options->{method} eq $requested_method) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"method"} eq $requested_method) 10 18 28
225 10 debug "[CORS] request method '$requested_method' not allowed: ".$options->{method} if DEBUG;
226 10 next RULE;
227 }
228 18 $headers->{'Access-Control-Allow-Methods'} = $options->{method};
229 }
230
231 21 ▶ if (exists $options->{headers}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $options->{'headers'}) { } 2 19 21
elsif (@requested_headers) { } 0 19 19
232 2 foreach my $requested_header (@requested_headers) {
233 2 ▶ unless (_isin(lc $requested_header => map lc, @{ $options->{headers} })) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&_isin(lc $requested_header, map(lc($_), @{$$options{"headers"};}))) 0 2 2
234 0 debug "[CORS] requested headers did not match allowed in rule" if DEBUG;
235 0 next RULE;
236 }
237 }
238 2 $headers->{'Access-Control-Allow-Headers'} = join ', ' => @{ $options->{headers} };
239 } elsif (@requested_headers) {
240 0 $headers->{'Access-Control-Allow-Headers'} = join ', ' => @requested_headers;
241 }
242  
243 21 ▶ if ($preflight and exists $options->{maxage}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preflight and exists $options->{"maxage"}) 2 19 21
Condition100%3/3
$preflight and exists $options->{"maxage"}
!ll&&!rl&&r
1362
MC/DC100%2/2
$preflight and exists $options->{"maxage"}
$preflight exists $options->{"maxage"}
Truth table100%3/3
A and B
A= $preflightB= exists $options->{"maxage"}
ABresult
0X0
100
111
244 2 $headers->{'Access-Control-Max-Age'} = $options->{maxage};
245 }
246
247 21 $ok = 1;
248 21 var CORS => {%$options};
249 21 Dancer::SharedData->response->headers(%$headers);
250 21 if (DEBUG) {
251 11 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
252 debug Dumper({headers => $headers});
253 }
254 21 last RULE;
255 }
256  
257 48 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 21 27 48
258 21 debug "[CORS] matched!" if DEBUG;
259 } else {
260 27 debug "[CORS] no rule matched" if DEBUG;
261 }
262
263 48 return $ok;
264 }
265  
266 =head1 KEYWORDS
267  
268 =head2 share(C<$route>, C<%options>)
269  
270 The parameter C<$route> may be any valid path like used I<get>, I<post>, I<put>, I<delete> or I<patch> but not I<option>.
271  
272 Alternatively a L<Dancer::Route> object may be used instead:
273  
274 $route = get '/' => sub { ... };
275 share $route => ... ;
276  
277 For any route more than one rule may be defined. The order is relevant: the first matching rule wins.
278  
279 Following keywords recognized by C<%options>:
280  
281 =over 4
282  
283 =item I<origin>
284  
285 This key defines a static origin (scalar), a list (arrayref), a regex or a subroutine.
286  
287 If not specified, any origin is allowed.
288  
289 If a subroutine is used, the first passed parameter is a L<URI> object. It should return a true value if this origin is allowed to access the route in question; otherwise false.
290  
291 origin => sub { shift->host ~~ [ 'localhost', '127.0.0.1', '::1' ] } # allow only from localhost
292  
293 Hint: a origin consists of protocol, hostname and maybe a port. Examples: C<http://www.example.com>, C<https://securesite.com>, C<http://localhost:3000>, C<http://127.0.0.1>, C<http://[::1]>
294  
295 =item I<credentials>
296  
297 This indicates whether cookies, HTTP authentication and/or client-side SSL certificates may sent by a client. Allowed values are C<0> or C<1>.
298  
299 This option must be used together with I<origin>.
300  
301 =item I<expose>
302  
303 A comma-seperated list of headers, that a client may extract from response for use in a client application.
304  
305 =item I<methods>
306  
307 A arrayref of allowed methods. If no methods are specified, all methods are allowed.
308  
309 =item I<method>
310  
311 A string containing a single supported method. This parameter is autofilled when I<share()> is used together with a L<Dancer::Route> object. If no method is specified, any method is allowed.
312  
313 =item I<headers>
314  
315 A arrayref of allowed request headers. In most cases that should be C<[ 'X-Requested-With' ]> when ajax requests are made. If not headers are specified, all requested headers are allowed.
316  
317 =item I<maxage>
318  
319 A maximum time (in seconds) a client may cache a preflight request. This can decrease the amount of requests made to the webservice.
320  
321 =item I<timing>
322  
323 Allow access to the resource timing information. If set to 1, the header C<Timing-Allow-Origin> is set to the same value as I<Access-Control-Allow-Origin>. Otherwise, its set to the value I<null>. If the keyword is not present, no I<Timing-Allow-Origin> header will be appended to response. See L<http://www.w3.org/TR/resource-timing/#cross-origin-resources> for more information.
324  
325 =back
326  
327 =cut
328  
329 11 register(share => \&_add_rule);
330  
331 hook(before => sub {
332 36 ▶ $current_route = shift || return;
Subroutine __ANON__: called CC=3 SCAR=11.0
Condition50%1/2
shift() || (return)
l!l
360
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
333 36 my $preflight = uc Dancer::SharedData->request->method eq 'OPTIONS';
334 36 ▶ if ($preflight) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preflight) { } 14 22 36
335 14 debug "[CORS] pre-check: preflight request, handle within main subroutine" if DEBUG;
336 } else {
337 22 debug "[CORS] pre-check: no preflight, handle actual request now" if DEBUG;
338 22 _handle($current_route);
339 }
340 11 });
341  
342 11 my $current_sharing;
343  
344 =head2 sharing
345  
346 This keyword is a helper for re-using rules for many routes.
347  
348 See L<Dancer::Plugin::CORS::Sharing> for more information about this feature.
349  
350 =cut
351  
352 register sharing => sub {
353 7 ▶ my $class = __PACKAGE__.'::Sharing';
Subroutine __ANON__: called CC=2 SCAR=7.0
354 7 ▶ $current_sharing ||= $class->new(@_,_add_rule=>\&_add_rule);
Condition66%2/3
$current_sharing ||= $class->new(@_, "_add_rule", \&Dancer::Plugin::CORS::_add_rule)
l!l&&r!l&&!r
610
MC/DC0%0/2
$current_sharing ||= $class->new(@_, "_add_rule", \&Dancer::Plugin::CORS::_add_rule)
$current_sharing $class->new(@_, "_add_rule", \&Dancer::Plugin::CORS::_add_rule)
Truth table66%2/3
A ||= B
A= $current_sharingB= $class->new(@_, "_add_rule", \&Dancer::Plugin::CORS::_add_rule)
ABresult
1X1
011
000
355 7 return $current_sharing;
356 11 };
357  
358 =head1 AUTHOR
359  
360 David Zurborg, C<< <zurborg@cpan.org> >>
361  
362 =head1 BUGS
363  
364 Please report any bugs or feature requests trough my project management tool
365 at L<http://development.david-zurb.org/projects/libdancer-plugin-cors-perl/issues/new>. I
366 will be notified, and then you'll automatically be notified of progress on
367 your bug as I make changes.
368  
369 =head1 SUPPORT
370  
371 You can find documentation for this module with the perldoc command.
372  
373 perldoc Dancer::Plugin::CORS
374  
375 You can also look for information at:
376  
377 =over 4
378  
379 =item * Redmine: Homepage of this module
380  
381 L<http://development.david-zurb.org/projects/libdancer-plugin-cors-perl>
382  
383 =item * RT: CPAN's request tracker
384  
385 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dancer-Plugin-CORS>
386  
387 =item * AnnoCPAN: Annotated CPAN documentation
388  
389 L<http://annocpan.org/dist/Dancer-Plugin-CORS>
390  
391 =item * CPAN Ratings
392  
393 L<http://cpanratings.perl.org/d/Dancer-Plugin-CORS>
394  
395 =item * Search CPAN
396  
397 L<http://search.cpan.org/dist/Dancer-Plugin-CORS/>
398  
399 =back
400  
401 =head1 COPYRIGHT & LICENSE
402  
403 Copyright 2014 David Zurborg, all rights reserved.
404  
405 This program is released under the following license: open-source
406  
407 =cut
408  
409 11 register_plugin;
410 11 1;
↑ Summary CORS/Sharing.pm »