router.go 11 KB

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