Stripe/WebHook/Apache.pm untested

filter: Statementstmt 0.0% 0 / 108 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 173 CC 19 SCAR 41.4
CC
19
Cov
0%
event_handler
110.0
handler
90.0
BEGIN
6.0
CRAP 62.6
1 ##----------------------------------------------------------------------------
2 ## Stripe API - ~/lib/Net/API/Stripe/WebHook/Apache.pm
3 ## Version v0.1.0
4 ## Copyright(c) 2019 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <@sitael.tokyo.deguest.jp>
6 ## Created 2019/11/02
7 ## Modified 2020/05/15
8 ##
9 ##----------------------------------------------------------------------------
10 package Net::API::Stripe::WebHook::Apache;
11 BEGIN
12 {
13 use strict;
14 use parent qw( Net::API::REST );
15 use Net::API::Stripe::Event;
16 use TryCatch;
17 use Devel::Confess;
18 ## use Apache2::Const -compile => qw( :common :http DECLINED );
19 eval
20 {
21 require Apache2::Const;
22 Apache2::Const->import( 'compile', qw( :common :http DECLINED ) );
23 };
24 die( $@ ) if( $@ );
25 use constant MAX_PAYLOAD_SIZE => 524288;
26 };
27  
28 sub handler
29 {
30 ## https://perl.apache.org/docs/2.0/user/handlers/http.html#HTTP_Request_Handler_Skeleton
31 my( $class, $r ) = @_;
32 $r->log_error( "Net::API::Stripe::WebHook::Apache(): Got here with Apache object '$r'." );
33 return( DECLINED ) if( !$r );
34 my $req = Net::API::REST::Request->new( $r );
35 $r->log_error( "Got here after getting a Net::API::REST::Request object." );
36 ## An error has occurred
37 if( !defined( $req ) )
38 {
39 return( 500 );
40 }
41 my $resp = Net::API::REST::Response->new( request => $req );
42 my $self = $class->new;
43 $self->request( $req );
44 $self->response( $resp );
45 my $sig = $self->request->headers( 'Stripe-Signature' );
46 my $q = $self->request->params;
47 my $payload = {};
48 if( $self->request->content_type =~ /^application\/json/i )
49 {
50 $self->message( 3, "Receiving Stripe data as application/json" );
51 if( $self->request->content_length > MAX_PAYLOAD_SIZE )
52 {
53 return( $self->reply( Apache2::Const::HTTP_REQUEST_ENTITY_TOO_LARGE, { message => sprintf( "Payload of %d bytes exceeds our limit", $self->request->content_length ) } ) );
54 }
55 my $buff = '';
56 $self->request->read( $buff, $self->request->content_length );
57 $self->message( 2, "Payload read from server is: '$buff'. Decoding it" );
58 my $payload = $self->decode_json( $buff );
59 if( !length( $payload ) )
60 {
61 return( $self->reply( Apache2::Const::HTTP_BAD_REQUEST, { message => "Malformed json error" }) );
62 }
63 }
64 else
65 {
66 return( $self->reply( Apache2::Const::HTTP_BAD_REQUEST, { message => sprintf( "I was expecting http request type of application/json, but received %s", $self->request->content_type ) }) );
67 }
68 ## Don't wait, reply ok back to Stripe so our request does not time out
69 $self->response->code( Apache2::Const::HTTP_OK );
70 my $json = $self->json->utf8->encode({ code => 200, success => \1 });
71 $self->response->print( $json );
72 $self->response->rflush;
73 $self->request->socket->close;
74
75 ## Net::API::Stripe object
76 my $stripe = $self->stripe || return( $self->error( "No Stripe object set up. You need to properly initiate a Net::API::Stripe object in your $class module." ) );
77
78 my $stripe_event;
79 try
80 {
81 $stripe_event = Net::API::Stripe::Event->new({
82 '_parent' => $stripe,
83 '_debug' => $stripe->{debug},
84 '_dbh' => $stripe->{_dbh},
85 }, $payload );
86 }
87 catch( $e )
88 {
89 return( $self->error( "Unable to initiate a Net::API::Stripe::Event object: $e" ) );
90 }
91 return( $self->pass_error( Net::API::Stripe::Event->error ) ) if( !defined( $stripe_event ) );
92 my $stripe_handler = $self->event_handler( $stripe_event->type );
93 return( $self->reply( Apache2::Const::HTTP_NOT_IMPLEMENTED, { message => "No function implemented to handle event of type \"", $stripe_event->type, "\"." }) );
94 my $rc = $stripe_handler->( $stripe_event );
95 if( !defined( $rc ) )
96 {
97 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
98 }
99 elsif( $rc == 1 || $rc == Apache2::Const::HTTP_OK )
100 {
101 return( Apache2::Const::OK );
102 }
103 else
104 {
105 return( $rc );
106 }
107 }
108  
109 sub event_handler
110 {
111 my $self = shift( @_ );
112 ## e.g. invoice.created or charge.refunded
113 ## See the list of all events here: https://stripe.com/docs/api/events/types
114 my $type = shift( @_ );
115 my $routes = $self->event_handlers || return( $self->error( "No event handlers map is set up. You need to set up a hash \"event_handlers\" pointing to each sub routine that handle Stripe events like { account => { updated => \&account_updated } }" ) );
116 return( $self->error( "Event handlers set in this object is not an hash reference." ) ) if( ref( $routes ) ne 'HASH' );
117 return( $self->error( "Event handlers hash found, but no event hadnlers set up. It's empty!" ) ) if( !scalar( keys( %$routes ) ) );
118 my $parts = split( /\./, $type );
119 local $check = sub
120 {
121 my( $pos, $subroutes ) = @_;
122 my $part = $parts->[ $pos ];
123 if( exists( $subroutes->{ lc( $part ) } ) )
124 {
125 $part = lc( $part );
126 ## Code reference
127 if( ref( $subroutes->{ $part } ) eq 'CODE' )
128 {
129 return( $subroutes->{ $part } );
130 }
131 ## path part has sub component, so we look for a key _handler in the sub hash
132 elsif( ref( $subroutes->{ $part } ) eq 'HASH' )
133 {
134 my $ref = $subroutes->{ $part };
135 return( $self->error( "I was expecting a code reference to handle this event \"$part\", but instead found a hash reference. It seems there is a misconfiguration." ) ) if( $pos == $#$parts );
136 return( $check->( $pos + 1, $ref ) );
137 }
138 ## Not a code or a hash reference, so it has got to be a package name
139 elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ )
140 {
141 my( $cl, $meth ) = ( $1, $2 );
142 try
143 {
144 ## https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
145 require $cl unless( defined( *{"${cl}::"} ) );
146 my $o = $cl->new( request => $req, response => $resp ) || return( $self->pass_error( $cl->error ) );
147 my $code = $o->can( $meth );
148 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
149 return( sub{ $code->( $o, api => $self, @_ ) } );
150 }
151 catch( $e )
152 {
153 return( $self->error({ code => 500, message => $e }) );
154 }
155 }
156 else
157 {
158 return( $self->error({ code => 500, message => "Found an entry for path part \"$part\" ($subroutes->{ $part }), but I do not know what to do with it. If this was supposed to be a package, the syntax needs to be My::Package->my_sub" }) );
159 }
160 }
161 ## Empty means not found
162 else
163 {
164 return( $self->error( "No event handler found for \"$part\"." ) );
165 }
166 };
167 my $sub = $check->( 0, $routes ) || return( undef() );
168 return( $sub );
169 }
170  
171 sub event_handlers { return( shift->_set_get_hash( 'event_handlers', @_ ) ); }
172  
173 sub stripe { return( shift->_set_get_object( 'stripe', 'Net::API::Stripe', @_ ) ); }
174  
175 1;
176  
177 __END__
178  
179 =encoding utf8
180  
181 =head1 NAME
182  
183 Net::API::Stripe::WebHook::Apache - An Apache handler for Stripe Web Hook
184  
185 =head1 SYNOPSIS
186  
187 package My::Module::WebHook;
188 BEGIN
189 {
190 use strict;
191 use curry;
192 use parent qw( Net::API::Stripe::WebHook::Apache );
193 };
194
195 sub init
196 {
197 my $self = shift( @_ );
198 $self->{event_handlers} =
199 {
200 account => { updated => $self->curry::account_updated,
201 # etc..
202 # See here for a list of Stripe events:
203 # https://stripe.com/docs/api/events/types
204 };
205 }
206  
207 =head1 VERSION
208  
209 v0.1.0
210  
211 =head1 DESCRIPTION
212  
213 This is the module to handle Stripe Web Hooks using Apache/mod_perl configuration
214  
215 The way this works is you create your own module which inherits from this one. You override the init method in which you create the object property I<event_handler> with an hash value with keys corresponding to the types of Stripe events. A dot in the Stripe event type corresponds to a sub hash in our I<event_handler> definition.
216  
217 When an http query is made by Stripe on your webhook, Apache will trigger the method B<handler>, which will check and create the object environment, and call the method B<event_handler> provided by this package to find out the sub in charge of this Stripe event type, as defined in your map I<event_handlers>. You own method is then called and you can do whatever you want with Stripe data.
218  
219 It is also worth mentioning that Stripe requires ssl to be enabled to perform webhook queries.
220  
221 =head1 CONFIGURATION
222  
223 Your Apache VirtualHost configuration would look something like this, assuming your module package is C<My::Module::WebHook>
224  
225 <VirtualHost *:443>
226 ServerName example.com:443
227 ServerAdmin www@example.com
228 DocumentRoot /home/john/example.com
229 DirectoryIndex "index.html" "index.php"
230 CustomLog "${APACHE_LOG_DIR}/example.com-access.log" combined
231 ErrorLog "${APACHE_LOG_DIR}/example.com-error.log"
232 LogLevel warn
233 <Directory "/home/john/example.com">
234 Options All +MultiViews -ExecCGI -Indexes +Includes +FollowSymLinks
235 AllowOverride All
236 </Directory>
237 ScriptAlias "/cgi-bin/" "/home/john/example.com/cgi-bin/"
238 <Directory "/home/john/example.com/cgi-bin/">
239 Options All +Includes +ExecCGI -Indexes -MultiViews
240 AllowOverride All
241 SetHandler cgi-script
242 AcceptPathInfo On
243 Require all granted
244 </Directory>
245 <IfModule mod_perl.c>
246 PerlOptions +GlobalRequest
247 PerlPassEnv MOD_PERL
248 PerlPassEnv PATH_INFO
249 PerlModule Apache2::Request
250 <Perl>
251 unshift( @INC, "/home/john/lib" );
252 </Perl>
253 <Location /hook>
254 SetHandler perl-script
255 ## Switch it back to modperl once the soft is stable
256 # SetHandler modperl
257 PerlSendHeader On
258 PerlSetupEnv On
259 PerlOptions +GlobalRequest
260 # PerlResponseHandler Net::API::Stripe::WebHook::Apache
261 PerlResponseHandler My::Module::WebHook
262 Options +ExecCGI
263 Order allow,deny
264 Allow from all
265 </Location>
266 </IfModule>
267  
268 SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
269 SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
270 Include /etc/letsencrypt/options-ssl-apache.conf
271 SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
272 </Virtualhost>
273  
274 The key part is the line with C<PerlResponseHandler> and value L<Net::API::Stripe::WebHook::Apache>. This will tell Apache/mod_perl that our module will handle all http request for this particular location.
275  
276 So, if we get an incoming event from Stripe at https://example.com/hook/d18bbab7-e537-4dba-9a1f-dd6cc70ea6c1, we receive C<d18bbab7-e537-4dba-9a1f-dd6cc70ea6c1> as part of the path info, and we call B<validate_webhook>() to validate it before processing the event incoming packet.
277  
278 Apache will call our special method B<handler>(), which will invoque B<validate_webhook>() that should be overriden by your module, and which must return either true or false. Upon successful return from B<validate_webhook>(), B<handler> will create a new constructor such as $class->new()
279  
280 What you want to do is inherit L<Net::API::Stripe::WebHook::Apache> and set your own module in Apache configuration, like so:
281  
282 PerlResponseHandler My::WebHookHandler
283  
284 The inherited handler will be called by Apache with the class My::WebHookHandler and the apache Apache2::RequestRec object. As we wrote above, once validated, B<handler> will initiate an object from your module by calling C<My::WebHookHandler->new( object => L<Net::API::Stripe::Event>, request => L<Net::API::REST::Request>, response => L<Net::API::REST::Response> )> where each package name are an object. C<object> represents the event packet received from Stripe. C<request> is an object to access great number of method to access the Apache API, and C<response> is an object to access Apache API to provide a reply. See the manual page for each of those package.
285  
286 =head1 CONSTRUCTOR
287  
288 =over 4
289  
290 =item B<new>( %args )
291  
292 Creates a new L<Net::API::Stripe::WebHook::Apache> object. This should be overriden by your own package.
293  
294 =over 4
295  
296 =item I<object> Net::API::Stripe::Event object
297  
298 =item I<request> Net::API::REST::Request
299  
300 =item I<request> Net::API::REST::Response
301  
302 =back
303  
304 =item B<handler>( $class, $r )
305  
306 This is called by Apache/mod_perl upon incoming http request
307  
308 =back
309  
310 =head1 METHODS
311  
312 =over 4
313  
314 =item handler( $r )
315  
316 This is called by Apache with an L<Apache2::Request> object and returns an L<Apache2::Constant> code such as 200
317  
318 =item B<event_handler>( Stripe event type )
319  
320 Provided with a Stripe event type, this checks for a suitable handler (set up in your B<init> method), then return the handler code reference.
321  
322 ~item B<event_handlers>
323  
324 Set/get an hash reference of Stripe event type to handling methods.
325  
326 Returns an hash reference.
327  
328 =item B<stripe>
329  
330 Set/get a L<Net::API::Stripe> object. It returns the current value.
331  
332 =back
333  
334 =head1 HISTORY
335  
336 =head2 v0.1
337  
338 Initial version
339  
340 =head1 AUTHOR
341  
342 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
343  
344 =head1 SEE ALSO
345  
346 Stripe API documentation: L<https://stripe.com/docs/api/events/types>
347  
348 L<Net::API::REST>, L<Apache2>
349  
350 L<ModPerl::Registry>, L<ModPerl::PerlRun>, L<http://perl.apache.org/>
351  
352 =head1 COPYRIGHT & LICENSE
353  
354 Copyright (c) 2019-2020 DEGUEST Pte. Ltd.
355  
356 You can use, copy, modify and redistribute this package and associated
357 files under the same terms as Perl itself.
358  
359 =cut