router.go 12 KB

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