-
Notifications
You must be signed in to change notification settings - Fork 1
/
receiver_test.go
85 lines (69 loc) · 1.87 KB
/
receiver_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package qstash
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
"os"
"strings"
"testing"
"time"
)
func sign(body string, key string) (string, error) {
// Compute SHA-256 hash
hash := sha256.New()
hash.Write([]byte(body))
bodyHash := hash.Sum(nil)
bodyHashBase64 := base64.URLEncoding.EncodeToString(bodyHash)
bodyHashBase64 = strings.Trim(bodyHashBase64, "=")
// Create JWT payload
now := time.Now().Unix()
payload := jwt.MapClaims{
"aud": "",
"body": bodyHashBase64,
"exp": now + 300,
"iat": now,
"iss": "Upstash",
"jti": fmt.Sprintf("%f", float64(now)), // Converting time to a string to mimic Python's time.time()
"nbf": now,
"sub": "https://example.com",
}
// Create JWT token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
token.Header["alg"] = "HS256"
token.Header["typ"] = "JWT"
// Sign the token
signature, err := token.SignedString([]byte(key))
if err != nil {
return "", err
}
return signature, nil
}
func TestVerify(t *testing.T) {
receiver := NewReceiverWithEnv()
body, err := json.Marshal(map[string]string{"hello": "world"})
assert.NoError(t, err)
signature, err := sign(string(body), os.Getenv(currentSigningKeyEnvProperty))
assert.NoError(t, err)
err = receiver.Verify(VerifyOptions{
Signature: signature,
Url: "https://example.com",
Body: string(body),
})
assert.NoError(t, err)
}
func TestFailedVerify(t *testing.T) {
receiver := NewReceiverWithEnv()
body, err := json.Marshal(map[string]string{"hello": "world"})
assert.NoError(t, err)
signature, err := sign(string(body), os.Getenv(currentSigningKeyEnvProperty))
assert.NoError(t, err)
err = receiver.Verify(VerifyOptions{
Signature: signature,
Url: "https://example.com/fail",
Body: string(body),
})
assert.Error(t, err)
}