Files
Ethan 166b9d25e3 test(coderd): remove low-value cron and chatwebhook tests (#32164)
The tests from #32063 and #32062 are two to three times the size of the
code they cover, and a lot of them can't fail for a reason we'd care
about. This PR removes those, with no production changes.

In `coderd/schedule/cron`, two tests rebuilt the schedule rule a second
time to compare against, which was also the only use of
`export_test.go`, so that goes too. Most of the rest, in both packages,
are table rows that take the same branch as a row that stays. I also
dropped a copy of the webhook scheme list and a repeated-request test
that belongs at the route.

What's left is a row per reject branch, the RFC cases, the regression
test for the `Next` hang and the constant-time scan. I replayed each fix
commit from the two PRs against the smaller suite, and the pre-fix code
still fails a test for every one, other than a fix to the wording of a
zone error.

One row that stays is changed: the bearer wrong-scheme case used
`Basic`, which was only rejected because of where its space lands, so
nothing covered the scheme word. It's now `Digest`.

#32162 overlaps with this in `cron`. With the shim's users gone it no
longer needs to touch that package, so it's now stacked on top of this
PR.
2026-11-18 14:14:26 +11:00

246 lines
7.7 KiB
Go

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)
}
})
}