webhooks

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package webhooks delivers events to the receivers webhooks.endpoints names, signed in the Standard Webhooks format (https://www.standardwebhooks.com/), through a dialer that checks every address it connects to.

Index

Constants

View Source
const (
	DeliveriesFile = "webhook-deliveries.jsonl"
	StateFile      = "webhook-state.json"
)

Files in the state directory.

View Source
const (
	// Timeout bounds a delivery from dial to the last response byte.
	Timeout = 10 * time.Second
	// MaxPayload is the largest body sent; a bigger event is not sent.
	MaxPayload = 256 << 10
)

Limits on one delivery.

View Source
const (
	HeaderID        = "webhook-id"
	HeaderTimestamp = "webhook-timestamp"
	HeaderSignature = "webhook-signature"
)

The Standard Webhooks headers.

View Source
const DefaultTolerance = 5 * time.Minute

DefaultTolerance is how far a receiver lets a timestamp drift.

View Source
const DisableAfter = 50

DisableAfter is how many consecutive failed attempts turn an endpoint off.

View Source
const QueueSize = 1000

QueueSize bounds the deliveries waiting; one more is dropped and logged.

View Source
const RotationGrace = 24 * time.Hour

RotationGrace is how long the previous secret keeps signing after a rotation, so a receiver can switch with no failed delivery.

View Source
const SecretPrefix = "whsec_"

SecretPrefix starts every secret, as Standard Webhooks writes them.

View Source
const SecretsFile = "webhook-secrets.json"

SecretsFile is where the tool keeps the secrets it generated, in the state directory, mode 0600: never in the global config, which is shareable.

Variables

View Source
var (
	ErrNoSignature = errors.New("webhook: missing id, timestamp or signature header")
	ErrTimestamp   = errors.New("webhook: timestamp outside the tolerance")
	ErrSignature   = errors.New("webhook: no signature matches")
)

Errors Verify returns.

View Source
var DefaultBackoff = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute, 2 * time.Hour, 6 * time.Hour}

DefaultBackoff is the wait before each retry: five retries after the first attempt, then the delivery is marked failed.

View Source
var ErrDenied = errors.New("webhook: address not allowed")

ErrDenied is a connection refused because of where it would go.

View Source
var ErrTooLarge = errors.New("webhook: payload over 256 KiB, not sent")

ErrTooLarge is an event whose body exceeds MaxPayload.

Functions

func DefaultSecretsPath

func DefaultSecretsPath(stateDir string) string

DefaultSecretsPath is webhook-secrets.json in stateDir.

func Denied

func Denied(addr netip.Addr) bool

Denied reports whether addr is in a denied range.

func Disabled

func Disabled(stateDir, name string) bool

Disabled reports whether name was turned off after DisableAfter failures.

func NewSecret

func NewSecret() string

NewSecret returns a Standard Webhooks secret: whsec_ and the base64 of 32 random bytes.

func Sign

func Sign(secret, id string, ts time.Time, body []byte) string

Sign returns one signature, "v1,<base64 HMAC-SHA256(id.timestamp.body)>".

func SignatureHeader

func SignatureHeader(secrets []string, id string, ts time.Time, body []byte) string

SignatureHeader is the webhook-signature value for every secret currently valid: during a rotation, both the new and the old secret sign, space separated, so a receiver holding either verifies.

func Verify

func Verify(secret string, h http.Header, body []byte, now time.Time, tolerance time.Duration) error

Verify is the receiver's check: the timestamp is within tolerance of now, and one of the signatures in the header is the HMAC of id.timestamp.body under secret. It is the Go version of the check docs/tools/webhooks.md gives, and this package's tests use it.

Types

type Dispatcher

