Secure Webhook Token (SWT) is a specialized, open JSON Web Token (JWT) specification defined in IETF Internet-Draft draft-knauer-secure-webhook-token-03 for authorizing and verifying webhook deliveries.
SWT provides cryptographic payload integrity binding, cross-service replay defense, audience enforcement (aud), and critical protection against indirect prompt injection and payload poisoning in autonomous AI agent architectures and Agent-to-Agent (A2A) workflows.
For full specification and architectural background, visit the SWT Documentation.
- IETF Draft-03 Compliant: Implements the specialized
webhookclaim (event,hash,retry_count), explicit typing (typ: "SWT"), and symmetric/asymmetric signature schemes. - Idiomatic HTTP Middleware: Standard
swt.Middlewarecompatible withnet/http, Chi, Echo, Gin, etc., restoringr.Bodyfor downstream handlers and exposing validated tokens via request context. - Single-Pass Streaming Hash: Computes and verifies payload hashes in a single read pass via
io.TeeReader, avoiding repeated memory buffers. - Dynamic Key Rotation & JWKS: Pluggable
KeyProvidercallback and JOSEkidheader injection (WithKeyID,WithHeaderClaim). - Clock Skew Tolerance: Built-in clock drift leeway (
ClockSkewoption andWithLeewayparser option). - Out-of-the-Box Replay Protection: Thread-safe, in-memory replay attacker defense (
MemoryReplayChecker) with automatic TTL eviction. - Hardened Security: Constant-time hash verification, algorithm confusion mitigation, defense-in-depth timeouts, and safe structured logging (
log/slog).
go get github.com/SecureWebhookToken/swtRequirements: Go 1.22+ (tested through Go 1.27+).
package main
import (
"log/slog"
"net/http"
"time"
"github.com/SecureWebhookToken/swt"
)
func main() {
secretKey := []byte("your-256-bit-secret-key-here-32b!")
// Build a signed HTTP POST request with embedded payload hash and audience claim
swtReq := swt.Request{
URL: "https://api.example.com/webhooks",
Issuer: "https://billing.example.com",
Audience: "https://api.example.com/webhooks",
Event: "invoice.paid",
Data: []byte(`{"invoice_id": "inv_12345", "amount": 99.00}`),
}
req, err := swtReq.Build(secretKey)
if err != nil {
slog.Error("Failed to build request", "error", err)
return
}
client := &http.Client{Timeout: 10 * time.Second}
res, err := client.Do(req)
if err != nil {
slog.Error("Failed to deliver webhook", "error", err)
return
}
defer res.Body.Close()
slog.Info("Webhook delivered", "status", res.StatusCode)
}swt.Middleware validates the request, verifies the payload hash in a single pass, restores r.Body, and injects the validated token into the request context:
package main
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"time"
"github.com/SecureWebhookToken/swt"
)
type InvoiceEvent struct {
InvoiceID string `json:"invoice_id"`
Amount float64 `json:"amount"`
}
func main() {
secretKey := []byte("your-256-bit-secret-key-here-32b!")
// Configure handler guardrails per Draft-03
opts := &swt.HandlerOptions{
ExpectedIssuer: "https://billing.example.com",
ExpectedAudience: "https://api.example.com/webhooks",
ClockSkew: 1 * time.Minute,
ReplayChecker: swt.NewMemoryReplayChecker(5 * time.Minute), // In-memory JTI tracking
}
mw, err := swt.Middleware(secretKey, opts)
if err != nil {
slog.Error("Failed to initialize middleware", "error", err)
return
}
// Downstream business handler
webhookHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 1. Extract validated SWT from context
token, ok := swt.FromContext(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
slog.Info("Processing webhook",
"event", token.Webhook().Event,
"jti", token.ID(),
"issuer", token.Issuer(),
"retry_count", token.Webhook().RetryCount,
)
// 2. Read restored request body
var payload InvoiceEvent
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "Invalid payload", http.StatusBadRequest)
return
}
slog.Info("Invoice processed", "invoice_id", payload.InvoiceID, "amount", payload.Amount)
w.WriteHeader(http.StatusOK)
})
mux := http.NewServeMux()
mux.Handle("/webhooks", mw(webhookHandler))
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
_ = server.ListenAndServe()
}For simple standalone endpoints:
handler, err := swt.NewHandlerFunc(secretKey, func(token *swt.SecureWebhookToken, data []byte) error {
slog.Info("Received event", "event", token.Webhook().Event, "payload", string(data))
return nil
}, opts)
if err != nil {
log.Fatal(err)
}
http.Handle("/webhook", handler)| Option | Type | Description |
|---|---|---|
ExpectedIssuer |
string |
Verifies the iss claim matches the authorized sender. |
ExpectedAudience |
string |
Verifies the aud claim matches the receiver endpoint per Draft-03. |
ClockSkew |
time.Duration |
Leeway tolerance for exp, nbf, iat claims (default: 1 * time.Minute). |
KeyProvider |
func(*jwt.Token) (any, error) |
Dynamic key lookup for key rotation and JWKS endpoints. |
ReplayChecker |
ReplayChecker |
Defense against token reuse attacks via jti tracking (e.g. NewMemoryReplayChecker). |
MaxBodySize |
int64 |
Maximum allowed request size in bytes (default: 32MB). |
ReturnErrorDetails |
bool |
Returns structured JSON error messages in responses (default: false). |
Logger |
*slog.Logger |
Custom structured logger (default: slog.Default()). |
Generate tokens with a Key ID (kid):
token, err := swt.New(
"https://billing.example.com",
"invoice.paid",
payloadHash,
swt.WithKeyID("key-2026-q4"),
)Resolve keys dynamically on the receiver:
opts := &swt.HandlerOptions{
KeyProvider: func(t *jwt.Token) (any, error) {
kid, _ := t.Header["kid"].(string)
return keyRegistry.LookupKey(kid)
},
}The project includes a Makefile with quality and security verification targets:
# Run unit and race-condition tests
make test
# Format code with go fmt and gofumpt
make fmt
make gofumpt
# Run static analysis
make lint
# Run vulnerability checks (gosec and govulncheck)
make vuln
# Full verification pipeline (fmt, gofumpt, lint, test, vuln)
make checkThis project is licensed under the MIT License.