Plack-Middleware-CrossOrigin-0.009/000755 000765 000024 00000000000 12111274667 017356 5ustar00gknopstaff000000 000000 Plack-Middleware-CrossOrigin-0.009/Changes000644 000765 000024 00000002142 12111274667 020650 0ustar00gknopstaff000000 000000 Revision history for Plack-Middleware-CrossOrigin 0.009 Feb 20 2013 - Suppress warnings when checking for buggy WebKit browsers. (Dave Rolsky) 0.008 Jan 29 2013 - Updated browser support documentation. 0.007 Sep 12 2011 - Add continue_on_failure to allow requests to be processed as if the module was not used. - Note required version of Test::More - Fix POD formatting 0.006 Jun 16 2011 - Only apply WebKit workaround to older versions - additional documentation and references, including notes on CSRF protection - Added a psgi script to help test browser behavior 0.005 Mar 16 2011 - Add a workaround for WebKit browsers with preflighted GET requests. 0.004 Feb 08 2011 - Allow setting expose_headers to * to allow all headers. - Fix cross origin OPTIONS requests. - Include all default HTTP and WebDAV methods by default. - Include common WebDAV and web framework headers as allowed headers by default. 0.003 Sep 22 2010 - Fixed handling of expose_headers 0.002 Sep 21 2010 - Fixed handling of allowed headers 0.001 Sep 19 2010 - Initial release Plack-Middleware-CrossOrigin-0.009/lib/000755 000765 000024 00000000000 12111274667 020124 5ustar00gknopstaff000000 000000 Plack-Middleware-CrossOrigin-0.009/LICENSE000644 000765 000024 00000043650 12111274667 020373 0ustar00gknopstaff000000 000000 This software is copyright (c) 2011 by Graham Knop. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2011 by Graham Knop. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2011 by Graham Knop. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Plack-Middleware-CrossOrigin-0.009/Makefile.PL000644 000765 000024 00000002444 12111274667 021334 0ustar00gknopstaff000000 000000 use strict; use warnings; use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( "ABSTRACT" => "Adds headers to allow Cross-Origin Resource Sharing", "AUTHOR" => "Graham Knop ", "BUILD_REQUIRES" => { "Plack::App::File" => 0, "Plack::Builder" => 0, "Plack::Request" => 0, "Plack::Test" => 0, "Socket" => 0, "Test::More" => "0.88" }, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.30" }, "DISTNAME" => "Plack-Middleware-CrossOrigin", "EXE_FILES" => [], "LICENSE" => "perl", "NAME" => "Plack::Middleware::CrossOrigin", "PREREQ_PM" => { "Plack::Middleware" => 0, "Plack::Util" => 0, "Plack::Util::Accessor" => 0, "parent" => 0, "strict" => 0, "warnings" => 0 }, "VERSION" => "0.009", "test" => { "TESTS" => "t/*.t" } ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.56) } ) { my $br = delete $WriteMakefileArgs{BUILD_REQUIRES}; my $pp = $WriteMakefileArgs{PREREQ_PM}; for my $mod ( keys %$br ) { if ( exists $pp->{$mod} ) { $pp->{$mod} = $br->{$mod} if $br->{$mod} > $pp->{$mod}; } else { $pp->{$mod} = $br->{$mod}; } } } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); Plack-Middleware-CrossOrigin-0.009/MANIFEST000644 000765 000024 00000000261 12111274667 020506 0ustar00gknopstaff000000 000000 Changes LICENSE MANIFEST META.json META.yml Makefile.PL README lib/Plack/Middleware/CrossOrigin.pm t/basic.t t/browser-test.psgi t/release-pod-coverage.t t/release-pod-syntax.t Plack-Middleware-CrossOrigin-0.009/META.json000644 000765 000024 00000003231 12111274667 020776 0ustar00gknopstaff000000 000000 { "abstract" : "Adds headers to allow Cross-Origin Resource Sharing", "author" : [ "Graham Knop " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 4.300030, CPAN::Meta::Converter version 2.120921", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Plack-Middleware-CrossOrigin", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.30" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08" } }, "runtime" : { "requires" : { "Plack::Middleware" : "0", "Plack::Util" : "0", "Plack::Util::Accessor" : "0", "parent" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Plack::App::File" : "0", "Plack::Builder" : "0", "Plack::Request" : "0", "Plack::Test" : "0", "Socket" : "0", "Test::More" : "0.88" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "http://github.com/haarg/Plack-Middleware-CrossOrigin/issues" }, "repository" : { "type" : "git", "url" : "git://github.com/haarg/Plack-Middleware-CrossOrigin.git", "web" : "http://github.com/haarg/Plack-Middleware-CrossOrigin" } }, "version" : "0.009" } Plack-Middleware-CrossOrigin-0.009/META.yml000644 000765 000024 00000001454 12111274667 020633 0ustar00gknopstaff000000 000000 --- abstract: 'Adds headers to allow Cross-Origin Resource Sharing' author: - 'Graham Knop ' build_requires: Plack::App::File: 0 Plack::Builder: 0 Plack::Request: 0 Plack::Test: 0 Socket: 0 Test::More: 0.88 configure_requires: ExtUtils::MakeMaker: 6.30 dynamic_config: 0 generated_by: 'Dist::Zilla version 4.300030, CPAN::Meta::Converter version 2.120921' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: Plack-Middleware-CrossOrigin requires: Plack::Middleware: 0 Plack::Util: 0 Plack::Util::Accessor: 0 parent: 0 strict: 0 warnings: 0 resources: bugtracker: http://github.com/haarg/Plack-Middleware-CrossOrigin/issues repository: git://github.com/haarg/Plack-Middleware-CrossOrigin.git version: 0.009 Plack-Middleware-CrossOrigin-0.009/README000644 000765 000024 00000001244 12111274667 020237 0ustar00gknopstaff000000 000000 NAME Plack-Middleware-CrossOrigin - Adds headers to allow Cross-Origin Resource Sharing INSTALLATION To install this distribution, run the following commands: perl Makefile.PL make make test make install Alternatively, have the CPAN client install it: cpan . BUILDING FROM SOURCE Dist::Zilla and several plugins are needed to build this distribution. After installing Dist::Zilla, you can see a list of additional modules needed with the command: dzil authordeps --missing The module can be built with the command dzil build or installed with the command dzil install Plack-Middleware-CrossOrigin-0.009/t/000755 000765 000024 00000000000 12111274667 017621 5ustar00gknopstaff000000 000000 Plack-Middleware-CrossOrigin-0.009/t/basic.t000644 000765 000024 00000022713 12111274667 021074 0ustar00gknopstaff000000 000000 use strict; use warnings; use Test::More 0.88; use Plack::Middleware::CrossOrigin; use Plack::Test; use Plack::Builder; test_psgi app => builder { enable 'CrossOrigin', origins => '*', headers => '*', methods => '*', credentials => 0, max_age => 60*60*24*30, expose_headers => 'X-Exposed-Header', ; sub { [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ] }; }, client => sub { my $cb = shift; my $req; my $res; $req = HTTP::Request->new(GET => 'http://localhost/'); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'No extra headers added with no Origin header'; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), '*', 'Access-Control-Allow-Origin header added'; is $res->header('Access-Control-Expose-Headers'), 'X-Exposed-Header', 'Access-Control-Expose-Headers header added'; is $res->header('Access-Control-Max-Age'), undef, 'No Max-Age header for simple request'; is $res->content, 'Hello World', "CORS handling doesn't interfere with request content"; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), '*', 'Access-Control-Allow-Origin header added for preflight'; is $res->header('Access-Control-Allow-Methods'), 'POST', 'Access-Control-Allow-Methods header added for preflight'; is $res->header('Access-Control-Max-Age'), 60*60*24*30, 'Max-Age header added for preflight'; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Access-Control-Request-Headers' => 'X-Extra-Header', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); ok $res->header('Access-Control-Allow-Origin'), 'Request with extra headers allowed'; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Referer' => 'http://www.example.com/page', 'User-Agent' => 'AppleWebKit/534.16', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), '*', 'Buggy GET request from WebKit includes Allow-Origin header'; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Referer' => 'http://www.example.com/page', 'User-Agent' => 'AppleWebKit/534.19', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'New versions of WebKit don\'t trigger referer workaround'; my @warnings; local $SIG{__WARN__} = sub { push @warnings, join '', @_ }; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'User-Agent' => 'AppleWebKit/534.16', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'Buggy GET request from WebKit without Referer does not include Allow-Origin header'; is_deeply \@warnings, [], 'No warnings from buggy WebKit request'; }; test_psgi app => builder { enable 'CrossOrigin', origins => [ 'http://www.example.com' ], methods => ['GET', 'POST'], headers => ['X-Extra-Header', 'X-Extra-Header-2'], max_age => 60*60*24*30, expose_headers => '*', ; sub { [ 200, [ 'Content-Type' => 'text/plain', 'X-Some-Other-Header' => 'true', ], [ 'Hello World' ] ] }; }, client => sub { my $cb = shift; my $req; my $res; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Access-Control-Request-Headers' => 'X-Extra-Header', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); ok $res->header('Access-Control-Allow-Origin'), 'Request with explicitly listed extra header allowed'; is $res->header('Access-Control-Allow-Origin'), 'http://www.example.com', 'Explicitly listed origin returned'; is $res->header('Access-Control-Allow-Headers'), 'X-Extra-Header, X-Extra-Header-2', 'Allowed headers returned'; is $res->header('Access-Control-Allow-Methods'), 'GET, POST', 'Allowed methods returned'; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Access-Control-Request-Headers' => 'X-Extra-Header-Other', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'Request with unmatched extra header rejected'; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Origin' => 'http://www.example2.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'Request with unmatched origin rejected'; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'DELETE', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'Request with unmatched method rejected'; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->content, 'Hello World', 'OPTIONS request without Allow-Origin processes as normal'; is $res->header('Access-Control-Expose-Headers'), 'X-Some-Other-Header', 'Wildcard expose headers returned'; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Referer' => 'http://www.example.com/page', 'User-Agent' => 'AppleWebKit/534.16', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), 'http://www.example.com', 'Buggy GET request from WebKit includes Allow-Origin header based on referer'; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Referer' => 'http://www.example.com/page', 'User-Agent' => 'AppleWebKit/534.19', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Origin'), undef, 'New versions of WebKit don\'t trigger referer workaround'; }; test_psgi app => builder { enable 'CrossOrigin', origins => '*', methods => '*', credentials => 1, ; sub { [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ] }; }, client => sub { my $cb = shift; my $req; my $res; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->header('Access-Control-Allow-Credentials'), 'true', 'Resource with credentials adds correct header'; is $res->header('Access-Control-Allow-Origin'), 'http://www.example.com', '... and an explicit origin'; }; my $has_run; test_psgi app => builder { enable 'CrossOrigin', origins => 'http://localhost', ; sub { $has_run = 1; [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ]; }; }, client => sub { my $cb = shift; my $req; my $res; $req = HTTP::Request->new(POST => 'http://localhost/', [ 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); is $res->code, 403, 'Disallowed simple request returns 403 error'; ok ! $has_run, ' ... and aborts before running main app'; $has_run = 0; $req = HTTP::Request->new(GET => 'http://localhost/', [ 'Referer' => 'http://www.example.com/page', 'User-Agent' => 'AppleWebKit/534.16', ]); $res = $cb->($req); ok $has_run, 'WebKit workaround always allows app to run'; }; test_psgi app => builder { enable 'CrossOrigin', origins => 'http://localhost', continue_on_failure => 1, ; sub { $has_run = 1; [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ] ]; }; }, client => sub { my $cb = shift; my $req; my $res; $has_run = 0; $req = HTTP::Request->new(POST => 'http://localhost/', [ 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); ok $has_run, 'continue_on_failure allows main app to run for simple requests'; is $res->code, 200, ' ... and passes through results'; is $res->header('Access-Control-Allow-Origin'), undef, ' ... and doesn\'t add headers to allow CORS'; $has_run = 0; $req = HTTP::Request->new(OPTIONS => 'http://localhost/', [ 'Access-Control-Request-Method' => 'POST', 'Origin' => 'http://www.example.com', ]); $res = $cb->($req); ok ! $has_run, 'continue_on_failure doesn\'t run main app for preflighted request'; }; done_testing; Plack-Middleware-CrossOrigin-0.009/t/browser-test.psgi000644 000765 000024 00000032012 12111274667 023143 0ustar00gknopstaff000000 000000 use strict; use warnings; use Plack::Builder; use Plack::App::File; use Plack::Request; use Plack::Util; use Plack::Middleware::CrossOrigin; use Socket; # Adjust these values to test how browsers respond to the different headers my $co_mw = Plack::Middleware::CrossOrigin->new( origins => '*', methods => '*', expose_headers => '*', max_age => 0, ); sub alt_addr { my $address = shift; if ($address =~ /^[\d.]+$/) { return gethostbyaddr(inet_aton($address), AF_INET); } else { no warnings; return ( eval { inet_ntoa(inet_aton($address)) } || $address ); } } builder { enable sub { my $app = shift; sub { my $env = shift; if ($env->{'psgi.multithread'} || $env->{'psgi.multiprocess'}) { return [401, ['Content-Type' => 'text/plain'], ['Unsupported server. Please use a single threaded, single process server.']]; } $app->($env); }; }; my $last_cors = ''; mount '/last_cors' => sub { my $out = $last_cors; $last_cors = ''; [200, ['Content-Type' => 'text/plain'], [$out]]; }; mount '/cors' => builder { my $main_app_run; enable sub { my $app = shift; sub { my $env = shift; my $req = Plack::Request->new($env); $main_app_run = undef; my $in_head = $req->headers; return Plack::Util::response_cb($app->($env), sub { my $res = shift; my $preflight = $req->method eq 'OPTIONS' && $in_head->header('Access-Control-Request-Method'); if ( $preflight ) { $last_cors .= "Preflight request:\n"; } else { $last_cors .= "Actual request:\n"; } if ( $main_app_run ) { $last_cors .= " Main Plack app run\n"; } $last_cors .= " Incoming:\n"; $last_cors .= sprintf " Method: %s\n", $req->method; if ( defined $in_head->header('Origin') ) { $last_cors .= sprintf " Origin: %s\n", $in_head->header('Origin'); } $in_head->scan( sub { my ($k, $v) = @_; return unless $k =~ /^Access-Control/i; $k =~ s/\b(\w)(\w+)\b/\u$1\L$2/g; $last_cors .= sprintf " %s: %s\n", $k, $v; } ); $last_cors .= " Response:\n"; $last_cors .= sprintf " Status code: %s\n", $res->[0]; my %out_headers = @{ $res->[1] }; my @cors_headers = grep { /^Access-Control/i } keys %out_headers; for my $header (@cors_headers) { for my $value (Plack::Util::header_get($res->[1], $header)) { $last_cors .= sprintf " %-30s: %s\n", $header, $value; } } my $will_browser_see = !( $preflight || ( $in_head->header('Origin') && ! @cors_headers) ); if ($will_browser_see) { $res->[2] = [$last_cors]; $last_cors = ''; } }); }; }; enable sub { $co_mw->wrap($_[0]) }; sub { $main_app_run = 1; [ 200, ['X-Some-Other-Header' => 1, 'Content-Type' => 'text/plain'], [ 'output' ] ] }; }; mount '/' => sub { my $env = shift; my $req = Plack::Request->new($env); my $cors = $req->base; $cors->host(alt_addr($cors->host)); $cors->path($cors->path . 'cors'); my $last_cors_url = $req->base; $last_cors_url->path($last_cors_url->path . 'last_cors'); return [ 200, ['Content-Type' => 'text/html'], [ sprintf <<'END_HTML', $cors->scheme, $cors->host_port, $cors->path_query, $last_cors_url ] ]; CORS Test
Requesting from %s://%s
Request Type :
Headers

Result Status:
Results:
END_HTML }; }; Plack-Middleware-CrossOrigin-0.009/t/release-pod-coverage.t000644 000765 000024 00000000765 12111274667 024007 0ustar00gknopstaff000000 000000 #!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; eval "use Pod::Coverage::TrustPod"; plan skip_all => "Pod::Coverage::TrustPod required for testing POD coverage" if $@; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); Plack-Middleware-CrossOrigin-0.009/t/release-pod-syntax.t000644 000765 000024 00000000450 12111274667 023531 0ustar00gknopstaff000000 000000 #!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); Plack-Middleware-CrossOrigin-0.009/lib/Plack/000755 000765 000024 00000000000 12111274667 021156 5ustar00gknopstaff000000 000000 Plack-Middleware-CrossOrigin-0.009/lib/Plack/Middleware/000755 000765 000024 00000000000 12111274667 023233 5ustar00gknopstaff000000 000000 Plack-Middleware-CrossOrigin-0.009/lib/Plack/Middleware/CrossOrigin.pm000644 000765 000024 00000031527 12111274667 026042 0ustar00gknopstaff000000 000000 use strict; use warnings; package Plack::Middleware::CrossOrigin; { $Plack::Middleware::CrossOrigin::VERSION = '0.009'; } # ABSTRACT: Adds headers to allow Cross-Origin Resource Sharing use parent qw(Plack::Middleware); use Plack::Util; use Plack::Util::Accessor qw( origins headers methods max_age expose_headers credentials continue_on_failure ); my @simple_headers = qw( Accept Accept-Language Content-Language ); my @simple_response_headers = qw( Cache-Control Content-Language Content-Type Expires Last-Modified Pragma ); my @common_headers = qw( Cache-Control Depth If-Modified-Since User-Agent X-File-Name X-File-Size X-Requested-With X-Prototype-Version ); my @http_methods = qw( GET HEAD POST ); my @webdav_methods = (@http_methods, qw( CANCELUPLOAD CHECKIN CHECKOUT COPY DELETE GETLIB LOCK MKCOL MOVE OPTIONS PROPFIND PROPPATCH PUT REPORT UNCHECKOUT UNLOCK UPDATE VERSION-CONTROL )); sub prepare_app { my ($self) = @_; $self->origins([$self->origins || ()]) unless ref $self->origins; $self->methods([$self->methods || @webdav_methods]) unless ref $self->methods; $self->headers([$self->headers || @common_headers]) unless ref $self->headers; $self->expose_headers([$self->expose_headers || ()]) unless ref $self->expose_headers; $self->{origins_h} = { map { $_ => 1 } @{ $self->origins } }; $self->{methods_h} = { map { $_ => 1 } @{ $self->methods } }; $self->{headers_h} = { map { lc $_ => 1 } @{ $self->headers } }; $self->{expose_headers_h} = { map { $_ => 1 } @{ $self->expose_headers } }; } sub call { my ($self, $env) = @_; my $origin = $env->{HTTP_ORIGIN}; my $continue_on_failure; if ($origin) { $continue_on_failure = $self->continue_on_failure; } # for preflighted GET requests, some WebKit versions don't # include Origin with the actual request. Fixed in current versions # of WebKit, Chrome, and Safari. # Work around it using the Referer header. # https://bugs.webkit.org/show_bug.cgi?id=50773 # http://code.google.com/p/chromium/issues/detail?id=57836 elsif ($env->{REQUEST_METHOD} eq 'GET' && $env->{HTTP_USER_AGENT} && $env->{HTTP_USER_AGENT} =~ m{\bAppleWebKit/(\d+\.\d+)} && $1 < 534.19 && $env->{HTTP_REFERER} && $env->{HTTP_REFERER} =~ m{\A ( \w+://[^/]+ )}msx ) { $origin = $1; $continue_on_failure = 1; } else { return $self->app->($env); } my @origins = split / /, $origin; my $request_method = $env->{HTTP_ACCESS_CONTROL_REQUEST_METHOD}; my $request_headers = $env->{HTTP_ACCESS_CONTROL_REQUEST_HEADERS}; my @request_headers = $request_headers ? (split /,\s*/, $request_headers) : (); my $preflight = $env->{REQUEST_METHOD} eq 'OPTIONS' && $request_method; my $fail = $continue_on_failure && !$preflight ? $self->app : \&_response_forbidden; my $allowed_origins_h = $self->{origins_h}; my $allowed_methods = $self->methods; my $allowed_methods_h = $self->{methods_h}; my $allowed_headers = $self->headers; my $allowed_headers_h = $self->{headers_h}; my $expose_headers = $self->expose_headers; my $expose_headers_h = $self->{expose_headers_h}; my @headers; if ($allowed_origins_h->{'*'} ) { # allow request to proceed } elsif ( grep { ! defined } @{$allowed_origins_h}{@origins} ) { return $fail->($env); } if ($preflight) { if ( $allowed_methods_h->{'*'} ) { $allowed_methods = [$request_method]; } elsif ( ! $allowed_methods_h->{$request_method} ) { return _response_forbidden(); } if ( $allowed_headers_h->{'*'} ) { $allowed_headers = \@request_headers; } elsif ( grep { ! defined } @{$allowed_headers_h}{map lc, @request_headers} ) { return _response_forbidden(); } } if ($self->credentials) { push @headers, 'Access-Control-Allow-Credentials' => 'true'; } elsif ($allowed_origins_h->{'*'}) { $origin = '*'; } push @headers, 'Access-Control-Allow-Origin' => $origin; my $res; if ($preflight) { if (defined $self->max_age) { push @headers, 'Access-Control-Max-Age' => $self->max_age; } push @headers, 'Access-Control-Allow-Methods' => $_ for @$allowed_methods; push @headers, 'Access-Control-Allow-Headers' => $_ for @$allowed_headers; $res = _response_success(); } else { $res = $self->app->($env); } return $self->response_cb($res, sub { my $res = shift; if ($expose_headers_h->{'*'}) { my %headers = @{ $res->[1] }; delete @headers{@simple_response_headers}; $expose_headers = [keys %headers]; } push @headers, 'Access-Control-Expose-Headers' => $_ for @$expose_headers; push @{ $res->[1] }, @headers; }); } sub _response_forbidden { [403, ['Content-Type' => 'text/plain', 'Content-Length' => 9], ['forbidden']]; } sub _response_success { [200, [ 'Content-Type' => 'text/plain' ], [] ]; } 1; __END__ =pod =head1 NAME Plack::Middleware::CrossOrigin - Adds headers to allow Cross-Origin Resource Sharing =head1 VERSION version 0.009 =head1 SYNOPSIS # Allow any WebDAV or standard HTTP request from any location. builder { enable 'CrossOrigin', origins => '*'; $app; }; # Allow GET and POST requests from any location, cache results for 30 days. builder { enable 'CrossOrigin', origins => '*', methods => ['GET', 'POST'], max_age => 60*60*24*30; $app; }; =head1 DESCRIPTION Adds Cross Origin Request Sharing headers used by modern browsers to allow C to work across domains. This module will also help protect against CSRF attacks in some browsers. This module attempts to fully conform to the CORS spec, while allowing additional flexibility in the values specified for the of the headers. =head1 CORS REQUESTS IN BRIEF There are two types of CORS requests. Simple requests, and preflighted requests. =head2 Simple Requests A simple request is one that could be generated by a standard HTML form. Either a C or C request, with no additional headers. For these requests, the server processes the request as normal, and attaches the correct CORS headers in the response. The browser then decides based on those headers whether to allow the client script access to the response. =head2 Preflighted Requests If additional headers are specified, or a method other than C or C is used, the request must be preflighted. This means that the browser will first send a special request to the server to check if access is allowed. If the server allows it by responding with the correct headers, the actual request is then performed. =head1 CSRF Protection Some browsers will also provide same headers with cross domain C requests from HTML forms. These requests will also be checked against the allowed origins and rejected before they reach the rest of your Plack application. =head1 CONFIGURATION =over 8 =item origins A list of allowed origins. Origins should be formatted as a URL scheme and host, with no path information. (C) 'C<*>' can be specified to allow access from any location. Must be specified for this middleware to have any effect. This will be matched against the C request header, and will control the C response header. If the origin does not match, the request is aborted. =item headers A list of allowed request headers. 'C<*>' can be specified to allow any headers. Controls the C response header. Includes a set of headers by default to simplify working with WebDAV and AJAX frameworks: =over 4 =item * C =item * C =item * C =item * C =item * C =item * C =item * C =item * C =back =item methods A list of allowed methods. '*' can be specified to allow any methods. Controls the C response header. Defaults to all of the standard HTTP and WebDAV methods. =item max_age The max length in seconds to cache the response data for. Controls the C response header. If not specified, the web browser will decide how long to use. =item expose_headers A list of allowed headers to expose to the client. '*' can be specified to allow the browser to see all of the response headers. Controls the C response header. =item credentials Whether the resource will be allowed with user credentials (cookies, HTTP authentication, and client-side SSL certificates) supplied. Controls the C response header. =item continue_on_failure Normally, simple requests with an Origin that hasn't been allowed will be stopped before they continue to the main app. If this option is set, the request will be allowed to continue, but no CORS headers will be added to the response. This matches how non-allowed requests would be handled if this module was not used at all. This disables the CSRF protection and is not recommended. It could be needed for applications that need to allow cross-origin HTML form Cs without whitelisting domains. =back =head1 BROWSER SUPPORT Different browsers have different levels of support for CORS headers. =over 8 =item Gecko (Firefox, Seamonkey) Initially supported in Gecko 1.9.1 (Firefox 3.5). Supports the complete CORS spec for Cs. Does not yet provide the C header for CSRF protection (L). =item WebKit (Safari, Google Chrome) Initially supported in Safari 4 and Chrome 3. Supports the complete CORS spec. The C feature has been supported since WebKit v535.18 (Safari 6, Chrome 18). Preflighted requests were buggy prior to WebKit v534.19 (Safari 5.1, Chrome 11), but this module uses a workaround where possible (using the C header). Also provides the C header for CSRF protection starting with WebKit v528.5 (Chrome 2, Safari 4). =item Internet Explorer Initially supported in IE8. Not supported with the standard C object. A separate object, C, must be used. Only C and C methods are allowed. No extra headers can be added to the request. Neither the status code or any headers aside from C can be retrieved from the response. IE10 supports CORS via the standard C object. =item Opera Opera and Opera Mobile support CORS since version 12. =back =head1 SEE ALSO =head2 CORS Resources =over 4 =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =back =head2 CSRF Resources =over 4 =item * L =item * L =item * L =item * L =back =head2 Related Technologies =over 4 =item * L =item * L =back =head1 AUTHOR Graham Knop =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011 by Graham Knop. 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