router.go 11 KB

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