|
| 1 | +/* |
| 2 | + * Copyright 2025 steadybit GmbH. All rights reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +package e2e |
| 6 | + |
| 7 | +import ( |
| 8 | + "crypto/rand" |
| 9 | + "crypto/rsa" |
| 10 | + "crypto/tls" |
| 11 | + "crypto/x509" |
| 12 | + "crypto/x509/pkix" |
| 13 | + "encoding/pem" |
| 14 | + "fmt" |
| 15 | + "math/big" |
| 16 | + "net" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +// generateSelfSignedCert creates a self-signed certificate and private key |
| 21 | +func generateSelfSignedCert() (tls.Certificate, error) { |
| 22 | + // Generate a private key |
| 23 | + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 24 | + if err != nil { |
| 25 | + return tls.Certificate{}, fmt.Errorf("failed to generate private key: %w", err) |
| 26 | + } |
| 27 | + |
| 28 | + // Create a certificate template |
| 29 | + serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) |
| 30 | + if err != nil { |
| 31 | + return tls.Certificate{}, fmt.Errorf("failed to generate serial number: %w", err) |
| 32 | + } |
| 33 | + |
| 34 | + notBefore := time.Now() |
| 35 | + notAfter := notBefore.Add(365 * 24 * time.Hour) // Valid for 1 year |
| 36 | + |
| 37 | + template := x509.Certificate{ |
| 38 | + SerialNumber: serialNumber, |
| 39 | + Subject: pkix.Name{ |
| 40 | + Organization: []string{"Steadybit Test"}, |
| 41 | + CommonName: "localhost", |
| 42 | + }, |
| 43 | + NotBefore: notBefore, |
| 44 | + NotAfter: notAfter, |
| 45 | + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, |
| 46 | + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 47 | + BasicConstraintsValid: true, |
| 48 | + DNSNames: []string{"localhost", "host.minikube.internal"}, |
| 49 | + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, |
| 50 | + } |
| 51 | + |
| 52 | + // Create the certificate |
| 53 | + derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) |
| 54 | + if err != nil { |
| 55 | + return tls.Certificate{}, fmt.Errorf("failed to create certificate: %w", err) |
| 56 | + } |
| 57 | + |
| 58 | + // Encode certificate and private key to PEM format |
| 59 | + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) |
| 60 | + privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) |
| 61 | + |
| 62 | + // Parse the certificate and private key |
| 63 | + cert, err := tls.X509KeyPair(certPEM, privateKeyPEM) |
| 64 | + if err != nil { |
| 65 | + return tls.Certificate{}, fmt.Errorf("failed to parse certificate: %w", err) |
| 66 | + } |
| 67 | + |
| 68 | + return cert, nil |
| 69 | +} |
0 commit comments