Skip to content

Commit

Permalink
Merge pull request #157 from AbelHu/abel/refine-test-data
Browse files Browse the repository at this point in the history
Generate test cert/key dynamically
  • Loading branch information
k8s-ci-robot authored Oct 23, 2024
2 parents 4a5c843 + 99c47ca commit c20b664
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 81 deletions.
1 change: 1 addition & 0 deletions admission-webhook/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/dev/
/integration_tests/tmp/
/vendor/
/testdata/
7 changes: 7 additions & 0 deletions admission-webhook/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,10 @@ func Test_env_bool(t *testing.T) {
os.Setenv(envkey, envVal)
env_bool("TEST_ENV_BOOL")
}

func TestMain(m *testing.M) {
GenerateTestCertAndKey()
code := m.Run() // run tests
ClearTestdata()
os.Exit(code)
}
29 changes: 0 additions & 29 deletions admission-webhook/testdata/cert.pem

This file was deleted.

52 changes: 0 additions & 52 deletions admission-webhook/testdata/key.pem

This file was deleted.

60 changes: 60 additions & 0 deletions admission-webhook/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ package main

import (
"context"
crand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"math/rand"
"os"
"time"

corev1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -106,3 +113,56 @@ func shuffleContainers(a []corev1.Container) {
a[i] = tmp
}
}

func GenerateTestCertAndKey() {
// Generate a 2048-bit RSA private key
priv, err := rsa.GenerateKey(crand.Reader, 2048)
if err != nil {
panic(err)
}

// Create a certificate template
certTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"test"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0), // Valid for 1 year
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}

// Create the certificate
certDER, err := x509.CreateCertificate(crand.Reader, certTemplate, certTemplate, &priv.PublicKey, priv)
if err != nil {
panic(err)
}

err = os.Mkdir("testdata", 0755)
if err != nil {
panic(err)
}

// Write the certificate to a PEM file
certFile, err := os.Create("testdata/cert.pem")
if err != nil {
panic(err)
}
pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})
certFile.Close()

// Write the private key to a PEM file
keyFile, err := os.Create("testdata/key.pem")
if err != nil {
panic(err)
}
keyBytes := x509.MarshalPKCS1PrivateKey(priv)
pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes})
keyFile.Close()
}

func ClearTestdata() {
os.RemoveAll("testdata")
}

0 comments on commit c20b664

Please sign in to comment.