middleware_test.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "testing"
  8. "github.com/Unknwon/macaron"
  9. "github.com/grafana/grafana/pkg/bus"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/util"
  12. "github.com/macaron-contrib/session"
  13. . "github.com/smartystreets/goconvey/convey"
  14. )
  15. type scenarioContext struct {
  16. m *macaron.Macaron
  17. context *Context
  18. resp *httptest.ResponseRecorder
  19. apiKey string
  20. respJson map[string]interface{}
  21. }
  22. func (sc *scenarioContext) PerformGet(url string) {
  23. req, err := http.NewRequest("GET", "/", nil)
  24. So(err, ShouldBeNil)
  25. if sc.apiKey != "" {
  26. req.Header.Add("Authorization", "Bearer "+sc.apiKey)
  27. }
  28. sc.m.ServeHTTP(sc.resp, req)
  29. if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
  30. err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
  31. So(err, ShouldBeNil)
  32. }
  33. }
  34. type scenarioFunc func(c *scenarioContext)
  35. type reqModifier func(c *http.Request)
  36. func middlewareScenario(desc string, fn scenarioFunc) {
  37. Convey(desc, func() {
  38. sc := &scenarioContext{}
  39. viewsPath, _ := filepath.Abs("../../public/views")
  40. sc.m = macaron.New()
  41. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  42. Directory: viewsPath,
  43. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  44. }))
  45. sc.m.Use(GetContextHandler())
  46. // mock out gc goroutine
  47. startSessionGC = func() {}
  48. sc.m.Use(Sessioner(&session.Options{}))
  49. sc.m.Get("/", func(c *Context) {
  50. sc.context = c
  51. })
  52. sc.resp = httptest.NewRecorder()
  53. fn(sc)
  54. })
  55. }
  56. func TestMiddlewareContext(t *testing.T) {
  57. Convey("Given grafana context", t, func() {
  58. middlewareScenario("middleware should add context to injector", func(sc *scenarioContext) {
  59. sc.PerformGet("/")
  60. So(sc.context, ShouldNotBeNil)
  61. })
  62. middlewareScenario("Default middleware should allow get request", func(sc *scenarioContext) {
  63. sc.PerformGet("/")
  64. So(sc.resp.Code, ShouldEqual, 200)
  65. })
  66. middlewareScenario("Non api request should init session", func(sc *scenarioContext) {
  67. sc.PerformGet("/")
  68. So(sc.resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "grafana_sess")
  69. })
  70. middlewareScenario("Invalid api key", func(sc *scenarioContext) {
  71. sc.apiKey = "invalid_key_test"
  72. sc.PerformGet("/")
  73. Convey("Should not init session", func() {
  74. So(sc.resp.Header().Get("Set-Cookie"), ShouldBeEmpty)
  75. })
  76. Convey("Should return 401", func() {
  77. So(sc.resp.Code, ShouldEqual, 401)
  78. So(sc.respJson["message"], ShouldEqual, "Invalid API key")
  79. })
  80. })
  81. middlewareScenario("Valid api key", func(sc *scenarioContext) {
  82. sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
  83. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  84. bus.AddHandler("test", func(query *m.GetApiKeyByNameQuery) error {
  85. query.Result = &m.ApiKey{OrgId: 12, Role: m.ROLE_EDITOR, Key: keyhash}
  86. return nil
  87. })
  88. sc.PerformGet("/")
  89. Convey("Should return 200", func() {
  90. So(sc.resp.Code, ShouldEqual, 200)
  91. })
  92. Convey("Should init middleware context", func() {
  93. So(sc.context.OrgId, ShouldEqual, 12)
  94. So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
  95. })
  96. })
  97. })
  98. }