api.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. SlackConf *oauth2.Config
  79. // analytics client for reporting
  80. AnalyticsClient analytics.AnalyticsSegmentClient
  81. db *gorm.DB
  82. validator *vr.Validate
  83. translator *ut.Translator
  84. tokenConf *token.TokenGeneratorConf
  85. }
  86. type AppCapabilities struct {
  87. Provisioning bool `json:"provisioner"`
  88. Github bool `json:"github"`
  89. BasicLogin bool `json:"basic_login"`
  90. GithubLogin bool `json:"github_login"`
  91. GoogleLogin bool `json:"google_login"`
  92. SlackNotifications bool `json:"slack_notifs"`
  93. Email bool `json:"email"`
  94. Analytics bool `json:"analytics"`
  95. }
  96. // New returns a new App instance
  97. func New(conf *AppConfig) (*App, error) {
  98. // create a new validator and translator
  99. validator := validator.New()
  100. en := en.New()
  101. uni := ut.New(en, en)
  102. translator, found := uni.GetTranslator("en")
  103. if !found {
  104. return nil, fmt.Errorf("could not find \"en\" translator")
  105. }
  106. app := &App{
  107. Logger: conf.Logger,
  108. Repo: conf.Repository,
  109. ServerConf: conf.ServerConf,
  110. RedisConf: conf.RedisConf,
  111. DBConf: conf.DBConf,
  112. TestAgents: conf.TestAgents,
  113. Capabilities: &AppCapabilities{},
  114. db: conf.DB,
  115. validator: validator,
  116. translator: &translator,
  117. }
  118. // if repository not specified, default to in-memory
  119. if app.Repo == nil {
  120. app.Repo = memory.NewRepository(true)
  121. }
  122. // create the session store
  123. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  124. if err != nil {
  125. return nil, err
  126. }
  127. app.Store = store
  128. sc := conf.ServerConf
  129. // get the InClusterAgent from either a file-based kubeconfig or the in-cluster agent
  130. app.assignProvisionerAgent(&sc)
  131. app.assignIngressAgent(&sc)
  132. // if server config contains OAuth client info, create clients
  133. if sc.GithubClientID != "" && sc.GithubClientSecret != "" {
  134. app.Capabilities.Github = true
  135. app.GithubUserConf = oauth.NewGithubClient(&oauth.Config{
  136. ClientID: sc.GithubClientID,
  137. ClientSecret: sc.GithubClientSecret,
  138. Scopes: []string{"read:user", "user:email"},
  139. BaseURL: sc.ServerURL,
  140. })
  141. app.GithubProjectConf = oauth.NewGithubClient(&oauth.Config{
  142. ClientID: sc.GithubClientID,
  143. ClientSecret: sc.GithubClientSecret,
  144. Scopes: []string{"repo", "read:user", "workflow"},
  145. BaseURL: sc.ServerURL,
  146. })
  147. app.Capabilities.GithubLogin = sc.GithubLoginEnabled
  148. }
  149. if sc.GithubAppClientID != "" &&
  150. sc.GithubAppClientSecret != "" &&
  151. sc.GithubAppName != "" &&
  152. sc.GithubAppWebhookSecret != "" &&
  153. sc.GithubAppSecretPath != "" &&
  154. sc.GithubAppID != "" {
  155. if AppID, err := strconv.ParseInt(sc.GithubAppID, 10, 64); err == nil {
  156. app.GithubAppConf = oauth.NewGithubAppClient(&oauth.Config{
  157. ClientID: sc.GithubAppClientID,
  158. ClientSecret: sc.GithubAppClientSecret,
  159. Scopes: []string{"read:user"},
  160. BaseURL: sc.ServerURL,
  161. }, sc.GithubAppName, sc.GithubAppWebhookSecret, sc.GithubAppSecretPath, AppID)
  162. }
  163. }
  164. if sc.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  165. app.Capabilities.GoogleLogin = true
  166. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  167. ClientID: sc.GoogleClientID,
  168. ClientSecret: sc.GoogleClientSecret,
  169. Scopes: []string{
  170. "openid",
  171. "profile",
  172. "email",
  173. },
  174. BaseURL: sc.ServerURL,
  175. })
  176. }
  177. if sc.SlackClientID != "" && sc.SlackClientSecret != "" {
  178. app.Capabilities.SlackNotifications = true
  179. app.SlackConf = oauth.NewSlackClient(&oauth.Config{
  180. ClientID: sc.SlackClientID,
  181. ClientSecret: sc.SlackClientSecret,
  182. Scopes: []string{
  183. "incoming-webhook",
  184. "team:read",
  185. },
  186. BaseURL: sc.ServerURL,
  187. })
  188. }
  189. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  190. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  191. ClientID: sc.DOClientID,
  192. ClientSecret: sc.DOClientSecret,
  193. Scopes: []string{"read", "write"},
  194. BaseURL: sc.ServerURL,
  195. })
  196. }
  197. app.Capabilities.Email = sc.SendgridAPIKey != ""
  198. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  199. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  200. app.tokenConf = &token.TokenGeneratorConf{
  201. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  202. }
  203. newSegmentClient := analytics.InitializeAnalyticsSegmentClient(sc.SegmentClientKey, app.Logger)
  204. app.AnalyticsClient = newSegmentClient
  205. app.updateChartRepoURLs()
  206. return app, nil
  207. }
  208. func (app *App) assignProvisionerAgent(sc *config.ServerConf) error {
  209. if sc.ProvisionerCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  210. app.Capabilities.Provisioning = true
  211. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  212. if err != nil {
  213. return fmt.Errorf("could not get in-cluster agent: %v", err)
  214. }
  215. app.ProvisionerAgent = agent
  216. return nil
  217. } else if sc.ProvisionerCluster == "kubeconfig" {
  218. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  219. }
  220. app.Capabilities.Provisioning = true
  221. agent, err := kubernetes.GetAgentInClusterConfig()
  222. if err != nil {
  223. return fmt.Errorf("could not get in-cluster agent: %v", err)
  224. }
  225. app.ProvisionerAgent = agent
  226. return nil
  227. }
  228. func (app *App) assignIngressAgent(sc *config.ServerConf) error {
  229. if sc.IngressCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  230. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  231. if err != nil {
  232. return fmt.Errorf("could not get in-cluster agent: %v", err)
  233. }
  234. app.IngressAgent = agent
  235. return nil
  236. } else if sc.IngressCluster == "kubeconfig" {
  237. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  238. }
  239. agent, err := kubernetes.GetAgentInClusterConfig()
  240. if err != nil {
  241. return fmt.Errorf("could not get in-cluster agent: %v", err)
  242. }
  243. app.IngressAgent = agent
  244. return nil
  245. }
  246. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  247. reqToken := r.Header.Get("Authorization")
  248. splitToken := strings.Split(reqToken, "Bearer")
  249. if len(splitToken) != 2 {
  250. return nil
  251. }
  252. reqToken = strings.TrimSpace(splitToken[1])
  253. tok, err := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  254. if err != nil {
  255. return nil
  256. }
  257. return tok
  258. }
  259. func (app *App) updateChartRepoURLs() {
  260. newCharts := make(map[string]string)
  261. for _, chartRepo := range []string{
  262. app.ServerConf.DefaultApplicationHelmRepoURL,
  263. app.ServerConf.DefaultAddonHelmRepoURL,
  264. } {
  265. indexFile, err := loader.LoadRepoIndexPublic(chartRepo)
  266. if err != nil {
  267. continue
  268. }
  269. for chartName, _ := range indexFile.Entries {
  270. newCharts[chartName] = chartRepo
  271. }
  272. }
  273. app.ChartLookupURLs = newCharts
  274. }