router.go 11 KB

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