blib/lib/Lemonldap/NG/Portal/Plugins/CrowdSec.pm untested

filter: Statementstmt 0.0% 0 / 39 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 10 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 69 CC 7 SCAR 31.2
CC
7
Cov
0%
checkIpStatus
42.0
init
6.0
BEGIN
2.0
CRAP 22.7
1 package Lemonldap::NG::Portal::Plugins::CrowdSec;
2  
3 use strict;
4 use Mouse;
5 use Lemonldap::NG::Portal::Main::Constants qw(
6 PE_OK
7 PE_SESSIONNOTGRANTED
8 );
9  
10 our $VERSION = '2.22.0';
11  
12 extends 'Lemonldap::NG::Portal::Main::Plugin';
13 with 'Lemonldap::NG::Portal::Lib::CrowdSec';
14  
15 # Entrypoint
16 use constant beforeAuth => 'checkIpStatus';
17  
18 has rule => ( is => 'rw', default => sub { 0 } );
19  
20 sub init {
21 my ($self) = @_;
22 $self->_init or return 0;
23  
24 # Parse activation rule
25 unless ( $self->conf->{crowdsecKey} ) {
26 $self->logger->error('Missing Crowdsec Bouncer key');
27 return 0;
28 }
29 $self->logger->info(
30 'CrowdSec policy is: ' . ( $self->conf->{crowdsecAction} || 'warn' ) );
31 $self->rule( $self->p->buildRule( $self->conf->{crowdsec}, 'crowdsec' ) );
32 return 1;
33 }
34  
35 sub checkIpStatus {
36 my ( $self, $req ) = @_;
37 if ( !$self->rule->( $req, $req->sessionInfo ) ) {
38 $self->logger->debug('Crowdsec disabled for this env');
39 return PE_OK;
40 }
41 my $ip = $req->address;
42 my ( $ok, $err ) = $self->bouncer($ip);
43  
44 # bouncer() answer $ok=0 only when Crowdsec response rejects the given IP
45 return PE_OK if ( $ok and $err and $self->conf->{crowdsecIgnoreFailures} );
46  
47 # When $ok==0, $err contains the Crowdsec decision
48 unless ($ok) {
49 if ( $self->conf->{crowdsecAction} eq 'reject' ) {
50 $self->auditLog(
51 $req,
52 code => 403,
53 message => $err,
54 ip => $ip,
55 );
56 return PE_SESSIONNOTGRANTED;
57 }
58 else {
59 $self->auditLog(
60 $req,
61 code => 200,
62 message => "$err (ignored)",
63 ip => $ip,
64 );
65 $req->env->{CROWDSEC_REJECT} = 1;
66 return PE_OK;
67 }
68 }
69 return $err ? $err : PE_OK;
70 }
71  
72 1;