Skip to main content

Crate octoevents

Crate octoevents 

Source
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: the WebhookMeta read 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::new builds one from a WebhookMeta and 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 the WebhookMeta’s; the rest are decoded from the payload by EventMeta::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 input I, any FromEnvelope, built from the envelope and its EventMeta: the Envelope, the EventMeta, a Payload view (a serde type declaring its kind with #[derive(Payload)]), or Event<P> for the meta beside the payload. An async fn, a struct, a closure, or an Arc of any of them, with any error that converts into BoxError: an Error + Send + Sync + 'static type of its own (any Error + 'static on wasm32), BoxError itself, anyhow::Error, a String.
  • Dispatcher: a handler over the envelope that routes to other handlers by kind and action in three tiers, always, route and fallback, and reports an Outcome. Built with DispatcherBuilder, whose routes take an IntoMatcher: an EventMatcher shape that says its kinds, or, for a handler over a payload, actions alone or AnyAction. Each handler’s error is boxed where it is registered, so handlers share no error enum. A failure is a DispatchError naming 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 wrapping dispatch, the policy seam.
  • WebhookReceiver: authenticates, bounds and dispatches one request, through WebhookReceiver::receive over an http::Request (http-body feature) or WebhookReceiver::receive_bytes over the http::HeaderMap and the body already read, answered as the http::StatusCode. Built with WebhookReceiverBuilder, which takes the Verifier (or a VerifierSource choosing one per request from the WebhookMeta, for several GitHub Apps at one URL), the body limit and ping handling.
  • Verifier and WebhookSecret: the configured secrets and the HMAC comparison; Verifier::also opens a rotation window, and Verifier::sign signs a test’s synthetic request. The header value parsed is a Signature, which is where a malformed one is refused; a signature that does not authenticate is a SignatureError.
  • authenticate and ReceiveError::status: the receiving path for a transport that wants the envelope and not the receiver’s answer. authenticate takes the same http::HeaderMap and body bytes the receiver does and produces the envelope; a failure is a ReceiveError, and status maps it to the http::StatusCode the receiver would answer. The header names are in header.

Always pass the exact request bytes. Parsing, re-encoding, or normalizing the body before verification invalidates GitHub’s signature.

§Features

FeatureDefaultProvides
http-bodyyesWebhookReceiver::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
deriveyes#[derive(Payload)], declaring a serde type’s kind with #[payload(EventKind::..)]; without it, a payload is declared with a three-line impl Payload
towernotower_service::Service for WebhookReceiver
octocrabnoFromEnvelope for octocrab’s WebhookEvent and Payload for its per-kind payload structs; see Feature caveats
tracingnoThe 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, around WebhookReceiver::receive and WebhookReceiver::receive_bytes alike, which share it. It records delivery_id and event from the headers as soon as they are read, before verification, and on the way out outcome and status, the HTTP code answered. outcome is one of ok, bad_request, unauthorized, payload_too_large and handler_error. A request refused before any handler ran also records the text of the ReceiveError that selected its status as error: outcome says the class of the answer, error which 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, around Verifier::verify, inside the receive span. It records secret_count and body_len on open and outcome on the way out: verified or mismatch. It is the detail behind the receive span’s unauthorized outcome, 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 as bad_request or unauthorized with the refusal’s text as error. So does a request whose target a VerifierSource has no verifier for, unauthorized as ReceiveError::UnknownTarget.
  • octoevents.dispatch, at INFO, around Dispatcher::dispatch, inside the receive span when the dispatcher is the receiver’s handler. It records delivery_id, event and, when the decoded meta has them, action and installation_id on open; on the way out outcome, one of ok, handler_error, unmatched_ok and unmatched_error, and when a handler failed its name as handler and its registration site as registration_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 always or fallback tier is unmatched_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§

AccountMeta
An account’s meta, the numeric ID and the login: the two fields EventMeta::decode keeps 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::on registration.
BodyError
The transport’s reason a webhook body could not be read, as text.
Bytes
The byte buffer type of Envelope::raw_payload and of the body authenticate takes, re-exported from the bytes crate.
DispatchError
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.
DispatcherBuilder
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 EventMeta beside the payload decoded as P.
EventMatcher
The kinds and actions one dispatcher registration selects.
EventMeta
The routing metadata of a delivery: the WebhookMeta read 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.
RepositoryMeta
The repository’s meta: the fields EventMeta::decode keeps of the payload’s repository object, read without decoding a full payload model.
Signature
A parsed X-Hub-Signature-256 value: the 32 MAC bytes.
UnknownAction
A wire string unknown to Action.
UnknownEventKind
A wire string unknown to EventKind.
UnknownTargetType
A wire string unknown to TargetType.
Verifier
The configured secrets, and the HMAC comparison they authenticate with.
WebhookMeta
The meta of the request GitHub sends, read from its headers alone: the delivery ID, the kind, and the target type and ID.
WebhookReceiver
Authenticates, bounds, and dispatches GitHub webhooks.
WebhookReceiverBuilder
Builds a WebhookReceiver.
WebhookSecret
A webhook secret whose owned bytes are zeroed when dropped.

Enums§

Action
The payload’s top-level action value: GitHub’s sub-classification of an event, opened or closed for issues, created for installation.
DecodeError
Why an envelope’s payload could not be decoded.
EventKind
The event kind, parsed from the X-GitHub-Event event name.
Match
Whether a delivery matched the route table.
ReceiveError
A failure while receiving a webhook.
SignatureError
A failure to authenticate a webhook body by its signature.
TargetType
The resource on which the webhook is installed, from X-GitHub-Hook-Installation-Target-Type: integration for a GitHub App, repository for a repository webhook and organization for an organization webhook.
WebhookSecretError
Bytes that cannot be a WebhookSecret.

Constants§

DEFAULT_BODY_LIMIT
GitHub’s maximum delivered payload size: 25 MiB.

Traits§

FromEnvelope
A handler’s input, decoded from an Envelope and its EventMeta.
Handler
Consumer-owned code that handles one delivery, received as I.
IntoMatcher
What DispatcherBuilder::on accepts as the matcher for a handler over I.
MaybeSend
Send on native targets; no requirement on wasm32.
MaybeSync
Sync on native targets; no requirement on wasm32.
Payload
One event kind’s decoded payload.
VerifierSource
What a receiver asks, per request and before verifying it, for the Verifier of 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 Envelope that can be trusted.

Type Aliases§

BoxErrorNon-WebAssembly
The erased error: what every handler’s error converts into at registration, and what a DispatchError holds as its source.

Derive Macros§

Payloadderive
Derives Payload for a serde type, declaring its kind: #[derive(Payload)] #[payload(EventKind::..)]. See the trait. Declares which EventKind a serde type is the payload of.