Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change content type check and add basic auth support #1325

Merged
merged 18 commits into from
Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 44 additions & 10 deletions src/Event/Http/Psr7Bridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,33 @@ final class Psr7Bridge
*/
public static function convertRequest(HttpRequestEvent $event, Context $context): ServerRequestInterface
{
$headers = $event->getHeaders();

[$files, $parsedBody] = self::parseBodyAndUploadedFiles($event);
[$user, $password] = self::parseBasicAuthorization($headers);

$server = [
'SERVER_PROTOCOL' => $event->getProtocolVersion(),
$server = array_filter([
'CONTENT_LENGTH' => $headers['content-length'][0] ?? null,
'CONTENT_TYPE' => $event->getContentType(),
'DOCUMENT_ROOT' => getcwd(),
'QUERY_STRING' => $event->getQueryString(),
'REQUEST_METHOD' => $event->getMethod(),
mnapoli marked this conversation as resolved.
Show resolved Hide resolved
'SERVER_NAME' => $event->getServerName(),
'SERVER_PORT' => $event->getServerPort(),
'SERVER_PROTOCOL' => $event->getProtocol(),
georgeboot marked this conversation as resolved.
Show resolved Hide resolved
'PATH_INFO' => $event->getPath(),
'HTTP_HOST' => $headers['host'] ?? null,
'REMOTE_ADDR' => $event->getSourceIp(),
'REMOTE_PORT' => $event->getRemotePort(),
'REQUEST_TIME' => time(),
'REQUEST_TIME_FLOAT' => microtime(true),
'QUERY_STRING' => $event->getQueryString(),
'DOCUMENT_ROOT' => getcwd(),
'REQUEST_URI' => $event->getUri(),
'REMOTE_ADDR' => $event->getSourceIp(),
];
'PHP_AUTH_USER' => $user,
'PHP_AUTH_PW' => $password,
], fn ($value) => ! is_null($value));
mnapoli marked this conversation as resolved.
Show resolved Hide resolved

$headers = $event->getHeaders();
if (isset($headers['Host'])) {
$server['HTTP_HOST'] = $headers['Host'];
foreach ($headers as $name => $values) {
$server['HTTP_' . strtoupper(str_replace('-', '_', $name))] = $values[0];
}
mnapoli marked this conversation as resolved.
Show resolved Hide resolved

/**
Expand Down Expand Up @@ -87,7 +98,7 @@ private static function parseBodyAndUploadedFiles(HttpRequestEvent $event): arra
$parsedBody = null;
$contentType = $event->getContentType();
if ($contentType !== null && $event->getMethod() === 'POST') {
if ($contentType === 'application/x-www-form-urlencoded') {
if (substr($contentType, 0, 33) === 'application/x-www-form-urlencoded') {
georgeboot marked this conversation as resolved.
Show resolved Hide resolved
parse_str($bodyString, $parsedBody);
} else {
$document = new Part("Content-type: $contentType\r\n\r\n" . $bodyString);
Expand Down Expand Up @@ -157,4 +168,27 @@ private static function parseKeyAndInsertValueInArray(array &$array, string $key

$pointer = $value;
}

/**
* Parse the username and password from the `Authorization` header.
* Only "Basic" is supported for now.
*
* @return array{string, string}|array{null, null}
*/
protected static function parseBasicAuthorization(array $headers): array
{
$authorization = trim($headers['authorization'][0] ?? '');
mnapoli marked this conversation as resolved.
Show resolved Hide resolved

if (! str_starts_with($authorization, 'Basic ')) {
return [null, null];
}

$auth = base64_decode(trim(explode(' ', $authorization)[1]));

if (! $auth || ! strpos($auth, ':')) {
return [null, null];
}

return explode(':', $auth, 2);
}
}
53 changes: 53 additions & 0 deletions tests/Event/Http/Fixture/ag-v1-body-base64-utf8.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"version": "1.0",
"resource": "/path",
"path": "/path",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Cache-Control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Host": "example.org",
"User-Agent": "PostmanRuntime/7.20.1",
"X-Amzn-Trace-Id": "Root=1-ffffffff-ffffffffffffffffffffffff",
"X-Forwarded-For": "1.1.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"resourceId": "xxxxxx",
"resourcePath": "/path",
"httpMethod": "PUT",
"extendedRequestId": "XXXXXX-xxxxxxxx=",
"requestTime": "24/Nov/2019:18:55:08 +0000",
"path": "/path",
"accountId": "123400000000",
"protocol": "HTTP/1.1",
"stage": "dev",
"domainPrefix": "dev",
"requestTimeEpoch": 1574621708700,
"requestId": "ffffffff-ffff-4fff-ffff-ffffffffffff",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"sourceIp": "1.1.1.1",
"principalOrgId": null,
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "PostmanRuntime/7.20.1",
"user": null
},
"domainName": "example.org",
"apiId": "xxxxxxxxxx"
},
"body": "Zm9vPWJhcg==",
"isBase64Encoded": true
}
54 changes: 54 additions & 0 deletions tests/Event/Http/Fixture/ag-v1-header-basic-auth.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"version": "1.0",
"resource": "/path",
"path": "/path",
"httpMethod": "GET",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Basic ZmFrZTpzZWNyZXQ=",
"Cache-Control": "no-cache",
"Host": "example.org",
"User-Agent": "PostmanRuntime/7.20.1",
"X-Amzn-Trace-Id": "Root=1-ffffffff-ffffffffffffffffffffffff",
"X-Forwarded-For": "1.1.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-My-Header": "Hello world"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"resourceId": "xxxxxx",
"resourcePath": "/path",
"httpMethod": "PUT",
"extendedRequestId": "XXXXXX-xxxxxxxx=",
"requestTime": "24/Nov/2019:18:55:08 +0000",
"path": "/path",
"accountId": "123400000000",
"protocol": "HTTP/1.1",
"stage": "dev",
"domainPrefix": "dev",
"requestTimeEpoch": 1574621708700,
"requestId": "ffffffff-ffff-4fff-ffff-ffffffffffff",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"sourceIp": "1.1.1.1",
"principalOrgId": null,
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "PostmanRuntime/7.20.1",
"user": null
},
"domainName": "example.org",
"apiId": "xxxxxxxxxx"
},
"body": "",
"isBase64Encoded": false
}
20 changes: 19 additions & 1 deletion tests/Event/Http/Psr7BridgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ public function test I can create a response from a PSR7 response()
], $response->toApiGatewayFormat());
}

