OAuth/SessionStore/SQLite.pm

filter: Statementstmt 98.3% 116 / 118 Branchbran 90.6% 29 / 32 Conditioncond 57.1% 4 / 7 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 100% 47 / 47 Podpod 17.6% 3 / 17 totaltotal 88.8% 200 / 225 CC 20 SCAR 6.1
CC
20
Cov
95%
BEGIN
5.2
lock_session
4.0
__ANON__
3.0
CRAP 1.8
« OAuth/SessionStore/Memory.pm ↑ Summary
1 package
2 Mojo::ATProto::OAuth::SessionStore::SQLite;
3 2 ▶use Mojo::Base 'Mojo::ATProto::OAuth::SessionStore', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use feature qw/try current_sub/;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Mojo::Loader qw/load_class/;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Mojo::JSON qw/encode_json decode_json/;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Mojo::Promise qw//;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Crypt::PRNG qw/random_string/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use Time::HiRes qw/time sleep/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # Mojo::SQLite is an optional prerequisite of this distribution (see
12 # dist.ini's RuntimeRecommends) - only consumers who actually load this
13 # class need it installed. Fail loudly and specifically here at compile
14 # time, rather than with Perl's own bare "Can't locate Mojo/SQLite.pm"
15 # once something below tries to call it.
16 2 ▶BEGIN {
Subroutine BEGIN: called CC=3 SCAR=16.5
17 2 my $e = load_class('Mojo::SQLite');
18 2 ▶ if ($e) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e) 0 2 2
19 0 ▶ my $reason = ref($e) ? "$e" : 'module not found in @INC';
Branch: 1 branch
BranchTrueFalseTotal
ref $e ? : 0 0 0
20 0 die "Mojo::ATProto::OAuth::SessionStore::SQLite requires the optional 'Mojo::SQLite' module, which is not installed ($reason).\n"
21 . "Install it separately, e.g.: cpanm Mojo::SQLite\n";
22 }
23 }
24  
25 2 has 'sqlite' => undef;
26 2 has 'lock_sessions' => 1;
27 2 has 'lock_timeout' => 30;
28 2 has 'lock_poll_interval' => 0.1;
29  
30 17 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
31 17 my $self = shift->SUPER::new(sqlite => Mojo::SQLite->new(@_));
32 17 $self->sqlite->auto_migrate(1)->migrations->name('sessionstore')->from_data;
33 17 return $self;
34 }
35  
36 #-- add after this line
37  
38 4 ▶sub get_auth_request($self, $state) {
Subroutine get_auth_request: called CC=2 SCAR=6.9
Pod undocumented
39 4 my $row = $self->sqlite->db->select('auth_requests', undef, {state => $state})->hash;
40 4 ▶ die "no auth request found for state\n" unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 3 1 4
41 1 return $self->_auth_request_from_row($row);
42 }
43  
44 3 ▶sub get_auth_request_p($self, $state) {
Subroutine get_auth_request_p: called CC=1 SCAR=0.0
Pod undocumented
45 3 ▶ return $self->sqlite->db->select_p('auth_requests', undef, {state => $state})->then(sub($results) {
Subroutine __ANON__: called CC=2 SCAR=6.9
46 3 my $row = $results->hash;
47 3 ▶ die "no auth request found for state\n" unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 2 1 3
48 1 return $self->_auth_request_from_row($row);
49 3 });
50 }
51  
52 2 ▶sub save_auth_request($self, $info) {
Subroutine save_auth_request: called CC=1 SCAR=0.0
Pod undocumented
53 2 $self->sqlite->db->insert('auth_requests', $self->_row_from_auth_request($info));
54 2 return;
55 }
56  
57 1 ▶sub save_auth_request_p($self, $info) {
Subroutine save_auth_request_p: called CC=1 SCAR=0.0
Pod undocumented
58 1 ▶ return $self->sqlite->db->insert_p('auth_requests', $self->_row_from_auth_request($info))->then(sub { return });
Subroutine __ANON__: called CC=1 SCAR=0.0
59 }
60  
61 2 ▶sub delete_auth_request($self, $state) {
Subroutine delete_auth_request: called CC=1 SCAR=0.0
Pod undocumented
62 2 $self->sqlite->db->delete('auth_requests', {state => $state});
63 2 return;
64 }
65  
66 1 ▶sub delete_auth_request_p($self, $state) {
Subroutine delete_auth_request_p: called CC=1 SCAR=0.0
Pod undocumented
67 1 ▶ return $self->sqlite->db->delete_p('auth_requests', {state => $state})->then(sub { return });
Subroutine __ANON__: called CC=1 SCAR=0.0
68 }
69  
70 17 ▶sub get_session($self, $account_did, $session_id) {
Subroutine get_session: called CC=2 SCAR=6.9
Pod undocumented
71 17 my $row = $self->sqlite->db->select('sessions', undef, {account_did => $account_did, session_id => $session_id})->hash;
72 17 ▶ die "no session found for did/session_id\n" unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 4 13 17
73 13 return $self->_session_from_row($row);
74 }
75  
76 11 ▶sub get_session_p($self, $account_did, $session_id) {
Subroutine get_session_p: called CC=1 SCAR=0.0
Pod undocumented
77 11 ▶ return $self->sqlite->db->select_p('sessions', undef, {account_did => $account_did, session_id => $session_id})->then(sub($results) {
Subroutine __ANON__: called CC=2 SCAR=6.9
78 11 my $row = $results->hash;
79 11 ▶ die "no session found for did/session_id\n" unless defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 1 10 11
80 10 return $self->_session_from_row($row);
81 11 });
82 }
83  
84 # save_session must be an upsert keyed on (account_did, session_id) - both
85 # an ordinary login and a scope-upgrade callback may call this on what's
86 # already an existing row. SQLite's ON CONFLICT DO UPDATE (3.24.0+) handles
87 # this in one statement.
88 14 ▶sub save_session($self, $session_data) {
Subroutine save_session: called CC=1 SCAR=0.0
Pod undocumented
89 14 my ($row, $update) = $self->_session_upsert_args($session_data);
90 14 $self->sqlite->db->insert('sessions', $row, {on_conflict => [['account_did', 'session_id'] => $update]});
91 14 return;
92 }
93  
94 1 ▶sub save_session_p($self, $session_data) {
Subroutine save_session_p: called CC=1 SCAR=0.0
Pod undocumented
95 1 my ($row, $update) = $self->_session_upsert_args($session_data);
96 1 ▶ return $self->sqlite->db->insert_p('sessions', $row, {on_conflict => [['account_did', 'session_id'] => $update]})->then(sub { return });
Subroutine __ANON__: called CC=1 SCAR=0.0
97 }
98  
99 1 ▶sub delete_session($self, $account_did, $session_id) {
Subroutine delete_session: called CC=1 SCAR=0.0
Pod undocumented
100 1 $self->sqlite->db->delete('sessions', {account_did => $account_did, session_id => $session_id});
101 1 return;
102 }
103  
104 1 ▶sub delete_session_p($self, $account_did, $session_id) {
Subroutine delete_session_p: called CC=1 SCAR=0.0
Pod undocumented
105 1 ▶ return $self->sqlite->db->delete_p('sessions', {account_did => $account_did, session_id => $session_id})->then(sub { return });
Subroutine __ANON__: called CC=1 SCAR=0.0
106 }
107  
108 # Updates only the given fields of an existing session - a caller that
109 # only learned a new DPoP nonce must not write back the tokens it read
110 # earlier, which another process may have rotated since.
111 5 ▶sub update_session($self, $account_did, $session_id, $fields) {
Subroutine update_session: called CC=2 SCAR=6.9
Pod undocumented
112 5 my $set = $self->_validated_session_update($fields);
113 2 my $rows = $self->sqlite->db->update('sessions', $set, {account_did => $account_did, session_id => $session_id})->sth->rows;
114 2 ▶ die "no session found for did/session_id\n" unless $rows > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows > 0 1 1 2
115 1 return;
116 }
117  
118 5 ▶sub update_session_p($self, $account_did, $session_id, $fields) {
Subroutine update_session_p: called CC=1 SCAR=0.0
Pod undocumented
119 5 my $set = $self->_validated_session_update($fields);
120 5 ▶ return $self->sqlite->db->update_p('sessions', $set, {account_did => $account_did, session_id => $session_id})->then(sub($results) {
Subroutine __ANON__: called CC=2 SCAR=6.9
121 5 ▶ die "no session found for did/session_id\n" unless $results->sth->rows > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $results->sth->rows > 0 1 4 5
122 4 return;
123 5 });
124 }
125  
126 # Serializes $code per (account_did, session_id) across every process
127 # sharing this database file, via a lease row in session_locks rather
128 # than a SQLite transaction: BEGIN IMMEDIATE would hold the database-wide
129 # write lock for as long as $code runs (an auth-server round trip), and
130 # $code's own writes go through a different pooled connection, which
131 # that lock would block - deadlocking the caller against itself. A lease
132 # left behind by a crashed holder expires after lock_timeout seconds.
133 # With lock_sessions off, $code just gets a fresh read with no locking.
134 7 ▶sub lock_session($self, $account_did, $session_id, $code) {
Subroutine lock_session: called CC=4 SCAR=13.9
Pod documented
135 7 ▶ return $code->($self->get_session($account_did, $session_id)) unless $self->lock_sessions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->lock_sessions 1 6 7
136  
137 6 my $owner = $self->_lock_owner;
138 6 my $deadline = time + $self->lock_timeout;
139 6 ▶ until ($self->_try_lock($account_did, $session_id, $owner)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_try_lock($account_did, $session_id, $owner)) 4 5 9
140 4 ▶ die "lock_session: timed out waiting for session lock\n" if time >= $deadline;
Branch: 1 branch
BranchTrueFalseTotal
if &Mojo::ATProto::OAuth::SessionStore::SQLite::time() >= $deadline 1 3 4
141 3 sleep($self->lock_poll_interval);
142 }
143  
144 5 my $result;
145 5 try {
146 5 $result = $code->($self->get_session($account_did, $session_id));
147 } catch($ex) {
148 2 $self->_unlock($account_did, $session_id, $owner);
149 2 die $ex;
150 }
151 3 $self->_unlock($account_did, $session_id, $owner);
152 3 return $result;
153 }
154  
155 # Waits for the lease with timers rather than sleep, so other work on
156 # the event loop (including whoever holds the lease in this process)
157 # keeps running. _try_lock/_unlock stay synchronous: Mojo::SQLite's own
158 # _p methods are blocking underneath anyway.
159 10 ▶sub lock_session_p($self, $account_did, $session_id, $code) {
Subroutine lock_session_p: called CC=2 SCAR=6.9
Pod documented
160 10 ▶ return $self->get_session_p($account_did, $session_id)->then($code) unless $self->lock_sessions;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->lock_sessions 1 9 10
161  
162 9 my $owner = $self->_lock_owner;
163 9 my $deadline = time + $self->lock_timeout;
164 15 ▶ my $acquire = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
165 15 ▶ return Mojo::Promise->resolve if $self->_try_lock($account_did, $session_id, $owner);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_try_lock($account_did, $session_id, $owner) 8 7 15
166 7 ▶ return Mojo::Promise->reject("lock_session_p: timed out waiting for session lock\n") if time >= $deadline;
Branch: 1 branch
BranchTrueFalseTotal
if &Mojo::ATProto::OAuth::SessionStore::SQLite::time() >= $deadline 1 6 7
167 6 return Mojo::Promise->timer($self->lock_poll_interval)->then(__SUB__);
168 9 };
169  
170 return $acquire->()
171 8 ▶ ->then(sub { return $self->get_session_p($account_did, $session_id) })
Subroutine __ANON__: called CC=1 SCAR=0.0
172 ->then($code)
173 9 ▶ ->finally(sub { $self->_unlock($account_did, $session_id, $owner) });
Subroutine __ANON__: called CC=1 SCAR=0.0
174 }
175  
176 # Takes the lease if it's free or expired; a lease still held by someone
177 # else is left alone by the upsert's WHERE clause. Reading the owner back
178 # afterwards is what decides whether this caller got it.
179 24 ▶sub _try_lock($self, $account_did, $session_id, $owner) {
Subroutine _try_lock: called CC=2 SCAR=7.0
180 24 my $now = time;
181 24 my $db = $self->sqlite->db;
182 24 $db->query(
183 'INSERT INTO session_locks (account_did, session_id, owner, expires_at) VALUES (?, ?, ?, ?) '
184 . 'ON CONFLICT (account_did, session_id) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at '
185 . 'WHERE session_locks.expires_at < ?',
186 $account_did, $session_id, $owner, $now + $self->lock_timeout, $now,
187 );
188 24 my $holder = $db->select('session_locks', ['owner'], {account_did => $account_did, session_id => $session_id})->array;
189 24 ▶ return defined($holder) && $holder->[0] eq $owner;
Condition66%2/3
defined $holder && $holder->[0] eq $owner
!ll&&!rl&&r
01113
MC/DC50%1/2
defined $holder && $holder->[0] eq $owner
defined $holder $holder->[0] eq $owner
Truth table66%2/3
A && B
A= defined $holderB= $holder->[0] eq $owner
ABresult
0X0
100
111
190 }
191  
192 # Deletes only this caller's own lease, so a holder whose lease expired
193 # and was taken over can't release the new holder's lock.
194 14 ▶sub _unlock($self, $account_did, $session_id, $owner) {
Subroutine _unlock: called CC=1 SCAR=0.0
195 14 $self->sqlite->db->delete('session_locks', {account_did => $account_did, session_id => $session_id, owner => $owner});
196 14 return;
197 }
198  
199 15 ▶sub _lock_owner($self) {
Subroutine _lock_owner: called CC=1 SCAR=0.0
200 15 return $$ . '-' . random_string(16);
201 }
202  
203 15 ▶sub _session_upsert_args($self, $session_data) {
Subroutine _session_upsert_args: called CC=1 SCAR=0.0
204 15 my $row = $self->_row_from_session($session_data);
205 15 my $update = {%$row};
206 15 delete @{$update}{qw/account_did session_id/};
207 15 return ($row, $update);
208 }
209  
210 3 ▶sub _row_from_auth_request($self, $info) {
Subroutine _row_from_auth_request: called CC=1 SCAR=0.0
211 return {
212 state => $info->{state},
213 account_did => $info->{account_did},
214 handle => $info->{handle},
215 host_url => $info->{host_url},
216 auth_server_url => $info->{auth_server_url},
217 auth_server_token_endpoint => $info->{auth_server_token_endpoint},
218 auth_server_revocation_endpoint => $info->{auth_server_revocation_endpoint},
219 scopes => $self->_encode_scopes($info->{scopes}),
220 request_uri => $info->{request_uri},
221 pkce_verifier => $info->{pkce_verifier},
222 dpop_authserver_nonce => $info->{dpop_authserver_nonce},
223 dpop_private_key_pem => $info->{dpop_private_key_pem},
224 upgrade_session_id => $info->{upgrade_session_id},
225 client_state => $self->_encode_json($info->{client_state}),
226 3 extra => $self->_encode_json($info->{extra}),
227 };
228 }
229  
230 2 ▶sub _auth_request_from_row($self, $row) {
Subroutine _auth_request_from_row: called CC=1 SCAR=0.0
231 return {
232 state => $row->{state},
233 account_did => $row->{account_did},
234 handle => $row->{handle},
235 host_url => $row->{host_url},
236 auth_server_url => $row->{auth_server_url},
237 auth_server_token_endpoint => $row->{auth_server_token_endpoint},
238 auth_server_revocation_endpoint => $row->{auth_server_revocation_endpoint},
239 scopes => $self->_decode_scopes($row->{scopes}),
240 request_uri => $row->{request_uri},
241 pkce_verifier => $row->{pkce_verifier},
242 dpop_authserver_nonce => $row->{dpop_authserver_nonce},
243 dpop_private_key_pem => $row->{dpop_private_key_pem},
244 upgrade_session_id => $row->{upgrade_session_id},
245 client_state => $self->_decode_json($row->{client_state}),
246 2 extra => $self->_decode_json($row->{extra}),
247 };
248 }
249  
250 # client_state/extra deliberately omitted - Mojo::ATProto::OAuth never
251 # reads them back off a persisted session, only off an auth request (see
252 # oauth-store-interface memory).
253 15 ▶sub _row_from_session($self, $session_data) {
Subroutine _row_from_session: called CC=1 SCAR=0.0
254 return {
255 account_did => $session_data->{account_did},
256 session_id => $session_data->{session_id},
257 handle => $session_data->{handle},
258 host_url => $session_data->{host_url},
259 auth_server_url => $session_data->{auth_server_url},
260 auth_server_token_endpoint => $session_data->{auth_server_token_endpoint},
261 auth_server_revocation_endpoint => $session_data->{auth_server_revocation_endpoint},
262 scopes => $self->_encode_scopes($session_data->{scopes}),
263 access_token => $session_data->{access_token},
264 refresh_token => $session_data->{refresh_token},
265 dpop_authserver_nonce => $session_data->{dpop_authserver_nonce},
266 dpop_host_nonce => $session_data->{dpop_host_nonce},
267 dpop_private_key_pem => $session_data->{dpop_private_key_pem},
268 15 };
269 }
270  
271 23 ▶sub _session_from_row($self, $row) {
Subroutine _session_from_row: called CC=1 SCAR=0.0
272 return {
273 account_did => $row->{account_did},
274 session_id => $row->{session_id},
275 handle => $row->{handle},
276 host_url => $row->{host_url},
277 auth_server_url => $row->{auth_server_url},
278 auth_server_token_endpoint => $row->{auth_server_token_endpoint},
279 auth_server_revocation_endpoint => $row->{auth_server_revocation_endpoint},
280 scopes => $self->_decode_scopes($row->{scopes}),
281 access_token => $row->{access_token},
282 refresh_token => $row->{refresh_token},
283 dpop_authserver_nonce => $row->{dpop_authserver_nonce},
284 dpop_host_nonce => $row->{dpop_host_nonce},
285 dpop_private_key_pem => $row->{dpop_private_key_pem},
286 23 };
287 }
288  
289 18 ▶sub _encode_scopes($self, $scopes) {
Subroutine _encode_scopes: called CC=2 SCAR=7.2
290 18 ▶ return join(' ', @{$scopes // []});
Condition50%1/2
$scopes // []
l!l
180
MC/DC0%0/1
$scopes // []
$scopes
Truth table50%1/2
A
A= $scopes
Aresult
11
00
291 }
292  
293 25 ▶sub _decode_scopes($self, $text) {
Subroutine _decode_scopes: called CC=2 SCAR=7.6
294 25 ▶ return [split(/ /, $text // '')];
Condition50%1/2
$text // ""
l!l
250
MC/DC0%0/1
$text // ""
$text
Truth table50%1/2
A
A= $text
Aresult
11
00
295 }
296  
297 # Stores real SQL NULL (not the JSON text 'null') when $value is undef,
298 # so it doesn't round-trip as the string 'null' on the way back out.
299 6 ▶sub _encode_json($self, $value) {
Subroutine _encode_json: called CC=2 SCAR=6.9
300 6 ▶ return defined($value) ? encode_json($value) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 3 3 6
301 }
302  
303 4 ▶sub _decode_json($self, $text) {
Subroutine _decode_json: called CC=2 SCAR=6.9
304 4 ▶ return defined($text) ? decode_json($text) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 2 2 4
305 }
306  
307 2 1;
308  
309 =head1 NAME
310  
311 Mojo::ATProto::OAuth::SessionStore::SQLite - SQLite-backed session store for Mojo::ATProto::OAuth
312  
313 =head1 SYNOPSIS
314  
315 my $oauth = Mojo::ATProto::OAuth->new(..., store => [SQLite => 'file:/var/lib/myapp/oauth.db']);
316  
317 # opt out of cross-process session locking (read the caveats below first)
318 $oauth->store->lock_sessions(0);
319  
320 =head1 DESCRIPTION
321  
322 Implements the full store interface described in L<Mojo::ATProto::OAuth/THE STORE INTERFACE> on top of L<Mojo::SQLite>. Constructor arguments are passed straight to C<< Mojo::SQLite->new >>; the schema is created and migrated automatically.
323  
324 =head2 Session locking
325  
326 C<lock_session>/C<lock_session_p> (which L<Mojo::ATProto::OAuth/refresh_tokens> runs under) take a lease: a row in the C<session_locks> table naming the holder and an expiry time. A caller that finds a live lease held by someone else polls every L</lock_poll_interval> seconds until it's released, giving up with C<lock_session: timed out waiting for session lock> after L</lock_timeout> seconds. The async form waits on timers, so the event loop keeps running while it waits. A lease left behind by a crashed process expires after L</lock_timeout> seconds and is then taken over.
327  
328 No SQLite transaction or database lock is held while the lease is held, so the lock never blocks any other reads or writes to the database - only other C<lock_session> callers for the same session.
329  
330 Caveats of leaving it on (the default):
331  
332 =over 4
333  
334 =item * A caller waiting for the lock waits in steps of L</lock_poll_interval>, so a concurrent refresh finishes up to that much later than it otherwise would. Each poll is a small write to the database.
335  
336 =item * L</lock_timeout> doubles as the lease length. It must be longer than a refresh can take - the default of 30 seconds covers L<Mojo::ATProto::OAuth>'s default 10-second request timeout with its one DPoP-nonce retry. If you raise the user agent's timeout, raise this too; otherwise a slow refresh can outlive its lease and a second caller can refresh concurrently.
337  
338 =item * The synchronous C<lock_session> blocks (sleeps) while it waits. Within one process, a synchronous call waiting on a lease held by a still-pending C<lock_session_p> for the same session can't make progress, and times out.
339  
340 =back
341  
342 Setting L</lock_sessions> to false skips all of this: the code just gets a fresh read of the session, with no lock. B<Only do this if no session is ever used by more than one process, or by more than one in-flight C<_p> call, at a time.> Otherwise two callers can present the same refresh token; the auth server rejects the second with C<invalid_grant>, and an ATProto auth server may revoke the whole session in response. L<Mojo::ATProto::OAuth/refresh_tokens> recovers from that C<invalid_grant> only if the other caller's refresh has already been saved by the time it re-reads the session.
343  
344 =head1 ATTRIBUTES
345  
346 =head2 sqlite
347  
348 The underlying L<Mojo::SQLite> instance.
349  
350 =head2 lock_sessions
351  
352 Whether C<lock_session>/C<lock_session_p> actually lock. Defaults to C<1>. See L</Session locking> before turning this off.
353  
354 =head2 lock_timeout
355  
356 Seconds to wait for a session lock before giving up, and the length of the lease once taken. Defaults to C<30>.
357  
358 =head2 lock_poll_interval
359  
360 Seconds between attempts to take a session lock held by someone else. Defaults to C<0.1>.
361  
362 =head1 SEE ALSO
363  
364 L<Mojo::ATProto::OAuth>, L<Mojo::ATProto::OAuth::SessionStore::Pg>
365  
366 =cut
367  
368 __DATA__
« OAuth/SessionStore/Memory.pm ↑ Summary