tlsconfig_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package tlsconfig
  2. import (
  3. "crypto/tls"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. // testcert.pem and testcert2.pem are Generated using `openssl req -newkey rsa:512 -nodes -x509 -days 3650`
  8. const (
  9. testcertCommonName = "localhost"
  10. )
  11. func TestGetFromEmptyConfig(t *testing.T) {
  12. c := &TLSParameters{}
  13. tlsConfig, err := GetConfig(c)
  14. assert.NoError(t, err)
  15. assert.Empty(t, tlsConfig.Certificates)
  16. assert.Empty(t, tlsConfig.NameToCertificate)
  17. assert.Nil(t, tlsConfig.ClientCAs)
  18. assert.Equal(t, tls.NoClientCert, tlsConfig.ClientAuth)
  19. assert.Nil(t, tlsConfig.RootCAs)
  20. assert.Len(t, tlsConfig.CurvePreferences, 1)
  21. assert.Equal(t, tls.CurveP256, tlsConfig.CurvePreferences[0])
  22. }
  23. func TestGetConfig(t *testing.T) {
  24. cert, err := tls.LoadX509KeyPair("testcert.pem", "testkey.pem")
  25. assert.NoError(t, err)
  26. c := &TLSParameters{
  27. Cert: "testcert.pem",
  28. Key: "testkey.pem",
  29. ClientCAs: []string{"testcert.pem", "testcert2.pem"},
  30. RootCAs: []string{"testcert.pem", "testcert2.pem"},
  31. ServerName: "test",
  32. CurvePreferences: []tls.CurveID{tls.CurveP384},
  33. }
  34. tlsConfig, err := GetConfig(c)
  35. assert.NoError(t, err)
  36. assert.Len(t, tlsConfig.Certificates, 1)
  37. assert.Equal(t, cert, tlsConfig.Certificates[0])
  38. assert.Equal(t, cert, *tlsConfig.NameToCertificate[testcertCommonName])
  39. assert.NotNil(t, tlsConfig.ClientCAs)
  40. assert.Equal(t, tls.RequireAndVerifyClientCert, tlsConfig.ClientAuth)
  41. assert.NotNil(t, tlsConfig.RootCAs)
  42. assert.Len(t, tlsConfig.CurvePreferences, 1)
  43. assert.Equal(t, tls.CurveP384, tlsConfig.CurvePreferences[0])
  44. }
  45. func TestCertReloader(t *testing.T) {
  46. expectedCert, err := tls.LoadX509KeyPair("testcert.pem", "testkey.pem")
  47. assert.NoError(t, err)
  48. certReloader, err := NewCertReloader("testcert.pem", "testkey.pem")
  49. assert.NoError(t, err)
  50. chi := &tls.ClientHelloInfo{ServerName: testcertCommonName}
  51. cert, err := certReloader.Cert(chi)
  52. assert.NoError(t, err)
  53. assert.Equal(t, expectedCert, *cert)
  54. c := &TLSParameters{
  55. GetCertificate: certReloader,
  56. }
  57. tlsConfig, err := GetConfig(c)
  58. assert.NoError(t, err)
  59. cert, err = tlsConfig.GetCertificate(chi)
  60. assert.NoError(t, err)
  61. assert.Equal(t, expectedCert, *cert)
  62. }