cluster.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package authz
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/server/shared/config"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/helm"
  11. "github.com/porter-dev/porter/internal/kubernetes"
  12. "github.com/porter-dev/porter/internal/models"
  13. "gorm.io/gorm"
  14. "k8s.io/client-go/dynamic"
  15. )
  16. const KubernetesAgentCtxKey string = "k8s-agent"
  17. const KubernetesDynamicClientCtxKey string = "k8s-dyn-client"
  18. const HelmAgentCtxKey string = "helm-agent"
  19. type ClusterScopedFactory struct {
  20. config *config.Config
  21. }
  22. func NewClusterScopedFactory(
  23. config *config.Config,
  24. ) *ClusterScopedFactory {
  25. return &ClusterScopedFactory{config}
  26. }
  27. func (p *ClusterScopedFactory) Middleware(next http.Handler) http.Handler {
  28. return &ClusterScopedMiddleware{next, p.config}
  29. }
  30. type ClusterScopedMiddleware struct {
  31. next http.Handler
  32. config *config.Config
  33. }
  34. func (p *ClusterScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. // read the project to check scopes
  36. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  37. // get the cluster id from the URL param context
  38. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  39. clusterID := reqScopes[types.ClusterScope].Resource.UInt
  40. cluster, err := p.config.Repo.Cluster().ReadCluster(proj.ID, clusterID)
  41. if err != nil {
  42. if err == gorm.ErrRecordNotFound {
  43. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrForbidden(
  44. fmt.Errorf("cluster with id %d not found in project %d", clusterID, proj.ID),
  45. ), true)
  46. } else {
  47. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  48. }
  49. return
  50. }
  51. ctx := NewClusterContext(r.Context(), cluster)
  52. r = r.Clone(ctx)
  53. p.next.ServeHTTP(w, r)
  54. }
  55. func NewClusterContext(ctx context.Context, cluster *models.Cluster) context.Context {
  56. return context.WithValue(ctx, types.ClusterScope, cluster)
  57. }
  58. type KubernetesAgentGetter interface {
  59. GetOutOfClusterConfig(cluster *models.Cluster) *kubernetes.OutOfClusterConfig
  60. GetDynamicClient(r *http.Request, cluster *models.Cluster) (dynamic.Interface, error)
  61. GetAgent(r *http.Request, cluster *models.Cluster, namespace string) (*kubernetes.Agent, error)
  62. GetHelmAgent(r *http.Request, cluster *models.Cluster, namespace string) (*helm.Agent, error)
  63. }
  64. type OutOfClusterAgentGetter struct {
  65. config *config.Config
  66. }
  67. func NewOutOfClusterAgentGetter(config *config.Config) KubernetesAgentGetter {
  68. return &OutOfClusterAgentGetter{config}
  69. }
  70. func (d *OutOfClusterAgentGetter) GetOutOfClusterConfig(cluster *models.Cluster) *kubernetes.OutOfClusterConfig {
  71. return &kubernetes.OutOfClusterConfig{
  72. Repo: d.config.Repo,
  73. DigitalOceanOAuth: d.config.DOConf,
  74. Cluster: cluster,
  75. }
  76. }
  77. func (d *OutOfClusterAgentGetter) GetAgent(r *http.Request, cluster *models.Cluster, namespace string) (*kubernetes.Agent, error) {
  78. // look for the agent in context
  79. ctxAgentVal := r.Context().Value(KubernetesAgentCtxKey)
  80. if ctxAgentVal != nil {
  81. if agent, ok := ctxAgentVal.(*kubernetes.Agent); ok {
  82. return agent, nil
  83. }
  84. }
  85. // if agent not found in context, get the agent from out of cluster config
  86. ooc := d.GetOutOfClusterConfig(cluster)
  87. if namespace == "" {
  88. ooc.DefaultNamespace = getNamespaceFromRequest(r)
  89. } else {
  90. ooc.DefaultNamespace = namespace
  91. }
  92. agent, err := kubernetes.GetAgentOutOfClusterConfig(ooc)
  93. if err != nil {
  94. return nil, fmt.Errorf("failed to get agent: %s", err.Error())
  95. }
  96. newCtx := context.WithValue(r.Context(), KubernetesAgentCtxKey, agent)
  97. r = r.WithContext(newCtx)
  98. return agent, nil
  99. }
  100. func (d *OutOfClusterAgentGetter) GetHelmAgent(r *http.Request, cluster *models.Cluster, namespace string) (*helm.Agent, error) {
  101. // look for the agent in context
  102. ctxAgentVal := r.Context().Value(HelmAgentCtxKey)
  103. if ctxAgentVal != nil {
  104. if agent, ok := ctxAgentVal.(*helm.Agent); ok {
  105. return agent, nil
  106. }
  107. }
  108. // if helm agent not found in context, construct it from k8s agent
  109. k8sAgent, err := d.GetAgent(r, cluster, namespace)
  110. if err != nil {
  111. return nil, err
  112. }
  113. if namespace == "" {
  114. namespace = getNamespaceFromRequest(r)
  115. }
  116. helmAgent, err := helm.GetAgentFromK8sAgent("secret", namespace, d.config.Logger, k8sAgent)
  117. if err != nil {
  118. return nil, fmt.Errorf("failed to get Helm agent: %s", err.Error())
  119. }
  120. newCtx := context.WithValue(r.Context(), HelmAgentCtxKey, helmAgent)
  121. r = r.WithContext(newCtx)
  122. return helmAgent, nil
  123. }
  124. func (d *OutOfClusterAgentGetter) GetDynamicClient(r *http.Request, cluster *models.Cluster) (dynamic.Interface, error) {
  125. // look for the agent in context
  126. ctxDynClientVal := r.Context().Value(KubernetesDynamicClientCtxKey)
  127. if ctxDynClientVal != nil {
  128. if dynClient, ok := ctxDynClientVal.(dynamic.Interface); ok {
  129. return dynClient, nil
  130. }
  131. }
  132. return kubernetes.GetDynamicClientOutOfClusterConfig(d.GetOutOfClusterConfig(cluster))
  133. }
  134. func getNamespaceFromRequest(r *http.Request) string {
  135. // look for namespace in context, otherwise go with default
  136. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  137. namespace := "default"
  138. if nsPolicy, ok := reqScopes[types.NamespaceScope]; ok {
  139. namespace = nsPolicy.Resource.Name
  140. }
  141. if strings.ToLower(namespace) == "all" {
  142. namespace = ""
  143. }
  144. return namespace
  145. }