-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth_test.go
More file actions
73 lines (58 loc) · 1.81 KB
/
auth_test.go
File metadata and controls
73 lines (58 loc) · 1.81 KB
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
package main
import (
"encoding/hex"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
)
func TestAddAuth_AllowsHS256AndHS384(t *testing.T) {
// 128-byte key hex encoded (256 chars)
secretHex := strings.Repeat("a", 256)
t.Setenv("DRAND_AUTH_KEY", secretHex)
secret, err := hex.DecodeString(secretHex)
require.NoError(t, err)
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
protected := AddAuth(next)
for _, tc := range []struct {
name string
method jwt.SigningMethod
}{
{name: "hs256", method: jwt.SigningMethodHS256},
{name: "hs384", method: jwt.SigningMethodHS384},
} {
t.Run(tc.name, func(t *testing.T) {
token := jwt.New(tc.method)
signed, err := token.SignedString(secret)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodGet, "/v2/chains", nil)
r.Header.Set("Authorization", "Bearer "+signed)
w := httptest.NewRecorder()
protected.ServeHTTP(w, r)
require.Equal(t, http.StatusOK, w.Code)
})
}
}
func TestAddAuth_RejectsHS512(t *testing.T) {
// Ensure the env var is present to avoid log.Fatal in AddAuth initialization.
secretHex := strings.Repeat("b", 256)
t.Setenv("DRAND_AUTH_KEY", secretHex)
secret, err := hex.DecodeString(secretHex)
require.NoError(t, err)
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
protected := AddAuth(next)
token := jwt.New(jwt.SigningMethodHS512)
signed, err := token.SignedString(secret)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodGet, "/v2/chains", nil)
r.Header.Set("Authorization", "Bearer "+signed)
w := httptest.NewRecorder()
protected.ServeHTTP(w, r)
require.Equal(t, http.StatusUnauthorized, w.Code)
}