| 1 | # -*- perl -*- | ||
| 2 | ##---------------------------------------------------------------------------- | ||
| 3 | ## REST API Framework - ~/lib/m | ||
| 4 | ## Version v1.2.6 | ||
| 5 | ## Copyright(c) 2026 DEGUEST Pte. Ltd. | ||
| 6 | ## Author: Jacques Deguest <jack@deguest.jp> | ||
| 7 | ## Created 2019/09/01 | ||
| 8 | ## Modified 2026/08/05 | ||
| 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 | 0 | ▶ | 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.6'; | ||
| 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 PATCH 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 | my $ex = $self->error; | ||
| 368 | if( $ex ) | ||
| 369 | { | ||
| 370 | # Apache2::API->reply that we inherit from recognises exception, and will extract code, message, locale from it. | ||
| 371 | return( $self->reply( $ex ) ); | ||
| 372 | } | ||
| 373 | else | ||
| 374 | { | ||
| 375 | # Net::API::REST::reply will automatically set a json with an error message based on the user language | ||
| 376 | # It is ok to set a reply ourself here, because if it were a normal response, we would not be getting an undef value | ||
| 377 | return( $self->reply({ code => Apache2::Const::HTTP_INTERNAL_SERVER_ERROR }) ); | ||
| 378 | # return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR ); | ||
| 379 | } | ||
| 380 | } | ||
| 381 | elsif( $rc == Apache2::Const::HTTP_OK ) | ||
| 382 | { | ||
| 383 | return( Apache2::Const::OK ); | ||
| 384 | } | ||
| 385 | else | ||
| 386 | { | ||
| 387 | return( $rc ); | ||
| 388 | } | ||
| 389 | # Stop sending data !! | ||
| 390 | $self->request->socket->close; | ||
| 391 | exit(0); | ||
| 392 | } | ||
| 393 | } | ||
| 394 | |||
| 395 | # Mut be overriden by sub package | ||
| 396 | sub http_cors { return; } | ||
| 397 | |||
| 398 | # https://www.w3.org/TR/cors/#http-access-control-allow-origin | ||
| 399 | sub http_options | ||
| 400 | { | ||
| 401 | my $self = shift( @_ ); | ||
| 402 | my $req = $self->request; | ||
| 403 | my $res = $self->response; | ||
| 404 | my $uri = $req->uri; | ||
| 405 | my $ep = $self->route( $uri ); | ||
| 406 | my $http_meth = $req->method; | ||
| 407 | if( !defined( $ep ) ) | ||
| 408 | { | ||
| 409 | return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR ); | ||
| 410 | } | ||
| 411 | elsif( !CORE::length( $ep ) ) | ||
| 412 | { | ||
| 413 | return( Apache2::Const::HTTP_NOT_FOUND ); | ||
| 414 | } | ||
| 415 | my $tmpl = <<EOT; | ||
| 416 | Endpoint information: | ||
| 417 | Handler .......: %s | ||
| 418 | Access type ...: %s | ||
| 419 | Ok methods ....: %s | ||
| 420 | Path info .....: %s | ||
| 421 | Variables .....: %s | ||
| 422 | EOT | ||
| 423 | $self->noexec->messagef( 3, $tmpl, $ep->handler, $ep->access, join( ', ', @{$ep->methods} ), join( ', ', @{$ep->path_info} ), $self->dumper( $ep->variables->as_hash ) ); | ||
| 424 | |||
| 425 | my $req_methods = [CORE::split( /\,[[:blank:]]*/, ( $req->headers( 'Access-Control-Request-Method' ) || '' ) )]; | ||
| 426 | if( scalar( @$req_methods ) ) | ||
| 427 | { | ||
| 428 | foreach my $m ( @$req_methods ) | ||
| 429 | { | ||
| 430 | if( !$ep->is_method_allowed( $m ) ) | ||
| 431 | { | ||
| 432 | return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED ); | ||
| 433 | } | ||
| 434 | } | ||
| 435 | if( !$ep->methods->is_empty ) | ||
| 436 | { | ||
| 437 | $res->headers( 'Access-Control-Allow-Methods' => $ep->methods->join( ', ' )->scalar ); | ||
| 438 | } | ||
| 439 | else | ||
| 440 | { | ||
| 441 | $res->headers( 'Access-Control-Allow-Methods' => '*' ); | ||
| 442 | } | ||
| 443 | } | ||
| 444 | |||
| 445 | my $origin = $req->headers( 'Origin' ) || $req->headers( 'Access-Control-Request-Origin' ); | ||
| 446 | if( !$origin ) | ||
| 447 | { | ||
| 448 | return( Apache2::Const::HTTP_NO_CONTENT ); | ||
| 449 | } | ||
| 450 | my $allow_origin = $req->headers( 'Access-Control-Allow-Origin' ); | ||
| 451 | # "The string "*" cannot be used for a resource that supports credentials" | ||
| 452 | # https://www.w3.org/TR/cors/#http-access-control-allow-origin | ||
| 453 | if( $allow_origin ) | ||
| 454 | { | ||
| 455 | if( $ep->access eq 'restricted' ) | ||
| 456 | { | ||
| 457 | if( $allow_origin eq '*' ) | ||
| 458 | { | ||
| 459 | $res->headers( 'Access-Control-Allow-Origin' => $origin ); | ||
| 460 | $res->headers( 'Access-Control-Max-Age' => 5 ); | ||
| 461 | } | ||
| 462 | } | ||
| 463 | $res->headers( 'Access-Control-Allow-Credentials' => 'true' ); | ||
| 464 | } | ||
| 465 | else | ||
| 466 | { | ||
| 467 | if( $ep->access eq 'restricted' ) | ||
| 468 | { | ||
| 469 | if( $origin ) | ||
| 470 | { | ||
| 471 | $res->headers( 'Access-Control-Allow-Origin' => $origin ); | ||
| 472 | } | ||
| 473 | else | ||
| 474 | { | ||
| 475 | # Stringify | ||
| 476 | $res->headers( 'Access-Control-Allow-Origin' => $self->api_uri . '' ); | ||
| 477 | } | ||
| 478 | $res->headers( | ||
| 479 | 'Access-Control-Allow-Credentials' => 'true', | ||
| 480 | 'Access-Control-Max-Age' => 5 | ||
| 481 | ); | ||
| 482 | } | ||
| 483 | elsif( $origin ) | ||
| 484 | { | ||
| 485 | $res->headers( | ||
| 486 | 'Access-Control-Allow-Origin' => $origin, | ||
| 487 | 'Access-Control-Allow-Credentials' => 'true', | ||
| 488 | 'Access-Control-Max-Age' => 5 | ||
| 489 | ); | ||
| 490 | } | ||
| 491 | else | ||
| 492 | { | ||
| 493 | $res->headers( 'Access-Control-Allow-Origin' => '*' ); | ||
| 494 | } | ||
| 495 | } | ||
| 496 | my $req_headers = $req->headers( 'Access-Control-Request-Headers' ); | ||
| 497 | if( $req_headers ) | ||
| 498 | { | ||
| 499 | $res->headers( 'Access-Control-Allow-Headers' => $req_headers ); | ||
| 500 | } | ||
| 501 | my $cred_required = $req->headers( 'Credentials' ) // ''; | ||
| 502 | if( lc( $cred_required ) eq 'include' ) | ||
| 503 | { | ||
| 504 | $res->headers( 'Access-Control-Allow-Credentials' => 'true' ); | ||
| 505 | } | ||
| 506 | # Check from the most restrictive allowed methods in the context of the endpoint to the broader one for generally all supported methods | ||
| 507 | my $ok_methods = scalar( @{$ep->methods} ) ? $ep->methods : $self->supported_methods; | ||
| 508 | $res->headers( 'Access-Control-Allow-Methods' => join( ', ', @$ok_methods ) ); | ||
| 509 | |||
| 510 | # $r->headers_out->add( 'Allow' => join( ',', @$ok_methods ) ); | ||
| 511 | # $r->rflush; | ||
| 512 | return( Apache2::Const::HTTP_NO_CONTENT ); | ||
| 513 | } | ||
| 514 | |||
| 515 | # To be overriden by module inheriting our package | ||
| 516 | sub init_headers { return(1); } | ||
| 517 | |||
| 518 | # Set or get handlers for various phases to check if the user is allowed access | ||
| 519 | # Currently available handlers: network and access | ||
| 520 | sub is_allowed | ||
| 521 | { | ||
| 522 | my $self = shift( @_ ); | ||
| 523 | my $all = $self->{is_allowed}; | ||
| 524 | if( @_ ) | ||
| 525 | { | ||
| 526 | return( $self->error( "Wrong number of parameters provided: '", join( "', '", @_ ), "'." ) ) if( scalar( @_ ) > 1 && !( scalar( @_ ) % 2 ) ); | ||
| 527 | if( !( scalar( @_ ) % 2 ) ) | ||
| 528 | { | ||
| 529 | while( my( $key, $code ) = splice( @_, 0, 2 ) ) | ||
| 530 | { | ||
| 531 | if( $code ) | ||
| 532 | { | ||
| 533 | return( $self->error( "I was expecting a code reference for the handler '$key', but instead I got '$code'." ) ) if( ref( $code ) ne 'CODE' ); | ||
| 534 | $all->{ $key } = $code; | ||
| 535 | } | ||
| 536 | } | ||
| 537 | return( $self ); | ||
| 538 | } | ||
| 539 | else | ||
| 540 | { | ||
| 541 | my $key = shift( @_ ); | ||
| 542 | return( '' ) if( !exists( $all->{ $key } ) ); | ||
| 543 | return( $all->{ $key } ); | ||
| 544 | } | ||
| 545 | } | ||
| 546 | } | ||
| 547 | |||
| 548 | sub jwt_accepted_algo { return( shift->_set_get_array( 'jwt_accepted_algo', @_ ) ); } | ||
| 549 | |||
| 550 | sub jwt_accepted_encoding { return( shift->_set_get_array( 'jwt_accepted_encoding', @_ ) ); } | ||
| 551 | |||
| 552 | sub jwt_algo { return( shift->_set_get_scalar( 'jwt_algo', @_ ) ); } | ||
| 553 | |||
| 554 | sub jwt_decode | ||
| 555 | { | ||
| 556 | my $self = shift( @_ ); | ||
| 557 | my $opts = {}; | ||
| 558 | if( ref( $_[0] ) eq 'HASH' ) | ||
| 559 | { | ||
| 560 | $opts = shift( @_ ); | ||
| 561 | } | ||
| 562 | # A simple decode, most likely for public jwt like google, linkedin, etc. | ||
| 563 | elsif( scalar( @_ ) == 1 ) | ||
| 564 | { | ||
| 565 | my $token = shift( @_ ); | ||
| 566 | my $data; | ||
| 567 | # try-catch | ||
| 568 | local $@; | ||
| 569 | eval | ||
| 570 | { | ||
| 571 | # $data = Crypt::JWT::decode_jwt( token => $token ); | ||
| 572 | $data = Net::API::REST::JWT::decode_jwt( token => $token ); | ||
| 573 | }; | ||
| 574 | if( $@ ) | ||
| 575 | { | ||
| 576 | return( $self->error( "There was an error decoding Json Web Token payload: $@" ) ); | ||
| 577 | } | ||
| 578 | return( $data ); | ||
| 579 | } | ||
| 580 | return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} ); | ||
| 581 | return( $self->error( "No token was provided to decode." ) ) if( !$opts->{token} ); | ||
| 582 | $opts->{algo} ||= $self->jwt_algo; | ||
| 583 | $opts->{accepted_algo} ||= $self->jwt_accepted_algo; | ||
| 584 | $opts->{accepted_encoding} ||= $self->jwt_accepted_encoding; | ||
| 585 | $opts->{verify_audience} ||= $self->jwt_verify_audience; | ||
| 586 | my $param = | ||
| 587 | { | ||
| 588 | token => $opts->{token}, | ||
| 589 | key => $opts->{key}, | ||
| 590 | decode_payload => 1, | ||
| 591 | decode_header => 1, | ||
| 592 | # verify_iss => sub{ 1; } | ||
| 593 | 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}$}, | ||
| 594 | }; | ||
| 595 | # PBES2-HS256+A128KW | ||
| 596 | # accepted_alg => qr{^(?:PBES2\-HS256\+A128KW|HS256)$}, | ||
| 597 | if( $opts->{accepted_algo} ) | ||
| 598 | { | ||
| 599 | return( $self->error( "Accepted alorithm option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_algo} ) ); | ||
| 600 | if( scalar( @{$opts->{accepted_algo}} ) ) | ||
| 601 | { | ||
| 602 | my $re = join( '|', @{$opts->{accepted_algo}} ); | ||
| 603 | $param->{accepted_alg} = qr{^(?:\Q$re\E)$}; | ||
| 604 | } | ||
| 605 | } | ||
| 606 | |||
| 607 | # accepted_enc => qr{^(?:A128GCM)$}, | ||
| 608 | if( $opts->{accepted_enc} ) | ||
| 609 | { | ||
| 610 | return( $self->error( "Accepted encoding option must be an array reference." ) ) if( !$self->_is_array( $opts->{accepted_enc} ) ); | ||
| 611 | if( scalar( @{$opts->{accepted_enc}} ) ) | ||
| 612 | { | ||
| 613 | my $re = join( '|', @{$opts->{accepted_enc}} ); | ||
| 614 | $param->{accepted_enc} = qr{^(?:\Q$re\E)$}; | ||
| 615 | } | ||
| 616 | } | ||
| 617 | |||
| 618 | if( ref( $opts->{verify_audience} ) eq 'Regexp' ) | ||
| 619 | { | ||
| 620 | $param->{verify_aud} = $opts->{verify_audience}; | ||
| 621 | } | ||
| 622 | |||
| 623 | my $data; | ||
| 624 | # try-catch | ||
| 625 | local $@; | ||
| 626 | eval | ||
| 627 | { | ||
| 628 | ## $data = Crypt::JWT::decode_jwt( %$param ); | ||
| 629 | $data = Net::API::REST::JWT::decode_jwt( %$param ); | ||
| 630 | }; | ||
| 631 | if( $@ ) | ||
| 632 | { | ||
| 633 | return( $self->error( "There was an error decoding Json Web Token payload: $@" ) ); | ||
| 634 | } | ||
| 635 | return( $data ); | ||
| 636 | } | ||
| 637 | |||
| 638 | sub jwt_encode | ||
| 639 | { | ||
| 640 | my $self = shift( @_ ); | ||
| 641 | my $opts = $self->_get_args_as_hash( @_ ); | ||
| 642 | return( $self->error( "No encryption key was set up in our object or provided." ) ) if( !$self->key && !$opts->{key} ); | ||
| 643 | $opts->{encrypt} ||= $self->jwt_encrypt if( !length( $opts->{encrypt} ) ); | ||
| 644 | $opts->{algo} ||= $self->jwt_algo; | ||
| 645 | if( $opts->{encrypt} ) | ||
| 646 | { | ||
| 647 | $opts->{algo} ||= 'PBES2-HS256+A128KW'; | ||
| 648 | } | ||
| 649 | else | ||
| 650 | { | ||
| 651 | $opts->{algo} ||= 'HS256'; | ||
| 652 | } | ||
| 653 | $opts->{encoding} ||= $self->jwt_encoding || 'A128GCM'; | ||
| 654 | return( $self->error( "No payload was provided." ) ) if( !$opts->{payload} ); | ||
| 655 | return( $self->error( "Payload submitted is not an hash reference." ) ) if( ref( $opts->{payload} ) ne 'HASH' ); | ||
| 656 | my $payload = $opts->{payload}; | ||
| 657 | $payload->{iss} = $opts->{issuer} if( length( $opts->{issuer} ) ); | ||
| 658 | $payload->{aud} = $opts->{audience} if( length( $opts->{audience} ) ); | ||
| 659 | $payload->{azd} = $opts->{audience} if( length( $opts->{audience} ) ); | ||
| 660 | $payload->{iat} = $opts->{issued_at} if( length( $opts->{issued_at} ) ); | ||
| 661 | $payload->{sub} = $opts->{subject} if( length( $opts->{subject} ) ); | ||
| 662 | if( length( $opts->{expires} ) ) | ||
| 663 | { | ||
| 664 | $payload->{exp} = $opts->{expires}; | ||
| 665 | } | ||
| 666 | elsif( length( $opts->{ttl} ) ) | ||
| 667 | { | ||
| 668 | return( $self->error( "Property \"ttl\" provided is not an integer." ) ) if( $opts->{ttl} !~ /^\d+$/ ); | ||
| 669 | $payload->{exp} = $opts->{iat} + $opts->{ttl}; | ||
| 670 | } | ||
| 671 | my $token; | ||
| 672 | my %params = | ||
| 673 | ( | ||
| 674 | payload => $payload, | ||
| 675 | ## do NOT allow the "none" algorithm, as this is massively insecure | ||
| 676 | allow_none => 0, | ||
| 677 | alg => $opts->{algo}, | ||
| 678 | key => ( $opts->{key} || $self->key ), | ||
| 679 | enc => $opts->{encoding}, | ||
| 680 | ); | ||
| 681 | my @possible_additional_parameters = qw( | ||
| 682 | allow_none | ||
| 683 | auto_iat | ||
| 684 | extra_headers | ||
| 685 | keypass | ||
| 686 | relative_exp | ||
| 687 | relative_nbf | ||
| 688 | serialization | ||
| 689 | shared_unprotected_headers | ||
| 690 | unprotected_headers | ||
| 691 | zip | ||
| 692 | ); | ||
| 693 | for( @possible_additional_parameters ) | ||
| 694 | { | ||
| 695 | $params{ $_ } = $opts->{ $_ } if( CORE::exists( $opts->{ $_ } ) && CORE::length( $opts->{ $_ } ) ); | ||
| 696 | } | ||
| 697 | |||
| 698 | # try-catch | ||
| 699 | local $@; | ||
| 700 | eval | ||
| 701 | { | ||
| 702 | ## $token = Crypt::JWT::encode_jwt( | ||
| 703 | $token = Net::API::REST::JWT::encode_jwt( %params ); | ||
| 704 | }; | ||
| 705 | if( $@ ) | ||
| 706 | { | ||
| 707 | return( $self->error( "Error in the arguments or payload when creating a Jason Web Token: $@" ) ); | ||
| 708 | } | ||
| 709 | return( $token ); | ||
| 710 | } | ||
| 711 | |||
| 712 | sub jwt_encoding { return( shift->_set_get_scalar( 'jwt_encoding', @_ ) ); } | ||
| 713 | |||
| 714 | sub jwt_encrypt { return( shift->_set_get_scalar( 'jwt_encrypt', @_ ) ); } | ||
| 715 | |||
| 716 | # We extract the jwt data, and do not verify it, which is very unsecure of course | ||
| 717 | # Best to use jwt_verify() | ||
| 718 | sub jwt_extract | ||
| 719 | { | ||
| 720 | my $self = shift( @_ ); | ||
| 721 | my $token = shift( @_ ) || return( $self->error( "No json web token was provided to extract its data." ) ); | ||
| 722 | return( $self->error( "Token provided ($token) seems malformed. I was expecting 3 chunks of base64 data separated by dots" ) ) if( $token !~ /^([^\.]+)\.([^\.]+)\.([^\.]+)$/ ); | ||
| 723 | my( $header, $claim, $crypto ) = split( /\./, $token, 3 ); | ||
| 724 | my $hash = {}; | ||
| 725 | # try-catch | ||
| 726 | local $@; | ||
| 727 | eval | ||
| 728 | { | ||
| 729 | $hash->{raw_header} = MIME::Base64::decode_base64( $header ); | ||
| 730 | $hash->{raw_claim} = MIME::Base64::decode_base64( $claim ); | ||
| 731 | my $j = JSON->new->allow_nonref; | ||
| 732 | $hash->{header} = $j->utf8->decode( $hash->{raw_header} ); | ||
| 733 | $hash->{claim} = $j->utf8->decode( $hash->{raw_claim} ); | ||
| 734 | }; | ||
| 735 | if( $@ ) | ||
| 736 | { | ||
| 737 | return( $self->error( "An error occured while attempting to extract token data: $@" ) ); | ||
| 738 | } | ||
| 739 | return( $hash ); | ||
| 740 | } | ||
| 741 | |||
| 742 | sub jwt_verify | ||
| 743 | { | ||
| 744 | my $self = shift( @_ ); | ||
| 745 | my $token; | ||
| 746 | my $opts = {}; | ||
| 747 | if( @_ ) | ||
| 748 | { | ||
| 749 | if( ref( $_[0] ) eq 'HASH' ) | ||
| 750 | { | ||
| 751 | $opts = shift( @_ ); | ||
| 752 | } | ||
| 753 | elsif( scalar( @_ ) >= 2 && !( @_ % 2 ) ) | ||
| 754 | { | ||
| 755 | $opts = { @_ }; | ||
| 756 | } | ||
| 757 | else | ||
| 758 | { | ||
| 759 | $token = shift( @_ ); | ||
| 760 | } | ||
| 761 | } | ||
| 762 | $token ||= $opts->{token} || return( $self->error( "No json web token was provided to extract its data." ) ); | ||
| 763 | my $hash = $self->jwt_extract( $token ) || return( undef() ); | ||
| 764 | # Something like this: | ||
| 765 | # Downloaded from https://accounts.google.com/.well-known/openid-configuration | ||
| 766 | # and then from https://www.googleapis.com/oauth2/v3/certs | ||
| 767 | # { | ||
| 768 | # "keys": [ | ||
| 769 | # { | ||
| 770 | # "kid": "2bf8418b2963f366f5fefdd127b2cee07c887e65", | ||
| 771 | # "e": "AQAB", | ||
| 772 | # "kty": "RSA", | ||
| 773 | # "alg": "RS256", | ||
| 774 | # "n": "uA8MNzSvgJTB_eHWj_HnpGzgtfBzsO4PjdNkEvdETRHEvyqIyqQnACRUNQ9KACnPV3R1M_1VlkJGRJ-xI3By3uylEOh4VagVRlCjLbsmuXburlOLn3TZSkwR7XE3pvVqcypq4nLPdu6foV__wcrLkZPMJzq654vepbOIegx5iVIvV2ilfdqs7VTwHRAUQU6nYfa8jaUwj1H_-zlaaHK-vxm-lWdGjAyiv-xBj5UmY24WtkTuX-MWLvOgbrqcYzMpzEm-LCdBbZR4qjQbWEatRISp4QW31xBZxF2FwMK2YWXDUW_GhXy0hgbsSyX-6jziTDSsulk9SNstSXmYCTZtvw", | ||
| 775 | # "use": "sig" | ||
| 776 | # }, | ||
| 777 | # { | ||
| 778 | # "use": "sig", | ||
| 779 | # "kid": "0b0bf186743471a1edcac3060d1256f9e4050ba8", | ||
| 780 | # "e": "AQAB", | ||
| 781 | # "kty": "RSA", | ||
| 782 | # "alg": "RS256", | ||
| 783 | # "n": "0s9r8J5G5I77VpYWS-ttQ8GBDZBlxN_TZHl4DJHAi1WzvxQcP0hBPdASNqAnAuXA-ZxMpMtW_ovjhwo1Ncqpofd3c0H5mSzA9nsmmiex3AO7ZbkaGIdOcMYr4ttOFKZJn2giZWsfQuTlMEvcGyghViyy6l7t1-dMyxjbNOAVLVn25PHfWLbtffv-5EXFXt0Bp0wf0JjPghy4xXf3GjqqqaG_pOnmY_g2c6s8NwZG8dLymiqq0sta3URCUzDYnEHfx7Ol-grOYBOg6YjQP-gl0r5_uvB9Vl9jXKz-WcUUqVTuLp6S-CBstsOheUpSjX3vVP48KJIS4DX6NFHgjn8ooQ" | ||
| 784 | # } | ||
| 785 | # ] | ||
| 786 | # } | ||
| 787 | if( $opts->{rsa_keys} ) | ||
| 788 | { | ||
| 789 | return( $self->error( "RSA keys provided with parameter \"rsa_keys\" is not an hash reference." ) ) if( ref( $opts->{rsa_keys} ) ne 'HASH' ); | ||
| 790 | my $keys = $opts->{rsa_keys}; | ||
| 791 | return( $self->error( "No \"keys\" property found in the rsa keys provided." ) ) if( !$keys->{keys} ); | ||
| 792 | return( $self->error( "Property \"keys\" in rsa eys provided is not an array reference (of rsa keys)." ) ) if( !$self->_is_array( $keys->{keys} ) ); | ||
| 793 | # Check all is in order before going further | ||
| 794 | my( $e, $n ); | ||
| 795 | $n = 0; | ||
| 796 | foreach my $ref ( @{$keys->{keys}} ) | ||
| 797 | { | ||
| 798 | $n++; | ||
| 799 | foreach my $p ( qw( kid e kty alg n ) ) | ||
| 800 | { | ||
| 801 | return( $self->error( "No property \"$p\" could be found in this rsa key No $n. Hash is: ", sub{ $self->dump( $ref ) } ) ) if( !$ref->{ $p } ); | ||
| 802 | } | ||
| 803 | } | ||
| 804 | # Make sure our header has alg set to rsa and there is a kid property, or else Crypt::JWT will die | ||
| 805 | # So at least, we can catch this issue and return an error gracefully... | ||
| 806 | # {"alg":"RS256","kid":"0b0bf186743471a1edcac3060d1256f9e4050ba8","typ":"JWT"} | ||
| 807 | my $header = $hash->{header} || return( $self->error( "Unable to get the header from the jwt token '$token'." ) ); | ||
| 808 | return( $self->error( "JWT token header returned by jwt_extract is empty! Original token is: '$token'" ) ) if( !scalar( keys( %$header ) ) ); | ||
| 809 | return( $self->error( "JWT token header found has no \"alg\" property set. Original token is: '$token'" ) ) if( !$header->{alg} ); | ||
| 810 | return( $self->error( "JWT token header found has no \"kid\" property set. Original token is: '$token'" ) ) if( !$header->{kid} ); | ||
| 811 | # https://metacpan.org/pod/Crypt::JWT#key | ||
| 812 | 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 ); | ||
| 813 | my $kid = $header->{kid}; | ||
| 814 | # Check if kid value is in the rsa keys provided. | ||
| 815 | foreach my $ref ( @{$keys->{keys}} ) | ||
| 816 | { | ||
| 817 | if( $ref->{kid} eq $kid ) | ||
| 818 | { | ||
| 819 | $e = $ref->{e}; | ||
| 820 | $n = $ref->{n}; | ||
| 821 | last; | ||
| 822 | } | ||
| 823 | } | ||
| 824 | 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 ) ); | ||
| 825 | # Ok, we are very reasonably safe to call Crypt::JWT now | ||
| 826 | my $data; | ||
| 827 | # try-catch | ||
| 828 | local $@; | ||
| 829 | eval | ||
| 830 | { | ||
| 831 | # $data = Crypt::JWT::decode_jwt( token => $token ); | ||
| 832 | # $data = Crypt::JWT::decode_jwt( | ||
| 833 | $data = Net::API::REST::JWT::decode_jwt( | ||
| 834 | token => $token, | ||
| 835 | kid_keys => $keys, | ||
| 836 | decode_payload => 1, | ||
| 837 | verify_exp => 0, | ||
| 838 | debug => 3, | ||
| 839 | ); | ||
| 840 | }; | ||
| 841 | if( $@ ) | ||
| 842 | { | ||
| 843 | return( $self->error( "Faile validating jwt token '$token'. Reason is: $@" ) ); | ||
| 844 | } | ||
| 845 | # Ok, we're good | ||
| 846 | } | ||
| 847 | return( $hash ); | ||
| 848 | } | ||
| 849 | |||
| 850 | sub jwt_verify_audience { return( shift->_set_get_object( 'jwt_verify_audience', 'Regexp', @_ ) ); } | ||
| 851 | |||
| 852 | sub key { return( shift->_set_get_scalar( 'key', @_ ) ); } | ||
| 853 | |||
| 854 | # The objects for request or response should be instantiated in handler() | ||
| 855 | sub request { return( shift->_set_get_object_without_init( 'request', 'Net::API::REST::Request', @_ ) ); } | ||
| 856 | |||
| 857 | sub response { return( shift->_set_get_object_without_init( 'response', 'Net::API::REST::Response', @_ ) ); } | ||
| 858 | |||
| 859 | sub route | ||
| 860 | { | ||
| 861 | my $self = shift( @_ ); | ||
| 862 | # my $parts = shift( @_ ) || return( $self->error( "No path parts as array reference was provided." ) ); | ||
| 863 | #return( $self->error( "Path parts provided ($parts) is not an array reference." ) ) if( ref( $parts ) ne 'ARRAY' ); | ||
| 864 | my $uri = shift( @_ ) || return( $self->error({ | ||
| 865 | code => 400, | ||
| 866 | message => "No uri was provided to find the appropriate route." | ||
| 867 | }) ); | ||
| 868 | return( $self->error({ code => 500, message => "URI provided \"$uri\" is not an object." }) ) if( !Scalar::Util::blessed( $uri ) ); | ||
| 869 | return( $self->error({ code => 500, message => "URI object provided \"$uri\" is not an URI object." }) ) if( !$uri->isa( 'URI' ) ); | ||
| 870 | my $path = $uri->path; | ||
| 871 | if( my $base = $self->base_path ) | ||
| 872 | { | ||
| 873 | $path =~ s/^\Q$base\E//; | ||
| 874 | } | ||
| 875 | my @points = split( /\/+/ , $path ); | ||
| 876 | # Clean up empty path | ||
| 877 | my $parts = [ grep{ length( $_ ) > 0 } @points ]; | ||
| 878 | my $client_api_version = ''; | ||
| 879 | if( ( $parts->[0] // '' ) =~ /^v?(\d+(?:\.\d+)*)$/ ) | ||
| 880 | { | ||
| 881 | $client_api_version = $1; | ||
| 882 | shift( @$parts ); | ||
| 883 | } | ||
| 884 | $client_api_version ||= $self->request->client_api_version || $self->api_version; | ||
| 885 | my $routes = $self->routes; | ||
| 886 | if( !scalar( keys( %$routes ) ) ) | ||
| 887 | { | ||
| 888 | return( $self->error({ code => 500, message => "No routes set up to find the appropriate resource." }) ); | ||
| 889 | } | ||
| 890 | elsif( !CORE::exists( $routes->{ $client_api_version } ) ) | ||
| 891 | { | ||
| 892 | return( $self->error({ code => Apache2::Const::HTTP_NOT_ACCEPTABLE, message => "API version requested ($client_api_version) is not supported." }) ); | ||
| 893 | } | ||
| 894 | my $req = $self->request; | ||
| 895 | my $resp = $self->response; | ||
| 896 | # Path variables like "/some/path/1234/more/thing/jack" where 1234 and jack are variables | ||
| 897 | # 2019-11-13: This is set by the caller of route() | ||
| 898 | # my $vars = $req->variables; | ||
| 899 | my $vars = {}; | ||
| 900 | my $def_methods = $self->default_methods; | ||
| 901 | my $http_meth = lc( $req->method // '' ); | ||
| 902 | # 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 | ||
| 903 | my $access = 'public'; | ||
| 904 | my $params; | ||
| 905 | my $check; | ||
| 906 | $check = sub | ||
| 907 | { | ||
| 908 | my( $pos, $subroutes ) = @_; | ||
| 909 | my $part = $parts->[ $pos ]; | ||
| 910 | # reserved words cannot be used in path | ||
| 911 | return( '' ) if( $part =~ /^_(access_control|allowed_methods|handler|name|var|delete|get|head|patch|post|put)$/i ); | ||
| 912 | if( exists( $subroutes->{ lc( $part ) } ) ) | ||
| 913 | { | ||
| 914 | $part = lc( $part ); | ||
| 915 | # Code reference | ||
| 916 | if( ref( $subroutes->{ $part } ) eq 'CODE' ) | ||
| 917 | { | ||
| 918 | # Do we have still more path? | ||
| 919 | # If we do, we store it as variable _path_info and let the handler deal with it | ||
| 920 | # $vars->{_path_info} = [ splice( @$parts, $pos + 1 ) ] if( $#$parts > $pos ); | ||
| 921 | # return( $subroutes->{ $part } ); | ||
| 922 | my $ep = Net::API::REST::Endpoint->new( | ||
| 923 | handler => $subroutes->{ $part }, | ||
| 924 | methods => $def_methods, | ||
| 925 | variables => $vars, | ||
| 926 | access => $access, | ||
| 927 | path => $uri, | ||
| 928 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 929 | debug => $self->debug, | ||
| 930 | ); | ||
| 931 | $ep->path_info( [ splice( @$parts, $pos + 1 ) ] ) if( $#$parts > $pos ); | ||
| 932 | return( $ep ); | ||
| 933 | } | ||
| 934 | # path part has sub component, so we look for a key _handler in the sub hash | ||
| 935 | elsif( ref( $subroutes->{ $part } ) eq 'HASH' ) | ||
| 936 | { | ||
| 937 | my $ref = $subroutes->{ $part }; | ||
| 938 | if( !exists( $ref->{_handler} ) && | ||
| 939 | !exists( $ref->{_delete} ) && | ||
| 940 | !exists( $ref->{_get} ) && | ||
| 941 | !exists( $ref->{_head} ) && | ||
| 942 | !exists( $ref->{_post} ) && | ||
| 943 | !exists( $ref->{_put} ) ) | ||
| 944 | { | ||
| 945 | 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." }) ); | ||
| 946 | } | ||
| 947 | my $methods = {}; | ||
| 948 | foreach my $h ( qw( _delete _get _head _patch _post _put ) ) | ||
| 949 | { | ||
| 950 | if( exists( $ref->{ $h } ) ) | ||
| 951 | { | ||
| 952 | $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h }; | ||
| 953 | } | ||
| 954 | } | ||
| 955 | |||
| 956 | my $supported_methods = [sort( keys( %$methods ) )]; | ||
| 957 | # If this is just a pre-flight check, at this stage the handler does not matter | ||
| 958 | my $handler = $http_meth eq 'options' | ||
| 959 | ? sub{} | ||
| 960 | : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler}; | ||
| 961 | |||
| 962 | # We reached the end, return the handler | ||
| 963 | # return( $ref->{_handler} ) if( $pos == $#$parts ); | ||
| 964 | # return( $check->( $pos + 1, $ref ) ); | ||
| 965 | $access = $ref->{_access_control} if( $ref->{_access_control} ); | ||
| 966 | $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' ); | ||
| 967 | |||
| 968 | if( $pos == $#$parts ) | ||
| 969 | { | ||
| 970 | if( ref( $handler ) eq 'CODE' ) | ||
| 971 | { | ||
| 972 | my $ep = Net::API::REST::Endpoint->new( | ||
| 973 | handler => $handler, | ||
| 974 | methods => exists( $methods->{ uc( $http_meth ) } ) | ||
| 975 | ? [uc( $http_meth )] | ||
| 976 | : ( scalar( @$supported_methods ) | ||
| 977 | ? $supported_methods | ||
| 978 | : $ref->{_allowed_methods} | ||
| 979 | ? $ref->{_allowed_methods} | ||
| 980 | : $def_methods ), | ||
| 981 | variables => $vars, | ||
| 982 | access => $access, | ||
| 983 | path => $uri, | ||
| 984 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 985 | debug => $self->debug, | ||
| 986 | ); | ||
| 987 | return( $ep ); | ||
| 988 | } | ||
| 989 | elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ ) | ||
| 990 | { | ||
| 991 | my( $cl, $meth ) = ( $1, $2 ); | ||
| 992 | # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860 | ||
| 993 | # require $cl unless( defined( *{"${cl}::"} ) ); | ||
| 994 | $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) ); | ||
| 995 | # 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 | ||
| 996 | my $code = $cl->can( $meth ); | ||
| 997 | return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code ); | ||
| 998 | # return( sub{ $code->( $o, api => $self, @_ ) } ); | ||
| 999 | # try-catch | ||
| 1000 | local $@; | ||
| 1001 | my $ep = eval | ||
| 1002 | { | ||
| 1003 | Net::API::REST::Endpoint->new( | ||
| 1004 | handler => sub | ||
| 1005 | { | ||
| 1006 | my $o = $cl->new( | ||
| 1007 | apache_request => $self->apache_request, | ||
| 1008 | debug => $self->debug, | ||
| 1009 | request => $req, | ||
| 1010 | response => $resp, | ||
| 1011 | # Pass the api object here as well | ||
| 1012 | api => $self, | ||
| 1013 | ); | ||
| 1014 | return( $self->pass_error( $cl->error ) ) if( !defined( $o ) ); | ||
| 1015 | $code->( $o, api => $self, @_ ); | ||
| 1016 | }, | ||
| 1017 | methods => exists( $methods->{ uc( $http_meth ) } ) | ||
| 1018 | ? [uc( $http_meth )] | ||
| 1019 | : ( scalar( @$supported_methods ) | ||
| 1020 | ? $supported_methods | ||
| 1021 | : $ref->{_allowed_methods} | ||
| 1022 | ? $ref->{_allowed_methods} | ||
| 1023 | : $def_methods ), | ||
| 1024 | variables => $vars, | ||
| 1025 | access => $access, | ||
| 1026 | path => $uri, | ||
| 1027 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 1028 | debug => $self->debug, | ||
| 1029 | ); | ||
| 1030 | }; | ||
| 1031 | if( $@ ) | ||
| 1032 | { | ||
| 1033 | return( $self->error({ code => 500, message => $@ }) ); | ||
| 1034 | } | ||
| 1035 | return( $ep ); | ||
| 1036 | } | ||
| 1037 | else | ||
| 1038 | { | ||
| 1039 | 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." }) ); | ||
| 1040 | } | ||
| 1041 | } | ||
| 1042 | return( $check->( $pos + 1, $ref ) ); | ||
| 1043 | } | ||
| 1044 | # Not a code or a hash reference, so it has got to be a package name | ||
| 1045 | elsif( $subroutes->{ $part } =~ /^([^\-]+)\-\>(\S+)$/ ) | ||
| 1046 | { | ||
| 1047 | my( $cl, $meth ) = ( $1, $2 ); | ||
| 1048 | # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860 | ||
| 1049 | # require $cl unless( defined( *{"${cl}::"} ) ); | ||
| 1050 | # my $rc = eval{ $self->_load_class( $cl ); }; | ||
| 1051 | $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) ); | ||
| 1052 | # 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. | ||
| 1053 | # As it turns out $cl->can( $meth ) works just as well. | ||
| 1054 | # my $o = $cl->new( | ||
| 1055 | # apache_request => $self->apache_request, | ||
| 1056 | # debug => $self->debug, | ||
| 1057 | # request => $req, | ||
| 1058 | # response => $resp, | ||
| 1059 | # # Pass the api object here as well | ||
| 1060 | # api => $self, | ||
| 1061 | # ) || return( $self->pass_error( $cl->error ) ); | ||
| 1062 | # my $code = $o->can( $meth ); | ||
| 1063 | my $code = $cl->can( $meth ); | ||
| 1064 | return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code ); | ||
| 1065 | # return( sub{ $code->( $o, api => $self, @_ ) } ); | ||
| 1066 | # try-catch | ||
| 1067 | local $@; | ||
| 1068 | my $ep = eval | ||
| 1069 | { | ||
| 1070 | Net::API::REST::Endpoint->new( | ||
| 1071 | handler => sub | ||
| 1072 | { | ||
| 1073 | my $o = $cl->new( | ||
| 1074 | apache_request => $self->apache_request, | ||
| 1075 | debug => $self->debug, | ||
| 1076 | request => $req, | ||
| 1077 | response => $resp, | ||
| 1078 | # Pass the api object here as well | ||
| 1079 | api => $self, | ||
| 1080 | ); | ||
| 1081 | return( $self->pass_error( $cl->error ) ) if( !defined( $o ) ); | ||
| 1082 | $code->( $o, api => $self, @_ ); | ||
| 1083 | }, | ||
| 1084 | methods => $def_methods, | ||
| 1085 | variables => $vars, | ||
| 1086 | access => $access, | ||
| 1087 | path => $uri, | ||
| 1088 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 1089 | debug => $self->debug, | ||
| 1090 | ); | ||
| 1091 | }; | ||
| 1092 | if( $@ ) | ||
| 1093 | { | ||
| 1094 | return( $self->error({ code => 500, message => $@ }) ); | ||
| 1095 | } | ||
| 1096 | return( $ep ); | ||
| 1097 | } | ||
| 1098 | else | ||
| 1099 | { | ||
| 1100 | 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" }) ); | ||
| 1101 | } | ||
| 1102 | } | ||
| 1103 | elsif( exists( $subroutes->{_var} ) ) | ||
| 1104 | { | ||
| 1105 | my $ref = $subroutes->{_var}; | ||
| 1106 | 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' ); | ||
| 1107 | 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} ) ); | ||
| 1108 | if( !exists( $ref->{_handler} ) && | ||
| 1109 | !exists( $ref->{_delete} ) && | ||
| 1110 | !exists( $ref->{_get} ) && | ||
| 1111 | !exists( $ref->{_head} ) && | ||
| 1112 | !exists( $ref->{_patch} ) && | ||
| 1113 | !exists( $ref->{_post} ) && | ||
| 1114 | !exists( $ref->{_put} ) ) | ||
| 1115 | { | ||
| 1116 | 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." }) ); | ||
| 1117 | } | ||
| 1118 | |||
| 1119 | my $methods = {}; | ||
| 1120 | foreach my $h ( qw( _delete _get _head _patch _post _put ) ) | ||
| 1121 | { | ||
| 1122 | if( exists( $ref->{ $h } ) ) | ||
| 1123 | { | ||
| 1124 | $methods->{ uc( substr( $h, 1 ) ) } = $ref->{ $h }; | ||
| 1125 | } | ||
| 1126 | } | ||
| 1127 | |||
| 1128 | my $supported_methods = [sort( keys( %$methods ) )]; | ||
| 1129 | # If this is just a pre-flight check, at this stage the handler does not matter | ||
| 1130 | my $handler = $http_meth eq 'options' | ||
| 1131 | ? sub{} | ||
| 1132 | : exists( $methods->{ uc( $http_meth ) } ) ? $methods->{ uc( $http_meth ) } : $ref->{_handler}; | ||
| 1133 | |||
| 1134 | my $var_name = $ref->{_name}; | ||
| 1135 | $params = $ref->{_params} if( CORE::exists( $ref->{_params} ) && ref( $ref->{_params} ) eq 'HASH' ); | ||
| 1136 | # For variable type to be array | ||
| 1137 | if( exists( $ref->{_type} ) ) | ||
| 1138 | { | ||
| 1139 | if( lc( $ref->{_type} ) eq 'array' || $ref->{_type} eq '[]' ) | ||
| 1140 | { | ||
| 1141 | if( exists( $vars->{ $var_name } ) ) | ||
| 1142 | { | ||
| 1143 | my $prev = $vars->{ $var_name }; | ||
| 1144 | $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' ); | ||
| 1145 | } | ||
| 1146 | else | ||
| 1147 | { | ||
| 1148 | $vars->{ $var_name } = []; | ||
| 1149 | } | ||
| 1150 | } | ||
| 1151 | } | ||
| 1152 | # Store variable value | ||
| 1153 | if( exists( $vars->{ $var_name } ) ) | ||
| 1154 | { | ||
| 1155 | my $prev = $vars->{ $var_name }; | ||
| 1156 | $vars->{ $var_name } = [ $prev ] if( ref( $prev ) ne 'ARRAY' ); | ||
| 1157 | push( @{$vars->{ $var_name }}, $part ); | ||
| 1158 | } | ||
| 1159 | else | ||
| 1160 | { | ||
| 1161 | $vars->{ $var_name } = $part; | ||
| 1162 | } | ||
| 1163 | |||
| 1164 | # We reached the end, return the handler | ||
| 1165 | if( $pos == $#$parts ) | ||
| 1166 | { | ||
| 1167 | $access = $ref->{_access_control} if( $ref->{_access_control} ); | ||
| 1168 | if( ref( $handler ) eq 'CODE' ) | ||
| 1169 | { | ||
| 1170 | # return( $ref->{_handler} ); | ||
| 1171 | my $ep = Net::API::REST::Endpoint->new( | ||
| 1172 | handler => $handler, | ||
| 1173 | methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ), | ||
| 1174 | variables => $vars, | ||
| 1175 | access => $access, | ||
| 1176 | path => $uri, | ||
| 1177 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 1178 | debug => $self->debug, | ||
| 1179 | ); | ||
| 1180 | $ep->access( $ref->{_access_control} ) if( $ref->{_access_control} ); | ||
| 1181 | return( $ep ); | ||
| 1182 | } | ||
| 1183 | elsif( $handler =~ /^([^\-]+)\-\>(\S+)$/ ) | ||
| 1184 | { | ||
| 1185 | my( $cl, $meth ) = ( $1, $2 ); | ||
| 1186 | # https://stackoverflow.com/questions/32608504/how-to-check-if-perl-module-is-available#comment53081298_32608860 | ||
| 1187 | # require $cl unless( defined( *{"${cl}::"} ) ); | ||
| 1188 | $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) ); | ||
| 1189 | # 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 | ||
| 1190 | # my $o = $cl->new( | ||
| 1191 | # apache_request => $self->apache_request, | ||
| 1192 | # debug => $self->debug, | ||
| 1193 | # request => $req, | ||
| 1194 | # response => $resp, | ||
| 1195 | # # Pass the api object here as well | ||
| 1196 | # api => $self, | ||
| 1197 | # ) || return( $self->pass_error( $cl->error ) ); | ||
| 1198 | # my $code = $o->can( $meth ); | ||
| 1199 | my $code = $cl->can( $meth ); | ||
| 1200 | return( $self->error({ code => 500, message => "Class \"$cl\" does not have a method \"$meth\"." }) ) if( !$code ); | ||
| 1201 | # return( sub{ $code->( $o, api => $self, @_ ) } ); | ||
| 1202 | # try-catch | ||
| 1203 | local $@; | ||
| 1204 | my $ep = eval | ||
| 1205 | { | ||
| 1206 | Net::API::REST::Endpoint->new( | ||
| 1207 | handler => sub | ||
| 1208 | { | ||
| 1209 | my $o = $cl->new( | ||
| 1210 | apache_request => $self->apache_request, | ||
| 1211 | debug => $self->debug, | ||
| 1212 | request => $req, | ||
| 1213 | response => $resp, | ||
| 1214 | # Pass the api object here as well | ||
| 1215 | api => $self, | ||
| 1216 | ); | ||
| 1217 | return( $self->pass_error( $cl->error ) ) if( !defined( $o ) ); | ||
| 1218 | $code->( $o, api => $self, @_ ); | ||
| 1219 | }, | ||
| 1220 | methods => ( scalar( @$supported_methods ) ? $supported_methods : $ref->{_allowed_methods} ? $ref->{_allowed_methods} : $def_methods ), | ||
| 1221 | variables => $vars, | ||
| 1222 | access => $access, | ||
| 1223 | path => $uri, | ||
| 1224 | ( defined( $params ) ? ( params => $params ) : () ), | ||
| 1225 | debug => $self->debug, | ||
| 1226 | ); | ||
| 1227 | }; | ||
| 1228 | if( $@ ) | ||
| 1229 | { | ||
| 1230 | return( $self->error({ code => 500, message => $@ }) ); | ||
| 1231 | } | ||
| 1232 | return( $ep ); | ||
| 1233 | } | ||
| 1234 | else | ||
| 1235 | { | ||
| 1236 | 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" }) ); | ||
| 1237 | } | ||
| 1238 | } | ||
| 1239 | return( $check->( $pos + 1, $ref ) ); | ||
| 1240 | } | ||
| 1241 | # Empty means not found | ||
| 1242 | else | ||
| 1243 | { | ||
| 1244 | return( '' ); | ||
| 1245 | } | ||
| 1246 | }; | ||
| 1247 | # We return empty, not undef if nothing was found | ||
| 1248 | my $ep = $check->( 0, $routes->{ $client_api_version } ); | ||
| 1249 | # An error occurred | ||
| 1250 | if( !defined( $ep ) ) | ||
| 1251 | { | ||
| 1252 | return; | ||
| 1253 | } | ||
| 1254 | # Nothing found | ||
| 1255 | elsif( !length( $ep ) ) | ||
| 1256 | { | ||
| 1257 | return( '' ); | ||
| 1258 | } | ||
| 1259 | else | ||
| 1260 | { | ||
| 1261 | return( $ep ); | ||
| 1262 | } | ||
| 1263 | } | ||
| 1264 | |||
| 1265 | sub routes | ||
| 1266 | { | ||
| 1267 | my $self = shift( @_ ); | ||
| 1268 | if( @_ ) | ||
| 1269 | { | ||
| 1270 | my $hash = shift( @_ ) || return( $self->error({ code => 500, message => "No route hash reference was provided." }) ); | ||
| 1271 | return( $self->error({ code => 500, message => "Routes provided ($hash) is not a hash reference." }) ) if( ref( $hash ) ne 'HASH' ); | ||
| 1272 | my $req = $self->request; | ||
| 1273 | my $resp = $self->response; | ||
| 1274 | # Walk through the hash to check everything is ok | ||
| 1275 | # Returns nothing if all is ok, or self returns an error description | ||
| 1276 | my $check; | ||
| 1277 | $check = sub | ||
| 1278 | { | ||
| 1279 | my $this = shift( @_ ); | ||
| 1280 | foreach my $k ( sort( keys( %$this ) ) ) | ||
| 1281 | { | ||
| 1282 | my $v = $this->{ $k }; | ||
| 1283 | if( $k eq '_params' ) | ||
| 1284 | { | ||
| 1285 | return( "Value provided for _params is not an hash reference." ) if( ref( $v ) ne 'HASH' ); | ||
| 1286 | } | ||
| 1287 | elsif( ref( $v ) eq 'HASH' ) | ||
| 1288 | { | ||
| 1289 | if( !CORE::exists( $v->{_handler} ) && | ||
| 1290 | !CORE::exists( $v->{_delete} ) && | ||
| 1291 | !CORE::exists( $v->{_get} ) && | ||
| 1292 | !CORE::exists( $v->{_head} ) && | ||
| 1293 | !CORE::exists( $v->{_post} ) && | ||
| 1294 | !CORE::exists( $v->{_put} ) ) | ||
| 1295 | { | ||
| 1296 | return( "The keyword '_handlers' used is mispelled. It should be '_handler'" ) if( CORE::exists( $this->{_handlers} ) ); | ||
| 1297 | 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." ); | ||
| 1298 | } | ||
| 1299 | if( my $err = $check->( $v ) ) | ||
| 1300 | { | ||
| 1301 | return( $err ); | ||
| 1302 | } | ||
| 1303 | } | ||
| 1304 | elsif( $k eq '_name' ) | ||
| 1305 | { | ||
| 1306 | return( "Value provided for _name is empty." ) if( !length( $v ) ); | ||
| 1307 | return( "Value provided for _name is a reference, but I was expecting a scalar." ) if( ref( $v ) ); | ||
| 1308 | } | ||
| 1309 | elsif( ref( $v ) eq 'CODE' ) | ||
| 1310 | { | ||
| 1311 | # We're ok | ||
| 1312 | } | ||
| 1313 | elsif( $v =~ /^([^\:]+)\:{2}[^\:]+/ ) | ||
| 1314 | { | ||
| 1315 | # my $cl = $subroutes->{ $part }; | ||
| 1316 | my $cl = $v; | ||
| 1317 | my $meth; | ||
| 1318 | if( $cl =~ /^([^\-]+)\-\>(\S+)$/ ) | ||
| 1319 | { | ||
| 1320 | ( $cl, $meth ) = ( $1, $2 ); | ||
| 1321 | } | ||
| 1322 | # require $cl unless( defined( *{"${cl}::"} ) ); | ||
| 1323 | $self->_load_class( $cl ) || return( $self->pass_error({ code => 500 }) ); | ||
| 1324 | # 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 :) | ||
| 1325 | #my $o = $cl->new( | ||
| 1326 | # apache_request => $self->apache_request, | ||
| 1327 | # debug => $self->debug, | ||
| 1328 | # request => $req, | ||
| 1329 | # response => $resp, | ||
| 1330 | # # Pass the api object here as well | ||
| 1331 | # api => $self, | ||
| 1332 | # checkonly => 1 | ||
| 1333 | #) || return( $self->pass_error( $cl->error ) ); | ||
| 1334 | if( !defined( $meth ) ) | ||
| 1335 | { | ||
| 1336 | return( "Class \"$cl\" does not have a method \"$meth\"." ) if( !$cl->can( $meth ) ); | ||
| 1337 | } | ||
| 1338 | } | ||
| 1339 | elsif( $k eq '_allowed_method' ) | ||
| 1340 | { | ||
| 1341 | return( "The keyword '_allowed_method' used is mispelled. It should be '_allowed_methods'" ) if( !CORE::exists( $this->{_allowed_methods} ) ); | ||
| 1342 | } | ||
| 1343 | elsif( $k eq '_access_controls' ) | ||
| 1344 | { | ||
| 1345 | return( "The keyword '_access_controls' used is mispelled. It should be '_access_control'" ) if( !CORE::exists( $this->{_access_control} ) ); | ||
| 1346 | } | ||
| 1347 | elsif( $k =~ /^_(allowed_methods|access_control)$/ ) | ||
| 1348 | { | ||
| 1349 | # Ok | ||
| 1350 | } | ||
| 1351 | # If it is neither a code reference nor a package name, we raise an error | ||
| 1352 | else | ||
| 1353 | { | ||
| 1354 | return( "I was expecting a code reference or a package name, but instead got '$v' for key $k" ); | ||
| 1355 | } | ||
| 1356 | } | ||
| 1357 | }; | ||
| 1358 | # first level of keys are api version numbers, such as 1, 1.2, 2, etc... | ||
| 1359 | # and for each api version there is a set of route | ||
| 1360 | my @api_versions = keys( %$hash ); | ||
| 1361 | foreach my $vers ( @api_versions ) | ||
| 1362 | { | ||
| 1363 | if( $vers !~ /^\d+(?:\.\d+)*$/ ) | ||
| 1364 | { | ||
| 1365 | return( $self->error( "API version number '$vers' is not a valid version number. Valid values are 1, 1.2, 1.5.3 for example." ) ); | ||
| 1366 | } | ||
| 1367 | elsif( ref( $hash->{ $vers } ) ne 'HASH' ) | ||
| 1368 | { | ||
| 1369 | return( $self->error( "API version number '$vers' value is not an hash reference. Its value must be a route to resources as hash reference." ) ); | ||
| 1370 | } | ||
| 1371 | } | ||
| 1372 | |||
| 1373 | foreach my $version ( sort( @api_versions ) ) | ||
| 1374 | { | ||
| 1375 | if( my $err = $check->( $hash->{ $version } ) ) | ||
| 1376 | { | ||
| 1377 | return( $self->error({ code => 500, message => $err }) ); | ||
| 1378 | } | ||
| 1379 | } | ||
| 1380 | $self->{routes} = $hash; | ||
| 1381 | } | ||
| 1382 | return( $self->{routes} ); | ||
| 1383 | } | ||
| 1384 | |||
| 1385 | sub supported_api_versions | ||
| 1386 | { | ||
| 1387 | my $self = shift( @_ ); | ||
| 1388 | if( @_ ) | ||
| 1389 | { | ||
| 1390 | my $v = ref( $_[0] ) ? shift( @_ ) : \@_; | ||
| 1391 | my $vers = []; | ||
| 1392 | foreach my $this ( @$v ) | ||
| 1393 | { | ||
| 1394 | push( @$vers, version->parse( $this ) ); | ||
| 1395 | } | ||
| 1396 | $self->{supported_api_versions} = $vers; | ||
| 1397 | } | ||
| 1398 | return( $self->{supported_api_versions} ); | ||
| 1399 | } | ||
| 1400 | |||
| 1401 | sub supported_content_types { return( shift->_set_get_array( 'supported_content_types', @_ ) ); } | ||
| 1402 | |||
| 1403 | sub supported_languages { return( shift->_set_get_array( 'supported_languages', @_ ) ); } | ||
| 1404 | |||
| 1405 | sub supported_methods { return( shift->_set_get_array( 'supported_methods', @_ ) ); } | ||
| 1406 | |||
| 1407 | sub well_known | ||
| 1408 | { | ||
| 1409 | my $self = shift( @_ ); | ||
| 1410 | return( Apache2::Const::DECLINED ); | ||
| 1411 | } | ||
| 1412 | |||
| 1413 | sub _try | ||
| 1414 | { | ||
| 1415 | my $self = shift( @_ ); | ||
| 1416 | my $pack = shift( @_ ) || return( $self->error( "No Apache package name was provided to call method" ) ); | ||
| 1417 | my $meth = shift( @_ ) || return( $self->error( "No method name was provided to try!" ) ); | ||
| 1418 | my $r = Apache2::RequestUtil->request; | ||
| 1419 | # $r->log_error( "Net::API::REST::_try to call method \"$meth\" in package \"$pack\"." ); | ||
| 1420 | # try-catch | ||
| 1421 | local $@; | ||
| 1422 | my $rv = eval | ||
| 1423 | { | ||
| 1424 | return( $self->$pack->$meth ) if( !scalar( @_ ) ); | ||
| 1425 | return( $self->$pack->$meth( @_ ) ); | ||
| 1426 | }; | ||
| 1427 | if( $@ ) | ||
| 1428 | { | ||
| 1429 | return( $self->error( "An error occurred while trying to call Apache ", ucfirst( $pack ), " method \"$meth\": $@" ) ); | ||
| 1430 | } | ||
| 1431 | return( $rv ); | ||
| 1432 | } | ||
| 1433 | |||
| 1434 | # NOTE: Net::API::REST::Endpoint package | ||
| 1435 | package Net::API::REST::Endpoint; | ||
| 1436 | BEGIN | ||
| 1437 | { | ||
| 1438 | use strict; | ||
| 1439 | use warnings; | ||
| 1440 | use parent qw( Module::Generic ); | ||
| 1441 | }; | ||
| 1442 | |||
| 1443 | sub init | ||
| 1444 | { | ||
| 1445 | my $self = shift( @_ ); | ||
| 1446 | # ACL | ||
| 1447 | $self->{access} = 'public'; | ||
| 1448 | $self->{handler} = ''; | ||
| 1449 | $self->{methods} = []; | ||
| 1450 | $self->{params} = {}; | ||
| 1451 | $self->{path} = ''; | ||
| 1452 | $self->{path_info} = []; | ||
| 1453 | $self->{variables} = {}; | ||
| 1454 | $self->{_init_strict_use_sub} = 1; | ||
| 1455 | $self->SUPER::init( @_ ); | ||
| 1456 | return( $self ); | ||
| 1457 | } | ||
| 1458 | |||
| 1459 | sub access { return( shift->_set_get_scalar( 'access', @_ ) ); } | ||
| 1460 | |||
| 1461 | sub handler { return( shift->_set_get_code( 'handler', @_ ) ); } | ||
| 1462 | |||
| 1463 | sub is_method_allowed | ||
| 1464 | { | ||
| 1465 | my $self = shift( @_ ); | ||
| 1466 | my $meth = shift( @_ ); | ||
| 1467 | my $ok_methods = $self->methods; | ||
| 1468 | return( scalar( grep( /^$meth$/i, @$ok_methods ) ) ); | ||
| 1469 | } | ||
| 1470 | |||
| 1471 | sub methods { return( shift->_set_get_array_as_object( 'methods', @_ ) ); } | ||
| 1472 | |||
| 1473 | sub params { return( shift->_set_get_hash_as_mix_object( 'params', @_ ) ); } | ||
| 1474 | |||
| 1475 | sub path { return( shift->_set_get_uri( 'path', @_ ) ); } | ||
| 1476 | |||
| 1477 | sub path_info { return( shift->_set_get_array_as_object( 'path_info', @_ ) ); } | ||
| 1478 | |||
| 1479 | # sub variables { return( shift->_set_get_hash_as_object( 'variables', 'Net::API::REST::Endpoint::Variables', @_ ) ); } | ||
| 1480 | sub variables { return( shift->_set_get_hash_as_mix_object( 'variables', @_ ) ); } | ||
| 1481 | |||
| 1482 | # NOTE: Net::API::REST::RC package | ||
| 1483 | package Net::API::REST::RC; | ||
| 1484 | BEGIN | ||
| 1485 | { | ||
| 1486 | use strict; | ||
| 1487 | use warnings; | ||
| 1488 | use parent qw( Module::Generic ); | ||
| 1489 | use overload ( | ||
| 1490 | '""' => 'as_string', | ||
| 1491 | ); | ||
| 1492 | }; | ||
| 1493 | |||
| 1494 | sub init | ||
| 1495 | { | ||
| 1496 | my $self = shift( @_ ); | ||
| 1497 | $self->{code} = undef(); | ||
| 1498 | $self->{message} = undef(); | ||
| 1499 | $self->{_init_strict_use_sub} = 1; | ||
| 1500 | $self->SUPER::init( @_ ); | ||
| 1501 | return( $self ); | ||
| 1502 | } | ||
| 1503 | |||
| 1504 | sub as_string { return( shift->{code} ); } | ||
| 1505 | |||
| 1506 | sub code { return( shift->_set_get_number( 'code', @_ ) ); } | ||
| 1507 | |||
| 1508 | sub message { return( shift->_set_get_scalar_as_object( 'message', @_ ) ); } | ||
| 1509 | |||
| 1510 | sub TO_JSON { return( shift->{code} ); } | ||
| 1511 | |||
| 1512 | 1; | ||
| 1513 | # NOTE: pod | ||
| 1514 | __END__ | ||