From b167dfd575095cd574560a054673b0d3e78d9966 Mon Sep 17 00:00:00 2001 From: Dylan William Hardison Date: Thu, 21 Jun 2018 15:35:34 -0400 Subject: port BlockIP to mojolicious --- Bugzilla/ModPerl/BlockIP.pm | 67 ++++++++++++++++----------------------------- Bugzilla/Quantum.pm | 1 + 2 files changed, 24 insertions(+), 44 deletions(-) (limited to 'Bugzilla') diff --git a/Bugzilla/ModPerl/BlockIP.pm b/Bugzilla/ModPerl/BlockIP.pm index 4e9a4be5c..57f61c71f 100644 --- a/Bugzilla/ModPerl/BlockIP.pm +++ b/Bugzilla/ModPerl/BlockIP.pm @@ -1,64 +1,43 @@ -package Bugzilla::ModPerl::BlockIP; +package Bugzilla::Quantum::Plugin::BlockIP; use 5.10.1; -use strict; -use warnings; +use Mojo::Base 'Mojolicious::Plugin'; -use Apache2::RequestRec (); -use Apache2::Connection (); - -use Apache2::Const -compile => qw(OK); -use Cache::Memcached::Fast; +use Bugzilla::Memcached; use constant BLOCK_TIMEOUT => 60*60; my $MEMCACHED = Bugzilla::Memcached->_new()->{memcached}; -my $STATIC_URI = qr{ - ^/ - (?: extensions/[^/]+/web - | robots\.txt - | __heartbeat__ - | __lbheartbeat__ - | __version__ - | images - | skins - | js - | errors - ) -}xms; -sub block_ip { +sub register { + my ( $self, $app, $conf ) = @_; + + $app->hook(before_routes => \&_before_routes) + $app->helper(block_ip => \&_block_ip); + $app->helper(unblock_ip => \&_unblock_ip); +} + +sub _block_ip { my ($class, $ip) = @_; $MEMCACHED->set("block_ip:$ip" => 1, BLOCK_TIMEOUT) if $MEMCACHED; } -sub unblock_ip { +sub _unblock_ip { my ($class, $ip) = @_; $MEMCACHED->delete("block_ip:$ip") if $MEMCACHED; } -sub handler { - my $r = shift; - return Apache2::Const::OK if $r->uri =~ $STATIC_URI; - - my $ip = $r->headers_in->{'X-Forwarded-For'}; - if ($ip) { - $ip = (split(/\s*,\s*/ms, $ip))[-1]; - } - else { - $ip = $r->connection->remote_ip; - } +sub _before_routes { + my ( $c ) = @_; + return if $c->stash->{'mojo.static'}; + my $ip = $c->tx->remote_address; + $c->app->log->debug("remote ip: $ip"); if ($MEMCACHED && $MEMCACHED->get("block_ip:$ip")) { - __PACKAGE__->block_ip($ip); - $r->status_line("429 Too Many Requests"); - # 500 is used here because apache 2.2 doesn't understand 429. - # the above line and the return value together mean we produce 429. - # Any other variation doesn't work. - $r->custom_response(500, "Too Many Requests"); - return 429; - } - else { - return Apache2::Const::OK; + $c->block_ip($ip); + $c->res->code(429); + $c->res->message("Too Many Requests"); + $c->res->body("Too Many Requests"); + $c->finish; } } diff --git a/Bugzilla/Quantum.pm b/Bugzilla/Quantum.pm index b11e183d2..e1cf94f2c 100644 --- a/Bugzilla/Quantum.pm +++ b/Bugzilla/Quantum.pm @@ -32,6 +32,7 @@ sub startup { $self->plugin('Bugzilla::Quantum::Plugin::Glue'); $self->plugin('Bugzilla::Quantum::Plugin::Hostage'); + $self->plugin('Bugzilla::Quantum::Plugin::BlockIP'); my $r = $self->routes; Bugzilla::Quantum::CGI->load_all($r); -- cgit v1.2.3-24-g4f1b