Skip to content

New Component: Expression Language #8913

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Sep 19, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"symfony/doctrine-bridge": "self.version",
"symfony/dom-crawler": "self.version",
"symfony/event-dispatcher": "self.version",
"symfony/expression-language": "self.version",
"symfony/filesystem": "self.version",
"symfony/finder": "self.version",
"symfony/form": "self.version",
Expand Down
47 changes: 47 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\ExpressionLanguage\Expression;

/**
* ExpressionExtension gives a way to create Expressions from a template.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('expression', array($this, 'createExpression')),
);
}

private function createExpression($expression)
{
return new Expression($expression);
}

/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'expression';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ public function load(array $configs, ContainerBuilder $container)
// will be used and everything will still work as expected.
$loader->load('translation.xml');

// Property access is used by both the Form and the Validator component
$loader->load('property_access.xml');

$loader->load('debug_prod.xml');

if ($container->getParameter('kernel.debug')) {
Expand Down
4 changes: 0 additions & 4 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
<parameter key="form.factory.class">Symfony\Component\Form\FormFactory</parameter>
<parameter key="form.extension.class">Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension</parameter>
<parameter key="form.type_guesser.validator.class">Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser</parameter>
<parameter key="property_accessor.class">Symfony\Component\PropertyAccess\PropertyAccessor</parameter>
</parameters>

<services>
Expand Down Expand Up @@ -54,9 +53,6 @@
<argument type="service" id="validator.mapping.class_metadata_factory" />
</service>

<!-- PropertyAccessor -->
<service id="property_accessor" class="%property_accessor.class%" />

<!-- CoreExtension -->
<service id="form.type.form" class="Symfony\Component\Form\Extension\Core\Type\FormType">
<argument type="service" id="property_accessor"/>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you have removed the service then please remove the class key also from this file as it is already moved to its own property_access.xml 👶

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter key="property_accessor.class">Symfony\Component\PropertyAccess\PropertyAccessor</parameter>
</parameters>

<services>
<service id="property_accessor" class="%property_accessor.class%" />
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<parameter key="validator.validator_factory.class">Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory</parameter>
<parameter key="validator.mapping.loader.xml_files_loader.mapping_files" type="collection" />
<parameter key="validator.mapping.loader.yaml_files_loader.mapping_files" type="collection" />
<parameter key="validator.expression.class">Symfony\Component\Validator\Constraints\ExpressionValidator</parameter>
</parameters>

<services>
Expand Down Expand Up @@ -63,5 +64,10 @@
<service id="validator.mapping.loader.yaml_files_loader" class="%validator.mapping.loader.yaml_files_loader.class%" public="false">
<argument>%validator.mapping.loader.yaml_files_loader.mapping_files%</argument>
</service>

<service id="validator.expression" class="%validator.expression.class%">
<argument type="service" id="property_accessor" />
<tag name="validator.constraint_validator" alias="validator.expression" />
</service>
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ private function addAccessControlSection(ArrayNodeDefinition $rootNode)
->beforeNormalization()->ifString()->then(function($v) { return preg_split('/\s*,\s*/', $v); })->end()
->prototype('scalar')->end()
->end()
->scalarNode('allow_if')->defaultNull()->end()
->end()
->fixXmlConfig('role')
->children()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;

