Skip to content

Add read API and signed webhooks - #390

Open
SebastiaanKloos wants to merge 4 commits into
mainfrom
pol-353-fase-2-ploi-roadmap-api-en-ondertekende-webhooks
Open

SebastiaanKloos wants to merge 4 commits into
mainfrom
pol-353-fase-2-ploi-roadmap-api-en-ondertekende-webhooks

Conversation

@SebastiaanKloos

@SebastiaanKloos SebastiaanKloos commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Implements POL-353.

  • Read API /api/v1/{projects,items,comments} with pagination and updated_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.
  • Webhook endpoints managed in Filament (URL, secret, events). API tokens and webhooks are admin-only (policies).
  • Events: item created/updated/status_changed/deleted, comment created/updated/deleted, project created/updated/deleted.
  • Delivered via queue, 5 tries with backoff, HMAC-SHA256 signature over timestamp.body. created_at is the time of the event.
  • Webhook URLs must be https and public (checked on save and on every delivery, connection pinned to the checked IP, no redirects).
  • On the sync queue delivery runs after the response and failures are only logged.
  • Tests and README docs.

Notes:

  • item.created is 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 send item.updated.
  • Vote count changes alone do not send item.updated.
  • Comments deleted in bulk with their item or user do not send comment.deleted.
  • Rebased on the Filament v5 / Livewire 4 main. CommentTest and PasskeyManagementTest fail on main too (ModelNotFoundException under Livewire 4).

@SebastiaanKloos
SebastiaanKloos marked this pull request as draft November 2, 2026 12:24
@SebastiaanKloos SebastiaanKloos changed the title Add read API and signed webhooks (POL-353) Add read API and signed webhooks Nov 2, 2026
@SebastiaanKloos
SebastiaanKloos marked this pull request as ready for review November 2, 2026 12:50
@SebastiaanKloos

Copy link
Copy Markdown
Collaborator Author

@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 Cannonb4ll left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Authorization: Employees can create API tokens and webhooks, which gives access to all private data (ApiTokenResource, WebhookResource).
  2. SSRF through the webhook URL (WebhookResource).
  3. Webhook failures break user requests on the default sync queue (SendWebhookJob).
  4. Webhooks can't be edited without rotating the secret (WebhookEndpoint::$hidden).
  5. Item creation sends a burst of events, and item.created has 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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([

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/Observers/CommentObserver.php Outdated

public function created(Comment $comment)
{
WebhookDispatcher::dispatch(WebhookEvent::CommentCreated, (new CommentResource($comment))->resolve());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/Observers/ProjectObserver.php Outdated
Storage::disk('public')->delete($originalIconImage);
}

WebhookDispatcher::dispatch(WebhookEvent::ProjectUpdated, (new ProjectResource($project))->resolve());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread README.md Outdated
| `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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/Services/WebhookDispatcher.php Outdated
*/
public static function dispatch(WebhookEvent $event, array $data): void
{
WebhookEndpoint::query()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@SebastiaanKloos
SebastiaanKloos force-pushed the pol-353-fase-2-ploi-roadmap-api-en-ondertekende-webhooks branch from 8d22246 to bc2ae11 Compare November 3, 2026 10:45
@SebastiaanKloos

Copy link
Copy Markdown
Collaborator Author

@Cannonb4ll thanks for the thorough review. Everything is addressed and pushed, and the branch is rebased on the Filament v5 / Livewire 4 main.

Blocking

  1. Admin-only policies for API tokens and webhooks. Filament skips a policy for abilities that aren't defined, so all abilities are spelled out (AdminsOnly trait). Employee 403 tests added.
  2. SSRF: https only, public addresses only, checked on save and on every delivery. The connection is pinned to the checked IP and redirects are off.
  3. On the sync queue delivery runs afterResponse() and failures are logged instead of thrown. The README mentions the queue worker.
  4. The secret is filled in EditWebhook::mutateFormDataBeforeFill, with an edit test.
  5. item.created is sent once, after commit, with the complete item. Item\Create, Header and CreateItemTool now run in a transaction, and follow-up saves during creation don't send item.updated. Vote count changes alone no longer send item.updated. item.updated moved to updated().

Other

  • updated_since is converted to the app time zone, per_page= falls back to 50, and items eager load project.
  • api.json middleware forces JSON responses.
  • url column is 2048 chars.
  • created_at is the event time, JSON_THROW_ON_ERROR is on, comment.created is sent after mentions are processed.
  • New events: project.created/deleted and comment.updated/deleted. Comments removed in bulk with their item or user still send nothing, which is documented.
  • The dispatcher exits early without subscribers and builds the payload lazily.
  • api.token alias uses an import.

CommentTest and PasskeyManagementTest fail on main too (the Livewire 4 ModelNotFoundException behaviour), the rest of the suite is green.

@Cannonb4ll Cannonb4ll left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Notifications now run inside the new transaction (Item\Create, Header, CreateItemTool): Slack/Discord jobs can run before the item is committed, and on sync a failing notification rolls back the user's item.
  2. TypeError after commit when the item no longer exists (ItemObserver::created).
  3. SSRF check still lets some internal ranges through (SafeWebhookUrl).
  4. Disabled endpoints keep receiving queued deliveries (SendWebhookJob).
  5. project.updated still arrives before project.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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Item then throws ModelNotFoundException, so the Slack/Discord notification fails now and then.
  • On the default sync queue, the Slack/Discord HTTP call (WebhookClient has 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()));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_id and board_id to Item::create() (they're all fillable)
  • let App\Traits\Sluggable store the slug with saveQuietly()

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)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, and 100.100.100.200 (the Alibaba Cloud metadata address)
  • 198.18.0.0/15 and 192.0.0.0/24
  • NAT64 64:ff9b::/96 (64:ff9b::7f00:1 maps to 127.0.0.1), 6to4 2002::/16 and site-local fec0::/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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: missing : void return type (CLAUDE.md asks for explicit return types).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants