config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package kubernetes
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "regexp"
  6. "strings"
  7. "time"
  8. "github.com/porter-dev/porter/internal/models"
  9. "github.com/porter-dev/porter/internal/repository"
  10. "k8s.io/apimachinery/pkg/api/meta"
  11. "k8s.io/apimachinery/pkg/runtime"
  12. "k8s.io/cli-runtime/pkg/genericclioptions"
  13. "k8s.io/client-go/discovery"
  14. diskcached "k8s.io/client-go/discovery/cached/disk"
  15. "k8s.io/client-go/kubernetes"
  16. "k8s.io/client-go/kubernetes/fake"
  17. "k8s.io/client-go/rest"
  18. "k8s.io/client-go/restmapper"
  19. "k8s.io/client-go/tools/clientcmd"
  20. "k8s.io/client-go/tools/clientcmd/api"
  21. "k8s.io/client-go/util/homedir"
  22. ints "github.com/porter-dev/porter/internal/models/integrations"
  23. // this line will register plugins
  24. _ "k8s.io/client-go/plugin/pkg/client/auth"
  25. )
  26. // GetAgentOutOfClusterConfig creates a new Agent using the OutOfClusterConfig
  27. func GetAgentOutOfClusterConfig(conf *OutOfClusterConfig) (*Agent, error) {
  28. restConf, err := conf.ToRESTConfig()
  29. if err != nil {
  30. return nil, err
  31. }
  32. clientset, err := kubernetes.NewForConfig(restConf)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &Agent{conf, clientset}, nil
  37. }
  38. // GetAgentInClusterConfig uses the service account that kubernetes
  39. // gives to pods to connect
  40. func GetAgentInClusterConfig() (*Agent, error) {
  41. conf, err := rest.InClusterConfig()
  42. if err != nil {
  43. return nil, err
  44. }
  45. restClientGetter := newRESTClientGetterFromInClusterConfig(conf)
  46. clientset, err := kubernetes.NewForConfig(conf)
  47. return &Agent{restClientGetter, clientset}, nil
  48. }
  49. // GetAgentTesting creates a new Agent using an optional existing storage class
  50. func GetAgentTesting(objects ...runtime.Object) *Agent {
  51. return &Agent{&fakeRESTClientGetter{}, fake.NewSimpleClientset(objects...)}
  52. }
  53. // OutOfClusterConfig is the set of parameters required for an out-of-cluster connection.
  54. // This implements RESTClientGetter
  55. type OutOfClusterConfig struct {
  56. Cluster *models.Cluster
  57. Repo *repository.Repository
  58. }
  59. // ToRESTConfig creates a kubernetes REST client factory -- it calls ClientConfig on
  60. // the result of ToRawKubeConfigLoader, and also adds a custom http transport layer
  61. // if necessary (required for GCP auth)
  62. func (conf *OutOfClusterConfig) ToRESTConfig() (*rest.Config, error) {
  63. restConf, err := conf.ToRawKubeConfigLoader().ClientConfig()
  64. if err != nil {
  65. return nil, err
  66. }
  67. rest.SetKubernetesDefaults(restConf)
  68. return restConf, nil
  69. }
  70. // ToRawKubeConfigLoader creates a clientcmd.ClientConfig from the raw kubeconfig found in
  71. // the OutOfClusterConfig. It does not implement loading rules or overrides.
  72. func (conf *OutOfClusterConfig) ToRawKubeConfigLoader() clientcmd.ClientConfig {
  73. cmdConf, _ := conf.GetClientConfigFromCluster()
  74. return cmdConf
  75. }
  76. // ToDiscoveryClient returns a CachedDiscoveryInterface using a computed RESTConfig
  77. // It's required to implement the interface genericclioptions.RESTClientGetter
  78. func (conf *OutOfClusterConfig) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
  79. // From: k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go > func (*configFlags) ToDiscoveryClient()
  80. restConf, err := conf.ToRESTConfig()
  81. if err != nil {
  82. return nil, err
  83. }
  84. restConf.Burst = 100
  85. defaultHTTPCacheDir := filepath.Join(homedir.HomeDir(), ".kube", "http-cache")
  86. // takes the parentDir and the host and comes up with a "usually non-colliding" name for the discoveryCacheDir
  87. parentDir := filepath.Join(homedir.HomeDir(), ".kube", "cache", "discovery")
  88. // strip the optional scheme from host if its there:
  89. schemelessHost := strings.Replace(strings.Replace(restConf.Host, "https://", "", 1), "http://", "", 1)
  90. // now do a simple collapse of non-AZ09 characters. Collisions are possible but unlikely. Even if we do collide the problem is short lived
  91. safeHost := regexp.MustCompile(`[^(\w/\.)]`).ReplaceAllString(schemelessHost, "_")
  92. discoveryCacheDir := filepath.Join(parentDir, safeHost)
  93. return diskcached.NewCachedDiscoveryClientForConfig(restConf, discoveryCacheDir, defaultHTTPCacheDir, time.Duration(10*time.Minute))
  94. }
  95. // ToRESTMapper returns a mapper
  96. func (conf *OutOfClusterConfig) ToRESTMapper() (meta.RESTMapper, error) {
  97. // From: k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go > func (*configFlags) ToRESTMapper()
  98. discoveryClient, err := conf.ToDiscoveryClient()
  99. if err != nil {
  100. return nil, err
  101. }
  102. mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
  103. expander := restmapper.NewShortcutExpander(mapper, discoveryClient)
  104. return expander, nil
  105. }
  106. // GetClientConfigFromCluster will construct new clientcmd.ClientConfig using
  107. // the configuration saved within a Cluster model
  108. func (conf *OutOfClusterConfig) GetClientConfigFromCluster() (clientcmd.ClientConfig, error) {
  109. cluster := conf.Cluster
  110. if cluster.AuthMechanism == models.Local {
  111. kubeAuth, err := conf.Repo.KubeIntegration.ReadKubeIntegration(
  112. cluster.KubeIntegrationID,
  113. )
  114. if err != nil {
  115. return nil, err
  116. }
  117. return clientcmd.NewClientConfigFromBytes(kubeAuth.Kubeconfig)
  118. }
  119. apiConfig, err := conf.createRawConfigFromCluster()
  120. if err != nil {
  121. return nil, err
  122. }
  123. config := clientcmd.NewDefaultClientConfig(*apiConfig, &clientcmd.ConfigOverrides{})
  124. return config, nil
  125. }
  126. func (conf *OutOfClusterConfig) createRawConfigFromCluster() (*api.Config, error) {
  127. cluster := conf.Cluster
  128. apiConfig := &api.Config{}
  129. clusterMap := make(map[string]*api.Cluster)
  130. clusterMap[cluster.Name] = &api.Cluster{
  131. Server: cluster.Server,
  132. LocationOfOrigin: cluster.ClusterLocationOfOrigin,
  133. TLSServerName: cluster.TLSServerName,
  134. InsecureSkipTLSVerify: cluster.InsecureSkipTLSVerify,
  135. CertificateAuthorityData: cluster.CertificateAuthorityData,
  136. }
  137. // construct the auth infos
  138. authInfoName := cluster.Name + "-" + string(cluster.AuthMechanism)
  139. authInfoMap := make(map[string]*api.AuthInfo)
  140. authInfoMap[authInfoName] = &api.AuthInfo{
  141. LocationOfOrigin: cluster.UserLocationOfOrigin,
  142. Impersonate: cluster.UserImpersonate,
  143. }
  144. if groups := strings.Split(cluster.UserImpersonateGroups, ","); len(groups) > 0 && groups[0] != "" {
  145. authInfoMap[authInfoName].ImpersonateGroups = groups
  146. }
  147. switch cluster.AuthMechanism {
  148. case models.X509:
  149. kubeAuth, err := conf.Repo.KubeIntegration.ReadKubeIntegration(
  150. cluster.KubeIntegrationID,
  151. )
  152. if err != nil {
  153. return nil, err
  154. }
  155. authInfoMap[authInfoName].ClientCertificateData = kubeAuth.ClientCertificateData
  156. authInfoMap[authInfoName].ClientKeyData = kubeAuth.ClientKeyData
  157. case models.Basic:
  158. kubeAuth, err := conf.Repo.KubeIntegration.ReadKubeIntegration(
  159. cluster.KubeIntegrationID,
  160. )
  161. if err != nil {
  162. return nil, err
  163. }
  164. authInfoMap[authInfoName].Username = string(kubeAuth.Username)
  165. authInfoMap[authInfoName].Password = string(kubeAuth.Password)
  166. case models.Bearer:
  167. kubeAuth, err := conf.Repo.KubeIntegration.ReadKubeIntegration(
  168. cluster.KubeIntegrationID,
  169. )
  170. if err != nil {
  171. return nil, err
  172. }
  173. authInfoMap[authInfoName].Token = string(kubeAuth.Token)
  174. case models.OIDC:
  175. oidcAuth, err := conf.Repo.OIDCIntegration.ReadOIDCIntegration(
  176. cluster.OIDCIntegrationID,
  177. )
  178. if err != nil {
  179. return nil, err
  180. }
  181. authInfoMap[authInfoName].AuthProvider = &api.AuthProviderConfig{
  182. Name: "oidc",
  183. Config: map[string]string{
  184. "idp-issuer-url": string(oidcAuth.IssuerURL),
  185. "client-id": string(oidcAuth.ClientID),
  186. "client-secret": string(oidcAuth.ClientSecret),
  187. "idp-certificate-authority-data": string(oidcAuth.CertificateAuthorityData),
  188. "id-token": string(oidcAuth.IDToken),
  189. "refresh-token": string(oidcAuth.RefreshToken),
  190. },
  191. }
  192. case models.GCP:
  193. gcpAuth, err := conf.Repo.GCPIntegration.ReadGCPIntegration(
  194. cluster.GCPIntegrationID,
  195. )
  196. if err != nil {
  197. return nil, err
  198. }
  199. tok, err := gcpAuth.GetBearerToken(conf.getTokenCache, conf.setTokenCache)
  200. if err != nil {
  201. return nil, err
  202. }
  203. // add this as a bearer token
  204. authInfoMap[authInfoName].Token = tok
  205. case models.AWS:
  206. awsAuth, err := conf.Repo.AWSIntegration.ReadAWSIntegration(
  207. cluster.AWSIntegrationID,
  208. )
  209. if err != nil {
  210. return nil, err
  211. }
  212. tok, err := awsAuth.GetBearerToken(conf.getTokenCache, conf.setTokenCache)
  213. if err != nil {
  214. return nil, err
  215. }
  216. // add this as a bearer token
  217. authInfoMap[authInfoName].Token = tok
  218. default:
  219. return nil, errors.New("not a supported auth mechanism")
  220. }
  221. // create a context of the cluster name
  222. contextMap := make(map[string]*api.Context)
  223. contextMap[cluster.Name] = &api.Context{
  224. LocationOfOrigin: cluster.ClusterLocationOfOrigin,
  225. Cluster: cluster.Name,
  226. AuthInfo: authInfoName,
  227. }
  228. apiConfig.Clusters = clusterMap
  229. apiConfig.AuthInfos = authInfoMap
  230. apiConfig.Contexts = contextMap
  231. apiConfig.CurrentContext = cluster.Name
  232. return apiConfig, nil
  233. }
  234. func (conf *OutOfClusterConfig) getTokenCache() (tok *ints.TokenCache, err error) {
  235. return &conf.Cluster.TokenCache, nil
  236. }
  237. func (conf *OutOfClusterConfig) setTokenCache(token string, expiry time.Time) error {
  238. _, err := conf.Repo.Cluster.UpdateClusterTokenCache(
  239. &ints.TokenCache{
  240. ClusterID: conf.Cluster.ID,
  241. Token: []byte(token),
  242. Expiry: expiry,
  243. },
  244. )
  245. return err
  246. }
  247. // newRESTClientGetterFromInClusterConfig returns a RESTClientGetter using
  248. // default values set from the *rest.Config
  249. func newRESTClientGetterFromInClusterConfig(conf *rest.Config) genericclioptions.RESTClientGetter {
  250. cfs := genericclioptions.NewConfigFlags(false)
  251. cfs.ClusterName = &conf.ServerName
  252. cfs.Insecure = &conf.Insecure
  253. cfs.APIServer = &conf.Host
  254. cfs.CAFile = &conf.CAFile
  255. cfs.KeyFile = &conf.KeyFile
  256. cfs.CertFile = &conf.CertFile
  257. cfs.BearerToken = &conf.BearerToken
  258. cfs.Timeout = stringptr(conf.Timeout.String())
  259. cfs.Impersonate = &conf.Impersonate.UserName
  260. cfs.ImpersonateGroup = &conf.Impersonate.Groups
  261. cfs.Username = &conf.Username
  262. cfs.Password = &conf.Password
  263. return cfs
  264. }
  265. func stringptr(val string) *string {
  266. return &val
  267. }
  268. type fakeRESTClientGetter struct{}
  269. func (f *fakeRESTClientGetter) ToRESTConfig() (*rest.Config, error) {
  270. return nil, nil
  271. }
  272. func (f *fakeRESTClientGetter) ToRawKubeConfigLoader() clientcmd.ClientConfig {
  273. return nil
  274. }
  275. func (f *fakeRESTClientGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
  276. return nil, nil
  277. }
  278. func (f *fakeRESTClientGetter) ToRESTMapper() (meta.RESTMapper, error) {
  279. return nil, nil
  280. }