interactions_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package discordgo
  2. import (
  3. "bytes"
  4. "crypto/ed25519"
  5. "encoding/hex"
  6. "net/http/httptest"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "time"
  11. )
  12. func TestVerifyInteraction(t *testing.T) {
  13. pubkey, privkey, err := ed25519.GenerateKey(nil)
  14. if err != nil {
  15. t.Errorf("error generating signing keypair: %s", err)
  16. }
  17. timestamp := "1608597133"
  18. t.Run("success", func(t *testing.T) {
  19. body := "body"
  20. request := httptest.NewRequest("POST", "http://localhost/interaction", strings.NewReader(body))
  21. request.Header.Set("X-Signature-Timestamp", timestamp)
  22. var msg bytes.Buffer
  23. msg.WriteString(timestamp)
  24. msg.WriteString(body)
  25. signature := ed25519.Sign(privkey, msg.Bytes())
  26. request.Header.Set("X-Signature-Ed25519", hex.EncodeToString(signature[:ed25519.SignatureSize]))
  27. if !VerifyInteraction(request, pubkey) {
  28. t.Error("expected true, got false")
  29. }
  30. })
  31. t.Run("failure/modified body", func(t *testing.T) {
  32. body := "body"
  33. request := httptest.NewRequest("POST", "http://localhost/interaction", strings.NewReader("WRONG"))
  34. request.Header.Set("X-Signature-Timestamp", timestamp)
  35. var msg bytes.Buffer
  36. msg.WriteString(timestamp)
  37. msg.WriteString(body)
  38. signature := ed25519.Sign(privkey, msg.Bytes())
  39. request.Header.Set("X-Signature-Ed25519", hex.EncodeToString(signature[:ed25519.SignatureSize]))
  40. if VerifyInteraction(request, pubkey) {
  41. t.Error("expected false, got true")
  42. }
  43. })
  44. t.Run("failure/modified timestamp", func(t *testing.T) {
  45. body := "body"
  46. request := httptest.NewRequest("POST", "http://localhost/interaction", strings.NewReader("WRONG"))
  47. request.Header.Set("X-Signature-Timestamp", strconv.FormatInt(time.Now().Add(time.Minute).Unix(), 10))
  48. var msg bytes.Buffer
  49. msg.WriteString(timestamp)
  50. msg.WriteString(body)
  51. signature := ed25519.Sign(privkey, msg.Bytes())
  52. request.Header.Set("X-Signature-Ed25519", hex.EncodeToString(signature[:ed25519.SignatureSize]))
  53. if VerifyInteraction(request, pubkey) {
  54. t.Error("expected false, got true")
  55. }
  56. })
  57. }