middleware_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/http/httptest"
  8. "path/filepath"
  9. "testing"
  10. "time"
  11. "github.com/grafana/grafana/pkg/bus"
  12. "github.com/grafana/grafana/pkg/infra/remotecache"
  13. m "github.com/grafana/grafana/pkg/models"
  14. "github.com/grafana/grafana/pkg/services/auth"
  15. "github.com/grafana/grafana/pkg/setting"
  16. "github.com/grafana/grafana/pkg/util"
  17. . "github.com/smartystreets/goconvey/convey"
  18. "gopkg.in/macaron.v1"
  19. )
  20. func TestMiddlewareContext(t *testing.T) {
  21. setting.ERR_TEMPLATE_NAME = "error-template"
  22. Convey("Given the grafana middleware", t, func() {
  23. middlewareScenario(t, "middleware should add context to injector", func(sc *scenarioContext) {
  24. sc.fakeReq("GET", "/").exec()
  25. So(sc.context, ShouldNotBeNil)
  26. })
  27. middlewareScenario(t, "Default middleware should allow get request", func(sc *scenarioContext) {
  28. sc.fakeReq("GET", "/").exec()
  29. So(sc.resp.Code, ShouldEqual, 200)
  30. })
  31. middlewareScenario(t, "middleware should add Cache-Control header for GET requests to API", func(sc *scenarioContext) {
  32. sc.fakeReq("GET", "/api/search").exec()
  33. So(sc.resp.Header().Get("Cache-Control"), ShouldEqual, "no-cache")
  34. So(sc.resp.Header().Get("Pragma"), ShouldEqual, "no-cache")
  35. So(sc.resp.Header().Get("Expires"), ShouldEqual, "-1")
  36. })
  37. middlewareScenario(t, "middleware should not add Cache-Control header to for non-API GET requests", func(sc *scenarioContext) {
  38. sc.fakeReq("GET", "/").exec()
  39. So(sc.resp.Header().Get("Cache-Control"), ShouldBeEmpty)
  40. })
  41. middlewareScenario(t, "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(t, "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", "/").withAuthorizationHeader(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(t, "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(t, "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(t, "Valid api key via Basic auth", func(sc *scenarioContext) {
  105. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  106. bus.AddHandler("test", func(query *m.GetApiKeyByNameQuery) error {
  107. query.Result = &m.ApiKey{OrgId: 12, Role: m.ROLE_EDITOR, Key: keyhash}
  108. return nil
  109. })
  110. authHeader := util.GetBasicAuthHeader("api_key", "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9")
  111. sc.fakeReq("GET", "/").withAuthorizationHeader(authHeader).exec()
  112. Convey("Should return 200", func() {
  113. So(sc.resp.Code, ShouldEqual, 200)
  114. })
  115. Convey("Should init middleware context", func() {
  116. So(sc.context.IsSignedIn, ShouldEqual, true)
  117. So(sc.context.OrgId, ShouldEqual, 12)
  118. So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
  119. })
  120. })
  121. middlewareScenario(t, "Non-expired auth token in cookie which not are being rotated", func(sc *scenarioContext) {
  122. sc.withTokenSessionCookie("token")
  123. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  124. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  125. return nil
  126. })
  127. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*m.UserToken, error) {
  128. return &m.UserToken{
  129. UserId: 12,
  130. UnhashedToken: unhashedToken,
  131. }, nil
  132. }
  133. sc.fakeReq("GET", "/").exec()
  134. Convey("should init context with user info", func() {
  135. So(sc.context.IsSignedIn, ShouldBeTrue)
  136. So(sc.context.UserId, ShouldEqual, 12)
  137. So(sc.context.UserToken.UserId, ShouldEqual, 12)
  138. So(sc.context.UserToken.UnhashedToken, ShouldEqual, "token")
  139. })
  140. Convey("should not set cookie", func() {
  141. So(sc.resp.Header().Get("Set-Cookie"), ShouldEqual, "")
  142. })
  143. })
  144. middlewareScenario(t, "Non-expired auth token in cookie which are being rotated", func(sc *scenarioContext) {
  145. sc.withTokenSessionCookie("token")
  146. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  147. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  148. return nil
  149. })
  150. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*m.UserToken, error) {
  151. return &m.UserToken{
  152. UserId: 12,
  153. UnhashedToken: "",
  154. }, nil
  155. }
  156. sc.userAuthTokenService.TryRotateTokenProvider = func(ctx context.Context, userToken *m.UserToken, clientIP, userAgent string) (bool, error) {
  157. userToken.UnhashedToken = "rotated"
  158. return true, nil
  159. }
  160. maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour)
  161. maxAge := (maxAgeHours + time.Hour).Seconds()
  162. expectedCookie := &http.Cookie{
  163. Name: setting.LoginCookieName,
  164. Value: "rotated",
  165. Path: setting.AppSubUrl + "/",
  166. HttpOnly: true,
  167. MaxAge: int(maxAge),
  168. Secure: setting.CookieSecure,
  169. SameSite: setting.CookieSameSite,
  170. }
  171. sc.fakeReq("GET", "/").exec()
  172. Convey("should init context with user info", func() {
  173. So(sc.context.IsSignedIn, ShouldBeTrue)
  174. So(sc.context.UserId, ShouldEqual, 12)
  175. So(sc.context.UserToken.UserId, ShouldEqual, 12)
  176. So(sc.context.UserToken.UnhashedToken, ShouldEqual, "rotated")
  177. })
  178. Convey("should set cookie", func() {
  179. So(sc.resp.Header().Get("Set-Cookie"), ShouldEqual, expectedCookie.String())
  180. })
  181. })
  182. middlewareScenario(t, "Invalid/expired auth token in cookie", func(sc *scenarioContext) {
  183. sc.withTokenSessionCookie("token")
  184. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*m.UserToken, error) {
  185. return nil, m.ErrUserTokenNotFound
  186. }
  187. sc.fakeReq("GET", "/").exec()
  188. Convey("should not init context with user info", func() {
  189. So(sc.context.IsSignedIn, ShouldBeFalse)
  190. So(sc.context.UserId, ShouldEqual, 0)
  191. So(sc.context.UserToken, ShouldBeNil)
  192. })
  193. })
  194. middlewareScenario(t, "When anonymous access is enabled", func(sc *scenarioContext) {
  195. setting.AnonymousEnabled = true
  196. setting.AnonymousOrgName = "test"
  197. setting.AnonymousOrgRole = string(m.ROLE_EDITOR)
  198. bus.AddHandler("test", func(query *m.GetOrgByNameQuery) error {
  199. So(query.Name, ShouldEqual, "test")
  200. query.Result = &m.Org{Id: 2, Name: "test"}
  201. return nil
  202. })
  203. sc.fakeReq("GET", "/").exec()
  204. Convey("should init context with org info", func() {
  205. So(sc.context.UserId, ShouldEqual, 0)
  206. So(sc.context.OrgId, ShouldEqual, 2)
  207. So(sc.context.OrgRole, ShouldEqual, m.ROLE_EDITOR)
  208. })
  209. Convey("context signed in should be false", func() {
  210. So(sc.context.IsSignedIn, ShouldBeFalse)
  211. })
  212. })
  213. Convey("auth_proxy", func() {
  214. setting.AuthProxyEnabled = true
  215. setting.AuthProxyWhitelist = ""
  216. setting.AuthProxyAutoSignUp = true
  217. setting.LdapEnabled = true
  218. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  219. setting.AuthProxyHeaderProperty = "username"
  220. name := "markelog"
  221. middlewareScenario(t, "should not sync the user if it's in the cache", func(sc *scenarioContext) {
  222. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  223. query.Result = &m.SignedInUser{OrgId: 4, UserId: query.UserId}
  224. return nil
  225. })
  226. key := fmt.Sprintf(cachePrefix, name)
  227. sc.remoteCacheService.Set(key, int64(33), 0)
  228. sc.fakeReq("GET", "/")
  229. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  230. sc.exec()
  231. Convey("Should init user via cache", 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(t, "should create an user from a header", func(sc *scenarioContext) {
  238. setting.LdapEnabled = false
  239. setting.AuthProxyAutoSignUp = true
  240. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  241. if query.UserId > 0 {
  242. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  243. return nil
  244. }
  245. return m.ErrUserNotFound
  246. })
  247. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  248. cmd.Result = &m.User{Id: 33}
  249. return nil
  250. })
  251. sc.fakeReq("GET", "/")
  252. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  253. sc.exec()
  254. Convey("Should create user from header info", func() {
  255. So(sc.context.IsSignedIn, ShouldBeTrue)
  256. So(sc.context.UserId, ShouldEqual, 33)
  257. So(sc.context.OrgId, ShouldEqual, 4)
  258. })
  259. })
  260. middlewareScenario(t, "should get an existing user from header", func(sc *scenarioContext) {
  261. setting.LdapEnabled = false
  262. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  263. query.Result = &m.SignedInUser{OrgId: 2, UserId: 12}
  264. return nil
  265. })
  266. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  267. cmd.Result = &m.User{Id: 12}
  268. return nil
  269. })
  270. sc.fakeReq("GET", "/")
  271. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  272. sc.exec()
  273. Convey("should init context with user info", func() {
  274. So(sc.context.IsSignedIn, ShouldBeTrue)
  275. So(sc.context.UserId, ShouldEqual, 12)
  276. So(sc.context.OrgId, ShouldEqual, 2)
  277. })
  278. })
  279. middlewareScenario(t, "should allow the request from whitelist IP", func(sc *scenarioContext) {
  280. setting.AuthProxyWhitelist = "192.168.1.0/24, 2001::0/120"
  281. setting.LdapEnabled = false
  282. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  283. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  284. return nil
  285. })
  286. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  287. cmd.Result = &m.User{Id: 33}
  288. return nil
  289. })
  290. sc.fakeReq("GET", "/")
  291. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  292. sc.req.RemoteAddr = "[2001::23]:12345"
  293. sc.exec()
  294. Convey("Should init context with user info", func() {
  295. So(sc.context.IsSignedIn, ShouldBeTrue)
  296. So(sc.context.UserId, ShouldEqual, 33)
  297. So(sc.context.OrgId, ShouldEqual, 4)
  298. })
  299. })
  300. middlewareScenario(t, "should not allow the request from whitelist IP", func(sc *scenarioContext) {
  301. setting.AuthProxyWhitelist = "8.8.8.8"
  302. setting.LdapEnabled = false
  303. bus.AddHandler("test", func(query *m.GetSignedInUserQuery) error {
  304. query.Result = &m.SignedInUser{OrgId: 4, UserId: 33}
  305. return nil
  306. })
  307. bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error {
  308. cmd.Result = &m.User{Id: 33}
  309. return nil
  310. })
  311. sc.fakeReq("GET", "/")
  312. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  313. sc.req.RemoteAddr = "[2001::23]:12345"
  314. sc.exec()
  315. Convey("should return 407 status code", func() {
  316. So(sc.resp.Code, ShouldEqual, 407)
  317. So(sc.context, ShouldBeNil)
  318. })
  319. })
  320. })
  321. })
  322. }
  323. func middlewareScenario(t *testing.T, desc string, fn scenarioFunc) {
  324. Convey(desc, func() {
  325. defer bus.ClearBusHandlers()
  326. setting.LoginCookieName = "grafana_session"
  327. setting.LoginMaxLifetimeDays = 30
  328. sc := &scenarioContext{}
  329. viewsPath, _ := filepath.Abs("../../public/views")
  330. sc.m = macaron.New()
  331. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  332. Directory: viewsPath,
  333. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  334. }))
  335. sc.userAuthTokenService = auth.NewFakeUserAuthTokenService()
  336. sc.remoteCacheService = remotecache.NewFakeStore(t)
  337. sc.m.Use(GetContextHandler(sc.userAuthTokenService, sc.remoteCacheService))
  338. sc.m.Use(OrgRedirect())
  339. sc.m.Use(AddDefaultResponseHeaders())
  340. sc.defaultHandler = func(c *m.ReqContext) {
  341. sc.context = c
  342. if sc.handlerFunc != nil {
  343. sc.handlerFunc(sc.context)
  344. }
  345. }
  346. sc.m.Get("/", sc.defaultHandler)
  347. fn(sc)
  348. })
  349. }
  350. type scenarioContext struct {
  351. m *macaron.Macaron
  352. context *m.ReqContext
  353. resp *httptest.ResponseRecorder
  354. apiKey string
  355. authHeader string
  356. tokenSessionCookie string
  357. respJson map[string]interface{}
  358. handlerFunc handlerFunc
  359. defaultHandler macaron.Handler
  360. url string
  361. userAuthTokenService *auth.FakeUserAuthTokenService
  362. remoteCacheService *remotecache.RemoteCache
  363. req *http.Request
  364. }
  365. func (sc *scenarioContext) withValidApiKey() *scenarioContext {
  366. sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
  367. return sc
  368. }
  369. func (sc *scenarioContext) withTokenSessionCookie(unhashedToken string) *scenarioContext {
  370. sc.tokenSessionCookie = unhashedToken
  371. return sc
  372. }
  373. func (sc *scenarioContext) withAuthorizationHeader(authHeader string) *scenarioContext {
  374. sc.authHeader = authHeader
  375. return sc
  376. }
  377. func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
  378. sc.resp = httptest.NewRecorder()
  379. req, err := http.NewRequest(method, url, nil)
  380. So(err, ShouldBeNil)
  381. sc.req = req
  382. return sc
  383. }
  384. func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map[string]string) *scenarioContext {
  385. sc.resp = httptest.NewRecorder()
  386. req, err := http.NewRequest(method, url, nil)
  387. q := req.URL.Query()
  388. for k, v := range queryParams {
  389. q.Add(k, v)
  390. }
  391. req.URL.RawQuery = q.Encode()
  392. So(err, ShouldBeNil)
  393. sc.req = req
  394. return sc
  395. }
  396. func (sc *scenarioContext) handler(fn handlerFunc) *scenarioContext {
  397. sc.handlerFunc = fn
  398. return sc
  399. }
  400. func (sc *scenarioContext) exec() {
  401. if sc.apiKey != "" {
  402. sc.req.Header.Add("Authorization", "Bearer "+sc.apiKey)
  403. }
  404. if sc.authHeader != "" {
  405. sc.req.Header.Add("Authorization", sc.authHeader)
  406. }
  407. if sc.tokenSessionCookie != "" {
  408. sc.req.AddCookie(&http.Cookie{
  409. Name: setting.LoginCookieName,
  410. Value: sc.tokenSessionCookie,
  411. })
  412. }
  413. sc.m.ServeHTTP(sc.resp, sc.req)
  414. if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
  415. err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
  416. So(err, ShouldBeNil)
  417. }
  418. }
  419. type scenarioFunc func(c *scenarioContext)
  420. type handlerFunc func(c *m.ReqContext)