2
0

router.go 11 KB

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