Skip to content

[Security][SecurityBundle] Show user account status errors #58300

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
Jan 31, 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
6 changes: 6 additions & 0 deletions UPGRADE-7.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ FrameworkBundle
because its default value will change in version 8.0
* Deprecate the `--show-arguments` option of the `container:debug` command, as arguments are now always shown


SecurityBundle
--------------

* Deprecate the `security.hide_user_not_found` config option in favor of `security.expose_security_errors`

Serializer
----------

Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ CHANGELOG

* Add `Security::isGrantedForUser()` to test user authorization without relying on the session. For example, users not currently logged in, or while processing a message from a message queue
* Add encryption support to `OidcTokenHandler` (JWE)
* Add `expose_security_errors` config option to display `AccountStatusException`
* Deprecate the `security.hide_user_not_found` config option in favor of `security.expose_security_errors`

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Security\Http\Authentication\ExposeSecurityLevel;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;

Expand Down Expand Up @@ -54,13 +55,30 @@ public function getConfigTreeBuilder(): TreeBuilder
$rootNode = $tb->getRootNode();

$rootNode
->beforeNormalization()
->always()
->then(function ($v) {
if (isset($v['hide_user_not_found']) && !isset($v['expose_security_errors'])) {
$v['expose_security_errors'] = $v['hide_user_not_found'] ? ExposeSecurityLevel::None : ExposeSecurityLevel::All;
}

return $v;
})
->end()
->children()
->scalarNode('access_denied_url')->defaultNull()->example('/foo/error403')->end()
->enumNode('session_fixation_strategy')
->values([SessionAuthenticationStrategy::NONE, SessionAuthenticationStrategy::MIGRATE, SessionAuthenticationStrategy::INVALIDATE])
->defaultValue(SessionAuthenticationStrategy::MIGRATE)
->end()
->booleanNode('hide_user_not_found')->defaultTrue()->end()
->booleanNode('hide_user_not_found')
->setDeprecated('symfony/security-bundle', '7.3', 'The "%node%" option is deprecated and will be removed in 8.0. Use the "expose_security_errors" option instead.')
->end()
->enumNode('expose_security_errors')
->beforeNormalization()->ifString()->then(fn ($v) => ['value' => ExposeSecurityLevel::tryFrom($v)])->end()
->values(ExposeSecurityLevel::cases())
->defaultValue(ExposeSecurityLevel::None)
->end()
->booleanNode('erase_credentials')->defaultTrue()->end()
->arrayNode('access_decision_manager')
->addDefaultsIfNotSet()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\ExposeSecurityLevel;
use Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticatorManagerListener;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
Expand Down Expand Up @@ -154,7 +155,8 @@ public function load(array $configs, ContainerBuilder $container): void
));
}

$container->setParameter('security.authentication.hide_user_not_found', $config['hide_user_not_found']);
$container->setParameter('security.authentication.hide_user_not_found', ExposeSecurityLevel::All !== $config['expose_security_errors']);
$container->setParameter('.security.authentication.expose_security_errors', $config['expose_security_errors']);