type Dispatcher struct {
	Endpoints []settings.Webhook
	Sender    *Sender
	// Log is the delivery log; StatePath the endpoint state file.
	Log       *jsonlog.Log
	StatePath string
	// Bus receives webhook.disabled.
	Bus *events.Bus
	// Backoff is the wait before each retry; nil is DefaultBackoff.
	Backoff []time.Duration
	// Now is the clock; nil means time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

Dispatcher delivers the bus's events to the configured endpoints.

func NewDispatcher

func NewDispatcher(stateDir string, endpoints []settings.Webhook, sender *Sender, bus *events.Bus) *Dispatcher

NewDispatcher wires a dispatcher to the state directory.

func (*Dispatcher) Run

func (d *Dispatcher) Run(ctx context.Context, sub *events.Subscription)

Run delivers what sub receives until ctx ends.

func (*Dispatcher) States

func (d *Dispatcher) States() map[string]endpointState

States reads every endpoint's state.

func (*Dispatcher) Test

Test sends a webhook.test event to w now, whatever its event filter and even when it is disabled, and turns it back on when the delivery succeeds.

type Policy

type Policy struct {
	// AllowPrivate opens every denied range (webhooks.allow_private).
	AllowPrivate bool
	// AllowInsecureLocalhost allows http:// to localhost, 127.0.0.1 or ::1,
	// and only there (webhooks.allow_insecure_localhost).
	AllowInsecureLocalhost bool
}

Policy is what a delivery may reach.

func (Policy) CheckURL

func (p Policy) CheckURL(raw string) (loopbackOK bool, err error)

CheckURL applies the scheme rule: https, or http to localhost with AllowInsecureLocalhost. It returns whether the delivery may connect to a loopback address, which only that exception allows without AllowPrivate.

func (Policy) DialContext

func (p Policy) DialContext(loopbackOK bool, timeout time.Duration) func(ctx context.Context, network, addr string) (net.Conn, error)

DialContext is the guarded dial function for an http.Transport.

func (Policy) Dialer

func (p Policy) Dialer(loopbackOK bool, timeout time.Duration) *net.Dialer

Dialer returns the guarded dialer for one delivery.

type Record

type Record struct {
	Time     time.Time `json:"time"`
	Endpoint string    `json:"endpoint"`
	EventID  string    `json:"event_id"`
	Type     string    `json:"type"`
	Attempt  int       `json:"attempt"`
	// Outcome is delivered, retrying, failed, dropped or disabled.
	Outcome    string    `json:"outcome"`
	Status     int       `json:"status,omitempty"`
	Error      string    `json:"error,omitempty"`
	DurationMs int64     `json:"duration_ms"`
	NextTry    time.Time `json:"next_try,omitzero"`
}

Record is one line of the delivery log.

type Result

type Result struct {
	// Status is the receiver's HTTP status; zero when none was received.
	Status int
	// Err is why it failed; nil for a 2xx.
	Err error
	// Permanent is set for a failure a retry cannot fix: a refused URL or
	// address, a missing secret, an oversized payload.
	Permanent bool
	Duration  time.Duration
}

Result is how one attempt went.

type Secrets

type Secrets struct {
	Path string
	// Now is the clock; nil means time.Now.
	Now func() time.Time
	// Lookup reads the environment, for secret_env; nil means os.LookupEnv.
	Lookup func(string) (string, bool)
	// contains filtered or unexported fields
}

Secrets is the secrets file.

func (*Secrets) Create

func (s *Secrets) Create(name string) (string, error)

Create makes and stores a secret for name, replacing none: an endpoint that has one keeps it (rotate it instead).

func (*Secrets) Has

func (s *Secrets) Has(name string) bool

Has reports whether name has a generated secret.

func (*Secrets) Remove

func (s *Secrets) Remove(name string) error

Remove deletes name's secret, when the endpoint is removed.

func (*Secrets) Rotate

func (s *Secrets) Rotate(name string) (string, error)

Rotate replaces name's secret, keeping the old one valid for RotationGrace, and returns the new one.

func (*Secrets) Signing

func (s *Secrets) Signing(w settings.Webhook) ([]string, error)

Signing returns the secrets that sign a delivery to w now: secret_env's value when it names one that is set, else the generated secret and, within a rotation's grace, the previous one.

type Sender

type Sender struct {
	Policy  Policy
	Secrets *Secrets
	// Now is the clock; nil means time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

Sender makes one signed delivery.

func (*Sender) Send

func (s *Sender) Send(ctx context.Context, w settings.Webhook, e events.Event) Result

Send posts e to w, signed with every secret valid now.

Jump to

Keyboard shortcuts

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