api.go 9.1 KB

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