api.go 8.2 KB

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