From 9ea1842360990426e241182be65529f187b9bc6a Mon Sep 17 00:00:00 2001 From: MrMelon54 Date: Mon, 19 Jun 2023 11:40:28 +0100 Subject: [PATCH] Add test for NewMJwtVerifierFromFile --- mjwt_test.go | 2 +- verifier.go | 5 +---- verifier_test.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 verifier_test.go diff --git a/mjwt_test.go b/mjwt_test.go index 14297e5..e6dff92 100644 --- a/mjwt_test.go +++ b/mjwt_test.go @@ -12,7 +12,7 @@ import ( type testClaims struct{ TestValue string } func (t testClaims) Valid() error { - if t.TestValue != "hello" { + if t.TestValue != "hello" && t.TestValue != "world" { return fmt.Errorf("TestValue should be hello") } return nil diff --git a/verifier.go b/verifier.go index ef54dc4..a0ef2b2 100644 --- a/verifier.go +++ b/verifier.go @@ -5,13 +5,10 @@ import ( "crypto/x509" "encoding/pem" "github.com/golang-jwt/jwt/v4" - "github.com/pkg/errors" "os" ) -var ErrCannotGenerateMJwtToken = errors.New("cannot generate mjwt token with verifier") - -// defaultMJwtVerifier implements Verifier and uses an rsa.PublicKey to validate +// defaultMJwtVerifier implements Verifier and uses a rsa.PublicKey to validate // MJWT tokens type defaultMJwtVerifier struct { pub *rsa.PublicKey diff --git a/verifier_test.go b/verifier_test.go new file mode 100644 index 0000000..87916f7 --- /dev/null +++ b/verifier_test.go @@ -0,0 +1,33 @@ +package mjwt + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "github.com/stretchr/testify/assert" + "os" + "testing" + "time" +) + +func TestNewMJwtVerifierFromFile(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + assert.NoError(t, err) + + s := NewMJwtSigner("mjwt.test", key) + token, err := s.GenerateJwt("1", "test", 10*time.Minute, testClaims{TestValue: "world"}) + assert.NoError(t, err) + + b := pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(&key.PublicKey)}) + temp, err := os.CreateTemp("", "this-is-a-test-file.pem") + assert.NoError(t, err) + _, err = temp.Write(b) + assert.NoError(t, err) + file, err := NewMJwtVerifierFromFile(temp.Name()) + assert.NoError(t, err) + _, _, err = ExtractClaims[testClaims](file, token) + assert.NoError(t, err) + err = os.Remove(temp.Name()) + assert.NoError(t, err) +}