Files
coder/coderd/x/chatd/chatwebhook/standardwebhooks.go
Thomas Kosiewski 85e689c89c feat(coderd/x/chatd/chatwebhook): add bearer, github and standard_webhooks verifiers (#32062)
## Why

An automation webhook must prove that a request comes from the holder of
the automation's secret before Coder parses the JSON body. The approved
RFC ([Automations for Coder
Agents](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d),
Webhooks section) puts that check behind one `WebhookVerifier` interface
with three schemes. This PR adds those verifiers as a pure Go package.
The webhook route that calls them comes in a later PR.

Part of CODAGT-1135.

## What changed

New leaf package `coderd/x/chatd/chatwebhook`:

- `WebhookVerifier`, with the three methods exactly as the RFC writes
them, and three verifiers: `bearer` (constant-time token compare, one or
more spaces after `Bearer` as in RFC 6750 section 2.1), `github`
(HMAC-SHA256 of the raw body in `X-Hub-Signature-256`) and
`standard_webhooks` (HMAC-SHA256 of `webhook-id.webhook-timestamp.body`,
`v1,` entries in `webhook-signature`, five-minute timestamp window,
`whsec_` secret).
- `Scheme` with the three RFC enum strings, and `NewVerifier(Scheme)`.
The package does not import `coderd/database`.
- Every `Verify` failure wraps `ErrRejected`, so the route can answer
`401`. Every `Verify` and `ValidateSecret` error is built from a fixed
string: it never holds the secret, the received token or a signature.
The package does not log. Only the `NewVerifier` error names the unknown
scheme.
- `GenerateSecret` reads 32 bytes from `crypto/rand` for `bearer` and
`github`. For `standard_webhooks` it returns `ok=false`, and
`ValidateSecret` checks the pasted `whsec_` secret.

## Scope

- No database, no HTTP route, no wiring, no new Go module. Nothing
imports the package yet, so `main` behaves as before with the
`chat-automations` experiment off.
- The map from the database enum to a verifier, and its "every enum
value has a verifier" test, belong to the route PR. It can call
`NewVerifier(chatwebhook.Scheme(automation.WebhookAuth))`. A
`NewVerifier` error is a server error, not a `401`.
- No deduplication by `webhook-id`, as in the RFC. The same valid
request verifies every time.

## Tradeoffs

- A pasted `whsec_` secret has no length bound. The spec describes
sender secrets of 24 to 64 bytes, but it does not tell a receiver to
reject others. A bound would lock out a sender that deviates, and it
protects only the owner from the sender's own key.
- The bearer verifier accepts one or more spaces between `Bearer` and
the token, as RFC 6750 section 2.1 and the API key middleware do. It
rejects a tab and an empty token. It also rejects trailing whitespace
after the token when it receives it, but an HTTP request cannot deliver
that: `net/http` strips trailing whitespace from the header value before
the verifier runs, so such a request is accepted with the right token.
- The signed Standard Webhooks content uses the `webhook-timestamp` text
as received. The reference Go library signs the reformatted number
instead. The two differ only for a timestamp with leading zeros, which a
conforming sender does not send.
- A `webhook-id` that contains `.` is rejected. The spec asks senders to
avoid it, because it makes `id.timestamp.body` ambiguous. A repeated
`Authorization`, `X-Hub-Signature-256`, `webhook-id` or
`webhook-timestamp` line is rejected for the same reason. Several
`webhook-signature` lines are read as one list.
- `TestSecretComparisonsAreConstantTime` reads the package source and
fails on `==`, `bytes.Equal` and similar on secrets. A correct
early-exit compare gives the same answers as a constant-time one, so a
request-level test cannot tell them apart. The scan is a guard against
the likely mistake, not a proof.

## Verification
- Test vectors come from the [GitHub
docs](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)
and from `TestWebhookSign` in the [Standard Webhooks Go
library](https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/go/webhook_test.go).
The tests cite the URL beside each vector.
- Live lane: none. No route, CLI or UI reaches this code yet, so there
is no surface to exercise.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
2026-11-12 02:49:28 +01:00

119 lines
3.8 KiB
Go

package chatwebhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"net/http"
"strconv"
"strings"
"time"
)
const (
// standardWebhooksTolerance is how far webhook-timestamp may differ
// from the server clock, in either direction.
standardWebhooksTolerance = 5 * time.Minute
standardWebhooksSecretPrefix = "whsec_"
)
// standardWebhooksVerifier checks a Standard Webhooks request:
// https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md
// The sender signs "webhook-id.webhook-timestamp.body" with HMAC-SHA256 and
// sends one or more "v1,<base64>" entries in webhook-signature.
type standardWebhooksVerifier struct {
tolerance time.Duration
}
func (v standardWebhooksVerifier) Verify(header http.Header, body []byte, secret string, now time.Time) error {
key, err := parseStandardWebhooksSecret(secret)
if err != nil {
return reject("secret is not usable")
}
// The spec asks senders to keep "." out of the id, because a "." would
// make the signed string ambiguous.
id, ok := singleHeader(header, "webhook-id")
if !ok || id == "" || strings.Contains(id, ".") {
return reject("webhook-id header missing, repeated or malformed")
}
timestamp, ok := singleHeader(header, "webhook-timestamp")
if !ok {
return reject("webhook-timestamp header missing or repeated")
}
// Digits only: no sign, space or fraction. 62 bits keeps time.Unix from
// overflowing.
seconds, err := strconv.ParseUint(timestamp, 10, 62)
if err != nil {
return reject("webhook-timestamp is not a unix timestamp")
}
age := now.Sub(time.Unix(int64(seconds), 0))
if age > v.tolerance || age < -v.tolerance {
return reject("webhook-timestamp outside the allowed window")
}
signatures := header.Values("webhook-signature")
if len(signatures) == 0 {
return reject("webhook-signature header missing")
}
mac := hmac.New(sha256.New, key)
_, _ = mac.Write([]byte(id + "." + timestamp + "."))
_, _ = mac.Write(body)
expected := mac.Sum(nil)
// A sender can list several signatures, for example during secret
// rotation. One valid v1 entry is enough. Entries with another version
// or a malformed entry are skipped.
for _, line := range signatures {
for entry := range strings.SplitSeq(line, " ") {
version, encoded, ok := strings.Cut(entry, ",")
if !ok || version != "v1" {
continue
}
received, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
continue
}
if hmac.Equal(received, expected) {
return nil
}
}
}
return reject("no signature matches")
}
// GenerateSecret reports ok=false: the sender creates the secret.
func (standardWebhooksVerifier) GenerateSecret() (string, bool, error) {
return "", false, nil
}
// ValidateSecret accepts "whsec_" followed by standard base64 that decodes
// to at least one byte. The spec describes secrets of 24 to 64 bytes, but
// this check does not enforce a length: it would lock out a sender that
// deviates and only protects the owner from the sender's own weak key.
func (standardWebhooksVerifier) ValidateSecret(secret string) error {
_, err := parseStandardWebhooksSecret(secret)
return err
}
// parseStandardWebhooksSecret returns the HMAC key inside a "whsec_" secret.
func parseStandardWebhooksSecret(secret string) ([]byte, error) {
encoded, ok := strings.CutPrefix(secret, standardWebhooksSecretPrefix)
if !ok {
return nil, invalidSecret("secret has no whsec_ prefix")
}
// The decoder skips newlines, so a pasted secret with one would pass.
if strings.ContainsAny(encoded, "\r\n") {
return nil, invalidSecret("secret contains a line break")
}
key, err := base64.StdEncoding.Strict().DecodeString(encoded)
if err != nil {
return nil, invalidSecret("secret is not base64")
}
if len(key) == 0 {
return nil, invalidSecret("secret is empty")
}
return key, nil
}