Skip to content
42 changes: 42 additions & 0 deletions coderd/x/chatd/chatwebhook/bearer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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")
}
56 changes: 56 additions & 0 deletions coderd/x/chatd/chatwebhook/bearer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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},
{name: "scheme word in upper case", header: auth("BEARER " + secret), secret: secret, accepted: true},
{name: "body is not part of the check", header: auth("Bearer " + secret), body: []byte(`{"any":"thing"}`), 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: "three spaces before the token", header: auth("Bearer " + secret), secret: secret, accepted: true},
{name: "lower case scheme and two spaces", header: auth("bearer " + secret), secret: secret, accepted: true},
{name: "non-ASCII token equal to the secret", header: auth("Bearer tökén-✓"), secret: "tökén-✓", accepted: true},

{name: "header missing", header: http.Header{}, secret: secret},
{name: "header nil", header: nil, secret: secret},
{name: "empty header value", header: auth(""), secret: secret},
{name: "wrong scheme Basic", header: auth("Basic " + secret), secret: secret},
{name: "wrong scheme Token", header: auth("Token " + secret), secret: secret},
{name: "token without a scheme", header: auth(secret), secret: secret},
{name: "no space after the scheme", header: auth("Bearer" + secret), secret: secret},
{name: "scheme only", header: auth("Bearer"), secret: secret},
{name: "scheme and space only", header: auth("Bearer "), secret: secret},
{name: "two spaces before a wrong token", header: auth("Bearer not-the-secret"), secret: secret},
{name: "three spaces before a wrong token", header: auth("Bearer not-the-secret"), secret: secret},
{name: "two spaces before a token that is a strict prefix", header: auth("Bearer " + secret[:len(secret)-1]), secret: secret},
{name: "spaces only after the scheme", 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: "two spaces and a trailing space", header: auth("Bearer " + secret + " "), secret: secret},
{name: "trailing space after the token", header: auth("Bearer " + 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 first byte", header: auth("Bearer Q" + secret[1:]), secret: secret},
{name: "token differs in the last byte", header: auth("Bearer " + secret[:len(secret)-1] + "X"), secret: secret},
{name: "non-ASCII near miss", header: auth("Bearer tökén-✗"), secret: "tökén-✓"},
{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: ""},
})
}
113 changes: 113 additions & 0 deletions coderd/x/chatd/chatwebhook/chatwebhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// 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
}
Loading
Loading