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.2');
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.2
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 =head3 API SPECIFICATION
134  
135 =head4 INPUT
136  
137 {} # no arguments
138  
139 =head4 OUTPUT
140  
141 { type => 'hashref' }
142  
143 =cut
144  
145 package Data::Throttler::Backend::VWF;
146  
147 use base 'Data::Throttler::Backend::YAML';
148  
149 sub load
150 {
151 my $self = shift;
152  
153 # Nothing is locked while the store is being created, so the parent's
154 # by-name read is both correct and the only thing that can work
155 return $self->SUPER::load() unless $self->{'fh'};
156  
157 my $fh = $self->{'fh'};
158  
159 # A seek flushes anything written by the previous save and puts the
160 # read position back at the start of the file
161 seek($fh, 0, 0) or return $self->SUPER::load();
162  
163 my $yaml = do {
164 local $/;
165 <$fh>;
166 };
167  
168 # A store that cannot be parsed is no longer deleted by the caller, which
169 # now leaves it alone and reports the failure, so it has to be rebuilt
170 # here instead. Reporting nothing is what asks for that: backend_store_ok()
171 # below sees no bucket chain, Data::Throttler creates a fresh one and saves
172 # it over the unusable file.
173 # YAML warns its way through garbage before it dies; the store is about to
174 # be rebuilt, so that noise would only fill the error log
175 my $data = eval { local $SIG{__WARN__} = sub { }; YAML::Load($yaml) };
176 $data = {} if($@ || ref($data) ne 'HASH');
177 $self->native_classes_restore($data);
178  
179 # A store that parses but holds no bucket chain parameters is the one case
180 # Data::Throttler cannot rebuild quietly. native_classes_restore() has
181 # just blessed its chain into a bucket chain, so backend_store_ok() would
182 # call the store usable, and Data::Throttler then compares that chain's
183 # max_items and interval - both undef - with the ones it was given. That
184 # comparison warns once per value and then reports the parameters as
185 # changed, discarding a chain that was never usable to begin with.
186 #
187 # A store handed back without that chain never reaches the comparison: the
188 # `if($data->{chain} and ...)` in Data::Throttler's new() is false, and
189 # backend_store_ok() below says the chain cannot be reused, which is what
190 # makes it build a chain - with the parameters it was given - and save the
191 # store. The repair is the one that happened before, minus the warnings.
192 delete $data->{'chain'} unless($self->_chain_is_usable($data->{'chain'}));
193  
194 return $data;
195 }
196  
197 =head2 backend_store_ok
198  
199 Purpose: whether the store holds a bucket chain that can be reused.
200  
201 An unreadable or unparsable store used to be deleted by C<Web::VWF::Display>
202 so that the next request would write a fresh one. That deletion is gone, so the
203 rebuild happens here: a false return makes C<Data::Throttler> create the chain
204 again and save it over the unusable file, without a moment in which another
205 request can find no store at all.
206  
207 Returns: true if the store can be reused.
208  
209 =head3 API SPECIFICATION
210  
211 =head4 INPUT
212  
213 {} # no arguments
214  
215 =head4 OUTPUT
216  
217 { type => 'boolean' }
218  
219 =cut
220  
221 sub backend_store_ok
222 {
223 my $self = shift;
224  
225 return 1 unless(-f $self->{'db_file'});
226  
227 my $data = eval { $self->load() };
228 return 0 if($@ || ref($data) ne 'HASH');
229  
230 return $self->_chain_is_usable($data->{'chain'});
231 }
232  
233 =head2 _chain_is_usable
234  
235 Purpose: whether a chain loaded from the store carries the parameters
236 C<Data::Throttler> compares a store against.
237  
238 A chain is usable when it is a bucket chain that knows the C<max_items> and
239 C<interval> it was built with. C<chain: {}> in a store is the case this
240 catches: it parses, it restores to a bucket chain, and it has neither parameter
241 on it - so C<Data::Throttler> would compare two undefined values against the
242 configured ones, and rebuild the chain after reporting the change.
243  
244 Returns: true if the chain can be reused as it stands.
245  
246 =head3 API SPECIFICATION
247  
248 =head4 INPUT
249  
250 { chain => { type => 'object', optional => 1 } } # positional; anything is accepted
251  
252 =head4 OUTPUT
253  
254 { type => 'boolean' }
255  
256 =cut
257  
258 sub _chain_is_usable
259 {
260 # No invocant to use: the only thing this reads is the chain it is handed
261 my(undef, $chain) = @_;
262  
263 return 0 unless(ref($chain) eq 'Data::Throttler::BucketChain');
264  
265 return defined($chain->{'max_items'}) && defined($chain->{'interval'});
266 }
267  
268 =head2 save
269  
270 Purpose: write the store, through the locked handle when there is one.
271  
272 Returns: true. Dies when the store cannot be rewound, truncated or written
273 through the locked handle.
274  
275 =head3 API SPECIFICATION
276  
277 =head4 INPUT
278  
279 { data => { type => 'hashref' } } # positional
280  
281 =head4 OUTPUT
282  
283 { type => 'boolean' }
284  
285 =cut
286  
287 sub save
288 {
289 my($self, $data) = @_;
290  
291 # Before the first lock the store is being created - see load() above
292 return $self->SUPER::save($data) unless $self->{'fh'};
293  
294 my $fh = $self->{'fh'};
295  
296 # Rewrite in place through the handle that owns the lock, rather than
297 # opening a second one: that is the whole point of this module
298 seek($fh, 0, 0) or die "Can't rewind $self->{'db_file'}: $!";
299 truncate($fh, 0) or die "Can't truncate $self->{'db_file'}: $!";
300 print {$fh} YAML::Dump($data) or die "Can't write $self->{'db_file'}: $!";
301  
302 return 1;
303 }
304  
305 1;
306  
307 =head1 AUTHOR
308  
309 Nigel Horne, C<< <njh at nigelhorne.com> >>
310  
311 =head1 LICENCE AND COPYRIGHT
312  
313 Copyright 2010-2026 Nigel Horne.
314  
315 Usage is subject to the GPL2 licence terms.
316 If you use it,
317 please let me know.
318  
319 =cut