Skip to content

Commit

Permalink
improve tests
Browse files Browse the repository at this point in the history
  • Loading branch information
morphy2k committed Aug 14, 2023
1 parent 00b7a8f commit 5f9f387
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 26 deletions.
2 changes: 1 addition & 1 deletion middleware/jwt/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func verifyCert(leaf *x509.Certificate, intermediates []*x509.Certificate, roots

_, err := leaf.Verify(opts)
if err != nil {
return fmt.Errorf("failed to verify certificate: %w", err)
return fmt.Errorf("failed to verify and build certificate chain: %v", err)
}

if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
Expand Down
14 changes: 7 additions & 7 deletions middleware/jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,19 +187,19 @@ func VerifyToken(tokenStr string) (*Claims, error) {
if err != nil {
switch {
case errors.Is(err, jwt.ErrTokenExpired):
return nil, ErrExpiredToken
return nil, errors.Join(ErrExpiredToken, err)
case errors.Is(err, jwt.ErrTokenNotValidYet):
return nil, ErrNotBefore
return nil, errors.Join(ErrNotBefore, err)
case errors.Is(err, jwt.ErrTokenInvalidAudience):
return nil, ErrInvalidAudience
return nil, errors.Join(ErrInvalidAudience, err)
case errors.Is(err, jwt.ErrTokenInvalidSubject):
return nil, ErrInvalidSubject
return nil, errors.Join(ErrInvalidSubject, err)
case errors.Is(err, jwt.ErrTokenMalformed):
return nil, ErrMalformed
return nil, errors.Join(ErrMalformed, err)
case errors.Is(err, jwt.ErrInvalidKey), errors.Is(err, jwt.ErrInvalidKeyType):
return nil, errors.New("invalid signing key")
return nil, err
default:
return nil, ErrInvalidToken
return nil, errors.Join(ErrInvalidToken, err)
}
}

Expand Down
64 changes: 46 additions & 18 deletions middleware/jwt/jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package jwt

import (
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
Expand Down Expand Up @@ -61,24 +63,50 @@ func TestHmacSignVerify(t *testing.T) {
}

func TestEd25519Verify(t *testing.T) {
claimsIn := &Claims{}

token, err := signTestingToken(claimsIn)
if err != nil {
t.Errorf("Token creation failed: %v", err)
}

claimsOut, err := VerifyToken(token)
if err != nil {
t.Errorf("Token verification failed: %v", err)
tests := []struct {
name string
claims *Claims
certFile string
keyFile string
expectError bool
}{
{
name: "valid token",
claims: &Claims{},
certFile: "testdata/certs.crt",
keyFile: "testdata/key.pem",
},
{
name: "invalid token",
claims: &Claims{},
certFile: "testdata/certs_invalid.crt",
keyFile: "testdata/key_invalid.pem",
expectError: true,
},
}

if !reflect.DeepEqual(claimsIn, claimsOut) {
t.Errorf("Token claim validation failed: claims %v and %v unequal", claimsIn, claimsOut)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
token, err := signTestingToken(tt.claims, tt.certFile, tt.keyFile)
if err != nil {
t.Fatalf("Token creation failed: %v", err)
}

_, err = VerifyToken(token)
if tt.expectError {
if errors.Is(err, x509.UnknownAuthorityError{}) {
t.Error("Token verification failed: expected error not returned")
}
} else {
if err != nil {
t.Errorf("Token verification failed: %v", err)
}
}
})
}
}

func TestGetToken(t *testing.T) {
func TestExtractToken(t *testing.T) {
header := http.Header{}
header.Add("Authorization", fmt.Sprintf("Bearer %s", badToken))

Expand All @@ -99,7 +127,7 @@ func TestAuhtorizationHandler(t *testing.T) {
},
}

validToken, err := signTestingToken(validClaims)
validToken, err := signTestingToken(validClaims, "testdata/certs.crt", "testdata/key.pem")
if err != nil {
t.Fatalf("Getting token failed: %s", err)
}
Expand Down Expand Up @@ -141,7 +169,7 @@ func TestAuhtorizationHandler(t *testing.T) {
},
}

invalidToken, err := signTestingToken(invalidClaims)
invalidToken, err := signTestingToken(invalidClaims, "testdata/certs.crt", "testdata/key.pem")
if err != nil {
t.Fatalf("Authorization handler failed: %s", err)
}
Expand All @@ -160,9 +188,9 @@ func TestAuhtorizationHandler(t *testing.T) {
}
}

func signTestingToken(c *Claims) (string, error) {
func signTestingToken(c *Claims, certPath, keyPath string) (string, error) {
// Load key and PEM certificates
keyBytes, err := os.ReadFile("testdata/key.pem")
keyBytes, err := os.ReadFile(keyPath)
if err != nil {
return "", fmt.Errorf("failed to read key file: %w", err)
}
Expand All @@ -172,7 +200,7 @@ func signTestingToken(c *Claims) (string, error) {
return "", fmt.Errorf("failed to parse key: %w", err)
}

certs, err := parseCertsFromPEM("testdata/certs.crt")
certs, err := parseCertsFromPEM(certPath)
if err != nil {
return "", fmt.Errorf("failed to read cert file: %w", err)
}
Expand Down
20 changes: 20 additions & 0 deletions middleware/jwt/testdata/certs_invalid.crt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIBUTCCAQOgAwIBAgIRANrykiuMfNiYfvdM9bsKQ9QwBQYDK2VwMBIxEDAOBgNV
BAMTB3Jvb3QtY2EwHhcNMjMwODE0MTc1ODM2WhcNMzMwODExMTc1ODM2WjAaMRgw
FgYDVQQDEw9pbnRlcm1lZGlhdGUtY2EwKjAFBgMrZXADIQD1iNGZHYLbvYkNULn1
N1+g/+/YIGGQGOxBORynUVhwU6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB
/wQIMAYBAf8CAQAwHQYDVR0OBBYEFD8QqveZI/Nc9pZ4ZmBxYlvVy5fEMB8GA1Ud
IwQYMBaAFCjKKGBx3n89/F1moJwRTgy1BLr+MAUGAytlcANBAMBRhY7xWTn2uV6F
XQu3xYNOnPJVqUpbmdG42mQWRVnyaXCoGNTe4uS8+MN5J9G65RgPspzX7kta2f7X
m1jrsg4=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIBaTCCARugAwIBAgIRALs/pW4QcJh9ZYIv85r95KYwBQYDK2VwMBoxGDAWBgNV
BAMTD2ludGVybWVkaWF0ZS1jYTAeFw0yMzA4MTQxNzU5NTFaFw0yMzA4MTUxNzU5
NTFaMA4xDDAKBgNVBAMTA2ZvbzAqMAUGAytlcAMhADUeFpoeNiby4WeGCY6a8kuL
9ocz+OHb1wJYTI/e50vfo4GBMH8wDgYDVR0PAQH/BAQDAgeAMB0GA1UdJQQWMBQG
CCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHQ4EFgQUUHJfzi32gHmay/+uoETMsQgl
EKcwHwYDVR0jBBgwFoAUPxCq95kj81z2lnhmYHFiW9XLl8QwDgYDVR0RBAcwBYID
Zm9vMAUGAytlcANBAAmjEHJ9HYeGKl9M6TSftNoJnTwP8nWnKWMEyG0rXKSFaAm1
P9V712wTUhadt+gHqhzOk9qGEDEnrSwGGShWWwY=
-----END CERTIFICATE-----
3 changes: 3 additions & 0 deletions middleware/jwt/testdata/key_invalid.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIIsFqGt9N1bT2FiFdcXUpn15cDQ2/8N1nz4R9KcqzEHl
-----END PRIVATE KEY-----

0 comments on commit 5f9f387

Please sign in to comment.