helpers.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 api
  14. import (
  15. "encoding/base64"
  16. "errors"
  17. "fmt"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "reflect"
  22. "strings"
  23. )
  24. func init() {
  25. sDec, _ := base64.StdEncoding.DecodeString("REDACTED+")
  26. redactedBytes = []byte(string(sDec))
  27. sDec, _ = base64.StdEncoding.DecodeString("DATA+OMITTED")
  28. dataOmittedBytes = []byte(string(sDec))
  29. }
  30. // IsConfigEmpty returns true if the config is empty.
  31. func IsConfigEmpty(config *Config) bool {
  32. return len(config.AuthInfos) == 0 && len(config.Clusters) == 0 && len(config.Contexts) == 0 &&
  33. len(config.CurrentContext) == 0 &&
  34. len(config.Preferences.Extensions) == 0 && !config.Preferences.Colors &&
  35. len(config.Extensions) == 0
  36. }
  37. // MinifyConfig read the current context and uses that to keep only the relevant pieces of config
  38. // This is useful for making secrets based on kubeconfig files
  39. func MinifyConfig(config *Config) error {
  40. if len(config.CurrentContext) == 0 {
  41. return errors.New("current-context must exist in order to minify")
  42. }
  43. currContext, exists := config.Contexts[config.CurrentContext]
  44. if !exists {
  45. return fmt.Errorf("cannot locate context %v", config.CurrentContext)
  46. }
  47. newContexts := map[string]*Context{}
  48. newContexts[config.CurrentContext] = currContext
  49. newClusters := map[string]*Cluster{}
  50. if len(currContext.Cluster) > 0 {
  51. if _, exists := config.Clusters[currContext.Cluster]; !exists {
  52. return fmt.Errorf("cannot locate cluster %v", currContext.Cluster)
  53. }
  54. newClusters[currContext.Cluster] = config.Clusters[currContext.Cluster]
  55. }
  56. newAuthInfos := map[string]*AuthInfo{}
  57. if len(currContext.AuthInfo) > 0 {
  58. if _, exists := config.AuthInfos[currContext.AuthInfo]; !exists {
  59. return fmt.Errorf("cannot locate user %v", currContext.AuthInfo)
  60. }
  61. newAuthInfos[currContext.AuthInfo] = config.AuthInfos[currContext.AuthInfo]
  62. }
  63. config.AuthInfos = newAuthInfos
  64. config.Clusters = newClusters
  65. config.Contexts = newContexts
  66. return nil
  67. }
  68. var (
  69. dataOmittedBytes []byte
  70. redactedBytes []byte
  71. )
  72. // ShortenConfig redacts raw data entries from the config object for a human-readable view.
  73. func ShortenConfig(config *Config) {
  74. // trick json encoder into printing a human-readable string in the raw data
  75. // by base64 decoding what we want to print. Relies on implementation of
  76. // http://golang.org/pkg/encoding/json/#Marshal using base64 to encode []byte
  77. for key, authInfo := range config.AuthInfos {
  78. if len(authInfo.ClientKeyData) > 0 {
  79. authInfo.ClientKeyData = dataOmittedBytes
  80. }
  81. if len(authInfo.ClientCertificateData) > 0 {
  82. authInfo.ClientCertificateData = dataOmittedBytes
  83. }
  84. if len(authInfo.Token) > 0 {
  85. authInfo.Token = "REDACTED"
  86. }
  87. config.AuthInfos[key] = authInfo
  88. }
  89. for key, cluster := range config.Clusters {
  90. if len(cluster.CertificateAuthorityData) > 0 {
  91. cluster.CertificateAuthorityData = dataOmittedBytes
  92. }
  93. config.Clusters[key] = cluster
  94. }
  95. }
  96. // FlattenConfig changes the config object into a self-contained config (useful for making secrets)
  97. func FlattenConfig(config *Config) error {
  98. for key, authInfo := range config.AuthInfos {
  99. baseDir, err := MakeAbs(path.Dir(authInfo.LocationOfOrigin), "")
  100. if err != nil {
  101. return err
  102. }
  103. if err := FlattenContent(&authInfo.ClientCertificate, &authInfo.ClientCertificateData, baseDir); err != nil {
  104. return err
  105. }
  106. if err := FlattenContent(&authInfo.ClientKey, &authInfo.ClientKeyData, baseDir); err != nil {
  107. return err
  108. }
  109. config.AuthInfos[key] = authInfo
  110. }
  111. for key, cluster := range config.Clusters {
  112. baseDir, err := MakeAbs(path.Dir(cluster.LocationOfOrigin), "")
  113. if err != nil {
  114. return err
  115. }
  116. if err := FlattenContent(&cluster.CertificateAuthority, &cluster.CertificateAuthorityData, baseDir); err != nil {
  117. return err
  118. }
  119. config.Clusters[key] = cluster
  120. }
  121. return nil
  122. }
  123. func FlattenContent(path *string, contents *[]byte, baseDir string) error {
  124. if len(*path) != 0 {
  125. if len(*contents) > 0 {
  126. return errors.New("cannot have values for both path and contents")
  127. }
  128. var err error
  129. absPath := ResolvePath(*path, baseDir)
  130. *contents, err = os.ReadFile(absPath)
  131. if err != nil {
  132. return err
  133. }
  134. *path = ""
  135. }
  136. return nil
  137. }
  138. // ResolvePath returns the path as an absolute paths, relative to the given base directory
  139. func ResolvePath(path string, base string) string {
  140. // Don't resolve empty paths
  141. if len(path) > 0 {
  142. // Don't resolve absolute paths
  143. if !filepath.IsAbs(path) {
  144. return filepath.Join(base, path)
  145. }
  146. }
  147. return path
  148. }
  149. func MakeAbs(path, base string) (string, error) {
  150. if filepath.IsAbs(path) {
  151. return path, nil
  152. }
  153. if len(base) == 0 {
  154. cwd, err := os.Getwd()
  155. if err != nil {
  156. return "", err
  157. }
  158. base = cwd
  159. }
  160. return filepath.Join(base, path), nil
  161. }
  162. // RedactSecrets replaces any sensitive values with REDACTED
  163. func RedactSecrets(config *Config) error {
  164. return redactSecrets(reflect.ValueOf(config), false)
  165. }
  166. func redactSecrets(curr reflect.Value, redact bool) error {
  167. redactedBytes = []byte("REDACTED")
  168. if !curr.IsValid() {
  169. return nil
  170. }
  171. actualCurrValue := curr
  172. if curr.Kind() == reflect.Ptr {
  173. actualCurrValue = curr.Elem()
  174. }
  175. switch actualCurrValue.Kind() {
  176. case reflect.Map:
  177. for _, v := range actualCurrValue.MapKeys() {
  178. err := redactSecrets(actualCurrValue.MapIndex(v), false)
  179. if err != nil {
  180. return err
  181. }
  182. }
  183. return nil
  184. case reflect.String:
  185. if redact {
  186. if !actualCurrValue.IsZero() {
  187. actualCurrValue.SetString("REDACTED")
  188. }
  189. }
  190. return nil
  191. case reflect.Slice:
  192. if actualCurrValue.Type() == reflect.TypeOf([]byte{}) && redact {
  193. if !actualCurrValue.IsNil() {
  194. actualCurrValue.SetBytes(redactedBytes)
  195. }
  196. return nil
  197. }
  198. for i := 0; i < actualCurrValue.Len(); i++ {
  199. err := redactSecrets(actualCurrValue.Index(i), false)
  200. if err != nil {
  201. return err
  202. }
  203. }
  204. return nil
  205. case reflect.Struct:
  206. for fieldIndex := 0; fieldIndex < actualCurrValue.NumField(); fieldIndex++ {
  207. currFieldValue := actualCurrValue.Field(fieldIndex)
  208. currFieldType := actualCurrValue.Type().Field(fieldIndex)
  209. currYamlTag := currFieldType.Tag.Get("datapolicy")
  210. currFieldTypeYamlName := strings.Split(currYamlTag, ",")[0]
  211. if currFieldTypeYamlName != "" {
  212. err := redactSecrets(currFieldValue, true)
  213. if err != nil {
  214. return err
  215. }
  216. } else {
  217. err := redactSecrets(currFieldValue, false)
  218. if err != nil {
  219. return err
  220. }
  221. }
  222. }
  223. return nil
  224. default:
  225. return nil
  226. }
  227. }