Files
go-sip/cmd/sip-go-agent/current_tls_test.go
T

68 lines
2.3 KiB
Go

package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"testing"
"time"
)
// localCommandCertificates creates isolated fixtures for both command-line
// roles. No certificate or key is stored outside the test's temporary files.
func localCommandCertificates(t *testing.T) (ca, agentCert, agentKey, dispatcherCert, dispatcherKey []byte, dispatcherLeaf *x509.Certificate) {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
now := time.Now()
root := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "isolated test root"},
NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour),
IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
}
rootDER, err := x509.CreateCertificate(rand.Reader, root, root, &caKey.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
root, err = x509.ParseCertificate(rootDER)
if err != nil {
t.Fatal(err)
}
ca = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootDER})
issue := func(serial int64, dns string) ([]byte, []byte, *x509.Certificate) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: dns},
NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour), DNSNames: []string{dns},
BasicConstraintsValid: true, KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, root, &key.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
parsed, err := x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
privateDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privateDER}), parsed
}
agentCert, agentKey, _ = issue(2, "agent.local")
dispatcherCert, dispatcherKey, dispatcherLeaf = issue(3, "dispatcher.local")
return
}