secret.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "strings"
  20. "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/util/validation"
  23. "k8s.io/kubernetes/pkg/kubectl/generate"
  24. "k8s.io/kubernetes/pkg/kubectl/util"
  25. "k8s.io/kubernetes/pkg/kubectl/util/hash"
  26. )
  27. // SecretGeneratorV1 supports stable generation of an opaque secret
  28. type SecretGeneratorV1 struct {
  29. // Name of secret (required)
  30. Name string
  31. // Type of secret (optional)
  32. Type string
  33. // FileSources to derive the secret from (optional)
  34. FileSources []string
  35. // LiteralSources to derive the secret from (optional)
  36. LiteralSources []string
  37. // EnvFileSource to derive the secret from (optional)
  38. EnvFileSource string
  39. // AppendHash; if true, derive a hash from the Secret data and type and append it to the name
  40. AppendHash bool
  41. }
  42. // Ensure it supports the generator pattern that uses parameter injection
  43. var _ generate.Generator = &SecretGeneratorV1{}
  44. // Ensure it supports the generator pattern that uses parameters specified during construction
  45. var _ generate.StructuredGenerator = &SecretGeneratorV1{}
  46. // Generate returns a secret using the specified parameters
  47. func (s SecretGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
  48. err := generate.ValidateParams(s.ParamNames(), genericParams)
  49. if err != nil {
  50. return nil, err
  51. }
  52. delegate := &SecretGeneratorV1{}
  53. fromFileStrings, found := genericParams["from-file"]
  54. if found {
  55. fromFileArray, isArray := fromFileStrings.([]string)
  56. if !isArray {
  57. return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
  58. }
  59. delegate.FileSources = fromFileArray
  60. delete(genericParams, "from-file")
  61. }
  62. fromLiteralStrings, found := genericParams["from-literal"]
  63. if found {
  64. fromLiteralArray, isArray := fromLiteralStrings.([]string)
  65. if !isArray {
  66. return nil, fmt.Errorf("expected []string, found :%v", fromLiteralStrings)
  67. }
  68. delegate.LiteralSources = fromLiteralArray
  69. delete(genericParams, "from-literal")
  70. }
  71. fromEnvFileString, found := genericParams["from-env-file"]
  72. if found {
  73. fromEnvFile, isString := fromEnvFileString.(string)
  74. if !isString {
  75. return nil, fmt.Errorf("expected string, found :%v", fromEnvFileString)
  76. }
  77. delegate.EnvFileSource = fromEnvFile
  78. delete(genericParams, "from-env-file")
  79. }
  80. hashParam, found := genericParams["append-hash"]
  81. if found {
  82. hashBool, isBool := hashParam.(bool)
  83. if !isBool {
  84. return nil, fmt.Errorf("expected bool, found :%v", hashParam)
  85. }
  86. delegate.AppendHash = hashBool
  87. delete(genericParams, "append-hash")
  88. }
  89. params := map[string]string{}
  90. for key, value := range genericParams {
  91. strVal, isString := value.(string)
  92. if !isString {
  93. return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
  94. }
  95. params[key] = strVal
  96. }
  97. delegate.Name = params["name"]
  98. delegate.Type = params["type"]
  99. return delegate.StructuredGenerate()
  100. }
  101. // ParamNames returns the set of supported input parameters when using the parameter injection generator pattern
  102. func (s SecretGeneratorV1) ParamNames() []generate.GeneratorParam {
  103. return []generate.GeneratorParam{
  104. {Name: "name", Required: true},
  105. {Name: "type", Required: false},
  106. {Name: "from-file", Required: false},
  107. {Name: "from-literal", Required: false},
  108. {Name: "from-env-file", Required: false},
  109. {Name: "force", Required: false},
  110. {Name: "append-hash", Required: false},
  111. }
  112. }
  113. // StructuredGenerate outputs a secret object using the configured fields
  114. func (s SecretGeneratorV1) StructuredGenerate() (runtime.Object, error) {
  115. if err := s.validate(); err != nil {
  116. return nil, err
  117. }
  118. secret := &v1.Secret{}
  119. secret.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("Secret"))
  120. secret.Name = s.Name
  121. secret.Data = map[string][]byte{}
  122. if len(s.Type) > 0 {
  123. secret.Type = v1.SecretType(s.Type)
  124. }
  125. if len(s.FileSources) > 0 {
  126. if err := handleFromFileSources(secret, s.FileSources); err != nil {
  127. return nil, err
  128. }
  129. }
  130. if len(s.LiteralSources) > 0 {
  131. if err := handleFromLiteralSources(secret, s.LiteralSources); err != nil {
  132. return nil, err
  133. }
  134. }
  135. if len(s.EnvFileSource) > 0 {
  136. if err := handleFromEnvFileSource(secret, s.EnvFileSource); err != nil {
  137. return nil, err
  138. }
  139. }
  140. if s.AppendHash {
  141. h, err := hash.SecretHash(secret)
  142. if err != nil {
  143. return nil, err
  144. }
  145. secret.Name = fmt.Sprintf("%s-%s", secret.Name, h)
  146. }
  147. return secret, nil
  148. }
  149. // validate validates required fields are set to support structured generation
  150. func (s SecretGeneratorV1) validate() error {
  151. if len(s.Name) == 0 {
  152. return fmt.Errorf("name must be specified")
  153. }
  154. if len(s.EnvFileSource) > 0 && (len(s.FileSources) > 0 || len(s.LiteralSources) > 0) {
  155. return fmt.Errorf("from-env-file cannot be combined with from-file or from-literal")
  156. }
  157. return nil
  158. }
  159. // handleFromLiteralSources adds the specified literal source information into the provided secret
  160. func handleFromLiteralSources(secret *v1.Secret, literalSources []string) error {
  161. for _, literalSource := range literalSources {
  162. keyName, value, err := util.ParseLiteralSource(literalSource)
  163. if err != nil {
  164. return err
  165. }
  166. if err = addKeyFromLiteralToSecret(secret, keyName, []byte(value)); err != nil {
  167. return err
  168. }
  169. }
  170. return nil
  171. }
  172. // handleFromFileSources adds the specified file source information into the provided secret
  173. func handleFromFileSources(secret *v1.Secret, fileSources []string) error {
  174. for _, fileSource := range fileSources {
  175. keyName, filePath, err := util.ParseFileSource(fileSource)
  176. if err != nil {
  177. return err
  178. }
  179. info, err := os.Stat(filePath)
  180. if err != nil {
  181. switch err := err.(type) {
  182. case *os.PathError:
  183. return fmt.Errorf("error reading %s: %v", filePath, err.Err)
  184. default:
  185. return fmt.Errorf("error reading %s: %v", filePath, err)
  186. }
  187. }
  188. if info.IsDir() {
  189. if strings.Contains(fileSource, "=") {
  190. return fmt.Errorf("cannot give a key name for a directory path")
  191. }
  192. fileList, err := ioutil.ReadDir(filePath)
  193. if err != nil {
  194. return fmt.Errorf("error listing files in %s: %v", filePath, err)
  195. }
  196. for _, item := range fileList {
  197. itemPath := path.Join(filePath, item.Name())
  198. if item.Mode().IsRegular() {
  199. keyName = item.Name()
  200. if err = addKeyFromFileToSecret(secret, keyName, itemPath); err != nil {
  201. return err
  202. }
  203. }
  204. }
  205. } else {
  206. if err := addKeyFromFileToSecret(secret, keyName, filePath); err != nil {
  207. return err
  208. }
  209. }
  210. }
  211. return nil
  212. }
  213. // handleFromEnvFileSource adds the specified env file source information
  214. // into the provided secret
  215. func handleFromEnvFileSource(secret *v1.Secret, envFileSource string) error {
  216. info, err := os.Stat(envFileSource)
  217. if err != nil {
  218. switch err := err.(type) {
  219. case *os.PathError:
  220. return fmt.Errorf("error reading %s: %v", envFileSource, err.Err)
  221. default:
  222. return fmt.Errorf("error reading %s: %v", envFileSource, err)
  223. }
  224. }
  225. if info.IsDir() {
  226. return fmt.Errorf("env secret file cannot be a directory")
  227. }
  228. return addFromEnvFile(envFileSource, func(key, value string) error {
  229. return addKeyFromLiteralToSecret(secret, key, []byte(value))
  230. })
  231. }
  232. func addKeyFromFileToSecret(secret *v1.Secret, keyName, filePath string) error {
  233. data, err := ioutil.ReadFile(filePath)
  234. if err != nil {
  235. return err
  236. }
  237. return addKeyFromLiteralToSecret(secret, keyName, data)
  238. }
  239. func addKeyFromLiteralToSecret(secret *v1.Secret, keyName string, data []byte) error {
  240. if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
  241. return fmt.Errorf("%q is not a valid key name for a Secret: %s", keyName, strings.Join(errs, ";"))
  242. }
  243. if _, entryExists := secret.Data[keyName]; entryExists {
  244. return fmt.Errorf("cannot add key %s, another key by that name already exists", keyName)
  245. }
  246. secret.Data[keyName] = data
  247. return nil
  248. }