webhooks

package
v3.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package webhooks provides reusable webhook receiver and signing primitives.

It verifies raw request bodies before decoding JSON payloads, signs outbound JSON webhook requests, and leaves provider-specific event schemas, replay storage, delivery retries, and idempotency policy to application code. Receiver verifier failures return a generic client-facing detail by default; use ReceiverConfig.VerificationErrorDetail only for explicitly safe text.

Index

Constants

View Source
const (
	// TimestampHeader is the default webhook timestamp header.
	TimestampHeader = "X-Webhook-Timestamp"
	// EventIDHeader is the default webhook event id header.
	EventIDHeader = "X-Webhook-Event-ID"
)

Variables

View Source
var (
	// ErrMissingSignature reports a request without the configured signature header.
	ErrMissingSignature = errors.New("missing webhook signature")
	// ErrInvalidSignature reports a request with a malformed or non-matching signature.
	ErrInvalidSignature = errors.New("invalid webhook signature")
)

Functions

func BuildSignedRequest

func BuildSignedRequest[T any](ctx context.Context, event OutgoingEvent[T], config SignedRequestConfig) (*http.Request, error)

BuildSignedRequest builds a JSON webhook request and signs the exact request body.

func DecodeJSON

func DecodeJSON[T any](body []byte) (T, error)

DecodeJSON decodes a webhook payload as JSON.

func DeliveryProblem

func DeliveryProblem(status int, detail string) httpx.Problem

DeliveryProblem returns the standard webhook delivery Problem Details value.

func WriteProblem

func WriteProblem(w http.ResponseWriter, status int, problem httpx.Problem)

WriteProblem writes a webhook Problem Details response.

Types

type DeliveryAttempt

type DeliveryAttempt struct {
	EventID   string    `json:"event_id"`
	URL       string    `json:"url"`
	Attempt   int       `json:"attempt"`
	Timestamp time.Time `json:"timestamp"`
}

DeliveryAttempt describes an outbound webhook delivery attempt.

type DeliveryContract

type DeliveryContract struct {
	AcceptedStatus int           `json:"accepted_status"`
	MaxAttempts    int           `json:"max_attempts,omitempty"`
	RetryAfter     time.Duration `json:"retry_after,omitempty"`
}

DeliveryContract documents accepted delivery status and retry behavior.

type DeliveryResult

type DeliveryResult struct {
	StatusCode int            `json:"status_code"`
	Accepted   bool           `json:"accepted"`
	Problem    *httpx.Problem `json:"problem,omitempty"`
}

DeliveryResult describes an outbound webhook delivery result.

type Event

type Event[T any] struct {
	Payload T
	RawBody []byte
	Request *http.Request
}

Event is a verified and decoded webhook event.

type HMACConfig

type HMACConfig struct {
	Secret     []byte
	HeaderName string
	Encoding   SignatureEncoding
	Prefix     string
}

HMACConfig configures HMAC-SHA256 signature verification.

type HMACSignerConfig

type HMACSignerConfig struct {
	Secret   []byte
	Encoding SignatureEncoding
	Prefix   string
}

HMACSignerConfig configures HMAC-SHA256 webhook signing.

type OutgoingEvent

type OutgoingEvent[T any] struct {
	ID      string `json:"id"`
	Type    string `json:"type,omitempty"`
	Payload T      `json:"payload,omitempty"`
}

OutgoingEvent is a JSON webhook event envelope for outbound signing helpers.

type Receiver

type Receiver[T any] struct {
	Config ReceiverConfig[T]
}

Receiver is an http.Handler for verified webhook events.

func (Receiver[T]) ServeHTTP

func (receiver Receiver[T]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP verifies, decodes, and accepts a webhook event.

type ReceiverConfig

type ReceiverConfig[T any] struct {
	Verifier     Verifier
	MaxBodyBytes int64
	Replay       ReplayConfig
	Decode       func([]byte) (T, error)
	Handle       func(context.Context, Event[T]) error
	ErrorWriter  func(http.ResponseWriter, int, httpx.Problem)
	// VerificationErrorDetail formats a safe client-facing detail for verifier
	// failures. When nil or empty, a generic detail is returned.
	VerificationErrorDetail func(error) string
}

ReceiverConfig configures a webhook receiver.

type ReplayConfig

type ReplayConfig struct {
	Tolerance       time.Duration
	Now             func() time.Time
	RequireEventID  bool
	TimestampHeader string
	EventIDHeader   string
}

ReplayConfig configures timestamp skew and event-id replay checks.

type ReplayDecision

type ReplayDecision struct {
	Allowed   bool
	Reason    string
	EventID   string
	Timestamp time.Time
}

ReplayDecision reports the replay-window check outcome.

func CheckReplayWindow

func CheckReplayWindow(r *http.Request, config ReplayConfig) ReplayDecision

CheckReplayWindow verifies timestamp skew and required event ids using headers.

type SignatureEncoding

type SignatureEncoding int

SignatureEncoding describes how a signature header is encoded.

const (
	SignatureEncodingHex SignatureEncoding = iota
	SignatureEncodingBase64
	SignatureEncodingBase64URL
)

type SignedRequestConfig

type SignedRequestConfig struct {
	Method          string
	URL             string
	Signer          Signer
	EventID         string
	Timestamp       time.Time
	SignatureHeader string
	EventIDHeader   string
	TimestampHeader string
	ContentType     string
	Headers         http.Header
}

SignedRequestConfig configures BuildSignedRequest.

type Signer

type Signer interface {
	SignWebhook(ctx context.Context, body []byte) (string, error)
}

Signer signs a raw webhook request body.

func NewHMACSHA256Signer

func NewHMACSHA256Signer(config HMACSignerConfig) (Signer, error)

NewHMACSHA256Signer constructs an HMAC-SHA256 signer.

type SignerFunc

type SignerFunc func(context.Context, []byte) (string, error)

SignerFunc adapts a function to Signer.

func (SignerFunc) SignWebhook

func (f SignerFunc) SignWebhook(ctx context.Context, body []byte) (string, error)

SignWebhook signs a raw webhook request body.

type Verifier

type Verifier interface {
	VerifyWebhook(ctx context.Context, r *http.Request, body []byte) error
}

Verifier verifies a raw webhook request body.

func NewHMACSHA256Verifier

func NewHMACSHA256Verifier(config HMACConfig) (Verifier, error)

NewHMACSHA256Verifier constructs an HMAC-SHA256 verifier.

type VerifierFunc

type VerifierFunc func(context.Context, *http.Request, []byte) error

VerifierFunc adapts a function to Verifier.

func (VerifierFunc) VerifyWebhook

func (f VerifierFunc) VerifyWebhook(ctx context.Context, r *http.Request, body []byte) error

VerifyWebhook verifies a raw webhook request body.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL