api.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "github.com/porter-dev/porter/internal/repository/test"
  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. DOConf *oauth2.Config
  68. GoogleUserConf *oauth2.Config
  69. db *gorm.DB
  70. validator *vr.Validate
  71. translator *ut.Translator
  72. tokenConf *token.TokenGeneratorConf
  73. segmentClient *segment.Client
  74. }
  75. type AppCapabilities struct {
  76. Provisioning bool `json:"provisioner"`
  77. Github bool `json:"github"`
  78. BasicLogin bool `json:"basic_login"`
  79. GithubLogin bool `json:"github_login"`
  80. GoogleLogin bool `json:"google_login"`
  81. Email bool `json:"email"`
  82. Analytics bool `json:"analytics"`
  83. }
  84. // New returns a new App instance
  85. func New(conf *AppConfig) (*App, error) {
  86. // create a new validator and translator
  87. validator := validator.New()
  88. en := en.New()
  89. uni := ut.New(en, en)
  90. translator, found := uni.GetTranslator("en")
  91. if !found {
  92. return nil, fmt.Errorf("could not find \"en\" translator")
  93. }
  94. app := &App{
  95. Logger: conf.Logger,
  96. Repo: conf.Repository,
  97. ServerConf: conf.ServerConf,
  98. RedisConf: conf.RedisConf,
  99. DBConf: conf.DBConf,
  100. TestAgents: conf.TestAgents,
  101. Capabilities: &AppCapabilities{},
  102. db: conf.DB,
  103. validator: validator,
  104. translator: &translator,
  105. }
  106. // if repository not specified, default to in-memory
  107. if app.Repo == nil {
  108. app.Repo = test.NewRepository(true)
  109. }
  110. // create the session store
  111. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  112. if err != nil {
  113. return nil, err
  114. }
  115. app.Store = store
  116. // if application is running in-cluster, set provisioning capabilities
  117. if kubernetes.IsInCluster() {
  118. app.Capabilities.Provisioning = true
  119. agent, err := kubernetes.GetAgentInClusterConfig()
  120. if err != nil {
  121. return nil, fmt.Errorf("could not get in-cluster agent: %v", err)
  122. }
  123. app.InClusterAgent = agent
  124. }
  125. sc := conf.ServerConf
  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.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  144. app.Capabilities.GoogleLogin = true
  145. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  146. ClientID: sc.GoogleClientID,
  147. ClientSecret: sc.GoogleClientSecret,
  148. Scopes: []string{
  149. "openid",
  150. "profile",
  151. "email",
  152. },
  153. BaseURL: sc.ServerURL,
  154. })
  155. }
  156. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  157. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  158. ClientID: sc.DOClientID,
  159. ClientSecret: sc.DOClientSecret,
  160. Scopes: []string{"read", "write"},
  161. BaseURL: sc.ServerURL,
  162. })
  163. }
  164. app.Capabilities.Email = sc.SendgridAPIKey != ""
  165. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  166. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  167. app.tokenConf = &token.TokenGeneratorConf{
  168. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  169. }
  170. if sc := conf.ServerConf; sc.SegmentClientKey != "" {
  171. client := segment.New(sc.SegmentClientKey)
  172. app.segmentClient = &client
  173. }
  174. return app, nil
  175. }
  176. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  177. reqToken := r.Header.Get("Authorization")
  178. splitToken := strings.Split(reqToken, "Bearer")
  179. if len(splitToken) != 2 {
  180. return nil
  181. }
  182. reqToken = strings.TrimSpace(splitToken[1])
  183. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  184. return tok
  185. }