1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
|
<?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\Bundle\SecurityBundle\Tests\Functional;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Bundle\SecurityBundle\Security\FirewallConfig;
use Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\SecuredPageBundle\Security\Core\User\ArrayUserProvider;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityTest extends AbstractWebTestCase
{
public function testServiceIsFunctional()
{
$kernel = self::createKernel(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml']);
$kernel->boot();
$container = $kernel->getContainer();
// put a token into the storage so the final calls can function
$user = new InMemoryUser('foo', 'pass');
$token = new UsernamePasswordToken($user, 'provider', ['ROLE_USER']);
$container->get('functional.test.security.token_storage')->setToken($token);
$security = $container->get('functional_test.security.helper');
$this->assertTrue($security->isGranted('ROLE_USER'));
$this->assertSame($token, $security->getToken());
$request = new Request();
$request->server->set('REQUEST_URI', '/main/foo');
$this->assertInstanceOf(FirewallConfig::class, $firewallConfig = $security->getFirewallConfig($request));
$this->assertSame('main', $firewallConfig->getName());
}
/**
* @dataProvider userWillBeMarkedAsChangedIfRolesHasChangedProvider
*/
public function testUserWillBeMarkedAsChangedIfRolesHasChanged(UserInterface $userWithAdminRole, UserInterface $userWithoutAdminRole)
{
$client = $this->createClient(['test_case' => 'AbstractTokenCompareRoles', 'root_config' => 'config.yml']);
$client->disableReboot();
/** @var ArrayUserProvider $userProvider */
$userProvider = static::$kernel->getContainer()->get('security.user.provider.array');
$userProvider->addUser($userWithAdminRole);
$client->request('POST', '/login', [
'_username' => 'user1',
'_password' => 'test',
]);
// user1 has ROLE_ADMIN and can visit secure page
$client->request('GET', '/admin');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
// updating user provider with same user but revoked ROLE_ADMIN from user1
$userProvider->setUser('user1', $userWithoutAdminRole);
// user1 has lost ROLE_ADMIN and MUST be redirected away from secure page
$client->request('GET', '/admin');
$this->assertEquals(302, $client->getResponse()->getStatusCode());
}
public static function userWillBeMarkedAsChangedIfRolesHasChangedProvider(): array
{
return [
[
new InMemoryUser('user1', 'test', ['ROLE_ADMIN']),
new InMemoryUser('user1', 'test', ['ROLE_USER']),
],
[
new UserWithoutEquatable('user1', 'test', ['ROLE_ADMIN']),
new UserWithoutEquatable('user1', 'test', ['ROLE_USER']),
],
];
}
/**
* @testWith ["form_login"]
* ["Symfony\\Bundle\\SecurityBundle\\Tests\\Functional\\Bundle\\AuthenticatorBundle\\ApiAuthenticator"]
*/
public function testLogin(string $authenticator)
{
$client = $this->createClient(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml', 'debug' > true]);
static::getContainer()->get(ForceLoginController::class)->authenticator = $authenticator;
$client->request('GET', '/main/force-login');
$response = $client->getResponse();
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(['message' => 'Welcome @chalasr!'], json_decode($response->getContent(), true));
$this->assertSame('chalasr', static::getContainer()->get('security.helper')->getUser()->getUserIdentifier());
}
public function testLogout()
{
$client = $this->createClient(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml', 'debug' => true]);
$client->loginUser(new InMemoryUser('chalasr', 'the-password', ['ROLE_FOO']), 'main');
$client->request('GET', '/main/force-logout');
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$this->assertNull(static::getContainer()->get('security.helper')->getUser());
$this->assertSame(['message' => 'Logout successful'], json_decode($response->getContent(), true));
}
public function testLogoutWithCsrf()
{
$client = $this->createClient(['test_case' => 'SecurityHelper', 'root_config' => 'config_logout_csrf.yml', 'debug' => true]);
$client->loginUser(new InMemoryUser('chalasr', 'the-password', ['ROLE_FOO']), 'main');
// put a csrf token in the storage
/** @var EventDispatcherInterface $eventDispatcher */
$eventDispatcher = static::getContainer()->get(EventDispatcherInterface::class);
$setCsrfToken = function (RequestEvent $event) {
static::getContainer()->get('security.csrf.token_storage')->setToken('logout', 'bar');
$event->setResponse(new Response(''));
};
$eventDispatcher->addListener(KernelEvents::REQUEST, $setCsrfToken);
try {
$client->request('GET', '/'.uniqid('', true));
} finally {
$eventDispatcher->removeListener(KernelEvents::REQUEST, $setCsrfToken);
}
static::getContainer()->get(LogoutController::class)->checkCsrf = true;
$client->request('GET', '/main/force-logout', ['_csrf_token' => 'bar']);
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$this->assertNull(static::getContainer()->get('security.helper')->getUser());
$this->assertSame(['message' => 'Logout successful'], json_decode($response->getContent(), true));
}
public function testLogoutBypassCsrf()
{
$client = $this->createClient(['test_case' => 'SecurityHelper', 'root_config' => 'config_logout_csrf.yml']);
$client->loginUser(new InMemoryUser('chalasr', 'the-password', ['ROLE_FOO']), 'main');
$client->request('GET', '/main/force-logout');
$response = $client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$this->assertNull(static::getContainer()->get('security.helper')->getUser());
$this->assertSame(['message' => 'Logout successful'], json_decode($response->getContent(), true));
}
}
final class UserWithoutEquatable implements UserInterface, PasswordAuthenticatedUserInterface
{
private ?string $username;
private ?string $password;
private bool $enabled;
private bool $accountNonExpired;
private bool $credentialsNonExpired;
private bool $accountNonLocked;
private array $roles;
public function __construct(?string $username, ?string $password, array $roles = [], bool $enabled = true, bool $userNonExpired = true, bool $credentialsNonExpired = true, bool $userNonLocked = true)
{
if ('' === $username || null === $username) {
throw new \InvalidArgumentException('The username cannot be empty.');
}
$this->username = $username;
$this->password = $password;
$this->enabled = $enabled;
$this->accountNonExpired = $userNonExpired;
$this->credentialsNonExpired = $credentialsNonExpired;
$this->accountNonLocked = $userNonLocked;
$this->roles = $roles;
}
public function __toString(): string
{
return $this->getUserIdentifier();
}
public function getRoles(): array
{
return $this->roles;
}
public function getPassword(): ?string
{
return $this->password;
}
public function getSalt(): string
{
return '';
}
public function getUsername(): string
{
return $this->username;
}
public function getUserIdentifier(): string
{
return $this->username;
}
public function isAccountNonExpired(): bool
{
return $this->accountNonExpired;
}
public function isAccountNonLocked(): bool
{
return $this->accountNonLocked;
}
public function isCredentialsNonExpired(): bool
{
return $this->credentialsNonExpired;
}
public function isEnabled(): bool
{
return $this->enabled;
}
public function eraseCredentials(): void
{
}
}
class ForceLoginController
{
public string $authenticator = 'form_login';
public function __construct(private Security $security)
{
}
public function welcome()
{
$user = new InMemoryUser('chalasr', 'the-password', ['ROLE_FOO']);
$this->security->login($user, $this->authenticator);
return new JsonResponse(['message' => \sprintf('Welcome @%s!', $this->security->getUser()->getUserIdentifier())]);
}
}
class LogoutController
{
public bool $checkCsrf = false;
public function __construct(private Security $security)
{
}
public function logout(UserInterface $user)
{
$this->security->logout($this->checkCsrf);
return new JsonResponse(['message' => 'Logout successful']);
}
}
class LoggedInController
{
public function __invoke(UserInterface $user)
{
return new JsonResponse(['message' => \sprintf('Welcome back @%s', $user->getUserIdentifier())]);
}
}
|