github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/protocol/v1/security_request_test.go (about) 1 // Copyright (c) 2017-2022, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package v1 6 7 import ( 8 "encoding/base64" 9 "errors" 10 "os" 11 12 "github.com/choria-io/go-choria/inter" 13 imock "github.com/choria-io/go-choria/inter/imocks" 14 "github.com/choria-io/go-choria/protocol" 15 "github.com/golang/mock/gomock" 16 . "github.com/onsi/ginkgo/v2" 17 . "github.com/onsi/gomega" 18 "github.com/sirupsen/logrus" 19 "github.com/tidwall/gjson" 20 ) 21 22 var _ = Describe("SecureRequest", func() { 23 var mockctl *gomock.Controller 24 var security *imock.MockSecurityProvider 25 var pub []byte 26 27 BeforeEach(func() { 28 logrus.SetLevel(logrus.FatalLevel) 29 mockctl = gomock.NewController(GinkgoT()) 30 security = imock.NewMockSecurityProvider(mockctl) 31 security.EXPECT().BackingTechnology().Return(inter.SecurityTechnologyX509) 32 33 protocol.Secure = "true" 34 35 pub, _ = os.ReadFile("testdata/ssl/certs/rip.mcollective.pem") 36 }) 37 38 AfterEach(func() { 39 mockctl.Finish() 40 }) 41 42 It("Should support insecure mode", func() { 43 security.EXPECT().PublicCertBytes().Return([]byte{}, errors.New("simulated")).AnyTimes() 44 45 protocol.Secure = "false" 46 47 r, _ := NewRequest("test", "go.tests", "rip.mcollective", 120, "a2f0ca717c694f2086cfa81b6c494648", "mcollective") 48 r.SetMessage([]byte(`{"test":1}`)) 49 rj, err := r.JSON() 50 Expect(err).ToNot(HaveOccurred()) 51 52 security.EXPECT().SignBytes(gomock.Any()).Times(0) 53 54 sr, err := NewSecureRequest(r, security) 55 Expect(err).ToNot(HaveOccurred()) 56 57 sj, err := sr.JSON() 58 Expect(err).ToNot(HaveOccurred()) 59 60 Expect(protocol.VersionFromJSON(sj)).To(Equal(protocol.SecureRequestV1)) 61 Expect(gjson.GetBytes(sj, "message").String()).To(Equal(string(rj))) 62 Expect(gjson.GetBytes(sj, "pubcert").String()).To(Equal("insecure")) 63 Expect(gjson.GetBytes(sj, "signature").String()).To(Equal("insecure")) 64 }) 65 66 It("Should create a valid SecureRequest", func() { 67 security.EXPECT().PublicCertBytes().Return(pub, nil).AnyTimes() 68 69 r, _ := NewRequest("test", "go.tests", "rip.mcollective", 120, "a2f0ca717c694f2086cfa81b6c494648", "mcollective") 70 r.SetMessage([]byte(`{"test":1}`)) 71 rj, err := r.JSON() 72 Expect(err).ToNot(HaveOccurred()) 73 74 security.EXPECT().SignBytes(rj).Return([]byte("stub.sig"), nil) 75 76 sr, err := NewSecureRequest(r, security) 77 Expect(err).ToNot(HaveOccurred()) 78 79 sj, err := sr.JSON() 80 Expect(err).ToNot(HaveOccurred()) 81 82 Expect(protocol.VersionFromJSON(sj)).To(Equal(protocol.SecureRequestV1)) 83 Expect(gjson.GetBytes(sj, "message").String()).To(Equal(string(rj))) 84 Expect(gjson.GetBytes(sj, "pubcert").String()).To(Equal(string(pub))) 85 Expect(gjson.GetBytes(sj, "signature").String()).To(Equal(base64.StdEncoding.EncodeToString([]byte("stub.sig")))) 86 }) 87 })