Expand description
Receive and verify GitHub webhook events.
octoevents is the receiving edge of a GitHub App: it turns an untrusted
HTTP request into a verified Envelope and hands it to your handlers.
The core is wasm-safe: one receiver over http types serves
Axum, Cloudflare Workers, and anything else that can hand over a request.
A receiver that thanks the author of every opened issue:
use octoevents::{
Action, BoxError, Dispatcher, EventKind, EventMeta, Verifier, WebhookReceiverBuilder,
WebhookSecret,
};
// Runs for `issues.opened`, handed the delivery's meta (delivery ID, kind,
// action, repository, sender, ...), which the dispatcher decoded from the
// payload the receiver authenticated.
// `BoxError` is the crate's erased error; any
// `Error + Send + Sync + 'static` converts into it with `?`, and a
// handler with an error type of its own keeps it.
async fn thank(meta: EventMeta) -> Result<(), BoxError> {
let sender = meta.sender.map(|s| s.login).unwrap_or_default();
println!("Thank you for your contribution, @{sender}! :)");
Ok(())
}
// Routes each verified envelope by kind and action.
let dispatcher = Dispatcher::builder()
.on((EventKind::Issues, Action::Opened), thank)
.build();
// Verifies `X-Hub-Signature-256` against the body with the secret, refuses
// what does not verify, and hands everything else to the dispatcher.
let webhook = WebhookReceiverBuilder::new(Verifier::new(WebhookSecret::new("development-secret")))
.build(dispatcher);webhook mounts on any router that hands over an http request: with the
tower feature as a Service (post_service(webhook) on Axum), or as a
plain handler calling WebhookReceiver::receive. It owns no paths or
methods. The response is a bare status: 204 when the handler succeeded,
500 when it failed, and 401, 400 or 413 for a request that never reached
one.
The README is the landing page and runnable quickstart. The integration guide covers real deliveries, handlers, testing and transports; recovery, observability and security cover operating a receiver. This page maps the crate’s concepts and states the API contracts.
Repository guides track the current checkout. For an older release, use its Git tag and versioned API docs; review the release notes before upgrading.
§Concepts
Envelope: the unit of receipt, what arrived: theWebhookMetaread from the headers beside the exact payload bytes. Building one reads nothing of the payload and cannot fail. It is data and makes no claim that it was authenticated:Envelope::newbuilds one from aWebhookMetaand the bytes, and an envelope a trusted transport forwarded is read back through serde.authenticate: the one path from an untrusted request to an envelope that can be trusted. It verifies the signature over the body, then builds the envelope; the receiver is built on it, and a received envelope is trustworthy because it came from there.EventMeta: the delivery ID,EventKind,Action, installation ID, repository, organization, sender and target. The first two and the target are theWebhookMeta’s; the rest are decoded from the payload byEventMeta::decode, strictly, in GitHub’s shape. The dispatcher decodes it once per delivery, since it routes by the action and the action is in the payload, and hands it to every input it builds; a payload whose meta does not decode fails the delivery there.Handler<I>: consumer code over one inputI, anyFromEnvelope, built from the envelope and itsEventMeta: theEnvelope, theEventMeta, aPayloadview (a serde type declaring its kind with#[derive(Payload)]), orEvent<P>for the meta beside the payload. Anasync fn, a struct, a closure, or anArcof any of them, with any error that converts intoBoxError: anError + Send + Sync + 'statictype of its own (anyError + 'staticonwasm32),BoxErroritself,anyhow::Error, aString.Dispatcher: a handler over the envelope that routes to other handlers by kind and action in three tiers, always, route and fallback, and reports anOutcome. Built withDispatcherBuilder, whose routes take anIntoMatcher: anEventMatchershape that says its kinds, or, for a handler over a payload, actions alone orAnyAction. Each handler’s error is boxed where it is registered, so handlers share no error enum. A failure is aDispatchErrornaming the handler and its registration site, the boxed error its source, or naming no handler when the meta did not decode. The policy the tiers cannot express lives in a handler wrappingdispatch, the policy seam.WebhookReceiver: authenticates, bounds and dispatches one request, throughWebhookReceiver::receiveover anhttp::Request(http-bodyfeature) orWebhookReceiver::receive_bytesover thehttp::HeaderMapand the body already read, answered as thehttp::StatusCode. Built withWebhookReceiverBuilder, which takes theVerifier(or aVerifierSourcechoosing one per request from theWebhookMeta, for several GitHub Apps at one URL), the body limit andpinghandling.VerifierandWebhookSecret: the configured secrets and the HMAC comparison;Verifier::alsoopens a rotation window, andVerifier::signsigns a test’s synthetic request. The header value parsed is aSignature, which is where a malformed one is refused; a signature that does not authenticate is aSignatureError.authenticateandReceiveError::status: the receiving path for a transport that wants the envelope and not the receiver’s answer.authenticatetakes the samehttp::HeaderMapand body bytes the receiver does and produces the envelope; a failure is aReceiveError, andstatusmaps it to thehttp::StatusCodethe receiver would answer. The header names are inheader.
Always pass the exact request bytes. Parsing, re-encoding, or normalizing the body before verification invalidates GitHub’s signature.
§Features
| Feature | Default | Provides |
|---|---|---|
http-body | yes | WebhookReceiver::receive over an http::Request whose body is an http_body::Body, answering an http::Response; the receiver itself, its builder and WebhookReceiver::receive_bytes are in the core |
derive | yes | #[derive(Payload)], declaring a serde type’s kind with #[payload(EventKind::..)]; without it, a payload is declared with a three-line impl Payload |
tower | no | tower_service::Service for WebhookReceiver |
octocrab | no | FromEnvelope for octocrab’s WebhookEvent and Payload for its per-kind payload structs; see Feature caveats |
tracing | no | The spans and the failed-delivery event under Tracing |
The core (envelope, verification, the handler trait and its inputs, the
dispatcher, the receiver over headers and bytes) depends on none of them
and builds for wasm32-unknown-unknown. authenticate and
WebhookReceiver::receive_bytes over an http::HeaderMap, the
header constants and ReceiveError::status as an http::StatusCode
are part of it: the http crate is not optional, since every surveyed
Rust runtime hands over its types, and it adds one entry to the dependency
tree.
§Tracing
With the tracing feature, a delivery runs in three spans:
octoevents.receive, at INFO, aroundWebhookReceiver::receiveandWebhookReceiver::receive_bytesalike, which share it. It recordsdelivery_idandeventfrom the headers as soon as they are read, before verification, and on the way outoutcomeandstatus, the HTTP code answered.outcomeis one ofok,bad_request,unauthorized,payload_too_largeandhandler_error. A request refused before any handler ran also records the text of theReceiveErrorthat selected its status aserror:outcomesays the class of the answer,errorwhich refusal it was. The text alone, the crate’s own fixed wording for each refusal; the error’s source, for a body that could not be read the transport’s own error text, stays off the span, since a transport may quote the request in it.octoevents.verify, at DEBUG, aroundVerifier::verify, inside the receive span. It recordssecret_countandbody_lenon open andoutcomeon the way out:verifiedormismatch. It is the detail behind the receive span’sunauthorizedoutcome, which is why it opens a level below it. A header that is absent or malformed is refused from the headers before the verifier is asked, so it opens no verify span: the receive span records that refusal asbad_requestorunauthorizedwith the refusal’s text aserror. So does a request whose target aVerifierSourcehas no verifier for,unauthorizedasReceiveError::UnknownTarget.octoevents.dispatch, at INFO, aroundDispatcher::dispatch, inside the receive span when the dispatcher is the receiver’s handler. It recordsdelivery_id,eventand, when the decoded meta has them,actionandinstallation_idon open; on the way outoutcome, one ofok,handler_error,unmatched_okandunmatched_error, and when a handler failed its name ashandlerand its registration site asregistration_site.
A field recorded in more than one place is recorded in one form
everywhere: delivery_id, event and action as strings,
installation_id as an integer, and outcome as a string label with its
own vocabulary per span. error is the error’s text to every subscriber
wherever it appears; the failed-delivery event records it as an error
value, so a subscriber that walks sources renders the chain beneath it
too, where the receive span records a refusal’s text alone. The one value
two vocabularies share, handler_error, partitions differently on the two
spans:
- on the receive span it is every delivery a handler failed, since any handler error is a 500;
- on the dispatch span it is a matched delivery a handler failed; an
unmatched delivery failed by its
alwaysorfallbacktier isunmatched_error.
So a receive handler_error is a dispatch handler_error or
unmatched_error.
A failed delivery also emits one event at ERROR, handler failed, with
delivery_id and event from the headers, action and
installation_id when the handler failed with a DispatchError whose
decoded meta has them, and the handler’s error, boxed, as error: an error
value, so the subscriber renders its text and the chain of sources beneath
it (the fmt subscriber prints error=<text> error.sources=[<cause>, ..]). With a dispatcher the text says where (the handler and its
registration site) and the chain why (the application error, and its
own sources). A subscriber filtering at ERROR sees every failed delivery
and why; the 500 it is answered with is
the receive span’s status, since a handler failure is answered nothing
else. A successful delivery, a request refused before any handler ran and
a short-circuited ping emit no event. Custom error reporting belongs in
the handler, which can inspect its result before returning it.
Nothing secret-derived is recorded anywhere: not the secret, the signature header, nor a computed MAC.
§Feature caveats
Enabling the octocrab feature makes octocrab’s pre-1.0 version part of
this crate’s public API: the FromEnvelope impl for its WebhookEvent
and the Payload impls for its per-kind payload structs expose octocrab’s
types, so an incompatible octocrab release (including a pre-1.0 minor
bump such as 0.54 to 0.55) is a breaking change for handlers over
them. octocrab goes in the
consumer’s own [dependencies] too, to name those types; this crate
re-exports none of them. The core (envelope, verification, receiver, the
handler trait and its inputs, and the whole dispatcher) does not depend on
it.
octoevents selects no octocrab JWT backend. octocrab’s defaults select
jwt-rust-crypto; when disabling its defaults, enable exactly one of
jwt-rust-crypto (also supported on wasm) or jwt-aws-lc-rs in your own
octocrab dependency. octocrab requires a backend even for model-only use.
The trade-off of octocrab’s types is whole-model decode: the struct names
far more of the payload than a handler reads, and an incompatible change
to any field it names (removed, renamed, retyped, or made null) fails the
delivery with 500, where a view names the fields its handler reads and
fails only on those; a field GitHub adds fails neither. A test fixture for
a struct is a complete payload, since the structs decode no fragment.
Many of the structs leave their main object untyped, as
serde_json::Value (check_run, check_suite, workflow_run,
workflow_job, release, deployment, discussion, label,
milestone and team among them). The per-kind payload structs mostly
omit the top-level installation, sender, repository and
organization objects, which its WebhookEvent carries and
EventMeta summarizes.
Known decoding limitation in octocrab 0.54.1: code_scanning_alert
and repository_advisory fail as WebhookEvent or Event<WebhookEvent>
even when their payloads fit the per-kind models. The decoder removes
common fields that those models require, producing DecodeError::Json
(500 through the receiver, before the routed handler runs). For these
kinds, use CodeScanningAlertWebhookEventPayload or
RepositoryAdvisoryWebhookEventPayload, optionally inside Event, or a
consumer-defined view. These inputs decode the original payload directly.
Modules§
- header
- The names of the request headers this crate reads, as
http::HeaderNames.
Structs§
- Account
Meta - An account’s meta, the numeric ID and the login: the two fields
EventMeta::decodekeeps of the payload’s account objects, a user’s, an organization’s or an app’s, read without decoding a full payload model. - AnyAction
- Every action of the kind a handler’s payload type declares, as the
matcher of a
DispatcherBuilder::onregistration. - Body
Error - The transport’s reason a webhook body could not be read, as text.
- Bytes
- The byte buffer type of
Envelope::raw_payloadand of the bodyauthenticatetakes, re-exported from thebytescrate. - Dispatch
Error - The error of a failed dispatch: the application error, boxed, and where in the dispatch and in the consumer’s source it came from.
- Dispatcher
- A handler that routes verified envelopes to other handlers by kind and action.
- Dispatcher
Builder - A builder for
Dispatcher. - Envelope
- The unit of receipt: the header meta and the exact payload bytes.
- Event
- The envelope decoded for one handler, the
EventMetabeside the payload decoded asP. - Event
Matcher - The kinds and actions one dispatcher registration selects.
- Event
Meta - The routing metadata of a delivery: the
WebhookMetaread from its headers, and the fields its payload names every delivery by. - Outcome
- What one dispatch reports: whether the delivery matched, and whether the handlers that ran succeeded.
- Repository
Meta - The repository’s meta: the fields
EventMeta::decodekeeps of the payload’srepositoryobject, read without decoding a full payload model. - Signature
- A parsed
X-Hub-Signature-256value: the 32 MAC bytes. - Unknown
Action - A wire string unknown to
Action. - Unknown
Event Kind - A wire string unknown to
EventKind. - Unknown
Target Type - A wire string unknown to
TargetType. - Verifier
- The configured secrets, and the HMAC comparison they authenticate with.
- Webhook
Meta - The meta of the request GitHub sends, read from its headers alone: the delivery ID, the kind, and the target type and ID.
- Webhook
Receiver - Authenticates, bounds, and dispatches GitHub webhooks.
- Webhook
Receiver Builder - Builds a
WebhookReceiver. - Webhook
Secret - A webhook secret whose owned bytes are zeroed when dropped.
Enums§
- Action
- The payload’s top-level
actionvalue: GitHub’s sub-classification of an event,openedorclosedforissues,createdforinstallation. - Decode
Error - Why an envelope’s payload could not be decoded.
- Event
Kind - The event kind, parsed from the
X-GitHub-Eventevent name. - Match
- Whether a delivery matched the route table.
- Receive
Error - A failure while receiving a webhook.
- Signature
Error - A failure to authenticate a webhook body by its signature.
- Target
Type - The resource on which the webhook is installed, from
X-GitHub-Hook-Installation-Target-Type:integrationfor a GitHub App,repositoryfor a repository webhook andorganizationfor an organization webhook. - Webhook
Secret Error - Bytes that cannot be a
WebhookSecret.
Constants§
- DEFAULT_
BODY_ LIMIT - GitHub’s maximum delivered payload size: 25 MiB.
Traits§
- From
Envelope - A handler’s input, decoded from an
Envelopeand itsEventMeta. - Handler
- Consumer-owned code that handles one delivery, received as
I. - Into
Matcher - What
DispatcherBuilder::onaccepts as the matcher for a handler overI. - Maybe
Send Sendon native targets; no requirement onwasm32.- Maybe
Sync Syncon native targets; no requirement onwasm32.- Payload
- One event kind’s decoded payload.
- Verifier
Source - What a receiver asks, per request and before verifying it, for the
Verifierof that request: one webhook URL serving several GitHub Apps, each signing with its own secret.
Functions§
- authenticate
- Authenticates a request and builds its envelope: the one path from an
untrusted request to an
Envelopethat can be trusted.
Type Aliases§
- BoxError
Non-WebAssembly - The erased error: what every handler’s error converts into at
registration, and what a
DispatchErrorholds as its source.