Behavior for inbound webhook providers.
A provider verifies a request's signature, parses its event type, and handles
its decoded payload. Optional callbacks resolve per-connection secrets,
declare an authenticated timestamp, or identify a complete delivery.
For HTTP protocols, optional handshake/1 and response/1 callbacks let
AshHooks.Plug answer subscription challenges and sender-specific acknowledgments.
Neither callback is generated by use AshHooks.Provider; absence means it
is not implemented.
Most providers describe the sender's scheme in configuration:
defmodule MyApp.Webhooks.Orders do
use AshHooks.Provider,
verify: [algorithm: :hmac_sha256, signature: {:header, "x-orders-signature"}]
endAshHooks.Provider.Scheme documents every option, and the
Verify any sender guide has recipes for common
signature shapes. A scheme that configuration cannot express implements
verify_signature/3 with the primitives in AshHooks.Provider.Signature.
HMAC verification accepts byte secrets, AshHooks.Custody.Key values, and
rotation lists mixing both. Custody errors remain classified through ingress.
Pinned public verification keys arrive as AshHooks.Custody.PublicKey,
outside custody. Hand-written providers must preserve this value when
calling asymmetric primitives. HMAC refuses it with KeyKindMismatch.
config :ash_hooks, key_material: :custody_only refuses inbound secret and
previous_secret sources (MFA, application environment, zero-argument or
tenant-aware functions) and host webhook_signing_secret/1 or /2 callbacks
at compile time. Endpoint and worker secret_resolver options are also refused.
The generated absent-secret default is not a byte source. The setting is off
by default; byte APIs remain supported.
Providers that keep the generated parse_event_type callback return generic
typed events (AshHooks.Provider.Event).
Override parse_event_type/1 and handle_event/2 when ingress must classify
events and execute application actions. Make those actions idempotent:
durable ingress claims prevent overlapping ownership, but cannot make a remote
side effect and the ledger update one transaction.
Summary
Types
The request context verify_signature/3 receives as its second argument.
Carries everything any provider's signature scheme can need
Where a provider's webhook signing secret lives
Callbacks
Optional payload format, defaulting to JSON; :form opts into flat form decoding.
Optional payload decoder, called only after signature verification succeeds.
Returns a map or list. Providers without it retain JSON decoding. A route's
explicit body_format takes precedence. Custom decoders must return an error
for malformed input. Decoder failures normally become permanent
malformed-payload rows. If the provider's identity callback cannot derive
an identity, ingress returns an error before creating the accepted row.
A host-defined /1 needs decode_payload/2 on ledgers configuring
json_decoder. Generated JWS decoders use the request's decoder in ingress;
direct calls to their /1 use Jason.decode/1.
Optional request-aware decoder, called with verified bytes and the ledger's one-argument JSON decoder. Decode JSON only through that function, including JSON inside an envelope. Return its map or list, or an error for malformed input.
Returns a stable provider-defined identity for a decoded webhook payload.
Resolves identity with ingest context. Preferred over event_identity/1 when exported.
Handles a verified, parsed payload. Any {:ok, value} marks the receipt
processed; the value may be a struct or any other term.
Handles a receipt with durable context, at ingest and recovery. Preferred over handle_event/2 when exported.
Optional HTTP handshake, called by AshHooks.Plug after resolving the source
and capturing raw bytes, before method refusal or signature verification.
Parses the event type from the decoded request body: a map for
object-shaped deliveries, a list for batch deliveries. Providers receiving a
shape their sender never sends
fail closed through their catch-all clause ({:error, :malformed_payload}).
Parses the event type with ingest context. Preferred over parse_event_type/1 when exported.
Optional HTTP acknowledgment policy. Receives exactly the outcome returned by
AshHooks.Ingress.ingest/4. Return {status, headers, body} or :default.
Optional signature location: :header (default) requires the host-supplied
ctx.signature; :body admits signed body envelopes; :request lets the
provider extract signatures from request headers itself.
The request header this provider's signature scheme carries a trustworthy
timestamp in (nil when the scheme has none). A DSL replay_window_seconds
requires a non-nil value here. A directly configured provider is checked
at compile time; a dynamically selected provider is checked at ingestion.
Other provider-defined timestamp checks and JWS
expiration and not-before checks can apply independently.
Optional, defaulting to nil.
Authenticates the exact body and request context.
Declares whether this provider's webhook signing secret is app-level (the default) or per-connection. Optional.
Resolves the signing secret used to verify an inbound webhook.
Optional. Resolves the signing secret from the connection and the ingest
tenant, for secrets kept per tenant and connection. A provider using
use AshHooks.Provider gets a
default implementation delegating to webhook_signing_secret/1 (existing
providers compile unchanged); a per-tenant provider overrides /2.
Functions
Defines a provider. With verify: opts, generates overridable verification,
timestamp, signature-source, event-parsing, and handling callbacks from an
AshHooks.Provider.Scheme; JWS-body providers also get a payload decoder and
a payload-based event_identity/1. The options are checked when the module
finishes compiling, so an invalid option is a compile error. Write them in
place as a keyword list; their values may read module attributes set before the
use line and may be
two-argument anonymous functions (which may call the module's private
functions), remote captures, or {module, function} tuples.
Default HMAC verify implementation: lowercase-hex HMAC of the raw body under the secret, compared in constant time behind a byte-size guard.
Resolves the optional stable event identity callback.
Dispatches the optional HTTP handshake; an absent callback continues delivery.
Dispatches the optional HTTP response policy; an absent callback returns :default.
Resolves a provider's webhook secret scope, defaulting to :app_level when
the optional webhook_secret_scope/0 callback is not implemented.
Resolves a provider's trustworthy timestamp header, defaulting to nil
when the optional timestamp_header/0 callback is not implemented.
Resolves the per-connection signing secret for an ingest: an overriding
webhook_signing_secret/2 (tenant-aware custody) wins; otherwise the
call delegates to webhook_signing_secret/1, so providers of either
implementation shape work through this one entry point.
Types
@type http_response() :: {pos_integer(), [{String.t(), String.t()}], iodata()}
@type parse_error() :: :unknown_event_type | :malformed_payload
@type raw_body() :: binary()
@type signature_algorithm() :: :hmac_sha256 | :hmac_sha512
@type signature_error() :: :invalid_signature | :no_webhook_secret | :stale_timestamp | :malformed_payload | struct()
@type signature_header_value() :: binary()
@type verification_key() :: webhook_secret() | AshHooks.Custody.Key.t() | AshHooks.Custody.PublicKey.t()
@type verification_keys() :: verification_key() | [verification_key()]
@type verify_context() :: %{ optional(:replay_window_seconds) => pos_integer(), optional(:json_decoder) => json_decoder(), optional(:host_context) => term(), signature: signature_header_value() | nil, headers: %{optional(String.t()) => String.t()}, header_list: [{String.t(), String.t()}], method: String.t() | nil, request_uri: String.t() | nil, tenant: term() }
The request context verify_signature/3 receives as its second argument.
Carries everything any provider's signature scheme can need:
:signature: the signature header value the host passed, ornil; for asignature_source/0of:body, the raw body.:headers: the request headers as a map. When the host passed the ordered list fromconn.req_headers, names are lowercased and repeated lines are joined with", "; a host-supplied map arrives unchanged.:header_list: every request header line as{name, value}, in arrival order with repeated lines kept, when the host passed a list (names lowercased); for a host-supplied map, its binary entries.:method: the uppercase HTTP method, for schemes that sign over it.nilwhen the caller does not supply it.:request_uri: the exact request URI the provider signed.nilwhen not supplied.:tenant: the ingest tenant when the ledger is multitenant,nilotherwise. A provider whose custody is per-tenant (per-connection secrets keyed by organization) reads it here.:replay_window_seconds: the declaration override when configured; absent when the provider should use its own default.:json_decoder: an optional one-argument function for JSON bytes. Ingress supplies the ledger's decoder on every request. Use it for protected JWS headers and claims, defaulting toJason.decode/1for direct calls without the key.:host_context: an opaque, transient upstream result supplied by the host. A provider reusing it must bind the proof to the raw body digest, tenant and source policy, including the source key credited. It never replaces the provider's admission decision and is never persisted.
A provider whose scheme needs only the signature reads :signature and
ignores the rest.
@type webhook_secret() :: binary()
@type webhook_secret_scope() :: :app_level | :per_connection
Where a provider's webhook signing secret lives:
:app_level: resolves the inbound declaration's secret source, which may be application-wide or tenant-aware. This is the default.:per_connection: uses the provider's secret callback for the connection.
Callbacks
@callback body_format() :: :json | :form
Optional payload format, defaulting to JSON; :form opts into flat form decoding.
Optional payload decoder, called only after signature verification succeeds.
Returns a map or list. Providers without it retain JSON decoding. A route's
explicit body_format takes precedence. Custom decoders must return an error
for malformed input. Decoder failures normally become permanent
malformed-payload rows. If the provider's identity callback cannot derive
an identity, ingress returns an error before creating the accepted row.
A host-defined /1 needs decode_payload/2 on ledgers configuring
json_decoder. Generated JWS decoders use the request's decoder in ingress;
direct calls to their /1 use Jason.decode/1.
@callback decode_payload(raw_body(), json_decoder()) :: {:ok, map() | list()} | {:error, term()}
Optional request-aware decoder, called with verified bytes and the ledger's one-argument JSON decoder. Decode JSON only through that function, including JSON inside an envelope. Return its map or list, or an error for malformed input.
This callback takes precedence over a host-defined decode_payload/1.
A generated decode_payload/1 instead uses its configured scheme with the
request's decoder. Direct calls of that generated /1 use Jason.decode/1.
An explicit declaration body_format takes precedence over both callbacks.
Ledgers configuring json_decoder require this callback when the provider
has a host-defined /1. Run AshHooks.Provider.Conformance in your tests
to check that /2 honors the supplied decoder.
@callback event_identity(payload :: map() | list()) :: {:ok, String.t()} | {:error, :malformed_payload}
Returns a stable provider-defined identity for a decoded webhook payload.
This callback is optional. Ingress uses it only when the inbound declaration
has no explicit host event_id extractor. An implemented callback's error is
authoritative and never falls back to the raw-body digest. Providers without
the callback retain the raw-body SHA-256 identity behavior.
@callback event_identity(map() | list(), AshHooks.Provider.DeliveryContext.t()) :: {:ok, String.t()} | {:error, :malformed_payload}
Resolves identity with ingest context. Preferred over event_identity/1 when exported.
@callback handle_event(event_type :: atom(), payload :: map() | list()) :: {:ok, result :: term()} | {:error, :retry | :permanent, term()}
Handles a verified, parsed payload. Any {:ok, value} marks the receipt
processed; the value may be a struct or any other term.
@callback handle_event(atom(), map() | list(), AshHooks.Provider.DeliveryContext.t()) :: {:ok, term()} | {:error, :retry | :permanent, term()}
Handles a receipt with durable context, at ingest and recovery. Preferred over handle_event/2 when exported.
@callback handshake(handshake_request()) :: {:respond, pos_integer(), [{String.t(), String.t()}], iodata()} | :deliver
Optional HTTP handshake, called by AshHooks.Plug after resolving the source
and capturing raw bytes, before method refusal or signature verification.
Receives the method, query params decoded with Plug.Conn.Query.decode/1,
ordered request headers, and exact raw body. Return
{:respond, status, headers, body} to send a challenge response without any
ledger write, or :deliver to continue. Response header names must be lowercase,
as required by Plug. The callback must authenticate any challenge as required
by the sender's protocol; delivery verification has not run yet.
@callback parse_event_type(payload :: map() | list()) :: {:ok, atom()} | {:error, parse_error()}
Parses the event type from the decoded request body: a map for
object-shaped deliveries, a list for batch deliveries. Providers receiving a
shape their sender never sends
fail closed through their catch-all clause ({:error, :malformed_payload}).
@callback parse_event_type(map() | list(), AshHooks.Provider.DeliveryContext.t()) :: {:ok, atom()} | {:error, parse_error()}
Parses the event type with ingest context. Preferred over parse_event_type/1 when exported.
@callback response(ingest_outcome()) :: http_response() | :default
Optional HTTP acknowledgment policy. Receives exactly the outcome returned by
AshHooks.Ingress.ingest/4. Return {status, headers, body} or :default.
An implemented response takes precedence over the plug's :respond policy;
:default falls through. Plug refusals and handshake responses never invoke
this callback. Response header names must be lowercase. A custom 503 owns its
headers, including any retry hint.
@callback signature_source() :: :header | :body | :request
Optional signature location: :header (default) requires the host-supplied
ctx.signature; :body admits signed body envelopes; :request lets the
provider extract signatures from request headers itself.
@callback timestamp_header() :: String.t() | nil
The request header this provider's signature scheme carries a trustworthy
timestamp in (nil when the scheme has none). A DSL replay_window_seconds
requires a non-nil value here. A directly configured provider is checked
at compile time; a dynamically selected provider is checked at ingestion.
Other provider-defined timestamp checks and JWS
expiration and not-before checks can apply independently.
Optional, defaulting to nil.
@callback verify_signature(raw_body(), verify_context(), verification_keys()) :: :ok | {:ok, map()} | {:error, signature_error()}
Authenticates the exact body and request context.
Return :ok or {:ok, facts}. Facts are a string-keyed JSON map with depth
at most eight and an encoded size at most 8 KiB. Invalid facts fail closed
even when recording is off. With record_verified_facts :on, the first
authenticated receipt retains them and the handler receives them through
AshHooks.Provider.DeliveryContext. Otherwise ingress admits and drops them.
Project only bounded metadata, never credentials or signature material.
@callback webhook_secret_scope() :: webhook_secret_scope()
Declares whether this provider's webhook signing secret is app-level (the default) or per-connection. Optional.
@callback webhook_signing_secret(connection :: struct()) :: {:ok, webhook_secret()} | {:error, :no_webhook_secret}
Resolves the signing secret used to verify an inbound webhook.
The secret SOURCE is provider-dependent, so it lives with the provider
module rather than in the generic ingress. App-level providers use the declaration's source, which can be tenant-aware;
per-connection providers read it from the connection
argument. Returns {:error, :no_webhook_secret} when unconfigured; the
caller verifies nothing and does not run the handler.
@callback webhook_signing_secret(connection :: struct(), tenant :: term()) :: {:ok, webhook_secret()} | {:error, :no_webhook_secret}
Optional. Resolves the signing secret from the connection and the ingest
tenant, for secrets kept per tenant and connection. A provider using
use AshHooks.Provider gets a
default implementation delegating to webhook_signing_secret/1 (existing
providers compile unchanged); a per-tenant provider overrides /2.
Functions
Defines a provider. With verify: opts, generates overridable verification,
timestamp, signature-source, event-parsing, and handling callbacks from an
AshHooks.Provider.Scheme; JWS-body providers also get a payload decoder and
a payload-based event_identity/1. The options are checked when the module
finishes compiling, so an invalid option is a compile error. Write them in
place as a keyword list; their values may read module attributes set before the
use line and may be
two-argument anonymous functions (which may call the module's private
functions), remote captures, or {module, function} tuples.
Plain use AshHooks.Provider sets the behavior and provides the
tenant-aware webhook_signing_secret/2 as an overridable default that
delegates to webhook_signing_secret/1 when the provider implements it:
implement /1 and both shapes resolve; override /2 for per-tenant
secrets; implement neither and the default fails closed as
{:error, :no_webhook_secret} (the optional-callback semantics: an
app-level provider never sees the callback called at all). Providers written against the plain @behaviour keep working
unchanged (webhook_signing_secret/3 resolves both).
@spec default_verify_signature( raw_body(), signature_header_value(), webhook_secret(), signature_algorithm() ) :: :ok | {:error, :invalid_signature | :no_webhook_secret}
Default HMAC verify implementation: lowercase-hex HMAC of the raw body under the secret, compared in constant time behind a byte-size guard.
The byte-size guard both short-circuits wrong-length signatures and
satisfies :crypto.hash_equals/2's equal-length requirement.
An EMPTY secret fails closed as {:error, :no_webhook_secret}: an HMAC
under the empty key is computable by anyone, so a secret source that quietly
resolves to "" must not verify anything.
@spec event_identity(module(), map() | list()) :: :not_supported | {:ok, String.t()} | {:error, :malformed_payload}
Resolves the optional stable event identity callback.
:not_supported means the provider leaves identity to the raw request
digest. Callback errors are returned unchanged for ingress to reject.
@spec handshake(module(), handshake_request()) :: {:respond, pos_integer(), [{String.t(), String.t()}], iodata()} | :deliver
Dispatches the optional HTTP handshake; an absent callback continues delivery.
@spec response(module(), ingest_outcome()) :: http_response() | :default
Dispatches the optional HTTP response policy; an absent callback returns :default.
@spec secret_scope(module()) :: webhook_secret_scope()
Resolves a provider's webhook secret scope, defaulting to :app_level when
the optional webhook_secret_scope/0 callback is not implemented.
Loads the provider module first: function_exported?/3 reports false for a
module that is not yet loaded, which would misread an unloaded
per-connection provider as app-level.
Resolves a provider's trustworthy timestamp header, defaulting to nil
when the optional timestamp_header/0 callback is not implemented.
Loads the provider module first, with the same unloaded-module guard as
secret_scope/1.
@spec webhook_signing_secret(module(), struct(), term()) :: {:ok, webhook_secret()} | {:error, :no_webhook_secret}
Resolves the per-connection signing secret for an ingest: an overriding
webhook_signing_secret/2 (tenant-aware custody) wins; otherwise the
call delegates to webhook_signing_secret/1, so providers of either
implementation shape work through this one entry point.