project_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "github.com/go-chi/chi"
  7. "github.com/porter-dev/porter/internal/forms"
  8. "github.com/porter-dev/porter/internal/models"
  9. )
  10. // Enumeration of user API error codes, represented as int64
  11. const (
  12. ErrProjectDecode ErrorCode = iota + 600
  13. ErrProjectValidateFields
  14. ErrProjectDataRead
  15. )
  16. // HandleCreateProject validates a project form entry, converts the project to a gorm
  17. // model, and saves the user to the database
  18. func (app *App) HandleCreateProject(w http.ResponseWriter, r *http.Request) {
  19. session, err := app.store.Get(r, app.cookieName)
  20. if err != nil {
  21. http.Error(w, err.Error(), http.StatusInternalServerError)
  22. return
  23. }
  24. userID, _ := session.Values["user_id"].(uint)
  25. form := &forms.CreateProjectForm{}
  26. // decode from JSON to form value
  27. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  28. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  29. return
  30. }
  31. // validate the form
  32. if err := app.validator.Struct(form); err != nil {
  33. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  34. return
  35. }
  36. // convert the form to a project model
  37. projModel, err := form.ToProject(app.repo.Project)
  38. if err != nil {
  39. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  40. return
  41. }
  42. // handle write to the database
  43. projModel, err = app.repo.Project.CreateProject(projModel)
  44. if err != nil {
  45. app.handleErrorDataWrite(err, w)
  46. return
  47. }
  48. // create a new Role with the user as the admin
  49. _, err = app.repo.Project.CreateProjectRole(projModel, &models.Role{
  50. UserID: userID,
  51. ProjectID: projModel.ID,
  52. Kind: models.RoleAdmin,
  53. })
  54. if err != nil {
  55. app.handleErrorDataWrite(err, w)
  56. return
  57. }
  58. app.logger.Info().Msgf("New project created: %d", projModel.ID)
  59. w.WriteHeader(http.StatusCreated)
  60. projExt := projModel.Externalize()
  61. if err := json.NewEncoder(w).Encode(projExt); err != nil {
  62. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  63. return
  64. }
  65. }
  66. // HandleReadProject returns an externalized Project (models.ProjectExternal)
  67. // based on an ID
  68. func (app *App) HandleReadProject(w http.ResponseWriter, r *http.Request) {
  69. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  70. if err != nil || id == 0 {
  71. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  72. return
  73. }
  74. proj, err := app.repo.Project.ReadProject(uint(id))
  75. if err != nil {
  76. app.handleErrorRead(err, ErrProjectDataRead, w)
  77. return
  78. }
  79. projExt := proj.Externalize()
  80. w.WriteHeader(http.StatusOK)
  81. if err := json.NewEncoder(w).Encode(projExt); err != nil {
  82. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  83. return
  84. }
  85. }
  86. // HandleListProjectClusters returns a list of clusters that have linked ServiceAccounts.
  87. // If multiple service accounts exist for a cluster, the service account created later
  88. // will take precedence. This may be changed in a future release to return multiple
  89. // service accounts.
  90. func (app *App) HandleListProjectClusters(w http.ResponseWriter, r *http.Request) {
  91. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  92. if err != nil || id == 0 {
  93. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  94. return
  95. }
  96. sas, err := app.repo.ServiceAccount.ListServiceAccountsByProjectID(uint(id))
  97. if err != nil {
  98. app.handleErrorRead(err, ErrProjectDataRead, w)
  99. return
  100. }
  101. clusters := make([]*models.ClusterExternal, 0)
  102. // clusterMapIndex used for checking if cluster has already been added
  103. // maps from the cluster's endpoint to the index in the cluster array
  104. clusterMapIndex := make(map[string]int)
  105. for _, sa := range sas {
  106. for _, cluster := range sa.Clusters {
  107. if currIndex, ok := clusterMapIndex[cluster.Server]; ok {
  108. if clusters[currIndex].ServiceAccountID <= cluster.ServiceAccountID {
  109. clusters[currIndex] = cluster.Externalize()
  110. continue
  111. }
  112. }
  113. clusterMapIndex[cluster.Server] = len(clusters)
  114. clusters = append(clusters, cluster.Externalize())
  115. }
  116. }
  117. w.WriteHeader(http.StatusOK)
  118. if err := json.NewEncoder(w).Encode(clusters); err != nil {
  119. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  120. return
  121. }
  122. }
  123. // HandleCreateProjectSACandidates handles the creation of ServiceAccountCandidates
  124. // using a kubeconfig and a project id
  125. func (app *App) HandleCreateProjectSACandidates(w http.ResponseWriter, r *http.Request) {
  126. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  127. if err != nil || projID == 0 {
  128. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  129. return
  130. }
  131. form := &forms.CreateServiceAccountCandidatesForm{
  132. ProjectID: uint(projID),
  133. }
  134. // decode from JSON to form value
  135. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  136. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  137. return
  138. }
  139. // validate the form
  140. if err := app.validator.Struct(form); err != nil {
  141. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  142. return
  143. }
  144. // convert the form to a ServiceAccountCandidate
  145. saCandidates, err := form.ToServiceAccountCandidates()
  146. if err != nil {
  147. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  148. return
  149. }
  150. extSACandidates := make([]*models.ServiceAccountCandidateExternal, 0)
  151. for _, saCandidate := range saCandidates {
  152. // handle write to the database
  153. saCandidate, err = app.repo.ServiceAccount.CreateServiceAccountCandidate(saCandidate)
  154. if err != nil {
  155. app.handleErrorDataWrite(err, w)
  156. return
  157. }
  158. app.logger.Info().Msgf("New service account candidate created: %d", saCandidate.ID)
  159. // if the SA candidate does not have any actions to perform, create the ServiceAccount
  160. // automatically
  161. if len(saCandidate.Actions) == 0 {
  162. // we query the repo again to get the decrypted version of the SA candidate
  163. saCandidate, err = app.repo.ServiceAccount.ReadServiceAccountCandidate(saCandidate.ID)
  164. if err != nil {
  165. app.handleErrorDataRead(err, w)
  166. return
  167. }
  168. saForm := &forms.ServiceAccountActionResolver{
  169. ServiceAccountCandidateID: saCandidate.ID,
  170. SACandidate: saCandidate,
  171. }
  172. err := saForm.PopulateServiceAccount(app.repo.ServiceAccount)
  173. if err != nil {
  174. app.handleErrorDataWrite(err, w)
  175. return
  176. }
  177. sa, err := app.repo.ServiceAccount.CreateServiceAccount(saForm.SA)
  178. if err != nil {
  179. app.handleErrorDataWrite(err, w)
  180. return
  181. }
  182. saCandidate, err = app.repo.ServiceAccount.UpdateServiceAccountCandidateCreatedSAID(saCandidate.ID, sa.ID)
  183. if err != nil {
  184. app.handleErrorDataWrite(err, w)
  185. return
  186. }
  187. app.logger.Info().Msgf("New service account created: %d", sa.ID)
  188. }
  189. extSACandidates = append(extSACandidates, saCandidate.Externalize())
  190. }
  191. w.WriteHeader(http.StatusCreated)
  192. if err := json.NewEncoder(w).Encode(extSACandidates); err != nil {
  193. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  194. return
  195. }
  196. }
  197. // HandleListProjectSACandidates returns a list of externalized ServiceAccountCandidate
  198. // ([]models.ServiceAccountCandidateExternal) based on a project ID
  199. func (app *App) HandleListProjectSACandidates(w http.ResponseWriter, r *http.Request) {
  200. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  201. if err != nil || projID == 0 {
  202. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  203. return
  204. }
  205. saCandidates, err := app.repo.ServiceAccount.ListServiceAccountCandidatesByProjectID(uint(projID))
  206. if err != nil {
  207. app.handleErrorRead(err, ErrProjectDataRead, w)
  208. return
  209. }
  210. extSACandidates := make([]*models.ServiceAccountCandidateExternal, 0)
  211. for _, saCandidate := range saCandidates {
  212. extSACandidates = append(extSACandidates, saCandidate.Externalize())
  213. }
  214. w.WriteHeader(http.StatusOK)
  215. if err := json.NewEncoder(w).Encode(extSACandidates); err != nil {
  216. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  217. return
  218. }
  219. }
  220. // HandleResolveSACandidateActions accepts a list of action configurations for a
  221. // given ServiceAccountCandidate, which "resolves" that ServiceAccountCandidate
  222. // and creates a ServiceAccount for a specific project
  223. func (app *App) HandleResolveSACandidateActions(w http.ResponseWriter, r *http.Request) {
  224. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  225. if err != nil || projID == 0 {
  226. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  227. return
  228. }
  229. candID, err := strconv.ParseUint(chi.URLParam(r, "candidate_id"), 0, 64)
  230. if err != nil || projID == 0 {
  231. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  232. return
  233. }
  234. // decode actions from request
  235. actions := make([]*models.ServiceAccountAllActions, 0)
  236. if err := json.NewDecoder(r.Body).Decode(&actions); err != nil {
  237. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  238. return
  239. }
  240. var saResolverBase *forms.ServiceAccountActionResolver = &forms.ServiceAccountActionResolver{
  241. ServiceAccountCandidateID: uint(candID),
  242. SA: nil,
  243. SACandidate: nil,
  244. }
  245. // for each action, create the relevant form and populate the service account
  246. // we'll chain the .PopulateServiceAccount functions
  247. for _, action := range actions {
  248. var err error
  249. switch action.Name {
  250. case models.ClusterCADataAction:
  251. form := &forms.ClusterCADataAction{
  252. ServiceAccountActionResolver: saResolverBase,
  253. ClusterCAData: action.ClusterCAData,
  254. }
  255. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  256. case models.ClientCertDataAction:
  257. form := &forms.ClientCertDataAction{
  258. ServiceAccountActionResolver: saResolverBase,
  259. ClientCertData: action.ClientCertData,
  260. }
  261. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  262. case models.ClientKeyDataAction:
  263. form := &forms.ClientKeyDataAction{
  264. ServiceAccountActionResolver: saResolverBase,
  265. ClientKeyData: action.ClientKeyData,
  266. }
  267. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  268. case models.OIDCIssuerDataAction:
  269. form := &forms.OIDCIssuerDataAction{
  270. ServiceAccountActionResolver: saResolverBase,
  271. OIDCIssuerCAData: action.OIDCIssuerCAData,
  272. }
  273. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  274. case models.TokenDataAction:
  275. form := &forms.TokenDataAction{
  276. ServiceAccountActionResolver: saResolverBase,
  277. TokenData: action.TokenData,
  278. }
  279. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  280. case models.GCPKeyDataAction:
  281. form := &forms.GCPKeyDataAction{
  282. ServiceAccountActionResolver: saResolverBase,
  283. GCPKeyData: action.GCPKeyData,
  284. }
  285. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  286. case models.AWSDataAction:
  287. form := &forms.AWSDataAction{
  288. ServiceAccountActionResolver: saResolverBase,
  289. AWSAccessKeyID: action.AWSAccessKeyID,
  290. AWSSecretAccessKey: action.AWSSecretAccessKey,
  291. AWSClusterID: action.AWSClusterID,
  292. }
  293. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  294. }
  295. if err != nil {
  296. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  297. return
  298. }
  299. }
  300. sa, err := app.repo.ServiceAccount.CreateServiceAccount(saResolverBase.SA)
  301. if err != nil {
  302. app.handleErrorDataWrite(err, w)
  303. return
  304. }
  305. if sa != nil {
  306. app.logger.Info().Msgf("New service account created: %d", sa.ID)
  307. _, err := app.repo.ServiceAccount.UpdateServiceAccountCandidateCreatedSAID(uint(candID), sa.ID)
  308. if err != nil {
  309. app.handleErrorDataWrite(err, w)
  310. return
  311. }
  312. saExternal := sa.Externalize()
  313. w.WriteHeader(http.StatusCreated)
  314. if err := json.NewEncoder(w).Encode(saExternal); err != nil {
  315. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  316. return
  317. }
  318. } else {
  319. w.WriteHeader(http.StatusNotModified)
  320. }
  321. }
  322. // HandleDeleteProject deletes a project from the db, reading from the project_id
  323. // in the URL param
  324. func (app *App) HandleDeleteProject(w http.ResponseWriter, r *http.Request) {
  325. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  326. if err != nil || id == 0 {
  327. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  328. return
  329. }
  330. proj, err := app.repo.Project.ReadProject(uint(id))
  331. if err != nil {
  332. app.handleErrorRead(err, ErrProjectDataRead, w)
  333. return
  334. }
  335. proj, err = app.repo.Project.DeleteProject(proj)
  336. if err != nil {
  337. app.handleErrorRead(err, ErrProjectDataRead, w)
  338. return
  339. }
  340. projExternal := proj.Externalize()
  341. w.WriteHeader(http.StatusOK)
  342. if err := json.NewEncoder(w).Encode(projExternal); err != nil {
  343. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  344. return
  345. }
  346. }