Best K6 code snippet using x509.ipAddresses
helper_test.go
Source:helper_test.go
1// Copyright 2021 Alex Szakaly2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//15//nolint:testpackage // Need to reach functions.16package certificatesigningrequest17import (18 "crypto/x509"19 "crypto/x509/pkix"20 "errors"21 "fmt"22 "net"23 "net/url"24 "testing"25 "github.com/stretchr/testify/assert"26 certificatesv1 "k8s.io/api/certificates/v1"27)28const (29 validOrganization = "system:nodes"30 validUsername = "system:node:node-01"31)32//nolint:gochecknoglobals33var (34 validDNSNames = []string{"foo.bar"}35 valdIPAddresses = []net.IP{net.ParseIP("1.2.3.4")}36 validUsages = []certificatesv1.KeyUsage{37 certificatesv1.UsageKeyEncipherment,38 certificatesv1.UsageDigitalSignature,39 certificatesv1.UsageServerAuth,40 }41)42func TestParseCSR(t *testing.T) {43 t.Parallel()44 csr, err := parseCSR(nil)45 assert.NotNil(t, err)46 assert.Nil(t, csr)47 assert.True(t, errors.Is(err, errNotCertificateRequest))48}49func TestParseCSRMissingBlock(t *testing.T) {50 t.Parallel()51 pemCSR := []byte(`52-----BEGIN CERTIFICATE REQUEST-----53-----END CERTIFICATE REQUEST-----54`)55 csr, err := parseCSR(pemCSR)56 assert.NotNil(t, err)57 assert.Nil(t, csr)58 assert.Contains(t, err.Error(), "during parsing of Certificate Signing Request")59}60func TestParseCSRValidInput(t *testing.T) {61 t.Parallel()62 csr, err := parseCSR(generatePEMEncodedCSR(t))63 assert.Nil(t, err)64 assert.NotNil(t, csr)65}66func TestIsRequestConformInvalidSigningRequest(t *testing.T) {67 t.Parallel()68 tables := []struct {69 expectedError error70 x509cr x509.CertificateRequest71 csr certificatesv1.CertificateSigningRequest72 }{73 {74 csr: certificatesv1.CertificateSigningRequest{75 Spec: certificatesv1.CertificateSigningRequestSpec{76 Usages: validUsages,77 Username: validUsername,78 SignerName: certificatesv1.KubeletServingSignerName,79 },80 },81 x509cr: x509.CertificateRequest{82 Subject: pkix.Name{83 CommonName: validUsername,84 Organization: []string{"invalid"},85 },86 DNSNames: validDNSNames,87 IPAddresses: valdIPAddresses,88 },89 expectedError: errOrganizationMismatch,90 },91 {92 csr: certificatesv1.CertificateSigningRequest{93 Spec: certificatesv1.CertificateSigningRequestSpec{94 Usages: validUsages,95 Username: validUsername,96 SignerName: certificatesv1.KubeletServingSignerName,97 },98 },99 x509cr: x509.CertificateRequest{100 Subject: pkix.Name{101 CommonName: "bad:prefix:node:node-01",102 Organization: []string{validOrganization},103 },104 DNSNames: validDNSNames,105 IPAddresses: valdIPAddresses,106 },107 expectedError: errX509CommonNamePrefixMismatch,108 },109 {110 csr: certificatesv1.CertificateSigningRequest{111 Spec: certificatesv1.CertificateSigningRequestSpec{112 Usages: validUsages,113 Username: validUsername,114 SignerName: certificatesv1.KubeletServingSignerName,115 },116 },117 x509cr: x509.CertificateRequest{118 Subject: pkix.Name{119 CommonName: validUsername + "mismatch",120 Organization: []string{validOrganization},121 },122 DNSNames: validDNSNames,123 IPAddresses: valdIPAddresses,124 },125 expectedError: errX509CommonNameMismatch,126 },127 {128 csr: certificatesv1.CertificateSigningRequest{129 Spec: certificatesv1.CertificateSigningRequestSpec{130 Username: validUsername,131 Usages: validUsages,132 SignerName: certificatesv1.KubeletServingSignerName,133 },134 },135 x509cr: x509.CertificateRequest{136 Subject: pkix.Name{137 CommonName: validUsername,138 Organization: []string{validOrganization},139 },140 EmailAddresses: []string{"foo@no-reply.bar"},141 },142 expectedError: errExtraExtensionsPresent,143 },144 {145 csr: certificatesv1.CertificateSigningRequest{146 Spec: certificatesv1.CertificateSigningRequestSpec{147 Username: validUsername,148 Usages: validUsages,149 SignerName: certificatesv1.KubeletServingSignerName,150 },151 },152 x509cr: x509.CertificateRequest{153 Subject: pkix.Name{154 CommonName: validUsername,155 Organization: []string{validOrganization},156 },157 URIs: []*url.URL{{Host: "foo.bar.acme"}},158 },159 expectedError: errExtraExtensionsPresent,160 },161 {162 csr: certificatesv1.CertificateSigningRequest{163 Spec: certificatesv1.CertificateSigningRequestSpec{164 Username: validUsername,165 Usages: validUsages,166 SignerName: certificatesv1.KubeletServingSignerName,167 },168 },169 x509cr: x509.CertificateRequest{170 Subject: pkix.Name{171 CommonName: validUsername,172 Organization: []string{validOrganization},173 },174 EmailAddresses: []string{"foo@no-reply.bar"},175 URIs: []*url.URL{{Host: "foo.bar.acme"}},176 },177 expectedError: errExtraExtensionsPresent,178 },179 {180 csr: certificatesv1.CertificateSigningRequest{181 Spec: certificatesv1.CertificateSigningRequestSpec{182 Username: validUsername,183 Usages: validUsages,184 SignerName: certificatesv1.KubeletServingSignerName,185 },186 },187 x509cr: x509.CertificateRequest{188 Subject: pkix.Name{189 CommonName: validUsername,190 Organization: []string{validOrganization},191 },192 },193 expectedError: errDNSOrIPMissing,194 },195 {196 csr: certificatesv1.CertificateSigningRequest{197 Spec: certificatesv1.CertificateSigningRequestSpec{198 Username: validUsername,199 Usages: []certificatesv1.KeyUsage{200 certificatesv1.UsageServerAuth,201 certificatesv1.UsageDigitalSignature,202 certificatesv1.UsageKeyEncipherment,203 certificatesv1.UsageCodeSigning,204 },205 SignerName: certificatesv1.KubeletServingSignerName,206 },207 },208 x509cr: x509.CertificateRequest{209 Subject: pkix.Name{210 CommonName: validUsername,211 Organization: []string{validOrganization},212 },213 DNSNames: validDNSNames,214 IPAddresses: valdIPAddresses,215 },216 expectedError: errKeyUsageMismatch,217 },218 {219 csr: certificatesv1.CertificateSigningRequest{220 Spec: certificatesv1.CertificateSigningRequestSpec{221 Username: validUsername,222 Usages: []certificatesv1.KeyUsage{223 certificatesv1.UsageKeyEncipherment,224 certificatesv1.UsageDigitalSignature,225 certificatesv1.UsageCodeSigning,226 },227 SignerName: certificatesv1.KubeletServingSignerName,228 },229 },230 x509cr: x509.CertificateRequest{231 Subject: pkix.Name{232 CommonName: validUsername,233 Organization: []string{validOrganization},234 },235 DNSNames: validDNSNames,236 IPAddresses: valdIPAddresses,237 },238 expectedError: errKeyUsageMismatch,239 },240 }241 for _, table := range tables { //nolint:paralleltest // Disable false-positive finding due to linter bug.242 table := table // pin!243 t.Run(fmt.Sprint(table.expectedError), func(t *testing.T) {244 t.Parallel()245 assert.True(t, errors.Is(isRequestConform(TestLogger, table.csr, &table.x509cr), table.expectedError))246 })247 }248}249func TestConformantKubeletServingCertificateSigningRequest(t *testing.T) {250 t.Parallel()251 tables := []struct {252 goal string253 csr certificatesv1.CertificateSigningRequest254 x509cr x509.CertificateRequest255 }{256 {257 goal: "Only DNSNames present",258 csr: certificatesv1.CertificateSigningRequest{259 Spec: certificatesv1.CertificateSigningRequestSpec{260 Usages: validUsages,261 Username: validUsername,262 SignerName: certificatesv1.KubeletServingSignerName,263 },264 },265 x509cr: x509.CertificateRequest{266 Subject: pkix.Name{267 CommonName: validUsername,268 Organization: []string{validOrganization},269 },270 DNSNames: validDNSNames,271 },272 },273 {274 goal: "Only IPAddresses present",275 csr: certificatesv1.CertificateSigningRequest{276 Spec: certificatesv1.CertificateSigningRequestSpec{277 Usages: validUsages,278 Username: validUsername,279 SignerName: certificatesv1.KubeletServingSignerName,280 },281 },282 x509cr: x509.CertificateRequest{283 Subject: pkix.Name{284 CommonName: validUsername,285 Organization: []string{validOrganization},286 },287 IPAddresses: valdIPAddresses,288 },289 },290 }291 for _, table := range tables { //nolint:paralleltest // Disable false-positive finding due to linter bug.292 table := table // pin!293 t.Run(fmt.Sprint(table.goal), func(t *testing.T) {294 t.Parallel()295 assert.NoError(t, isRequestConform(TestLogger, table.csr, &table.x509cr))296 })297 }298}...
x509.go
Source:x509.go
1package tlsutil2import (3 "crypto/rand"4 "crypto/rsa"5 "crypto/x509"6 "crypto/x509/pkix"7 "math"8 "math/big"9 "net"10 "time"11)12var (13 Duration90d = time.Hour * 24 * 9014 Duration365d = time.Hour * 24 * 36515)16type CACertConfig struct {17 CommonName string18 Organization string19}20type ServerCertConfig struct {21 CommonName string22 DNSNames []string23 IPAddresses []string24}25type ClientCertConfig struct {26 CommonName string27 DNSNames []string28 IPAddresses []string29}30func NewSelfSignedCACertificate(cfg CACertConfig, key *rsa.PrivateKey) (*x509.Certificate, error) {31 now := time.Now()32 tmpl := x509.Certificate{33 SerialNumber: new(big.Int).SetInt64(0),34 Subject: pkix.Name{35 CommonName: cfg.CommonName,36 Organization: []string{cfg.Organization},37 },38 NotBefore: now.UTC(),39 NotAfter: now.Add(Duration365d).UTC(),40 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,41 BasicConstraintsValid: true,42 IsCA: true,43 }44 certDERBytes, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, key.Public(), key)45 if err != nil {46 return nil, err47 }48 return x509.ParseCertificate(certDERBytes)49}50func NewSignedServerCertificate(cfg ServerCertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {51 ips := make([]net.IP, len(cfg.IPAddresses))52 for i, ipStr := range cfg.IPAddresses {53 ips[i] = net.ParseIP(ipStr)54 }55 serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))56 if err != nil {57 return nil, err58 }59 certTmpl := x509.Certificate{60 Subject: pkix.Name{61 CommonName: cfg.CommonName,62 Organization: caCert.Subject.Organization,63 },64 DNSNames: cfg.DNSNames,65 IPAddresses: ips,66 SerialNumber: serial,67 NotBefore: caCert.NotBefore,68 NotAfter: time.Now().Add(Duration90d).UTC(),69 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,70 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},71 }72 certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)73 if err != nil {74 return nil, err75 }76 return x509.ParseCertificate(certDERBytes)77}78func NewSignedClientCertificate(cfg ClientCertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {79 ips := make([]net.IP, len(cfg.IPAddresses))80 for i, ipStr := range cfg.IPAddresses {81 ips[i] = net.ParseIP(ipStr)82 }83 serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))84 if err != nil {85 return nil, err86 }87 certTmpl := x509.Certificate{88 Subject: pkix.Name{89 CommonName: cfg.CommonName,90 Organization: caCert.Subject.Organization,91 },92 DNSNames: cfg.DNSNames,93 IPAddresses: ips,94 SerialNumber: serial,95 NotBefore: caCert.NotBefore,96 NotAfter: time.Now().Add(Duration90d).UTC(),97 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,98 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},99 }100 certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)101 if err != nil {102 return nil, err103 }104 return x509.ParseCertificate(certDERBytes)105}...
ipAddresses
Using AI Code Generation
1import (2func main() {3 pemData, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 panic(err)6 }7 block, _ := pem.Decode(pemData)8 if block == nil {9 panic("failed to parse certificate PEM")10 }11 cert, err := x509.ParseCertificate(block.Bytes)12 if err != nil {13 panic("failed to parse certificate: " + err.Error())14 }15 fmt.Println(cert.IPAddresses)16}
ipAddresses
Using AI Code Generation
1import (2func main() {3 cert, err := x509.ParseCertificate([]byte(certStr))4 if err != nil {5 log.Fatal(err)6 }7 for _, ip := range cert.IPAddresses {8 fmt.Println(ip)9 }10}11import (12func main() {13 cert, err := x509.ParseCertificate([]byte(certStr))14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(cert.Subject.CommonName)18}19import (20func main() {21 cert, err := x509.ParseCertificate([]byte(certStr))22 if err != nil {23 log.Fatal(err)24 }25 for _, dns := range cert.DNSNames {26 fmt.Println(dns)27 }28}29import (30func main() {31 cert, err := x509.ParseCertificate([]byte(certStr))32 if err != nil {33 log.Fatal(err)34 }35 for _, email := range cert.EmailAddresses {36 fmt.Println(email)37 }38}39import (40func main() {41 cert, err := x509.ParseCertificate([]byte(certStr))42 if err != nil {43 log.Fatal(err)44 }45 fmt.Println(cert.SerialNumber)46}47import (48func main() {49 cert, err := x509.ParseCertificate([]byte(certStr))50 if err != nil {51 log.Fatal(err)52 }53 for _, ext := range cert.Extensions {54 fmt.Println(ext.Id)55 }56}57import (58func main()
ipAddresses
Using AI Code Generation
1import (2func main() {3 certPEM, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 panic(err)6 }7 block, _ := pem.Decode(certPEM)8 if block == nil {9 panic("failed to parse certificate PEM")10 }11 cert, err := x509.ParseCertificate(block.Bytes)12 if err != nil {13 panic(err)14 }15 fmt.Println("IP addresses from certificate:")16 for _, ip := range ips {17 fmt.Println(ip)18 }19}
ipAddresses
Using AI Code Generation
1import (2func main() {3 file, err := ioutil.ReadFile("cert.pem")4 if err != nil {5 fmt.Println("Error reading file:", err)6 }7 block, _ := pem.Decode(file)8 if block == nil {9 fmt.Println("Error decoding file")10 }11 cert, err := x509.ParseCertificate(block.Bytes)12 if err != nil {13 fmt.Println("Error parsing certificate:", err)14 }15 fmt.Println(cert.Issuer)16 fmt.Println(cert.Subject)17 fmt.Println(cert.NotBefore)18 fmt.Println(cert.NotAfter)19 fmt.Println(cert.KeyUsage)20 fmt.Println(cert.ExtKeyUsage)21 fmt.Println(cert.UnknownExtKeyUsage)22 fmt.Println(cert.BasicConstraintsValid)23 fmt.Println(cert.IsCA)24 fmt.Println(cert.MaxPathLen)25 fmt.Println(cert.MaxPathLenZero)26 fmt.Println(cert.SubjectKeyId)27 fmt.Println(cert.AuthorityKeyId)28 fmt.Println(cert.DNSNames)29 fmt.Println(cert.EmailAddresses)30 fmt.Println(cert.IPAddresses)31}
ipAddresses
Using AI Code Generation
1import (2func main() {3 cert := x509.Certificate{4 SerialNumber: big.NewInt(1),5 Subject: pkix.Name{CommonName: "example.com"},6 NotBefore: time.Now(),7 NotAfter: time.Now().Add(time.Hour),8 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},9 }10 priv, err := rsa.GenerateKey(rand.Reader, 2048)11 if err != nil {12 panic(err)13 }14 derBytes, err := x509.CreateCertificate(rand.Reader, &cert, &parent, &priv.PublicKey, priv)15 if err != nil {16 panic(err)17 }18 parsedCert, err := x509.ParseCertificate(derBytes)19 if err != nil {20 panic(err)21 }22 fmt.Println("IP Addresses:")23 for _, ip := range ips {24 fmt.Println(ip)25 }26}27How to create a certificate signing request (CSR) in Go28How to create a certificate signing request (CSR) in Go29How to create a certificate signing request (CSR) in Go30How to create a certificate signing request (CSR) in Go
ipAddresses
Using AI Code Generation
1import (2func main() {3 template := x509.Certificate{4 SerialNumber: big.NewInt(1),5 Subject: pkix.Name{6 Organization: []string{"Acme Co"},7 },8 NotBefore: time.Now(),9 NotAfter: time.Now().Add(time.Hour),10 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},11 DNSNames: []string{"localhost"},12 }13 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)14 if err != nil {15 fmt.Println(err)16 }17 derBytes, err := x509.CreateCertificate(rand.Reader, &template, parent, &privateKey.PublicKey, privateKey)18 if err != nil {19 fmt.Println(err)20 }21 cert, err := x509.ParseCertificate(derBytes)22 if err != nil {23 fmt.Println(err)24 }25 for _, ip := range ips {26 fmt.Println(ip)27 }28}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!