api.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. 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. Subdomains bool `json:"subdomains"`
  78. Github bool `json:"github"`
  79. GoogleLogin bool `json:"google"`
  80. Email bool `json:"email"`
  81. Analytics bool `json:"analytics"`
  82. }
  83. // New returns a new App instance
  84. func New(conf *AppConfig) (*App, error) {
  85. // create a new validator and translator
  86. validator := validator.New()
  87. en := en.New()
  88. uni := ut.New(en, en)
  89. translator, found := uni.GetTranslator("en")
  90. if !found {
  91. return nil, fmt.Errorf("could not find \"en\" translator")
  92. }
  93. app := &App{
  94. Logger: conf.Logger,
  95. Repo: conf.Repository,
  96. ServerConf: conf.ServerConf,
  97. RedisConf: conf.RedisConf,
  98. DBConf: conf.DBConf,
  99. TestAgents: conf.TestAgents,
  100. Capabilities: &AppCapabilities{},
  101. db: conf.DB,
  102. validator: validator,
  103. translator: &translator,
  104. }
  105. // if repository not specified, default to in-memory
  106. if app.Repo == nil {
  107. app.Repo = memory.NewRepository(true)
  108. }
  109. // create the session store
  110. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  111. if err != nil {
  112. return nil, err
  113. }
  114. app.Store = store
  115. // if application is running in-cluster, set provisioning capabilities
  116. if kubernetes.IsInCluster() {
  117. app.Capabilities.Provisioning = true
  118. agent, err := kubernetes.GetAgentInClusterConfig()
  119. if err != nil {
  120. return nil, fmt.Errorf("could not get in-cluster agent: %v", err)
  121. }
  122. app.InClusterAgent = agent
  123. }
  124. sc := conf.ServerConf
  125. // if server config contains OAuth client info, create clients
  126. if sc.GithubClientID != "" && sc.GithubClientSecret != "" {
  127. app.Capabilities.Github = true
  128. app.GithubUserConf = oauth.NewGithubClient(&oauth.Config{
  129. ClientID: sc.GithubClientID,
  130. ClientSecret: sc.GithubClientSecret,
  131. Scopes: []string{"read:user", "user:email"},
  132. BaseURL: sc.ServerURL,
  133. })
  134. app.GithubProjectConf = oauth.NewGithubClient(&oauth.Config{
  135. ClientID: sc.GithubClientID,
  136. ClientSecret: sc.GithubClientSecret,
  137. Scopes: []string{"repo", "read:user", "workflow"},
  138. BaseURL: sc.ServerURL,
  139. })
  140. }
  141. if sc.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  142. app.Capabilities.GoogleLogin = true
  143. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  144. ClientID: sc.GoogleClientID,
  145. ClientSecret: sc.GoogleClientSecret,
  146. Scopes: []string{
  147. "openid",
  148. "profile",
  149. "email",
  150. },
  151. BaseURL: sc.ServerURL,
  152. })
  153. }
  154. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  155. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  156. ClientID: sc.DOClientID,
  157. ClientSecret: sc.DOClientSecret,
  158. Scopes: []string{"read", "write"},
  159. BaseURL: sc.ServerURL,
  160. })
  161. }
  162. app.Capabilities.Email = sc.SendgridAPIKey != ""
  163. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  164. app.tokenConf = &token.TokenGeneratorConf{
  165. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  166. }
  167. if sc := conf.ServerConf; sc.SegmentClientKey != "" {
  168. client := segment.New(sc.SegmentClientKey)
  169. app.segmentClient = &client
  170. }
  171. return app, nil
  172. }
  173. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  174. reqToken := r.Header.Get("Authorization")
  175. splitToken := strings.Split(reqToken, "Bearer")
  176. if len(splitToken) != 2 {
  177. return nil
  178. }
  179. reqToken = strings.TrimSpace(splitToken[1])
  180. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  181. return tok
  182. }