/**
* SecurityExtension.
Expand All @@ -33,10 +35,12 @@
class SecurityExtension extends Extension
{
private $requestMatchers = array();
private $expressions = array();
private $contextListeners = array();
private $listenerPositions = array('pre_auth', 'form', 'http', 'remember_me');
private $factories = array();
private $userProviderFactories = array();
private $expressionLanguage;

public function __construct()
{
Expand Down Expand Up @@ -188,8 +192,13 @@ private function createAuthorization($config, ContainerBuilder $container)
$access['ips']
);

$attributes = $access['roles'];
if ($access['allow_if']) {
$attributes[] = $this->createExpression($container, $access['allow_if']);
}

$container->getDefinition('security.access_map')
->addMethodCall('add', array($matcher, $access['roles'], $access['requires_channel']));
->addMethodCall('add', array($matcher, $attributes, $access['requires_channel']));
}
}

Expand Down Expand Up @@ -596,6 +605,22 @@ private function createSwitchUserListener($container, $id, $config, $defaultProv
return $switchUserListenerId;
}

private function createExpression($container, $expression)
{
if (isset($this->expressions[$id = 'security.expression.'.sha1($expression)])) {
return $this->expressions[$id];
}

$container
->register($id, 'Symfony\Component\ExpressionLanguage\SerializedParsedExpression')
->setPublic(false)
->addArgument($expression)
->addArgument(serialize($this->getExpressionLanguage()->parse($expression, array('token', 'user', 'object', 'roles', 'request'))))
;

return $this->expressions[$id] = new Reference($id);
}

private function createRequestMatcher($container, $path = null, $host = null, $methods = array(), $ip = null, array $attributes = array())
{
$serialized = serialize(array($path, $host, $methods, $ip, $attributes));
Expand Down Expand Up @@ -654,4 +679,16 @@ public function getConfiguration(array $config, ContainerBuilder $container)
// first assemble the factories
return new MainConfiguration($this->factories, $this->userProviderFactories);
}

private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();
}

return $this->expressionLanguage;
}
}
12 changes: 12 additions & 0 deletions src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,21 @@
<parameter key="security.access.simple_role_voter.class">Symfony\Component\Security\Core\Authorization\Voter\RoleVoter</parameter>
<parameter key="security.access.authenticated_voter.class">Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter</parameter>
<parameter key="security.access.role_hierarchy_voter.class">Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter</parameter>
<parameter key="security.access.expression_voter.class">Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter</parameter>

<parameter key="security.firewall.class">Symfony\Component\Security\Http\Firewall</parameter>
<parameter key="security.firewall.map.class">Symfony\Bundle\SecurityBundle\Security\FirewallMap</parameter>
<parameter key="security.firewall.context.class">Symfony\Bundle\SecurityBundle\Security\FirewallContext</parameter>
<parameter key="security.matcher.class">Symfony\Component\HttpFoundation\RequestMatcher</parameter>
<parameter key="security.expression_matcher.class">Symfony\Component\HttpFoundation\ExpressionRequestMatcher</parameter>

<parameter key="security.role_hierarchy.class">Symfony\Component\Security\Core\Role\RoleHierarchy</parameter>

<parameter key="security.http_utils.class">Symfony\Component\Security\Http\HttpUtils</parameter>

<parameter key="security.validator.user_password.class">Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator</parameter>

<parameter key="security.expression_language.class">Symfony\Component\Security\Core\Authorization\ExpressionLanguage</parameter>
</parameters>

<services>
Expand Down Expand Up @@ -78,6 +82,7 @@

<service id="security.user_checker" class="%security.user_checker.class%" public="false" />

<service id="security.expression_language" class="%security.expression_language.class%" public="false" />

<!-- Authorization related services -->
<service id="security.access.decision_manager" class="%security.access.decision_manager.class%" public="false">
Expand All @@ -104,6 +109,13 @@
<tag name="security.voter" priority="245" />
</service>

<service id="security.access.expression_voter" class="%security.access.expression_voter.class%" public="false">
<argument type="service" id="security.expression_language" />
<argument type="service" id="security.authentication.trust_resolver" />
<argument type="service" id="security.role_hierarchy" on-invalid="null" />
<tag name="security.voter" priority="245" />
</service>


<!-- Firewall related services -->
<service id="security.firewall" class="%security.firewall.class%">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\ExpressionLanguage\Expression;

abstract class CompleteConfigurationTest extends \PHPUnit_Framework_TestCase
{
Expand Down Expand Up @@ -133,27 +134,31 @@ public function testAccess()

$matcherIds = array();
foreach ($rules as $rule) {
list($matcherId, $roles, $channel) = $rule;
list($matcherId, $attributes, $channel) = $rule;
$requestMatcher = $container->getDefinition($matcherId);

$this->assertFalse(isset($matcherIds[$matcherId]));
$matcherIds[$matcherId] = true;

$i = count($matcherIds);
if (1 === $i) {
$this->assertEquals(array('ROLE_USER'), $roles);
$this->assertEquals(array('ROLE_USER'), $attributes);
$this->assertEquals('https', $channel);
$this->assertEquals(
array('/blog/524', null, array('GET', 'POST')),
$requestMatcher->getArguments()
);
} elseif (2 === $i) {
$this->assertEquals(array('IS_AUTHENTICATED_ANONYMOUSLY'), $roles);
$this->assertEquals(array('IS_AUTHENTICATED_ANONYMOUSLY'), $attributes);
$this->assertNull($channel);
$this->assertEquals(
array('/blog/.*'),
$requestMatcher->getArguments()
);
} elseif (3 === $i) {
$this->assertEquals('IS_AUTHENTICATED_ANONYMOUSLY', $attributes[0]);
$expression = $container->getDefinition($attributes[1])->getArgument(0);
$this->assertEquals("token.getUsername() =~ '/^admin/'", $expression);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
'access_control' => array(
array('path' => '/blog/524', 'role' => 'ROLE_USER', 'requires_channel' => 'https', 'methods' => array('get', 'POST')),
array('path' => '/blog/.*', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY'),
array('path' => '/blog/524', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY', 'allow_if' => "token.getUsername() =~ '/^admin/'"),
),

'role_hierarchy' => array(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,6 @@

<rule path="/blog/524" role="ROLE_USER" requires-channel="https" methods="get,POST" />
<rule role='IS_AUTHENTICATED_ANONYMOUSLY' path="/blog/.*" />
<rule role='IS_AUTHENTICATED_ANONYMOUSLY' allow-if="token.getUsername() =~ '/^admin/'" path="/blog/524" />
</config>
</srv:container>
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,4 @@ security:
-
path: /blog/.*
role: IS_AUTHENTICATED_ANONYMOUSLY
- { path: /blog/524, role: IS_AUTHENTICATED_ANONYMOUSLY, allow_if: "token.getUsername() =~ '/^admin/'" }
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@ form_logout:
form_secure_action:
path: /secure-but-not-covered-by-access-control
defaults: { _controller: FormLoginBundle:Login:secure }

protected-via-expression:
path: /protected-via-expression
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,28 @@ public function testSecurityConfigurationForMultipleIPAddresses($config)
$this->assertRestricted($barredClient, '/secured-by-two-ips');
}

/**
* @dataProvider getConfigs
*/
public function testSecurityConfigurationForExpression($config)
{
$allowedClient = $this->createClient(array('test_case' => 'StandardFormLogin', 'root_config' => $config), array('HTTP_USER_AGENT' => 'Firefox 1.0'));
$this->assertAllowed($allowedClient, '/protected-via-expression');

$barredClient = $this->createClient(array('test_case' => 'StandardFormLogin', 'root_config' => $config), array());
$this->assertRestricted($barredClient, '/protected-via-expression');

$allowedClient = $this->createClient(array('test_case' => 'StandardFormLogin', 'root_config' => $config), array());

$allowedClient->request('GET', '/protected-via-expression');
$form = $allowedClient->followRedirect()->selectButton('login')->form();
$form['_username'] = 'johannes';
$form['_password'] = 'test';
$allowedClient->submit($form);
$this->assertRedirect($allowedClient->getResponse(), '/protected-via-expression');
$this->assertAllowed($allowedClient, '/protected-via-expression');
}

