Server/PSGI.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Server.pm ↑ Summary Server/Storage/Test.pm »
1 package Net::Blossom::Server::PSGI;
2  
3 1 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use Net::Blossom::_ConstructorArgs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 0 ▶use Net::Blossom::Server;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Net::Blossom::Server::Authorization;
8 use Net::Blossom::Server::Error;
9 use Net::Blossom::Server::Request;
10 use Net::Blossom::Server::Response;
11  
12 use Carp qw(croak);
13 use Class::Tiny qw(server authorize authorization);
14 use Scalar::Util qw(blessed);
15  
16 my %CORS_HEADERS = (
17 'Access-Control-Allow-Origin' => '*',
18 );
19  
20 my %PREFLIGHT_HEADERS = (
21 'Access-Control-Allow-Headers' => 'Authorization, *',
22 'Access-Control-Allow-Methods' => 'GET, HEAD, PUT, DELETE',
23 'Access-Control-Max-Age' => 86400,
24 );
25  
26 sub BUILDARGS {
27 my $class = shift;
28 my %args = Net::Blossom::_ConstructorArgs::normalize(@_);
29 my %known = map { $_ => 1 } qw(server authorize authorization);
30 my @unknown = grep { !exists $known{$_} } keys %args;
31 croak "unknown argument(s): " . join(', ', sort @unknown) if @unknown;
32  
33 return \%args;
34 }
35  
36 sub BUILD {
37 my ($self) = @_;
38 croak "server is required" unless defined $self->server;
39 croak "server must be a Net::Blossom::Server"
40 unless blessed($self->server) && $self->server->isa('Net::Blossom::Server');
41  
42 croak "authorize must be a code reference"
43 if defined $self->authorize && ref($self->authorize) ne 'CODE';
44 croak "authorization must be a Net::Blossom::Server::Authorization"
45 if defined $self->authorization
46 && !(blessed($self->authorization) && $self->authorization->isa('Net::Blossom::Server::Authorization'));
47 croak "authorize and authorization are mutually exclusive"
48 if defined $self->authorize && defined $self->authorization;
49  
50 return;
51 }
52  
53 sub to_app {
54 my ($self) = @_;
55  
56 return sub {
57 my ($env) = @_;
58 my $request = eval { _request_from_env($env) };
59 return _exception_to_psgi($@, 400, 'Bad Request') if $@;
60  
61 return _response_to_psgi(_preflight_response())
62 if $request->method eq 'OPTIONS';
63  
64 my %opts;
65  
66 my $response = eval {
67 if (defined $self->authorization) {
68 my $authorization = $self->authorization->authorize($request);
69 if (defined $authorization) {
70 $opts{pubkey} = $authorization->pubkey;
71 $opts{authorization} = $authorization;
72 }
73 }
74 elsif (defined $self->authorize) {
75 my $pubkey = $self->authorize->(
76 request => $request,
77 env => $env,
78 );
79 $opts{pubkey} = $pubkey if defined $pubkey;
80 }
81  
82 $self->server->handle_request($request, %opts);
83 };
84 return _exception_to_psgi($@, 500, 'Internal Server Error') if $@;
85  
86 return _response_to_psgi($response);
87 };
88 }
89  
90 sub _request_from_env {
91 my ($env) = @_;
92 croak "env must be a hash reference" unless ref($env) eq 'HASH';
93  
94 my %args = (
95 method => $env->{REQUEST_METHOD},
96 path => defined($env->{PATH_INFO}) && length($env->{PATH_INFO}) ? $env->{PATH_INFO} : '/',
97 headers => _headers_from_env($env),
98 query => _query_from_env($env),
99 );
100  
101 $args{body} = $env->{'psgi.input'} if defined $env->{'psgi.input'};
102 $args{remote_addr} = $env->{REMOTE_ADDR} if defined $env->{REMOTE_ADDR};
103 $args{content_type} = $env->{CONTENT_TYPE}
104 if defined($env->{CONTENT_TYPE}) && length($env->{CONTENT_TYPE});
105 $args{content_length} = $env->{CONTENT_LENGTH}
106 if defined($env->{CONTENT_LENGTH}) && length($env->{CONTENT_LENGTH});
107  
108 return Net::Blossom::Server::Request->new(%args);
109 }
110  
111 sub _response_to_psgi {
112 my ($response) = @_;
113 croak "response must be a Net::Blossom::Server::Response"
114 unless blessed($response) && $response->isa('Net::Blossom::Server::Response');
115  
116 my $body = $response->body;
117 $body = [$body] unless ref($body);
118 return [$response->status, _header_pairs_with_cors($response), $body];
119 }
120  
121 sub _preflight_response {
122 return Net::Blossom::Server::Response->empty(204, headers => \%PREFLIGHT_HEADERS);
123 }
124  
125 sub _header_pairs_with_cors {
126 my ($response) = @_;
127 my $headers = $response->headers;
128  
129 for my $name (keys %CORS_HEADERS) {
130 my $lower = lc $name;
131 for my $existing (keys %$headers) {
132 delete $headers->{$existing} if lc($existing) eq $lower;
133 }
134 $headers->{$name} = $CORS_HEADERS{$name};
135 }
136  
137 my @pairs;
138 for my $name (sort keys %$headers) {
139 push @pairs, $name, $headers->{$name};
140 }
141 return \@pairs;
142 }
143  
144 sub _exception_to_psgi {
145 my ($error, $status, $reason) = @_;
146  
147 my $response;
148 if (blessed($error) && $error->isa('Net::Blossom::Server::Error')) {
149 $response = $error->as_response;
150 }
151 else {
152 $response = Net::Blossom::Server::Response->error($status, $reason);
153 }
154  
155 return _response_to_psgi($response);
156 }
157  
158 sub _headers_from_env {
159 my ($env) = @_;
160 my %headers;
161  
162 $headers{'Content-Type'} = $env->{CONTENT_TYPE}
163 if defined($env->{CONTENT_TYPE}) && length($env->{CONTENT_TYPE});
164 $headers{'Content-Length'} = $env->{CONTENT_LENGTH}
165 if defined($env->{CONTENT_LENGTH}) && length($env->{CONTENT_LENGTH});
166  
167 for my $key (sort keys %$env) {
168 next unless $key =~ /\AHTTP_(.+)\z/;
169 my $name = _header_name_from_env($1);
170 $headers{$name} = $env->{$key};
171 }
172  
173 return \%headers;
174 }
175  
176 sub _header_name_from_env {
177 my ($name) = @_;
178 return join '-', map { ucfirst lc $_ } split /_/, $name;
179 }
180  
181 sub _query_from_env {
182 my ($env) = @_;
183 my $query_string = $env->{QUERY_STRING};
184 return {} unless defined($query_string) && length($query_string);
185  
186 my %query;
187 for my $pair (split /&/, $query_string, -1) {
188 next unless length $pair;
189 my ($name, $value) = split /=/, $pair, 2;
190 $name = _decode_query_component($name);
191 $value = defined $value ? _decode_query_component($value) : '';
192  
193 if (exists $query{$name}) {
194 $query{$name} = [$query{$name}] unless ref($query{$name}) eq 'ARRAY';
195 push @{$query{$name}}, $value;
196 }
197 else {
198 $query{$name} = $value;
199 }
200 }
201  
202 return \%query;
203 }
204  
205 sub _decode_query_component {
206 my ($value) = @_;
207 $value =~ tr/+/ /;
208 croak "invalid query percent encoding" if $value =~ /%(?![0-9A-Fa-f]{2})/;
209 $value =~ s/%([0-9A-Fa-f]{2})/chr hex $1/eg;
210 return $value;
211 }
212  
213 1;
214  
215 =pod
216  
217 =head1 NAME
218  
219 Net::Blossom::Server::PSGI - PSGI adapter for the Blossom server core
220  
221 =head1 SYNOPSIS
222  
223 use Net::Blossom::Server::PSGI;
224  
225 my $app = Net::Blossom::Server::PSGI->new(
226 server => $server,
227 authorize => sub {
228 my %ctx = @_;
229 return $pubkey;
230 },
231 )->to_app;
232  
233 =head1 DESCRIPTION
234  
235 C<Net::Blossom::Server::PSGI> turns a C<Net::Blossom::Server> object into a
236 PSGI application code reference. It does not depend on Plack and does not choose
237 an HTTP daemon for the application.
238  
239 The adapter translates the PSGI environment into a
240 C<Net::Blossom::Server::Request>, applies optional authorization, and passes the
241 request into C<Net::Blossom::Server>. The returned
242 C<Net::Blossom::Server::Response> is translated into the PSGI response array.
243  
244 CORS headers required by BUD-01 are added to every PSGI response. C<OPTIONS>
245 requests are handled directly by this adapter as CORS preflight requests and do
246 not reach authorization or server route dispatch.
247  
248 Malformed requests are returned as C<400> responses. Typed
249 C<Net::Blossom::Server::Error> exceptions are returned with their configured
250 status and headers. Other exceptions are returned as generic C<500> responses.
251  
252 =head1 CONSTRUCTOR
253  
254 =head2 new
255  
256 my $adapter = Net::Blossom::Server::PSGI->new(%args);
257  
258 Required arguments:
259  
260 =over 4
261  
262 =item * C<server>
263  
264 A C<Net::Blossom::Server> object.
265  
266 =back
267  
268 Optional arguments:
269  
270 =over 4
271  
272 =item * C<authorize>
273  
274 Code reference called before dispatch. It receives C<request> and C<env> named
275 arguments. When it returns a defined value, that value is passed to the server
276 core as the verified C<pubkey>.
277  
278 =item * C<authorization>
279  
280 A C<Net::Blossom::Server::Authorization> object. When supplied, the adapter
281 validates BUD-11 C<Authorization> headers for implemented Blossom endpoints and
282 passes the verified event pubkey and authorization result to the server core.
283  
284 =back
285  
286 Unknown arguments or invalid values croak. C<authorize> and C<authorization> are
287 mutually exclusive.
288  
289 =head1 ACCESSORS
290  
291 =head2 server
292  
293 Returns the C<Net::Blossom::Server> object.
294  
295 =head2 authorize
296  
297 Returns the optional authorization callback.
298  
299 =head2 authorization
300  
301 Returns the optional BUD-11 authorization verifier.
302  
303 =head1 METHODS
304  
305 =head2 to_app
306  
307 my $app = $adapter->to_app;
308  
309 Returns a PSGI application code reference.
310  
311 =head1 INTERNAL METHODS
312  
313 =head2 BUILDARGS
314  
315 Normalizes constructor arguments for Class::Tiny.
316  
317 =head2 BUILD
318  
319 Validates the constructed object for Class::Tiny.
320  
321 =cut
« Server.pm ↑ Summary Server/Storage/Test.pm »