Fix Insecure Webhooks in Chi
Webhooks are an attack vector often overlooked by lazy devs. If your Chi endpoint processes incoming payloads without cryptographic verification, you are essentially providing an unauthenticated RCE or data-manipulation primitive. Blindly trusting the `User-Agent` or source IP is amateur hour. To secure a Chi-based webhook, you must implement HMAC-SHA256 signature verification to ensure the payload originated from a trusted provider and hasn't been tampered with in transit.
The Vulnerable Pattern
func InsecureHandler(r chi.Router) {
r.Post("/webhook", func(w http.ResponseWriter, r *http.Request) {
var payload map[string]interface{}
// VULNERABILITY: No signature verification.
// Anyone can POST arbitrary JSON to this endpoint.
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "Bad Request", 400)
return
}
processWebhook(payload)
w.WriteHeader(http.StatusOK)
})
}
The Secure Implementation
The secure implementation uses a shared secret to generate an HMAC-SHA256 hash of the raw request body. Key points: 1. We use `io.ReadAll` to grab the body for hashing, then replace it using `io.NopCloser` so the next handler can still read it. 2. We compare the provided signature with our computed hash using `subtle.ConstantTimeCompare`. This is critical; standard string comparison (`==`) is vulnerable to timing attacks that allow an attacker to brute-force the signature byte-by-byte. 3. The logic is encapsulated in a Chi middleware, ensuring the business logic only executes if the authenticity is cryptographically proven.
func SecureHandler(r chi.Router) { webhookSecret := []byte(os.Getenv("WEBHOOK_SECRET"))r.With(VerifyHMAC(webhookSecret)).Post("/webhook", func(w http.ResponseWriter, r *http.Request) { // Payload is already verified by middleware w.WriteHeader(http.StatusOK) })}
func VerifyHMAC(secret []byte) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { signature := r.Header.Get(“X-Hub-Signature-256”) body, _ := io.ReadAll(r.Body) r.Body = io.NopCloser(bytes.NewBuffer(body))
h := hmac.New(sha256.New, secret) h.Write(body) expected := "sha256=" + hex.EncodeToString(h.Sum(nil)) // Use ConstantTimeCompare to prevent timing attacks if subtle.ConstantTimeCompare([]byte(signature), []byte(expected)) != 1 { http.Error(w, "Invalid Signature", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) }
}
Your Chi API
might be exposed to Insecure Webhooks
74% of Chi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.