PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/api_test.go

https://gitlab.com/jjae2124/tyk
Go | 539 lines | 418 code | 118 blank | 3 comment | 105 complexity | cc523b4d229a3890050049368ace89f0 MD5 | raw file
  1. package main
  2. import (
  3. "encoding/json"
  4. "github.com/gorilla/mux"
  5. "github.com/TykTechnologies/tykcommon"
  6. "net/http"
  7. "net/http/httptest"
  8. "net/url"
  9. "os"
  10. "strings"
  11. "testing"
  12. )
  13. var apiTestDef string = `
  14. {
  15. "id": "507f1f77bcf86cd799439011",
  16. "name": "Tyk Test API ONE",
  17. "api_id": "1",
  18. "org_id": "default",
  19. "definition": {
  20. "location": "header",
  21. "key": "version"
  22. },
  23. "auth": {
  24. "auth_header_name": "authorization"
  25. },
  26. "version_data": {
  27. "not_versioned": false,
  28. "versions": {
  29. "Default": {
  30. "name": "Default",
  31. "expires": "3006-01-02 15:04",
  32. "use_extended_paths": true,
  33. "paths": {
  34. "ignored": [],
  35. "white_list": [],
  36. "black_list": []
  37. }
  38. }
  39. }
  40. },
  41. "proxy": {
  42. "listen_path": "/v1",
  43. "target_url": "http://lonelycode.com",
  44. "strip_listen_path": false
  45. }
  46. }
  47. `
  48. func MakeSampleAPI() *APISpec {
  49. log.Debug("CREATING TEMPORARY API")
  50. thisSpec := createDefinitionFromString(apiTestDef)
  51. redisStore := RedisStorageManager{KeyPrefix: "apikey-"}
  52. healthStore := &RedisStorageManager{KeyPrefix: "apihealth."}
  53. orgStore := &RedisStorageManager{KeyPrefix: "orgKey."}
  54. thisSpec.Init(&redisStore, &redisStore, healthStore, orgStore)
  55. specs := &[]*APISpec{&thisSpec}
  56. newMuxes := mux.NewRouter()
  57. loadAPIEndpoints(newMuxes)
  58. loadApps(specs, newMuxes)
  59. newHttmMuxer := http.NewServeMux()
  60. newHttmMuxer.Handle("/", newMuxes)
  61. http.DefaultServeMux = newHttmMuxer
  62. log.Debug("TEST Reload complete")
  63. return &thisSpec
  64. }
  65. type Success struct {
  66. Key string `json:"key"`
  67. Status string `json:"status"`
  68. Action string `json:"action"`
  69. }
  70. type testAPIDefinition struct {
  71. tykcommon.APIDefinition
  72. ID string `json:"id"`
  73. }
  74. func init() {
  75. // Clean up our API list
  76. log.Debug("Setting up Empty API path")
  77. config.AppPath = os.TempDir() + "/tyk_test/"
  78. os.Mkdir(config.AppPath, 0755)
  79. }
  80. func TestHealthCheckEndpoint(t *testing.T) {
  81. log.Debug("TEST GET HEALTHCHECK")
  82. uri := "/tyk/health/?api_id=1"
  83. method := "GET"
  84. recorder := httptest.NewRecorder()
  85. param := make(url.Values)
  86. MakeSampleAPI()
  87. req, err := http.NewRequest(method, uri+param.Encode(), nil)
  88. if err != nil {
  89. t.Fatal(err)
  90. }
  91. healthCheckhandler(recorder, req)
  92. var ApiHealthValues HealthCheckValues
  93. err = json.Unmarshal([]byte(recorder.Body.String()), &ApiHealthValues)
  94. if err != nil {
  95. t.Error("Could not unmarshal API Health check:\n", err, recorder.Body.String())
  96. }
  97. if recorder.Code != 200 {
  98. t.Error("Recorder should return 200 for health check")
  99. }
  100. }
  101. func TestApiHandler(t *testing.T) {
  102. uri := "/tyk/apis/"
  103. method := "GET"
  104. sampleKey := createSampleSession()
  105. body, _ := json.Marshal(&sampleKey)
  106. recorder := httptest.NewRecorder()
  107. param := make(url.Values)
  108. MakeSampleAPI()
  109. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. apiHandler(recorder, req)
  114. // We can't deserialize BSON ObjectID's if they are not in th test base!
  115. var ApiList []testAPIDefinition
  116. err = json.Unmarshal([]byte(recorder.Body.String()), &ApiList)
  117. if err != nil {
  118. t.Error("Could not unmarshal API List:\n", err, recorder.Body.String())
  119. } else {
  120. if len(ApiList) != 1 {
  121. t.Error("API's not returned, len was: \n", len(ApiList), recorder.Body.String())
  122. } else {
  123. if ApiList[0].APIID != "1" {
  124. t.Error("Response is incorrect - no API ID value in struct :\n", recorder.Body.String())
  125. }
  126. }
  127. }
  128. }
  129. func TestApiHandlerGetSingle(t *testing.T) {
  130. log.Debug("TEST GET SINGLE API DEFINITION")
  131. uri := "/tyk/apis/1"
  132. method := "GET"
  133. sampleKey := createSampleSession()
  134. body, _ := json.Marshal(&sampleKey)
  135. recorder := httptest.NewRecorder()
  136. param := make(url.Values)
  137. MakeSampleAPI()
  138. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  139. if err != nil {
  140. t.Fatal(err)
  141. }
  142. apiHandler(recorder, req)
  143. // We can't deserialize BSON ObjectID's if they are not in th test base!
  144. var ApiDefinition testAPIDefinition
  145. err = json.Unmarshal([]byte(recorder.Body.String()), &ApiDefinition)
  146. if err != nil {
  147. t.Error("Could not unmarshal API Definition:\n", err, recorder.Body.String())
  148. } else {
  149. if ApiDefinition.APIID != "1" {
  150. t.Error("Response is incorrect - no API ID value in struct :\n", recorder.Body.String())
  151. }
  152. }
  153. }
  154. func TestApiHandlerPost(t *testing.T) {
  155. log.Debug("TEST POST SINGLE API DEFINITION")
  156. uri := "/tyk/apis/1"
  157. method := "POST"
  158. recorder := httptest.NewRecorder()
  159. param := make(url.Values)
  160. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(apiTestDef))
  161. if err != nil {
  162. t.Fatal(err)
  163. }
  164. apiHandler(recorder, req)
  165. var success Success
  166. err = json.Unmarshal([]byte(recorder.Body.String()), &success)
  167. if err != nil {
  168. t.Error("Could not unmarshal POST result:\n", err, recorder.Body.String())
  169. } else {
  170. if success.Status != "ok" {
  171. t.Error("Response is incorrect - not success :\n", recorder.Body.String())
  172. }
  173. }
  174. }
  175. func TestApiHandlerPostDbConfig(t *testing.T) {
  176. log.Debug("TEST POST SINGLE API DEFINITION ON USE_DB_CONFIG")
  177. uri := "/tyk/apis/1"
  178. method := "POST"
  179. config.UseDBAppConfigs = true
  180. defer func() { config.UseDBAppConfigs = false }()
  181. recorder := httptest.NewRecorder()
  182. param := make(url.Values)
  183. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(apiTestDef))
  184. if err != nil {
  185. t.Fatal(err)
  186. }
  187. apiHandler(recorder, req)
  188. var success Success
  189. err = json.Unmarshal([]byte(recorder.Body.String()), &success)
  190. if err != nil {
  191. t.Error("Could not unmarshal POST result:\n", err, recorder.Body.String())
  192. } else {
  193. if success.Status == "ok" {
  194. t.Error("Response is incorrect - expected error due to use_db_app_config :\n", recorder.Body.String())
  195. }
  196. }
  197. }
  198. func TestKeyHandlerNewKey(t *testing.T) {
  199. uri := "/tyk/keys/1234"
  200. method := "POST"
  201. sampleKey := createSampleSession()
  202. body, _ := json.Marshal(&sampleKey)
  203. recorder := httptest.NewRecorder()
  204. param := make(url.Values)
  205. MakeSampleAPI()
  206. param.Set("api_id", "1")
  207. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. keyHandler(recorder, req)
  212. newSuccess := Success{}
  213. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  214. if err != nil {
  215. t.Error("Could not unmarshal success message:\n", err)
  216. } else {
  217. if newSuccess.Status != "ok" {
  218. t.Error("key not created, status error:\n", recorder.Body.String())
  219. }
  220. if newSuccess.Action != "added" {
  221. t.Error("Response is incorrect - action is not 'added' :\n", recorder.Body.String())
  222. }
  223. }
  224. }
  225. func TestKeyHandlerUpdateKey(t *testing.T) {
  226. uri := "/tyk/keys/1234"
  227. method := "PUT"
  228. sampleKey := createSampleSession()
  229. body, _ := json.Marshal(&sampleKey)
  230. recorder := httptest.NewRecorder()
  231. param := make(url.Values)
  232. MakeSampleAPI()
  233. param.Set("api_id", "1")
  234. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. keyHandler(recorder, req)
  239. newSuccess := Success{}
  240. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  241. if err != nil {
  242. t.Error("Could not unmarshal success message:\n", err)
  243. } else {
  244. if newSuccess.Status != "ok" {
  245. t.Error("key not created, status error:\n", recorder.Body.String())
  246. }
  247. if newSuccess.Action != "modified" {
  248. t.Error("Response is incorrect - action is not 'modified' :\n", recorder.Body.String())
  249. }
  250. }
  251. }
  252. func TestKeyHandlerGetKey(t *testing.T) {
  253. MakeSampleAPI()
  254. createKey()
  255. uri := "/tyk/keys/1234"
  256. method := "GET"
  257. recorder := httptest.NewRecorder()
  258. param := make(url.Values)
  259. param.Set("api_id", "1")
  260. req, err := http.NewRequest(method, uri+"?"+param.Encode(), nil)
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. keyHandler(recorder, req)
  265. newSuccess := make(map[string]interface{})
  266. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  267. if err != nil {
  268. t.Error("Could not unmarshal success message:\n", err)
  269. } else {
  270. if recorder.Code != 200 {
  271. t.Error("key not requested, status error:\n", recorder.Body.String())
  272. }
  273. }
  274. }
  275. func TestKeyHandlerGetKeyNoAPIID(t *testing.T) {
  276. MakeSampleAPI()
  277. createKey()
  278. uri := "/tyk/keys/1234"
  279. method := "GET"
  280. recorder := httptest.NewRecorder()
  281. param := make(url.Values)
  282. req, err := http.NewRequest(method, uri+"?"+param.Encode(), nil)
  283. if err != nil {
  284. t.Fatal(err)
  285. }
  286. keyHandler(recorder, req)
  287. newSuccess := make(map[string]interface{})
  288. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  289. if err != nil {
  290. t.Error("Could not unmarshal success message:\n", err)
  291. } else {
  292. if recorder.Code != 200 {
  293. t.Error("key not requested, status error:\n", recorder.Body.String())
  294. }
  295. }
  296. }
  297. func createKey() {
  298. uri := "/tyk/keys/1234"
  299. method := "POST"
  300. sampleKey := createSampleSession()
  301. body, _ := json.Marshal(&sampleKey)
  302. recorder := httptest.NewRecorder()
  303. param := make(url.Values)
  304. req, _ := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  305. keyHandler(recorder, req)
  306. }
  307. func TestKeyHandlerDeleteKey(t *testing.T) {
  308. createKey()
  309. uri := "/tyk/keys/1234?"
  310. method := "DELETE"
  311. recorder := httptest.NewRecorder()
  312. param := make(url.Values)
  313. MakeSampleAPI()
  314. param.Set("api_id", "1")
  315. req, err := http.NewRequest(method, uri+param.Encode(), nil)
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. keyHandler(recorder, req)
  320. newSuccess := Success{}
  321. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  322. if err != nil {
  323. t.Error("Could not unmarshal success message:\n", err)
  324. } else {
  325. if newSuccess.Status != "ok" {
  326. t.Error("key not deleted, status error:\n", recorder.Body.String())
  327. }
  328. if newSuccess.Action != "deleted" {
  329. t.Error("Response is incorrect - action is not 'deleted' :\n", recorder.Body.String())
  330. }
  331. }
  332. }
  333. func TestCreateKeyHandlerCreateNewKey(t *testing.T) {
  334. createKey()
  335. uri := "/tyk/keys/create"
  336. method := "POST"
  337. sampleKey := createSampleSession()
  338. body, _ := json.Marshal(&sampleKey)
  339. recorder := httptest.NewRecorder()
  340. param := make(url.Values)
  341. MakeSampleAPI()
  342. param.Set("api_id", "1")
  343. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. createKeyHandler(recorder, req)
  348. newSuccess := Success{}
  349. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  350. if err != nil {
  351. t.Error("Could not unmarshal success message:\n", err)
  352. } else {
  353. if newSuccess.Status != "ok" {
  354. t.Error("key not created, status error:\n", recorder.Body.String())
  355. }
  356. if newSuccess.Action != "create" {
  357. t.Error("Response is incorrect - action is not 'create' :\n", recorder.Body.String())
  358. }
  359. }
  360. }
  361. func TestCreateKeyHandlerCreateNewKeyNoAPIID(t *testing.T) {
  362. createKey()
  363. uri := "/tyk/keys/create"
  364. method := "POST"
  365. sampleKey := createSampleSession()
  366. body, _ := json.Marshal(&sampleKey)
  367. recorder := httptest.NewRecorder()
  368. param := make(url.Values)
  369. MakeSampleAPI()
  370. req, err := http.NewRequest(method, uri+param.Encode(), strings.NewReader(string(body)))
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. createKeyHandler(recorder, req)
  375. newSuccess := Success{}
  376. err = json.Unmarshal([]byte(recorder.Body.String()), &newSuccess)
  377. if err != nil {
  378. t.Error("Could not unmarshal success message:\n", err)
  379. } else {
  380. if newSuccess.Status != "ok" {
  381. t.Error("key not created, status error:\n", recorder.Body.String())
  382. }
  383. if newSuccess.Action != "create" {
  384. t.Error("Response is incorrect - action is not 'create' :\n", recorder.Body.String())
  385. }
  386. }
  387. }
  388. func TestAPIAuthFail(t *testing.T) {
  389. uri := "/tyk/health/?api_id=1"
  390. method := "GET"
  391. recorder := httptest.NewRecorder()
  392. param := make(url.Values)
  393. req, err := http.NewRequest(method, uri+param.Encode(), nil)
  394. req.Header.Add("x-tyk-authorization", "12345")
  395. if err != nil {
  396. t.Fatal(err)
  397. }
  398. MakeSampleAPI()
  399. CheckIsAPIOwner(healthCheckhandler)(recorder, req)
  400. if recorder.Code == 200 {
  401. t.Error("Access to API should have been blocked, but response code was: ", recorder.Code)
  402. }
  403. }
  404. func TestAPIAuthOk(t *testing.T) {
  405. uri := "/tyk/health/?api_id=1"
  406. method := "GET"
  407. recorder := httptest.NewRecorder()
  408. param := make(url.Values)
  409. req, err := http.NewRequest(method, uri+param.Encode(), nil)
  410. req.Header.Add("x-tyk-authorization", "352d20ee67be67f6340b4c0605b044b7")
  411. if err != nil {
  412. t.Fatal(err)
  413. }
  414. MakeSampleAPI()
  415. CheckIsAPIOwner(healthCheckhandler)(recorder, req)
  416. if recorder.Code != 200 {
  417. t.Error("Access to API should have been blocked, but response code was: ", recorder.Code)
  418. }
  419. }