| 1 | package WWW::Suffit::Server::API::Auth; | ||
| 2 | use strict; | ||
| 3 | use utf8; | ||
| 4 | |||
| 5 | =encoding utf8 | ||
| 6 | |||
| 7 | =head1 NAME | ||
| 8 | |||
| 9 | WWW::Suffit::Server::API::Auth - The authentication and authorization Suffit API controller | ||
| 10 | |||
| 11 | =head1 SYNOPSIS | ||
| 12 | |||
| 13 | use WWW::Suffit::Server::API::Auth; | ||
| 14 | |||
| 15 | =head1 DESCRIPTION | ||
| 16 | |||
| 17 | The authentication and authorization Suffit API controller | ||
| 18 | |||
| 19 | =head1 METHODS | ||
| 20 | |||
| 21 | List of authorization/authentication methods | ||
| 22 | |||
| 23 | =head2 authorize | ||
| 24 | |||
| 25 | $c->routes->post('/authorize')->to('API::Auth#authorize' | ||
| 26 | => {token_type => 'session'}); | ||
| 27 | $c->routes->post('/authorize')->to('API::Auth#authorize' | ||
| 28 | => {token_type => 'access'}); | ||
| 29 | $c->routes->post('/authorize')->to('API::Auth#authorize' | ||
| 30 | => {token_type => 'api'}); | ||
| 31 | |||
| 32 | The authorization controller by stashed parameters | ||
| 33 | |||
| 34 | Options: | ||
| 35 | |||
| 36 | =over 8 | ||
| 37 | |||
| 38 | =item skip_authdb_connect | ||
| 39 | |||
| 40 | skip_authdb_connect => 1 | ||
| 41 | |||
| 42 | This option disables connection to authorization database | ||
| 43 | |||
| 44 | =item token_type | ||
| 45 | |||
| 46 | token_type => 'access' | ||
| 47 | |||
| 48 | This option is required and sets the token type: C<access>, C<session>, C<refresh> or C<api> | ||
| 49 | |||
| 50 | =back | ||
| 51 | |||
| 52 | See L</"POST /authorize"> | ||
| 53 | |||
| 54 | =head2 is_authorized | ||
| 55 | |||
| 56 | my $authorized = $c->routes->under('/api')->to('API::Auth#is_authorized') | ||
| 57 | ->name('api'); | ||
| 58 | |||
| 59 | The API Authorization checker. If use `init_api_routes` startup option then | ||
| 60 | this route will be exists by default. To get access to this route use: | ||
| 61 | |||
| 62 | my $authorized = $r->lookup('api'); | ||
| 63 | |||
| 64 | =head1 API METHODS | ||
| 65 | |||
| 66 | List of API methods | ||
| 67 | |||
| 68 | =head2 POST /api/authorize | ||
| 69 | |||
| 70 | This method performs authentication and authorization on the Suffit API server, | ||
| 71 | then returns the access token | ||
| 72 | |||
| 73 | # curl -v -X POST \ | ||
| 74 | -H "Accept: application/json" \ | ||
| 75 | -d '{ | ||
| 76 | "username": "test", | ||
| 77 | "password": "test", | ||
| 78 | "encrypted": false, | ||
| 79 | "remember": false, | ||
| 80 | "cachekey": "" | ||
| 81 | }' \ | ||
| 82 | https://localhost:8695/api/authorize | ||
| 83 | |||
| 84 | # curl -v -X POST \ | ||
| 85 | -H "Accept: application/json" \ | ||
| 86 | -F username=test -F password=test \ | ||
| 87 | https://localhost:8695/api/authorize | ||
| 88 | |||
| 89 | > POST /authorize HTTP/1.1 | ||
| 90 | > Host: localhost:8695 | ||
| 91 | > User-Agent: curl/7.68.0 | ||
| 92 | > Accept: application/json | ||
| 93 | > Content-Length: 248 | ||
| 94 | > Content-Type: multipart/form-data; boundary=-----6a21ca7cea8dc981 | ||
| 95 | > | ||
| 96 | < HTTP/1.1 200 OK | ||
| 97 | < Date: Tue, 13 Aug 2024 14:42:56 GMT | ||
| 98 | < Content-Type: application/json;charset=UTF-8 | ||
| 99 | < Content-Length: 635 | ||
| 100 | < Server: WWW::Suffit/1.00 | ||
| 101 | < | ||
| 102 | { | ||
| 103 | "cachekey": "97vyZgPzskPG", | ||
| 104 | "clientid": "f459f12619c961122450ae5883e44a60", | ||
| 105 | "code": "E0000", | ||
| 106 | "datetime": "2024-08-13T14:42:56Z", | ||
| 107 | "elapsed": 0.230106, | ||
| 108 | "encrypted": false, | ||
| 109 | "expires": "2024-08-14T14:42:56Z", | ||
| 110 | "jti": "oWwGYKT2MdKj-xVvF9s9", | ||
| 111 | "message": "The user is successfully authorized", | ||
| 112 | "referer": "", | ||
| 113 | "status": true, | ||
| 114 | "token": "ey...8o", | ||
| 115 | "type": "access", | ||
| 116 | "user": { | ||
| 117 | "algorithm": "SHA256", | ||
| 118 | "attributes": "", | ||
| 119 | "comment": "Test user for internal testing only", | ||
| 120 | "created": 1678741533, | ||
| 121 | "email": "test@owl.localhost", | ||
| 122 | "email_md5": "163e50783979333ebae6fd63b2d96d16", | ||
| 123 | "expires": 1723560176, | ||
| 124 | "flags": 31, | ||
| 125 | "groups": [ | ||
| 126 | "user" | ||
| 127 | ], | ||
| 128 | "name": "Test User", | ||
| 129 | "not_after": 0, | ||
| 130 | "not_before": 1695334721, | ||
| 131 | "public_key": "-----BEGIN RSA PUBLIC KEY-----...", | ||
| 132 | "role": "Test user", | ||
| 133 | "uid": 3, | ||
| 134 | "username": "test" | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 138 | =head1 ERROR CODES | ||
| 139 | |||
| 140 | List of authentication and authorization Suffit API error codes | ||
| 141 | |||
| 142 | API | HTTP | DESCRIPTION | ||
| 143 | -------+-------+------------------------------------------------- | ||
| 144 | E1000 [403] Access denied. No token/session exists | ||
| 145 | E1001 [403] Access denied. JWT error | ||
| 146 | E1002 [403] Access denied. The token has been revoked | ||
| 147 | E1003 [ * ] Access denied. Session is not authorized | ||
| 148 | E1004 [ * ] Access denied by realm restrictions | ||
| 149 | E1005 [500] The authorization database is not ready | ||
| 150 | E1006 [500] Can't connect to authorization database | ||
| 151 | E1007 [---] Reserved | ||
| 152 | E1008 [---] Reserved | ||
| 153 | E1009 [---] Reserved | ||
| 154 | E1010 [---] Reserved | ||
| 155 | E1011 [---] Reserved | ||
| 156 | E1012 [---] Reserved | ||
| 157 | E1013 [---] Reserved | ||
| 158 | E1014 [---] Reserved | ||
| 159 | E1015 [---] Reserved | ||
| 160 | E1016 [---] Reserved | ||
| 161 | E1017 [---] Reserved | ||
| 162 | E1018 [---] Reserved | ||
| 163 | E1019 [---] Reserved | ||
| 164 | E1020 [400] Incorrect token type | ||
| 165 | E1021 [401] No username specified | ||
| 166 | E1022 [401] No password specified | ||
| 167 | E1023 [500] RSA decode error | ||
| 168 | E1024 [500] Can't JWT generate | ||
| 169 | E1025 [500] Can't token store to database | ||
| 170 | E1026 [---] Reserved | ||
| 171 | E1027 [---] Reserved | ||
| 172 | E1028 [---] Reserved | ||
| 173 | E1029 [---] Reserved | ||
| 174 | |||
| 175 | B<*> -- this code will be defined later on the interface side | ||
| 176 | |||
| 177 | See also list of common Suffit API error codes in L<WWW::Suffit::API/"ERROR CODES"> | ||
| 178 | |||
| 179 | =head1 HISTORY | ||
| 180 | |||
| 181 | See C<Changes> file | ||
| 182 | |||
| 183 | =head1 TO DO | ||
| 184 | |||
| 185 | See C<TODO> file | ||
| 186 | |||
| 187 | =head1 SEE ALSO | ||
| 188 | |||
| 189 | L<WWW::Suffit::Server> | ||
| 190 | |||
| 191 | =head1 AUTHOR | ||
| 192 | |||
| 193 | Serż Minus (Sergey Lepenkov) L<https://www.serzik.com> E<lt>abalama@cpan.orgE<gt> | ||
| 194 | |||
| 195 | =head1 COPYRIGHT | ||
| 196 | |||
| 197 | Copyright (C) 1998-2026 D&D Corporation | ||
| 198 | |||
| 199 | =head1 LICENSE | ||
| 200 | |||
| 201 | This program is distributed under the terms of the Artistic License Version 2.0 | ||
| 202 | |||
| 203 | See the C<LICENSE> file or L<https://opensource.org/license/artistic-2-0> for details | ||
| 204 | |||
| 205 | =cut | ||
| 206 | |||
| 207 | use Mojo::Base 'Mojolicious::Controller'; | ||
| 208 | |||
| 209 | use Mojo::JSON qw / true false /; | ||
| 210 | use Mojo::Util qw/ md5_sum /; | ||
| 211 | use Mojo::Date; | ||
| 212 | use Mojo::URL; | ||
| 213 | use Mojo::JSON qw / true false /; | ||
| 214 | |||
| 215 | use Acrux::Util qw/ parse_time_offset randchars /; | ||
| 216 | use Acrux::RefUtil qw/ is_true_flag /; | ||
| 217 | |||
| 218 | use WWW::Suffit::Const qw/ TOKEN_EXPIRATION TOKEN_EXPIRE_MAX /; | ||
| 219 | use WWW::Suffit::RSA; | ||
| 220 | |||
| 221 | sub is_authorized { | ||
| 222 | my $self = shift; | ||
| 223 | my ($username, $expiration, $cachekey); | ||
| 224 | |||
| 225 | # Get authdb instance | ||
| 226 | my $authdb = $self->authdb; | ||
| 227 | |||
| 228 | # Get authorization data from token (if specified) | ||
| 229 | if (my $token = $self->token) { | ||
| 230 | my $jwt = $self->jwt; | ||
| 231 | |||
| 232 | # Get payload from JWT | ||
| 233 | my $payload = $jwt->decode($token)->payload; | ||
| 234 | if ($jwt->error) { | ||
| 235 | $self->reply->json_error(403 => "E1001" => sprintf("Access denied. %s", $jwt->error)); | ||
| 236 | return; | ||
| 237 | } | ||
| 238 | $username = $payload->{'usr'}; | ||
| 239 | $expiration = $payload->{'exp'} || (time + TOKEN_EXPIRATION); | ||
| 240 | $cachekey = $payload->{'key'}; | ||
| 241 | |||
| 242 | # Check the token by database | ||
| 243 | if ($payload->{'jti'}) { | ||
| 244 | unless ($authdb->token_check($username, $payload->{'jti'})) { | ||
| 245 | if ($authdb->error) { | ||
| 246 | $self->reply->json_error($authdb->code, $authdb->error); | ||
| 247 | return; | ||
| 248 | } | ||
| 249 | $self->log->info(sprintf("Revoked token: \"%s\"", $payload->{'jti'})); | ||
| 250 | $self->reply->json_error(403 => "E1002" => "Access denied. The token has been revoked"); | ||
| 251 | return; | ||
| 252 | } | ||
| 253 | } | ||
| 254 | } else { # No token specified | ||
| 255 | $self->reply->json_error(403 => "E1000" => "Access denied. No token exists"); | ||
| 256 | return; | ||
| 257 | } | ||
| 258 | |||
| 259 | # Set expiration and cachekey to stash if exists | ||
| 260 | $self->stash(expiration => $expiration) if $expiration; | ||
| 261 | $self->stash(cachekey => $cachekey) if $cachekey; | ||
| 262 | |||
| 263 | # Authorization (username is optional) | ||
| 264 | if ($username) { | ||
| 265 | my $user = $authdb->authz( | ||
| 266 | u => $username, | ||
| 267 | 's' => 0, | ||
| 268 | k => $cachekey, | ||
| 269 | ); | ||
| 270 | unless ($user) { | ||
| 271 | $self->log->info(sprintf("Session is not authorized for \"%s\"", $username)); | ||
| 272 | $self->reply->json_error($authdb->code, $authdb->error || "E1003: Access denied. Session is not authorized"); | ||
| 273 | return; | ||
| 274 | } | ||
| 275 | |||
| 276 | # Stash user data | ||
| 277 | $self->stash($user->to_hash); | ||
| 278 | |||
| 279 | # Stah is_authorized flag | ||
| 280 | $self->stash(is_authorized => $user->is_authorized ? 1 : 0) ; | ||
| 281 | } | ||
| 282 | |||
| 283 | # Access (username is optional; b,m,url,p,i,r will be got from controller) | ||
| 284 | my $has_access = $authdb->access( | ||
| 285 | c => $self, | ||
| 286 | u => $username, | ||
| 287 | k => $cachekey, | ||
| 288 | ); | ||
| 289 | unless ($has_access) { | ||
| 290 | $self->reply->json_error($authdb->code, $authdb->error || "E1004: Access denied by realm restrictions"); | ||
| 291 | return; | ||
| 292 | } | ||
| 293 | |||
| 294 | # Ok | ||
| 295 | return 1; | ||
| 296 | } | ||
| 297 | sub authorize { | ||
| 298 | my $self = shift; | ||
| 299 | $self->timing->begin('suffit_authorize'); | ||
| 300 | my $token_type = $self->stash('token_type') || ''; | ||
| 301 | my $skip_authdb_connect = $self->stash('skip_authdb_connect') ? 1 : 0; | ||
| 302 | my $username = $self->param('username') // $self->req->json('/username') // ''; | ||
| 303 | my $password = $self->param('password') // $self->req->json('/password') // ''; | ||
| 304 | my $encrypted = is_true_flag($self->param('encrypted') // $self->req->json('/encrypted')) || 0; | ||
| 305 | my $remember = is_true_flag($self->param('remember') // $self->req->json('/remember')) || 0; | ||
| 306 | my $cachekey = $self->param('cachekey') // $self->req->json('/cachekey') // $self->app->gen_cachekey; | ||
| 307 | |||
| 308 | # md5(User-Agent . Remote-Address) | ||
| 309 | my $ip = $self->client_ip($self->app->trustedproxies); | ||
| 310 | my $clientid = $self->param('clientid') // $self->req->json('/clientid') | ||
| 311 | || md5_sum(sprintf("%s%s", $self->req->headers->header('User-Agent') // 'unknown', $ip)); | ||
| 312 | |||
| 313 | # Get Referer from flash or header | ||
| 314 | my $href = $self->req->headers->header("Referer") // ''; | ||
| 315 | my $referer = $self->flash("referer") // ($href ? Mojo::URL->new($href)->path->to_string // '' : ''); | ||
| 316 | $referer =~ s/\/authorize//; | ||
| 317 | $self->stash(referer => $referer); | ||
| 318 | |||
| 319 | # Get authdb instance | ||
| 320 | my $authdb = $self->authdb; | ||
| 321 | return $self->reply->json_error(500 => "E1005" => "The authorization database is not ready") unless $authdb; | ||
| 322 | |||
| 323 | # Connect to AuthDB (optional) | ||
| 324 | if (!$skip_authdb_connect) { | ||
| 325 | $authdb->connect; | ||
| 326 | if ($authdb->error) { | ||
| 327 | return $self->reply->json_error(500 => $authdb->error); | ||
| 328 | } elsif (!$authdb->initialized) { | ||
| 329 | return $self->reply->json_error(500 => "E1307" => "The authorization database is not initialized"); | ||
| 330 | } | ||
| 331 | } | ||
| 332 | |||
| 333 | # Token type | ||
| 334 | return $self->reply->json_error(400 => "E1020" => "Incorrect token type. Allowed: session, access, refresh, api") | ||
| 335 | unless grep {$token_type eq $_} (qw/session access refresh api/); | ||
| 336 | |||
| 337 | # Please provide username and password for authorization | ||
| 338 | return $self->reply->json_error(401 => "E1021" => "No username specified") unless length($username); | ||
| 339 | return $self->reply->json_error(401 => "E1022" => "No password specified") unless length($password); | ||
| 340 | |||
| 341 | # Password decrypt | ||
| 342 | if ($encrypted && length($password)) { | ||
| 343 | my $rsa = WWW::Suffit::RSA->new(private_key => $self->app->private_key); | ||
| 344 | $password = $rsa->decrypt($password); | ||
| 345 | return $self->reply->json_error(500 => "E1023" => $rsa->error) if $rsa->error; # RSA decrypt error | ||
| 346 | } | ||
| 347 | |||
| 348 | # Authentication | ||
| 349 | $authdb->authn( | ||
| 350 | u => $username, | ||
| 351 | p => $password, | ||
| 352 | a => $ip, # For check by stats | ||
| 353 | k => $cachekey, | ||
| 354 | ) or return $self->reply->json_error($authdb->code, $authdb->error); # Unauthenticated (incorrect username or password) | ||
| 355 | |||
| 356 | # Authorization | ||
| 357 | my $user = $authdb->authz( | ||
| 358 | u => $username, | ||
| 359 | 's' => 0, | ||
| 360 | k => $cachekey, | ||
| 361 | ); | ||
| 362 | return $self->reply->json_error($authdb->code, $authdb->error) unless $user; # Unauthorized (Access denied) | ||
| 363 | |||
| 364 | # Generate token: access, session, api, etc. | ||
| 365 | my $jwt = $self->jwt; | ||
| 366 | my $jws_algorithm = $authdb->meta("jws_algorithm") || $self->conf->latest("/jws_algorithm") || ''; | ||
| 367 | $jwt->algorithm($jws_algorithm) if length $jws_algorithm; | ||
| 368 | |||
| 369 | # Expires | ||
| 370 | my $now = time(); # NOW | ||
| 371 | my $tokenexpires = $authdb->meta("tokenexpires") || parse_time_offset($self->conf->latest("/tokenexpires")) || TOKEN_EXPIRATION; | ||
| 372 | my $exp = $now + ($remember ? TOKEN_EXPIRE_MAX : $tokenexpires); | ||
| 373 | if ($token_type eq 'api') { | ||
| 374 | $exp = $user->forever ? undef : ($now + TOKEN_EXPIRATION * 365); | ||
| 375 | } | ||
| 376 | my $jti = sprintf("%s%s", randchars(8), $self->req->request_id); | ||
| 377 | $jwt->expires($exp); | ||
| 378 | $jwt->iat($now)->jti($jti)->payload({ | ||
| 379 | ver => $self->app->VERSION, | ||
| 380 | typ => $token_type, | ||
| 381 | usr => $username, | ||
| 382 | ip => $ip, | ||
| 383 | cid => $clientid, | ||
| 384 | $cachekey ? (key => $cachekey) : (), | ||
| 385 | }); | ||
| 386 | |||
| 387 | # Issue (generate) | ||
| 388 | my $token = $jwt->encode->token; | ||
| 389 | return $self->reply->json_error(500 => "E1024" => $jwt->error || "Can't JWT generate") unless $token; # Can't JWT generation | ||
| 390 | |||
| 391 | # Store token | ||
| 392 | $authdb->token_set( | ||
| 393 | type => $token_type, | ||
| 394 | jti => $jti, | ||
| 395 | username => $username, | ||
| 396 | clientid => $clientid, | ||
| 397 | iat => $now, | ||
| 398 | exp => $exp || 0, | ||
| 399 | address => $ip, | ||
| 400 | ) or return $self->reply->json_error($authdb->code, $authdb->error || "E1025: Can't token store to database"); # Can't store token data | ||
| 401 | |||
| 402 | # Ok | ||
| 403 | return $self->reply->json_ok({ | ||
| 404 | message => "The user is successfully authorized", | ||
| 405 | encrypted => $encrypted ? true : false, | ||
| 406 | clientid => $clientid, | ||
| 407 | datetime => Mojo::Date->new($now)->to_datetime, # RFC 3339 | ||
| 408 | expires => Mojo::Date->new($exp || 0)->to_datetime, # RFC 3339 | ||
| 409 | elapsed => $self->timing->elapsed('suffit_authorize') // 0, | ||
| 410 | referer => $referer, | ||
| 411 | jti => $jti, | ||
| 412 | type => $token_type, | ||
| 413 | token => $token, | ||
| 414 | cachekey => $cachekey, | ||
| 415 | user => { ($user->to_hash(1)) }, | ||
| 416 | }); | ||
| 417 | } | ||
| 418 | |||
| 419 | 1; | ||
| 420 | |||
| 421 | __END__ |