Skip to content

Commit

Permalink
Add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
nesmabadr committed May 6, 2024
1 parent eccfcae commit 2c3bd5b
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package cacertificatehandler_test

import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/kyma-project/runtime-watcher/skr/internal/cacertificatehandler"
"github.com/kyma-project/runtime-watcher/skr/internal/tlstest"
)

func TestGetCertificatePool(t *testing.T) {
t.Parallel()

certPath := "ca.cert"
err := writeCertificatesToFile(certPath)
require.NoError(t, err)

got, err := cacertificatehandler.GetCertificatePool(certPath)
require.NoError(t, err)
require.False(t, got.Equal(x509.NewCertPool()))

certificates, err := getCertificates(certPath)
require.NoError(t, err)
err = os.Remove(certPath)
require.NoError(t, err)

expectedCertPool := x509.NewCertPool()
for _, certificate := range certificates {
expectedCertPool.AddCert(certificate)
}
require.True(t, got.Equal(expectedCertPool))
}

func getCertificates(certPath string) ([]*x509.Certificate, error) {
caCertBytes, err := os.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf("could not load CA certificate :%w", err)
}
var certs []*x509.Certificate
remainingCert := caCertBytes
for len(remainingCert) > 0 {
var publicPemBlock *pem.Block
publicPemBlock, remainingCert = pem.Decode(remainingCert)
rootPubCrt, errParse := x509.ParseCertificate(publicPemBlock.Bytes)
if errParse != nil {
msg := "failed to parse public key"
return nil, fmt.Errorf("%s :%w", msg, errParse)
}
certs = append(certs, rootPubCrt)
}

return certs, nil
}

func createCertificate() *x509.Certificate {
sn, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
cert := &x509.Certificate{
SerialNumber: sn,
Subject: pkix.Name{
CommonName: "127.0.0.1",
},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
IsCA: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}

return cert
}

func writeCertificatesToFile(certPath string) error {
certificate := createCertificate()
rootKey, err := tlstest.GenerateRootKey()
if err != nil {
return fmt.Errorf("failed to generate root key: %w", err)
}

cert, err := tlstest.CreateCert(certificate, certificate, rootKey, rootKey)
if err != nil {
return fmt.Errorf("failed to create certificate: %w", err)
}
certBytes := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Certificate[0],
})
file, err := os.OpenFile(certPath, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}

_, err = file.Write(certBytes)
if err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}

certificate = createCertificate()
cert, err = tlstest.CreateCert(certificate, certificate, rootKey, rootKey)
if err != nil {
return fmt.Errorf("failed to create certificate: %w", err)
}
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Certificate[0],
})

_, err = file.Write(certBytes)
if err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}
return nil
}
21 changes: 15 additions & 6 deletions runtime-watcher/internal/tlstest/certificate_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (p *CertProvider) CleanUp() error {
return p.removeTempFiles()
}

func CreateCertTemplate(isCA bool) (*x509.Certificate, error) {
func createCertTemplate(isCA bool) (*x509.Certificate, error) {
sn, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), certSerialNumberUpperLimit))
if err != nil {
return nil, fmt.Errorf("serial number generation failed: %w", err)
Expand Down Expand Up @@ -141,12 +141,21 @@ func CreateCert(template, parent *x509.Certificate, privateKey *rsa.PrivateKey,
return &cert, nil
}

func GenerateRootKey() (rootKey *rsa.PrivateKey, err error) {

Check failure on line 144 in runtime-watcher/internal/tlstest/certificate_provider.go

View workflow job for this annotation

GitHub Actions / lint-build-test

named return "rootKey" with type "*rsa.PrivateKey" found (nonamedreturns)
rootKey, err = rsa.GenerateKey(rand.Reader, privateKeyBits)
if err != nil {
return nil, fmt.Errorf("%s: %w", errMsgCreatingPrivateKey, err)
}
return rootKey, nil

Check failure on line 150 in runtime-watcher/internal/tlstest/certificate_provider.go

View workflow job for this annotation

GitHub Actions / lint-build-test

File is not `gofumpt`-ed (gofumpt)
}

Check failure on line 151 in runtime-watcher/internal/tlstest/certificate_provider.go

View workflow job for this annotation

GitHub Actions / lint-build-test

unnecessary trailing newline (whitespace)

func (p *CertProvider) GenerateCerts() error {
rootKey, err := rsa.GenerateKey(rand.Reader, privateKeyBits)
rootKey, err := GenerateRootKey()
if err != nil {
return fmt.Errorf("%s: %w", errMsgCreatingPrivateKey, err)
return err
}
rootTemplate, err := CreateCertTemplate(true)
rootTemplate, err := createCertTemplate(true)
if err != nil {
return err
}
Expand All @@ -163,7 +172,7 @@ func (p *CertProvider) GenerateCerts() error {
if err != nil {
return fmt.Errorf("%s: %w", errMsgCreatingPrivateKey, err)
}
serverTemplate, err := CreateCertTemplate(false)
serverTemplate, err := createCertTemplate(false)
if err != nil {
return err
}
Expand All @@ -177,7 +186,7 @@ func (p *CertProvider) GenerateCerts() error {
if err != nil {
return fmt.Errorf("%s: %w", errMsgCreatingPrivateKey, err)
}
clientTemplate, err := CreateCertTemplate(false)
clientTemplate, err := createCertTemplate(false)
if err != nil {
return err
}
Expand Down

0 comments on commit 2c3bd5b

Please sign in to comment.