router.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package router
  2. import (
  3. "net/http"
  4. "os"
  5. "path"
  6. "strings"
  7. "github.com/go-chi/chi"
  8. "github.com/porter-dev/porter/api/server/authn"
  9. "github.com/porter-dev/porter/api/server/authz"
  10. "github.com/porter-dev/porter/api/server/authz/policy"
  11. "github.com/porter-dev/porter/api/server/router/middleware"
  12. "github.com/porter-dev/porter/api/server/shared"
  13. "github.com/porter-dev/porter/api/server/shared/config"
  14. "github.com/porter-dev/porter/api/types"
  15. )
  16. func NewAPIRouter(config *config.Config) *chi.Mux {
  17. r := chi.NewRouter()
  18. endpointFactory := shared.NewAPIObjectEndpointFactory(config)
  19. baseRegisterer := NewBaseRegisterer()
  20. oauthCallbackRegisterer := NewOAuthCallbackRegisterer()
  21. releaseRegisterer := NewReleaseScopedRegisterer()
  22. namespaceRegisterer := NewNamespaceScopedRegisterer(releaseRegisterer)
  23. clusterRegisterer := NewClusterScopedRegisterer(namespaceRegisterer)
  24. infraRegisterer := NewInfraScopedRegisterer()
  25. gitInstallationRegisterer := NewGitInstallationScopedRegisterer()
  26. registryRegisterer := NewRegistryScopedRegisterer()
  27. helmRepoRegisterer := NewHelmRepoScopedRegisterer()
  28. inviteRegisterer := NewInviteScopedRegisterer()
  29. projectIntegrationRegisterer := NewProjectIntegrationScopedRegisterer()
  30. projectOAuthRegisterer := NewProjectOAuthScopedRegisterer()
  31. slackIntegrationRegisterer := NewSlackIntegrationScopedRegisterer()
  32. projRegisterer := NewProjectScopedRegisterer(
  33. clusterRegisterer,
  34. registryRegisterer,
  35. helmRepoRegisterer,
  36. inviteRegisterer,
  37. gitInstallationRegisterer,
  38. infraRegisterer,
  39. projectIntegrationRegisterer,
  40. projectOAuthRegisterer,
  41. slackIntegrationRegisterer,
  42. )
  43. userRegisterer := NewUserScopedRegisterer(projRegisterer)
  44. panicMW := middleware.NewPanicMiddleware(config)
  45. r.Route("/api", func(r chi.Router) {
  46. // set panic middleware for all API endpoints to catch panics
  47. r.Use(panicMW.Middleware)
  48. // set the content type for all API endpoints and log all request info
  49. r.Use(middleware.ContentTypeJSON)
  50. baseRoutes := baseRegisterer.GetRoutes(
  51. r,
  52. config,
  53. &types.Path{
  54. RelativePath: "",
  55. },
  56. endpointFactory,
  57. )
  58. oauthCallbackRoutes := oauthCallbackRegisterer.GetRoutes(
  59. r,
  60. config,
  61. &types.Path{
  62. RelativePath: "",
  63. },
  64. endpointFactory,
  65. )
  66. userRoutes := userRegisterer.GetRoutes(
  67. r,
  68. config,
  69. &types.Path{
  70. RelativePath: "",
  71. },
  72. endpointFactory,
  73. userRegisterer.Children...,
  74. )
  75. routes := [][]*Route{
  76. baseRoutes,
  77. userRoutes,
  78. oauthCallbackRoutes,
  79. }
  80. var allRoutes []*Route
  81. for _, r := range routes {
  82. allRoutes = append(allRoutes, r...)
  83. }
  84. registerRoutes(config, allRoutes)
  85. })
  86. staticFilePath := config.ServerConf.StaticFilePath
  87. fs := http.FileServer(http.Dir(staticFilePath))
  88. r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
  89. if _, err := os.Stat(staticFilePath + r.RequestURI); os.IsNotExist(err) {
  90. w.Header().Set("Cache-Control", "no-cache")
  91. http.StripPrefix(r.URL.Path, fs).ServeHTTP(w, r)
  92. } else {
  93. // Set static files involving html, js, or empty cache to "no-cache", which means they must be validated
  94. // for changes before the browser uses the cache
  95. if base := path.Base(r.URL.Path); strings.Contains(base, "html") || strings.Contains(base, "js") || base == "." || base == "/" {
  96. w.Header().Set("Cache-Control", "no-cache")
  97. }
  98. fs.ServeHTTP(w, r)
  99. }
  100. })
  101. return r
  102. }
  103. type Route struct {
  104. Endpoint *shared.APIEndpoint
  105. Handler http.Handler
  106. Router chi.Router
  107. }
  108. type Registerer struct {
  109. GetRoutes func(
  110. r chi.Router,
  111. config *config.Config,
  112. basePath *types.Path,
  113. factory shared.APIEndpointFactory,
  114. children ...*Registerer,
  115. ) []*Route
  116. Children []*Registerer
  117. }
  118. func registerRoutes(config *config.Config, routes []*Route) {
  119. // Create a new "user-scoped" factory which will create a new user-scoped request
  120. // after authentication. Each subsequent http.Handler can lookup the user in context.
  121. authNFactory := authn.NewAuthNFactory(config)
  122. // Create a new "project-scoped" factory which will create a new project-scoped request
  123. // after authorization. Each subsequent http.Handler can lookup the project in context.
  124. projFactory := authz.NewProjectScopedFactory(config)
  125. // Create a new "cluster-scoped" factory which will create a new cluster-scoped request
  126. // after authorization. Each subsequent http.Handler can lookup the cluster in context.
  127. clusterFactory := authz.NewClusterScopedFactory(config)
  128. // Create a new "namespace-scoped" factory which will create a new namespace-scoped request
  129. // after authorization. Each subsequent http.Handler can lookup the namespace in context.
  130. namespaceFactory := authz.NewNamespaceScopedFactory(config)
  131. // Create a new "helmrepo-scoped" factory which will create a new helmrepo-scoped request
  132. // after authorization. Each subsequent http.Handler can lookup the helm repo in context.
  133. helmRepoFactory := authz.NewHelmRepoScopedFactory(config)
  134. // Create a new "registry-scoped" factory which will create a new registry-scoped request
  135. // after authorization. Each subsequent http.Handler can lookup the registry in context.
  136. registryFactory := authz.NewRegistryScopedFactory(config)
  137. // Create a new "gitinstallation-scoped" factory which will create a new gitinstallation-scoped request
  138. // after authorization. Each subsequent http.Handler can lookup the gitinstallation in context.
  139. gitInstallationFactory := authz.NewGitInstallationScopedFactory(config)
  140. // Create a new "invite-scoped" factory which will create a new invite-scoped request
  141. // after authorization. Each subsequent http.Handler can lookup the invite in context.
  142. inviteFactory := authz.NewInviteScopedFactory(config)
  143. // Create a new "infra-scoped" factory which will create a new infra-scoped request
  144. // after authorization. Each subsequent http.Handler can lookup the infra in context.
  145. infraFactory := authz.NewInfraScopedFactory(config)
  146. // Create a new "release-scoped" factory which will create a new release-scoped request
  147. // after authorization. Each subsequent http.Handler can lookup the release in context.
  148. releaseFactory := authz.NewReleaseScopedFactory(config)
  149. // Policy doc loader loads the policy documents for a specific project.
  150. policyDocLoader := policy.NewBasicPolicyDocumentLoader(config.Repo.Project())
  151. // set up logging middleware to log information about the request
  152. loggerMw := middleware.NewRequestLoggerMiddleware(config.Logger)
  153. // websocket middleware for upgrading requests
  154. websocketMw := middleware.NewWebsocketMiddleware(config)
  155. for _, route := range routes {
  156. atomicGroup := route.Router.Group(nil)
  157. for _, scope := range route.Endpoint.Metadata.Scopes {
  158. switch scope {
  159. case types.UserScope:
  160. // if the endpoint should redirect when authn fails, attach redirect handler
  161. if route.Endpoint.Metadata.ShouldRedirect {
  162. atomicGroup.Use(authNFactory.NewAuthenticatedWithRedirect)
  163. } else {
  164. atomicGroup.Use(authNFactory.NewAuthenticated)
  165. }
  166. case types.ProjectScope:
  167. policyFactory := authz.NewPolicyMiddleware(config, *route.Endpoint.Metadata, policyDocLoader)
  168. atomicGroup.Use(policyFactory.Middleware)
  169. atomicGroup.Use(projFactory.Middleware)
  170. case types.ClusterScope:
  171. atomicGroup.Use(clusterFactory.Middleware)
  172. case types.NamespaceScope:
  173. atomicGroup.Use(namespaceFactory.Middleware)
  174. case types.HelmRepoScope:
  175. atomicGroup.Use(helmRepoFactory.Middleware)
  176. case types.RegistryScope:
  177. atomicGroup.Use(registryFactory.Middleware)
  178. case types.InviteScope:
  179. atomicGroup.Use(inviteFactory.Middleware)
  180. case types.GitInstallationScope:
  181. atomicGroup.Use(gitInstallationFactory.Middleware)
  182. case types.InfraScope:
  183. atomicGroup.Use(infraFactory.Middleware)
  184. case types.ReleaseScope:
  185. atomicGroup.Use(releaseFactory.Middleware)
  186. }
  187. }
  188. if !route.Endpoint.Metadata.Quiet {
  189. atomicGroup.Use(loggerMw.Middleware)
  190. }
  191. if route.Endpoint.Metadata.IsWebsocket {
  192. atomicGroup.Use(websocketMw.Middleware)
  193. }
  194. if route.Endpoint.Metadata.CheckUsage {
  195. usageMW := middleware.NewUsageMiddleware(config, route.Endpoint.Metadata.UsageMetric)
  196. atomicGroup.Use(usageMW.Middleware)
  197. }
  198. atomicGroup.Method(
  199. string(route.Endpoint.Metadata.Method),
  200. route.Endpoint.Metadata.Path.RelativePath,
  201. route.Handler,
  202. )
  203. }
  204. }