2
0

router.go 11 KB

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