public function test request with basic auth contains a user and password()
georgeboot marked this conversation as resolved.
Show resolved Hide resolved
{
$this->fromFixture(__DIR__ . '/Fixture/ag-v1-header-basic-auth.json');

$this->assertEquals('fake', $this->request->getServerParams()['PHP_AUTH_USER']);
$this->assertEquals('secret', $this->request->getServerParams()['PHP_AUTH_PW']);
}

public function test multipart form content type can have a suffix()
{
$this->fromFixture(__DIR__ . '/Fixture/ag-v1-body-base64-utf8.json');

$this->assertContentType('application/x-www-form-urlencoded;charset=UTF-8');
$this->assertParsedBody([
'foo' => 'bar',
]);
}

protected function fromFixture(string $file): void
{
$event = new HttpRequestEvent(json_decode(file_get_contents($file), true));
Expand Down Expand Up @@ -83,12 +101,12 @@ protected function assertQueryParameters(array $expected): void
protected function assertProtocol(string $expected): void
{
$this->assertEquals($expected, 'HTTP/' . $this->request->getProtocolVersion());
$this->assertEquals($expected, $this->request->getServerParams()['SERVER_PROTOCOL']);
}

protected function assertProtocolVersion(string $expected): void
{
$this->assertEquals($expected, $this->request->getProtocolVersion());
$this->assertEquals($expected, $this->request->getServerParams()['SERVER_PROTOCOL']);
}

protected function assertHeader(string $header, array $expectedValue): void
Expand Down