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

Added fuzzers in utils and authorization(graphql) #4467

Merged
merged 12 commits into from
Mar 14, 2024
1 change: 1 addition & 0 deletions chaoscenter/graphql/server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.20

require (
github.com/99designs/gqlgen v0.17.42
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24
github.com/argoproj/argo-workflows/v3 v3.3.1
github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32
github.com/gin-contrib/cors v1.3.1
Expand Down
2 changes: 2 additions & 0 deletions chaoscenter/graphql/server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/99designs/gqlgen v0.17.42 h1:BVWDOb2VVHQC5k3m6oa0XhDnxltLLrU4so7x/u39Zu4=
github.com/99designs/gqlgen v0.17.42/go.mod h1:GQ6SyMhwFbgHR0a8r2Wn8fYgEwPxxmndLFPhU63+cJE=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/azure-sdk-for-go v32.5.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/azure-sdk-for-go v35.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/azure-sdk-for-go v43.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
Expand Down
130 changes: 130 additions & 0 deletions chaoscenter/graphql/server/pkg/authorization/tests/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package tests
imrajdas marked this conversation as resolved.
Show resolved Hide resolved

import (
"fmt"
"testing"
"time"

fuzz "github.com/AdaLogics/go-fuzz-headers"
"github.com/golang-jwt/jwt"
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/authorization"
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/utils"
)

// generateExpiredFakeJWTToken generates a fake JWT token with expiration time set to the past
func generateExpiredFakeJWTToken(username string) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["username"] = username
claims["exp"] = time.Now().Add(-time.Hour).Unix() // Set expiration time to 1 hour ago
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see the time package being used in many functions, better to define the variable at a single place and pass it as function argument.

signedToken, _ := token.SignedString([]byte("your-secret-key")) // Sign the token with a secret key
return signedToken
}

// generateFakeJWTTokenWithInvalidSignature generates a fake JWT token with an invalid signature
func generateFakeJWTTokenWithInvalidSignature(username string) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["username"] = username
claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Set expiration time to 24 hours from now
signedToken, _ := token.SignedString([]byte("invalid-secret-key")) // Sign the token with an invalid secret key
return signedToken
}

// generateFakeJWTToken generates a fake JWT token with predefined claims
func generateFakeJWTToken(username string) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"username": username,
"exp": time.Now().Add(time.Hour * 24).Unix(), // Set expiration time to 24 hours from now
})

signedToken, _ := token.SignedString([]byte(utils.Config.JwtSecret)) // No signature is needed for testing
return signedToken
}

func FuzzGetUsername(f *testing.F) {
f.Fuzz(func(t *testing.T, input string) {
// Create a fake JWT token with predefined claims

// Invalid token format check
_, err := authorization.GetUsername(input)
if err == nil {
t.Error("Expected error for invalid token format")
}

// Generating fake jwt token for testing
token := generateFakeJWTToken(input)

// Run the test with the fake JWT token
username, err := authorization.GetUsername(token)
if err != nil {
t.Errorf("Error encountered: %v", err)
}

// Check if the decoded username matches the input string
if username != input {
t.Errorf("Expected username: %s, got: %s", input, username)
}

// Additional checks
// Expiration check
expiredToken := generateExpiredFakeJWTToken(input)
_, err = authorization.GetUsername(expiredToken)
if err == nil {
t.Error("Expected error for expired token")
}

// Token signature check (invalid secret key)
invalidSignatureToken := generateFakeJWTTokenWithInvalidSignature(input)
_, err = authorization.GetUsername(invalidSignatureToken)
if err == nil {
t.Error("Expected error for token with invalid signature")
}

})
}

// generateJWTToken generates a JWT token with the given claims
func generateJWTTokenFromClaims(claims jwt.MapClaims) (string, error) {
// Set expiration time to 24 hours from now
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

// Create a new token with the claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

// Sign the token with a secret key
tokenString, err := token.SignedString([]byte(utils.Config.JwtSecret))
if err != nil {
return "", fmt.Errorf("failed to sign JWT token: %v", err)
}

return tokenString, nil
}

func FuzzUserValidateJWT(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte) {
fuzzConsumer := fuzz.NewConsumer(data)
inputClaims := &jwt.MapClaims{}
err := fuzzConsumer.GenerateStruct(inputClaims)
if err != nil {
return
}
// Generate a JWT token with fuzzed claims
tokenString, err := generateJWTTokenFromClaims(*inputClaims)
if err != nil {
t.Fatalf("Error generating JWT token: %v", err)
}

// Run the test with the generated JWT token
claims, err := authorization.UserValidateJWT(tokenString)
if err != nil {
t.Errorf("Error encountered: %v", err)
}

// Optionally, check if claims are nil when there's an error
if claims == nil && err == nil {
SarthakJain26 marked this conversation as resolved.
Show resolved Hide resolved
t.Errorf("Claims are nil while no error is returned")
}

})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
string("0")
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
string("\x88")
25 changes: 3 additions & 22 deletions chaoscenter/graphql/server/pkg/authorization/user_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,19 @@ func UserValidateJWT(token string) (jwt.MapClaims, error) {

if err != nil {
log.Print("USER JWT ERROR: ", err)
return nil, errors.New("Invalid Token")
return nil, errors.New("invalid Token")
}

if !tkn.Valid {
return nil, errors.New("Invalid Token")
return nil, errors.New("invalid Token")
}

claims, ok := tkn.Claims.(jwt.MapClaims)
if ok {
return claims, nil
}

return nil, errors.New("Invalid Token")
return nil, errors.New("invalid Token")
}

