Documentation
¶
Overview ¶
Package webhooks signs and verifies HTTP webhook deliveries in the Standard Webhooks v1 format (https://standardwebhooks.com/): the webhook-id, webhook-timestamp and webhook-signature headers, an HMAC-SHA256 over id + "." + timestamp + "." + body, and whsec_ secrets.
It knows nothing about what is being delivered. Callers build the body, pick the message id (the receiver dedups on it, so keep it stable across retries of the same delivery) and set the headers. It moved here from mcpkit's experimental/ext/events (mcpkit issue 1578), which keeps its own names as wrappers.
Example ¶
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
"github.com/panyam/servicekit/http/webhooks"
)
func main() {
secret := webhooks.GenerateSecret()
receiver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
id, ts, sig := r.Header.Get(webhooks.HeaderID), r.Header.Get(webhooks.HeaderTimestamp), r.Header.Get(webhooks.HeaderSignature)
if !webhooks.TimestampWithinTolerance(ts, time.Now(), webhooks.DefaultTolerance) ||
!webhooks.Verify(secret, id, ts, body, sig) {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
fmt.Printf("verified %s: %s\n", id, body)
}))
defer receiver.Close()
send := func(body []byte, signWith string) int {
msgID := "msg_1"
ts := webhooks.Timestamp(time.Now())
req, _ := http.NewRequest(http.MethodPost, receiver.URL, bytes.NewReader(body))
req.Header.Set(webhooks.HeaderID, msgID)
req.Header.Set(webhooks.HeaderTimestamp, ts)
req.Header.Set(webhooks.HeaderSignature, webhooks.Sign(signWith, msgID, ts, body))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
resp.Body.Close()
return resp.StatusCode
}
fmt.Println(send([]byte(`{"event":"created"}`), secret))
fmt.Println(send([]byte(`{"event":"created"}`), webhooks.GenerateSecret()))
}
Output: verified msg_1: {"event":"created"} 200 401
Index ¶
- Constants
- Variables
- func GenerateSecret() string
- func Sign(secret, msgID, timestamp string, body []byte) string
- func Timestamp(t time.Time) string
- func TimestampWithinTolerance(timestamp string, now time.Time, tolerance time.Duration) bool
- func ValidateSecret(s string) error
- func Verify(secret, msgID, timestamp string, body []byte, signature string) bool
Examples ¶
Constants ¶
const ( HeaderID = "webhook-id" HeaderTimestamp = "webhook-timestamp" HeaderSignature = "webhook-signature" )
Header names for a Standard Webhooks delivery. HTTP header names are case-insensitive; these are the lower-case forms the specification uses.
const ( MinSecretBytes = 24 MaxSecretBytes = 64 )
Secret length bounds, in raw bytes after base64 decoding. 24 bytes is 192 bits.
const DefaultTolerance = 5 * time.Minute
DefaultTolerance is how far a webhook timestamp may sit from the receiver's clock, either way, and still be accepted. Five minutes matches the Standard Webhooks reference libraries.
const SecretPrefix = "whsec_"
SecretPrefix starts every spec-format signing secret. The rest of the secret is base64 of the raw key bytes.
Variables ¶
var ( ErrSecretPrefix = errors.New("must start with the whsec_ prefix") ErrSecretEmpty = errors.New("missing the random portion after whsec_") ErrSecretEncoding = errors.New("portion after whsec_ must be base64-encoded") ErrSecretTooShort = errors.New("must decode to at least 24 random bytes (192 bits)") ErrSecretTooLong = errors.New("must decode to at most 64 random bytes (512 bits)") )
Errors returned by ValidateSecret. Their messages are written to be shown to whoever supplied the secret, e.g. as an invalid-params message.
Functions ¶
func GenerateSecret ¶
func GenerateSecret() string
GenerateSecret returns a new whsec_ secret holding 32 random bytes, encoded as standard padded base64 (RFC 4648 §4). That is the alphabet the reference verifier libraries decode; they can't read URL-safe secrets.
func Sign ¶
Sign returns the webhook-signature value ("v1,<base64>") for one delivery. timestamp is the exact webhook-timestamp header value, usually Timestamp(time.Now()).
The HMAC key is the base64-decoded bytes after the whsec_ prefix, as the specification says, never the literal string. A secret without the prefix is used verbatim, and a prefixed one that won't decode falls back to its raw bytes, so a stored legacy secret keeps signing instead of silently stopping deliveries. ValidateSecret is where malformed secrets get refused.
func TimestampWithinTolerance ¶
TimestampWithinTolerance reports whether timestamp (unix seconds) is within tolerance of now, in either direction. An empty or unparseable timestamp is outside every tolerance.
func ValidateSecret ¶
ValidateSecret checks that s is a spec-format secret: whsec_ followed by base64 that decodes to MinSecretBytes to MaxSecretBytes bytes. Both standard and raw URL-safe base64 are accepted, since some clients emit the latter. It returns nil or one of the ErrSecret* errors.
A server should run this when it accepts a secret, rather than store one that can never produce a delivery the receiver can verify.
func Verify ¶
Verify reports whether signature, a webhook-signature header value, holds a v1 signature of this delivery under secret. The header may carry several space-separated signatures (a sender mid-rotation signs with both secrets); any match is accepted. The comparison is constant-time.
Verify checks only the HMAC, so a captured delivery verifies forever. Receivers should also check TimestampWithinTolerance and dedup on msgID.
Types ¶
This section is empty.