webhook

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 21 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 webhook is the provider-webhook HTTP server the integration-controller embeds: one listener, one bounded worker pool, and one delivery-ID dedup window shared by every provider route, plus health/readiness endpoints with graceful drain.

Providers are the same shape downstream and differ only at the door, so an Endpoint supplies the two things that vary: how a delivery proves it is genuine (Authenticator) and where its event type and delivery id live (Decoder). The server owns everything after that. GitHub signs an HMAC over the raw body and labels deliveries with headers; a Google Cloud Pub/Sub push cannot compute an HMAC at all and instead presents a Google-signed OIDC token, with the message id inside the body.

Every route answers 202 before handling: the delivery is queued, and a full queue answers 503 so the provider retries. Handlers must be idempotent: providers redeliver, the dedup window is finite, and the controllers' reconcile loops converge missed or dropped deliveries anyway.

Index

Constants

View Source
const DefaultMaxBody = 25 << 20

DefaultMaxBody matches GitHub's 25 MB webhook payload cap, comfortably above a Pub/Sub push (10 MB) too.

View Source
const GoogleIssuer = "https://accounts.google.com"

GoogleIssuer is the issuer of the identity tokens Pub/Sub signs.

Variables

View Source
var ErrUnauthenticated = errors.New("delivery failed authentication")

ErrUnauthenticated is what an Authenticator returns when a delivery fails validation. The server answers 401 and says no more: a caller that cannot prove who it is gets no diagnostics.

Functions

func GitHubDecoder added in v0.8.0

func GitHubDecoder(r *http.Request, _ []byte) (eventType, deliveryID string, err error)

GitHubDecoder reads the event type and delivery GUID from GitHub's headers.

Types

type Authenticator added in v0.8.0

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

Authenticator validates one delivery before it is queued. body is the raw bytes as received. Signature schemes are computed over exactly those, so it must not be re-serialized before it gets here.

Returning a non-nil error rejects the delivery with 401; the error is logged, never returned to the caller.

type AuthenticatorFunc added in v0.8.0

type AuthenticatorFunc func(ctx context.Context, r *http.Request, body []byte) error

AuthenticatorFunc adapts a function to Authenticator.

func (AuthenticatorFunc) Authenticate added in v0.8.0

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

Authenticate implements Authenticator.

type Config

type Config struct {
	// Addr is the listen address, e.g. ":8080".
	Addr string
	// Endpoints are the provider routes to serve. At least one is required.
	Endpoints []Endpoint
	// Workers is the handler pool size. Default 4.
	Workers int
	// QueueSize bounds the delivery queue; a full queue answers 503 so the
	// provider redelivers. Default 64.
	QueueSize int
	// Ready optionally gates /readyz; nil means ready once serving.
	Ready func() bool
}

Config configures a Server.

type Decoder added in v0.8.0

type Decoder func(r *http.Request, body []byte) (eventType, deliveryID string, err error)

Decoder extracts the event type and delivery id from an authenticated request. Providers differ on where those live (GitHub uses headers, a Pub/Sub push carries the id in the body and needs no type at all), so the endpoint supplies the rule rather than the server assuming one.

An empty event type rejects the delivery with 400. An empty delivery id skips deduplication, for providers that do not give one.

type Endpoint added in v0.8.0

type Endpoint struct {
	// Path the provider POSTs to, e.g. "/github/webhooks".
	Path string
	// Auth validates deliveries. Required: an endpoint with no authenticator
	// would accept anything, so NewServer rejects it rather than defaulting
	// to something permissive.
	Auth Authenticator
	// Decode extracts the event type and delivery id. Required.
	Decode Decoder
	// Handler consumes validated deliveries.
	Handler Handler
	// MaxBody caps the request body in bytes; zero means DefaultMaxBody.
	MaxBody int
}

Endpoint is one provider's receiver route. patchy exposes a single internet-facing port: providers differ in how they authenticate and label a delivery, not in how it is queued and handled.

type Event

type Event struct {
	// Type is the provider's event discriminator, e.g. "code_scanning_alert".
	Type string
	// DeliveryID uniquely identifies the delivery, for deduplication.
	DeliveryID string
	// Payload is the raw JSON body.
	Payload []byte
	// Path is the request path the delivery arrived on, so a handler serving
	// more than one route can tell them apart. It equals the endpoint's
	// pattern for exact routes; for a wildcard route it is the concrete path,
	// carrying the matched segments (e.g. the integration name).
	Path string
}

Event is one validated webhook delivery.

type GoogleOIDCAuthenticator added in v0.8.0

type GoogleOIDCAuthenticator struct {
	// Verify checks the token signature and issuer.
	Verify TokenVerifier
	// Audience the token must carry, matching the subscription's
	// oidcToken.audience.
	Audience string
	// ServiceAccount is the email the token must be issued for. Checking it
	// stops any Google-issued token from being accepted: anyone with a GCP
	// account can mint one.
	ServiceAccount string
}

GoogleOIDCAuthenticator validates the OIDC token Pub/Sub signs for an authenticated push subscription.

A push subscription cannot compute an HMAC over the body (Pub/Sub composes the message, not the sender), so this is the only authentication available on that path. It is also a stronger one: the token is asymmetric, short-lived, and bound to both a service account and an audience.

