1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
|
package tlsutil
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"math/big"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"go.step.sm/crypto/x509util"
)
func testServerRenewFunc(hello *tls.ClientHelloInfo) (*tls.Certificate, *tls.Config, error) {
var err error
leafCert.NotBefore = time.Now()
leafCert.DNSNames, leafCert.IPAddresses, leafCert.EmailAddresses, leafCert.URIs = x509util.SplitSANs([]string{hello.ServerName})
leafCert.NotAfter = leafCert.NotBefore.Add(time.Hour)
leafCert.SerialNumber = leafCert.SerialNumber.Add(leafCert.SerialNumber, big.NewInt(1))
leafCert, err = x509util.CreateCertificate(leafCert, issuerCert, leafKey.Public(), issuerKey)
if err != nil {
return nil, nil, err
}
return &tls.Certificate{
Certificate: [][]byte{leafCert.Raw},
PrivateKey: leafKey,
Leaf: leafCert,
}, tlsConfig, nil
}
func TestNewServerCredentials(t *testing.T) {
type args struct {
fn ServerRenewFunc
}
tests := []struct {
name string
args args
want *ServerCredentials
wantErr bool
}{
{"ok", args{testServerRenewFunc}, &ServerCredentials{RenewFunc: testServerRenewFunc, cache: newCredentialsCache()}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewServerCredentials(tt.args.fn)
if (err != nil) != tt.wantErr {
t.Errorf("NewServerCredentials() error = %v, wantErr %v", err, tt.wantErr)
return
}
// Cannot deep equal methods
if got != nil {
got.RenewFunc = nil
}
if tt.want != nil {
tt.want.RenewFunc = nil
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewServerCredentials() = %v, want %v", got, tt.want)
}
})
}
}
func TestNewServerCredentialsFromFile(t *testing.T) {
dir := t.TempDir()
certFile := filepath.Join(dir, "testcert.crt")
keyFile := filepath.Join(dir, "testcert.key")
if err := os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: leafCert.Raw,
}), 0600); err != nil {
t.Fatal(err)
}
keyBytes, err := x509.MarshalPKCS8PrivateKey(leafKey)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: keyBytes,
}), 0600); err != nil {
t.Fatal(err)
}
type args struct {
certFile string
keyFile string
}
tests := []struct {
name string
args args
wantCert *tls.Certificate
wantErr bool
}{
{"ok", args{certFile, keyFile}, &tls.Certificate{
Certificate: [][]byte{leafCert.Raw},
PrivateKey: leafKey,
Leaf: leafCert,
}, false},
{"fail", args{certFile, filepath.Join(dir, "missing.key")}, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewServerCredentialsFromFile(tt.args.certFile, tt.args.keyFile)
if (err != nil) != tt.wantErr {
t.Errorf("NewServerCredentialsFromFile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantCert != nil {
cert, err := got.GetCertificate(&tls.ClientHelloInfo{ServerName: "localhost"})
if err != nil {
t.Errorf("GetCertificate() error = %v", err)
return
}
if !reflect.DeepEqual(cert, tt.wantCert) {
t.Errorf("GetCertificate() = \n%v, want \n%v", cert, tt.wantCert)
}
}
})
}
}
func TestServerCredentials_GetCertificate(t *testing.T) {
// Prepare server
sc, err := NewServerCredentials(testServerRenewFunc)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ok")
}))
srv.TLS = &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: sc.GetCertificate,
}
srv.StartTLS()
// We need to set Certificates to nil, because if the hello message does not
// have a SNI, this certificate will be used.
srv.TLS.Certificates = nil
defer srv.Close()
// Create url with localhost
dnsURL := getLocalHostURL(t, srv.URL)
// Prepare valid client
pool := x509.NewCertPool()
pool.AddCert(issuerCert)
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: pool,
}
tests := []struct {
name string
client *http.Client
url string
want []byte
wantErr bool
}{
{"ok", &http.Client{Transport: tr}, dnsURL, []byte("ok"), false},
{"fail empty", &http.Client{}, dnsURL, nil, true},
{"fail httptest", srv.Client(), dnsURL, nil, true},
{"fail ip", &http.Client{Transport: tr}, srv.URL, nil, true},
{"fail httptest ip", srv.Client(), srv.URL, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := tt.client.Get(tt.url)
if (err != nil) != tt.wantErr {
t.Errorf("http.Client.Get() error = %v, wantErr %v", err, tt.wantErr)
return
}
if resp != nil && resp.Body != nil {
got, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("io.ReadAll() error = %v", err)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("http.Client.Get() = %v, want %v", got, tt.want)
}
}
})
}
}
func TestServerCredentials_GetConfigForClient(t *testing.T) {
// Prepare server
sc, err := NewServerCredentials(testServerRenewFunc)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ok")
}))
srv.TLS = &tls.Config{
MinVersion: tls.VersionTLS12,
GetConfigForClient: sc.GetConfigForClient,
}
srv.StartTLS()
// We need to set Certificates to nil, because if the hello message does not
// have a SNI, this certificate will be used.
srv.TLS.Certificates = nil
defer srv.Close()
// Create url with localhost
dnsURL := getLocalHostURL(t, srv.URL)
// Prepare valid client
pool := x509.NewCertPool()
pool.AddCert(issuerCert)
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: pool,
}
tests := []struct {
name string
client *http.Client
url string
want []byte
wantErr bool
}{
{"ok", &http.Client{Transport: tr}, dnsURL, []byte("ok"), false},
{"fail empty", &http.Client{}, dnsURL, nil, true},
{"fail httptest", srv.Client(), dnsURL, nil, true},
{"fail ip", &http.Client{Transport: tr}, srv.URL, nil, true},
{"fail httptest ip", srv.Client(), srv.URL, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := tt.client.Get(tt.url)
if (err != nil) != tt.wantErr {
t.Errorf("http.Client.Get() error = %v, wantErr %v", err, tt.wantErr)
return
}
if resp != nil && resp.Body != nil {
got, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("io.ReadAll() error = %v", err)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("http.Client.Get() = %v, want %v", got, tt.want)
}
}
})
}
}
func TestServerCredentials_RenewFunc_error(t *testing.T) {
// Prepare server
sc, err := NewServerCredentials(func(hello *tls.ClientHelloInfo) (*tls.Certificate, *tls.Config, error) {
return nil, nil, fmt.Errorf("test error")
})
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
tlsConfig *tls.Config
}{
{"fail GetCertificate", &tls.Config{GetCertificate: sc.GetCertificate, MinVersion: tls.VersionTLS12}},
{"fail GetConfigForClient", &tls.Config{GetConfigForClient: sc.GetConfigForClient, MinVersion: tls.VersionTLS12}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ok")
}))
srv.TLS = tt.tlsConfig
srv.StartTLS()
defer srv.Close()
// Prepare valid client
pool := x509.NewCertPool()
pool.AddCert(issuerCert)
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: pool,
}
c := &http.Client{Transport: tr}
if _, err := c.Get(getLocalHostURL(t, srv.URL)); err == nil {
t.Errorf("http.Client.Get() error = %v, wantErr true", err)
}
})
}
}
func TestServerCredentials_TLSConfig(t *testing.T) {
sc, err := NewServerCredentials(testServerRenewFunc)
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
serverCredentials *ServerCredentials
want *tls.Config
}{
{"ok", sc, &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: sc.GetCertificate,
GetConfigForClient: sc.GetConfigForClient,
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.serverCredentials.TLSConfig()
if got.GetCertificate == nil || got.GetConfigForClient == nil {
t.Errorf("ServerCredentials.TLSConfig() = \n%#v, want \n%#v", got, tt.want)
}
})
}
}
|