config.go 11 KB

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