config.go 11 KB

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