release.go 1.8 KB

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