api.go 9.5 KB

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