api.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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/oauth"
  12. "golang.org/x/oauth2"
  13. "gorm.io/gorm"
  14. "github.com/gorilla/sessions"
  15. "github.com/porter-dev/porter/internal/helm"
  16. "github.com/porter-dev/porter/internal/kubernetes"
  17. lr "github.com/porter-dev/porter/internal/logger"
  18. "github.com/porter-dev/porter/internal/repository"
  19. memory "github.com/porter-dev/porter/internal/repository/memory"
  20. "github.com/porter-dev/porter/internal/validator"
  21. segment "gopkg.in/segmentio/analytics-go.v3"
  22. "helm.sh/helm/v3/pkg/storage"
  23. "github.com/porter-dev/porter/internal/config"
  24. )
  25. // TestAgents are the k8s agents used for testing
  26. type TestAgents struct {
  27. HelmAgent *helm.Agent
  28. HelmTestStorageDriver *storage.Storage
  29. K8sAgent *kubernetes.Agent
  30. }
  31. // AppConfig is the configuration required for creating a new App
  32. type AppConfig struct {
  33. DB *gorm.DB
  34. Logger *lr.Logger
  35. Repository *repository.Repository
  36. ServerConf config.ServerConf
  37. RedisConf *config.RedisConf
  38. DBConf config.DBConf
  39. CapConf config.CapConf
  40. // TestAgents if API is in testing mode
  41. TestAgents *TestAgents
  42. }
  43. // App represents an API instance with handler methods attached, a DB connection
  44. // and a logger instance
  45. type App struct {
  46. // Server configuration
  47. ServerConf config.ServerConf
  48. // Logger for logging
  49. Logger *lr.Logger
  50. // Repo implements a query repository
  51. Repo *repository.Repository
  52. // session store for cookie-based sessions
  53. Store sessions.Store
  54. // agents exposed for testing
  55. TestAgents *TestAgents
  56. // An in-cluster agent if service is running in cluster
  57. InClusterAgent *kubernetes.Agent
  58. // redis client for redis connection
  59. RedisConf *config.RedisConf
  60. // config for db
  61. DBConf config.DBConf
  62. // config for capabilities
  63. Capabilities *AppCapabilities
  64. // oauth-specific clients
  65. GithubUserConf *oauth2.Config
  66. GithubProjectConf *oauth2.Config
  67. GithubAppConf *oauth2.Config
  68. DOConf *oauth2.Config
  69. GoogleUserConf *oauth2.Config
  70. db *gorm.DB
  71. validator *vr.Validate
  72. translator *ut.Translator
  73. tokenConf *token.TokenGeneratorConf
  74. segmentClient *segment.Client
  75. }
  76. type AppCapabilities struct {
  77. Provisioning bool `json:"provisioner"`
  78. Github bool `json:"github"`
  79. BasicLogin bool `json:"basic_login"`
  80. GithubLogin bool `json:"github_login"`
  81. GoogleLogin bool `json:"google_login"`
  82. Email bool `json:"email"`
  83. Analytics bool `json:"analytics"`
  84. }
  85. // New returns a new App instance
  86. func New(conf *AppConfig) (*App, error) {
  87. // create a new validator and translator
  88. validator := validator.New()
  89. en := en.New()
  90. uni := ut.New(en, en)
  91. translator, found := uni.GetTranslator("en")
  92. if !found {
  93. return nil, fmt.Errorf("could not find \"en\" translator")
  94. }
  95. app := &App{
  96. Logger: conf.Logger,
  97. Repo: conf.Repository,
  98. ServerConf: conf.ServerConf,
  99. RedisConf: conf.RedisConf,
  100. DBConf: conf.DBConf,
  101. TestAgents: conf.TestAgents,
  102. Capabilities: &AppCapabilities{},
  103. db: conf.DB,
  104. validator: validator,
  105. translator: &translator,
  106. }
  107. // if repository not specified, default to in-memory
  108. if app.Repo == nil {
  109. app.Repo = memory.NewRepository(true)
  110. }
  111. // create the session store
  112. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  113. if err != nil {
  114. return nil, err
  115. }
  116. app.Store = store
  117. // if application is running in-cluster, set provisioning capabilities
  118. if kubernetes.IsInCluster() {
  119. app.Capabilities.Provisioning = true
  120. agent, err := kubernetes.GetAgentInClusterConfig()
  121. if err != nil {
  122. return nil, fmt.Errorf("could not get in-cluster agent: %v", err)
  123. }
  124. app.InClusterAgent = agent
  125. }
  126. sc := conf.ServerConf
  127. // if server config contains OAuth client info, create clients
  128. if sc.GithubClientID != "" && sc.GithubClientSecret != "" {
  129. app.Capabilities.Github = true
  130. app.GithubUserConf = oauth.NewGithubClient(&oauth.Config{
  131. ClientID: sc.GithubClientID,
  132. ClientSecret: sc.GithubClientSecret,
  133. Scopes: []string{"read:user", "user:email"},
  134. BaseURL: sc.ServerURL,
  135. })
  136. app.GithubProjectConf = oauth.NewGithubClient(&oauth.Config{
  137. ClientID: sc.GithubClientID,
  138. ClientSecret: sc.GithubClientSecret,
  139. Scopes: []string{"repo", "read:user", "workflow"},
  140. BaseURL: sc.ServerURL,
  141. })
  142. app.Capabilities.GithubLogin = sc.GithubLoginEnabled
  143. }
  144. if sc.GithubAppClientID != "" && sc.GithubAppClientSecret != "" {
  145. app.GithubAppConf = oauth.NewGithubAppClient(&oauth.Config{
  146. ClientID: sc.GithubAppClientID,
  147. ClientSecret: sc.GithubAppClientSecret,
  148. Scopes: []string{"read:user"},
  149. BaseURL: sc.ServerURL,
  150. })
  151. }
  152. if sc.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  153. app.Capabilities.GoogleLogin = true
  154. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  155. ClientID: sc.GoogleClientID,
  156. ClientSecret: sc.GoogleClientSecret,
  157. Scopes: []string{
  158. "openid",
  159. "profile",
  160. "email",
  161. },
  162. BaseURL: sc.ServerURL,
  163. })
  164. }
  165. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  166. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  167. ClientID: sc.DOClientID,
  168. ClientSecret: sc.DOClientSecret,
  169. Scopes: []string{"read", "write"},
  170. BaseURL: sc.ServerURL,
  171. })
  172. }
  173. app.Capabilities.Email = sc.SendgridAPIKey != ""
  174. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  175. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  176. app.tokenConf = &token.TokenGeneratorConf{
  177. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  178. }
  179. if sc := conf.ServerConf; sc.SegmentClientKey != "" {
  180. client := segment.New(sc.SegmentClientKey)
  181. app.segmentClient = &client
  182. }
  183. return app, nil
  184. }
  185. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  186. reqToken := r.Header.Get("Authorization")
  187. splitToken := strings.Split(reqToken, "Bearer")
  188. if len(splitToken) != 2 {
  189. return nil
  190. }
  191. reqToken = strings.TrimSpace(splitToken[1])
  192. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  193. return tok
  194. }