router.go 12 KB

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