router.go 11 KB

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