-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthorization.php
More file actions
359 lines (318 loc) · 12.2 KB
/
Authorization.php
File metadata and controls
359 lines (318 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
declare(strict_types=1);
/**
* This file is part of php-fast-forward/http-message.
*
* This source file is subject to the license bundled
* with this source code in the file LICENSE.
*
* @link https://github.com/php-fast-forward/http-message
* @copyright Copyright (c) 2025 Felipe Sayão Lobato Abreu <[email protected]>
* @license https://opensource.org/licenses/MIT MIT License
*/
namespace FastForward\Http\Message\Header;
use FastForward\Http\Message\Header\Authorization\ApiKeyCredential;
use FastForward\Http\Message\Header\Authorization\AuthorizationCredential;
use FastForward\Http\Message\Header\Authorization\AwsCredential;
use FastForward\Http\Message\Header\Authorization\BasicCredential;
use FastForward\Http\Message\Header\Authorization\BearerCredential;
use FastForward\Http\Message\Header\Authorization\DigestCredential;
use Psr\Http\Message\RequestInterface;
/**
* Enum Authorization.
*
* Represents supported HTTP `Authorization` header authentication schemes and
* provides helpers to parse raw header values into structured credential
* objects.
*
* The `Authorization` header is used to authenticate a user agent with a
* server, as defined primarily in RFC 7235 and scheme-specific RFCs. This
* utility enum MUST be used in a case-sensitive manner for its enum values
* but MUST treat incoming header names and schemes according to the
* specification of each scheme. Callers SHOULD use the parsing helpers to
* centralize and normalize authentication handling.
*/
enum Authorization: string
{
/**
* A common, non-standard scheme for API key authentication.
*
* This scheme is not defined by an RFC and MAY vary between APIs.
* Implementations using this scheme SHOULD document how the key is
* generated, scoped, and validated.
*/
case ApiKey = 'ApiKey';
/**
* Basic authentication scheme using Base64-encoded "username:password".
*
* Credentials are transmitted in plaintext (after Base64 decoding) and
* therefore MUST only be used over secure transports such as HTTPS.
*
* @see https://datatracker.ietf.org/doc/html/rfc7617
*/
case Basic = 'Basic';
/**
* Bearer token authentication scheme.
*
* Commonly used with OAuth 2.0 access tokens and JWTs. Bearer tokens
* MUST be treated as opaque secrets; any party in possession of a valid
* token MAY use it to obtain access.
*
* @see https://datatracker.ietf.org/doc/html/rfc6750
*/
case Bearer = 'Bearer';
/**
* Digest access authentication scheme.
*
* Uses a challenge-response mechanism to avoid sending passwords in
* cleartext. Implementations SHOULD fully follow the RFC requirements
* to avoid interoperability and security issues.
*
* @see https://datatracker.ietf.org/doc/html/rfc7616
*/
case Digest = 'Digest';
/**
* Amazon Web Services Signature Version 4 scheme.
*
* Used to authenticate requests to AWS services. The credential
* components MUST be constructed according to the AWS Signature Version 4
* process, or validation will fail on the server side.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-requests-v4.html
*/
case Aws = 'AWS4-HMAC-SHA256';
/**
* Parses a raw Authorization header string into a structured credential object.
*
* This method MUST:
* - Split the header into an authentication scheme and a credentials part.
* - Resolve the scheme to a supported enum value.
* - Delegate to the appropriate scheme-specific parser.
*
* If the header is empty, malformed, or uses an unsupported scheme,
* this method MUST return null. Callers SHOULD treat a null result as
* an authentication parsing failure.
*
* @param string $header the raw value of the `Authorization` header
*
* @return null|AuthorizationCredential a credential object on successful parsing, or null on failure
*/
public static function parse(string $header): ?AuthorizationCredential
{
if ('' === $header) {
return null;
}
$parts = explode(' ', $header, 2);
if (2 !== \count($parts)) {
return null;
}
[$scheme, $credentials] = $parts;
$authScheme = self::tryFrom($scheme);
if (null === $authScheme) {
return null;
}
return match ($authScheme) {
self::ApiKey => self::parseApiKey($credentials),
self::Basic => self::parseBasic($credentials),
self::Bearer => self::parseBearer($credentials),
self::Digest => self::parseDigest($credentials),
self::Aws => self::parseAws($credentials),
};
}
/**
* Extracts and parses the Authorization header from a collection of headers.
*
* This method MUST treat header names case-insensitively and SHALL use
* the first `Authorization` value if multiple values are provided. If the
* header is missing or cannot be parsed successfully, it MUST return null.
*
* @param array<string, string|string[]> $headers an associative array of HTTP headers
*
* @return null|AuthorizationCredential a parsed credential object or null if not present or invalid
*/
public static function fromHeaderCollection(array $headers): ?AuthorizationCredential
{
$normalizedHeaders = array_change_key_case($headers, CASE_LOWER);
if (!isset($normalizedHeaders['authorization'])) {
return null;
}
$authHeaderValue = $normalizedHeaders['authorization'];
if (\is_array($authHeaderValue)) {
$authHeaderValue = $authHeaderValue[0];
}
return self::parse($authHeaderValue);
}
/**
* Extracts and parses the Authorization header from a PSR-7 request.
*
* This method SHALL delegate to {@see Authorization::fromHeaderCollection()}
* using the request's header collection. It MUST NOT modify the request.
*
* @param RequestInterface $request the PSR-7 request instance
*
* @return null|AuthorizationCredential a parsed credential object or null if not present or invalid
*/
public static function fromRequest(RequestInterface $request): ?AuthorizationCredential
{
return self::fromHeaderCollection($request->getHeaders());
}
/**
* Parses credentials for the ApiKey authentication scheme.
*
* The complete credential string MUST be treated as the API key. No
* additional structure is assumed or validated here; callers MAY apply
* further validation according to application rules.
*
* @param string $credentials the raw credentials portion of the header
*
* @return ApiKeyCredential the parsed API key credential object
*/
private static function parseApiKey(string $credentials): ApiKeyCredential
{
return new ApiKeyCredential($credentials);
}
/**
* Parses credentials for the Basic authentication scheme.
*
* This method MUST:
* - Base64-decode the credentials.
* - Split the decoded string into `username:password`.
*
* If decoding fails or the decoded value does not contain exactly one
* colon separator, this method MUST return null.
*
* @param string $credentials the Base64-encoded "username:password" string
*
* @return null|BasicCredential the parsed Basic credential, or null on failure
*/
private static function parseBasic(string $credentials): ?BasicCredential
{
$decoded = base64_decode($credentials, true);
if (false === $decoded) {
return null;
}
$parts = explode(':', $decoded, 2);
if (2 !== \count($parts)) {
return null;
}
[$username, $password] = $parts;
return new BasicCredential($username, $password);
}
/**
* Parses credentials for the Bearer authentication scheme.
*
* The credentials MUST be treated as an opaque bearer token. This method
* SHALL NOT attempt to validate or inspect the token contents.
*
* @param string $credentials the bearer token string
*
* @return BearerCredential the parsed Bearer credential object
*/
private static function parseBearer(string $credentials): BearerCredential
{
return new BearerCredential($credentials);
}
/**
* Parses credentials for the Digest authentication scheme.
*
* This method MUST parse comma-separated key=value pairs according to
* RFC 7616. Values MAY be quoted or unquoted. If any part is malformed
* or required parameters are missing, it MUST return null.
*
* Required parameters:
* - username
* - realm
* - nonce
* - uri
* - response
* - qop
* - nc
* - cnonce
*
* Optional parameters such as `opaque` and `algorithm` SHALL be included
* in the credential object when present.
*
* @param string $credentials the raw credentials portion of the header
*
* @return null|DigestCredential the parsed Digest credential object, or null on failure
*/
private static function parseDigest(string $credentials): ?DigestCredential
{
$params = [];
$parts = explode(',', $credentials);
foreach ($parts as $part) {
$part = mb_trim($part);
$pattern = '/^(?<key>[a-zA-Z0-9_-]+)=(?<value>"[^"]*"|[^"]*)$/i';
if (!preg_match($pattern, $part, $match)) {
return null;
}
$key = mb_strtolower($match['key']);
$value = mb_trim($match['value'], '"');
$params[$key] = $value;
}
$required = ['username', 'realm', 'nonce', 'uri', 'response', 'qop', 'nc', 'cnonce'];
foreach ($required as $key) {
if (!isset($params[$key])) {
return null;
}
}
return new DigestCredential(
username: $params['username'],
realm: $params['realm'],
nonce: $params['nonce'],
uri: $params['uri'],
response: $params['response'],
qop: $params['qop'],
nc: $params['nc'],
cnonce: $params['cnonce'],
opaque: $params['opaque'] ?? null,
algorithm: $params['algorithm'] ?? null,
);
}
/**
* Parses credentials for the AWS Signature Version 4 authentication scheme.
*
* This method MUST parse comma-separated key=value pairs and verify that
* the mandatory parameters `Credential`, `SignedHeaders`, and `Signature`
* are present. The `Signature` value MUST be a 64-character hexadecimal
* string. If parsing or validation fails, it MUST return null.
*
* The `Credential` parameter contains the full credential scope in the form
* `AccessKeyId/Date/Region/Service/aws4_request`, which SHALL be stored
* as-is for downstream processing.
*
* @param string $credentials the raw credentials portion of the header
*
* @return null|AwsCredential the parsed AWS credential object, or null on failure
*/
private static function parseAws(string $credentials): ?AwsCredential
{
$params = [];
$parts = explode(',', $credentials);
foreach ($parts as $part) {
$part = mb_trim($part);
$pattern = '/^(?<key>[a-zA-Z0-9_-]+)=(?<value>[^, ]+)$/';
if (!preg_match($pattern, $part, $match)) {
return null;
}
$key = mb_trim($match['key']);
$value = mb_trim($match['value']);
$params[$key] = $value;
}
$required = ['Credential', 'SignedHeaders', 'Signature'];
foreach ($required as $key) {
if (!isset($params[$key])) {
return null;
}
}
if (!preg_match('/^[0-9a-fA-F]{64}$/', $params['Signature'])) {
return null;
}
return new AwsCredential(
algorithm: self::Aws->value,
credentialScope: $params['Credential'],
signedHeaders: $params['SignedHeaders'],
signature: $params['Signature'],
);
}
}