config.go 13 KB

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