api.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "github.com/go-playground/locales/en"
  8. ut "github.com/go-playground/universal-translator"
  9. vr "github.com/go-playground/validator/v10"
  10. "github.com/porter-dev/porter/internal/auth/sessionstore"
  11. "github.com/porter-dev/porter/internal/auth/token"
  12. "github.com/porter-dev/porter/internal/kubernetes/local"
  13. "github.com/porter-dev/porter/internal/oauth"
  14. "golang.org/x/oauth2"
  15. "gorm.io/gorm"
  16. "github.com/gorilla/sessions"
  17. "github.com/porter-dev/porter/internal/helm"
  18. "github.com/porter-dev/porter/internal/helm/loader"
  19. "github.com/porter-dev/porter/internal/kubernetes"
  20. lr "github.com/porter-dev/porter/internal/logger"
  21. "github.com/porter-dev/porter/internal/repository"
  22. memory "github.com/porter-dev/porter/internal/repository/memory"
  23. "github.com/porter-dev/porter/internal/validator"
  24. "helm.sh/helm/v3/pkg/storage"
  25. "github.com/porter-dev/porter/internal/analytics"
  26. "github.com/porter-dev/porter/internal/config"
  27. )
  28. // TestAgents are the k8s agents used for testing
  29. type TestAgents struct {
  30. HelmAgent *helm.Agent
  31. HelmTestStorageDriver *storage.Storage
  32. K8sAgent *kubernetes.Agent
  33. }
  34. // AppConfig is the configuration required for creating a new App
  35. type AppConfig struct {
  36. DB *gorm.DB
  37. Logger *lr.Logger
  38. Repository *repository.Repository
  39. ServerConf config.ServerConf
  40. RedisConf *config.RedisConf
  41. DBConf config.DBConf
  42. CapConf config.CapConf
  43. // TestAgents if API is in testing mode
  44. TestAgents *TestAgents
  45. }
  46. // App represents an API instance with handler methods attached, a DB connection
  47. // and a logger instance
  48. type App struct {
  49. // Server configuration
  50. ServerConf config.ServerConf
  51. // Logger for logging
  52. Logger *lr.Logger
  53. // Repo implements a query repository
  54. Repo *repository.Repository
  55. // session store for cookie-based sessions
  56. Store sessions.Store
  57. // agents exposed for testing
  58. TestAgents *TestAgents
  59. // An in-cluster agent if service is running in cluster
  60. ProvisionerAgent *kubernetes.Agent
  61. IngressAgent *kubernetes.Agent
  62. // redis client for redis connection
  63. RedisConf *config.RedisConf
  64. // config for db
  65. DBConf config.DBConf
  66. // config for capabilities
  67. Capabilities *AppCapabilities
  68. // ChartLookupURLs contains an in-memory store of Porter chart names matched with
  69. // a repo URL, so that finding a chart does not involve multiple lookups to our
  70. // chart repo's index.yaml file
  71. ChartLookupURLs map[string]string
  72. // oauth-specific clients
  73. GithubUserConf *oauth2.Config
  74. GithubProjectConf *oauth2.Config
  75. GithubAppConf *oauth.GithubAppConf
  76. DOConf *oauth2.Config
  77. GoogleUserConf *oauth2.Config
  78. db *gorm.DB
  79. validator *vr.Validate
  80. translator *ut.Translator
  81. tokenConf *token.TokenGeneratorConf
  82. analyticsClient analytics.AnalyticsSegmentClient
  83. }
  84. type AppCapabilities struct {
  85. Provisioning bool `json:"provisioner"`
  86. Github bool `json:"github"`
  87. BasicLogin bool `json:"basic_login"`
  88. GithubLogin bool `json:"github_login"`
  89. GoogleLogin bool `json:"google_login"`
  90. Email bool `json:"email"`
  91. Analytics bool `json:"analytics"`
  92. }
  93. // New returns a new App instance
  94. func New(conf *AppConfig) (*App, error) {
  95. // create a new validator and translator
  96. validator := validator.New()
  97. en := en.New()
  98. uni := ut.New(en, en)
  99. translator, found := uni.GetTranslator("en")
  100. if !found {
  101. return nil, fmt.Errorf("could not find \"en\" translator")
  102. }
  103. app := &App{
  104. Logger: conf.Logger,
  105. Repo: conf.Repository,
  106. ServerConf: conf.ServerConf,
  107. RedisConf: conf.RedisConf,
  108. DBConf: conf.DBConf,
  109. TestAgents: conf.TestAgents,
  110. Capabilities: &AppCapabilities{},
  111. db: conf.DB,
  112. validator: validator,
  113. translator: &translator,
  114. }
  115. // if repository not specified, default to in-memory
  116. if app.Repo == nil {
  117. app.Repo = memory.NewRepository(true)
  118. }
  119. // create the session store
  120. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  121. if err != nil {
  122. return nil, err
  123. }
  124. app.Store = store
  125. sc := conf.ServerConf
  126. // get the InClusterAgent from either a file-based kubeconfig or the in-cluster agent
  127. app.assignProvisionerAgent(&sc)
  128. app.assignIngressAgent(&sc)
  129. // if server config contains OAuth client info, create clients
  130. if sc.GithubClientID != "" && sc.GithubClientSecret != "" {
  131. app.Capabilities.Github = true
  132. app.GithubUserConf = oauth.NewGithubClient(&oauth.Config{
  133. ClientID: sc.GithubClientID,
  134. ClientSecret: sc.GithubClientSecret,
  135. Scopes: []string{"read:user", "user:email"},
  136. BaseURL: sc.ServerURL,
  137. })
  138. app.GithubProjectConf = oauth.NewGithubClient(&oauth.Config{
  139. ClientID: sc.GithubClientID,
  140. ClientSecret: sc.GithubClientSecret,
  141. Scopes: []string{"repo", "read:user", "workflow"},
  142. BaseURL: sc.ServerURL,
  143. })
  144. app.Capabilities.GithubLogin = sc.GithubLoginEnabled
  145. }
  146. if sc.GithubAppClientID != "" &&
  147. sc.GithubAppClientSecret != "" &&
  148. sc.GithubAppName != "" &&
  149. sc.GithubAppWebhookSecret != "" &&
  150. sc.GithubAppSecretPath != "" &&
  151. sc.GithubAppID != "" {
  152. if AppID, err := strconv.ParseInt(sc.GithubAppID, 10, 64); err == nil {
  153. app.GithubAppConf = oauth.NewGithubAppClient(&oauth.Config{
  154. ClientID: sc.GithubAppClientID,
  155. ClientSecret: sc.GithubAppClientSecret,
  156. Scopes: []string{"read:user"},
  157. BaseURL: sc.ServerURL,
  158. }, sc.GithubAppName, sc.GithubAppWebhookSecret, sc.GithubAppSecretPath, AppID)
  159. }
  160. }
  161. if sc.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  162. app.Capabilities.GoogleLogin = true
  163. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  164. ClientID: sc.GoogleClientID,
  165. ClientSecret: sc.GoogleClientSecret,
  166. Scopes: []string{
  167. "openid",
  168. "profile",
  169. "email",
  170. },
  171. BaseURL: sc.ServerURL,
  172. })
  173. }
  174. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  175. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  176. ClientID: sc.DOClientID,
  177. ClientSecret: sc.DOClientSecret,
  178. Scopes: []string{"read", "write"},
  179. BaseURL: sc.ServerURL,
  180. })
  181. }
  182. app.Capabilities.Email = sc.SendgridAPIKey != ""
  183. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  184. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  185. app.tokenConf = &token.TokenGeneratorConf{
  186. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  187. }
  188. newSegmentClient := analytics.InitializeAnalyticsSegmentClient(sc.SegmentClientKey, app.Logger)
  189. app.analyticsClient = newSegmentClient
  190. app.updateChartRepoURLs()
  191. return app, nil
  192. }
  193. func (app *App) assignProvisionerAgent(sc *config.ServerConf) error {
  194. if sc.ProvisionerCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  195. app.Capabilities.Provisioning = true
  196. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  197. if err != nil {
  198. return fmt.Errorf("could not get in-cluster agent: %v", err)
  199. }
  200. app.ProvisionerAgent = agent
  201. return nil
  202. } else if sc.ProvisionerCluster == "kubeconfig" {
  203. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  204. }
  205. app.Capabilities.Provisioning = true
  206. agent, err := kubernetes.GetAgentInClusterConfig()
  207. if err != nil {
  208. return fmt.Errorf("could not get in-cluster agent: %v", err)
  209. }
  210. app.ProvisionerAgent = agent
  211. return nil
  212. }
  213. func (app *App) assignIngressAgent(sc *config.ServerConf) error {
  214. if sc.IngressCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  215. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  216. if err != nil {
  217. return fmt.Errorf("could not get in-cluster agent: %v", err)
  218. }
  219. app.IngressAgent = agent
  220. return nil
  221. } else if sc.IngressCluster == "kubeconfig" {
  222. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  223. }
  224. agent, err := kubernetes.GetAgentInClusterConfig()
  225. if err != nil {
  226. return fmt.Errorf("could not get in-cluster agent: %v", err)
  227. }
  228. app.IngressAgent = agent
  229. return nil
  230. }
  231. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  232. reqToken := r.Header.Get("Authorization")
  233. splitToken := strings.Split(reqToken, "Bearer")
  234. if len(splitToken) != 2 {
  235. return nil
  236. }
  237. reqToken = strings.TrimSpace(splitToken[1])
  238. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  239. return tok
  240. }
  241. func (app *App) updateChartRepoURLs() {
  242. newCharts := make(map[string]string)
  243. for _, chartRepo := range []string{
  244. app.ServerConf.DefaultApplicationHelmRepoURL,
  245. app.ServerConf.DefaultAddonHelmRepoURL,
  246. } {
  247. indexFile, err := loader.LoadRepoIndexPublic(chartRepo)
  248. if err != nil {
  249. continue
  250. }
  251. for chartName, _ := range indexFile.Entries {
  252. newCharts[chartName] = chartRepo
  253. }
  254. }
  255. app.ChartLookupURLs = newCharts
  256. }