Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/UriSigner.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 use Psr\Clock\ClockInterface;
15 use Symfony\Component\HttpFoundation\Exception\ExpiredSignedUriException;
16 use Symfony\Component\HttpFoundation\Exception\LogicException;
17 use Symfony\Component\HttpFoundation\Exception\SignedUriException;
18 use Symfony\Component\HttpFoundation\Exception\UnsignedUriException;
19 use Symfony\Component\HttpFoundation\Exception\UnverifiedSignedUriException;
20
21 /**
22 * @author Fabien Potencier <[email protected]>
23 */
24 class UriSigner
25 {
26 private const STATUS_VALID = 1;
27 private const STATUS_INVALID = 2;
28 private const STATUS_MISSING = 3;
29 private const STATUS_EXPIRED = 4;
30
31 /**
32 * @param string $hashParameter Query string parameter to use
33 * @param string $expirationParameter Query string parameter to use for expiration
34 */
35 public function __construct(
36 #[\SensitiveParameter] private string $secret,
37 private string $hashParameter = '_hash',
38 private string $expirationParameter = '_expiration',
39 private ?ClockInterface $clock = null,
40 ) {
41 if (!$secret) {
42 throw new \InvalidArgumentException('A non-empty secret is required.');
43 }
44 }
45
46 /**
47 * Signs a URI.
48 *
49 * The given URI is signed by adding the query string parameter
50 * which value depends on the URI and the secret.
51 *
52 * @param \DateTimeInterface|\DateInterval|int|null $expiration The expiration for the given URI.
53 * If $expiration is a \DateTimeInterface, it's expected to be the exact date + time.
54 * If $expiration is a \DateInterval, the interval is added to "now" to get the date + time.
55 * If $expiration is an int, it's expected to be a timestamp in seconds of the exact date + time.
56 * If $expiration is null, no expiration.
57 *
58 * The expiration is added as a query string parameter.
59 */
60 public function sign(string $uri/* , \DateTimeInterface|\DateInterval|int|null $expiration = null */): string
61 {
62 $expiration = null;
63
64 if (1 < \func_num_args()) {
65 $expiration = func_get_arg(1);
66 }
67
68 if (null !== $expiration && !$expiration instanceof \DateTimeInterface && !$expiration instanceof \DateInterval && !\is_int($expiration)) {
69 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)));
70 }
71
72 $url = parse_url($uri);
73 $params = [];
74
75 if (isset($url['query'])) {
76 parse_str($url['query'], $params);
77 }
78
79 if (isset($params[$this->hashParameter])) {
80 throw new LogicException(\sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->hashParameter));
81 }
82
83 if (isset($params[$this->expirationParameter])) {
84 throw new LogicException(\sprintf('URI query parameter conflict: parameter name "%s" is reserved.', $this->expirationParameter));
85 }
86
87 if (null !== $expiration) {
88 $params[$this->expirationParameter] = $this->getExpirationTime($expiration);
89 }
90
91 $uri = $this->buildUrl($url, $params);
92 $params[$this->hashParameter] = $this->computeHash($uri);
93
94 return $this->buildUrl($url, $params);
95 }
96
97 /**
98 * Checks that a URI contains the correct hash.
99 * Also checks if the URI has not expired (If you used expiration during signing).
100 */
101 public function check(string $uri): bool
102 {
103 return self::STATUS_VALID === $this->doVerify($uri);
104 }
105
106 public function checkRequest(Request $request): bool
107 {
108 return self::STATUS_VALID === $this->doVerify(self::normalize($request));
109 }
110
111 /**
112 * Verify a Request or string URI.
113 *
114 * @throws UnsignedUriException If the URI is not signed
115 * @throws UnverifiedSignedUriException If the signature is invalid
116 * @throws ExpiredSignedUriException If the URI has expired
117 * @throws SignedUriException
118 */
119 public function verify(Request|string $uri): void
120 {
121 $uri = self::normalize($uri);
122 $status = $this->doVerify($uri);
123
124 match ($status) {
125 self::STATUS_VALID => null,
126 self::STATUS_INVALID => throw new UnverifiedSignedUriException(),
127 self::STATUS_EXPIRED => throw new ExpiredSignedUriException(),
128 default => throw new UnsignedUriException(),
129 };
130 }
131
132 private function computeHash(string $uri): string
133 {
134 return strtr(rtrim(base64_encode(hash_hmac('sha256', $uri, $this->secret, true)), '='), ['/' => '_', '+' => '-']);
135 }
136
137 private function buildUrl(array $url, array $params = []): string
138 {
139 ksort($params, \SORT_STRING);
140 $url['query'] = http_build_query($params, '', '&');
141
142 $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
143 $host = $url['host'] ?? '';
144 $port = isset($url['port']) ? ':'.$url['port'] : '';
145 $user = $url['user'] ?? '';
146 $pass = isset($url['pass']) ? ':'.$url['pass'] : '';
147 $pass = ($user || $pass) ? "$pass@" : '';
148 $path = $url['path'] ?? '';
149 $query = $url['query'] ? '?'.$url['query'] : '';
150 $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
151
152 return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
153 }
154
155 private function getExpirationTime(\DateTimeInterface|\DateInterval|int $expiration): string
156 {
157 if ($expiration instanceof \DateTimeInterface) {
158 return $expiration->format('U');
159 }
160
161 if ($expiration instanceof \DateInterval) {
162 return $this->now()->add($expiration)->format('U');
163 }
164
165 return (string) $expiration;
166 }
167
168 private function now(): \DateTimeImmutable
169 {
170 return $this->clock?->now() ?? \DateTimeImmutable::createFromFormat('U', time());
171 }
172
173 /**
174 * @return self::STATUS_*
175 */
176 private function doVerify(string $uri): int
177 {
178 $url = parse_url($uri);
179 $params = [];
180
181 if (isset($url['query'])) {
182 parse_str($url['query'], $params);
183 }
184
185 if (empty($params[$this->hashParameter])) {
186 return self::STATUS_MISSING;
187 }
188
189 $hash = $params[$this->hashParameter];
190 unset($params[$this->hashParameter]);
191
192 if (!hash_equals($this->computeHash($this->buildUrl($url, $params)), strtr(rtrim($hash, '='), ['/' => '_', '+' => '-']))) {
193 return self::STATUS_INVALID;
194 }
195
196 if (!$expiration = $params[$this->expirationParameter] ?? false) {
197 return self::STATUS_VALID;
198 }
199
200 if ($this->now()->getTimestamp() < $expiration) {
201 return self::STATUS_VALID;
202 }
203
204 return self::STATUS_EXPIRED;
205 }
206
207 private static function normalize(Request|string $uri): string
208 {
209 if ($uri instanceof Request) {
210 $qs = ($qs = $uri->server->get('QUERY_STRING')) ? '?'.$qs : '';
211 $uri = $uri->getSchemeAndHttpHost().$uri->getBaseUrl().$uri->getPathInfo().$qs;
212 }
213
214 return $uri;
215 }
216 }