OpenIDConnect/Utils/Store/Redis.pm

filter: Statementstmt 34.0% 33 / 97 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 36.3% 8 / 22 Podpod 100% 6 / 6 totaltotal 27.8% 47 / 169 CC 22 SCAR 28.2
CC
22
Cov
24%
_build_redis
42.0
get_authorization_code
30.0
consume_authorization_code
30.0
CRAP 16.8
« OpenIDConnect.pm ↑ Summary OpenIDConnect/Context.pm »
1 package Catalyst::Plugin::OpenIDConnect::Utils::Store::Redis;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use JSON::MaybeXS qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Bytes::Random::Secure qw(random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use MIME::Base64 qw(encode_base64url);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 with 'Catalyst::Plugin::OpenIDConnect::Role::Store';
14  
15 =head1 NAME
16  
17 Catalyst::Plugin::OpenIDConnect::Utils::Store::Redis - Redis-backed OIDC store
18  
19 =head1 SYNOPSIS
20  
21 # In your Catalyst application configuration:
22 'Plugin::OpenIDConnect' => {
23 store_class => 'Catalyst::Plugin::OpenIDConnect::Utils::Store::Redis',
24 store_args => {
25 server => '127.0.0.1:6379', # default
26 prefix => 'myapp:oidc:', # optional namespace prefix
27 # password => 'secret', # if Redis AUTH is required
28 },
29 issuer => { ... },
30 clients => { ... },
31 },
32  
33 =head1 DESCRIPTION
34  
35 A Redis-backed implementation of L<Catalyst::Plugin::OpenIDConnect::Role::Store>
36 that stores authorization codes in Redis with automatic TTL expiry.
37  
38 Because all FastCGI/pre-fork worker processes share the same Redis server, this
39 backend is safe for multi-process deployments. Code expiry is enforced natively
40 by Redis via C<SETEX>, so no background cleanup is needed.
41  
42 Requires the L<Redis::Fast> module (C<Redis::Fast> is preferred for performance;
43 C<Redis> also works; install whichever suits your environment).
44  
45 =head1 ATTRIBUTES
46  
47 =head2 server
48  
49 The Redis server address in C<< host:port >> form. Defaults to C<127.0.0.1:6379>.
50  
51 =cut
52  
53 1 has server => (
54 is => 'ro',
55 isa => 'Str',
56 default => '127.0.0.1:6379',
57 );
58  
59 =head2 prefix
60  
61 Key namespace prefix prepended to every Redis key. Defaults to C<oidc:code:>.
62 Set this to a unique value per application to avoid collisions on shared Redis
63 instances.
64  
65 =cut
66  
67 1 has prefix => (
68 is => 'ro',
69 isa => 'Str',
70 default => 'oidc:code:',
71 );
72  
73 =head2 password
74  
75 Optional Redis AUTH password. Leave unset if your Redis server does not require
76 authentication. If the environment variable C<REDIS_PASSWORD> is set, it will
77 be have been passed as the default value for this attribute by the plugin.
78  
79 =cut
80  
81 1 has password => (
82 is => 'ro',
83 isa => 'Maybe[Str]',
84 required => 0,
85 );
86  
87 =head2 code_ttl
88  
89 Lifetime of an authorization code in seconds. Defaults to 600 (10 minutes).
90 The value is passed directly to Redis C<SETEX>.
91  
92 =cut
93  
94 1 has code_ttl => (
95 is => 'ro',
96 isa => 'Int',
97 default => 600,
98 );
99  
100 =head2 logger
101  
102 Optional logger instance for debug/info/warn logging.
103  
104 =cut
105  
106 1 has logger => (
107 is => 'ro',
108 isa => 'Maybe[Object]',
109 required => 0,
110 );
111  
112 =head2 _redis
113  
114 The underlying Redis connection, lazily created on first use. This defers the
115 TCP connection until after the parent process has forked, which is necessary for
116 pre-forking servers: each worker gets its own independent socket.
117  
118 =cut
119  
120 1 has _redis => (
121 is => 'ro',
122 lazy => 1,
123 builder => '_build_redis',
124 );
125  
126 0 ▶sub _build_redis {
Subroutine _build_redis: not called CC=6 SCAR=37.4
127 0 my ($self) = @_;
128  
129 # Prefer Redis::Fast when available; fall back to Redis.
130 0 my $class;
131 0 for my $candidate (qw( Redis::Fast Redis )) {
132 0 ▶ if ( eval "require $candidate; 1" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval "require $candidate; 1") 0 0 0
133 0 $class = $candidate;
134 0 last;
135 }
136 }
137 0 ▶ die 'Neither Redis::Fast nor Redis is installed. '
Branch: 1 branch
BranchTrueFalseTotal
unless $class 0 0 0
138 . 'Install one to use the Redis store backend.'
139 unless $class;
140  
141 0 ▶ $self->logger->debug("Connecting to Redis via $class at " . $self->server)
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
142 if $self->logger;
143  
144 0 my %args = (
145 server => $self->server,
146 reconnect => 60,
147 every => 500_000, # microseconds between reconnect attempts
148 );
149 0 ▶ $args{password} = $self->password if defined $self->password;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->password 0 0 0
150  
151 0 return $class->new(%args);
152 }
153  
154 =head1 METHODS
155  
156 =head2 create_authorization_code($client_id, $user, $scope, $redirect_uri, $nonce, $pkce)
157  
158 Creates an authorization code and stores it in Redis with an automatic TTL equal
159 to L</code_ttl> seconds. C<$pkce> is an optional hashref with keys
160 C<code_challenge> and C<code_challenge_method>; omit or pass C<undef> for
161 non-PKCE flows.
162  
163 Returns the authorization code string.
164  
165 =cut
166  
167 0 ▶sub create_authorization_code {
Subroutine create_authorization_code: not called CC=4 SCAR=30.0
Pod documented
168 0 my ( $self, $client_id, $user, $scope, $redirect_uri, $nonce, $pkce ) = @_;
169  
170 0 ▶ $self->logger->debug("Creating authorization code for client: $client_id")
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
171 if $self->logger;
172  
173 0 my $code = _generate_secure_random();
174 0 my $now = time();
175  
176 my $data = encode_json({
177 client_id => $client_id,
178 user => $user,
179 scope => $scope,
180 redirect_uri => $redirect_uri,
181 nonce => $nonce,
182 created_at => $now,
183 expires_at => $now + $self->code_ttl,
184 ( $pkce ? (
185 code_challenge => $pkce->{code_challenge},
186 code_challenge_method => $pkce->{code_challenge_method},
187 0 ▶ ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
$pkce ? : 0 0 0
188 });
189  
190 0 $self->_redis->setex( $self->prefix . $code, $self->code_ttl, $data );
191  
192 0 ▶ $self->logger->debug(
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
193 "Authorization code created: $code (TTL=" . $self->code_ttl . "s)")
194 if $self->logger;
195  
196 0 return $code;
197 }
198  
199 =head2 get_authorization_code($code)
200  
201 Retrieves authorization code data from Redis.
202  
203 Returns a hashref with the code data, or C<undef> if the code does not exist
204 or has already expired (Redis TTL handles expiry automatically).
205  
206 =cut
207  
208 0 ▶sub get_authorization_code {
Subroutine get_authorization_code: not called CC=5 SCAR=34.0
Pod documented
209 0 my ( $self, $code ) = @_;
210  
211 0 ▶ $self->logger->debug("Retrieving authorization code: $code") if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
212  
213 0 my $raw = $self->_redis->get( $self->prefix . $code );
214 0 ▶ return unless defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 0 0 0
215  
216 0 ▶ my $data = try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
217 0 decode_json($raw);
218 }
219 0 ▶ catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
220 0 ▶ $self->logger->warn("Failed to decode authorization code data: $_")
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
221 if $self->logger;
222 0 undef;
223 0 };
224  
225 0 ▶ $self->logger->debug("Authorization code found: $code") if $self->logger && $data;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger and $data 0 0 0
Condition0%0/3
$self->logger and $data
!ll&&!rl&&r
000
MC/DC0%0/2
$self->logger and $data
$self->logger $data
Truth table0%0/3
A and B
A= $self->loggerB= $data
ABresult
0X0
100
111
226 0 return $data;
227 }
228  
229 =head2 consume_authorization_code($code)
230  
231 Atomically fetches and deletes the authorization code from Redis using the
232 C<GETDEL> command (Redis E<ge> 6.2). Because C<GETDEL> is a single server-side
233 operation it is race-free: a second concurrent request carrying the same code
234 will receive C<nil> from Redis and be rejected.
235  
236 Returns the decoded code data hashref on success, or C<undef> if the code
237 does not exist, has already been consumed, or cannot be decoded.
238  
239 =cut
240  
241 0 ▶sub consume_authorization_code {
Subroutine consume_authorization_code: not called CC=5 SCAR=34.0
Pod documented
242 0 my ( $self, $code ) = @_;
243  
244 0 ▶ $self->logger->debug("Consuming authorization code: $code") if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
245  
246 # GETDEL (Redis >= 6.2) fetches and deletes atomically in a single
247 # round-trip, eliminating the GET + DEL race condition (HIGH-4).
248 0 my $raw = $self->_redis->getdel( $self->prefix . $code );
249 0 ▶ return unless defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 0 0 0
250  
251 0 ▶ my $data = try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
252 0 decode_json($raw);
253 }
254 0 ▶ catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
255 0 ▶ $self->logger->warn("Failed to decode consumed authorization code data: $_")
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
256 if $self->logger;
257 0 undef;
258 0 };
259  
260 0 ▶ $self->logger->debug("Authorization code consumed: $code") if $self->logger && $data;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger and $data 0 0 0
Condition0%0/3
$self->logger and $data
!ll&&!rl&&r
000
MC/DC0%0/2
$self->logger and $data
$self->logger $data
Truth table0%0/3
A and B
A= $self->loggerB= $data
ABresult
0X0
100
111
261 0 return $data;
262 }
263  
264 =head2 store_refresh_token($jti, $sub, $client_id, $ttl)
265  
266 Stores a refresh token JTI in Redis with C<SETEX> using C<$ttl> seconds. Also
267 maintains a secondary per-subject Set (C<{prefix}rt_sub:{sub}>) so that all
268 tokens for a user can be revoked atomically at logout time.
269  
270 =cut
271  
272 0 ▶sub store_refresh_token {
Subroutine store_refresh_token: not called CC=1 SCAR=6.9
Pod documented
273 0 my ( $self, $jti, $sub, $client_id, $ttl ) = @_;
274 0 my $data = encode_json({ sub => $sub, client_id => $client_id });
275 0 $self->_redis->setex( $self->prefix . 'rt:' . $jti, $ttl, $data );
276 # Secondary index for bulk-revocation at logout.
277 0 my $set_key = $self->prefix . 'rt_sub:' . $sub;
278 0 $self->_redis->sadd( $set_key, $jti );
279 0 $self->_redis->expire( $set_key, $ttl );
280 }
281  
282 =head2 consume_refresh_token($jti)
283  
284 Atomically fetches and deletes the JTI entry using C<GETDEL> (Redis E<ge> 6.2).
285 Returns the decoded data hashref, or C<undef> if absent (already used, revoked,
286 or expired).
287  
288 =cut
289  
290 0 ▶sub consume_refresh_token {
Subroutine consume_refresh_token: not called CC=3 SCAR=24.8
Pod documented
291 0 my ( $self, $jti ) = @_;
292 0 my $raw = $self->_redis->getdel( $self->prefix . 'rt:' . $jti );
293 0 ▶ return unless defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 0 0 0
294 0 ▶ my $data = try { decode_json($raw) } catch { undef };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
295 0 ▶ if ($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 0 0 0
296 0 $self->_redis->srem( $self->prefix . 'rt_sub:' . $data->{sub}, $jti );
297 }
298 0 return $data;
299 }
300  
301 =head2 revoke_refresh_tokens_for_user($sub)
302  
303 Revokes all outstanding refresh tokens for the given subject by iterating the
304 per-subject Redis Set and deleting each JTI key, then deleting the Set itself.
305 Called at logout time.
306  
307 =cut
308  
309 0 ▶sub revoke_refresh_tokens_for_user {
Subroutine revoke_refresh_tokens_for_user: not called CC=2 SCAR=17.9
Pod documented
310 0 my ( $self, $sub ) = @_;
311 0 my $set_key = $self->prefix . 'rt_sub:' . $sub;
312 0 my @jtis = $self->_redis->smembers($set_key);
313 0 for my $jti (@jtis) {
314 0 $self->_redis->del( $self->prefix . 'rt:' . $jti );
315 }
316 0 $self->_redis->del($set_key);
317 }
318  
319 # Generate a cryptographically secure random string for authorization codes.
320 # Uses Bytes::Random::Secure which reads from the OS CSPRNG. The lazy _redis
321 # attribute means the connection is made after fork(), so random state is
322 # not shared between worker processes.
323 0 ▶sub _generate_secure_random {
Subroutine _generate_secure_random: not called CC=1 SCAR=6.9
324 0 my $bytes = random_bytes(120);
325 0 my $encoded = encode_base64url($bytes);
326 0 $encoded =~ s/[^a-zA-Z0-9]//g;
327 0 return substr( $encoded, 0, 128 );
328 }
329  
330 1 __PACKAGE__->meta->make_immutable;
331 1 1;
332  
333 =head1 DEPENDENCIES
334  
335 L<Redis::Fast> (preferred) or L<Redis>, plus L<JSON::MaybeXS> and
336 L<Bytes::Random::Secure>.
337  
338 =head1 AUTHOR
339  
340 Tim F. Rayner
341  
342 =head1 LICENSE
343  
344 This library is free software; you can redistribute it and/or modify
345 it under the terms of The Artistic License 2.0.
346  
347 =cut
« OpenIDConnect.pm ↑ Summary OpenIDConnect/Context.pm »