registry.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package authz
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/authz/policy"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/models"
  11. "gorm.io/gorm"
  12. )
  13. type RegistryScopedFactory struct {
  14. config *shared.Config
  15. }
  16. func NewRegistryScopedFactory(
  17. config *shared.Config,
  18. ) *RegistryScopedFactory {
  19. return &RegistryScopedFactory{config}
  20. }
  21. func (p *RegistryScopedFactory) Middleware(next http.Handler) http.Handler {
  22. return &RegistryScopedMiddleware{next, p.config}
  23. }
  24. type RegistryScopedMiddleware struct {
  25. next http.Handler
  26. config *shared.Config
  27. }
  28. func (p *RegistryScopedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. // read the project to check scopes
  30. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  31. // get the registry id from the URL param context
  32. reqScopes, _ := r.Context().Value(RequestScopeCtxKey).(map[types.PermissionScope]*policy.RequestAction)
  33. registryID := reqScopes[types.RegistryScope].Resource.UInt
  34. registry, err := p.config.Repo.Registry().ReadRegistry(proj.ID, registryID)
  35. if err != nil {
  36. if err == gorm.ErrRecordNotFound {
  37. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrForbidden(
  38. fmt.Errorf("registry with id %d not found in project %d", registryID, proj.ID),
  39. ))
  40. } else {
  41. apierrors.HandleAPIError(w, p.config.Logger, apierrors.NewErrInternal(err))
  42. }
  43. return
  44. }
  45. ctx := NewRegistryContext(r.Context(), registry)
  46. r = r.WithContext(ctx)
  47. p.next.ServeHTTP(w, r)
  48. }
  49. func NewRegistryContext(ctx context.Context, registry *models.Registry) context.Context {
  50. return context.WithValue(ctx, types.RegistryScope, registry)
  51. }