router.go 11 KB

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