BlockerHelper/backends/fastly.pm

filter: Statementstmt 28.8% 120 / 416 Branchbran 30.1% 50 / 166 Conditioncond 27.4% 14 / 51 MC/DCmcdc 10.7% 3 / 28 Subroutinesub 66.6% 16 / 24 Podpod 100% 13 / 13 totaltotal 30.9% 216 / 698 CC 108 SCAR 39.7
CC
108
Cov
29%
_unban_cidr_range
90.0
re_init
90.0
flush
90.0
CRAP 52.9
« BlockerHelper/backends/dummy.pm ↑ Summary BlockerHelper/backends/cloudflare.pm »
1 package Net::Firewall::BlockerHelper::backends::fastly;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::fastly - Fastly Edge ACL backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.2.0
17  
18 =cut
19  
20 1 our $VERSION = '0.2.0';
21  
22 =head1 SYNOPSIS
23  
24 use Net::Firewall::BlockerHelper;
25  
26 my $fw_helper = Net::Firewall::BlockerHelper->new(
27 backend => 'fastly',
28 name => 'ssh',
29 options => {
30 token => $fastly_api_token,
31 service => $fastly_service_id,
32 acl => $fastly_acl_id,
33 },
34 );
35  
36 $fw_helper->init_backend;
37 $fw_helper->ban( ban => '1.2.3.4' );
38 $fw_helper->unban( ban => '1.2.3.4' );
39  
40 =head1 DESCRIPTION
41  
42 Blocks IPs remotely via the Fastly API by adding and removing entries in an
43 Edge ACL. An ACL entry is created per IP, with a /32 subnet for IPv4 and a
44 /128 subnet for IPv6. A VCL service that references the ACL and takes action
45 on matching requests must already exist.
46  
47 Auth is via a Fastly API token, passed in the C<token> option and sent in the
48 C<Fastly-Key> header.
49  
50 Blocking is per IP; ports and protocols are not supported and specifying them
51 is an error.
52  
53 L<LWP::UserAgent> is only loaded at run time, so it is only required if this
54 backend is actually used. For https, L<LWP::Protocol::https> must be present
55 as well.
56  
57 =head1 NOTES
58  
59 This backend was written going off the API docs and actual testing is
60 needed to double check a few things as the exact behavior is not clear.
61  
62 teardown currently only removes the single IP entries from the ACL,
63 leaving CIDR entries in place, while flush removes both. A re_init after
64 a teardown will re-add the CIDR entries, and how the API handles creating
65 an entry that already exists needs checking.
66  
67 =head1 METHODS
68  
69 =head2 new
70  
71 Initiates the the object.
72  
73 - options :: Backend specific options. See below.
74 - Default :: {}
75  
76 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
77 - default :: kur
78  
79 - name :: Name of this specific instance. This must be specified.
80 - default :: undef
81  
82 Ports and protocols are not supported by this backend and specifying either
83 is an error.
84  
85 The options hash accepts the following.
86  
87 - token :: Fastly API token, sent in the Fastly-Key header.
88 - Default :: undef
89  
90 - service :: Fastly service ID the ACL belongs to.
91 - Default :: undef
92  
93 - acl :: Fastly Edge ACL ID to manage entries under.
94 - Default :: undef
95  
96 - timeout :: HTTP timeout in seconds.
97 - Default :: 30
98  
99 - insecure :: If true, skip TLS certificate verification.
100 - Default :: 0
101  
102 All errors are considered fatal, meaning if new fails it will die.
103  
104 =cut
105  
106 4 ▶sub new {
Subroutine new: called CC=24 SCAR=42.8
Pod documented
107 4 my ( $blank, %opts ) = @_;
108  
109 4 my $self = {
110 perror => undef,
111 error => undef,
112 errorLine => undef,
113 errorFilename => undef,
114 errorString => "",
115 errorExtra => {
116 all_errors_fatal => 1,
117 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
118 # is kept for the name documented in its POD
119 all_fatal => 1,
120 flags => {
121 1 => 'notInited',
122 6 => 'invalidPrefixSpecified',
123 7 => 'invalidName',
124 8 => 'optionsNotHash',
125 9 => 'noBanItem',
126 10 => 'banItemNotIP',
127 12 => 'backendInitError',
128 13 => 'banFailed',
129 14 => 'unbanFailed',
130 15 => 'listFailed',
131 16 => 'reInitFailed',
132 17 => 'teardownFailed',
133 18 => 'alreadyInited',
134 23 => 'initFailed',
135 24 => 'checkFailed',
136 25 => 'flushFailed',
137 26 => 'portsNotSupported',
138 27 => 'protocolsNotSupported',
139 30 => 'serviceNotDefined',
140 31 => 'tokenNotDefined',
141 32 => 'aclNotDefined',
142 33 => 'banCidrFailed',
143 34 => 'unbanCidrFailed',
144 35 => 'cidrItemNotCidr',
145 36 => 'cidrNotSupported',
146 37 => 'listCidrFailed',
147 },
148 fatal_flags => {},
149 perror_not_fatal => 0,
150 },
151 options => {},
152 ports => [],
153 protocols => [],
154 testing => undef,
155 test_data => undef,
156 prefix => 'kur',
157 name => undef,
158 frontend_obj => undef,
159 inited => 0,
160 banned => {},
161 banned_cidr => {},
162 cidr_supported => 1,
163 ua => undef,
164 };
165 4 bless $self;
166  
167 # blocking is per IP; the ACL has no concept of ports or protocols
168 4 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) eq 'ARRAY' && defined( $opts{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]) 0 4 4
Condition33%2/6
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
!ll&&!rl&&r
040
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY"
!ll&&!rl&&r
004
MC/DC0%0/3
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
defined $opts{"ports"} ref $opts{"ports"} eq "ARRAY" defined $opts{"ports"}[0]
Truth table25%1/4
A and B and C
A= defined $opts{"ports"}B= ref $opts{"ports"} eq "ARRAY"C= defined $opts{"ports"}[0]
ABCresult
0XX0
10X0
1100
1111
169 0 $self->{perror} = 1;
170 0 $self->{error} = 26;
171 0 $self->{errorString} = 'the fastly backend blocks whole IPs and does not support ports';
172 0 $self->warn;
173 }
174 4 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) eq 'ARRAY' && defined( $opts{protocols}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]) 0 4 4
Condition33%2/6
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
!ll&&!rl&&r
040
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY"
!ll&&!rl&&r
004
MC/DC0%0/3
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
defined $opts{"protocols"} ref $opts{"protocols"} eq "ARRAY" defined $opts{"protocols"}[0]
Truth table25%1/4
A and B and C
A= defined $opts{"protocols"}B= ref $opts{"protocols"} eq "ARRAY"C= defined $opts{"protocols"}[0]
ABCresult
0XX0
10X0
1100
1111
175 0 $self->{perror} = 1;
176 0 $self->{error} = 27;
177 0 $self->{errorString} = 'the fastly backend blocks whole IPs and does not support protocols';
178 0 $self->warn;
179 }
180  
181 # make sure prefix is sane if defiend
182 4 ▶ if ( defined( $opts{prefix} ) && $opts{prefix} !~ /^[a-zA-Z0-9]+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'prefix'} and not $opts{'prefix'} =~ /^[a-zA-Z0-9]+$/) { } 0 4 4
elsif (defined $opts{'prefix'}) { } 4 0 4
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
040
MC/DC0%0/2
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
defined $opts{"prefix"} not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
Truth table33%1/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
183 0 $self->{perror} = 1;
184 0 $self->{error} = 6;
185 $self->{errorString}
186 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
187 0 $self->warn;
188 } elsif ( defined( $opts{prefix} ) ) {
189 4 $self->{prefix} = $opts{prefix};
190 }
191  
192 # make sure we have a name and that it is valid
193 4 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 4 4
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 4 4
194 0 $self->{perror} = 1;
195 0 $self->{error} = 7;
196 0 $self->{errorString} = 'name is undef';
197 0 $self->warn;
198 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
199 0 $self->{perror} = 1;
200 0 $self->{error} = 7;
201 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
202 0 $self->warn;
203 }
204 4 $self->{name} = $opts{name};
205  
206 # used internally for testing
207 4 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 4 0 4
208 4 $self->{testing} = $opts{testing};
209 }
210 4 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 4 0 4
211 4 $self->{frontend_obj} = $opts{frontend_obj};
212 }
213  
214 4 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 4 0 4
215 4 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 4 4
216 0 $self->{perror} = 1;
217 0 $self->{error} = 8;
218 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
219 0 $self->warn;
220 }
221 4 $self->{options} = $opts{options};
222 }
223  
224 # required options
225 4 ▶ if ( !defined( $self->{options}{token} ) || $self->{options}{token} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"token"} or $self->{"options"}{"token"} eq "") 1 3 4
Condition66%2/3
not defined $self->{"options"}{"token"} or $self->{"options"}{"token"} eq ""
l!l&&r!l&&!r
103
MC/DC50%1/2
not defined $self->{"options"}{"token"} or $self->{"options"}{"token"} eq ""
not defined $self->{"options"}{"token"} $self->{"options"}{"token"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"token"}B= $self->{"options"}{"token"} eq ""
ABresult
1X1
011
000
226 1 $self->{perror} = 1;
227 1 $self->{error} = 31;
228 1 $self->{errorString} = 'the option token is undef or blank';
229 1 $self->warn;
230 }
231 3 ▶ if ( !defined( $self->{options}{service} ) || $self->{options}{service} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"service"} or $self->{"options"}{"service"} eq "") 1 2 3
Condition66%2/3
not defined $self->{"options"}{"service"} or $self->{"options"}{"service"} eq ""
l!l&&r!l&&!r
102
MC/DC50%1/2
not defined $self->{"options"}{"service"} or $self->{"options"}{"service"} eq ""
not defined $self->{"options"}{"service"} $self->{"options"}{"service"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"service"}B= $self->{"options"}{"service"} eq ""
ABresult
1X1
011
000
232 1 $self->{perror} = 1;
233 1 $self->{error} = 30;
234 1 $self->{errorString} = 'the option service is undef or blank';
235 1 $self->warn;
236 }
237 2 ▶ if ( !defined( $self->{options}{acl} ) || $self->{options}{acl} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"acl"} or $self->{"options"}{"acl"} eq "") 1 1 2
Condition66%2/3
not defined $self->{"options"}{"acl"} or $self->{"options"}{"acl"} eq ""
l!l&&r!l&&!r
101
MC/DC50%1/2
not defined $self->{"options"}{"acl"} or $self->{"options"}{"acl"} eq ""
not defined $self->{"options"}{"acl"} $self->{"options"}{"acl"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"acl"}B= $self->{"options"}{"acl"} eq ""
ABresult
1X1
011
000
238 1 $self->{perror} = 1;
239 1 $self->{error} = 32;
240 1 $self->{errorString} = 'the option acl is undef or blank';
241 1 $self->warn;
242 }
243  
244 # defaults
245 1 ▶ $self->{options}{timeout} = 30 if ( !defined( $self->{options}{timeout} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"timeout"} 1 0 1
246 1 ▶ $self->{options}{insecure} = 0 if ( !defined( $self->{options}{insecure} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"insecure"} 1 0 1
247  
248 1 return $self;
249 } ## end sub new
250  
251 # Internal helper. Returns the URL of the ACL's entries collection.
252 #
253 # This is the read side of the API: a GET here answers with every entry in the
254 # ACL, which is how both unban paths find the entry they need to delete. Note
255 # it is a different path from the single entry endpoint, 'entries' rather than
256 # 'entry', which is easy to misread.
257 #
258 # The ACL is expected to already exist and be referenced by a service
259 # configuration; this backend does not create it.
260 #
261 # Takes no arguments; the service and ACL ids come from the options.
262 #
263 # Returns the URL as a string.
264 #
265 # $self->_entries_url;
266 # # https://api.fastly.com/service/<service>/acl/<acl>/entries
267 8 ▶sub _entries_url {
Subroutine _entries_url: called CC=1 SCAR=0.0
268 8 my ($self) = @_;
269  
270 return
271 'https://api.fastly.com/service/'
272 . $self->{options}{service}
273 . '/acl/'
274 . $self->{options}{acl}
275 8 . '/entries';
276 }
277  
278 # Internal helper. Returns the URL of the single entry endpoint, either the
279 # collection it is created through or one specific entry.
280 #
281 # The optional id is what makes this serve both halves of the lifecycle. With
282 # no id it is where a new entry is POSTed; with one it addresses an existing
283 # entry for deletion. Keeping them in one helper is reasonable because Fastly
284 # uses the same 'entry' stem for both, unlike the plural 'entries' used for
285 # reading the whole ACL.
286 #
287 # Args:
288 #
289 # id - Optional entry id, as a plain string, from a previous lookup
290 # against _entries_url. When omitted or undef the collection URL is
291 # returned instead. Appended as is, so it is expected to be an id
292 # Fastly issued rather than anything needing encoding.
293 #
294 # Returns the URL as a string.
295 #
296 # # for creating an entry
297 # $self->_entry_url;
298 # # https://api.fastly.com/service/<service>/acl/<acl>/entry
299 #
300 # # for deleting a specific one
301 # $self->_entry_url('7i6HN3TK9wS159v2xAZOSj');
302 # # https://api.fastly.com/service/<service>/acl/<acl>/entry/7i6HN3TK9wS159v2xAZOSj
303 5 ▶sub _entry_url {
Subroutine _entry_url: called CC=2 SCAR=6.9
304 5 my ( $self, $id ) = @_;
305  
306 my $url
307 = 'https://api.fastly.com/service/'
308 . $self->{options}{service}
309 . '/acl/'
310 . $self->{options}{acl}
311 5 . '/entry';
312  
313 5 ▶ if ( defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $id) 2 3 5
314 2 $url .= '/' . $id;
315 }
316  
317 5 return $url;
318 }
319  
320 # Internal helper. Performs one HTTP request against the Fastly API. Every
321 # call this backend makes goes through here.
322 #
323 # The user agent is built on first use and cached on the object, so a run of
324 # requests shares one agent. LWP::UserAgent is loaded with require at that
325 # point rather than at compile time, since only the HTTP backends need it;
326 # failing to load it dies with an explanation naming this backend.
327 #
328 # Authentication is the API token in a Fastly-Key header rather than basic
329 # auth or a bearer token.
330 #
331 # Any HTTP level failure dies rather than setting an error. The callers wrap
332 # this in eval and turn the exception into the appropriate error code, which
333 # is what lets one helper serve paths that report ban, unban, and teardown
334 # failures differently.
335 #
336 # A body that fails to decode as JSON is not fatal; the decode runs inside its
337 # own eval and leaves the result undef.
338 #
339 # Never called in testing mode; those paths record the request instead.
340 #
341 # Args:
342 #
343 # method - The HTTP method, as a plain string: 'GET' to read the entries,
344 # 'POST' to create one, 'DELETE' to remove one.
345 #
346 # url - The full URL to request, as a plain string, from _entries_url
347 # or _entry_url.
348 #
349 # body - Optional request body, as an already encoded JSON string. undef
350 # for the reads and deletes.
351 #
352 # Returns the decoded response body as whatever structure the JSON held. Note
353 # that a GET of the entries collection yields an arrayref rather than a
354 # hashref, which is why the callers check the reference type. undef when the
355 # body was empty or did not parse. Dies on any non success HTTP status.
356 #
357 # my $decoded = $self->_request( 'GET', $self->_entries_url );
358 #
359 # # the usual shape at the call sites
360 # eval { $self->_request( 'POST', $self->_entry_url, $body ); };
361 # if ($@) { ... raise banFailed ... }
362 0 ▶sub _request {
Subroutine _request: not called CC=8 SCAR=42.8
363 0 my ( $self, $method, $url, $body ) = @_;
364  
365 0 ▶ if ( !defined( $self->{ua} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"ua"}) 0 0 0
366 0 local $@;
367 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require LWP::UserAgent; my(%args) = ("agent", 'Net::Firewall::BlockerHelper/' . $Net::Firewall::BlockerHelper::backends::fastly::VERSION, "timeout", $self->{"options"}{"timeout"}); if ($self->{"options"}{"insecure"}) { $args{"ssl_opts"} = {"verify_hostname", 0, "SSL_verify_mode", 0}; } ; $self->{"ua"} = "LWP::UserAgent"->new(%args); 1 } } or die 'failed to load LWP::UserAgent, which the fastly backend requires... ' . $@ 0 0 0
368 0 require LWP::UserAgent;
369 my %args = (
370 agent => 'Net::Firewall::BlockerHelper/' . $VERSION,
371 timeout => $self->{options}{timeout},
372 0 );
373 0 ▶ if ( $self->{options}{insecure} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"insecure"}) 0 0 0
374 0 $args{ssl_opts} = { verify_hostname => 0, SSL_verify_mode => 0 };
375 }
376 0 $self->{ua} = LWP::UserAgent->new(%args);
377 0 1;
378 } or die( 'failed to load LWP::UserAgent, which the fastly backend requires... ' . $@ );
379 }
380  
381 0 my @headers = ( 'Content-Type' => 'application/json', 'Fastly-Key' => $self->{options}{token} );
382  
383 0 require HTTP::Request;
384 0 my $request = HTTP::Request->new( $method, $url, \@headers, $body );
385  
386 0 my $response = $self->{ua}->request($request);
387  
388 0 ▶ if ( !$response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
389 0 my $detail = $response->decoded_content;
390 0 ▶ $detail = defined($detail) ? ( ' body... ' . $detail ) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $detail ? : 0 0 0
391 0 die( $method . ' ' . $url . ' failed... HTTP status... ' . $response->status_line . $detail );
392 }
393  
394 0 my $decoded;
395 0 my $content = $response->decoded_content;
396 0 ▶ if ( defined($content) && $content ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content and $content ne "") 0 0 0
Condition0%0/3
defined $content and $content ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $content and $content ne ""
defined $content $content ne ""
Truth table0%0/3
A and B
A= defined $contentB= $content ne ""
ABresult
0X0
100
111
397 0 local $@;
398 0 eval { $decoded = $self->_json->decode($content); };
399 }
400  
401 0 return $decoded;
402 } ## end sub _request
403  
404 =head2 init
405  
406 Initiates the backend. Verifies the credentials and endpoint by fetching a
407 single ACL entry.
408  
409 $backend->init;
410  
411 =cut
412  
413 1 ▶sub init {
Subroutine init: called CC=4 SCAR=20.3
Pod documented
414 1 my ( $self, %opts ) = @_;
415  
416 1 $self->errorblank;
417  
418 1 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 1 1
419 0 $self->{error} = 18;
420 0 $self->{errorString} = 'backend has already been inited';
421 0 $self->warn;
422 }
423  
424 1 my $url = $self->_entries_url . '?per_page=1';
425  
426 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
427 1 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $url } ];
428 } else {
429 0 local $@;
430 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or do { $self->{"error"} = 23; $self->{"errorString"} = 'init failed. probing the ACL entries endpoint failed... ' . $@; $self->warn } 0 0 0
431 0 $self->{error} = 23;
432 0 $self->{errorString} = 'init failed. probing the ACL entries endpoint failed... ' . $@;
433 0 $self->warn;
434 };
435 }
436  
437 1 $self->{inited} = 1;
438 } ## end sub init
439  
440 =head2 ban
441  
442 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
443 and lowercased, then an ACL entry is created for it via a POST, with a /32
444 subnet for IPv4 and a /128 subnet for IPv6. Banning an already banned IP is
445 a noop.
446  
447 $backend->ban(ban => $ip);
448  
449 =cut
450  
451 2 ▶sub ban {
Subroutine ban: called CC=11 SCAR=37.7
Pod documented
452 2 my ( $self, %opts ) = @_;
453  
454 2 $self->errorblank;
455  
456 2 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 2 2
457 0 $self->{error} = 1;
458 0 $self->{errorString} = 'backend has not been inited';
459 0 $self->warn;
460 0 return;
461 }
462  
463 2 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 2 2
elsif (ref $opts{'ban'} ne '') { } 0 2 2
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/) { } 0 2 2
464 0 $self->{error} = 9;
465 0 $self->{errorString} = 'Nothing specified for the value ban';
466 0 $self->warn;
467 0 return;
468 } elsif ( ref( $opts{ban} ) ne '' ) {
469 0 $self->{error} = 10;
470 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
471 0 $self->warn;
472 0 return;
473 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
l!l&&r!l&&!r
110
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
ABresult
1X1
011
000
474 && $opts{ban} !~ /\A$IPv6_re\z/ )
475 {
476 0 $self->{error} = 10;
477 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
478 0 $self->warn;
479 0 return;
480 }
481  
482 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
483 2 $opts{ban} = lc( $opts{ban} );
484  
485 2 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 2 2
486 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
487 0 $self->{frontend_obj}->{test_data} = 'already banned';
488 }
489 0 return;
490 }
491  
492 2 ▶ my $subnet = ( $opts{ban} =~ /\A$IPv4_re\z/ ) ? 32 : 128;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ ? : 1 1 2
493 2 my $body = $self->_json->encode( { ip => $opts{ban}, subnet => $subnet } );
494  
495 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
496 2 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_entry_url, content => $body } ];
497 } else {
498 0 local $@;
499 0 ▶ eval { $self->_request( 'POST', $self->_entry_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_entry_url, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
500 0 $self->{error} = 13;
501 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
502 0 $self->warn;
503 0 return;
504 };
505 }
506  
507 2 $self->{banned}{ $opts{ban} } = 1;
508 } ## end sub ban
509  
510 # Internal helper. Performs the full two step unban of one address: find its
511 # ACL entry, then delete it by id.
512 #
513 # Fastly entries are addressed by an opaque id rather than by their contents,
514 # so the id has to be found before anything can be deleted. Unlike the
515 # cloudflare and routeros_api backends there is no server side filter for
516 # this: the whole entries collection is fetched and walked locally looking for
517 # a matching ip field. That means the cost of an unban grows with the size of
518 # the ACL rather than staying constant.
519 #
520 # Matching is on the ip field alone, since a single address entry carries no
521 # subnet. The search stops at the first match.
522 #
523 # An entry that is not found is treated as success rather than as an error.
524 # The entry having already gone means the address is not banned, which is what
525 # the caller wanted; erroring would make an unban fail for having already
526 # achieved its goal.
527 #
528 # Never called in testing mode; that path records the request instead.
529 #
530 # Args:
531 #
532 # ip - The address to unban, as a plain string. Expected to be an already
533 # validated and lowercased IPv4 or IPv6 address, matched exactly
534 # against the stored entry, so it must be spelled the same way it was
535 # when banned.
536 #
537 # Returns nothing. Dies if either request fails, which the caller catches and
538 # turns into unbanFailed.
539 #
540 # $self->_unban_ip('10.0.0.1');
541 #
542 # # the usual shape at the call site
543 # eval { $self->_unban_ip( $opts{ban} ); };
544 # if ($@) { ... raise unbanFailed ... }
545 0 ▶sub _unban_ip {
Subroutine _unban_ip: not called CC=7 SCAR=40.3
546 0 my ( $self, $ip ) = @_;
547  
548 0 my $decoded = $self->_request( 'GET', $self->_entries_url );
549  
550 0 my $id;
551 0 ▶ if ( ref($decoded) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded eq "ARRAY") 0 0 0
552 0 foreach my $entry ( @{$decoded} ) {
553 0 ▶ if ( ref($entry) eq 'HASH' && defined( $entry->{ip} ) && $entry->{ip} eq $ip ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $ip) 0 0 0
Condition0%0/6
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $ip
!ll&&!rl&&r
000
ref $entry eq "HASH" and defined $entry->{"ip"}
!ll&&!rl&&r
000
MC/DC0%0/3
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $ip
ref $entry eq "HASH" defined $entry->{"ip"} $entry->{"ip"} eq $ip
Truth table0%0/4
A and B and C
A= ref $entry eq "HASH"B= defined $entry->{"ip"}C= $entry->{"ip"} eq $ip
ABCresult
0XX0
10X0
1100
1111
554 0 $id = $entry->{id};
555 0 last;
556 }
557 }
558 }
559  
560 # no entry found means something else removed it already, which is fine
561 0 ▶ if ( !defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 0 0 0
562 0 return;
563 }
564  
565 0 $self->_request( 'DELETE', $self->_entry_url($id) );
566  
567 0 return;
568 } ## end sub _unban_ip
569  
570 =head2 unban
571  
572 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
573 and lowercased, then the ACL entries are fetched, the entry for the IP is
574 found, and it is deleted by its ID. An entry that can not be found is
575 treated as already unbanned. Unbanning an IP that is not banned is a noop.
576  
577 $backend->unban(ban => $ip);
578  
579 =cut
580  
581 1 ▶sub unban {
Subroutine unban: called CC=10 SCAR=38.2
Pod documented
582 1 my ( $self, %opts ) = @_;
583  
584 1 $self->errorblank;
585  
586 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
587 0 $self->{error} = 1;
588 0 $self->{errorString} = 'backend has not been inited';
589 0 $self->warn;
590 0 return;
591 }
592  
593 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/) { } 0 1 1
594 0 $self->{error} = 9;
595 0 $self->{errorString} = 'Nothing specified for the value ban';
596 0 $self->warn;
597 0 return;
598 } elsif ( ref( $opts{ban} ) ne '' ) {
599 0 $self->{error} = 10;
600 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
601 0 $self->warn;
602 0 return;
603 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition33%1/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
l!l&&r!l&&!r
100
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
Truth table33%1/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv6_re\z/
ABresult
1X1
011
000
604 && $opts{ban} !~ /\A$IPv6_re\z/ )
605 {
606 0 $self->{error} = 10;
607 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
608 0 $self->warn;
609 0 return;
610 }
611  
612 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
613 1 $opts{ban} = lc( $opts{ban} );
614  
615 1 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 1 1
616 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
617 0 $self->{frontend_obj}->{test_data} = 'not banned';
618 }
619 0 return;
620 }
621  
622 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
623 $self->{frontend_obj}->{test_data} = [
624 1 { method => 'GET', url => $self->_entries_url },
625 { method => 'DELETE', url => $self->_entry_url('<id>') },
626 ];
627 } else {
628 0 local $@;
629 0 ▶ eval { $self->_unban_ip( $opts{ban} ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($opts{"ban"}); 1 } } or do { $self->{"error"} = 14; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
630 0 $self->{error} = 14;
631 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
632 0 $self->warn;
633 0 return;
634 };
635 }
636  
637 1 delete( $self->{banned}{ $opts{ban} } );
638 } ## end sub unban
639  
640 =head2 list
641  
642 List banned IPs. Returns an array of the currently banned single IPs. CIDR
643 ranges are not included; for those see L</list_cidr>.
644  
645 my @banned = $backend->list;
646  
647 =cut
648  
649 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
650 0 my ( $self, %opts ) = @_;
651  
652 0 $self->errorblank;
653  
654 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
655 0 $self->{frontend_obj}->{test_data} = 'list';
656 }
657  
658 0 return keys( %{ $self->{banned} } );
659 }
660  
661 =head2 ban_cidr
662  
663 Bans a CIDR range by creating an ACL entry for it. The range is split into its
664 address and prefix length, sent as the ACL entry's ip and subnet, mirroring how
665 a single IP is banned as a /32 or /128 entry. The value of ban is validated
666 as being a IPv4 or IPv6 CIDR range and lowercased. Banning an already
667 banned range is a noop.
668  
669 $backend->ban_cidr(ban => '1.2.3.0/24');
670  
671 =cut
672  
673 1 ▶sub ban_cidr {
Subroutine ban_cidr: called CC=9 SCAR=35.2
Pod documented
674 1 my ( $self, %opts ) = @_;
675  
676 1 $self->errorblank;
677  
678 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
679 0 $self->{error} = 1;
680 0 $self->{errorString} = 'backend has not been inited';
681 0 $self->warn;
682 0 return;
683 }
684  
685 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 1 1
686 0 $self->{error} = 9;
687 0 $self->{errorString} = 'Nothing specified for the value ban';
688 0 $self->warn;
689 0 return;
690 } elsif ( ref( $opts{ban} ) ne '' ) {
691 0 $self->{error} = 35;
692 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
693 0 $self->warn;
694 0 return;
695 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
696 0 $self->{error} = 35;
697 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
698 0 $self->warn;
699 0 return;
700 }
701  
702 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
703 1 $opts{ban} = lc( $opts{ban} );
704  
705 1 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
706 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
707 0 $self->{frontend_obj}->{test_data} = 'already banned';
708 }
709 0 return;
710 }
711  
712 1 my ( $cidr_ip, $cidr_subnet ) = split( m!/!, $opts{ban}, 2 );
713 # numify the prefix length so it is encoded as a JSON number, matching how
714 # ban() sends the /32 or /128 subnet
715 1 $cidr_subnet += 0;
716 1 my $body = $self->_json->encode( { ip => $cidr_ip, subnet => $cidr_subnet } );
717  
718 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
719 1 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_entry_url, content => $body } ];
720 } else {
721 0 local $@;
722 0 ▶ eval { $self->_request( 'POST', $self->_entry_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_entry_url, $body); 1 } } or do { $self->{"error"} = 33; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
723 0 $self->{error} = 33;
724 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
725 0 $self->warn;
726 0 return;
727 };
728 }
729  
730 1 $self->{banned_cidr}{ $opts{ban} } = 1;
731 } ## end sub ban_cidr
732  
733 # Internal helper. Performs the full two step unban of one CIDR range, the
734 # range counterpart of _unban_ip.
735 #
736 # The shape is the same, fetch the entries collection and walk it for a match,
737 # and a missing entry is treated as success for the same reason.
738 #
739 # The difference is what a match means. Fastly stores a range as two separate
740 # fields, the network address in ip and the prefix length in subnet, so the
741 # range is split at the slash and both halves must match. Comparing against
742 # the ip field alone would match the single address entry for the same network
743 # address, and deleting that would unban the wrong thing.
744 #
745 # Never called in testing mode; that path records the request instead.
746 #
747 # Args:
748 #
749 # cidr - The range to unban, as a plain string. Expected to be an already
750 # validated and lowercased CIDR range such as "10.0.0.0/8". Split
751 # on the first slash, so the address goes to ip and everything
752 # after to subnet. Both halves are compared as strings, so the
753 # spelling must match what was stored at ban time.
754 #
755 # Returns nothing. Dies if either request fails, which the caller catches and
756 # turns into unbanCidrFailed.
757 #
758 # $self->_unban_cidr_range('10.0.0.0/8');
759 # # looks for an entry with ip '10.0.0.0' and subnet '8'
760 0 ▶sub _unban_cidr_range {
Subroutine _unban_cidr_range: not called CC=9 SCAR=45.0
761 0 my ( $self, $cidr ) = @_;
762  
763 0 my ( $cidr_ip, $cidr_subnet ) = split( m!/!, $cidr, 2 );
764  
765 0 my $decoded = $self->_request( 'GET', $self->_entries_url );
766  
767 0 my $id;
768 0 ▶ if ( ref($decoded) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded eq "ARRAY") 0 0 0
769 0 foreach my $entry ( @{$decoded} ) {
770 0 ▶ if ( ref($entry) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $cidr_ip and defined $entry->{"subnet"} and $entry->{"subnet"} eq $cidr_subnet) 0 0 0
Condition0%0/12
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $cidr_ip and defined $entry->{"subnet"} and $entry->{"subnet"} eq $cidr_subnet
!ll&&!rl&&r
000
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $cidr_ip and defined $entry->{"subnet"}
!ll&&!rl&&r
000
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $cidr_ip
!ll&&!rl&&r
000
ref $entry eq "HASH" and defined $entry->{"ip"}
!ll&&!rl&&r
000
MC/DC0%0/5
ref $entry eq "HASH" and defined $entry->{"ip"} and $entry->{"ip"} eq $cidr_ip and defined $entry->{"subnet"} and $entry->{"subnet"} eq $cidr_subnet
ref $entry eq "HASH" defined $entry->{"ip"} $entry->{"ip"} eq $cidr_ip defined $entry->{"subnet"} $entry->{"subnet"} eq $cidr_subnet
Truth table0%0/6
A and B and C and D and E
A= ref $entry eq "HASH"B= defined $entry->{"ip"}C= $entry->{"ip"} eq $cidr_ipD= defined $entry->{"subnet"}E= $entry->{"subnet"} eq $cidr_subnet
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
771 && defined( $entry->{ip} )
772 && $entry->{ip} eq $cidr_ip
773 && defined( $entry->{subnet} )
774 && $entry->{subnet} eq $cidr_subnet )
775 {
776 0 $id = $entry->{id};
777 0 last;
778 }
779 }
780 }
781  
782 # no entry found means something else removed it already, which is fine
783 0 ▶ if ( !defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 0 0 0
784 0 return;
785 }
786  
787 0 $self->_request( 'DELETE', $self->_entry_url($id) );
788  
789 0 return;
790 } ## end sub _unban_cidr_range
791  
792 =head2 unban_cidr
793  
794 Unbans a CIDR range. The value of ban is validated as being a IPv4 or IPv6
795 CIDR range and lowercased, then the ACL entries are fetched, the entry
796 matching its address and prefix length is found, and it is deleted by its
797 ID. An entry that can not be found is treated as already unbanned.
798 Unbanning a range that is not banned is a noop.
799  
800 $backend->unban_cidr(ban => '1.2.3.0/24');
801  
802 =cut
803  
804 1 ▶sub unban_cidr {
Subroutine unban_cidr: called CC=9 SCAR=36.4
Pod documented
805 1 my ( $self, %opts ) = @_;
806  
807 1 $self->errorblank;
808  
809 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
810 0 $self->{error} = 1;
811 0 $self->{errorString} = 'backend has not been inited';
812 0 $self->warn;
813 0 return;
814 }
815  
816 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 1 1
817 0 $self->{error} = 9;
818 0 $self->{errorString} = 'Nothing specified for the value ban';
819 0 $self->warn;
820 0 return;
821 } elsif ( ref( $opts{ban} ) ne '' ) {
822 0 $self->{error} = 35;
823 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
824 0 $self->warn;
825 0 return;
826 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
827 0 $self->{error} = 35;
828 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
829 0 $self->warn;
830 0 return;
831 }
832  
833 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
834 1 $opts{ban} = lc( $opts{ban} );
835  
836 1 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
837 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
838 0 $self->{frontend_obj}->{test_data} = 'not banned';
839 }
840 0 return;
841 }
842  
843 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
844 $self->{frontend_obj}->{test_data} = [
845 1 { method => 'GET', url => $self->_entries_url },
846 { method => 'DELETE', url => $self->_entry_url('<id>') },
847 ];
848 } else {
849 0 local $@;
850 0 ▶ eval { $self->_unban_cidr_range( $opts{ban} ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_cidr_range($opts{"ban"}); 1 } } or do { $self->{"error"} = 34; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
851 0 $self->{error} = 34;
852 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
853 0 $self->warn;
854 0 return;
855 };
856 }
857  
858 1 delete( $self->{banned_cidr}{ $opts{ban} } );
859 } ## end sub unban_cidr
860  
861 =head2 list_cidr
862  
863 List banned CIDR ranges. Returns an array of the currently banned CIDR
864 ranges. Single IPs are not included; for those see L</list>.
865  
866 my @banned_cidrs = $backend->list_cidr;
867  
868 =cut
869  
870 2 ▶sub list_cidr {
Subroutine list_cidr: called CC=2 SCAR=7.0
Pod documented
871 2 my ( $self, %opts ) = @_;
872  
873 2 $self->errorblank;
874  
875 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
876 2 $self->{frontend_obj}->{test_data} = 'list_cidr';
877 }
878  
879 2 return keys( %{ $self->{banned_cidr} } );
880 }
881  
882 =head2 re_init
883  
884 Tells the backend to re-init it's self.
885  
886 This will call teardown and init again. After that it will re-add all
887 previously added bans, POSTing an ACL entry for each retained IP and CIDR
888 range.
889  
890 $backend->re_init;
891  
892 =cut
893  
894 0 ▶sub re_init {
Subroutine re_init: not called CC=9 SCAR=45.0
Pod documented
895 0 my ( $self, %opts ) = @_;
896  
897 0 $self->errorblank;
898  
899 # teardown is best effort here as a partially or fully wiped setup is
900 # exactly what re_init needs to recover from; init cleans up any remnants
901 {
902 0 local $@;
903 0 eval { $self->teardown; };
904 }
905 0 $self->init;
906  
907 0 my @re_init_test_data;
908 0 foreach my $item ( keys( %{ $self->{banned} } ) ) {
909 0 ▶ my $subnet = ( $item =~ /\A$IPv4_re\z/ ) ? 32 : 128;
Branch: 1 branch
BranchTrueFalseTotal
$item =~ /\A$Net::Firewall::BlockerHelper::backends::fastly::IPv4_re\z/ ? : 0 0 0
910 0 my $body = $self->_json->encode( { ip => $item, subnet => $subnet } );
911  
912 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
913 0 push( @re_init_test_data, { method => 'POST', url => $self->_entry_url, content => $body } );
914 } else {
915 0 local $@;
916 0 ▶ eval { $self->_request( 'POST', $self->_entry_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_entry_url, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $item . '" failed... ' . $@; $self->warn } 0 0 0
917 0 $self->{error} = 13;
918 0 $self->{errorString} = 'banning "' . $item . '" failed... ' . $@;
919 0 $self->warn;
920 };
921 }
922 } ## end foreach my $item ( keys( %{ ...}))
923  
924 # re-add the CIDR ranges as well, splitting each into its ip and subnet the
925 # same way ban_cidr does
926 0 foreach my $item ( keys( %{ $self->{banned_cidr} } ) ) {
927 0 my ( $cidr_ip, $cidr_subnet ) = split( m!/!, $item, 2 );
928 0 $cidr_subnet += 0;
929 0 my $body = $self->_json->encode( { ip => $cidr_ip, subnet => $cidr_subnet } );
930  
931 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
932 0 push( @re_init_test_data, { method => 'POST', url => $self->_entry_url, content => $body } );
933 } else {
934 0 local $@;
935 0 ▶ eval { $self->_request( 'POST', $self->_entry_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_entry_url, $body); 1 } } or do { $self->{"error"} = 33; $self->{"errorString"} = 'banning "' . $item . '" failed... ' . $@; $self->warn } 0 0 0
936 0 $self->{error} = 33;
937 0 $self->{errorString} = 'banning "' . $item . '" failed... ' . $@;
938 0 $self->warn;
939 };
940 }
941 } ## end foreach my $item ( keys( %{ ...}))
942  
943 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
944 0 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
945 }
946  
947 0 $self->{inited} = 1;
948 } ## end sub re_init
949  
950 =head2 teardown
951  
952 Tears down the setup for the backend by removing the ACL entry for each
953 currently banned IP. The internal list of bans is kept, so a following
954 re_init will re-add them.
955  
956 $backend->teardown;
957  
958 =cut
959  
960 0 ▶sub teardown {
Subroutine teardown: not called CC=5 SCAR=34.0
Pod documented
961 0 my ( $self, %opts ) = @_;
962  
963 0 $self->errorblank;
964  
965 0 $self->{inited} = 0;
966  
967 0 my @requests;
968 0 foreach my $item ( sort( keys( %{ $self->{banned} } ) ) ) {
969 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
970 0 push(
971 @requests,
972 { method => 'GET', url => $self->_entries_url },
973 { method => 'DELETE', url => $self->_entry_url('<id>') }
974 );
975 } else {
976 0 local $@;
977 0 ▶ eval { $self->_unban_ip($item); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($item); 1 } } or do { $self->{"error"} = 17; $self->{"errorString"} = 'teardown failed removing the entry for "' . $item . '"... ' . $@; $self->warn } 0 0 0
978 0 $self->{error} = 17;
979 0 $self->{errorString} = 'teardown failed removing the entry for "' . $item . '"... ' . $@;
980 0 $self->warn;
981 };
982 }
983 } ## end foreach my $item ( sort( keys( %{ $self->{banned...})))
984  
985 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
986 0 $self->{frontend_obj}->{test_data} = \@requests;
987 }
988 } ## end sub teardown
989  
990 =head2 stop
991  
992 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
993 concept.
994  
995 $backend->stop;
996  
997 =cut
998  
999 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
1000 0 my ( $self, %opts ) = @_;
1001  
1002 0 return $self->teardown(%opts);
1003 }
1004  
1005 =head2 check
1006  
1007 Verifies the endpoint and credentials are still usable by fetching a single
1008 ACL entry. Returns a true value if so and a false value otherwise. This is the
1009 equivalent of fail2ban's C<actioncheck>.
1010  
1011 if ( !$backend->check ) {
1012 $backend->re_init;
1013 }
1014  
1015 =cut
1016  
1017 5 ▶sub check {
Subroutine check: called CC=3 SCAR=14.7
Pod documented
1018 5 my ( $self, %opts ) = @_;
1019  
1020 5 $self->errorblank;
1021  
1022 5 my $url = $self->_entries_url . '?per_page=1';
1023  
1024 5 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 5 0 5
1025 5 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $url } ];
1026 5 return 1;
1027 }
1028  
1029 0 local $@;
1030 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or return 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or return 0 0 0 0
1031  
1032 0 return 1;
1033 } ## end sub check
1034  
1035 =head2 flush
1036  
1037 Removes all currently banned IPs at once by removing their ACL entries and
1038 forgetting them. This is the equivalent of fail2ban's C<actionflush>.
1039  
1040 $backend->flush;
1041  
1042 =cut
1043  
1044 0 ▶sub flush {
Subroutine flush: not called CC=9 SCAR=45.0
Pod documented
1045 0 my ( $self, %opts ) = @_;
1046  
1047 0 $self->errorblank;
1048  
1049 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1050 0 $self->{error} = 1;
1051 0 $self->{errorString} = 'backend has not been inited';
1052 0 $self->warn;
1053 0 return;
1054 }
1055  
1056 0 my @requests;
1057 0 foreach my $item ( sort( keys( %{ $self->{banned} } ) ) ) {
1058 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1059 0 push(
1060 @requests,
1061 { method => 'GET', url => $self->_entries_url },
1062 { method => 'DELETE', url => $self->_entry_url('<id>') }
1063 );
1064 } else {
1065 0 local $@;
1066 0 ▶ eval { $self->_unban_ip($item); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($item); 1 } } or do { $self->{"error"} = 25; $self->{"errorString"} = 'flush failed removing the entry for "' . $item . '"... ' . $@; $self->warn } 0 0 0
1067 0 $self->{error} = 25;
1068 0 $self->{errorString} = 'flush failed removing the entry for "' . $item . '"... ' . $@;
1069 0 $self->warn;
1070 };
1071 }
1072 } ## end foreach my $item ( sort( keys( %{ $self->{banned...})))
1073  
1074 # remove the CIDR entries the same way
1075 0 foreach my $item ( sort( keys( %{ $self->{banned_cidr} } ) ) ) {
1076 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1077 0 push(
1078 @requests,
1079 { method => 'GET', url => $self->_entries_url },
1080 { method => 'DELETE', url => $self->_entry_url('<id>') }
1081 );
1082 } else {
1083 0 local $@;
1084 0 ▶ eval { $self->_unban_cidr_range($item); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_cidr_range($item); 1 } } or do { $self->{"error"} = 25; $self->{"errorString"} = 'flush failed removing the entry for "' . $item . '"... ' . $@; $self->warn } 0 0 0
1085 0 $self->{error} = 25;
1086 0 $self->{errorString} = 'flush failed removing the entry for "' . $item . '"... ' . $@;
1087 0 $self->warn;
1088 };
1089 }
1090 } ## end foreach my $item ( sort( keys( %{ $self->{banned_cidr...})))
1091  
1092 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1093 0 $self->{frontend_obj}->{test_data} = \@requests;
1094 }
1095  
1096 0 $self->{banned} = {};
1097 0 $self->{banned_cidr} = {};
1098 } ## end sub flush
1099  
1100 =head1 ERROR CODES / FLAGS
1101  
1102 Error handling is provided by L<Error::Helper>. All
1103 errors are considered fatal.
1104  
1105 =head2 1, notInited
1106  
1107 The backend has not been inited yet.
1108  
1109 =head2 6, invalidPrefixSpecified
1110  
1111 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1112  
1113 =head2 7, invalidName
1114  
1115 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1116  
1117 =head2 8, optionsNotHash
1118  
1119 The item passed to new for options is not a hash.
1120  
1121 =head2 9, noBanItem
1122  
1123 No IP or CIDR range specified to ban or unban.
1124  
1125 =head2 10, banItemNotIP
1126  
1127 The item to ban is not an IP. Either wrong ref type or regexp
1128 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1129  
1130 =head2 12, backendInitError
1131  
1132 Failed to init the backend.
1133  
1134 =head2 13, banFailed
1135  
1136 Failed to ban the item.
1137  
1138 =head2 14, unbanFailed
1139  
1140 Failed to unban the item.
1141  
1142 =head2 15, listFailed
1143  
1144 Failed to get a list of bans.
1145  
1146 =head2 16, reInitFailed
1147  
1148 Failed to re_init the backend.
1149  
1150 =head2 17, teardownFailed
1151  
1152 Failed to teardown the backend.
1153  
1154 =head2 18, alreadyInited
1155  
1156 init called, but the backend has already been inited.
1157  
1158 =head2 23, initFailed
1159  
1160 Init failed. Probing the ACL entries endpoint failed.
1161  
1162 =head2 24, checkFailed
1163  
1164 The backend check raised an error.
1165  
1166 =head2 25, flushFailed
1167  
1168 Failed to flush the bans.
1169  
1170 =head2 26, portsNotSupported
1171  
1172 The fastly backend blocks whole IPs and does not support ports.
1173  
1174 =head2 27, protocolsNotSupported
1175  
1176 The fastly backend blocks whole IPs and does not support protocols.
1177  
1178 =head2 30, serviceNotDefined
1179  
1180 The option service is undef or blank.
1181  
1182 =head2 31, tokenNotDefined
1183  
1184 The option token is undef or blank.
1185  
1186 =head2 32, aclNotDefined
1187  
1188 The option acl is undef or blank.
1189  
1190 =head2 33, banCidrFailed
1191  
1192 Failed to ban the CIDR range.
1193  
1194 =head2 34, unbanCidrFailed
1195  
1196 Failed to unban the CIDR range.
1197  
1198 =head2 35, cidrItemNotCidr
1199  
1200 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1201 IPv4 or IPv6 address followed by a prefix length valid for its family.
1202  
1203 =head2 36, cidrNotSupported
1204  
1205 The backend does not support CIDR bans.
1206  
1207 =head2 37, listCidrFailed
1208  
1209 Failed to get a list of CIDR bans.
1210  
1211 =head1 AUTHOR
1212  
1213 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1214  
1215 =head1 BUGS
1216  
1217 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1218 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>.
1219  
1220 =head1 LICENSE AND COPYRIGHT
1221  
1222 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1223  
1224 This is free software, licensed under:
1225  
1226 The GNU Lesser General Public License, Version 2.1, February 1999
1227  
1228  
1229 =cut
1230  
1231 1 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/dummy.pm ↑ Summary BlockerHelper/backends/cloudflare.pm »