blib/lib/DBIx/Class/BcryptColumn.pm

filter: Statementstmt 97.4% 76 / 78 Branchbran 78.5% 11 / 14 Conditioncond 53.8% 7 / 13 MC/DCmcdc 25.0% 2 / 8 Subroutinesub 100% 20 / 20 Podpod 57.1% 4 / 7 totaltotal 85.7% 120 / 140 CC 15 SCAR 9.5
CC
15
Cov
90%
_get_normalized_bcrypt_args
4.2
register_column
4.1
update
4.1
CRAP 2.6
↑ Summary
1 package DBIx::Class::BcryptColumn;
2  
3 1 our $VERSION = '0.001003';
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Crypt::Bcrypt ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Crypt::URandom ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Sub::Name ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 ▶use parent 'DBIx::Class';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 __PACKAGE__->mk_classdata('_bcrypt_columns_info');
14  
15 1 our $DEFAULT_COST = 12;
16 1 our $SALT_SIZE = 16; # You really can't change this
17  
18 1 ▶sub default_cost { return $DEFAULT_COST }
Subroutine default_cost: called CC=1 SCAR=0.0
Pod documented
19  
20 3 ▶sub generate_salt {
Subroutine generate_salt: called CC=2 SCAR=7.6
Pod documented
21 3 my ($self, $size) = @_;
22 3 ▶ $size ||= $SALT_SIZE;
Condition33%1/3
$size ||= $DBIx::Class::BcryptColumn::SALT_SIZE
l!l&&r!l&&!r
030
MC/DC0%0/2
$size ||= $DBIx::Class::BcryptColumn::SALT_SIZE
$size $DBIx::Class::BcryptColumn::SALT_SIZE
Truth table33%1/3
A ||= B
A= $sizeB= $DBIx::Class::BcryptColumn::SALT_SIZE
ABresult
1X1
011
000
23 3 return Crypt::URandom::urandom($size);
24 }
25
26 1 ▶sub _default_check_method_format {
Subroutine _default_check_method_format: called CC=1 SCAR=0.0
27 1 my ($self, $column, $info) = @_;
28 1 return "check_${column}";
29 }
30  
31 1 ▶sub _default_check_generator {
Subroutine _default_check_generator: called CC=1 SCAR=0.0
32 1 my ($self, $column, %info) = @_;
33 5 ▶ return sub {
Subroutine check_password: called CC=1 SCAR=0.0
34 5 my ($self, $value_to_check) = @_;
35 5 my $col_value = $self->get_column($column);
36 5 return Crypt::Bcrypt::bcrypt_check($value_to_check, $col_value);
37 1 };
38 }
39  
40 3 ▶sub _get_normalized_bcrypt_args {
Subroutine _get_normalized_bcrypt_args: called CC=4 SCAR=14.5
41 3 my ($self, $column, $info) = @_;
42 3 ▶ return unless exists $info->{bcrypt};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $info->{"bcrypt"} 2 1 3
43  
44 0 ▶ my %info = $info->{bcrypt} eq '1' ? () : %{$info->{bcrypt}};
Branch: 1 branch
BranchTrueFalseTotal
$info->{'bcrypt'} eq '1' ? : 1 0 1
45 1 ▶ $info{cost} = $self->default_cost unless exists $info{cost};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $info{"cost"} 1 0 1
46 1 return %info;
47 }
48  
49 1 ▶sub _inject_check_method {
Subroutine _inject_check_method: called CC=1 SCAR=0.0
50 1 my ($self, $check_name, $check_subref) = @_;
51  
52 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
53 1 *$check_name = Sub::Name::subname $check_name => $check_subref;
54 }
55  
56 3 ▶sub bcrypt {
Subroutine bcrypt: called CC=1 SCAR=0.0
Pod documented
57 3 my ($self, $password, $cost) = @_;
58 3 return Crypt::Bcrypt::bcrypt($password, '2b', $cost, $self->generate_salt);
59 }
60  
61 3 ▶sub register_column {
Subroutine register_column: called CC=4 SCAR=14.1
Pod undocumented
62 3 my ($self, $column, $info, @rest) = @_;
63 3 $self->next::method($column, $info, @rest);
64
65 3 ▶ return unless my %info = $self->_get_normalized_bcrypt_args($column, $info);
Branch: 1 branch
BranchTrueFalseTotal
unless my(%info) = $self->_get_normalized_bcrypt_args($column, $info) 2 1 3
66  
67 $self->_bcrypt_columns_info({
68 1 ▶ %{ $self->_bcrypt_columns_info || {} },
Condition50%1/2
$self->_bcrypt_columns_info || {}
l!l
01
MC/DC0%0/1
$self->_bcrypt_columns_info || {}
$self->_bcrypt_columns_info
Truth table50%1/2
A
A= $self->_bcrypt_columns_info
Aresult
11
00
69 $column => \%info,
70 });
71
72 1 ▶ my $method_name = $info{'check_method'} || $self->_default_check_method_format($column, $info);
Condition33%1/3
$info{'check_method'} || $self->_default_check_method_format($column, $info)
l!l&&r!l&&!r
010
MC/DC0%0/2
$info{'check_method'} || $self->_default_check_method_format($column, $info)
$info{'check_method'} $self->_default_check_method_format($column, $info)
Truth table33%1/3
A || B
A= $info{'check_method'}B= $self->_default_check_method_format($column, $info)
ABresult
1X1
011
000
73 1 my $check_subref = $self->_default_check_generator($column, %info);
74 1 my $check_name = join q[::] => $self->result_class, $method_name;
75  
76 1 $self->_inject_check_method($check_name, $check_subref);
77 }
78  
79 6 ▶sub bcrypt_columns {
Subroutine bcrypt_columns: called CC=2 SCAR=7.1
Pod documented
80 6 my $self = shift;
81 6 ▶ return my @columns = keys %{ $self->_bcrypt_columns_info||+{} };
Condition50%1/2
$self->_bcrypt_columns_info || {}
l!l
60
MC/DC0%0/1
$self->_bcrypt_columns_info || {}
$self->_bcrypt_columns_info
Truth table50%1/2
A
A= $self->_bcrypt_columns_info
Aresult
11
00
82 }
83  
84 4 ▶sub _bcrypt_set_columns {
Subroutine _bcrypt_set_columns: called CC=4 SCAR=13.9
85 4 my $self = shift;
86 4 my @columns = $self->bcrypt_columns;
87 4 foreach my $column (@columns) {
88 4 ▶ next unless $self->is_column_changed($column) || !$self->in_storage; # Don't hash unless changed (TODO: Is this premature optimization?)
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_column_changed($column) or not $self->in_storage 1 3 4
Condition100%3/3
$self->is_column_changed($column) or not $self->in_storage
l!l&&r!l&&!r
211
MC/DC100%2/2
$self->is_column_changed($column) or not $self->in_storage
$self->is_column_changed($column) not $self->in_storage
Truth table100%3/3
A or not(B)
A= $self->is_column_changed($column)B= not $self->in_storage
ABresult
1X1
011
000
89 3 my $value = $self->get_column($column);
90 3 my %info = %{$self->_bcrypt_columns_info->{$column}};
91 3 $self->set_column($column, $self->bcrypt($value, $info{cost}));
92 }
93 }
94  
95 2 ▶sub insert {
Subroutine insert: called CC=1 SCAR=0.0
Pod undocumented
96 2 my $self = shift;
97 2 $self->_bcrypt_set_columns;
98 2 $self->next::method(@_);
99 }
100
101 2 ▶sub update {
Subroutine update: called CC=4 SCAR=14.0
Pod undocumented
102 2 my ($self, $upd, @rest) = @_;
103 2 ▶ if (ref $upd) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $upd) 1 1 2
104 1 my @columns = $self->bcrypt_columns;
105 1 foreach my $column (@columns) {
106 1 ▶ next unless exists $upd->{$column};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $upd->{$column} 1 0 1
107 0 $self->set_column($column => delete $upd->{$column})
108 }
109 }
110 2 $self->_bcrypt_set_columns;
111 2 $self->next::method($upd, @rest);
112 }
113  
114 1 1;
115  
116 =head1 NAME
117  
118 DBIx::Class::BcryptColumn - Set a column to securely hash on insert/update using bcrypt
119  
120 =head1 SYNOPSIS
121  
122 __PACKAGE__->load_components('BcryptColumn');
123
124 __PACKAGE__->add_columns(
125 password => {
126 data_type => 'text',
127 bcrypt => 1, # Or a hashref of option overrides, see below
128 },
129 );
130  
131 =head1 DESCRIPTION
132  
133 It's considered best practice to store credential data about your system users (such as passwords)
134 using a one way hashing algorithm. That way if your system gets hack and your database becomes
135 compromised then at least the hackers won't know everyone's password. It also is useful as a
136 protective measure against in-house bad actors who have access to your production system as part
137 of their regular job duties.
138  
139 There's a few distributions on CPAN to make it easier to do this with L<DBIx::Class>. The two most
140 commonly cited are L<DBIx::Class::PassphraseColumn> and L<DBIx::Class::EncodedColumn>. Those are
141 both good choices for this problem and all things equal you might want to review those before making
142 a final choice. The main reason I wrote this was to solve two issues for me. First, both of those
143 perform hashing on C<new> or C<set_column> instead of on insert / update as this module does. That
144 approach is considered more secure by the DBIC community since it means that there is never a time
145 where unhashed passwords are in DBIC code and if you have a core dump or similar error those plain
146 text passwords have no chance of ending up in a file readable by an unauthorized person. However if
147 you are using L<Valiant> and its DBIC glue L<DBIx::Class::Valiant> this means you can't apply any
148 validation rules at the DBIC level such as minimal password complexity, or do things like use the
149 confirmation validator, since hashing on C<new> / C<set_column> would happen before validation occurs
150 (In L<DBIx::Class::Valiant> validation doesn't happen until you try to update / insert the data, or if
151 you manually invoke C<validate>). So For L<Valiant> users I wrote this as an option to allow you
152 to do those things if you are willing to accept the additional risk of plain text passwords in live
153 memory. Personal I find this to be a minimal additional risk since it's likely those password will reside
154 in other parts of the code memory space anyway (such as in L<Catalyst::Request>). If this risk
155 bothers you and you still want to use L<DBIx::Class::Valiant> then you can do password validation work
156 prior to sending the data to L<DBIx::Class>. For example if you are using L<Catalyst> you can invoke
157 some validation work from the controller before sending parameters to DBIC.
158  
159 As a second difference, this distribution only does hashing using the bcrypt algorithm (via
160 L<Crypt::Eksblowfish::Bcrypt>). As of late 2021 this is my goto hashing algorithm and the defaults
161 I have set should be sufficient to protect you against all but nation state level hackers. You can
162 tweak the defaults a bit to make it a harder algorithm at a higher performance cost. The other popular
163 modules mentioned above support a lot of different hashing approaches and if you are not schooled
164 in security its very easy to accidentally choose a configuration that is not secure. With this
165 module its very easy to get a setup that is considered secure today (just follow the L</SYNOPSIS>).
166 If for some reason bcrypt becomes no longer considered secure I will mark this distribution as deprecated.
167  
168 B<NOTE>: When using this with L<DBIx::Class::Valiant> you should add it AFTER adding the L<DBIx::Class::Valiant::Result>
169 component. Otherwise you will still get passwords hashed prior to running validations, which will
170 negate the entire point.
171  
172 B<NOTE>: Bcrypt has one downside in that it will truncate values at 72 bytes. This might be an issue
173 if you are using this in a country with 2 or 4 byte wide characters (such as Chinese or Japanese
174 characters). There are ways around this (the most common approach is to pre hash the password using
175 a cheaper algorithm like SHA-1) but for now those options are not available in this code. You'd need
176 to override or wrap the L</bcrypt> method. If this becomes a common issue I will consider adding an
177 option for this (open issues on the issue tracker and hassle the author :) ).
178  
179 =head1 CONFIGURATION
180  
181 This component permits the following configuration. Example usage:
182  
183 __PACKAGE__->load_components('BcryptColumn');
184
185 __PACKAGE__->add_columns(
186 password => {
187 data_type => 'text',
188 bcrypt => {
189 cost => $alt_cost,
190 check_method => $alternative_check_method,
191 }
192 },
193 );
194  
195 =over 4
196  
197 =item cost
198  
199 Defaults to 12. You can use this to change the cost used to generate the hash. I don't recommend using
200 a smaller value; using a higher one might cause performance issues on equipment commonly available in
201 late 2021 when this module was written.
202  
203 =item check_method
204  
205 By default we create a method called C<check_${column}> which is useful when you want to see if a
206 proposed value is the same as the stored but hashed value. Useful for things like logging into a
207 website. If you prefer or need a different method name you can override it here.
208  
209 =back
210  
211 =head1 METHODS
212
213 This component contains the following public methods.
214  
215 =head2 bcrypt_columns
216  
217 Returns an array of columns marked to be hashed.
218  
219 =head2 bcrypt
220  
221 Arguments: ($value, $cost)
222  
223 Returns a hashed version of C<$value> using L<Crypt::Eksblowfish::Bcrypt>. This is used internally
224 by the component to hash columns but I've exposed it as a public method since you might find it
225 useful to have in your code.
226  
227 =head2 default_cost
228  
229 Returns the default cost we use for C<bcrypt>. This is 12 unless you override. If you want a bigger cost
230 its best to set this via column level configuration.
231  
232 =head2 generate_salt
233  
234 Arguments ($size).
235  
236 Returns a salt suitable for using with C<bcrypt>. You might like to have access to this for things like
237 creating tokens. The default $size is 16, which should not be changed for salts that are used with bcrypt
238 but we offer an argument here in cast you want to make larger results. Just remember that this also runs
239 the random value thru base64 so you always get a longer strong than the size specified (although its always
240 the same length in the end).
241  
242 =head1 AUTHOR
243  
244 John Napiorkowski <jnapiork@cpan.org>
245
246 =head1 COPYRIGHT
247
248 Copyright (c) 2021 the above named AUTHOR
249
250 =head1 LICENSE
251
252 You may distribute this code under the same terms as Perl itself.
253
254 =cut
↑ Summary