Skip to content

Commit

Permalink
Merge pull request #133 from stackkit/feature/app-engine-header-verif…
Browse files Browse the repository at this point in the history
…ication

Verify authentic Cloud Tasks request to App Engine
  • Loading branch information
marickvantuil authored Feb 13, 2024
2 parents e5a6cb3 + 1065df2 commit eb2b6a0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 33 deletions.
20 changes: 15 additions & 5 deletions src/TaskHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ public function handle(?string $task = null): void

$this->setQueue();

if (empty($this->config['app_engine'])) {
OpenIdVerificator::verify(request()->bearerToken(), $this->config);
}
$this->guard();

$this->handleTask($task);
}
Expand All @@ -75,12 +73,10 @@ private function captureTask($task): array
$validator = validator([
'json' => $task,
'task' => $array,
'name_header' => request()->header('X-CloudTasks-TaskName') ?? request()->header('X-AppEngine-TaskName'),
], [
'json' => 'required|json',
'task' => 'required|array',
'task.data' => 'required|array',
'name_header' => 'required|string',
]);

try {
Expand Down Expand Up @@ -114,6 +110,20 @@ private function setQueue(): void
$this->queue = new CloudTasksQueue($this->config, $this->client);
}

private function guard(): void
{
$appEngine = ! empty($this->config['app_engine']);

if ($appEngine) {
// https://cloud.google.com/tasks/docs/creating-appengine-handlers#reading_task_request_headers
// "If your request handler finds any of the headers listed above, it can trust
// that the request is a Cloud Tasks request."
abort_if(empty(request()->header('X-AppEngine-TaskName')), 404);
} else {
OpenIdVerificator::verify(request()->bearerToken(), $this->config);
}
}

private function handleTask(array $task): void
{
$job = new CloudTasksJob($task, $this->queue);
Expand Down
28 changes: 0 additions & 28 deletions tests/TaskHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,34 +110,6 @@ public function it_returns_responses_for_invalid_payloads(string $payload)
$response->assertJsonValidationErrors('task.data');
}

/**
* @test
* @testWith [true]
* [false]
*/
public function it_validates_headers(bool $withHeaders)
{
// Arrange
$this->withExceptionHandling();

// Act
$response = $this->postJson(
action([TaskHandler::class, 'handle']),
[],
$withHeaders
? [
'X-CloudTasks-Taskname' => 'MyTask',
] : []
);

// Assert
if ($withHeaders) {
$response->assertJsonMissingValidationErrors('name_header');
} else {
$response->assertJsonValidationErrors('name_header');
}
}

/**
* @test
*/
Expand Down

0 comments on commit eb2b6a0

Please sign in to comment.