router.go 11 KB

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