api.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/go-playground/locales/en"
  7. ut "github.com/go-playground/universal-translator"
  8. vr "github.com/go-playground/validator/v10"
  9. "github.com/porter-dev/porter/internal/auth/sessionstore"
  10. "github.com/porter-dev/porter/internal/auth/token"
  11. "github.com/porter-dev/porter/internal/notifier"
  12. "github.com/porter-dev/porter/internal/notifier/sendgrid"
  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. "github.com/porter-dev/porter/internal/repository/test"
  22. "github.com/porter-dev/porter/internal/validator"
  23. segment "gopkg.in/segmentio/analytics-go.v3"
  24. "helm.sh/helm/v3/pkg/storage"
  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. InClusterAgent *kubernetes.Agent
  60. // redis client for redis connection
  61. RedisConf *config.RedisConf
  62. // config for db
  63. DBConf config.DBConf
  64. // config for capabilities
  65. Capabilities *AppCapabilities
  66. // oauth-specific clients
  67. GithubUserConf *oauth2.Config
  68. GithubProjectConf *oauth2.Config
  69. DOConf *oauth2.Config
  70. GoogleUserConf *oauth2.Config
  71. db *gorm.DB
  72. validator *vr.Validate
  73. translator *ut.Translator
  74. tokenConf *token.TokenGeneratorConf
  75. segmentClient *segment.Client
  76. notifier notifier.UserNotifier
  77. }
  78. type AppCapabilities struct {
  79. Provisioning bool `json:"provisioner"`
  80. Github bool `json:"github"`
  81. BasicLogin bool `json:"basic_login"`
  82. GithubLogin bool `json:"github_login"`
  83. GoogleLogin bool `json:"google_login"`
  84. Email bool `json:"email"`
  85. Analytics bool `json:"analytics"`
  86. }
  87. // New returns a new App instance
  88. func New(conf *AppConfig) (*App, error) {
  89. // create a new validator and translator
  90. validator := validator.New()
  91. en := en.New()
  92. uni := ut.New(en, en)
  93. translator, found := uni.GetTranslator("en")
  94. if !found {
  95. return nil, fmt.Errorf("could not find \"en\" translator")
  96. }
  97. app := &App{
  98. Logger: conf.Logger,
  99. Repo: conf.Repository,
  100. ServerConf: conf.ServerConf,
  101. RedisConf: conf.RedisConf,
  102. DBConf: conf.DBConf,
  103. TestAgents: conf.TestAgents,
  104. Capabilities: &AppCapabilities{},
  105. db: conf.DB,
  106. validator: validator,
  107. translator: &translator,
  108. }
  109. // if repository not specified, default to in-memory
  110. if app.Repo == nil {
  111. app.Repo = test.NewRepository(true)
  112. }
  113. // create the session store
  114. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  115. if err != nil {
  116. return nil, err
  117. }
  118. app.Store = store
  119. // if application is running in-cluster, set provisioning capabilities
  120. if kubernetes.IsInCluster() {
  121. app.Capabilities.Provisioning = true
  122. agent, err := kubernetes.GetAgentInClusterConfig()
  123. if err != nil {
  124. return nil, fmt.Errorf("could not get in-cluster agent: %v", err)
  125. }
  126. app.InClusterAgent = agent
  127. }
  128. sc := conf.ServerConf
  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.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  147. app.Capabilities.GoogleLogin = true
  148. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  149. ClientID: sc.GoogleClientID,
  150. ClientSecret: sc.GoogleClientSecret,
  151. Scopes: []string{
  152. "openid",
  153. "profile",
  154. "email",
  155. },
  156. BaseURL: sc.ServerURL,
  157. })
  158. }
  159. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  160. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  161. ClientID: sc.DOClientID,
  162. ClientSecret: sc.DOClientSecret,
  163. Scopes: []string{"read", "write"},
  164. BaseURL: sc.ServerURL,
  165. })
  166. }
  167. if sc.SendgridAPIKey != "" {
  168. app.Capabilities.Email = true
  169. sgClient := &sendgrid.Client{
  170. APIKey: sc.SendgridAPIKey,
  171. PWResetTemplateID: sc.SendgridPWResetTemplateID,
  172. PWGHTemplateID: sc.SendgridPWGHTemplateID,
  173. VerifyEmailTemplateID: sc.SendgridVerifyEmailTemplateID,
  174. ProjectInviteTemplateID: sc.SendgridProjectInviteTemplateID,
  175. SenderEmail: sc.SendgridSenderEmail,
  176. }
  177. app.notifier = sendgrid.NewUserNotifier(sgClient)
  178. }
  179. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  180. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  181. app.tokenConf = &token.TokenGeneratorConf{
  182. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  183. }
  184. if sc := conf.ServerConf; sc.SegmentClientKey != "" {
  185. client := segment.New(sc.SegmentClientKey)
  186. app.segmentClient = &client
  187. }
  188. return app, nil
  189. }
  190. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  191. reqToken := r.Header.Get("Authorization")
  192. splitToken := strings.Split(reqToken, "Bearer")
  193. if len(splitToken) != 2 {
  194. return nil
  195. }
  196. reqToken = strings.TrimSpace(splitToken[1])
  197. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  198. return tok
  199. }