func (*GoogleOIDCAuthenticator) Authenticate added in v0.8.0

func (a *GoogleOIDCAuthenticator) Authenticate(ctx context.Context, r *http.Request, _ []byte) error

Authenticate implements Authenticator.

type GoogleVerifier added in v0.8.0

type GoogleVerifier struct {

	// Issuer overrides the Google issuer; tests point it at a local server.
	Issuer string
	// Audience the verifier is built for.
	Audience string
	// contains filtered or unexported fields
}

GoogleVerifier is a TokenVerifier backed by Google's OIDC discovery document. Verifiers are cached per audience: building one fetches the discovery document over the network, which must not happen per delivery.

func NewGoogleVerifier added in v0.8.0

func NewGoogleVerifier(audience string) *GoogleVerifier

NewGoogleVerifier builds a verifier for one audience.

func (*GoogleVerifier) Verify added in v0.8.0

func (g *GoogleVerifier) Verify(ctx context.Context, raw string) (*IDTokenClaims, error)

Verify implements TokenVerifier. The provider is fetched on first use rather than at construction, so a network blip at startup cannot stop the controller coming up. Pub/Sub retries the delivery either way.

type HMACAuthenticator added in v0.8.0

type HMACAuthenticator struct {
	// SecretsFor returns the candidate secrets for a delivery.
	SecretsFor func(ctx context.Context) [][]byte
	// SecretsForRequest returns the candidate secrets for a delivery whose
	// candidate set depends on the request: a wildcard route whose path
	// names the integration the secret belongs to. When set it supersedes
	// SecretsFor. Returning an empty set fails authentication, so an
	// unknown path segment is indistinguishable from a bad signature.
	SecretsForRequest func(ctx context.Context, r *http.Request) [][]byte
	// Header carries the signature; empty means X-Hub-Signature-256.
	Header string
}

HMACAuthenticator validates GitHub's X-Hub-Signature-256 against the HMAC of the raw body. Secrets are supplied per request because they are per-Integration configuration that can change without a restart; the candidate set is tiny, and a signature matching any member passes.

func (*HMACAuthenticator) Authenticate added in v0.8.0

func (a *HMACAuthenticator) Authenticate(ctx context.Context, r *http.Request, body []byte) error

Authenticate implements Authenticator.

type Handler

type Handler interface {
	Handle(ctx context.Context, e Event) error
}

Handler consumes validated deliveries. Handle runs on a worker goroutine. Returning an error records the failure but is not retried here: the reconcile loop is the retry mechanism.

type HandlerFunc

type HandlerFunc func(ctx context.Context, e Event) error

HandlerFunc adapts a function to Handler.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(ctx context.Context, e Event) error

Handle implements Handler.

type IDTokenClaims added in v0.8.0

type IDTokenClaims struct {
	Audience string
	Email    string
	Verified bool `json:"email_verified"`
}

IDTokenClaims are the claims the authenticator decides on. Pub/Sub's push tokens are service-account tokens, so the identity is the email.

type Server

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

Server is the webhook HTTP server. One listener serves every provider: patchy exposes a single internet-facing port, and the endpoints differ only in how a delivery is authenticated and labelled.

func NewServer

func NewServer(cfg Config, log *slog.Logger) (*Server, error)

NewServer builds a Server and applies defaults for zero Config fields. It fails rather than serving an endpoint that cannot authenticate or label its deliveries: an unauthenticated internet-facing route is not something to discover at runtime.

func (*Server) ResetDedup added in v0.5.6

func (s *Server) ResetDedup()

ResetDedup drops the delivery dedup window, so redeliveries of already-seen IDs are handled as new. Called when an Integration's reset or replay request is consumed: both make the provider resend deliveries whose IDs the receiver has already recorded.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run serves until ctx is cancelled, then drains: the listener shuts down gracefully, queued deliveries finish, and the worker pool exits.

func (*Server) Serve added in v0.9.1

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve runs the accept loop on a caller-owned listener; Run is Serve with the listener bound from cfg.Addr. A caller that needs the bound address (an ephemeral-port test, the CLI dev harness printing its webhook URL) listens itself and hands the listener in.

type TokenAuthenticator added in v0.9.0

type TokenAuthenticator struct {
	// SecretsFor returns the candidate tokens for a delivery.
	SecretsFor func(ctx context.Context) [][]byte
}

TokenAuthenticator validates the shared bearer token a delivery carries in its Authorization header. It exists for providers (Wiz automation actions) that send a static header and cannot compute an HMAC over the body. Tokens are supplied per request because they are per-Integration configuration that can change without a restart; the candidate set is tiny, and a token matching any member passes.

func (*TokenAuthenticator) Authenticate added in v0.9.0

func (a *TokenAuthenticator) Authenticate(ctx context.Context, r *http.Request, _ []byte) error

Authenticate implements Authenticator. Only the "Bearer" scheme is accepted; each comparison is constant-time.

type TokenVerifier added in v0.8.0

type TokenVerifier interface {
	Verify(ctx context.Context, rawIDToken string) (*IDTokenClaims, error)
}

TokenVerifier checks a raw ID token and returns its claims. Narrowed to the one method the authenticator needs so tests can sign their own tokens without standing up a discovery document and a JWKS.

Jump to

Keyboard shortcuts

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