blib/lib/Web/VWF/Throttle.pm untested

filter: Statementstmt 0.0% 0 / 47 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 101 CC 8 SCAR 22.4
CC
8
Cov
0%
load
20.0
backend_store_ok
12.0
_chain_is_usable
6.0
CRAP 9.4
1 package Web::VWF::Throttle;
2  
3 # A Data::Throttler backend that keeps the throttle store intact where file
4 # locks are mandatory.
5 #
6 # Data::Throttler's own YAML backend locks the store, then reads and rewrites it
7 # by file name, opening a fresh handle for each of those. Unix locks are
8 # advisory, so a second handle is unaffected and the store round-trips. Windows
9 # locks are mandatory: as the documentation for LockFileEx puts it, "if the
10 # locking process opens the file a second time, it cannot access the specified
11 # region through this second handle". Every read and every write through the
12 # new handle therefore fails there, Web::VWF::Display catches the exception and
13 # removes the store it thinks is corrupt, and throttling quietly stops working -
14 # which is a security feature turning itself off on one platform, silently.
15 #
16 # Nothing in Data::Throttler is wrong on its own terms: it uses a plain file as
17 # a lock, and the file is meant to be rewritten. The two together are what
18 # Windows cannot do, so this backend keeps the store and the YAML format, and
19 # does both the reading and the writing through the one handle that already
20 # holds the lock.
21  
22 use strict;
23 use warnings;
24  
25 use Data::Throttler (); # For Data::Throttler::Backend::YAML, which this extends
26  
27 use version; our $VERSION = version->declare('0.004.0');
28  
29 =encoding utf8
30  
31 =head1 NAME
32  
33 Web::VWF::Throttle - persistent request throttling that works on Windows too
34  
35 =head1 VERSION
36  
37 Version 0.004.0
38  
39 =head1 SYNOPSIS
40  
41 use Data::Throttler;
42 use Web::VWF::Throttle; # Defines the 'VWF' backend
43  
44 my $throttler = Data::Throttler->new(
45 max_items => 30,
46 interval => 90,
47 backend => 'VWF',
48 backend_options => { db_file => '/path/to/throttle' },
49 );
50  
51 =head1 DESCRIPTION
52  
53 C<Data::Throttler> builds its backend class name from the C<backend> option, so
54 requesting C<< backend => 'VWF' >> asks for C<Data::Throttler::Backend::VWF>.
55 This module provides that class, inheriting everything from
56 C<Data::Throttler::Backend::YAML> except the two methods that touch the store.
57 The package is deliberately in Data::Throttler's namespace, because that is where
58 Data::Throttler looks, so it is not indexed by PAUSE as part of this distribution
59 (see C<no_index> in F<Makefile.PL>) and nothing else here should be added to it.
60  
61 The YAML backend locks the store and then opens it again by name to read it and
62 to rewrite it. That is fine where locks are advisory, which is what they are on
63 Unix. Windows locks are mandatory: a process that opens the file a second time
64 cannot read or write the locked region through that second handle, so the store
65 can be neither loaded nor saved, and a caller that treats a broken store as a
66 reason to carry on unthrottled will never throttle anyone. Both methods here
67 use the handle that holds the lock instead, which is allowed to read and write
68 its own locked region on every platform.
69  
70 The file keeps the YAML format and layout that C<Data::Throttler> writes, so an
71 existing store carries on being used, and it can still be read by the backend it
72 came from.
73  
74 =head1 WHEN THE STORE CANNOT BE USED
75  
76 A store that cannot be opened, locked or written leaves the framework unable to
77 throttle anybody. The request is then served unthrottled, which is a decision
78 rather than an accident:
79  
80 =over 4
81  
82 =item * Throttling protects capacity, not privilege
83  
84 It grants access to nothing and hides nothing. A request served while the
85 store is unusable is still subject to the country blacklist, to the intrusion
86 detection beside it in the same block, and to every check the caller makes
87 afterwards.
88  
89 =item * The failure is this machine's, not the client's
90  
91 Failing closed would answer every visitor with C<429> for a fault of the
92 server. The store normally lives in the site's temporary directory, so a
93 filesystem that is full, mounted read-only or left with the wrong ownership
94 would take the whole site down - and the throttle, whose purpose is to keep the
95 site serving, would be what brought it down.
96  
97 =item * It is not quiet
98  
99 The failure is reported at error level on each request that meets it, because a
100 site that has stopped throttling anybody is a security problem rather than a
101 warning. A store that cannot be I<parsed> is a different case and heals itself:
102 C<load()> returns an empty store, C<backend_store_ok()> says so, and the caller
103 rebuilds the bucket chain over the unusable file. A store that parses but holds
104 no bucket chain parameters is healed the same way, and just as quietly - see
105 L</_chain_is_usable>.
106  
107 =item * And nothing is deleted
108  
109 The store belongs to every client, so deleting it discards their counters, and a
110 backend that cannot be used is not repaired by removing its file.
111  
112 =back
113  
114 A site that needs a hard limit even while the store is unusable needs a check
115 that does not depend on the store: at the form or the page that has to be
116 protected, rather than here.
117  
118 =head1 METHODS
119  
120 These are the methods of C<Data::Throttler::Backend::VWF>, not of
121 C<Web::VWF::Throttle> itself, which exists only to load them.
122  
123 =head2 load
124  
125 Purpose: read the store, through the locked handle when there is one.
126  
127 A store whose chain carries no bucket chain parameters comes back without that
128 chain, so that the caller rebuilds it silently rather than after comparing two
129 undefined values with the ones it was given - see L</_chain_is_usable>.
130  
131 Returns: the throttler's data, with its bucket chain restored.
132  
133 =cut
134  
135 package Data::Throttler::Backend::VWF;
136  
137 use base 'Data::Throttler::Backend::YAML';
138  
139 sub load
140 {
141 my $self = shift;
142  
143 # Nothing is locked while the store is being created, so the parent's
144 # by-name read is both correct and the only thing that can work
145 return $self->SUPER::load() unless $self->{'fh'};
146  
147 my $fh = $self->{'fh'};
148  
149 # A seek flushes anything written by the previous save and puts the
150 # read position back at the start of the file
151 seek($fh, 0, 0) or return $self->SUPER::load();
152  
153 my $yaml = do {
154 local $/;
155 <$fh>;
156 };
157  
158 # A store that cannot be parsed is no longer deleted by the caller, which
159 # now leaves it alone and reports the failure, so it has to be rebuilt
160 # here instead. Reporting nothing is what asks for that: backend_store_ok()
161 # below sees no bucket chain, Data::Throttler creates a fresh one and saves
162 # it over the unusable file.
163 # YAML warns its way through garbage before it dies; the store is about to
164 # be rebuilt, so that noise would only fill the error log
165 my $data = eval { local $SIG{__WARN__} = sub { }; YAML::Load($yaml) };
166 $data = {} if($@ || ref($data) ne 'HASH');
167 $self->native_classes_restore($data);
168  
169 # A store that parses but holds no bucket chain parameters is the one case
170 # Data::Throttler cannot rebuild quietly. native_classes_restore() has
171 # just blessed its chain into a bucket chain, so backend_store_ok() would
172 # call the store usable, and Data::Throttler then compares that chain's
173 # max_items and interval - both undef - with the ones it was given. That
174 # comparison warns once per value and then reports the parameters as
175 # changed, discarding a chain that was never usable to begin with.
176 #
177 # A store handed back without that chain never reaches the comparison: the
178 # `if($data->{chain} and ...)` in Data::Throttler's new() is false, and
179 # backend_store_ok() below says the chain cannot be reused, which is what
180 # makes it build a chain - with the parameters it was given - and save the
181 # store. The repair is the one that happened before, minus the warnings.
182 delete $data->{'chain'} unless($self->_chain_is_usable($data->{'chain'}));
183  
184 return $data;
185 }
186  
187 =head2 backend_store_ok
188  
189 Purpose: whether the store holds a bucket chain that can be reused.
190  
191 An unreadable or unparsable store used to be deleted by C<Web::VWF::Display>
192 so that the next request would write a fresh one. That deletion is gone, so the
193 rebuild happens here: a false return makes C<Data::Throttler> create the chain
194 again and save it over the unusable file, without a moment in which another
195 request can find no store at all.
196  
197 Returns: true if the store can be reused.
198  
199 =cut
200  
201 sub backend_store_ok
202 {
203 my $self = shift;
204  
205 return 1 unless(-f $self->{'db_file'});
206  
207 my $data = eval { $self->load() };
208 return 0 if($@ || ref($data) ne 'HASH');
209  
210 return $self->_chain_is_usable($data->{'chain'});
211 }
212  
213 =head2 _chain_is_usable
214  
215 Purpose: whether a chain loaded from the store carries the parameters
216 C<Data::Throttler> compares a store against.
217  
218 A chain is usable when it is a bucket chain that knows the C<max_items> and
219 C<interval> it was built with. C<chain: {}> in a store is the case this
220 catches: it parses, it restores to a bucket chain, and it has neither parameter
221 on it - so C<Data::Throttler> would compare two undefined values against the
222 configured ones, and rebuild the chain after reporting the change.
223  
224 Returns: true if the chain can be reused as it stands.
225  
226 =cut
227  
228 sub _chain_is_usable
229 {
230 # No invocant to use: the only thing this reads is the chain it is handed
231 my(undef, $chain) = @_;
232  
233 return 0 unless(ref($chain) eq 'Data::Throttler::BucketChain');
234  
235 return defined($chain->{'max_items'}) && defined($chain->{'interval'});
236 }
237  
238 =head2 save
239  
240 Purpose: write the store, through the locked handle when there is one.
241  
242 Returns: true.
243  
244 =cut
245  
246 sub save
247 {
248 my($self, $data) = @_;
249  
250 # Before the first lock the store is being created - see load() above
251 return $self->SUPER::save($data) unless $self->{'fh'};
252  
253 my $fh = $self->{'fh'};
254  
255 # Rewrite in place through the handle that owns the lock, rather than
256 # opening a second one: that is the whole point of this module
257 seek($fh, 0, 0) or die "Can't rewind $self->{'db_file'}: $!";
258 truncate($fh, 0) or die "Can't truncate $self->{'db_file'}: $!";
259 print {$fh} YAML::Dump($data) or die "Can't write $self->{'db_file'}: $!";
260  
261 return 1;
262 }
263  
264 1;
265  
266 =head1 AUTHOR
267  
268 Nigel Horne, C<< <njh at nigelhorne.com> >>
269  
270 =head1 LICENCE AND COPYRIGHT
271  
272 Copyright 2010-2026 Nigel Horne.
273  
274 Usage is subject to the GPL2 licence terms.
275 If you use it,
276 please let me know.
277  
278 =cut