| 1 | package Dancer2::Session::Pg; | ||
| 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 English qw( -no_match_vars ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | # $data is what Dancer2::Core::Role::SessionFactory calls a session payload, in | ||
| 8 | # the very signatures this module exists to implement. Renaming it to satisfy | ||
| 9 | # Bangs::ProhibitVagueNames would make the two halves of the contract disagree, | ||
| 10 | # and a reader comparing them would have to translate. | ||
| 11 | ## no critic (Bangs::ProhibitVagueNames) | ||
| 12 | |||
| 13 | 1 | ▶ | use Moo; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 14 | 1 | ▶ | use Carp qw( croak ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 15 | 0 | ▶ | use DBI (); |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 16 | use DBD::Pg qw( :pg_types ); | ||
| 17 | use Module::Runtime qw( is_module_name use_module ); | ||
| 18 | use Types::Standard qw( CodeRef HashRef Int Maybe Object Str ); | ||
| 19 | use Types::Common::String qw( NonEmptySimpleStr ); | ||
| 20 | use Scalar::Util qw( blessed ); | ||
| 21 | use Crypt::Digest::SHA256 qw( sha256_hex ); | ||
| 22 | use Crypt::PRNG (); | ||
| 23 | |||
| 24 | # Core `use constant`, which is what Dancer2 itself uses. | ||
| 25 | use constant { | ||
| 26 | |||
| 27 | # Every stored payload begins with three bytes -- format version, cipher id, | ||
| 28 | # key id -- and every length after them comes from the cipher that id names. | ||
| 29 | # So a cipher with a 24-byte nonce or a 32-byte tag needs no change here, and | ||
| 30 | # a row says what wrote it instead of the configuration having to agree. | ||
| 31 | FORMAT_VERSION => 1, | ||
| 32 | HEADER_BYTES => 3, | ||
| 33 | |||
| 34 | # A session is not worth waiting on: a write that blocks indefinitely blocks | ||
| 35 | # a worker indefinitely. Seconds and milliseconds respectively, matching what | ||
| 36 | # DBD::Pg and PostgreSQL each expect. | ||
| 37 | DEFAULT_CONNECT_TIMEOUT => 2, | ||
| 38 | DEFAULT_STATEMENT_TIMEOUT_MS => 2000, | ||
| 39 | }; | ||
| 40 | |||
| 41 | our $VERSION = '0.002'; | ||
| 42 | |||
| 43 | with 'Dancer2::Core::Role::SessionFactory'; | ||
| 44 | |||
| 45 | # --------------------------------------------------------------------------- | ||
| 46 | # Authenticated encryption | ||
| 47 | # --------------------------------------------------------------------------- | ||
| 48 | # | ||
| 49 | # Authenticated modes only. A session that has been altered in the database must | ||
| 50 | # fail to decrypt rather than deserialise into a structure the application then | ||
| 51 | # trusts, so a mode without a tag is not offered here. | ||
| 52 | # | ||
| 53 | # A cipher is an object doing Dancer2::Session::Pg::Cipher, and the id it | ||
| 54 | # declares goes into every payload it writes. That is the whole mechanism behind | ||
| 55 | # replacing one: point `alg` at the new cipher and new sessions use it while rows | ||
| 56 | # written by the old one stay readable until they expire. A cipher revealed to be | ||
| 57 | # weak next year is then a configuration change, not a forced logout. | ||
| 58 | |||
| 59 | my %BUILTIN = ( | ||
| 60 | 'AES-128-GCM' => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 16 ], | ||
| 61 | 'AES-192-GCM' => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 24 ], | ||
| 62 | 'AES-256-GCM' => [ 'Dancer2::Session::Pg::Cipher::AESGCM', key_bytes => 32 ], | ||
| 63 | 'ChaCha20-Poly1305' => ['Dancer2::Session::Pg::Cipher::ChaCha20Poly1305'], | ||
| 64 | ); | ||
| 65 | |||
| 66 | sub algorithms { | ||
| 67 | |||
| 68 | # Not `return sort ...`: that is undefined in scalar context. | ||
| 69 | my @names = sort keys %BUILTIN; | ||
| 70 | return @names; | ||
| 71 | } | ||
| 72 | |||
| 73 | # cipher_self_check is in the list on purpose: it is the one method a cipher gets | ||
| 74 | # only by consuming the role, so requiring it is how "do the role" is enforced | ||
| 75 | # without reaching into Role::Tiny. | ||
| 76 | my @CIPHER_CONTRACT = qw( | ||
| 77 | cipher_id cipher_name key_bytes iv_bytes tag_bytes seal unseal cipher_self_check | ||
| 78 | ); | ||
| 79 | |||
| 80 | # A class named in configuration may be anything at all, so say what went wrong | ||
| 81 | # rather than letting "Can't locate object method new" out of a module nobody asked | ||
| 82 | # to be a cipher. | ||
| 83 | sub _construct { | ||
| 84 | my ( $class, @args ) = @_; | ||
| 85 | my $cipher = eval { use_module($class)->new(@args) }; | ||
| 86 | croak sprintf 'Dancer2::Session::Pg: alg %s could not be constructed as a cipher: %s', | ||
| 87 | "'$class'", ( $EVAL_ERROR || 'new returned no object' ) | ||
| 88 | if !blessed $cipher; | ||
| 89 | return $cipher; | ||
| 90 | } | ||
| 91 | |||
| 92 | sub _resolve_cipher { | ||
| 93 | my ($spec) = @_; | ||
| 94 | |||
| 95 | my $cipher; | ||
| 96 | if ( blessed $spec ) { | ||
| 97 | $cipher = $spec; | ||
| 98 | } elsif ( ref $spec eq 'ARRAY' ) { | ||
| 99 | my ( $class, @args ) = @{$spec}; | ||
| 100 | croak sprintf 'Dancer2::Session::Pg: implausible cipher class %s', ( defined $class ? "'$class'" : 'undef' ) | ||
| 101 | if !defined $class || !is_module_name($class); | ||
| 102 | $cipher = _construct( $class, @args ); | ||
| 103 | } elsif ( defined $spec && exists $BUILTIN{$spec} ) { | ||
| 104 | my ( $class, @args ) = @{ $BUILTIN{$spec} }; | ||
| 105 | $cipher = _construct( $class, @args ); | ||
| 106 | } else { | ||
| 107 | croak sprintf | ||
| 108 | 'Dancer2::Session::Pg: unknown alg %s (built in: %s -- or name a class that does Dancer2::Session::Pg::Cipher)', | ||
| 109 | ( defined $spec ? "'$spec'" : 'undef' ), join q{, }, algorithms() | ||
| 110 | if !defined $spec || ref $spec || !is_module_name($spec); | ||
| 111 | $cipher = _construct($spec); | ||
| 112 | } | ||
| 113 | |||
| 114 | my @missing = grep { !$cipher->can($_) } @CIPHER_CONTRACT; | ||
| 115 | croak sprintf 'Dancer2::Session::Pg: %s does not do %s (missing: %s)', | ||
| 116 | ref $cipher, 'Dancer2::Session::Pg::Cipher', join q{, }, @missing | ||
| 117 | if @missing; | ||
| 118 | |||
| 119 | return $cipher; | ||
| 120 | } | ||
| 121 | |||
| 122 | # --------------------------------------------------------------------------- | ||
| 123 | # Connection | ||
| 124 | # --------------------------------------------------------------------------- | ||
| 125 | |||
| 126 | # Maybe[Str] rather than Str on the optional four, deliberately. An engine | ||
| 127 | # configured from YAML gets undef for a key that is present but empty -- | ||
| 128 | # `dsn:` with nothing after it -- and undef there means "not set", which the | ||
| 129 | # checks in BUILD answer with a sentence an operator can act on. A bare Str | ||
| 130 | # would intercept that case and report a type constraint instead. | ||
| 131 | has dsn => ( is => 'ro', isa => Maybe [Str] ); | ||
| 132 | has dbuser => ( is => 'ro', isa => Maybe [Str] ); | ||
| 133 | has dbpass => ( is => 'ro', isa => Maybe [Str] ); | ||
| 134 | |||
| 135 | # NO DEFAULT SCHEMA. Assuming 'public' would be wrong wherever the default | ||
| 136 | # schema is called something else, and qualifying a name the deployment did not | ||
| 137 | # ask us to qualify takes a decision that belongs to search_path. Unset means the | ||
| 138 | # table is referenced bare and resolved by the connection's search_path. | ||
| 139 | has dbschema => ( is => 'ro', isa => Maybe [Str] ); | ||
| 140 | |||
| 141 | # The table name, on the other hand, is not guessable and is not optional. | ||
| 142 | has dbtable => ( is => 'ro', required => 1, isa => NonEmptySimpleStr ); | ||
| 143 | |||
| 144 | # An existing handle, or a coderef returning one -- so an application already | ||
| 145 | # holding a connection (Dancer2::Plugin::Database, DBIx::Class, a pool) can hand | ||
| 146 | # it over instead of opening a second one. A coderef is re-invoked on every | ||
| 147 | # access, which is what makes it safe with a pool that hands out live handles. | ||
| 148 | # | ||
| 149 | # Typed because the alternative is a string from a configuration file reaching | ||
| 150 | # the first query as a method call on an unblessed scalar, several minutes after | ||
| 151 | # the mistake was made. | ||
| 152 | has dbh => ( is => 'ro', predicate => 1, isa => CodeRef | Object ); | ||
| 153 | |||
| 154 | # Int, because `connect_timeout: two` in YAML would otherwise be appended to the | ||
| 155 | # DSN verbatim and the engine would fail to connect for a reason the message does | ||
| 156 | # not mention. | ||
| 157 | has connect_timeout => ( is => 'ro', isa => Int, default => sub { DEFAULT_CONNECT_TIMEOUT } ); | ||
| 158 | has statement_timeout => ( is => 'ro', isa => Int, default => sub { DEFAULT_STATEMENT_TIMEOUT_MS } ); | ||
| 159 | |||
| 160 | # --------------------------------------------------------------------------- | ||
| 161 | # The optional principal | ||
| 162 | # --------------------------------------------------------------------------- | ||
| 163 | # | ||
| 164 | # OFF by default: the principal column is an optional extra, and an application | ||
| 165 | # with no principal concept should not be asked to carry one -- not in its | ||
| 166 | # configuration and not in its table. | ||
| 167 | |||
| 168 | # A string names the session key whose value is copied. A coderef is handed the | ||
| 169 | # session data and returns the value, which is how an identity spread over | ||
| 170 | # several keys -- sub { $_[0]->{'user'}{'id'} } -- still becomes one indexable | ||
| 171 | # column. | ||
| 172 | has principal_key => ( is => 'ro', isa => Str | CodeRef ); | ||
| 173 | |||
| 174 | # The column that value is written to. Separate from the session key because a | ||
| 175 | # deployment making it a foreign key will want it named after the table it | ||
| 176 | # references -- account_id, not principal_id. | ||
| 177 | has principal_column => ( is => 'ro', isa => NonEmptySimpleStr, default => sub { 'principal_id' } ); | ||
| 178 | |||
| 179 | # The columns _flush writes itself. principal_column may not be one of them; see | ||
| 180 | # the check in BUILD for why. | ||
| 181 | our @RESERVED_COLUMNS = qw( id session_data created updated expires ); | ||
| 182 | our %RESERVED_COLUMN = map { $_ => 1 } @RESERVED_COLUMNS; | ||
| 183 | |||
| 184 | # --------------------------------------------------------------------------- | ||
| 185 | # Keys, and the cipher each one belongs to | ||
| 186 | # --------------------------------------------------------------------------- | ||
| 187 | # | ||
| 188 | # A SLOT pairs a key with the cipher it is used by. That pairing is the whole | ||
| 189 | # design, and it is worth saying why, because the obvious alternative -- a list | ||
| 190 | # of keys and a separate choice of cipher -- is what this replaced. | ||
| 191 | # | ||
| 192 | # Decoupled, nothing records which cipher a key was meant for, so key LENGTH | ||
| 193 | # becomes the only thing linking them and has to be re-derived at five separate | ||
| 194 | # points: validating the write key, catching a typo in a read key, deciding | ||
| 195 | # which ciphers are usable at all, checking a row's cipher against its key, and | ||
| 196 | # even deciding whether a configured string is hex or raw bytes. Paired, every | ||
| 197 | # one of those is one check in one place: this slot's key must fit this slot's | ||
| 198 | # cipher. A whole attribute went with it -- there is no `read_algs`, because a | ||
| 199 | # cipher you can still read but no longer write IS the other slot. | ||
| 200 | # | ||
| 201 | # Exactly one slot is `active`, and that is the one written with. Reading uses | ||
| 202 | # the slot the ROW names -- every payload carries its key id -- so it is one | ||
| 203 | # lookup and one decrypt attempt, not a try-every-key loop that would blur a | ||
| 204 | # misconfiguration into something that looks like tampering. | ||
| 205 | # | ||
| 206 | # encryption_keys: | ||
| 207 | # 0: | ||
| 208 | # key: "${ENV:SESSION_KEY_0}" | ||
| 209 | # alg: "AES-256-GCM" | ||
| 210 | # active: true | ||
| 211 | # 1: | ||
| 212 | # key: "${ENV:SESSION_KEY_1}" | ||
| 213 | # alg: "ChaCha20-Poly1305" | ||
| 214 | |||
| 215 | has encryption_keys => ( is => 'ro', required => 1, isa => HashRef ); | ||
| 216 | |||
| 217 | has json_module => ( is => 'ro', isa => Str, default => sub { 'JSON::MaybeXS' } ); | ||
| 218 | |||
| 219 | sub BUILD { | ||
| 220 | my ($self) = @_; | ||
| 221 | croak 'Dancer2::Session::Pg: pass either dsn or dbh' | ||
| 222 | if !$self->has_dbh && !defined $self->dsn; | ||
| 223 | |||
| 224 | # principal_key is checked by its type constraint, which says the same thing | ||
| 225 | # earlier and in one line. principal_column needs more than a type: it has to | ||
| 226 | # not collide with a column this module already writes. | ||
| 227 | # | ||
| 228 | # _flush builds one INSERT column list, so a principal_column of 'expires' | ||
| 229 | # would emit that column twice and PostgreSQL would refuse every session | ||
| 230 | # write with error 42701. Quoting does not help -- "expires" and expires are | ||
| 231 | # the same column. It takes a nonsensical configuration to reach, but the | ||
| 232 | # module's whole bargain is to fail at startup rather than at somebody's | ||
| 233 | # first login, and this was the one place not holding up its end. | ||
| 234 | croak sprintf q{Dancer2::Session::Pg: principal_column may not be '%s' -- this module } | ||
| 235 | . q{writes that column itself, and _flush would name it twice in one INSERT. } | ||
| 236 | . q{Reserved: %s}, $self->principal_column, join q{, }, @RESERVED_COLUMNS | ||
| 237 | if defined $self->principal_key | ||
| 238 | && exists $RESERVED_COLUMN{ lc $self->principal_column }; | ||
| 239 | |||
| 240 | # One call settles every slot: each alg names a real cipher, each cipher does | ||
| 241 | # what it claims, each key is the length its own cipher needs, and exactly | ||
| 242 | # one slot is active. A configuration that cannot work stops the process here | ||
| 243 | # rather than at somebody's first login. | ||
| 244 | $self->_slots; | ||
| 245 | |||
| 246 | # A supplied handle is never modified, so if it is in manual-commit mode the | ||
| 247 | # session write joins somebody else's transaction and is durable only when | ||
| 248 | # they commit. Say so once, loudly, rather than let it surface later as a | ||
| 249 | # login that mysteriously did not complete. | ||
| 250 | # | ||
| 251 | # Only a handle we can look at NOW. A coderef cannot be called here -- doing | ||
| 252 | # so would open a connection at construction, which is the whole thing the | ||
| 253 | # coderef form exists to avoid -- so that case is checked in _dbh instead, | ||
| 254 | # at the first access, where the handle is in hand. | ||
| 255 | $self->_warn_if_manual_commit( $self->dbh ) | ||
| 256 | if $self->has_dbh && ref $self->dbh ne 'CODE'; | ||
| 257 | |||
| 258 | return; | ||
| 259 | } | ||
| 260 | |||
| 261 | # Shared by BUILD and _dbh so the two cannot drift, and keyed on one message so | ||
| 262 | # `_report_once` suppresses the second of them. | ||
| 263 | # | ||
| 264 | # carp AND log_cb, deliberately: carp reaches an engine built by hand, where | ||
| 265 | # log_cb is the role's no-op default and a warning would otherwise vanish; log_cb | ||
| 266 | # reaches the application log of an engine Dancer2 built from config, where | ||
| 267 | # STDERR may go nowhere anybody reads. | ||
| 268 | sub _warn_if_manual_commit { | ||
| 269 | my ( $self, $handle ) = @_; | ||
| 270 | |||
| 271 | return if !$handle || $handle->{'AutoCommit'}; | ||
| 272 | |||
| 273 | my $message = | ||
| 274 | 'the supplied dbh has AutoCommit off. Session writes will join the ' | ||
| 275 | . q{caller's transaction and are not durable until the caller commits. This } | ||
| 276 | . 'module will not commit a handle it does not own. See "SHARING A HANDLE" ' | ||
| 277 | . 'in the docs.'; | ||
| 278 | |||
| 279 | return if $self->_reported->{$message}; | ||
| 280 | Carp::carp "Dancer2::Session::Pg: $message"; | ||
| 281 | $self->_report_once( 'warning', $message ); | ||
| 282 | return; | ||
| 283 | } | ||
| 284 | |||
| 285 | # id => { key => raw bytes, cipher => object }, and which id is written with. | ||
| 286 | # | ||
| 287 | # Everything knowable before the first request is settled here, so a | ||
| 288 | # configuration that cannot work stops the process at startup rather than at | ||
| 289 | # somebody's first login. Under Kubernetes that is the behaviour you want: the | ||
| 290 | # pod refuses to start, the rollout halts, and the previous generation carries | ||
| 291 | # on serving. | ||
| 292 | has _slots => ( is => 'lazy' ); | ||
| 293 | |||
| 294 | has _write_slot_id => ( is => 'lazy' ); | ||
| 295 | |||
| 296 | sub _build__slots { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 297 | my ($self) = @_; | ||
| 298 | |||
| 299 | my $configured = $self->encryption_keys; | ||
| 300 | croak 'Dancer2::Session::Pg: encryption_keys has no entries. One slot is enough: ' | ||
| 301 | . '{ 0 => { key => ..., alg => ..., active => 1 } }' | ||
| 302 | if !keys %{$configured}; | ||
| 303 | |||
| 304 | my ( %slot, @active, %class_for_id ); | ||
| 305 | for my $id ( sort keys %{$configured} ) { | ||
| 306 | |||
| 307 | # CANONICAL decimal, not merely digits. A slot id of '00' would pass a | ||
| 308 | # digits-only check, be packed into the header as the byte 0, and then be | ||
| 309 | # looked up on read as the integer 0 -- which misses a %slot keyed by the | ||
| 310 | # string '00'. Writes would succeed and every read would fail. | ||
| 311 | croak sprintf 'Dancer2::Session::Pg: key id %s must be a canonical integer in 0..255' | ||
| 312 | . ' -- it is one byte of every stored payload', "'$id'" | ||
| 313 | if $id !~ m/\A(?:0|[1-9][0-9]*)\z/msx || $id > 255; ## no critic (RegularExpressions::ProhibitEnumeratedClasses) -- [0-9] is ASCII-only; \d and [[:digit:]] both match Unicode digits | ||
| 314 | |||
| 315 | my $spec = $configured->{$id}; | ||
| 316 | croak "Dancer2::Session::Pg: encryption_keys entry $id must be a hash with 'key' and 'alg'" | ||
| 317 | if ref $spec ne 'HASH'; | ||
| 318 | |||
| 319 | my $cipher = _resolve_cipher( $spec->{'alg'} ); | ||
| 320 | $cipher->cipher_self_check; | ||
| 321 | |||
| 322 | # One cipher id, one implementation. Several slots may share a cipher -- | ||
| 323 | # that is an ordinary key rotation -- but two DIFFERENT classes claiming | ||
| 324 | # one id would defeat the header's cross-check, which is the only thing | ||
| 325 | # that diagnoses a slot whose alg was edited in place: both would agree | ||
| 326 | # on the id while disagreeing about everything else. | ||
| 327 | my $claimed = $cipher->cipher_id; | ||
| 328 | croak sprintf 'Dancer2::Session::Pg: cipher id %d is claimed by both %s and %s. ' | ||
| 329 | . 'An id identifies one implementation, and the stored header cannot tell them apart.', | ||
| 330 | $claimed, ref $class_for_id{$claimed}, ref $cipher | ||
| 331 | if exists $class_for_id{$claimed} && ref $class_for_id{$claimed} ne ref $cipher; | ||
| 332 | $class_for_id{$claimed} = $cipher; | ||
| 333 | |||
| 334 | $slot{$id} = { key => $self->_slot_key( $id, $spec->{'key'}, $cipher ), cipher => $cipher }; | ||
| 335 | push @active, $id if $spec->{'active'}; | ||
| 336 | } | ||
| 337 | |||
| 338 | croak sprintf 'Dancer2::Session::Pg: no slot in encryption_keys is active, so there is ' | ||
| 339 | . 'nothing to write sessions with. Mark one with active => 1 (have: %s)', join q{, }, sort { $a <=> $b } keys %slot | ||
| 340 | if !@active; | ||
| 341 | |||
| 342 | # NOT "use the first one". Perl randomises hash order per process, so a | ||
| 343 | # silent choice would differ between pods and between restarts of one pod -- | ||
| 344 | # every pod writing a different key, which is the rolling outage the slots | ||
| 345 | # exist to prevent, made permanent. | ||
| 346 | # | ||
| 347 | # And even in a defined order, picking silently is the worst failure here: | ||
| 348 | # activating a new slot while forgetting to deactivate the old one would | ||
| 349 | # leave the rotation NOT DONE while looking done, and the operator would | ||
| 350 | # then retire the old slot on schedule and lose every live session at once. | ||
| 351 | # If the reason for rotating was that the old key leaked, it would also mean | ||
| 352 | # quietly continuing to use the leaked key. | ||
| 353 | croak sprintf 'Dancer2::Session::Pg: slots %s are both active, and exactly one must be. ' | ||
| 354 | . 'The active slot is the one sessions are WRITTEN with; the others stay to be read ' | ||
| 355 | . 'until their sessions expire.', join q{ and }, sort { $a <=> $b } @active | ||
| 356 | if @active > 1; | ||
| 357 | |||
| 358 | return \%slot; | ||
| 359 | } | ||
| 360 | |||
| 361 | sub _build__write_slot_id { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 362 | my ($self) = @_; | ||
| 363 | my $configured = $self->encryption_keys; | ||
| 364 | my ($id) = grep { ref $configured->{$_} eq 'HASH' && $configured->{$_}{'active'} } | ||
| 365 | sort keys %{$configured}; | ||
| 366 | $self->_slots; # so an invalid configuration croaks with ITS message, not undef | ||
| 367 | return $id; | ||
| 368 | } | ||
| 369 | |||
| 370 | sub _slot_key { | ||
| 371 | my ( $self, $id, $raw, $cipher ) = @_; | ||
| 372 | |||
| 373 | croak "Dancer2::Session::Pg: the key in slot $id is empty" | ||
| 374 | if !defined $raw || !length $raw; | ||
| 375 | |||
| 376 | # Hex detection is EXACT here, which it could not be before: this slot names | ||
| 377 | # its cipher, so the one correct length is known rather than guessed at from | ||
| 378 | # a set of plausible ones. | ||
| 379 | my $wanted = $cipher->key_bytes; | ||
| 380 | $raw = pack 'H*', $raw | ||
| 381 | if $raw =~ m/\A(?:[0-9a-fA-F]{2})+\z/msx && length($raw) == 2 * $wanted; ## no critic (RegularExpressions::ProhibitEnumeratedClasses) -- [0-9] is ASCII-only; \d and [[:digit:]] both match Unicode digits | ||
| 382 | |||
| 383 | croak sprintf 'Dancer2::Session::Pg: the key in slot %d is %d bytes, but %s needs %d. ' | ||
| 384 | . 'Generate one with: openssl rand -hex %d', $id, length $raw, $cipher->cipher_name, $wanted, $wanted | ||
| 385 | if length($raw) != $wanted; | ||
| 386 | |||
| 387 | return $raw; | ||
| 388 | } | ||
| 389 | |||
| 390 | has _json => ( is => 'lazy' ); | ||
| 391 | |||
| 392 | sub _build__json { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 393 | my ($self) = @_; | ||
| 394 | my $module = $self->json_module; | ||
| 395 | croak "Dancer2::Session::Pg: implausible json_module '$module'" | ||
| 396 | if $module !~ m/\A[[:alpha:]_]\w*(?:::[[:alpha:]_]\w*)*\z/msx; | ||
| 397 | return use_module($module)->new->utf8(1)->canonical(1); | ||
| 398 | } | ||
| 399 | |||
| 400 | has _own_dbh => ( is => 'lazy', clearer => 1, predicate => 1 ); | ||
| 401 | |||
| 402 | sub _build__own_dbh { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 403 | my ($self) = @_; | ||
| 404 | my $dsn = $self->dsn; | ||
| 405 | $dsn .= ';connect_timeout=' . $self->connect_timeout | ||
| 406 | if $self->connect_timeout && $dsn !~ m/connect_timeout=/msx; | ||
| 407 | |||
| 408 | my $dbh = DBI->connect( | ||
| 409 | $dsn, | ||
| 410 | $self->dbuser, | ||
| 411 | $self->dbpass, | ||
| 412 | { | ||
| 413 | RaiseError => 1, | ||
| 414 | PrintError => 0, | ||
| 415 | AutoCommit => 1, | ||
| 416 | pg_enable_utf8 => 1, | ||
| 417 | }, | ||
| 418 | ); | ||
| 419 | |||
| 420 | $dbh->do( sprintf 'SET statement_timeout = %d', $self->statement_timeout ) | ||
| 421 | if $self->statement_timeout; | ||
| 422 | |||
| 423 | return $dbh; | ||
| 424 | } | ||
| 425 | |||
| 426 | sub _dbh { | ||
| 427 | my ($self) = @_; | ||
| 428 | |||
| 429 | # A handle we were given belongs to the caller: its attributes, its | ||
| 430 | # transaction, its lifetime. We neither reconfigure nor reconnect it. | ||
| 431 | # | ||
| 432 | # RaiseError is the one exception, and it is a refusal rather than a warning | ||
| 433 | # because without it this module reports nonsense instead of failing. With | ||
| 434 | # DBI's default of RaiseError => 0, `do` and `execute` return undef on | ||
| 435 | # error: a lost session write looks like a successful one, and | ||
| 436 | # destroy_for_principal answers "0 sessions revoked" when the DELETE | ||
| 437 | # actually failed. Being told an account's sessions are gone when they are | ||
| 438 | # not is worse than any error this could raise. | ||
| 439 | # | ||
| 440 | # Checked on every access rather than memoised: a pool may hand out a | ||
| 441 | # different handle each time, and one attribute read is cheap beside the | ||
| 442 | # queries that follow. | ||
| 443 | if ( $self->has_dbh ) { | ||
| 444 | my $handle = $self->dbh; | ||
| 445 | $handle = $handle->() if ref $handle eq 'CODE'; | ||
| 446 | |||
| 447 | croak 'Dancer2::Session::Pg: the supplied dbh has RaiseError off. This module ' | ||
| 448 | . 'checks no DBI return values of its own, so a failed write would be reported ' | ||
| 449 | . 'as a success and a failed revocation as "0 sessions". Set RaiseError => 1 on ' | ||
| 450 | . 'the handle you pass, or pass a dsn and let this module open its own.' | ||
| 451 | if !$handle->{'RaiseError'}; | ||
| 452 | |||
| 453 | # The coderef case BUILD could not reach. Warn rather than croak: | ||
| 454 | # AutoCommit off is a legitimate choice by the caller, who then owns the | ||
| 455 | # commit -- unlike RaiseError off, which leaves this module reporting | ||
| 456 | # nonsense. Once per worker, via the same message BUILD would have used. | ||
| 457 | $self->_warn_if_manual_commit($handle); | ||
| 458 | |||
| 459 | return $handle; | ||
| 460 | } | ||
| 461 | |||
| 462 | my $dbh = $self->_own_dbh; | ||
| 463 | return $dbh if $dbh && $dbh->ping; | ||
| 464 | |||
| 465 | # One reconnect: a process should survive a database restart without a | ||
| 466 | # rollout, but a connection failing twice is a fault and must surface. | ||
| 467 | # | ||
| 468 | # Reported, because a silent reconnect is indistinguishable from nothing | ||
| 469 | # happening. One of these after a database restart is the system working; | ||
| 470 | # one in every process, repeatedly, is a connection being killed by | ||
| 471 | # something -- an idle timeout, a pooler, a firewall -- and without a line | ||
| 472 | # in the log there is nothing to notice. | ||
| 473 | $self->_report_once( 'info', 'the database connection had gone away and was reopened (reported once per worker)' ); | ||
| 474 | $self->_clear_own_dbh; | ||
| 475 | return $self->_own_dbh; | ||
| 476 | } | ||
| 477 | |||
| 478 | has _table => ( is => 'lazy' ); | ||
| 479 | |||
| 480 | sub _build__table { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 481 | my ($self) = @_; | ||
| 482 | my $schema = $self->dbschema; | ||
| 483 | return $self->_dbh->quote_identifier( $self->dbtable ) | ||
| 484 | if !defined $schema || !length $schema; | ||
| 485 | return $self->_dbh->quote_identifier( undef, $schema, $self->dbtable ); | ||
| 486 | } | ||
| 487 | |||
| 488 | has _principal_column => ( is => 'lazy' ); | ||
| 489 | |||
| 490 | sub _build__principal_column { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- a Moo lazy builder, reached through the attribute and never by name | ||
| 491 | my ($self) = @_; | ||
| 492 | |||
| 493 | # An identifier cannot be a bind parameter, so the only safe way to put a | ||
| 494 | # configured column name into SQL is to let the driver quote it. | ||
| 495 | return $self->_dbh->quote_identifier( $self->principal_column ); | ||
| 496 | } | ||
| 497 | |||
| 498 | sub _principal_of { | ||
| 499 | my ( $self, $data ) = @_; | ||
| 500 | my $key = $self->principal_key; | ||
| 501 | my $value = ref $key eq 'CODE' ? $key->($data) : $data->{$key}; | ||
| 502 | |||
| 503 | # Only a scalar is worth indexing, and a reference is not an identifier. | ||
| 504 | # | ||
| 505 | # REPORTED, because this is a configuration mistake that disables a security | ||
| 506 | # feature in silence. principal_key pointing at a structure leaves the column | ||
| 507 | # NULL, destroy_for_principal then never finds the session, and suspending | ||
| 508 | # the account quietly fails to end it. The VALUE is not logged -- it is | ||
| 509 | # session content, and some of it is the reason this module encrypts. | ||
| 510 | if ( ref $value ) { | ||
| 511 | $self->_report_once( 'warning', | ||
| 512 | 'principal_key produced a ' | ||
| 513 | . ref($value) | ||
| 514 | . ' reference rather than a value, so ' | ||
| 515 | . 'the principal column was left NULL. Sessions written this way cannot be found ' | ||
| 516 | . 'by destroy_for_principal. Give principal_key a coderef that returns one scalar.' ); | ||
| 517 | return (); | ||
| 518 | } | ||
| 519 | |||
| 520 | return $value; | ||
| 521 | } | ||
| 522 | |||
| 523 | # --------------------------------------------------------------------------- | ||
| 524 | # Payload | ||
| 525 | # --------------------------------------------------------------------------- | ||
| 526 | # | ||
| 527 | # Layout: version || cipher id || key id || iv || tag || ciphertext. | ||
| 528 | |||
| 529 | has _reported => ( is => 'ro', default => sub { {} } ); | ||
| 530 | |||
| 531 | # --------------------------------------------------------------------------- | ||
| 532 | # What this module logs, and the much longer list of what it does not | ||
| 533 | # --------------------------------------------------------------------------- | ||
| 534 | # | ||
| 535 | # THE SESSION ID IS A BEARER TOKEN. Dancer2::Core::App::_build_session takes it | ||
| 536 | # straight from the session cookie, so an id in a log file is a live credential | ||
| 537 | # in a log file, and read access to the log becomes session hijacking. That one | ||
| 538 | # fact rules out most of what a store like this would otherwise report: no id on | ||
| 539 | # a retrieve, a write, a destroy or a decrypt failure. The principal is out for | ||
| 540 | # the same reason plus a second one -- it names a person, and the clear column | ||
| 541 | # exists so that revocation needs no decryption, not so that every request | ||
| 542 | # writes an account identifier to disk. | ||
| 543 | # | ||
| 544 | # So nothing here is logged per session. What IS logged is per PROCESS and | ||
| 545 | # per CONFIGURATION: states an operator can act on, each reported once, with | ||
| 546 | # counts and integers rather than identifiers. | ||
| 547 | # | ||
| 548 | # `report_once` and not `log`: anything on the request path can fire on every | ||
| 549 | # request, and a message repeated ten thousand times is a message nobody reads. | ||
| 550 | sub _report_once { | ||
| 551 | my ( $self, $level, $message ) = @_; | ||
| 552 | return if $self->_reported->{$message}++; | ||
| 553 | $self->log_cb->( $level, "Dancer2::Session::Pg: $message" ); | ||
| 554 | return; | ||
| 555 | } | ||
| 556 | |||
| 557 | # An unreadable row is not an error: it is a session this engine does not have, | ||
| 558 | # and Dancer2 answers that by starting a fresh one. But silence here is how a | ||
| 559 | # changed key becomes "everybody keeps getting logged out" with nothing written | ||
| 560 | # down anywhere. | ||
| 561 | sub _unreadable { | ||
| 562 | my ( $self, $message ) = @_; | ||
| 563 | $self->_report_once( 'warning', "a stored session could not be read: $message" ); | ||
| 564 | return; | ||
| 565 | } | ||
| 566 | |||
| 567 | # THE PAYLOAD IS SEALED AGAINST THE SESSION IT BELONGS TO. The header and the | ||
| 568 | # session id go in as additional authenticated data: authenticated, not | ||
| 569 | # encrypted, so they are covered by the tag without being stored twice. | ||
| 570 | # | ||
| 571 | # Without this the tag covers the payload and nothing else, and a payload is | ||
| 572 | # then portable between rows. Somebody with UPDATE on this table and NO | ||
| 573 | # ENCRYPTION KEY AT ALL could copy an administrator's sealed session_data into | ||
| 574 | # their own row and their cookie would open it -- the bytes verify, because | ||
| 575 | # nothing in them says which session they were for. Binding the id makes that | ||
| 576 | # copy fail to decrypt, which is the same answer the module gives to any other | ||
| 577 | # alteration. | ||
| 578 | # WHAT GOES IN THE `id` COLUMN IS A DIGEST, NOT THE COOKIE. | ||
| 579 | # | ||
| 580 | # The session id IS a bearer token: Dancer2 takes it straight off the cookie and | ||
| 581 | # this module hands back whatever it unlocks. Storing it verbatim would mean a | ||
| 582 | # database dump contained a working credential for every unexpired session -- | ||
| 583 | # readable without the encryption key and replayable against any reachable | ||
| 584 | # instance of the application. Encrypting the payload while storing the id in | ||
| 585 | # the clear protects what is inside the house and leaves the front door key | ||
| 586 | # under the mat. | ||
| 587 | # | ||
| 588 | # So the column holds SHA-256 of the id. The cookie is unchanged, every lookup | ||
| 589 | # hashes first, and a dump yields digests that cannot be replayed. | ||
| 590 | # | ||
| 591 | # UNKEYED, deliberately. A keyed digest would also stop an attacker confirming a | ||
| 592 | # guessed id, but Dancer2's ids are long and random -- the same reason an API | ||
| 593 | # token needs no salt. And a key here could never be rotated: rotating it would | ||
| 594 | # orphan every live session, in a module whose entire design is that keys | ||
| 595 | # rotate. One un-rotatable key hiding among the rotatable ones is a worse trap | ||
| 596 | # than the attack it would prevent. | ||
| 597 | # | ||
| 598 | # The payload binding in _aad still uses the RAW id, so a sealed payload stays | ||
| 599 | # tied to the session it was written for rather than to its digest. | ||
| 600 | sub _row_id { | ||
| 601 | my ( $self, $id ) = @_; | ||
| 602 | return sha256_hex( defined $id ? $id : q{} ); | ||
| 603 | } | ||
| 604 | |||
| 605 | sub _aad { | ||
| 606 | my ( $self, $header, $id ) = @_; | ||
| 607 | return $header . ( defined $id ? $id : q{} ); | ||
| 608 | } | ||
| 609 | |||
| 610 | sub _encrypt { | ||
| 611 | my ( $self, $id, $data ) = @_; | ||
| 612 | |||
| 613 | my $slot_id = $self->_write_slot_id; | ||
| 614 | my $slot = $self->_slots->{$slot_id}; | ||
| 615 | my $cipher = $slot->{'cipher'}; | ||
| 616 | |||
| 617 | my $iv = Crypt::PRNG::random_bytes( $cipher->iv_bytes ); | ||
| 618 | my $header = pack 'C3', FORMAT_VERSION, $cipher->cipher_id, $slot_id; | ||
| 619 | my ( $ciphertext, $tag ) = $cipher->seal( $slot->{'key'}, $iv, $self->_json->encode($data), $self->_aad( $header, $id ) ); | ||
| 620 | return $header . $iv . $tag . $ciphertext; | ||
| 621 | } | ||
| 622 | |||
| 623 | sub _decrypt { | ||
| 624 | my ( $self, $id, $blob ) = @_; | ||
| 625 | return () if !defined $blob || length $blob < HEADER_BYTES; | ||
| 626 | |||
| 627 | my ( $version, $cipher_id, $key_id ) = unpack 'C3', $blob; | ||
| 628 | |||
| 629 | return $self->_unreadable("stored format version $version is not one this release writes") | ||
| 630 | if $version != FORMAT_VERSION; | ||
| 631 | |||
| 632 | # The row names its slot, so this is one lookup. Not a loop over every key: | ||
| 633 | # trying them all would turn a misconfiguration into something that looks | ||
| 634 | # exactly like a tampered row. | ||
| 635 | my $slot = $self->_slots->{$key_id}; | ||
| 636 | return $self->_unreadable( | ||
| 637 | "key id $key_id is not configured" . ' -- keep the retired slot in encryption_keys until its sessions have expired' ) | ||
| 638 | if !$slot; | ||
| 639 | |||
| 640 | my $cipher = $slot->{'cipher'}; | ||
| 641 | |||
| 642 | # The cipher id is a CROSS-CHECK rather than a selector: the slot already | ||
| 643 | # says which cipher it uses. They disagree only when a slot's alg was edited | ||
| 644 | # in place while rows written under the old one were still alive, which is | ||
| 645 | # the one rotation mistake the slots cannot prevent -- so say exactly that | ||
| 646 | # instead of letting it surface as a decrypt failure. | ||
| 647 | return $self->_unreadable( | ||
| 648 | sprintf 'slot %d now says %s, but this row was written with ' | ||
| 649 | . 'cipher id %d. Changing a slot\'s alg in place strands its sessions; give the ' | ||
| 650 | . 'new cipher a slot of its own', | ||
| 651 | $key_id, $cipher->cipher_name, $cipher_id ) | ||
| 652 | if $cipher_id != $cipher->cipher_id; | ||
| 653 | |||
| 654 | my $key = $slot->{'key'}; | ||
| 655 | |||
| 656 | my $tag_at = HEADER_BYTES + $cipher->iv_bytes; | ||
| 657 | my $body_at = $tag_at + $cipher->tag_bytes; | ||
| 658 | return () if length $blob <= $body_at; | ||
| 659 | |||
| 660 | my $plain = eval { | ||
| 661 | $cipher->unseal( | ||
| 662 | $key, | ||
| 663 | substr( $blob, HEADER_BYTES, $cipher->iv_bytes ), | ||
| 664 | substr( $blob, $body_at ), | ||
| 665 | substr( $blob, $tag_at, $cipher->tag_bytes ), | ||
| 666 | $self->_aad( substr( $blob, 0, HEADER_BYTES ), $id ), | ||
| 667 | ); | ||
| 668 | }; | ||
| 669 | return $self->_unreadable( | ||
| 670 | sprintf '%s did not authenticate it -- the key of its slot in encryption_keys' | ||
| 671 | . ' has changed, the row was altered, or the payload belongs to a different session id', | ||
| 672 | $cipher->cipher_name | ||
| 673 | ) if !defined $plain; | ||
| 674 | |||
| 675 | my $data = eval { $self->_json->decode($plain) }; | ||
| 676 | return $self->_unreadable('it decrypted, but is not the JSON this module wrote') | ||
| 677 | if !defined $data; | ||
| 678 | |||
| 679 | return $data; | ||
| 680 | } | ||
| 681 | |||
| 682 | # --------------------------------------------------------------------------- | ||
| 683 | # Dancer2::Core::Role::SessionFactory | ||
| 684 | # --------------------------------------------------------------------------- | ||
| 685 | |||
| 686 | sub _retrieve { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- required by Dancer2::Core::Role::SessionFactory, which is what calls it | ||
| 687 | my ( $self, $id ) = @_; | ||
| 688 | my $table = $self->_table; | ||
| 689 | |||
| 690 | # Expiry is decided by the server's clock. Application clocks drift, and two | ||
| 691 | # processes disagreeing about whether a session is alive makes the answer | ||
| 692 | # depend on which one the request reached. | ||
| 693 | my $row = | ||
| 694 | $self->_dbh->selectrow_arrayref( "SELECT session_data FROM $table WHERE id = ? AND (expires IS NULL OR expires > now())", | ||
| 695 | undef, $self->_row_id($id), ); | ||
| 696 | |||
| 697 | return () if !$row; | ||
| 698 | return $self->_decrypt( $id, $row->[0] ); | ||
| 699 | } | ||
| 700 | |||
| 701 | sub _flush { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- required by Dancer2::Core::Role::SessionFactory, which is what calls it | ||
| 702 | my ( $self, $id, $data ) = @_; | ||
| 703 | my $table = $self->_table; | ||
| 704 | |||
| 705 | my $seconds = $self->has_session_duration ? $self->session_duration : undef; | ||
| 706 | my $expires = defined $seconds ? q{now() + (? * interval '1 second')} : 'NULL'; | ||
| 707 | |||
| 708 | my ( @columns, @values, @bind ); | ||
| 709 | push @columns, 'id'; | ||
| 710 | push @values, q{?}; | ||
| 711 | push @bind, [ $self->_row_id($id), undef ]; | ||
| 712 | if ( defined $self->principal_key ) { | ||
| 713 | |||
| 714 | # Assigned to a scalar first, ON PURPOSE. _principal_of returns a bare | ||
| 715 | # `return;` when the value is not a scalar, which in LIST context is an | ||
| 716 | # empty list -- so inlining the call would collapse the pair to a | ||
| 717 | # one-element arrayref. It binds NULL either way today, which is the | ||
| 718 | # intended result, but by luck rather than by design. | ||
| 719 | my $principal = $self->_principal_of($data); | ||
| 720 | push @columns, $self->_principal_column; | ||
| 721 | push @values, q{?}; | ||
| 722 | push @bind, [ $principal, undef ]; | ||
| 723 | } | ||
| 724 | push @columns, 'session_data'; | ||
| 725 | push @values, q{?}; | ||
| 726 | push @bind, [ $self->_encrypt( $id, $data ), { pg_type => PG_BYTEA } ]; | ||
| 727 | push @columns, 'created'; | ||
| 728 | push @values, 'now()'; | ||
| 729 | push @columns, 'updated'; | ||
| 730 | push @values, 'now()'; | ||
| 731 | push @columns, 'expires'; | ||
| 732 | push @values, $expires; | ||
| 733 | push @bind, [ $seconds, undef ] if defined $seconds; | ||
| 734 | |||
| 735 | # `expires` is NOT reassigned on conflict, and that is the whole point of the | ||
| 736 | # cap. Dancer2::Core::Role::SessionFactory documents session_duration as a | ||
| 737 | # limit on session validity regardless of the cookie; a limit that every | ||
| 738 | # write pushes further away is not a limit, and the session that would never | ||
| 739 | # reach it is exactly the one an attacker holding stolen cookies is using. | ||
| 740 | # The row keeps the expiry it was created with. | ||
| 741 | my $assignments = join ",\n ", map { "$_ = EXCLUDED.$_" } | ||
| 742 | grep { $_ ne 'id' && $_ ne 'created' && $_ ne 'updated' && $_ ne 'expires' } @columns; | ||
| 743 | |||
| 744 | my $sql = sprintf <<'SQL', $table, join( q{, }, @columns ), join( q{, }, @values ), $assignments; | ||
| 745 | INSERT INTO %s (%s) | ||
| 746 | VALUES (%s) | ||
| 747 | ON CONFLICT (id) DO UPDATE | ||
| 748 | SET %s, | ||
| 749 | updated = now() | ||
| 750 | SQL | ||
| 751 | |||
| 752 | my $sth = $self->_dbh->prepare($sql); | ||
| 753 | my $n = 0; | ||
| 754 | for my $b (@bind) { | ||
| 755 | $n++; | ||
| 756 | $b->[1] ? $sth->bind_param( $n, $b->[0], $b->[1] ) : $sth->bind_param( $n, $b->[0] ); | ||
| 757 | } | ||
| 758 | $sth->execute; | ||
| 759 | return; | ||
| 760 | } | ||
| 761 | |||
| 762 | sub _destroy { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- required by Dancer2::Core::Role::SessionFactory, which is what calls it | ||
| 763 | my ( $self, $id ) = @_; | ||
| 764 | croak 'Dancer2::Session::Pg: no session id passed to _destroy' if !defined $id; | ||
| 765 | my $table = $self->_table; | ||
| 766 | $self->_dbh->do( "DELETE FROM $table WHERE id = ?", undef, $self->_row_id($id) ); | ||
| 767 | return; | ||
| 768 | } | ||
| 769 | |||
| 770 | sub _change_id { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- required by Dancer2::Core::Role::SessionFactory, which is what calls it | ||
| 771 | my ( $self, $old_id, $new_id ) = @_; | ||
| 772 | my $table = $self->_table; | ||
| 773 | |||
| 774 | # A rename cannot be a rename any more. The payload is sealed against its | ||
| 775 | # session id, so moving the row to a new id means RE-SEALING it -- which is | ||
| 776 | # the price of making a payload unportable between rows, and it is charged | ||
| 777 | # on login, where one extra round trip is affordable. | ||
| 778 | my $row = $self->_dbh->selectrow_arrayref( "SELECT session_data FROM $table WHERE id = ?", undef, $self->_row_id($old_id) ); | ||
| 779 | my $data = $row ? $self->_decrypt( $old_id, $row->[0] ) : undef; | ||
| 780 | |||
| 781 | if ( !defined $data ) { | ||
| 782 | |||
| 783 | # Nothing readable to carry across. Delete rather than rename: a payload | ||
| 784 | # nobody can open is worth less under a new id than it is gone, and the | ||
| 785 | # caller still holds the session, so the next flush writes it afresh. | ||
| 786 | $self->_dbh->do( "DELETE FROM $table WHERE id = ?", undef, $self->_row_id($old_id) ); | ||
| 787 | return; | ||
| 788 | } | ||
| 789 | |||
| 790 | my $sth = $self->_dbh->prepare("UPDATE $table SET id = ?, session_data = ?, updated = now() WHERE id = ?"); | ||
| 791 | $sth->bind_param( 1, $self->_row_id($new_id) ); | ||
| 792 | $sth->bind_param( 2, $self->_encrypt( $new_id, $data ), { pg_type => PG_BYTEA } ); | ||
| 793 | $sth->bind_param( 3, $self->_row_id($old_id) ); | ||
| 794 | $sth->execute; | ||
| 795 | return; | ||
| 796 | } | ||
| 797 | |||
| 798 | sub _sessions { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) -- required by Dancer2::Core::Role::SessionFactory, which is what calls it | ||
| 799 | my ($self) = @_; | ||
| 800 | my $table = $self->_table; | ||
| 801 | my $ids = $self->_dbh->selectcol_arrayref("SELECT id FROM $table WHERE expires IS NULL OR expires > now()"); | ||
| 802 | return $ids || []; | ||
| 803 | } | ||
| 804 | |||
| 805 | # --------------------------------------------------------------------------- | ||
| 806 | # What the clear columns make possible | ||
| 807 | # --------------------------------------------------------------------------- | ||
| 808 | |||
| 809 | sub _require_principal { | ||
| 810 | my ( $self, $method ) = @_; | ||
| 811 | croak sprintf | ||
| 812 | 'Dancer2::Session::Pg: %s needs principal_key to be configured, and a %s column in the table', | ||
| 813 | $method, $self->principal_column | ||
| 814 | if !defined $self->principal_key; | ||
| 815 | return; | ||
| 816 | } | ||
| 817 | |||
| 818 | sub destroy_for_principal { | ||
| 819 | my ( $self, $principal ) = @_; | ||
| 820 | $self->_require_principal('destroy_for_principal'); | ||
| 821 | croak 'Dancer2::Session::Pg: destroy_for_principal needs a principal' | ||
| 822 | if !defined $principal || !length $principal; | ||
| 823 | my $table = $self->_table; | ||
| 824 | my $column = $self->_principal_column; | ||
| 825 | return 0 + $self->_dbh->do( "DELETE FROM $table WHERE $column = ?", undef, $principal ); | ||
| 826 | } | ||
| 827 | |||
| 828 | # THE OTHER HALF OF sessions(). _sessions returns what the id column holds, | ||
| 829 | # which is a digest, and Dancer2::Core::Role::SessionFactory documents those | ||
| 830 | # values as the input to a cleaning script. Hashing is what breaks that: handing | ||
| 831 | # a digest back to destroy() would hash it a second time and match no row, so | ||
| 832 | # the script would report success having deleted nothing. | ||
| 833 | # | ||
| 834 | # So the pair is explicit rather than clever. destroy() takes a session id and | ||
| 835 | # hashes it; this takes a value the id column already holds and does not. Each | ||
| 836 | # method has ONE input language, and passing the wrong one croaks instead of | ||
| 837 | # quietly doing nothing. | ||
| 838 | # | ||
| 839 | # Deliberately NOT a shape check inside destroy(): a digest is 64 hex characters | ||
| 840 | # and a Dancer2 id is 32 base64url ones, so they cannot collide today -- but | ||
| 841 | # generate_id is overridable, and a heuristic in the main delete path would turn | ||
| 842 | # somebody's custom id format into a silent no-op. A separate method cannot. | ||
| 843 | sub destroy_row { | ||
| 844 | my ( $self, $row_id ) = @_; | ||
| 845 | |||
| 846 | croak 'Dancer2::Session::Pg: destroy_row needs a row id from sessions() or ' | ||
| 847 | . 'sessions_for_principal() -- 64 hex characters. To delete by SESSION id, ' | ||
| 848 | . 'which is what a cookie holds, use destroy() instead' | ||
| 849 | if !defined $row_id | ||
| 850 | || $row_id !~ m/\A[0-9a-f]{64}\z/msx; ## no critic (RegularExpressions::ProhibitEnumeratedClasses) -- sha256_hex output is ASCII lower-case hex; [[:xdigit:]] is Unicode-aware and allows A-F | ||
| 851 | |||
| 852 | my $table = $self->_table; | ||
| 853 | return 0 + $self->_dbh->do( "DELETE FROM $table WHERE id = ?", undef, $row_id ); | ||
| 854 | } | ||
| 855 | |||
| 856 | sub sessions_for_principal { | ||
| 857 | my ( $self, $principal ) = @_; | ||
| 858 | $self->_require_principal('sessions_for_principal'); | ||
| 859 | my $table = $self->_table; | ||
| 860 | my $column = $self->_principal_column; | ||
| 861 | my $ids = $self->_dbh->selectcol_arrayref( "SELECT id FROM $table WHERE $column = ? AND (expires IS NULL OR expires > now())", | ||
| 862 | undef, $principal, ); | ||
| 863 | return $ids || []; | ||
| 864 | } | ||
| 865 | |||
| 866 | sub reap { | ||
| 867 | my ($self) = @_; | ||
| 868 | my $table = $self->_table; | ||
| 869 | return 0 + $self->_dbh->do("DELETE FROM $table WHERE expires IS NOT NULL AND expires <= now()"); | ||
| 870 | } | ||
| 871 | |||
| 872 | # THE NUMBERS IN ONE ROUND TRIP, because they are only useful together: live | ||
| 873 | # sessions say how many browsers are holding one, signed_in says how many belong | ||
| 874 | # to somebody, and expired says how much reap() would remove right now -- a | ||
| 875 | # number that only grows if the reaping trigger has stopped working. | ||
| 876 | # | ||
| 877 | # NOTHING IS DECRYPTED and nobody is named. The clear columns answer all of them, | ||
| 878 | # which is what they are for. | ||
| 879 | # | ||
| 880 | # `signed_in` IS ABSENT when principal_key is unset, rather than zero or undef. | ||
| 881 | # The column need not exist in that configuration, so there is no query that | ||
| 882 | # could answer it -- asking anyway used to be a crash against the table this | ||
| 883 | # module's own documentation tells you to create. | ||
| 884 | sub count_sessions { | ||
| 885 | my ($self) = @_; | ||
| 886 | my $table = $self->_table; | ||
| 887 | my $live = 'count(*) FILTER (WHERE expires IS NULL OR expires > now())'; | ||
| 888 | my $expired = 'count(*) FILTER (WHERE expires IS NOT NULL AND expires <= now())'; | ||
| 889 | |||
| 890 | if ( !defined $self->principal_key ) { | ||
| 891 | my ( $l, $e ) = $self->_dbh->selectrow_array("SELECT $live, $expired FROM $table"); | ||
| 892 | return { live => $l, expired => $e }; | ||
| 893 | } | ||
| 894 | |||
| 895 | my $column = $self->_principal_column; | ||
| 896 | my ( $l, $s, $e ) = $self->_dbh->selectrow_array( | ||
| 897 | "SELECT $live, | ||
| 898 | count(*) FILTER (WHERE (expires IS NULL OR expires > now()) | ||
| 899 | AND $column IS NOT NULL), | ||
| 900 | $expired | ||
| 901 | FROM $table" | ||
| 902 | ); | ||
| 903 | return { live => $l, signed_in => $s, expired => $e }; | ||
| 904 | } | ||
| 905 | |||
| 906 | 1; | ||
| 907 | __END__ | ||