dmstr / webhook-bundle
Symfony bundle for incoming webhooks: endpoints per source (slug, encrypted write-only secret, IP allowlist, limits) with an audited admin API for API Platform, an event trail aligned with CloudEvents, and source adapters on the RequestParser contract of symfony/webhook, enabled per source by bundle
Requires
- php: >=8.5
- api-platform/core: ^4.4.8
- dmstr/api-configuration-bundle: ^0.7
- dmstr/api-platform-utils-bundle: ^0.6
- doctrine/dbal: ^3.8
- doctrine/doctrine-bundle: ^2.14
- doctrine/doctrine-migrations-bundle: ^3.4
- doctrine/migrations: ^3.9
- doctrine/orm: ^3.3
- gedmo/doctrine-extensions: ^3.20
- psr/clock: ^1.0
- psr/container: ^1.1 || ^2.0
- psr/log: ^1.0 || ^2.0 || ^3.0
- symfony/config: ^7.4
- symfony/console: ^7.4
- symfony/dependency-injection: ^7.4
- symfony/doctrine-bridge: ^7.4
- symfony/event-dispatcher: ^7.4
- symfony/framework-bundle: ^7.4
- symfony/http-foundation: ^7.4
- symfony/http-kernel: ^7.4
- symfony/rate-limiter: ^7.4
- symfony/remote-event: ^7.4
- symfony/serializer: ^7.4
- symfony/uid: ^7.4
- symfony/validator: ^7.4
- symfony/webhook: ^7.4
Requires (Dev)
- ext-pdo_pgsql: *
- dmstr/doctrine-audit-log-bundle: ^0.4
- dmstr/openapi-json-schema-bundle: ^0.5
- monolog/monolog: ^3.0
- phpunit/phpunit: ^12.0 || ^13.0
- symfony/browser-kit: ^7.4
- symfony/clock: ^7.4
- symfony/http-client: ^7.4
- symfony/lock: ^7.4
- symfony/monolog-bundle: ^3.10
- symfony/routing: ^7.4
- symfony/security-bundle: ^7.4
- symfony/yaml: ^7.4
Suggests
- dmstr/doctrine-audit-log-bundle: Provides a Gedmo loggable listener and log entry entity, so every endpoint change (including each secret rotation as a timestamp) is recorded with its actor.
- monolog/monolog: Version 3 is needed by `Dmstr\Webhook\Log\WebhookSecretRedactionProcessor`, which masks webhook secrets in every log record where MonologBundle registers it.
- symfony/cache: Provides the cache pool `cache.rate_limiter` of FrameworkBundle, which holds the sliding-window counters of the endpoint rate limit (FrameworkBundle installs it; use a shared adapter such as Redis when several PHP containers serve the intake).
- symfony/clock: Registers the `clock` service of FrameworkBundle, which the Standard Webhooks adapter then uses for its replay window (system time without it); tests freeze it with `MockClock`.
- symfony/lock: Lets the endpoint rate limiter lock its sliding window, so concurrent deliveries of one endpoint do not overshoot the limit.
- symfony/monolog-bundle: Registers the log channel `webhook` the bundle writes rejected deliveries and failed hand-offs to, and the secret redaction processor.
- symfony/security-bundle: Provides the firewall the intake needs and the `is_granted()` checks of the admin API resources.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-30 22:38:49 UTC
README
dmstr/webhook-bundle
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 it exactly once per endpoint and dedupe key, and answers immediately; processing happens later, behind a hand-off seam that runs after the response. Endpoints 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
- Secrets
- Intake
- Hand-off
- Adapters
- Events
- Audit and logging
- Log redaction
- Trusted proxies
- Console commands
- Writing an own adapter
- Not built yet
- Tests
Requirements
- PHP 8.5, Symfony 7.4, API Platform 4.4, Doctrine ORM 3 with DBAL 3.8 or later (tested on PostgreSQL; the migration uses the portable Schema API)
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 window per endpoint) with the cache poolcache.rate_limiterof FrameworkBundle (symfony/cache, which FrameworkBundle installs);symfony/lock(recommended) keeps concurrent deliveries of one endpoint from overshooting the limitpsr/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(the endpoint isLoggable); 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)
The bundle requires neither a process engine nor a specific platform bundle; a reference to a process engine is only a connection record.
Installation and wiring
The bundle is published on Packagist. Install it with Composer:
composer require dmstr/webhook-bundle
Bundle and migrations
Symfony 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, its API Platform resource path and its migrations path (namespace Dmstr\Webhook\Migrations). Run the migrations:
php bin/console doctrine:migrations:migrate
The migration creates 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.
Routes
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'
FrameworkBundle integration
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: false
The admin resources come with the API Platform routes of the application (/api/admin/webhook_endpoints and /api/admin/webhook_events when API Platform is mounted at /api).
Firewall and access control
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 }
Permissions
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 |
the admin API of routes (reserved, see Not built yet) |
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.
Encryption key
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.
Configuration reference
# config/packages/dmstr_webhook.yaml dmstr_webhook: adapters: 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.
Endpoints
/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 |
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), so later processing 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) |
allowedActorIds |
list of strings | [] |
actor ids in the source that may trigger processing; stored now, applied by a later stage |
actorRateLimit |
int, 1 to 10000 | 20 |
runs per actor and hour; stored now, applied by a later stage |
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", "secret": "'"${WEBHOOK_SECRET}"'", "ipAllowlist": ["192.0.2.0/24"]}'
Deleting an endpoint deletes its events (ON DELETE CASCADE).
Secrets
- 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 '='
Intake
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 stored once per (endpoint, dedupe key) and answered 202 Accepted with {"status":"accepted"}. 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. The request path does nothing beyond the lookup, the verification and one database insert per event; the new events are passed to the hand-off after the response.
Rate limit before verification. The 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, GitLab for example, 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.
Body cap. The cap of an endpoint can only lower the 1 MiB of the reverse proxy, never raise it.
Hand-off
The seam after the intake 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) and source (/webhook/<slug>).
- Every service implementing the interface is autoconfigured with the tag
dmstr_webhook.delivery_handler. - Handlers run after the response: on
kernel.terminatefor HTTP (with php-fpm after the response was sent), and after the command printed the response forwebhook:deliver. - They receive only newly stored events; a duplicate is not handed off, its first delivery was.
- An exception of a handler is logged on the channel
webhook(slug,event_id,handler,exception_class; no payload), the other handlers still run, and the delivery stays accepted. - 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. Return early for sources the handler does not serve (
$delivery->endpoint->getSourceType()).
The bundle ships no implementation yet; without one, accepted events stay in status received.
Adapters
An adapter is a symfony/webhook request parser for one source type that also declares its verification strategy (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. 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 |
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.
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 the hand-off 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.
Events
/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 |
received, ignored, routed, started, completed or failed |
reason |
why the event has its status |
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, processInstanceId, replyReference, error |
filled by 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.
Audit and logging
- Endpoint 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. - Failed hand-offs write one
errorline on the channelwebhookper failing handler (see Hand-off).
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 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.json
Log redaction
A 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.
Trusted proxies
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 commands
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> [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: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 of webhook:event:list is long-only, because -e is --env; the remaining shortcuts are -l for --limit of both list commands and -f for --force of webhook:endpoint:delete. The options of create and update are the endpoint fields: --source-type, --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.
- 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.
php bin/console webhook:endpoint:create ci-builds --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:event:list --endpoint=ci-builds --status=received
webhook:deliver is the twin of the intake: it runs the raw body in <file> through the same checks, the same rejection log line and the same storage as the HTTP route, prints the status code and the response body (202 {"status":"accepted"}), and then hands the new events off like the HTTP path.
<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).- Exit code
0when the delivery is accepted (also a duplicate),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.10
Like --secret=<value>, a --header value with a token lands in the shell history and the process list; use it for tests and diagnosis.
Writing an own adapter
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 verificationStrategy(): VerificationStrategy, the enum Dmstr\Webhook\Adapter\VerificationStrategy with the cases HeaderToken, PathSecret and StandardWebhooks. 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 and offers bodyHash() (SHA-256 hex of the raw body) and jsonPayload() (the body decoded as a JSON object or array, an empty array otherwise). Return a Dmstr\Webhook\Adapter\WebhookRemoteEvent to also pass the event time; a plain RemoteEvent has none.
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. - 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.createSuccessfulResponse()andcreateRejectedResponse()are not used: the intake's responses are the same for every source.
use Dmstr\Webhook\Adapter\AbstractWebhookParser; use Dmstr\Webhook\Adapter\AsWebhookAdapter; use Dmstr\Webhook\Adapter\VerificationStrategy; use Dmstr\Webhook\Adapter\WebhookRemoteEvent; 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; } 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); $event = $payload['event'] ?? null; $deliveryId = $payload['delivery_id'] ?? null; // Name: the CloudEvents type; id: the dedupe key. return new WebhookRemoteEvent( 'acme.'.(\is_string($event) ? $event : 'unknown'), \is_string($deliveryId) && '' !== $deliveryId ? $deliveryId : self::bodyHash($request), $payload, ); } }
dmstr_webhook: adapters: acme: true
Rules 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.
- Do no processing in the parser; the request path ends with storing 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).
Not built yet
- The GitLab adapter (header token
X-Gitlab-Token) and its payload parsing. - Routes and filters: which events start which processing (
webhook:route:manageis reserved for their admin API), the allowlist of triggering actors and the per-actor rate limit (stored on the endpoint, not applied). - A detail view of an event with its payload.
- A retention purge of old events.
- Starting processes or any other processing of the stored events: no
DeliveryHandlerInterfaceimplementation ships yet.
Tests
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 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, and the log channelswebhookandrequestin a test log file. Kernel variants cover a host without theclockservice, without a lock factory and without MonologBundle. Tests in the groupdatabaseneed PostgreSQL fromDATABASE_URL(default inphpunit.dist.xml; the database name must end with_test);./tests/Kernel/TestDatabase.phpcreates the schema once per process by running all registered migrations, the bundle's own one included, and one test runs them on an empty database to prove their order.
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
CI is the GitHub Action ./.github/workflows/tests.yml (PHP 8.5 with pdo_pgsql, service container postgres:16), which runs both suites including the group database.
License
MIT, see LICENSE.