release.go 1.8 KB

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