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

[Unit Tests] - PubKeyContext #2240

Closed
tomsmith8 opened this issue Dec 19, 2024 · 3 comments · Fixed by #2254
Closed

[Unit Tests] - PubKeyContext #2240

tomsmith8 opened this issue Dec 19, 2024 · 3 comments · Fixed by #2254
Assignees

Comments

@tomsmith8
Copy link

Unit Test Coverage for "PubKeyContext"


Stakwork Run


Unit Test Code


File: /tmp/stakwork/sphinx-tribes/auth/auth.go


package auth

import (
  "context"
  "fmt"
  "net/http"
  "net/http/httptest"
  "strings"
  "testing"
  "time"

  "github.com/stretchr/testify/assert"
  "github.com/stretchr/testify/mock"
)

// Mocking DecodeJwt and VerifyTribeUUID functions
type MockAuth struct {
  mock.Mock
}

func (m *MockAuth) DecodeJwt(token string) (map[string]interface{}, error) {
  args := m.Called(token)
  return args.Get(0).(map[string]interface{}), args.Error(1)
}

func (m *MockAuth) VerifyTribeUUID(uuid string, checkTimestamp bool) (string, error) {
  args := m.Called(uuid, checkTimestamp)
  return args.String(0), args.Error(1)
}

func TestPubKeyContext(t *testing.T) {
  mockAuth := new(MockAuth)

  tests := []struct {
  	name           string
  	token          string
  	header         bool
  	isJwt          bool
  	mockJwtClaims  map[string]interface{}
  	mockJwtError   error
  	mockUuidPubkey string
  	mockUuidError  error
  	expectedStatus int
  	expectedLog    string
  }{
  	{
  		name:           "Valid JWT Token in Query Parameter",
  		token:          "valid.jwt.token",
  		isJwt:          true,
  		mockJwtClaims:  map[string]interface{}{"pubkey": "pubkey1"},
  		mockJwtError:   nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Valid JWT Token in Header",
  		token:          "valid.jwt.token",
  		header:         true,
  		isJwt:          true,
  		mockJwtClaims:  map[string]interface{}{"pubkey": "pubkey1"},
  		mockJwtError:   nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Valid Tribe UUID Token in Query Parameter",
  		token:          "valid-uuid-token",
  		isJwt:          false,
  		mockUuidPubkey: "pubkey2",
  		mockUuidError:  nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Valid Tribe UUID Token in Header",
  		token:          "valid-uuid-token",
  		header:         true,
  		isJwt:          false,
  		mockUuidPubkey: "pubkey2",
  		mockUuidError:  nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Empty Token in Query and Header",
  		token:          "",
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "[auth] no token",
  	},
  	{
  		name:           "Malformed JWT Token",
  		token:          "malformed.jwt.token",
  		isJwt:          true,
  		mockJwtError:   fmt.Errorf("malformed token"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "Failed to parse JWT",
  	},
  	{
  		name:           "Expired JWT Token",
  		token:          "expired.jwt.token",
  		isJwt:          true,
  		mockJwtClaims:  map[string]interface{}{"pubkey": "pubkey1"},
  		mockJwtError:   nil,
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "Token has expired",
  	},
  	{
  		name:           "Invalid Tribe UUID Token",
  		token:          "invalid-uuid-token",
  		isJwt:          false,
  		mockUuidError:  fmt.Errorf("invalid token"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "[auth] no pubkey || err != nil",
  	},
  	{
  		name:           "DecodeJwt Function Error",
  		token:          "error.jwt.token",
  		isJwt:          true,
  		mockJwtError:   fmt.Errorf("decode error"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "Failed to parse JWT",
  	},
  	{
  		name:           "VerifyTribeUUID Function Error",
  		token:          "error-uuid-token",
  		isJwt:          false,
  		mockUuidError:  fmt.Errorf("verification error"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "[auth] no pubkey || err != nil",
  	},
  	{
  		name:           "Token with Leading Dot",
  		token:          ".leading.dot.token",
  		isJwt:          false,
  		mockUuidPubkey: "pubkey3",
  		mockUuidError:  nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Token with No Dot but Valid UUID Format",
  		token:          "valid-uuid-format",
  		isJwt:          false,
  		mockUuidPubkey: "pubkey4",
  		mockUuidError:  nil,
  		expectedStatus: http.StatusOK,
  	},
  	{
  		name:           "Token with Multiple Dots but Invalid JWT Format",
  		token:          "invalid..jwt.format",
  		isJwt:          true,
  		mockJwtError:   fmt.Errorf("invalid format"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "Failed to parse JWT",
  	},
  	{
  		name:           "Token with Valid JWT Format but Invalid Signature",
  		token:          "valid.jwt.invalid.signature",
  		isJwt:          true,
  		mockJwtError:   fmt.Errorf("invalid signature"),
  		expectedStatus: http.StatusUnauthorized,
  		expectedLog:    "Failed to parse JWT",
  	},
  }

  for _, tt := range tests {
  	t.Run(tt.name, func(t *testing.T) {
  		if tt.isJwt {
  			mockAuth.On("DecodeJwt", tt.token).Return(tt.mockJwtClaims, tt.mockJwtError)
  		} else {
  			mockAuth.On("VerifyTribeUUID", tt.token, true).Return(tt.mockUuidPubkey, tt.mockUuidError)
  		}

  		nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  			w.WriteHeader(http.StatusOK)
  		})

  		handler := PubKeyContext(nextHandler)

  		req := httptest.NewRequest("GET", "http://example.com", nil)
  		if tt.header {
  			req.Header.Set("x-jwt", tt.token)
  		} else {
  			q := req.URL.Query()
  			q.Add("token", tt.token)
  			req.URL.RawQuery = q.Encode()
  		}

  		rr := httptest.NewRecorder()

  		handler.ServeHTTP(rr, req)

  		assert.Equal(t, tt.expectedStatus, rr.Code)

  		if tt.expectedLog != "" {
  			// Here you would check the logs if necessary
  		}
  	})
  }
}
@Shoaibdev7
Copy link
Contributor

@tomsmith8 assign me?

@MahtabBukhari
Copy link
Contributor

@tomsmith8 assign

@aliraza556
Copy link
Contributor

tomsmith8 @humansinstitute, could you please assign me a new task? My previous task is completed; please review it here: #2237

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants