UriSigner.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\Exception\LogicException;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. class UriSigner
  16. {
  17. private string $secret;
  18. private string $hashParameter;
  19. private string $expirationParameter;
  20. /**
  21. * @param string $hashParameter Query string parameter to use
  22. * @param string $expirationParameter Query string parameter to use for expiration
  23. */
  24. public function __construct(#[\SensitiveParameter] string $secret, string $hashParameter = '_hash', string $expirationParameter = '_expiration')
  25. {
  26. if (!$secret) {
  27. throw new \InvalidArgumentException('A non-empty secret is required.');
  28. }
  29. $this->secret = $secret;
  30. $this->hashParameter = $hashParameter;
  31. $this->expirationParameter = $expirationParameter;
  32. }
  33. /**
  34. * Signs a URI.
  35. *
  36. * The given URI is signed by adding the query string parameter
  37. * which value depends on the URI and the secret.
  38. *
  39. * @param \DateTimeInterface|\DateInterval|int|null $expiration The expiration for the given URI.
  40. * If $expiration is a \DateTimeInterface, it's expected to be the exact date + time.
  41. * If $expiration is a \DateInterval, the interval is added to "now" to get the date + time.
  42. * If $expiration is an int, it's expected to be a timestamp in seconds of the exact date + time.
  43. * If $expiration is null, no expiration.
  44. *
  45. * The expiration is added as a query string parameter.
  46. */
  47. public function sign(string $uri/*, \DateTimeInterface|\DateInterval|int|null $expiration = null*/): string
  48. {
  49. $expiration = null;
  50. if (1 < \func_num_args()) {
  51. $expiration = func_get_arg(1);
  52. }
  53. if (null !== $expiration && !$expiration instanceof \DateTimeInterface && !$expiration instanceof \DateInterval && !\is_int($expiration)) {
  54. throw new \TypeError(sprintf('The second argument of %s() must be an instance of %s or %s, an integer or null (%s given).', __METHOD__, \DateTimeInterface::class, \DateInterval::class, get_debug_type($expiration)));
  55. }
  56. $url = parse_url($uri);
  57. $params = [];
  58. if (isset($url['query'])) {
  59. parse_str($url['query'], $params);
  60. }
  61. if (isset($params[$this->hashParameter])) {
  62. throw new LogicException(sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->hashParameter));
  63. }
  64. if (isset($params[$this->expirationParameter])) {
  65. throw new LogicException(sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->expirationParameter));
  66. }
  67. if (null !== $expiration) {
  68. $params[$this->expirationParameter] = $this->getExpirationTime($expiration);
  69. }
  70. $uri = $this->buildUrl($url, $params);
  71. $params[$this->hashParameter] = $this->computeHash($uri);
  72. return $this->buildUrl($url, $params);
  73. }
  74. /**
  75. * Checks that a URI contains the correct hash.
  76. * Also checks if the URI has not expired (If you used expiration during signing).
  77. */
  78. public function check(string $uri): bool
  79. {
  80. $url = parse_url($uri);
  81. $params = [];
  82. if (isset($url['query'])) {
  83. parse_str($url['query'], $params);
  84. }
  85. if (empty($params[$this->hashParameter])) {
  86. return false;
  87. }
  88. $hash = $params[$this->hashParameter];
  89. unset($params[$this->hashParameter]);
  90. if (!hash_equals($this->computeHash($this->buildUrl($url, $params)), $hash)) {
  91. return false;
  92. }
  93. if ($expiration = $params[$this->expirationParameter] ?? false) {
  94. return time() < $expiration;
  95. }
  96. return true;
  97. }
  98. public function checkRequest(Request $request): bool
  99. {
  100. $qs = ($qs = $request->server->get('QUERY_STRING')) ? '?'.$qs : '';
  101. // we cannot use $request->getUri() here as we want to work with the original URI (no query string reordering)
  102. return $this->check($request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo().$qs);
  103. }
  104. private function computeHash(string $uri): string
  105. {
  106. return base64_encode(hash_hmac('sha256', $uri, $this->secret, true));
  107. }
  108. private function buildUrl(array $url, array $params = []): string
  109. {
  110. ksort($params, \SORT_STRING);
  111. $url['query'] = http_build_query($params, '', '&');
  112. $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
  113. $host = $url['host'] ?? '';
  114. $port = isset($url['port']) ? ':'.$url['port'] : '';
  115. $user = $url['user'] ?? '';
  116. $pass = isset($url['pass']) ? ':'.$url['pass'] : '';
  117. $pass = ($user || $pass) ? "$pass@" : '';
  118. $path = $url['path'] ?? '';
  119. $query = $url['query'] ? '?'.$url['query'] : '';
  120. $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
  121. return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
  122. }
  123. private function getExpirationTime(\DateTimeInterface|\DateInterval|int $expiration): string
  124. {
  125. if ($expiration instanceof \DateTimeInterface) {
  126. return $expiration->format('U');
  127. }
  128. if ($expiration instanceof \DateInterval) {
  129. return \DateTimeImmutable::createFromFormat('U', time())->add($expiration)->format('U');
  130. }
  131. return (string) $expiration;
  132. }
  133. }