diff --git a/src/TaskHandler.php b/src/TaskHandler.php index 8d3a40e..f8786ec 100644 --- a/src/TaskHandler.php +++ b/src/TaskHandler.php @@ -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); } @@ -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 { @@ -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); diff --git a/tests/TaskHandlerTest.php b/tests/TaskHandlerTest.php index b100da6..089ba4e 100644 --- a/tests/TaskHandlerTest.php +++ b/tests/TaskHandlerTest.php @@ -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 */