cluster.go 6.2 KB

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