config.go 13 KB

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