Skip to content

Commit

Permalink
Resolve data race in JWT validator test
Browse files Browse the repository at this point in the history
  • Loading branch information
kasugamirai committed Oct 3, 2024
1 parent 583aa90 commit 373ec89
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion appx/jwt_validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/rsa"
"encoding/json"
"net/http"
"sync"
"testing"
"time"

Expand All @@ -23,7 +24,10 @@ func TestMultiValidator(t *testing.T) {
key := lo.Must(rsa.GenerateKey(rand.Reader, 2048))

httpmock.Activate()
defer httpmock.DeactivateAndReset()
t.Cleanup(func() {
httpmock.DeactivateAndReset()
})

httpmock.RegisterResponder(
http.MethodGet,
"https://example.com/.well-known/openid-configuration",
Expand Down Expand Up @@ -207,4 +211,42 @@ func TestMultiValidator(t *testing.T) {
assert.Nil(t, res)
assert.ErrorIs(t, err, context.Canceled)
})

t.Run("mixed valid and invalid tokens", func(t *testing.T) {
v, err := NewJWTMultipleValidator([]JWTProvider{
{ISS: "https://example.com/", AUD: []string{"a", "b"}, ALG: &jwt.SigningMethodRS256.Name},
{ISS: "https://example2.com/", AUD: []string{"c"}, ALG: &jwt.SigningMethodRS256.Name},
})
assert.NoError(t, err)

// Test with valid token
res, err := v.ValidateToken(context.Background(), tokenString)
assert.NoError(t, err)
assert.NotNil(t, res)

// Test with invalid token
res, err = v.ValidateToken(context.Background(), "invalid.token")
assert.Error(t, err)
assert.Nil(t, res)
})

t.Run("concurrent validations", func(t *testing.T) {
v, err := NewJWTMultipleValidator([]JWTProvider{
{ISS: "https://example.com/", AUD: []string{"a", "b"}, ALG: &jwt.SigningMethodRS256.Name},
{ISS: "https://example2.com/", AUD: []string{"c"}, ALG: &jwt.SigningMethodRS256.Name},
})
assert.NoError(t, err)

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
res, err := v.ValidateToken(context.Background(), tokenString)
assert.NoError(t, err)
assert.NotNil(t, res)
}()
}
wg.Wait()
})
}

0 comments on commit 373ec89

Please sign in to comment.