| 1 | package PAGI::Middleware::RateLimit; | ||||||||||||||||||||||||||||
| 2 | 2 | $PAGI::Middleware::RateLimit::VERSION = '0.002002'; | |||||||||||||||||||||||||||
| 3 | 2 | ▶ | use strict; | ||||||||||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 4 | 2 | ▶ | use warnings; | ||||||||||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 5 | 2 | ▶ | use parent 'PAGI::Middleware'; | ||||||||||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 6 | 2 | ▶ | use Future::AsyncAwait; | ||||||||||||||||||||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 7 | |||||||||||||||||||||||||||||
| 8 | =head1 NAME | ||||||||||||||||||||||||||||
| 9 | |||||||||||||||||||||||||||||
| 10 | PAGI::Middleware::RateLimit - Request rate limiting middleware | ||||||||||||||||||||||||||||
| 11 | |||||||||||||||||||||||||||||
| 12 | =head1 SYNOPSIS | ||||||||||||||||||||||||||||
| 13 | |||||||||||||||||||||||||||||
| 14 | use PAGI::Middleware::Builder; | ||||||||||||||||||||||||||||
| 15 | |||||||||||||||||||||||||||||
| 16 | my $app = builder { | ||||||||||||||||||||||||||||
| 17 | enable 'RateLimit', | ||||||||||||||||||||||||||||
| 18 | requests_per_second => 10, | ||||||||||||||||||||||||||||
| 19 | burst => 20, | ||||||||||||||||||||||||||||
| 20 | key_generator => sub { | ||||||||||||||||||||||||||||
| 21 | my ($scope) = @_; exists $scope->{client} ? $scope->{client}[0] : 'unknown' }; | ||||||||||||||||||||||||||||
| 22 | $my_app; | ||||||||||||||||||||||||||||
| 23 | }; | ||||||||||||||||||||||||||||
| 24 | |||||||||||||||||||||||||||||
| 25 | =head1 DESCRIPTION | ||||||||||||||||||||||||||||
| 26 | |||||||||||||||||||||||||||||
| 27 | PAGI::Middleware::RateLimit implements token bucket rate limiting per client. | ||||||||||||||||||||||||||||
| 28 | Clients exceeding the rate limit receive 429 Too Many Requests. | ||||||||||||||||||||||||||||
| 29 | |||||||||||||||||||||||||||||
| 30 | =head1 CONFIGURATION | ||||||||||||||||||||||||||||
| 31 | |||||||||||||||||||||||||||||
| 32 | =over 4 | ||||||||||||||||||||||||||||
| 33 | |||||||||||||||||||||||||||||
| 34 | =item * requests_per_second (default: 10) | ||||||||||||||||||||||||||||
| 35 | |||||||||||||||||||||||||||||
| 36 | Average requests allowed per second. | ||||||||||||||||||||||||||||
| 37 | |||||||||||||||||||||||||||||
| 38 | =item * burst (default: 20) | ||||||||||||||||||||||||||||
| 39 | |||||||||||||||||||||||||||||
| 40 | Maximum burst size (bucket capacity). | ||||||||||||||||||||||||||||
| 41 | |||||||||||||||||||||||||||||
| 42 | =item * key_generator (default: client IP) | ||||||||||||||||||||||||||||
| 43 | |||||||||||||||||||||||||||||
| 44 | Coderef to generate rate limit key from $scope. | ||||||||||||||||||||||||||||
| 45 | |||||||||||||||||||||||||||||
| 46 | =item * backend (default: in-memory) | ||||||||||||||||||||||||||||
| 47 | |||||||||||||||||||||||||||||
| 48 | Rate limit storage backend. Can be 'memory' or a custom object | ||||||||||||||||||||||||||||
| 49 | implementing get/set methods. | ||||||||||||||||||||||||||||
| 50 | |||||||||||||||||||||||||||||
| 51 | =item * cleanup_interval (default: 60) | ||||||||||||||||||||||||||||
| 52 | |||||||||||||||||||||||||||||
| 53 | Seconds between periodic cleanup of stale buckets. | ||||||||||||||||||||||||||||
| 54 | |||||||||||||||||||||||||||||
| 55 | =item * max_buckets (default: 10000) | ||||||||||||||||||||||||||||
| 56 | |||||||||||||||||||||||||||||
| 57 | Maximum number of tracked client buckets. When exceeded, the oldest | ||||||||||||||||||||||||||||
| 58 | half are evicted as a safety valve. | ||||||||||||||||||||||||||||
| 59 | |||||||||||||||||||||||||||||
| 60 | =back | ||||||||||||||||||||||||||||
| 61 | |||||||||||||||||||||||||||||
| 62 | =cut | ||||||||||||||||||||||||||||
| 63 | |||||||||||||||||||||||||||||
| 64 | 2 | my %buckets; # In-memory storage | |||||||||||||||||||||||||||
| 65 | 2 | my $_time_offset = 0; | |||||||||||||||||||||||||||
| 66 | |||||||||||||||||||||||||||||
| 67 | 8 | ▶ | sub _clear_buckets { %buckets = (); $_time_offset = 0; } | ||||||||||||||||||||||||||
|
Subroutine
_clear_buckets: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 68 | 6 | ▶ | sub _bucket_count { return scalar keys %buckets } | ||||||||||||||||||||||||||
|
Subroutine
_bucket_count: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 69 | 13 | ▶ | sub _advance_time_for_test { $_time_offset += $_[1] } | ||||||||||||||||||||||||||
|
Subroutine
_advance_time_for_test: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 70 | 45 | ▶ | sub _now { return time() + $_time_offset } | ||||||||||||||||||||||||||
|
Subroutine
_now: called CC=1 SCAR=0.0
| |||||||||||||||||||||||||||||
| 71 | |||||||||||||||||||||||||||||
| 72 | 8 | ▶ | sub _init { | ||||||||||||||||||||||||||
|
Subroutine
_init: called CC=7 SCAR=20.3
| |||||||||||||||||||||||||||||
| 73 | 8 | my ($self, $config) = @_; | |||||||||||||||||||||||||||
| 74 | |||||||||||||||||||||||||||||
| 75 | 8 | ▶ | $self->{requests_per_second} = $config->{requests_per_second} // 10; | ||||||||||||||||||||||||||
|
Condition50%1/2
$config->{"requests_per_second"} // 10
MC/DC0%0/1
$config->{"requests_per_second"} // 10
$config->{"requests_per_second"}
Truth table50%1/2
A
A= $config->{"requests_per_second"}
| |||||||||||||||||||||||||||||
| 76 | 8 | ▶ | $self->{burst} = $config->{burst} // 20; | ||||||||||||||||||||||||||
|
Condition50%1/2
$config->{"burst"} // 20
MC/DC0%0/1
$config->{"burst"} // 20
$config->{"burst"}
Truth table50%1/2
A
A= $config->{"burst"}
| |||||||||||||||||||||||||||||
| 77 | 38 | ▶ | $self->{key_generator} = $config->{key_generator} // sub { | ||||||||||||||||||||||||||
|
Subroutine
__ANON__: called CC=3 SCAR=12.0
| |||||||||||||||||||||||||||||
| 78 | 38 | my ($scope) = @_; | |||||||||||||||||||||||||||
| 79 | 38 | ▶ | return exists $scope->{client} ? ($scope->{client}[0] // 'unknown') : 'unknown'; | ||||||||||||||||||||||||||
|
Branch: 1 branch
Condition50%1/2
$scope->{"client"}[0] // "unknown"
MC/DC0%0/1
$scope->{"client"}[0] // "unknown"
$scope->{"client"}[0]
Truth table50%1/2
A
A= $scope->{"client"}[0]
| |||||||||||||||||||||||||||||
| 80 | 8 | ▶ | }; | ||||||||||||||||||||||||||
|
Condition66%2/3
$config->{"key_generator"} // sub {
my($scope) = @_;
return exists $scope->{"client"} ? $scope->{"client"}[0] // "unknown" : "unknown";
}
MC/DC0%0/2
$config->{"key_generator"} // sub {
my($scope) = @_;
return exists $scope->{"client"} ? $scope->{"client"}[0] // "unknown" : "unknown";
}
$config->{"key_generator"}
sub {
my($scope) = @_;
return exists $scope->{"client"} ? $scope->{"client"}[0] // "unknown" : "unknown";
}
Truth table66%2/3
A // B
A= $config->{"key_generator"}B= sub {
my($scope) = @_;
return exists $scope->{"client"} ? $scope->{"client"}[0] // "unknown" : "unknown";
}
| |||||||||||||||||||||||||||||
| 81 | 8 | ▶ | $self->{backend} = $config->{backend} // 'memory'; | ||||||||||||||||||||||||||
|
Condition50%1/2
$config->{"backend"} // "memory"
MC/DC0%0/1
$config->{"backend"} // "memory"
$config->{"backend"}
Truth table50%1/2
A
A= $config->{"backend"}
| |||||||||||||||||||||||||||||
| 82 | 8 | ▶ | $self->{cleanup_interval} = $config->{cleanup_interval} // 60; | ||||||||||||||||||||||||||
|
Condition100%2/2
$config->{"cleanup_interval"} // 60
MC/DC100%1/1
$config->{"cleanup_interval"} // 60
$config->{"cleanup_interval"}
Truth table100%2/2
A
A= $config->{"cleanup_interval"}
| |||||||||||||||||||||||||||||
| 83 | 8 | ▶ | $self->{max_buckets} = $config->{max_buckets} // 10_000; | ||||||||||||||||||||||||||
|
Condition100%2/2
$config->{"max_buckets"} // 10000
MC/DC100%1/1
$config->{"max_buckets"} // 10000
$config->{"max_buckets"}
Truth table100%2/2
A
A= $config->{"max_buckets"}
| |||||||||||||||||||||||||||||
| 84 | } | ||||||||||||||||||||||||||||
| 85 | |||||||||||||||||||||||||||||
| 86 | 8 | ▶ | sub wrap { | ||||||||||||||||||||||||||
|
Subroutine
wrap: called CC=1 SCAR=0.0
Pod
documented
| |||||||||||||||||||||||||||||
| 87 | 8 | my ($self, $app) = @_; | |||||||||||||||||||||||||||
| 88 | |||||||||||||||||||||||||||||
| 89 | 41 | ▶ | return async sub { | ||||||||||||||||||||||||||
|
Subroutine
__ANON__: called CC=3 SCAR=11.1
| |||||||||||||||||||||||||||||
| 90 | 41 | my ($scope, $receive, $send) = @_; | |||||||||||||||||||||||||||
| 91 | 41 | ▶ | if ($scope->{type} ne 'http') { | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 92 | 0 | await $app->($scope, $receive, $send); | |||||||||||||||||||||||||||
| 93 | 0 | return; | |||||||||||||||||||||||||||
| 94 | } | ||||||||||||||||||||||||||||
| 95 | |||||||||||||||||||||||||||||
| 96 | 41 | my $key = $self->{key_generator}->($scope); | |||||||||||||||||||||||||||
| 97 | 41 | my ($allowed, $remaining, $reset) = $self->_check_rate_limit($key); | |||||||||||||||||||||||||||
| 98 | |||||||||||||||||||||||||||||
| 99 | 41 | ▶ | if (!$allowed) { | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 100 | 4 | await $self->_send_rate_limited($send, $remaining, $reset); | |||||||||||||||||||||||||||
| 101 | 4 | return; | |||||||||||||||||||||||||||
| 102 | } | ||||||||||||||||||||||||||||
| 103 | |||||||||||||||||||||||||||||
| 104 | # Add rate limit headers to response | ||||||||||||||||||||||||||||
| 105 | 74 | ▶ | my $wrapped_send = async sub { | ||||||||||||||||||||||||||
|
Subroutine
__ANON__: called CC=3 SCAR=11.0
| |||||||||||||||||||||||||||||
| 106 | 74 | my ($event) = @_; | |||||||||||||||||||||||||||
| 107 | 74 | ▶ | if ($event->{type} eq 'http.response.start') { | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 108 | 37 | ▶ | my @headers = @{$event->{headers} // []}; | ||||||||||||||||||||||||||
|
Condition50%1/2
$event->{"headers"} // []
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
| |||||||||||||||||||||||||||||
| 109 | 37 | push @headers, ['X-RateLimit-Limit', $self->{burst}]; | |||||||||||||||||||||||||||
| 110 | 37 | push @headers, ['X-RateLimit-Remaining', $remaining]; | |||||||||||||||||||||||||||
| 111 | 37 | push @headers, ['X-RateLimit-Reset', $reset]; | |||||||||||||||||||||||||||
| 112 | 37 | await $send->({ | |||||||||||||||||||||||||||
| 113 | %$event, | ||||||||||||||||||||||||||||
| 114 | headers => \@headers, | ||||||||||||||||||||||||||||
| 115 | }); | ||||||||||||||||||||||||||||
| 116 | } else { | ||||||||||||||||||||||||||||
| 117 | 37 | await $send->($event); | |||||||||||||||||||||||||||
| 118 | } | ||||||||||||||||||||||||||||
| 119 | 37 | }; | |||||||||||||||||||||||||||
| 120 | |||||||||||||||||||||||||||||
| 121 | 37 | await $app->($scope, $receive, $wrapped_send); | |||||||||||||||||||||||||||
| 122 | 8 | }; | |||||||||||||||||||||||||||
| 123 | } | ||||||||||||||||||||||||||||
| 124 | |||||||||||||||||||||||||||||
| 125 | 41 | ▶ | sub _check_rate_limit { | ||||||||||||||||||||||||||
|
Subroutine
_check_rate_limit: called CC=10 SCAR=23.0
| |||||||||||||||||||||||||||||
| 126 | 41 | my ($self, $key) = @_; | |||||||||||||||||||||||||||
| 127 | |||||||||||||||||||||||||||||
| 128 | 41 | my $now = _now(); | |||||||||||||||||||||||||||
| 129 | 41 | my $rate = $self->{requests_per_second}; | |||||||||||||||||||||||||||
| 130 | 41 | my $burst = $self->{burst}; | |||||||||||||||||||||||||||
| 131 | |||||||||||||||||||||||||||||
| 132 | # Get or initialize bucket | ||||||||||||||||||||||||||||
| 133 | 41 | ▶ | my $bucket = $buckets{$key} //= { | ||||||||||||||||||||||||||
|
Condition100%2/2
$buckets{$key} //= {"tokens", $burst, "last_time", $now}
MC/DC100%1/1
$buckets{$key} //= {"tokens", $burst, "last_time", $now}
$buckets{$key}
Truth table100%2/2
A
A= $buckets{$key}
| |||||||||||||||||||||||||||||
| 134 | tokens => $burst, | ||||||||||||||||||||||||||||
| 135 | last_time => $now, | ||||||||||||||||||||||||||||
| 136 | }; | ||||||||||||||||||||||||||||
| 137 | |||||||||||||||||||||||||||||
| 138 | # Refill tokens based on time elapsed | ||||||||||||||||||||||||||||
| 139 | 41 | my $elapsed = $now - $bucket->{last_time}; | |||||||||||||||||||||||||||
| 140 | 41 | my $refill = $elapsed * $rate; | |||||||||||||||||||||||||||
| 141 | 41 | $bucket->{tokens} = $bucket->{tokens} + $refill; | |||||||||||||||||||||||||||
| 142 | 41 | ▶ | $bucket->{tokens} = $burst if $bucket->{tokens} > $burst; | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 143 | 41 | $bucket->{last_time} = $now; | |||||||||||||||||||||||||||
| 144 | |||||||||||||||||||||||||||||
| 145 | # Determine rate limit result | ||||||||||||||||||||||||||||
| 146 | 41 | my @result; | |||||||||||||||||||||||||||
| 147 | 41 | ▶ | if ($bucket->{tokens} >= 1) { | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 148 | 37 | $bucket->{tokens} -= 1; | |||||||||||||||||||||||||||
| 149 | 37 | my $remaining = int($bucket->{tokens}); | |||||||||||||||||||||||||||
| 150 | 37 | my $reset = $now + int(($burst - $bucket->{tokens}) / $rate); | |||||||||||||||||||||||||||
| 151 | 37 | @result = (1, $remaining, $reset); # Allowed | |||||||||||||||||||||||||||
| 152 | } else { | ||||||||||||||||||||||||||||
| 153 | 4 | my $wait_time = (1 - $bucket->{tokens}) / $rate; | |||||||||||||||||||||||||||
| 154 | 4 | my $reset = $now + int($wait_time) + 1; | |||||||||||||||||||||||||||
| 155 | 4 | @result = (0, 0, $reset); # Not allowed | |||||||||||||||||||||||||||
| 156 | } | ||||||||||||||||||||||||||||
| 157 | |||||||||||||||||||||||||||||
| 158 | # Periodic cleanup of stale buckets | ||||||||||||||||||||||||||||
| 159 | 41 | ▶ | if (!$self->{_last_cleanup} || ($now - $self->{_last_cleanup}) >= $self->{cleanup_interval}) { | ||||||||||||||||||||||||||
|
Branch: 1 branch
Condition100%3/3
not $self->{"_last_cleanup"} or $now - $self->{"_last_cleanup"} >= $self->{"cleanup_interval"}
MC/DC100%2/2
not $self->{"_last_cleanup"} or $now - $self->{"_last_cleanup"} >= $self->{"cleanup_interval"}
not $self->{"_last_cleanup"}
$now - $self->{"_last_cleanup"} >= $self->{"cleanup_interval"}
Truth table100%3/3
not(A) or B
A= not $self->{"_last_cleanup"}B= $now - $self->{"_last_cleanup"} >= $self->{"cleanup_interval"}
| |||||||||||||||||||||||||||||
| 160 | 10 | $self->{_last_cleanup} = $now; | |||||||||||||||||||||||||||
| 161 | 10 | my $stale_threshold = $now - (2 * $burst / $rate); | |||||||||||||||||||||||||||
| 162 | 10 | for my $k (keys %buckets) { | |||||||||||||||||||||||||||
| 163 | 16 | ▶ | delete $buckets{$k} if $buckets{$k}{last_time} < $stale_threshold; | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 164 | } | ||||||||||||||||||||||||||||
| 165 | } | ||||||||||||||||||||||||||||
| 166 | |||||||||||||||||||||||||||||
| 167 | # Safety valve: evict oldest buckets when over max | ||||||||||||||||||||||||||||
| 168 | 41 | ▶ | if (keys %buckets > $self->{max_buckets}) { | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 169 | 1 | my @sorted = sort { $buckets{$a}{last_time} <=> $buckets{$b}{last_time} } keys %buckets; | |||||||||||||||||||||||||||
| 170 | 1 | my $to_remove = @sorted - int($self->{max_buckets} / 2); | |||||||||||||||||||||||||||
| 171 | 1 | delete $buckets{$_} for @sorted[0 .. $to_remove - 1]; | |||||||||||||||||||||||||||
| 172 | } | ||||||||||||||||||||||||||||
| 173 | |||||||||||||||||||||||||||||
| 174 | 41 | return @result; | |||||||||||||||||||||||||||
| 175 | } | ||||||||||||||||||||||||||||
| 176 | |||||||||||||||||||||||||||||
| 177 | 4 | ▶ | async sub _send_rate_limited { | ||||||||||||||||||||||||||
|
Subroutine
_send_rate_limited: called CC=2 SCAR=7.0
| |||||||||||||||||||||||||||||
| 178 | 4 | my ($self, $send, $remaining, $reset) = @_; | |||||||||||||||||||||||||||
| 179 | |||||||||||||||||||||||||||||
| 180 | 4 | my $retry_after = $reset - _now(); | |||||||||||||||||||||||||||
| 181 | 4 | ▶ | $retry_after = 1 if $retry_after < 1; | ||||||||||||||||||||||||||
|
Branch: 1 branch
| |||||||||||||||||||||||||||||
| 182 | |||||||||||||||||||||||||||||
| 183 | 4 | my $body = 'Rate limit exceeded. Try again later.'; | |||||||||||||||||||||||||||
| 184 | |||||||||||||||||||||||||||||
| 185 | await $send->({ | ||||||||||||||||||||||||||||
| 186 | type => 'http.response.start', | ||||||||||||||||||||||||||||
| 187 | status => 429, | ||||||||||||||||||||||||||||
| 188 | headers => [ | ||||||||||||||||||||||||||||
| 189 | ['Content-Type', 'text/plain'], | ||||||||||||||||||||||||||||
| 190 | ['Content-Length', length($body)], | ||||||||||||||||||||||||||||
| 191 | ['Retry-After', $retry_after], | ||||||||||||||||||||||||||||
| 192 | 4 | ['X-RateLimit-Limit', $self->{burst}], | |||||||||||||||||||||||||||
| 193 | ['X-RateLimit-Remaining', 0], | ||||||||||||||||||||||||||||
| 194 | ['X-RateLimit-Reset', $reset], | ||||||||||||||||||||||||||||
| 195 | ], | ||||||||||||||||||||||||||||
| 196 | }); | ||||||||||||||||||||||||||||
| 197 | 4 | await $send->({ | |||||||||||||||||||||||||||
| 198 | type => 'http.response.body', | ||||||||||||||||||||||||||||
| 199 | body => $body, | ||||||||||||||||||||||||||||
| 200 | more => 0, | ||||||||||||||||||||||||||||
| 201 | }); | ||||||||||||||||||||||||||||
| 202 | 2 | } | |||||||||||||||||||||||||||
| 203 | |||||||||||||||||||||||||||||
| 204 | # Class method to reset rate limits (useful for testing) | ||||||||||||||||||||||||||||
| 205 | 4 | ▶ | sub reset_all { | ||||||||||||||||||||||||||
|
Subroutine
reset_all: called CC=1 SCAR=0.0
Pod
undocumented
| |||||||||||||||||||||||||||||
| 206 | 4 | _clear_buckets(); | |||||||||||||||||||||||||||
| 207 | } | ||||||||||||||||||||||||||||
| 208 | |||||||||||||||||||||||||||||
| 209 | 2 | 1; | |||||||||||||||||||||||||||
| 210 | |||||||||||||||||||||||||||||
| 211 | __END__ | ||||||||||||||||||||||||||||