Gin and your data · 8 MIN READ
Signed webhooks in Gin: verify the raw bytes, reject stale timestamps, dedupe event IDs, answer fast
Receive signed webhooks in Gin by authenticating the raw body before binding, rejecting replays, deduplicating deliveries and choosing status codes that make the sender retry only when a retry can help.
A webhook endpoint is a public URL that anyone can POST to, called by a sender that retries whatever it believes failed. Three things matter more than the business logic: proving the request came from the sender unaltered, refusing old requests replayed by someone who captured one, and processing each event once although it may arrive several times. The status code is an instruction to the sender's retry machinery, so choose it as carefully as the verification.
gin · A MAP OF THE IDEA
- Read the bounded raw body
- Verify HMAC and timestamp
- Dedupe by event ID
- Enqueue, answer 2xx
Useful when
- Forged, altered and replayed requests never reach business code.
- Duplicate deliveries are acknowledged without reprocessing.
Watch out
- Dedupe records must outlive the sender's retry schedule.
- A 4xx for unhandled event types only causes pointless retries.
Implementation & operation cost: A shared secret per sender with rotation, a dedupe store with retention, a queue and workers, and monitoring of rejection rates.
The signature covers bytes, so read them before anything parses them
The sender computes HMAC-SHA256 with a shared secret over the exact bytes it sends; in this lesson that is the timestamp header, a dot and the body, a layout many providers use in some form, but follow your sender's documentation for the precise format. The receiver must recompute the MAC over the same bytes. Binding first breaks that: c.ShouldBindJSON reads c.Request.Body to the end, and re-encoding the bound struct does not reproduce the sender's bytes, because field order, spacing, escaping, number formatting and unknown fields all change. It also parses unauthenticated input before you know who sent it. So the verification middleware reads the body once through http.MaxBytesReader, checks it, and puts the same bytes back as a fresh reader so the handler can bind as usual. io.ReadAll is right here, unlike in the streaming-import lesson: a webhook payload is small, the cap is tight and the MAC needs every byte anyway. c.GetRawData is the same io.ReadAll with no limit of its own, so it needs the MaxBytesReader just as much.
A payments endpoint and seven deliveries
verifySignature runs on the /webhooks group only. It bounds and reads the body, verifies the signature and then the timestamp against an injected clock, records the precise reason with c.Error when it rejects, and restores the body. receive binds the event, acknowledges types it does not handle, and asks Inbox to deduplicate and enqueue in one step. main signs each delivery with a test-only secret, the way a sender would, and prints the status, the body and the reason an access log would record.
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
const (
maxPayload = 64 << 10
tolerance = 5 * time.Minute
)
type Event struct {
ID string `json:"id" binding:"required"`
Type string `json:"type" binding:"required"`
Data json.RawMessage `json:"data"`
}
func sign(secret []byte, ts string, body []byte) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(ts))
mac.Write([]byte{'.'})
mac.Write(body)
return mac.Sum(nil)
}
// verify checks every v1= signature in the header, so a sender can rotate secrets.
func verify(secret []byte, ts, header string, body []byte, now time.Time) error {
want := sign(secret, ts, body)
ok := false
for part := range strings.SplitSeq(header, ",") {
if v, found := strings.CutPrefix(strings.TrimSpace(part), "v1="); found {
got, err := hex.DecodeString(v)
ok = ok || (err == nil && hmac.Equal(got, want))
}
}
if !ok {
return errors.New("signature mismatch")
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return errors.New("bad timestamp")
}
if age := now.Sub(time.Unix(sec, 0)); age > tolerance || age < -tolerance {
return errors.New("timestamp outside tolerance")
}
return nil
}
// verifySignature authenticates the raw bytes before anything parses them,
// then hands the same bytes to the handler.
func verifySignature(secret []byte, now func() time.Time) gin.HandlerFunc {
return func(c *gin.Context) {
raw, err := io.ReadAll(http.MaxBytesReader(c.Writer, c.Request.Body, maxPayload))
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{"error": "payload too large"})
return
}
if err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
ts, sig := c.GetHeader("Webhook-Timestamp"), c.GetHeader("Webhook-Signature")
if err := verify(secret, ts, sig, raw, now()); err != nil {
_ = c.Error(err) // the reason goes to the log, not to the caller
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid signature"})
return
}
c.Request.Body = io.NopCloser(bytes.NewReader(raw))
c.Next()
}
}
// Inbox records event IDs and queues events; both happen under one lock.
type Inbox struct {
mu sync.Mutex
seen map[string]bool
queue chan Event
}
var errBusy = errors.New("queue full")
func (in *Inbox) Accept(e Event) (duplicate bool, err error) {
in.mu.Lock()
defer in.mu.Unlock()
if in.seen[e.ID] {
return true, nil
}
select {
case in.queue <- e:
in.seen[e.ID] = true // only once the event is safely queued
return false, nil
default:
return false, errBusy
}
}
var handled = map[string]bool{"payment.succeeded": true, "payment.refunded": true}
func receive(in *Inbox) gin.HandlerFunc {
return func(c *gin.Context) {
var e Event
if err := c.ShouldBindJSON(&e); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "malformed event"}) // a retry sends the same bytes
return
}
if !handled[e.Type] {
c.JSON(http.StatusOK, gin.H{"status": "ignored"}) // 4xx here would only cause retries
return
}
dup, err := in.Accept(e)
switch {
case err != nil:
c.Header("Retry-After", "60")
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "busy, retry later"})
case dup:
c.JSON(http.StatusOK, gin.H{"status": "duplicate"})
default:
c.JSON(http.StatusAccepted, gin.H{"status": "queued"})
}
}
}
func main() {
gin.SetMode(gin.TestMode)
secret := []byte("whsec-test-only-not-a-real-secret") // test key, never a production secret
clock := time.Unix(1_800_000_000, 0)
in := &Inbox{seen: map[string]bool{}, queue: make(chan Event, 2)}
r := gin.New()
var logged string
r.Use(func(c *gin.Context) { // stands in for the access log
c.Next()
if e := c.Errors.Last(); e != nil {
logged = " (log: " + e.Error() + ")"
}
})
hooks := r.Group("/webhooks", verifySignature(secret, func() time.Time { return clock }))
hooks.POST("/payments", receive(in))
event := func(id, typ string) string {
return `{"id":"` + id + `","type":"` + typ + `","data":{"amount":1200}}`
}
deliver := func(label, signed, sent string, at time.Time) {
ts := strconv.FormatInt(at.Unix(), 10)
req := httptest.NewRequest("POST", "/webhooks/payments", strings.NewReader(sent))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Webhook-Timestamp", ts)
req.Header.Set("Webhook-Signature", "v1="+hex.EncodeToString(sign(secret, ts, []byte(signed))))
w := httptest.NewRecorder()
logged = ""
r.ServeHTTP(w, req)
fmt.Printf("%-24s %d %s%s\n", label, w.Code, w.Body.String(), logged)
}
e1 := event("evt_1", "payment.succeeded")
deliver("first delivery", e1, e1, clock)
deliver("sender retry", e1, e1, clock.Add(40*time.Second))
deliver("tampered body", e1, strings.Replace(e1, "1200", "9900", 1), clock)
deliver("replay after 10 minutes", e1, e1, clock.Add(-10*time.Minute))
e2 := event("evt_2", "customer.updated")
deliver("unhandled type", e2, e2, clock)
e3, e4 := event("evt_3", "payment.refunded"), event("evt_4", "payment.succeeded")
deliver("second event", e3, e3, clock)
deliver("queue full", e4, e4, clock)
fmt.Println("evt_4 recorded as seen:", in.seen["evt_4"])
// The worker runs after the requests here only so the queue-full case is deterministic.
close(in.queue)
var wg sync.WaitGroup
var processed []string
wg.Go(func() {
for e := range in.queue {
processed = append(processed, e.ID)
}
})
wg.Wait()
fmt.Println("worker processed:", strings.Join(processed, " "))
}The first delivery is queued with 202. The sender's retry 40 seconds later has a new timestamp and a valid signature over the same event, and Inbox answers 200 duplicate without queuing it again. Changing the amount after signing breaks the MAC; replaying a genuine delivery whose timestamp is ten minutes old passes the MAC but fails the five-minute window. Both get the same 400 body, while the log line tells them apart. An event type the service does not handle is acknowledged with 200, so the sender stops offering it. With evt_3 queued the two-slot queue is full, so evt_4 gets 503 with Retry-After and is not recorded as seen, and the sender's next attempt will be accepted. The worker starts only after the requests here, purely so that the queue-full case is deterministic; in a service it runs from startup.
Compare in constant time, then check the clock
verify decodes each hex signature and compares it with hmac.Equal, which does not return at the first differing byte; the security.constant-time lesson explains why == and bytes.Equal leak how much of a guess was right. Accepting any v1= entry lets the sender sign with an old and a new secret during rotation; keep both configured on your side until the old one is retired. The timestamp is inside the MAC, so an attacker cannot refresh a captured request without the secret. It is parsed strictly and compared with the injected clock, which lets tests move time without sleeping, and the five-minute tolerance applies in both directions to absorb clock skew, so keep server clocks synchronized. The signature is checked first so that a stale-timestamp log line always describes an authentic request. Every verification failure returns the same body; the specific reason goes to the log. Not every provider signs a timestamp: GitHub's X-Hub-Signature-256 covers only the body, so replay protection there rests on deduplicating the X-GitHub-Delivery ID.
Deduplicate after verification, and record only what you queued
Senders deliver at least once. A timeout on their side or a lost response triggers a retry with the same event ID, usually with a new timestamp and signature, and Inbox turns it into 200 duplicate. Two orderings matter. Deduplicate only after verification, or forged requests can plant event IDs and make you drop the real events later. And mark an ID as seen in the same step that queues the event, only if queuing succeeded; otherwise a 503 is followed by a retry that is wrongly answered as a duplicate, and the event is lost. The tolerance window and the dedupe store work together: the window limits how long a captured request stays usable, dedupe covers replays inside it, and because sender retries can arrive hours or days later, dedupe records must outlive the sender's retry schedule. In a real service the inbox is a table with a unique key on sender and event ID, written in the same transaction as the job that will process the event, which is the inbox half of the systems.outbox-inbox lesson.
// Same contract as Inbox.Accept, so the handler does not change.
func (s *Store) Accept(ctx context.Context, e Event, raw []byte) (duplicate bool, err error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return false, err // the handler answers 503 and the sender retries
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `INSERT INTO webhook_inbox (sender, event_id, payload)
VALUES ($1, $2, $3) ON CONFLICT (sender, event_id) DO NOTHING`, "payments", e.ID, raw)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
if err != nil {
return false, err
}
if n == 0 {
return true, nil // already received: the handler answers 200
}
if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (kind, input) VALUES ('webhook', $1)`, raw); err != nil {
return false, err
}
return false, tx.Commit() // the handler answers 202 only when this is nil
}This fragment runs against PostgreSQL in your own environment. ON CONFLICT DO NOTHING makes the duplicate check and the insert one atomic statement, so two concurrent deliveries of the same event cannot both pass. Zero affected rows means a duplicate, reported as duplicate=true so the handler answers 200. The job row for the workers from the async-jobs lesson goes into the same transaction, and a nil error from Commit is the only path to 202; any error before that becomes a 503, and because the rollback also removes the inbox row, a retry from the sender is processed rather than taken for a duplicate.
Answer in milliseconds, with a status that steers retries
The handler verifies, deduplicates, enqueues and answers; the business work happens later in a worker. Senders time out quickly, and GitHub, for example, expects a response within 10 seconds, so processing inline turns every slow database moment into a retry of an event you may already have handled. Treat the status code as an instruction to the sender's retry logic. 2xx means do not send this again: 202 for a queued event, 200 for a duplicate, and 200 for an event type you do not handle, because a 4xx there only causes retries and, with some senders, a disabled endpoint. 4xx means retrying the same bytes cannot help: a bad or missing signature, a stale timestamp, malformed JSON in an authentic body, or a payload over the cap, which gets 413. 5xx means the failure is yours and temporary: a full queue or an unavailable database gets 503 with Retry-After, and an unexpected panic becomes a 500 through Recovery. Senders differ: many retry any non-2xx with backoff, some never retry, some ignore Retry-After, and several disable an endpoint after a run of failures. These codes are truthful under every policy; check which codes your sender treats specially, and alert on a rising 4xx rate, which usually means a rotated secret or a drifting clock.
Test with signed fixtures and a fake clock
Build test deliveries with the same sign function and a test-only secret, as main does, and never commit a real one. Cover a valid delivery, a retry, a tampered body, a tampered timestamp header, missing headers, malformed hex, a wrong secret, two signatures during rotation, timestamps exactly at the tolerance and one second beyond in both directions, a body over the cap, malformed JSON with a valid signature, an unhandled type, and a full queue followed by a successful retry. Assert that every rejected delivery leaves the inbox unchanged. Add a route-table test that fails if a webhook route is registered outside the verifying group, and remember that a webhook route has no browser session: exempt it from CSRF middleware, never from signature verification.
TAKE THIS WITH YOU
Read the bounded raw body once, verify an HMAC over timestamp and body with hmac.Equal, reject timestamps outside a window from an injected clock, dedupe by event ID only after verification, enqueue and answer 2xx fast, and keep 5xx for failures a retry can fix.
Check your understanding
Why must a Gin webhook handler verify the signature before it calls c.ShouldBindJSON?
Go to the source
Progress stays in this browser. No account needed.