vendor/symfony/security-bundle/DependencyInjection/MainConfiguration.php line 54

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\SecurityBundle\DependencyInjection;
  11. use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory;
  12. use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
  13. use Symfony\Component\Config\Definition\Builder\TreeBuilder;
  14. use Symfony\Component\Config\Definition\ConfigurationInterface;
  15. use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
  16. use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
  17. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  18. use Symfony\Component\Security\Http\Event\LogoutEvent;
  19. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;
  20. /**
  21.  * SecurityExtension configuration structure.
  22.  *
  23.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  24.  */
  25. class MainConfiguration implements ConfigurationInterface
  26. {
  27.     private $factories;
  28.     private $userProviderFactories;
  29.     public function __construct(array $factories, array $userProviderFactories)
  30.     {
  31.         $this->factories $factories;
  32.         $this->userProviderFactories $userProviderFactories;
  33.     }
  34.     /**
  35.      * Generates the configuration tree builder.
  36.      *
  37.      * @return TreeBuilder The tree builder
  38.      */
  39.     public function getConfigTreeBuilder()
  40.     {
  41.         $tb = new TreeBuilder('security');
  42.         $rootNode $tb->getRootNode();
  43.         $rootNode
  44.             ->beforeNormalization()
  45.                 ->ifTrue(function ($v) {
  46.                     if ($v['encoders'] ?? false) {
  47.                         trigger_deprecation('symfony/security-bundle''5.3''The child node "encoders" at path "security" is deprecated, use "password_hashers" instead.');
  48.                         return true;
  49.                     }
  50.                     return $v['password_hashers'] ?? false;
  51.                 })
  52.                 ->then(function ($v) {
  53.                     $v['password_hashers'] = array_merge($v['password_hashers'] ?? [], $v['encoders'] ?? []);
  54.                     $v['encoders'] = $v['password_hashers'];
  55.                     return $v;
  56.                 })
  57.             ->end()
  58.             ->children()
  59.                 ->scalarNode('access_denied_url')->defaultNull()->example('/foo/error403')->end()
  60.                 ->enumNode('session_fixation_strategy')
  61.                     ->values([SessionAuthenticationStrategy::NONESessionAuthenticationStrategy::MIGRATESessionAuthenticationStrategy::INVALIDATE])
  62.                     ->defaultValue(SessionAuthenticationStrategy::MIGRATE)
  63.                 ->end()
  64.                 ->booleanNode('hide_user_not_found')->defaultTrue()->end()
  65.                 ->booleanNode('always_authenticate_before_granting')->defaultFalse()->end()
  66.                 ->booleanNode('erase_credentials')->defaultTrue()->end()
  67.                 ->booleanNode('enable_authenticator_manager')->defaultFalse()->info('Enables the new Symfony Security system based on Authenticators, all used authenticators must support this before enabling this.')->end()
  68.                 ->arrayNode('access_decision_manager')
  69.                     ->addDefaultsIfNotSet()
  70.                     ->children()
  71.                         ->enumNode('strategy')
  72.                             ->values($this->getAccessDecisionStrategies())
  73.                         ->end()
  74.                         ->scalarNode('service')->end()
  75.                         ->booleanNode('allow_if_all_abstain')->defaultFalse()->end()
  76.                         ->booleanNode('allow_if_equal_granted_denied')->defaultTrue()->end()
  77.                     ->end()
  78.                     ->validate()
  79.                         ->ifTrue(function ($v) { return isset($v['strategy']) && isset($v['service']); })
  80.                         ->thenInvalid('"strategy" and "service" cannot be used together.')
  81.                     ->end()
  82.                 ->end()
  83.             ->end()
  84.         ;
  85.         $this->addEncodersSection($rootNode);
  86.         $this->addPasswordHashersSection($rootNode);
  87.         $this->addProvidersSection($rootNode);
  88.         $this->addFirewallsSection($rootNode$this->factories);
  89.         $this->addAccessControlSection($rootNode);
  90.         $this->addRoleHierarchySection($rootNode);
  91.         return $tb;
  92.     }
  93.     private function addRoleHierarchySection(ArrayNodeDefinition $rootNode)
  94.     {
  95.         $rootNode
  96.             ->fixXmlConfig('role''role_hierarchy')
  97.             ->children()
  98.                 ->arrayNode('role_hierarchy')
  99.                     ->useAttributeAsKey('id')
  100.                     ->prototype('array')
  101.                         ->performNoDeepMerging()
  102.                         ->beforeNormalization()->ifString()->then(function ($v) { return ['value' => $v]; })->end()
  103.                         ->beforeNormalization()
  104.                             ->ifTrue(function ($v) { return \is_array($v) && isset($v['value']); })
  105.                             ->then(function ($v) { return preg_split('/\s*,\s*/'$v['value']); })
  106.                         ->end()
  107.                         ->prototype('scalar')->end()
  108.                     ->end()
  109.                 ->end()
  110.             ->end()
  111.         ;
  112.     }
  113.     private function addAccessControlSection(ArrayNodeDefinition $rootNode)
  114.     {
  115.         $rootNode
  116.             ->fixXmlConfig('rule''access_control')
  117.             ->children()
  118.                 ->arrayNode('access_control')
  119.                     ->cannotBeOverwritten()
  120.                     ->prototype('array')
  121.                         ->fixXmlConfig('ip')
  122.                         ->fixXmlConfig('method')
  123.                         ->children()
  124.                             ->scalarNode('requires_channel')->defaultNull()->end()
  125.                             ->scalarNode('path')
  126.                                 ->defaultNull()
  127.                                 ->info('use the urldecoded format')
  128.                                 ->example('^/path to resource/')
  129.                             ->end()
  130.                             ->scalarNode('host')->defaultNull()->end()
  131.                             ->integerNode('port')->defaultNull()->end()
  132.                             ->arrayNode('ips')
  133.                                 ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end()
  134.                                 ->prototype('scalar')->end()
  135.                             ->end()
  136.                             ->arrayNode('methods')
  137.                                 ->beforeNormalization()->ifString()->then(function ($v) { return preg_split('/\s*,\s*/'$v); })->end()
  138.                                 ->prototype('scalar')->end()
  139.                             ->end()
  140.                             ->scalarNode('allow_if')->defaultNull()->end()
  141.                         ->end()
  142.                         ->fixXmlConfig('role')
  143.                         ->children()
  144.                             ->arrayNode('roles')
  145.                                 ->beforeNormalization()->ifString()->then(function ($v) { return preg_split('/\s*,\s*/'$v); })->end()
  146.                                 ->prototype('scalar')->end()
  147.                             ->end()
  148.                         ->end()
  149.                     ->end()
  150.                 ->end()
  151.             ->end()
  152.         ;
  153.     }
  154.     private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $factories)
  155.     {
  156.         $firewallNodeBuilder $rootNode
  157.             ->fixXmlConfig('firewall')
  158.             ->children()
  159.                 ->arrayNode('firewalls')
  160.                     ->isRequired()
  161.                     ->requiresAtLeastOneElement()
  162.                     ->disallowNewKeysInSubsequentConfigs()
  163.                     ->useAttributeAsKey('name')
  164.                     ->prototype('array')
  165.                         ->fixXmlConfig('required_badge')
  166.                         ->children()
  167.         ;
  168.         $firewallNodeBuilder
  169.             ->scalarNode('pattern')->end()
  170.             ->scalarNode('host')->end()
  171.             ->arrayNode('methods')
  172.                 ->beforeNormalization()->ifString()->then(function ($v) { return preg_split('/\s*,\s*/'$v); })->end()
  173.                 ->prototype('scalar')->end()
  174.             ->end()
  175.             ->booleanNode('security')->defaultTrue()->end()
  176.             ->scalarNode('user_checker')
  177.                 ->defaultValue('security.user_checker')
  178.                 ->treatNullLike('security.user_checker')
  179.                 ->info('The UserChecker to use when authenticating users in this firewall.')
  180.             ->end()
  181.             ->scalarNode('request_matcher')->end()
  182.             ->scalarNode('access_denied_url')->end()
  183.             ->scalarNode('access_denied_handler')->end()
  184.             ->scalarNode('entry_point')
  185.                 ->info(sprintf('An enabled authenticator name or a service id that implements "%s"'AuthenticationEntryPointInterface::class))
  186.             ->end()
  187.             ->scalarNode('provider')->end()
  188.             ->booleanNode('stateless')->defaultFalse()->end()
  189.             ->booleanNode('lazy')->defaultFalse()->end()
  190.             ->scalarNode('context')->cannotBeEmpty()->end()
  191.             ->arrayNode('logout')
  192.                 ->treatTrueLike([])
  193.                 ->canBeUnset()
  194.                 ->children()
  195.                     ->scalarNode('csrf_parameter')->defaultValue('_csrf_token')->end()
  196.                     ->scalarNode('csrf_token_generator')->cannotBeEmpty()->end()
  197.                     ->scalarNode('csrf_token_id')->defaultValue('logout')->end()
  198.                     ->scalarNode('path')->defaultValue('/logout')->end()
  199.                     ->scalarNode('target')->defaultValue('/')->end()
  200.                     ->scalarNode('success_handler')->setDeprecated('symfony/security-bundle''5.1'sprintf('The "%%node%%" at path "%%path%%" is deprecated, register a listener on the "%s" event instead.'LogoutEvent::class))->end()
  201.                     ->booleanNode('invalidate_session')->defaultTrue()->end()
  202.                 ->end()
  203.                 ->fixXmlConfig('delete_cookie')
  204.                 ->children()
  205.                     ->arrayNode('delete_cookies')
  206.                         ->normalizeKeys(false)
  207.                         ->beforeNormalization()
  208.                             ->ifTrue(function ($v) { return \is_array($v) && \is_int(key($v)); })
  209.                             ->then(function ($v) { return array_map(function ($v) { return ['name' => $v]; }, $v); })
  210.                         ->end()
  211.                         ->useAttributeAsKey('name')
  212.                         ->prototype('array')
  213.                             ->children()
  214.                                 ->scalarNode('path')->defaultNull()->end()
  215.                                 ->scalarNode('domain')->defaultNull()->end()
  216.                                 ->scalarNode('secure')->defaultFalse()->end()
  217.                                 ->scalarNode('samesite')->defaultNull()->end()
  218.                             ->end()
  219.                         ->end()
  220.                     ->end()
  221.                 ->end()
  222.                 ->fixXmlConfig('handler')
  223.                 ->children()
  224.                     ->arrayNode('handlers')
  225.                         ->prototype('scalar')->setDeprecated('symfony/security-bundle''5.1'sprintf('The "%%node%%" at path "%%path%%" is deprecated, register a listener on the "%s" event instead.'LogoutEvent::class))->end()
  226.                     ->end()
  227.                 ->end()
  228.             ->end()
  229.             ->arrayNode('switch_user')
  230.                 ->canBeUnset()
  231.                 ->children()
  232.                     ->scalarNode('provider')->end()
  233.                     ->scalarNode('parameter')->defaultValue('_switch_user')->end()
  234.                     ->scalarNode('role')->defaultValue('ROLE_ALLOWED_TO_SWITCH')->end()
  235.                 ->end()
  236.             ->end()
  237.             ->arrayNode('required_badges')
  238.                 ->info('A list of badges that must be present on the authenticated passport.')
  239.                 ->validate()
  240.                     ->always()
  241.                     ->then(function ($requiredBadges) {
  242.                         return array_map(function ($requiredBadge) {
  243.                             if (class_exists($requiredBadge)) {
  244.                                 return $requiredBadge;
  245.                             }
  246.                             if (false === strpos($requiredBadge'\\')) {
  247.                                 $fqcn 'Symfony\Component\Security\Http\Authenticator\Passport\Badge\\'.$requiredBadge;
  248.                                 if (class_exists($fqcn)) {
  249.                                     return $fqcn;
  250.                                 }
  251.                             }
  252.                             throw new InvalidConfigurationException(sprintf('Undefined security Badge class "%s" set in "security.firewall.required_badges".'$requiredBadge));
  253.                         }, $requiredBadges);
  254.                     })
  255.                 ->end()
  256.                 ->prototype('scalar')->end()
  257.             ->end()
  258.         ;
  259.         $abstractFactoryKeys = [];
  260.         foreach ($factories as $factoriesAtPosition) {
  261.             foreach ($factoriesAtPosition as $factory) {
  262.                 $name str_replace('-''_'$factory->getKey());
  263.                 $factoryNode $firewallNodeBuilder->arrayNode($name)
  264.                     ->canBeUnset()
  265.                 ;
  266.                 if ($factory instanceof AbstractFactory) {
  267.                     $abstractFactoryKeys[] = $name;
  268.                 }
  269.                 $factory->addConfiguration($factoryNode);
  270.             }
  271.         }
  272.         // check for unreachable check paths
  273.         $firewallNodeBuilder
  274.             ->end()
  275.             ->validate()
  276.                 ->ifTrue(function ($v) {
  277.                     return true === $v['security'] && isset($v['pattern']) && !isset($v['request_matcher']);
  278.                 })
  279.                 ->then(function ($firewall) use ($abstractFactoryKeys) {
  280.                     foreach ($abstractFactoryKeys as $k) {
  281.                         if (!isset($firewall[$k]['check_path'])) {
  282.                             continue;
  283.                         }
  284.                         if (str_contains($firewall[$k]['check_path'], '/') && !preg_match('#'.$firewall['pattern'].'#'$firewall[$k]['check_path'])) {
  285.                             throw new \LogicException(sprintf('The check_path "%s" for login method "%s" is not matched by the firewall pattern "%s".'$firewall[$k]['check_path'], $k$firewall['pattern']));
  286.                         }
  287.                     }
  288.                     return $firewall;
  289.                 })
  290.             ->end()
  291.         ;
  292.     }
  293.     private function addProvidersSection(ArrayNodeDefinition $rootNode)
  294.     {
  295.         $providerNodeBuilder $rootNode
  296.             ->fixXmlConfig('provider')
  297.             ->children()
  298.                 ->arrayNode('providers')
  299.                     ->example([
  300.                         'my_memory_provider' => [
  301.                             'memory' => [
  302.                                 'users' => [
  303.                                     'foo' => ['password' => 'foo''roles' => 'ROLE_USER'],
  304.                                     'bar' => ['password' => 'bar''roles' => '[ROLE_USER, ROLE_ADMIN]'],
  305.                                 ],
  306.                             ],
  307.                         ],
  308.                         'my_entity_provider' => ['entity' => ['class' => 'SecurityBundle:User''property' => 'username']],
  309.                     ])
  310.                     ->requiresAtLeastOneElement()
  311.                     ->useAttributeAsKey('name')
  312.                     ->prototype('array')
  313.         ;
  314.         $providerNodeBuilder
  315.             ->children()
  316.                 ->scalarNode('id')->end()
  317.                 ->arrayNode('chain')
  318.                     ->fixXmlConfig('provider')
  319.                     ->children()
  320.                         ->arrayNode('providers')
  321.                             ->beforeNormalization()
  322.                                 ->ifString()
  323.                                 ->then(function ($v) { return preg_split('/\s*,\s*/'$v); })
  324.                             ->end()
  325.                             ->prototype('scalar')->end()
  326.                         ->end()
  327.                     ->end()
  328.                 ->end()
  329.             ->end()
  330.         ;
  331.         foreach ($this->userProviderFactories as $factory) {
  332.             $name str_replace('-''_'$factory->getKey());
  333.             $factoryNode $providerNodeBuilder->children()->arrayNode($name)->canBeUnset();
  334.             $factory->addConfiguration($factoryNode);
  335.         }
  336.         $providerNodeBuilder
  337.             ->validate()
  338.                 ->ifTrue(function ($v) { return \count($v) > 1; })
  339.                 ->thenInvalid('You cannot set multiple provider types for the same provider')
  340.             ->end()
  341.             ->validate()
  342.                 ->ifTrue(function ($v) { return === \count($v); })
  343.                 ->thenInvalid('You must set a provider definition for the provider.')
  344.             ->end()
  345.         ;
  346.     }
  347.     private function addEncodersSection(ArrayNodeDefinition $rootNode)
  348.     {
  349.         $rootNode
  350.             ->fixXmlConfig('encoder')
  351.             ->children()
  352.                 ->arrayNode('encoders')
  353.                     ->example([
  354.                         'App\Entity\User1' => 'auto',
  355.                         'App\Entity\User2' => [
  356.                             'algorithm' => 'auto',
  357.                             'time_cost' => 8,
  358.                             'cost' => 13,
  359.                         ],
  360.                     ])
  361.                     ->requiresAtLeastOneElement()
  362.                     ->useAttributeAsKey('class')
  363.                     ->prototype('array')
  364.                         ->canBeUnset()
  365.                         ->performNoDeepMerging()
  366.                         ->beforeNormalization()->ifString()->then(function ($v) { return ['algorithm' => $v]; })->end()
  367.                         ->children()
  368.                             ->scalarNode('algorithm')
  369.                                 ->cannotBeEmpty()
  370.                                 ->validate()
  371.                                     ->ifTrue(function ($v) { return !\is_string($v); })
  372.                                     ->thenInvalid('You must provide a string value.')
  373.                                 ->end()
  374.                             ->end()
  375.                             ->arrayNode('migrate_from')
  376.                                 ->prototype('scalar')->end()
  377.                                 ->beforeNormalization()->castToArray()->end()
  378.                             ->end()
  379.                             ->scalarNode('hash_algorithm')->info('Name of hashing algorithm for PBKDF2 (i.e. sha256, sha512, etc..) See hash_algos() for a list of supported algorithms.')->defaultValue('sha512')->end()
  380.                             ->scalarNode('key_length')->defaultValue(40)->end()
  381.                             ->booleanNode('ignore_case')->defaultFalse()->end()
  382.                             ->booleanNode('encode_as_base64')->defaultTrue()->end()
  383.                             ->scalarNode('iterations')->defaultValue(5000)->end()
  384.                             ->integerNode('cost')
  385.                                 ->min(4)
  386.                                 ->max(31)
  387.                                 ->defaultNull()
  388.                             ->end()
  389.                             ->scalarNode('memory_cost')->defaultNull()->end()
  390.                             ->scalarNode('time_cost')->defaultNull()->end()
  391.                             ->scalarNode('id')->end()
  392.                         ->end()
  393.                     ->end()
  394.                 ->end()
  395.             ->end()
  396.         ;
  397.     }
  398.     private function addPasswordHashersSection(ArrayNodeDefinition $rootNode)
  399.     {
  400.         $rootNode
  401.             ->fixXmlConfig('password_hasher')
  402.             ->children()
  403.                 ->arrayNode('password_hashers')
  404.                     ->example([
  405.                         'App\Entity\User1' => 'auto',
  406.                         'App\Entity\User2' => [
  407.                             'algorithm' => 'auto',
  408.                             'time_cost' => 8,
  409.                             'cost' => 13,
  410.                         ],
  411.                     ])
  412.                     ->requiresAtLeastOneElement()
  413.                     ->useAttributeAsKey('class')
  414.                     ->prototype('array')
  415.                         ->canBeUnset()
  416.                         ->performNoDeepMerging()
  417.                         ->beforeNormalization()->ifString()->then(function ($v) { return ['algorithm' => $v]; })->end()
  418.                         ->children()
  419.                             ->scalarNode('algorithm')
  420.                                 ->cannotBeEmpty()
  421.                                 ->validate()
  422.                                     ->ifTrue(function ($v) { return !\is_string($v); })
  423.                                     ->thenInvalid('You must provide a string value.')
  424.                                 ->end()
  425.                             ->end()
  426.                             ->arrayNode('migrate_from')
  427.                                 ->prototype('scalar')->end()
  428.                                 ->beforeNormalization()->castToArray()->end()
  429.                             ->end()
  430.                             ->scalarNode('hash_algorithm')->info('Name of hashing algorithm for PBKDF2 (i.e. sha256, sha512, etc..) See hash_algos() for a list of supported algorithms.')->defaultValue('sha512')->end()
  431.                             ->scalarNode('key_length')->defaultValue(40)->end()
  432.                             ->booleanNode('ignore_case')->defaultFalse()->end()
  433.                             ->booleanNode('encode_as_base64')->defaultTrue()->end()
  434.                             ->scalarNode('iterations')->defaultValue(5000)->end()
  435.                             ->integerNode('cost')
  436.                                 ->min(4)
  437.                                 ->max(31)
  438.                                 ->defaultNull()
  439.                             ->end()
  440.                             ->scalarNode('memory_cost')->defaultNull()->end()
  441.                             ->scalarNode('time_cost')->defaultNull()->end()
  442.                             ->scalarNode('id')->end()
  443.                         ->end()
  444.                     ->end()
  445.                 ->end()
  446.         ->end();
  447.     }
  448.     private function getAccessDecisionStrategies()
  449.     {
  450.         $strategies = [
  451.             AccessDecisionManager::STRATEGY_AFFIRMATIVE,
  452.             AccessDecisionManager::STRATEGY_CONSENSUS,
  453.             AccessDecisionManager::STRATEGY_UNANIMOUS,
  454.         ];
  455.         if (\defined(AccessDecisionManager::class.'::STRATEGY_PRIORITY')) {
  456.             $strategies[] = AccessDecisionManager::STRATEGY_PRIORITY;
  457.         }
  458.         return $strategies;
  459.     }
  460. }