From d4e66907c42f228c036747ffae5fb7b420db8fb0 Mon Sep 17 00:00:00 2001 From: Thomas Kosiewski Date: Wed, 25 Nov 2026 07:22:44 +0100 Subject: [PATCH] refactor(coderd/x/chatd/chatwebhook): keep only the Standard Webhooks verifier (#32614) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_ --- coderd/x/chatd/chatwebhook/bearer.go | 42 --- coderd/x/chatd/chatwebhook/bearer_test.go | 38 --- coderd/x/chatd/chatwebhook/chatwebhook.go | 113 -------- .../x/chatd/chatwebhook/chatwebhook_test.go | 245 ------------------ .../x/chatd/chatwebhook/constanttime_test.go | 77 ------ coderd/x/chatd/chatwebhook/github.go | 47 ---- coderd/x/chatd/chatwebhook/github_test.go | 45 ---- .../x/chatd/chatwebhook/standardwebhooks.go | 95 +++---- .../chatwebhook/standardwebhooks_test.go | 94 ++++--- 9 files changed, 99 insertions(+), 697 deletions(-) delete mode 100644 coderd/x/chatd/chatwebhook/bearer.go delete mode 100644 coderd/x/chatd/chatwebhook/bearer_test.go delete mode 100644 coderd/x/chatd/chatwebhook/chatwebhook.go delete mode 100644 coderd/x/chatd/chatwebhook/chatwebhook_test.go delete mode 100644 coderd/x/chatd/chatwebhook/constanttime_test.go delete mode 100644 coderd/x/chatd/chatwebhook/github.go delete mode 100644 coderd/x/chatd/chatwebhook/github_test.go diff --git a/coderd/x/chatd/chatwebhook/bearer.go b/coderd/x/chatd/chatwebhook/bearer.go deleted file mode 100644 index 84fd3ed39e3..00000000000 --- a/coderd/x/chatd/chatwebhook/bearer.go +++ /dev/null @@ -1,42 +0,0 @@ -package chatwebhook - -import ( - "net/http" - "strings" - "time" -) - -// bearerVerifier compares the token of an "Authorization: Bearer TOKEN" -// header with the secret. It does not read the body. -type bearerVerifier struct{} - -func (bearerVerifier) Verify(header http.Header, _ []byte, secret string, _ time.Time) error { - value, ok := singleHeader(header, "Authorization") - if !ok { - return reject("authorization header missing or repeated") - } - // RFC 6750 section 2.1: credentials = "Bearer" 1*SP b64token. RFC 7235: - // the authentication scheme is case-insensitive. Only spaces separate - // the scheme from the token. Anything after the token is part of it. - const scheme = "Bearer" - if len(value) <= len(scheme) || strings.ToLower(value[:len(scheme)]) != "bearer" || value[len(scheme)] != ' ' { - return reject("authorization header is not a bearer token") - } - // A token is required, so "Bearer " never matches an empty secret. - token := strings.TrimLeft(value[len(scheme):], " ") - if token == "" { - return reject("bearer token is empty") - } - if !secretsEqual(token, secret) { - return reject("token does not match") - } - return nil -} - -func (bearerVerifier) GenerateSecret() (string, bool, error) { - return generateSecret() -} - -func (bearerVerifier) ValidateSecret(string) error { - return invalidSecret("coder creates the secret for this scheme") -} diff --git a/coderd/x/chatd/chatwebhook/bearer_test.go b/coderd/x/chatd/chatwebhook/bearer_test.go deleted file mode 100644 index 5b53252ded7..00000000000 --- a/coderd/x/chatd/chatwebhook/bearer_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package chatwebhook_test - -import ( - "net/http" - "testing" - - "github.com/coder/coder/v2/coderd/x/chatd/chatwebhook" -) - -func TestBearer(t *testing.T) { - t.Parallel() - - const secret = "q1w2e3r4t5y6u7i8o9p0q1w2e3r4t5y6u7i8o9p0abc" - auth := func(value string) http.Header { return header("Authorization", value) } - - runVerifyCases(t, newVerifier(t, chatwebhook.SchemeBearer), []verifyCase{ - {name: "valid token", header: auth("Bearer " + secret), secret: secret, accepted: true}, - {name: "scheme word in lower case", header: auth("bearer " + secret), secret: secret, accepted: true}, - // RFC 6750 section 2.1: credentials = "Bearer" 1*SP b64token. - {name: "two spaces before the token", header: auth("Bearer " + secret), secret: secret, accepted: true}, - - {name: "header missing", header: http.Header{}, secret: secret}, - {name: "wrong scheme Digest", header: auth("Digest " + secret), secret: secret}, - {name: "no space after the scheme", header: auth("Bearer" + secret), secret: secret}, - {name: "scheme only", header: auth("Bearer"), secret: secret}, - {name: "spaces only after the scheme and an empty secret", header: auth("Bearer "), secret: ""}, - {name: "tab before the token", header: auth("Bearer\t" + secret), secret: secret}, - {name: "tab after the spaces", header: auth("Bearer \t" + secret), secret: secret}, - {name: "wrong token", header: auth("Bearer not-the-secret"), secret: secret}, - {name: "token is a strict prefix of the secret", header: auth("Bearer " + secret[:len(secret)-1]), secret: secret}, - {name: "secret is a strict prefix of the token", header: auth("Bearer " + secret + "x"), secret: secret}, - {name: "token differs in the last byte", header: auth("Bearer " + secret[:len(secret)-1] + "X"), secret: secret}, - {name: "two Authorization lines, first valid", header: header("Authorization", "Bearer "+secret, "Authorization", "Bearer x"), secret: secret}, - {name: "two Authorization lines, second valid", header: header("Authorization", "Bearer x", "Authorization", "Bearer "+secret), secret: secret}, - {name: "empty secret and empty token", header: auth("Bearer "), secret: ""}, - {name: "empty secret and any token", header: auth("Bearer anything"), secret: ""}, - }) -} diff --git a/coderd/x/chatd/chatwebhook/chatwebhook.go b/coderd/x/chatd/chatwebhook/chatwebhook.go deleted file mode 100644 index 8203290fedc..00000000000 --- a/coderd/x/chatd/chatwebhook/chatwebhook.go +++ /dev/null @@ -1,113 +0,0 @@ -// 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 -} diff --git a/coderd/x/chatd/chatwebhook/chatwebhook_test.go b/coderd/x/chatd/chatwebhook/chatwebhook_test.go deleted file mode 100644 index ddcdaf7092d..00000000000 --- a/coderd/x/chatd/chatwebhook/chatwebhook_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package chatwebhook_test - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - "strconv" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/coder/coder/v2/coderd/x/chatd/chatwebhook" -) - -// now is the server clock that tests pass to Verify. -var now = time.Date(2026, time.November, 11, 12, 0, 0, 0, time.UTC) - -// verifyCase is one request for a verifier. accepted false means Verify must -// return an error that wraps ErrRejected. -type verifyCase struct { - name string - header http.Header - body []byte - secret string - now time.Time // The zero value means the package-level now. - accepted bool -} - -func newVerifier(t *testing.T, scheme chatwebhook.Scheme) chatwebhook.WebhookVerifier { - t.Helper() - v, err := chatwebhook.NewVerifier(scheme) - require.NoError(t, err) - return v -} - -// header builds a header from name and value pairs. A name that repeats -// becomes several header lines. -func header(pairs ...string) http.Header { - h := http.Header{} - for i := 0; i < len(pairs); i += 2 { - h.Add(pairs[i], pairs[i+1]) - } - return h -} - -func hmacSHA256(key, msg []byte) []byte { - h := hmac.New(sha256.New, key) - _, _ = h.Write(msg) - return h.Sum(nil) -} - -func requireRejected(t *testing.T, err error) { - t.Helper() - require.Error(t, err) - require.ErrorIs(t, err, chatwebhook.ErrRejected) -} - -func runVerifyCases(t *testing.T, v chatwebhook.WebhookVerifier, cases []verifyCase) { - t.Helper() - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - at := tc.now - if at.IsZero() { - at = now - } - err := v.Verify(tc.header, tc.body, tc.secret, at) - if tc.accepted { - require.NoError(t, err) - return - } - requireRejected(t, err) - }) - } -} - -func TestNewVerifier(t *testing.T) { - t.Parallel() - - for _, scheme := range []chatwebhook.Scheme{"", "Bearer"} { - t.Run("unknown scheme "+strconv.Quote(string(scheme)), func(t *testing.T) { - t.Parallel() - v, err := chatwebhook.NewVerifier(scheme) - require.Error(t, err) - require.Nil(t, v) - }) - } -} - -func TestGenerateSecret(t *testing.T) { - t.Parallel() - - for _, scheme := range []chatwebhook.Scheme{chatwebhook.SchemeBearer, chatwebhook.SchemeGitHub} { - t.Run(string(scheme), func(t *testing.T) { - t.Parallel() - v := newVerifier(t, scheme) - - seen := map[string]struct{}{} - for range 50 { - secret, ok, err := v.GenerateSecret() - require.NoError(t, err) - require.True(t, ok) - - raw, err := base64.RawURLEncoding.DecodeString(secret) - require.NoError(t, err, "a generated secret is base64url, which is safe in a header") - require.GreaterOrEqual(t, len(raw), 32, "at least 32 random bytes") - - _, dup := seen[secret] - require.False(t, dup, "generated secrets are unique") - seen[secret] = struct{}{} - } - - // Coder creates this secret, so a pasted one is refused. - err := v.ValidateSecret("anything") - require.ErrorIs(t, err, chatwebhook.ErrInvalidSecret) - }) - } - - t.Run("standard_webhooks sender creates the secret", func(t *testing.T) { - t.Parallel() - secret, ok, err := newVerifier(t, chatwebhook.SchemeStandardWebhooks).GenerateSecret() - require.NoError(t, err) - require.False(t, ok) - require.Empty(t, secret) - }) -} - -// errorTexts returns every text an error can show: its message, its verbose -// form, and the message of each error in its unwrap chain. -func errorTexts(err error) []string { - texts := []string{err.Error(), fmt.Sprintf("%+v", err), fmt.Sprintf("%#v", err)} - for e := errors.Unwrap(err); e != nil; e = errors.Unwrap(e) { - texts = append(texts, e.Error(), fmt.Sprintf("%+v", e)) - } - return texts -} - -func requireNoCanary(t *testing.T, err error, canaries ...string) { - t.Helper() - require.Error(t, err) - for _, text := range errorTexts(err) { - for _, canary := range canaries { - require.NotContains(t, text, canary) - } - } -} - -// badRequest is a request that Verify must reject. -type badRequest struct { - name string - header http.Header - secret string -} - -// requireOpaqueRejections checks that each request is rejected and that no -// error text shows a canary. -func requireOpaqueRejections(t *testing.T, v chatwebhook.WebhookVerifier, body []byte, requests []badRequest, canaries ...string) { - t.Helper() - for _, req := range requests { - t.Run(req.name, func(t *testing.T) { - t.Parallel() - err := v.Verify(req.header, body, req.secret, now) - requireRejected(t, err) - requireNoCanary(t, err, canaries...) - }) - } -} - -func TestErrorsDoNotLeakCredentials(t *testing.T) { - t.Parallel() - - // Each canary stands for a value that must never appear in an error: the - // stored secret, a received token or signature, an expected signature. - const ( - secretCanary = "CANARY-SECRET-0f9e8d7c6b5a4938" //nolint:gosec // Fixture that must never appear in an error. - tokenCanary = "CANARY-TOKEN-1a2b3c4d5e6f7089" //nolint:gosec // Fixture that must never appear in an error. - receivedCanary = "CANARY-RECEIVED-77665544" - ) - - t.Run("bearer", func(t *testing.T) { - t.Parallel() - v := newVerifier(t, chatwebhook.SchemeBearer) - requireOpaqueRejections(t, v, nil, []badRequest{ - {"wrong token", header("Authorization", "Bearer "+tokenCanary), secretCanary}, - {"wrong scheme", header("Authorization", "Basic "+tokenCanary), secretCanary}, - {"two lines", header("Authorization", "Bearer "+tokenCanary, "Authorization", "Bearer "+secretCanary), secretCanary}, - }, secretCanary, tokenCanary) - requireNoCanary(t, v.ValidateSecret(secretCanary), secretCanary) - }) - - t.Run("github", func(t *testing.T) { - t.Parallel() - v := newVerifier(t, chatwebhook.SchemeGitHub) - body := []byte(`{"a":1}`) - expected := hex.EncodeToString(hmacSHA256([]byte(secretCanary), body)) - wrong := hex.EncodeToString(hmacSHA256([]byte("other"), body)) - sig := func(v string) http.Header { return header("X-Hub-Signature-256", v) } - requireOpaqueRejections(t, v, body, []badRequest{ - {"wrong signature", sig("sha256=" + wrong), secretCanary}, - {"not hex", sig("sha256=" + receivedCanary), secretCanary}, - {"no prefix", sig(wrong), secretCanary}, - {"two lines", header("X-Hub-Signature-256", "sha256="+wrong, "X-Hub-Signature-256", "sha256="+expected), secretCanary}, - {"empty secret", sig("sha256=" + expected), ""}, - }, secretCanary, expected, "sha256="+expected, wrong, receivedCanary) - }) - - t.Run("standard_webhooks", func(t *testing.T) { - t.Parallel() - v := newVerifier(t, chatwebhook.SchemeStandardWebhooks) - key := []byte(secretCanary) - keyB64 := base64.StdEncoding.EncodeToString(key) - secret := "whsec_" + keyB64 - body := []byte(`{"a":1}`) - ts := strconv.FormatInt(now.Unix(), 10) - old := strconv.FormatInt(now.Add(-time.Hour).Unix(), 10) - signature := func(key []byte, ts string) string { - return base64.StdEncoding.EncodeToString(hmacSHA256(key, []byte("msg_1."+ts+"."+string(body)))) - } - expected, wrong, oldSig := signature(key, ts), signature([]byte("other"), ts), signature(key, old) - hdr := func(ts string, sigs ...string) http.Header { - return header("webhook-id", "msg_1", "webhook-timestamp", ts, "webhook-signature", strings.Join(sigs, " ")) - } - requireOpaqueRejections(t, v, body, []badRequest{ - {"wrong signature", hdr(ts, "v1,"+wrong), secret}, - {"timestamp too old", hdr(old, "v1,"+oldSig), secret}, - {"not base64", hdr(ts, "v1,"+receivedCanary), secret}, - {"wrong version", hdr(ts, "v2,"+expected), secret}, - {"missing id", header("webhook-timestamp", ts, "webhook-signature", "v1,"+expected), secret}, - {"secret without prefix", hdr(ts, "v1,"+expected), keyB64}, - {"secret not base64", hdr(ts, "v1,"+expected), secret + "!"}, - }, secretCanary, keyB64, secret, expected, "v1,"+expected, wrong, oldSig, receivedCanary) - - for _, bad := range []string{secret + "!", keyB64} { - err := v.ValidateSecret(bad) - require.ErrorIs(t, err, chatwebhook.ErrInvalidSecret) - requireNoCanary(t, err, secretCanary, keyB64) - } - }) -} diff --git a/coderd/x/chatd/chatwebhook/constanttime_test.go b/coderd/x/chatd/chatwebhook/constanttime_test.go deleted file mode 100644 index ed964013795..00000000000 --- a/coderd/x/chatd/chatwebhook/constanttime_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package chatwebhook_test - -import ( - "go/ast" - "go/parser" - "go/token" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/require" -) - -// TestSecretComparisonsAreConstantTime fails when the package compares -// secrets or signatures in variable time. A compare that exits at the first -// differing byte gives the same answers as a constant-time one, so no -// request-level test can tell them apart. This guard reads the source -// instead. Comparisons must go through crypto/subtle or hmac.Equal. -func TestSecretComparisonsAreConstantTime(t *testing.T) { - t.Parallel() - - variableTimeCalls := map[string]bool{ - "bytes.Equal": true, - "bytes.Compare": true, - "strings.Compare": true, - "strings.EqualFold": true, - "slices.Equal": true, - "reflect.DeepEqual": true, - } - // A comparison against a literal, nil, or a length cannot compare two - // secrets. - isBenign := func(e ast.Expr) bool { - switch e := e.(type) { - case *ast.BasicLit: - return true - case *ast.Ident: - return e.Name == "nil" || e.Name == "true" || e.Name == "false" - case *ast.CallExpr: - id, ok := e.Fun.(*ast.Ident) - return ok && id.Name == "len" - } - return false - } - - files, err := filepath.Glob("*.go") - require.NoError(t, err) - checked := 0 - for _, file := range files { - if strings.HasSuffix(file, "_test.go") { - continue - } - checked++ - fset := token.NewFileSet() - parsed, err := parser.ParseFile(fset, file, nil, 0) - require.NoError(t, err) - - ast.Inspect(parsed, func(n ast.Node) bool { - switch n := n.(type) { - case *ast.CallExpr: - sel, ok := n.Fun.(*ast.SelectorExpr) - if !ok { - return true - } - pkg, ok := sel.X.(*ast.Ident) - if ok && variableTimeCalls[pkg.Name+"."+sel.Sel.Name] { - t.Errorf("%s: %s.%s compares in variable time", fset.Position(n.Pos()), pkg.Name, sel.Sel.Name) - } - case *ast.BinaryExpr: - if (n.Op == token.EQL || n.Op == token.NEQ) && !isBenign(n.X) && !isBenign(n.Y) { - t.Errorf("%s: == or != between two values; compare secrets with crypto/subtle or hmac.Equal", fset.Position(n.Pos())) - } - } - return true - }) - } - require.NotZero(t, checked, "the guard must find the package's source files") -} diff --git a/coderd/x/chatd/chatwebhook/github.go b/coderd/x/chatd/chatwebhook/github.go deleted file mode 100644 index be25ed0ee87..00000000000 --- a/coderd/x/chatd/chatwebhook/github.go +++ /dev/null @@ -1,47 +0,0 @@ -package chatwebhook - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "net/http" - "strings" - "time" -) - -// githubVerifier checks the HMAC-SHA256 of the raw body that GitHub sends -// in X-Hub-Signature-256. -type githubVerifier struct{} - -func (githubVerifier) Verify(header http.Header, body []byte, secret string, _ time.Time) error { - // HMAC accepts an empty key, so a sender could sign with one. - if secret == "" { - return reject("secret is empty") - } - value, ok := singleHeader(header, "X-Hub-Signature-256") - if !ok { - return reject("signature header missing or repeated") - } - digest, ok := strings.CutPrefix(value, "sha256=") - if !ok { - return reject("signature header has no sha256= prefix") - } - received, err := hex.DecodeString(digest) - if err != nil { - return reject("signature is not hex") - } - mac := hmac.New(sha256.New, []byte(secret)) - _, _ = mac.Write(body) - if !hmac.Equal(received, mac.Sum(nil)) { - return reject("signature does not match") - } - return nil -} - -func (githubVerifier) GenerateSecret() (string, bool, error) { - return generateSecret() -} - -func (githubVerifier) ValidateSecret(string) error { - return invalidSecret("coder creates the secret for this scheme") -} diff --git a/coderd/x/chatd/chatwebhook/github_test.go b/coderd/x/chatd/chatwebhook/github_test.go deleted file mode 100644 index 718d07481ce..00000000000 --- a/coderd/x/chatd/chatwebhook/github_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package chatwebhook_test - -import ( - "encoding/hex" - "net/http" - "strings" - "testing" - - "github.com/coder/coder/v2/coderd/x/chatd/chatwebhook" -) - -func TestGitHub(t *testing.T) { - t.Parallel() - - // Official vector from - // https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries - const ( - vectorSecret = "It's a Secret to Everybody" - vectorBody = "Hello, World!" - vectorSig = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17" - ) - - const secret = "j9X0c2Vy-Z2l0aHViLXRlc3Qtc2VjcmV0LTAxMjM0NTY" //nolint:gosec // Test fixture, not a credential. - signHex := func(secret string, body []byte) string { - return hex.EncodeToString(hmacSHA256([]byte(secret), body)) - } - sig := func(value string) http.Header { return header("X-Hub-Signature-256", value) } - body := []byte(`{"action":"opened","number":1}`) - valid := signHex(secret, body) - - runVerifyCases(t, newVerifier(t, chatwebhook.SchemeGitHub), []verifyCase{ - {name: "official vector", header: sig(vectorSig), body: []byte(vectorBody), secret: vectorSecret, accepted: true}, - {name: "valid signature", header: sig("sha256=" + valid), body: body, secret: secret, accepted: true}, - - {name: "header missing", header: http.Header{}, body: body, secret: secret}, - {name: "no prefix", header: sig(valid), body: body, secret: secret}, - {name: "truncated digest", header: sig("sha256=" + valid[:62]), body: body, secret: secret}, - {name: "digest with extra bytes", header: sig("sha256=" + valid + "00"), body: body, secret: secret}, - {name: "two lines, first valid", header: header("X-Hub-Signature-256", "sha256="+valid, "X-Hub-Signature-256", "sha256="+strings.Repeat("0", 64)), body: body, secret: secret}, - {name: "two lines, second valid", header: header("X-Hub-Signature-256", "sha256="+strings.Repeat("0", 64), "X-Hub-Signature-256", "sha256="+valid), body: body, secret: secret}, - {name: "wrong secret", header: sig("sha256=" + valid), body: body, secret: secret + "x"}, - {name: "tampered body", header: sig("sha256=" + valid), body: append([]byte(nil), append(body, ' ')...), secret: secret}, - {name: "signature made with an empty key", header: sig("sha256=" + signHex("", body)), body: body, secret: ""}, - }) -} diff --git a/coderd/x/chatd/chatwebhook/standardwebhooks.go b/coderd/x/chatd/chatwebhook/standardwebhooks.go index 339c8a3255e..a8c34ae04a1 100644 --- a/coderd/x/chatd/chatwebhook/standardwebhooks.go +++ b/coderd/x/chatd/chatwebhook/standardwebhooks.go @@ -1,3 +1,9 @@ +// Package chatwebhook verifies Standard Webhooks requests: +// https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md +// +// Verify keeps no state and never logs. Every error it returns is built from +// a fixed string, so it never holds a secret, a received signature, or an +// expected one. package chatwebhook import ( @@ -8,54 +14,52 @@ import ( "strconv" "strings" "time" + + "golang.org/x/xerrors" ) const ( - // standardWebhooksTolerance is how far webhook-timestamp may differ - // from the server clock, in either direction. - standardWebhooksTolerance = 5 * time.Minute + // tolerance is how far webhook-timestamp may differ from the server + // clock, in either direction. + tolerance = 5 * time.Minute - standardWebhooksSecretPrefix = "whsec_" + secretPrefix = "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," 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") +// Verify returns nil when the request is signed with secret, a "whsec_" +// secret. body is the raw request body. now is the server clock. The sender +// signs "webhook-id.webhook-timestamp.body" with HMAC-SHA256 and sends one or +// more "v1," entries in webhook-signature. +func Verify(header http.Header, body []byte, secret string, now time.Time) error { + key, ok := parseSecret(secret) + if !ok { + return xerrors.New("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") + return xerrors.New("webhook-id header missing, repeated or malformed") } timestamp, ok := singleHeader(header, "webhook-timestamp") if !ok { - return reject("webhook-timestamp header missing or repeated") + return xerrors.New("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") + return xerrors.New("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") + if age > tolerance || age < -tolerance { + return xerrors.New("webhook-timestamp outside the allowed window") } signatures := header.Values("webhook-signature") if len(signatures) == 0 { - return reject("webhook-signature header missing") + return xerrors.New("webhook-signature header missing") } mac := hmac.New(sha256.New, key) _, _ = mac.Write([]byte(id + "." + timestamp + ".")) @@ -80,39 +84,36 @@ func (v standardWebhooksVerifier) Verify(header http.Header, body []byte, secret } } } - return reject("no signature matches") + return xerrors.New("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) +// parseSecret returns the HMAC key inside a "whsec_" secret: standard base64 +// that decodes to at least one byte. The spec describes keys of 24 to 64 +// bytes, but no length is enforced: that would lock out a sender that +// deviates and only protects against the sender's own weak key. +func parseSecret(secret string) ([]byte, bool) { + encoded, ok := strings.CutPrefix(secret, secretPrefix) if !ok { - return nil, invalidSecret("secret has no whsec_ prefix") + return nil, false } // 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") + return nil, false } key, err := base64.StdEncoding.Strict().DecodeString(encoded) - if err != nil { - return nil, invalidSecret("secret is not base64") + if err != nil || len(key) == 0 { + return nil, false } - if len(key) == 0 { - return nil, invalidSecret("secret is empty") + return key, true +} + +// 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 key, nil + return values[0], true } diff --git a/coderd/x/chatd/chatwebhook/standardwebhooks_test.go b/coderd/x/chatd/chatwebhook/standardwebhooks_test.go index 822056fd94a..680243f9bea 100644 --- a/coderd/x/chatd/chatwebhook/standardwebhooks_test.go +++ b/coderd/x/chatd/chatwebhook/standardwebhooks_test.go @@ -1,6 +1,8 @@ package chatwebhook_test import ( + "crypto/hmac" + "crypto/sha256" "encoding/base64" "net/http" "strconv" @@ -13,7 +15,7 @@ import ( "github.com/coder/coder/v2/coderd/x/chatd/chatwebhook" ) -func TestStandardWebhooks(t *testing.T) { +func TestVerify(t *testing.T) { t.Parallel() // Official vector from @@ -27,6 +29,7 @@ func TestStandardWebhooks(t *testing.T) { vectorSig = "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=" ) vectorNow := time.Unix(1614265330, 0) + now := time.Date(2026, time.November, 11, 12, 0, 0, 0, time.UTC) key := []byte("0123456789abcdef0123456789abcdef") secret := "whsec_" + base64.StdEncoding.EncodeToString(key) @@ -37,34 +40,47 @@ func TestStandardWebhooks(t *testing.T) { ts := stamp(0) // sign signs the string "id.timestamp.body" with key, in the v1 format. sign := func(key []byte, id, ts string, body []byte) string { - return "v1," + base64.StdEncoding.EncodeToString(hmacSHA256(key, []byte(id+"."+ts+"."+string(body)))) + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(id + "." + ts + "." + string(body))) + return "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil)) } valid := sign(key, id, ts, body) + // header adds each name and value pair, so a repeated name makes several lines. + header := func(pairs ...string) http.Header { + h := http.Header{} + for i := 0; i < len(pairs); i += 2 { + h.Add(pairs[i], pairs[i+1]) + } + return h + } hdr := func(id, ts string, sigs ...string) http.Header { return header("webhook-id", id, "webhook-timestamp", ts, "webhook-signature", strings.Join(sigs, " ")) } // badSig has the shape of a v1 entry and the wrong MAC. badSig := sign([]byte("another key"), id, ts, body) - // at is a correctly signed request stamped d from now. - at := func(d time.Duration) verifyCase { - return verifyCase{header: hdr(id, stamp(d), sign(key, id, stamp(d), body)), body: body, secret: secret} + type verifyCase struct { + name string + header http.Header + body []byte + secret string + now time.Time // The zero value means now. + accepted bool } - boundary := func(name string, d time.Duration, accepted bool) verifyCase { - tc := at(d) - tc.name, tc.accepted = name, accepted - return tc + // at is a correctly signed request stamped d from now. + at := func(name string, d time.Duration, accepted bool) verifyCase { + return verifyCase{name: name, header: hdr(id, stamp(d), sign(key, id, stamp(d), body)), body: body, secret: secret, accepted: accepted} } - runVerifyCases(t, newVerifier(t, chatwebhook.SchemeStandardWebhooks), []verifyCase{ + for _, tc := range []verifyCase{ {name: "official vector", header: hdr(vectorID, vectorTS, vectorSig), body: []byte(vectorBody), secret: vectorSecret, now: vectorNow, accepted: true}, {name: "valid request", header: hdr(id, ts, valid), body: body, secret: secret, accepted: true}, // Timestamp window: "more than five minutes old" is rejected, and so // is a timestamp more than five minutes ahead. - boundary("timestamp five minutes old", -5*time.Minute, true), - boundary("timestamp five minutes ahead", 5*time.Minute, true), - boundary("timestamp one second more than five minutes old", -5*time.Minute-time.Second, false), - boundary("timestamp one second more than five minutes ahead", 5*time.Minute+time.Second, false), + at("timestamp five minutes old", -5*time.Minute, true), + at("timestamp five minutes ahead", 5*time.Minute, true), + at("timestamp one second more than five minutes old", -5*time.Minute-time.Second, false), + at("timestamp one second more than five minutes ahead", 5*time.Minute+time.Second, false), {name: "timestamp not a number", header: hdr(id, "now", sign(key, id, "now", body)), body: body, secret: secret}, // Headers. @@ -90,37 +106,29 @@ func TestStandardWebhooks(t *testing.T) { // Secrets. {name: "wrong secret", header: hdr(id, ts, valid), body: body, secret: "whsec_" + base64.StdEncoding.EncodeToString([]byte("another key"))}, {name: "signature made with an empty key", header: hdr(id, ts, sign(nil, id, ts, body)), body: body, secret: "whsec_"}, - }) -} - -func TestStandardWebhooksValidateSecret(t *testing.T) { - t.Parallel() - - v := newVerifier(t, chatwebhook.SchemeStandardWebhooks) - // Official secret, from - // https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/go/webhook_test.go - const official = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" - - for name, secret := range map[string]string{ - "official secret": official, - "one byte": "whsec_" + base64.StdEncoding.EncodeToString([]byte{1}), + {name: "secret without the whsec_ prefix", header: hdr(id, ts, valid), body: body, secret: strings.TrimPrefix(secret, "whsec_")}, + {name: "secret with a line break", header: hdr(id, ts, valid), body: body, secret: secret + "\n"}, + {name: "secret in the URL-safe base64 alphabet", header: hdr(id, ts, sign([]byte{0xfb, 0xff, 0xbf}, id, ts, body)), body: body, secret: "whsec_-_-_"}, } { - t.Run("valid "+name, func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { t.Parallel() - require.NoError(t, v.ValidateSecret(secret)) - }) - } - - for name, secret := range map[string]string{ - "prefix only": "whsec_", - "no prefix": strings.TrimPrefix(official, "whsec_"), - "base64 url alphabet": "whsec_" + base64.URLEncoding.EncodeToString([]byte{0xfb, 0xff, 0xbf}), - "base64 without padding": "whsec_" + base64.RawStdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef")), - "base64 with a newline": official + "\n", - } { - t.Run("invalid "+name, func(t *testing.T) { - t.Parallel() - require.ErrorIs(t, v.ValidateSecret(secret), chatwebhook.ErrInvalidSecret) + at := tc.now + if at.IsZero() { + at = now + } + err := chatwebhook.Verify(tc.header, tc.body, tc.secret, at) + if tc.accepted { + require.NoError(t, err) + return + } + require.Error(t, err) + // The error must not show the secret, a received signature or the + // expected one. + require.NotContains(t, err.Error(), tc.secret) + require.NotContains(t, err.Error(), strings.TrimPrefix(valid, "v1,")) + for _, sig := range tc.header.Values("webhook-signature") { + require.NotContains(t, err.Error(), sig) + } }) } }