Skip to content

Commit

Permalink
Fix CS using Symfony CS
Browse files Browse the repository at this point in the history
  • Loading branch information
romainneutron committed Apr 16, 2016
1 parent 10c378b commit 92c6121
Show file tree
Hide file tree
Showing 25 changed files with 90 additions and 100 deletions.
2 changes: 1 addition & 1 deletion ContentSecurityPolicy/ContentSecurityPolicyParser.php
Expand Up @@ -28,7 +28,7 @@ public function parseSourceList(array $sourceList = null)

$sourceList = $this->quoteKeywords($sourceList);

return join(' ', $sourceList);
return implode(' ', $sourceList);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions ContentSecurityPolicy/DirectiveSet.php
Expand Up @@ -76,11 +76,11 @@ public function buildHeaderValue()
$policy[] = $name;
} elseif ($name === 'default-src' || $value !== $this->getDirective('default-src')) {
// prevents using the same value as default for a directive
$policy[] = $name . ' ' . $value;
$policy[] = $name.' '.$value;
}
}

return join('; ', $policy);
return implode('; ', $policy);
}

public static function fromConfig(array $config, $kind)
Expand Down Expand Up @@ -110,7 +110,7 @@ public static function getNames()
private function checkDirectiveName($name)
{
if (!in_array($name, self::$directiveNames, true)) {
throw new \InvalidArgumentException('Unknown CSP directive name: ' . $name);
throw new \InvalidArgumentException('Unknown CSP directive name: '.$name);
}
}
}
16 changes: 8 additions & 8 deletions DependencyInjection/Configuration.php
Expand Up @@ -11,9 +11,8 @@

namespace Nelmio\SecurityBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder,
Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Nelmio\SecurityBundle\ContentSecurityPolicy\DirectiveSet;

class Configuration implements ConfigurationInterface
Expand All @@ -25,7 +24,7 @@ public function getConfigTreeBuilder()

