Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for validating webhooks #40

Merged
merged 2 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1600,3 +1601,55 @@ func TestGetCurrentAccount(t *testing.T) {
assert.Equal(t, "Replicate", account.Name)
assert.Equal(t, "https://github.com/replicate", account.GithubURL)
}

func TestGetDefaultWebhookSecret(t *testing.T) {
// This is a test secret and should not be used in production
testSecret := replicate.WebhookSigningSecret{
Key: "whsec_5WbX5kEWLlfzsGNjH64I8lOOqUB6e8FH", // nolint:gosec
}

mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/webhooks/default/secret", r.URL.Path)
assert.Equal(t, http.MethodGet, r.Method)

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
body, _ := json.Marshal(testSecret)
w.Write(body)
}))
defer mockServer.Close()

client, err := replicate.NewClient(
replicate.WithToken("test-token"),
replicate.WithBaseURL(mockServer.URL),
)
require.NotNil(t, client)
require.NoError(t, err)

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

secret, err := client.GetDefaultWebhookSecret(ctx)
assert.NoError(t, err)
assert.Equal(t, testSecret.Key, secret.Key)
}

func TestValidateWebhook(t *testing.T) {
// Test case from https://github.com/svix/svix-webhooks/blob/b41728cd98a7e7004a6407a623f43977b82fcba4/javascript/src/webhook.test.ts#L190-L200

// This is a test secret and should not be used in production
testSecret := replicate.WebhookSigningSecret{
Key: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw", // nolint:gosec
}

body := `{"test": 2432232314}`
req := httptest.NewRequest(http.MethodPost, "http://test.host/webhook", strings.NewReader(body))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Webhook-ID", "msg_p5jXN8AQM9LWM0D4loKWxJek")
req.Header.Add("Webhook-Timestamp", "1614265330")
req.Header.Add("Webhook-Signature", "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=")

isValid, err := replicate.ValidateWebhookRequest(req, testSecret)
require.NoError(t, err)
assert.True(t, isValid)
}
75 changes: 75 additions & 0 deletions webhook.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
package replicate

import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"net/http"
"strings"
)

type Webhook struct {
URL string
Events []WebhookEventType
Expand All @@ -24,3 +35,67 @@ var WebhookEventAll = []WebhookEventType{
func (w WebhookEventType) String() string {
return string(w)
}

type WebhookSigningSecret struct {
Key string `json:"key"`
}

// GetDefaultWebhookSecret gets the default webhook signing secret
func (r *Client) GetDefaultWebhookSecret(ctx context.Context) (*WebhookSigningSecret, error) {
secret := &WebhookSigningSecret{}
err := r.fetch(ctx, http.MethodGet, "/webhooks/default/secret", nil, secret)
if err != nil {
return nil, fmt.Errorf("failed to get default webhook signing secret")
}

return secret, nil
}

// ValidateWebhookRequest validates the signature from an incoming webhook request using the provided secret
func ValidateWebhookRequest(req *http.Request, secret WebhookSigningSecret) (bool, error) {
id := req.Header.Get("webhook-id")
timestamp := req.Header.Get("webhook-timestamp")
signature := req.Header.Get("webhook-signature")
if id == "" || timestamp == "" || signature == "" {
return false, fmt.Errorf("missing required webhook headers: id=%s, timestamp=%s, signature=%s", id, timestamp, signature)
}

bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return false, fmt.Errorf("failed to read request body: %w", err)
}
body := string(bodyBytes)

signedContent := fmt.Sprintf("%s.%s.%s", id, timestamp, body)

keyParts := strings.Split(secret.Key, "_")
if len(keyParts) != 2 {
return false, fmt.Errorf("invalid secret key format: %s", secret.Key)
}
secretBytes, err := base64.StdEncoding.DecodeString(keyParts[1])
if err != nil {
return false, fmt.Errorf("failed to base64 decode secret key: %w", err)
}

h := hmac.New(sha256.New, secretBytes)
h.Write([]byte(signedContent))
computedSignatureBytes := h.Sum(nil)

for _, sig := range strings.Split(signature, " ") {
sigParts := strings.Split(sig, ",")
if len(sigParts) < 2 {
return false, fmt.Errorf("invalid signature format: %s", sig)
}

sigBytes, err := base64.StdEncoding.DecodeString(sigParts[1])
if err != nil {
return false, fmt.Errorf("failed to base64 decode signature: %w", err)
}

if hmac.Equal(sigBytes, computedSignatureBytes) {
return true, nil
}
}

return false, nil
}
Loading