user_handler_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package api_test
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "reflect"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/go-chi/chi"
  11. "github.com/porter-dev/porter/internal/config"
  12. "github.com/porter-dev/porter/internal/models"
  13. "github.com/porter-dev/porter/internal/repository"
  14. "github.com/porter-dev/porter/internal/repository/test"
  15. "github.com/porter-dev/porter/server/api"
  16. "github.com/porter-dev/porter/server/router"
  17. lr "github.com/porter-dev/porter/internal/logger"
  18. vr "github.com/porter-dev/porter/internal/validator"
  19. )
  20. func initApi(canQuery bool) (*api.App, *repository.Repository) {
  21. appConf := config.Conf{
  22. Debug: true,
  23. Server: config.ServerConf{
  24. Port: 8080,
  25. TimeoutRead: time.Second * 5,
  26. TimeoutWrite: time.Second * 10,
  27. TimeoutIdle: time.Second * 15,
  28. },
  29. // unimportant
  30. Db: config.DBConf{},
  31. }
  32. logger := lr.NewConsole(appConf.Debug)
  33. validator := vr.New()
  34. repo := test.NewRepository(canQuery)
  35. return api.New(logger, repo, validator), repo
  36. }
  37. func testUserRequest(t *testing.T, c userTest) {
  38. // create a mock API
  39. api, repo := initApi(c.canQuery)
  40. r := router.New(api)
  41. if c.init != nil {
  42. c.init(repo)
  43. }
  44. req, err := http.NewRequest(
  45. c.method,
  46. c.endpoint,
  47. strings.NewReader(c.body),
  48. )
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. rr := httptest.NewRecorder()
  53. r.ServeHTTP(rr, req)
  54. // first, check that the status matches
  55. if status := rr.Code; status != c.expStatus {
  56. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  57. c.msg, status, c.expStatus)
  58. }
  59. // if there's a validator, call it
  60. for _, validate := range c.validators {
  61. validate(rr, c, r, t)
  62. }
  63. }
  64. type userTest struct {
  65. init func(repo *repository.Repository)
  66. msg,
  67. method,
  68. endpoint,
  69. body string
  70. expStatus int
  71. expBody string
  72. canQuery bool
  73. validators []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T)
  74. }
  75. var createUserTests = []userTest{
  76. userTest{
  77. msg: "Create user",
  78. method: "POST",
  79. endpoint: "/api/users",
  80. body: `{
  81. "email": "belanger@getporter.dev",
  82. "password": "hello"
  83. }`,
  84. expStatus: http.StatusCreated,
  85. expBody: "",
  86. canQuery: true,
  87. },
  88. userTest{
  89. msg: "Create user invalid email",
  90. method: "POST",
  91. endpoint: "/api/users",
  92. body: `{
  93. "email": "notanemail",
  94. "password": "hello"
  95. }`,
  96. expStatus: http.StatusUnprocessableEntity,
  97. expBody: `{"code":601,"errors":["email validation failed"]}`,
  98. canQuery: true,
  99. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  100. BasicBodyValidator,
  101. },
  102. },
  103. userTest{
  104. msg: "Create user missing field",
  105. method: "POST",
  106. endpoint: "/api/users",
  107. body: `{
  108. "password": "hello"
  109. }`,
  110. expStatus: http.StatusUnprocessableEntity,
  111. expBody: `{"code":601,"errors":["required validation failed"]}`,
  112. canQuery: true,
  113. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  114. BasicBodyValidator,
  115. },
  116. },
  117. userTest{
  118. msg: "Create user cannot write to db",
  119. method: "POST",
  120. endpoint: "/api/users",
  121. body: `{
  122. "email": "belanger@getporter.dev",
  123. "password": "hello"
  124. }`,
  125. expStatus: http.StatusInternalServerError,
  126. expBody: `{"code":500,"errors":["could not read from database"]}`,
  127. canQuery: false,
  128. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  129. BasicBodyValidator,
  130. },
  131. },
  132. userTest{
  133. init: func(repo *repository.Repository) {
  134. repo.User.CreateUser(&models.User{
  135. Email: "belanger@getporter.dev",
  136. Password: "hello",
  137. })
  138. },
  139. msg: "Create user same email",
  140. method: "POST",
  141. endpoint: "/api/users",
  142. body: `{
  143. "email": "belanger@getporter.dev",
  144. "password": "hello"
  145. }`,
  146. expStatus: http.StatusUnprocessableEntity,
  147. expBody: `{"code":601,"errors":["email already taken"]}`,
  148. canQuery: true,
  149. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  150. BasicBodyValidator,
  151. },
  152. },
  153. }
  154. func TestHandleCreateUser(t *testing.T) {
  155. for _, c := range createUserTests {
  156. testUserRequest(t, c)
  157. }
  158. }
  159. var readUserTests = []userTest{
  160. userTest{
  161. init: func(repo *repository.Repository) {
  162. repo.User.CreateUser(&models.User{
  163. Email: "belanger@getporter.dev",
  164. Password: "hello",
  165. Clusters: []models.ClusterConfig{
  166. models.ClusterConfig{
  167. Name: "cluster-test",
  168. Server: "https://localhost",
  169. Context: "context-test",
  170. User: "test-admin",
  171. },
  172. },
  173. RawKubeConfig: []byte("apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"),
  174. })
  175. },
  176. msg: "Read user successful",
  177. method: "GET",
  178. endpoint: "/api/users/1",
  179. body: "",
  180. expStatus: http.StatusOK,
  181. expBody: `{"id":1,"email":"belanger@getporter.dev","clusters":[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"}`,
  182. canQuery: true,
  183. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  184. UserModelBodyValidator,
  185. },
  186. },
  187. userTest{
  188. init: func(repo *repository.Repository) {
  189. repo.User.CreateUser(&models.User{
  190. Email: "belanger@getporter.dev",
  191. Password: "hello",
  192. })
  193. },
  194. msg: "Read user bad id field",
  195. method: "GET",
  196. endpoint: "/api/users/aldkfjas",
  197. body: "",
  198. expStatus: http.StatusBadRequest,
  199. expBody: `{"code":600,"errors":["could not process request"]}`,
  200. canQuery: true,
  201. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  202. BasicBodyValidator,
  203. },
  204. },
  205. userTest{
  206. init: func(repo *repository.Repository) {
  207. repo.User.CreateUser(&models.User{
  208. Email: "belanger@getporter.dev",
  209. Password: "hello",
  210. })
  211. },
  212. msg: "Read user not found",
  213. method: "GET",
  214. endpoint: "/api/users/2",
  215. body: "",
  216. expStatus: http.StatusNotFound,
  217. expBody: `{"code":602,"errors":["could not find requested object"]}`,
  218. canQuery: true,
  219. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  220. BasicBodyValidator,
  221. },
  222. },
  223. }
  224. func TestHandleReadUser(t *testing.T) {
  225. for _, c := range readUserTests {
  226. testUserRequest(t, c)
  227. }
  228. }
  229. var readUserClustersTests = []userTest{
  230. userTest{
  231. init: func(repo *repository.Repository) {
  232. repo.User.CreateUser(&models.User{
  233. Email: "belanger@getporter.dev",
  234. Password: "hello",
  235. Clusters: []models.ClusterConfig{
  236. models.ClusterConfig{
  237. Name: "cluster-test",
  238. Server: "https://localhost",
  239. Context: "context-test",
  240. User: "test-admin",
  241. },
  242. },
  243. RawKubeConfig: []byte("apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"),
  244. })
  245. },
  246. msg: "Read user successful",
  247. method: "GET",
  248. endpoint: "/api/users/1/clusters",
  249. body: "",
  250. expStatus: http.StatusOK,
  251. expBody: `[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}]`,
  252. canQuery: true,
  253. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  254. ClusterBodyValidator,
  255. },
  256. },
  257. }
  258. func TestHandleReadUserClusters(t *testing.T) {
  259. for _, c := range readUserClustersTests {
  260. testUserRequest(t, c)
  261. }
  262. }
  263. var readUserClustersAllTests = []userTest{
  264. userTest{
  265. init: func(repo *repository.Repository) {
  266. repo.User.CreateUser(&models.User{
  267. Email: "belanger@getporter.dev",
  268. Password: "hello",
  269. Clusters: []models.ClusterConfig{},
  270. RawKubeConfig: []byte("apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"),
  271. })
  272. },
  273. msg: "Read user successful",
  274. method: "GET",
  275. endpoint: "/api/users/1/clusters/all",
  276. body: "",
  277. expStatus: http.StatusOK,
  278. expBody: `[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}]`,
  279. canQuery: true,
  280. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  281. ClusterBodyValidator,
  282. },
  283. },
  284. }
  285. func TestHandleReadUserClustersAll(t *testing.T) {
  286. for _, c := range readUserClustersAllTests {
  287. testUserRequest(t, c)
  288. }
  289. }
  290. var updateUserTests = []userTest{
  291. userTest{
  292. init: func(repo *repository.Repository) {
  293. repo.User.CreateUser(&models.User{
  294. Email: "belanger@getporter.dev",
  295. Password: "hello",
  296. })
  297. },
  298. msg: "Update user successful",
  299. method: "PUT",
  300. endpoint: "/api/users/1",
  301. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin", "allowedClusters":[]}`,
  302. expStatus: http.StatusNoContent,
  303. expBody: "",
  304. canQuery: true,
  305. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  306. func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  307. req, err := http.NewRequest(
  308. "GET",
  309. "/api/users/1",
  310. strings.NewReader(""),
  311. )
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. rr2 := httptest.NewRecorder()
  316. r.ServeHTTP(rr2, req)
  317. gotBody := &models.UserExternal{}
  318. expBody := &models.UserExternal{}
  319. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  320. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","clusters":[],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"}`), expBody)
  321. if !reflect.DeepEqual(gotBody, expBody) {
  322. t.Errorf("%s, handler returned wrong body: got %v want %v",
  323. "validator failed", gotBody, expBody)
  324. }
  325. },
  326. },
  327. },
  328. userTest{
  329. init: func(repo *repository.Repository) {
  330. repo.User.CreateUser(&models.User{
  331. Email: "belanger@getporter.dev",
  332. Password: "hello",
  333. })
  334. },
  335. msg: "Update user invalid id",
  336. method: "PUT",
  337. endpoint: "/api/users/alsdfjk",
  338. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin", "allowedClusters":[]}`,
  339. expStatus: http.StatusBadRequest,
  340. expBody: `{"code":600,"errors":["could not process request"]}`,
  341. canQuery: true,
  342. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  343. BasicBodyValidator,
  344. },
  345. },
  346. }
  347. func TestHandleUpdateUser(t *testing.T) {
  348. for _, c := range updateUserTests {
  349. testUserRequest(t, c)
  350. }
  351. }
  352. var deleteUserTests = []userTest{
  353. userTest{
  354. init: func(repo *repository.Repository) {
  355. repo.User.CreateUser(&models.User{
  356. Email: "belanger@getporter.dev",
  357. Password: "hello",
  358. })
  359. },
  360. msg: "Delete user successful",
  361. method: "DELETE",
  362. endpoint: "/api/users/1",
  363. body: `{"password":"hello"}`,
  364. expStatus: http.StatusNoContent,
  365. expBody: "",
  366. canQuery: true,
  367. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  368. func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  369. req, err := http.NewRequest(
  370. "GET",
  371. "/api/users/1",
  372. strings.NewReader(""),
  373. )
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. rr2 := httptest.NewRecorder()
  378. r.ServeHTTP(rr2, req)
  379. gotBody := &models.UserExternal{}
  380. expBody := &models.UserExternal{}
  381. if status := rr2.Code; status != 404 {
  382. t.Errorf("DELETE user validation, handler returned wrong status code: got %v want %v",
  383. status, 404)
  384. }
  385. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  386. json.Unmarshal([]byte(`{"code":602,"errors":["could not find requested object"]}`), expBody)
  387. if !reflect.DeepEqual(gotBody, expBody) {
  388. t.Errorf("%s, handler returned wrong body: got %v want %v",
  389. "validator failed", gotBody, expBody)
  390. }
  391. },
  392. },
  393. },
  394. }
  395. func TestHandleDeleteUser(t *testing.T) {
  396. for _, c := range deleteUserTests {
  397. testUserRequest(t, c)
  398. }
  399. }
  400. func BasicBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  401. if body := rr.Body.String(); body != c.expBody {
  402. t.Errorf("%s, handler returned wrong body: got %v want %v",
  403. c.msg, body, c.expBody)
  404. }
  405. }
  406. func UserModelBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  407. gotBody := &models.UserExternal{}
  408. expBody := &models.UserExternal{}
  409. json.Unmarshal(rr.Body.Bytes(), gotBody)
  410. json.Unmarshal([]byte(c.expBody), expBody)
  411. if !reflect.DeepEqual(gotBody, expBody) {
  412. t.Errorf("%s, handler returned wrong body: got %v want %v",
  413. c.msg, gotBody, expBody)
  414. }
  415. }
  416. func ClusterBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  417. // if status is expected to be 200, parse the body for UserExternal
  418. gotBody := &[]models.ClusterConfigExternal{}
  419. expBody := &[]models.ClusterConfigExternal{}
  420. json.Unmarshal(rr.Body.Bytes(), gotBody)
  421. json.Unmarshal([]byte(c.expBody), expBody)
  422. if !reflect.DeepEqual(gotBody, expBody) {
  423. t.Errorf("%s, handler returned wrong body: got %v want %v",
  424. c.msg, gotBody, expBody)
  425. }
  426. }