Repository navigation
Add read API and signed webhooks - #390
SebastiaanKloos wants to merge 4 commits into
Conversation
|
@Cannonb4ll I just tested it locally and everything seems to be working well. What do you think of this PR? Can we merge it? |
Cannonb4ll
left a comment
There was a problem hiding this comment.
Thanks for this, the API and the signed webhooks are a nice addition. I found a few things that should be fixed before merging. The first five are the important ones, two of them security-related:
- Authorization: Employees can create API tokens and webhooks, which gives access to all private data (
ApiTokenResource,WebhookResource). - SSRF through the webhook URL (
WebhookResource). - Webhook failures break user requests on the default
syncqueue (SendWebhookJob). - Webhooks can't be edited without rotating the secret (
WebhookEndpoint::$hidden). - Item creation sends a burst of events, and
item.createdhas null user/project/board (ItemObserver).
The other comments are about data correctness for API/webhook consumers, plus a few smaller items.
This branch is based on main from before the Filament v5 / Livewire 4 upgrade (#392). Please rebase and rerun the suite. Under Livewire 4, a ModelNotFoundException in component tests becomes a 404 response instead of being thrown.
Nit (CLAUDE.md conventions): app/Http/Kernel.php registers api.token with an inline FQCN, while every other alias in that file uses an import.
| use App\Filament\Resources\ApiTokens\Pages\ListApiTokens; | ||
| use App\Filament\Resources\ApiTokens\Pages\CreateApiToken; | ||
|
|
||
| class ApiTokenResource extends Resource |
There was a problem hiding this comment.
Blocking (security): this resource has no policy, canAccess() or shouldRegisterNavigation() guard. User::canAccessPanel() lets both Admins and Employees in, so an Employee can open Manage > API tokens, create a token and read every private project, item and comment through /api/v1.
The rest of the admin-only area restricts this explicitly. Settings and System check hasRole(UserRole::Admin), and UserPolicy does the same. The README also says "Admins manage webhooks". The tests only log in as an Admin, so nothing covers this.
Suggestion: add an ApiTokenPolicy (and a WebhookEndpointPolicy) that only allows UserRole::Admin, plus a test that an Employee gets a 403.
| use App\Filament\Resources\Webhooks\Pages\ListWebhooks; | ||
| use App\Filament\Resources\Webhooks\Pages\CreateWebhook; | ||
|
|
||
| class WebhookResource extends Resource |
There was a problem hiding this comment.
Blocking (security): same as ApiTokenResource, there's no admin-only guard here. An Employee can add a webhook that points at their own server, subscribe to all events and receive the content of private items and comments.
| ->schema([ | ||
| TextInput::make('url') | ||
| ->label(trans('resources.webhook.url')) | ||
| ->url() |
There was a problem hiding this comment.
Security (SSRF): ->url() only validates the format. SendWebhookJob then POSTs to that URL and follows redirects, so a webhook can target internal addresses: http://169.254.169.254/... (cloud metadata), http://localhost:6379, or a public URL that redirects to an internal one. Every subscribed event would then send signed POSTs with item data to internal services.
Suggestion: require https, resolve the host and reject private/loopback/link-local ranges (both on save and at send time, to cover DNS rebinding), and turn off redirects in the job (->withoutRedirecting()).
| ->withBody($body, 'application/json') | ||
| ->timeout(10) | ||
| ->post($this->endpoint->url) | ||
| ->throw(); |
There was a problem hiding this comment.
Blocking: QUEUE_CONNECTION defaults to sync (config/queue.php and .env.example), so on a default install this job runs inside the model observers. If an endpoint returns a 500 or is unreachable, ->throw() (or the connection timeout) propagates out of the observer. The user then gets a 500 after their item/comment/vote was already saved. In CommentObserver::created the mentions and notifications after the dispatch never run. Each event can also block the request for up to 10 seconds per endpoint, and nothing is retried.
Suggestion: make sure delivery failures can't escape into the user's request. On a real queue, the current ->throw() plus retries is fine. When the connection is sync, dispatch with afterResponse() and catch/log the exception instead. It would also help to document in the README that webhooks need a queue worker.
| 'active', | ||
| ]; | ||
|
|
||
| protected $hidden = ['secret']; |
There was a problem hiding this comment.
Blocking: because secret is in $hidden, the Edit Webhook page never loads it. Filament fills the form from attributesToArray(), which leaves out hidden attributes. The secret field then shows up empty and is ->required(), so an admin who only wants to disable a webhook or add an event can't save without typing a new secret. Typing one silently breaks signature verification for the receiver, and the revealable() field can never show the current value.
Suggestion: fill the secret in EditWebhook::mutateFormDataBeforeFill(), or make it optional on edit and keep the existing value when it's left empty. Only creation is tested right now, so a test for editing would be good too.
| public function handle(): void | ||
| { | ||
| $timestamp = time(); | ||
| $body = json_encode([ |
There was a problem hiding this comment.
Minor hardening: without JSON_THROW_ON_ERROR, a failed json_encode() returns false. The job would then sign "<timestamp>." and POST an empty body that still carries a valid signature, and the delivery counts as successful. That's unlikely given the DB encoding, but json_encode([...], JSON_THROW_ON_ERROR) makes it fail loudly.
|
|
||
| public function created(Comment $comment) | ||
| { | ||
| WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, (new CommentResource($comment))->resolve()); |
There was a problem hiding this comment.
comment.created is dispatched before processMentions() rewrites and saves the content. For a comment like thanks @jane, the webhook sends the raw text. processMentions() then stores the linked markdown with updateQuietly(), which sends no webhook. The receiver keeps the raw version while GET /api/v1/comments returns the linked one, which contradicts the README's "same shape as the API". Moving the dispatch after processMentions() fixes this.
| Storage::disk('public')->delete($originalIconImage); | ||
| } | ||
|
|
||
| WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, (new ProjectResource($project))->resolve()); |
There was a problem hiding this comment.
There's no project.created. When a project is created without a slug, Sluggable's created hook calls save() and this sends project.updated for a project the receiver has never seen. With a slug filled in, nothing is sent at all. Whether a new project shows up therefore depends on an optional form field. Consider adding a project.created event (and project.deleted, see the README comment).
| | `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. |
There was a problem hiding this comment.
This only covers items. Consumers can't detect deleted comments or deleted projects: the API leaves them out, updated_since doesn't show them, and there's no comment.deleted or project.deleted (or comment.updated for edits). Comments are also removed in bulk with query-builder deletes when an item or user is deleted, and those don't fire model events. A mirror built on /api/v1/comments + comment.created would keep deleted comments forever. Either add the missing events or document the limitation.
| */ | ||
| public static function dispatch(WebhookEvent $event, array $data): void | ||
| { | ||
| WebhookEndpoint::query() |
There was a problem hiding this comment.
Performance: every item, comment and project save loads all active endpoints, and the callers build the resource payload first (webhookData() with load('board')), even when no endpoint subscribes to the event. A board change does this twice. Consider exiting early when no endpoint subscribes to the event (filtered in the query or cached), and passing a closure for the payload so it's only built when needed.
8d22246 to
bc2ae11
Compare
|
@Cannonb4ll thanks for the thorough review. Everything is addressed and pushed, and the branch is rebased on the Filament v5 / Livewire 4 Blocking
Other
|
Cannonb4ll
left a comment
There was a problem hiding this comment.
Thanks for working through the first round. I went over it again and found a few new issues, mostly around the transaction/afterCommit approach for item creation. The first five are the important ones:
- Notifications now run inside the new transaction (
Item\Create,Header,CreateItemTool): Slack/Discord jobs can run before the item is committed, and onsynca failing notification rolls back the user's item. - TypeError after commit when the item no longer exists (
ItemObserver::created). - SSRF check still lets some internal ranges through (
SafeWebhookUrl). - Disabled endpoints keep receiving queued deliveries (
SendWebhookJob). project.updatedstill arrives beforeproject.created(ProjectObserver).
The other comments are about JSON responses, the remaining events not waiting for the commit, and some cleanup. The comment on the static WeakMap suggests a simpler way to create items that would make 1, 2 and 5 go away.
Nit (CLAUDE.md conventions): several new inline comments describe simple logic, e.g. // Avoid a write on every request. in AuthenticateApiToken and // Part of the update that is being saved. in ItemObserver. CLAUDE.md prefers PHPDoc and keeps inline comments for complex logic.
| $item = Item::create([ | ||
| ...$formState, | ||
| ]); | ||
| $item = DB::transaction(function () use ($formState) { |
There was a problem hiding this comment.
Blocking: with this transaction, ItemObserver::created runs while the transaction is still open, and it still dispatches SendWebhookForNewItemJob and sends ItemHasBeenCreatedEmail straight away (ItemObserver.php:72-75). None of the queue connections set after_commit.
- On redis/database/sqs, a worker can pick up the job before the commit. Unserializing the
Itemthen throwsModelNotFoundException, so the Slack/Discord notification fails now and then. - On the default
syncqueue, the Slack/Discord HTTP call (WebhookClienthas no timeout) and the SMTP send run inside the transaction. If either one throws, the user's item is rolled back.
The same applies to Header.php:171 and CreateItemTool.php:88. Moving the notifications into the DB::afterCommit() callback in ItemObserver::created fixes both. See also the comment on the static WeakMap: if the item is created in a single save, the transaction isn't needed at all.
| DB::afterCommit(function () use ($item) { | ||
| unset(self::$pendingCreation[$item]); | ||
|
|
||
| WebhookDispatcher::dispatch(WebhookEvent::ItemCreated, fn () => $this->webhookData($item->fresh())); |
There was a problem hiding this comment.
$item->fresh() returns null when the item no longer exists at commit time, and webhookData(Item $item) then throws a TypeError. Example: Item::create() followed by $item->delete() in the same transaction. item.deleted is sent, and then the commit throws.
That exception comes out of DB::transaction() after the data has been committed, so the request returns a 500 for an item that was saved, and a retry by the user creates a duplicate. The same goes for any other exception from the dispatcher in this callback. Consider returning early when fresh() returns null, and reporting exceptions here instead of letting them bubble up.
| * | ||
| * @var WeakMap<Item, true>|null | ||
| */ | ||
| private static ?WeakMap $pendingCreation = null; |
There was a problem hiding this comment.
This keeps request state in a static property, which CLAUDE.md rules out because of Octane: the map lives as long as the worker. If the creating transaction rolls back, the Item instance stays flagged, and later updates on that same instance skip item.updated without any warning.
The underlying cause is that creating an item takes several saves. Sluggable saves the slug inside created (where every attribute still counts as changed), and the creation flows call associate()->save() three times. The WeakMap, the three DB::transaction wrappers, afterCommit + fresh() and the wasRecentlyCreated check in ProjectObserver all work around that. A simpler route:
- pass
user_id,project_idandboard_idtoItem::create()(they're all fillable) - let
App\Traits\Sluggablestore the slug withsaveQuietly()
Then created can dispatch item.created directly with a complete item, and the static state and the transactions can go.
| $addresses = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : (gethostbynamel($host) ?: []); | ||
|
|
||
| foreach ($addresses as $address) { | ||
| if (! filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { |
There was a problem hiding this comment.
Security (SSRF): FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE doesn't cover every internal range. These still pass on PHP 8.5:
100.64.0.0/10: CGNAT, Tailscale, some Kubernetes CNIs, and100.100.100.200(the Alibaba Cloud metadata address)198.18.0.0/15and192.0.0.0/24- NAT64
64:ff9b::/96(64:ff9b::7f00:1maps to127.0.0.1), 6to42002::/16and site-localfec0::/10
So https://100.100.100.200/... or https://[64:ff9b::a9fe:a9fe]/ passes both the check on save and the check on delivery. Consider an explicit list of blocked CIDR ranges on top of the flags; Symfony\Component\HttpFoundation\IpUtils::checkIp() works for this.
| } | ||
| } | ||
|
|
||
| private function deliver(): void |
There was a problem hiding this comment.
deliver() works with the current endpoint, but doesn't check whether it's still active or still subscribed to $this->event. Disabling a misbehaving or compromised endpoint, or unticking an event, doesn't stop jobs that are already queued, including up to 5 retries over about 21 minutes. If the admin changes the URL instead, the pending jobs go to the new URL. Consider returning early when the endpoint is inactive or $this->event is no longer in its events.
| $occurredAt = now()->toIso8601String(); | ||
|
|
||
| $endpoints->each(function (WebhookEndpoint $endpoint) use ($event, $payload, $occurredAt) { | ||
| $pending = SendWebhookJob::dispatch($endpoint, $event->value, $payload, (string) Str::uuid(), $occurredAt); |
There was a problem hiding this comment.
Only item.created waits for the commit. All other events (item.updated, item.status_changed, item.deleted, comment.*, project.*) are dispatched right away. When the change happens inside a transaction that later rolls back, the job is already queued (or registered with afterResponse() on sync), and the receiver gets a signed event for a change that was never saved. Wrapping the body of dispatch() in DB::afterCommit() covers every event and both queue modes: without a transaction it runs immediately, and on a rollback the callback is dropped.
| */ | ||
| public static function dispatch(WebhookEvent $event, Closure $data): void | ||
| { | ||
| $endpoints = WebhookEndpoint::query() |
There was a problem hiding this comment.
Performance follow-up: the payload closure helps, but every item, comment and project create/update/delete still runs select * from webhook_endpoints where active = 1 and filters events in PHP, also on installs without any webhooks. A board move runs it twice, and ItemObserver::updated builds the item payload twice (so load(['board', 'project']) twice). Filtering in the query with whereJsonContains('events', $event->value) or loading the active endpoints once per request (scoped, so it's safe under Octane), and building the item payload once in updated(), would remove most of that.
| return ItemResource::collection( | ||
| Item::query() | ||
| ->with(['board', 'project']) | ||
| ->when($request->date('updated_since')?->setTimezone(config('app.timezone')), fn ($query, $since) => $query->where('updated_at', '>=', $since)) |
There was a problem hiding this comment.
Minor: ItemController, CommentController and ProjectController repeat the same updated_since/per_page validation, this time-zone filter and the paginate(... ?: 50)->withQueryString() chain. A fix to the time-zone handling or the default page size now has to be made in three places. A shared FormRequest plus an updatedSince scope (or a small trait) would keep it in one place.
|
|
||
| protected static ?int $navigationSort = 1400; | ||
|
|
||
| public static function shouldRegisterNavigation(): bool |
There was a problem hiding this comment.
Nit: now that the policy is in place, this override isn't needed. Filament v5's HasNavigation::registerNavigationItems() already returns early when ! static::canAccess(). Same in WebhookResource.php:33.
| } | ||
| } | ||
|
|
||
| public function deleted(Comment $comment) |
There was a problem hiding this comment.
Nit: missing : void return type (CLAUDE.md asks for explicit return types).
Implements POL-353.
/api/v1/{projects,items,comments}with pagination andupdated_since(time zone aware), authenticated with API tokens created in the admin panel (Manage > API tokens). Tokens are not tied to a user; only a SHA-256 hash is stored and the token is shown once. Always answers with JSON.timestamp.body.created_atis the time of the event.syncqueue delivery runs after the response and failures are only logged.Notes:
item.createdis sent once after commit with the complete item, so the item create flows (Livewire\Item\Create,Header,CreateItemTool) now run in a transaction. Follow-up saves during creation do not senditem.updated.item.updated.comment.deleted.main.CommentTestandPasskeyManagementTestfail onmaintoo (ModelNotFoundExceptionunder Livewire 4).