mirror of
https://github.com/silverstripe/silverstripe-environmentcheck
synced 2024-10-22 17:05:40 +02:00
Merge pull request #60 from silverstripe-terraformers/feature/extra-checks
Extra checks; cache headers, and session cookies
This commit is contained in:
commit
c5783a2450
@ -22,3 +22,14 @@ SilverStripe\Core\Injector\Injector:
|
||||
class: SilverStripe\EnvironmentCheck\Checks\SolrIndexCheck
|
||||
URLCheck:
|
||||
class: SilverStripe\EnvironmentCheck\Checks\URLCheck
|
||||
EnvCheckClient:
|
||||
factory: 'SilverStripe\EnvironmentCheck\Services\ClientFactory'
|
||||
constructor:
|
||||
timeout: 10.0
|
||||
|
||||
SilverStripe\EnvironmentCheck\Checks\SessionCheck:
|
||||
dependencies:
|
||||
client: '%$EnvCheckClient'
|
||||
SilverStripe\EnvironmentCheck\Checks\CacheHeadersCheck:
|
||||
dependencies:
|
||||
client: '%$EnvCheckClient'
|
||||
|
@ -16,7 +16,8 @@
|
||||
],
|
||||
"require": {
|
||||
"silverstripe/framework": "^4.0",
|
||||
"silverstripe/versioned": "^1.0"
|
||||
"silverstripe/versioned": "^1.0",
|
||||
"guzzlehttp/guzzle": "^6.3.3"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^5.7",
|
||||
|
@ -92,6 +92,9 @@ SilverStripe\EnvironmentCheck\EnvironmentCheckSuite:
|
||||
* `ExternalURLCheck`: Checks that one or more URLs are reachable via HTTP.
|
||||
* `SMTPConnectCheck`: Checks if the SMTP connection configured through PHP.ini works as expected.
|
||||
* `SolrIndexCheck`: Checks if the Solr cores of given class are available.
|
||||
* `SessionCheck`: Checks that a given URL does not generate a session.
|
||||
* `CacheHeadersCheck`: Check cache headers in response for directives that must either be included or excluded as well
|
||||
checking for existence of ETag.
|
||||
* `EnvTypeCheck`: Checks environment type, dev and test should not be used on production environments.
|
||||
|
||||
## Monitoring Checks
|
||||
|
207
src/Checks/CacheHeadersCheck.php
Normal file
207
src/Checks/CacheHeadersCheck.php
Normal file
@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Checks;
|
||||
|
||||
use SilverStripe\Control\Director;
|
||||
use SilverStripe\Control\Controller;
|
||||
use SilverStripe\ORM\ValidationResult;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use SilverStripe\Core\Config\Configurable;
|
||||
use SilverStripe\EnvironmentCheck\Traits\Fetcher;
|
||||
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
|
||||
|
||||
/**
|
||||
* Check cache headers for any response, can specify directives that must be included and
|
||||
* also must be excluded from Cache-Control headers in response. Also checks for
|
||||
* existence of ETag.
|
||||
*
|
||||
* @example SilverStripe\EnvironmentCheck\Checks\CacheHeadersCheck("/",["must-revalidate", "max-age=120"],["no-store"])
|
||||
* @package environmentcheck
|
||||
*/
|
||||
class CacheHeadersCheck implements EnvironmentCheck
|
||||
{
|
||||
use Fetcher;
|
||||
|
||||
/**
|
||||
* Settings that must be included in the Cache-Control header
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $mustInclude = [];
|
||||
|
||||
/**
|
||||
* Settings that must be excluded in the Cache-Control header
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $mustExclude = [];
|
||||
|
||||
/**
|
||||
* Result to keep track of status and messages for all checks, reuses
|
||||
* ValidationResult for convenience.
|
||||
*
|
||||
* @var ValidationResult
|
||||
*/
|
||||
protected $result;
|
||||
|
||||
/**
|
||||
* Set up with URL, arrays of header settings to check.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $mustInclude Settings that must be included in Cache-Control
|
||||
* @param array $mustExclude Settings that must be excluded in Cache-Control
|
||||
*/
|
||||
public function __construct($url = '', $mustInclude = [], $mustExclude = [])
|
||||
{
|
||||
$this->setURL($url);
|
||||
$this->mustInclude = $mustInclude;
|
||||
$this->mustExclude = $mustExclude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that correct caching headers are present.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function check()
|
||||
{
|
||||
// Using a validation result to capture messages
|
||||
$this->result = new ValidationResult();
|
||||
|
||||
$response = $this->client->get($this->getURL());
|
||||
$fullURL = $this->getURL();
|
||||
if ($response === null) {
|
||||
return [
|
||||
EnvironmentCheck::ERROR,
|
||||
"Cache headers check request failed for $fullURL",
|
||||
];
|
||||
}
|
||||
|
||||
//Check that Etag exists
|
||||
$this->checkEtag($response);
|
||||
|
||||
// Check Cache-Control settings
|
||||
$this->checkCacheControl($response);
|
||||
|
||||
if ($this->result->isValid()) {
|
||||
return [
|
||||
EnvironmentCheck::OK,
|
||||
$this->getMessage(),
|
||||
];
|
||||
} else {
|
||||
// @todo Ability to return a warning
|
||||
return [
|
||||
EnvironmentCheck::ERROR,
|
||||
$this->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collate messages from ValidationResult so that it is clear which parts
|
||||
* of the check passed and which failed.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getMessage()
|
||||
{
|
||||
$ret = '';
|
||||
// Filter good messages
|
||||
$goodTypes = [ValidationResult::TYPE_GOOD, ValidationResult::TYPE_INFO];
|
||||
$good = array_filter(
|
||||
$this->result->getMessages(),
|
||||
function ($val, $key) use ($goodTypes) {
|
||||
if (in_array($val['messageType'], $goodTypes)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
ARRAY_FILTER_USE_BOTH
|
||||
);
|
||||
if (!empty($good)) {
|
||||
$ret .= "GOOD: " . implode('; ', array_column($good, 'message')) . " ";
|
||||
}
|
||||
|
||||
// Filter bad messages
|
||||
$badTypes = [ValidationResult::TYPE_ERROR, ValidationResult::TYPE_WARNING];
|
||||
$bad = array_filter(
|
||||
$this->result->getMessages(),
|
||||
function ($val, $key) use ($badTypes) {
|
||||
if (in_array($val['messageType'], $badTypes)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
ARRAY_FILTER_USE_BOTH
|
||||
);
|
||||
if (!empty($bad)) {
|
||||
$ret .= "BAD: " . implode('; ', array_column($bad, 'message'));
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that ETag header exists
|
||||
*
|
||||
* @param ResponseInterface $response
|
||||
* @return void
|
||||
*/
|
||||
private function checkEtag(ResponseInterface $response)
|
||||
{
|
||||
$eTag = $response->getHeaderLine('ETag');
|
||||
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
|
||||
|
||||
if ($eTag) {
|
||||
$this->result->addMessage(
|
||||
"$fullURL includes an Etag header in response",
|
||||
ValidationResult::TYPE_GOOD
|
||||
);
|
||||
return;
|
||||
}
|
||||
$this->result->addError(
|
||||
"$fullURL is missing an Etag header",
|
||||
ValidationResult::TYPE_WARNING
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the correct header settings are either included or excluded.
|
||||
*
|
||||
* @param ResponseInterface $response
|
||||
* @return void
|
||||
*/
|
||||
private function checkCacheControl(ResponseInterface $response)
|
||||
{
|
||||
$cacheControl = $response->getHeaderLine('Cache-Control');
|
||||
$vals = array_map('trim', explode(',', $cacheControl));
|
||||
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
|
||||
|
||||
// All entries from must contain should be present
|
||||
if ($this->mustInclude == array_intersect($this->mustInclude, $vals)) {
|
||||
$matched = implode(",", $this->mustInclude);
|
||||
$this->result->addMessage(
|
||||
"$fullURL includes all settings: {$matched}",
|
||||
ValidationResult::TYPE_GOOD
|
||||
);
|
||||
} else {
|
||||
$missing = implode(",", array_diff($this->mustInclude, $vals));
|
||||
$this->result->addError(
|
||||
"$fullURL is excluding some settings: {$missing}"
|
||||
);
|
||||
}
|
||||
|
||||
// All entries from must exclude should not be present
|
||||
if (empty(array_intersect($this->mustExclude, $vals))) {
|
||||
$missing = implode(",", $this->mustExclude);
|
||||
$this->result->addMessage(
|
||||
"$fullURL excludes all settings: {$missing}",
|
||||
ValidationResult::TYPE_GOOD
|
||||
);
|
||||
} else {
|
||||
$matched = implode(",", array_intersect($this->mustExclude, $vals));
|
||||
$this->result->addError(
|
||||
"$fullURL is including some settings: {$matched}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
71
src/Checks/SessionCheck.php
Normal file
71
src/Checks/SessionCheck.php
Normal file
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Checks;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use SilverStripe\EnvironmentCheck\Traits\Fetcher;
|
||||
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
|
||||
|
||||
/**
|
||||
* Check that a given URL does not generate a session.
|
||||
*
|
||||
* @author Adrian Humphreys
|
||||
* @package environmentcheck
|
||||
*/
|
||||
class SessionCheck implements EnvironmentCheck
|
||||
{
|
||||
use Fetcher;
|
||||
|
||||
/**
|
||||
* Set up check with URL
|
||||
*
|
||||
* @param string $url The route, excluding the domain
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function __construct($url = '')
|
||||
{
|
||||
$this->setURL($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the response for URL does not create a session
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function check()
|
||||
{
|
||||
$response = $this->client->get($this->getURL());
|
||||
$cookie = $this->getCookie($response);
|
||||
$fullURL = $this->getURL();
|
||||
|
||||
if ($cookie) {
|
||||
return [
|
||||
EnvironmentCheck::ERROR,
|
||||
"Sessions are being set for {$fullURL} : Set-Cookie => " . $cookie,
|
||||
];
|
||||
}
|
||||
return [
|
||||
EnvironmentCheck::OK,
|
||||
"Sessions are not being created for {$fullURL} 👍",
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get PHPSESSID or SECSESSID cookie set from the response if it exists.
|
||||
*
|
||||
* @param ResponseInterface $response
|
||||
* @return string|null Cookie contents or null if it doesn't exist
|
||||
*/
|
||||
public function getCookie(ResponseInterface $response)
|
||||
{
|
||||
$result = null;
|
||||
$cookies = $response->getHeader('Set-Cookie');
|
||||
|
||||
foreach ($cookies as $cookie) {
|
||||
if (strpos($cookie, 'SESSID') !== false) {
|
||||
$result = $cookie;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
49
src/Services/ClientFactory.php
Normal file
49
src/Services/ClientFactory.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Services;
|
||||
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use SilverStripe\Core\Injector\Factory;
|
||||
use SilverStripe\Core\Config\Configurable;
|
||||
|
||||
/**
|
||||
* Factory class for creating HTTP client which are injected into some env check classes. Inject via YAML,
|
||||
* arguments for Guzzle client can be supplied using "constructor" property or set as default_config.
|
||||
*
|
||||
* @see SilverStripe\EnvironmentCheck\Traits\Fetcher
|
||||
*/
|
||||
class ClientFactory implements Factory
|
||||
{
|
||||
use Configurable;
|
||||
|
||||
/**
|
||||
* Default config for Guzzle client.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static $default_config = [];
|
||||
|
||||
/**
|
||||
* Wrapper to create a Guzzle client.
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function create($service, array $params = [])
|
||||
{
|
||||
return new GuzzleClient($this->getConfig($params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge config provided from yaml with default config
|
||||
*
|
||||
* @param array $overrides
|
||||
* @return array
|
||||
*/
|
||||
public function getConfig(array $overrides)
|
||||
{
|
||||
return array_merge(
|
||||
$this->config()->get('default_config'),
|
||||
$overrides
|
||||
);
|
||||
}
|
||||
}
|
51
src/Traits/Fetcher.php
Normal file
51
src/Traits/Fetcher.php
Normal file
@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Traits;
|
||||
|
||||
use SilverStripe\Control\Director;
|
||||
|
||||
/**
|
||||
* Simple helper for env checks which require HTTP clients.
|
||||
*
|
||||
* @package environmentcheck
|
||||
*/
|
||||
trait Fetcher
|
||||
{
|
||||
/**
|
||||
* Client for making requests, set vi Injector.
|
||||
*
|
||||
* @see SilverStripe\EnvironmentCheck\Services
|
||||
*
|
||||
* @var GuzzleHttp\Client
|
||||
*/
|
||||
public $client = null;
|
||||
|
||||
/**
|
||||
* Absolute URL for requests.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* Set URL for requests.
|
||||
*
|
||||
* @param string $url Relative URL
|
||||
* @return self
|
||||
*/
|
||||
public function setURL($url)
|
||||
{
|
||||
$this->url = Director::absoluteURL($url);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for URL
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getURL()
|
||||
{
|
||||
return $this->url;
|
||||
}
|
||||
}
|
101
tests/Checks/CacheHeadersCheckTest.php
Normal file
101
tests/Checks/CacheHeadersCheckTest.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use SilverStripe\Dev\SapphireTest;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
|
||||
use SilverStripe\EnvironmentCheck\Checks\CacheHeadersCheck;
|
||||
|
||||
/**
|
||||
* Test session checks.
|
||||
*/
|
||||
class CacheHeadersCheckTest extends SapphireTest
|
||||
{
|
||||
/**
|
||||
* Test that directives that must be included, are.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testMustInclude()
|
||||
{
|
||||
// Create a mock and queue responses
|
||||
$mock = new MockHandler([
|
||||
new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
|
||||
new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
|
||||
new Response(200, ['ETag' => '123']),
|
||||
new Response(200, ['Cache-Control' => 'must-revalidate, private', 'ETag' => '123']),
|
||||
]);
|
||||
|
||||
$handler = HandlerStack::create($mock);
|
||||
$client = new Client(['handler' => $handler]);
|
||||
|
||||
$cacheHeadersCheck = new CacheHeadersCheck('/', ['must-revalidate']);
|
||||
$cacheHeadersCheck->client = $client;
|
||||
|
||||
// Run checks for each response above
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that directives that must be excluded, are.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testMustExclude()
|
||||
{
|
||||
// Create a mock and queue responses
|
||||
$mock = new MockHandler([
|
||||
new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
|
||||
new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
|
||||
new Response(200, ['ETag' => '123']),
|
||||
new Response(200, ['Cache-Control' =>'private, no-store', ' ETag' => '123']),
|
||||
]);
|
||||
|
||||
$handler = HandlerStack::create($mock);
|
||||
$client = new Client(['handler' => $handler]);
|
||||
|
||||
$cacheHeadersCheck = new CacheHeadersCheck('/', [], ["no-store", "no-cache", "private"]);
|
||||
$cacheHeadersCheck->client = $client;
|
||||
|
||||
// Run checks for each response above
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that Etag header must exist in response.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testEtag()
|
||||
{
|
||||
// Create a mock and queue responses
|
||||
$mock = new MockHandler([
|
||||
new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
|
||||
new Response(200, ['Cache-Control' =>'no-cache']),
|
||||
new Response(200, ['ETag' => '123']),
|
||||
new Response(200, []),
|
||||
]);
|
||||
|
||||
$handler = HandlerStack::create($mock);
|
||||
$client = new Client(['handler' => $handler]);
|
||||
|
||||
$cacheHeadersCheck = new CacheHeadersCheck('/');
|
||||
$cacheHeadersCheck->client = $client;
|
||||
|
||||
// Run checks for each response above
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
|
||||
}
|
||||
}
|
76
tests/Checks/SessionCheckTest.php
Normal file
76
tests/Checks/SessionCheckTest.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use SilverStripe\Dev\SapphireTest;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
|
||||
use SilverStripe\EnvironmentCheck\Checks\SessionCheck;
|
||||
|
||||
/**
|
||||
* Test session checks.
|
||||
*/
|
||||
class SessionCheckTest extends SapphireTest
|
||||
{
|
||||
/**
|
||||
* @var SilverStripe\EnvironmentCheck\Checks\SessionCheck
|
||||
*/
|
||||
public $sessionCheck = null;
|
||||
|
||||
/**
|
||||
* Create a session check for use by tests.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
$this->sessionCheck = new SessionCheck('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Env check reports error when session cookies are being set.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testSessionSet()
|
||||
{
|
||||
// Create a mock and queue two responses.
|
||||
$mock = new MockHandler([
|
||||
new Response(200, ['Set-Cookie' => 'PHPSESSID:foo']),
|
||||
new Response(200, ['Set-Cookie' => 'SECSESSID:bar'])
|
||||
]);
|
||||
|
||||
$handler = HandlerStack::create($mock);
|
||||
$client = new Client(['handler' => $handler]);
|
||||
$this->sessionCheck->client = $client;
|
||||
|
||||
// Check for PHPSESSID
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
|
||||
|
||||
// Check for SECSESSID
|
||||
$this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
|
||||
}
|
||||
|
||||
/**
|
||||
* Env check responds OK when no session cookies are set in response.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testSessionNotSet()
|
||||
{
|
||||
// Create a mock and queue two responses.
|
||||
$mock = new MockHandler([
|
||||
new Response(200)
|
||||
]);
|
||||
|
||||
$handler = HandlerStack::create($mock);
|
||||
$client = new Client(['handler' => $handler]);
|
||||
$this->sessionCheck->client = $client;
|
||||
|
||||
$this->assertContains(EnvironmentCheck::OK, $this->sessionCheck->check());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user