webhooks

package
v0.0.0-...-3ac6500 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

github.com/ubgo/filesystem/records/webhooks

A records plugin that delivers chosen events to URLs registered per scope, signed in the Standard Webhooks format, retried with backoff through jobs.WebhookDeliver, and guarded against internal addresses with upload.PublicAddr. The guide is docs/plugins/webhooks.md.

Install

go get github.com/ubgo/filesystem/records

Part of the records module; it uses only the standard library, the core and upload from the core module, whose guarded client (upload.FetchOptions.Client) it sends with.

Go API

Symbol What it does
New(opts...) The plugin; CodeInvalidArgument for a nil client, backoff or logger, or fewer than one attempt
WithClient(c) Replaces the guarded default client (the escape hatch); the client must guard addresses itself
WithBackoff(fn), DefaultBackoff Wait after the n-th failure; default 30 s doubling to 6 h
WithMaxAttempts(n), DefaultMaxAttempts Attempts before StateFailed; default 10
WithSealer(s), Sealer Seals endpoint secrets at rest (Seal/Open); plaintext without one
WithLogger(l) Where failed attempts are logged; default slog.Default()
WithSigner(sg), Signer, SignRequest, StandardSigner Signs each delivery; default StandardSigner (Standard Webhooks v1, one signature per active secret). Plug in ed25519, GitHub-style or KMS signing; a failing signer fails the attempt, which is retried, never sent unsigned
WithPayload(fn), PayloadFunc, DefaultPayload(e) Builds each event's JSON body with fn(ctx, event) (any, error) (a CloudEvents envelope, a trimmed body); an error fails the change. Default DefaultPayload
WithEndpointPayload(fn), EndpointPayloadFunc, Body{Data, ContentType, Header} Builds each delivery's body per endpoint with fn(ctx, event, endpoint): a Slack message for one receiver, CloudEvents structured (application/cloudevents+json) or binary (ce-* headers) for another, a non-JSON body. The body and headers are stored with the delivery, so a retry sends the same bytes. An error, a body that is not valid UTF-8, or a Webhook-*, Host or framing header fails the change; the signer runs after and always wins. Default: WithPayload's JSON for every endpoint, as application/json (DefaultContentType, also what an empty Body.ContentType sends)
WithBatch(n), WithConcurrency(n) Deliveries one Deliver run takes (default DefaultBatch, 100) and sends at once (default DefaultConcurrency, 1); each delivery is still claimed on its own
(*Plugin).AddEndpoint(ctx, s, scope, url, kinds...) Registers an endpoint (all kinds when none) with a new Secret
(*Plugin).Register(ctx, s, EndpointSpec{Scope, URL, Kinds, Secret, Global}) Registers an endpoint with a caller's secret (whsec_ and 24 to 64 bytes; CheckSecret, or the signer's SecretFormat), or a global one
SecretFormat (NewSecret(), CheckSecret(secret)) An optional Signer upgrade for secrets that are not whsec_ base64 (a GitHub-style free-form secret, ed25519 key material): Register and RotateSecret then generate and check with it. The floor holds whatever the format: MinSecretBytes (24) to MaxSecretTextBytes (1024) bytes, no whitespace
(*Plugin).AddGlobalEndpoint(ctx, s, url, kinds...), GlobalEndpoints, RemoveGlobalEndpoint An endpoint for the events of every scope (one internal consumer); never hand one to a tenant
(*Plugin).RotateSecret(ctx, s, EndpointRef{Scope, ID, Global}, next), RetireSecrets(ctx, s, ref) Zero-downtime rotation: up to MaxSecrets (5) active secrets, each signing every delivery (Endpoint.Secrets, newest first), then retire the old ones; NewSecret() makes one
(*Plugin).Endpoints(ctx, s, scope), RemoveEndpoint(ctx, s, scope, id) List and delete a scope's endpoints (global ones excluded)
(*Plugin).OnEvent records.EventHooks: writes a pending delivery per matching endpoint inside the change's transaction
(*Plugin).Deliver(ctx, s, now) Claims and posts up to DefaultBatch due deliveries; returns how many were delivered
(*Plugin).Deliveries(ctx, s, scope, state) Lists deliveries in StatePending, StateDelivered or StateFailed
(*Plugin).Prune(ctx, s, cutoff) Deletes delivered and failed deliveries last updated before cutoff
Secret Prints, logs and marshals as [redacted]; Reveal() returns it
Sign(h, secret, id, at, body), SignAll(h, secrets, id, at, body), VerifySignature(h, secret, body, now, tolerance) The signature on both sides; HeaderID, HeaderTimestamp, HeaderSignature, DefaultTolerance
Payload, FilePayload The JSON body; no disk or storage key

