github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/authorization/api_test.go (about) 1 package authorization // import "github.com/demonoid81/moby/pkg/authorization" 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/tls" 7 "crypto/x509" 8 "crypto/x509/pkix" 9 "math/big" 10 "net/http" 11 "testing" 12 "time" 13 14 "gotest.tools/v3/assert" 15 is "gotest.tools/v3/assert/cmp" 16 ) 17 18 func TestPeerCertificateMarshalJSON(t *testing.T) { 19 template := &x509.Certificate{ 20 IsCA: true, 21 BasicConstraintsValid: true, 22 SubjectKeyId: []byte{1, 2, 3}, 23 SerialNumber: big.NewInt(1234), 24 Subject: pkix.Name{ 25 Country: []string{"Earth"}, 26 Organization: []string{"Mother Nature"}, 27 }, 28 NotBefore: time.Now(), 29 NotAfter: time.Now().AddDate(5, 5, 5), 30 31 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 32 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, 33 } 34 // generate private key 35 privatekey, err := rsa.GenerateKey(rand.Reader, 2048) 36 assert.NilError(t, err) 37 publickey := &privatekey.PublicKey 38 39 // create a self-signed certificate. template = parent 40 var parent = template 41 raw, err := x509.CreateCertificate(rand.Reader, template, parent, publickey, privatekey) 42 assert.NilError(t, err) 43 44 cert, err := x509.ParseCertificate(raw) 45 assert.NilError(t, err) 46 47 var certs = []*x509.Certificate{cert} 48 addr := "www.authz.com/auth" 49 req, err := http.NewRequest(http.MethodGet, addr, nil) 50 assert.NilError(t, err) 51 52 req.RequestURI = addr 53 req.TLS = &tls.ConnectionState{} 54 req.TLS.PeerCertificates = certs 55 req.Header.Add("header", "value") 56 57 for _, c := range req.TLS.PeerCertificates { 58 pcObj := PeerCertificate(*c) 59 60 t.Run("Marshalling :", func(t *testing.T) { 61 raw, err = pcObj.MarshalJSON() 62 assert.Assert(t, raw != nil) 63 assert.NilError(t, err) 64 }) 65 66 t.Run("UnMarshalling :", func(t *testing.T) { 67 err := pcObj.UnmarshalJSON(raw) 68 assert.Assert(t, is.Nil(err)) 69 assert.Equal(t, "Earth", pcObj.Subject.Country[0]) 70 assert.Equal(t, true, pcObj.IsCA) 71 72 }) 73 74 } 75 76 }