Implement webhook inspector
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Events\WebhookRequestReceived;
|
||||
use App\Models\WebhookEndpoint;
|
||||
use App\Models\WebhookRequest;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
class CaptureWebhookRequestAction
|
||||
{
|
||||
public function handle(WebhookEndpoint $endpoint, Request $request): WebhookRequest
|
||||
{
|
||||
$body = $request->getContent();
|
||||
$bodySize = strlen($body);
|
||||
|
||||
if ($bodySize > (int) config('webhooks.max_body_bytes', 1024 * 1024)) {
|
||||
throw new HttpException(413, 'The webhook request body is too large.');
|
||||
}
|
||||
|
||||
$webhookRequest = DB::transaction(function () use ($endpoint, $request, $body, $bodySize): WebhookRequest {
|
||||
$lockedEndpoint = WebhookEndpoint::query()
|
||||
->whereKey($endpoint->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $lockedEndpoint instanceof WebhookEndpoint || ! $lockedEndpoint->acceptsRequests()) {
|
||||
throw (new ModelNotFoundException)->setModel(WebhookEndpoint::class, [$endpoint->getKey()]);
|
||||
}
|
||||
|
||||
$webhookRequest = WebhookRequest::create([
|
||||
'webhook_endpoint_id' => $lockedEndpoint->getKey(),
|
||||
'method' => Str::upper($request->method()),
|
||||
'request_uri' => $request->getRequestUri(),
|
||||
'headers' => $request->headers->all(),
|
||||
'query_parameters' => $request->query(),
|
||||
'body' => $body,
|
||||
'json_payload' => $this->parseJsonPayload($body, $request->header('Content-Type')),
|
||||
'content_type' => $request->header('Content-Type'),
|
||||
'body_size' => $bodySize,
|
||||
'ip_address' => $request->ip(),
|
||||
'user_agent' => $request->userAgent(),
|
||||
'received_at' => now(),
|
||||
]);
|
||||
|
||||
$lockedEndpoint->forceFill([
|
||||
'last_request_at' => $webhookRequest->received_at,
|
||||
])->save();
|
||||
|
||||
$this->pruneExcessRequests($lockedEndpoint);
|
||||
|
||||
return $webhookRequest;
|
||||
});
|
||||
|
||||
WebhookRequestReceived::dispatch(
|
||||
(string) $endpoint->getKey(),
|
||||
(string) $webhookRequest->getKey(),
|
||||
);
|
||||
|
||||
return $webhookRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function parseJsonPayload(string $body, ?string $contentType): ?array
|
||||
{
|
||||
if ($body === '' || $contentType === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalizedContentType = Str::lower($contentType);
|
||||
|
||||
if (! Str::contains($normalizedContentType, ['application/json', '+json'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$payload = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return is_array($payload) ? $payload : null;
|
||||
}
|
||||
|
||||
private function pruneExcessRequests(WebhookEndpoint $endpoint): void
|
||||
{
|
||||
$requestIds = $endpoint->requests()
|
||||
->select('id')
|
||||
->orderByDesc('received_at')
|
||||
->orderByDesc('id')
|
||||
->skip((int) config('webhooks.max_requests_per_endpoint', 1000))
|
||||
->take(1_000_000_000)
|
||||
->pluck('id');
|
||||
|
||||
if ($requestIds->isNotEmpty()) {
|
||||
WebhookRequest::query()->whereKey($requestIds)->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\WebhookEndpoint;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ConfigureWebhookEndpointAction
|
||||
{
|
||||
/**
|
||||
* @param array<string, string|array<int, string>> $headers
|
||||
*/
|
||||
public function handle(
|
||||
?User $user,
|
||||
WebhookEndpoint $endpoint,
|
||||
int $status,
|
||||
array $headers,
|
||||
string $body,
|
||||
): WebhookEndpoint {
|
||||
Gate::forUser($user)->authorize('update', $endpoint);
|
||||
|
||||
$maxResponseBodyBytes = (int) config('webhooks.max_response_body_bytes', 1024 * 1024);
|
||||
|
||||
if (strlen($body) > $maxResponseBodyBytes) {
|
||||
throw ValidationException::withMessages([
|
||||
'response_body' => "The response body may not exceed {$maxResponseBodyBytes} bytes.",
|
||||
]);
|
||||
}
|
||||
|
||||
Validator::make([
|
||||
'status' => $status,
|
||||
'body' => $body,
|
||||
], [
|
||||
'status' => ['integer', 'between:100,599'],
|
||||
'body' => ['string'],
|
||||
])->validate();
|
||||
|
||||
$this->validateHeaders($headers);
|
||||
|
||||
$endpoint->forceFill([
|
||||
'response_status' => $status,
|
||||
'response_headers' => $headers,
|
||||
'response_body' => $body,
|
||||
])->save();
|
||||
|
||||
return $endpoint->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|array<int, string>> $headers
|
||||
*/
|
||||
private function validateHeaders(array $headers): void
|
||||
{
|
||||
if (count($headers) > 50) {
|
||||
throw ValidationException::withMessages([
|
||||
'response_headers' => 'A maximum of 50 response headers is allowed.',
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ($headers as $name => $value) {
|
||||
if (! is_string($name) || preg_match("/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/", $name) !== 1) {
|
||||
throw ValidationException::withMessages([
|
||||
'response_headers' => 'Every response header name must be a valid HTTP header name.',
|
||||
]);
|
||||
}
|
||||
|
||||
$values = is_array($value) ? $value : [$value];
|
||||
|
||||
foreach ($values as $headerValue) {
|
||||
if (! is_string($headerValue) || preg_match('/[\r\n]/', $headerValue) === 1 || strlen($headerValue) > 8192) {
|
||||
throw ValidationException::withMessages([
|
||||
'response_headers' => 'Response headers must not contain line breaks and may not exceed 8 KiB.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\WebhookEndpoint;
|
||||
|
||||
class CreateAnonymousEndpointAction
|
||||
{
|
||||
public function handle(): WebhookEndpoint
|
||||
{
|
||||
$token = WebhookEndpoint::generateToken();
|
||||
|
||||
return WebhookEndpoint::create([
|
||||
'name' => 'Anonymous test endpoint',
|
||||
'token' => $token,
|
||||
'token_hash' => WebhookEndpoint::tokenHash($token),
|
||||
'is_public' => true,
|
||||
'expires_at' => now()->addDays((int) config('webhooks.anonymous_ttl_days', 7)),
|
||||
'response_headers' => ['Content-Type' => 'application/json'],
|
||||
'response_body' => '{}',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\WebhookEndpoint;
|
||||
|
||||
class CreatePrivateEndpointAction
|
||||
{
|
||||
public function handle(User $user, ?string $name = null): WebhookEndpoint
|
||||
{
|
||||
$token = WebhookEndpoint::generateToken();
|
||||
|
||||
return WebhookEndpoint::create([
|
||||
'user_id' => $user->getKey(),
|
||||
'name' => $name ?: 'Private endpoint',
|
||||
'token' => $token,
|
||||
'token_hash' => WebhookEndpoint::tokenHash($token),
|
||||
'is_public' => false,
|
||||
'expires_at' => null,
|
||||
'response_headers' => ['Content-Type' => 'application/json'],
|
||||
'response_body' => '{}',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\WebhookRequest;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
class DeleteWebhookRequestAction
|
||||
{
|
||||
public function handle(?User $user, WebhookRequest $webhookRequest): void
|
||||
{
|
||||
$webhookRequest->loadMissing('endpoint');
|
||||
Gate::forUser($user)->authorize('delete', $webhookRequest);
|
||||
$webhookRequest->delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions\Fortify;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Laravel\Fortify\Contracts\CreatesNewUsers;
|
||||
|
||||
class CreateNewUser implements CreatesNewUsers
|
||||
{
|
||||
public function create(array $input): User
|
||||
{
|
||||
Validator::make($input, [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users'],
|
||||
'password' => ['required', 'string', 'confirmed', 'min:8'],
|
||||
])->validate();
|
||||
|
||||
return User::create([
|
||||
'name' => $input['name'],
|
||||
'email' => $input['email'],
|
||||
'password' => $input['password'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions\Fortify;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Laravel\Fortify\Contracts\ResetsUserPasswords;
|
||||
|
||||
class ResetUserPassword implements ResetsUserPasswords
|
||||
{
|
||||
public function reset(User $user, array $input): void
|
||||
{
|
||||
Validator::make($input, [
|
||||
'password' => ['required', 'string', 'confirmed', 'min:8'],
|
||||
])->validate();
|
||||
|
||||
$user->forceFill([
|
||||
'password' => $input['password'],
|
||||
])->save();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user