Symfony bundle for incoming webhooks. Each source gets an endpoint under its own URL /webhook/{slug} with an encrypted, write-only secret, an optional sender IP allowlist and its own limits. The intake verifies a delivery, stores each event exactly once per endpoint and dedupe key, and answers immediately. What happens to a stored event depends on the endpoint's mode: in the mode process the bundle filters it, applies a rate limit per actor and routes it to a process; in the mode handler it hands it to the application's delivery handlers after the response. Endpoints, routes and the accepted deliveries (events) are managed through an audited admin API for API Platform and through console twins. Events carry CloudEvents-aligned fields, and source adapters implement Dmstr\Webhook\Adapter\WebhookAdapterInterface, an extension of the RequestParserInterface of symfony/webhook.
- Requirements
- Installation and wiring
- Configuration reference
- Endpoints
- Endpoint modes
- Secrets
- Intake
- Filters and reasons
- Rate limit per actor
- Routes
- Delivery handlers
- Adapters
- GitLab reply client
- Events
- Audit and logging
- Log redaction
- Trusted proxies
- Console commands
- Writing an own adapter
- Upgrade from 0.1.x
- Not built yet
- Tests
- PHP 8.5, Symfony 7.4, API Platform 4.4, Doctrine ORM 3 with DBAL 3.8 or later
- PostgreSQL (tested with 16) or MySQL 8 (tested with 8.0,
utf8mb4); the migrations use the portable Schema API, see Database platforms symfony/webhookandsymfony/remote-event7.4 (only their parser and event contracts; the webhook controller and the consumers of their FrameworkBundle integration are not used, see FrameworkBundle integration)symfony/rate-limiter(sliding windows per endpoint and per endpoint and actor) with the cache poolcache.rate_limiterof FrameworkBundle (symfony/cache, which FrameworkBundle installs);symfony/lock(recommended) keeps concurrent deliveries of one endpoint from overshooting the limitspsr/clock; withsymfony/clock(optional) FrameworkBundle registers the serviceclock, which the Standard Webhooks adapter then uses for its replay window (system time without it)symfony/consolefor the console commandsmonolog/monolog3 withsymfony/monolog-bundle(recommended) for the log channelwebhookand the secret redaction processordmstr/api-platform-utils-bundlefor the encryption of the secret (Dmstr\ApiPlatformUtils\Service\CredentialEncryption, keyCREDENTIALS_ENCRYPTION_KEY)dmstr/api-configuration-bundlefor the connections an endpoint references (flowableConnection,replyConnection)gedmo/doctrine-extensions(endpoints and routes areLoggable); changes are audited when the application registers a loggable listener, for example throughdmstr/doctrine-audit-log-bundlesymfony/security-bundlefor the firewall of the intake and theis_granted()checks of the admin API- a permission voter that decides the permission strings of the bundle (see Permissions)
- optional, for the GitLab reply client only:
m4tthumphrey/php-gitlab-api(^12.1.1),symfony/http-clientand a PSR-17 implementation such asnyholm/psr7; all three are suggestions, not requirements
The bundle requires neither a process engine nor a specific platform bundle; a reference to a process engine is only a connection record, and a route names its process by a definition key.
The bundle is published on Packagist. Install it with Composer:
composer require dmstr/webhook-bundleSymfony Flex registers the bundle; without Flex, add it yourself:
// config/bundles.php
return [
// ...
Dmstr\Webhook\WebhookBundle::class => ['all' => true],
];The bundle prepends its Doctrine mapping and its migrations path (namespace Dmstr\Webhook\Migrations). API Platform discovers the bundle's resources through the registered bundle (its src/Entity directory); the bundle does not touch api_platform.mapping.paths, so the application's own paths, or API Platform's default directories when the application sets none, stay as they are. Run the migrations:
php bin/console doctrine:migrations:migrateThe migrations create foreign keys to dmstr_api_configuration, so the migrations of dmstr/api-configuration-bundle must run first. The bundle ships no version comparator: Doctrine Migrations sorts by the fully qualified class name, and Dmstr\ApiConfiguration\Migrations\… sorts before Dmstr\Webhook\Migrations\…. An application with its own comparator has to keep that order.
The bundle supports PostgreSQL and MySQL 8; the CI runs the full suite against postgres:16 and mysql:8.0 (server character set utf8mb4, collation utf8mb4_unicode_ci). On MySQL, connect with charset=utf8mb4 in DATABASE_URL and run PHP in UTC (date.timezone), because MySQL stores the bundle's datetime columns as DATETIME without an offset.
Two columns of webhook_event differ between the platforms, so both hold the same data:
| Column | PostgreSQL | MySQL |
|---|---|---|
payload |
TEXT |
LONGTEXT, enough for the body cap of 1 MiB |
dedupe_key |
VARCHAR(255), compared exactly |
VARCHAR(255) with the binary collation utf8mb4_0900_bin, so the unique index compares exactly as on PostgreSQL (letter case, accents and trailing spaces count) |
The migration Dmstr\Webhook\Migrations\Version20261201180000 sets the collation on MySQL (on MariaDB and MySQL before 8.0, which lack utf8mb4_0900_bin, it is utf8mb4_bin, which ignores trailing spaces) and changes nothing on other platforms; it is recorded as executed everywhere. The listener Dmstr\Webhook\Doctrine\DedupeKeyCollationListener adds the same collation to the schema the ORM generates, so doctrine:schema:validate and doctrine:migrations:diff report no difference for the bundle's tables.
The migration Dmstr\Webhook\Migrations\Version20261203182500 adds the column webhook_endpoint.mode (every existing endpoint gets process, see Upgrade from 0.1.x) and creates the table webhook_route.
Import the routes of the bundle, which define the intake POST /webhook/{slug}/{secret} (route name dmstr_webhook_intake, secret optional):
# config/routes/dmstr_webhook.yaml
dmstr_webhook:
resource: '@WebhookBundle/config/routes.yaml'With symfony/webhook and symfony/remote-event installed, FrameworkBundle enables framework.webhook and framework.remote_event by default (the component's webhook controller and the messenger handlers of its consumers). The bundle uses neither: it has its own intake controller and no synchronous consumer. Disable both:
# config/packages/framework.yaml
framework:
webhook:
enabled: false
remote_event:
enabled: falseThe admin resources come with the API Platform routes of the application (/api/admin/webhook_endpoints, /api/admin/webhook_routes and /api/admin/webhook_events when API Platform is mounted at /api).
The intake authenticates the sender with the endpoint's secret, not with a user token. Give /webhook/ its own stateless firewall without an authenticator, before the main firewall, and a public access rule bound to POST before any catch-all rule:
# config/packages/security.yaml
security:
firewalls:
webhook:
pattern: ^/webhook/
stateless: true
# ... the API firewall and main follow
access_control:
# Public for POST only; other methods get the router's 405 before the firewall runs.
- { path: ^/webhook/, methods: [POST], roles: PUBLIC_ACCESS }
# ... the catch-all of the API follows
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }The admin API checks permissions; the intake needs none. The bundle announces three permission strings at the container tag za7_core.permission (constants in Dmstr\Webhook\Security\WebhookPermissions):
| Permission | Grants |
|---|---|
webhook:endpoint:manage |
/api/admin/webhook_endpoints: list, read, create, update, delete |
webhook:route:manage |
/api/admin/webhook_routes: list, read, create, update, delete |
webhook:event:read |
/api/admin/webhook_events: list and read |
The host application decides who holds them, typically with a permission voter that maps each permission string to roles. Without a voter that knows these strings, is_granted() denies them for everyone. Grant them to administrators only: an endpoint holds a secret and decides which deliveries reach later processing, and a route decides which process an event starts.
The secret is encrypted at rest with CREDENTIALS_ENCRYPTION_KEY, the key of dmstr/api-platform-utils-bundle (32 bytes, base64). Generate it once per deployment and keep it: changing it makes every stored secret unreadable, and every endpoint then needs a new secret.
# config/packages/dmstr_webhook.yaml
dmstr_webhook:
adapters:
basecamp4: false # off by default
gitlab: false # off by default
passthrough: true # on by default
passthrough_path: false # off by default
standard_webhooks: false # off by default
body_cap: 1048576 # default request body cap in bytes
rate_limit: 60 # default deliveries per minute and endpoint| Key | Type | Default | Meaning |
|---|---|---|---|
adapters |
map of source name to bool | {passthrough: true} |
Enabled flag per source adapter. passthrough is enabled unless set to false; every other source is disabled unless set to true. A disabled adapter registers no service, and an endpoint's sourceType must name an enabled source (422 otherwise). |
body_cap |
int, 1 to 1048576 | 1048576 (1 MiB) |
Request body cap for endpoints without their own bodyCap. 1 MiB is also the hard upper bound, because the reverse proxy caps every webhook body at 1 MiB (see Log redaction). |
rate_limit |
int, at least 1 | 60 |
Deliveries per minute (sliding window) for endpoints without their own rateLimit. |
The values are also published as container parameters: dmstr_webhook.adapters (the full map), dmstr_webhook.enabled_adapters (list of enabled source names), dmstr_webhook.body_cap and dmstr_webhook.rate_limit. The rate limit per actor has no bundle default to configure; it is the endpoint field actorRateLimit (default 20).
/api/admin/webhook_endpoints (GET collection, GET, POST, PATCH as merge patch, DELETE), permission webhook:endpoint:manage, filters slug, sourceType and active, ordered by slug.
| Field | Type | Default | Meaning |
|---|---|---|---|
id |
UUID | generated | read-only |
slug |
string | required | URL segment /webhook/<slug>: lowercase letters, digits and single dashes, at most 100 characters, unique |
sourceType |
string | passthrough |
the adapter that verifies and parses deliveries; must be an enabled source |
mode |
process or handler |
none, required on create | what happens to a stored event, see Endpoint modes; null or another value is rejected with 422 |
secret |
string | required on create | write-only, always read as ********, see Secrets |
secretChangedAt |
datetime | set with the secret | read-only; when the secret was last set or rotated |
active |
bool | true |
an inactive endpoint answers 404 like an unknown one |
actorId |
string or null | null | the endpoint's own actor id in the source (e.g. the user id of a bot account); events of this actor are ignored in both modes (own_actor), so the endpoint does not answer its own events |
actorHandle |
string or null | null | the endpoint's own handle in the source (e.g. the username a mention addresses); passed to the adapter, which decides whether an event mentions the endpoint |
allowedActorIds |
list of strings | [] |
actor ids in the source that may trigger processing, applied in the mode process; an empty list allows nobody, see Filters and reasons |
actorRateLimit |
int, 1 to 10000 | 20 |
events per actor and hour, applied in the mode process, see Rate limit per actor |
ipAllowlist |
list of strings | [] |
sender addresses and CIDR ranges, IPv4 or IPv6 (192.0.2.10, 192.0.2.0/24, 2001:db8::/32); a non-empty list rejects other senders with 403, an empty list filters nothing |
flowableConnection |
IRI or null | null | the connection (dmstr/api-configuration-bundle) later processing runs on |
replyConnection |
IRI or null | null | the connection answers are posted with |
classifierAgent |
string or null | null | id or IRI of an optional classifier agent; a plain string, no association |
bodyCap |
int or null | null | request body cap in bytes, 1 to 1048576; null takes dmstr_webhook.body_cap |
rateLimit |
int or null | null | deliveries per minute, 1 to 10000; null takes dmstr_webhook.rate_limit |
createdAt, updatedAt |
datetime | set by the bundle | read-only |
Example:
curl --request POST "https://app.example.com/api/admin/webhook_endpoints" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/ld+json" \
--data '{"slug": "ci-builds", "sourceType": "passthrough", "mode": "handler", "secret": "'"${WEBHOOK_SECRET}"'", "ipAllowlist": ["192.0.2.0/24"]}'Deleting an endpoint deletes its routes and its events (ON DELETE CASCADE).
Every endpoint has a mode, process or handler (Dmstr\Webhook\Model\EndpointMode). The mode is mandatory: there is no default, and creating an endpoint without it fails with 422 in the admin API and in webhook:endpoint:create. Change it with PATCH /api/admin/webhook_endpoints/{id} and the body {"mode": "handler"} (application/merge-patch+json) or with webhook:endpoint:update <endpoint> --mode=handler; the change is audited like every endpoint field and applies to the next delivery.
Both modes share the checks of the intake (404, 403, 413, 429, 401) and answer every verified delivery with the same 202. After the verification, each event the adapter returns goes through these steps:
Mode process: the bundle decides.
- The filters run in their fixed order. If one applies, the event is inserted directly as
ignoredwith its reason (one write), and nothing else happens. - Otherwise the event is inserted as
received. A duplicate (same endpoint and dedupe key) writes nothing and stops here. - The rate limit per actor counts the event. Over the budget, the event becomes
ignoredwithactor_rate_limited. - The routes of the endpoint are matched. The first matching route makes the event
routedwith the route's id inroute; without a match it becomesignoredwithno_route. - Steps 3 and 4 end in one conditional update, so an event is written at most twice. Nothing of this mode reaches a delivery handler.
Mode handler: the application decides.
- Only the filter on the endpoint's own identity runs: an event whose actor id equals the endpoint's
actorIdis inserted asignoredwithown_actor(one write) and is not handed over. - Otherwise the event is inserted as
received(one write). A duplicate writes nothing and is not handed over again. - After the response, the new event goes to every delivery handler of the application, once, with the payload unchanged. The handlers set its terminal status (
handled,ignoredorfailed). No other filter, no rate limit per actor and no routing apply; routes of such an endpoint are stored but never consulted.
Which mode fits: the mode process needs an adapter that reports who caused an event (an actor), because the allowlist allows no event without one (see Filters and reasons). A source whose adapter reports no actor, which includes the shipped adapters passthrough, passthrough_path and standard_webhooks, is in practice only usable in the mode handler; the shipped adapters GitLab and Basecamp 4 report an actor and work in both modes (for Basecamp 4 mind the missing mention fact in the mode process).
- Write-only. Every response (item, collection, POST, PATCH) shows
********for a stored secret; the ciphertext is never serialized. - Keep. Omitting
secreton PATCH or sending the mask********keeps the stored secret. - Rotate. A new value replaces the stored secret and sets
secretChangedAt; the audit log records the rotation with its actor (see Audit and logging). - No removal.
nullis rejected with 422: an endpoint always has a secret. Deactivate it withactive: falseinstead. - Formats. Token and path secrets are at least 32 characters from
A-Z a-z 0-9 _ -(at most 512). Standard Webhooks secrets arewhsec_followed by the base64 of 24 to 64 random bytes. Which format a source needs is decided by its adapter; the endpoint accepts either. - Storage. The secret is encrypted with
CredentialEncryption(CREDENTIALS_ENCRYPTION_KEY). The plain value exists only between the write and the encryption, and between the decryption and the comparison of the verification strategy. Violation messages never repeat the value.
A random token secret, for example:
openssl rand -base64 48 | tr '+/' '-_' | tr -d '='POST /webhook/{slug}/{secret}, route name dmstr_webhook_intake, where the secret segment is optional and used only by the path strategy (sources that cannot send a header). The secret segment takes the rest of the path, so every POST /webhook/<slug>/<anything> reaches the intake. Two request shapes never reach it:
- Other methods than
POSTget the router's 405 (the application's error response, not the JSON below), before the firewall runs. POST /webhook/<slug>/with an empty trailing segment matches no route and gets the router's 404.
The checks run in this order; every rejection stores no event:
| Step | Rejection |
|---|---|
| 1. The slug is known, the endpoint active and its source adapter enabled | 404, identical for an unknown slug, an inactive endpoint and a source that is not enabled |
2. The sender address (from the trusted proxy chain, see Trusted proxies) is inside a non-empty ipAllowlist |
403 |
3. The body is within the endpoint's body cap (the declared Content-Length first, then the body read) |
413 |
| 4. The delivery is within the endpoint's rate limit (sliding window per minute, per endpoint) | 429 with Retry-After (seconds) |
| 5. The request shape fits the adapter's verification strategy and the adapter verifies the delivery (token, path secret, signature) | 401 |
Step 5 also rejects a secret path segment on an endpoint whose adapter does not use the path strategy, and a request without the segment on one that does, both with 401.
Every rejection answers its status code with the JSON body {"status":"rejected","reason":"<reason>"}, where <reason> is unknown_endpoint (404), ip_not_allowed (403), body_too_large (413), rate_limited (429) or verification_failed (401).
A verified delivery is answered 202 Accepted with {"status":"accepted"}, whatever happens to its events: stored, duplicate, ignored by a filter or routed. Each event is stored once per (endpoint, dedupe key); a duplicate gets the same answer and stores nothing. This also holds for two identical deliveries arriving at the same time (unique index on endpoint_id and dedupe_key; a unique violation counts as a duplicate). An adapter that returns no event (null) gets the same answer too, so the response never tells a sender anything about earlier deliveries or about the filters. What happens to each event after the verification depends on the endpoint mode; the request path does the lookup, the verification, the filters, the rate limit per actor and the routing, with at most two writes per event (see Events) and no other I/O. New events of an endpoint in the mode handler are passed to the delivery handlers after the response.
Rate limit before verification. The endpoint's limit is consumed after the IP allowlist and the body cap but before the verification, so a party that knows the slug and passes the IP allowlist can use up the budget with unverified requests and delay genuine deliveries with 429 (some senders disable a hook after repeated 4xx answers). This is a decided trade-off of the fixed check order. The mitigation is the IP allowlist, because the requests it rejects never reach the limiter: set it wherever the source publishes its sender addresses. The rate limit per actor is a second, separate limit that never rejects a delivery.
Body cap. The cap of an endpoint can only lower the 1 MiB of the reverse proxy, never raise it.
The filters decide, per event and without I/O, whether the intake ignores it. They read the source-neutral context the adapter reports (actor, facts; see Writing an own adapter). They run in this fixed order, and when several apply, the first one is the reason stored in the event's reason (Dmstr\Webhook\Model\IgnoreReason; the values never change):
| Order | Reason | The event is ignored when | Mode |
|---|---|---|---|
| 1 | own_actor |
its actor id equals the endpoint's actorId (both set) |
process and handler |
| 2 | system_generated |
the fact "system generated" is yes (the source generated the event itself) | process |
| 3 | edit |
the fact "edit" is yes (the event is the edit of something that existed before) | process |
| 4 | not_mentioned |
the fact "mentions the endpoint" is no | process |
| 5 | confidential |
the fact "confidential or internal" is yes | process |
| 6 | actor_not_allowed |
the actor id is not in allowedActorIds, or the event has no actor |
process |
| 7 | actor_rate_limited |
the actor used up its budget at the endpoint, see Rate limit per actor | process |
| 8 | no_route |
no active route of the endpoint matches, see Routes | process |
Reasons 1 to 6 are decided before the event is stored, so a filtered event is inserted once with its final status ignored. Reasons 7 and 8 come after the insert of a new event, in one conditional update.
- Unknown facts are neutral. Each fact is yes, no or unknown (
Dmstr\Webhook\Model\Fact), and an unknown fact never triggers its filter. A source that cannot tell whether an event is an edit, for example, never getsedit. - The allowlist allows only the listed ids. An empty
allowedActorIdsallows nobody, so a new endpoint in the modeprocessignores every event withactor_not_alloweduntil actors are added. An event without actor is never on the allowlist. A source whose adapter reports no actor therefore ends every eventignoredwithactor_not_allowedin the modeprocessand is in practice only usable in the modehandler; creating such an endpoint is not rejected. - Actors are compared by id. The ids are strings compared exactly (
===), never display names, so a renamed actor keeps its place on the allowlist and a reused name gains nothing. Put the source's stable account ids intoallowedActorIdsandactorId, not usernames. - Passing. An event that passes filters 1 to 6 is stored as
receivedand goes on to the rate limit per actor and the routing.
Every ignored or routed decision writes one info line on the log channel webhook (see Audit and logging).
In the mode process, each pair of endpoint and actor has its own budget: actorRateLimit events (default 20, 1 to 10000) within a sliding hour. It is a second limit next to the endpoint's rateLimit (deliveries per minute, 429), with its own limiter id (dmstr_webhook_actor) on the same storage (the cache pool cache.rate_limiter) and the same lock factory. A changed actorRateLimit applies to the next event.
- What consumes budget: only a new event that passed all filters (reasons 1 to 6). Duplicates, filtered events and events of endpoints in the mode
handlerconsume nothing. - Over the budget, the event is stored as
ignoredwithactor_rate_limited. The delivery is still answered202; nothing is retried, and the sender is not told. - Counted before routing. The budget is consumed before the routes are matched, so an event that matches no route has used budget as well. An endpoint in the mode
processwithout a matching route (no routes, all routes inactive, or a rule that never matches) burns the budget of its allowed actors while nothing is started. Recognise it by eventsignoredwith the reasonno_route(webhook:event:list --endpoint=<endpoint> --status=ignored, or the filterstatus=ignoredof/api/admin/webhook_events), followed byactor_rate_limitedonce the budget is used up.
A route is a routing rule of an endpoint in the mode process (Dmstr\Webhook\Entity\WebhookRoute, table webhook_route): an event that passed the filters and the rate limit per actor and matches the rule is routed to the process the route names. Routes of an endpoint in the mode handler are accepted but never consulted.
/api/admin/webhook_routes (GET collection, GET, POST, PATCH as merge patch, DELETE), permission webhook:route:manage, filters endpoint, name, eventType and active, ordered by priority, createdAt and id (the order in which routes are tried), 30 items per page.
| Field | Type | Default | Meaning |
|---|---|---|---|
id |
UUID | generated | read-only |
endpoint |
IRI | required on create | the endpoint the route belongs to; cannot be changed afterwards (a PATCH ignores it) |
name |
string | required | at most 100 characters, unique per endpoint |
eventType |
string or null | null | the event type (CloudEvents type as the adapter reports it) the route matches exactly; null or empty matches any type |
filters |
map of attribute name to string, integer or boolean | {} |
every entry must equal the event's attribute of that name; an empty map adds no condition; at most 50 entries; only attributes the endpoint's adapter declares, see below |
processDefinitionKey |
string | required | key of the process definition to start, at most 255 characters |
variables |
map of name to string, integer or boolean | {} |
process variables passed with a matching event; names of letters, digits and underscores, not starting with a digit, at most 64 characters; at most 50 entries |
agent |
string or null | null | optional agent the process uses, as id or IRI |
priority |
int, -1000000 to 1000000 | 0 |
lower is tried first |
active |
bool | true |
an inactive route never matches |
createdAt, updatedAt |
datetime | set by the bundle | read-only |
filters and variables are replaced as a whole on PATCH. String values of both maps are at most 1000 characters.
Variables are static. They are values an administrator configures on the route; nothing of an event (payload, note or comment text) is ever written into them.
Matching. A route matches an event when it is active, its eventType is null or exactly the event's type, and every entry of filters is strictly equal (===) to the event's attribute of that name: "1" does not match 1, 1 does not match true, and an attribute the event does not carry matches no value. The active routes of the endpoint are tried by priority ascending, then createdAt, then id; the first match wins.
Validation against the adapter. Each adapter declares the attributes a route may filter on, by name and kind (string, integer or boolean; see Writing an own adapter). Creating or changing a route checks every filter against the declaration of the endpoint's adapter: a filter on an undeclared attribute, or with a value of another kind, is rejected with 422 at filters[<name>], and the message lists the declared names. Filters on an endpoint whose source type is not an enabled adapter are rejected at filters. The GitLab adapter declares project_id, project_path, noteable_type, target_iid and action (see GitLab), the Basecamp 4 adapter kind, project_id and recording_type (see Basecamp 4); the other shipped adapters declare no attributes, so their routes can only use eventType.
Result on the event. A matching route sets the event to routed and stores the route's id (a UUID string, no foreign key) in the event's route; the id stays when the route is renamed or deleted. Without a match the event is ignored with no_route. Starting the process of a routed event is not part of the bundle yet (see Not built yet).
Example:
curl --request POST "https://app.example.com/api/admin/webhook_routes" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/ld+json" \
--data '{"endpoint": "/api/admin/webhook_endpoints/<endpoint-uuid>", "name": "mention", "eventType": "acme.comment", "filters": {"project_id": 42}, "processDefinitionKey": "answer-mention", "variables": {"language": "en"}, "priority": 10}'The console twins are listed under Console commands.
The seam for endpoints in the mode handler is Dmstr\Webhook\Intake\DeliveryHandlerInterface:
public function handle(Dmstr\Webhook\Intake\AcceptedDelivery $delivery): void;AcceptedDelivery carries eventId (the id of the stored event row), endpoint, event (the adapter's RemoteEvent: id = dedupe key, name = type, decoded payload, unchanged) and source (/webhook/<slug>).
- Every service implementing the interface is autoconfigured with the tag
dmstr_webhook.delivery_handler. Every handler gets every delivery of every endpoint in the modehandler; return early for endpoints the handler does not serve ($delivery->endpoint->getSourceType(), the slug). - Only endpoints in the mode
handlerhand over. An endpoint in the modeprocessnever reaches a delivery handler, neither after an HTTP delivery nor throughwebhook:deliver. - Each new event that was not ignored (
own_actor) is handed over exactly once, after the response: onkernel.terminatefor HTTP (with php-fpm after the response was sent), and after the command printed the response forwebhook:deliver. A duplicate is not handed over; its first delivery was. - "Exactly once" is at most once in operation: if the PHP process dies between storing the event and the hand-over, the event stays
receivedand is never handed over. Nothing is retried, neither a lost hand-over nor a failed handler. - Do no slow or remote work in a handler (no process start, no HTTP call): enqueue it, for example as a messenger message with the event id, and return.
Terminal status. The event stays received until the application gives it a terminal status with Dmstr\Webhook\Intake\EventStatusTransition, either in the handler or later from asynchronous code that only knows the event id:
use Dmstr\Webhook\Intake\AcceptedDelivery;
use Dmstr\Webhook\Intake\DeliveryHandlerInterface;
use Dmstr\Webhook\Intake\EventStatusTransition;
use Symfony\Component\Messenger\MessageBusInterface;
final readonly class CiBuildHandler implements DeliveryHandlerInterface
{
public function __construct(
private MessageBusInterface $bus,
private EventStatusTransition $transition,
) {
}
public function handle(AcceptedDelivery $delivery): void
{
if ('ci-builds' !== $delivery->endpoint->getSlug()) {
return;
}
if (!\is_int($delivery->event->getPayload()['build'] ?? null)) {
$this->transition->ignored($delivery->eventId, 'no build number');
return;
}
// The message handler calls $transition->handled($eventId) or ->failed($eventId, '...') when done.
$this->bus->dispatch(new ProcessCiBuild($delivery->eventId->toRfc4122()));
}
}handled(),ignored()andfailed()take the event id (Uuidor its string form) and an optional reason (at most 255 characters, clipped; it is shown in the admin API, so put no payload text in it).- A transition is allowed only from
received, as one conditionalUPDATE … WHERE id = ? AND status = 'received': race-free, the first transition wins and a terminal status is never left. The return value says whether the call changed the event (false for an unknown id or an event that is no longerreceived, which includes events the intake ignored or routed). - A handler that throws is logged with one
errorline on the channelwebhook(slug,event_id,handler,exception_class; no message, no payload), the event is set tofailedwith the reasonhandler_exception: <exception class>unless the handler already gave it a terminal status, and the other handlers still run. The delivery stays accepted.
The bundle ships no delivery handler; without one, the events of an endpoint in the mode handler stay received.
An adapter is a symfony/webhook request parser for one source type that also declares its verification strategy and its filter attributes (Dmstr\Webhook\Adapter\WebhookAdapterInterface, see Writing an own adapter). It verifies the delivery and returns a RemoteEvent whose id is the dedupe key and whose name is the CloudEvents type, optionally with a source-neutral context for the filters and routes. Adapters are enabled per source under dmstr_webhook.adapters; a disabled adapter registers no service, and an endpoint's sourceType must be an enabled source. All comparisons run in constant time (hash_equals, for HMACs after hash_hmac).
| Source | Default | Strategy and credential | Dedupe key | Type | Time |
|---|---|---|---|---|---|
passthrough |
enabled | header token: header X-Webhook-Token equal to the secret |
SHA-256 hex of the body | webhook.passthrough |
none |
passthrough_path |
disabled | path secret: the secret as path segment, /webhook/<slug>/<secret>, for sources that cannot send a header |
SHA-256 hex of the body | webhook.passthrough_path |
none |
standard_webhooks |
disabled | Standard Webhooks, see below | webhook-id |
payload.type if it is a non-empty string, else webhook.standard_webhooks |
payload.timestamp if it is an RFC 3339 date-time, else none |
gitlab |
disabled | header token: header X-Gitlab-Token equal to the secret, see GitLab |
semantic key per hook kind, see below | gitlab.note, gitlab.merge_request, gitlab.tag_push |
object_attributes.updated_at of notes and merge requests, none for tag pushes |
basecamp4 |
disabled | path secret: the secret as path segment, /webhook/<slug>/<secret>, see Basecamp 4 |
basecamp4:event:<event id>, see below |
basecamp4.<kind>, basecamp4.unknown without a valid kind |
top-level created_at if it is an ISO 8601 date-time with Z or an offset, else none |
The adapters passthrough, passthrough_path and standard_webhooks report no event context: no actor, all facts unknown, no references and no filter attributes. In the mode process every one of their events ends ignored with actor_not_allowed, so use them in the mode handler. The adapters gitlab and basecamp4 report a context and declare filter attributes, see GitLab and Basecamp 4.
The pass-through adapters set no event time. The event row always stores the raw body; for a body that is not a JSON object or array, the decoded payload of the remote event (the one a delivery handler receives) is empty.
A pass-through delivery:
curl --request POST "https://app.example.com/webhook/ci-builds" \
--header "X-Webhook-Token: ${WEBHOOK_SECRET}" \
--header "Content-Type: application/json" \
--data '{"build": 42, "status": "passed"}'Because the dedupe key of the pass-through adapters is the hash of the body, two deliveries with the same body are one event. A source that may legitimately send the same body twice should include an id or a timestamp in it, or use Standard Webhooks.
As built:
- Headers
webhook-id(message id, at most 255 characters),webhook-timestamp(Unix seconds) andwebhook-signature(a space-separated list ofv1,<base64>; other versions are ignored, any one matchingv1signature verifies). - The signature is the base64 of HMAC-SHA256 over
<id>.<timestamp>.<raw body>, keyed with the base64-decoded part of the endpoint secretwhsec_<base64>; an endpoint secret without thewhsec_prefix fails verification. - A timestamp that differs from the server time by more than 300 s in either direction, or is not an integer, fails verification (replay window; exactly 300 s is accepted). The server time comes from the service
clockwhen the container has one (FrameworkBundle registers it withsymfony/clock; tests can replace it with aMockClock), otherwise from the system time. typeandtimeof the event come from the JSON payload (payload.type,payload.timestamp), not from the headers.
Project and group webhooks of GitLab. The adapter is built and tested against the payloads GitLab 15.11 delivers; the fixtures in ./tests/Fixtures/gitlab/ are anonymised copies of such deliveries (see Tests).
Enable it in the bundle configuration and create an endpoint with the source type gitlab, the bot's GitLab user id as actorId, its username as actorHandle and the user ids allowed to trigger a run in allowedActorIds:
# config/packages/dmstr_webhook.yaml
dmstr_webhook:
adapters:
gitlab: trueHook settings in GitLab (project or group, Settings, Webhooks): URL https://<app>/webhook/<slug>, "Secret token" = the endpoint secret (sent as X-Gitlab-Token), and the triggers "Comments" and "Confidential comments" (notes), "Merge request events" and "Tag push events". Other triggers can stay off; their deliveries are accepted with 202 and stored as nothing.
Hook kinds and event types. The header X-Gitlab-Event selects the kind, and the payload's object_kind must agree, else the delivery is accepted without an event:
Header X-Gitlab-Event |
object_kind |
Event type | Notes |
|---|---|---|---|
Note Hook, Confidential Note Hook |
note |
gitlab.note |
only notes on a merge request or an issue (noteable_type MergeRequest or Issue); a note on a commit or a snippet is accepted without an event |
Merge Request Hook |
merge_request |
gitlab.merge_request |
every action (open, update, approved, merge, close, …) |
Tag Push Hook |
tag_push |
gitlab.tag_push |
created and deleted tags |
anything else (Push Hook, Issue Hook, Pipeline Hook, …) |
none | accepted with 202, no event |
A missing, empty or wrong X-Gitlab-Token fails verification (401, nothing stored); the token is compared with hash_equals() and masked in every log record (see Log redaction).
Event context.
- Actor: the GitLab user id (
user.id, for a tag pushuser_id) as a string, display nameuser.name(user_name). The username is never used for a decision, so a renamed user stays on the allowlist and a new account that takes over an old username does not. - References: project (
project_id); targetmerge_requestorissuewith its project-scopediid(the number in the URL and the API path/projects/:id/merge_requests/:iid), for a tag pushtagwith the tag name; for notes also the note (object_attributes.id) and the discussion (object_attributes.discussion_id, present on every note, also on a note that starts no thread; a reply carries the id of its thread). systemGenerated:object_attributes.systemof a note; unknown for merge request and tag push hooks.edit: Yes when the note'sobject_attributes.updated_atdiffers from itscreated_at, No when they are equal (an unedited note has both the same); unknown for merge request and tag push hooks.confidential: Yes when the payload'sevent_typeisconfidential_noteor the header isConfidential Note Hook, or whenissue.confidentialis true. GitLab 15.11 sends both an internal note and a note on a confidential issue asconfidential_note; an internal note has nointernalorconfidentialfield of its own, and its issue saysconfidential: false. No for every other note and for merge request and tag push hooks.mentionsEndpoint: for a note, whetherobject_attributes.notementions the endpoint'sactorHandle(rule below); unknown when the endpoint has no handle. Merge request and tag push hooks report No, so in the modeprocessthey endignoredwithnot_mentionedand use no budget; use them in the modehandler.
Mention rule. A mention is @<handle> as a whole token, without regard to case; actorHandle may be stored with or without the leading @. The handle must end the token: @agent-example-bot, @agent-example2 and @agent-example.bot do not mention agent-example, while @agent-example. or @agent-example? at the end of a sentence, (@agent-example) and a note that is only @agent-example do. A handle preceded by a letter, digit, ., -, _, +, / or @ (an e-mail address, a path) is no mention. Occurrences inside fenced code blocks (``` or ~~~) and inline code (backticks) do not count; indented code blocks are not recognised.
Filter attributes, each only on the events whose payload has it:
| Attribute | Kind | Events | Value |
|---|---|---|---|
project_id |
integer | all | project_id |
project_path |
string | all | project.path_with_namespace |
noteable_type |
string | notes | MergeRequest or Issue |
target_iid |
integer | notes, merge requests | iid of the merge request or issue |
action |
string | merge requests | object_attributes.action, e.g. open, update, approved |
A route for mentions in merge request notes of one project:
{"endpoint": "/api/admin/webhook_endpoints/<endpoint-uuid>", "name": "mr-mentions", "eventType": "gitlab.note", "filters": {"noteable_type": "MergeRequest", "project_path": "example-group/sample-project"}, "processDefinitionKey": "answer-mention"}No text of a delivery (note bodies, titles, descriptions, commit messages) enters the context, the attributes, the type, the dedupe key or a log line; it stays in the stored payload, which a delivery handler receives unchanged.
Dedupe key. The semantic key of the event, built from ids and timestamps only (the intake hashes a key longer than 255 characters):
| Kind | Key |
|---|---|
| note | gitlab:note:<project id>:<note id>:<object_attributes.updated_at> |
| merge request | gitlab:merge_request:<project id>:<iid>:<action>:<object_attributes.updated_at> |
| tag push | gitlab:tag_push:<project id>:<ref>:<before>:<after> |
When one of the parts is missing, the key is gitlab:<kind>:sha256:<SHA-256 hex of the body>. The delivery UUID is not part of the key: GitLab 15.11 sends X-Gitlab-Event-UUID, but a "Resend Request" from the hook's "Recent events" carries the identical body with a new UUID, so a key with the UUID would turn every resend into a second event. With the semantic key a resend is a duplicate, while the edit of a note (new updated_at), another action on the same merge request, and the deletion of a tag after its creation are events of their own.
Accepted collisions of the semantic key: two updates of one merge request with the same action within the same second (updated_at has second precision; GitLab 15.11 sends a description change and a label change made in the same second as two update hooks with the same updated_at) are one event, and the second is dropped as a duplicate; likewise two approvals of one merge request by different users if updated_at does not change, and a tag that is created, deleted and created again on the same commit. A handler that needs every such delivery reads the current state from GitLab instead.
What GitLab 15.11 does not deliver. The edit of a note and system notes (e.g. "changed the description", "approved this merge request") produced no Note Hook delivery on GitLab 15.11. The adapter still evaluates edit and systemGenerated for later versions that send them; the fixtures of these cases are derived from captured deliveries and marked as derived.
Project webhooks of Basecamp 4 (the API documented as bc3-api, section Webhooks). The adapter is built against that documentation, not against captured deliveries: the fixtures in ./tests/Fixtures/basecamp4/ follow the documented payload and headers with invented values and are marked documented or derived from such a fixture; none is captured (see Tests). Where the documentation is silent, the adapter makes an assumption, listed under "What the documentation leaves open" below.
Enable it in the bundle configuration and create an endpoint with the source type basecamp4, a token secret (see below) and the Basecamp person ids allowed to trigger a run in allowedActorIds; actorId is the person id of the application's own Basecamp account, with the caveat under "Event context". actorHandle has no effect for this source.
# config/packages/dmstr_webhook.yaml
dmstr_webhook:
adapters:
basecamp4: trueSecret in the path. Basecamp signs nothing and sends no secret header, so the endpoint secret is the last segment of the hook URL (VerificationStrategy::PathSecret): https://<app>/webhook/<slug>/<secret>. The segment is compared with the endpoint secret in constant time; a wrong, missing, shortened or extended segment, a further path segment after it, and a secret sent in a header instead of the path all fail with 401 and store nothing.
- Use a token secret: at least 32 and at most 512 characters from
A-Z a-z 0-9 _ -(the format the endpoint validates, see Secrets), which needs no encoding in a URL path. The endpoint would also accept a Standard Webhooks secretwhsec_<base64>, but its base64 may contain+,/and=; do not use one for this source. - Basecamp requires an HTTPS
payload_url, so the secret travels only inside TLS. - The secret ends up wherever the URL is logged. The bundle masks the segment after
/webhook/<slug>/on every Monolog channel (see Log redaction); the reverse proxy and every proxy or load balancer in front of the application must mask it in their access logs as well (therequest>urifilter of the Caddy example). Rotating the secret means changing the hook URL in Basecamp.
Hook settings in Basecamp. Register the hook URL per project, in the project's webhook settings (Project, Webhooks) or through the API with POST /buckets/<project id>/webhooks.json and a JSON body with payload_url (the hook URL above) and types (the recording types to deliver, e.g. Comment, Message, Kanban::Card). Basecamp documents the delivery headers Content-Type: application/json, User-Agent: Basecamp3 Webhook and X-Request-Id; none of them is used for verification or the dedupe key (X-Request-Id only appears as delivery_id in the log lines, see Audit and logging). Basecamp retries a delivery that does not get a 2xx answer, up to 10 attempts with exponential backoff, and follows no redirects: point the hook at the final URL. The intake answers every verified delivery with 202, so an accepted delivery is not retried.
Event types. Every verified delivery is one event, whatever its kind; no kind is dropped. The type is basecamp4.<kind> with the payload's kind taken verbatim when it consists of 1 to 100 characters from a-z 0-9 _ (e.g. basecamp4.message_created, basecamp4.comment_created, basecamp4.todo_completed), and basecamp4.unknown when kind is missing or does not fit. The kind kanban_card_moved is not in the documented list of kinds; it is known from use and treated like any other kind (basecamp4.kanban_card_moved). A body that is not JSON is still an event of the type basecamp4.unknown with an empty decoded payload; the stored payload is always the raw body, unchanged.
Event context.
- Actor: the person id of the top-level
creator(creator.id, an integer or a string of digits) as a string, display namecreator.name. A name or e-mail address is never the id, so a person who takes over the display name of the application's account gains nothing. An event without a usable top-levelcreator.idhas no actor (thecreatorinsiderecordingis not taken) and endsignoredwithactor_not_allowedin the modeprocess. - Own identity: the endpoint's
actorIdis compared withcreator.id, and a match isignoredwithown_actorin both modes. Basecamp names the account that performed an action ascreator, so when the application writes to Basecamp with the account set asactorId, the deliveries of its own writes are ignored. An endpoint whose application writes with that account and still needs those deliveries must not setactorId. - References: project
recording.bucket.id; target of the reference kindrecordingwithrecording.id, the recording the event is about; no note and no discussion. For a comment the target is the comment itself: the recording it belongs to (e.g. the card or message) is only in the payload (recording.parent). For copy and move kinds the destination (copy.bucket.id) is only in the payload as well. edit: Yes for a kind ending in_title_updatedor_content_updated(the edit of an existing recording), No for a kind ending in_created, unknown for every other kind (archived, unarchived, trashed, untrashed, copied, moved, completed, assignment changes, …) and without a valid kind.systemGenerated,confidentialandmentionsEndpoint: always unknown; the payload has no equivalent, so their filters never fire.
No mention gate in the mode process. With mentionsEndpoint unknown, the filter not_mentioned never applies: every event of an allowed creator that is not an edit and matches a route is routed, including trashed, archived, moved and unknown kinds, whose edit fact is unknown. A catch-all route therefore starts a process for every such event. Give routes an eventType or a kind filter, or use the mode handler and decide in a delivery handler.
Filter attributes, each only on the events whose payload has it:
| Attribute | Kind | Value |
|---|---|---|
kind |
string | kind, only when it fits the pattern above, e.g. comment_created |
project_id |
integer | recording.bucket.id |
recording_type |
string | recording.type, e.g. Message, Comment, Todo, Kanban::Card |
A route for new comments in one project:
{"endpoint": "/api/admin/webhook_endpoints/<endpoint-uuid>", "name": "new-comments", "eventType": "basecamp4.comment_created", "filters": {"project_id": 70200001, "recording_type": "Comment"}, "processDefinitionKey": "answer-comment"}No text of a delivery (titles, content, details, names other than the actor's display name) enters the context, the attributes, the type, the dedupe key or a log line; it stays in the stored payload, which a delivery handler receives unchanged.
Dedupe key. basecamp4:event:<id> from the top-level event id (an integer or a string of digits) when the payload also has a valid kind; otherwise basecamp4:event:sha256:<SHA-256 hex of the body>. Headers never enter the key, so a delivery that arrives again with another X-Request-Id and the same body is a duplicate. Each change in Basecamp is an event with an id of its own, so the creation, every edit and the trashing of a recording are separate events.
What the documentation leaves open. It does not say whether the top-level id stays the same when Basecamp retries a delivery. The dedupe key assumes it does; if a retry carried a new id, the retry would be stored as a second event. It does not list kanban_card_moved among the kinds, and it describes no field that tells a system-generated, confidential or mentioning event apart, hence the unknown facts.
Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient posts answers to GitLab with the reply connection of an endpoint (replyConnection), for example the answer of a process to the note that mentioned the bot. It does exactly three things and nothing else:
| Method | GitLab API | Returns |
|---|---|---|
replyToDiscussion(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int|string $projectId, int $iid, string $discussionId, string $body) |
POST /projects/:id/merge_requests/:iid/discussions/:discussion_id/notes or the same under issues |
GitlabNote |
addNote(WebhookEndpoint $endpoint, GitlabNoteable $noteable, int|string $projectId, int $iid, string $body) |
POST /projects/:id/merge_requests/:iid/notes or the same under issues |
GitlabNote |
currentUser(WebhookEndpoint $endpoint) |
GET /user |
GitlabUser (id, username, name, bot flag) |
GitlabNoteable is MergeRequest or Issue; $projectId is the numeric id or the full path of the project. The GitLab adapter reports what a reply needs in its event context: the project, the target iid and the discussion. GitlabNote carries the note id, its type, the author's id and username, the noteable type and iid and the creation time, never the body. currentUser() tells which GitLab user the token belongs to, e.g. to compare it with the endpoint's actorId.
Packages. The client is built on m4tthumphrey/php-gitlab-api (^12.1.1) over symfony/http-client (through its Psr18Client, which is also the PSR-17 factory the library is given); the library itself requires a PSR-17 implementation such as nyholm/psr7. All three are suggestions of the bundle, not requirements; install them in the application to use the client:
composer require m4tthumphrey/php-gitlab-api:^12.1.1 symfony/http-client nyholm/psr7Registration. The service Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient (private, autowired, inject it by its class) exists only when both hold: the library is installed (the class Gitlab\Client exists) and the adapter gitlab is enabled (dmstr_webhook.adapters.gitlab: true). Otherwise nothing of it is registered and the container builds as without it. A service of the application that should work either way takes ?GitlabReplyClient $replyClient = null.
HTTP transport. The client sends its requests through the service dmstr_webhook.reply_http_client (WebhookBundle::REPLY_HTTP_CLIENT), which the bundle defines as an alias of FrameworkBundle's http_client. Without http_client (no symfony/http-client, or framework.http_client.enabled: false) and without an own definition of dmstr_webhook.reply_http_client, the client is removed from the container, which still builds. To replace the transport, for example in an end-to-end test of the application, define the service id yourself; the application's definition wins over the bundle's alias:
# config/services.yaml
when@test:
services:
dmstr_webhook.reply_http_client:
class: Symfony\Component\HttpClient\MockHttpClient
arguments: ['@App\Tests\GitlabResponses'] # a callable that answers each requestConnection contract. The endpoint's replyConnection is an ApiConfiguration of dmstr/api-configuration-bundle with the type gitlab and two config keys: base_url, the GitLab root URL as an absolute http or https URL without a path, query or credentials (https://gitlab.example.com, a trailing slash is fine; the library appends /api/v4/… to the host, so a path prefix would be dropped), and token, the access token of the bot user, stored encrypted and decrypted with ConfigSecrets::decrypt() only for the request. This is a contract with the GitLab connection schema of the application: the bundle registers no connection type and no schema of its own, so the application's schema for the type gitlab must provide these keys and mark token as writeOnly.
Errors. Every failure is an exception under Dmstr\Webhook\Reply\Gitlab\Exception\, all extending GitlabReplyException:
| Exception | When |
|---|---|
ReplyConnectionException |
the endpoint has no reply connection, it is not of the type gitlab, base_url is missing or not an absolute http(s) root URL, or token is missing or empty; no request is sent |
DiscussionNotFoundException |
replyToDiscussion(): GitLab answered 404 (no such project, target or discussion, or the token cannot see it) |
DiscussionNotRepliableException |
replyToDiscussion(): GitLab answered 400 (the discussion takes no replies) |
GitlabRequestFailedException |
every other failure: another HTTP status (getStatusCode()), a redirect, a transport error (status null) or a response of an unexpected shape |
No exception of the library or the HTTP client is chained; a message names the operation, the status and at most GitLab's shortened error text, with the token masked if GitLab echoed it.
No redirects. Neither the HTTP client (max_redirects: 0) nor the library (its redirect plugin is removed) follows a redirect, so a request and its token never go to another host; a 3xx answer fails with GitlabRequestFailedException.
No permission checks. The client checks no permission and no role. What it may do is bounded by the bot's role in the GitLab project and the scope of its token (api for notes); give the bot user only the projects and the role it needs. The caller decides whether an answer is due.
Logging. Each request writes one info line (success) or one warning line (failure) on the channel webhook with the operation, the endpoint id, the noteable type, the project, the iid and the HTTP status; never the token, the base URL or the note body.
Not a model tool. The client is deterministic code for the application's process steps: the application decides what to post where. Do not offer it, or a wrapper that passes model output into its arguments, as a tool to a language model; a model that can choose the project, target and body could post anywhere the bot's token reaches.
/api/admin/webhook_events (GET collection, GET), permission webhook:event:read, read-only, newest first, filters endpoint, status, type and dedupeKey.
| Field | Meaning |
|---|---|
id |
CloudEvents id, a UUID v7 assigned on receipt |
endpoint |
the endpoint: its IRI in the item response; in the list, when the application enables relation_labels of dmstr/api-platform-utils-bundle, {"@id": "<IRI>", "slug": "<slug>"} (the slug is the endpoint's label property) |
source |
CloudEvents source: /webhook/<slug> of the endpoint at receipt |
type |
CloudEvents type, as the adapter names it (e.g. webhook.passthrough, see Adapters) |
time |
CloudEvents time: when the event happened according to the source (a WebhookRemoteEvent of the adapter), null if the source does not say |
status |
see below |
reason |
why the event has its status: an ignore reason, handler_exception: <exception class>, or the reason a delivery handler gave |
dedupeKey |
the idempotency key, unique per endpoint: the id of the adapter's event, or its SHA-256 hex when it is longer than 255 characters |
route |
the id of the route that matched (routed); no foreign key, kept when the route is renamed or deleted |
processInstanceId, replyReference, error |
reserved for later processing |
receivedAt |
when the delivery was accepted |
The raw payload is stored but is in no serialization group: neither the list nor the item response contains it, and neither do the console commands.
| Status | Meaning | Set by |
|---|---|---|
received |
stored and not decided yet | the intake |
ignored |
passed over, with a reason | the intake (filters, rate limit per actor, no route) or a delivery handler |
routed |
a route matched; route holds its id |
the intake, mode process |
handled |
a delivery handler of the application processed the event | the application, mode handler |
failed |
processing failed, with a reason | a delivery handler, or the bundle when a handler throws |
started, completed |
reserved for the processing of routed events, which is not built yet | nothing in the bundle sets them |
Life cycle per mode and the number of writes to webhook_event per event:
| Case | Status after the intake | Writes by the intake |
|---|---|---|
| rejected delivery (404, 403, 413, 429, 401) | no event | 0 |
| duplicate (either mode) | the earlier event is unchanged | 0 |
filtered by reasons 1 to 6 (in the mode handler only own_actor) |
ignored with the reason |
1 (insert with the final status) |
mode process, over the rate limit per actor or no matching route |
received, then ignored with actor_rate_limited or no_route |
2 (insert, one conditional update) |
mode process, matching route |
received, then routed with the route id |
2 (insert, one conditional update) |
mode handler, new event |
received, then handled, ignored or failed by the application |
1 (insert); the terminal status is one more conditional update by the application, or by the bundle when a handler throws |
Nothing in the bundle moves a routed event further, and EventStatusTransition only leaves received.
- Endpoint and route changes are audited through Gedmo loggable: creation and every change of a configuration field, with the actor the application's loggable listener records (the authenticated user for the admin API). The secret and its ciphertext are never versioned;
secretChangedAtis, so every rotation is in the audit log with its actor. Console writes run without a security token, so the actor of their entries is whatever the application's actor provider returns without one (often null). - Events are not audited: they are the trail themselves.
- Rejected deliveries are not stored. Each writes exactly one
warningline on the log channelwebhookwithslug,ip,reasonanddelivery_id(the sender's delivery id from the first of the headerswebhook-id,X-Gitlab-Event-UUIDandX-Request-Idthat is set), never the secret or the payload. Reasons:unknown_endpoint,ip_not_allowed,body_too_large,rate_limited,verification_failed, the same as in the response body. - Decisions of the intake: every event the intake sets to
ignoredorroutedwrites oneinfoline on the channelwebhookwithslug,event_id,type,status,reason,routeanddelivery_id, never the payload. - Failed hand-overs write one
errorline on the channelwebhookper failing handler (see Delivery handlers).
The bundle registers the channel when MonologBundle is installed. In production, give it its own handler: a fingers_crossed main handler drops info and warning lines unless an error follows, so the rejection and decision lines would be lost.
# config/packages/monolog.yaml
when@prod:
monolog:
handlers:
webhook:
type: stream
path: php://stderr
level: info
channels: [webhook]
formatter: monolog.formatter.jsonA path secret is part of the URL and a header secret part of the request, so both must be kept out of every log.
Application log. Symfony's RouterListener logs request_uri and route_parameters on the channel request, a fingers_crossed handler flushes those records on any error, and the "No route found" exception of a 405 repeats the URL. The bundle ships the Monolog processor Dmstr\Webhook\Log\WebhookSecretRedactionProcessor (#[AsMonologProcessor] without a channel, so MonologBundle registers it for every channel). It rewrites the message, the context and the extra fields of every record, recursively, and masks with ********:
- the secret path segment: everything after
/webhook/<slug>/up to whitespace, a quote,?or#; - the route parameter
route_parameters.secret; - the values of the headers
X-Webhook-Token,X-Gitlab-Tokenandwebhook-signature, as array keys in any spelling (x_gitlab_token,HTTP_X_GITLAB_TOKEN) and asName: valuein a string; - the messages of exceptions in the context and of their previous exceptions (rewritten in place, so every formatter sees the masked text).
The processor needs monolog/monolog 3 and is active only where MonologBundle registers it. An own adapter whose credential travels in another header is not covered: register a processor of the application for that header. Check the test log after a delivery with a path secret.
Reverse proxy. Caddy redacts only Authorization, Cookie and Proxy-Authorization by default. Cap the body of the intake and filter the access log, for example in the Caddyfile:
# The body limit answers 413 before PHP reads more than 1 MiB; it is the upper
# bound of every endpoint's body cap (1048576 bytes, hence MiB and not MB).
@webhook path /webhook/*
handle @webhook {
request_body {
max_size 1MiB
}
php_fastcgi php:9000
}
# The secret path segment after /webhook/<slug>/ is masked, the token and
# signature headers are dropped.
log {
output stdout
format filter {
wrap console
fields {
request>uri regexp "^(/webhook/[^/?]+/)[^?]+" "${1}********"
request>headers>X-Gitlab-Token delete
request>headers>X-Webhook-Token delete
request>headers>Webhook-Signature delete
}
}
}Add a delete line for the header of every further adapter that carries a secret. In Caddy 1MB means 1,000,000 bytes and 1MiB 1,048,576 bytes, the bundle's maximum. Proxies in front of Caddy (load balancers, ingress controllers) keep access logs of their own that need the same treatment.
The IP allowlist compares the address of Request::getClientIp(). Behind proxies that address is only as reliable as the chain that forwards it:
- The outer reverse proxy (load balancer, ingress) sets
X-Forwarded-For. - Caddy accepts it only from the proxies listed in
trusted_proxiesand passes it on. - Symfony accepts it only from the proxies in
SYMFONY_TRUSTED_PROXIES(together withSYMFONY_TRUSTED_HEADERS, orframework.trusted_proxiesandframework.trusted_headers).
An X-Forwarded-For sent by an untrusted peer is ignored. Two cases make the allowlist unreliable: a sender that itself has a private address while the chain trusts private_ranges, and an outer proxy that passes on an X-Forwarded-For the client set. For deployments behind another proxy, set SYMFONY_TRUSTED_PROXIES to the address of Caddy instead of private_ranges, and let the outer proxy overwrite rather than append the client address.
Console twins of the admin API, with the same validation and the same secret semantics. The secret is never printed: the output shows ******** and secretChangedAt.
| Command | Twin of |
|---|---|
webhook:endpoint:list [--source-type=<type>] [--active=true|false] [--limit=50] |
GET /api/admin/webhook_endpoints |
webhook:endpoint:show <endpoint> |
GET /api/admin/webhook_endpoints/{id} |
webhook:endpoint:create <slug> --mode=process|handler [options] |
POST /api/admin/webhook_endpoints |
webhook:endpoint:update <endpoint> [--slug=<new>] [options] |
PATCH /api/admin/webhook_endpoints/{id} |
webhook:endpoint:delete <endpoint> [--force] |
DELETE /api/admin/webhook_endpoints/{id} |
webhook:route:list [--endpoint=<endpoint>] [--name=<name>] [--event-type=<type>] [--active=true|false] [--limit=50] |
GET /api/admin/webhook_routes |
webhook:route:show <route> [--endpoint=<endpoint>] |
GET /api/admin/webhook_routes/{id} |
webhook:route:create <name> --endpoint=<endpoint> --process-definition-key=<key> [options] |
POST /api/admin/webhook_routes |
webhook:route:update <route> [--endpoint=<endpoint>] [--name=<new>] [options] |
PATCH /api/admin/webhook_routes/{id} |
webhook:route:delete <route> [--endpoint=<endpoint>] [--force] |
DELETE /api/admin/webhook_routes/{id} |
webhook:event:list [--endpoint=<endpoint>] [--status=<status>] [--type=<type>] [--dedupe-key=<key>] [--limit=50] |
GET /api/admin/webhook_events |
webhook:event:show <id> |
GET /api/admin/webhook_events/{id} |
webhook:deliver <slug> <file> [--header="Name: Value"]... [--secret=<path secret>] [--ip=<address>] |
POST /webhook/{slug}[/{secret}] |
<endpoint> is a slug or a full UUID. The webhook:* options have no shortcuts that collide with the global options of the console application (-h, -q, -v, -V, -n, -e): --endpoint is long-only everywhere, because -e is --env; the remaining shortcuts are -l for --limit of the list commands and -f for --force of webhook:endpoint:delete and webhook:route:delete.
The options of create and update are the endpoint fields: --source-type, --mode=process|handler, --secret=<value> or --ask-secret (hidden prompt; prefer it, because an option value lands in the shell history and the process list), --active=true|false, --actor-id, --actor-handle, --allowed-actor-ids=<csv>, --actor-rate-limit, --ip-allowlist=<csv>, --flowable-connection and --reply-connection (UUID, IRI or name of a connection), --classifier-agent, --body-cap and --rate-limit.
--modehas no default:webhook:endpoint:createwithout it fails validation, as a POST withoutmodedoes. Scripts that create endpoints must pass it.- Update changes only the options given. An empty value clears an optional field (
--ip-allowlist=removes the filter),defaultor an empty value resets--body-capand--rate-limitto the bundle defaults, andnoneor an empty value clears a connection. - The mask
********as--secretkeeps the stored secret, an empty--secret=is rejected likenullthrough the API, and a rotation reports the newsecretChangedAt. - A rejected create or update writes nothing and prints the violations with their property paths, as the API answers 422.
- Delete asks for confirmation unless
--forceis given, and reports how many events go with the endpoint; its routes are deleted with it.
php bin/console webhook:endpoint:create ci-builds --mode=handler --ask-secret --ip-allowlist=192.0.2.0/24 --rate-limit=30
php bin/console webhook:endpoint:update ci-builds --ask-secret
php bin/console webhook:endpoint:update ci-builds --mode=process --allowed-actor-ids=4711,4712 --actor-rate-limit=10
php bin/console webhook:event:list --endpoint=ci-builds --status=ignoredA route is addressed by its full UUID, or by its name together with --endpoint=<slug or UUID> (the name is unique per endpoint only). With a UUID and --endpoint, the route must belong to that endpoint. The options of create and update are the route fields: --event-type (empty: any type), --filter=<name>=<value> and --variable=<name>=<value> (one option per entry), --process-definition-key, --agent (empty clears), --priority and --active=true|false; update also takes --name.
- Create needs
--endpointand--process-definition-key; left-out options take the defaults (any event type, no filters, no variables, no agent, priority 0, active). The endpoint cannot be changed later; on update--endpointonly addresses the route by name. - Update changes only the options given. The
--filterand--variableoptions given replace the whole map, asfiltersandvariablesin a PATCH do; a single empty value (--filter=,--variable=) clears it. - A route is validated like a POST or PATCH through the admin API before anything is written, including the check of the filters against the adapter's declared attributes; a rejected write prints the violations and writes nothing.
- Show and the output of create and update print the maps in the notation of the options,
name=<JSON value>, so a printed entry can be passed back unchanged. - Delete asks for confirmation unless
--forceis given. Events that name the route keep its id.
Typing of --filter and --variable values: the value is read as JSON when it is a JSON string, integer or boolean, and taken as a plain string otherwise. confidential=true is the boolean true, project_id=42 the integer 42, project_id='"42"' the string "42", flag='"true"' the string "true", and object_kind=comment the string "comment" (not JSON, so taken as is). Quote a value as JSON to make it a string (mind the shell: --filter 'ref="42"'). null, numbers with a fraction or exponent, arrays and objects are rejected. Since route filters compare strictly, the kind must match the adapter's declaration: an integer attribute needs project_id=42, not project_id='"42"'.
php bin/console webhook:route:create mention --endpoint=acme --event-type=acme.comment --filter project_id=42 --process-definition-key=answer-mention --variable language=en --priority=10
php bin/console webhook:route:list --endpoint=acme
php bin/console webhook:route:update mention --endpoint=acme --active=false
php bin/console webhook:route:update 0193a5c4-7e2b-7c1d-9f3e-2a4b6c8d0e1f --priority=-10 --filter=
php bin/console webhook:route:delete mention --endpoint=acme --forcewebhook:deliver is the twin of the intake: it runs the raw body in <file> through the same checks, filters, rate limits, routing, log lines and storage as the HTTP route, prints the status code and the response body (202 {"status":"accepted"}), then one line per event of an accepted delivery, and then hands the new events over like the HTTP path, only for an endpoint in the mode handler.
<file>is the path of the raw request body, or-to read it from stdin.--header="Name: Value"sets one request header and is repeatable;X-Forwarded-*andForwardedheaders given this way are dropped, so the sender address never comes from a header.--secretis the secret path segment (path strategy only),--ipthe sender address checked against the IP allowlist (default127.0.0.1).- Per event it prints
event <id> <type> <status>withreason=<reason>for an ignored event orroute=<route id>for a routed one, orduplicate <type> (stored before, nothing written). - For an endpoint in the mode
handlerit ends withHanded over to the delivery handlers: <n> event(s).; for the modeprocesswithEndpoint mode "process": nothing is handed over to the delivery handlers. - Exit code
0when the delivery is accepted (also a duplicate or an ignored event),1when it is rejected (404, 403, 413, 429, 401),2for invalid input (unreadable file, an--ipthat is no IPv4 or IPv6 address, a--headerwithoutName: Value).
php bin/console webhook:deliver ci-builds ./payload.json --header="X-Webhook-Token: ${WEBHOOK_SECRET}"
echo '{"build": 42}' | php bin/console webhook:deliver ci-builds - --header="X-Webhook-Token: ${WEBHOOK_SECRET}" --ip=192.0.2.10Like --secret=<value>, a --header value with a token lands in the shell history and the process list; use it for tests and diagnosis.
An adapter is a service implementing Dmstr\Webhook\Adapter\WebhookAdapterInterface and marked with #[Dmstr\Webhook\Adapter\AsWebhookAdapter('<source>')]. The interface extends Symfony\Component\Webhook\Client\RequestParserInterface with two methods:
verificationStrategy(): VerificationStrategy, the enumDmstr\Webhook\Adapter\VerificationStrategywith the casesHeaderToken,PathSecretandStandardWebhooks;filterAttributes(): FilterAttributes, the attributes a route may filter on (see below).
The attribute tags the service dmstr_webhook.adapter with the source name; when the source is not enabled under dmstr_webhook.adapters, the service is removed from the container. Classes under the application's own namespace need autoconfiguration (the default in config/services.yaml) for the attribute to take effect.
The usual base is Dmstr\Webhook\Adapter\AbstractWebhookParser, an AbstractRequestParser that matches POST only, declares no filter attributes (FilterAttributes::none()) and offers bodyHash() (SHA-256 hex of the raw body), jsonPayload() (the body decoded as a JSON object or array, an empty array otherwise) endpointHandle() (the endpoint's handle, see below) and verifyPathSecret() (the check of the strategy PathSecret: the secret path segment must equal the endpoint secret, compared in constant time, else a RejectWebhookException with 401; the adapters passthrough_path and basecamp4 use it). Return a Dmstr\Webhook\Adapter\WebhookRemoteEvent to also pass the event time and the event context; a plain RemoteEvent has neither.
How the intake calls parse(Request $request, string $secret):
$secretis the endpoint's decrypted secret.- The secret path segment, if the request has one, is in the request attribute
Dmstr\Webhook\Intake\WebhookIntake::PATH_SECRET_ATTRIBUTE; the intake lets it through only to an adapter whose strategy isPathSecret, and requires it there. - The endpoint's own handle (
actorHandle), if it has one, is in the request attributeDmstr\Webhook\Intake\WebhookIntake::ENDPOINT_HANDLE_ATTRIBUTE(null without); an adapter needs it only for the fact "mentions the endpoint", which is unknown when the endpoint has no handle. - A
RejectWebhookExceptionwith any status code becomes401 verification_failed;AbstractRequestParseralso turns a malformed body read with$request->toArray()into one, so preferjsonPayload()after the verification. - Return one
RemoteEventor a list of them (one event row each), or null to accept the delivery without storing anything (e.g. an event kind the adapter does not handle).createSuccessfulResponse()andcreateRejectedResponse()are not used: the intake's responses are the same for every source. - The id of each returned event is the complete dedupe key: the intake stores one row per endpoint and id, and treats a second event with the same id as a duplicate.
Dmstr\Webhook\Model\EventContext is the source-neutral description of one event, passed as the fifth argument of WebhookRemoteEvent. Every part is optional; an event without a context has no actor, no references, all facts unknown and no attributes (EventContext::none()).
actor:Dmstr\Webhook\Model\Actorwithid, the source's stable, immutable account id as a string (never a renamable username), and an optionaldisplayNamefor humans only. The own-identity filter, the allowlist and the rate limit per actor compareidwith===. Without an actor, an event never passes the allowlist of the modeprocess.project,target,note,discussion:Dmstr\Webhook\Model\Referencewith a lower snake_casekind(suggested:project,merge_request,issue,note,discussion; a source uses its own word where none fits) and the source'sidas a string.facts:Dmstr\Webhook\Model\EventFactswith the four tri-state factssystemGenerated,edit,confidentialandmentionsEndpoint, each aDmstr\Webhook\Model\Fact(Yes,No,Unknown, defaultUnknown;Fact::fromBool()maps true, false and null). ReportUnknownfor what the source does not tell: an unknown fact never triggers its filter. An event kind that cannot mention anyone reportsmentionsEndpointasNo, notUnknown, so its events do not pass the "not mentioned" filter.attributes: values for the route matcher by name, string, int or bool only, of the kinds the adapter declares infilterAttributes(). An attribute an event does not carry matches no route filter.
Filter attributes. filterAttributes() returns a Dmstr\Webhook\Model\FilterAttributes that maps lower snake_case names (at most 64 characters) to a Dmstr\Webhook\Model\AttributeKind (String, Integer, Boolean). The declaration is per adapter, not per event, and must be the same on every call; route filters are validated against it.
No text of the source. The context carries no text of the source object. The body of a note or comment, and any other free text of the source, must not be exposed through the actor's display name, a reference id or an attribute value: these reach routes, logs and the admin API. The text stays in the stored payload, which a delivery handler receives unchanged.
use Dmstr\Webhook\Adapter\AbstractWebhookParser;
use Dmstr\Webhook\Adapter\AsWebhookAdapter;
use Dmstr\Webhook\Adapter\VerificationStrategy;
use Dmstr\Webhook\Adapter\WebhookRemoteEvent;
use Dmstr\Webhook\Model\Actor;
use Dmstr\Webhook\Model\AttributeKind;
use Dmstr\Webhook\Model\EventContext;
use Dmstr\Webhook\Model\EventFacts;
use Dmstr\Webhook\Model\Fact;
use Dmstr\Webhook\Model\FilterAttributes;
use Dmstr\Webhook\Model\Reference;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\RemoteEvent\RemoteEvent;
use Symfony\Component\Webhook\Exception\RejectWebhookException;
#[AsWebhookAdapter('acme')]
final class AcmeParser extends AbstractWebhookParser
{
public function verificationStrategy(): VerificationStrategy
{
return VerificationStrategy::HeaderToken;
}
public function filterAttributes(): FilterAttributes
{
return new FilterAttributes(['project_id' => AttributeKind::Integer]);
}
protected function doParse(Request $request, #[\SensitiveParameter] string $secret): ?RemoteEvent
{
// Constant-time comparison with the endpoint's decrypted secret.
$token = $request->headers->get('X-Acme-Token');
if (null === $token || '' === $secret || !hash_equals($secret, $token)) {
throw new RejectWebhookException(401, 'Invalid token.');
}
$payload = self::jsonPayload($request);
$deliveryId = $payload['delivery_id'] ?? null;
if ('comment' !== ($payload['event'] ?? null) || !\is_string($deliveryId) || '' === $deliveryId) {
return null; // accepted, nothing stored
}
$user = \is_array($payload['user'] ?? null) ? $payload['user'] : [];
$projectId = $payload['project_id'] ?? null;
$body = $payload['comment']['body'] ?? null;
$handle = self::endpointHandle($request);
$context = new EventContext(
actor: \is_int($user['id'] ?? null) ? new Actor((string) $user['id'], \is_string($user['name'] ?? null) ? $user['name'] : null) : null,
project: \is_int($projectId) ? new Reference(Reference::PROJECT, (string) $projectId) : null,
facts: new EventFacts(
systemGenerated: Fact::fromBool(\is_bool($payload['system'] ?? null) ? $payload['system'] : null),
edit: Fact::fromBool(\is_bool($payload['edited'] ?? null) ? $payload['edited'] : null),
// The source does not tell confidentiality: unknown, the filter never fires.
mentionsEndpoint: null === $handle || !\is_string($body)
? Fact::Unknown
: Fact::fromBool(1 === preg_match('/(?<![\w@-])@'.preg_quote($handle, '/').'(?![\w-])/i', $body)),
),
// Only declared attributes; never the comment text.
attributes: \is_int($projectId) ? ['project_id' => $projectId] : [],
);
// Name: the CloudEvents type; id: the complete dedupe key.
return new WebhookRemoteEvent('acme.comment', $deliveryId, $payload, null, $context);
}
}dmstr_webhook:
adapters:
acme: trueRules for an adapter:
- Verify before anything else and compare in constant time; never log the secret, the presented credential or the payload.
- Return a stable dedupe key: the sender's delivery or message id where there is one, otherwise a hash of the body or of the fields that identify the event.
- Report an actor by its stable id, unknown facts as
Fact::Unknown, and no text of the source in the context. - Do no processing in the parser; the request path ends with storing and deciding on the event, and source-specific work belongs in a delivery handler.
- Add the header that carries the credential to the access-log filter of the reverse proxy and, unless it is one the shipped processor knows, to a redaction processor of the application (see Log redaction).
0.2.0 breaks 0.1.x installations; read this before deploying it.
-
Run the migrations (
php bin/console doctrine:migrations:migrate).Dmstr\Webhook\Migrations\Version20261203182500adds the columnwebhook_endpoint.mode, sets every existing endpoint toprocessand creates the tablewebhook_route. -
Switch endpoints that feed delivery handlers to
handler. After the migration an existing endpoint is in the modeprocesswith an empty allowlist and no routes: its deliveries are still answered202, but every event is storedignoredwith a reason (actor_not_allowedfor the shipped adapters) and none reaches a delivery handler until the endpoint is switched:php bin/console webhook:endpoint:update <slug-or-uuid> --mode=handler
or
PATCH /api/admin/webhook_endpoints/{id}with{"mode": "handler"}(application/merge-patch+json). Events stored asignoredbefore the switch are not handed over afterwards. -
Pass the mode wherever endpoints are created.
modehas no default: a POST without it answers 422, andwebhook:endpoint:createneeds--mode=processor--mode=handler. Update scripts, fixtures and tests that create endpoints. -
Adapters that implement
WebhookAdapterInterfacedirectly must addfilterAttributes(); adapters extendingAbstractWebhookParserinheritFilterAttributes::none(). -
Delivery handlers now set the terminal status of their events with
EventStatusTransition; without it the events stayreceived. A handler that throws leaves its eventfailed. -
Changed constructors. Application code that builds these classes itself instead of through the container has to follow the new signatures:
WebhookIntaketakesEventFilter,ActorRateLimiterandEventRouterafterEventStore;EndpointRateLimitertakes aSlidingWindowLimiterinstead of the storage and lock factory;DeliveryHandOfftakesEventStatusTransitionafter the handlers;IntakeOutcome::accepted()takes the deliveries for the hand-over, the event dispositions and the endpoint's mode;EventStore::insert()takes an optional status and reason.
- Starting the process of a
routedevent (the statusesstartedandcompleted, and the event fieldsprocessInstanceId,replyReferenceanderror): the bundle stops atrouted. - Answering in the source on its own: the bundle ships the GitLab reply client, but nothing in the bundle calls it; the application decides when to answer.
- A detail view of an event with its payload.
- A retention purge of old events.
- Re-delivery of events that stayed
received(a lost hand-over or a missing handler).
The PHPUnit suites live in this repository (configuration ./phpunit.dist.xml, PHPUnit 12 or 13):
unit(./tests/Unit): no kernel, no database; the intake, the filters, the limiters, the router, the adapters, the console twins and the container wiring against stubs and in-memory doubles (./tests/Support).integration(./tests/Integration): boots the test kernel./tests/Kernel/TestKernel.php, a minimal host application with the dependency bundles, header-based test authentication (X-Test-User,X-Test-Roles) with neutral test roles (./tests/Kernel/TestRoles.php,ROLE_WEBHOOK_ADMIN) and a test permission voter that maps the bundle's permissions to them, a frozenclock(MockClock) for the Standard Webhooks replay window, test adapters with an event context, and the log channelswebhookandrequestin a test log file. Kernel variants cover a host without theclockservice, without a lock factory, MonologBundle andhttp_client, and the GitLab reply client without its library (simulated by building the bundle withnew OptionalLibraries([Gitlab\Client::class])), with the adaptergitlabdisabled, enabled, and with the host's own reply transport. Tests in the groupdatabaseneed PostgreSQL or MySQL 8 fromDATABASE_URL(PostgreSQL by default inphpunit.dist.xml; the database name must end with_test, because one test drops every table);./tests/Kernel/TestDatabase.phpcreates the schema once per process by running all registered migrations, the bundle's own ones included, and one test runs them on an empty database to prove their order. The same tests run on both platforms; the few statements that cannot be portable branch on the DBAL platform.
The intake is covered by a data-driven matrix: each row (./tests/Support/IntakeCase.php) is an endpoint configuration, one request and the expected status, reason, route and hand-over in each mode (./tests/Support/IntakeExpectation.php). ./tests/Support/IntakeHarness.php runs a row without kernel and database (the real intake over an in-memory store), the group database runs the same rows against the database. The source-neutral rows (./tests/Support/IntakeMatrix.php) use the test adapters ./tests/Kernel/ContextTestAdapter.php (context from the JSON body), ./tests/Kernel/ActorlessTestAdapter.php (a source without actor and facts) and ./tests/Kernel/FilterAttributesTestAdapter.php (one declared attribute of each kind). A source adapter with fixtures adds its rows in its own data provider with the same row shape. Its fixtures are YAML files under ./tests/Fixtures/<source>/, one delivery per file with origin, headers and body, loaded through ./tests/Support/FixtureSet.php; origin is captured (a recorded delivery with neutral values), documented (<source of the shape>) (built from the source's documentation, every value invented, for a source without recorded deliveries) or derived from <fixture> (<what changed>) (single values of another fixture of the same source changed). ./tests/Support/FixtureMatrix.php turns fixtures into rows with the source's default endpoint and, for a path secret source, the secret path segment of every request; the traits ./tests/Support/FixtureSequenceTests.php and ./tests/Support/IntakeHarnessSequences.php run a source's sequences (several deliveries to one endpoint, then the event rows in order) without database, and ./tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php runs them against the database. Two sources have fixtures: GitLab (./tests/Support/GitlabFixtures.php, ./tests/Support/GitlabMatrix.php), whose fixtures are captured GitLab 15.11 deliveries with neutral values or derived from them, and Basecamp 4 (./tests/Support/Basecamp4Fixtures.php, ./tests/Support/Basecamp4Matrix.php), whose fixtures are all documented or derived, none captured. ./tests/Unit/Fixtures/FixtureAnonymisationTest.php guards the anonymisation with one definition per source: structural rules on every fixture (only the source's example.com hosts, no redaction placeholders, no avatar service, ASCII only, a valid origin, the source's headers with fixture values only), and, when the source's environment variable points to a local directory of raw captures (never committed; WEBHOOK_RAW_CAPTURES_DIR for GitLab, WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4 for Basecamp 4), a check that no value of those captures occurs in any fixture of any source; without the variable that check is skipped. ./tests/Unit/Intake/Basecamp4LogTest.php runs Basecamp 4 deliveries through the intake with a logger without the redaction processor and fails if a raw log record carries the secret path segment, the request path or any text of the payload; a deliberately leaking test adapter proves that the check detects a leak.
composer install
vendor/bin/phpunit --testsuite unit
vendor/bin/phpunit --testsuite integration --exclude-group database
# with a PostgreSQL server (e.g. the image postgres:16):
DATABASE_URL='postgresql://app:app@127.0.0.1:5432/webhook_test?serverVersion=16&charset=utf8' vendor/bin/phpunit
# with a MySQL 8 server (e.g. the image mysql:8.0 with
# --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci):
DATABASE_URL='mysql://app:app@127.0.0.1:3306/webhook_test?serverVersion=8.0.40&charset=utf8mb4' vendor/bin/phpunitcomposer install needs both pdo_pgsql and pdo_mysql (development requirements). CI is the GitHub Action ./.github/workflows/tests.yml (PHP 8.5 with pdo_pgsql and pdo_mysql), a matrix of two jobs that run both suites including the group database: one against the service container postgres:16, one against mysql:8.0 with the character set and collation above.
MIT, see LICENSE.