github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/service/jwt_token_test.go (about)

     1  package service_test
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/golang-jwt/jwt"
     7  	. "github.com/onsi/ginkgo/v2"
     8  	. "github.com/onsi/gomega"
     9  
    10  	"github.com/pyroscope-io/pyroscope/pkg/model"
    11  	"github.com/pyroscope-io/pyroscope/pkg/service"
    12  )
    13  
    14  var _ = Describe("API key JWT encoding", func() {
    15  	var (
    16  		userName string
    17  		userRole model.Role
    18  		tokenTTL time.Duration
    19  		svc      service.JWTTokenService
    20  
    21  		token  *jwt.Token
    22  		signed string
    23  		err    error
    24  		key    []byte
    25  	)
    26  
    27  	BeforeEach(func() {
    28  		userName = "johndoe"
    29  		userRole = model.AdminRole
    30  		key = []byte("signing-key")
    31  		tokenTTL = 0
    32  	})
    33  
    34  	JustBeforeEach(func() {
    35  		svc = service.NewJWTTokenService(key, tokenTTL)
    36  		token = svc.GenerateUserJWTToken(userName, userRole)
    37  		signed, err = svc.Sign(token)
    38  	})
    39  
    40  	Context("when a new token is generated for a user", func() {
    41  		It("does not return error", func() {
    42  			Expect(err).ToNot(HaveOccurred())
    43  		})
    44  
    45  		It("produces a valid JWT token", func() {
    46  			parsed, parseErr := svc.Parse(signed)
    47  			Expect(parseErr).ToNot(HaveOccurred())
    48  			Expect(parsed.Valid).To(BeTrue())
    49  		})
    50  	})
    51  
    52  	Context("invalid JWT token", func() {
    53  		Context("when an expired JWT token is parsed", func() {
    54  			BeforeEach(func() {
    55  				tokenTTL = time.Millisecond
    56  			})
    57  			It("returns error if token has expired", func() {
    58  				time.Sleep(time.Second)
    59  				_, err = svc.Parse(signed)
    60  				Expect(err).To(HaveOccurred())
    61  			})
    62  		})
    63  
    64  		Context("when a token with invalid signature is parsed", func() {
    65  			It("returns error if its signature can not be verified", func() {
    66  				svc = service.NewJWTTokenService([]byte("invalid"), tokenTTL)
    67  				_, err = svc.Parse(signed)
    68  				Expect(err).To(HaveOccurred())
    69  			})
    70  		})
    71  	})
    72  
    73  	Context("when a token is acquired with UserFromJWTToken", func() {
    74  		It("creates a valid user token", func() {
    75  			user, ok := svc.UserFromJWTToken(svc.GenerateUserJWTToken(userName, userRole))
    76  			Expect(ok).To(BeTrue())
    77  			Expect(user).To(Equal(model.TokenUser{
    78  				Name: userName,
    79  				Role: userRole,
    80  			}))
    81  		})
    82  
    83  		It("returns false if user token can not be retrieved", func() {
    84  			_, ok := svc.UserFromJWTToken(svc.GenerateUserJWTToken("", model.InvalidRole))
    85  			Expect(ok).To(BeFalse())
    86  		})
    87  	})
    88  })