api.go 7.1 KB

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