## 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`_
114 lines
4.0 KiB
Go
114 lines
4.0 KiB
Go
// Package chatwebhook verifies that a webhook request for a chat automation
|
|
// comes from the sender that holds the automation's secret.
|
|
//
|
|
// A verifier keeps no state and never logs. Every error from Verify and
|
|
// ValidateSecret is built from a fixed string, so it never holds a secret, a
|
|
// received token, or a signature.
|
|
package chatwebhook
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"net/http"
|
|
"time"
|
|
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// Scheme names how a webhook proves its sender. The values equal the
|
|
// webhook_auth enum strings.
|
|
type Scheme string
|
|
|
|
const (
|
|
// SchemeBearer compares the Authorization bearer token with the secret.
|
|
SchemeBearer Scheme = "bearer"
|
|
// SchemeGitHub checks the HMAC-SHA256 in X-Hub-Signature-256.
|
|
SchemeGitHub Scheme = "github"
|
|
// SchemeStandardWebhooks checks the Standard Webhooks signature headers.
|
|
SchemeStandardWebhooks Scheme = "standard_webhooks"
|
|
)
|
|
|
|
var (
|
|
// ErrRejected wraps every error that Verify returns. The webhook route
|
|
// answers it with 401, the same as for an unknown automation.
|
|
ErrRejected = xerrors.New("webhook request rejected")
|
|
// ErrInvalidSecret wraps every error that ValidateSecret returns.
|
|
ErrInvalidSecret = xerrors.New("invalid webhook secret")
|
|
)
|
|
|
|
// WebhookVerifier checks that a webhook request comes from the sender
|
|
// that holds the automation's secret.
|
|
type WebhookVerifier interface {
|
|
// Verify returns nil when the request is authentic. body is the raw
|
|
// request body, already cut to the body limit. now is the server
|
|
// clock, for schemes that check a timestamp.
|
|
Verify(header http.Header, body []byte, secret string, now time.Time) error
|
|
// GenerateSecret returns a new secret when Coder creates the secret
|
|
// for this scheme, and ok=false when the sender creates it.
|
|
GenerateSecret() (secret string, ok bool, err error)
|
|
// ValidateSecret checks a secret that the owner pasted, for schemes
|
|
// where the sender creates the secret.
|
|
ValidateSecret(secret string) error
|
|
}
|
|
|
|
// NewVerifier returns the verifier for scheme.
|
|
func NewVerifier(scheme Scheme) (WebhookVerifier, error) {
|
|
switch scheme {
|
|
case SchemeBearer:
|
|
return bearerVerifier{}, nil
|
|
case SchemeGitHub:
|
|
return githubVerifier{}, nil
|
|
case SchemeStandardWebhooks:
|
|
return standardWebhooksVerifier{tolerance: standardWebhooksTolerance}, nil
|
|
default:
|
|
return nil, xerrors.Errorf("unknown webhook scheme %q", string(scheme))
|
|
}
|
|
}
|
|
|
|
// reject returns the error for a request that failed verification. reason
|
|
// must be a constant: it must never hold data from the request or the secret.
|
|
func reject(reason string) error {
|
|
return xerrors.Errorf("%s: %w", reason, ErrRejected)
|
|
}
|
|
|
|
// invalidSecret returns the error for a pasted secret that failed
|
|
// validation. reason must be a constant, for the same reason as in reject.
|
|
func invalidSecret(reason string) error {
|
|
return xerrors.Errorf("%s: %w", reason, ErrInvalidSecret)
|
|
}
|
|
|
|
// singleHeader returns the value of the named header when the request has
|
|
// exactly one such line. A repeated header is ambiguous, so it counts as
|
|
// missing.
|
|
func singleHeader(h http.Header, name string) (string, bool) {
|
|
values := h.Values(name)
|
|
if len(values) != 1 {
|
|
return "", false
|
|
}
|
|
return values[0], true
|
|
}
|
|
|
|
// secretsEqual compares in constant time. Hashing both sides first keeps
|
|
// the comparison time from showing the length of the secret.
|
|
func secretsEqual(a, b string) bool {
|
|
hashA, hashB := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b))
|
|
return subtle.ConstantTimeCompare(hashA[:], hashB[:]) == 1
|
|
}
|
|
|
|
// generatedSecretBytes is the amount of randomness in a secret that Coder
|
|
// creates.
|
|
const generatedSecretBytes = 32
|
|
|
|
// generateSecret returns a new secret for a scheme where Coder creates it.
|
|
// The unpadded base64url form is safe in a header and in the GitHub
|
|
// settings page.
|
|
func generateSecret() (string, bool, error) {
|
|
buf := make([]byte, generatedSecretBytes)
|
|
if _, err := rand.Read(buf); err != nil {
|
|
return "", false, xerrors.Errorf("read random bytes: %w", err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(buf), true, nil
|
|
}
|