Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve concurrency #134

Merged
merged 1 commit into from
Jan 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

.PHONY: test
test: ## Run tests.
go test -cover -covermode=atomic -coverprofile=coverage.out ./...
go test -race -cover -covermode=atomic -coverprofile=coverage.out ./...

.PHONY: lint
lint: ## Run golangci-lint.
Expand Down
4 changes: 3 additions & 1 deletion examples/http-example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ func main() {

// We want this struct to be filled in with
// our custom claims from the token.
customClaims := &CustomClaimsExample{}
customClaims := func() validator.CustomClaims {
return &CustomClaimsExample{}
}

// Set up the validator.
jwtValidator, err := validator.New(
Expand Down
4 changes: 4 additions & 0 deletions extractor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ func Test_AuthHeaderTokenExtractor(t *testing.T) {

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()

gotToken, err := AuthHeaderTokenExtractor(testCase.request)
if testCase.wantError != "" {
assert.EqualError(t, err, testCase.wantError)
Expand Down Expand Up @@ -96,6 +98,8 @@ func Test_CookieTokenExtractor(t *testing.T) {

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()

request, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
require.NoError(t, err)

Expand Down
11 changes: 8 additions & 3 deletions middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func Test_CheckJWT(t *testing.T) {
name: "it can successfully validate a token",
validateToken: jwtValidator.ValidateToken,
token: validToken,
method: http.MethodGet,
wantToken: tokenClaims,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
Expand All @@ -67,19 +68,22 @@ func Test_CheckJWT(t *testing.T) {
{
name: "it fails to validate a token with a bad format",
token: "bad",
method: http.MethodGet,
wantStatusCode: http.StatusInternalServerError,
wantBody: `{"message":"Something went wrong while checking the JWT."}`,
},
{
name: "it fails to validate if token is missing and credentials are not optional",
token: "",
method: http.MethodGet,
wantStatusCode: http.StatusBadRequest,
wantBody: `{"message":"JWT is missing."}`,
},
{
name: "it fails to validate an invalid token",
validateToken: jwtValidator.ValidateToken,
token: invalidToken,
method: http.MethodGet,
wantStatusCode: http.StatusUnauthorized,
wantBody: `{"message":"JWT is invalid."}`,
},
Expand All @@ -100,6 +104,7 @@ func Test_CheckJWT(t *testing.T) {
return "", errors.New("token extractor error")
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusInternalServerError,
wantBody: `{"message":"Something went wrong while checking the JWT."}`,
},
Expand All @@ -111,6 +116,7 @@ func Test_CheckJWT(t *testing.T) {
return "", nil
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
Expand All @@ -123,16 +129,15 @@ func Test_CheckJWT(t *testing.T) {
return "", nil
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusBadRequest,
wantBody: `{"message":"JWT is missing."}`,
},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
if testCase.method == "" {
testCase.method = http.MethodGet
}
t.Parallel()

middleware := New(testCase.validateToken, testCase.options...)

Expand Down
4 changes: 2 additions & 2 deletions validator/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ func WithAllowedClockSkew(skew time.Duration) Option {
// CustomClaims that will be unmarshalled into and on which
// Validate is called on for custom validation. If this option
// is not used the Validator will do nothing for custom claims.
func WithCustomClaims(c CustomClaims) Option {
func WithCustomClaims(f func() CustomClaims) Option {
return func(v *Validator) {
v.customClaims = c
v.customClaims = f
}
}
9 changes: 5 additions & 4 deletions validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type Validator struct {
keyFunc func(context.Context) (interface{}, error) // Required.
signatureAlgorithm SignatureAlgorithm // Required.
expectedClaims jwt.Expected // Internal.
customClaims CustomClaims // Optional.
customClaims func() CustomClaims // Optional.
allowedClockSkew time.Duration // Optional.
}

Expand Down Expand Up @@ -114,16 +114,17 @@ func (v *Validator) ValidateToken(ctx context.Context, tokenString string) (inte

claimDest := []interface{}{&jwt.Claims{}}
if v.customClaims != nil {
claimDest = append(claimDest, v.customClaims)
claimDest = append(claimDest, v.customClaims())
}

if err = token.Claims(key, claimDest...); err != nil {
return nil, fmt.Errorf("could not get token claims: %w", err)
}

registeredClaims := *claimDest[0].(*jwt.Claims)
v.expectedClaims.Time = time.Now()
if err = registeredClaims.ValidateWithLeeway(v.expectedClaims, v.allowedClockSkew); err != nil {
expectedClaims := v.expectedClaims
expectedClaims.Time = time.Now()
if err = registeredClaims.ValidateWithLeeway(expectedClaims, v.allowedClockSkew); err != nil {
return nil, fmt.Errorf("expected claims not validated: %w", err)
}

Expand Down
23 changes: 16 additions & 7 deletions validator/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestValidator_ValidateToken(t *testing.T) {
token string
keyFunc func(context.Context) (interface{}, error)
algorithm SignatureAlgorithm
customClaims CustomClaims
customClaims func() CustomClaims
expectedError error
expectedClaims *ValidatedClaims
}{
Expand All @@ -40,6 +40,7 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
algorithm: HS256,
expectedClaims: &ValidatedClaims{
RegisteredClaims: RegisteredClaims{
Issuer: issuer,
Expand All @@ -54,7 +55,10 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
customClaims: &testClaims{},
algorithm: HS256,
customClaims: func() CustomClaims {
return &testClaims{}
},
expectedClaims: &ValidatedClaims{
RegisteredClaims: RegisteredClaims{
Issuer: issuer,
Expand All @@ -81,6 +85,7 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
algorithm: HS256,
expectedError: errors.New("could not parse the token: square/go-jose: compact JWS format must have three parts"),
},
{
Expand All @@ -89,6 +94,7 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return nil, errors.New("key func error message")
},
algorithm: HS256,
expectedError: errors.New("error getting the keys from the key func: key func error message"),
},
{
Expand All @@ -97,6 +103,7 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
algorithm: HS256,
expectedError: errors.New("could not get token claims: square/go-jose: error in cryptographic primitive"),
},
{
Expand All @@ -105,6 +112,7 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
algorithm: HS256,
expectedError: errors.New("expected claims not validated: square/go-jose/jwt: validation failed, invalid audience claim (aud)"),
},
{
Expand All @@ -113,18 +121,19 @@ func TestValidator_ValidateToken(t *testing.T) {
keyFunc: func(context.Context) (interface{}, error) {
return []byte("secret"), nil
},
customClaims: &testClaims{
ReturnError: errors.New("custom claims error message"),
algorithm: HS256,
customClaims: func() CustomClaims {
return &testClaims{
ReturnError: errors.New("custom claims error message"),
}
},
expectedError: errors.New("custom claims not validated: custom claims error message"),
},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
if testCase.algorithm == "" {
testCase.algorithm = HS256
}
t.Parallel()

validator, err := New(
testCase.keyFunc,
Expand Down