middleware_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "testing"
  8. "github.com/go-macaron/session"
  9. "github.com/grafana/grafana/pkg/bus"
  10. l "github.com/grafana/grafana/pkg/login"
  11. m "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/setting"
  13. "github.com/grafana/grafana/pkg/util"
  14. . "github.com/smartystreets/goconvey/convey"
  15. "gopkg.in/macaron.v1"
  16. )
  17. func TestMiddlewareContext(t *testing.T) {
  18. Convey("Given the grafana middleware", t, func() {
  19. middlewareScenario("middleware should add context to injector", func(sc *scenarioContext) {
  20. sc.fakeReq("GET", "/").exec()
  21. So(sc.context, ShouldNotBeNil)
  22. })
  23. middlewareScenario("Default middleware should allow get request", func(sc *scenarioContext) {
  24. sc.fakeReq("GET", "/").exec()
  25. So(sc.resp.Code, ShouldEqual, 200)
  26. })
  27. middlewareScenario("middleware should add Cache-Control header for GET requests to API", func(sc *scenarioContext) {
  28. sc.fakeReq("GET", "/api/search").exec()
  29. So(sc.resp.Header().Get("Cache-Control"), ShouldEqual, "no-cache")
  30. So(sc.resp.Header().Get("Pragma"), ShouldEqual, "no-cache")
  31. So(sc.resp.Header().Get("Expires"), ShouldEqual, "-1")
  32. })
  33. middlewareScenario("middleware should not add Cache-Control header to for non-API GET requests", func(sc *scenarioContext) {
  34. sc.fakeReq("GET", "/").exec()
  35. So(sc.resp.Header().Get("Cache-Control"), ShouldBeEmpty)
  36. })
  37. middlewareScenario("Non api request should init session", func(sc *scenarioContext) {
  38. sc.fakeReq("GET", "/").exec()
  39. So(sc.resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "grafana_sess")
  40. })
  41. middlewareScenario("Invalid api key", func(sc *scenarioContext) {
  42. sc.apiKey = "invalid_key_test"
  43. sc.fakeReq("GET", "/").exec()
  44. Convey("Should not init session", func() {
  45. So(sc.resp.Header().Get("Set-Cookie"), ShouldBeEmpty)
  46. })
  47. Convey("Should return 401", func() {
  48. So(sc.resp.Code, ShouldEqual, 401)
  49. So(sc.respJson["message"], ShouldEqual, "Invalid API key")
  50. })
  51. })
  52. middlewareScenario("Using basic auth", func(sc *scenarioContext) {
  53. bus.AddHandler("test", func(query *m.GetUserByLoginQuery) error {
  54. query.Result = &m.User{
  55. Password: util.EncodePassword("myPass", "salt"),
  56. Salt: "salt",
  57. }
  58. return nil
  59. })
  60. bus.AddHandler("test", func(loginUserQuery *l.LoginUserQuery) error {
  61. return nil
  62. })
  63. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  64. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  65. return nil
  66. })
  67. setting.BasicAuthEnabled = true
  68. authHeader := util.GetBasicAuthHeader("myUser", "myPass")
  69. sc.fakeReq("GET", "/").withAuthoriziationHeader(authHeader).exec()
  70. Convey("Should init middleware context with user", func() {
  71. So(sc.context.IsSignedIn, ShouldEqual, true)
  72. So(sc.context.OrgId, ShouldEqual, 2)
  73. So(sc.context.UserId, ShouldEqual, 12)
  74. })
  75. })
  76. middlewareScenario("Valid api key", func(sc *scenarioContext) {
  77. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  78. bus.AddHandler("test", func(query *m.GetApiKeyByNameQuery) error {
  79. query.Result = &m.ApiKey{OrgId: 12, Role: m.ROLE_EDITOR, Key: keyhash}
  80. return nil
  81. })
  82. sc.fakeReq("GET", "/").withValidApiKey().exec()
  83. Convey("Should return 200", func() {
  84. So(sc.resp.Code, ShouldEqual, 200)
  85. })
  86. Convey("Should init middleware context", func() {
  87. So(sc.context.IsSignedIn, ShouldEqual, true)
  88. So(sc.context.OrgId, ShouldEqual, 12)
  89. So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
  90. })
  91. })
  92. middlewareScenario("Valid api key, but does not match db hash", func(sc *scenarioContext) {
  93. keyhash := "something_not_matching"
  94. bus.AddHandler("test", func(query *m.GetApiKeyByNameQuery) error {
  95. query.Result = &m.ApiKey{OrgId: 12, Role: m.ROLE_EDITOR, Key: keyhash}
  96. return nil
  97. })
  98. sc.fakeReq("GET", "/").withValidApiKey().exec()
  99. Convey("Should return api key invalid", func() {
  100. So(sc.resp.Code, ShouldEqual, 401)
  101. So(sc.respJson["message"], ShouldEqual, "Invalid API key")
  102. })
  103. })
  104. middlewareScenario("UserId in session", func(sc *scenarioContext) {
  105. sc.fakeReq("GET", "/").handler(func(c *Context) {
  106. c.Session.Set(SESS_KEY_USERID, int64(12))
  107. }).exec()
  108. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  109. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  110. return nil
  111. })
  112. sc.fakeReq("GET", "/").exec()
  113. Convey("should init context with user info", func() {
  114. So(sc.context.IsSignedIn, ShouldBeTrue)
  115. So(sc.context.UserId, ShouldEqual, 12)
  116. })
  117. })
  118. middlewareScenario("When anonymous access is enabled", func(sc *scenarioContext) {
  119. setting.AnonymousEnabled = true
  120. setting.AnonymousOrgName = "test"
  121. setting.AnonymousOrgRole = string(m.ROLE_EDITOR)
  122. bus.AddHandler("test", func(query *m.GetOrgByNameQuery) error {
  123. So(query.Name, ShouldEqual, "test")
  124. query.Result = &m.Org{Id: 2, Name: "test"}
  125. return nil
  126. })
  127. sc.fakeReq("GET", "/").exec()
  128. Convey("should init context with org info", func() {
  129. So(sc.context.UserId, ShouldEqual, 0)
  130. So(sc.context.OrgId, ShouldEqual, 2)
  131. So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
  132. })
  133. Convey("context signed in should be false", func() {
  134. So(sc.context.IsSignedIn, ShouldBeFalse)
  135. })
  136. })
  137. middlewareScenario("When auth_proxy is enabled enabled and user exists", func(sc *scenarioContext) {
  138. setting.AuthProxyEnabled = true
  139. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  140. setting.AuthProxyHeaderProperty = "username"
  141. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  142. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  143. return nil
  144. })
  145. sc.fakeReq("GET", "/")
  146. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  147. sc.exec()
  148. Convey("should init context with user info", func() {
  149. So(sc.context.IsSignedIn, ShouldBeTrue)
  150. So(sc.context.UserId, ShouldEqual, 12)
  151. So(sc.context.OrgId, ShouldEqual, 2)
  152. })
  153. })
  154. middlewareScenario("When auth_proxy is enabled enabled and user does not exists", func(sc *scenarioContext) {
  155. setting.AuthProxyEnabled = true
  156. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  157. setting.AuthProxyHeaderProperty = "username"
  158. setting.AuthProxyAutoSignUp = true
  159. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  160. if query.UserId > 0 {
  161. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  162. return nil
  163. } else {
  164. return m.ErrUserNotFound
  165. }
  166. })
  167. bus.AddHandler("test", func(cmd *m.CreateUserCommand) error {
  168. cmd.Result = m.User{Id: 33}
  169. return nil
  170. })
  171. sc.fakeReq("GET", "/")
  172. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  173. sc.exec()
  174. Convey("Should create user if auto sign up is enabled", func() {
  175. So(sc.context.IsSignedIn, ShouldBeTrue)
  176. So(sc.context.UserId, ShouldEqual, 33)
  177. So(sc.context.OrgId, ShouldEqual, 4)
  178. })
  179. })
  180. middlewareScenario("When auth_proxy is enabled and request RemoteAddr is not trusted", func(sc *scenarioContext) {
  181. setting.AuthProxyEnabled = true
  182. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  183. setting.AuthProxyHeaderProperty = "username"
  184. setting.AuthProxyWhitelist = "192.168.1.1, 192.168.2.1"
  185. sc.fakeReq("GET", "/")
  186. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  187. sc.req.RemoteAddr = "192.168.3.1:12345"
  188. sc.exec()
  189. Convey("should return 407 status code", func() {
  190. So(sc.resp.Code, ShouldEqual, 407)
  191. })
  192. })
  193. middlewareScenario("When auth_proxy is enabled and request RemoteAddr is trusted", func(sc *scenarioContext) {
  194. setting.AuthProxyEnabled = true
  195. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  196. setting.AuthProxyHeaderProperty = "username"
  197. setting.AuthProxyWhitelist = "192.168.1.1, 192.168.2.1"
  198. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  199. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  200. return nil
  201. })
  202. sc.fakeReq("GET", "/")
  203. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  204. sc.req.RemoteAddr = "192.168.2.1:12345"
  205. sc.exec()
  206. Convey("Should init context with user info", func() {
  207. So(sc.context.IsSignedIn, ShouldBeTrue)
  208. So(sc.context.UserId, ShouldEqual, 33)
  209. So(sc.context.OrgId, ShouldEqual, 4)
  210. })
  211. })
  212. middlewareScenario("When session exists for previous user, create a new session", func(sc *scenarioContext) {
  213. setting.AuthProxyEnabled = true
  214. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  215. setting.AuthProxyHeaderProperty = "username"
  216. setting.AuthProxyWhitelist = ""
  217. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  218. query.Result = &m.SignedInUser{OrgId: 4, UserId: 32}
  219. return nil
  220. })
  221. // create session
  222. sc.fakeReq("GET", "/").handler(func(c *Context) {
  223. c.Session.Set(SESS_KEY_USERID, int64(33))
  224. }).exec()
  225. oldSessionID := sc.context.Session.ID()
  226. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  227. sc.exec()
  228. newSessionID := sc.context.Session.ID()
  229. Convey("Should not share session with other user", func() {
  230. So(oldSessionID, ShouldNotEqual, newSessionID)
  231. })
  232. })
  233. middlewareScenario("When auth_proxy and ldap enabled call sync with ldap user", func(sc *scenarioContext) {
  234. setting.AuthProxyEnabled = true
  235. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  236. setting.AuthProxyHeaderProperty = "username"
  237. setting.AuthProxyWhitelist = ""
  238. setting.LdapEnabled = true
  239. called := false
  240. syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQuery) error {
  241. called = true
  242. return nil
  243. }
  244. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  245. query.Result = &m.SignedInUser{OrgId: 4, UserId: 32}
  246. return nil
  247. })
  248. sc.fakeReq("GET", "/")
  249. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  250. sc.exec()
  251. Convey("Should call syncGrafanaUserWithLdapUser", func() {
  252. So(called, ShouldBeTrue)
  253. })
  254. })
  255. })
  256. }
  257. func middlewareScenario(desc string, fn scenarioFunc) {
  258. Convey(desc, func() {
  259. defer bus.ClearBusHandlers()
  260. sc := &scenarioContext{}
  261. viewsPath, _ := filepath.Abs("../../public/views")
  262. sc.m = macaron.New()
  263. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  264. Directory: viewsPath,
  265. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  266. }))
  267. sc.m.Use(GetContextHandler())
  268. // mock out gc goroutine
  269. startSessionGC = func() {}
  270. sc.m.Use(Sessioner(&session.Options{}))
  271. sc.m.Use(OrgRedirect())
  272. sc.m.Use(AddDefaultResponseHeaders())
  273. sc.defaultHandler = func(c *Context) {
  274. sc.context = c
  275. if sc.handlerFunc != nil {
  276. sc.handlerFunc(sc.context)
  277. }
  278. }
  279. sc.m.Get("/", sc.defaultHandler)
  280. fn(sc)
  281. })
  282. }
  283. type scenarioContext struct {
  284. m *macaron.Macaron
  285. context *Context
  286. resp *httptest.ResponseRecorder
  287. apiKey string
  288. authHeader string
  289. respJson map[string]interface{}
  290. handlerFunc handlerFunc
  291. defaultHandler macaron.Handler
  292. req *http.Request
  293. }
  294. func (sc *scenarioContext) withValidApiKey() *scenarioContext {
  295. sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
  296. return sc
  297. }
  298. func (sc *scenarioContext) withInvalidApiKey() *scenarioContext {
  299. sc.apiKey = "nvalidhhhhds"
  300. return sc
  301. }
  302. func (sc *scenarioContext) withAuthoriziationHeader(authHeader string) *scenarioContext {
  303. sc.authHeader = authHeader
  304. return sc
  305. }
  306. func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
  307. sc.resp = httptest.NewRecorder()
  308. req, err := http.NewRequest(method, url, nil)
  309. So(err, ShouldBeNil)
  310. sc.req = req
  311. // add session cookie from last request
  312. if sc.context != nil {
  313. if sc.context.Session.ID() != "" {
  314. req.Header.Add("Cookie", "grafana_sess="+sc.context.Session.ID()+";")
  315. }
  316. }
  317. return sc
  318. }
  319. func (sc *scenarioContext) handler(fn handlerFunc) *scenarioContext {
  320. sc.handlerFunc = fn
  321. return sc
  322. }
  323. func (sc *scenarioContext) exec() {
  324. if sc.apiKey != "" {
  325. sc.req.Header.Add("Authorization", "Bearer "+sc.apiKey)
  326. }
  327. if sc.authHeader != "" {
  328. sc.req.Header.Add("Authorization", sc.authHeader)
  329. }
  330. sc.m.ServeHTTP(sc.resp, sc.req)
  331. if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
  332. err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
  333. So(err, ShouldBeNil)
  334. }
  335. }
  336. type scenarioFunc func(c *scenarioContext)
  337. type handlerFunc func(c *Context)