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

  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 null, ?RoleHierarchyInterface $roleHierarchy null, ?LogoutUrlGenerator $logoutUrlGenerator null, ?AccessDecisionManagerInterface $accessDecisionManager null, ?FirewallMapInterface $firewallMap null, ?TraceableFirewallListener $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): void
  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' => (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.             $this->data['voters'] = [];
  124.             foreach ($this->accessDecisionManager->getVoters() as $voter) {
  125.                 if ($voter instanceof TraceableVoter) {
  126.                     $voter $voter->getDecoratedVoter();
  127.                 }
  128.                 $this->data['voters'][] = $this->hasVarDumper ? new ClassStub($voter::class) : $voter::class;
  129.             }
  130.             // collect voter details
  131.             $decisionLog $this->accessDecisionManager->getDecisionLog();
  132.             foreach ($decisionLog as $key => $log) {
  133.                 $decisionLog[$key]['voter_details'] = [];
  134.                 foreach ($log['voterDetails'] as $voterDetail) {
  135.                     $voterClass $voterDetail['voter']::class;
  136.                     $classData $this->hasVarDumper ? new ClassStub($voterClass) : $voterClass;
  137.                     $decisionLog[$key]['voter_details'][] = [
  138.                         'class' => $classData,
  139.                         'attributes' => $voterDetail['attributes'], // Only displayed for unanimous strategy
  140.                         'vote' => $voterDetail['vote'],
  141.                     ];
  142.                 }
  143.                 unset($decisionLog[$key]['voterDetails']);
  144.             }
  145.             $this->data['access_decision_log'] = $decisionLog;
  146.         } else {
  147.             $this->data['access_decision_log'] = [];
  148.             $this->data['voter_strategy'] = 'unknown';
  149.             $this->data['voters'] = [];
  150.         }
  151.         // collect firewall context information
  152.         $this->data['firewall'] = null;
  153.         if ($this->firewallMap instanceof FirewallMap) {
  154.             $firewallConfig $this->firewallMap->getFirewallConfig($request);
  155.             if (null !== $firewallConfig) {
  156.                 $this->data['firewall'] = [
  157.                     'name' => $firewallConfig->getName(),
  158.                     'request_matcher' => $firewallConfig->getRequestMatcher(),
  159.                     'security_enabled' => $firewallConfig->isSecurityEnabled(),
  160.                     'stateless' => $firewallConfig->isStateless(),
  161.                     'provider' => $firewallConfig->getProvider(),
  162.                     'context' => $firewallConfig->getContext(),
  163.                     'entry_point' => $firewallConfig->getEntryPoint(),
  164.                     'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(),
  165.                     'access_denied_url' => $firewallConfig->getAccessDeniedUrl(),
  166.                     'user_checker' => $firewallConfig->getUserChecker(),
  167.                     'authenticators' => $firewallConfig->getAuthenticators(),
  168.                 ];
  169.                 // generate exit impersonation path from current request
  170.                 if ($this->data['impersonated'] && null !== $switchUserConfig $firewallConfig->getSwitchUser()) {
  171.                     $exitPath $request->getRequestUri();
  172.                     $exitPath .= null === $request->getQueryString() ? '?' '&';
  173.                     $exitPath .= sprintf('%s=%s'urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE);
  174.                     $this->data['impersonation_exit_path'] = $exitPath;
  175.                 }
  176.             }
  177.         }
  178.         // collect firewall listeners information
  179.         $this->data['listeners'] = [];
  180.         if ($this->firewall) {
  181.             $this->data['listeners'] = $this->firewall->getWrappedListeners();
  182.         }
  183.         $this->data['authenticators'] = $this->firewall $this->firewall->getAuthenticatorsInfo() : [];
  184.     }
  185.     public function reset(): void
  186.     {
  187.         $this->data = [];
  188.     }
  189.     public function lateCollect(): void
  190.     {
  191.         $this->data $this->cloneVar($this->data);
  192.     }
  193.     /**
  194.      * Checks if security is enabled.
  195.      */
  196.     public function isEnabled(): bool
  197.     {
  198.         return $this->data['enabled'];
  199.     }
  200.     /**
  201.      * Gets the user.
  202.      */
  203.     public function getUser(): string
  204.     {
  205.         return $this->data['user'];
  206.     }
  207.     /**
  208.      * Gets the roles of the user.
  209.      */
  210.     public function getRoles(): array|Data
  211.     {
  212.         return $this->data['roles'];
  213.     }
  214.     /**
  215.      * Gets the inherited roles of the user.
  216.      */
  217.     public function getInheritedRoles(): array|Data
  218.     {
  219.         return $this->data['inherited_roles'];
  220.     }
  221.     /**
  222.      * Checks if the data contains information about inherited roles. Still the inherited
  223.      * roles can be an empty array.
  224.      */
  225.     public function supportsRoleHierarchy(): bool
  226.     {
  227.         return $this->data['supports_role_hierarchy'];
  228.     }
  229.     /**
  230.      * Checks if the user is authenticated or not.
  231.      */
  232.     public function isAuthenticated(): bool
  233.     {
  234.         return $this->data['authenticated'];
  235.     }
  236.     public function isImpersonated(): bool
  237.     {
  238.         return $this->data['impersonated'];
  239.     }
  240.     public function getImpersonatorUser(): ?string
  241.     {
  242.         return $this->data['impersonator_user'];
  243.     }
  244.     public function getImpersonationExitPath(): ?string
  245.     {
  246.         return $this->data['impersonation_exit_path'];
  247.     }
  248.     /**
  249.      * Get the class name of the security token.
  250.      */
  251.     public function getTokenClass(): string|Data|null
  252.     {
  253.         return $this->data['token_class'];
  254.     }
  255.     /**
  256.      * Get the full security token class as Data object.
  257.      */
  258.     public function getToken(): ?Data
  259.     {
  260.         return $this->data['token'];
  261.     }
  262.     /**
  263.      * Get the logout URL.
  264.      */
  265.     public function getLogoutUrl(): ?string
  266.     {
  267.         return $this->data['logout_url'];
  268.     }
  269.     /**
  270.      * Returns the FQCN of the security voters enabled in the application.
  271.      *
  272.      * @return string[]|Data
  273.      */
  274.     public function getVoters(): array|Data
  275.     {
  276.         return $this->data['voters'];
  277.     }
  278.     /**
  279.      * Returns the strategy configured for the security voters.
  280.      */
  281.     public function getVoterStrategy(): string
  282.     {
  283.         return $this->data['voter_strategy'];
  284.     }
  285.     /**
  286.      * Returns the log of the security decisions made by the access decision manager.
  287.      */
  288.     public function getAccessDecisionLog(): array|Data
  289.     {
  290.         return $this->data['access_decision_log'];
  291.     }
  292.     /**
  293.      * Returns the configuration of the current firewall context.
  294.      */
  295.     public function getFirewall(): array|Data|null
  296.     {
  297.         return $this->data['firewall'];
  298.     }
  299.     public function getListeners(): array|Data
  300.     {
  301.         return $this->data['listeners'];
  302.     }
  303.     public function getAuthenticators(): array|Data
  304.     {
  305.         return $this->data['authenticators'];
  306.     }
  307.     public function getName(): string
  308.     {
  309.         return 'security';
  310.     }
  311. }