middleware_test.go 13 KB

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