Documentation
¶
Overview ¶
Package webhooks signs and verifies HTTP webhook deliveries in the Standard Webhooks format (https://standardwebhooks.com/): the webhook-id, webhook-timestamp and webhook-signature headers, an HMAC-SHA256 over id + "." + timestamp + "." + body, and whsec_ secrets. It also signs and verifies the asymmetric ed25519 schemes, v2a and the deprecated v1a, with whsk_ and whpk_ keys (asymmetric.go).
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 EncodePrivateKey(key ed25519.PrivateKey) string
- func EncodePublicKey(key ed25519.PublicKey) string
- func GenerateKeyPair() (privateKey, publicKey string)
- func GenerateSecret() string
- func ParsePrivateKey(s string) (ed25519.PrivateKey, error)
- func ParsePublicKey(s string) (ed25519.PublicKey, error)
- func Sign(secret, msgID, timestamp string, body []byte) string
- func SignV1a(signer crypto.Signer, msgID, timestamp string, body []byte) (string, error)
- func SignV2a(signer crypto.Signer, endpointID, msgID, timestamp string, body []byte) (string, error)
- 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
- func VerifyV1a(keys []ed25519.PublicKey, msgID, timestamp string, body []byte, ...) bool
- func VerifyV2a(keys []ed25519.PublicKey, endpointID, msgID, timestamp string, body []byte, ...) bool
Examples ¶
Constants ¶
const ( PrivateKeyPrefix = "whsk_" PublicKeyPrefix = "whpk_" )
Key prefixes for the serialized ed25519 keys. The rest of each key is base64 of the raw key bytes.
const ( SchemeV1 = "v1" SchemeV1a = "v1a" SchemeV2a = "v2a" )
Signature identifiers, the part before the comma in a webhook-signature entry.
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 ( ErrKeyPrefix = errors.New("key must start with whsk_ (private) or whpk_ (public)") ErrKeyEncoding = errors.New("portion after the key prefix must be base64-encoded") ErrKeyLength = errors.New("key has the wrong length for ed25519") ErrEndpointID = errors.New("endpoint ID must be non-empty and must not contain '.'") )
Errors returned by the key parsers and the v2a signer.
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 EncodePrivateKey ¶ added in v0.2.4
func EncodePrivateKey(key ed25519.PrivateKey) string
EncodePrivateKey serializes key as whsk_ followed by base64 of its 32-byte seed, the form the spec's example key uses.
func EncodePublicKey ¶ added in v0.2.4
EncodePublicKey serializes key as whpk_ followed by base64 of its 32 bytes.
func GenerateKeyPair ¶ added in v0.2.4
func GenerateKeyPair() (privateKey, publicKey string)
GenerateKeyPair returns a new ed25519 key pair, serialized as whsk_ and whpk_ strings in standard padded base64.
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 ParsePrivateKey ¶ added in v0.2.4
func ParsePrivateKey(s string) (ed25519.PrivateKey, error)
ParsePrivateKey reads a whsk_ key. The base64 may hold the 32-byte seed or the 64-byte seed-plus-public-key form. In the 64-byte form the public half must match the seed, so a corrupted key fails here instead of signing deliveries nobody can verify.
func ParsePublicKey ¶ added in v0.2.4
ParsePublicKey reads a whpk_ key.
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 SignV1a ¶ added in v0.2.4
SignV1a returns the deprecated v1a webhook-signature entry ("v1a,<base64>") for one delivery: ed25519 over "msg_id.timestamp.payload". New producers should send v2a. The signer receives the whole content, so a KMS signer with a message cap fails on large bodies.
func SignV2a ¶ added in v0.2.4
func SignV2a(signer crypto.Signer, endpointID, msgID, timestamp string, body []byte) (string, error)
SignV2a returns the webhook-signature entry ("v2a,<base64>") for one delivery to the endpoint endpointID. It hands the signer the 32-byte SHA-256 digest of the content, so a KMS or HSM signer that caps the message size works. An ed25519.PrivateKey is a crypto.Signer.
It returns ErrEndpointID when endpointID is empty or contains '.', since the receiver couldn't split the signed content back apart. Any other error comes from the signer.
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.
func VerifyV1a ¶ added in v0.2.4
func VerifyV1a(keys []ed25519.PublicKey, msgID, timestamp string, body []byte, signature string) bool
VerifyV1a reports whether signature, a webhook-signature header value, holds a v1a signature of this delivery under any of keys. Entries of other schemes are skipped. v1a carries no endpoint ID, so a receiver that trusts a key shared across endpoints accepts deliveries replayed from those endpoints.
func VerifyV2a ¶ added in v0.2.4
func VerifyV2a(keys []ed25519.PublicKey, endpointID, msgID, timestamp string, body []byte, signature string) bool
VerifyV2a reports whether signature, a webhook-signature header value, holds a v2a signature of this delivery under any of keys. endpointID must be the one the producer shared when the endpoint was set up, never a value read from the request. Entries of other schemes are skipped.
Like Verify, it checks only the signature. Receivers should also check TimestampWithinTolerance and dedup on msgID.
Types ¶
This section is empty.