config.go 12 KB

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