middleware_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/services/session"
  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 *m.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 *m.ReqContext) {
  106. c.Session.Set(session.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. setting.LdapEnabled = false
  142. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  143. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  144. return nil
  145. })
  146. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  147. cmd.Result = &m.User{Id: 12}
  148. return nil
  149. })
  150. sc.fakeReq("GET", "/")
  151. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  152. sc.exec()
  153. Convey("should init context with user info", func() {
  154. So(sc.context.IsSignedIn, ShouldBeTrue)
  155. So(sc.context.UserId, ShouldEqual, 12)
  156. So(sc.context.OrgId, ShouldEqual, 2)
  157. })
  158. })
  159. middlewareScenario("When auth_proxy is enabled enabled and user does not exists", func(sc *scenarioContext) {
  160. setting.AuthProxyEnabled = true
  161. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  162. setting.AuthProxyHeaderProperty = "username"
  163. setting.AuthProxyAutoSignUp = true
  164. setting.LdapEnabled = false
  165. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  166. if query.UserId > 0 {
  167. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  168. return nil
  169. } else {
  170. return m.ErrUserNotFound
  171. }
  172. })
  173. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  174. cmd.Result = &m.User{Id: 33}
  175. return nil
  176. })
  177. sc.fakeReq("GET", "/")
  178. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  179. sc.exec()
  180. Convey("Should create user if auto sign up is enabled", func() {
  181. So(sc.context.IsSignedIn, ShouldBeTrue)
  182. So(sc.context.UserId, ShouldEqual, 33)
  183. So(sc.context.OrgId, ShouldEqual, 4)
  184. })
  185. })
  186. middlewareScenario("When auth_proxy is enabled and IPv4 request RemoteAddr is not trusted", func(sc *scenarioContext) {
  187. setting.AuthProxyEnabled = true
  188. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  189. setting.AuthProxyHeaderProperty = "username"
  190. setting.AuthProxyWhitelist = "192.168.1.1, 2001::23"
  191. sc.fakeReq("GET", "/")
  192. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  193. sc.req.RemoteAddr = "192.168.3.1:12345"
  194. sc.exec()
  195. Convey("should return 407 status code", func() {
  196. So(sc.resp.Code, ShouldEqual, 407)
  197. So(sc.resp.Body.String(), ShouldContainSubstring, "Request for user (torkelo) from 192.168.3.1 is not from the authentication proxy")
  198. })
  199. })
  200. middlewareScenario("When auth_proxy is enabled and IPv6 request RemoteAddr is not trusted", func(sc *scenarioContext) {
  201. setting.AuthProxyEnabled = true
  202. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  203. setting.AuthProxyHeaderProperty = "username"
  204. setting.AuthProxyWhitelist = "192.168.1.1, 2001::23"
  205. sc.fakeReq("GET", "/")
  206. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  207. sc.req.RemoteAddr = "[2001:23]:12345"
  208. sc.exec()
  209. Convey("should return 407 status code", func() {
  210. So(sc.resp.Code, ShouldEqual, 407)
  211. So(sc.resp.Body.String(), ShouldContainSubstring, "Request for user (torkelo) from 2001:23 is not from the authentication proxy")
  212. })
  213. })
  214. middlewareScenario("When auth_proxy is enabled and request RemoteAddr is trusted", func(sc *scenarioContext) {
  215. setting.AuthProxyEnabled = true
  216. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  217. setting.AuthProxyHeaderProperty = "username"
  218. setting.AuthProxyWhitelist = "192.168.1.1, 2001::23"
  219. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  220. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  221. return nil
  222. })
  223. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  224. cmd.Result = &m.User{Id: 33}
  225. return nil
  226. })
  227. sc.fakeReq("GET", "/")
  228. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  229. sc.req.RemoteAddr = "[2001::23]:12345"
  230. sc.exec()
  231. Convey("Should init context with user info", func() {
  232. So(sc.context.IsSignedIn, ShouldBeTrue)
  233. So(sc.context.UserId, ShouldEqual, 33)
  234. So(sc.context.OrgId, ShouldEqual, 4)
  235. })
  236. })
  237. middlewareScenario("When session exists for previous user, create a new session", func(sc *scenarioContext) {
  238. setting.AuthProxyEnabled = true
  239. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  240. setting.AuthProxyHeaderProperty = "username"
  241. setting.AuthProxyWhitelist = ""
  242. bus.AddHandler("test", func(query *m.UpsertUserCommand) error {
  243. query.Result = &m.User{Id: 32}
  244. return nil
  245. })
  246. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  247. query.Result = &m.SignedInUser{OrgId: 4, UserId: 32}
  248. return nil
  249. })
  250. // create session
  251. sc.fakeReq("GET", "/").handler(func(c *m.ReqContext) {
  252. c.Session.Set(session.SESS_KEY_USERID, int64(33))
  253. }).exec()
  254. oldSessionID := sc.context.Session.ID()
  255. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  256. sc.exec()
  257. newSessionID := sc.context.Session.ID()
  258. Convey("Should not share session with other user", func() {
  259. So(oldSessionID, ShouldNotEqual, newSessionID)
  260. })
  261. })
  262. middlewareScenario("When auth_proxy and ldap enabled call sync with ldap user", func(sc *scenarioContext) {
  263. setting.AuthProxyEnabled = true
  264. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  265. setting.AuthProxyHeaderProperty = "username"
  266. setting.AuthProxyWhitelist = ""
  267. setting.LdapEnabled = true
  268. called := false
  269. syncGrafanaUserWithLdapUser = func(query *m.LoginUserQuery) error {
  270. called = true
  271. query.User = &m.User{Id: 32}
  272. return nil
  273. }
  274. bus.AddHandler("test", func(query *m.UpsertUserCommand) error {
  275. query.Result = &m.User{Id: 32}
  276. return nil
  277. })
  278. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  279. query.Result = &m.SignedInUser{OrgId: 4, UserId: 32}
  280. return nil
  281. })
  282. sc.fakeReq("GET", "/")
  283. sc.req.Header.Add("X-WEBAUTH-USER", "torkelo")
  284. sc.exec()
  285. Convey("Should call syncGrafanaUserWithLdapUser", func() {
  286. So(called, ShouldBeTrue)
  287. })
  288. })
  289. })
  290. }
  291. func middlewareScenario(desc string, fn scenarioFunc) {
  292. Convey(desc, func() {
  293. defer bus.ClearBusHandlers()
  294. sc := &scenarioContext{}
  295. viewsPath, _ := filepath.Abs("../../public/views")
  296. sc.m = macaron.New()
  297. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  298. Directory: viewsPath,
  299. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  300. }))
  301. sc.m.Use(GetContextHandler())
  302. // mock out gc goroutine
  303. session.StartSessionGC = func() {}
  304. sc.m.Use(Sessioner(&ms.Options{}, 0))
  305. sc.m.Use(OrgRedirect())
  306. sc.m.Use(AddDefaultResponseHeaders())
  307. sc.defaultHandler = func(c *m.ReqContext) {
  308. sc.context = c
  309. if sc.handlerFunc != nil {
  310. sc.handlerFunc(sc.context)
  311. }
  312. }
  313. sc.m.Get("/", sc.defaultHandler)
  314. fn(sc)
  315. })
  316. }
  317. type scenarioContext struct {
  318. m *macaron.Macaron
  319. context *m.ReqContext
  320. resp *httptest.ResponseRecorder
  321. apiKey string
  322. authHeader string
  323. respJson map[string]interface{}
  324. handlerFunc handlerFunc
  325. defaultHandler macaron.Handler
  326. url string
  327. req *http.Request
  328. }
  329. func (sc *scenarioContext) withValidApiKey() *scenarioContext {
  330. sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
  331. return sc
  332. }
  333. func (sc *scenarioContext) withInvalidApiKey() *scenarioContext {
  334. sc.apiKey = "nvalidhhhhds"
  335. return sc
  336. }
  337. func (sc *scenarioContext) withAuthoriziationHeader(authHeader string) *scenarioContext {
  338. sc.authHeader = authHeader
  339. return sc
  340. }
  341. func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
  342. sc.resp = httptest.NewRecorder()
  343. req, err := http.NewRequest(method, url, nil)
  344. So(err, ShouldBeNil)
  345. sc.req = req
  346. // add session cookie from last request
  347. if sc.context != nil {
  348. if sc.context.Session.ID() != "" {
  349. req.Header.Add("Cookie", "grafana_sess="+sc.context.Session.ID()+";")
  350. }
  351. }
  352. return sc
  353. }
  354. func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map[string]string) *scenarioContext {
  355. sc.resp = httptest.NewRecorder()
  356. req, err := http.NewRequest(method, url, nil)
  357. q := req.URL.Query()
  358. for k, v := range queryParams {
  359. q.Add(k, v)
  360. }
  361. req.URL.RawQuery = q.Encode()
  362. So(err, ShouldBeNil)
  363. sc.req = req
  364. return sc
  365. }
  366. func (sc *scenarioContext) handler(fn handlerFunc) *scenarioContext {
  367. sc.handlerFunc = fn
  368. return sc
  369. }
  370. func (sc *scenarioContext) exec() {
  371. if sc.apiKey != "" {
  372. sc.req.Header.Add("Authorization", "Bearer "+sc.apiKey)
  373. }
  374. if sc.authHeader != "" {
  375. sc.req.Header.Add("Authorization", sc.authHeader)
  376. }
  377. sc.m.ServeHTTP(sc.resp, sc.req)
  378. if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
  379. err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
  380. So(err, ShouldBeNil)
  381. }
  382. }
  383. type scenarioFunc func(c *scenarioContext)
  384. type handlerFunc func(c *m.ReqContext)