FastAPI/Middleware/BotProtection.pm

filter: Statementstmt 97.6% 42 / 43 Branchbran 83.3% 5 / 6 Conditioncond 60.0% 6 / 10 MC/DCmcdc 40.0% 2 / 5 Subroutinesub 87.5% 7 / 8 Podpod 50.0% 1 / 2 totaltotal 85.1% 63 / 74 CC 8 SCAR 12.7
CC
8
Cov
90%
handle
6.0
__ANON__
3.7
pow
1.1
CRAP 3.6
« FastAPI/Middleware/RateLimit.pm ↑ Summary FastAPI/Response/SSE.pm »
1 package PAGI::FastAPI::Middleware::BotProtection;
2  
3 23 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 23 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 23 our $VERSION = qv('v1.7.3');
8 23 our $AUTHORITY = 'cpan:MANWAR';
9  
10 23 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 23 ▶use PAGI::FastAPI::BotProtection::ProofOfWork;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 23 class PAGI::FastAPI::Middleware::BotProtection {
14 23 field $difficulty :param = 3;
15 23 field $ttl :param = 300;
16 23 field $trust_proxies :param = 0;
17 23 field $secret :param;
18 23 field $pow;
19  
20 5 ▶ ADJUST {
Subroutine __ANON__: called CC=3 SCAR=13.1
21 5 ▶ die "BotProtection: 'secret' parameter must be defined and non-empty in production\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $secret and length $secret > 0 0 5 5
Condition33%1/3
defined $secret and length $secret > 0
!ll&&!rl&&r
005
MC/DC0%0/2
defined $secret and length $secret > 0
defined $secret length $secret > 0
Truth table33%1/3
A and B
A= defined $secretB= length $secret > 0
ABresult
0X0
100
111
22 unless defined $secret && length($secret) > 0;
23  
24 5 $pow = PAGI::FastAPI::BotProtection::ProofOfWork->new(
25 difficulty => $difficulty,
26 secret => $secret,
27 ttl => $ttl,
28 );
29 }
30  
31 0 ▶ method pow () { return $pow }
Subroutine pow: not called CC=1 SCAR=1.2
Pod documented
32  
33 7 ▶ async method handle ($c, $next) {
Subroutine handle: called CC=6 SCAR=17.9
Pod undocumented
34 7 my $client_ip;
35 7 ▶ if ($trust_proxies && (my $forwarded = $c->header('x-forwarded-for'))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trust_proxies and my $forwarded = $c->header("x-forwarded-for")) 2 5 7
Condition66%2/3
$trust_proxies and my $forwarded = $c->header("x-forwarded-for")
!ll&&!rl&&r
502
MC/DC50%1/2
$trust_proxies and my $forwarded = $c->header("x-forwarded-for")
$trust_proxies my $forwarded = $c->header("x-forwarded-for")
Truth table66%2/3
A and B
A= $trust_proxiesB= my $forwarded = $c->header("x-forwarded-for")
ABresult
0X0
100
111
36 2 ($client_ip) = split /\s*,\s*/, $forwarded;
37 }
38 7 ▶ $client_ip //= $c->scope->{client}[0] // '127.0.0.1';
Condition75%3/4
$client_ip //= $c->scope->{"client"}[0] // "127.0.0.1"
l!l
25
$c->scope->{"client"}[0] // "127.0.0.1"
l!l
50
MC/DC100%1/1
$client_ip //= $c->scope->{"client"}[0] // "127.0.0.1"
$client_ip
Truth table100%2/2
A
A= $client_ip
Aresult
11
00
39  
40 # Standard header keys expected from client requests
41 7 my $challenge = $c->header('x-bot-challenge');
42 7 my $nonce = $c->header('x-bot-nonce');
43  
44 # Allow request to proceed if valid Proof-of-Work token is provided
45 7 ▶ if ($pow->verify($challenge, $nonce, $client_ip)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pow->verify($challenge, $nonce, $client_ip)) 3 4 7
46 3 return await $next->($c);
47 }
48  
49 # Issue new challenge and return HTTP 401 Unauthorized
50 4 my $ch = $pow->create_challenge($client_ip);
51  
52 4 $c->status(401);
53 4 $c->set_header('x-bot-challenge' => $ch->{challenge});
54 4 $c->set_header('x-bot-difficulty' => $ch->{difficulty});
55  
56 return {
57 4 detail => 'Bot Protection Triggered',
58 message => 'Proof-of-Work challenge required to access this endpoint.',
59 };
60 23 }
61 }
62  
63 =encoding utf-8
64  
65 =head1 NAME
66  
67 PAGI::FastAPI::Middleware::BotProtection - Asynchronous Proof-of-Work Bot Protection Middleware for PAGI::FastAPI
68  
69 =head1 VERSION
70  
71 Version v1.7.3
72  
73 =head1 SYNOPSIS
74  
75 use PAGI::FastAPI;
76  
77 my $app = PAGI::FastAPI->new();
78  
79 # Register bot protection middleware
80 $app->add_bot_protection(
81 difficulty => 3,
82 secret => $ENV{BOT_PROTECTION_SECRET} // die("BOT_PROTECTION_SECRET is required"),
83 ttl => 300,
84 );
85  
86 =head1 DESCRIPTION
87  
88 C<PAGI::FastAPI::Middleware::BotProtection> integrates cryptographic
89 Proof-of-Work bot mitigation into L<PAGI::FastAPI> application request
90 pipelines.
91  
92 When active, incoming requests without a valid C<X-Bot-Challenge> and
93 C<X-Bot-Nonce> header are rejected with an HTTP C<401 Unauthorized>
94 response accompanied by challenge parameters in the response headers. Real
95 client environments (such as web browsers executing background JavaScript)
96 solve the puzzle and retry the request, bypassing automated bots and naive
97 scrapers.
98  
99 =head1 CONSTRUCTOR
100  
101 =head2 new(%options)
102  
103 Creates a new instance of L<PAGI::FastAPI::Middleware::BotProtection>.
104  
105 Accepted options:
106  
107 =over 4
108  
109 =item * C<secret> (required)
110  
111 A non-empty string used as the C<HMAC> key to sign and verify generated
112 challenges.
113  
114 B<Security Note:> Keep this value secure and avoid using hardcoded default
115 strings in production environments.
116  
117 =item * C<difficulty> (optional)
118  
119 An integer specifying the required leading zero bits (or hexadecimal zeros)
120 for the Proof-of-Work solution. Defaults to C<3>.
121  
122 Higher values exponentially increase the CPU time required for the client to
123 generate a valid nonce, while lower values reduce client computation
124 overhead.
125  
126 =item * C<ttl> (optional)
127  
128 The time-to-live duration for issued challenges, in seconds. Defaults to
129 C<300> (5 minutes).
130  
131 Challenges presented after this time window has elapsed will be rejected as
132 expired, requiring the client to request a fresh challenge.
133  
134 =item * C<trust_proxies> (optional)
135  
136 Boolean flag indicating whether to trust incoming proxy headers for client
137 IP resolution. Defaults to C<0> (false).
138  
139 When set to C<0>, the middleware extracts the client IP strictly from the
140 direct TCP connection socket, ignoring client-supplied headers. When set to
141 C<1>, the middleware parses the first IP from the C<X-Forwarded-For> header
142 if present.
143  
144 B<Security Note:> Only set C<trust_proxies> to C<1> when running behind a
145 trusted reverse proxy (such as NGINX, HAProxy, or AWS ALB) that strips or
146 overwrites incoming client header values.
147  
148 =back
149  
150 =head1 METHODS
151  
152 =head2 pow
153  
154 my $pow = $mw->pow;
155  
156 Returns the underlying L<PAGI::FastAPI::BotProtection::ProofOfWork> instance
157 managed by this middleware.
158  
159 This accessor exposes the Proof-of-Work engine directly to callers, allowing
160 custom challenge creation (via C<create_challenge>), manual verification
161 (via C<verify>), or direct inspection during testing and advanced
162 application integrations.
163  
164 =head1 HEADERS
165  
166 The middleware inspects and sets the following HTTP response/request headers:
167  
168 =over 4
169  
170 =item * C<x-bot-challenge> (Request/Response)
171  
172 The HMAC-signed challenge token string issued by the server.
173  
174 =item * C<x-bot-difficulty> (Response)
175  
176 The integer difficulty level assigned to the active challenge.
177  
178 =item * C<x-bot-nonce> (Request)
179  
180 The integer solution nonce computed by the client.
181  
182 =back
183  
184 =head1 SEE ALSO
185  
186 L<PAGI::FastAPI::BotProtection::ProofOfWork>, L<PAGI::FastAPI>
187  
188 =head1 AUTHOR
189  
190 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
191  
192 =head1 BUGS
193  
194 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
195 I will be notified and then you'll automatically be notified of progress on your
196 bug as I make changes.
197  
198 =head1 SUPPORT
199  
200 You can find documentation for this module with the perldoc command.
201  
202 perldoc PAGI::FastAPI::Middleware::BotProtection
203  
204 You can also look for information at:
205  
206 =over 4
207  
208 =item * BUG Report
209  
210 L<https://github.com/manwar/PAGI-FastAPI/issues>
211  
212 =item * Search MetaCPAN
213  
214 L<https://metacpan.org/dist/PAGI-FastAPI/>
215  
216 =back
217  
218 =head1 LICENSE AND COPYRIGHT
219  
220 Copyright (C) 2026 Mohammad Sajid Anwar.
221  
222 This program is free software; you can redistribute it and/or modify it under
223 the terms of the Artistic License (2.0).
224  
225 =cut
226  
227 23 1; # End of PAGI::FastAPI::Middleware::BotProtection
« FastAPI/Middleware/RateLimit.pm ↑ Summary FastAPI/Response/SSE.pm »