Documentation
¶
Overview ¶
Package webhooks delivers normalized ReputeCast events to the endpoints a workspace registers (main spec 7.13). Every request is signed with HMAC-SHA256 using a write-only secret, retried with backoff (then kept in the dead-letter queue for 7 days), and protected against SSRF.
Index ¶
- Constants
- Variables
- func Emit(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, ...) (int, error)
- func Register(h huma.API, s *Service)
- func RegisterJobs(reg *jobs.Registry, s *Service, log *slog.Logger)
- func Sign(secret string, timestamp int64, body []byte) string
- func ValidEvent(name string) bool
- func Verify(secret, signature string, timestamp int64, body []byte, now time.Time, ...) bool
- type DeliverArgs
- type DeliverWorker
- type DeliveryPathInput
- type DispatchArgs
- type DispatchWorker
- type Envelope
- type Service
- func (s *Service) Attempt(ctx context.Context, deliveryID uuid.UUID) (*time.Time, error)
- func (s *Service) Create(ctx context.Context, ws *store.Workspace, p *authz.Principal, in WebhookInput) (WebhookCreated, error)
- func (s *Service) Delete(ctx context.Context, ws *store.Workspace, id uuid.UUID) error
- func (s *Service) Deliveries(ctx context.Context, ws *store.Workspace, webhookID *uuid.UUID, state string, ...) (WebhookDeliveryList, error)
- func (s *Service) Delivery(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookDeliveryDetail, error)
- func (s *Service) List(ctx context.Context, ws *store.Workspace) (WebhookList, error)
- func (s *Service) Retry(ctx context.Context, ws *store.Workspace, deliveryID, webhookID *uuid.UUID) (WebhookRetryResult, error)
- func (s *Service) RotateSecret(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookSecretResult, error)
- func (s *Service) SetEnabled(ctx context.Context, ws *store.Workspace, id uuid.UUID, enabled bool) error
- func (s *Service) Test(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookTestResult, error)
- func (s *Service) Update(ctx context.Context, ws *store.Workspace, id uuid.UUID, in WebhookInput) (WebhookView, error)
- type WebhookCreated
- type WebhookDeliveryDetail
- type WebhookDeliveryList
- type WebhookDeliveryView
- type WebhookEventInfo
- type WebhookInput
- type WebhookList
- type WebhookPathInput
- type WebhookRetryInput
- type WebhookRetryResult
- type WebhookSecretResult
- type WebhookTestResult
- type WebhookView
Constants ¶
const ( HeaderSignature = "X-ReputeCast-Signature" HeaderTimestamp = "X-ReputeCast-Timestamp" HeaderEvent = "X-ReputeCast-Event" HeaderDelivery = "X-ReputeCast-Delivery" )
Headers sent with every delivery.
const MaxAttempts = 8
MaxAttempts is how often a delivery is tried before it goes to the dead-letter queue.
Variables ¶
var Backoff = []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 30 * time.Minute, 90 * time.Minute, 225 * time.Minute}
Backoff after attempt n (1-based): 1, 2, 4, 8, 30, 90 and 225 minutes, so eight attempts span six hours.
var Events = []WebhookEventInfo{
{"contact.subscribed", "Contacts", "A contact joined a list (after double opt-in when it's on)."},
{"contact.unsubscribed", "Contacts", "A contact left a list or unsubscribed from everything."},
{"contact.updated", "Contacts", "Fields, tags or preferences changed."},
{"contact.erased", "Contacts", "Personal data was erased."},
{"email.sent", "Email", "A sending provider accepted a message."},
{"email.delivered", "Email", "The mailbox provider accepted the message."},
{"email.deferred", "Email", "Delivery was delayed and will be retried."},
{"email.bounced", "Email", "Hard or soft bounce, with the provider's original code."},
{"email.complained", "Email", "The recipient marked the message as spam."},
{"email.opened", "Email", "A human open (machine opens carry machine: true)."},
{"email.clicked", "Email", "A tracked link was clicked."},
{"campaign.scheduled", "Campaigns", "A campaign was scheduled."},
{"campaign.started", "Campaigns", "A send started."},
{"campaign.paused", "Campaigns", "A send paused, by a person or automatically."},
{"campaign.resumed", "Campaigns", "A paused send resumed."},
{"campaign.completed", "Campaigns", "A send finished."},
{"approval.requested", "Approvals", "A send needs approval."},
{"approval.decided", "Approvals", "A send was approved, rejected or sent back."},
{"provider.down", "Sending providers", "A sending provider is failing or unreachable."},
{"provider.recovered", "Sending providers", "A sending provider is healthy again."},
{"automation.published", "Automations", "A flow was published."},
}
Events is the catalogue of events, in display order.
Functions ¶
func Emit ¶
func Emit(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, workspaceSlug, event string, data any) (int, error)
Emit queues an event for every endpoint of the workspace subscribed to it. Call it inside the transaction that changes the state the event reports; a periodic job picks the deliveries up within seconds. It returns the number of deliveries queued.
func RegisterJobs ¶
RegisterJobs adds the delivery worker and the periodic dispatcher.
func ValidEvent ¶
ValidEvent reports whether name is a known event or wildcard ("email.*", "*").
Types ¶
type DeliverArgs ¶
DeliverArgs makes one attempt at one delivery.
func (DeliverArgs) InsertOpts ¶
func (DeliverArgs) InsertOpts() river.InsertOpts
InsertOpts puts deliveries on the events queue. River's own retries are off: the delivery row tracks attempts and backoff itself.
type DeliverWorker ¶
type DeliverWorker struct {
river.WorkerDefaults[DeliverArgs]
S *Service
Log *slog.Logger
}
DeliverWorker posts a delivery and schedules the next attempt on failure.
func (*DeliverWorker) Timeout ¶
func (w *DeliverWorker) Timeout(*river.Job[DeliverArgs]) time.Duration
Timeout bounds one attempt.
func (*DeliverWorker) Work ¶
func (w *DeliverWorker) Work(ctx context.Context, job *river.Job[DeliverArgs]) error
Work implements river.Worker.
type DeliveryPathInput ¶
type DeliveryPathInput struct {
api.WorkspaceInput
DeliveryID string `path:"deliveryId" format:"uuid"`
}
DeliveryPathInput is a path or query input shared by several operations.
type DispatchArgs ¶
type DispatchArgs struct{}
DispatchArgs is the periodic sweep that queues due deliveries (emitted by other domains inside their transactions) and purges old ones.
func (DispatchArgs) InsertOpts ¶
func (DispatchArgs) InsertOpts() river.InsertOpts
InsertOpts keeps one sweep at a time.
type DispatchWorker ¶
type DispatchWorker struct {
river.WorkerDefaults[DispatchArgs]
S *Service
Log *slog.Logger
}
DispatchWorker queues jobs for due deliveries.
func (*DispatchWorker) Work ¶
func (w *DispatchWorker) Work(ctx context.Context, _ *river.Job[DispatchArgs]) error
Work implements river.Worker.
type Envelope ¶
type Envelope struct {
ID string `json:"id"`
Type string `json:"type"`
CreatedAt time.Time `json:"created_at"`
Workspace string `json:"workspace"`
Data any `json:"data"`
}
Envelope is the JSON body of every delivery.
type Service ¶
type Service struct {
Pool *pgxpool.Pool
Q *store.Queries
Audit *audit.Logger
Box *secrets.Box
Jobs *jobs.Client
// AllowPrivate reports whether endpoints may resolve to private
// networks (webhooks.allow_private_networks); read at each use.
AllowPrivate func() bool
Now func() time.Time
// HTTP overrides the delivery client (tests).
HTTP *http.Client
}
func (*Service) Attempt ¶
Attempt makes one delivery attempt and records the result. It returns the time of the next attempt when the delivery will be retried.
func (*Service) Create ¶
func (s *Service) Create(ctx context.Context, ws *store.Workspace, p *authz.Principal, in WebhookInput) (WebhookCreated, error)
Create registers an endpoint and returns its signing secret once.
func (*Service) Deliveries ¶
func (s *Service) Deliveries(ctx context.Context, ws *store.Workspace, webhookID *uuid.UUID, state string, limit int) (WebhookDeliveryList, error)
Deliveries returns the latest deliveries, newest first.
func (*Service) Delivery ¶
func (s *Service) Delivery(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookDeliveryDetail, error)
Delivery returns one delivery with its payload.
func (*Service) Retry ¶
func (s *Service) Retry(ctx context.Context, ws *store.Workspace, deliveryID, webhookID *uuid.UUID) (WebhookRetryResult, error)
Retry queues failed deliveries for an immediate attempt: one delivery, every failed one of an endpoint, or every failed one of the workspace. Dead-lettered deliveries start a fresh round of attempts (replay).
func (*Service) RotateSecret ¶
func (s *Service) RotateSecret(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookSecretResult, error)
RotateSecret replaces the signing secret. Deliveries sign with the new one at once.
func (*Service) SetEnabled ¶
func (s *Service) SetEnabled(ctx context.Context, ws *store.Workspace, id uuid.UUID, enabled bool) error
SetEnabled pauses or resumes an endpoint. Events keep queuing while it is paused and are delivered in order when it resumes.
type WebhookCreated ¶
type WebhookCreated struct {
Webhook WebhookView `json:"webhook"`
Secret string `json:"secret" doc:"The signing secret. Shown only in this response."`
}
WebhookCreated carries the signing secret, shown once.
type WebhookDeliveryDetail ¶
type WebhookDeliveryDetail struct {
Delivery WebhookDeliveryView `json:"delivery"`
Payload json.RawMessage `json:"payload"`
Response string `json:"response" doc:"First kilobyte of the endpoint's last response"`
}
WebhookDeliveryDetail adds the payload and the endpoint's response.
type WebhookDeliveryList ¶
type WebhookDeliveryList struct {
Items []WebhookDeliveryView `json:"items"`
// Queued counts deliveries waiting per endpoint id.
Queued map[string]int64 `json:"queued"`
}
WebhookDeliveryList is the delivery log.
type WebhookDeliveryView ¶
type WebhookDeliveryView struct {
ID string `json:"id"`
WebhookID string `json:"webhookId"`
Endpoint string `json:"endpoint" doc:"Host and path, e.g. api.acme.io/hooks/reputecast"`
Event string `json:"event"`
// Subtype qualifies the event ("hard" for email.bounced).
Subtype string `json:"subtype,omitempty"`
State string `json:"state" enum:"pending,delivering,delivered,retrying,dead,held"`
StatusCode *int32 `json:"statusCode,omitempty"`
StatusText string `json:"statusText,omitempty" doc:"Bad Gateway"`
DurationMs *int32 `json:"durationMs,omitempty"`
Error string `json:"error,omitempty"`
Attempts int32 `json:"attempts"`
MaxAttempts int32 `json:"maxAttempts"`
CreatedAt time.Time `json:"createdAt"`
LastAttemptAt *time.Time `json:"lastAttemptAt,omitempty"`
NextAttemptAt *time.Time `json:"nextAttemptAt,omitempty"`
// BackoffMinutes is the wait before the next attempt.
BackoffMinutes *int `json:"backoffMinutes,omitempty"`
}
WebhookDeliveryView is one row of the delivery log.
type WebhookEventInfo ¶
type WebhookEventInfo struct {
Name string `json:"name" example:"email.bounced"`
Group string `json:"group" example:"Email"`
Description string `json:"description"`
}
WebhookEventInfo describes an event endpoints can subscribe to.
type WebhookInput ¶
type WebhookInput struct {
Name string `json:"name" maxLength:"80"`
Description string `json:"description,omitempty" maxLength:"120"`
URL string `json:"url" maxLength:"500"`
Events []string `json:"events" minItems:"1" maxItems:"40"`
}
WebhookInput creates or updates an endpoint.
type WebhookList ¶
type WebhookList struct {
Items []WebhookView `json:"items"`
Events []WebhookEventInfo `json:"events"`
// Headers name the signature headers for the "Verify a signature" card.
SignatureHeader string `json:"signatureHeader"`
TimestampHeader string `json:"timestampHeader"`
MaxAttempts int `json:"maxAttempts"`
}
WebhookList is the outgoing webhooks card.
type WebhookPathInput ¶
type WebhookPathInput struct {
api.WorkspaceInput
WebhookID string `path:"webhookId" format:"uuid"`
}
WebhookPathInput is a path or query input shared by several operations.
type WebhookRetryInput ¶
type WebhookRetryInput struct {
WebhookID string `json:"webhookId,omitempty" doc:"Only this endpoint; empty retries every endpoint"`
}
WebhookRetryInput limits "Retry all failed" to one endpoint.
type WebhookRetryResult ¶
type WebhookRetryResult struct {
Queued int `json:"queued"`
}
WebhookRetryResult counts the deliveries queued again.
type WebhookSecretResult ¶
type WebhookSecretResult struct {
Secret string `json:"secret"`
}
WebhookSecretResult carries a new signing secret, shown once.
type WebhookTestResult ¶
type WebhookTestResult struct {
Delivery WebhookDeliveryView `json:"delivery"`
}
WebhookTestResult is the outcome of a test delivery.
type WebhookView ¶
type WebhookView struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
Events []string `json:"events"`
Enabled bool `json:"enabled"`
// Status is new (no delivery yet), healthy, failing or paused.
Status string `json:"status" enum:"new,healthy,failing,paused"`
LastStatus *int32 `json:"lastStatus,omitempty"`
LastDeliveryAt *time.Time `json:"lastDeliveryAt,omitempty"`
FailingSince *time.Time `json:"failingSince,omitempty"`
SecretRotatedAt *time.Time `json:"secretRotatedAt,omitempty" doc:"Set when the secret was replaced after creation"`
CreatedAt time.Time `json:"createdAt"`
Total24h int64 `json:"total24h" doc:"Deliveries attempted in the last 24 hours"`
Success24h *float64 `json:"success24h,omitempty" doc:"Percent delivered in the last 24 hours"`
Queued int64 `json:"queued" doc:"Deliveries waiting for an attempt or a retry"`
}
WebhookView is an endpoint as listed. The secret is never returned.