api.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "github.com/go-playground/locales/en"
  8. ut "github.com/go-playground/universal-translator"
  9. vr "github.com/go-playground/validator/v10"
  10. "github.com/porter-dev/porter/internal/auth/sessionstore"
  11. "github.com/porter-dev/porter/internal/auth/token"
  12. "github.com/porter-dev/porter/internal/kubernetes/local"
  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. memory "github.com/porter-dev/porter/internal/repository/memory"
  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. ProvisionerAgent *kubernetes.Agent
  60. IngressAgent *kubernetes.Agent
  61. // redis client for redis connection
  62. RedisConf *config.RedisConf
  63. // config for db
  64. DBConf config.DBConf
  65. // config for capabilities
  66. Capabilities *AppCapabilities
  67. // oauth-specific clients
  68. GithubUserConf *oauth2.Config
  69. GithubProjectConf *oauth2.Config
  70. GithubAppConf *oauth.GithubAppConf
  71. DOConf *oauth2.Config
  72. GoogleUserConf *oauth2.Config
  73. db *gorm.DB
  74. validator *vr.Validate
  75. translator *ut.Translator
  76. tokenConf *token.TokenGeneratorConf
  77. segmentClient *segment.Client
  78. }
  79. type AppCapabilities struct {
  80. Provisioning bool `json:"provisioner"`
  81. Github bool `json:"github"`
  82. BasicLogin bool `json:"basic_login"`
  83. GithubLogin bool `json:"github_login"`
  84. GoogleLogin bool `json:"google_login"`
  85. Email bool `json:"email"`
  86. Analytics bool `json:"analytics"`
  87. }
  88. // New returns a new App instance
  89. func New(conf *AppConfig) (*App, error) {
  90. // create a new validator and translator
  91. validator := validator.New()
  92. en := en.New()
  93. uni := ut.New(en, en)
  94. translator, found := uni.GetTranslator("en")
  95. if !found {
  96. return nil, fmt.Errorf("could not find \"en\" translator")
  97. }
  98. app := &App{
  99. Logger: conf.Logger,
  100. Repo: conf.Repository,
  101. ServerConf: conf.ServerConf,
  102. RedisConf: conf.RedisConf,
  103. DBConf: conf.DBConf,
  104. TestAgents: conf.TestAgents,
  105. Capabilities: &AppCapabilities{},
  106. db: conf.DB,
  107. validator: validator,
  108. translator: &translator,
  109. }
  110. // if repository not specified, default to in-memory
  111. if app.Repo == nil {
  112. app.Repo = memory.NewRepository(true)
  113. }
  114. // create the session store
  115. store, err := sessionstore.NewStore(app.Repo, app.ServerConf)
  116. if err != nil {
  117. return nil, err
  118. }
  119. app.Store = store
  120. sc := conf.ServerConf
  121. // get the InClusterAgent from either a file-based kubeconfig or the in-cluster agent
  122. app.assignProvisionerAgent(&sc)
  123. app.assignIngressAgent(&sc)
  124. // if server config contains OAuth client info, create clients
  125. if sc.GithubClientID != "" && sc.GithubClientSecret != "" {
  126. app.Capabilities.Github = true
  127. app.GithubUserConf = oauth.NewGithubClient(&oauth.Config{
  128. ClientID: sc.GithubClientID,
  129. ClientSecret: sc.GithubClientSecret,
  130. Scopes: []string{"read:user", "user:email"},
  131. BaseURL: sc.ServerURL,
  132. })
  133. app.GithubProjectConf = oauth.NewGithubClient(&oauth.Config{
  134. ClientID: sc.GithubClientID,
  135. ClientSecret: sc.GithubClientSecret,
  136. Scopes: []string{"repo", "read:user", "workflow"},
  137. BaseURL: sc.ServerURL,
  138. })
  139. app.Capabilities.GithubLogin = sc.GithubLoginEnabled
  140. }
  141. if sc.GithubAppClientID != "" &&
  142. sc.GithubAppClientSecret != "" &&
  143. sc.GithubAppName != "" &&
  144. sc.GithubAppWebhookSecret != "" &&
  145. sc.GithubAppSecretPath != "" &&
  146. sc.GithubAppID != "" {
  147. if AppID, err := strconv.ParseInt(sc.GithubAppID, 10, 64); err == nil {
  148. app.GithubAppConf = oauth.NewGithubAppClient(&oauth.Config{
  149. ClientID: sc.GithubAppClientID,
  150. ClientSecret: sc.GithubAppClientSecret,
  151. Scopes: []string{"read:user"},
  152. BaseURL: sc.ServerURL,
  153. }, sc.GithubAppName, sc.GithubAppWebhookSecret, sc.GithubAppSecretPath, AppID)
  154. }
  155. }
  156. if sc.GoogleClientID != "" && sc.GoogleClientSecret != "" {
  157. app.Capabilities.GoogleLogin = true
  158. app.GoogleUserConf = oauth.NewGoogleClient(&oauth.Config{
  159. ClientID: sc.GoogleClientID,
  160. ClientSecret: sc.GoogleClientSecret,
  161. Scopes: []string{
  162. "openid",
  163. "profile",
  164. "email",
  165. },
  166. BaseURL: sc.ServerURL,
  167. })
  168. }
  169. if sc.DOClientID != "" && sc.DOClientSecret != "" {
  170. app.DOConf = oauth.NewDigitalOceanClient(&oauth.Config{
  171. ClientID: sc.DOClientID,
  172. ClientSecret: sc.DOClientSecret,
  173. Scopes: []string{"read", "write"},
  174. BaseURL: sc.ServerURL,
  175. })
  176. }
  177. app.Capabilities.Email = sc.SendgridAPIKey != ""
  178. app.Capabilities.Analytics = sc.SegmentClientKey != ""
  179. app.Capabilities.BasicLogin = sc.BasicLoginEnabled
  180. app.tokenConf = &token.TokenGeneratorConf{
  181. TokenSecret: conf.ServerConf.TokenGeneratorSecret,
  182. }
  183. if sc := conf.ServerConf; sc.SegmentClientKey != "" {
  184. client := segment.New(sc.SegmentClientKey)
  185. app.segmentClient = &client
  186. }
  187. return app, nil
  188. }
  189. func (app *App) assignProvisionerAgent(sc *config.ServerConf) error {
  190. if sc.ProvisionerCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  191. app.Capabilities.Provisioning = true
  192. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  193. if err != nil {
  194. return fmt.Errorf("could not get in-cluster agent: %v", err)
  195. }
  196. app.ProvisionerAgent = agent
  197. return nil
  198. } else if sc.ProvisionerCluster == "kubeconfig" {
  199. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  200. }
  201. app.Capabilities.Provisioning = true
  202. agent, err := kubernetes.GetAgentInClusterConfig()
  203. if err != nil {
  204. return fmt.Errorf("could not get in-cluster agent: %v", err)
  205. }
  206. app.ProvisionerAgent = agent
  207. return nil
  208. }
  209. func (app *App) assignIngressAgent(sc *config.ServerConf) error {
  210. if sc.IngressCluster == "kubeconfig" && sc.SelfKubeconfig != "" {
  211. agent, err := local.GetSelfAgentFromFileConfig(sc.SelfKubeconfig)
  212. if err != nil {
  213. return fmt.Errorf("could not get in-cluster agent: %v", err)
  214. }
  215. app.IngressAgent = agent
  216. return nil
  217. } else if sc.IngressCluster == "kubeconfig" {
  218. return fmt.Errorf(`"kubeconfig" cluster option requires path to kubeconfig`)
  219. }
  220. agent, err := kubernetes.GetAgentInClusterConfig()
  221. if err != nil {
  222. return fmt.Errorf("could not get in-cluster agent: %v", err)
  223. }
  224. app.IngressAgent = agent
  225. return nil
  226. }
  227. func (app *App) getTokenFromRequest(r *http.Request) *token.Token {
  228. reqToken := r.Header.Get("Authorization")
  229. splitToken := strings.Split(reqToken, "Bearer")
  230. if len(splitToken) != 2 {
  231. return nil
  232. }
  233. reqToken = strings.TrimSpace(splitToken[1])
  234. tok, _ := token.GetTokenFromEncoded(reqToken, app.tokenConf)
  235. return tok
  236. }