AuthorizationServer/Server.pm

filter: Statementstmt 100% 196 / 196 Branchbran 91.3% 106 / 116 Conditioncond 62.3% 58 / 93 MC/DCmcdc 37.7% 20 / 53 Subroutinesub 100% 34 / 34 Podpod 87.5% 7 / 8 totaltotal 84.2% 421 / 500 CC 102 SCAR 25.0
CC
102
Cov
89%
register_client
21.1
validate_authorize
20.7
_validate_client_metadata
19.5
CRAP 12.2
↑ Summary AuthorizationServer.pm »
1 package Catalyst::Plugin::OAuth2::AuthorizationServer::Server;
2 9 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 9 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use Crypt::JWT qw/encode_jwt/;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use Bytes::Random::Secure qw/random_bytes/;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use MIME::Base64 qw/encode_base64url/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use Digest::SHA qw/sha256 sha256_hex/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use URI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Catalyst::Plugin::OAuth2::AuthorizationServer::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use MooX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 9 our $VERSION = '0.003';
16  
17 9 has store => ( is => 'ro', required => 1 );
18 9 has signing_key => ( is => 'ro', required => 1 );
19 9 has issuer => ( is => 'ro', required => 1 );
20 9 has resource => ( is => 'ro', required => 1 );
21  
22 9 has jwt_alg => ( is => 'ro', default => 'HS256' );
23 9 has access_ttl => ( is => 'ro', default => 900 );
24 9 has refresh_ttl => ( is => 'ro', default => 2592000 );
25 9 has code_ttl => ( is => 'ro', default => 60 );
26  
27 9 has scopes_supported => ( is => 'ro' ); # arrayref or undef
28 9 has metadata_max_bytes => ( is => 'ro', default => 8192 );
29 9 has redirect_uris_max => ( is => 'ro', default => 5 );
30 9 has redirect_uri_max_length => ( is => 'ro', default => 2048 );
31  
32 9 has authorize_endpoint => ( is => 'lazy' );
33 9 has token_endpoint => ( is => 'lazy' );
34 9 has registration_endpoint => ( is => 'lazy' );
35  
36 18 ▶sub _build_authorize_endpoint ( $self ) { $self->issuer . '/authorize' }
Subroutine _build_authorize_endpoint: called CC=1 SCAR=0.0
37 18 ▶sub _build_token_endpoint ( $self ) { $self->issuer . '/token' }
Subroutine _build_token_endpoint: called CC=1 SCAR=0.0
38 18 ▶sub _build_registration_endpoint ( $self ) { $self->issuer . '/register' }
Subroutine _build_registration_endpoint: called CC=1 SCAR=0.0
39  
40 96 ▶sub BUILD ( $self, $args ) {
Subroutine BUILD: called CC=7 SCAR=19.5
Pod undocumented
41 Carp::croak 'resource must be a non-empty scalar or arrayref'
42 96 ▶ unless @{ $self->_resource_list };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->_resource_list;} 1 95 96
43 95 for my $ttl (qw/access_ttl refresh_ttl code_ttl/) {
44 282 my $v = $self->$ttl;
45 282 ▶ Carp::croak "$ttl must be a positive integer"
Branch: 1 branch
BranchTrueFalseTotal
if not $v or $v <= 0 3 279 282
Condition100%3/3
not $v or $v <= 0
l!l&&r!l&&!r
21279
MC/DC100%2/2
not $v or $v <= 0
not $v $v <= 0
Truth table100%3/3
not(A) or B
A= not $vB= $v <= 0
ABresult
1X1
011
000
46 if !$v || $v <= 0;
47 }
48 92 state %ALLOWED_ALG = map { $_ => 1 } qw/HS256 HS384 HS512/;
49 Carp::croak 'jwt_alg must be one of HS256, HS384, HS512'
50 92 ▶ unless $ALLOWED_ALG{ $self->jwt_alg };
Branch: 1 branch
BranchTrueFalseTotal
unless $ALLOWED_ALG{$self->jwt_alg} 2 90 92
51 90 state %MIN_KEY_BYTES = ( HS256 => 32, HS384 => 48, HS512 => 64 );
52 Carp::croak sprintf(
53 'signing_key must be at least %d bytes for %s',
54 $MIN_KEY_BYTES{ $self->jwt_alg }, $self->jwt_alg )
55 90 ▶ if length( $self->signing_key ) < $MIN_KEY_BYTES{ $self->jwt_alg };
Branch: 1 branch
BranchTrueFalseTotal
if length $self->signing_key < $MIN_KEY_BYTES{$self->jwt_alg} 3 87 90
56 }
57  
58 # resource may be a scalar or arrayref; normalise to a list.
59 137 ▶sub _resource_list ( $self ) {
Subroutine _resource_list: called CC=4 SCAR=15.2
60 137 my $r = $self->resource;
61 137 ▶ return ref $r eq 'ARRAY' ? $r : defined $r && length $r ? [$r] : [];
Branch: 2 branches
BranchTrueFalseTotal
ref $r eq 'ARRAY' ? : 3 134 137
defined $r && length $r ? : 134 0 134
Condition33%1/3
defined $r and length $r
!ll&&!rl&&r
00134
MC/DC0%0/2
defined $r and length $r
defined $r length $r
Truth table33%1/3
A and B
A= defined $rB= length $r
ABresult
0X0
100
111
62 }
63  
64 156 ▶sub _now ( $self ) { return time }
Subroutine _now: called CC=1 SCAR=0.0
65  
66 # A URL-safe random token of $bytes entropy, base64url with no padding.
67 290 ▶sub _random_token ( $self, $bytes = 32 ) {
Subroutine _random_token: called CC=2 SCAR=6.9
68 290 my $b64 = encode_base64url( random_bytes($bytes) );
69 290 $b64 =~ s/=+\z//; # encode_base64url already drops padding; belt + braces
70 290 return $b64;
71 }
72  
73 # Mint a signed access-token JWT. Caller supplies sub + scope (+ any extras);
74 # the engine stamps iss, aud, iat, exp, jti.
75 45 ▶sub mint_access_token ( $self, $claims, $aud = undef ) {
Subroutine mint_access_token: called CC=5 SCAR=16.3
Pod documented
76 45 my $now = $self->_now;
77 # aud is the AUTHORIZED resource (from the code/refresh binding); fall back
78 # to the configured resource list only when the caller passes none.
79 my @aud =
80 45 ▶ !defined $aud ? @{ $self->_resource_list }
Branch: 2 branches
BranchTrueFalseTotal
!defined($aud) ? : 4 41 45
ref $aud eq 'ARRAY' ? : 0 41 41
81 : ref $aud eq 'ARRAY' ? @$aud
82 : ($aud);
83 45 ▶ my %payload = (
Branch: 1 branch
BranchTrueFalseTotal
@aud == 1 ? : 45 0 45
84 %$claims,
85 iss => $self->issuer,
86 aud => ( @aud == 1 ? $aud[0] : \@aud ),
87 iat => $now,
88 exp => $now + $self->access_ttl,
89 # Nothing reads jti yet. It exists so a revocation denylist can be
90 # added later without changing the token format for issued tokens.
91 jti => $self->_random_token(16),
92 );
93 45 return encode_jwt(
94 payload => \%payload,
95 alg => $self->jwt_alg,
96 key => $self->signing_key,
97 );
98 }
99  
100 # Authorize errors are redirect-safe only AFTER the client and redirect_uri
101 # have been validated (RFC 6749 4.1.2.1). Pass redirect_uri (+ state) for
102 # those so the seam can 302 the error back to the client; omit it for
103 # unknown-client / bad-redirect errors so the seam renders them directly and
104 # never redirects to an untrusted URI.
105 10 ▶sub _authz_error ( $self, $error, $desc, %opt ) {
Subroutine _authz_error: called CC=3 SCAR=11.0
106 Catalyst::Plugin::OAuth2::AuthorizationServer::Error->throw(
107 error => $error,
108 error_description => $desc,
109 ( exists $opt{redirect_uri} ? ( redirect_uri => $opt{redirect_uri} ) : () ),
110 10 ▶ ( exists $opt{state} ? ( state => $opt{state} ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
exists $opt{'redirect_uri'} ? : 7 3 10
exists $opt{'state'} ? : 7 3 10
111 http_status => 400,
112 );
113 }
114  
115 46 ▶sub validate_authorize ( $self, $params ) {
Subroutine validate_authorize: called CC=20 SCAR=30.3
Pod documented
116 46 my $state = $params->{state};
117  
118 # Client + redirect_uri first; their failures are NOT redirect-safe.
119 46 ▶ my $client = $self->store->find_client( $params->{client_id} // '' );
Condition50%1/2
$params->{"client_id"} // ""
l!l
460
MC/DC0%0/1
$params->{"client_id"} // ""
$params->{"client_id"}
Truth table50%1/2
A
A= $params->{"client_id"}
Aresult
11
00
120 46 ▶ $self->_authz_error( 'invalid_client', 'unknown client' ) unless $client;
Branch: 1 branch
BranchTrueFalseTotal
unless $client 2 44 46
121  
122 44 ▶ my $redirect = $params->{redirect_uri} // '';
Condition50%1/2
$params->{"redirect_uri"} // ""
l!l
440
MC/DC0%0/1
$params->{"redirect_uri"} // ""
$params->{"redirect_uri"}
Truth table50%1/2
A
A= $params->{"redirect_uri"}
Aresult
11
00
123 44 ▶ my $known = $client->{redirect_uris} || [];
Condition50%1/2
$client->{'redirect_uris'} || []
l!l
440
MC/DC0%0/1
$client->{'redirect_uris'} || []
$client->{'redirect_uris'}
Truth table50%1/2
A
A= $client->{'redirect_uris'}
Aresult
11
00
124 $self->_authz_error( 'invalid_client', 'redirect_uri mismatch' )
125 44 ▶ unless grep { $_ eq $redirect } @$known;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $redirect;} @$known 1 43 44
126  
127 # From here the redirect_uri is trusted, so further errors are redirect-safe.
128 43 my %rd = ( redirect_uri => $redirect, state => $state );
129  
130 $self->_authz_error( 'invalid_request', 'response_type must be code', %rd )
131 43 ▶ unless ( $params->{response_type} // '' ) eq 'code';
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"response_type"} // "") eq "code" 1 42 43
Condition50%1/2
$params->{"response_type"} // ""
l!l
430
MC/DC0%0/1
$params->{"response_type"} // ""
$params->{"response_type"}
Truth table50%1/2
A
A= $params->{"response_type"}
Aresult
11
00
132  
133 42 my $challenge = $params->{code_challenge};
134 42 ▶ $self->_authz_error( 'invalid_request', 'code_challenge required', %rd )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $challenge and length $challenge 1 41 42
Condition66%2/3
defined $challenge and length $challenge
!ll&&!rl&&r
1041
MC/DC50%1/2
defined $challenge and length $challenge
defined $challenge length $challenge
Truth table66%2/3
A and B
A= defined $challengeB= length $challenge
ABresult
0X0
100
111
135 unless defined $challenge && length $challenge;
136 $self->_authz_error( 'invalid_request', 'code_challenge_method must be S256', %rd )
137 41 ▶ unless ( $params->{code_challenge_method} // '' ) eq 'S256';
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"code_challenge_method"} // "") eq "S256" 1 40 41
Condition50%1/2
$params->{"code_challenge_method"} // ""
l!l
410
MC/DC0%0/1
$params->{"code_challenge_method"} // ""
$params->{"code_challenge_method"}
Truth table50%1/2
A
A= $params->{"code_challenge_method"}
Aresult
11
00
138 40 ▶ $self->_authz_error( 'invalid_request',
Branch: 1 branch
BranchTrueFalseTotal
unless $challenge =~ /\A[A-Za-z0-9_-]{43}\z/u 1 39 40
139 'code_challenge must be 43-character base64url (S256)', %rd )
140 unless $challenge =~ m{\A[A-Za-z0-9_-]{43}\z};
141  
142 39 my $scope = $params->{scope};
143 39 ▶ if ( defined $scope && length $scope && $self->scopes_supported ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scope and length $scope and $self->scopes_supported) 5 34 39
Condition83%5/6
defined $scope and length $scope and $self->scopes_supported
!ll&&!rl&&r
1335
defined $scope and length $scope
!ll&&!rl&&r
1038
MC/DC66%2/3
defined $scope and length $scope and $self->scopes_supported
defined $scope length $scope $self->scopes_supported
Truth table75%3/4
A and B and C
A= defined $scopeB= length $scopeC= $self->scopes_supported
ABCresult
0XX0
10X0
1100
1111
144 5 my %ok = map { $_ => 1 } @{ $self->scopes_supported };
145 5 for my $s ( split ' ', $scope ) {
146 $self->_authz_error( 'invalid_scope',
147 'one or more requested scopes are not supported', %rd )
148 6 ▶ unless $ok{$s};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok{$s} 2 4 6
149 }
150 }
151  
152 37 ▶ my $resource = $params->{resource} // '';
Condition50%1/2
$params->{"resource"} // ""
l!l
370
MC/DC0%0/1
$params->{"resource"} // ""
$params->{"resource"}
Truth table50%1/2
A
A= $params->{"resource"}
Aresult
11
00
153 37 my %valid_res = map { $_ => 1 } @{ $self->_resource_list };
154 $self->_authz_error( 'invalid_target', 'unknown resource', %rd )
155 37 ▶ unless $valid_res{$resource};
Branch: 1 branch
BranchTrueFalseTotal
unless $valid_res{$resource} 1 36 37
156  
157 36 my $rid = $self->_random_token(24);
158 my $data = {
159 client_id => $params->{client_id},
160 36 redirect_uri => $redirect,
161 response_type => 'code',
162 code_challenge => $challenge,
163 code_challenge_method => 'S256',
164 scope => $scope,
165 resource => $resource,
166 state => $state,
167 };
168 36 $self->store->save_authorization_request(
169 $rid, $data, $self->_now + 600 );
170 36 return { request_id => $rid };
171 }
172  
173 37 ▶sub issue_code ( $self, $subject, $request_id ) {
Subroutine issue_code: called CC=2 SCAR=6.9
Pod documented
174 37 my $req = $self->store->take_authorization_request( $request_id );
175 37 ▶ Catalyst::Plugin::OAuth2::AuthorizationServer::Error->throw(
Branch: 1 branch
BranchTrueFalseTotal
unless $req 2 35 37
176 error => 'invalid_request',
177 error_description => 'unknown or expired authorization request',
178 http_status => 400,
179 ) unless $req;
180  
181 35 my $code = $self->_random_token(32);
182 my $binding = {
183 client_id => $req->{client_id},
184 subject => $subject,
185 redirect_uri => $req->{redirect_uri},
186 code_challenge => $req->{code_challenge},
187 scope => $req->{scope},
188 resource => $req->{resource},
189 35 };
190 35 $self->store->create_auth_code(
191 $code, $binding, $self->_now + $self->code_ttl );
192  
193 return {
194 code => $code,
195 redirect_uri => $req->{redirect_uri},
196 state => $req->{state},
197 35 };
198 }
199  
200 28 ▶sub _grant_error ( $self, $desc ) {
Subroutine _grant_error: called CC=1 SCAR=0.0
201 28 Catalyst::Plugin::OAuth2::AuthorizationServer::Error->throw(
202 error => 'invalid_grant',
203 error_description => $desc,
204 http_status => 400,
205 );
206 }
207  
208 25 ▶sub _pkce_s256 ( $self, $verifier ) {
Subroutine _pkce_s256: called CC=1 SCAR=0.0
209 25 return encode_base64url( sha256($verifier) );
210 }
211  
212 # Constant-time string equality, so the PKCE challenge comparison does not
213 # leak a byte-prefix match via short-circuit timing.
214 25 ▶sub _ct_eq ( $self, $a, $b ) {
Subroutine _ct_eq: called CC=3 SCAR=11.1
215 25 ▶ return 0 unless length($a) == length($b);
Branch: 1 branch
BranchTrueFalseTotal
unless length $a == length $b 0 25 25
216 25 my $d = 0;
217 $d |= ord( substr $a, $_, 1 ) ^ ord( substr $b, $_, 1 )
218 25 for 0 .. length($a) - 1;
219 25 return $d == 0;
220 }
221  
222 73 ▶sub _hash_token ( $self, $raw ) { return sha256_hex($raw) }
Subroutine _hash_token: called CC=1 SCAR=0.0
223  
224 # Mint an access + refresh pair from a binding ({ subject, scope, ... }).
225 41 ▶sub _issue_token_pair ( $self, $binding ) {
Subroutine _issue_token_pair: called CC=6 SCAR=17.9
226 # Birth is the caller's job (see exchange_authorization_code); inheritance
227 # is the rotated binding's. Defaulting here with // would silently birth a
228 # new family per rotation, so revoke_family would revoke exactly one token
229 # and detection would look like it works while protecting nothing.
230 Carp::croak 'internal: _issue_token_pair requires a family_id'
231 41 ▶ unless defined $binding->{family_id} && length $binding->{family_id};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $binding->{"family_id"} and length $binding->{"family_id"} 1 40 41
Condition66%2/3
defined $binding->{"family_id"} and length $binding->{"family_id"}
!ll&&!rl&&r
1040
MC/DC50%1/2
defined $binding->{"family_id"} and length $binding->{"family_id"}
defined $binding->{"family_id"} length $binding->{"family_id"}
Truth table66%2/3
A and B
A= defined $binding->{"family_id"}B= length $binding->{"family_id"}
ABresult
0X0
100
111
232  
233 my $access = $self->mint_access_token(
234 {
235 sub => $binding->{subject},
236 ( defined $binding->{scope} ? ( scope => $binding->{scope} ) : () ),
237 },
238 $binding->{resource},
239 40 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
defined $binding->{'scope'} ? : 39 1 40
240 40 my $refresh = $self->_random_token(32);
241 my $created = $self->store->create_refresh_token(
242 $self->_hash_token($refresh),
243 {
244 client_id => $binding->{client_id},
245 subject => $binding->{subject},
246 scope => $binding->{scope},
247 resource => $binding->{resource},
248 family_id => $binding->{family_id},
249 },
250 40 $self->_now + $self->refresh_ttl,
251 );
252 # The family was revoked while this rotation was in flight: a concurrent
253 # replay was detected. Same generic error as any other dead token.
254 40 ▶ $self->_grant_error('unknown or revoked refresh token') unless $created;
Branch: 1 branch
BranchTrueFalseTotal
unless $created 1 39 40
255 return {
256 access_token => $access,
257 token_type => 'Bearer',
258 expires_in => $self->access_ttl,
259 refresh_token => $refresh,
260 39 ▶ ( defined $binding->{scope} ? ( scope => $binding->{scope} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
defined $binding->{'scope'} ? : 38 1 39
261 };
262 }
263  
264 37 ▶sub exchange_authorization_code ( $self, $params ) {
Subroutine exchange_authorization_code: called CC=13 SCAR=26.4
Pod documented
265 37 my $code = $params->{code};
266 37 ▶ $self->_grant_error('code is required')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code and length $code 0 37 37
Condition33%1/3
defined $code and length $code
!ll&&!rl&&r
0037
MC/DC0%0/2
defined $code and length $code
defined $code length $code
Truth table33%1/3
A and B
A= defined $codeB= length $code
ABresult
0X0
100
111
267 unless defined $code && length $code;
268  
269 37 my $binding = $self->store->consume_auth_code($code);
270 37 ▶ $self->_grant_error('unknown or used authorization code') unless $binding;
Branch: 1 branch
BranchTrueFalseTotal
unless $binding 3 34 37
271  
272 # When the request identifies its client, it must match the code's bound
273 # client (RFC 6749 4.1.3 defence-in-depth on top of PKCE).
274 34 ▶ if ( defined $params->{client_id} && length $params->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"client_id"} and length $params->{"client_id"}) 1 33 34
Condition66%2/3
defined $params->{"client_id"} and length $params->{"client_id"}
!ll&&!rl&&r
3301
MC/DC50%1/2
defined $params->{"client_id"} and length $params->{"client_id"}
defined $params->{"client_id"} length $params->{"client_id"}
Truth table66%2/3
A and B
A= defined $params->{"client_id"}B= length $params->{"client_id"}
ABresult
0X0
100
111
275 $self->_grant_error('client_id mismatch')
276 1 ▶ unless $params->{client_id} eq $binding->{client_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"client_id"} eq $binding->{"client_id"} 1 0 1
277 }
278  
279 $self->_grant_error('redirect_uri mismatch')
280 33 ▶ unless ( $params->{redirect_uri} // '' ) eq $binding->{redirect_uri};
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"redirect_uri"} // "") eq $binding->{"redirect_uri"} 1 32 33
Condition50%1/2
$params->{"redirect_uri"} // ""
l!l
330
MC/DC0%0/1
$params->{"redirect_uri"} // ""
$params->{"redirect_uri"}
Truth table50%1/2
A
A= $params->{"redirect_uri"}
Aresult
11
00
281  
282 32 my $verifier = $params->{code_verifier};
283 32 ▶ $self->_grant_error('code_verifier required')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $verifier and length $verifier 1 31 32
Condition66%2/3
defined $verifier and length $verifier
!ll&&!rl&&r
1031
MC/DC50%1/2
defined $verifier and length $verifier
defined $verifier length $verifier
Truth table66%2/3
A and B
A= defined $verifierB= length $verifier
ABresult
0X0
100
111
284 unless defined $verifier && length $verifier;
285 # RFC 7636 4.1: 43-128 characters of the unreserved set.
286 31 ▶ $self->_grant_error(
Branch: 1 branch
BranchTrueFalseTotal
unless $verifier =~ /\A[A-Za-z0-9._~-]{43,128}\z/u 6 25 31
287 'code_verifier must be 43-128 characters of [A-Za-z0-9._~-]')
288 unless $verifier =~ m{\A[A-Za-z0-9._~-]{43,128}\z};
289 $self->_grant_error('PKCE verification failed')
290 unless $self->_ct_eq( $self->_pkce_s256($verifier),
291 25 ▶ $binding->{code_challenge} );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_ct_eq($self->_pkce_s256($verifier), $binding->{"code_challenge"}) 1 24 25
292  
293 # A code exchange births a new family; a rotation inherits one.
294 24 return $self->_issue_token_pair(
295 { %$binding, family_id => $self->_random_token(16) } );
296 }
297  
298 32 ▶sub refresh ( $self, $params ) {
Subroutine refresh: called CC=10 SCAR=23.6
Pod documented
299 32 my $raw = $params->{refresh_token};
300 32 ▶ $self->_grant_error('refresh_token is required')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and length $raw 0 32 32
Condition33%1/3
defined $raw and length $raw
!ll&&!rl&&r
0032
MC/DC0%0/2
defined $raw and length $raw
defined $raw length $raw
Truth table33%1/3
A and B
A= defined $rawB= length $raw
ABresult
0X0
100
111
301 unless defined $raw && length $raw;
302  
303 32 my $result = $self->store->rotate_refresh_token( $self->_hash_token($raw) );
304 32 ▶ $self->_grant_error('unknown or revoked refresh token') unless $result;
Branch: 1 branch
BranchTrueFalseTotal
unless $result 3 29 32
305  
306 # RFC 9700: a replay means the chain is compromised and we cannot tell the
307 # legitimate client from the attacker, so the whole family goes. Revoke
308 # before erroring, and let a failing revoke_family surface as a 500: a
309 # Store that cannot revoke is broken, and answering invalid_grant while
310 # leaving the family alive fails the wrong way.
311 29 ▶ if ( $result->{reused} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"reused"}) 12 17 29
312 Carp::croak 'internal: reused refresh token binding has no family_id'
313 unless defined $result->{binding}{family_id}
314 12 ▶ && length $result->{binding}{family_id};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result->{"binding"}{"family_id"} and length $result->{"binding"}{"family_id"} 1 11 12
Condition66%2/3
defined $result->{"binding"}{"family_id"} and length $result->{"binding"}{"family_id"}
!ll&&!rl&&r
1011
MC/DC50%1/2
defined $result->{"binding"}{"family_id"} and length $result->{"binding"}{"family_id"}
defined $result->{"binding"}{"family_id"} length $result->{"binding"}{"family_id"}
Truth table66%2/3
A and B
A= defined $result->{"binding"}{"family_id"}B= length $result->{"binding"}{"family_id"}
ABresult
0X0
100
111
315 11 $self->store->revoke_family( $result->{binding}{family_id} );
316 # Same error and description as an unknown token: telling an attacker
317 # that reuse was detected confirms they hold a real token.
318 10 $self->_grant_error('unknown or revoked refresh token');
319 }
320  
321 17 my $binding = $result->{binding};
322  
323 # Mirror the code-exchange client binding check (RFC 6749 6).
324 17 ▶ if ( defined $params->{client_id} && length $params->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params->{"client_id"} and length $params->{"client_id"}) 1 16 17
Condition66%2/3
defined $params->{"client_id"} and length $params->{"client_id"}
!ll&&!rl&&r
1601
MC/DC50%1/2
defined $params->{"client_id"} and length $params->{"client_id"}
defined $params->{"client_id"} length $params->{"client_id"}
Truth table66%2/3
A and B
A= defined $params->{"client_id"}B= length $params->{"client_id"}
ABresult
0X0
100
111
325 $self->_grant_error('client_id mismatch')
326 1 ▶ unless $params->{client_id} eq $binding->{client_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"client_id"} eq $binding->{"client_id"} 1 0 1
327 }
328  
329 16 return $self->_issue_token_pair($binding);
330 }
331  
332 14 ▶sub _invalid_metadata ( $self, $desc ) {
Subroutine _invalid_metadata: called CC=1 SCAR=0.0
333 14 Catalyst::Plugin::OAuth2::AuthorizationServer::Error->throw(
334 error => 'invalid_client_metadata',
335 error_description => $desc,
336 http_status => 400,
337 );
338 }
339  
340 21 ▶sub metadata_document ( $self ) {
Subroutine metadata_document: called CC=2 SCAR=6.9
Pod documented
341 21 my %doc = (
342 issuer => $self->issuer,
343 authorization_endpoint => $self->authorize_endpoint,
344 token_endpoint => $self->token_endpoint,
345 registration_endpoint => $self->registration_endpoint,
346 response_types_supported => ['code'],
347 grant_types_supported => [ 'authorization_code', 'refresh_token' ],
348 code_challenge_methods_supported => ['S256'],
349 token_endpoint_auth_methods_supported => ['none'],
350 );
351 21 ▶ $doc{scopes_supported} = $self->scopes_supported if $self->scopes_supported;
Branch: 1 branch
BranchTrueFalseTotal
if $self->scopes_supported 6 15 21
352 21 return \%doc;
353 }
354  
355 24 ▶sub register_client ( $self, $metadata ) {
Subroutine register_client: called CC=19 SCAR=30.5
Pod documented
356 24 my $uris = $metadata->{redirect_uris};
357 24 ▶ $self->_invalid_metadata('redirect_uris is required')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $uris eq "ARRAY" and @$uris 1 23 24
Condition66%2/3
ref $uris eq "ARRAY" and @$uris
!ll&&!rl&&r
1023
MC/DC50%1/2
ref $uris eq "ARRAY" and @$uris
ref $uris eq "ARRAY" @$uris
Truth table66%2/3
A and B
A= ref $uris eq "ARRAY"B= @$uris
ABresult
0X0
100
111
358 unless ref $uris eq 'ARRAY' && @$uris;
359 23 ▶ $self->_invalid_metadata('too many redirect_uris')
Branch: 1 branch
BranchTrueFalseTotal
if @$uris > $self->redirect_uris_max 1 22 23
360 if @$uris > $self->redirect_uris_max;
361 22 for my $u (@$uris) {
362 22 ▶ $self->_invalid_metadata('redirect_uri not a string')
Branch: 1 branch
BranchTrueFalseTotal
if ref $u or not defined $u or not length $u 0 22 22
Condition33%2/6
ref $u or not defined $u or not length $u
l!l&&r!l&&!r
0022
ref $u or not defined $u
l!l&&r!l&&!r
0022
MC/DC0%0/3
ref $u or not defined $u or not length $u
ref $u not defined $u not length $u
Truth table25%1/4
A or not(B) or not(C)
A= ref $uB= not defined $uC= not length $u
ABCresult
1XX1
01X1
0011
0000
363 if ref $u || !defined $u || !length $u;
364 22 ▶ $self->_invalid_metadata('redirect_uri too long')
Branch: 1 branch
BranchTrueFalseTotal
if length $u > $self->redirect_uri_max_length 1 21 22
365 if length $u > $self->redirect_uri_max_length;
366  
367 21 my $parsed = URI->new($u);
368 21 ▶ my $scheme = lc( $parsed->scheme // '' );
Condition50%1/2
$parsed->scheme // ""
l!l
210
MC/DC0%0/1
$parsed->scheme // ""
$parsed->scheme
Truth table50%1/2
A
A= $parsed->scheme
Aresult
11
00
369 21 ▶ my $ok_scheme =
Branch: 2 branches
BranchTrueFalseTotal
$scheme eq 'https' ? : 18 3 21
$scheme eq 'http' && $parsed->can('host') && ($parsed->host // '') =~ /\A(?:localhost|127\.\d+\.\d+\.\d+|::1)\z/u ? : 1 2 3
Condition75%6/8
$scheme eq "http" and $parsed->can("host") and ($parsed->host // "") =~ /\A(?:localhost|127\.\d+\.\d+\.\d+|::1)\z/u
!ll&&!rl&&r
111
$scheme eq "http" and $parsed->can("host")
!ll&&!rl&&r
102
$parsed->host // ""
l!l
20
MC/DC33%1/3
$scheme eq "http" and $parsed->can("host") and ($parsed->host // "") =~ /\A(?:localhost|127\.\d+\.\d+\.\d+|::1)\z/u
$scheme eq "http" $parsed->can("host") $parsed->host
Truth table50%2/4
A and B and C
A= $scheme eq "http"B= $parsed->can("host")C= $parsed->host
ABCresult
0XX0
10X0
1100
1111
370 $scheme eq 'https' ? 1
371 : $scheme eq 'http'
372 && $parsed->can('host')
373 && ( $parsed->host // '' )
374 =~ m{\A(?:localhost|127\.\d+\.\d+\.\d+|::1)\z} ? 1
375 : 0;
376 21 ▶ $self->_invalid_metadata('redirect_uri scheme not allowed')
Branch: 1 branch
BranchTrueFalseTotal
unless $ok_scheme 2 19 21
377 unless $ok_scheme;
378 19 ▶ $self->_invalid_metadata('redirect_uri must not contain a fragment')
Branch: 1 branch
BranchTrueFalseTotal
if $parsed->can("fragment") and defined $parsed->fragment 1 18 19
Condition66%2/3
$parsed->can("fragment") and defined $parsed->fragment
!ll&&!rl&&r
0181
MC/DC50%1/2
$parsed->can("fragment") and defined $parsed->fragment
$parsed->can("fragment") defined $parsed->fragment
Truth table66%2/3
A and B
A= $parsed->can("fragment")B= defined $parsed->fragment
ABresult
0X0
100
111
379 if $parsed->can('fragment') && defined $parsed->fragment;
380 }
381  
382 18 $self->_validate_client_metadata($metadata);
383  
384 11 my $json = JSON::MaybeXS->new( utf8 => 1, canonical => 1 );
385 11 ▶ $self->_invalid_metadata('client metadata too large')
Branch: 1 branch
BranchTrueFalseTotal
if length $json->encode($metadata) > $self->metadata_max_bytes 1 10 11
386 if length( $json->encode($metadata) ) > $self->metadata_max_bytes;
387  
388 10 my $client = { %$metadata, client_id => $self->_random_token(16) };
389 10 return $self->store->create_client($client);
390 }
391  
392 # RFC 7591 3.2.1: reject a registration whose metadata asks for something this
393 # AS does not support. The allow-lists are read straight off metadata_document,
394 # so registration can never accept a value discovery does not advertise. Fields
395 # RFC 7591 leaves free-form (client_name, logo_uri, contacts, extensions, and
396 # scope when no scopes_supported is configured) are left alone: a value is only
397 # rejected where the AS has actually declared what it supports.
398 18 ▶sub _validate_client_metadata ( $self, $metadata ) {
Subroutine _validate_client_metadata: called CC=19 SCAR=29.7
399 18 my $doc = $self->metadata_document;
400  
401 18 ▶ if ( exists $metadata->{token_endpoint_auth_method} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $metadata->{"token_endpoint_auth_method"}) 3 15 18
402 3 my $method = $metadata->{token_endpoint_auth_method};
403 3 my %ok = map { $_ => 1 }
404 3 @{ $doc->{token_endpoint_auth_methods_supported} };
405 $self->_invalid_metadata('unsupported token_endpoint_auth_method')
406 3 ▶ if ref $method || !defined $method || !$ok{$method};
Branch: 1 branch
BranchTrueFalseTotal
if ref $method or not defined $method or not $ok{$method} 1 2 3
Condition50%3/6
ref $method or not defined $method or not $ok{$method}
l!l&&r!l&&!r
012
ref $method or not defined $method
l!l&&r!l&&!r
003
MC/DC33%1/3
ref $method or not defined $method or not $ok{$method}
ref $method not defined $method not $ok{$method}
Truth table50%2/4
A or not(B) or not(C)
A= ref $methodB= not defined $methodC= not $ok{$method}
ABCresult
1XX1
01X1
0011
0000
407 }
408  
409 17 for my $field (qw/grant_types response_types/) {
410 30 ▶ next unless exists $metadata->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $metadata->{$field} 21 9 30
411 9 my $values = $metadata->{$field};
412 9 ▶ $self->_invalid_metadata(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "ARRAY" and @$values 2 7 9
Condition100%3/3
ref $values eq "ARRAY" and @$values
!ll&&!rl&&r
117
MC/DC100%2/2
ref $values eq "ARRAY" and @$values
ref $values eq "ARRAY" @$values
Truth table100%3/3
A and B
A= ref $values eq "ARRAY"B= @$values
ABresult
0X0
100
111
413 "$field must be a non-empty array of strings")
414 unless ref $values eq 'ARRAY' && @$values;
415 7 my %ok = map { $_ => 1 } @{ $doc->{"${field}_supported"} };
416 7 for my $v (@$values) {
417 $self->_invalid_metadata("unsupported $field value")
418 10 ▶ if ref $v || !defined $v || !$ok{$v};
Branch: 1 branch
BranchTrueFalseTotal
if ref $v or not defined $v or not $ok{$v} 3 7 10
Condition83%5/6
ref $v or not defined $v or not $ok{$v}
l!l&&r!l&&!r
127
ref $v or not defined $v
l!l&&r!l&&!r
109
MC/DC66%2/3
ref $v or not defined $v or not $ok{$v}
ref $v not defined $v not $ok{$v}
Truth table75%3/4
A or not(B) or not(C)
A= ref $vB= not defined $vC= not $ok{$v}
ABCresult
1XX1
01X1
0011
0000
419 }
420 }
421  
422 # scope is only constrained when the AS advertises scopes_supported.
423 12 ▶ if ( exists $metadata->{scope} && $self->scopes_supported ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $metadata->{"scope"} and $self->scopes_supported) 3 9 12
Condition100%3/3
exists $metadata->{"scope"} and $self->scopes_supported
!ll&&!rl&&r
813
MC/DC100%2/2
exists $metadata->{"scope"} and $self->scopes_supported
exists $metadata->{"scope"} $self->scopes_supported
Truth table100%3/3
A and B
A= exists $metadata->{"scope"}B= $self->scopes_supported
ABresult
0X0
100
111
424 3 my $scope = $metadata->{scope};
425 3 ▶ $self->_invalid_metadata('scope must be a string')
Branch: 1 branch
BranchTrueFalseTotal
if ref $scope or not defined $scope 0 3 3
Condition33%1/3
ref $scope or not defined $scope
l!l&&r!l&&!r
003
MC/DC0%0/2
ref $scope or not defined $scope
ref $scope not defined $scope
Truth table33%1/3
A or not(B)
A= ref $scopeB= not defined $scope
ABresult
1X1
011
000
426 if ref $scope || !defined $scope;
427 3 my %ok = map { $_ => 1 } @{ $self->scopes_supported };
428 3 for my $s ( split ' ', $scope ) {
429 $self->_invalid_metadata(
430 'one or more requested scopes are not supported')
431 4 ▶ unless $ok{$s};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok{$s} 1 3 4
432 }
433 }
434 11 return;
435 }
436  
437 =head1 NAME
438  
439 Catalyst::Plugin::OAuth2::AuthorizationServer::Server - Pure-logic OAuth 2.1
440 Authorization Server engine
441  
442 =head1 DESCRIPTION
443  
444 The pure-logic OAuth 2.1 engine behind the Catalyst seam. Holds the Store
445 reference, the signing key, and configuration; is otherwise stateless (the
446 only mutable state lives in the injected Store).
447  
448 Access tokens are signed with a symmetric HMAC algorithm only: C<jwt_alg> may
449 be C<HS256> (the default), C<HS384> or C<HS512>. Asymmetric signing (C<RS*>,
450 C<ES*>, C<PS*>) and C<alg=none> are not supported, and no JWKS is published:
451 this is deliberate for the MCP single-server profile, where the Authorization
452 Server and Resource Server share one deployment and one key. C<signing_key>
453 must be at least as long as the algorithm's hash output (32, 48 or 64 bytes
454 respectively, per RFC 7518 3.2); a shorter key is rejected at construction.
455  
456 =head1 METHODS
457  
458 =head2 mint_access_token( \%claims, $aud )
459  
460 Mint a signed JWT access token. The engine stamps C<iss>, C<aud>, C<iat>,
461 C<exp> and C<jti>, and they are stamped after C<\%claims>, so a caller cannot
462 override them. C<$aud> defaults to the configured C<resource> list. Returns the
463 encoded JWT string.
464  
465 =head2 register_client( \%metadata )
466  
467 Dynamic Client Registration (RFC 7591). Validates C<redirect_uris> (must be
468 present; each must be HTTPS or loopback HTTP; no fragments; within length
469 limits). Generates a C<client_id>, calls C<Store::create_client>, and returns
470 the stored client hashref.
471  
472 Per RFC 7591 3.2.1, registration also rejects metadata asking for anything
473 this AS does not support, with C<invalid_client_metadata>. The allow-lists are
474 taken from L</metadata_document>, so registration can never accept a value the
475 discovery document does not advertise:
476  
477 =over
478  
479 =item *
480  
481 C<token_endpoint_auth_method> must be one of
482 C<token_endpoint_auth_methods_supported> (C<none>: this profile registers
483 public PKCE clients, so C<client_secret_basic> and friends are rejected).
484  
485 =item *
486  
487 C<grant_types> must be a non-empty arrayref, each value one of
488 C<grant_types_supported> (C<authorization_code>, C<refresh_token>).
489  
490 =item *
491  
492 C<response_types> must be a non-empty arrayref, each value one of
493 C<response_types_supported> (C<code>).
494  
495 =item *
496  
497 C<scope> is checked against C<scopes_supported> B<only> when the AS is
498 configured with one; with no C<scopes_supported> the server declares no
499 constraint, so C<scope> is left free-form.
500  
501 =back
502  
503 Everything else RFC 7591 leaves free-form (C<client_name>, C<client_uri>,
504 C<logo_uri>, C<contacts>, C<software_id>, extension fields) is stored as
505 given and never rejected merely for being present.
506  
507 =head2 validate_authorize( \%params )
508  
509 Validate an authorization request (RFC 6749 4.1.1 + PKCE RFC 7636). Checks
510 client, redirect_uri, response_type, code_challenge (must be a 43-character
511 base64url string), code_challenge_method (must be C<S256>), scope, and
512 resource. On success, stashes the request via
513 C<Store::save_authorization_request> and returns C<{ request_id }>.
514  
515 =head2 issue_code( $subject, $request_id )
516  
517 Atomically consume the stashed authorization request and mint a single-use
518 authorization code bound to C<$subject>. Returns C<{ code, redirect_uri,
519 state }>. Throws C<invalid_request> if the request is unknown or expired.
520  
521 =head2 exchange_authorization_code( \%params )
522  
523 Authorization-code grant (RFC 6749 4.1.3). Validates code, redirect_uri,
524 client_id binding, and PKCE verifier. Returns C<{ access_token, token_type,
525 expires_in, refresh_token }> (plus C<scope> if the request carried one).
526  
527 =head2 refresh( \%params )
528  
529 Refresh-token grant (RFC 6749 6). Rotates the refresh token via
530 C<Store::rotate_refresh_token> and mints a new access + refresh pair.
531 Optionally validates a C<client_id> parameter against the binding.
532  
533 =head2 metadata_document
534  
535 Return the RFC 8414 Authorization Server Metadata hashref.
536  
537 =cut
538  
539 9 1;
↑ Summary AuthorizationServer.pm »