private function assertAllowed($client, $path)
{
$client->request('GET', $path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ security:
- { path: ^/secured-by-one-ip$, ip: 10.10.10.10, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/secured-by-two-ips$, ips: [1.1.1.1, 2.2.2.2], roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/highly_protected_resource$, roles: IS_ADMIN }
- { path: ^/protected-via-expression$, allow_if: "(is_anonymous() and request.headers.get('user-agent') =~ '/Firefox/i') or has_role('ROLE_USER')" }
- { path: .*, roles: IS_AUTHENTICATED_FULLY }
3 changes: 2 additions & 1 deletion src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"symfony/twig-bundle": "~2.2",
"symfony/form": "~2.1",
"symfony/validator": "~2.2",
"symfony/yaml": "~2.0"
"symfony/yaml": "~2.0",
"symfony/expression-language": "~2.4"
},
"autoload": {
"psr-0": { "Symfony\\Bundle\\SecurityBundle\\": "" }
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<parameter key="twig.extension.form.class">Symfony\Bridge\Twig\Extension\FormExtension</parameter>
<parameter key="twig.extension.httpkernel.class">Symfony\Bridge\Twig\Extension\HttpKernelExtension</parameter>
<parameter key="twig.extension.debug.stopwatch.class">Symfony\Bridge\Twig\Extension\StopwatchExtension</parameter>
<parameter key="twig.extension.expression.class">Symfony\Bridge\Twig\Extension\ExpressionExtension</parameter>
<parameter key="twig.form.engine.class">Symfony\Bridge\Twig\Form\TwigRendererEngine</parameter>
<parameter key="twig.form.renderer.class">Symfony\Bridge\Twig\Form\TwigRenderer</parameter>
<parameter key="twig.translation.extractor.class">Symfony\Bridge\Twig\Translation\TwigExtractor</parameter>
Expand Down Expand Up @@ -92,6 +93,10 @@
<argument type="service" id="debug.stopwatch" on-invalid="ignore" />
</service>

<service id="twig.extension.expression" class="%twig.extension.expression.class%" public="false">
<tag name="twig.extension" />
</service>

<service id="twig.extension.httpkernel" class="%twig.extension.httpkernel.class%" public="false">
<argument type="service" id="fragment.handler" />
</service>
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
2.4.0
-----

* added support for expressions in service definitions
* added ContainerAwareTrait to add default container aware behavior to a class

2.2.0
Expand Down
Loading