operation.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package authz
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. "gorm.io/gorm"
  11. )
  12. type OperationScopedFactory struct {
  13. config *config.Config
  14. }
  15. func NewOperationScopedFactory(
  16. config *config.Config,
  17. ) *OperationScopedFactory {
  18. return &OperationScopedFactory{config}
  19. }
  20. func (p *OperationScopedFactory) Middleware(next http.Handler) http.Handler {
  21. return &OperationScopedMiddleware{next, p.config}
  22. }
  23. type OperationScopedMiddleware struct {
  24. next http.Handler
  25. config *config.Config
  26. }
  27. func (p *OperationScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. infra, _ := r.Context().Value(types.InfraScope).(*models.Infra)
  29. reqScopes, _ := r.Context().Value(types.RequestScopeCtxKey).(map[types.PermissionScope]*types.RequestAction)
  30. operationID := reqScopes[types.OperationScope].Resource.Name
  31. // look for matching operation for the infra
  32. operation, err := p.config.Repo.Infra().ReadOperation(infra.ID, operationID)
  33. if err != nil {
  34. if errors.Is(err, gorm.ErrRecordNotFound) {
  35. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrForbidden(err), true)
  36. return
  37. }
  38. apierrors.HandleAPIError(p.config.Logger, p.config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  39. return
  40. }
  41. ctx := NewOperationContext(r.Context(), operation)
  42. r = r.Clone(ctx)
  43. p.next.ServeHTTP(w, r)
  44. }
  45. func NewOperationContext(ctx context.Context, operation *models.Operation) context.Context {
  46. return context.WithValue(ctx, types.OperationScope, operation)
  47. }