UriSigner.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. $expiration = null;
  57. if (1 < \func_num_args()) {
  58. $expiration = func_get_arg(1);
  59. }
  60. if (null !== $expiration && !$expiration instanceof \DateTimeInterface && !$expiration instanceof \DateInterval && !\is_int($expiration)) {
  61. 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)));
  62. }
  63. $url = parse_url($uri);
  64. $params = [];
  65. if (isset($url['query'])) {
  66. parse_str($url['query'], $params);
  67. }
  68. if (isset($params[$this->hashParameter])) {
  69. throw new LogicException(\sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->hashParameter));
  70. }
  71. if (isset($params[$this->expirationParameter])) {
  72. throw new LogicException(\sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->expirationParameter));
  73. }
  74. if (null !== $expiration) {
  75. $params[$this->expirationParameter] = $this->getExpirationTime($expiration);
  76. }
  77. $uri = $this->buildUrl($url, $params);
  78. $params[$this->hashParameter] = $this->computeHash($uri);
  79. return $this->buildUrl($url, $params);
  80. }
  81. /**
  82. * Checks that a URI contains the correct hash.
  83. * Also checks if the URI has not expired (If you used expiration during signing).
  84. */
  85. public function check(string $uri): bool
  86. {
  87. return self::STATUS_VALID === $this->doVerify($uri);
  88. }
  89. public function checkRequest(Request $request): bool
  90. {
  91. return self::STATUS_VALID === $this->doVerify(self::normalize($request));
  92. }
  93. /**
  94. * Verify a Request or string URI.
  95. *
  96. * @throws UnsignedUriException If the URI is not signed
  97. * @throws UnverifiedSignedUriException If the signature is invalid
  98. * @throws ExpiredSignedUriException If the URI has expired
  99. * @throws SignedUriException
  100. */
  101. public function verify(Request|string $uri): void
  102. {
  103. $uri = self::normalize($uri);
  104. $status = $this->doVerify($uri);
  105. match ($status) {
  106. self::STATUS_VALID => null,
  107. self::STATUS_INVALID => throw new UnverifiedSignedUriException(),
  108. self::STATUS_EXPIRED => throw new ExpiredSignedUriException(),
  109. default => throw new UnsignedUriException(),
  110. };
  111. }
  112. private function computeHash(string $uri): string
  113. {
  114. return strtr(rtrim(base64_encode(hash_hmac('sha256', $uri, $this->secret, true)), '='), ['/' => '_', '+' => '-']);
  115. }
  116. private function buildUrl(array $url, array $params = []): string
  117. {
  118. ksort($params, \SORT_STRING);
  119. $url['query'] = http_build_query($params, '', '&');
  120. $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
  121. $host = $url['host'] ?? '';
  122. $port = isset($url['port']) ? ':'.$url['port'] : '';
  123. $user = $url['user'] ?? '';
  124. $pass = isset($url['pass']) ? ':'.$url['pass'] : '';
  125. $pass = ($user || $pass) ? "$pass@" : '';
  126. $path = $url['path'] ?? '';
  127. $query = $url['query'] ? '?'.$url['query'] : '';
  128. $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
  129. return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
  130. }
  131. private function getExpirationTime(\DateTimeInterface|\DateInterval|int $expiration): string
  132. {
  133. if ($expiration instanceof \DateTimeInterface) {
  134. return $expiration->format('U');
  135. }
  136. if ($expiration instanceof \DateInterval) {
  137. return $this->now()->add($expiration)->format('U');
  138. }
  139. return (string) $expiration;
  140. }
  141. private function now(): \DateTimeImmutable
  142. {
  143. return $this->clock?->now() ?? \DateTimeImmutable::createFromFormat('U', time());
  144. }
  145. /**
  146. * @return self::STATUS_*
  147. */
  148. private function doVerify(string $uri): int
  149. {
  150. $url = parse_url($uri);
  151. $params = [];
  152. if (isset($url['query'])) {
  153. parse_str($url['query'], $params);
  154. }
  155. if (empty($params[$this->hashParameter])) {
  156. return self::STATUS_MISSING;
  157. }
  158. $hash = $params[$this->hashParameter];
  159. unset($params[$this->hashParameter]);
  160. if (!hash_equals($this->computeHash($this->buildUrl($url, $params)), strtr(rtrim($hash, '='), ['/' => '_', '+' => '-']))) {
  161. return self::STATUS_INVALID;
  162. }
  163. if (!$expiration = $params[$this->expirationParameter] ?? false) {
  164. return self::STATUS_VALID;
  165. }
  166. if ($this->now()->getTimestamp() < $expiration) {
  167. return self::STATUS_VALID;
  168. }
  169. return self::STATUS_EXPIRED;
  170. }
  171. private static function normalize(Request|string $uri): string
  172. {
  173. if ($uri instanceof Request) {
  174. $qs = ($qs = $uri->server->get('QUERY_STRING')) ? '?'.$qs : '';
  175. $uri = $uri->getSchemeAndHttpHost().$uri->getBaseUrl().$uri->getPathInfo().$qs;
  176. }
  177. return $uri;
  178. }
  179. }