UriSigner.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 Psr\Clock\ClockInterface;
  12. use Symfony\Component\HttpFoundation\Exception\ExpiredSignedUriException;
  13. use Symfony\Component\HttpFoundation\Exception\LogicException;
  14. use Symfony\Component\HttpFoundation\Exception\SignedUriException;
  15. use Symfony\Component\HttpFoundation\Exception\UnsignedUriException;
  16. use Symfony\Component\HttpFoundation\Exception\UnverifiedSignedUriException;
  17. /**
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class UriSigner
  21. {
  22. private const STATUS_VALID = 1;
  23. private const STATUS_INVALID = 2;
  24. private const STATUS_MISSING = 3;
  25. private const STATUS_EXPIRED = 4;
  26. /**
  27. * @param string $hashParameter Query string parameter to use
  28. * @param string $expirationParameter Query string parameter to use for expiration
  29. */
  30. public function __construct(
  31. #[\SensitiveParameter] private string $secret,
  32. private string $hashParameter = '_hash',
  33. private string $expirationParameter = '_expiration',
  34. private ?ClockInterface $clock = null,
  35. ) {
  36. if (!$secret) {
  37. throw new \InvalidArgumentException('A non-empty secret is required.');
  38. }
  39. }
  40. /**
  41. * Signs a URI.
  42. *
  43. * The given URI is signed by adding the query string parameter
  44. * which value depends on the URI and the secret.
  45. *
  46. * @param \DateTimeInterface|\DateInterval|int|null $expiration The expiration for the given URI.
  47. * If $expiration is a \DateTimeInterface, it's expected to be the exact date + time.
  48. * If $expiration is a \DateInterval, the interval is added to "now" to get the date + time.
  49. * If $expiration is an int, it's expected to be a timestamp in seconds of the exact date + time.
  50. * If $expiration is null, no expiration.
  51. *
  52. * The expiration is added as a query string parameter.
  53. */
  54. public function sign(string $uri, \DateTimeInterface|\DateInterval|int|null $expiration = null): string
  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. return self::STATUS_VALID === $this->doVerify($uri);
  81. }
  82. public function checkRequest(Request $request): bool
  83. {
  84. return self::STATUS_VALID === $this->doVerify(self::normalize($request));
  85. }
  86. /**
  87. * Verify a Request or string URI.
  88. *
  89. * @throws UnsignedUriException If the URI is not signed
  90. * @throws UnverifiedSignedUriException If the signature is invalid
  91. * @throws ExpiredSignedUriException If the URI has expired
  92. * @throws SignedUriException
  93. */
  94. public function verify(Request|string $uri): void
  95. {
  96. $uri = self::normalize($uri);
  97. $status = $this->doVerify($uri);
  98. match ($status) {
  99. self::STATUS_VALID => null,
  100. self::STATUS_INVALID => throw new UnverifiedSignedUriException(),
  101. self::STATUS_EXPIRED => throw new ExpiredSignedUriException(),
  102. default => throw new UnsignedUriException(),
  103. };
  104. }
  105. private function computeHash(string $uri): string
  106. {
  107. return strtr(rtrim(base64_encode(hash_hmac('sha256', $uri, $this->secret, true)), '='), ['/' => '_', '+' => '-']);
  108. }
  109. private function buildUrl(array $url, array $params = []): string
  110. {
  111. ksort($params, \SORT_STRING);
  112. $url['query'] = http_build_query($params, '', '&');
  113. $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
  114. $host = $url['host'] ?? '';
  115. $port = isset($url['port']) ? ':'.$url['port'] : '';
  116. $user = $url['user'] ?? '';
  117. $pass = isset($url['pass']) ? ':'.$url['pass'] : '';
  118. $pass = ($user || $pass) ? "$pass@" : '';
  119. $path = $url['path'] ?? '';
  120. $query = $url['query'] ? '?'.$url['query'] : '';
  121. $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
  122. return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
  123. }
  124. private function getExpirationTime(\DateTimeInterface|\DateInterval|int $expiration): string
  125. {
  126. if ($expiration instanceof \DateTimeInterface) {
  127. return $expiration->format('U');
  128. }
  129. if ($expiration instanceof \DateInterval) {
  130. return $this->now()->add($expiration)->format('U');
  131. }
  132. return (string) $expiration;
  133. }
  134. private function now(): \DateTimeImmutable
  135. {
  136. return $this->clock?->now() ?? \DateTimeImmutable::createFromFormat('U', time());
  137. }
  138. /**
  139. * @return self::STATUS_*
  140. */
  141. private function doVerify(string $uri): int
  142. {
  143. $url = parse_url($uri);
  144. $params = [];
  145. if (isset($url['query'])) {
  146. parse_str($url['query'], $params);
  147. }
  148. if (empty($params[$this->hashParameter])) {
  149. return self::STATUS_MISSING;
  150. }
  151. $hash = $params[$this->hashParameter];
  152. unset($params[$this->hashParameter]);
  153. if (!hash_equals($this->computeHash($this->buildUrl($url, $params)), strtr(rtrim($hash, '='), ['/' => '_', '+' => '-']))) {
  154. return self::STATUS_INVALID;
  155. }
  156. if (!$expiration = $params[$this->expirationParameter] ?? false) {
  157. return self::STATUS_VALID;
  158. }
  159. if ($this->now()->getTimestamp() < $expiration) {
  160. return self::STATUS_VALID;
  161. }
  162. return self::STATUS_EXPIRED;
  163. }
  164. private static function normalize(Request|string $uri): string
  165. {
  166. if ($uri instanceof Request) {
  167. $qs = ($qs = $uri->server->get('QUERY_STRING')) ? '?'.$qs : '';
  168. $uri = $uri->getSchemeAndHttpHost().$uri->getBaseUrl().$uri->getPathInfo().$qs;
  169. }
  170. return $uri;
  171. }
  172. }