secret_for_tls.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package versioned
  14. import (
  15. "crypto/tls"
  16. "fmt"
  17. "io/ioutil"
  18. "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/kubernetes/pkg/kubectl/generate"
  21. "k8s.io/kubernetes/pkg/kubectl/util/hash"
  22. )
  23. // SecretForTLSGeneratorV1 supports stable generation of a TLS secret.
  24. type SecretForTLSGeneratorV1 struct {
  25. // Name is the name of this TLS secret.
  26. Name string
  27. // Key is the path to the user's private key.
  28. Key string
  29. // Cert is the path to the user's public key certificate.
  30. Cert string
  31. // AppendHash; if true, derive a hash from the Secret and append it to the name
  32. AppendHash bool
  33. }
  34. // Ensure it supports the generator pattern that uses parameter injection
  35. var _ generate.Generator = &SecretForTLSGeneratorV1{}
  36. // Ensure it supports the generator pattern that uses parameters specified during construction
  37. var _ generate.StructuredGenerator = &SecretForTLSGeneratorV1{}
  38. // Generate returns a secret using the specified parameters
  39. func (s SecretForTLSGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
  40. err := generate.ValidateParams(s.ParamNames(), genericParams)
  41. if err != nil {
  42. return nil, err
  43. }
  44. delegate := &SecretForTLSGeneratorV1{}
  45. hashParam, found := genericParams["append-hash"]
  46. if found {
  47. hashBool, isBool := hashParam.(bool)
  48. if !isBool {
  49. return nil, fmt.Errorf("expected bool, found :%v", hashParam)
  50. }
  51. delegate.AppendHash = hashBool
  52. delete(genericParams, "append-hash")
  53. }
  54. params := map[string]string{}
  55. for key, value := range genericParams {
  56. strVal, isString := value.(string)
  57. if !isString {
  58. return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
  59. }
  60. params[key] = strVal
  61. }
  62. delegate.Name = params["name"]
  63. delegate.Key = params["key"]
  64. delegate.Cert = params["cert"]
  65. return delegate.StructuredGenerate()
  66. }
  67. // StructuredGenerate outputs a secret object using the configured fields
  68. func (s SecretForTLSGeneratorV1) StructuredGenerate() (runtime.Object, error) {
  69. if err := s.validate(); err != nil {
  70. return nil, err
  71. }
  72. tlsCrt, err := readFile(s.Cert)
  73. if err != nil {
  74. return nil, err
  75. }
  76. tlsKey, err := readFile(s.Key)
  77. if err != nil {
  78. return nil, err
  79. }
  80. if _, err := tls.X509KeyPair(tlsCrt, tlsKey); err != nil {
  81. return nil, fmt.Errorf("failed to load key pair %v", err)
  82. }
  83. // TODO: Add more validation.
  84. // 1. If the certificate contains intermediates, it is a valid chain.
  85. // 2. Format etc.
  86. secret := &v1.Secret{}
  87. secret.Name = s.Name
  88. secret.Type = v1.SecretTypeTLS
  89. secret.Data = map[string][]byte{}
  90. secret.Data[v1.TLSCertKey] = []byte(tlsCrt)
  91. secret.Data[v1.TLSPrivateKeyKey] = []byte(tlsKey)
  92. if s.AppendHash {
  93. h, err := hash.SecretHash(secret)
  94. if err != nil {
  95. return nil, err
  96. }
  97. secret.Name = fmt.Sprintf("%s-%s", secret.Name, h)
  98. }
  99. return secret, nil
  100. }
  101. // readFile just reads a file into a byte array.
  102. func readFile(file string) ([]byte, error) {
  103. b, err := ioutil.ReadFile(file)
  104. if err != nil {
  105. return []byte{}, fmt.Errorf("Cannot read file %v, %v", file, err)
  106. }
  107. return b, nil
  108. }
  109. // ParamNames returns the set of supported input parameters when using the parameter injection generator pattern
  110. func (s SecretForTLSGeneratorV1) ParamNames() []generate.GeneratorParam {
  111. return []generate.GeneratorParam{
  112. {Name: "name", Required: true},
  113. {Name: "key", Required: true},
  114. {Name: "cert", Required: true},
  115. {Name: "append-hash", Required: false},
  116. }
  117. }
  118. // validate validates required fields are set to support structured generation
  119. func (s SecretForTLSGeneratorV1) validate() error {
  120. // TODO: This is not strictly necessary. We can generate a self signed cert
  121. // if no key/cert is given. The only requirement is that we either get both
  122. // or none. See test/e2e/ingress_utils for self signed cert generation.
  123. if len(s.Key) == 0 {
  124. return fmt.Errorf("key must be specified")
  125. }
  126. if len(s.Cert) == 0 {
  127. return fmt.Errorf("certificate must be specified")
  128. }
  129. return nil
  130. }