Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Core/JWKSet.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Core;
6
7 use ArrayIterator;
8 use Countable;
9 use InvalidArgumentException;
10 use IteratorAggregate;
11 use JsonSerializable;
12 use Traversable;
13 use function array_key_exists;
14 use function count;
15 use function in_array;
16 use function is_array;
17 use const COUNT_NORMAL;
18 use const JSON_THROW_ON_ERROR;
19
20 class JWKSet implements Countable, IteratorAggregate, JsonSerializable
21 {
22 private array $keys = [];
23
24 /**
25 * @param JWK[] $keys
26 */
27 public function __construct(array $keys)
28 {
29 foreach ($keys as $k => $key) {
30 if (! $key instanceof JWK) {
31 throw new InvalidArgumentException('Invalid list. Should only contains JWK objects');
32 }
33
34 if ($key->has('kid')) {
35 unset($keys[$k]);
36 $this->keys[$key->get('kid')] = $key;
37 } else {
38 $this->keys[] = $key;
39 }
40 }
41 }
42
43 /**
44 * Creates a JWKSet object using the given values.
45 */
46 public static function createFromKeyData(array $data): self
47 {
48 if (! isset($data['keys'])) {
49 throw new InvalidArgumentException('Invalid data.');
50 }
51 if (! is_array($data['keys'])) {
52 throw new InvalidArgumentException('Invalid data.');
53 }
54
55 $jwkset = new self([]);
56 foreach ($data['keys'] as $key) {
57 $jwk = new JWK($key);
58 if ($jwk->has('kid')) {
59 $jwkset->keys[$jwk->get('kid')] = $jwk;
60 } else {
61 $jwkset->keys[] = $jwk;
62 }
63 }
64
65 return $jwkset;
66 }
67
68 /**
69 * Creates a JWKSet object using the given Json string.
70 */
71 public static function createFromJson(string $json): self
72 {
73 $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
74 if (! is_array($data)) {
75 throw new InvalidArgumentException('Invalid argument.');
76 }
77
78 return self::createFromKeyData($data);
79 }
80
81 /**
82 * Returns an array of keys stored in the key set.
83 *
84 * @return JWK[]
85 */
86 public function all(): array
87 {
88 return $this->keys;
89 }
90
91 /**
92 * Add key to store in the key set. This method is immutable and will return a new object.
93 */
94 public function with(JWK $jwk): self
95 {
96 $clone = clone $this;
97
98 if ($jwk->has('kid')) {
99 $clone->keys[$jwk->get('kid')] = $jwk;
100 } else {
101 $clone->keys[] = $jwk;
102 }
103
104 return $clone;
105 }
106
107 /**
108 * Remove key from the key set. This method is immutable and will return a new object.
109 *
110 * @param int|string $key Key to remove from the key set
111 */
112 public function without(int|string $key): self
113 {
114 if (! $this->has($key)) {
115 return $this;
116 }
117
118 $clone = clone $this;
119 unset($clone->keys[$key]);
120
121 return $clone;
122 }
123
124 /**
125 * Returns true if the key set contains a key with the given index.
126 */
127 public function has(int|string $index): bool
128 {
129 return array_key_exists($index, $this->keys);
130 }
131
132 /**
133 * Returns the key with the given index. Throws an exception if the index is not present in the key store.
134 */
135 public function get(int|string $index): JWK
136 {
137 if (! $this->has($index)) {
138 throw new InvalidArgumentException('Undefined index.');
139 }
140
141 return $this->keys[$index];
142 }
143
144 /**
145 * Returns the values to be serialized.
146 */
147 public function jsonSerialize(): array
148 {
149 return [
150 'keys' => array_values($this->keys),
151 ];
152 }
153
154 /**
155 * Returns the number of keys in the key set.
156 *
157 * @param int $mode
158 */
159 public function count($mode = COUNT_NORMAL): int
160 {
161 return count($this->keys, $mode);
162 }
163
164 /**
165 * Try to find a key that fits on the selected requirements. Returns null if not found.
166 *
167 * @param string $type Must be 'sig' (signature) or 'enc' (encryption)
168 * @param Algorithm|null $algorithm Specifies the algorithm to be used
169 * @param array<string, mixed> $restrictions More restrictions such as 'kid' or 'kty'
170 */
171 public function selectKey(string $type, ?Algorithm $algorithm = null, array $restrictions = []): ?JWK
172 {
173 if (! in_array($type, ['enc', 'sig'], true)) {
174 throw new InvalidArgumentException('Allowed key types are "sig" or "enc".');
175 }
176
177 $result = [];
178 foreach ($this->keys as $key) {
179 $ind = 0;
180
181 $can_use = $this->canKeyBeUsedFor($type, $key);
182 if ($can_use === false) {
183 continue;
184 }
185 $ind += $can_use;
186
187 $alg = $this->canKeyBeUsedWithAlgorithm($algorithm, $key);
188 if ($alg === false) {
189 continue;
190 }
191 $ind += $alg;
192
193 if ($this->doesKeySatisfyRestrictions($restrictions, $key) === false) {
194 continue;
195 }
196
197 $result[] = [
198 'key' => $key,
199 'ind' => $ind,
200 ];
201 }
202
203 if (count($result) === 0) {
204 return null;
205 }
206
207 usort($result, [$this, 'sortKeys']);
208
209 return $result[0]['key'];
210 }
211
212 /**
213 * Internal method only. Should not be used.
214 *
215 * @internal
216 */
217 public static function sortKeys(array $a, array $b): int
218 {
219 return $b['ind'] <=> $a['ind'];
220 }
221
222 /**
223 * Internal method only. Should not be used.
224 *
225 * @internal
226 */
227 public function getIterator(): Traversable
228 {
229 return new ArrayIterator($this->keys);
230 }
231
232 private function canKeyBeUsedFor(string $type, JWK $key): bool|int
233 {
234 if ($key->has('use')) {
235 return $type === $key->get('use') ? 1 : false;
236 }
237 if ($key->has('key_ops')) {
238 $key_ops = $key->get('key_ops');
239 if (! is_array($key_ops)) {
240 throw new InvalidArgumentException(
241 'Invalid key parameter "key_ops". Should be a list of key operations'
242 );
243 }
244
245 return $type === self::convertKeyOpsToKeyUse($key_ops) ? 1 : false;
246 }
247
248 return 0;
249 }
250
251 private function canKeyBeUsedWithAlgorithm(?Algorithm $algorithm, JWK $key): bool|int
252 {
253 if ($algorithm === null) {
254 return 0;
255 }
256 if (! in_array($key->get('kty'), $algorithm->allowedKeyTypes(), true)) {
257 return false;
258 }
259 if ($key->has('alg')) {
260 return $algorithm->name() === $key->get('alg') ? 2 : false;
261 }
262
263 return 1;
264 }
265
266 private function doesKeySatisfyRestrictions(array $restrictions, JWK $key): bool
267 {
268 foreach ($restrictions as $k => $v) {
269 if (! $key->has($k) || $v !== $key->get($k)) {
270 return false;
271 }
272 }
273
274 return true;
275 }
276
277 private static function convertKeyOpsToKeyUse(array $key_ops): string
278 {
279 return match (true) {
280 in_array('verify', $key_ops, true), in_array('sign', $key_ops, true) => 'sig',
281 in_array('encrypt', $key_ops, true), in_array('decrypt', $key_ops, true), in_array(
282 'wrapKey',
283 $key_ops,
284 true
285 ), in_array(
286 'unwrapKey',
287 $key_ops,
288 true
289 ), in_array('deriveKey', $key_ops, true), in_array('deriveBits', $key_ops, true) => 'enc',
290 default => throw new InvalidArgumentException(sprintf(
291 'Unsupported key operation value "%s"',
292 implode(', ', $key_ops)
293 )),
294 };
295 }
296 }