$rootNode
->validate()
->ifTrue(function($v) {
->ifTrue(function ($v) {
return $v['forced_ssl']['enabled'] && $v['flexible_ssl']['enabled'];
})
->thenInvalid('"forced_ssl" and "flexible_ssl" can not be used together')
Expand Down Expand Up @@ -63,7 +62,7 @@ public function getConfigTreeBuilder()
->useAttributeAsKey('pattern')
->prototype('array')
->beforeNormalization()
->always(function($v) {
->always(function ($v) {
if (!is_array($v)) {
$v = array('header' => $v ?: 'DENY');
}
Expand All @@ -75,7 +74,7 @@ public function getConfigTreeBuilder()
})
->end()
->validate()
->ifTrue(function($v) {
->ifTrue(function ($v) {
return isset($v['header']) && !in_array($v['header'], array('DENY', 'SAMEORIGIN', 'ALLOW'), true)
&& !preg_match('{^ALLOW FROM \S+}', $v['header']);
})
Expand All @@ -93,7 +92,7 @@ public function getConfigTreeBuilder()

->arrayNode('external_redirects')
->validate()
->ifTrue(function($v) {
->ifTrue(function ($v) {
return isset($v['abort']) && $v['abort'] && isset($v['override']) && $v['override'];
})
->thenInvalid('"abort" and "override" can not be combined')
Expand Down Expand Up @@ -183,7 +182,7 @@ private function addCspNode()
->append($this->addReportOrEnforceNode('enforce'))
->end()
->validate()
->ifTrue(function($v) {
->ifTrue(function ($v) {
foreach (array('report', 'enforce') as $type) {
foreach (array('upgrade-insecure-requests', 'block-all-mixed-content') as $directive) {
if (isset($v[$type][$directive]) && !empty($v[$type][$directive])) {
Expand Down Expand Up @@ -214,6 +213,7 @@ private function addReportOrEnforceNode($reportOrEnforce)
->prototype('scalar')
->end();
}

return $children->end();
}
}
2 changes: 1 addition & 1 deletion DependencyInjection/NelmioSecurityExtension.php
Expand Up @@ -90,7 +90,7 @@ public function load(array $configs, ContainerBuilder $container)
$container->setParameter('nelmio_security.external_redirects.forward_as', $config['external_redirects']['forward_as']);
$container->setParameter('nelmio_security.external_redirects.abort', $config['external_redirects']['abort']);
if ($config['external_redirects']['whitelist']) {
$whitelist = array_map(function($el) {
$whitelist = array_map(function ($el) {
if ($host = parse_url($el, PHP_URL_HOST)) {
return ltrim($host, '.');
}
Expand Down
12 changes: 6 additions & 6 deletions Encrypter.php
Expand Up @@ -22,7 +22,7 @@ public function __construct($secret, $algorithm)
{
$this->secret = substr($secret, 0, 32);
$this->algorithm = $algorithm;

if (!function_exists('mcrypt_module_open')) {
throw new \RuntimeException('You need to install mcrypt if you want to encrypt your cookies.');
}
Expand All @@ -39,35 +39,35 @@ public function __construct($secret, $algorithm)
public function encrypt($input)
{
if (empty($input)) {
return null;
return;
}

$iv = mcrypt_create_iv($this->ivSize, MCRYPT_RAND);

mcrypt_generic_init($this->module, $this->secret, $iv);

return rtrim(base64_encode($iv . mcrypt_generic($this->module, (string) $input)), '=');
return rtrim(base64_encode($iv.mcrypt_generic($this->module, (string) $input)), '=');
}

public function decrypt($input)
{
if (empty($input)) {
return null;
return;
}

$encryptedData = base64_decode($input, true);

$iv = substr($encryptedData, 0, $this->ivSize);

if (strlen($iv) < $this->ivSize) {
return null;
return;
}

$encryptedData = substr($encryptedData, $this->ivSize);

$init = @mcrypt_generic_init($this->module, $this->secret, $iv);
if ($init === false || $init < 0) {
return null;
return;
}

return rtrim(mdecrypt_generic($this->module, $encryptedData), "\0");
Expand Down
8 changes: 4 additions & 4 deletions EventListener/ContentSecurityPolicyListener.php
Expand Up @@ -53,7 +53,7 @@ public function onKernelResponse(FilterResponseEvent $e)
if ($response->isRedirection()) {
return;
}

if ((empty($this->hosts) || in_array($e->getRequest()->getHost(), $this->hosts, true)) && $this->isContentTypeValid($response)) {
$response->headers->add($this->buildHeaders($this->report, true, $this->compatHeaders));
$response->headers->add($this->buildHeaders($this->enforce, false, $this->compatHeaders));
Expand All @@ -67,12 +67,12 @@ private function buildHeaders(DirectiveSet $directiveSet, $reportOnly, $compatHe
return array();
}

$hn = function($name) use ($reportOnly) {
return $name . ($reportOnly ? '-Report-Only' : '');
$hn = function ($name) use ($reportOnly) {
return $name.($reportOnly ? '-Report-Only' : '');
};

$headers = array(
$hn('Content-Security-Policy') => $headerValue
$hn('Content-Security-Policy') => $headerValue,
);

if ($compatHeaders) {
Expand Down
12 changes: 6 additions & 6 deletions EventListener/ExternalRedirectListener.php
Expand Up @@ -29,12 +29,12 @@ class ExternalRedirectListener
private $generator;

/**
* @param Boolean $abort If true, the offending redirects are turned into 403 responses, can't be combined with $override
* @param string $override Absolute path, complete URL or route name that must be used instead of the offending redirect's url
* @param string $forwardAs Name of the route-/query string parameter the blocked url will be passed to destination location
* @param bool $abort If true, the offending redirects are turned into 403 responses, can't be combined with $override
* @param string $override Absolute path, complete URL or route name that must be used instead of the offending redirect's url
* @param string $forwardAs Name of the route-/query string parameter the blocked url will be passed to destination location
* @param mixed $targetValidator array of hosts to be whitelisted, or regex that matches whitelisted hosts, or implementation of TargetValidator
* @param LoggerInterface $logger A logger, if it's present, detected offenses are logged at the warning level
* @param UrlGeneratorInterface $generator Router or equivalent that can generate a route, only if override is a route name
* @param LoggerInterface $logger A logger, if it's present, detected offenses are logged at the warning level
* @param UrlGeneratorInterface $generator Router or equivalent that can generate a route, only if override is a route name
*/
public function __construct($abort = true, $override = null, $forwardAs = null, $targetValidator = null, LoggerInterface $logger = null, UrlGeneratorInterface $generator = null)
{
Expand All @@ -47,7 +47,7 @@ public function __construct($abort = true, $override = null, $forwardAs = null,

if (is_string($targetValidator) || is_array($targetValidator)) {
$targetValidator = new WhitelistBasedTargetValidator($targetValidator);
} elseif ($targetValidator !== null && ! $targetValidator instanceof TargetValidator) {
} elseif ($targetValidator !== null && !$targetValidator instanceof TargetValidator) {
throw new \LogicException('$targetValidator should be an array of hosts, a regular expression, or an implementation of TargetValidator.');
}
$this->targetValidator = $targetValidator;
Expand Down
1 change: 0 additions & 1 deletion EventListener/FlexibleSslListener.php
Expand Up @@ -18,7 +18,6 @@
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
Expand Down
2 changes: 0 additions & 2 deletions EventListener/ForcedSslListener.php
Expand Up @@ -11,9 +11,7 @@

namespace Nelmio\SecurityBundle\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
Expand Down
3 changes: 2 additions & 1 deletion ExternalRedirect/TargetValidator.php
Expand Up @@ -17,7 +17,8 @@ interface TargetValidator
* Returns whether a target is acceptable.
*
* @param string $targetUrl
* @return boolean
*
* @return bool
*/
public function isTargetAllowed($targetUrl);
}
2 changes: 1 addition & 1 deletion ExternalRedirect/WhitelistBasedTargetValidator.php
Expand Up @@ -19,7 +19,7 @@ public function __construct($whitelist = null)
{
if (is_array($whitelist)) {
if ($whitelist) {
$whitelist = array_map(function($el) {
$whitelist = array_map(function ($el) {
return preg_quote(ltrim($el, '.'));
}, $whitelist);
$whitelist = '(?:.*\.'.implode('|.*\.', $whitelist).'|'.implode('|', $whitelist).')';
Expand Down
2 changes: 1 addition & 1 deletion Session/CookieSessionHandler.php
Expand Up @@ -182,7 +182,7 @@ public function read($sessionId)
if ($content === false) {
$content = array(
'expire' => strtotime('now'),
'data' => ''
'data' => '',
);
}

Expand Down
4 changes: 2 additions & 2 deletions Signer.php
Expand Up @@ -46,7 +46,7 @@ public function verifySignedValue($signedValue)
}

$result = 0;
for ($i = 0, $j = strlen($signature); $i < $j; $i++) {
for ($i = 0, $j = strlen($signature); $i < $j; ++$i) {
$result |= ord($signature[$i]) ^ ord($signature2[$i]);
}

Expand Down Expand Up @@ -76,6 +76,6 @@ private function splitSignatureFromSignedValue($signedValue)
return array($signedValue, null);
}

return array(substr($signedValue, 0, $pos), substr($signedValue, $pos+1));
return array(substr($signedValue, 0, $pos), substr($signedValue, $pos + 1));
}
}
Expand Up @@ -14,7 +14,7 @@ public function testQuotesKeywords($source, $expected)
$parser = new ContentSecurityPolicyParser();

$sourceList = array($source);
$result = $parser->parseSourceList($sourceList);
$result = $parser->parseSourceList($sourceList);
$this->assertEquals($expected, $result, 'CSP parser should quote CSP keywords');
}

Expand Down
26 changes: 13 additions & 13 deletions Tests/ContentSecurityPolicy/DirectiveSetTest.php
Expand Up @@ -9,20 +9,20 @@ class DirectiveSetTest extends \PHPUnit_Framework_TestCase
public function testFromConfig()
{
$ds = DirectiveSet::fromConfig(array('enforce' => array(
'default-src' => array("example.org", "'self'"),
'script-src' => array("script.example.org", "'self'"),
'object-src' => array("object.example.org", "'self'"),
'style-src' => array("style.example.org", "'self'"),
'img-src' => array("img.example.org", "'self'"),
'media-src' => array("media.example.org", "'self'"),
'frame-src' => array("frame.example.org", "'self'"),
'font-src' => array("font.example.org", "'self'"),
'connect-src' => array("connect.example.org", "'self'"),
'default-src' => array('example.org', "'self'"),
'script-src' => array('script.example.org', "'self'"),
'object-src' => array('object.example.org', "'self'"),
'style-src' => array('style.example.org', "'self'"),
'img-src' => array('img.example.org', "'self'"),
'media-src' => array('media.example.org', "'self'"),
'frame-src' => array('frame.example.org', "'self'"),
'font-src' => array('font.example.org', "'self'"),
'connect-src' => array('connect.example.org', "'self'"),
'report-uri' => array('http://report-uri'),
'base-uri' => array("base-uri.example.org", "'self'"),
'child-src' => array("child-src.example.org", "'self'"),
'form-action' => array("form-action.example.org", "'self'"),
'frame-ancestors' => array("frame-ancestors.example.org", "'self'"),
'base-uri' => array('base-uri.example.org', "'self'"),
'child-src' => array('child-src.example.org', "'self'"),
'form-action' => array('form-action.example.org', "'self'"),
'frame-ancestors' => array('frame-ancestors.example.org', "'self'"),
'plugin-types' => array('application/shockwave-flash'),
'block-all-mixed-content' => null,
'upgrade-insecure-requests' => null,
Expand Down
35 changes: 18 additions & 17 deletions Tests/DependencyInjection/ConfigurationTest.php
Expand Up @@ -3,7 +3,6 @@
namespace Nelmio\SecurityBundle\Tests\DependencyInjection;

use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Yaml\Yaml;
use Nelmio\SecurityBundle\DependencyInjection\Configuration;
use Symfony\Component\Yaml\Parser;

Expand All @@ -12,24 +11,24 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
public function testCspWithReportAndEnforceSubtrees()
{
$this->processYamlConfiguration(
"csp:\n" .
" report:\n" .
" script-src:\n" .
" - 'self'\n" .
" enforce:\n" .
" script-src:\n" .
"csp:\n".
" report:\n".
" script-src:\n".
" - 'self'\n".
" enforce:\n".
" script-src:\n".
" - 'self'"
);
}

public function testCspWithLevel2()
{
$this->processYamlConfiguration(
"csp:\n" .
" report:\n" .
" script-src:\n" .
" - 'self'\n" .
" upgrade-insecure-requests: ~\n" .
"csp:\n".
" report:\n".
" script-src:\n".
" - 'self'\n".
" upgrade-insecure-requests: ~\n".
" block-all-mixed-content: ~\n"
);
}
Expand All @@ -41,25 +40,27 @@ public function testCspWithLevel2()
public function testCspInvalidLevel2()
{
$this->processYamlConfiguration(
"csp:\n" .
" report:\n" .
" script-src:\n" .
" - 'self'\n" .
" upgrade-insecure-requests:\n" .
"csp:\n".
" report:\n".
" script-src:\n".
" - 'self'\n".
" upgrade-insecure-requests:\n".
" - 'self'\n"
);
}

private function processYamlConfiguration($config)
{
$parser = new Parser();

return $this->processYaml($parser->parse($config));
}

private function processYaml($parsedYaml)
{
$processor = new Processor();
$configDefinition = new Configuration();

return $processor->processConfiguration($configDefinition, array($parsedYaml));
}
}
1 change: 0 additions & 1 deletion Tests/Listener/ClickjackingListenerTest.php
Expand Up @@ -12,7 +12,6 @@
namespace Nelmio\SecurityBundle\Tests\Listener;

use Nelmio\SecurityBundle\EventListener\ClickjackingListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
Expand Down

0 comments on commit 92c6121

Please sign in to comment.