UriSigner.php 5.7 KB

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