Skip to content

Commit eb2b6a0

Browse files
Merge pull request #133 from stackkit/feature/app-engine-header-verification
Verify authentic Cloud Tasks request to App Engine
2 parents e5a6cb3 + 1065df2 commit eb2b6a0

File tree

2 files changed

+15
-33
lines changed

2 files changed

+15
-33
lines changed

src/TaskHandler.php

+15-5
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,7 @@ public function handle(?string $task = null): void
5050

5151
$this->setQueue();
5252

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

5755
$this->handleTask($task);
5856
}
@@ -75,12 +73,10 @@ private function captureTask($task): array
7573
$validator = validator([
7674
'json' => $task,
7775
'task' => $array,
78-
'name_header' => request()->header('X-CloudTasks-TaskName') ?? request()->header('X-AppEngine-TaskName'),
7976
], [
8077
'json' => 'required|json',
8178
'task' => 'required|array',
8279
'task.data' => 'required|array',
83-
'name_header' => 'required|string',
8480
]);
8581

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

113+
private function guard(): void
114+
{
115+
$appEngine = ! empty($this->config['app_engine']);
116+
117+
if ($appEngine) {
118+
// https://cloud.google.com/tasks/docs/creating-appengine-handlers#reading_task_request_headers
119+
// "If your request handler finds any of the headers listed above, it can trust
120+
// that the request is a Cloud Tasks request."
121+
abort_if(empty(request()->header('X-AppEngine-TaskName')), 404);
122+
} else {
123+
OpenIdVerificator::verify(request()->bearerToken(), $this->config);
124+
}
125+
}
126+
117127
private function handleTask(array $task): void
118128
{
119129
$job = new CloudTasksJob($task, $this->queue);

tests/TaskHandlerTest.php

-28
Original file line numberDiff line numberDiff line change
@@ -110,34 +110,6 @@ public function it_returns_responses_for_invalid_payloads(string $payload)
110110
$response->assertJsonValidationErrors('task.data');
111111
}
112112

113-
/**
114-
* @test
115-
* @testWith [true]
116-
* [false]
117-
*/
118-
public function it_validates_headers(bool $withHeaders)
119-
{
120-
// Arrange
121-
$this->withExceptionHandling();
122-
123-
// Act
124-
$response = $this->postJson(
125-
action([TaskHandler::class, 'handle']),
126-
[],
127-
$withHeaders
128-
? [
129-
'X-CloudTasks-Taskname' => 'MyTask',
130-
] : []
131-
);
132-
133-
// Assert
134-
if ($withHeaders) {
135-
$response->assertJsonMissingValidationErrors('name_header');
136-
} else {
137-
$response->assertJsonValidationErrors('name_header');
138-
}
139-
}
140-
141113
/**
142114
* @test
143115
*/

0 commit comments

Comments
 (0)