lib/Net/API/REST.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/Net/API/REST/Status.pm ↑ Summary lib/Net/API/REST/Cookie.pm »
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## REST API Framework - ~/lib/m
4 ## Version v1.2.5
5 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2019/09/01
8 ## Modified 2026/03/20
9 ## All rights reserved
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package Net::API::REST;
15 BEGIN
16 {
17 2 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶ use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶ use Apache2::API qw( :common );
Subroutine BEGIN: called CC=1 SCAR=2.6
21 use parent qw( Apache2::API );
22 use vars qw( $VERSION $DEBUG $API_VERSION );
23 use curry;
24 use version;
25 use Apache2::Reload;
26 use JSON::PP ();
27 use Regexp::Common;
28 use Scalar::Util ();
29 # use Crypt::JWT;
30 # 2019-09-26
31 # We use our own drop-in replacement because of a bug in ModPerl and JSON::XS not recognising hash reference passed
32 use Net::API::REST::JWT;
33 # use DateTime::Format::Strptime;
34 use Net::API::REST::DateTime;
35 use MIME::Base64 ();
36 # use IO::Compress::Gzip;
37 # use IO::Compress::Bzip2;
38 # use IO::Compress::Deflate;
39 use Net::API::REST::Request;
40 use Net::API::REST::Response;
41 use Apache2::API::Status;
42 $VERSION = 'v1.2.5';
43 };
44  
45 use strict;
46 use warnings;
47  
48 $DEBUG = 0;
49 $API_VERSION = 1;
50 our @AVAILABLE_API_VERSIONS = qw( 1 );
51  
52 sub init
53 {
54 my $self = shift( @_ );
55 $self->{request} = '' unless( $self->{request} );
56 $self->{response} = '' unless( $self->{response} );
57 $self->{apache_request} = '' unless( $self->{apache_request} );
58 # Routes to endpoint to which are attached resources
59 $self->{routes} = {} unless( scalar( keys( %{$self->{routes}} ) ) );
60 $self->{api_version} = 1 if( !length( $self->{api_version} ) );
61 $self->{default_methods} = [qw( GET POST )] unless( $self->{default_methods} );
62 $self->{is_allowed} = {} unless( $self->{is_allowed} && scalar( keys( %{$self->{is_allowed}} ) ) );
63 $self->{supported_content_types} = [] unless( $self->{supported_methods} );
64 $self->{supported_methods} = [qw( DELETE GET HEAD OPTIONS POST PUT )] unless( $self->{supported_methods} );
65 $self->{supported_api_versions} = [qw( 1 )] unless( $self->{supported_api_versions} );
66 $self->{key} = '' unless( length( $self->{key} ) );
67 $self->{jwt_accepted_algo} = [] unless( length( $self->{jwt_accepted_algo} ) );
68 $self->{jwt_accepted_encoding} = [] unless( length( $self->{jwt_accepted_encoding} ) );
69 $self->{jwt_encrypt} = 1 unless( length( $self->{jwt_encrypt} ) );
70 $self->{jwt_algo} = 'HS256' unless( length( $self->{jwt_algo} ) );
71 $self->{jwt_encoding} = 'A128GCM' unless( length( $self->{jwt_encoding} ) );
72 # 200Kb
73 $self->{compression_threshold} = 204800 unless( length( $self->{compression_threshold} ) );
74 $self->{lang} = '' unless( length( $self->{lang} ) );
75 $self->{api_uri} = '' unless( length( $self->{api_uri} ) );
76 $self->{is_allowed} = {} unless( $self->{is_allowed} && ref( $self->{is_allowed} ) eq 'HASH' );
77 # Default handlers
78 $self->{is_allowed}->{access} = sub{ return( Apache2::Const::HTTP_OK ); } unless( exists( $self->{is_allowed}->{access} ) && ref( $self->{is_allowed}->{access} ) eq 'CODE' );
79 $self->{is_allowed}->{network} = sub{ return( Apache2::Const::HTTP_OK ); } unless( exists( $self->{is_allowed}->{network} ) && ref( $self->{is_allowed}->{network} ) eq 'CODE' );
80 $self->SUPER::init( @_ ) || return( $self->pass_error );
81 if( length( $self->{api_version} ) )
82 {
83 $self->api_version( $self->{api_version} );
84 }
85 if( $self->{routes} )
86 {
87 $self->routes( $self->{routes} ) || return( $self->pass_error );
88 }
89 $self->supported_api_versions( $self->{supported_api_versions} ) if( $self->{supported_api_versions} );
90 foreach my $k ( qw( jwt_encrypt jwt_algo jwt_encoding jwt_accepted_algo jwt_accepted_encoding ) )
91 {
92 $self->$k( $self->{ $k } );
93 }
94 return( $self );
95 }
96  
97 sub api_uri { return( shift->_set_get_object( 'api_uri', 'URI', @_ ) ); }
98  
99 sub api_version
100 {
101 my $self = shift( @_ );
102 if( @_ )
103 {
104 my $v = shift( @_ );
105 unless( ref( $v ) eq 'version' )
106 {
107 $v = version->parse( $v );
108 }
109 $self->{api_version} = $v;
110 }
111 return( $self->{api_version} );
112 }
113  
114 sub base_path { return( shift->_set_get_scalar( 'base_path', @_ ) ); }
115  
116 sub checkonly { return( shift->_set_get_boolean( 'checkonly', @_ ) ); }
117  
118 sub default_methods { return( shift->_set_get_array( 'default_methods', @_ ) ); }
119  
120 sub endpoint { return( shift->_set_get_object( 'endpoint', 'Net::API::REST::Endpoint', @_ ) ); }
121  
122 # In Apache2 conf:
123 # PerlResponseHandler MyPackage::REST which would inherit from Net::API::REST
124 sub handler : method
125 {
126 # https://perl.apache.org/docs/2.0/user/handlers/http.html#HTTP_Request_Handler_Skeleton
127 my( $class, $r ) = @_;
128 # my $handlerClass = $r->dir_config( 'Net_API_REST_Handler' ) || 'Net::API::REST' ;
129 my $debug = $r->dir_config( 'DEBUG' ) || $DEBUG;
130 my $req = Net::API::REST::Request->new( $r, debug => $debug );
131 # An error has occurred
132 if( !defined( $req ) )
133 {
134 $r->log_error( "${class}::handler: Error instantiating an Net::API::REST::Request object: " . Net::API::REST::Request->error );
135 return( Net::API::REST::Request->error->code || Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
136 }
137 my $resp = Net::API::REST::Response->new( request => $req, debug => $debug ) || do
138 {
139 $r->log_error( "${class}::handler: Error instantiating an Net::API::REST::Response object: " . Net::API::REST::Response->error );
140 return( Net::API::REST::Response->error->code || Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
141 };
142 my $self = $class->new(
143 apache_request => $r,
144 debug => $debug,
145 request => $req,
146 response => $resp,
147 );
148 if( !defined( $self ) )
149 {
150 $r->log_error( "Error instantiating a new $class object: ", $class->error );
151 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
152 }
153  
154 $self->request( $req );
155 $self->response( $resp );
156  
157 if( my $code = $self->log_handler )
158 {
159 $r->set_handlers( 'PerlPrivateLogHandler' => $code );
160 }
161  
162 # $self->apache_request( $r );
163 # $r->log_error( "Received Apache request $r, object debug value is: ", $self->debug );
164 # Full uri. $r->uri only returns the path
165 my $uri = $req->uri;
166 $self->api_uri( URI->new( $uri->scheme . '://' . $uri->host ) );
167 # Response content type
168 $r->content_type( 'application/json' );
169 my $json = JSON->new->relaxed->utf8;
170 $self->{json} = $json;
171  
172 # No need to go further if the ip address is not allowed to access the REST api.
173 # Here you could check for IP ban, or whether there is enough authorisation to access the endpoint
174 my $ok_net = $self->is_allowed( 'network' );
175 if( $ok_net && ref( $ok_net ) )
176 {
177 # Get a return code, and possibly a hash containing the message property
178 my( $rc, $rdef ) = $ok_net->( $req->remote_ip );
179 if( defined( $rc ) && $resp->is_error( "$rc" ) )
180 {
181 if( $self->_is_a( $rc, 'Net::API::REST::RC' ) )
182 {
183 return( $self->reply({ code => $rc->code, message => $rc->message }) );
184 }
185 elsif( $rdef && $self->_is_hash( $rdef ) && CORE::exists( $rdef->{message} ) )
186 {
187 return( $self->reply({ code => $rc, message => $rdef->{message} }) );
188 }
189 # Net::API::REST::reply will automatically set a json with an error message based on the user language
190 else
191 {
192 return( $self->reply({ code => $rc }) );
193 }
194 }
195 }
196  
197 # No need to go further if the requested method is not supported
198 my $ok_methods = $self->supported_methods;
199 my $http_meth = $req->method;
200 if( scalar( @$ok_methods ) && !scalar( grep( /^$http_meth$/i, @$ok_methods ) ) )
201 {
202 # Net::API::REST::reply will automatically set a json with an error message based on the user language
203 return( $self->reply({ code => Apache2::Const::HTTP_METHOD_NOT_ALLOWED }) );
204 }
205  
206 # Check supported content-type
207 # Ref: <https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html>
208 my $ok_ct = $self->supported_content_types;
209 # Only the content type, ie without the charset. Example: application/json; charset=utf-8
210 my $ct = lc( $req->type // '' );
211 # We check if content type is provided at all since it could be missing, such as in
212 # a OPTIONS, POST or GET request with no content or query
213 if( length( $ct ) && scalar( @$ok_ct ) && !scalar( grep( $ct eq $_, @$ok_ct ) ) )
214 {
215 # Net::API::REST::reply will automatically set a json with an error message based on the user language
216 return( $self->reply({ code => Apache2::Const::HTTP_NOT_ACCEPTABLE }) );
217 }
218  
219 # Check if there is a required api version and if we support it
220 if( $req->client_api_version )
221 {
222 my $ok_versions = $self->supported_api_versions;
223 my $client_version = $req->client_api_version;
224 my $client_api_version_is_ok = 0;
225 foreach my $v ( @$ok_versions )
226 {
227 if( $v == $client_version )
228 {
229 $client_api_version_is_ok++;
230 }
231 }
232 return( $self->reply( Apache2::Const::HTTP_NOT_ACCEPTABLE, { error => "API version requested ($client_version) is not supported." } ) ) unless( $client_api_version_is_ok );
233 }
234  
235 # Protection against DNS rebinding attacks
236 # https://www.w3.org/TR/cors/#list-of-headers
237 if( my $req_host = $req->headers( 'Host' ) )
238 {
239 my $req_host_uri = URI->new( $self->api_uri->scheme . '://' . $req_host );
240 if( lc( $req_host_uri->host ) ne $self->api_uri->host )
241 {
242 # Net::API::REST::reply will automatically set a json with an error message based on the user language
243 return( $self->reply({ code => Apache2::Const::HTTP_UNAUTHORIZED }) );
244 }
245 }
246  
247 # If there is a init_headers handler, call it to initiate the headers
248 my $init_headers = $self->init_headers;
249 if( $init_headers && ref( $init_headers ) eq 'CODE' )
250 {
251 $init_headers->({ request => $req, response => $resp });
252 }
253  
254 if( $http_meth eq 'OPTIONS' )
255 {
256 return( $self->http_options );
257 }
258 elsif( $http_meth eq 'HEAD' )
259 {
260 # $r->send_http_header;
261 return( Apache2::Const::HTTP_NO_CONTENT );
262 }
263  
264 my $origin = $req->headers( 'Origin' );
265 if( $origin )
266 {
267 $self->http_cors;
268 }
269  
270 my $path = $uri->path;
271 if( my $base = $r->dir_config( 'Net_API_REST_Base' ) )
272 {
273 $self->base_path( $base );
274 }
275 my $ep = $self->route( $uri );
276 if( !defined( $ep ) )
277 {
278 my $json = {};
279 my $code = $self->error->code;
280 if( $code )
281 {
282 $json->{code} = $code;
283 $json->{message} = $self->error->message;
284 }
285 else
286 {
287 $json->{code} = Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
288 }
289 # Net::API::REST::reply will automatically set a json with an error message based on the user language
290 return( $self->reply( $json ) );
291 }
292 # No resource found matching the user request, returning a 400
293 elsif( !length( $ep ) )
294 {
295 # Net::API::REST::reply will automatically set a json with an error message based on the user language
296 return( $self->reply({ code => Apache2::Const::HTTP_BAD_REQUEST }) );
297 }
298 elsif( !$ep->is_method_allowed( $http_meth ) )
299 {
300 return( $self->reply({ code => Apache2::Const::HTTP_METHOD_NOT_ALLOWED }) );
301 }
302 else
303 {
304 $self->endpoint( $ep );
305 my $handler = $ep->handler;
306 my $vars = $ep->variables;
307 $req->variables( $vars );
308 # require B::Deparse;
309 # my $deparse = B::Deparse->new( '-p', '-sC' );
310 # my $meth_body = $deparse->coderef2text( $ep->handler );
311 my $tmpl = <<EOT;
312 Endpoint information:
313 Handler .......: %s
314 Access type ...: %s
315 Ok methods ....: %s
316 Path ..........: %s
317 Path info .....: %s
318 Variables .....: %s
319 Params ........: %s
320 EOT
321 $self->noexec->messagef( 3, $tmpl, $handler, $ep->access, join( ', ', @{$ep->methods} ), $ep->path, join( ', ', @{$ep->path_info} ), $self->dumper( $ep->variables->as_hash( strict => 1 ) ), $self->dumper( $ep->params->as_hash( strict => 1 ) ) );
322 # Check access with handler
323 my $ok_access = $self->is_allowed( 'access' );
324 if( $ok_access && ref( $ok_access ) eq 'CODE' )
325 {
326 my( $rc, $rdef ) = $ok_access->( $ep );
327 if( $resp->is_error( "$rc" ) )
328 {
329 # Net::API::REST::reply will automatically set a json with an error message based on the user language
330 # return( $self->reply({ code => $rc }) );
331 if( $self->_is_a( $rc, 'Net::API::REST::RC' ) )
332 {
333 return( $self->reply({ code => $rc->code, message => $rc->message }) );
334 }
335 elsif( $rdef && $self->_is_hash( $rdef ) && CORE::exists( $rdef->{message} ) )
336 {
337 return( $self->reply({ code => $rc, message => $rdef->{message} }) );
338 }
339 # Net::API::REST::reply will automatically set a json with an error message based on the user language
340 else
341 {
342 return( $self->reply({ code => $rc }) );
343 }
344 }
345 }
346  
347 # use B::Deparse;
348 # my $deparse = B::Deparse->new("-p", "-sC");
349 # my $code_body = $deparse->coderef2text( $handler );
350  
351 # try-catch
352 local $@;
353 my $rc = eval
354 {
355 # my $rc = $ep->handler->();
356 $handler->();
357 };
358 if( $@ )
359 {
360 $self->error({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => $@ });
361 # return( $self->reply( 500, { message => 'An internal server error occured' } ) );
362 return( $self->bailout( "An error occurred while executing code for api resource: $@" ) );
363 }
364 # Server error
365 if( !defined( $rc ) )
366 {
367 # Net::API::REST::reply will automatically set a json with an error message based on the user language
368 # It is ok to set a reply ourself here, because if it were a normal response, we would not be getting an undef value
369 return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR }) );
370 # return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
371 }
372 elsif( $rc == Apache2::Const::HTTP_OK )
373 {
374 return( Apache2::Const::OK );
375 }
376 else
377 {
378 return( $rc );
379 }
380 # Stop sending data !!
381 $self->request->socket->close;
382 exit(0);
383 }
384 }
385  
386 # Mut be overriden by sub package
387 sub http_cors { return; }
388  
389 # https://www.w3.org/TR/cors/#http-access-control-allow-origin
390 sub http_options
391 {
392 my $self = shift( @_ );
393 my $req = $self->request;
394 my $res = $self->response;
395 my $uri = $req->uri;
396 my $ep = $self->route( $uri );
397 my $http_meth = $req->method;
398 if( !defined( $ep ) )
399 {
400 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
401 }
402 elsif( !CORE::length( $ep ) )
403 {
404 return( Apache2::Const::HTTP_NOT_FOUND );
405 }
406 my $tmpl = <<EOT;
407 Endpoint information:
408 Handler .......: %s
409 Access type ...: %s
410 Ok methods ....: %s
411 Path info .....: %s
412 Variables .....: %s
413 EOT
414 $self->noexec->messagef( 3, $tmpl, $ep->handler, $ep->access, join( ', ', @{$ep->methods} ), join( ', ', @{$ep->path_info} ), $self->dumper( $ep->variables->as_hash ) );
415  
416 my $req_methods = [CORE::split( /\,[[:blank:]]*/, ( $req->headers( 'Access-Control-Request-Method' ) || '' ) )];
417 if( scalar( @$req_methods ) )
418 {
419 foreach my $m ( @$req_methods )
420 {
421 if( !$ep->is_method_allowed( $m ) )
422 {
423 return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED );
424 }
425 }
426 if( !$ep->methods->is_empty )
427 {
428 $res->headers( 'Access-Control-Allow-Methods' => $ep->methods->join( ', ' )->scalar );
429 }
430 else
431 {
432 $res->headers( 'Access-Control-Allow-Methods' => '*' );
433 }
434 }
435  
436 my $origin = $req->headers( 'Origin' ) || $req->headers( 'Access-Control-Request-Origin' );
437 if( !$origin )
438 {
439 return( Apache2::Const::HTTP_NO_CONTENT );
440 }
441 my $allow_origin = $req->headers( 'Access-Control-Allow-Origin' );
442 # "The string "*" cannot be used for a resource that supports credentials"
443 # https://www.w3.org/TR/cors/#http-access-control-allow-origin
444 if( $allow_origin )
445 {
446 if( $ep->access eq 'restricted' )
447 {
448 if( $allow_origin eq '*' )
449 {
450 $res->headers( 'Access-Control-Allow-Origin' => $origin );
451 $res->headers( 'Access-Control-Max-Age' => 5 );
452 }
453 }
454 $res->headers( 'Access-Control-Allow-Credentials' => 'true' );
455 }
456 else
457 {
458 if( $ep->access eq 'restricted' )
459 {
460 if( $origin )
461 {
462 $res->headers( 'Access-Control-Allow-Origin' => $origin );
463 }
464 else
465 {
466 # Stringify
467 $res->headers( 'Access-Control-Allow-Origin' => $self->api_uri . '' );
468 }
469 $res->headers(
470 'Access-Control-Allow-Credentials' => 'true',
471 'Access-Control-Max-Age' => 5
472 );
473 }
474 elsif( $origin )
475 {
476 $res->headers(
477 'Access-Control-Allow-Origin' => $origin,
478 'Access-Control-Allow-Credentials' => 'true',
479 'Access-Control-Max-Age' => 5
480 );
481 }
482 else
483 {
484 $res->headers( 'Access-Control-Allow-Origin' => '*' );
485 }
486 }
487 my $req_headers = $req->headers( 'Access-Control-Request-Headers' );
488 if( $req_headers )
489 {
490 $res->headers( 'Access-Control-Allow-Headers' => $req_headers );
491 }
492 my $cred_required = $req->headers( 'Credentials' ) // '';
493 if( lc( $cred_required ) eq 'include' )
494 {
495 $res->headers( 'Access-Control-Allow-Credentials' => 'true' );
496 }
497 # Check from the most restrictive allowed methods in the context of the endpoint to the broader one for generally all supported methods
498 my $ok_methods = scalar( @{$ep->methods} ) ? $ep->methods : $self->supported_methods;
499 $res->headers( 'Access-Control-Allow-Methods' => join( ', ', @$ok_methods ) );
500  
501 # $r->headers_out->add( 'Allow' => join( ',', @$ok_methods ) );
502 # $r->rflush;
503 return( Apache2::Const::HTTP_NO_CONTENT );
504 }
505  
506 # To be overriden by module inheriting our package
507 sub init_headers { return(1); }
508  
509 # Set or get handlers for various phases to check if the user is allowed access
510 # Currently available handlers: network and access
511 sub is_allowed
512 {
513 my $self = shift( @_ );
514 my $all = $self->{is_allowed};
515 if( @_ )
516 {
517 return( $self->error( "Wrong number of parameters provided: '", join( "', '", @_ ), "'." ) ) if( scalar( @_ ) > 1 && !( scalar( @_ ) % 2 ) );
518 if( !( scalar( @_ ) % 2 ) )
519 {
520 while( my( $key, $code ) = splice( @_, 0, 2 ) )
521 {
522 if( $code )
523 {
524 return( $self->error( "I was expecting a code reference for the handler '$key', but instead I got '$code'." ) ) if( ref( $code ) ne 'CODE' );
525 $all->{ $key } = $code;
526 }
527 }
528 return( $self );
529 }
530 else
531 {
532 my $key = shift( @_ );
533 return( '' ) if( !exists( $all->{ $key } ) );
534 return( $all->{ $key } );
535 }
536 }
537 }
538  
539 sub jwt_accepted_algo { return( shift->_set_get_array( 'jwt_accepted_algo', @_ ) ); }
540  
541 sub jwt_accepted_encoding { return( shift->_set_get_array( 'jwt_accepted_encoding', @_ ) ); }
542  
543 sub jwt_algo { return( shift->_set_get_scalar( 'jwt_algo', @_ ) ); }
544  
545 sub jwt_decode
546 {
547 my $self = shift( @_ );
548 my $opts = {};
549 if( ref( $_[0] ) eq 'HASH' )
550 {
551 $opts = shift( @_ );
552 }
553 # A simple decode, most likely for public jwt like google, linkedin, etc.
554 elsif( scalar( @_ ) == 1 )
555 {
556 my $token = shift( @_ );
557 my $data;
558 # try-catch
559 local $@;
560 eval
561 {
562 # $data = Crypt::JWT::decode_jwt( token => $token );
563 $data = Net::API::REST::JWT::decode_jwt( token => $token );
564 };
565 if( $@ )
566 {
567 return( $self->error( "There was an error decoding Json Web Token payload: $@" ) );
568 }
569 return( $data );
570 }
571 return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} );
572 return( $self->error( "No token was provided to decode." ) ) if( !$opts->{token} );
573 $opts->{algo} ||= $self->jwt_algo;
574 $opts->{accepted_algo} ||= $self->jwt_accepted_algo;
575 $opts->{accepted_encoding} ||= $self->jwt_accepted_encoding;
576 $opts->{verify_audience} ||= $self->jwt_verify_audience;
577 my $param =
578 {
579 token => $opts->{token},
580 key => $opts->{key},
581 decode_payload => 1,
582 decode_header => 1,
583 # verify_iss => sub{ 1; }
584 verify_aud => qr{^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$},
585 };
586 # PBES2-HS256+A128KW
587 # accepted_alg => qr{^(?:PBES2\-HS256\+A128KW|HS256)$},
588 if( $opts->{accepted_algo} )
589 {
590 return( $self->error( "Accepted alorithm option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_algo} ) );
591 if( scalar( @{$opts->{accepted_algo}} ) )
592 {
593 my $re = join( '|', @{$opts->{accepted_algo}} );
594 $param->{accepted_alg} = qr{^(?:\Q$re\E)$};
595 }
596 }
597  
598 # accepted_enc => qr{^(?:A128GCM)$},
599 if( $opts->{accepted_enc} )
600 {
601 return( $self->error( "Accepted encoding option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_enc} ) );
602 if( scalar( @{$opts->{accepted_enc}} ) )
603 {
604 my $re = join( '|', @{$opts->{accepted_enc}} );
605 $param->{accepted_enc} = qr{^(?:\Q$re\E)$};
606 }
607 }
608  
609 if( ref( $opts->{verify_audience} ) eq 'Regexp' )
610 {
611 $param->{verify_aud} = $opts->{verify_audience};
612 }
613  
614 my $data;
615 # try-catch
616 local $@;
617 eval
618 {
619 ## $data = Crypt::JWT::decode_jwt( %$param );
620 $data = Net::API::REST::JWT::decode_jwt( %$param );
621 };
622 if( $@ )
623 {
624 return( $self->error( "There was an error decoding Json Web Token payload: $@" ) );
625 }
626 return( $data );
627 }
628  
629 sub jwt_encode
630 {
631 my $self = shift( @_ );
632 my $opts = $self->_get_args_as_hash( @_ );
633 return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} );
634 $opts->{encrypt} ||= $self->jwt_encrypt if( !length( $opts->{encrypt} ) );
635 $opts->{algo} ||= $self->jwt_algo;
636 if( $opts->{encrypt} )
637 {
638 $opts->{algo} ||= 'PBES2-HS256+A128KW';
639 }
640 else
641 {
642 $opts->{algo} ||= 'HS256';
643 }
644 $opts->{encoding} ||= $self->jwt_encoding || 'A128GCM';
645 return( $self->error( "No payload was provided." ) ) if( !$opts->{payload} );
646 return( $self->error( "Payload submitted is not an hash reference." ) ) if( ref( $opts->{payload} ) ne 'HASH' );
647 my $payload = $opts->{payload};
648 $payload->{iss} = $opts->{issuer} if( length( $opts->{issuer} ) );
649 $payload->{aud} = $opts->{audience} if( length( $opts->{audience} ) );
650 $payload->{azd} = $opts->{audience} if( length( $opts->{audience} ) );
651 $payload->{iat} = $opts->{issued_at} if( length( $opts->{issued_at} ) );
652 $payload->{sub} = $opts->{subject} if( length( $opts->{subject} ) );
653 if( length( $opts->{expires} ) )
654 {
655 $payload->{exp} = $opts->{expires};
656 }
657 elsif( length( $opts->{ttl} ) )
658 {
659 return( $self->error( "Property \"ttl\" provided is not an integer." ) ) if( $opts->{ttl} !~ /^\d+$/ );
660 $payload->{exp} = $opts->{iat} + $opts->{ttl};
661 }
662 my $token;
663 my %params =
664 (
665 payload => $payload,
666 ## do NOT allow the "none" algorithm, as this is massively insecure
667 allow_none => 0,
668 alg => $opts->{algo},
669 key => ( $opts->{key} || $self->key ),
670 enc => $opts->{encoding},
671 );
672 my @possible_additional_parameters = qw(
673 allow_none
674 auto_iat
675 extra_headers
676 keypass
677 relative_exp
678 relative_nbf
679 serialization
680 shared_unprotected_headers
681 unprotected_headers
682 zip
683 );
684 for( @possible_additional_parameters )
685 {
686 $params{ $_ } = $opts->{ $_ } if( CORE::exists( $opts->{ $_ } ) && CORE::length( $opts->{ $_ } ) );
687 }
688  
689 # try-catch
690 local $@;
691 eval
692 {
693 ## $token = Crypt::JWT::encode_jwt(
694 $token = Net::API::REST::JWT::encode_jwt( %params );
695 };
696 if( $@ )
697 {
698 return( $self->error( "Error in the arguments or payload when creating a Jason Web Token: $@" ) );
699 }
700 return( $token );
701 }
702  
703 sub jwt_encoding { return( shift->_set_get_scalar( 'jwt_encoding', @_ ) ); }
704  
705 sub jwt_encrypt { return( shift->_set_get_scalar( 'jwt_encrypt', @_ ) ); }
706  
707 # We extract the jwt data, and do not verify it, which is very unsecure of course
708 # Best to use jwt_verify()
709 sub jwt_extract
710 {
711 my $self = shift( @_ );
712 my $token = shift( @_ ) || return( $self->error( "No json web token was provided to extract its data." ) );
713 return( $self->error( "Token provided ($token) seems malformed. I was expecting 3 chunks of base64 data separated by dots" ) ) if( $token !~ /^([^\.]+)\.([^\.]+)\.([^\.]+)$/ );
714 my( $header, $claim, $crypto ) = split( /\./, $token, 3 );
715 my $hash = {};
716 # try-catch
717 local $@;
718 eval
719 {
720 $hash->{raw_header} = MIME::Base64::decode_base64( $header );
721 $hash->{raw_claim} = MIME::Base64::decode_base64( $claim );
722 my $j = JSON->new->allow_nonref;
723 $hash->{header} = $j->utf8->decode( $hash->{raw_header} );
724 $hash->{claim} = $j->utf8->decode( $hash->{raw_claim} );
725 };
726 if( $@ )
727 {
728 return( $self->error( "An error occured while attempting to extract token data: $@" ) );
729 }
730 return( $hash );
731 }
732  
733 sub jwt_verify
734 {
735 my $self = shift( @_ );
736 my $token;
737 my $opts = {};
738 if( @_ )
739 {
740 if( ref( $_[0] ) eq 'HASH' )
741 {
742 $opts = shift( @_ );
743 }
744 elsif( scalar( @_ ) >= 2 && !( @_ % 2 ) )
745 {
746 $opts = { @_ };
747 }
748 else
749 {
750 $token = shift( @_ );
751 }
752 }
753 $token ||= $opts->{token} || return( $self->error( "No json web token was provided to extract its data." ) );
754 my $hash = $self->jwt_extract( $token ) || return( undef() );
755 # Something like this:
756 # Downloaded from https://accounts.google.com/.well-known/openid-configuration
757 # and then from https://www.googleapis.com/oauth2/v3/certs
758 # {
759 # "keys": [
760 # {
761 # "kid": "2bf8418b2963f366f5fefdd127b2cee07c887e65",
762 # "e": "AQAB",
763 # "kty": "RSA",
764 # "alg": "RS256",
765 # "n": "uA8MNzSvgJTB_eHWj_HnpGzgtfBzsO4PjdNkEvdETRHEvyqIyqQnACRUNQ9KACnPV3R1M_1VlkJGRJ-xI3By3uylEOh4VagVRlCjLbsmuXburlOLn3TZSkwR7XE3pvVqcypq4nLPdu6foV__wcrLkZPMJzq654vepbOIegx5iVIvV2ilfdqs7VTwHRAUQU6nYfa8jaUwj1H_-zlaaHK-vxm-lWdGjAyiv-xBj5UmY24WtkTuX-MWLvOgbrqcYzMpzEm-LCdBbZR4qjQbWEatRISp4QW31xBZxF2FwMK2YWXDUW_GhXy0hgbsSyX-6jziTDSsulk9SNstSXmYCTZtvw",
766 # "use": "sig"
767 # },
768 # {
769 # "use": "sig",
770 # "kid": "0b0bf186743471a1edcac3060d1256f9e4050ba8",
771 # "e": "AQAB",
772 # "kty": "RSA",
773 # "alg": "RS256",
774 # "n": "0s9r8J5G5I77VpYWS-ttQ8GBDZBlxN_TZHl4DJHAi1WzvxQcP0hBPdASNqAnAuXA-ZxMpMtW_ovjhwo1Ncqpofd3c0H5mSzA9nsmmiex3AO7ZbkaGIdOcMYr4ttOFKZJn2giZWsfQuTlMEvcGyghViyy6l7t1-dMyxjbNOAVLVn25PHfWLbtffv-5EXFXt0Bp0wf0JjPghy4xXf3GjqqqaG_pOnmY_g2c6s8NwZG8dLymiqq0sta3URCUzDYnEHfx7Ol-grOYBOg6YjQP-gl0r5_uvB9Vl9jXKz-WcUUqVTuLp6S-CBstsOheUpSjX3vVP48KJIS4DX6NFHgjn8ooQ"
775 # }
776 # ]
777 # }
778 if( $opts->{rsa_keys} )
779 {
780 return( $self->error( "RSA keys provided with parameter \"rsa_keys\" is not an hash reference." ) ) if( ref( $opts->{rsa_keys} ) ne 'HASH' );
781 my $keys = $opts->{rsa_keys};
782 return( $self->error( "No \"keys\" property found in the rsa keys provided." ) ) if( !$keys->{keys} );
783 return( $self->error( "Property \"keys\" in rsa eys provided is not an array reference (of rsa keys)." ) ) if( !$self->_is_array( $keys->{keys} ) );
784 # Check all is in order before going further
785 my( $e, $n );
786 $n = 0;
787 foreach my $ref ( @{$keys->{keys}} )
788 {
789 $n++;
790 foreach my $p ( qw( kid e kty alg n ) )
791 {
792 return( $self->error( "No property \"$p\" could be found in this rsa key No $n. Hash is: ", sub{ $self->dump( $ref ) } ) ) if( !$ref->{ $p } );
793 }
794 }
795 # Make sure our header has alg set to rsa and there is a kid property, or else Crypt::JWT will die
796 # So at least, we can catch this issue and return an error gracefully...
797 # {"alg":"RS256","kid":"0b0bf186743471a1edcac3060d1256f9e4050ba8","typ":"JWT"}
798 my $header = $hash->{header} || return( $self->error( "Unable to get the header from the jwt token '$token'." ) );
799 return( $self->error( "JWT token header returned by jwt_extract is empty! Original token is: '$token'" ) ) if( !scalar( keys( %$header ) ) );
800 return( $self->error( "JWT token header found has no \"alg\" property set. Original token is: '$token'" ) ) if( !$header->{alg} );
801 return( $self->error( "JWT token header found has no \"kid\" property set. Original token is: '$token'" ) ) if( !$header->{kid} );
802 # https://metacpan.org/pod/Crypt::JWT#key
803 return( $self->error( "JWT validation was requested using rsa keys, but could not find the property \"alg\" set to \"RS256\"." ) ) if( $header->{alg} !~ /^(RS|PS|ES)\d{3}$/i );
804 my $kid = $header->{kid};
805 # Check if kid value is in the rsa keys provided.
806 foreach my $ref ( @{$keys->{keys}} )
807 {
808 if( $ref->{kid} eq $kid )
809 {
810 $e = $ref->{e};
811 $n = $ref->{n};
812 last;
813 }
814 }
815 return( $self->error( "Unable to find a matching key for the one found in the token header ($kid) against the rsa keys provided." ) ) if( !CORE::length( $e ) || !CORE::length( $n ) );
816 # Ok, we are very reasonably safe to call Crypt::JWT now
817 my $data;
818 # try-catch
819 local $@;
820 eval
821 {
822 # $data = Crypt::JWT::decode_jwt( token => $token );
823 # $data = Crypt::JWT::decode_jwt(
824 $data = Net::API::REST::JWT::decode_jwt(
825 token => $token,
826 kid_keys => $keys,
827 decode_payload => 1,
828 verify_exp => 0,
829 debug => 3,
830 );
831 };
832 if( $@ )
833 {
834 return( $self->error( "Faile validating jwt token '$token'. Reason is: $@" ) );
835 }
836 # Ok, we're good
837 }
838 return( $hash );
839 }
840  
841 sub jwt_verify_audience { return( shift->_set_get_object( 'jwt_verify_audience', 'Regexp', @_ ) ); }
842  
843 sub key { return( shift->_set_get_scalar( 'key', @_ ) ); }
844  
845 # The objects for request or response should be instantiated in handler()
846 sub request { return( shift->_set_get_object_without_init( 'request', 'Net::API::REST::Request', @_ ) ); }
847  
848 sub response { return( shift->_set_get_object_without_init( 'response', 'Net::API::REST::Response', @_ ) ); }
849  
850 sub route
851 {
852 my $self = shift( @_ );
853 # my $parts = shift( @_ ) || return( $self->error( "No path parts as array reference was provided." ) );
854 #return( $self->error( "Path parts provided ($parts) is not an array reference." ) ) if( ref( $parts ) ne 'ARRAY' );
855 my $uri = shift( @_ ) || return( $self->error({
856 code => 400,
857 message => "No uri was provided to find the appropriate route."
858 }) );
859 return( $self->error({ code => 500, message => "URI provided \"$uri\" is not an object." }) ) if( !Scalar::Util::blessed( $uri ) );
860 return( $self->error({ code => 500, message => "URI object provided \"$uri\" is not an URI object." }) ) if( !$uri->isa( 'URI' ) );
861 my $path = $uri->path;
862 if( my $base = $self->base_path )
863 {
864 $path =~ s/^\Q$base\E//;
865 }
866 my @points = split( /\/+/ , $path );
867 # Clean up empty path
868 my $parts = [ grep{ length( $_ ) > 0 } @points ];
869 my $client_api_version = '';
870 if( $parts->[0] =~ /^v?(\d+(?:\.\d+)*)$/ )
871 {
872 $client_api_version = $1;
873 shift( @$parts );
874 }
875 $client_api_version ||= $self->request->client_api_version || $self->api_version;
876 my $routes = $self->routes;
877 if( !scalar( keys( %$routes ) ) )
878 {
879 return( $self->error({ code => 500, message => "No routes set up to find the appropriate resource." }) );
880 }
881 elsif( !CORE::exists( $routes->{ $client_api_version } ) )
882 {
883 return( $self->error({ code => Apache2::Const::HTTP_NOT_ACCEPTABLE, message => "API version requested ($client_api_version) is not supported." }) );
884 }
885 my $req = $self->request;
886 my $resp = $self->response;
887 # Path variables like "/some/path/1234/more/thing/jack" where 1234 and jack are variables
888 # 2019-11-13: This is set by the caller of route()
889 # my $vars = $req->variables;
890 my $vars = {};
891 my $def_methods = $self->default_methods;
892 my $http_meth = lc( $req->method // '' );
893 # Until proven otherwise; If it is set at a certain point of the path, and nowhere after, then the path below inherit its value set before like a toll gate
894 my $access = 'public';
895 my $params;
896 my $check;
897 $check = sub
898 {
899 my( $pos, $subroutes ) = @_;
900 my $part = $parts->[ $pos ];
901 # reserved words cannot be used in path
902 return( '' ) if( $part =~ /^_(access_control|allowed_methods|handler|name|var|delete|get|head|patch|post|put)$/i );
903 if( exists( $subroutes->{ lc( $part ) } ) )
904 {
905 $part = lc( $part );
906 # Code reference
907 if( ref( $subroutes->{ $part } ) eq 'CODE' )
908 {
909 # Do we have still more path?
910 # If we do, we store it as variable _path_info and let the handler deal with it
911 # $vars->{_path_info} = [ splice( @$parts, $pos + 1 ) ] if( $#$parts > $pos );
912 # return( $subroutes->{ $part } );
913 my $ep = Net::API::REST::Endpoint->new(
914 handler => $subroutes->{ $part },
915 methods => $def_methods,
916 variables => $vars,
917 access => $access,
918 path => $uri,
919 ( defined( $params ) ? ( params => $params ) : () ),
920 debug => $self->debug,
921 );
922 $ep->path_info( [ splice( @$parts, $pos + 1 ) ] ) if( $#$parts > $pos );
923 return( $ep );
924 }
925 # path part has sub component, so we look for a key _handler in the sub hash
926 elsif( ref( $subroutes->{ $part } ) eq 'HASH' )
927 {
928 my $ref = $subroutes->{ $part };
929 if( !exists( $ref->{_handler} ) &&
930 !exists( $ref->{_delete} ) &&
931 !exists( $ref->{_get} ) &&
932 !exists( $ref->{_head} ) &&
933 !exists( $ref->{_post} ) &&
934 !exists( $ref->{_put} ) )
935 {
936 return( $self->error({ code => 500, message => "Found an entry for path part \"$part\", which is a hash reference, but could not find a key \"_handler\", \"_delete\", \"_get\", \"_head\", \"_post\", or \"_put\" inside it." }) );
937 }
938 my $methods = {};
939 foreach my $h ( qw( _delete _get _head _patch _post _put ) )
940 {
941 if( exists( $ref->{ $h } ) )
942 {
943 $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h };
944 }
945 }
946  
947 my $supported_methods = [sort( keys( %$methods ) )];
948 # If this is just a pre-flight check, at this stage the handler does not matter
949 my $handler = $http_meth eq 'options'
950 ? sub{}
951 : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler};
952  
953 # We reached the end, return the handler
954 # return( $ref->{_handler} ) if( $pos == $#$parts );
955 # return( $check->( $pos + 1, $ref ) );
956 $access = $ref->{_access_control} if( $ref->{_access_control} );
957 $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' );
958  
959 if( $pos == $#$parts )
960 {
961 if( ref( $handler ) eq 'CODE' )
962 {
963 my $ep = Net::API::REST::Endpoint->new(
964 handler => $handler,
965 methods => exists( $methods->{ uc( $http_meth ) } )
966 ? [uc( $http_meth )]
967 : ( scalar( @$supported_methods )
968 ? $supported_methods
969 : $ref->{_allowed_methods}
970 ? $ref->{_allowed_methods}
971 : $def_methods ),
972 variables => $vars,
973 access => $access,
974 path => $uri,
975 ( defined( $params ) ? ( params => $params ) : () ),
976 debug => $self->debug,
977 );
978 return( $ep );
979 }
980 elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ )
981 {
982 my( $cl, $meth ) = ( $1, $2 );
983 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
984 # require $cl unless( defined( *{"${cl}::"} ) );
985 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
986 # NOTE: 2021-09-05 (Jacques): See above same comment for the same issue, i.e. we only need to use the class name to check if the method exists, otherwise creating an instance of the object would have undesirable consequences under OPTIONS
987 my $code = $cl->can( $meth );
988 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
989 # return( sub{ $code->( $o, api => $self, @_ ) } );
990 # try-catch
991 local $@;
992 my $ep = eval
993 {
994 Net::API::REST::Endpoint->new(
995 handler => sub
996 {
997 my $o = $cl->new(
998 apache_request => $self->apache_request,
999 debug => $self->debug,
1000 request => $req,
1001 response => $resp,
1002 # Pass the api object here as well
1003 api => $self,
1004 );
1005 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1006 $code->( $o, api => $self, @_ );
1007 },
1008 methods => exists( $methods->{ uc( $http_meth ) } )
1009 ? [uc( $http_meth )]
1010 : ( scalar( @$supported_methods )
1011 ? $supported_methods
1012 : $ref->{_allowed_methods}
1013 ? $ref->{_allowed_methods}
1014 : $def_methods ),
1015 variables => $vars,
1016 access => $access,
1017 path => $uri,
1018 ( defined( $params ) ? ( params => $params ) : () ),
1019 debug => $self->debug,
1020 );
1021 };
1022 if( $@ )
1023 {
1024 return( $self->error({ code => 500, message => $@ }) );
1025 }
1026 return( $ep );
1027 }
1028 else
1029 {
1030 return( $self->error({ code => 500, message => "Found a route for the path part \"${part}\" and HTTP method ${http_meth}, but the handler found is not a code reference." }) );
1031 }
1032 }
1033 return( $check->( $pos + 1, $ref ) );
1034 }
1035 # Not a code or a hash reference, so it has got to be a package name
1036 elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ )
1037 {
1038 my( $cl, $meth ) = ( $1, $2 );
1039 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
1040 # require $cl unless( defined( *{"${cl}::"} ) );
1041 # my $rc = eval{ $self->_load_class( $cl ); };
1042 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1043 # NOTE: 2021-09-05 (Jacques): This turned out to be a bad idea to check if a method exists in class, because by merely instantiating an object, it would trigger execution of code that is undesirable when running under OPTIONS, which only aims to check sanity and not actually run the query.
1044 # As it turns out $cl->can( $meth ) works just as well.
1045 # my $o = $cl->new(
1046 # apache_request => $self->apache_request,
1047 # debug => $self->debug,
1048 # request => $req,
1049 # response => $resp,
1050 # # Pass the api object here as well
1051 # api => $self,
1052 # ) || return( $self->pass_error( $cl->error ) );
1053 # my $code = $o->can( $meth );
1054 my $code = $cl->can( $meth );
1055 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
1056 # return( sub{ $code->( $o, api => $self, @_ ) } );
1057 # try-catch
1058 local $@;
1059 my $ep = eval
1060 {
1061 Net::API::REST::Endpoint->new(
1062 handler => sub
1063 {
1064 my $o = $cl->new(
1065 apache_request => $self->apache_request,
1066 debug => $self->debug,
1067 request => $req,
1068 response => $resp,
1069 # Pass the api object here as well
1070 api => $self,
1071 );
1072 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1073 $code->( $o, api => $self, @_ );
1074 },
1075 methods => $def_methods,
1076 variables => $vars,
1077 access => $access,
1078 path => $uri,
1079 ( defined( $params ) ? ( params => $params ) : () ),
1080 debug => $self->debug,
1081 );
1082 };
1083 if( $@ )
1084 {
1085 return( $self->error({ code => 500, message => $@ }) );
1086 }
1087 return( $ep );
1088 }
1089 else
1090 {
1091 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" }) );
1092 }
1093 }
1094 elsif( exists( $subroutes->{_var} ) )
1095 {
1096 my $ref = $subroutes->{_var};
1097 return( $self->error({ code => 500, message => "Found a variable, and I was expecting a hash reference, but intsead got '$ref'." }) ) if( ref( $ref ) ne 'HASH' );
1098 return( $self->error({ code => 500, message => "Found a variable, and I was expecting a key _name to be present in the definition hash reference, but could not find one." }) ) if( !exists( $ref->{_name} ) );
1099 if( !exists( $ref->{_handler} ) &&
1100 !exists( $ref->{_delete} ) &&
1101 !exists( $ref->{_get} ) &&
1102 !exists( $ref->{_head} ) &&
1103 !exists( $ref->{_patch} ) &&
1104 !exists( $ref->{_post} ) &&
1105 !exists( $ref->{_put} ) )
1106 {
1107 return( $self->error({ code => 500, message => "Found a variable with name \"$ref->{_name}\" and was expecting a key _handler to be present in the definition hash reference, but could not find one." }) );
1108 }
1109  
1110 my $methods = {};
1111 foreach my $h ( qw( _delete _get _head _patch _post _put ) )
1112 {
1113 if( exists( $ref->{ $h } ) )
1114 {
1115 $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h };
1116 }
1117 }
1118  
1119 my $supported_methods = [sort( keys( %$methods ) )];
1120 # If this is just a pre-flight check, at this stage the handler does not matter
1121 my $handler = $http_meth eq 'options'
1122 ? sub{}
1123 : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler};
1124  
1125 my $var_name = $ref->{_name};
1126 $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' );
1127 # For variable type to be array
1128 if( exists( $ref->{_type} ) )
1129 {
1130 if( lc( $ref->{_type} ) eq 'array' || $ref->{_type} eq '[]' )
1131 {
1132 if( exists( $vars->{ $var_name } ) )
1133 {
1134 my $prev = $vars->{ $var_name };
1135 $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' );
1136 }
1137 else
1138 {
1139 $vars->{ $var_name } = [];
1140 }
1141 }
1142 }
1143 # Store variable value
1144 if( exists( $vars->{ $var_name } ) )
1145 {
1146 my $prev = $vars->{ $var_name };
1147 $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' );
1148 push( @{$vars->{ $var_name }}, $part );
1149 }
1150 else
1151 {
1152 $vars->{ $var_name } = $part;
1153 }
1154  
1155 # We reached the end, return the handler
1156 if( $pos == $#$parts )
1157 {
1158 $access = $ref->{_access_control} if( $ref->{_access_control} );
1159 if( ref( $handler ) eq 'CODE' )
1160 {
1161 # return( $ref->{_handler} );
1162 my $ep = Net::API::REST::Endpoint->new(
1163 handler => $handler,
1164 methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ),
1165 variables => $vars,
1166 access => $access,
1167 path => $uri,
1168 ( defined( $params ) ? ( params => $params ) : () ),
1169 debug => $self->debug,
1170 );
1171 $ep->access( $ref->{_access_control} ) if( $ref->{_access_control} );
1172 return( $ep );
1173 }
1174 elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ )
1175 {
1176 my( $cl, $meth ) = ( $1, $2 );
1177 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
1178 # require $cl unless( defined( *{"${cl}::"} ) );
1179 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1180 # NOTE: 2021-09-05 (Jacques): See above same comment for the same issue, i.e. we only need to use the class name to check if the method exists, otherwise creating an instance of the object would have undesirable consequences under OPTIONS
1181 # my $o = $cl->new(
1182 # apache_request => $self->apache_request,
1183 # debug => $self->debug,
1184 # request => $req,
1185 # response => $resp,
1186 # # Pass the api object here as well
1187 # api => $self,
1188 # ) || return( $self->pass_error( $cl->error ) );
1189 # my $code = $o->can( $meth );
1190 my $code = $cl->can( $meth );
1191 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
1192 # return( sub{ $code->( $o, api => $self, @_ ) } );
1193 # try-catch
1194 local $@;
1195 my $ep = eval
1196 {
1197 Net::API::REST::Endpoint->new(
1198 handler => sub
1199 {
1200 my $o = $cl->new(
1201 apache_request => $self->apache_request,
1202 debug => $self->debug,
1203 request => $req,
1204 response => $resp,
1205 # Pass the api object here as well
1206 api => $self,
1207 );
1208 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1209 $code->( $o, api => $self, @_ );
1210 },
1211 methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ),
1212 variables => $vars,
1213 access => $access,
1214 path => $uri,
1215 ( defined( $params ) ? ( params => $params ) : () ),
1216 debug => $self->debug,
1217 );
1218 };
1219 if( $@ )
1220 {
1221 return( $self->error({ code => 500, message => $@ }) );
1222 }
1223 return( $ep );
1224 }
1225 else
1226 {
1227 return( $self->error({ code => 500, message => "Found a scalar \"${handler}\" to handle variable \"$var_name\", 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" }) );
1228 }
1229 }
1230 return( $check->( $pos + 1, $ref ) );
1231 }
1232 # Empty means not found
1233 else
1234 {
1235 return( '' );
1236 }
1237 };
1238 # We return empty, not undef if nothing was found
1239 my $ep = $check->( 0, $routes->{ $client_api_version } );
1240 # An error occurred
1241 if( !defined( $ep ) )
1242 {
1243 return;
1244 }
1245 # Nothing found
1246 elsif( !length( $ep ) )
1247 {
1248 return( '' );
1249 }
1250 else
1251 {
1252 return( $ep );
1253 }
1254 }
1255  
1256 sub routes
1257 {
1258 my $self = shift( @_ );
1259 if( @_ )
1260 {
1261 my $hash = shift( @_ ) || return( $self->error({ code => 500, message => "No route hash reference was provided." }) );
1262 return( $self->error({ code => 500, message => "Routes provided ($hash) is not a hash reference." }) ) if( ref( $hash ) ne 'HASH' );
1263 my $req = $self->request;
1264 my $resp = $self->response;
1265 # Walk through the hash to check everything is ok
1266 # Returns nothing if all is ok, or self returns an error description
1267 my $check;
1268 $check = sub
1269 {
1270 my $this = shift( @_ );
1271 foreach my $k ( sort( keys( %$this ) ) )
1272 {
1273 my $v = $this->{ $k };
1274 if( $k eq '_params' )
1275 {
1276 return( "Value provided for _params is not an hash reference." ) if( ref( $v ) ne 'HASH' );
1277 }
1278 elsif( ref( $v ) eq 'HASH' )
1279 {
1280 if( !CORE::exists( $v->{_handler} ) &&
1281 !CORE::exists( $v->{_delete} ) &&
1282 !CORE::exists( $v->{_get} ) &&
1283 !CORE::exists( $v->{_head} ) &&
1284 !CORE::exists( $v->{_post} ) &&
1285 !CORE::exists( $v->{_put} ) )
1286 {
1287 return( "The keyword '_handlers' used is mispelled. It should be '_handler'" ) if( CORE::exists( $this->{_handlers} ) );
1288 return( "No handler was specified for the end point \"$k\". I was expecting a key \"_handler\", \"_delete\", \"_get\", \"_head\", \"_post\", or \"_put\" to be present." );
1289 }
1290 if( my $err = $check->( $v ) )
1291 {
1292 return( $err );
1293 }
1294 }
1295 elsif( $k eq '_name' )
1296 {
1297 return( "Value provided for _name is empty." ) if( !length( $v ) );
1298 return( "Value provided for _name is a reference, but I was expecting a scalar." ) if( ref( $v ) );
1299 }
1300 elsif( ref( $v ) eq 'CODE' )
1301 {
1302 # We're ok
1303 }
1304 elsif( $v =~ /^([^\:]+)\:{2}[^\:]+/ )
1305 {
1306 # my $cl = $subroutes->{ $part };
1307 my $cl = $v;
1308 my $meth;
1309 if( $cl =~ /^([^\-]+)\-\>(\S+)$/ )
1310 {
1311 ( $cl, $meth ) = ( $1, $2 );
1312 }
1313 # require $cl unless( defined( *{"${cl}::"} ) );
1314 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1315 # 2021-09-06: We do not need to instantiate an object to check if the module 'can' a method, and also this would trigger code which could lead to undesired results, because the instantiated object does not know if this is an actual query and at this stage could be missing authentication tokens to work properly. Yes, I am talking out of experience here :)
1316 #my $o = $cl->new(
1317 # apache_request => $self->apache_request,
1318 # debug => $self->debug,
1319 # request => $req,
1320 # response => $resp,
1321 # # Pass the api object here as well
1322 # api => $self,
1323 # checkonly => 1
1324 #) || return( $self->pass_error( $cl->error ) );
1325 if( !defined( $meth ) )
1326 {
1327 return( "Class \"$cl\" does not have a method \"$meth\"." ) if( !$cl->can( $meth ) );
1328 }
1329 }
1330 elsif( $k eq '_allowed_method' )
1331 {
1332 return( "The keyword '_allowed_method' used is mispelled. It should be '_allowed_methods'" ) if( !CORE::exists( $this->{_allowed_methods} ) );
1333 }
1334 elsif( $k eq '_access_controls' )
1335 {
1336 return( "The keyword '_access_controls' used is mispelled. It should be '_access_control'" ) if( !CORE::exists( $this->{_access_control} ) );
1337 }
1338 elsif( $k =~ /^_(allowed_methods|access_control)$/ )
1339 {
1340 # Ok
1341 }
1342 # If it is neither a code reference nor a package name, we raise an error
1343 else
1344 {
1345 return( "I was expecting a code reference or a package name, but instead got '$v' for key $k" );
1346 }
1347 }
1348 };
1349 # first level of keys are api version numbers, such as 1, 1.2, 2, etc...
1350 # and for each api version there is a set of route
1351 my @api_versions = keys( %$hash );
1352 foreach my $vers ( @api_versions )
1353 {
1354 if( $vers !~ /^\d+(?:\.\d+)*$/ )
1355 {
1356 return( $self->error( "API version number '$vers' is not a valid version number. Valid values are 1, 1.2, 1.5.3 for example." ) );
1357 }
1358 elsif( ref( $hash->{ $vers } ) ne 'HASH' )
1359 {
1360 return( $self->error( "API version number '$vers' value is not an hash reference. Its value must be a route to resources as hash reference." ) );
1361 }
1362 }
1363  
1364 foreach my $version ( sort( @api_versions ) )
1365 {
1366 if( my $err = $check->( $hash->{ $version } ) )
1367 {
1368 return( $self->error({ code => 500, message => $err }) );
1369 }
1370 }
1371 $self->{routes} = $hash;
1372 }
1373 return( $self->{routes} );
1374 }
1375  
1376 sub supported_api_versions
1377 {
1378 my $self = shift( @_ );
1379 if( @_ )
1380 {
1381 my $v = ref( $_[0] ) ? shift( @_ ) : \@_;
1382 my $vers = [];
1383 foreach my $this ( @$v )
1384 {
1385 push( @$vers, version->parse( $this ) );
1386 }
1387 $self->{supported_api_versions} = $vers;
1388 }
1389 return( $self->{supported_api_versions} );
1390 }
1391  
1392 sub supported_content_types { return( shift->_set_get_array( 'supported_content_types', @_ ) ); }
1393  
1394 sub supported_languages { return( shift->_set_get_array( 'supported_languages', @_ ) ); }
1395  
1396 sub supported_methods { return( shift->_set_get_array( 'supported_methods', @_ ) ); }
1397  
1398 sub well_known
1399 {
1400 my $self = shift( @_ );
1401 return( Apache2::Const::DECLINED );
1402 }
1403  
1404 sub _try
1405 {
1406 my $self = shift( @_ );
1407 my $pack = shift( @_ ) || return( $self->error( "No Apache package name was provided to call method" ) );
1408 my $meth = shift( @_ ) || return( $self->error( "No method name was provided to try!" ) );
1409 my $r = Apache2::RequestUtil->request;
1410 # $r->log_error( "Net::API::REST::_try to call method \"$meth\" in package \"$pack\"." );
1411 # try-catch
1412 local $@;
1413 my $rv = eval
1414 {
1415 return( $self->$pack->$meth ) if( !scalar( @_ ) );
1416 return( $self->$pack->$meth( @_ ) );
1417 };
1418 if( $@ )
1419 {
1420 return( $self->error( "An error occurred while trying to call Apache ", ucfirst( $pack ), " method \"$meth\": $@" ) );
1421 }
1422 return( $rv );
1423 }
1424  
1425 # NOTE: Net::API::REST::Endpoint package
1426 package Net::API::REST::Endpoint;
1427 BEGIN
1428 {
1429 use strict;
1430 use warnings;
1431 use parent qw( Module::Generic );
1432 };
1433  
1434 sub init
1435 {
1436 my $self = shift( @_ );
1437 # ACL
1438 $self->{access} = 'public';
1439 $self->{handler} = '';
1440 $self->{methods} = [];
1441 $self->{params} = {};
1442 $self->{path} = '';
1443 $self->{path_info} = [];
1444 $self->{variables} = {};
1445 $self->{_init_strict_use_sub} = 1;
1446 $self->SUPER::init( @_ );
1447 return( $self );
1448 }
1449  
1450 sub access { return( shift->_set_get_scalar( 'access', @_ ) ); }
1451  
1452 sub handler { return( shift->_set_get_code( 'handler', @_ ) ); }
1453  
1454 sub is_method_allowed
1455 {
1456 my $self = shift( @_ );
1457 my $meth = shift( @_ );
1458 my $ok_methods = $self->methods;
1459 return( scalar( grep( /^$meth$/i, @$ok_methods ) ) );
1460 }
1461  
1462 sub methods { return( shift->_set_get_array_as_object( 'methods', @_ ) ); }
1463  
1464 sub params { return( shift->_set_get_hash_as_mix_object( 'params', @_ ) ); }
1465  
1466 sub path { return( shift->_set_get_uri( 'path', @_ ) ); }
1467  
1468 sub path_info { return( shift->_set_get_array_as_object( 'path_info', @_ ) ); }
1469  
1470 # sub variables { return( shift->_set_get_hash_as_object( 'variables', 'Net::API::REST::Endpoint::Variables', @_ ) ); }
1471 sub variables { return( shift->_set_get_hash_as_mix_object( 'variables', @_ ) ); }
1472  
1473 # NOTE: Net::API::REST::RC package
1474 package Net::API::REST::RC;
1475 BEGIN
1476 {
1477 use strict;
1478 use warnings;
1479 use parent qw( Module::Generic );
1480 use overload (
1481 '""' => 'as_string',
1482 );
1483 };
1484  
1485 sub init
1486 {
1487 my $self = shift( @_ );
1488 $self->{code} = undef();
1489 $self->{message} = undef();
1490 $self->{_init_strict_use_sub} = 1;
1491 $self->SUPER::init( @_ );
1492 return( $self );
1493 }
1494  
1495 sub as_string { return( shift->{code} ); }
1496  
1497 sub code { return( shift->_set_get_number( 'code', @_ ) ); }
1498  
1499 sub message { return( shift->_set_get_scalar_as_object( 'message', @_ ) ); }
1500  
1501 sub TO_JSON { return( shift->{code} ); }
1502  
1503 1;
1504 # NOTE: pod
1505 __END__
1506  
1507 =encoding utf8
1508  
1509 =head1 NAME
1510  
1511 Net::API::REST - Framework for RESTful APIs
1512  
1513 =head1 SYNOPSIS
1514  
1515 package MyPackage;
1516 BEGIN
1517 {
1518 use strict;
1519 use curry;
1520 use parent qw( Net::API::REST );
1521 use Net::API::Stripe;
1522 };
1523  
1524 sub init
1525 {
1526 my $self = shift( @_ );
1527 $self->{routes} =
1528 {
1529 # API version 1
1530 1 =>
1531 {
1532 'favicon.ico' => $self->curry::noop,
1533 auth =>
1534 {
1535 google =>
1536 {
1537 _handler => $self->curry::oauth_google,
1538 callback => $self->curry::oauth_google(callback => 1),
1539 },
1540 linkedin =>
1541 {
1542 _handler => $self->curry::oauth_linkedin,
1543 callback => $self->curry::oauth_linkedin(callback => 1),
1544 },
1545 },
1546 },
1547 stripe => $self->curry::stripe,
1548 # Whatever method is fine. Will call the method handle in package MyAPI::Users to handle the endpoint
1549 users => 'MyAPI::Users->handle',
1550 preferences =>
1551 {
1552 _access_control => 'restricted',
1553 _delete => $self->curry::remove_preferences,
1554 _get => $self->curry::get_preferences,
1555 _post => $self->curry::update_preferences,
1556 },
1557 };
1558 $self->{api_version} = 1;
1559 $self->{supported_api_versions} = [qw( 1 )];
1560 # By default, we support the GET and POST to access our endpoints
1561 # It may be adjusted endpoint by endpoint and if nothing is specified this default is used.
1562 $self->{default_methods} = [qw( GET POST )];
1563 # This is ALL possible supported methods
1564 $self->{supported_methods} = [qw( DELETE GET HEAD OPTIONS PATCH POST PUT )];
1565 $self->{supported_languages} = [qw( en-GB en fr-FR fr ja-JP )];
1566 $self->{key} = 'kAncmaDajnacSnbGmbXamn';
1567 # We want JWE (Json Web Token encrypted). This will affect jwt_encode's behaviour
1568 $self->{jwt_encrypt} = 1;
1569 # Because we are encrypting
1570 $self->{jwt_algo} = 'PBES2-HS256+A128KW';
1571 $self->{jwt_encoding} = 'A128GCM' unless( length( $self->{jwt_encoding} ) );
1572 $self->{jwt_accepted_algo} = [qw( PBES2-HS256+A128KW HS256 )];
1573 $self->{jwt_accepted_encoding} = [qw( A128GCM )];
1574 $self->SUPER::init( @_ );
1575 return( $self );
1576 }
1577  
1578 sub stripe
1579 {
1580 my $self = shift( @_ );
1581 my $ep = $self->endpoint;
1582 my $pinfo = $ep->path_info;
1583 my $remote_ip = $self->request->remote_ip;
1584 my $sig = $self->request->headers( 'Stripe-Signature' );
1585 return( $self->reply({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "No signature found" }) ) if( !CORE::length( $sig ) );
1586 my $payload = $self->request->data || return( $self->reply({ code => Apache2::Const::HTTP_BAD_REQUEST, message => "No payload data received from the client." }) );
1587 ## Net::API::Stripe object
1588 my $stripe = Net::API::Stripe->new(
1589 # Enable debug to get debug data in http server log
1590 debug => 0,
1591 conf_file => "/home/john_doe/stripe-settings.json",
1592 ) || do
1593 {
1594 $self->message( 3, "Unable to initiate a Net::API::Stripe object using the configuration file /home/john_doe/stripe-settings.json" );
1595 return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => $self->oops }) );
1596 };
1597  
1598 # Do an IP source check to be sure this is Stripe talking to us
1599 if( !defined( my $ip_check = $stripe->webhook_validate_caller_ip({ ip => $remote_ip, ignore_ip => $ignore_ip }) ) )
1600 {
1601 return( $self->reply({ code => $stripe->error->code, message => $stripe->error->message }) );
1602 }
1603  
1604 # Now, we make sure this is Stripe sending this by checking the signature of the payload
1605 my $check = $stripe->webhook_validate_signature({
1606 secret => $signing_secret,
1607 signature => $sig,
1608 payload => $payload,
1609 time_tolerance => $max_time_spread,
1610 });
1611 if( !defined( $check ) )
1612 {
1613 return( $self->reply({code => $stripe->error->code, message => $stripe->error->message }) );
1614 }
1615  
1616 # Ok, if we are here, we passed all checks
1617 # Don't wait, reply ok back to Stripe so our request does not time out
1618 $self->response->code( Apache2::Const::HTTP_OK );
1619 my $json = $self->json->utf8->encode({ code => 200, success => $self->true });
1620 $self->response->print( $json );
1621 $self->response->rflush;
1622 # Do something with the payload received
1623 my $evt = $stripe->event( $payload ) ||
1624 return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => $self->oops }) );
1625 printf( STDERR "Received an event from api version %s on %s for Stripe object type %s\n", $evt->api_version, $evt->created->iso8601, $evt->type );
1626 return( Apache2::Const::HTTP_OK );
1627 }
1628  
1629 =head1 VERSION
1630  
1631 v1.2.5
1632  
1633 =head1 DESCRIPTION
1634  
1635 The purpose of this module is to provide a powerful, yet simple framework to implement a RESTful API under Apache2 mod_perl.
1636  
1637 As of version C<1.0.0>, this module inherits from L<Apache2::API>. Please check its documentation. Other methods specific to this module are documented here.
1638  
1639 =head1 METHODS
1640  
1641 =head2 new
1642  
1643 This initiates the package and take the following parameters:
1644  
1645 =over 4
1646  
1647 =item * C<request>
1648  
1649 This is a required parameter to be sent with a value set to a L<Apache2::RequestRec> object
1650  
1651 =item * C<debug>
1652  
1653 Optional. If set with a positive integer, this will activate verbose debugging message
1654  
1655 =back
1656  
1657 =head2 api_uri()
1658  
1659 Returns the api URI as a C<URI> object.
1660  
1661 =head2 api_version( integer or decimal )
1662  
1663 Get or sets the current api version on the server.
1664  
1665 =head2 base_path( path )
1666  
1667 If in the Directory directive of the Apache Virtual Host, a C<Net_API_REST_Base> was set, this method will be set with this value.
1668  
1669 =head2 compression_threshold( integer )
1670  
1671 The number of bytes threshold beyond which, the B<reply> method will gzip compress the data returned to the client.
1672  
1673 =head2 default_methods( [ qw( GET POST ... ) ] )
1674  
1675 This sets or gets the default methods supported by an endpoint.
1676  
1677 =head2 endpoint( [ Net::API::REST::Endpoint object ] )
1678  
1679 This gets or sets an L<Net::API::REST::Endpoint> object.
1680  
1681 =head2 handler
1682  
1683 This is the main method called by Apache to handle the response. To make this work, in the Apache configuration, you must set the handler to your package and have your package inherit from L<Net::API::REST>. For example:
1684  
1685 PerlResponseHandler MyPackage
1686  
1687 When called by Apache, B<handler> will initiate a L<Net::API::REST::Request> object and a L<Net::API::REST::Response>
1688  
1689 If the incoming request is an OPTIONS request such as a typical one issued during a javascript Ajax call, it will call the method B<http_options>() which will also set the cors policy by calling B<http_cors>()
1690  
1691 Finally, it will try to find a route for the endpoint sought in the incoming query, and construct a L<Net::API::REST::Endpoint> object with the context information of the endpoint, including information such as variables that could exist in the path. For example:
1692  
1693 /org/jp/llc/123/directors/42/profile
1694  
1695 Here the llc property has an id 123 and the directors property has an id 42. Those two variables are stored in the L<Net::API::REST::Endpoint> object. This object can then be accessed with the method B<endpoint>
1696  
1697 Having found a route, B<handler> calls the anonymous subroutine in charge of handling the endpoint.
1698  
1699 If no route was found, B<handler> returns a C<400 Bad Request>.
1700  
1701 If the endpoint handler returns undef(), B<handler> will return a C<500 Server Error>, otherwise it will pass the return value back to Apache. The return value should be an L<Apache2::Const> return code.
1702  
1703 =head2 http_cors()
1704  
1705 Checks http request context and set the proper CORS http headers.
1706  
1707 =head2 http_options()
1708  
1709 If the request is an OPTIONS request, this method is called. It will do a C<pre-flight check> and look forward to see if the user has access to the resource sought and sets the response http headers accordingly.
1710  
1711 =head2 init_headers( code reference )
1712  
1713 If this is set, then L<Net::API::REST::handler> will call it.
1714  
1715 =head2 is_allowed
1716  
1717 Get or set handlers to check permission for various aspects of the api.
1718  
1719 Each handler must return a valid HTTP Status code as an L<Apache2::Cons> value and if the returned code is an error, L<Net::API::REST> will stop right there and return it to Apache. See L<Net::API::REST::Status> for more information.
1720  
1721 Currently supported handlers types are:
1722  
1723 =over 4
1724  
1725 =item I<access>
1726  
1727 This is called in L</handler> and before it runs the code associated with the endpoint.
1728  
1729 For example:
1730  
1731 $self->is_allowed( access => sub
1732 {
1733 my $req = $self->request;
1734 my $ep = $self->endpoint;
1735 my $ref;
1736 # See: <https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html>
1737 if( $ep->access eq 'restricted' )
1738 {
1739 if( !$req->headers->get( 'Authorization' ) || !$req->headers->get( 'X-CSRF-Token' ) )
1740 {
1741 return( Apache2::Const::HTTP_NOT_ACCEPTABLE );
1742 }
1743 elsif( !( $ref = $self->auth_check ) )
1744 {
1745 return( Apache2::Const::HTTP_UNAUTHORIZED );
1746 }
1747 }
1748 # To implement the double submit security measure
1749 elsif( !$req->headers->get( 'X-CSRF-Token' ) )
1750 {
1751 return( Apache2::Const::HTTP_NOT_ACCEPTABLE );
1752 }
1753 });
1754  
1755 =item I<content_type>
1756  
1757 This handler, if present, is called from L</handler> before executing the code reference associated with the endpoint.
1758  
1759 It is designed to check the content type in the request is acceptable as a security measure recommended and described in L<OWASP REST security cheat sheet|https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html>
1760  
1761 For example:
1762  
1763 $self->is_allowed( content_type => sub
1764 {
1765 my $type = shift( @_ );
1766 # You can also get the request content type with:
1767 # my $type = $self->request->type;
1768 });
1769  
1770 =item I<method>
1771  
1772 This handler, if present, is called with the request method (e.g. GET, POST, etc) to check if it is allowed.
1773  
1774 Note that C<OPTIONS> is different and should always be allowed to implement pre-flight check for L<CORS|https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>
1775  
1776 For example:
1777  
1778 $self->is_allowed( method => sub
1779 {
1780 my $meth = shift( @_ );
1781 my $ok_methods = [qw( GET POST )];
1782 return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED ) if( !scalar( grep( $meth eq $_, @$ok_methods ) ) );
1783 });
1784  
1785 Note that this is equivalent to setting the value of L</supported_methods> to an array reference with values C<GET POST>, but provides you with more granularity and control.
1786  
1787 =item I<network>
1788  
1789 This is called very early in L</handler> and is designed to check if the user's ip is authorised to access the api.
1790  
1791 The handler is called with the remote ip address as a string.
1792  
1793 This could be a good opportunity to check for api abuse and throttling.
1794  
1795 For example:
1796  
1797 $self->is_allowed( network => sub
1798 {
1799 my $ip = shift( @_ );
1800 if( $self->is_banned( $ip ) )
1801 {
1802 return( Apache2::Const::HTTP_FORBIDDEN );
1803 }
1804 elsif( $self->is_throttled( $ip ) )
1805 {
1806 return( Apache2::Const::HTTP_TOO_MANY_REQUESTS );
1807 }
1808 else
1809 {
1810 # returning Apache2::Const::OK would work too although it is not the same value
1811 return( Apache2::Const::HTTP_OK );
1812 }
1813 });
1814  
1815 =back
1816  
1817 =head2 jwt_accepted_algo( string )
1818  
1819 Get or set the algorithm supported for the JWT tokens.
1820  
1821 =head2 jwt_accepted_encoding( string )
1822  
1823 Get or set the supported encoding for the JWT tokens.
1824  
1825 =head2 jwt_algo( string )
1826  
1827 The chosen algorithm to create JWT tokens
1828  
1829 =head2 jwt_decode( token )
1830  
1831 Given a JWT token, this will decode it and returns a hash reference
1832  
1833 =head2 jwt_encode
1834  
1835 Provided with an hash reference of parameters, and this will prepare the token data and call L<Net::API::REST::JWT/encode_jwt>
1836  
1837 It accepts the following arguments and additional arguments recognised by L<Net::API::REST::JWT> can also be provided and will be passed to L<Net::API::REST::JWT/encode_jwt> directly.
1838  
1839 It returns the encrypted token as a string or C<undef> if an error occurred which can be retrieved using the L<Module::Generic/error> method.
1840  
1841 =over 4
1842  
1843 =item * C<algo>
1844  
1845 This will set the I<alg> property in the token.
1846  
1847 =item * C<audience>
1848  
1849 This will set the I<aud> property in the token payload.
1850  
1851 =item * C<encoding>
1852  
1853 This will set the I<enc> property in the token payload.
1854  
1855 =item * C<encrypt>
1856  
1857 If true, this will encrypt the token. When provided this will affect the I<algo>.
1858  
1859 For example, when not encrypted, by default the algorithm used is C<HS256>, but when encryption is activated, the algorithm becomes C<PBES2-HS256+A128KW>
1860  
1861 =item * C<expires>
1862  
1863 This will set the I<exp> property in the token payload.
1864  
1865 =item * C<issued_at>
1866  
1867 This will set the I<iat> property in the token payload.
1868  
1869 =item * C<issuer>
1870  
1871 This will set the I<iss> property in the token payload.
1872  
1873 =item * C<key>
1874  
1875 This will set the I<key> property in the token payload.
1876  
1877 =item * C<payload>
1878  
1879 The hash data to become the token payload. It can contains discretionary elements.
1880  
1881 =item * C<subject>
1882  
1883 This will set the I<sub> property in the token payload.
1884  
1885 =item * C<ttl>
1886  
1887 If provided, this will set the I<exp> property to I<iat> + I<ttl>
1888  
1889 =back
1890  
1891 =head2 jwt_encoding
1892  
1893 =head2 jwt_encrypt
1894  
1895 =head2 jwt_extract
1896  
1897 =head2 jwt_verify
1898  
1899 =head2 jwt_verify_audience
1900  
1901 =head2 key
1902  
1903 =head2 request()
1904  
1905 Returns the L<Net::API::REST::Request> object. This object is set early during the instantiation in the B<handler> method.
1906  
1907 =head2 response
1908  
1909 Returns the L<Net::API::REST::Response> object. This object is set early during the instantiation in the B<handler> method.
1910  
1911 =head2 route( URI object )
1912  
1913 Given an uri, this will find the route for the endpoint sought and return and L<Net::API::REST::Endpoint> object.
1914 If nothing found, it will return an empty string.
1915 If there was an error, it will return C<undef> and set an error object that can be retrieved with the inherited L<Module::Generic/error> method. The error object will also contain a C<code> attribute which will represent an http status code.
1916  
1917 L</route> is called from L</handler> to get the endpoint object and related handler, then calls the handler after performing a number of operations. See L</handler> for more information.
1918  
1919 Otherwise, a L<Net::API::REST::Endpoint> is returned.
1920  
1921 =head2 routes( hash reference )
1922  
1923 This sets the routes for all the endpoints proposed by the RESTful server
1924  
1925 =head2 supported_api_versions( array reference )
1926  
1927 Get or set the list of supported api versions
1928  
1929 =head2 supported_content_types
1930  
1931 Get or set an array of supported content types, such as C<application/json>, C<text/html> or C<text/plain>
1932  
1933 =head2 supported_languages( array reference )
1934  
1935 Get or set the list of supported language codes, such as fr_FR, en_GB, ja_JP, zh_TW, etc
1936  
1937 =head2 supported_methods( array reference )
1938  
1939 =head2 well_known()
1940  
1941 If the http request is for /.well-know, then we simply decline to process it.
1942  
1943 This does not mean it won't get processed, but just that we pass and let Apache handle it directly.
1944  
1945 =head2 _try( object type, method name, @_ )
1946  
1947 Given an object type, a method name and optional parameters, this attempts to call it.
1948  
1949 Apache2 methods are designed to die upon error, whereas our model is based on returning C<undef> and setting an exception with L<Module::Generic::Exception>, because we believe that only the main program should be in control of the flow and decide whether to interrupt abruptly the execution, not some sub routines.
1950  
1951 =head1 AUTHOR
1952  
1953 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1954  
1955 =head1 SEE ALSO
1956  
1957 L<Net::API::REST::JWT>, L<Net::API::REST::Endpoint>, L<Net::API::REST::Request>, L<Net::API::REST::Response>
1958  
1959 L<Apache2::API::DateTime>, L<Apache2::API::Query>, L<Apache2::API::Request>, L<Apache2::API::Response>, L<Apache2::API::Status>
1960  
1961 L<Apache2::Request>, L<Apache2::RequestRec>, L<Apache2::RequestUtil>
1962  
1963 =head1 COPYRIGHT & LICENSE
1964  
1965 Copyright (c) 2018-2023 DEGUEST Pte. Ltd.
1966  
1967 You can use, copy, modify and redistribute this package and associated
1968 files under the same terms as Perl itself.
1969  
1970 =cut
« blib/lib/Net/API/REST/Status.pm ↑ Summary lib/Net/API/REST/Cookie.pm »