// GetUsername returns the username from the jwt token
Expand All @@ -54,22 +54,3 @@ func GetUsername(token string) (string, error) {

return "", errors.New("invalid Token")
}

// GetUserID returns the GetUserID from the jwt token
func GetUserID(token string) (string, error) {
tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(utils.Config.JwtSecret), nil
})

if err != nil {
log.Print("USER JWT ERROR: ", err)
return "", errors.New("invalid Token")
}

claims, ok := tkn.Claims.(jwt.MapClaims)
if ok {
return claims["uid"].(string), nil
}

return "", errors.New("invalid Token")
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package handler
package test

namkyu1999 marked this conversation as resolved.
Show resolved Hide resolved
import (
"context"
"errors"
"testing"
"time"

"github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/environment/handler"

"github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb"
"go.mongodb.org/mongo-driver/mongo"

Expand Down Expand Up @@ -99,7 +101,7 @@ func TestCreateEnvironment(t *testing.T) {
token := tc.given()
ctx := context.WithValue(context.Background(), authorization.AuthKey, token)
mockOperator := environmentOperator
service := NewEnvironmentService(mockOperator)
service := handler.NewEnvironmentService(mockOperator)

env, err := service.CreateEnvironment(ctx, tc.projectID, tc.input)
if (err != nil && tc.expectedErr == nil) ||
Expand Down Expand Up @@ -176,7 +178,7 @@ func TestDeleteEnvironment(t *testing.T) {
ctx := context.WithValue(context.Background(), authorization.AuthKey, token)

mockOperator := environmentOperator
service := NewEnvironmentService(mockOperator)
service := handler.NewEnvironmentService(mockOperator)

_, err := service.DeleteEnvironment(ctx, tc.projectID, tc.environmentID)
if (err != nil && tc.expectedErr == nil) ||
Expand Down Expand Up @@ -211,7 +213,7 @@ func FuzzTestGetEnvironment(f *testing.F) {
}}
singleResult := mongo.NewSingleResultFromDocument(findResult[0], nil, nil)
mongodbMockOperator.On("Get", mock.Anything, mongodb.EnvironmentCollection, mock.Anything).Return(singleResult, nil).Once()
service := NewEnvironmentService(environmentOperator)
service := handler.NewEnvironmentService(environmentOperator)

env, err := service.GetEnvironment(projectID, environmentID)
if err != nil {
Expand Down
17 changes: 10 additions & 7 deletions chaoscenter/graphql/server/utils/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,17 @@ func WriteHeaders(w *gin.ResponseWriter, statusCode int) {

// RandomString generates random strings, can be used to create ids or random secrets
func RandomString(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
rand.Seed(time.Now().UnixNano())
s := make([]rune, n)
for i := range s {
s[i] = letters[rand.Intn(len(letters))]
}
if n > 0 {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
rand.Seed(time.Now().UnixNano())
s := make([]rune, n)
for i := range s {
s[i] = letters[rand.Intn(len(letters))]
}

return string(s)
return string(s)
}
return ""
}

func AddRootIndent(b []byte, n int) []byte {
Expand Down
81 changes: 81 additions & 0 deletions chaoscenter/graphql/server/utils/tests/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package tests
namkyu1999 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Saranya-jena , this file is still in the /tests folder. Can you change this one? Other than that LGTM 🚀

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry missed it, added the changes


import (
"strings"
"testing"

fuzz "github.com/AdaLogics/go-fuzz-headers"
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/utils"
)

func isValidString(s string) bool {
// Define the set of valid characters
validChars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"

// Iterate over each character in the string
for _, char := range s {
// Check if the character is not in the set of valid characters
if !strings.ContainsRune(validChars, char) {
return false
}
}
return true
}

func FuzzRandomString(f *testing.F) {
f.Add(10)
f.Fuzz(func(t *testing.T, n int) {
randomString := utils.RandomString(n)
// Perform checks on the generated string
// Check if the length matches the expected length
if n >= 0 && len(randomString) != n {
t.Errorf("Generated string length doesn't match expected length")
}

// Check if the string contains only valid characters
if !isValidString(randomString) {
t.Errorf("Generated string contains invalid characters")
}
})

}

func FuzzContainsString(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte) {
fuzzConsumer := fuzz.NewConsumer(data)
targetStruct := &struct {
s []string
str string
}{}
err := fuzzConsumer.GenerateStruct(targetStruct)
if err != nil {
return
}
// Perform checks on the ContainsString function
// Check if ContainsString returns true when the target string is in the array
if utils.ContainsString(targetStruct.s, targetStruct.str) {
found := false
for _, v := range targetStruct.s {
if v == targetStruct.str {
found = true
break
}
}
if !found {
t.Errorf("ContainsString returned true for target '%s' not present in the array", targetStruct.str)
}
} else {
// Check if ContainsString returns false when the target string is not in the array
found := false
for _, v := range targetStruct.s {
if v == targetStruct.str {
found = true
break
}
}
if found {
t.Errorf("ContainsString returned false for target '%s' present in the array", targetStruct.str)
}
}
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
int(-57)
Loading