From 4e3fcc52f49b4177efcb2b66ac8d5fb43ba31760 Mon Sep 17 00:00:00 2001 From: Sebastiaan Kloos Date: Mon, 2 Nov 2026 12:21:43 +0000 Subject: [PATCH 1/4] Add read API and signed webhooks (POL-353) --- README.md | 37 ++++++ app/Enums/WebhookEvent.php | 21 ++++ .../Webhooks/Pages/CreateWebhook.php | 11 ++ .../Resources/Webhooks/Pages/EditWebhook.php | 19 +++ .../Resources/Webhooks/Pages/ListWebhooks.php | 19 +++ .../Resources/Webhooks/WebhookResource.php | 116 ++++++++++++++++++ .../Controllers/Api/V1/CommentController.php | 30 +++++ .../Controllers/Api/V1/ItemController.php | 31 +++++ .../Controllers/Api/V1/ProjectController.php | 28 +++++ app/Http/Kernel.php | 1 + app/Http/Middleware/EnsureApiAccess.php | 22 ++++ app/Http/Resources/Api/V1/CommentResource.php | 28 +++++ app/Http/Resources/Api/V1/ItemResource.php | 36 ++++++ app/Http/Resources/Api/V1/ProjectResource.php | 30 +++++ app/Jobs/SendWebhookJob.php | 64 ++++++++++ app/Models/WebhookEndpoint.php | 29 +++++ app/Observers/CommentObserver.php | 5 + app/Observers/ItemObserver.php | 33 +++++ app/Observers/ProjectObserver.php | 5 + app/Services/WebhookDispatcher.php | 25 ++++ database/factories/WebhookEndpointFactory.php | 25 ++++ ..._121506_create_webhook_endpoints_table.php | 25 ++++ lang/en/nav.php | 1 + lang/en/resources.php | 9 ++ routes/api.php | 10 ++ tests/Feature/Api/ReadApiTest.php | 57 +++++++++ .../Feature/Filament/WebhookResourceTest.php | 30 +++++ .../Feature/Webhooks/WebhookDeliveryTest.php | 91 ++++++++++++++ 28 files changed, 838 insertions(+) create mode 100644 app/Enums/WebhookEvent.php create mode 100644 app/Filament/Resources/Webhooks/Pages/CreateWebhook.php create mode 100644 app/Filament/Resources/Webhooks/Pages/EditWebhook.php create mode 100644 app/Filament/Resources/Webhooks/Pages/ListWebhooks.php create mode 100644 app/Filament/Resources/Webhooks/WebhookResource.php create mode 100644 app/Http/Controllers/Api/V1/CommentController.php create mode 100644 app/Http/Controllers/Api/V1/ItemController.php create mode 100644 app/Http/Controllers/Api/V1/ProjectController.php create mode 100644 app/Http/Middleware/EnsureApiAccess.php create mode 100644 app/Http/Resources/Api/V1/CommentResource.php create mode 100644 app/Http/Resources/Api/V1/ItemResource.php create mode 100644 app/Http/Resources/Api/V1/ProjectResource.php create mode 100644 app/Jobs/SendWebhookJob.php create mode 100644 app/Models/WebhookEndpoint.php create mode 100644 app/Services/WebhookDispatcher.php create mode 100644 database/factories/WebhookEndpointFactory.php create mode 100644 database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php create mode 100644 tests/Feature/Api/ReadApiTest.php create mode 100644 tests/Feature/Filament/WebhookResourceTest.php create mode 100644 tests/Feature/Webhooks/WebhookDeliveryTest.php diff --git a/README.md b/README.md index 26f34161..aa9f9e97 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,43 @@ GET /projects/{project}/items/{item}/ai /projects/1-bugs/items/2-bug-in-sites-overview/ai?format=yml&include[comments]=1 ``` +## Read API and webhooks + +### Read API + +Authenticate with a personal access token (create one under your profile) of an admin or employee user and send it as `Authorization: Bearer `. Private projects, items and comments are included. + +``` +GET /api/v1/projects +GET /api/v1/items?project_id=1 +GET /api/v1/comments?item_id=1 +``` + +| Parameter | Description | +|---|---| +| `updated_since` | Only records updated at or after this date, e.g. `2026-01-01T00:00:00Z` | +| `per_page` | 1-100, defaults to 50 | +| `page` | Page number; responses include `data`, `links` and `meta` | + +Deleted records are not listed, use the `item.deleted` webhook for those. + +### Webhooks + +Admins manage webhooks in the admin panel under **Manage > Webhooks**: a URL, a secret and the events to receive. + +| Event | Sent when | +|---|---| +| `item.created` | an item is created | +| `item.updated` | an item is changed | +| `item.status_changed` | an item moves to another board (adds `previous_board_id`) | +| `item.deleted` | an item is deleted | +| `comment.created` | a comment is placed | +| `project.updated` | a project is changed | + +Requests are `POST` with a JSON body `{"event", "delivery_id", "created_at", "data"}`, where `data` has the same shape as the API resources. They are sent through the queue (make sure a worker is running) and retried up to 5 times with increasing delays when the endpoint does not answer with a 2xx status. + +Verify a request by computing `sha256=` + `HMAC_SHA256(secret, X-Roadmap-Timestamp + "." + raw body)` and comparing it with the `X-Roadmap-Signature` header. Reject requests with an old timestamp to prevent replays. + ## Docker Support ### Getting up and running... diff --git a/app/Enums/WebhookEvent.php b/app/Enums/WebhookEvent.php new file mode 100644 index 00000000..8b9501aa --- /dev/null +++ b/app/Enums/WebhookEvent.php @@ -0,0 +1,21 @@ + + */ + public static function options(): array + { + return collect(self::cases())->mapWithKeys(fn (self $event) => [$event->value => $event->value])->all(); + } +} diff --git a/app/Filament/Resources/Webhooks/Pages/CreateWebhook.php b/app/Filament/Resources/Webhooks/Pages/CreateWebhook.php new file mode 100644 index 00000000..0547c399 --- /dev/null +++ b/app/Filament/Resources/Webhooks/Pages/CreateWebhook.php @@ -0,0 +1,11 @@ +components([ + Section::make() + ->columnSpanFull() + ->schema([ + TextInput::make('url') + ->label(trans('resources.webhook.url')) + ->url() + ->maxLength(2048) + ->required(), + + TextInput::make('secret') + ->label(trans('resources.webhook.secret')) + ->helperText(trans('resources.webhook.secret-helper-text')) + ->password() + ->revealable() + ->default(fn () => Str::random(40)) + ->required(), + + CheckboxList::make('events') + ->label(trans('resources.webhook.events')) + ->options(WebhookEvent::options()) + ->required(), + + Toggle::make('active') + ->label(trans('resources.webhook.active')) + ->default(true), + ]), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('url') + ->label(trans('resources.webhook.url')) + ->searchable(), + TextColumn::make('events') + ->label(trans('resources.webhook.events')) + ->badge(), + IconColumn::make('active') + ->label(trans('resources.webhook.active')) + ->boolean(), + ]) + ->recordActions([ + EditAction::make(), + DeleteAction::make(), + ]) + ->toolbarActions([ + DeleteBulkAction::make(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListWebhooks::route('/'), + 'create' => CreateWebhook::route('/create'), + 'edit' => EditWebhook::route('/{record}/edit'), + ]; + } +} diff --git a/app/Http/Controllers/Api/V1/CommentController.php b/app/Http/Controllers/Api/V1/CommentController.php new file mode 100644 index 00000000..404c6896 --- /dev/null +++ b/app/Http/Controllers/Api/V1/CommentController.php @@ -0,0 +1,30 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'item_id' => ['nullable', 'integer'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return CommentResource::collection( + Comment::query() + ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->integer('item_id'), fn ($query, $itemId) => $query->where('item_id', $itemId)) + ->orderBy('id') + ->paginate($request->integer('per_page', 50)) + ->withQueryString() + ); + } +} diff --git a/app/Http/Controllers/Api/V1/ItemController.php b/app/Http/Controllers/Api/V1/ItemController.php new file mode 100644 index 00000000..b373a0a9 --- /dev/null +++ b/app/Http/Controllers/Api/V1/ItemController.php @@ -0,0 +1,31 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'project_id' => ['nullable', 'integer'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return ItemResource::collection( + Item::query() + ->with('board') + ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->integer('project_id'), fn ($query, $projectId) => $query->where('project_id', $projectId)) + ->orderBy('id') + ->paginate($request->integer('per_page', 50)) + ->withQueryString() + ); + } +} diff --git a/app/Http/Controllers/Api/V1/ProjectController.php b/app/Http/Controllers/Api/V1/ProjectController.php new file mode 100644 index 00000000..5ee47a9d --- /dev/null +++ b/app/Http/Controllers/Api/V1/ProjectController.php @@ -0,0 +1,28 @@ +validate([ + 'updated_since' => ['nullable', 'date'], + 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + + return ProjectResource::collection( + Project::query() + ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->orderBy('id') + ->paginate($request->integer('per_page', 50)) + ->withQueryString() + ); + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 4dc60a2d..2bf9b86c 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -85,6 +85,7 @@ class Kernel extends HttpKernel * @var array */ protected $middlewareAliases = [ + 'api.access' => \App\Http\Middleware\EnsureApiAccess::class, 'auth' => Authenticate::class, 'auth.basic' => AuthenticateWithBasicAuth::class, 'auth.session' => AuthenticateSession::class, diff --git a/app/Http/Middleware/EnsureApiAccess.php b/app/Http/Middleware/EnsureApiAccess.php new file mode 100644 index 00000000..cf559a3f --- /dev/null +++ b/app/Http/Middleware/EnsureApiAccess.php @@ -0,0 +1,22 @@ +user()?->hasAdminAccess(), 403); + + return $next($request); + } +} diff --git a/app/Http/Resources/Api/V1/CommentResource.php b/app/Http/Resources/Api/V1/CommentResource.php new file mode 100644 index 00000000..143c6d62 --- /dev/null +++ b/app/Http/Resources/Api/V1/CommentResource.php @@ -0,0 +1,28 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'item_id' => $this->item_id, + 'parent_id' => $this->parent_id, + 'user_id' => $this->user_id, + 'content' => $this->content, + 'private' => (bool) $this->private, + 'total_votes' => (int) $this->total_votes, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Http/Resources/Api/V1/ItemResource.php b/app/Http/Resources/Api/V1/ItemResource.php new file mode 100644 index 00000000..e502e26d --- /dev/null +++ b/app/Http/Resources/Api/V1/ItemResource.php @@ -0,0 +1,36 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'slug' => $this->slug, + 'title' => $this->title, + 'content' => $this->content, + 'project_id' => $this->project_id, + 'board_id' => $this->board_id, + 'status' => $this->board?->title, + 'user_id' => $this->user_id, + 'private' => (bool) $this->private, + 'pinned' => (bool) $this->pinned, + 'total_votes' => (int) $this->total_votes, + 'issue_number' => $this->issue_number, + 'url' => $this->view_url, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Http/Resources/Api/V1/ProjectResource.php b/app/Http/Resources/Api/V1/ProjectResource.php new file mode 100644 index 00000000..de5ca513 --- /dev/null +++ b/app/Http/Resources/Api/V1/ProjectResource.php @@ -0,0 +1,30 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'slug' => $this->slug, + 'title' => $this->title, + 'group' => $this->group, + 'description' => $this->description, + 'url' => $this->url, + 'repo' => $this->repo, + 'private' => (bool) $this->private, + 'sort_order' => $this->sort_order, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php new file mode 100644 index 00000000..a83dd464 --- /dev/null +++ b/app/Jobs/SendWebhookJob.php @@ -0,0 +1,64 @@ + $data + */ + public function __construct( + public readonly WebhookEndpoint $endpoint, + public readonly string $event, + public readonly array $data, + public readonly string $deliveryId, + ) { + } + + /** + * @return array + */ + public function backoff(): array + { + return [10, 60, 300, 900]; + } + + public function handle(): void + { + $timestamp = time(); + $body = json_encode([ + 'event' => $this->event, + 'delivery_id' => $this->deliveryId, + 'created_at' => now()->toIso8601String(), + 'data' => $this->data, + ]); + + // The signature covers the timestamp too, so receivers can reject replayed requests. + $signature = hash_hmac('sha256', $timestamp . '.' . $body, $this->endpoint->secret); + + Http::withHeaders([ + 'X-Roadmap-Event' => $this->event, + 'X-Roadmap-Delivery' => $this->deliveryId, + 'X-Roadmap-Timestamp' => (string) $timestamp, + 'X-Roadmap-Signature' => 'sha256=' . $signature, + ]) + ->withBody($body, 'application/json') + ->timeout(10) + ->post($this->endpoint->url) + ->throw(); + } +} diff --git a/app/Models/WebhookEndpoint.php b/app/Models/WebhookEndpoint.php new file mode 100644 index 00000000..aa69abc2 --- /dev/null +++ b/app/Models/WebhookEndpoint.php @@ -0,0 +1,29 @@ + 'encrypted', + 'events' => 'array', + 'active' => 'boolean', + ]; + } +} diff --git a/app/Observers/CommentObserver.php b/app/Observers/CommentObserver.php index 86a00c41..0004ca9e 100644 --- a/app/Observers/CommentObserver.php +++ b/app/Observers/CommentObserver.php @@ -4,6 +4,9 @@ use App\Models\User; use App\Models\Comment; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\CommentResource; use App\Services\MentionParser; use App\Notifications\CommentHasReplyNotification; use App\Notifications\Item\ItemHasNewCommentNotification; @@ -22,6 +25,8 @@ public function creating(Comment $comment) public function created(Comment $comment) { + WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, (new CommentResource($comment))->resolve()); + $this->processMentions($comment); $userIds = $comment->item?->votes() diff --git a/app/Observers/ItemObserver.php b/app/Observers/ItemObserver.php index 6d1817b4..e386896a 100644 --- a/app/Observers/ItemObserver.php +++ b/app/Observers/ItemObserver.php @@ -8,6 +8,9 @@ use App\Models\User; use App\Models\Project; use App\Enums\ItemActivity; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\ItemResource; use App\Settings\GeneralSettings; use App\Jobs\SendWebhookForNewItemJob; use Illuminate\Support\Facades\Storage; @@ -20,6 +23,8 @@ public function created(Item $item) { ItemActivity::createForItem($item, ItemActivity::Created); + WebhookDispatcher::dispatch(WebhookEvent::ItemCreated, $this->webhookData($item)); + if ($item->isPrivate()) { return; } @@ -50,9 +55,24 @@ public function created(Item $item) } } + public function deleted(Item $item): void + { + WebhookDispatcher::dispatch(WebhookEvent::ItemDeleted, $this->webhookData($item)); + } + + /** + * @return array + */ + private function webhookData(Item $item): array + { + return (new ItemResource($item->load('board')))->resolve(); + } + public function updating(Item $item) { $isDirty = false; + $changes = array_diff_key($item->getDirty(), array_flip(['updated_at', 'notify_subscribers'])); + $previousBoardId = $item->getOriginal('board_id'); if ($item->isDirty('board_id') && $item->board) { ItemActivity::createForItem($item, ItemActivity::MovedToBoard, [ @@ -109,7 +129,20 @@ public function updating(Item $item) }); } + // This saves the pending changes, so the model is no longer dirty and Eloquent will not fire `updated`. $item->updateQuietly(['notify_subscribers' => true]); + + if ($changes === []) { + return; + } + + WebhookDispatcher::dispatch(WebhookEvent::ItemUpdated, $this->webhookData($item)); + + if (array_key_exists('board_id', $changes)) { + WebhookDispatcher::dispatch(WebhookEvent::ItemStatusChanged, $this->webhookData($item) + [ + 'previous_board_id' => $previousBoardId, + ]); + } } public function deleting(Item $item) diff --git a/app/Observers/ProjectObserver.php b/app/Observers/ProjectObserver.php index c9f1f4cc..1cd6929f 100644 --- a/app/Observers/ProjectObserver.php +++ b/app/Observers/ProjectObserver.php @@ -5,6 +5,9 @@ use Throwable; use App\Models\Board; use App\Models\Project; +use App\Enums\WebhookEvent; +use App\Services\WebhookDispatcher; +use App\Http\Resources\Api\V1\ProjectResource; use Illuminate\Support\Facades\Storage; class ProjectObserver @@ -16,6 +19,8 @@ public function updated(Project $project): void if ($project->wasChanged('icon_image') && $originalIconImage) { Storage::disk('public')->delete($originalIconImage); } + + WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, (new ProjectResource($project))->resolve()); } public function deleting(Project $project) diff --git a/app/Services/WebhookDispatcher.php b/app/Services/WebhookDispatcher.php new file mode 100644 index 00000000..b8b04be3 --- /dev/null +++ b/app/Services/WebhookDispatcher.php @@ -0,0 +1,25 @@ + $data + */ + public static function dispatch(WebhookEvent $event, array $data): void + { + WebhookEndpoint::query() + ->where('active', true) + ->get() + ->filter(fn (WebhookEndpoint $endpoint) => in_array($event->value, $endpoint->events ?? [], true)) + ->each(fn (WebhookEndpoint $endpoint) => SendWebhookJob::dispatch($endpoint, $event->value, $data, (string) Str::uuid())); + } +} diff --git a/database/factories/WebhookEndpointFactory.php b/database/factories/WebhookEndpointFactory.php new file mode 100644 index 00000000..43ca6da7 --- /dev/null +++ b/database/factories/WebhookEndpointFactory.php @@ -0,0 +1,25 @@ + + */ +class WebhookEndpointFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'url' => 'https://example.com/hooks/roadmap', + 'secret' => $this->faker->sha256(), + 'events' => array_column(WebhookEvent::cases(), 'value'), + 'active' => true, + ]; + } +} diff --git a/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php new file mode 100644 index 00000000..3433522d --- /dev/null +++ b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php @@ -0,0 +1,25 @@ +id(); + $table->string('url'); + $table->text('secret'); + $table->json('events'); + $table->boolean('active')->default(true); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('webhook_endpoints'); + } +}; diff --git a/lang/en/nav.php b/lang/en/nav.php index e9259a69..6c150ccf 100644 --- a/lang/en/nav.php +++ b/lang/en/nav.php @@ -11,6 +11,7 @@ 'item' => 'Items', 'project' => 'Projects', 'tags' => 'Tags', + 'webhooks' => 'Webhooks', 'votes' => 'Votes', 'public-view' => 'Public View', 'external' => 'External', diff --git a/lang/en/resources.php b/lang/en/resources.php index b3b89952..ead16c1e 100644 --- a/lang/en/resources.php +++ b/lang/en/resources.php @@ -121,6 +121,15 @@ 'name' => 'Name', 'changelog' => 'Changelog', ], + 'webhook' => [ + 'label' => 'Webhook', + 'label-plural' => 'Webhooks', + 'url' => 'URL', + 'secret' => 'Secret', + 'secret-helper-text' => 'Used to sign every request with an HMAC SHA-256 signature in the X-Roadmap-Signature header.', + 'events' => 'Events', + 'active' => 'Active', + ], 'user' => [ 'label' => 'User', 'label-plural' => 'Users', diff --git a/routes/api.php b/routes/api.php index e165ea47..89aedf3b 100644 --- a/routes/api.php +++ b/routes/api.php @@ -3,6 +3,9 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\WidgetController; +use App\Http\Controllers\Api\V1\ItemController; +use App\Http\Controllers\Api\V1\CommentController; +use App\Http\Controllers\Api\V1\ProjectController; /* |-------------------------------------------------------------------------- @@ -30,3 +33,10 @@ Route::get('/config', [WidgetController::class, 'activityConfig']); Route::get('/activities', [WidgetController::class, 'activityList']); }); + +// Read API (admin and employee tokens) +Route::prefix('v1')->middleware(['auth:sanctum', 'api.access'])->group(function () { + Route::get('/projects', [ProjectController::class, 'index']); + Route::get('/items', [ItemController::class, 'index']); + Route::get('/comments', [CommentController::class, 'index']); +}); diff --git a/tests/Feature/Api/ReadApiTest.php b/tests/Feature/Api/ReadApiTest.php new file mode 100644 index 00000000..b50321fb --- /dev/null +++ b/tests/Feature/Api/ReadApiTest.php @@ -0,0 +1,57 @@ +create(['role' => $role])->createToken('API')->plainTextToken; +} + +it('requires a token', function () { + getJson('/api/v1/items')->assertUnauthorized(); +}); + +it('rejects tokens of regular users', function () { + withToken(apiToken(UserRole::User))->getJson('/api/v1/items')->assertForbidden(); +}); + +it('lists projects, items and comments including private ones', function () { + $project = Project::factory()->private()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $item = Item::factory()->create(['project_id' => $project->id, 'board_id' => $board->id, 'private' => true]); + $comment = Comment::factory()->create(['item_id' => $item->id]); + + $token = apiToken(); + + withToken($token)->getJson('/api/v1/projects')->assertOk()->assertJsonPath('data.0.id', $project->id); + withToken($token)->getJson('/api/v1/items')->assertOk() + ->assertJsonPath('data.0.id', $item->id) + ->assertJsonPath('data.0.status', $board->title) + ->assertJsonPath('data.0.private', true); + withToken($token)->getJson('/api/v1/comments')->assertOk()->assertJsonPath('data.0.id', $comment->id); +}); + +it('paginates and filters on updated_since', function () { + $old = Item::factory()->create(); + $old->forceFill(['updated_at' => now()->subDays(10)])->saveQuietly(); + $new = Item::factory()->create(); + + $response = withToken(apiToken()) + ->getJson('/api/v1/items?per_page=1&updated_since=' . urlencode(now()->subDay()->toIso8601String())) + ->assertOk(); + + expect($response->json('data'))->toHaveCount(1) + ->and($response->json('data.0.id'))->toBe($new->id) + ->and($response->json('meta.total'))->toBe(1); +}); + +it('validates updated_since', function () { + withToken(apiToken())->getJson('/api/v1/items?updated_since=nope')->assertUnprocessable(); +}); diff --git a/tests/Feature/Filament/WebhookResourceTest.php b/tests/Feature/Filament/WebhookResourceTest.php new file mode 100644 index 00000000..187a70e8 --- /dev/null +++ b/tests/Feature/Filament/WebhookResourceTest.php @@ -0,0 +1,30 @@ + UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => 'https://example.com/hook', 'secret' => 'abc123', 'events' => ['item.created']]) + ->call('create') + ->assertHasNoFormErrors(); + + $endpoint = WebhookEndpoint::first(); + + expect($endpoint->url)->toBe('https://example.com/hook') + ->and($endpoint->secret)->toBe('abc123') + ->and($endpoint->events)->toBe(['item.created']); +}); + +it('requires events', function () { + createAndLoginUser(['role' => UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => 'https://example.com/hook', 'secret' => 'abc123', 'events' => []]) + ->call('create') + ->assertHasFormErrors(['events' => 'required']); +}); diff --git a/tests/Feature/Webhooks/WebhookDeliveryTest.php b/tests/Feature/Webhooks/WebhookDeliveryTest.php new file mode 100644 index 00000000..84550f5d --- /dev/null +++ b/tests/Feature/Webhooks/WebhookDeliveryTest.php @@ -0,0 +1,91 @@ +event; + + return true; + }); + + return $events; +} + +it('queues the events an endpoint subscribed to', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['events' => ['item.created', 'item.deleted']]); + + $item = Item::factory()->create(); + $item->update(['title' => 'Changed']); + $item->delete(); + + expect(dispatchedEvents())->toBe(['item.created', 'item.deleted']); +}); + +it('does not queue anything for inactive endpoints', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['active' => false]); + + Item::factory()->create(); + + Bus::assertNotDispatched(SendWebhookJob::class); +}); + +it('queues update, status change, comment and project events', function () { + $project = Project::factory()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $item = Item::factory()->create(['project_id' => $project->id]); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $item->update(['board_id' => $board->id]); + Comment::factory()->create(['item_id' => $item->id]); + $project->update(['title' => 'Renamed']); + + expect(dispatchedEvents())->toEqualCanonicalizing([ + 'item.updated', 'item.status_changed', 'comment.created', 'project.updated', + ]); + + Bus::assertDispatched( + SendWebhookJob::class, + fn (SendWebhookJob $job) => $job->event === 'item.status_changed' && $job->data['board_id'] === $board->id + ); +}); + +it('sends a signed request and retries with backoff', function () { + Http::fake(['example.com/*' => Http::response('', 200)]); + $endpoint = WebhookEndpoint::factory()->create(['secret' => 'top-secret']); + + $job = new SendWebhookJob($endpoint, WebhookEvent::ItemCreated->value, ['id' => 1], 'delivery-1'); + $job->handle(); + + Http::assertSent(function ($request) { + $expected = 'sha256=' . hash_hmac('sha256', $request->header('X-Roadmap-Timestamp')[0] . '.' . $request->body(), 'top-secret'); + + return $request->header('X-Roadmap-Signature')[0] === $expected + && $request->header('X-Roadmap-Event')[0] === 'item.created' + && $request['data'] === ['id' => 1]; + }); + + expect($job->tries)->toBe(5)->and($job->backoff())->toHaveCount(4); +}); + +it('fails the job on a non-2xx response so it is retried', function () { + Http::fake(['example.com/*' => Http::response('', 500)]); + $endpoint = WebhookEndpoint::factory()->create(); + + (new SendWebhookJob($endpoint, 'item.created', [], 'delivery-1'))->handle(); +})->throws(Illuminate\Http\Client\RequestException::class); From a4a3223956233ad63f503ee761aaf3b36914cca7 Mon Sep 17 00:00:00 2001 From: Sebastiaan Kloos Date: Mon, 2 Nov 2026 12:40:31 +0000 Subject: [PATCH 2/4] Use admin-managed API tokens not tied to a user for the read API --- README.md | 2 +- .../Resources/ApiTokens/ApiTokenResource.php | 84 +++++++++++++++++++ .../ApiTokens/Pages/CreateApiToken.php | 38 +++++++++ .../ApiTokens/Pages/ListApiTokens.php | 19 +++++ app/Http/Kernel.php | 2 +- app/Http/Middleware/AuthenticateApiToken.php | 31 +++++++ app/Http/Middleware/EnsureApiAccess.php | 22 ----- app/Models/ApiToken.php | 52 ++++++++++++ database/factories/ApiTokenFactory.php | 22 +++++ ...6_11_02_124013_create_api_tokens_table.php | 24 ++++++ lang/en/nav.php | 1 + lang/en/resources.php | 8 ++ routes/api.php | 4 +- tests/Feature/Api/ReadApiTest.php | 25 ++++-- .../Feature/Filament/ApiTokenResourceTest.php | 21 +++++ 15 files changed, 323 insertions(+), 32 deletions(-) create mode 100644 app/Filament/Resources/ApiTokens/ApiTokenResource.php create mode 100644 app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php create mode 100644 app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php create mode 100644 app/Http/Middleware/AuthenticateApiToken.php delete mode 100644 app/Http/Middleware/EnsureApiAccess.php create mode 100644 app/Models/ApiToken.php create mode 100644 database/factories/ApiTokenFactory.php create mode 100644 database/migrations/2026_11_02_124013_create_api_tokens_table.php create mode 100644 tests/Feature/Filament/ApiTokenResourceTest.php diff --git a/README.md b/README.md index aa9f9e97..87ecf06d 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ GET /projects/{project}/items/{item}/ai ### Read API -Authenticate with a personal access token (create one under your profile) of an admin or employee user and send it as `Authorization: Bearer `. Private projects, items and comments are included. +Create an API token in the admin panel under **Manage > API tokens** (not tied to a user, shown only once) and send it as `Authorization: Bearer `. Private projects, items and comments are included. ``` GET /api/v1/projects diff --git a/app/Filament/Resources/ApiTokens/ApiTokenResource.php b/app/Filament/Resources/ApiTokens/ApiTokenResource.php new file mode 100644 index 00000000..af78278d --- /dev/null +++ b/app/Filament/Resources/ApiTokens/ApiTokenResource.php @@ -0,0 +1,84 @@ +components([ + TextInput::make('name') + ->label(trans('resources.api-token.name')) + ->maxLength(255) + ->required(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('name') + ->label(trans('resources.api-token.name')) + ->searchable(), + TextColumn::make('last_used_at') + ->label(trans('resources.api-token.last-used-at')) + ->since() + ->placeholder('-'), + TextColumn::make('created_at') + ->label(trans('resources.created-at')) + ->dateTime(), + ]) + ->recordActions([ + DeleteAction::make(), + ]) + ->toolbarActions([ + DeleteBulkAction::make(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListApiTokens::route('/'), + 'create' => CreateApiToken::route('/create'), + ]; + } +} diff --git a/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php b/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php new file mode 100644 index 00000000..12675195 --- /dev/null +++ b/app/Filament/Resources/ApiTokens/Pages/CreateApiToken.php @@ -0,0 +1,38 @@ +title(trans('resources.api-token.created-title')) + ->body(trans('resources.api-token.created-body', ['token' => $plainTextToken])) + ->success() + ->persistent() + ->send(); + + return $token; + } + + protected function getCreatedNotification(): ?Notification + { + return null; + } + + protected function getRedirectUrl(): string + { + return static::getResource()::getUrl('index'); + } +} diff --git a/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php b/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php new file mode 100644 index 00000000..a27cdca0 --- /dev/null +++ b/app/Filament/Resources/ApiTokens/Pages/ListApiTokens.php @@ -0,0 +1,19 @@ + */ protected $middlewareAliases = [ - 'api.access' => \App\Http\Middleware\EnsureApiAccess::class, + 'api.token' => \App\Http\Middleware\AuthenticateApiToken::class, 'auth' => Authenticate::class, 'auth.basic' => AuthenticateWithBasicAuth::class, 'auth.session' => AuthenticateSession::class, diff --git a/app/Http/Middleware/AuthenticateApiToken.php b/app/Http/Middleware/AuthenticateApiToken.php new file mode 100644 index 00000000..b09935aa --- /dev/null +++ b/app/Http/Middleware/AuthenticateApiToken.php @@ -0,0 +1,31 @@ +bearerToken(); + $token = $plainTextToken ? ApiToken::findByPlainTextToken($plainTextToken) : null; + + abort_unless($token, 401, 'Unauthenticated.'); + + // Avoid a write on every request. + if (! $token->last_used_at || $token->last_used_at->lt(now()->subMinute())) { + $token->forceFill(['last_used_at' => now()])->saveQuietly(); + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/EnsureApiAccess.php b/app/Http/Middleware/EnsureApiAccess.php deleted file mode 100644 index cf559a3f..00000000 --- a/app/Http/Middleware/EnsureApiAccess.php +++ /dev/null @@ -1,22 +0,0 @@ -user()?->hasAdminAccess(), 403); - - return $next($request); - } -} diff --git a/app/Models/ApiToken.php b/app/Models/ApiToken.php new file mode 100644 index 00000000..7622b7f3 --- /dev/null +++ b/app/Models/ApiToken.php @@ -0,0 +1,52 @@ + 'datetime', + ]; + } + + /** + * Only a hash is stored, so the returned plain text token can be shown once and never again. + * + * @return array{0: self, 1: string} + */ + public static function generate(string $name): array + { + $plainTextToken = 'rm_' . Str::random(40); + + return [ + static::create(['name' => $name, 'token' => static::hash($plainTextToken)]), + $plainTextToken, + ]; + } + + public static function findByPlainTextToken(string $plainTextToken): ?self + { + return static::where('token', static::hash($plainTextToken))->first(); + } + + private static function hash(string $plainTextToken): string + { + return hash('sha256', $plainTextToken); + } +} diff --git a/database/factories/ApiTokenFactory.php b/database/factories/ApiTokenFactory.php new file mode 100644 index 00000000..f33b1d2b --- /dev/null +++ b/database/factories/ApiTokenFactory.php @@ -0,0 +1,22 @@ + + */ +class ApiTokenFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'name' => $this->faker->word(), + 'token' => hash('sha256', $this->faker->unique()->sha256()), + ]; + } +} diff --git a/database/migrations/2026_11_02_124013_create_api_tokens_table.php b/database/migrations/2026_11_02_124013_create_api_tokens_table.php new file mode 100644 index 00000000..3d9a3367 --- /dev/null +++ b/database/migrations/2026_11_02_124013_create_api_tokens_table.php @@ -0,0 +1,24 @@ +id(); + $table->string('name'); + $table->string('token', 64)->unique(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('api_tokens'); + } +}; diff --git a/lang/en/nav.php b/lang/en/nav.php index 6c150ccf..6d138bd8 100644 --- a/lang/en/nav.php +++ b/lang/en/nav.php @@ -12,6 +12,7 @@ 'project' => 'Projects', 'tags' => 'Tags', 'webhooks' => 'Webhooks', + 'api-tokens' => 'API tokens', 'votes' => 'Votes', 'public-view' => 'Public View', 'external' => 'External', diff --git a/lang/en/resources.php b/lang/en/resources.php index ead16c1e..0ba48bb2 100644 --- a/lang/en/resources.php +++ b/lang/en/resources.php @@ -121,6 +121,14 @@ 'name' => 'Name', 'changelog' => 'Changelog', ], + 'api-token' => [ + 'label' => 'API token', + 'label-plural' => 'API tokens', + 'name' => 'Name', + 'last-used-at' => 'Last used', + 'created-title' => 'API token created', + 'created-body' => 'Copy this token now, it will not be shown again: :token', + ], 'webhook' => [ 'label' => 'Webhook', 'label-plural' => 'Webhooks', diff --git a/routes/api.php b/routes/api.php index 89aedf3b..4503ee23 100644 --- a/routes/api.php +++ b/routes/api.php @@ -34,8 +34,8 @@ Route::get('/activities', [WidgetController::class, 'activityList']); }); -// Read API (admin and employee tokens) -Route::prefix('v1')->middleware(['auth:sanctum', 'api.access'])->group(function () { +// Read API (API tokens from the admin panel) +Route::prefix('v1')->middleware('api.token')->group(function () { Route::get('/projects', [ProjectController::class, 'index']); Route::get('/items', [ItemController::class, 'index']); Route::get('/comments', [CommentController::class, 'index']); diff --git a/tests/Feature/Api/ReadApiTest.php b/tests/Feature/Api/ReadApiTest.php index b50321fb..9c1a48ab 100644 --- a/tests/Feature/Api/ReadApiTest.php +++ b/tests/Feature/Api/ReadApiTest.php @@ -1,25 +1,38 @@ create(['role' => $role])->createToken('API')->plainTextToken; + return ApiToken::generate('Polder')[1]; } it('requires a token', function () { getJson('/api/v1/items')->assertUnauthorized(); }); -it('rejects tokens of regular users', function () { - withToken(apiToken(UserRole::User))->getJson('/api/v1/items')->assertForbidden(); +it('rejects an unknown token', function () { + withToken('rm_unknown')->getJson('/api/v1/items')->assertUnauthorized(); +}); + +it('rejects user tokens', function () { + $token = createUser()->createToken('MCP')->plainTextToken; + + withToken($token)->getJson('/api/v1/items')->assertUnauthorized(); +}); + +it('records when a token was last used', function () { + [$apiToken, $plain] = ApiToken::generate('Polder'); + + withToken($plain)->getJson('/api/v1/items')->assertOk(); + + expect($apiToken->refresh()->last_used_at)->not->toBeNull(); }); it('lists projects, items and comments including private ones', function () { diff --git a/tests/Feature/Filament/ApiTokenResourceTest.php b/tests/Feature/Filament/ApiTokenResourceTest.php new file mode 100644 index 00000000..d0f39f21 --- /dev/null +++ b/tests/Feature/Filament/ApiTokenResourceTest.php @@ -0,0 +1,21 @@ + UserRole::Admin]); + + Livewire::test(CreateApiToken::class) + ->fillForm(['name' => 'Polder']) + ->call('create') + ->assertHasNoFormErrors() + ->assertNotified(trans('resources.api-token.created-title')); + + $token = ApiToken::first(); + + expect($token->name)->toBe('Polder') + ->and($token->getAttributes()['token'])->toHaveLength(64); +}); From bc2ae113be3c53337edd70b95382e2977855400e Mon Sep 17 00:00:00 2001 From: Sebastiaan Kloos Date: Tue, 3 Nov 2026 11:37:21 +0100 Subject: [PATCH 3/4] Address review feedback on read API and webhooks --- README.md | 10 +- app/Enums/WebhookEvent.php | 4 + .../Resources/Webhooks/Pages/EditWebhook.php | 8 ++ .../Resources/Webhooks/WebhookResource.php | 2 + .../Controllers/Api/V1/CommentController.php | 4 +- .../Controllers/Api/V1/ItemController.php | 6 +- .../Controllers/Api/V1/ProjectController.php | 4 +- app/Http/Kernel.php | 5 +- app/Http/Middleware/ForceJsonResponse.php | 22 +++++ app/Jobs/SendWebhookJob.php | 32 ++++++- app/Livewire/Header.php | 21 ++-- app/Livewire/Item/Create.php | 19 ++-- app/Mcp/Tools/CreateItemTool.php | 23 +++-- app/Observers/CommentObserver.php | 21 +++- app/Observers/ItemObserver.php | 64 +++++++++---- app/Observers/ProjectObserver.php | 27 +++++- app/Policies/ApiTokenPolicy.php | 13 +++ app/Policies/Concerns/AdminsOnly.php | 47 +++++++++ app/Policies/WebhookEndpointPolicy.php | 13 +++ app/Rules/SafeWebhookUrl.php | 41 ++++++++ app/Services/WebhookDispatcher.php | 28 +++++- database/factories/WebhookEndpointFactory.php | 2 +- ..._121506_create_webhook_endpoints_table.php | 2 +- lang/en/resources.php | 1 + routes/api.php | 2 +- tests/Feature/Api/ReadApiTest.php | 22 +++++ .../Feature/Filament/ApiTokenResourceTest.php | 8 ++ .../Feature/Filament/WebhookResourceTest.php | 36 ++++++- .../Feature/Webhooks/WebhookDeliveryTest.php | 95 ++++++++++++++++++- 29 files changed, 508 insertions(+), 74 deletions(-) create mode 100644 app/Http/Middleware/ForceJsonResponse.php create mode 100644 app/Policies/ApiTokenPolicy.php create mode 100644 app/Policies/Concerns/AdminsOnly.php create mode 100644 app/Policies/WebhookEndpointPolicy.php create mode 100644 app/Rules/SafeWebhookUrl.php diff --git a/README.md b/README.md index 87ecf06d..cdf4d20c 100644 --- a/README.md +++ b/README.md @@ -257,11 +257,11 @@ GET /api/v1/comments?item_id=1 | `per_page` | 1-100, defaults to 50 | | `page` | Page number; responses include `data`, `links` and `meta` | -Deleted records are not listed, use the `item.deleted` webhook for those. +Deleted records are not listed, use the `*.deleted` webhooks for those. `updated_since` accepts a time zone offset. Responses are always JSON. ### Webhooks -Admins manage webhooks in the admin panel under **Manage > Webhooks**: a URL, a secret and the events to receive. +Admins manage webhooks in the admin panel under **Manage > Webhooks**: a URL, a secret and the events to receive. The URL must use `https` and resolve to a public address, redirects are not followed. | Event | Sent when | |---|---| @@ -270,9 +270,13 @@ Admins manage webhooks in the admin panel under **Manage > Webhooks**: a URL, a | `item.status_changed` | an item moves to another board (adds `previous_board_id`) | | `item.deleted` | an item is deleted | | `comment.created` | a comment is placed | +| `comment.updated` | the content or visibility of a comment is changed | +| `comment.deleted` | a comment is deleted | +| `project.created` | a project is created | | `project.updated` | a project is changed | +| `project.deleted` | a project is deleted | -Requests are `POST` with a JSON body `{"event", "delivery_id", "created_at", "data"}`, where `data` has the same shape as the API resources. They are sent through the queue (make sure a worker is running) and retried up to 5 times with increasing delays when the endpoint does not answer with a 2xx status. +Requests are `POST` with a JSON body `{"event", "delivery_id", "created_at", "data"}`, where `data` has the same shape as the API resources. `created_at` is the time the event happened. Changes to the vote count alone do not send `item.updated`. Comments that are removed together with their item or user do not send `comment.deleted`, use `item.deleted` for that. Requests are sent through the queue (make sure a worker is running, with `QUEUE_CONNECTION=sync` they are sent after the response and failures are only logged) and retried up to 5 times with increasing delays when the endpoint does not answer with a 2xx status. Verify a request by computing `sha256=` + `HMAC_SHA256(secret, X-Roadmap-Timestamp + "." + raw body)` and comparing it with the `X-Roadmap-Signature` header. Reject requests with an old timestamp to prevent replays. diff --git a/app/Enums/WebhookEvent.php b/app/Enums/WebhookEvent.php index 8b9501aa..d32cc2ca 100644 --- a/app/Enums/WebhookEvent.php +++ b/app/Enums/WebhookEvent.php @@ -9,7 +9,11 @@ enum WebhookEvent: string case ItemStatusChanged = 'item.status_changed'; case ItemDeleted = 'item.deleted'; case CommentCreated = 'comment.created'; + case CommentUpdated = 'comment.updated'; + case CommentDeleted = 'comment.deleted'; + case ProjectCreated = 'project.created'; case ProjectUpdated = 'project.updated'; + case ProjectDeleted = 'project.deleted'; /** * @return array diff --git a/app/Filament/Resources/Webhooks/Pages/EditWebhook.php b/app/Filament/Resources/Webhooks/Pages/EditWebhook.php index 9ea2f543..09aaa6e2 100644 --- a/app/Filament/Resources/Webhooks/Pages/EditWebhook.php +++ b/app/Filament/Resources/Webhooks/Pages/EditWebhook.php @@ -10,6 +10,14 @@ class EditWebhook extends EditRecord { protected static string $resource = WebhookResource::class; + protected function mutateFormDataBeforeFill(array $data): array + { + // `secret` is hidden on the model, so Filament would otherwise leave the field empty. + $data['secret'] = $this->record->secret; + + return $data; + } + protected function getHeaderActions(): array { return [ diff --git a/app/Filament/Resources/Webhooks/WebhookResource.php b/app/Filament/Resources/Webhooks/WebhookResource.php index 3d2e44a5..018c2f66 100644 --- a/app/Filament/Resources/Webhooks/WebhookResource.php +++ b/app/Filament/Resources/Webhooks/WebhookResource.php @@ -7,6 +7,7 @@ use Filament\Tables\Table; use Filament\Schemas\Schema; use App\Models\WebhookEndpoint; +use App\Rules\SafeWebhookUrl; use Filament\Actions\EditAction; use Filament\Resources\Resource; use Filament\Actions\DeleteAction; @@ -59,6 +60,7 @@ public static function form(Schema $schema): Schema TextInput::make('url') ->label(trans('resources.webhook.url')) ->url() + ->rule(new SafeWebhookUrl()) ->maxLength(2048) ->required(), diff --git a/app/Http/Controllers/Api/V1/CommentController.php b/app/Http/Controllers/Api/V1/CommentController.php index 404c6896..8c87c48e 100644 --- a/app/Http/Controllers/Api/V1/CommentController.php +++ b/app/Http/Controllers/Api/V1/CommentController.php @@ -20,10 +20,10 @@ public function index(Request $request): AnonymousResourceCollection return CommentResource::collection( Comment::query() - ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) ->when($request->integer('item_id'), fn ($query, $itemId) => $query->where('item_id', $itemId)) ->orderBy('id') - ->paginate($request->integer('per_page', 50)) + ->paginate($request->integer('per_page') ?: 50) ->withQueryString() ); } diff --git a/app/Http/Controllers/Api/V1/ItemController.php b/app/Http/Controllers/Api/V1/ItemController.php index b373a0a9..b2521e92 100644 --- a/app/Http/Controllers/Api/V1/ItemController.php +++ b/app/Http/Controllers/Api/V1/ItemController.php @@ -20,11 +20,11 @@ public function index(Request $request): AnonymousResourceCollection return ItemResource::collection( Item::query() - ->with('board') - ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->with(['board', 'project']) + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) ->when($request->integer('project_id'), fn ($query, $projectId) => $query->where('project_id', $projectId)) ->orderBy('id') - ->paginate($request->integer('per_page', 50)) + ->paginate($request->integer('per_page') ?: 50) ->withQueryString() ); } diff --git a/app/Http/Controllers/Api/V1/ProjectController.php b/app/Http/Controllers/Api/V1/ProjectController.php index 5ee47a9d..e3f07fdb 100644 --- a/app/Http/Controllers/Api/V1/ProjectController.php +++ b/app/Http/Controllers/Api/V1/ProjectController.php @@ -19,9 +19,9 @@ public function index(Request $request): AnonymousResourceCollection return ProjectResource::collection( Project::query() - ->when($request->date('updated_since'), fn ($query, $since) => $query->where('updated_at', '>=', $since)) + ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) ->orderBy('id') - ->paginate($request->integer('per_page', 50)) + ->paginate($request->integer('per_page') ?: 50) ->withQueryString() ); } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 60900a88..df4d25e5 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -3,6 +3,8 @@ namespace App\Http; use App\Http\Middleware\Localize; +use App\Http\Middleware\ForceJsonResponse; +use App\Http\Middleware\AuthenticateApiToken; use App\Http\Middleware\TrimStrings; use App\Http\Middleware\Authenticate; use App\Http\Middleware\TrustProxies; @@ -85,7 +87,8 @@ class Kernel extends HttpKernel * @var array */ protected $middlewareAliases = [ - 'api.token' => \App\Http\Middleware\AuthenticateApiToken::class, + 'api.json' => ForceJsonResponse::class, + 'api.token' => AuthenticateApiToken::class, 'auth' => Authenticate::class, 'auth.basic' => AuthenticateWithBasicAuth::class, 'auth.session' => AuthenticateSession::class, diff --git a/app/Http/Middleware/ForceJsonResponse.php b/app/Http/Middleware/ForceJsonResponse.php new file mode 100644 index 00000000..2b357330 --- /dev/null +++ b/app/Http/Middleware/ForceJsonResponse.php @@ -0,0 +1,22 @@ +headers->set('Accept', 'application/json'); + + return $next($request); + } +} diff --git a/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php index a83dd464..826a5412 100644 --- a/app/Jobs/SendWebhookJob.php +++ b/app/Jobs/SendWebhookJob.php @@ -2,6 +2,9 @@ namespace App\Jobs; +use Throwable; +use RuntimeException; +use App\Rules\SafeWebhookUrl; use App\Models\WebhookEndpoint; use Illuminate\Bus\Queueable; use Illuminate\Support\Facades\Http; @@ -26,6 +29,7 @@ public function __construct( public readonly string $event, public readonly array $data, public readonly string $deliveryId, + public readonly string $occurredAt, ) { } @@ -39,17 +43,38 @@ public function backoff(): array public function handle(): void { + try { + $this->deliver(); + } catch (Throwable $exception) { + // Without a real queue there is no retry, and a failing endpoint must not break the request. + if (config('queue.default') !== 'sync') { + throw $exception; + } + + report($exception); + } + } + + private function deliver(): void + { + // Checked again on every attempt, DNS may have changed since the endpoint was saved. + $address = SafeWebhookUrl::resolveAddress($this->endpoint->url) + ?? throw new RuntimeException('The webhook URL is not allowed.'); + $timestamp = time(); $body = json_encode([ 'event' => $this->event, 'delivery_id' => $this->deliveryId, - 'created_at' => now()->toIso8601String(), + 'created_at' => $this->occurredAt, 'data' => $this->data, - ]); + ], JSON_THROW_ON_ERROR); // The signature covers the timestamp too, so receivers can reject replayed requests. $signature = hash_hmac('sha256', $timestamp . '.' . $body, $this->endpoint->secret); + $host = parse_url($this->endpoint->url, PHP_URL_HOST); + $port = parse_url($this->endpoint->url, PHP_URL_PORT) ?: 443; + Http::withHeaders([ 'X-Roadmap-Event' => $this->event, 'X-Roadmap-Delivery' => $this->deliveryId, @@ -57,6 +82,9 @@ public function handle(): void 'X-Roadmap-Signature' => 'sha256=' . $signature, ]) ->withBody($body, 'application/json') + ->withoutRedirecting() + // Connect to the address we just checked, so DNS rebinding cannot swap it afterwards. + ->withOptions(['curl' => [CURLOPT_RESOLVE => ["{$host}:{$port}:{$address}"]]]) ->timeout(10) ->post($this->endpoint->url) ->throw(); diff --git a/app/Livewire/Header.php b/app/Livewire/Header.php index a5577314..9fe7f1aa 100644 --- a/app/Livewire/Header.php +++ b/app/Livewire/Header.php @@ -22,6 +22,7 @@ use App\Filament\Resources\Users\UserResource; use Filament\Forms\Concerns\InteractsWithForms; use Filament\Actions\Concerns\InteractsWithActions; +use Illuminate\Support\Facades\DB; class Header extends Component implements HasForms, HasActions { @@ -167,15 +168,19 @@ public function submitItemAction(): Action return redirect()->route('verification.notice'); } - $item = Item::create([ - 'title' => $data['title'], - 'content' => $data['content'], - 'project_id' => $data['project_id'] ?? null, - 'board_id' => $data['board_id'] ?? null - ]); + $item = DB::transaction(function () use ($data) { + $item = Item::create([ + 'title' => $data['title'], + 'content' => $data['content'], + 'project_id' => $data['project_id'] ?? null, + 'board_id' => $data['board_id'] ?? null + ]); - $item->user()->associate(auth()->user())->save(); - $item->toggleUpvote(); + $item->user()->associate(auth()->user())->save(); + $item->toggleUpvote(); + + return $item; + }); Notification::make('item_created') ->title('Item') diff --git a/app/Livewire/Item/Create.php b/app/Livewire/Item/Create.php index ccba6290..f8785525 100644 --- a/app/Livewire/Item/Create.php +++ b/app/Livewire/Item/Create.php @@ -14,6 +14,7 @@ use Filament\Notifications\Notification; use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Concerns\InteractsWithForms; +use Illuminate\Support\Facades\DB; class Create extends Component implements HasForms { @@ -60,15 +61,19 @@ public function submit() $formState = $this->form->getState(); - $item = Item::create([ - ...$formState, - ]); + $item = DB::transaction(function () use ($formState) { + $item = Item::create([ + ...$formState, + ]); - $item->user()->associate(auth()->user())->save(); - $item->project()->associate($this->project)->save(); - $item->board()->associate($this->board)->save(); + $item->user()->associate(auth()->user())->save(); + $item->project()->associate($this->project)->save(); + $item->board()->associate($this->board)->save(); - $item->toggleUpvote(); + $item->toggleUpvote(); + + return $item; + }); Notification::make('items') ->title('Items') diff --git a/app/Mcp/Tools/CreateItemTool.php b/app/Mcp/Tools/CreateItemTool.php index d5c12d5e..be39c37d 100644 --- a/app/Mcp/Tools/CreateItemTool.php +++ b/app/Mcp/Tools/CreateItemTool.php @@ -13,6 +13,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Illuminate\Contracts\JsonSchema\JsonSchema; use App\Mcp\Tools\Concerns\InteractsWithRoadmap; +use Illuminate\Support\Facades\DB; #[Name('create-item')] #[Description('Create a new roadmap item (feature request, idea or bug), optionally on a board of a project. Admins and employees can create it as a private item, which does not send new item notifications. Available to admins and employees, and to other users when an admin allows it.')] @@ -84,16 +85,20 @@ public function handle(Request $request): Response return Response::error('A board is required, pass the board to create the item on.'); } - $item = Item::create([ - 'title' => $validated['title'], - 'content' => $validated['content'], - 'project_id' => $project?->id, - 'board_id' => $board?->id, - 'private' => $private, - ]); + $item = DB::transaction(function () use ($validated, $project, $board, $private, $user) { + $item = Item::create([ + 'title' => $validated['title'], + 'content' => $validated['content'], + 'project_id' => $project?->id, + 'board_id' => $board?->id, + 'private' => $private, + ]); + + $item->user()->associate($user)->save(); + $item->toggleUpvote($user); - $item->user()->associate($user)->save(); - $item->toggleUpvote($user); + return $item; + }); return Response::json([ 'message' => "Created \"{$item->title}\".", diff --git a/app/Observers/CommentObserver.php b/app/Observers/CommentObserver.php index 0004ca9e..b40dc057 100644 --- a/app/Observers/CommentObserver.php +++ b/app/Observers/CommentObserver.php @@ -25,10 +25,10 @@ public function creating(Comment $comment) public function created(Comment $comment) { - WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, (new CommentResource($comment))->resolve()); - $this->processMentions($comment); + WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, fn () => $this->webhookData($comment)); + $userIds = $comment->item?->votes() ->subscribed() ->where('user_id', '!=', auth()->id()) // Don't get the current user, they obviously already know about the new comment @@ -46,6 +46,23 @@ public function updated(Comment $comment) if ($comment->wasChanged('content')) { $this->processMentions($comment); } + + if ($comment->wasChanged(['content', 'private'])) { + WebhookDispatcher::dispatch(WebhookEvent::CommentUpdated, fn () => $this->webhookData($comment)); + } + } + + public function deleted(Comment $comment) + { + WebhookDispatcher::dispatch(WebhookEvent::CommentDeleted, fn () => $this->webhookData($comment)); + } + + /** + * @return array + */ + private function webhookData(Comment $comment): array + { + return (new CommentResource($comment))->resolve(); } public function deleting(Comment $comment) diff --git a/app/Observers/ItemObserver.php b/app/Observers/ItemObserver.php index e386896a..5c98a7ba 100644 --- a/app/Observers/ItemObserver.php +++ b/app/Observers/ItemObserver.php @@ -4,6 +4,7 @@ use Mail; use Throwable; +use WeakMap; use App\Models\Item; use App\Models\User; use App\Models\Project; @@ -13,17 +14,38 @@ use App\Http\Resources\Api\V1\ItemResource; use App\Settings\GeneralSettings; use App\Jobs\SendWebhookForNewItemJob; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use App\Mail\Admin\ItemHasBeenCreatedEmail; use App\Notifications\Item\ItemUpdatedNotification; class ItemObserver { + /** + * Items that are being created and not committed yet, their follow-up saves must not send `item.updated`. + * Static, because Laravel resolves a new observer instance for every model event. + * + * @var WeakMap|null + */ + private static ?WeakMap $pendingCreation = null; + + public function creating(Item $item): void + { + self::$pendingCreation ??= new WeakMap(); + self::$pendingCreation[$item] = true; + } + public function created(Item $item) { ItemActivity::createForItem($item, ItemActivity::Created); - WebhookDispatcher::dispatch(WebhookEvent::ItemCreated, $this->webhookData($item)); + // Creating an item takes several saves (slug, user, project, board, vote). Wrap them in a transaction + // and the webhook is sent once, with the complete item, after the commit. + DB::afterCommit(function () use ($item) { + unset(self::$pendingCreation[$item]); + + WebhookDispatcher::dispatch(WebhookEvent::ItemCreated, fn () => $this->webhookData($item->fresh())); + }); if ($item->isPrivate()) { return; @@ -57,7 +79,25 @@ public function created(Item $item) public function deleted(Item $item): void { - WebhookDispatcher::dispatch(WebhookEvent::ItemDeleted, $this->webhookData($item)); + WebhookDispatcher::dispatch(WebhookEvent::ItemDeleted, fn () => $this->webhookData($item)); + } + + public function updated(Item $item): void + { + // Vote counts change on every vote, consumers can read them from the API. + $changes = array_diff_key($item->getChanges(), array_flip(['updated_at', 'notify_subscribers', 'total_votes'])); + + if ($changes === [] || isset(self::$pendingCreation[$item])) { + return; + } + + WebhookDispatcher::dispatch(WebhookEvent::ItemUpdated, fn () => $this->webhookData($item)); + + if (array_key_exists('board_id', $changes)) { + WebhookDispatcher::dispatch(WebhookEvent::ItemStatusChanged, fn () => $this->webhookData($item) + [ + 'previous_board_id' => $item->getOriginal('board_id'), + ]); + } } /** @@ -65,14 +105,12 @@ public function deleted(Item $item): void */ private function webhookData(Item $item): array { - return (new ItemResource($item->load('board')))->resolve(); + return (new ItemResource($item->load(['board', 'project'])))->resolve(); } public function updating(Item $item) { $isDirty = false; - $changes = array_diff_key($item->getDirty(), array_flip(['updated_at', 'notify_subscribers'])); - $previousBoardId = $item->getOriginal('board_id'); if ($item->isDirty('board_id') && $item->board) { ItemActivity::createForItem($item, ItemActivity::MovedToBoard, [ @@ -129,20 +167,8 @@ public function updating(Item $item) }); } - // This saves the pending changes, so the model is no longer dirty and Eloquent will not fire `updated`. - $item->updateQuietly(['notify_subscribers' => true]); - - if ($changes === []) { - return; - } - - WebhookDispatcher::dispatch(WebhookEvent::ItemUpdated, $this->webhookData($item)); - - if (array_key_exists('board_id', $changes)) { - WebhookDispatcher::dispatch(WebhookEvent::ItemStatusChanged, $this->webhookData($item) + [ - 'previous_board_id' => $previousBoardId, - ]); - } + // Part of the update that is being saved. + $item->notify_subscribers = true; } public function deleting(Item $item) diff --git a/app/Observers/ProjectObserver.php b/app/Observers/ProjectObserver.php index 1cd6929f..3c526c44 100644 --- a/app/Observers/ProjectObserver.php +++ b/app/Observers/ProjectObserver.php @@ -12,6 +12,11 @@ class ProjectObserver { + public function created(Project $project): void + { + WebhookDispatcher::dispatch(WebhookEvent::ProjectCreated, fn () => $this->webhookData($project)); + } + public function updated(Project $project): void { $originalIconImage = $project->getOriginal('icon_image'); @@ -20,7 +25,27 @@ public function updated(Project $project): void Storage::disk('public')->delete($originalIconImage); } - WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, (new ProjectResource($project))->resolve()); + // The slug that is filled right after creation is part of `project.created`. + $changes = array_keys(array_diff_key($project->getChanges(), ['updated_at' => true])); + + if ($changes === [] || ($project->wasRecentlyCreated && $changes === ['slug'])) { + return; + } + + WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, fn () => $this->webhookData($project)); + } + + public function deleted(Project $project): void + { + WebhookDispatcher::dispatch(WebhookEvent::ProjectDeleted, fn () => $this->webhookData($project)); + } + + /** + * @return array + */ + private function webhookData(Project $project): array + { + return (new ProjectResource($project))->resolve(); } public function deleting(Project $project) diff --git a/app/Policies/ApiTokenPolicy.php b/app/Policies/ApiTokenPolicy.php new file mode 100644 index 00000000..b2d56fad --- /dev/null +++ b/app/Policies/ApiTokenPolicy.php @@ -0,0 +1,13 @@ +isAdmin($user); + } + + public function view(User $user): bool + { + return $this->isAdmin($user); + } + + public function create(User $user): bool + { + return $this->isAdmin($user); + } + + public function update(User $user): bool + { + return $this->isAdmin($user); + } + + public function delete(User $user): bool + { + return $this->isAdmin($user); + } + + public function deleteAny(User $user): bool + { + return $this->isAdmin($user); + } + + private function isAdmin(User $user): bool + { + return $user->hasRole(UserRole::Admin); + } +} diff --git a/app/Policies/WebhookEndpointPolicy.php b/app/Policies/WebhookEndpointPolicy.php new file mode 100644 index 00000000..8bc3a2ce --- /dev/null +++ b/app/Policies/WebhookEndpointPolicy.php @@ -0,0 +1,13 @@ + $data + * The payload is only built when at least one endpoint subscribed. + * + * @param Closure(): array $data */ - public static function dispatch(WebhookEvent $event, array $data): void + public static function dispatch(WebhookEvent $event, Closure $data): void { - WebhookEndpoint::query() + $endpoints = WebhookEndpoint::query() ->where('active', true) ->get() - ->filter(fn (WebhookEndpoint $endpoint) => in_array($event->value, $endpoint->events ?? [], true)) - ->each(fn (WebhookEndpoint $endpoint) => SendWebhookJob::dispatch($endpoint, $event->value, $data, (string) Str::uuid())); + ->filter(fn (WebhookEndpoint $endpoint) => in_array($event->value, $endpoint->events ?? [], true)); + + if ($endpoints->isEmpty()) { + return; + } + + $payload = $data(); + $occurredAt = now()->toIso8601String(); + + $endpoints->each(function (WebhookEndpoint $endpoint) use ($event, $payload, $occurredAt) { + $pending = SendWebhookJob::dispatch($endpoint, $event->value, $payload, (string) Str::uuid(), $occurredAt); + + // On the sync queue delivery would otherwise block the user's request. + if (config('queue.default') === 'sync') { + $pending->afterResponse(); + } + }); } } diff --git a/database/factories/WebhookEndpointFactory.php b/database/factories/WebhookEndpointFactory.php index 43ca6da7..b7f880cd 100644 --- a/database/factories/WebhookEndpointFactory.php +++ b/database/factories/WebhookEndpointFactory.php @@ -16,7 +16,7 @@ class WebhookEndpointFactory extends Factory public function definition(): array { return [ - 'url' => 'https://example.com/hooks/roadmap', + 'url' => 'https://1.1.1.1/hooks/roadmap', 'secret' => $this->faker->sha256(), 'events' => array_column(WebhookEvent::cases(), 'value'), 'active' => true, diff --git a/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php index 3433522d..357a8e97 100644 --- a/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php +++ b/database/migrations/2026_11_02_121506_create_webhook_endpoints_table.php @@ -10,7 +10,7 @@ public function up(): void { Schema::create('webhook_endpoints', function (Blueprint $table) { $table->id(); - $table->string('url'); + $table->string('url', 2048); $table->text('secret'); $table->json('events'); $table->boolean('active')->default(true); diff --git a/lang/en/resources.php b/lang/en/resources.php index 0ba48bb2..864c747a 100644 --- a/lang/en/resources.php +++ b/lang/en/resources.php @@ -133,6 +133,7 @@ 'label' => 'Webhook', 'label-plural' => 'Webhooks', 'url' => 'URL', + 'url-not-allowed' => 'The URL must use https and point to a public address.', 'secret' => 'Secret', 'secret-helper-text' => 'Used to sign every request with an HMAC SHA-256 signature in the X-Roadmap-Signature header.', 'events' => 'Events', diff --git a/routes/api.php b/routes/api.php index 4503ee23..6338232e 100644 --- a/routes/api.php +++ b/routes/api.php @@ -35,7 +35,7 @@ }); // Read API (API tokens from the admin panel) -Route::prefix('v1')->middleware('api.token')->group(function () { +Route::prefix('v1')->middleware(['api.json', 'api.token'])->group(function () { Route::get('/projects', [ProjectController::class, 'index']); Route::get('/items', [ItemController::class, 'index']); Route::get('/comments', [CommentController::class, 'index']); diff --git a/tests/Feature/Api/ReadApiTest.php b/tests/Feature/Api/ReadApiTest.php index 9c1a48ab..63224ec4 100644 --- a/tests/Feature/Api/ReadApiTest.php +++ b/tests/Feature/Api/ReadApiTest.php @@ -68,3 +68,25 @@ function apiToken(): string it('validates updated_since', function () { withToken(apiToken())->getJson('/api/v1/items?updated_since=nope')->assertUnprocessable(); }); + +it('converts the updated_since offset to the app timezone', function () { + $item = Item::factory()->create(); + $item->forceFill(['updated_at' => '2026-11-02 11:00:00'])->saveQuietly(); + + // 12:00+02:00 is 10:00 UTC, so an item updated at 11:00 UTC must be included. + withToken(apiToken()) + ->getJson('/api/v1/items?updated_since=' . urlencode('2026-11-02T12:00:00+02:00')) + ->assertOk() + ->assertJsonCount(1, 'data'); +}); + +it('falls back to the default page size for an empty per_page', function () { + Item::factory()->count(3)->create(); + + withToken(apiToken())->getJson('/api/v1/items?per_page=')->assertOk()->assertJsonPath('meta.per_page', 50); +}); + +it('answers with json errors without an Accept header', function () { + $this->get('/api/v1/items')->assertUnauthorized()->assertJsonPath('message', 'Unauthenticated.'); + $this->withToken(apiToken())->get('/api/v1/items?updated_since=nope')->assertUnprocessable(); +}); diff --git a/tests/Feature/Filament/ApiTokenResourceTest.php b/tests/Feature/Filament/ApiTokenResourceTest.php index d0f39f21..b0f5b74e 100644 --- a/tests/Feature/Filament/ApiTokenResourceTest.php +++ b/tests/Feature/Filament/ApiTokenResourceTest.php @@ -4,6 +4,7 @@ use App\Enums\UserRole; use App\Models\ApiToken; use App\Filament\Resources\ApiTokens\Pages\CreateApiToken; +use App\Filament\Resources\ApiTokens\Pages\ListApiTokens; it('lets admins create an api token that only stores a hash', function () { createAndLoginUser(['role' => UserRole::Admin]); @@ -19,3 +20,10 @@ expect($token->name)->toBe('Polder') ->and($token->getAttributes()['token'])->toHaveLength(64); }); + +it('is not available to employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + Livewire::test(ListApiTokens::class)->assertForbidden(); + Livewire::test(CreateApiToken::class)->assertForbidden(); +}); diff --git a/tests/Feature/Filament/WebhookResourceTest.php b/tests/Feature/Filament/WebhookResourceTest.php index 187a70e8..96334606 100644 --- a/tests/Feature/Filament/WebhookResourceTest.php +++ b/tests/Feature/Filament/WebhookResourceTest.php @@ -4,18 +4,20 @@ use App\Enums\UserRole; use App\Models\WebhookEndpoint; use App\Filament\Resources\Webhooks\Pages\CreateWebhook; +use App\Filament\Resources\Webhooks\Pages\EditWebhook; +use App\Filament\Resources\Webhooks\Pages\ListWebhooks; it('lets admins create a webhook with a secret and events', function () { createAndLoginUser(['role' => UserRole::Admin]); Livewire::test(CreateWebhook::class) - ->fillForm(['url' => 'https://example.com/hook', 'secret' => 'abc123', 'events' => ['item.created']]) + ->fillForm(['url' => 'https://1.1.1.1/hook', 'secret' => 'abc123', 'events' => ['item.created']]) ->call('create') ->assertHasNoFormErrors(); $endpoint = WebhookEndpoint::first(); - expect($endpoint->url)->toBe('https://example.com/hook') + expect($endpoint->url)->toBe('https://1.1.1.1/hook') ->and($endpoint->secret)->toBe('abc123') ->and($endpoint->events)->toBe(['item.created']); }); @@ -24,7 +26,35 @@ createAndLoginUser(['role' => UserRole::Admin]); Livewire::test(CreateWebhook::class) - ->fillForm(['url' => 'https://example.com/hook', 'secret' => 'abc123', 'events' => []]) + ->fillForm(['url' => 'https://1.1.1.1/hook', 'secret' => 'abc123', 'events' => []]) ->call('create') ->assertHasFormErrors(['events' => 'required']); }); + +it('rejects urls that are not https or not public', function (string $url) { + createAndLoginUser(['role' => UserRole::Admin]); + + Livewire::test(CreateWebhook::class) + ->fillForm(['url' => $url, 'secret' => 'abc123', 'events' => ['item.created']]) + ->call('create') + ->assertHasFormErrors(['url']); +})->with(['http://1.1.1.1/hook', 'https://127.0.0.1/hook', 'https://169.254.169.254/latest', 'https://localhost/hook']); + +it('keeps the secret when an admin edits a webhook', function () { + createAndLoginUser(['role' => UserRole::Admin]); + $endpoint = WebhookEndpoint::factory()->create(['secret' => 'abc123']); + + Livewire::test(EditWebhook::class, ['record' => $endpoint->getKey()]) + ->assertSchemaStateSet(['secret' => 'abc123']) + ->fillForm(['active' => false]) + ->call('save') + ->assertHasNoFormErrors(); + + expect($endpoint->refresh()->active)->toBeFalse()->and($endpoint->secret)->toBe('abc123'); +}); + +it('is not available to employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + Livewire::test(ListWebhooks::class)->assertForbidden(); +}); diff --git a/tests/Feature/Webhooks/WebhookDeliveryTest.php b/tests/Feature/Webhooks/WebhookDeliveryTest.php index 84550f5d..7b1995f3 100644 --- a/tests/Feature/Webhooks/WebhookDeliveryTest.php +++ b/tests/Feature/Webhooks/WebhookDeliveryTest.php @@ -7,6 +7,7 @@ use App\Jobs\SendWebhookJob; use App\Enums\WebhookEvent; use App\Models\WebhookEndpoint; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Http; @@ -66,10 +67,10 @@ function dispatchedEvents(): array }); it('sends a signed request and retries with backoff', function () { - Http::fake(['example.com/*' => Http::response('', 200)]); + Http::fake(['1.1.1.1/*' => Http::response('', 200)]); $endpoint = WebhookEndpoint::factory()->create(['secret' => 'top-secret']); - $job = new SendWebhookJob($endpoint, WebhookEvent::ItemCreated->value, ['id' => 1], 'delivery-1'); + $job = new SendWebhookJob($endpoint, WebhookEvent::ItemCreated->value, ['id' => 1], 'delivery-1', now()->toIso8601String()); $job->handle(); Http::assertSent(function ($request) { @@ -84,8 +85,94 @@ function dispatchedEvents(): array }); it('fails the job on a non-2xx response so it is retried', function () { - Http::fake(['example.com/*' => Http::response('', 500)]); + Http::fake(['1.1.1.1/*' => Http::response('', 500)]); $endpoint = WebhookEndpoint::factory()->create(); - (new SendWebhookJob($endpoint, 'item.created', [], 'delivery-1'))->handle(); + config(['queue.default' => 'database']); + + (new SendWebhookJob($endpoint, 'item.created', [], 'delivery-1', now()->toIso8601String()))->handle(); })->throws(Illuminate\Http\Client\RequestException::class); + +it('does not call addresses that are not public', function () { + Http::fake(); + config(['queue.default' => 'database']); + + foreach (['https://127.0.0.1/hook', 'https://169.254.169.254/latest', 'http://1.1.1.1/hook'] as $url) { + $endpoint = WebhookEndpoint::factory()->create(['url' => $url]); + + expect(fn () => (new SendWebhookJob($endpoint, 'item.created', [], 'd', now()->toIso8601String()))->handle()) + ->toThrow(RuntimeException::class); + } + + Http::assertNothingSent(); +}); + +it('does not let a failing endpoint break the request on the sync queue', function () { + Http::fake(['1.1.1.1/*' => Http::response('', 500)]); + $endpoint = WebhookEndpoint::factory()->create(); + + (new SendWebhookJob($endpoint, 'item.created', [], 'd', now()->toIso8601String()))->handle(); + + Http::assertSentCount(1); +}); + +it('sends one complete item.created for an item that is created in a transaction', function () { + $project = Project::factory()->create(); + $board = Board::factory()->create(['project_id' => $project->id]); + $user = createUser(); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + DB::transaction(function () use ($project, $board, $user) { + $item = Item::create(['title' => 'Idea', 'content' => 'Content']); + $item->user()->associate($user)->save(); + $item->project()->associate($project)->save(); + $item->board()->associate($board)->save(); + $item->toggleUpvote($user); + }); + + expect(dispatchedEvents())->toBe(['item.created']); + + Bus::assertDispatched(SendWebhookJob::class, fn (SendWebhookJob $job) => $job->data['user_id'] === $user->id + && $job->data['project_id'] === $project->id + && $job->data['board_id'] === $board->id + && $job->data['total_votes'] === 1); +}); + +it('does not send item.updated for vote count changes', function () { + $item = Item::factory()->create(); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $item->toggleUpvote(createUser()); + + Bus::assertNotDispatched(SendWebhookJob::class); +}); + +it('sends the comment as stored, after mentions are linked', function () { + $jane = createUser(['username' => 'jane']); + + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(['events' => ['comment.created']]); + + $comment = Comment::factory()->create(['content' => 'thanks @jane']); + + Bus::assertDispatched(SendWebhookJob::class, fn (SendWebhookJob $job) => $job->data['content'] === $comment->fresh()->content); +}); + +it('sends project and comment lifecycle events', function () { + Bus::fake([SendWebhookJob::class]); + WebhookEndpoint::factory()->create(); + + $project = Project::factory()->create(); + $comment = Comment::factory()->create(); + $comment->update(['content' => 'Edited']); + $comment->delete(); + $project->delete(); + + expect(dispatchedEvents())->toEqualCanonicalizing([ + 'project.created', 'comment.created', 'comment.updated', 'comment.deleted', 'project.deleted', + ]); +}); From 8387763d3132163b55f46d9b70b1c4891b89c1fa Mon Sep 17 00:00:00 2001 From: Sebastiaan Kloos Date: Tue, 3 Nov 2026 11:48:15 +0100 Subject: [PATCH 4/4] Hide API token and webhook navigation from non-admins --- app/Filament/Resources/ApiTokens/ApiTokenResource.php | 5 +++++ app/Filament/Resources/Webhooks/WebhookResource.php | 5 +++++ tests/Feature/Filament/ApiTokenResourceTest.php | 7 +++++++ tests/Feature/Filament/WebhookResourceTest.php | 7 +++++++ 4 files changed, 24 insertions(+) diff --git a/app/Filament/Resources/ApiTokens/ApiTokenResource.php b/app/Filament/Resources/ApiTokens/ApiTokenResource.php index af78278d..7ec1d99a 100644 --- a/app/Filament/Resources/ApiTokens/ApiTokenResource.php +++ b/app/Filament/Resources/ApiTokens/ApiTokenResource.php @@ -21,6 +21,11 @@ class ApiTokenResource extends Resource protected static ?int $navigationSort = 1400; + public static function shouldRegisterNavigation(): bool + { + return static::canAccess(); + } + public static function getNavigationGroup(): ?string { return trans('nav.manage'); diff --git a/app/Filament/Resources/Webhooks/WebhookResource.php b/app/Filament/Resources/Webhooks/WebhookResource.php index 018c2f66..8c3a33f3 100644 --- a/app/Filament/Resources/Webhooks/WebhookResource.php +++ b/app/Filament/Resources/Webhooks/WebhookResource.php @@ -30,6 +30,11 @@ class WebhookResource extends Resource protected static ?int $navigationSort = 1300; + public static function shouldRegisterNavigation(): bool + { + return static::canAccess(); + } + public static function getNavigationGroup(): ?string { return trans('nav.manage'); diff --git a/tests/Feature/Filament/ApiTokenResourceTest.php b/tests/Feature/Filament/ApiTokenResourceTest.php index b0f5b74e..d0558203 100644 --- a/tests/Feature/Filament/ApiTokenResourceTest.php +++ b/tests/Feature/Filament/ApiTokenResourceTest.php @@ -1,6 +1,7 @@ assertForbidden(); Livewire::test(CreateApiToken::class)->assertForbidden(); }); + +it('hides the navigation item from employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + expect(ApiTokenResource::shouldRegisterNavigation())->toBeFalse(); +}); diff --git a/tests/Feature/Filament/WebhookResourceTest.php b/tests/Feature/Filament/WebhookResourceTest.php index 96334606..47f161bd 100644 --- a/tests/Feature/Filament/WebhookResourceTest.php +++ b/tests/Feature/Filament/WebhookResourceTest.php @@ -1,6 +1,7 @@ assertForbidden(); }); + +it('hides the navigation item from employees', function () { + createAndLoginUser(['role' => UserRole::Employee]); + + expect(WebhookResource::shouldRegisterNavigation())->toBeFalse(); +});