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

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