init.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 secrets
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. )
  21. // Secret define sensitive data to be bound as file
  22. type Secret struct {
  23. Name string
  24. Keys []string
  25. }
  26. // CreateSecretFiles retrieve sensitive data from env and store as plain text a a file in path
  27. func CreateSecretFiles(secret Secret, path string) error {
  28. value, ok := os.LookupEnv(secret.Name)
  29. if !ok {
  30. return fmt.Errorf("%q variable not set", secret.Name)
  31. }
  32. secrets := filepath.Join(path, secret.Name)
  33. if len(secret.Keys) == 0 {
  34. // raw Secret
  35. fmt.Printf("inject Secret %q info %s\n", secret.Name, secrets)
  36. return ioutil.WriteFile(secrets, []byte(value), 0444)
  37. }
  38. var unmarshalled interface{}
  39. err := json.Unmarshal([]byte(value), &unmarshalled)
  40. if err != nil {
  41. return fmt.Errorf("%q Secret is not a valid JSON document: %w", secret.Name, err)
  42. }
  43. dict, ok := unmarshalled.(map[string]interface{})
  44. if !ok {
  45. return fmt.Errorf("%q Secret is not a JSON dictionary: %w", secret.Name, err)
  46. }
  47. err = os.MkdirAll(secrets, 0755)
  48. if err != nil {
  49. return err
  50. }
  51. if contains(secret.Keys, "*") {
  52. var keys []string
  53. for k := range dict {
  54. keys = append(keys, k)
  55. }
  56. secret.Keys = keys
  57. }
  58. for _, k := range secret.Keys {
  59. path := filepath.Join(secrets, k)
  60. fmt.Printf("inject Secret %q info %s\n", k, path)
  61. v, ok := dict[k]
  62. if !ok {
  63. return fmt.Errorf("%q Secret has no %q key", secret.Name, k)
  64. }
  65. var raw []byte
  66. if s, ok := v.(string); ok {
  67. raw = []byte(s)
  68. } else {
  69. raw, err = json.Marshal(v)
  70. if err != nil {
  71. return err
  72. }
  73. }
  74. err = ioutil.WriteFile(path, raw, 0444)
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. return nil
  80. }
  81. func contains(keys []string, s string) bool {
  82. for _, k := range keys {
  83. if k == s {
  84. return true
  85. }
  86. }
  87. return false
  88. }