release.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package authz
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/authz/policy"
  6. "github.com/porter-dev/porter/api/server/shared"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/helm"
  10. "github.com/porter-dev/porter/internal/models"
  11. "helm.sh/helm/v3/pkg/release"
  12. )
  13. type ReleaseScopedFactory struct {
  14. config *shared.Config
  15. }
  16. func NewReleaseScopedFactory(
  17. config *shared.Config,
  18. ) *ReleaseScopedFactory {
  19. return &ReleaseScopedFactory{config}
  20. }
  21. func (p *ReleaseScopedFactory) Middleware(next http.Handler) http.Handler {
  22. return &ReleaseScopedMiddleware{next, p.config, NewOutOfClusterAgentGetter(p.config)}
  23. }
  24. type ReleaseScopedMiddleware struct {
  25. next http.Handler
  26. config *shared.Config
  27. agentGetter KubernetesAgentGetter
  28. }
  29. func (p *ReleaseScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  30. // get the project id from the URL param context
  31. reqScopes, _ := r.Context().Value(RequestScopeCtxKey).(map[types.PermissionScope]*policy.RequestAction)
  32. // get the name and the namespace of the application
  33. namespace := reqScopes[types.NamespaceScope].Resource.Name
  34. name := reqScopes[types.ReleaseScope].Resource.Name
  35. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  36. k8sAgent, err := p.agentGetter.GetAgent(r, cluster)
  37. if err != nil {
  38. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  39. return
  40. }
  41. helmAgent, err := helm.GetAgentFromK8sAgent("secret", namespace, p.config.Logger, k8sAgent)
  42. if err != nil {
  43. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  44. return
  45. }
  46. release, err := helmAgent.GetRelease(name, 0)
  47. if err != nil {
  48. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  49. return
  50. }
  51. ctx := NewReleaseContext(r.Context(), release)
  52. r = r.WithContext(ctx)
  53. p.next.ServeHTTP(w, r)
  54. }
  55. func NewReleaseContext(ctx context.Context, helmRelease *release.Release) context.Context {
  56. return context.WithValue(ctx, types.ReleaseScope, helmRelease)
  57. }