Tables

fs_webhook_endpoints and fs_webhook_deliveries, migration webhooks/0001_webhooks, webhooks/0002_webhooks_global adding fs_webhook_endpoints.is_global, and webhooks/0003_webhooks_headers adding fs_webhook_deliveries.headers ("" for a default JSON body, else the JSON of the request headers WithEndpointPayload chose); the secret column holds every active secret, space-separated, sealed as a whole with WithSealer; typed columns EndpointTable, Endpoint*, DeliveryTable, Delivery*.

Documentation

Overview

Package webhooks is a records plugin that delivers chosen events (file changes, plugin events such as quota.usage_changed or egress.daily_total) to HTTPS endpoints registered per scope (or for every scope, Register with Global), signed with HMAC-SHA256 in the Standard Webhooks format (or by a Signer of the application's), retried with exponential backoff, and refused for any address outside the public internet. Secrets rotate without downtime: an endpoint holds up to MaxSecrets at once and every delivery is signed with each.

Delivery is an outbox. OnEvent writes one delivery row per matching endpoint inside the change's own transaction, so a change that rolls back sends nothing and one that commits is never lost. Deliver, run on a schedule (jobs.WebhookDeliver), posts the due rows; a failure moves a row's next attempt out by Backoff until MaxAttempts, after which it is marked failed. Every attempt carries the event's ID (records.Event.ID) as Webhook-Id, so a receiver that keeps the IDs it handled drops the repeats that at-least-once delivery brings.

Index

Constants

View Source
const (
	MinSecretBytes     = secretBytes
	MaxSecretTextBytes = 1024
)

Bounds every secret meets whatever its format (SecretFormat): at least as long as the 24 random bytes a generated secret has, and short enough for MaxSecrets of them to sit in one column.

View Source
const (
	HeaderID        = "Webhook-Id"
	HeaderTimestamp = "Webhook-Timestamp"
	HeaderSignature = "Webhook-Signature"
)

Header names of a signed delivery, as Standard Webhooks (standardwebhooks.com) defines them, so its receiver libraries in any language check these deliveries unchanged.

View Source
const (
	TableNameEndpoints  = "fs_webhook_endpoints"
	TableNameDeliveries = "fs_webhook_deliveries"
)

Table names of the plugin.

View Source
const (
	ColEndpointID        = "id"
	ColEndpointScope     = "scope"
	ColEndpointURL       = "url"
	ColEndpointSecret    = "secret"
	ColEndpointKinds     = "kinds"
	ColEndpointCreatedAt = "created_at"
	// ColEndpointGlobal is 1 for an endpoint that takes events of every
	// scope (Register with Global; its scope column holds ""), 0 for one
	// scope's (migration 0002_webhooks_global).
	ColEndpointGlobal = "is_global"
)

Column names of fs_webhook_endpoints.

View Source
const (
	ColDeliveryID         = "id"
	ColDeliveryEndpointID = "endpoint_id"
	ColDeliveryScope      = "scope"
	ColDeliveryEventID    = "event_id"
	ColDeliveryKind       = "kind"
	ColDeliveryPayload    = "payload"
	ColDeliveryState      = "state"
	ColDeliveryAttempts   = "attempts"
	ColDeliveryNextAt     = "next_at"
	ColDeliveryLastError  = "last_error"
	ColDeliveryCreatedAt  = "created_at"
	ColDeliveryUpdatedAt  = "updated_at"
	// ColDeliveryHeaders holds the request headers WithEndpointPayload
	// chose (migration 0003_webhooks_headers): "" for the default, a JSON
	// body sent as application/json; otherwise the JSON of an http.Header
	// holding Content-Type and any extra headers.
	ColDeliveryHeaders = "headers"
)

Column names of fs_webhook_deliveries.

View Source
const (
	EndpointIDPrefix = "whe_"
	DeliveryIDPrefix = "whd_"
)

ID prefixes.

View Source
const (
	// DefaultMaxAttempts is how many times a delivery is tried before it
	// is marked failed, when WithMaxAttempts is not given: with
	// DefaultBackoff that spans about a day.
	DefaultMaxAttempts = 10
	// DefaultTimeout bounds one attempt with the default client.
	DefaultTimeout = 10 * time.Second
	// DefaultBatch is how many due deliveries one Deliver run takes,
	// unless WithBatch says otherwise.
	DefaultBatch = 100
	// DefaultConcurrency is how many deliveries one Deliver run sends at
	// once, unless WithConcurrency says otherwise: one after another.
	DefaultConcurrency = 1

	// MaxSecrets is how many secrets an endpoint holds at once while it
	// rotates: each adds a signature of about 50 bytes to every delivery's
	// headers, and more than a few means old ones were never retired.
	MaxSecrets = 5
)

Defaults and limits.

View Source
const DefaultContentType = "application/json"

DefaultContentType is a delivery's Content-Type unless WithEndpointPayload names another.

View Source
const DefaultTolerance = 5 * time.Minute

DefaultTolerance is how far a delivery's timestamp may be from the receiver's clock before VerifySignature refuses it as a replay.

View Source
const PluginName = "webhooks"

PluginName is the plugin's name in the migration ledger.

Variables

Table and typed columns of fs_webhook_endpoints. Kinds holds the event kinds an endpoint wants, separated by kindSeparator, "" for every kind. Secret holds the endpoint's active secrets, newest first, separated by secretSeparator (one secret for an endpoint never rotated), sealed as a whole with WithSealer.

Table and typed columns of fs_webhook_deliveries.

Functions

func CheckSecret

func CheckSecret(secret Secret) error

CheckSecret reports whether secret is one Register and RotateSecret accept: "whsec_" and the base64 of 24 to 64 bytes. A shorter key would sign with less entropy than a generated secret has.

func DefaultBackoff

func DefaultBackoff(attempt int) time.Duration

DefaultBackoff waits 30 seconds after the first failure and doubles each time, up to six hours.

func Sign

func Sign(h http.Header, secret Secret, id string, at time.Time, body []byte) error

Sign sets the three headers on h for body sent as message id at time at: HeaderSignature is "v1," and the base64 HMAC-SHA256, under the secret's key, of "id.timestamp.body". A malformed secret is CodeInvalidArgument.

func SignAll

func SignAll(h http.Header, secrets []Secret, id string, at time.Time, body []byte) error

SignAll is Sign with several secrets, for an endpoint that rotates: HeaderSignature holds one "v1,<base64>" per secret, space-separated, in the order given, as Standard Webhooks allows, so a receiver holding any one of them accepts the delivery. With one secret it is exactly Sign.

func VerifySignature

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

VerifySignature is the receiving side of Sign, for an application that receives its own webhooks or tests them: it accepts body when one of the space-separated signatures in h matches and the timestamp is within tolerance of now (DefaultTolerance when 0), and refuses it with CodePermission otherwise. Compare in constant time; never trust a body before this passes.

Types

type Body

type Body struct {
	// Data is sent as it is. It is stored as text until delivered, so it
	// must be valid UTF-8 (JSON, XML, a form): a binary body is refused.
	Data []byte
	// ContentType is the Content-Type header; "" is DefaultContentType.
	// "application/cloudevents+json" is CloudEvents' structured mode.
	ContentType string
	// Header holds extra request headers, such as the ce-* headers of
	// CloudEvents' binary mode. The signing headers (Webhook-*), Host and
	// the framing headers (Content-Length, Transfer-Encoding, Connection)
	// are refused: the signer and the transport own them. The Signer runs
	// after these are set, so a header it writes always wins.
	Header http.Header
}

Body is one delivery's request body as WithEndpointPayload builds it.

type Delivery

type Delivery struct {
	ID         string
	EndpointID string
	Scope      string
	EventID    string
	Kind       string
	State      State
	Attempts   int64
	NextAt     time.Time
	LastError  string
}

Delivery is one event on its way to one endpoint.

type Endpoint

type Endpoint struct {
	ID string
	// Scope is the scope whose events are delivered; "" for a Global
	// endpoint.
	Scope string
	URL   string
	// Kinds lists the event kinds delivered; empty delivers every kind.
	Kinds []records.EventKind
	// Secret is the newest active secret, Secrets[0]: the one a receiver
	// set up now should be given.
	Secret Secret
	// Secrets are every active secret, newest first; each signs every
	// delivery while the endpoint rotates (RotateSecret). One secret for
	// an endpoint never rotated.
	Secrets []Secret
	// Global is an endpoint that takes the events of every scope.
	Global    bool
	CreatedAt time.Time
}

Endpoint is a URL one scope's events, or every scope's, are delivered to.

type EndpointPayloadFunc

type EndpointPayloadFunc func(ctx context.Context, e records.Event, ep Endpoint) (Body, error)

EndpointPayloadFunc builds the body of one event's delivery to one endpoint, so receivers of one event can each get their own shape: a Slack message for one, a CloudEvents envelope for another, a non-JSON body for a third. ep carries the endpoint's URL, scope and kinds.

type EndpointRef

type EndpointRef struct {
	Scope  string
	ID     string
	Global bool
}

EndpointRef names one endpoint: endpoint ID of scope Scope, or, with Global, global endpoint ID (Scope is then ignored). Scoped and global endpoints are kept apart because "" is a valid scope: a tenant of scope "" never reaches a global endpoint through a scoped ref.

type EndpointSpec

type EndpointSpec struct {
	// Scope is the scope whose events are delivered. Ignored (stored as
	// "") when Global is set.
	Scope string
	// URL must be http or https with a host and no credentials, at most
	// 1024 bytes.
	URL string
	// Kinds lists the event kinds delivered; empty delivers every kind.
	Kinds []records.EventKind
	// Secret is the signing secret, "whsec_" and the base64 of 24 to 64
	// bytes, for a receiver that already has one (a migration from another
	// sender); empty generates a random one.
	Secret Secret
	// Global takes the events of every scope: one internal consumer (a
	// search indexer, a data warehouse) for all tenants. Never hand a
	// global endpoint to a tenant: it sees every tenant's events.
	Global bool
}

EndpointSpec is what Register registers. It is a struct so fields can be added without breaking callers.

type FilePayload

type FilePayload struct {
	ID          string `json:"id"`
	Filename    string `json:"filename"`
	ContentType string `json:"content_type"`
	Size        int64  `json:"size"`
	SHA256      string `json:"sha256"`
	Visibility  string `json:"visibility"`
	Status      string `json:"status"`
}

FilePayload is the file an event is about, as the change left it. It carries no storage key or disk: a receiver asks the application for the bytes.

type Option

type Option func(*Plugin)

Option configures a Plugin.

func WithBackoff

func WithBackoff(fn func(attempt int) time.Duration) Option

WithBackoff sets the wait after a delivery's n-th failed attempt (DefaultBackoff otherwise).

func WithBatch

func WithBatch(n int) Option

WithBatch sets how many due deliveries one Deliver run takes (DefaultBatch otherwise), at least 1: raise it, with WithConcurrency, for high-volume delivery, or schedule Deliver more often.

func WithClient

func WithClient(c *http.Client) Option

WithClient replaces the guarded default client: the escape hatch for a proxy, mutual TLS, or tests against a local server. The application's client must then do its own guarding against internal addresses, and AddEndpoint no longer refuses literal internal addresses either.

func WithConcurrency

func WithConcurrency(n int) Option

WithConcurrency sets how many deliveries one Deliver run sends at once (DefaultConcurrency, one after another, otherwise), at least 1. Each delivery is still claimed on its own before it is sent, so concurrent sends, and runs on several machines, never send one delivery twice at the same time. The Store's database must allow that many concurrent statements.

func WithEndpointPayload

func WithEndpointPayload(fn EndpointPayloadFunc) Option

WithEndpointPayload builds every delivery's body with fn, once per endpoint that wants the event, instead of WithPayload's single JSON body for all of them; WithPayload is then not used. It runs inside the change's transaction: an error from fn, a body that is not valid UTF-8 or a refused header fails the change (it rolls back), so no event is dropped or sent in a shape the receiver was not promised. The body and headers are stored with the delivery, so a retry sends the same bytes. nil keeps WithPayload's, or DefaultPayload.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger logs every failed attempt (slog.Default otherwise).

func WithMaxAttempts

func WithMaxAttempts(n int) Option

WithMaxAttempts sets how many attempts a delivery gets before it is marked failed (DefaultMaxAttempts otherwise).

func WithPayload

func WithPayload(fn PayloadFunc) Option

WithPayload builds every delivery's JSON body with fn instead of DefaultPayload. It runs once per event inside the change's transaction, when at least one endpoint wants the event; an error from fn, or a value that does not marshal, fails the change (it rolls back), so no event is dropped or sent in a shape the receivers were not promised.

func WithSealer

func WithSealer(sl Sealer) Option

WithSealer stores every new endpoint's secret sealed by sl and opens it to sign. Endpoints added before it was set hold plaintext, which Open receives as is: remove and re-add them, or seal them in a migration of your own.

func WithSigner

func WithSigner(sg Signer) Option

WithSigner signs every delivery with sg instead of StandardSigner (Standard Webhooks v1, HMAC-SHA256 under each active secret): for receivers that check ed25519 (Standard Webhooks v1a), a GitHub-style X-Hub-Signature-256, or a key held in a KMS. A Signer that fails fails the attempt, which is retried like any other: nothing is ever sent unsigned.

type Payload

type Payload struct {
	// ID is the event's ID, also sent as Webhook-Id: the same on every
	// attempt, for the receiver to drop repeats.
	ID           string            `json:"id"`
	Kind         string            `json:"kind"`
	Scope        string            `json:"scope"`
	At           time.Time         `json:"at"`
	FileID       string            `json:"file_id,omitempty"`
	AttachmentID string            `json:"attachment_id,omitempty"`
	OwnerType    string            `json:"owner_type,omitempty"`
	OwnerID      string            `json:"owner_id,omitempty"`
	Role         string            `json:"role,omitempty"`
	Subject      string            `json:"subject,omitempty"`
	Detail       map[string]string `json:"detail,omitempty"`
	File         *FilePayload      `json:"file,omitempty"`
}

Payload is the JSON body of a delivery.

func DefaultPayload

func DefaultPayload(e records.Event) Payload

DefaultPayload is the body of an event's deliveries without WithPayload: the event, and the file it is about without its storage key or disk.

type PayloadFunc

type PayloadFunc func(ctx context.Context, e records.Event) (any, error)

PayloadFunc builds the body of the deliveries of one event: any value encoding/json marshals (a CloudEvents envelope, a trimmed body, the application's own schema). DefaultPayload is the body without it, to wrap or extend.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin delivers events. Construct it with New and install it with records.WithPlugins.

func New

func New(opts ...Option) (*Plugin, error)

New returns a Plugin. A nil client, backoff, logger or signer, fewer than one attempt, or a batch or concurrency below 1, is CodeInvalidArgument.

func (*Plugin) AddEndpoint

func (p *Plugin) AddEndpoint(ctx context.Context, s *records.Store, scope, rawURL string, kinds ...records.EventKind) (Endpoint, error)

AddEndpoint registers url for scope's events of kinds (every kind when empty) and returns it with a new random secret, which the receiver needs to check signatures (Endpoint.Secret.Reveal). The URL must be http or https with a host and no credentials; with the default client a host that is a literal internal address is refused here, and every address a name resolves to is checked again on each attempt. Register takes a secret of the caller's, or registers a global endpoint.

func (*Plugin) AddGlobalEndpoint

func (p *Plugin) AddGlobalEndpoint(ctx context.Context, s *records.Store, rawURL string, kinds ...records.EventKind) (Endpoint, error)

AddGlobalEndpoint registers url for the events of kinds (every kind when empty) of every scope, with a new random secret: Register with Global.

func (*Plugin) Deliver

func (p *Plugin) Deliver(ctx context.Context, s *records.Store, now time.Time) (int, error)

Deliver attempts up to DefaultBatch (WithBatch) deliveries due at now, DefaultConcurrency (WithConcurrency) at a time, and returns how many were delivered. Each is first claimed at the moment it is attempted (its next attempt moved out by a lease from the Store's clock then, if no other run moved it first), so runs on several machines never send one delivery at the same time however long a batch takes, and a run that crashes mid-attempt leaves it to be retried once the lease passes. An attempt is cut off well inside its lease. Its Webhook-Timestamp is the Store's clock at the attempt. A 2xx answer delivers it; anything else, a redirect included, schedules the next attempt after Backoff, or marks it failed after MaxAttempts. Errors of single deliveries are recorded on them and logged, not returned; the error is for the database (the first one, after every send already started has finished).

func (*Plugin) Deliveries

func (p *Plugin) Deliveries(ctx context.Context, s *records.Store, scope string, state State) ([]Delivery, error)

Deliveries lists scope's deliveries in state, oldest first, for an admin screen or a test.

func (*Plugin) Endpoints

func (p *Plugin) Endpoints(ctx context.Context, s *records.Store, scope string) ([]Endpoint, error)

Endpoints lists scope's endpoints, oldest first, without the global ones (GlobalEndpoints). Their secrets are filled but redacted in any output; Reveal reads them.

func (*Plugin) GlobalEndpoints

func (p *Plugin) GlobalEndpoints(ctx context.Context, s *records.Store) ([]Endpoint, error)

GlobalEndpoints lists the global endpoints, oldest first.

func (*Plugin) Migrations

func (p *Plugin) Migrations(engine string) ([]records.Migration, error)

Migrations implements records.Migrator.

func (*Plugin) Name

func (p *Plugin) Name() string

Name implements records.Plugin.

func (*Plugin) OnEvent

func (p *Plugin) OnEvent(ctx context.Context, s *records.Store, e records.Event) error

OnEvent implements records.EventHooks: inside the change's transaction it writes one pending delivery for every endpoint of the event's scope, and every global endpoint, that wants its kind, due at once.

func (*Plugin) Prune

func (p *Plugin) Prune(ctx context.Context, s *records.Store, cutoff time.Time) (int64, error)

Prune deletes the delivered and failed deliveries last updated before cutoff and returns how many it deleted; pending ones are kept whatever their age. Schedule it (jobs.WebhookPrune).

func (*Plugin) Register

func (p *Plugin) Register(ctx context.Context, s *records.Store, spec EndpointSpec) (Endpoint, error)

Register registers the endpoint spec describes and returns it, its secret filled (the caller's, or a new random one). The URL is checked as AddEndpoint does; a caller's secret that is not "whsec_" and the base64 of 24 to 64 bytes is CodeInvalidArgument, unless the Signer implements SecretFormat, whose check then applies with the MinSecretBytes floor.

func (*Plugin) RemoveEndpoint

func (p *Plugin) RemoveEndpoint(ctx context.Context, s *records.Store, scope, id string) (bool, error)

RemoveEndpoint deletes endpoint id of scope and reports whether it existed. Its pending deliveries are marked failed when next attempted. A global endpoint is removed with RemoveGlobalEndpoint.

func (*Plugin) RemoveGlobalEndpoint

func (p *Plugin) RemoveGlobalEndpoint(ctx context.Context, s *records.Store, id string) (bool, error)

RemoveGlobalEndpoint deletes global endpoint id and reports whether it existed.

func (*Plugin) RetireSecrets

func (p *Plugin) RetireSecrets(ctx context.Context, s *records.Store, ref EndpointRef) (Endpoint, error)

RetireSecrets drops every secret of the endpoint but its newest, ending a rotation, and returns the endpoint. An unknown endpoint is CodeNotFound.

func (*Plugin) RotateSecret

func (p *Plugin) RotateSecret(ctx context.Context, s *records.Store, ref EndpointRef, next Secret) (Endpoint, error)

RotateSecret makes next (a new random secret when "") the endpoint's newest secret and keeps the ones it had, so every delivery is signed with each of them (Standard Webhooks allows several signatures) and a receiver still set up with an older secret keeps verifying while it is switched over. Past MaxSecrets the oldest is dropped. Call RetireSecrets once every receiver has the new one. It returns the endpoint with its secrets; a next that is malformed, or already active, is CodeInvalidArgument; an unknown endpoint is CodeNotFound; a rotation racing another is CodeConflict, to retry.

type Sealer

type Sealer interface {
	Seal(ctx context.Context, secret string) (string, error)
	Open(ctx context.Context, sealed string) (string, error)
}

Sealer protects endpoint secrets at rest: Seal turns a secret into the text stored in fs_webhook_endpoints, Open turns that text back. Back it with a KMS, or an AEAD whose key lives outside the database, so a dump of the table does not hand out the means to forge deliveries. Without one (the default) secrets are stored as they are, since the plugin must read them back to sign.

type Secret

type Secret string

Secret is an endpoint's signing secret, "whsec_" and base64 as Standard Webhooks writes it. It prints, logs and marshals as "[redacted]", so it never leaks through fmt, slog or JSON; Reveal returns the value, to show once to whoever registers the endpoint.

func NewSecret

func NewSecret() Secret

NewSecret returns a random secret: "whsec_" and the base64 of 24 random bytes, as Standard Webhooks writes them.

func (Secret) GoString

func (Secret) GoString() string

GoString implements fmt.GoStringer, for %#v.

func (Secret) LogValue

func (Secret) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler, which JSON uses.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the secret itself.

func (Secret) String

func (Secret) String() string

String implements fmt.Stringer.

type SecretFormat

type SecretFormat interface {
	// NewSecret returns a new random secret in the signer's format.
	NewSecret() (Secret, error)
	// CheckSecret refuses a caller's secret the signer cannot sign with.
	CheckSecret(secret Secret) error
}

SecretFormat is an optional upgrade of a Signer whose secrets are not "whsec_" base64: a GitHub-style X-Hub-Signature-256 signer whose receivers already hold a free-form secret, endpoints imported from another webhook service, or ed25519 key material. When the plugin's Signer implements it, Register and RotateSecret generate secrets with NewSecret and check a caller's with CheckSecret instead of the package's NewSecret and CheckSecret. The floor stays the plugin's, whatever the format: every secret, generated or given, is at least MinSecretBytes and at most MaxSecretTextBytes long and holds no whitespace, so a lenient CheckSecret cannot let a short secret in.

type SignRequest

type SignRequest struct {
	// Header is the request's header: set the signature headers on it.
	Header http.Header
	// Endpoint is where the delivery goes, with its active secrets
	// (Secrets, newest first).
	Endpoint Endpoint
	// MessageID is the event's ID, the same on every attempt: Standard
	// Webhooks' Webhook-Id, for the receiver to drop repeats.
	MessageID string
	// At is the attempt's time, by the Store's clock.
	At time.Time
	// Body is exactly the bytes sent.
	Body []byte
}

SignRequest is one delivery attempt to sign. It is a struct so fields can be added without breaking Signers.

type Signer

type Signer interface {
	Sign(ctx context.Context, req SignRequest) error
}

Signer signs a delivery. The default, StandardSigner, is Standard Webhooks v1; an application plugs in ed25519 (v1a), GitHub-style X-Hub-Signature-256, or a key that never leaves its KMS. An error fails the attempt (retried after Backoff), so nothing is sent unsigned.

type StandardSigner

type StandardSigner struct{}

StandardSigner is the default Signer: SignAll with the endpoint's active secrets, HMAC-SHA256 in the Standard Webhooks v1 format. An Endpoint built by hand with only Secret set is signed with that one.

func (StandardSigner) Sign

Sign implements Signer.

type State

type State string

State is where a delivery stands.

const (
	StatePending   State = "pending"
	StateDelivered State = "delivered"
	// StateFailed is a delivery that used up MaxAttempts, or whose
	// endpoint was removed; it is never tried again.
	StateFailed State = "failed"
)

The closed set of delivery states.

Jump to

Keyboard shortcuts

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