ResourceServer.pm

filter: Statementstmt 96.9% 127 / 131 Branchbran 79.4% 54 / 68 Conditioncond 63.3% 38 / 60 MC/DCmcdc 43.2% 16 / 37 Subroutinesub 100% 23 / 23 Podpod 100% 7 / 7 totaltotal 81.2% 265 / 326 CC 59 SCAR 23.8
CC
59
Cov
85%
oauth_challenge
23.4
_oauth_rs_metadata_url
13.6
oauth_protect
9.4
CRAP 10.8
↑ Summary ResourceServer/Server.pm »
1 package Catalyst::Plugin::OAuth2::ResourceServer;
2 4 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 4 ▶use Scalar::Util qw/blessed/;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use URI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Catalyst::Plugin::OAuth2::ResourceServer::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Catalyst::Plugin::OAuth2::ResourceServer::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 our $VERSION = '0.003';
11  
12 4 my $CONFIG_KEY = 'Catalyst::Plugin::OAuth2::ResourceServer';
13 4 my $SLOT = 'Catalyst::Plugin::OAuth2::ResourceServer/ctx';
14 4 my $JSON = JSON::MaybeXS->new( utf8 => 1, canonical => 1 );
15  
16 16 ▶sub _oauth_rs_config ( $c ) { return $c->config->{$CONFIG_KEY} // {} }
Subroutine _oauth_rs_config: called CC=2 SCAR=7.6
Condition50%1/2
$c->config->{$CONFIG_KEY} // {}
l!l
160
MC/DC0%0/1
$c->config->{$CONFIG_KEY} // {}
$c->config->{$CONFIG_KEY}
Truth table50%1/2
A
A= $c->config->{$CONFIG_KEY}
Aresult
11
00
17  
18 # RFC 7230 quoted-string: backslash-escape `\` and `"` so a value carrying
19 # either cannot terminate the quoted-string or forge extra auth-params.
20 # A plain function, not a method.
21 18 ▶sub _oauth_rs_quote_hval ( $value ) {
Subroutine _oauth_rs_quote_hval: called CC=2 SCAR=6.9
22 18 ▶ my $v = $value // '';
Condition100%2/2
$value // ""
l!l
171
MC/DC100%1/1
$value // ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
23 18 $v =~ s/([\\"])/\\$1/g;
24 18 return $v;
25 }
26  
27 # RFC 9728 3.1: derive the protected-resource metadata URL from the resource
28 # identifier by inserting the well-known segment after the authority, before
29 # the resource's path. This is only defined for an http(s) resource id: for a
30 # URN or any other non-hierarchical scheme there is no authority to insert
31 # after, so return undef and let the caller omit the parameter rather than
32 # emit a malformed one. A plain function, not a method.
33 12 ▶sub _oauth_rs_metadata_url ( $base ) {
Subroutine _oauth_rs_metadata_url: called CC=12 SCAR=26.1
34 12 ▶ return undef unless defined $base && length $base;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $base and length $base 2 10 12
Condition100%3/3
defined $base and length $base
!ll&&!rl&&r
1110
MC/DC100%2/2
defined $base and length $base
defined $base length $base
Truth table100%3/3
A and B
A= defined $baseB= length $base
ABresult
0X0
100
111
35 10 my $u = URI->new($base);
36 10 ▶ return undef unless $u->can('scheme') && defined $u->scheme;
Branch: 1 branch
BranchTrueFalseTotal
unless $u->can("scheme") and defined $u->scheme 1 9 10
Condition66%2/3
$u->can("scheme") and defined $u->scheme
!ll&&!rl&&r
019
MC/DC50%1/2
$u->can("scheme") and defined $u->scheme
$u->can("scheme") defined $u->scheme
Truth table66%2/3
A and B
A= $u->can("scheme")B= defined $u->scheme
ABresult
0X0
100
111
37 9 ▶ return undef unless $u->scheme =~ /\A https? \z/xi;
Branch: 1 branch
BranchTrueFalseTotal
unless $u->scheme =~ /\A https? \z/iux 5 4 9
38 4 ▶ return undef unless $u->can('authority') && $u->can('path');
Branch: 1 branch
BranchTrueFalseTotal
unless $u->can("authority") and $u->can("path") 0 4 4
Condition33%1/3
$u->can("authority") and $u->can("path")
!ll&&!rl&&r
004
MC/DC0%0/2
$u->can("authority") and $u->can("path")
$u->can("authority") $u->can("path")
Truth table33%1/3
A and B
A= $u->can("authority")B= $u->can("path")
ABresult
0X0
100
111
39 4 ▶ return undef unless defined $u->authority && length $u->authority;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u->authority and length $u->authority 0 4 4
Condition33%1/3
defined $u->authority and length $u->authority
!ll&&!rl&&r
004
MC/DC0%0/2
defined $u->authority and length $u->authority
defined $u->authority length $u->authority
Truth table33%1/3
A and B
A= defined $u->authorityB= length $u->authority
ABresult
0X0
100
111
40 4 ▶ my $path = $u->path // '';
Condition50%1/2
$u->path // ""
l!l
40
MC/DC0%0/1
$u->path // ""
$u->path
Truth table50%1/2
A
A= $u->path
Aresult
11
00
41 4 ▶ $path = '' if $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/" 1 3 4
42 4 $u->path( '/.well-known/oauth-protected-resource' . $path );
43 4 return $u->as_string;
44 }
45  
46 # Per-request engine built from config. Only the engine's own attrs are passed
47 # (StrictConstructor rejects the seam/metadata-only keys).
48 9 ▶sub _oauth_rs_engine ( $c ) {
Subroutine _oauth_rs_engine: called CC=2 SCAR=6.9
49 9 my $cfg = $c->_oauth_rs_config;
50 return Catalyst::Plugin::OAuth2::ResourceServer::Server->new(
51 9 ▶ map { exists $cfg->{$_} ? ( $_ => $cfg->{$_} ) : () }
Branch: 1 branch
BranchTrueFalseTotal
exists $cfg->{$_} ? : 27 18 45
52 qw/signing_key resource issuer jwt_alg leeway/
53 );
54 }
55  
56 # Write a WWW-Authenticate: Bearer challenge. $err is an optional ...::Error.
57 8 ▶sub oauth_challenge ( $c, $err = undef ) {
Subroutine oauth_challenge: called CC=22 SCAR=31.5
Pod documented
58 8 ▶ my $status = ( $err && $err->http_status ) ? $err->http_status : 401;
Branch: 1 branch
BranchTrueFalseTotal
$err && $err->http_status ? : 5 3 8
Condition66%2/3
$err and $err->http_status
!ll&&!rl&&r
305
MC/DC50%1/2
$err and $err->http_status
$err $err->http_status
Truth table66%2/3
A and B
A= $errB= $err->http_status
ABresult
0X0
100
111
59 8 my @p;
60 8 ▶ push @p, sprintf( 'error="%s"', _oauth_rs_quote_hval( $err->error ) )
Branch: 1 branch
BranchTrueFalseTotal
if $err and defined $err->error 5 3 8
Condition66%2/3
$err and defined $err->error
!ll&&!rl&&r
305
MC/DC50%1/2
$err and defined $err->error
$err defined $err->error
Truth table66%2/3
A and B
A= $errB= defined $err->error
ABresult
0X0
100
111
61 if $err && defined $err->error;
62 8 ▶ push @p,
Branch: 1 branch
BranchTrueFalseTotal
if $err and defined $err->error_description 2 6 8
Condition100%3/3
$err and defined $err->error_description
!ll&&!rl&&r
332
MC/DC100%2/2
$err and defined $err->error_description
$err defined $err->error_description
Truth table100%3/3
A and B
A= $errB= defined $err->error_description
ABresult
0X0
100
111
63 sprintf( 'error_description="%s"',
64 _oauth_rs_quote_hval( $err->error_description ) )
65 if $err && defined $err->error_description;
66 8 ▶ push @p, sprintf( 'scope="%s"', _oauth_rs_quote_hval( $err->scope ) )
Branch: 1 branch
BranchTrueFalseTotal
if $err and defined $err->scope 1 7 8
Condition100%3/3
$err and defined $err->scope
!ll&&!rl&&r
341
MC/DC100%2/2
$err and defined $err->scope
$err defined $err->scope
Truth table100%3/3
A and B
A= $errB= defined $err->scope
ABresult
0X0
100
111
67 if $err && defined $err->scope;
68 8 ▶ if ( $status == 401 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 401) 6 2 8
69 6 my $cfg = $c->_oauth_rs_config;
70 my $base = ref $cfg->{resource} eq 'ARRAY'
71 ? ( $cfg->{resource}[0] // '' )
72 6 ▶ : ( $cfg->{resource} // '' );
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'resource'} eq 'ARRAY' ? : 0 6 6
Condition25%1/4
$cfg->{"resource"}[0] // ""
l!l
00
$cfg->{"resource"} // ""
l!l
60
MC/DC0%0/1
$cfg->{"resource"}[0] // ""
$cfg->{"resource"}[0]
MC/DC0%0/1
$cfg->{"resource"} // ""
$cfg->{"resource"}
Truth table0%0/2
A
A= $cfg->{"resource"}[0]
Aresult
11
00
Truth table50%1/2
A
A= $cfg->{"resource"}
Aresult
11
00
73 # An explicit override always wins; otherwise derive it, which only
74 # works for an http(s) resource id.
75 6 ▶ my $url = $cfg->{resource_metadata_url} // _oauth_rs_metadata_url($base);
Condition66%2/3
$cfg->{"resource_metadata_url"} // _oauth_rs_metadata_url($base)
l!l&&r!l&&!r
402
MC/DC50%1/2
$cfg->{"resource_metadata_url"} // _oauth_rs_metadata_url($base)
$cfg->{"resource_metadata_url"} _oauth_rs_metadata_url($base)
Truth table66%2/3
A // B
A= $cfg->{"resource_metadata_url"}B= _oauth_rs_metadata_url($base)
ABresult
1X1
011
000
76 6 ▶ if ( defined $url && length $url ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $url and length $url) { } 4 2 6
Condition66%2/3
defined $url and length $url
!ll&&!rl&&r
204
MC/DC50%1/2
defined $url and length $url
defined $url length $url
Truth table66%2/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
77 4 push @p,
78 sprintf( 'resource_metadata="%s"', _oauth_rs_quote_hval($url) );
79 }
80 else {
81 # Warn once per process: omitting the parameter is correct, but the
82 # deployer probably wants to set resource_metadata_url explicitly.
83 2 state $warned = 0;
84 2 ▶ $c->log->warn( 'OAuth2 RS: cannot derive resource_metadata from a '
Branch: 1 branch
BranchTrueFalseTotal
if not $warned++ and $c->can("log") 1 1 2
Condition66%2/3
not $warned++ and $c->can("log")
!ll&&!rl&&r
101
MC/DC50%1/2
not $warned++ and $c->can("log")
not $warned++ $c->can("log")
Truth table66%2/3
not(A) and B
A= not $warned++B= $c->can("log")
ABresult
0X0
100
111
85 . 'non-http(s) resource identifier; set resource_metadata_url '
86 . 'explicitly to advertise it in 401 challenges' )
87 if !$warned++ && $c->can('log');
88 }
89 }
90 8 ▶ my $hdr = 'Bearer' . ( @p ? ' ' . join( ', ', @p ) : '' );
Branch: 1 branch
BranchTrueFalseTotal
@p ? : 7 1 8
91  
92 8 my $res = $c->response;
93 8 $res->status($status);
94 8 $res->header( 'WWW-Authenticate' => $hdr );
95 8 $res->header( 'Cache-Control' => 'no-store' );
96 8 $res->content_type('application/json');
97 8 ▶ $res->body(
Branch: 1 branch
BranchTrueFalseTotal
$err && defined $err->error ? : 5 3 8
Condition66%2/3
$err and defined $err->error
!ll&&!rl&&r
305
MC/DC50%1/2
$err and defined $err->error
$err defined $err->error
Truth table66%2/3
A and B
A= $errB= defined $err->error
ABresult
0X0
100
111
98 $JSON->encode( { ( $err && defined $err->error ) ? ( error => $err->error ) : () } ) );
99 8 return;
100 }
101  
102 13 ▶sub oauth_protect ( $c ) {
Subroutine oauth_protect: called CC=9 SCAR=22.4
Pod documented
103 13 ▶ my $auth = $c->request->header('Authorization') // '';
Condition100%2/2
$c->request->header("Authorization") // ""
l!l
112
MC/DC100%1/1
$c->request->header("Authorization") // ""
$c->request->header("Authorization")
Truth table100%2/2
A
A= $c->request->header("Authorization")
Aresult
11
00
104 # RFC 7235 auth-scheme names are case-insensitive.
105 13 my ($jwt) = $auth =~ /\A Bearer \s+ (\S+) \z/xi;
106 13 ▶ unless ( defined $jwt && length $jwt ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $jwt and length $jwt) 4 9 13
Condition66%2/3
defined $jwt and length $jwt
!ll&&!rl&&r
409
MC/DC50%1/2
defined $jwt and length $jwt
defined $jwt length $jwt
Truth table66%2/3
A and B
A= defined $jwtB= length $jwt
ABresult
0X0
100
111
107 # RFC 6750 section 3: a malformed *Bearer* attempt is invalid_request; an
108 # absent header or a different/unsupported scheme gets a bare 401.
109 4 ▶ if ( $auth =~ /\A \s* Bearer \b/xi ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth =~ /\A \s* Bearer \b/iux) { } 1 3 4
110 1 $c->oauth_challenge(
111 Catalyst::Plugin::OAuth2::ResourceServer::Error->new(
112 error => 'invalid_request', http_status => 400 ) );
113 }
114 else {
115 3 $c->oauth_challenge; # no credentials -> plain 401
116 }
117 4 return 0;
118 }
119  
120 # Token verification: a structured Error is a token failure (-> its 401);
121 # anything else (engine misconfig, internal bug) is a 500, never invalid_token.
122 9 my $verified = 1;
123 9 ▶ my $claims = try {
Subroutine __ANON__: called CC=1 SCAR=0.0
124 9 $c->_oauth_rs_engine->verify_token($jwt);
125 }
126 2 ▶ catch {
Subroutine __ANON__: called CC=4 SCAR=18.7
127 2 ▶ if ( blessed $_
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($_) and $_->isa('Catalyst::Plugin::OAuth2::ResourceServer::Error')) { } 2 0 2
Condition33%1/3
builtin::blessed($_) and $_->isa("Catalyst::Plugin::OAuth2::ResourceServer::Error")
!ll&&!rl&&r
002
MC/DC0%0/2
builtin::blessed($_) and $_->isa("Catalyst::Plugin::OAuth2::ResourceServer::Error")
builtin::blessed($_) $_->isa("Catalyst::Plugin::OAuth2::ResourceServer::Error")
Truth table33%1/3
A and B
A= builtin::blessed($_)B= $_->isa("Catalyst::Plugin::OAuth2::ResourceServer::Error")
ABresult
0X0
100
111
128 && $_->isa('Catalyst::Plugin::OAuth2::ResourceServer::Error') )
129 {
130 2 $c->oauth_challenge($_);
131 }
132 else {
133 # Deliberately a fixed string: this path is credential-adjacent and
134 # the exception could carry token material.
135 0 ▶ $c->log->error('OAuth2 RS: token verification failed')
Branch: 1 branch
BranchTrueFalseTotal
if $c->can("log") 0 0 0
136 if $c->can('log');
137 0 $c->_oauth_server_error;
138 }
139 2 $verified = 0;
140 2 undef;
141 9 };
142 9 ▶ return 0 unless $verified;
Branch: 1 branch
BranchTrueFalseTotal
unless $verified 2 7 9
143  
144 # Subject resolution is an app hook; a die in it is an internal error (500),
145 # NOT an invalid_token. An undef return means the subject is rejected (401).
146 7 my $identity;
147 7 ▶ if ( $c->can('oauth_resolve_subject') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->can("oauth_resolve_subject")) 7 0 7
148 7 my $resolved = 1;
149 7 ▶ $identity = try {
Subroutine __ANON__: called CC=1 SCAR=0.0
150 7 $c->oauth_resolve_subject($claims);
151 }
152 2 ▶ catch {
Subroutine __ANON__: called CC=2 SCAR=7.0
153 # Fixed string for the same reason as the verify_token catch above:
154 # the hook is handed the verified claims, so an exception raised in
155 # it can carry them into the log. The host app is better placed to
156 # log its own failure detail than we are to guess what is safe.
157 2 ▶ $c->log->error('OAuth2 RS: oauth_resolve_subject died')
Branch: 1 branch
BranchTrueFalseTotal
if $c->can("log") 2 0 2
158 if $c->can('log');
159 2 $c->_oauth_server_error;
160 2 $resolved = 0;
161 2 undef;
162 7 };
163 7 ▶ return 0 unless $resolved;
Branch: 1 branch
BranchTrueFalseTotal
unless $resolved 2 5 7
164 5 ▶ unless ($identity) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($identity) 1 4 5
165 # subject rejected -> generic 401 (no account-state leak)
166 1 $c->oauth_challenge(
167 Catalyst::Plugin::OAuth2::ResourceServer::Error->new(
168 error => 'invalid_token', http_status => 401 ) );
169 1 return 0;
170 }
171 }
172  
173 4 $c->stash->{$SLOT} = { claims => $claims, identity => $identity };
174 4 return 1;
175 }
176  
177 # Render a clean 500 for an internal/operational failure (engine misconfig, a
178 # die in an app hook): never leak the underlying reason to the client.
179 2 ▶sub _oauth_server_error ( $c ) {
Subroutine _oauth_server_error: called CC=1 SCAR=0.0
180 2 my $res = $c->response;
181 2 $res->status(500);
182 2 $res->content_type('application/json');
183 2 $res->header( 'Cache-Control' => 'no-store' );
184 2 $res->body( $JSON->encode( { error => 'server_error' } ) );
185 2 return;
186 }
187  
188 7 ▶sub oauth_claims ( $c ) { return ( $c->stash->{$SLOT} // {} )->{claims} }
Subroutine oauth_claims: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
$c->stash->{$SLOT} // {}
l!l
70
MC/DC0%0/1
$c->stash->{$SLOT} // {}
$c->stash->{$SLOT}
Truth table50%1/2
A
A= $c->stash->{$SLOT}
Aresult
11
00
189 3 ▶sub oauth_identity ( $c ) { return ( $c->stash->{$SLOT} // {} )->{identity} }
Subroutine oauth_identity: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
$c->stash->{$SLOT} // {}
l!l
30
MC/DC0%0/1
$c->stash->{$SLOT} // {}
$c->stash->{$SLOT}
Truth table50%1/2
A
A= $c->stash->{$SLOT}
Aresult
11
00
190  
191 7 ▶sub oauth_scopes ( $c ) {
Subroutine oauth_scopes: called CC=5 SCAR=16.6
Pod documented
192 7 ▶ my $claims = $c->oauth_claims or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $claims = $c->oauth_claims or return () 7 0 7
193 7 my $s = $claims->{scope};
194 7 ▶ return () unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 7 7
195 7 ▶ return @$s if ref $s eq 'ARRAY'; # some ASes emit scope as a JSON array
Branch: 1 branch
BranchTrueFalseTotal
if ref $s eq "ARRAY" 2 5 7
196 5 ▶ return () unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 0 5 5
197 5 return split ' ', $s;
198 }
199  
200 4 ▶sub oauth_assert_scope ( $c, @required ) {
Subroutine oauth_assert_scope: called CC=3 SCAR=11.2
Pod documented
201 # oauth_protect must have run; without verified claims this is an
202 # unauthenticated request (401), not insufficient scope (403).
203 4 ▶ unless ( $c->stash->{$SLOT} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->stash->{$SLOT}) 0 4 4
204 0 $c->oauth_challenge; # bare 401
205 0 return 0;
206 }
207 4 my %have = map { $_ => 1 } $c->oauth_scopes;
208 4 my @missing = grep { !$have{$_} } @required;
209 4 ▶ if (@missing) {
Branch: 1 branch
BranchTrueFalseTotal
if (@missing) 1 3 4
210 1 $c->oauth_challenge(
211 Catalyst::Plugin::OAuth2::ResourceServer::Error->new(
212 error => 'insufficient_scope',
213 http_status => 403,
214 scope => join( ' ', @required ),
215 )
216 );
217 1 return 0;
218 }
219 3 return 1;
220 }
221  
222 1 ▶sub oauth_protected_resource_metadata ( $c ) {
Subroutine oauth_protected_resource_metadata: called CC=4 SCAR=14.1
Pod documented
223 1 my $cfg = $c->_oauth_rs_config;
224 # RFC 9728 `resource` is a single identifier string. `resource` config may
225 # be an arrayref (the engine matches aud against any of them); advertise the
226 # first as the canonical resource id.
227 my $resource = ref $cfg->{resource} eq 'ARRAY'
228 ? $cfg->{resource}[0]
229 1 ▶ : $cfg->{resource};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'resource'} eq 'ARRAY' ? : 0 1 1
230 my %doc = (
231 resource => $resource,
232 1 ▶ authorization_servers => $cfg->{authorization_servers} // [],
Condition50%1/2
$cfg->{"authorization_servers"} // []
l!l
10
MC/DC0%0/1
$cfg->{"authorization_servers"} // []
$cfg->{"authorization_servers"}
Truth table50%1/2
A
A= $cfg->{"authorization_servers"}
Aresult
11
00
233 bearer_methods_supported => ['header'],
234 );
235 1 ▶ $doc{scopes_supported} = $cfg->{scopes_supported} if $cfg->{scopes_supported};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"scopes_supported"} 1 0 1
236 1 my $res = $c->response;
237 1 $res->status(200);
238 1 $res->content_type('application/json');
239 1 $res->header( 'Cache-Control' => 'no-store' );
240 1 $res->body( $JSON->encode( \%doc ) );
241 1 return;
242 }
243  
244 =head1 NAME
245  
246 Catalyst::Plugin::OAuth2::ResourceServer - MCP-profile OAuth 2.1 Resource
247 Server plugin for Catalyst
248  
249 =head1 SYNOPSIS
250  
251 package MyApp;
252 use Catalyst qw/+Catalyst::Plugin::OAuth2::ResourceServer/;
253  
254 __PACKAGE__->config(
255 'Catalyst::Plugin::OAuth2::ResourceServer' => {
256 signing_key => $ENV{MCP_OAUTH_JWT_KEY}, # same key the AS mints with
257 resource => 'https://api.example/mcp',
258 issuer => 'https://api.example',
259 authorization_servers => ['https://api.example'],
260 scopes_supported => ['example:read'],
261 },
262 );
263  
264 # re-validate the subject on every request; return undef to force a 401
265 sub oauth_resolve_subject ( $c, $claims ) {
266 my $user = MyApp::User->active->find( $claims->{sub} ) or return undef;
267 return $user;
268 }
269  
270 __PACKAGE__->setup;
271  
272 # in a controller
273 sub mcp :Path('/mcp') :Args(0) {
274 my ( $self, $c ) = @_;
275 return unless $c->oauth_protect;
276 return unless $c->oauth_assert_scope('example:read');
277 # $c->oauth_identity / $c->oauth_claims now available
278 }
279  
280 Mount C<oauth_protected_resource_metadata> at
281 C</.well-known/oauth-protected-resource>.
282  
283 =head1 CONFIGURATION
284  
285 Configuration is supplied under the key C<Catalyst::Plugin::OAuth2::ResourceServer>
286 in the Catalyst app config. The seam reads keys by name, so a typo'd key is
287 silently ignored (a missing I<required> engine key such as C<signing_key> still
288 croaks at construction, but a typo'd C<authorization_servers> just yields an
289 empty list in the metadata document).
290  
291 =over 4
292  
293 =item C<signing_key> (required)
294  
295 The symmetric key (plain string for HS256/HS384/HS512) used to verify bearer
296 JWTs. Must match the key the Authorization Server mints with.
297  
298 =item C<resource> (required)
299  
300 The resource identifier (URI string, or arrayref of URIs) used to verify the
301 C<aud> claim. The first element is advertised as the canonical resource id in
302 the metadata document.
303  
304 =item C<issuer> (required)
305  
306 The expected C<iss> claim value; tokens from other issuers are rejected.
307  
308 =item C<jwt_alg>
309  
310 The permitted JWT algorithm. Defaults to C<HS256>; supported values are
311 C<HS256>, C<HS384>, C<HS512>.
312  
313 =item C<leeway>
314  
315 Seconds of clock-skew leeway for C<exp>, C<nbf> and C<iat> verification.
316 Default 0.
317  
318 =item C<authorization_servers>
319  
320 Arrayref of Authorization Server URIs. Included in the RFC 9728 metadata
321 document; not used for token verification. A typo here yields an empty list
322 in the metadata: it is not caught at construction.
323  
324 =item C<scopes_supported>
325  
326 Optional arrayref of scope strings to advertise in the metadata document.
327  
328 =item C<resource_metadata_url>
329  
330 Override for the C<resource_metadata> URI embedded in 401 challenges. When set,
331 it is used verbatim and always wins over the derivation below.
332  
333 When it is not set, the URI is derived from the first C<resource> value per
334 RFC 9728 section 3.1: the C</.well-known/oauth-protected-resource> segment is
335 inserted after the authority and before any path of the resource. So
336 C<https://api.example.com/v1> derives
337 C<https://api.example.com/.well-known/oauth-protected-resource/v1>, and
338 C<https://api.example.com> derives
339 C<https://api.example.com/.well-known/oauth-protected-resource>.
340  
341 B<Derivation only works for an C<http> or C<https> resource identifier.> A URN
342 (C<urn:example:resource>) or any other non-hierarchical scheme has no authority
343 to insert the well-known segment after, so nothing can be derived: the
344 C<resource_metadata> parameter is then B<omitted> from the challenge (which
345 remains a valid RFC 6750 C<Bearer> challenge; C<resource_metadata> is optional)
346 and a warning is logged once per process. If your C<resource> is not an http(s)
347 URI and you want 401 challenges to advertise your metadata document, you must
348 set C<resource_metadata_url> explicitly.
349  
350 =back
351  
352 =head1 DESCRIPTION
353  
354 Protects Catalyst routes with OAuth 2.1 bearer tokens: verifies the access-token
355 JWT, calls an app-supplied subject resolver, exposes claims/scopes, and emits
356 RFC 6750 challenges + an RFC 9728 protected-resource metadata document. The
357 verification engine lives in
358 L<Catalyst::Plugin::OAuth2::ResourceServer::Server>; this module is the thin
359 Catalyst seam.
360  
361 Challenge and metadata responses are sent with C<Cache-Control: no-store>. The
362 consuming application is responsible for setting an appropriate C<Cache-Control>
363 on its own protected responses (RFC 6750 section 5.3).
364  
365 =head1 METHODS
366  
367 =head2 oauth_protect
368  
369 return unless $c->oauth_protect;
370  
371 Extracts a C<Bearer> token from the C<Authorization> header (scheme name is
372 case-insensitive per RFC 7235), verifies it via the engine, and optionally
373 calls the app hook C<oauth_resolve_subject>. Returns true on success and stashes
374 identity + claims; writes a 401 challenge and returns false on failure.
375  
376 =head2 oauth_assert_scope( @required )
377  
378 return unless $c->oauth_assert_scope('example:read', 'example:write');
379  
380 Returns true if all required scopes are present in the verified token; writes a
381 403 C<insufficient_scope> challenge and returns false otherwise. Call after
382 C<oauth_protect>.
383  
384 =head2 oauth_claims
385  
386 Returns the raw decoded JWT claims hashref (after a successful C<oauth_protect>),
387 or C<undef>.
388  
389 =head2 oauth_scopes
390  
391 Returns the list of scopes from the token's C<scope> claim (split on whitespace),
392 or an empty list.
393  
394 =head2 oauth_identity
395  
396 Returns the identity value returned by C<oauth_resolve_subject> (if the hook was
397 defined), or C<undef>.
398  
399 =head2 oauth_protected_resource_metadata
400  
401 Emits the RFC 9728 protected-resource metadata JSON document with
402 C<Cache-Control: no-store>. Mount at
403 C</.well-known/oauth-protected-resource>.
404  
405 =head2 oauth_challenge( $err )
406  
407 $c->oauth_challenge; # plain 401
408 $c->oauth_challenge( $err_obj ); # 401/403 with error= params
409  
410 Writes a C<WWW-Authenticate: Bearer> response. C<$err> is an optional
411 L<Catalyst::Plugin::OAuth2::ResourceServer::Error> object. 401 responses
412 include a C<resource_metadata> parameter whenever one is available: either
413 configured via C<resource_metadata_url> or derivable from an http(s)
414 C<resource> (see L</CONFIGURATION>). All parameter values are escaped as
415 RFC 7230 quoted-strings.
416  
417 =head1 APP HOOKS
418  
419 =head2 oauth_resolve_subject( $c, $claims )
420  
421 Optional method the consuming application may define. Receives the Catalyst
422 context and the decoded JWT claims hashref; should return an identity value
423 (any truthy scalar or hashref) to allow the request, or C<undef> to reject
424 it with a generic 401 C<invalid_token> challenge.
425  
426 B<Security note:> if you do not provide C<oauth_resolve_subject>, C<oauth_protect>
427 accepts any cryptographically valid, non-expired token without checking whether
428 the subject still exists or is active. Token revocation and account-deactivation
429 enforcement depend entirely on this hook; omitting it means a revoked subject's
430 token keeps working until it expires. Also: C<oauth_identity> is C<undef> when no
431 resolver is defined, so guard before dereferencing it.
432  
433 =head1 EXAMPLES
434  
435 A runnable example lives in F<examples/>: a small Catalyst app protecting
436 C</api/whoami> with a Bearer token, plus a core-Perl client that mints its own
437 demo JWT (via C<Crypt::JWT>) to exercise it. Start it with
438 C<plackup examples/app.psgi> and run C<perl examples/client.pl>. See
439 F<examples/README.md>.
440  
441 =head1 AUTHOR
442  
443 Mike Whitaker <mike@altrion.org>
444  
445 Built with tool assistance from Claude Code/(mostly) Opus 4.8 to accelerate
446 code generation and maximise test coverage (and reduce typing :D).
447  
448 With thanks to
449  
450 =over
451  
452 =item *
453  
454 Jesse Vincent for C</superpowers> (L<https://github.com/obra/superpowers>) and
455 the C<AGENTS.md> boilerplate
456  
457 =item *
458  
459 Curtis "Ovid" Poe for C</paad> (L<https://github.com/Ovid/paad>)
460  
461 =back
462  
463 for providing an agentic development framework that keeps code authority
464 firmly where it belongs.
465  
466 Iteratively reviewed by Finn Kempers <finn@shadow.cat> with analysis from
467 ZCode/GLM-5.2.
468  
469 =head1 LICENSE
470  
471 This library is free software; you can redistribute it and/or modify it
472 under the terms of the Artistic License, as distributed with Perl.
473  
474 =cut
475  
476 4 1;
↑ Summary ResourceServer/Server.pm »