if (class_exists(Application::class)) {
$loader->load('debug_console.php');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
<xsd:attribute name="strategy" type="access_decision_manager_strategy" />
<xsd:attribute name="service" type="xsd:string" />
<xsd:attribute name="strategy-service" type="xsd:string" />
<xsd:attribute name="expose-security-errors" type="access_decision_manager_expose_security_level" />
<xsd:attribute name="allow-if-all-abstain" type="xsd:boolean" />
<xsd:attribute name="allow-if-equal-granted-denied" type="xsd:boolean" />
</xsd:complexType>
Expand All @@ -68,6 +69,14 @@
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="access_decision_manager_expose_security_level">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="none" />
<xsd:enumeration value="account_status" />
<xsd:enumeration value="all" />
</xsd:restriction>
</xsd:simpleType>

<xsd:complexType name="password_hasher">
<xsd:sequence>
<xsd:element name="migrate-from" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
abstract_arg('provider key'),
service('logger')->nullOnInvalid(),
param('security.authentication.manager.erase_credentials'),
param('security.authentication.hide_user_not_found'),
param('.security.authentication.expose_security_errors'),
abstract_arg('required badges'),
])
->tag('monolog.logger', ['channel' => 'security'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@
namespace Symfony\Bundle\SecurityBundle\Tests\DependencyInjection;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectUserDeprecationMessageTrait;
use Symfony\Bundle\SecurityBundle\DependencyInjection\MainConfiguration;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AuthenticatorFactoryInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Security\Http\Authentication\ExposeSecurityLevel;

class MainConfigurationTest extends TestCase
{
use ExpectUserDeprecationMessageTrait;

/**
* The minimal, required config needed to not have any required validation
* issues.
Expand Down Expand Up @@ -228,4 +232,52 @@ public function testFirewalls()
$configuration = new MainConfiguration(['stub' => $factory], []);
$configuration->getConfigTreeBuilder();
}

/**
* @dataProvider provideHideUserNotFoundData
*/
public function testExposeSecurityErrors(array $config, ExposeSecurityLevel $expectedExposeSecurityErrors)
{
$config = array_merge(static::$minimalConfig, $config);

$processor = new Processor();
$configuration = new MainConfiguration([], []);
$processedConfig = $processor->processConfiguration($configuration, [$config]);

$this->assertEquals($expectedExposeSecurityErrors, $processedConfig['expose_security_errors']);
$this->assertArrayNotHasKey('hide_user_not_found', $processedConfig);
}

public static function provideHideUserNotFoundData(): iterable
{
yield [[], ExposeSecurityLevel::None];
yield [['expose_security_errors' => ExposeSecurityLevel::None], ExposeSecurityLevel::None];
yield [['expose_security_errors' => ExposeSecurityLevel::AccountStatus], ExposeSecurityLevel::AccountStatus];
yield [['expose_security_errors' => ExposeSecurityLevel::All], ExposeSecurityLevel::All];
}

/**
* @dataProvider provideHideUserNotFoundLegacyData
*
* @group legacy
*/
public function testExposeSecurityErrorsWithLegacyConfig(array $config, ExposeSecurityLevel $expectedExposeSecurityErrors, ?bool $expectedHideUserNotFound)
{
$this->expectUserDeprecationMessage('Since symfony/security-bundle 7.3: The "hide_user_not_found" option is deprecated and will be removed in 8.0. Use the "expose_security_errors" option instead.');

$config = array_merge(static::$minimalConfig, $config);

$processor = new Processor();
$configuration = new MainConfiguration([], []);
$processedConfig = $processor->processConfiguration($configuration, [$config]);

$this->assertEquals($expectedExposeSecurityErrors, $processedConfig['expose_security_errors']);
$this->assertEquals($expectedHideUserNotFound, $processedConfig['hide_user_not_found']);
}

public static function provideHideUserNotFoundLegacyData(): iterable
{
yield [['hide_user_not_found' => true], ExposeSecurityLevel::None, true];
yield [['hide_user_not_found' => false], ExposeSecurityLevel::All, false];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
*/
class AuthenticatorManager implements AuthenticatorManagerInterface, UserAuthenticatorInterface
{
private ExposeSecurityLevel $exposeSecurityErrors;

/**
* @param iterable<mixed, AuthenticatorInterface> $authenticators
*/
Expand All @@ -56,9 +58,17 @@ public function __construct(
private string $firewallName,
private ?LoggerInterface $logger = null,
private bool $eraseCredentials = true,
private bool $hideUserNotFoundExceptions = true,
ExposeSecurityLevel|bool $exposeSecurityErrors = ExposeSecurityLevel::None,
private array $requiredBadges = [],
) {
if (\is_bool($exposeSecurityErrors)) {
trigger_deprecation('symfony/security-http', '7.3', 'Passing a boolean as "exposeSecurityErrors" parameter is deprecated, use %s value instead.', ExposeSecurityLevel::class);

// The old parameter had an inverted meaning ($hideUserNotFoundExceptions), for that reason the current name does not reflect the behavior
$exposeSecurityErrors = $exposeSecurityErrors ? ExposeSecurityLevel::None : ExposeSecurityLevel::All;
}

$this->exposeSecurityErrors = $exposeSecurityErrors;
}

/**
Expand Down Expand Up @@ -250,7 +260,7 @@ private function handleAuthenticationFailure(AuthenticationException $authentica

// Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
// to prevent user enumeration via response content comparison
if ($this->hideUserNotFoundExceptions && ($authenticationException instanceof UserNotFoundException || ($authenticationException instanceof AccountStatusException && !$authenticationException instanceof CustomUserMessageAccountStatusException))) {
if ($this->isSensitiveException($authenticationException)) {
$authenticationException = new BadCredentialsException('Bad credentials.', 0, $authenticationException);
}

Expand All @@ -264,4 +274,17 @@ private function handleAuthenticationFailure(AuthenticationException $authentica
// returning null is ok, it means they want the request to continue
return $loginFailureEvent->getResponse();
}

private function isSensitiveException(AuthenticationException $exception): bool
{
if (ExposeSecurityLevel::All !== $this->exposeSecurityErrors && $exception instanceof UserNotFoundException) {
return true;
}

if (ExposeSecurityLevel::None === $this->exposeSecurityErrors && $exception instanceof AccountStatusException && !$exception instanceof CustomUserMessageAccountStatusException) {
return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Component\Security\Http\Authentication;

/**
* @author Christian Gripp <mail@core23.de>
*/
enum ExposeSecurityLevel: string
{
case None = 'none';
case AccountStatus = 'account_status';
case All = 'all';
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add encryption support to `OidcTokenHandler` (JWE)
* Replace `$hideAccountStatusExceptions` argument with `$exposeSecurityErrors` in `AuthenticatorManager` constructor

7.2
---
Expand Down
Loading
Loading