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

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