60 lines
1.8 KiB
Go
60 lines
1.8 KiB
Go
package v1
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
twitterchannel "github.com/gochat/gochat/internal/channel/twitter"
|
|
)
|
|
|
|
func TestTwitterWebhookCRCUsesConfiguredSecret(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
t.Setenv("TWITTER_CRC_SECRET", "crc-secret")
|
|
provider := twitterchannel.NewTwitterProvider(twitterchannel.TwitterOAuth2Config{})
|
|
h := NewTwitterChannelHandler(nil, provider, nil, nil)
|
|
r := gin.New()
|
|
r.GET("/webhooks/twitter", h.WebhookCRC)
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/webhooks/twitter?crc_token=crc-token", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
mac := hmac.New(sha256.New, []byte("crc-secret"))
|
|
mac.Write([]byte("crc-token"))
|
|
expected := "sha256=" + base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
|
var payload map[string]string
|
|
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
|
|
t.Fatalf("decode crc response: %v", err)
|
|
}
|
|
if payload["response_token"] != expected {
|
|
t.Fatalf("unexpected response token: %q", payload["response_token"])
|
|
}
|
|
}
|
|
|
|
func TestTwitterWebhookEventAcknowledgesPayload(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
provider := twitterchannel.NewTwitterProvider(twitterchannel.TwitterOAuth2Config{})
|
|
h := NewTwitterChannelHandler(nil, provider, nil, nil)
|
|
r := gin.New()
|
|
r.POST("/webhooks/twitter", h.WebhookEvent)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/webhooks/twitter", bytes.NewReader([]byte(`{"direct_message_events":[]}`)))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
}
|