user_handler_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. sessionstore "github.com/porter-dev/porter/internal/auth"
  18. lr "github.com/porter-dev/porter/internal/logger"
  19. vr "github.com/porter-dev/porter/internal/validator"
  20. )
  21. func initApi(canQuery bool) (*api.App, *repository.Repository) {
  22. appConf := config.Conf{
  23. Debug: true,
  24. Server: config.ServerConf{
  25. Port: 8080,
  26. TimeoutRead: time.Second * 5,
  27. TimeoutWrite: time.Second * 10,
  28. TimeoutIdle: time.Second * 15,
  29. },
  30. // unimportant
  31. Db: config.DBConf{},
  32. }
  33. logger := lr.NewConsole(appConf.Debug)
  34. validator := vr.New()
  35. repo := test.NewRepository(canQuery)
  36. key := []byte("secret") // TODO: change to os.Getenv("SESSION_KEY")
  37. store, _ := sessionstore.NewStore(repo, key)
  38. return api.New(logger, repo, validator, store), repo
  39. }
  40. func testUserRequest(t *testing.T, c userTest) {
  41. // create a mock API
  42. api, repo := initApi(c.canQuery)
  43. r := router.New(api)
  44. if c.init != nil {
  45. c.init(repo)
  46. }
  47. req, err := http.NewRequest(
  48. c.method,
  49. c.endpoint,
  50. strings.NewReader(c.body),
  51. )
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. rr := httptest.NewRecorder()
  56. r.ServeHTTP(rr, req)
  57. // first, check that the status matches
  58. if status := rr.Code; status != c.expStatus {
  59. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  60. c.msg, status, c.expStatus)
  61. }
  62. // if there's a validator, call it
  63. for _, validate := range c.validators {
  64. validate(rr, c, r, t)
  65. }
  66. }
  67. type userTest struct {
  68. init func(repo *repository.Repository)
  69. msg,
  70. method,
  71. endpoint,
  72. body string
  73. expStatus int
  74. expBody string
  75. canQuery bool
  76. validators []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T)
  77. }
  78. var createUserTests = []userTest{
  79. userTest{
  80. msg: "Create user",
  81. method: "POST",
  82. endpoint: "/api/users",
  83. body: `{
  84. "email": "belanger@getporter.dev",
  85. "password": "hello"
  86. }`,
  87. expStatus: http.StatusCreated,
  88. expBody: "",
  89. canQuery: true,
  90. },
  91. userTest{
  92. msg: "Create user invalid email",
  93. method: "POST",
  94. endpoint: "/api/users",
  95. body: `{
  96. "email": "notanemail",
  97. "password": "hello"
  98. }`,
  99. expStatus: http.StatusUnprocessableEntity,
  100. expBody: `{"code":601,"errors":["email validation failed"]}`,
  101. canQuery: true,
  102. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  103. BasicBodyValidator,
  104. },
  105. },
  106. userTest{
  107. msg: "Create user missing field",
  108. method: "POST",
  109. endpoint: "/api/users",
  110. body: `{
  111. "password": "hello"
  112. }`,
  113. expStatus: http.StatusUnprocessableEntity,
  114. expBody: `{"code":601,"errors":["required validation failed"]}`,
  115. canQuery: true,
  116. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  117. BasicBodyValidator,
  118. },
  119. },
  120. userTest{
  121. msg: "Create user db connection down",
  122. method: "POST",
  123. endpoint: "/api/users",
  124. body: `{
  125. "email": "belanger@getporter.dev",
  126. "password": "hello"
  127. }`,
  128. expStatus: http.StatusInternalServerError,
  129. expBody: `{"code":500,"errors":["could not read from database"]}`,
  130. canQuery: false,
  131. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  132. BasicBodyValidator,
  133. },
  134. },
  135. userTest{
  136. init: func(repo *repository.Repository) {
  137. repo.User.CreateUser(&models.User{
  138. Email: "belanger@getporter.dev",
  139. Password: "hello",
  140. })
  141. },
  142. msg: "Create user same email",
  143. method: "POST",
  144. endpoint: "/api/users",
  145. body: `{
  146. "email": "belanger@getporter.dev",
  147. "password": "hello"
  148. }`,
  149. expStatus: http.StatusUnprocessableEntity,
  150. expBody: `{"code":601,"errors":["email already taken"]}`,
  151. canQuery: true,
  152. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  153. BasicBodyValidator,
  154. },
  155. },
  156. userTest{
  157. msg: "Create user invalid field type",
  158. method: "POST",
  159. endpoint: "/api/users",
  160. body: `{
  161. "email": "belanger@getporter.dev",
  162. "password": 0
  163. }`,
  164. expStatus: http.StatusBadRequest,
  165. expBody: `{"code":600,"errors":["could not process request"]}`,
  166. canQuery: true,
  167. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  168. BasicBodyValidator,
  169. },
  170. },
  171. }
  172. func TestHandleCreateUser(t *testing.T) {
  173. for _, c := range createUserTests {
  174. testUserRequest(t, c)
  175. }
  176. }
  177. var readUserTests = []userTest{
  178. userTest{
  179. init: func(repo *repository.Repository) {
  180. repo.User.CreateUser(&models.User{
  181. Email: "belanger@getporter.dev",
  182. Password: "hello",
  183. Clusters: []models.ClusterConfig{
  184. models.ClusterConfig{
  185. Name: "cluster-test",
  186. Server: "https://localhost",
  187. Context: "context-test",
  188. User: "test-admin",
  189. },
  190. },
  191. 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"),
  192. })
  193. },
  194. msg: "Read user successful",
  195. method: "GET",
  196. endpoint: "/api/users/1",
  197. body: "",
  198. expStatus: http.StatusOK,
  199. 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"}`,
  200. canQuery: true,
  201. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  202. UserModelBodyValidator,
  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 bad id field",
  213. method: "GET",
  214. endpoint: "/api/users/aldkfjas",
  215. body: "",
  216. expStatus: http.StatusBadRequest,
  217. expBody: `{"code":600,"errors":["could not process request"]}`,
  218. canQuery: true,
  219. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  220. BasicBodyValidator,
  221. },
  222. },
  223. userTest{
  224. init: func(repo *repository.Repository) {
  225. repo.User.CreateUser(&models.User{
  226. Email: "belanger@getporter.dev",
  227. Password: "hello",
  228. })
  229. },
  230. msg: "Read user not found",
  231. method: "GET",
  232. endpoint: "/api/users/2",
  233. body: "",
  234. expStatus: http.StatusNotFound,
  235. expBody: `{"code":602,"errors":["could not find requested object"]}`,
  236. canQuery: true,
  237. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  238. BasicBodyValidator,
  239. },
  240. },
  241. }
  242. func TestHandleReadUser(t *testing.T) {
  243. for _, c := range readUserTests {
  244. testUserRequest(t, c)
  245. }
  246. }
  247. var readUserClustersTests = []userTest{
  248. userTest{
  249. init: func(repo *repository.Repository) {
  250. repo.User.CreateUser(&models.User{
  251. Email: "belanger@getporter.dev",
  252. Password: "hello",
  253. Clusters: []models.ClusterConfig{
  254. models.ClusterConfig{
  255. Name: "cluster-test",
  256. Server: "https://localhost",
  257. Context: "context-test",
  258. User: "test-admin",
  259. },
  260. },
  261. 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"),
  262. })
  263. },
  264. msg: "Read user successful",
  265. method: "GET",
  266. endpoint: "/api/users/1/clusters",
  267. body: "",
  268. expStatus: http.StatusOK,
  269. expBody: `[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}]`,
  270. canQuery: true,
  271. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  272. ClusterBodyValidator,
  273. },
  274. },
  275. }
  276. func TestHandleReadUserClusters(t *testing.T) {
  277. for _, c := range readUserClustersTests {
  278. testUserRequest(t, c)
  279. }
  280. }
  281. var readUserClustersAllTests = []userTest{
  282. userTest{
  283. init: func(repo *repository.Repository) {
  284. repo.User.CreateUser(&models.User{
  285. Email: "belanger@getporter.dev",
  286. Password: "hello",
  287. Clusters: []models.ClusterConfig{},
  288. 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"),
  289. })
  290. },
  291. msg: "Read user successful",
  292. method: "GET",
  293. endpoint: "/api/users/1/clusters/all",
  294. body: "",
  295. expStatus: http.StatusOK,
  296. expBody: `[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}]`,
  297. canQuery: true,
  298. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  299. ClusterBodyValidator,
  300. },
  301. },
  302. userTest{
  303. init: func(repo *repository.Repository) {
  304. repo.User.CreateUser(&models.User{
  305. Email: "belanger@getporter.dev",
  306. Password: "hello",
  307. Clusters: []models.ClusterConfig{},
  308. RawKubeConfig: []byte("apiVersion: \xc5\n"),
  309. })
  310. },
  311. msg: "Read user with invalid utf-8 \xc5 in kubeconfig",
  312. method: "GET",
  313. endpoint: "/api/users/1/clusters/all",
  314. body: "",
  315. expStatus: http.StatusBadRequest,
  316. expBody: `{"code":600,"errors":["could not process request"]}`,
  317. canQuery: true,
  318. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  319. BasicBodyValidator,
  320. },
  321. },
  322. }
  323. func TestHandleReadUserClustersAll(t *testing.T) {
  324. for _, c := range readUserClustersAllTests {
  325. testUserRequest(t, c)
  326. }
  327. }
  328. var updateUserTests = []userTest{
  329. userTest{
  330. init: func(repo *repository.Repository) {
  331. repo.User.CreateUser(&models.User{
  332. Email: "belanger@getporter.dev",
  333. Password: "hello",
  334. })
  335. },
  336. msg: "Update user successful",
  337. method: "PUT",
  338. endpoint: "/api/users/1",
  339. 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":[]}`,
  340. expStatus: http.StatusNoContent,
  341. expBody: "",
  342. canQuery: true,
  343. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  344. func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  345. req, err := http.NewRequest(
  346. "GET",
  347. "/api/users/1",
  348. strings.NewReader(""),
  349. )
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. rr2 := httptest.NewRecorder()
  354. r.ServeHTTP(rr2, req)
  355. gotBody := &models.UserExternal{}
  356. expBody := &models.UserExternal{}
  357. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  358. 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)
  359. if !reflect.DeepEqual(gotBody, expBody) {
  360. t.Errorf("%s, handler returned wrong body: got %v want %v",
  361. "validator failed", gotBody, expBody)
  362. }
  363. },
  364. },
  365. },
  366. userTest{
  367. init: func(repo *repository.Repository) {
  368. repo.User.CreateUser(&models.User{
  369. Email: "belanger@getporter.dev",
  370. Password: "hello",
  371. })
  372. },
  373. msg: "Update user invalid id",
  374. method: "PUT",
  375. endpoint: "/api/users/alsdfjk",
  376. 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":[]}`,
  377. expStatus: http.StatusBadRequest,
  378. expBody: `{"code":600,"errors":["could not process request"]}`,
  379. canQuery: true,
  380. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  381. BasicBodyValidator,
  382. },
  383. },
  384. userTest{
  385. init: func(repo *repository.Repository) {
  386. repo.User.CreateUser(&models.User{
  387. Email: "belanger@getporter.dev",
  388. Password: "hello",
  389. })
  390. },
  391. msg: "Update user bad kubeconfig",
  392. method: "PUT",
  393. endpoint: "/api/users/1",
  394. body: `{"rawKubeConfig":"notvalidyaml", "allowedClusters":[]}`,
  395. expStatus: http.StatusBadRequest,
  396. expBody: `{"code":600,"errors":["could not process request"]}`,
  397. canQuery: true,
  398. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  399. BasicBodyValidator,
  400. },
  401. },
  402. userTest{
  403. init: func(repo *repository.Repository) {
  404. repo.User.CreateUser(&models.User{
  405. Email: "belanger@getporter.dev",
  406. Password: "hello",
  407. })
  408. },
  409. msg: "Update user db connection down",
  410. method: "PUT",
  411. endpoint: "/api/users/1",
  412. 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":[]}`,
  413. expStatus: http.StatusInternalServerError,
  414. expBody: `{"code":500,"errors":["could not write to database"]}`,
  415. canQuery: false,
  416. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  417. BasicBodyValidator,
  418. },
  419. },
  420. }
  421. func TestHandleUpdateUser(t *testing.T) {
  422. for _, c := range updateUserTests {
  423. testUserRequest(t, c)
  424. }
  425. }
  426. var deleteUserTests = []userTest{
  427. userTest{
  428. init: func(repo *repository.Repository) {
  429. repo.User.CreateUser(&models.User{
  430. Email: "belanger@getporter.dev",
  431. Password: "hello",
  432. })
  433. },
  434. msg: "Delete user successful",
  435. method: "DELETE",
  436. endpoint: "/api/users/1",
  437. body: `{"password":"hello"}`,
  438. expStatus: http.StatusNoContent,
  439. expBody: "",
  440. canQuery: true,
  441. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  442. func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  443. req, err := http.NewRequest(
  444. "GET",
  445. "/api/users/1",
  446. strings.NewReader(""),
  447. )
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. rr2 := httptest.NewRecorder()
  452. r.ServeHTTP(rr2, req)
  453. gotBody := &models.UserExternal{}
  454. expBody := &models.UserExternal{}
  455. if status := rr2.Code; status != 404 {
  456. t.Errorf("DELETE user validation, handler returned wrong status code: got %v want %v",
  457. status, 404)
  458. }
  459. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  460. json.Unmarshal([]byte(`{"code":602,"errors":["could not find requested object"]}`), expBody)
  461. if !reflect.DeepEqual(gotBody, expBody) {
  462. t.Errorf("%s, handler returned wrong body: got %v want %v",
  463. "validator failed", gotBody, expBody)
  464. }
  465. },
  466. },
  467. },
  468. userTest{
  469. init: func(repo *repository.Repository) {
  470. repo.User.CreateUser(&models.User{
  471. Email: "belanger@getporter.dev",
  472. Password: "hello",
  473. })
  474. },
  475. msg: "Delete user invalid id",
  476. method: "DELETE",
  477. endpoint: "/api/users/aldkjf",
  478. body: `{"password":"hello"}`,
  479. expStatus: http.StatusBadRequest,
  480. expBody: `{"code":600,"errors":["could not process request"]}`,
  481. canQuery: true,
  482. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  483. BasicBodyValidator,
  484. },
  485. },
  486. userTest{
  487. init: func(repo *repository.Repository) {
  488. repo.User.CreateUser(&models.User{
  489. Email: "belanger@getporter.dev",
  490. Password: "hello",
  491. })
  492. },
  493. msg: "Delete user missing password",
  494. method: "DELETE",
  495. endpoint: "/api/users/1",
  496. body: `{}`,
  497. expStatus: http.StatusUnprocessableEntity,
  498. expBody: `{"code":601,"errors":["required validation failed"]}`,
  499. canQuery: true,
  500. validators: []func(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T){
  501. BasicBodyValidator,
  502. },
  503. },
  504. }
  505. func TestHandleDeleteUser(t *testing.T) {
  506. for _, c := range deleteUserTests {
  507. testUserRequest(t, c)
  508. }
  509. }
  510. func BasicBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  511. if body := rr.Body.String(); body != c.expBody {
  512. t.Errorf("%s, handler returned wrong body: got %v want %v",
  513. c.msg, body, c.expBody)
  514. }
  515. }
  516. func UserModelBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  517. gotBody := &models.UserExternal{}
  518. expBody := &models.UserExternal{}
  519. json.Unmarshal(rr.Body.Bytes(), gotBody)
  520. json.Unmarshal([]byte(c.expBody), expBody)
  521. if !reflect.DeepEqual(gotBody, expBody) {
  522. t.Errorf("%s, handler returned wrong body: got %v want %v",
  523. c.msg, gotBody, expBody)
  524. }
  525. }
  526. func ClusterBodyValidator(rr *httptest.ResponseRecorder, c userTest, r *chi.Mux, t *testing.T) {
  527. // if status is expected to be 200, parse the body for UserExternal
  528. gotBody := &[]models.ClusterConfigExternal{}
  529. expBody := &[]models.ClusterConfigExternal{}
  530. json.Unmarshal(rr.Body.Bytes(), gotBody)
  531. json.Unmarshal([]byte(c.expBody), expBody)
  532. if !reflect.DeepEqual(gotBody, expBody) {
  533. t.Errorf("%s, handler returned wrong body: got %v want %v",
  534. c.msg, gotBody, expBody)
  535. }
  536. }