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
« REST/JWT.pm ↑ Summary REST/Cookie.pm »
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## REST API Framework - ~/lib/Net/API/REST.pm
4 ## Version v1.2.7
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2019/09/01
8 ## Modified 2026/11/09
9 ##
10 ## All rights reserved
11 ##
12 ## This program is free software; you can redistribute it and/or modify it
13 ## under the same terms as Perl itself.
14 ##----------------------------------------------------------------------------
15 package Net::API::REST;
16 BEGIN
17 {
18 2 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶ use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 0 ▶ use Apache2::API qw( :common );
Subroutine BEGIN: called CC=1 SCAR=2.6
22 use parent qw( Apache2::API );
23 use vars qw( $VERSION $DEBUG $API_VERSION );
24 use curry;
25 use version;
26 use Apache2::Reload;
27 use JSON::PP ();
28 use Regexp::Common;
29 use Scalar::Util ();
30 # use Crypt::JWT;
31 # 2019-09-26
32 # We use our own drop-in replacement because of a bug in ModPerl and JSON::XS not recognising hash reference passed
33 use Net::API::REST::JWT;
34 # use DateTime::Format::Strptime;
35 use Net::API::REST::DateTime;
36 use MIME::Base64 ();
37 # use IO::Compress::Gzip;
38 # use IO::Compress::Bzip2;
39 # use IO::Compress::Deflate;
40 use Net::API::REST::Request;
41 use Net::API::REST::Response;
42 use Apache2::API::Status;
43 $VERSION = 'v1.2.7';
44 };
45  
46 use strict;
47 use warnings;
48  
49 $DEBUG = 0;
50 $API_VERSION = 1;
51 our @AVAILABLE_API_VERSIONS = qw( 1 );
52  
53 sub init
54 {
55 my $self = shift( @_ );
56 $self->{request} = '' unless( $self->{request} );
57 $self->{response} = '' unless( $self->{response} );
58 $self->{apache_request} = '' unless( $self->{apache_request} );
59 # Routes to endpoint to which are attached resources
60 $self->{routes} = {} unless( scalar( keys( %{$self->{routes}} ) ) );
61 $self->{api_version} = 1 if( !length( $self->{api_version} ) );
62 $self->{default_methods} = [qw( GET POST )] unless( $self->{default_methods} );
63 $self->{is_allowed} = {} unless( $self->{is_allowed} && scalar( keys( %{$self->{is_allowed}} ) ) );
64 $self->{supported_content_types} = [] unless( $self->{supported_methods} );
65 $self->{supported_methods} = [qw( DELETE GET HEAD OPTIONS PATCH POST PUT )] unless( $self->{supported_methods} );
66 $self->{supported_api_versions} = [qw( 1 )] unless( $self->{supported_api_versions} );
67 $self->{key} = '' unless( length( $self->{key} ) );
68 $self->{jwt_accepted_algo} = [] unless( length( $self->{jwt_accepted_algo} ) );
69 $self->{jwt_accepted_encoding} = [] unless( length( $self->{jwt_accepted_encoding} ) );
70 $self->{jwt_encrypt} = 1 unless( length( $self->{jwt_encrypt} ) );
71 $self->{jwt_algo} = 'HS256' unless( length( $self->{jwt_algo} ) );
72 $self->{jwt_encoding} = 'A128GCM' unless( length( $self->{jwt_encoding} ) );
73 # 200Kb
74 $self->{compression_threshold} = 204800 unless( length( $self->{compression_threshold} ) );
75 $self->{lang} = '' unless( length( $self->{lang} ) );
76 $self->{api_uri} = '' unless( length( $self->{api_uri} ) );
77 $self->{is_allowed} = {} unless( $self->{is_allowed} && ref( $self->{is_allowed} ) eq 'HASH' );
78 # Default handlers
79 $self->{is_allowed}->{access} = sub{ return( Apache2::Const::HTTP_OK ); } unless( exists( $self->{is_allowed}->{access} ) && ref( $self->{is_allowed}->{access} ) eq 'CODE' );
80 $self->{is_allowed}->{network} = sub{ return( Apache2::Const::HTTP_OK ); } unless( exists( $self->{is_allowed}->{network} ) && ref( $self->{is_allowed}->{network} ) eq 'CODE' );
81 $self->SUPER::init( @_ ) || return( $self->pass_error );
82 if( length( $self->{api_version} ) )
83 {
84 $self->api_version( $self->{api_version} );
85 }
86 if( $self->{routes} )
87 {
88 $self->routes( $self->{routes} ) || return( $self->pass_error );
89 }
90 $self->supported_api_versions( $self->{supported_api_versions} ) if( $self->{supported_api_versions} );
91 foreach my $k ( qw( jwt_encrypt jwt_algo jwt_encoding jwt_accepted_algo jwt_accepted_encoding ) )
92 {
93 $self->$k( $self->{ $k } );
94 }
95 return( $self );
96 }
97  
98 sub api_uri { return( shift->_set_get_object( 'api_uri', 'URI', @_ ) ); }
99  
100 sub api_version
101 {
102 my $self = shift( @_ );
103 if( @_ )
104 {
105 my $v = shift( @_ );
106 unless( ref( $v ) eq 'version' )
107 {
108 $v = version->parse( $v );
109 }
110 $self->{api_version} = $v;
111 }
112 return( $self->{api_version} );
113 }
114  
115 sub base_path { return( shift->_set_get_scalar( 'base_path', @_ ) ); }
116  
117 sub checkonly { return( shift->_set_get_boolean( 'checkonly', @_ ) ); }
118  
119 sub default_methods { return( shift->_set_get_array( 'default_methods', @_ ) ); }
120  
121 sub endpoint { return( shift->_set_get_object( 'endpoint', 'Net::API::REST::Endpoint', @_ ) ); }
122  
123 # In Apache2 conf:
124 # PerlResponseHandler MyPackage::REST which would inherit from Net::API::REST
125 sub handler : method
126 {
127 # https://perl.apache.org/docs/2.0/user/handlers/http.html#HTTP_Request_Handler_Skeleton
128 my( $class, $r ) = @_;
129 # my $handlerClass = $r->dir_config( 'Net_API_REST_Handler' ) || 'Net::API::REST' ;
130 my $debug = $r->dir_config( 'DEBUG' ) || $DEBUG;
131 my $req = Net::API::REST::Request->new( $r, debug => $debug );
132 # An error has occurred
133 if( !defined( $req ) )
134 {
135 $r->log_error( "${class}::handler: Error instantiating an Net::API::REST::Request object: " . Net::API::REST::Request->error );
136 return( Net::API::REST::Request->error->code || Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
137 }
138 my $resp = Net::API::REST::Response->new( request => $req, debug => $debug ) || do
139 {
140 $r->log_error( "${class}::handler: Error instantiating an Net::API::REST::Response object: " . Net::API::REST::Response->error );
141 return( Net::API::REST::Response->error->code || Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
142 };
143 my $self = $class->new(
144 apache_request => $r,
145 debug => $debug,
146 request => $req,
147 response => $resp,
148 );
149 if( !defined( $self ) )
150 {
151 $r->log_error( "Error instantiating a new $class object: ", $class->error );
152 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
153 }
154  
155 $self->request( $req );
156 $self->response( $resp );
157  
158 if( my $code = $self->log_handler )
159 {
160 $r->set_handlers( 'PerlPrivateLogHandler' => $code );
161 }
162  
163 # $self->apache_request( $r );
164 # $r->log_error( "Received Apache request $r, object debug value is: ", $self->debug );
165 # Full uri. $r->uri only returns the path
166 my $uri = $req->uri;
167 $self->api_uri( URI->new( $uri->scheme . '://' . $uri->host ) );
168 # Response content type
169 $r->content_type( 'application/json' );
170 my $json = JSON->new->relaxed->utf8;
171 $self->{json} = $json;
172  
173 # No need to go further if the ip address is not allowed to access the REST api.
174 # Here you could check for IP ban, or whether there is enough authorisation to access the endpoint
175 my $ok_net = $self->is_allowed( 'network' );
176 if( $ok_net && ref( $ok_net ) )
177 {
178 # Get a return code, and possibly a hash containing the message property
179 my( $rc, $rdef ) = $ok_net->( $req->remote_ip );
180 if( defined( $rc ) && $resp->is_error( "$rc" ) )
181 {
182 if( $self->_is_a( $rc, 'Net::API::REST::RC' ) )
183 {
184 return( $self->reply({ code => $rc->code, message => $rc->message }) );
185 }
186 elsif( $rdef && $self->_is_hash( $rdef ) && CORE::exists( $rdef->{message} ) )
187 {
188 return( $self->reply({ code => $rc, message => $rdef->{message} }) );
189 }
190 # Net::API::REST::reply will automatically set a json with an error message based on the user language
191 else
192 {
193 return( $self->reply({ code => $rc }) );
194 }
195 }
196 }
197  
198 # No need to go further if the requested method is not supported
199 my $ok_methods = $self->supported_methods;
200 my $http_meth = $req->method;
201 if( scalar( @$ok_methods ) && !scalar( grep( /^$http_meth$/i, @$ok_methods ) ) )
202 {
203 # Net::API::REST::reply will automatically set a json with an error message based on the user language
204 return( $self->reply({ code => Apache2::Const::HTTP_METHOD_NOT_ALLOWED }) );
205 }
206  
207 # Check supported content-type
208 # Ref: <https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html>
209 my $ok_ct = $self->supported_content_types;
210 # Only the content type, ie without the charset. Example: application/json; charset=utf-8
211 my $ct = lc( $req->type // '' );
212 # We check if content type is provided at all since it could be missing, such as in
213 # a OPTIONS, POST or GET request with no content or query
214 if( length( $ct ) && scalar( @$ok_ct ) && !scalar( grep( $ct eq $_, @$ok_ct ) ) )
215 {
216 # Net::API::REST::reply will automatically set a json with an error message based on the user language
217 return( $self->reply({ code => Apache2::Const::HTTP_NOT_ACCEPTABLE }) );
218 }
219  
220 # Check if there is a required api version and if we support it
221 if( $req->client_api_version )
222 {
223 my $ok_versions = $self->supported_api_versions;
224 my $client_version = $req->client_api_version;
225 my $client_api_version_is_ok = 0;
226 foreach my $v ( @$ok_versions )
227 {
228 if( $v == $client_version )
229 {
230 $client_api_version_is_ok++;
231 }
232 }
233 return( $self->reply( Apache2::Const::HTTP_NOT_ACCEPTABLE, { error => "API version requested ($client_version) is not supported." } ) ) unless( $client_api_version_is_ok );
234 }
235  
236 # Protection against DNS rebinding attacks
237 # https://www.w3.org/TR/cors/#list-of-headers
238 if( my $req_host = $req->headers( 'Host' ) )
239 {
240 my $req_host_uri = URI->new( $self->api_uri->scheme . '://' . $req_host );
241 if( lc( $req_host_uri->host ) ne $self->api_uri->host )
242 {
243 # Net::API::REST::reply will automatically set a json with an error message based on the user language
244 return( $self->reply({ code => Apache2::Const::HTTP_UNAUTHORIZED }) );
245 }
246 }
247  
248 # If there is a init_headers handler, call it to initiate the headers
249 my $init_headers = $self->init_headers;
250 if( $init_headers && ref( $init_headers ) eq 'CODE' )
251 {
252 $init_headers->({ request => $req, response => $resp });
253 }
254  
255 if( $http_meth eq 'OPTIONS' )
256 {
257 return( $self->http_options );
258 }
259 elsif( $http_meth eq 'HEAD' )
260 {
261 # $r->send_http_header;
262 return( Apache2::Const::HTTP_NO_CONTENT );
263 }
264  
265 my $origin = $req->headers( 'Origin' );
266 if( $origin )
267 {
268 $self->http_cors;
269 }
270  
271 my $path = $uri->path;
272 if( my $base = $r->dir_config( 'Net_API_REST_Base' ) )
273 {
274 $self->base_path( $base );
275 }
276 my $ep = $self->route( $uri );
277 if( !defined( $ep ) )
278 {
279 my $json = {};
280 my $code = $self->error->code;
281 if( $code )
282 {
283 $json->{code} = $code;
284 $json->{message} = $self->error->message;
285 }
286 else
287 {
288 $json->{code} = Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
289 }
290 # Net::API::REST::reply will automatically set a json with an error message based on the user language
291 return( $self->reply( $json ) );
292 }
293 # No resource found matching the user request, returning a 400
294 elsif( !length( $ep ) )
295 {
296 # Net::API::REST::reply will automatically set a json with an error message based on the user language
297 return( $self->reply({ code => Apache2::Const::HTTP_BAD_REQUEST }) );
298 }
299 elsif( !$ep->is_method_allowed( $http_meth ) )
300 {
301 return( $self->reply({ code => Apache2::Const::HTTP_METHOD_NOT_ALLOWED }) );
302 }
303 else
304 {
305 $self->endpoint( $ep );
306 my $handler = $ep->handler;
307 my $vars = $ep->variables;
308 $req->variables( $vars );
309 # require B::Deparse;
310 # my $deparse = B::Deparse->new( '-p', '-sC' );
311 # my $meth_body = $deparse->coderef2text( $ep->handler );
312 my $tmpl = <<EOT;
313 Endpoint information:
314 Handler .......: %s
315 Access type ...: %s
316 Ok methods ....: %s
317 Path ..........: %s
318 Path info .....: %s
319 Variables .....: %s
320 Params ........: %s
321 EOT
322 $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 ) ) );
323 # Check access with handler
324 my $ok_access = $self->is_allowed( 'access' );
325 if( $ok_access && ref( $ok_access ) eq 'CODE' )
326 {
327 my( $rc, $rdef ) = $ok_access->( $ep );
328 if( $resp->is_error( "$rc" ) )
329 {
330 # Net::API::REST::reply will automatically set a json with an error message based on the user language
331 # return( $self->reply({ code => $rc }) );
332 if( $self->_is_a( $rc, 'Net::API::REST::RC' ) )
333 {
334 return( $self->reply({ code => $rc->code, message => $rc->message }) );
335 }
336 elsif( $rdef && $self->_is_hash( $rdef ) && CORE::exists( $rdef->{message} ) )
337 {
338 return( $self->reply({ code => $rc, message => $rdef->{message} }) );
339 }
340 # Net::API::REST::reply will automatically set a json with an error message based on the user language
341 else
342 {
343 return( $self->reply({ code => $rc }) );
344 }
345 }
346 }
347  
348 # use B::Deparse;
349 # my $deparse = B::Deparse->new("-p", "-sC");
350 # my $code_body = $deparse->coderef2text( $handler );
351  
352 # try-catch
353 local $@;
354 my $rc = eval
355 {
356 # my $rc = $ep->handler->();
357 $handler->();
358 };
359 if( $@ )
360 {
361 $self->error({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR, message => $@ });
362 # return( $self->reply( 500, { message => 'An internal server error occured' } ) );
363 return( $self->bailout( "An error occurred while executing code for api resource: $@" ) );
364 }
365 # Server error
366 if( !defined( $rc ) )
367 {
368 my $ex = $self->error;
369 if( $ex )
370 {
371 # Apache2::API->reply that we inherit from recognises exception, and will extract code, message, locale from it.
372 return( $self->reply( $ex ) );
373 }
374 else
375 {
376 # Net::API::REST::reply will automatically set a json with an error message based on the user language
377 # It is ok to set a reply ourself here, because if it were a normal response, we would not be getting an undef value
378 return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR }) );
379 # return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
380 }
381 }
382 elsif( $rc == Apache2::Const::HTTP_OK )
383 {
384 return( Apache2::Const::OK );
385 }
386 else
387 {
388 return( $rc );
389 }
390 # Stop sending data !!
391 $self->request->socket->close;
392 exit(0);
393 }
394 }
395  
396 # Mut be overriden by sub package
397 sub http_cors { return; }
398  
399 # https://www.w3.org/TR/cors/#http-access-control-allow-origin
400 sub http_options
401 {
402 my $self = shift( @_ );
403 my $req = $self->request;
404 my $res = $self->response;
405 my $uri = $req->uri;
406 my $ep = $self->route( $uri );
407 my $http_meth = $req->method;
408 if( !defined( $ep ) )
409 {
410 return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
411 }
412 elsif( !CORE::length( $ep ) )
413 {
414 return( Apache2::Const::HTTP_NOT_FOUND );
415 }
416 my $tmpl = <<EOT;
417 Endpoint information:
418 Handler .......: %s
419 Access type ...: %s
420 Ok methods ....: %s
421 Path info .....: %s
422 Variables .....: %s
423 EOT
424 $self->noexec->messagef( 3, $tmpl, $ep->handler, $ep->access, join( ', ', @{$ep->methods} ), join( ', ', @{$ep->path_info} ), $self->dumper( $ep->variables->as_hash ) );
425  
426 my $req_methods = [CORE::split( /\,[[:blank:]]*/, ( $req->headers( 'Access-Control-Request-Method' ) || '' ) )];
427 if( scalar( @$req_methods ) )
428 {
429 foreach my $m ( @$req_methods )
430 {
431 if( !$ep->is_method_allowed( $m ) )
432 {
433 return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED );
434 }
435 }
436 if( !$ep->methods->is_empty )
437 {
438 $res->headers( 'Access-Control-Allow-Methods' => $ep->methods->join( ', ' )->scalar );
439 }
440 else
441 {
442 $res->headers( 'Access-Control-Allow-Methods' => '*' );
443 }
444 }
445  
446 my $origin = $req->headers( 'Origin' ) || $req->headers( 'Access-Control-Request-Origin' );
447 if( !$origin )
448 {
449 return( Apache2::Const::HTTP_NO_CONTENT );
450 }
451 my $allow_origin = $req->headers( 'Access-Control-Allow-Origin' );
452 # "The string "*" cannot be used for a resource that supports credentials"
453 # https://www.w3.org/TR/cors/#http-access-control-allow-origin
454 if( $allow_origin )
455 {
456 if( $ep->access eq 'restricted' )
457 {
458 if( $allow_origin eq '*' )
459 {
460 $res->headers( 'Access-Control-Allow-Origin' => $origin );
461 $res->headers( 'Access-Control-Max-Age' => 5 );
462 }
463 }
464 $res->headers( 'Access-Control-Allow-Credentials' => 'true' );
465 }
466 else
467 {
468 if( $ep->access eq 'restricted' )
469 {
470 if( $origin )
471 {
472 $res->headers( 'Access-Control-Allow-Origin' => $origin );
473 }
474 else
475 {
476 # Stringify
477 $res->headers( 'Access-Control-Allow-Origin' => $self->api_uri . '' );
478 }
479 $res->headers(
480 'Access-Control-Allow-Credentials' => 'true',
481 'Access-Control-Max-Age' => 5
482 );
483 }
484 elsif( $origin )
485 {
486 $res->headers(
487 'Access-Control-Allow-Origin' => $origin,
488 'Access-Control-Allow-Credentials' => 'true',
489 'Access-Control-Max-Age' => 5
490 );
491 }
492 else
493 {
494 $res->headers( 'Access-Control-Allow-Origin' => '*' );
495 }
496 }
497 my $req_headers = $req->headers( 'Access-Control-Request-Headers' );
498 if( $req_headers )
499 {
500 $res->headers( 'Access-Control-Allow-Headers' => $req_headers );
501 }
502 my $cred_required = $req->headers( 'Credentials' ) // '';
503 if( lc( $cred_required ) eq 'include' )
504 {
505 $res->headers( 'Access-Control-Allow-Credentials' => 'true' );
506 }
507 # Check from the most restrictive allowed methods in the context of the endpoint to the broader one for generally all supported methods
508 my $ok_methods = scalar( @{$ep->methods} ) ? $ep->methods : $self->supported_methods;
509 $res->headers( 'Access-Control-Allow-Methods' => join( ', ', @$ok_methods ) );
510  
511 # $r->headers_out->add( 'Allow' => join( ',', @$ok_methods ) );
512 # $r->rflush;
513 return( Apache2::Const::HTTP_NO_CONTENT );
514 }
515  
516 # To be overriden by module inheriting our package
517 sub init_headers { return(1); }
518  
519 # Set or get handlers for various phases to check if the user is allowed access
520 # Currently available handlers: network and access
521 sub is_allowed
522 {
523 my $self = shift( @_ );
524 my $all = $self->{is_allowed};
525 if( @_ )
526 {
527 return( $self->error( "Wrong number of parameters provided: '", join( "', '", @_ ), "'." ) ) if( scalar( @_ ) > 1 && !( scalar( @_ ) % 2 ) );
528 if( !( scalar( @_ ) % 2 ) )
529 {
530 while( my( $key, $code ) = splice( @_, 0, 2 ) )
531 {
532 if( $code )
533 {
534 return( $self->error( "I was expecting a code reference for the handler '$key', but instead I got '$code'." ) ) if( ref( $code ) ne 'CODE' );
535 $all->{ $key } = $code;
536 }
537 }
538 return( $self );
539 }
540 else
541 {
542 my $key = shift( @_ );
543 return( '' ) if( !exists( $all->{ $key } ) );
544 return( $all->{ $key } );
545 }
546 }
547 }
548  
549 sub jwt_accepted_algo { return( shift->_set_get_array( 'jwt_accepted_algo', @_ ) ); }
550  
551 sub jwt_accepted_encoding { return( shift->_set_get_array( 'jwt_accepted_encoding', @_ ) ); }
552  
553 sub jwt_algo { return( shift->_set_get_scalar( 'jwt_algo', @_ ) ); }
554  
555 sub jwt_decode
556 {
557 my $self = shift( @_ );
558 my $opts = {};
559 if( ref( $_[0] ) eq 'HASH' )
560 {
561 $opts = shift( @_ );
562 }
563 # A simple decode, most likely for public jwt like google, linkedin, etc.
564 elsif( scalar( @_ ) == 1 )
565 {
566 my $token = shift( @_ );
567 my $data;
568 # try-catch
569 local $@;
570 eval
571 {
572 # $data = Crypt::JWT::decode_jwt( token => $token );
573 $data = Net::API::REST::JWT::decode_jwt( token => $token );
574 };
575 if( $@ )
576 {
577 return( $self->error( "There was an error decoding Json Web Token payload: $@" ) );
578 }
579 return( $data );
580 }
581 return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} );
582 return( $self->error( "No token was provided to decode." ) ) if( !$opts->{token} );
583 $opts->{algo} ||= $self->jwt_algo;
584 $opts->{accepted_algo} ||= $self->jwt_accepted_algo;
585 $opts->{accepted_encoding} ||= $self->jwt_accepted_encoding;
586 $opts->{verify_audience} ||= $self->jwt_verify_audience;
587 my $param =
588 {
589 token => $opts->{token},
590 key => $opts->{key},
591 decode_payload => 1,
592 decode_header => 1,
593 # verify_iss => sub{ 1; }
594 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}$},
595 };
596 # PBES2-HS256+A128KW
597 # accepted_alg => qr{^(?:PBES2\-HS256\+A128KW|HS256)$},
598 if( $opts->{accepted_algo} )
599 {
600 return( $self->error( "Accepted alorithm option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_algo} ) );
601 if( scalar( @{$opts->{accepted_algo}} ) )
602 {
603 my $re = join( '|', @{$opts->{accepted_algo}} );
604 $param->{accepted_alg} = qr{^(?:\Q$re\E)$};
605 }
606 }
607  
608 # accepted_enc => qr{^(?:A128GCM)$},
609 if( $opts->{accepted_enc} )
610 {
611 return( $self->error( "Accepted encoding option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_enc} ) );
612 if( scalar( @{$opts->{accepted_enc}} ) )
613 {
614 my $re = join( '|', @{$opts->{accepted_enc}} );
615 $param->{accepted_enc} = qr{^(?:\Q$re\E)$};
616 }
617 }
618  
619 if( ref( $opts->{verify_audience} ) eq 'Regexp' )
620 {
621 $param->{verify_aud} = $opts->{verify_audience};
622 }
623  
624 my $data;
625 # try-catch
626 local $@;
627 eval
628 {
629 ## $data = Crypt::JWT::decode_jwt( %$param );
630 $data = Net::API::REST::JWT::decode_jwt( %$param );
631 };
632 if( $@ )
633 {
634 return( $self->error( "There was an error decoding Json Web Token payload: $@" ) );
635 }
636 return( $data );
637 }
638  
639 sub jwt_encode
640 {
641 my $self = shift( @_ );
642 my $opts = $self->_get_args_as_hash( @_ );
643 return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} );
644 $opts->{encrypt} ||= $self->jwt_encrypt if( !length( $opts->{encrypt} ) );
645 $opts->{algo} ||= $self->jwt_algo;
646 if( $opts->{encrypt} )
647 {
648 $opts->{algo} ||= 'PBES2-HS256+A128KW';
649 }
650 else
651 {
652 $opts->{algo} ||= 'HS256';
653 }
654 $opts->{encoding} ||= $self->jwt_encoding || 'A128GCM';
655 return( $self->error( "No payload was provided." ) ) if( !$opts->{payload} );
656 return( $self->error( "Payload submitted is not an hash reference." ) ) if( ref( $opts->{payload} ) ne 'HASH' );
657 my $payload = $opts->{payload};
658 $payload->{iss} = $opts->{issuer} if( length( $opts->{issuer} ) );
659 $payload->{aud} = $opts->{audience} if( length( $opts->{audience} ) );
660 $payload->{azd} = $opts->{audience} if( length( $opts->{audience} ) );
661 $payload->{iat} = $opts->{issued_at} if( length( $opts->{issued_at} ) );
662 $payload->{sub} = $opts->{subject} if( length( $opts->{subject} ) );
663 if( length( $opts->{expires} ) )
664 {
665 $payload->{exp} = $opts->{expires};
666 }
667 elsif( length( $opts->{ttl} ) )
668 {
669 return( $self->error( "Property \"ttl\" provided is not an integer." ) ) if( $opts->{ttl} !~ /^\d+$/ );
670 $payload->{exp} = $opts->{iat} + $opts->{ttl};
671 }
672 my $token;
673 my %params =
674 (
675 payload => $payload,
676 ## do NOT allow the "none" algorithm, as this is massively insecure
677 allow_none => 0,
678 alg => $opts->{algo},
679 key => ( $opts->{key} || $self->key ),
680 enc => $opts->{encoding},
681 );
682 my @possible_additional_parameters = qw(
683 allow_none
684 auto_iat
685 extra_headers
686 keypass
687 relative_exp
688 relative_nbf
689 serialization
690 shared_unprotected_headers
691 unprotected_headers
692 zip
693 );
694 for( @possible_additional_parameters )
695 {
696 $params{ $_ } = $opts->{ $_ } if( CORE::exists( $opts->{ $_ } ) && CORE::length( $opts->{ $_ } ) );
697 }
698  
699 # try-catch
700 local $@;
701 eval
702 {
703 ## $token = Crypt::JWT::encode_jwt(
704 $token = Net::API::REST::JWT::encode_jwt( %params );
705 };
706 if( $@ )
707 {
708 return( $self->error( "Error in the arguments or payload when creating a Jason Web Token: $@" ) );
709 }
710 return( $token );
711 }
712  
713 sub jwt_encoding { return( shift->_set_get_scalar( 'jwt_encoding', @_ ) ); }
714  
715 sub jwt_encrypt { return( shift->_set_get_scalar( 'jwt_encrypt', @_ ) ); }
716  
717 # We extract the jwt data, and do not verify it, which is very unsecure of course
718 # Best to use jwt_verify()
719 sub jwt_extract
720 {
721 my $self = shift( @_ );
722 my $token = shift( @_ ) || return( $self->error( "No json web token was provided to extract its data." ) );
723 return( $self->error( "Token provided ($token) seems malformed. I was expecting 3 chunks of base64 data separated by dots" ) ) if( $token !~ /^([^\.]+)\.([^\.]+)\.([^\.]+)$/ );
724 my( $header, $claim, $crypto ) = split( /\./, $token, 3 );
725 my $hash = {};
726 # try-catch
727 local $@;
728 eval
729 {
730 $hash->{raw_header} = MIME::Base64::decode_base64( $header );
731 $hash->{raw_claim} = MIME::Base64::decode_base64( $claim );
732 my $j = JSON->new->allow_nonref;
733 $hash->{header} = $j->utf8->decode( $hash->{raw_header} );
734 $hash->{claim} = $j->utf8->decode( $hash->{raw_claim} );
735 };
736 if( $@ )
737 {
738 return( $self->error( "An error occured while attempting to extract token data: $@" ) );
739 }
740 return( $hash );
741 }
742  
743 sub jwt_verify
744 {
745 my $self = shift( @_ );
746 my $token;
747 my $opts = {};
748 if( @_ )
749 {
750 if( ref( $_[0] ) eq 'HASH' )
751 {
752 $opts = shift( @_ );
753 }
754 elsif( scalar( @_ ) >= 2 && !( @_ % 2 ) )
755 {
756 $opts = { @_ };
757 }
758 else
759 {
760 $token = shift( @_ );
761 }
762 }
763 $token ||= $opts->{token} || return( $self->error( "No json web token was provided to extract its data." ) );
764 my $hash = $self->jwt_extract( $token ) || return( undef() );
765 # Something like this:
766 # Downloaded from https://accounts.google.com/.well-known/openid-configuration
767 # and then from https://www.googleapis.com/oauth2/v3/certs
768 # {
769 # "keys": [
770 # {
771 # "kid": "2bf8418b2963f366f5fefdd127b2cee07c887e65",
772 # "e": "AQAB",
773 # "kty": "RSA",
774 # "alg": "RS256",
775 # "n": "uA8MNzSvgJTB_eHWj_HnpGzgtfBzsO4PjdNkEvdETRHEvyqIyqQnACRUNQ9KACnPV3R1M_1VlkJGRJ-xI3By3uylEOh4VagVRlCjLbsmuXburlOLn3TZSkwR7XE3pvVqcypq4nLPdu6foV__wcrLkZPMJzq654vepbOIegx5iVIvV2ilfdqs7VTwHRAUQU6nYfa8jaUwj1H_-zlaaHK-vxm-lWdGjAyiv-xBj5UmY24WtkTuX-MWLvOgbrqcYzMpzEm-LCdBbZR4qjQbWEatRISp4QW31xBZxF2FwMK2YWXDUW_GhXy0hgbsSyX-6jziTDSsulk9SNstSXmYCTZtvw",
776 # "use": "sig"
777 # },
778 # {
779 # "use": "sig",
780 # "kid": "0b0bf186743471a1edcac3060d1256f9e4050ba8",
781 # "e": "AQAB",
782 # "kty": "RSA",
783 # "alg": "RS256",
784 # "n": "0s9r8J5G5I77VpYWS-ttQ8GBDZBlxN_TZHl4DJHAi1WzvxQcP0hBPdASNqAnAuXA-ZxMpMtW_ovjhwo1Ncqpofd3c0H5mSzA9nsmmiex3AO7ZbkaGIdOcMYr4ttOFKZJn2giZWsfQuTlMEvcGyghViyy6l7t1-dMyxjbNOAVLVn25PHfWLbtffv-5EXFXt0Bp0wf0JjPghy4xXf3GjqqqaG_pOnmY_g2c6s8NwZG8dLymiqq0sta3URCUzDYnEHfx7Ol-grOYBOg6YjQP-gl0r5_uvB9Vl9jXKz-WcUUqVTuLp6S-CBstsOheUpSjX3vVP48KJIS4DX6NFHgjn8ooQ"
785 # }
786 # ]
787 # }
788 if( $opts->{rsa_keys} )
789 {
790 return( $self->error( "RSA keys provided with parameter \"rsa_keys\" is not an hash reference." ) ) if( ref( $opts->{rsa_keys} ) ne 'HASH' );
791 my $keys = $opts->{rsa_keys};
792 return( $self->error( "No \"keys\" property found in the rsa keys provided." ) ) if( !$keys->{keys} );
793 return( $self->error( "Property \"keys\" in rsa eys provided is not an array reference (of rsa keys)." ) ) if( !$self->_is_array( $keys->{keys} ) );
794 # Check all is in order before going further
795 my( $e, $n );
796 $n = 0;
797 foreach my $ref ( @{$keys->{keys}} )
798 {
799 $n++;
800 foreach my $p ( qw( kid e kty alg n ) )
801 {
802 return( $self->error( "No property \"$p\" could be found in this rsa key No $n. Hash is: ", sub{ $self->dump( $ref ) } ) ) if( !$ref->{ $p } );
803 }
804 }
805 # Make sure our header has alg set to rsa and there is a kid property, or else Crypt::JWT will die
806 # So at least, we can catch this issue and return an error gracefully...
807 # {"alg":"RS256","kid":"0b0bf186743471a1edcac3060d1256f9e4050ba8","typ":"JWT"}
808 my $header = $hash->{header} || return( $self->error( "Unable to get the header from the jwt token '$token'." ) );
809 return( $self->error( "JWT token header returned by jwt_extract is empty! Original token is: '$token'" ) ) if( !scalar( keys( %$header ) ) );
810 return( $self->error( "JWT token header found has no \"alg\" property set. Original token is: '$token'" ) ) if( !$header->{alg} );
811 return( $self->error( "JWT token header found has no \"kid\" property set. Original token is: '$token'" ) ) if( !$header->{kid} );
812 # https://metacpan.org/pod/Crypt::JWT#key
813 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 );
814 my $kid = $header->{kid};
815 # Check if kid value is in the rsa keys provided.
816 foreach my $ref ( @{$keys->{keys}} )
817 {
818 if( $ref->{kid} eq $kid )
819 {
820 $e = $ref->{e};
821 $n = $ref->{n};
822 last;
823 }
824 }
825 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 ) );
826 # Ok, we are very reasonably safe to call Crypt::JWT now
827 my $data;
828 # try-catch
829 local $@;
830 eval
831 {
832 # $data = Crypt::JWT::decode_jwt( token => $token );
833 # $data = Crypt::JWT::decode_jwt(
834 $data = Net::API::REST::JWT::decode_jwt(
835 token => $token,
836 kid_keys => $keys,
837 decode_payload => 1,
838 verify_exp => 0,
839 debug => 3,
840 );
841 };
842 if( $@ )
843 {
844 return( $self->error( "Faile validating jwt token '$token'. Reason is: $@" ) );
845 }
846 # Ok, we're good
847 }
848 return( $hash );
849 }
850  
851 sub jwt_verify_audience { return( shift->_set_get_object( 'jwt_verify_audience', 'Regexp', @_ ) ); }
852  
853 sub key { return( shift->_set_get_scalar( 'key', @_ ) ); }
854  
855 # The objects for request or response should be instantiated in handler()
856 sub request { return( shift->_set_get_object_without_init( 'request', 'Net::API::REST::Request', @_ ) ); }
857  
858 sub response { return( shift->_set_get_object_without_init( 'response', 'Net::API::REST::Response', @_ ) ); }
859  
860 sub route
861 {
862 my $self = shift( @_ );
863 # my $parts = shift( @_ ) || return( $self->error( "No path parts as array reference was provided." ) );
864 #return( $self->error( "Path parts provided ($parts) is not an array reference." ) ) if( ref( $parts ) ne 'ARRAY' );
865 my $uri = shift( @_ ) || return( $self->error({
866 code => 400,
867 message => "No uri was provided to find the appropriate route."
868 }) );
869 return( $self->error({ code => 500, message => "URI provided \"$uri\" is not an object." }) ) if( !Scalar::Util::blessed( $uri ) );
870 return( $self->error({ code => 500, message => "URI object provided \"$uri\" is not an URI object." }) ) if( !$uri->isa( 'URI' ) );
871 my $path = $uri->path;
872 if( my $base = $self->base_path )
873 {
874 $path =~ s/^\Q$base\E//;
875 }
876 my @points = split( /\/+/ , $path );
877 # Clean up empty path
878 my $parts = [ grep{ length( $_ ) > 0 } @points ];
879 my $client_api_version = '';
880 if( ( $parts->[0] // '' ) =~ /^v?(\d+(?:\.\d+)*)$/ )
881 {
882 $client_api_version = $1;
883 shift( @$parts );
884 }
885 $client_api_version ||= $self->request->client_api_version || $self->api_version;
886 my $routes = $self->routes;
887 if( !scalar( keys( %$routes ) ) )
888 {
889 return( $self->error({ code => 500, message => "No routes set up to find the appropriate resource." }) );
890 }
891 elsif( !CORE::exists( $routes->{ $client_api_version } ) )
892 {
893 return( $self->error({ code => Apache2::Const::HTTP_NOT_ACCEPTABLE, message => "API version requested ($client_api_version) is not supported." }) );
894 }
895 my $req = $self->request;
896 my $resp = $self->response;
897 # Path variables like "/some/path/1234/more/thing/jack" where 1234 and jack are variables
898 # 2019-11-13: This is set by the caller of route()
899 # my $vars = $req->variables;
900 my $vars = {};
901 my $def_methods = $self->default_methods;
902 my $http_meth = lc( $req->method // '' );
903 # 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
904 my $access = 'public';
905 my $params;
906 my $check;
907 $check = sub
908 {
909 my( $pos, $subroutes ) = @_;
910 my $part = $parts->[ $pos ];
911 # reserved words cannot be used in path
912 return( '' ) if( $part =~ /^_(access_control|allowed_methods|handler|name|var|delete|get|head|patch|post|put)$/i );
913 if( exists( $subroutes->{ lc( $part ) } ) )
914 {
915 $part = lc( $part );
916 # Code reference
917 if( ref( $subroutes->{ $part } ) eq 'CODE' )
918 {
919 # Do we have still more path?
920 # If we do, we store it as variable _path_info and let the handler deal with it
921 # $vars->{_path_info} = [ splice( @$parts, $pos + 1 ) ] if( $#$parts > $pos );
922 # return( $subroutes->{ $part } );
923 my $ep = Net::API::REST::Endpoint->new(
924 handler => $subroutes->{ $part },
925 methods => $def_methods,
926 variables => $vars,
927 access => $access,
928 path => $uri,
929 ( defined( $params ) ? ( params => $params ) : () ),
930 debug => $self->debug,
931 );
932 $ep->path_info( [ splice( @$parts, $pos + 1 ) ] ) if( $#$parts > $pos );
933 return( $ep );
934 }
935 # path part has sub component, so we look for a key _handler in the sub hash
936 elsif( ref( $subroutes->{ $part } ) eq 'HASH' )
937 {
938 my $ref = $subroutes->{ $part };
939 if( !exists( $ref->{_handler} ) &&
940 !exists( $ref->{_delete} ) &&
941 !exists( $ref->{_get} ) &&
942 !exists( $ref->{_head} ) &&
943 !exists( $ref->{_patch} ) &&
944 !exists( $ref->{_post} ) &&
945 !exists( $ref->{_put} ) )
946 {
947 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\", \"_patch\", \"_post\", or \"_put\" inside it." }) );
948 }
949 my $methods = {};
950 foreach my $h ( qw( _delete _get _head _patch _post _put ) )
951 {
952 if( exists( $ref->{ $h } ) )
953 {
954 $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h };
955 }
956 }
957  
958 my $supported_methods = [sort( keys( %$methods ) )];
959 # If this is just a pre-flight check, at this stage the handler does not matter
960 my $handler = $http_meth eq 'options'
961 ? sub{}
962 : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler};
963  
964 # We reached the end, return the handler
965 # return( $ref->{_handler} ) if( $pos == $#$parts );
966 # return( $check->( $pos + 1, $ref ) );
967 $access = $ref->{_access_control} if( $ref->{_access_control} );
968 $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' );
969  
970 if( $pos == $#$parts )
971 {
972 if( ref( $handler ) eq 'CODE' )
973 {
974 my $ep = Net::API::REST::Endpoint->new(
975 handler => $handler,
976 methods => exists( $methods->{ uc( $http_meth ) } )
977 ? [uc( $http_meth )]
978 : ( scalar( @$supported_methods )
979 ? $supported_methods
980 : $ref->{_allowed_methods}
981 ? $ref->{_allowed_methods}
982 : $def_methods ),
983 variables => $vars,
984 access => $access,
985 path => $uri,
986 ( defined( $params ) ? ( params => $params ) : () ),
987 debug => $self->debug,
988 );
989 return( $ep );
990 }
991 elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ )
992 {
993 my( $cl, $meth ) = ( $1, $2 );
994 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
995 # require $cl unless( defined( *{"${cl}::"} ) );
996 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
997 # 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
998 my $code = $cl->can( $meth );
999 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
1000 # return( sub{ $code->( $o, api => $self, @_ ) } );
1001 # try-catch
1002 local $@;
1003 my $ep = eval
1004 {
1005 Net::API::REST::Endpoint->new(
1006 handler => sub
1007 {
1008 my $o = $cl->new(
1009 apache_request => $self->apache_request,
1010 debug => $self->debug,
1011 request => $req,
1012 response => $resp,
1013 # Pass the api object here as well
1014 api => $self,
1015 );
1016 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1017 $code->( $o, api => $self, @_ );
1018 },
1019 methods => exists( $methods->{ uc( $http_meth ) } )
1020 ? [uc( $http_meth )]
1021 : ( scalar( @$supported_methods )
1022 ? $supported_methods
1023 : $ref->{_allowed_methods}
1024 ? $ref->{_allowed_methods}
1025 : $def_methods ),
1026 variables => $vars,
1027 access => $access,
1028 path => $uri,
1029 ( defined( $params ) ? ( params => $params ) : () ),
1030 debug => $self->debug,
1031 );
1032 };
1033 if( $@ )
1034 {
1035 return( $self->error({ code => 500, message => $@ }) );
1036 }
1037 return( $ep );
1038 }
1039 else
1040 {
1041 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." }) );
1042 }
1043 }
1044 return( $check->( $pos + 1, $ref ) );
1045 }
1046 # Not a code or a hash reference, so it has got to be a package name
1047 elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ )
1048 {
1049 my( $cl, $meth ) = ( $1, $2 );
1050 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
1051 # require $cl unless( defined( *{"${cl}::"} ) );
1052 # my $rc = eval{ $self->_load_class( $cl ); };
1053 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1054 # 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.
1055 # As it turns out $cl->can( $meth ) works just as well.
1056 # my $o = $cl->new(
1057 # apache_request => $self->apache_request,
1058 # debug => $self->debug,
1059 # request => $req,
1060 # response => $resp,
1061 # # Pass the api object here as well
1062 # api => $self,
1063 # ) || return( $self->pass_error( $cl->error ) );
1064 # my $code = $o->can( $meth );
1065 my $code = $cl->can( $meth );
1066 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
1067 # return( sub{ $code->( $o, api => $self, @_ ) } );
1068 # try-catch
1069 local $@;
1070 my $ep = eval
1071 {
1072 Net::API::REST::Endpoint->new(
1073 handler => sub
1074 {
1075 my $o = $cl->new(
1076 apache_request => $self->apache_request,
1077 debug => $self->debug,
1078 request => $req,
1079 response => $resp,
1080 # Pass the api object here as well
1081 api => $self,
1082 );
1083 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1084 $code->( $o, api => $self, @_ );
1085 },
1086 methods => $def_methods,
1087 variables => $vars,
1088 access => $access,
1089 path => $uri,
1090 ( defined( $params ) ? ( params => $params ) : () ),
1091 debug => $self->debug,
1092 );
1093 };
1094 if( $@ )
1095 {
1096 return( $self->error({ code => 500, message => $@ }) );
1097 }
1098 return( $ep );
1099 }
1100 else
1101 {
1102 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" }) );
1103 }
1104 }
1105 elsif( exists( $subroutes->{_var} ) )
1106 {
1107 my $ref = $subroutes->{_var};
1108 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' );
1109 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} ) );
1110 if( !exists( $ref->{_handler} ) &&
1111 !exists( $ref->{_delete} ) &&
1112 !exists( $ref->{_get} ) &&
1113 !exists( $ref->{_head} ) &&
1114 !exists( $ref->{_patch} ) &&
1115 !exists( $ref->{_post} ) &&
1116 !exists( $ref->{_put} ) )
1117 {
1118 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." }) );
1119 }
1120  
1121 my $methods = {};
1122 foreach my $h ( qw( _delete _get _head _patch _post _put ) )
1123 {
1124 if( exists( $ref->{ $h } ) )
1125 {
1126 $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h };
1127 }
1128 }
1129  
1130 my $supported_methods = [sort( keys( %$methods ) )];
1131 # If this is just a pre-flight check, at this stage the handler does not matter
1132 my $handler = $http_meth eq 'options'
1133 ? sub{}
1134 : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler};
1135  
1136 my $var_name = $ref->{_name};
1137 $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' );
1138 # For variable type to be array
1139 if( exists( $ref->{_type} ) )
1140 {
1141 if( lc( $ref->{_type} ) eq 'array' || $ref->{_type} eq '[]' )
1142 {
1143 if( exists( $vars->{ $var_name } ) )
1144 {
1145 my $prev = $vars->{ $var_name };
1146 $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' );
1147 }
1148 else
1149 {
1150 $vars->{ $var_name } = [];
1151 }
1152 }
1153 }
1154 # Store variable value
1155 if( exists( $vars->{ $var_name } ) )
1156 {
1157 my $prev = $vars->{ $var_name };
1158 $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' );
1159 push( @{$vars->{ $var_name }}, $part );
1160 }
1161 else
1162 {
1163 $vars->{ $var_name } = $part;
1164 }
1165  
1166 # We reached the end, return the handler
1167 if( $pos == $#$parts )
1168 {
1169 $access = $ref->{_access_control} if( $ref->{_access_control} );
1170 if( ref( $handler ) eq 'CODE' )
1171 {
1172 # return( $ref->{_handler} );
1173 my $ep = Net::API::REST::Endpoint->new(
1174 handler => $handler,
1175 methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ),
1176 variables => $vars,
1177 access => $access,
1178 path => $uri,
1179 ( defined( $params ) ? ( params => $params ) : () ),
1180 debug => $self->debug,
1181 );
1182 $ep->access( $ref->{_access_control} ) if( $ref->{_access_control} );
1183 return( $ep );
1184 }
1185 elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ )
1186 {
1187 my( $cl, $meth ) = ( $1, $2 );
1188 # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860
1189 # require $cl unless( defined( *{"${cl}::"} ) );
1190 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1191 # 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
1192 # my $o = $cl->new(
1193 # apache_request => $self->apache_request,
1194 # debug => $self->debug,
1195 # request => $req,
1196 # response => $resp,
1197 # # Pass the api object here as well
1198 # api => $self,
1199 # ) || return( $self->pass_error( $cl->error ) );
1200 # my $code = $o->can( $meth );
1201 my $code = $cl->can( $meth );
1202 return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code );
1203 # return( sub{ $code->( $o, api => $self, @_ ) } );
1204 # try-catch
1205 local $@;
1206 my $ep = eval
1207 {
1208 Net::API::REST::Endpoint->new(
1209 handler => sub
1210 {
1211 my $o = $cl->new(
1212 apache_request => $self->apache_request,
1213 debug => $self->debug,
1214 request => $req,
1215 response => $resp,
1216 # Pass the api object here as well
1217 api => $self,
1218 );
1219 return( $self->pass_error( $cl->error ) ) if( !defined( $o ) );
1220 $code->( $o, api => $self, @_ );
1221 },
1222 methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ),
1223 variables => $vars,
1224 access => $access,
1225 path => $uri,
1226 ( defined( $params ) ? ( params => $params ) : () ),
1227 debug => $self->debug,
1228 );
1229 };
1230 if( $@ )
1231 {
1232 return( $self->error({ code => 500, message => $@ }) );
1233 }
1234 return( $ep );
1235 }
1236 else
1237 {
1238 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" }) );
1239 }
1240 }
1241 return( $check->( $pos + 1, $ref ) );
1242 }
1243 # Empty means not found
1244 else
1245 {
1246 return( '' );
1247 }
1248 };
1249 # We return empty, not undef if nothing was found
1250 my $ep = $check->( 0, $routes->{ $client_api_version } );
1251 # An error occurred
1252 if( !defined( $ep ) )
1253 {
1254 return;
1255 }
1256 # Nothing found
1257 elsif( !length( $ep ) )
1258 {
1259 return( '' );
1260 }
1261 else
1262 {
1263 return( $ep );
1264 }
1265 }
1266  
1267 sub routes
1268 {
1269 my $self = shift( @_ );
1270 if( @_ )
1271 {
1272 my $hash = shift( @_ ) || return( $self->error({ code => 500, message => "No route hash reference was provided." }) );
1273 return( $self->error({ code => 500, message => "Routes provided ($hash) is not a hash reference." }) ) if( ref( $hash ) ne 'HASH' );
1274 my $req = $self->request;
1275 my $resp = $self->response;
1276 # Walk through the hash to check everything is ok
1277 # Returns nothing if all is ok, or self returns an error description
1278 my $check;
1279 $check = sub
1280 {
1281 my $this = shift( @_ );
1282 foreach my $k ( sort( keys( %$this ) ) )
1283 {
1284 my $v = $this->{ $k };
1285 if( $k eq '_params' )
1286 {
1287 return( "Value provided for _params is not an hash reference." ) if( ref( $v ) ne 'HASH' );
1288 }
1289 elsif( ref( $v ) eq 'HASH' )
1290 {
1291 if( !CORE::exists( $v->{_handler} ) &&
1292 !CORE::exists( $v->{_delete} ) &&
1293 !CORE::exists( $v->{_get} ) &&
1294 !CORE::exists( $v->{_head} ) &&
1295 !CORE::exists( $v->{_post} ) &&
1296 !CORE::exists( $v->{_put} ) )
1297 {
1298 return( "The keyword '_handlers' used is mispelled. It should be '_handler'" ) if( CORE::exists( $this->{_handlers} ) );
1299 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." );
1300 }
1301 if( my $err = $check->( $v ) )
1302 {
1303 return( $err );
1304 }
1305 }
1306 elsif( $k eq '_name' )
1307 {
1308 return( "Value provided for _name is empty." ) if( !length( $v ) );
1309 return( "Value provided for _name is a reference, but I was expecting a scalar." ) if( ref( $v ) );
1310 }
1311 elsif( ref( $v ) eq 'CODE' )
1312 {
1313 # We're ok
1314 }
1315 elsif( $v =~ /^([^\:]+)\:{2}[^\:]+/ )
1316 {
1317 # my $cl = $subroutes->{ $part };
1318 my $cl = $v;
1319 my $meth;
1320 if( $cl =~ /^([^\-]+)\-\>(\S+)$/ )
1321 {
1322 ( $cl, $meth ) = ( $1, $2 );
1323 }
1324 # require $cl unless( defined( *{"${cl}::"} ) );
1325 $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) );
1326 # 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 :)
1327 #my $o = $cl->new(
1328 # apache_request => $self->apache_request,
1329 # debug => $self->debug,
1330 # request => $req,
1331 # response => $resp,
1332 # # Pass the api object here as well
1333 # api => $self,
1334 # checkonly => 1
1335 #) || return( $self->pass_error( $cl->error ) );
1336 if( !defined( $meth ) )
1337 {
1338 return( "Class \"$cl\" does not have a method \"$meth\"." ) if( !$cl->can( $meth ) );
1339 }
1340 }
1341 elsif( $k eq '_allowed_method' )
1342 {
1343 return( "The keyword '_allowed_method' used is mispelled. It should be '_allowed_methods'" ) if( !CORE::exists( $this->{_allowed_methods} ) );
1344 }
1345 elsif( $k eq '_access_controls' )
1346 {
1347 return( "The keyword '_access_controls' used is mispelled. It should be '_access_control'" ) if( !CORE::exists( $this->{_access_control} ) );
1348 }
1349 elsif( $k =~ /^_(allowed_methods|access_control)$/ )
1350 {
1351 # Ok
1352 }
1353 # If it is neither a code reference nor a package name, we raise an error
1354 else
1355 {
1356 return( "I was expecting a code reference or a package name, but instead got '$v' for key $k" );
1357 }
1358 }
1359 };
1360 # first level of keys are api version numbers, such as 1, 1.2, 2, etc...
1361 # and for each api version there is a set of route
1362 my @api_versions = keys( %$hash );
1363 foreach my $vers ( @api_versions )
1364 {
1365 if( $vers !~ /^\d+(?:\.\d+)*$/ )
1366 {
1367 return( $self->error( "API version number '$vers' is not a valid version number. Valid values are 1, 1.2, 1.5.3 for example." ) );
1368 }
1369 elsif( ref( $hash->{ $vers } ) ne 'HASH' )
1370 {
1371 return( $self->error( "API version number '$vers' value is not an hash reference. Its value must be a route to resources as hash reference." ) );
1372 }
1373 }
1374  
1375 foreach my $version ( sort( @api_versions ) )
1376 {
1377 if( my $err = $check->( $hash->{ $version } ) )
1378 {
1379 return( $self->error({ code => 500, message => $err }) );
1380 }
1381 }
1382 $self->{routes} = $hash;
1383 }
1384 return( $self->{routes} );
1385 }
1386  
1387 sub supported_api_versions
1388 {
1389 my $self = shift( @_ );
1390 if( @_ )
1391 {
1392 my $v = ref( $_[0] ) ? shift( @_ ) : \@_;
1393 my $vers = [];
1394 foreach my $this ( @$v )
1395 {
1396 push( @$vers, version->parse( $this ) );
1397 }
1398 $self->{supported_api_versions} = $vers;
1399 }
1400 return( $self->{supported_api_versions} );
1401 }
1402  
1403 sub supported_content_types { return( shift->_set_get_array( 'supported_content_types', @_ ) ); }
1404  
1405 sub supported_languages { return( shift->_set_get_array( 'supported_languages', @_ ) ); }
1406  
1407 sub supported_methods { return( shift->_set_get_array( 'supported_methods', @_ ) ); }
1408  
1409 sub well_known
1410 {
1411 my $self = shift( @_ );
1412 return( Apache2::Const::DECLINED );
1413 }
1414  
1415 sub _try
1416 {
1417 my $self = shift( @_ );
1418 my $pack = shift( @_ ) || return( $self->error( "No Apache package name was provided to call method" ) );
1419 my $meth = shift( @_ ) || return( $self->error( "No method name was provided to try!" ) );
1420 my $r = Apache2::RequestUtil->request;
1421 # $r->log_error( "Net::API::REST::_try to call method \"$meth\" in package \"$pack\"." );
1422 # try-catch
1423 local $@;
1424 my $rv = eval
1425 {
1426 return( $self->$pack->$meth ) if( !scalar( @_ ) );
1427 return( $self->$pack->$meth( @_ ) );
1428 };
1429 if( $@ )
1430 {
1431 return( $self->error( "An error occurred while trying to call Apache ", ucfirst( $pack ), " method \"$meth\": $@" ) );
1432 }
1433 return( $rv );
1434 }
1435  
1436 # NOTE: Net::API::REST::Endpoint package
1437 package Net::API::REST::Endpoint;
1438 BEGIN
1439 {
1440 use strict;
1441 use warnings;
1442 use parent qw( Module::Generic );
1443 };
1444  
1445 sub init
1446 {
1447 my $self = shift( @_ );
1448 # ACL
1449 $self->{access} = 'public';
1450 $self->{handler} = '';
1451 $self->{methods} = [];
1452 $self->{params} = {};
1453 $self->{path} = '';
1454 $self->{path_info} = [];
1455 $self->{variables} = {};
1456 $self->{_init_strict_use_sub} = 1;
1457 $self->SUPER::init( @_ );
1458 return( $self );
1459 }
1460  
1461 sub access { return( shift->_set_get_scalar( 'access', @_ ) ); }
1462  
1463 sub handler { return( shift->_set_get_code( 'handler', @_ ) ); }
1464  
1465 sub is_method_allowed
1466 {
1467 my $self = shift( @_ );
1468 my $meth = shift( @_ );
1469 my $ok_methods = $self->methods;
1470 return( scalar( grep( /^$meth$/i, @$ok_methods ) ) );
1471 }
1472  
1473 sub methods { return( shift->_set_get_array_as_object( 'methods', @_ ) ); }
1474  
1475 sub params { return( shift->_set_get_hash_as_mix_object( 'params', @_ ) ); }
1476  
1477 sub path { return( shift->_set_get_uri( 'path', @_ ) ); }
1478  
1479 sub path_info { return( shift->_set_get_array_as_object( 'path_info', @_ ) ); }
1480  
1481 # sub variables { return( shift->_set_get_hash_as_object( 'variables', 'Net::API::REST::Endpoint::Variables', @_ ) ); }
1482 sub variables { return( shift->_set_get_hash_as_mix_object( 'variables', @_ ) ); }
1483  
1484 # NOTE: Net::API::REST::RC package
1485 package Net::API::REST::RC;
1486 BEGIN
1487 {
1488 use strict;
1489 use warnings;
1490 use parent qw( Module::Generic );
1491 use overload (
1492 '""' => 'as_string',
1493 );
1494 };
1495  
1496 sub init
1497 {
1498 my $self = shift( @_ );
1499 $self->{code} = undef();
1500 $self->{message} = undef();
1501 $self->{_init_strict_use_sub} = 1;
1502 $self->SUPER::init( @_ );
1503 return( $self );
1504 }
1505  
1506 sub as_string { return( shift->{code} ); }
1507  
1508 sub code { return( shift->_set_get_number( 'code', @_ ) ); }
1509  
1510 sub message { return( shift->_set_get_scalar_as_object( 'message', @_ ) ); }
1511  
1512 sub TO_JSON { return( shift->{code} ); }
1513  
1514 1;
1515 # NOTE: pod
1516 __END__
« REST/JWT.pm ↑ Summary REST/Cookie.pm »