github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/interactions_test.go (about)

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