helpers.go 6.8 KB

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