config.go 13 KB

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