config.go 11 KB

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