-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage_test.go
More file actions
253 lines (225 loc) · 8.16 KB
/
coverage_test.go
File metadata and controls
253 lines (225 loc) · 8.16 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package crypto
// Internal tests that exercise hard-to-reach branches via package-private
// affordances (swappable random sources). Kept in `package crypto` rather
// than `crypto_test` so the rand-reader vars can be mocked without exporting
// them to the public API.
import (
"errors"
"io"
"strings"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
)
// errReader always fails — used to drive the io.ReadFull error paths in
// Encrypt and GenerateAPIKey.
type errReader struct{ err error }
func (r errReader) Read(_ []byte) (int, error) { return 0, r.err }
func TestEncrypt_NonceReadFails(t *testing.T) {
// Swap the package-level rand source for one that always errors.
orig := randReader
defer func() { randReader = orig }()
sentinel := errors.New("rand-source dead")
randReader = errReader{err: sentinel}
key, err := ParseAESKey("0000000000000000000000000000000000000000000000000000000000000000")
if err != nil {
t.Fatalf("ParseAESKey: %v", err)
}
_, err = Encrypt(key, "plaintext")
if err == nil {
t.Fatal("expected error when nonce read fails")
}
if !errors.Is(err, sentinel) {
t.Errorf("expected wrapped sentinel error, got %v", err)
}
var ee *ErrEncrypt
if !errors.As(err, &ee) {
t.Errorf("expected *ErrEncrypt, got %T", err)
}
}
func TestGenerateAPIKey_RandReadFails(t *testing.T) {
orig := tokenRandReader
defer func() { tokenRandReader = orig }()
sentinel := errors.New("rng failure")
tokenRandReader = errReader{err: sentinel}
_, err := GenerateAPIKey()
if err == nil {
t.Fatal("expected error when rand.Read fails")
}
if !errors.Is(err, sentinel) {
t.Errorf("expected wrapped sentinel error, got %v", err)
}
var te *ErrTokenGenerate
if !errors.As(err, &te) {
t.Errorf("expected *ErrTokenGenerate, got %T", err)
}
// Error message should mention the underlying cause.
if !strings.Contains(err.Error(), "rng failure") {
t.Errorf("expected error to mention cause, got %q", err.Error())
}
}
// Sanity: the default randReader/tokenRandReader are non-nil. Documents
// invariant relied on by the production path.
func TestDefaultRandReaders_NonNil(t *testing.T) {
if randReader == nil {
t.Error("randReader is nil")
}
if tokenRandReader == nil {
t.Error("tokenRandReader is nil")
}
}
// shortReader returns fewer bytes than requested, then io.EOF — exercises the
// io.ReadFull short-read path (distinct from outright error).
type shortReader struct {
calls int
}
func (r *shortReader) Read(p []byte) (int, error) {
r.calls++
if len(p) == 0 {
return 0, nil
}
// Fill 1 byte then signal EOF — io.ReadFull turns this into
// io.ErrUnexpectedEOF.
p[0] = 0xaa
return 1, io.EOF
}
func TestGenerateAPIKey_ShortRead(t *testing.T) {
orig := tokenRandReader
defer func() { tokenRandReader = orig }()
tokenRandReader = &shortReader{}
_, err := GenerateAPIKey()
if err == nil {
t.Fatal("expected error from short rand read")
}
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Errorf("expected ErrUnexpectedEOF, got %v", err)
}
}
func TestEncrypt_ShortNonceRead(t *testing.T) {
orig := randReader
defer func() { randReader = orig }()
randReader = &shortReader{}
key, _ := ParseAESKey("0000000000000000000000000000000000000000000000000000000000000000")
_, err := Encrypt(key, "x")
if err == nil {
t.Fatal("expected error from short nonce read")
}
}
// TestVerifyOnboardingJWT_WrongAlg exercises the keyfunc alg-confusion guard
// in VerifyOnboardingJWT (mirrors TestVerifyJWT_WrongAlg in the external test
// file). A token claiming alg=RS256 must be rejected because the keyfunc only
// returns the HMAC key.
func TestVerifyOnboardingJWT_WrongAlg(t *testing.T) {
bad := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcCI6ImEifQ.sig"
_, err := VerifyOnboardingJWT([]byte("secret"), bad)
if err == nil {
t.Fatal("expected error for non-HMAC alg")
}
var ve *ErrJWTVerify
if !errors.As(err, &ve) {
t.Errorf("expected *ErrJWTVerify, got %T", err)
}
}
// failingSigningMethod is a jwt.SigningMethod whose Sign always errors —
// used to exercise the SignedString error path in SignJWT and
// SignOnboardingJWT.
type failingSigningMethod struct{ err error }
func (m *failingSigningMethod) Alg() string { return "FAIL" }
func (m *failingSigningMethod) Sign(_ string, _ interface{}) (string, error) {
return "", m.err
}
func (m *failingSigningMethod) Verify(_, _ string, _ interface{}) error { return m.err }
func TestSignJWT_SignedStringFails(t *testing.T) {
orig := jwtSigningMethod
defer func() { jwtSigningMethod = orig }()
sentinel := errors.New("signing dead")
jwtSigningMethod = &failingSigningMethod{err: sentinel}
_, err := SignJWT([]byte("secret"), InstantClaims{Fingerprint: "x"})
if err == nil {
t.Fatal("expected error when signing fails")
}
if !errors.Is(err, sentinel) {
t.Errorf("expected wrapped sentinel, got %v", err)
}
var se *ErrJWTSign
if !errors.As(err, &se) {
t.Errorf("expected *ErrJWTSign, got %T", err)
}
}
// TestVerifyJWT_FutureIssuedAt_OurCheck drives the second-line-of-defense iat
// check inside VerifyJWT (lines after the library's err path). jwt/v4's
// RegisteredClaims.Valid uses jwt.TimeFunc — by setting TimeFunc to a moment
// in the future, the library's parse passes; our own time.Now().UTC()
// comparison then catches the future-iat and returns ValidationErrorIssuedAt.
// Guards against jwt/v4 upstream silently dropping the iat check.
func TestVerifyJWT_FutureIssuedAt_OurCheck(t *testing.T) {
origTimeFunc := jwt.TimeFunc
defer func() { jwt.TimeFunc = origTimeFunc }()
// Pretend "now" inside the library is 1 day from now — so future-iat
// tokens validate at the library layer but our code still flags them.
jwt.TimeFunc = func() time.Time { return time.Now().UTC().Add(24 * time.Hour) }
claims := InstantClaims{Fingerprint: "fp"}
claims.IssuedAt = jwt.NewNumericDate(time.Now().UTC().Add(30 * time.Minute))
claims.ExpiresAt = jwt.NewNumericDate(time.Now().UTC().Add(48 * time.Hour))
signed, err := SignJWT([]byte("sec"), claims)
if err != nil {
t.Fatalf("SignJWT: %v", err)
}
_, err = VerifyJWT([]byte("sec"), signed)
if err == nil {
t.Fatal("expected our iat-future check to flag the token")
}
var ve *jwt.ValidationError
if !errors.As(err, &ve) {
t.Errorf("expected *jwt.ValidationError, got %T", err)
} else if ve.Errors&jwt.ValidationErrorIssuedAt == 0 {
t.Errorf("expected ValidationErrorIssuedAt flag, got %d", ve.Errors)
}
}
// TestVerifyOnboardingJWT_FutureIssuedAt_OurCheck — sibling of the InstantClaims
// test above. SignOnboardingJWT stamps iat from real time.Now(), so we must
// hand-craft a token with a future iat and verify it under a library TimeFunc
// that lets the iat-check pass at the library layer.
func TestVerifyOnboardingJWT_FutureIssuedAt_OurCheck(t *testing.T) {
origTimeFunc := jwt.TimeFunc
defer func() { jwt.TimeFunc = origTimeFunc }()
jwt.TimeFunc = func() time.Time { return time.Now().UTC().Add(24 * time.Hour) }
claims := OnboardingClaims{Fingerprint: "fp"}
claims.RegisteredClaims = jwt.RegisteredClaims{
ID: "test-jti",
IssuedAt: jwt.NewNumericDate(time.Now().UTC().Add(30 * time.Minute)),
ExpiresAt: jwt.NewNumericDate(time.Now().UTC().Add(72 * time.Hour)),
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := tok.SignedString([]byte("sec"))
if err != nil {
t.Fatalf("manual sign: %v", err)
}
_, err = VerifyOnboardingJWT([]byte("sec"), signed)
if err == nil {
t.Fatal("expected our iat-future check to flag the token")
}
var ve *jwt.ValidationError
if !errors.As(err, &ve) {
t.Errorf("expected *jwt.ValidationError, got %T", err)
} else if ve.Errors&jwt.ValidationErrorIssuedAt == 0 {
t.Errorf("expected ValidationErrorIssuedAt flag, got %d", ve.Errors)
}
}
func TestSignOnboardingJWT_SignedStringFails(t *testing.T) {
orig := jwtSigningMethod
defer func() { jwtSigningMethod = orig }()
sentinel := errors.New("onboarding signing dead")
jwtSigningMethod = &failingSigningMethod{err: sentinel}
_, _, err := SignOnboardingJWT([]byte("secret"), OnboardingClaims{Fingerprint: "x"})
if err == nil {
t.Fatal("expected error when signing fails")
}
if !errors.Is(err, sentinel) {
t.Errorf("expected wrapped sentinel, got %v", err)
}
var se *ErrJWTSign
if !errors.As(err, &se) {
t.Errorf("expected *ErrJWTSign, got %T", err)
}
}