blib/lib/PAGI/Middleware/CORS.pm untested

filter: Statementstmt 0.0% 0 / 95 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 23 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 152 CC 6 SCAR 27.4
CC
6
Cov
0%
wrap
30.0
_init
6.0
BEGIN
2.0
CRAP 15.5
1 package PAGI::Middleware::CORS;
2 $PAGI::Middleware::CORS::VERSION = '0.002001';
3 use strict;
4 use warnings;
5 use parent 'PAGI::Middleware';
6 use Future::AsyncAwait;
7  
8 =head1 NAME
9  
10 PAGI::Middleware::CORS - Cross-Origin Resource Sharing middleware
11  
12 =head1 SYNOPSIS
13  
14 use PAGI::Middleware::Builder;
15  
16 my $app = builder {
17 enable 'CORS',
18 origins => ['https://example.com', 'https://app.example.com'],
19 methods => ['GET', 'POST', 'PUT', 'DELETE'],
20 headers => ['Content-Type', 'Authorization'],
21 credentials => 1,
22 max_age => 86400;
23 $my_app;
24 };
25  
26 =head1 DESCRIPTION
27  
28 PAGI::Middleware::CORS implements Cross-Origin Resource Sharing (CORS)
29 for PAGI applications. It handles preflight OPTIONS requests and adds
30 the appropriate CORS headers to responses.
31  
32 =head1 CONFIGURATION
33  
34 =over 4
35  
36 =item * origins (default: ['*'])
37  
38 Array of allowed origins, or ['*'] for any origin.
39  
40 =item * methods (default: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])
41  
42 Array of allowed HTTP methods.
43  
44 =item * headers (default: ['Content-Type', 'Authorization', 'X-Requested-With'])
45  
46 Array of allowed request headers.
47  
48 =item * expose_headers (default: [])
49  
50 Array of headers to expose to the client.
51  
52 =item * credentials (default: 0)
53  
54 If true, allow credentials (cookies, auth headers).
55  
56 =item * max_age (default: 86400)
57  
58 Max age for preflight cache in seconds.
59  
60 =back
61  
62 =cut
63  
64 sub _init {
65 my ($self, $config) = @_;
66  
67 $self->{origins} = $config->{origins} // ['*'];
68 $self->{methods} = $config->{methods} // [qw(GET POST PUT DELETE PATCH OPTIONS)];
69 $self->{headers} = $config->{headers} // [qw(Content-Type Authorization X-Requested-With)];
70 $self->{expose_headers} = $config->{expose_headers} // [];
71 $self->{credentials} = $config->{credentials} // 0;
72 $self->{max_age} = $config->{max_age} // 86400;
73  
74 if ($self->{credentials} && grep { $_ eq '*' } @{$self->{origins}}) {
75 warn "PAGI::Middleware::CORS: wildcard origins ('*') with credentials "
76 . "enabled reflects any Origin with Access-Control-Allow-Credentials. "
77 . "This allows any website to make credentialed cross-origin requests. "
78 . "Consider specifying explicit origins.\n";
79 }
80 }
81  
82 sub wrap {
83 my ($self, $app) = @_;
84  
85 return async sub {
86 my ($scope, $receive, $send) = @_;
87 # Only handle HTTP requests
88 if ($scope->{type} ne 'http') {
89 await $app->($scope, $receive, $send);
90 return;
91 }
92  
93 # Get Origin header
94 my $origin = $self->_get_header($scope, 'origin');
95  
96 # Check if this is a preflight request
97 if ($scope->{method} eq 'OPTIONS' && $origin) {
98 await $self->_handle_preflight($scope, $send, $origin);
99 return;
100 }
101  
102 # For actual requests, add CORS headers to response
103 if ($origin && $self->_is_origin_allowed($origin)) {
104 my $wrapped_send = async sub {
105 my ($event) = @_;
106 if ($event->{type} eq 'http.response.start') {
107 $self->_add_cors_headers($event->{headers}, $origin);
108 }
109 await $send->($event);
110 };
111 await $app->($scope, $receive, $wrapped_send);
112 } else {
113 await $app->($scope, $receive, $send);
114 }
115 };
116 }
117  
118 async sub _handle_preflight {
119 my ($self, $scope, $send, $origin) = @_;
120  
121 my @headers;
122  
123 if ($self->_is_origin_allowed($origin)) {
124 $self->_add_cors_headers(\@headers, $origin);
125  
126 # Add preflight-specific headers
127 push @headers, ['Access-Control-Allow-Methods', join(', ', @{$self->{methods}})];
128 push @headers, ['Access-Control-Allow-Headers', join(', ', @{$self->{headers}})];
129 push @headers, ['Access-Control-Max-Age', $self->{max_age}];
130 }
131  
132 await $send->({
133 type => 'http.response.start',
134 status => 204,
135 headers => \@headers,
136 });
137  
138 await $send->({
139 type => 'http.response.body',
140 body => '',
141 more => 0,
142 });
143 }
144  
145 sub _add_cors_headers {
146 my ($self, $headers, $origin) = @_;
147  
148 # Determine origin to return
149 my $allowed_origin;
150 if (grep { $_ eq '*' } @{$self->{origins}}) {
151 $allowed_origin = $self->{credentials} ? $origin : '*';
152 } else {
153 $allowed_origin = $origin;
154 }
155  
156 push @$headers, ['Access-Control-Allow-Origin', $allowed_origin];
157  
158 if ($self->{credentials}) {
159 push @$headers, ['Access-Control-Allow-Credentials', 'true'];
160 }
161  
162 if (@{$self->{expose_headers}}) {
163 push @$headers, ['Access-Control-Expose-Headers', join(', ', @{$self->{expose_headers}})];
164 }
165  
166 # Vary header for caching
167 push @$headers, ['Vary', 'Origin'];
168 }
169  
170 sub _is_origin_allowed {
171 my ($self, $origin) = @_;
172  
173 return 1 if grep { $_ eq '*' } @{$self->{origins}};
174 return 1 if grep { $_ eq $origin } @{$self->{origins}};
175 return 0;
176 }
177  
178 sub _get_header {
179 my ($self, $scope, $name) = @_;
180  
181 $name = lc($name);
182 for my $h (@{$scope->{headers} // []}) {
183 return $h->[1] if lc($h->[0]) eq $name;
184 }
185 return;
186 }
187  
188 1;
189  
190 __END__