Skip to content

Commit

Permalink
Throw exception instead of returning 403
Browse files Browse the repository at this point in the history
  • Loading branch information
danizord committed Jun 27, 2016
1 parent cfe745d commit a7d0b28
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
10 changes: 7 additions & 3 deletions src/Middleware/LocalhostCheckerMiddleware.php
Expand Up @@ -4,6 +4,7 @@

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ZfrEbWorker\Exception\RuntimeException;

/**
* Middleware that protects the worker middleware by only allowing localhost requests
Expand All @@ -29,11 +30,14 @@ public function __invoke(
callable $out = null
): ResponseInterface {
$serverParams = $request->getServerParams();
$remoteAddr = $serverParams['REMOTE_ADDR'] ?? '';
$remoteAddr = $serverParams['REMOTE_ADDR'] ?? 'unknown IP address';

// If request is not originating from localhost or from Docker local IP, we simply return 200
// If request is not originating from localhost or from Docker local IP, we throw an RuntimeException
if (!in_array($remoteAddr, $this->localhost) && !fnmatch('172.17.*', $remoteAddr)) {
return $response->withStatus(403);
throw new RuntimeException(sprintf(
'Worker requests must come from localhost, request originated from %s given',
$remoteAddr
));
}

return $out($request, $response, $out);
Expand Down
14 changes: 9 additions & 5 deletions test/Middleware/LocalhostCheckerMiddlewareTest.php
Expand Up @@ -4,11 +4,12 @@

use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response;
use ZfrEbWorker\Exception\RuntimeException;
use ZfrEbWorker\Middleware\LocalhostCheckerMiddleware;

class LocalhostCheckerMiddlewareTest extends \PHPUnit_Framework_TestCase
{
public function testReturns403IfNotFromLocalhost()
public function testThrowsExceptionIfNotFromLocalhost()
{
$request = $this->prophesize(ServerRequestInterface::class);
$response = new Response();
Expand All @@ -17,11 +18,14 @@ public function testReturns403IfNotFromLocalhost()

$middleware = new LocalhostCheckerMiddleware();

$returnedResponse = $middleware->__invoke($request->reveal(), $response, function() {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage(
'Worker requests must come from localhost, request originated from 123.43.45.242 given'
);

$middleware->__invoke($request->reveal(), $response, function() {
$this->fail('Should not be called');
});

$this->assertEquals(403, $returnedResponse->getStatusCode());
}

public function dockerIpAddresses()
Expand Down Expand Up @@ -79,4 +83,4 @@ public function testDelegateIfFromIPv6Localhost()

$this->assertEquals(200, $returnedResponse->getStatusCode());
}
}
}

0 comments on commit a7d0b28

Please sign in to comment.