Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Signature/JWSBuilder.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Signature;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\Algorithm;
9 use Jose\Component\Core\AlgorithmManager;
10 use Jose\Component\Core\JWK;
11 use Jose\Component\Core\Util\Base64UrlSafe;
12 use Jose\Component\Core\Util\JsonConverter;
13 use Jose\Component\Core\Util\KeyChecker;
14 use Jose\Component\Signature\Algorithm\MacAlgorithm;
15 use Jose\Component\Signature\Algorithm\SignatureAlgorithm;
16 use LogicException;
17 use RuntimeException;
18 use function array_key_exists;
19 use function count;
20 use function in_array;
21 use function is_array;
22 use function is_string;
23
24 class JWSBuilder
25 {
26 protected ?string $payload = null;
27
28 protected bool $isPayloadDetached = false;
29
30 /**
31 * @var array<array{
32 * header: array<string, mixed>,
33 * protected_header: array<string, mixed>,
34 * signature_key: JWK,
35 * signature_algorithm: Algorithm
36 * }>
37 */
38 protected array $signatures = [];
39
40 protected ?bool $isPayloadEncoded = null;
41
42 public function __construct(
43 private readonly AlgorithmManager $signatureAlgorithmManager
44 ) {
45 }
46
47 /**
48 * Returns the algorithm manager associated to the builder.
49 */
50 public function getSignatureAlgorithmManager(): AlgorithmManager
51 {
52 return $this->signatureAlgorithmManager;
53 }
54
55 /**
56 * Reset the current data.
57 */
58 public function create(): self
59 {
60 $this->payload = null;
61 $this->isPayloadDetached = false;
62 $this->signatures = [];
63 $this->isPayloadEncoded = null;
64
65 return $this;
66 }
67
68 /**
69 * Set the payload. This method will return a new JWSBuilder object.
70 */
71 public function withPayload(string $payload, bool $isPayloadDetached = false): self
72 {
73 $clone = clone $this;
74 $clone->payload = $payload;
75 $clone->isPayloadDetached = $isPayloadDetached;
76
77 return $clone;
78 }
79
80 /**
81 * Adds the information needed to compute the signature. This method will return a new JWSBuilder object.
82 *
83 * @param array<string, mixed> $protectedHeader
84 * @param array<string, mixed> $header
85 */
86 public function addSignature(JWK $signatureKey, array $protectedHeader, array $header = []): self
87 {
88 $this->checkB64AndCriticalHeader($protectedHeader);
89 $isPayloadEncoded = $this->checkIfPayloadIsEncoded($protectedHeader);
90 if ($this->isPayloadEncoded === null) {
91 $this->isPayloadEncoded = $isPayloadEncoded;
92 } elseif ($this->isPayloadEncoded !== $isPayloadEncoded) {
93 throw new InvalidArgumentException('Foreign payload encoding detected.');
94 }
95 $this->checkDuplicatedHeaderParameters($protectedHeader, $header);
96 KeyChecker::checkKeyUsage($signatureKey, 'signature');
97 $algorithm = $this->findSignatureAlgorithm($signatureKey, $protectedHeader, $header);
98 KeyChecker::checkKeyAlgorithm($signatureKey, $algorithm->name());
99 $clone = clone $this;
100 $clone->signatures[] = [
101 'signature_algorithm' => $algorithm,
102 'signature_key' => $signatureKey,
103 'protected_header' => $protectedHeader,
104 'header' => $header,
105 ];
106
107 return $clone;
108 }
109
110 /**
111 * Computes all signatures and return the expected JWS object.
112 */
113 public function build(): JWS
114 {
115 if ($this->payload === null) {
116 throw new RuntimeException('The payload is not set.');
117 }
118 if (count($this->signatures) === 0) {
119 throw new RuntimeException('At least one signature must be set.');
120 }
121
122 $encodedPayload = $this->isPayloadEncoded === false ? $this->payload : Base64UrlSafe::encodeUnpadded(
123 $this->payload
124 );
125
126 if ($this->isPayloadEncoded === false && $this->isPayloadDetached === false) {
127 mb_detect_encoding($this->payload, 'UTF-8', true) !== false || throw new InvalidArgumentException(
128 'The payload must be encoded in UTF-8'
129 );
130 }
131
132 $jws = new JWS($this->payload, $encodedPayload, $this->isPayloadDetached);
133 foreach ($this->signatures as $signature) {
134 /** @var MacAlgorithm|SignatureAlgorithm $algorithm */
135 $algorithm = $signature['signature_algorithm'];
136 /** @var JWK $signatureKey */
137 $signatureKey = $signature['signature_key'];
138 /** @var array<string, mixed> $protectedHeader */
139 $protectedHeader = $signature['protected_header'];
140 /** @var array<string, mixed> $header */
141 $header = $signature['header'];
142 $encodedProtectedHeader = count($protectedHeader) === 0 ? null : Base64UrlSafe::encodeUnpadded(
143 JsonConverter::encode($protectedHeader)
144 );
145 $input = sprintf('%s.%s', $encodedProtectedHeader, $encodedPayload);
146 if ($algorithm instanceof SignatureAlgorithm) {
147 $s = $algorithm->sign($signatureKey, $input);
148 } else {
149 $s = $algorithm->hash($signatureKey, $input);
150 }
151 $jws = $jws->addSignature($s, $protectedHeader, $encodedProtectedHeader, $header);
152 }
153
154 return $jws;
155 }
156
157 /**
158 * @param array<string, mixed> $protectedHeader
159 */
160 private function checkIfPayloadIsEncoded(array $protectedHeader): bool
161 {
162 return ! array_key_exists('b64', $protectedHeader) || $protectedHeader['b64'] === true;
163 }
164
165 /**
166 * @param array<string, mixed> $protectedHeader
167 */
168 private function checkB64AndCriticalHeader(array $protectedHeader): void
169 {
170 if (! array_key_exists('b64', $protectedHeader)) {
171 return;
172 }
173 if (! array_key_exists('crit', $protectedHeader)) {
174 throw new LogicException(
175 'The protected header parameter "crit" is mandatory when protected header parameter "b64" is set.'
176 );
177 }
178 if (! is_array($protectedHeader['crit'])) {
179 throw new LogicException('The protected header parameter "crit" must be an array.');
180 }
181 if (! in_array('b64', $protectedHeader['crit'], true)) {
182 throw new LogicException(
183 'The protected header parameter "crit" must contain "b64" when protected header parameter "b64" is set.'
184 );
185 }
186 }
187
188 /**
189 * @param array<string, mixed> $protectedHeader
190 * @param array<string, mixed> $header
191 * @return MacAlgorithm|SignatureAlgorithm
192 */
193 private function findSignatureAlgorithm(JWK $key, array $protectedHeader, array $header): Algorithm
194 {
195 $completeHeader = [...$header, ...$protectedHeader];
196 $alg = $completeHeader['alg'] ?? null;
197 if (! is_string($alg)) {
198 throw new InvalidArgumentException('No "alg" parameter set in the header.');
199 }
200 $keyAlg = $key->has('alg') ? $key->get('alg') : null;
201 if (is_string($keyAlg) && $keyAlg !== $alg) {
202 throw new InvalidArgumentException(sprintf('The algorithm "%s" is not allowed with this key.', $alg));
203 }
204
205 $algorithm = $this->signatureAlgorithmManager->get($alg);
206 if (! $algorithm instanceof SignatureAlgorithm && ! $algorithm instanceof MacAlgorithm) {
207 throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported.', $alg));
208 }
209
210 return $algorithm;
211 }
212
213 /**
214 * @param array<string, mixed> $header1
215 * @param array<string, mixed> $header2
216 */
217 private function checkDuplicatedHeaderParameters(array $header1, array $header2): void
218 {
219 $inter = array_intersect_key($header1, $header2);
220 if (count($inter) !== 0) {
221 throw new InvalidArgumentException(sprintf(
222 'The header contains duplicated entries: %s.',
223 implode(', ', array_keys($inter))
224 ));
225 }
226 }
227 }