github.com/MerlinKodo/quic-go@v0.39.2/internal/handshake/token_protector_test.go (about) 1 package handshake 2 3 import ( 4 "crypto/rand" 5 6 . "github.com/onsi/ginkgo/v2" 7 . "github.com/onsi/gomega" 8 ) 9 10 var _ = Describe("Token Protector", func() { 11 var tp tokenProtector 12 13 BeforeEach(func() { 14 var key TokenProtectorKey 15 rand.Read(key[:]) 16 var err error 17 tp = newTokenProtector(key) 18 Expect(err).ToNot(HaveOccurred()) 19 }) 20 21 It("encodes and decodes tokens", func() { 22 token, err := tp.NewToken([]byte("foobar")) 23 Expect(err).ToNot(HaveOccurred()) 24 Expect(token).ToNot(ContainSubstring("foobar")) 25 decoded, err := tp.DecodeToken(token) 26 Expect(err).ToNot(HaveOccurred()) 27 Expect(decoded).To(Equal([]byte("foobar"))) 28 }) 29 30 It("uses the different keys", func() { 31 var key1, key2 TokenProtectorKey 32 rand.Read(key1[:]) 33 rand.Read(key2[:]) 34 tp1 := newTokenProtector(key1) 35 tp2 := newTokenProtector(key2) 36 t1, err := tp1.NewToken([]byte("foo")) 37 Expect(err).ToNot(HaveOccurred()) 38 t2, err := tp2.NewToken([]byte("foo")) 39 Expect(err).ToNot(HaveOccurred()) 40 41 _, err = tp1.DecodeToken(t1) 42 Expect(err).ToNot(HaveOccurred()) 43 _, err = tp1.DecodeToken(t2) 44 Expect(err).To(HaveOccurred()) 45 46 // now create another token protector, reusing key1 47 tp3 := newTokenProtector(key1) 48 _, err = tp3.DecodeToken(t1) 49 Expect(err).ToNot(HaveOccurred()) 50 _, err = tp3.DecodeToken(t2) 51 Expect(err).To(HaveOccurred()) 52 }) 53 54 It("doesn't decode invalid tokens", func() { 55 token, err := tp.NewToken([]byte("foobar")) 56 Expect(err).ToNot(HaveOccurred()) 57 _, err = tp.DecodeToken(token[1:]) // the token is invalid without the first byte 58 Expect(err).To(HaveOccurred()) 59 Expect(err.Error()).To(ContainSubstring("message authentication failed")) 60 }) 61 62 It("errors when decoding too short tokens", func() { 63 _, err := tp.DecodeToken([]byte("foobar")) 64 Expect(err).To(MatchError("token too short: 6")) 65 }) 66 })