key_provider_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package kp
  2. import (
  3. "os"
  4. "testing"
  5. "github.com/cloudflare/cfssl/csr"
  6. "github.com/cloudflare/cfssl/transport/core"
  7. )
  8. const (
  9. testKey = "testdata/test.key"
  10. testCert = "testdata/test.pem"
  11. )
  12. var testIdentity = &core.Identity{
  13. Request: &csr.CertificateRequest{
  14. CN: "localhost test certificate",
  15. },
  16. Profiles: map[string]map[string]string{
  17. "paths": {
  18. "private_key": testKey,
  19. "certificate": testCert,
  20. },
  21. },
  22. }
  23. func removeIfPresent(path string) error {
  24. if _, err := os.Stat(path); !os.IsNotExist(err) {
  25. return os.Remove(path)
  26. }
  27. return nil
  28. }
  29. func TestMain(m *testing.M) {
  30. exitCode := m.Run()
  31. err := removeIfPresent(testKey)
  32. if err == nil {
  33. err = removeIfPresent(testCert)
  34. }
  35. if err != nil {
  36. os.Exit(1)
  37. }
  38. os.Exit(exitCode)
  39. }
  40. var kp KeyProvider
  41. func TestNewStandardProvider(t *testing.T) {
  42. var err error
  43. kp, err = NewStandardProvider(testIdentity)
  44. if err != nil {
  45. t.Fatalf("%v", err)
  46. }
  47. if kp.Ready() {
  48. t.Fatalf("key provider should not be ready yet")
  49. }
  50. if err = kp.Check(); err != nil {
  51. t.Fatalf("calling check should return no error")
  52. }
  53. if nil != kp.Certificate() {
  54. t.Fatal("key provider should not have a certificate yet")
  55. }
  56. if kp.Ready() {
  57. t.Fatal("key provider should not be ready")
  58. }
  59. if !kp.Persistent() {
  60. t.Fatal("key provider should be persistent")
  61. }
  62. }
  63. func TestGenerate(t *testing.T) {
  64. err := kp.Load()
  65. if err == nil {
  66. t.Fatal("key provider shouldn't have a key yet")
  67. }
  68. err = kp.Generate("rsa", 2048)
  69. if err != nil {
  70. t.Fatalf("key provider couldn't generate key: %v", err)
  71. }
  72. err = kp.Generate("ecdsa", 256)
  73. if err != nil {
  74. t.Fatalf("key provider couldn't generate key: %v", err)
  75. }
  76. err = kp.Generate("ed25519", 256) // ed25519 key size is ignored
  77. if err != nil {
  78. t.Fatalf("key provider couldn't generate key: %v", err)
  79. }
  80. }