vendor/symfony/security-bundle/DataCollector/SecurityDataCollector.php line 58

  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\DataCollector;
  11. use Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener;
  12. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\DataCollector\DataCollector;
  16. use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  19. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  20. use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
  21. use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
  22. use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
  23. use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
  24. use Symfony\Component\Security\Http\FirewallMapInterface;
  25. use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator;
  26. use Symfony\Component\VarDumper\Caster\ClassStub;
  27. use Symfony\Component\VarDumper\Cloner\Data;
  28. /**
  29.  * @author Fabien Potencier <fabien@symfony.com>
  30.  *
  31.  * @final
  32.  */
  33. class SecurityDataCollector extends DataCollector implements LateDataCollectorInterface
  34. {
  35.     private ?TokenStorageInterface $tokenStorage;
  36.     private ?RoleHierarchyInterface $roleHierarchy;
  37.     private ?LogoutUrlGenerator $logoutUrlGenerator;
  38.     private ?AccessDecisionManagerInterface $accessDecisionManager;
  39.     private ?FirewallMapInterface $firewallMap;
  40.     private ?TraceableFirewallListener $firewall;
  41.     private bool $hasVarDumper;
  42.     public function __construct(TokenStorageInterface $tokenStorage nullRoleHierarchyInterface $roleHierarchy nullLogoutUrlGenerator $logoutUrlGenerator nullAccessDecisionManagerInterface $accessDecisionManager nullFirewallMapInterface $firewallMap nullTraceableFirewallListener $firewall null)
  43.     {
  44.         $this->tokenStorage $tokenStorage;
  45.         $this->roleHierarchy $roleHierarchy;
  46.         $this->logoutUrlGenerator $logoutUrlGenerator;
  47.         $this->accessDecisionManager $accessDecisionManager;
  48.         $this->firewallMap $firewallMap;
  49.         $this->firewall $firewall;
  50.         $this->hasVarDumper class_exists(ClassStub::class);
  51.     }
  52.     public function collect(Request $requestResponse $response\Throwable $exception null)
  53.     {
  54.         if (null === $this->tokenStorage) {
  55.             $this->data = [
  56.                 'enabled' => false,
  57.                 'authenticated' => false,
  58.                 'impersonated' => false,
  59.                 'impersonator_user' => null,
  60.                 'impersonation_exit_path' => null,
  61.                 'token' => null,
  62.                 'token_class' => null,
  63.                 'logout_url' => null,
  64.                 'user' => '',
  65.                 'roles' => [],
  66.                 'inherited_roles' => [],
  67.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  68.             ];
  69.         } elseif (null === $token $this->tokenStorage->getToken()) {
  70.             $this->data = [
  71.                 'enabled' => true,
  72.                 'authenticated' => false,
  73.                 'impersonated' => false,
  74.                 'impersonator_user' => null,
  75.                 'impersonation_exit_path' => null,
  76.                 'token' => null,
  77.                 'token_class' => null,
  78.                 'logout_url' => null,
  79.                 'user' => '',
  80.                 'roles' => [],
  81.                 'inherited_roles' => [],
  82.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  83.             ];
  84.         } else {
  85.             $inheritedRoles = [];
  86.             $assignedRoles $token->getRoleNames();
  87.             $impersonatorUser null;
  88.             if ($token instanceof SwitchUserToken) {
  89.                 $originalToken $token->getOriginalToken();
  90.                 $impersonatorUser $originalToken->getUserIdentifier();
  91.             }
  92.             if (null !== $this->roleHierarchy) {
  93.                 foreach ($this->roleHierarchy->getReachableRoleNames($assignedRoles) as $role) {
  94.                     if (!\in_array($role$assignedRolestrue)) {
  95.                         $inheritedRoles[] = $role;
  96.                     }
  97.                 }
  98.             }
  99.             $logoutUrl null;
  100.             try {
  101.                 $logoutUrl $this->logoutUrlGenerator?->getLogoutPath();
  102.             } catch (\Exception) {
  103.                 // fail silently when the logout URL cannot be generated
  104.             }
  105.             $this->data = [
  106.                 'enabled' => true,
  107.                 'authenticated' => method_exists($token'isAuthenticated') ? $token->isAuthenticated(false) : (bool) $token->getUser(),
  108.                 'impersonated' => null !== $impersonatorUser,
  109.                 'impersonator_user' => $impersonatorUser,
  110.                 'impersonation_exit_path' => null,
  111.                 'token' => $token,
  112.                 'token_class' => $this->hasVarDumper ? new ClassStub($token::class) : $token::class,
  113.                 'logout_url' => $logoutUrl,
  114.                 'user' => $token->getUserIdentifier(),
  115.                 'roles' => $assignedRoles,
  116.                 'inherited_roles' => array_unique($inheritedRoles),
  117.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  118.             ];
  119.         }
  120.         // collect voters and access decision manager information
  121.         if ($this->accessDecisionManager instanceof TraceableAccessDecisionManager) {
  122.             $this->data['voter_strategy'] = $this->accessDecisionManager->getStrategy();
  123.             foreach ($this->accessDecisionManager->getVoters() as $voter) {
  124.                 if ($voter instanceof TraceableVoter) {
  125.                     $voter $voter->getDecoratedVoter();
  126.                 }
  127.                 $this->data['voters'][] = $this->hasVarDumper ? new ClassStub($voter::class) : $voter::class;
  128.             }
  129.             // collect voter details
  130.             $decisionLog $this->accessDecisionManager->getDecisionLog();
  131.             foreach ($decisionLog as $key => $log) {
  132.                 $decisionLog[$key]['voter_details'] = [];
  133.                 foreach ($log['voterDetails'] as $voterDetail) {
  134.                     $voterClass \get_class($voterDetail['voter']);
  135.                     $classData $this->hasVarDumper ? new ClassStub($voterClass) : $voterClass;
  136.                     $decisionLog[$key]['voter_details'][] = [
  137.                         'class' => $classData,
  138.                         'attributes' => $voterDetail['attributes'], // Only displayed for unanimous strategy
  139.                         'vote' => $voterDetail['vote'],
  140.                     ];
  141.                 }
  142.                 unset($decisionLog[$key]['voterDetails']);
  143.             }
  144.             $this->data['access_decision_log'] = $decisionLog;
  145.         } else {
  146.             $this->data['access_decision_log'] = [];
  147.             $this->data['voter_strategy'] = 'unknown';
  148.             $this->data['voters'] = [];
  149.         }
  150.         // collect firewall context information
  151.         $this->data['firewall'] = null;
  152.         if ($this->firewallMap instanceof FirewallMap) {
  153.             $firewallConfig $this->firewallMap->getFirewallConfig($request);
  154.             if (null !== $firewallConfig) {
  155.                 $this->data['firewall'] = [
  156.                     'name' => $firewallConfig->getName(),
  157.                     'request_matcher' => $firewallConfig->getRequestMatcher(),
  158.                     'security_enabled' => $firewallConfig->isSecurityEnabled(),
  159.                     'stateless' => $firewallConfig->isStateless(),
  160.                     'provider' => $firewallConfig->getProvider(),
  161.                     'context' => $firewallConfig->getContext(),
  162.                     'entry_point' => $firewallConfig->getEntryPoint(),
  163.                     'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(),
  164.                     'access_denied_url' => $firewallConfig->getAccessDeniedUrl(),
  165.                     'user_checker' => $firewallConfig->getUserChecker(),
  166.                     'authenticators' => $firewallConfig->getAuthenticators(),
  167.                 ];
  168.                 // generate exit impersonation path from current request
  169.                 if ($this->data['impersonated'] && null !== $switchUserConfig $firewallConfig->getSwitchUser()) {
  170.                     $exitPath $request->getRequestUri();
  171.                     $exitPath .= null === $request->getQueryString() ? '?' '&';
  172.                     $exitPath .= sprintf('%s=%s'urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE);
  173.                     $this->data['impersonation_exit_path'] = $exitPath;
  174.                 }
  175.             }
  176.         }
  177.         // collect firewall listeners information
  178.         $this->data['listeners'] = [];
  179.         if ($this->firewall) {
  180.             $this->data['listeners'] = $this->firewall->getWrappedListeners();
  181.         }
  182.         $this->data['authenticators'] = $this->firewall $this->firewall->getAuthenticatorsInfo() : [];
  183.     }
  184.     public function reset()
  185.     {
  186.         $this->data = [];
  187.     }
  188.     public function lateCollect()
  189.     {
  190.         $this->data $this->cloneVar($this->data);
  191.     }
  192.     /**
  193.      * Checks if security is enabled.
  194.      */
  195.     public function isEnabled(): bool
  196.     {
  197.         return $this->data['enabled'];
  198.     }
  199.     /**
  200.      * Gets the user.
  201.      */
  202.     public function getUser(): string
  203.     {
  204.         return $this->data['user'];
  205.     }
  206.     /**
  207.      * Gets the roles of the user.
  208.      */
  209.     public function getRoles(): array|Data
  210.     {
  211.         return $this->data['roles'];
  212.     }
  213.     /**
  214.      * Gets the inherited roles of the user.
  215.      */
  216.     public function getInheritedRoles(): array|Data
  217.     {
  218.         return $this->data['inherited_roles'];
  219.     }
  220.     /**
  221.      * Checks if the data contains information about inherited roles. Still the inherited
  222.      * roles can be an empty array.
  223.      */
  224.     public function supportsRoleHierarchy(): bool
  225.     {
  226.         return $this->data['supports_role_hierarchy'];
  227.     }
  228.     /**
  229.      * Checks if the user is authenticated or not.
  230.      */
  231.     public function isAuthenticated(): bool
  232.     {
  233.         return $this->data['authenticated'];
  234.     }
  235.     public function isImpersonated(): bool
  236.     {
  237.         return $this->data['impersonated'];
  238.     }
  239.     public function getImpersonatorUser(): ?string
  240.     {
  241.         return $this->data['impersonator_user'];
  242.     }
  243.     public function getImpersonationExitPath(): ?string
  244.     {
  245.         return $this->data['impersonation_exit_path'];
  246.     }
  247.     /**
  248.      * Get the class name of the security token.
  249.      */
  250.     public function getTokenClass(): string|Data|null
  251.     {
  252.         return $this->data['token_class'];
  253.     }
  254.     /**
  255.      * Get the full security token class as Data object.
  256.      */
  257.     public function getToken(): ?Data
  258.     {
  259.         return $this->data['token'];
  260.     }
  261.     /**
  262.      * Get the logout URL.
  263.      */
  264.     public function getLogoutUrl(): ?string
  265.     {
  266.         return $this->data['logout_url'];
  267.     }
  268.     /**
  269.      * Returns the FQCN of the security voters enabled in the application.
  270.      *
  271.      * @return string[]|Data
  272.      */
  273.     public function getVoters(): array|Data
  274.     {
  275.         return $this->data['voters'];
  276.     }
  277.     /**
  278.      * Returns the strategy configured for the security voters.
  279.      */
  280.     public function getVoterStrategy(): string
  281.     {
  282.         return $this->data['voter_strategy'];
  283.     }
  284.     /**
  285.      * Returns the log of the security decisions made by the access decision manager.
  286.      */
  287.     public function getAccessDecisionLog(): array|Data
  288.     {
  289.         return $this->data['access_decision_log'];
  290.     }
  291.     /**
  292.      * Returns the configuration of the current firewall context.
  293.      */
  294.     public function getFirewall(): array|Data|null
  295.     {
  296.         return $this->data['firewall'];
  297.     }
  298.     public function getListeners(): array|Data
  299.     {
  300.         return $this->data['listeners'];
  301.     }
  302.     public function getAuthenticators(): array|Data
  303.     {
  304.         return $this->data['authenticators'];
  305.     }
  306.     public function getName(): string
  307.     {
  308.         return 'security';
  309.     }
  310. }