project_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. saForm := &forms.ServiceAccountActionResolver{
  163. ServiceAccountCandidateID: saCandidate.ID,
  164. SACandidate: saCandidate,
  165. }
  166. err := saForm.PopulateServiceAccount(app.repo.ServiceAccount)
  167. if err != nil {
  168. app.handleErrorDataWrite(err, w)
  169. return
  170. }
  171. sa, err := app.repo.ServiceAccount.CreateServiceAccount(saForm.SA)
  172. if err != nil {
  173. app.handleErrorDataWrite(err, w)
  174. return
  175. }
  176. app.logger.Info().Msgf("New service account created: %d", sa.ID)
  177. }
  178. extSACandidates = append(extSACandidates, saCandidate.Externalize())
  179. }
  180. w.WriteHeader(http.StatusCreated)
  181. if err := json.NewEncoder(w).Encode(extSACandidates); err != nil {
  182. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  183. return
  184. }
  185. }
  186. // HandleListProjectSACandidates returns a list of externalized ServiceAccountCandidate
  187. // ([]models.ServiceAccountCandidateExternal) based on a project ID
  188. func (app *App) HandleListProjectSACandidates(w http.ResponseWriter, r *http.Request) {
  189. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  190. if err != nil || projID == 0 {
  191. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  192. return
  193. }
  194. saCandidates, err := app.repo.ServiceAccount.ListServiceAccountCandidatesByProjectID(uint(projID))
  195. if err != nil {
  196. app.handleErrorRead(err, ErrProjectDataRead, w)
  197. return
  198. }
  199. extSACandidates := make([]*models.ServiceAccountCandidateExternal, 0)
  200. for _, saCandidate := range saCandidates {
  201. extSACandidates = append(extSACandidates, saCandidate.Externalize())
  202. }
  203. w.WriteHeader(http.StatusOK)
  204. if err := json.NewEncoder(w).Encode(extSACandidates); err != nil {
  205. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  206. return
  207. }
  208. }
  209. // HandleResolveSACandidateActions accepts a list of action configurations for a
  210. // given ServiceAccountCandidate, which "resolves" that ServiceAccountCandidate
  211. // and creates a ServiceAccount for a specific project
  212. func (app *App) HandleResolveSACandidateActions(w http.ResponseWriter, r *http.Request) {
  213. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  214. if err != nil || projID == 0 {
  215. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  216. return
  217. }
  218. candID, err := strconv.ParseUint(chi.URLParam(r, "candidate_id"), 0, 64)
  219. if err != nil || projID == 0 {
  220. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  221. return
  222. }
  223. // decode actions from request
  224. actions := make([]*models.ServiceAccountAllActions, 0)
  225. if err := json.NewDecoder(r.Body).Decode(&actions); err != nil {
  226. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  227. return
  228. }
  229. var saResolverBase *forms.ServiceAccountActionResolver = &forms.ServiceAccountActionResolver{
  230. ServiceAccountCandidateID: uint(candID),
  231. SA: nil,
  232. SACandidate: nil,
  233. }
  234. // for each action, create the relevant form and populate the service account
  235. // we'll chain the .PopulateServiceAccount functions
  236. for _, action := range actions {
  237. var err error
  238. switch action.Name {
  239. case models.ClusterCADataAction:
  240. form := &forms.ClusterCADataAction{
  241. ServiceAccountActionResolver: saResolverBase,
  242. ClusterCAData: action.ClusterCAData,
  243. }
  244. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  245. case models.ClientCertDataAction:
  246. form := &forms.ClientCertDataAction{
  247. ServiceAccountActionResolver: saResolverBase,
  248. ClientCertData: action.ClientCertData,
  249. }
  250. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  251. case models.ClientKeyDataAction:
  252. form := &forms.ClientKeyDataAction{
  253. ServiceAccountActionResolver: saResolverBase,
  254. ClientKeyData: action.ClientKeyData,
  255. }
  256. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  257. case models.OIDCIssuerDataAction:
  258. form := &forms.OIDCIssuerDataAction{
  259. ServiceAccountActionResolver: saResolverBase,
  260. OIDCIssuerCAData: action.OIDCIssuerCAData,
  261. }
  262. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  263. case models.TokenDataAction:
  264. form := &forms.TokenDataAction{
  265. ServiceAccountActionResolver: saResolverBase,
  266. TokenData: action.TokenData,
  267. }
  268. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  269. case models.GCPKeyDataAction:
  270. form := &forms.GCPKeyDataAction{
  271. ServiceAccountActionResolver: saResolverBase,
  272. GCPKeyData: action.GCPKeyData,
  273. }
  274. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  275. case models.AWSKeyDataAction:
  276. form := &forms.AWSKeyDataAction{
  277. ServiceAccountActionResolver: saResolverBase,
  278. AWSKeyData: action.AWSKeyData,
  279. }
  280. err = form.PopulateServiceAccount(app.repo.ServiceAccount)
  281. }
  282. if err != nil {
  283. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  284. return
  285. }
  286. }
  287. sa, err := app.repo.ServiceAccount.CreateServiceAccount(saResolverBase.SA)
  288. if err != nil {
  289. app.handleErrorDataWrite(err, w)
  290. return
  291. }
  292. if sa != nil {
  293. app.logger.Info().Msgf("New service account created: %d", sa.ID)
  294. saExternal := sa.Externalize()
  295. w.WriteHeader(http.StatusCreated)
  296. if err := json.NewEncoder(w).Encode(saExternal); err != nil {
  297. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  298. return
  299. }
  300. } else {
  301. w.WriteHeader(http.StatusNotModified)
  302. }
  303. }
  304. // HandleDeleteProject deletes a project from the db, reading from the project_id
  305. // in the URL param
  306. func (app *App) HandleDeleteProject(w http.ResponseWriter, r *http.Request) {
  307. id, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  308. if err != nil || id == 0 {
  309. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  310. return
  311. }
  312. proj, err := app.repo.Project.ReadProject(uint(id))
  313. if err != nil {
  314. app.handleErrorRead(err, ErrProjectDataRead, w)
  315. return
  316. }
  317. proj, err = app.repo.Project.DeleteProject(proj)
  318. if err != nil {
  319. app.handleErrorRead(err, ErrProjectDataRead, w)
  320. return
  321. }
  322. projExternal := proj.Externalize()
  323. w.WriteHeader(http.StatusOK)
  324. if err := json.NewEncoder(w).Encode(projExternal); err != nil {
  325. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  326. return
  327. }
  328. }