Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Form][FrameworkBundle] Use auto-configuration to make the default CSRF token id apply only to the app; not to bundles #59728

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 1 commit into from
Feb 10, 2025
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
[Form][FrameworkBundle] Use auto-configuration to make the default CS…
…RF token id apply only to the app; not to bundles
  • Loading branch information
nicolas-grekas committed Feb 7, 2025
commit bf1e312250df72d7a68e1caed7ecfaff75045700
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ public function load(array $configs, ContainerBuilder $container): void
$container->registerForAutoconfiguration(DataCollectorInterface::class)
->addTag('data_collector');
$container->registerForAutoconfiguration(FormTypeInterface::class)
->addTag('form.type');
->addTag('form.type', ['csrf_token_id' => '%.form.type_extension.csrf.token_id%']);
$container->registerForAutoconfiguration(FormTypeGuesserInterface::class)
->addTag('form.type_guesser');
$container->registerForAutoconfiguration(FormTypeExtensionInterface::class)
Expand Down Expand Up @@ -777,9 +777,7 @@ private function registerFormConfiguration(array $config, ContainerBuilder $cont
$container->setParameter('form.type_extension.csrf.enabled', true);
$container->setParameter('form.type_extension.csrf.field_name', $config['form']['csrf_protection']['field_name']);
$container->setParameter('form.type_extension.csrf.field_attr', $config['form']['csrf_protection']['field_attr']);

$container->getDefinition('form.type_extension.csrf')
->replaceArgument(7, $config['form']['csrf_protection']['token_id']);
$container->setParameter('.form.type_extension.csrf.token_id', $config['form']['csrf_protection']['token_id']);
} else {
$container->setParameter('form.type_extension.csrf.enabled', false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
param('validator.translation_domain'),
service('form.server_params'),
param('form.type_extension.csrf.field_attr'),
abstract_arg('framework.form.csrf_protection.token_id'),
param('.form.type_extension.csrf.token_id'),
])
->tag('form.type_extension')
;
Expand Down
13 changes: 13 additions & 0 deletions 13 src/Symfony/Component/Form/DependencyInjection/FormPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,18 @@ private function processFormTypes(ContainerBuilder $container): Reference
// Get service locator argument
$servicesMap = [];
$namespaces = ['Symfony\Component\Form\Extension\Core\Type' => true];
$csrfTokenIds = [];

// Builds an array with fully-qualified type class names as keys and service IDs as values
foreach ($container->findTaggedServiceIds('form.type', true) as $serviceId => $tag) {
// Add form type service to the service locator
$serviceDefinition = $container->getDefinition($serviceId);
$servicesMap[$formType = $serviceDefinition->getClass()] = new Reference($serviceId);
$namespaces[substr($formType, 0, strrpos($formType, '\\'))] = true;

if (isset($tag[0]['csrf_token_id'])) {
$csrfTokenIds[$formType] = $tag[0]['csrf_token_id'];
}
}

if ($container->hasDefinition('console.command.form_debug')) {
Expand All @@ -62,6 +67,14 @@ private function processFormTypes(ContainerBuilder $container): Reference
$commandDefinition->setArgument(2, array_keys($servicesMap));
}

if ($csrfTokenIds && $container->hasDefinition('form.type_extension.csrf')) {
$csrfExtension = $container->getDefinition('form.type_extension.csrf');

if (8 <= \count($csrfExtension->getArguments())) {
$csrfExtension->replaceArgument(7, $csrfTokenIds);
}
}

return ServiceLocatorTagPass::register($container, $servicesMap);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(
private ?string $translationDomain = null,
private ?ServerParams $serverParams = null,
private array $fieldAttr = [],
private ?string $defaultTokenId = null,
private string|array|null $defaultTokenId = null,
) {
}

Expand All @@ -50,11 +50,17 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
return;
}

$csrfTokenId = $options['csrf_token_id']
?: $this->defaultTokenId[$builder->getType()->getInnerType()::class]
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
?? $builder->getName()
?: $builder->getType()->getInnerType()::class;
$builder->setAttribute('csrf_token_id', $csrfTokenId);

$builder
->addEventSubscriber(new CsrfValidationListener(
$options['csrf_field_name'],
$options['csrf_token_manager'],
$options['csrf_token_id'] ?: ($builder->getName() ?: $builder->getType()->getInnerType()::class),
$csrfTokenId,
$options['csrf_message'],
$this->translator,
$this->translationDomain,
Expand All @@ -70,7 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options):
{
if ($options['csrf_protection'] && !$view->parent && $options['compound']) {
$factory = $form->getConfig()->getFormFactory();
$tokenId = $options['csrf_token_id'] ?: ($form->getName() ?: $form->getConfig()->getType()->getInnerType()::class);
$tokenId = $form->getConfig()->getAttribute('csrf_token_id');
$data = (string) $options['csrf_token_manager']->getToken($tokenId);

$csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [
Expand All @@ -85,9 +91,11 @@ public function finishView(FormView $view, FormInterface $form, array $options):

public function configureOptions(OptionsResolver $resolver): void
{
if ($defaultTokenId = $this->defaultTokenId) {
if (\is_string($defaultTokenId = $this->defaultTokenId) && $defaultTokenId) {
$defaultTokenManager = $this->defaultTokenManager;
$defaultTokenId = static fn (Options $options) => $options['csrf_token_manager'] === $defaultTokenManager ? $defaultTokenId : null;
} else {
$defaultTokenId = null;
}

$resolver->setDefaults([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Command\DebugCommand;
use Symfony\Component\Form\DependencyInjection\FormPass;
use Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension;
use Symfony\Component\Form\FormRegistry;

/**
Expand Down Expand Up @@ -95,6 +96,25 @@ public function testAddTaggedTypesToDebugCommand()
);
}

public function testAddTaggedTypesToCsrfTypeExtension()
{
$container = $this->createContainerBuilder();

$container->register('form.registry', FormRegistry::class);
$container->register('form.type_extension.csrf', FormTypeCsrfExtension::class)
->setArguments([null, true, '_token', null, 'validator.translation_domain', null, [], null])
->setPublic(true);

$container->setDefinition('form.extension', $this->createExtensionDefinition());
$container->register('my.type1', __CLASS__.'_Type1')->addTag('form.type', ['csrf_token_id' => 'the_token_id']);
$container->register('my.type2', __CLASS__.'_Type2')->addTag('form.type');

$container->compile();

$csrfDefinition = $container->getDefinition('form.type_extension.csrf');
$this->assertSame([__CLASS__.'_Type1' => 'the_token_id'], $csrfDefinition->getArgument(7));
}

/**
* @dataProvider addTaggedTypeExtensionsDataProvider
*/
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.