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

Add pre-firewall request body validation #98

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions src/Routing/RouteContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ final class RouteContext

public const REQUEST_VALIDATE_QUERY_PARAMETERS = 'request_validate_query_parameters';

public const REQUEST_VALIDATE_BEFORE_FIREWALL = 'request_validate_before_firewall';

public const DESERIALIZATION_OBJECT = 'deserialization_object';

public const DESERIALIZATION_OBJECT_ARGUMENT_NAME = 'deserialization_object_argument_name';
Expand Down
2 changes: 2 additions & 0 deletions src/Routing/RouteLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ private function parseOpenapiBundleSpecificationExtension(stdClass $operation, a
$defaults['_controller'] = $operation->{'x-openapi-bundle'}->controller;
}

$openapiRouteContext[RouteContext::REQUEST_VALIDATE_BEFORE_FIREWALL] = $operation->{'x-openapi-bundle'}->validateBeforeFirewall ?? false;

if (isset($operation->{'x-openapi-bundle'}->deserializationObject)) {
$openapiRouteContext[RouteContext::DESERIALIZATION_OBJECT] = $operation->{'x-openapi-bundle'}->deserializationObject;
}
Expand Down
18 changes: 18 additions & 0 deletions src/Validation/EventSubscriber/RequestValidationSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['validateRequestBeforeFirewall', 10],
['validateRequest', 7],
],
];
Expand All @@ -47,6 +48,16 @@ public function __construct(ValidatorInterface $requestValidator)
$this->requestValidator = $requestValidator;
}

public function validateRequestBeforeFirewall(RequestEvent $event): void
{
$request = $event->getRequest();
if ($this->isManagedRoute($request) === false || $this->isPreFirewallRequestValidationEnabled($request) === false) {
return;
}

$this->validateRequest($event);
}

public function validateRequest(RequestEvent $event): void
{
$request = $event->getRequest();
Expand All @@ -64,4 +75,11 @@ private function isManagedRoute(Request $request): bool
{
return $request->attributes->has(RouteContext::REQUEST_ATTRIBUTE);
}

private function isPreFirewallRequestValidationEnabled(Request $request): bool
{
$routeContext = $request->attributes->get(RouteContext::REQUEST_ATTRIBUTE);

return $routeContext[RouteContext::REQUEST_VALIDATE_BEFORE_FIREWALL] ?? false;
}
}
4 changes: 2 additions & 2 deletions tests/Functional/App/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ security:

firewalls:
main:
pattern: '^/api/authenticated'
pattern: '^/api/(authenticate|authenticated)'
lazy: true
stateless: true
provider: users_in_memory
json_login:
check_path: "/api/authenticated"
check_path: "/api/authenticate"
username_path: email
password_path: password

Expand Down
28 changes: 28 additions & 0 deletions tests/Functional/App/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,34 @@ paths:
type: integer
format: int64

/authenticate:
post:
operationId: authenticate
summary: Authenticate a user
x-openapi-bundle:
validateBeforeFirewall: true
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
password:
type: string
required:
- username
- password
responses:
'204':
description: Successfully authenticated the user.
'401':
description: Invalid username/password supplied.
tags:
- pet

/authenticated/pets:
post:
x-openapi-bundle:
Expand Down
39 changes: 39 additions & 0 deletions tests/Functional/Validation/JsonRequestBodyValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,45 @@ public function testCanReturnProblemDetailsJsonObjectForInvalidRequestBody(): vo
);
}

public function testCanReturnProblemDetailsJsonObjectForInvalidRequestBodyBeforeFirewall(): void
{
$this->client->request(
Request::METHOD_POST,
'/api/authenticate',
[],
[],
[
'CONTENT_TYPE' => 'application/json',
],
'{}'
);

$expectedJsonResponseBody = [
'type' => 'about:blank',
'title' => 'The request body contains errors.',
'status' => 400,
'detail' => 'Validation of JSON request body failed.',
'violations' => [
[
'constraint' => 'required',
'message' => 'The property username is required',
'property' => 'username',
],
[
'constraint' => 'required',
'message' => 'The property password is required',
'property' => 'password',
],
],
];

static::assertResponseStatusCodeSame(Response::HTTP_BAD_REQUEST);
static::assertJsonStringEqualsJsonString(
json_encode($expectedJsonResponseBody),
$this->client->getResponse()->getContent()
);
}

public function testCannotReturnProblemDetailsJsonObjectWithoutRequiredRequestBody(): void
{
$this->client->request(
Expand Down
2 changes: 2 additions & 0 deletions tests/Routing/RouteLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public function testCanLoadRoutesWithRouteContextForRequestParameterValidation()
static::assertEquals(
[
RouteContext::RESOURCE => __DIR__.'/../Resources/specifications/route-loader-request-validation.yaml',
RouteContext::REQUEST_VALIDATE_BEFORE_FIREWALL => false,
RouteContext::REQUEST_BODY_REQUIRED => false,
RouteContext::REQUEST_ALLOWED_CONTENT_TYPES => [],
RouteContext::REQUEST_VALIDATE_QUERY_PARAMETERS => [
Expand All @@ -155,6 +156,7 @@ public function testCanLoadRoutesWithRouteContextForRequestBodyValidation(): voi
static::assertSame(
[
RouteContext::RESOURCE => __DIR__.'/../Resources/specifications/route-loader-request-validation.yaml',
RouteContext::REQUEST_VALIDATE_BEFORE_FIREWALL => false,
RouteContext::REQUEST_BODY_REQUIRED => false,
RouteContext::REQUEST_ALLOWED_CONTENT_TYPES => ['application/json'],
RouteContext::REQUEST_VALIDATE_QUERY_PARAMETERS => [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function testCanReturnSubscribedEvents(): void
$this->assertSame(
[
KernelEvents::REQUEST => [
['validateRequestBeforeFirewall', 10],
['validateRequest', 7],
],
],
Expand Down
Loading