middleware_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/base32"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "net/http/httptest"
  9. "path/filepath"
  10. "testing"
  11. "time"
  12. "github.com/grafana/grafana/pkg/api/dtos"
  13. "github.com/grafana/grafana/pkg/bus"
  14. "github.com/grafana/grafana/pkg/infra/remotecache"
  15. "github.com/grafana/grafana/pkg/models"
  16. "github.com/grafana/grafana/pkg/services/auth"
  17. "github.com/grafana/grafana/pkg/services/login"
  18. "github.com/grafana/grafana/pkg/setting"
  19. "github.com/grafana/grafana/pkg/util"
  20. . "github.com/smartystreets/goconvey/convey"
  21. "github.com/stretchr/testify/assert"
  22. "gopkg.in/macaron.v1"
  23. )
  24. const errorTemplate = "error-template"
  25. func mockGetTime() {
  26. var timeSeed int64
  27. getTime = func() time.Time {
  28. fakeNow := time.Unix(timeSeed, 0)
  29. timeSeed++
  30. return fakeNow
  31. }
  32. }
  33. func resetGetTime() {
  34. getTime = time.Now
  35. }
  36. func TestMiddleWareSecurityHeaders(t *testing.T) {
  37. setting.ERR_TEMPLATE_NAME = errorTemplate
  38. Convey("Given the grafana middleware", t, func() {
  39. middlewareScenario(t, "middleware should get correct x-xss-protection header", func(sc *scenarioContext) {
  40. setting.XSSProtectionHeader = true
  41. sc.fakeReq("GET", "/api/").exec()
  42. So(sc.resp.Header().Get("X-XSS-Protection"), ShouldEqual, "1; mode=block")
  43. })
  44. middlewareScenario(t, "middleware should not get x-xss-protection when disabled", func(sc *scenarioContext) {
  45. setting.XSSProtectionHeader = false
  46. sc.fakeReq("GET", "/api/").exec()
  47. So(sc.resp.Header().Get("X-XSS-Protection"), ShouldBeEmpty)
  48. })
  49. middlewareScenario(t, "middleware should add correct Strict-Transport-Security header", func(sc *scenarioContext) {
  50. setting.StrictTransportSecurity = true
  51. setting.Protocol = setting.HTTPS
  52. setting.StrictTransportSecurityMaxAge = 64000
  53. sc.fakeReq("GET", "/api/").exec()
  54. So(sc.resp.Header().Get("Strict-Transport-Security"), ShouldEqual, "max-age=64000")
  55. setting.StrictTransportSecurityPreload = true
  56. sc.fakeReq("GET", "/api/").exec()
  57. So(sc.resp.Header().Get("Strict-Transport-Security"), ShouldEqual, "max-age=64000; preload")
  58. setting.StrictTransportSecuritySubDomains = true
  59. sc.fakeReq("GET", "/api/").exec()
  60. So(sc.resp.Header().Get("Strict-Transport-Security"), ShouldEqual, "max-age=64000; preload; includeSubDomains")
  61. })
  62. })
  63. }
  64. func TestMiddlewareContext(t *testing.T) {
  65. setting.ERR_TEMPLATE_NAME = errorTemplate
  66. Convey("Given the grafana middleware", t, func() {
  67. middlewareScenario(t, "middleware should add context to injector", func(sc *scenarioContext) {
  68. sc.fakeReq("GET", "/").exec()
  69. So(sc.context, ShouldNotBeNil)
  70. })
  71. middlewareScenario(t, "Default middleware should allow get request", func(sc *scenarioContext) {
  72. sc.fakeReq("GET", "/").exec()
  73. So(sc.resp.Code, ShouldEqual, 200)
  74. })
  75. middlewareScenario(t, "middleware should add Cache-Control header for requests to API", func(sc *scenarioContext) {
  76. sc.fakeReq("GET", "/api/search").exec()
  77. So(sc.resp.Header().Get("Cache-Control"), ShouldEqual, "no-cache")
  78. So(sc.resp.Header().Get("Pragma"), ShouldEqual, "no-cache")
  79. So(sc.resp.Header().Get("Expires"), ShouldEqual, "-1")
  80. })
  81. middlewareScenario(t, "middleware should not add Cache-Control header for requests to datasource proxy API", func(sc *scenarioContext) {
  82. sc.fakeReq("GET", "/api/datasources/proxy/1/test").exec()
  83. So(sc.resp.Header().Get("Cache-Control"), ShouldBeEmpty)
  84. So(sc.resp.Header().Get("Pragma"), ShouldBeEmpty)
  85. So(sc.resp.Header().Get("Expires"), ShouldBeEmpty)
  86. })
  87. middlewareScenario(t, "middleware should add Cache-Control header for requests with html response", func(sc *scenarioContext) {
  88. sc.handler(func(c *models.ReqContext) {
  89. data := &dtos.IndexViewData{
  90. User: &dtos.CurrentUser{},
  91. Settings: map[string]interface{}{},
  92. NavTree: []*dtos.NavLink{},
  93. }
  94. c.HTML(200, "index-template", data)
  95. })
  96. sc.fakeReq("GET", "/").exec()
  97. So(sc.resp.Code, ShouldEqual, 200)
  98. So(sc.resp.Header().Get("Cache-Control"), ShouldEqual, "no-cache")
  99. So(sc.resp.Header().Get("Pragma"), ShouldEqual, "no-cache")
  100. So(sc.resp.Header().Get("Expires"), ShouldEqual, "-1")
  101. })
  102. middlewareScenario(t, "middleware should add X-Frame-Options header with deny for request when not allowing embedding", func(sc *scenarioContext) {
  103. sc.fakeReq("GET", "/api/search").exec()
  104. So(sc.resp.Header().Get("X-Frame-Options"), ShouldEqual, "deny")
  105. })
  106. middlewareScenario(t, "middleware should not add X-Frame-Options header for request when allowing embedding", func(sc *scenarioContext) {
  107. setting.AllowEmbedding = true
  108. sc.fakeReq("GET", "/api/search").exec()
  109. So(sc.resp.Header().Get("X-Frame-Options"), ShouldBeEmpty)
  110. })
  111. middlewareScenario(t, "Invalid api key", func(sc *scenarioContext) {
  112. sc.apiKey = "invalid_key_test"
  113. sc.fakeReq("GET", "/").exec()
  114. Convey("Should not init session", func() {
  115. So(sc.resp.Header().Get("Set-Cookie"), ShouldBeEmpty)
  116. })
  117. Convey("Should return 401", func() {
  118. So(sc.resp.Code, ShouldEqual, 401)
  119. So(sc.respJson["message"], ShouldEqual, "Invalid API key")
  120. })
  121. })
  122. middlewareScenario(t, "Using basic auth", func(sc *scenarioContext) {
  123. bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error {
  124. query.Result = &models.User{
  125. Password: util.EncodePassword("myPass", "salt"),
  126. Salt: "salt",
  127. }
  128. return nil
  129. })
  130. bus.AddHandler("test", func(loginUserQuery *models.LoginUserQuery) error {
  131. return nil
  132. })
  133. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  134. query.Result = &models.SignedInUser{OrgId: 2, UserId: 12}
  135. return nil
  136. })
  137. setting.BasicAuthEnabled = true
  138. authHeader := util.GetBasicAuthHeader("myUser", "myPass")
  139. sc.fakeReq("GET", "/").withAuthorizationHeader(authHeader).exec()
  140. Convey("Should init middleware context with user", func() {
  141. So(sc.context.IsSignedIn, ShouldEqual, true)
  142. So(sc.context.OrgId, ShouldEqual, 2)
  143. So(sc.context.UserId, ShouldEqual, 12)
  144. })
  145. })
  146. middlewareScenario(t, "Valid api key", func(sc *scenarioContext) {
  147. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  148. bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error {
  149. query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash}
  150. return nil
  151. })
  152. sc.fakeReq("GET", "/").withValidApiKey().exec()
  153. Convey("Should return 200", func() {
  154. So(sc.resp.Code, ShouldEqual, 200)
  155. })
  156. Convey("Should init middleware context", func() {
  157. So(sc.context.IsSignedIn, ShouldEqual, true)
  158. So(sc.context.OrgId, ShouldEqual, 12)
  159. So(sc.context.OrgRole, ShouldEqual, models.ROLE_EDITOR)
  160. })
  161. })
  162. middlewareScenario(t, "Valid api key, but does not match db hash", func(sc *scenarioContext) {
  163. keyhash := "something_not_matching"
  164. bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error {
  165. query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash}
  166. return nil
  167. })
  168. sc.fakeReq("GET", "/").withValidApiKey().exec()
  169. Convey("Should return api key invalid", func() {
  170. So(sc.resp.Code, ShouldEqual, 401)
  171. So(sc.respJson["message"], ShouldEqual, "Invalid API key")
  172. })
  173. })
  174. middlewareScenario(t, "Valid api key, but expired", func(sc *scenarioContext) {
  175. mockGetTime()
  176. defer resetGetTime()
  177. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  178. bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error {
  179. // api key expired one second before
  180. expires := getTime().Add(-1 * time.Second).Unix()
  181. query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash,
  182. Expires: &expires}
  183. return nil
  184. })
  185. sc.fakeReq("GET", "/").withValidApiKey().exec()
  186. Convey("Should return 401", func() {
  187. So(sc.resp.Code, ShouldEqual, 401)
  188. So(sc.respJson["message"], ShouldEqual, "Expired API key")
  189. })
  190. })
  191. middlewareScenario(t, "Valid api key via Basic auth", func(sc *scenarioContext) {
  192. keyhash := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
  193. bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error {
  194. query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash}
  195. return nil
  196. })
  197. authHeader := util.GetBasicAuthHeader("api_key", "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9")
  198. sc.fakeReq("GET", "/").withAuthorizationHeader(authHeader).exec()
  199. Convey("Should return 200", func() {
  200. So(sc.resp.Code, ShouldEqual, 200)
  201. })
  202. Convey("Should init middleware context", func() {
  203. So(sc.context.IsSignedIn, ShouldEqual, true)
  204. So(sc.context.OrgId, ShouldEqual, 12)
  205. So(sc.context.OrgRole, ShouldEqual, models.ROLE_EDITOR)
  206. })
  207. })
  208. middlewareScenario(t, "Non-expired auth token in cookie which not are being rotated", func(sc *scenarioContext) {
  209. sc.withTokenSessionCookie("token")
  210. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  211. query.Result = &models.SignedInUser{OrgId: 2, UserId: 12}
  212. return nil
  213. })
  214. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*models.UserToken, error) {
  215. return &models.UserToken{
  216. UserId: 12,
  217. UnhashedToken: unhashedToken,
  218. }, nil
  219. }
  220. sc.fakeReq("GET", "/").exec()
  221. Convey("should init context with user info", func() {
  222. So(sc.context.IsSignedIn, ShouldBeTrue)
  223. So(sc.context.UserId, ShouldEqual, 12)
  224. So(sc.context.UserToken.UserId, ShouldEqual, 12)
  225. So(sc.context.UserToken.UnhashedToken, ShouldEqual, "token")
  226. })
  227. Convey("should not set cookie", func() {
  228. So(sc.resp.Header().Get("Set-Cookie"), ShouldEqual, "")
  229. })
  230. })
  231. middlewareScenario(t, "Non-expired auth token in cookie which are being rotated", func(sc *scenarioContext) {
  232. sc.withTokenSessionCookie("token")
  233. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  234. query.Result = &models.SignedInUser{OrgId: 2, UserId: 12}
  235. return nil
  236. })
  237. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*models.UserToken, error) {
  238. return &models.UserToken{
  239. UserId: 12,
  240. UnhashedToken: "",
  241. }, nil
  242. }
  243. sc.userAuthTokenService.TryRotateTokenProvider = func(ctx context.Context, userToken *models.UserToken, clientIP, userAgent string) (bool, error) {
  244. userToken.UnhashedToken = "rotated"
  245. return true, nil
  246. }
  247. maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour)
  248. maxAge := (maxAgeHours + time.Hour).Seconds()
  249. expectedCookie := &http.Cookie{
  250. Name: setting.LoginCookieName,
  251. Value: "rotated",
  252. Path: setting.AppSubUrl + "/",
  253. HttpOnly: true,
  254. MaxAge: int(maxAge),
  255. Secure: setting.CookieSecure,
  256. SameSite: setting.CookieSameSite,
  257. }
  258. sc.fakeReq("GET", "/").exec()
  259. Convey("should init context with user info", func() {
  260. So(sc.context.IsSignedIn, ShouldBeTrue)
  261. So(sc.context.UserId, ShouldEqual, 12)
  262. So(sc.context.UserToken.UserId, ShouldEqual, 12)
  263. So(sc.context.UserToken.UnhashedToken, ShouldEqual, "rotated")
  264. })
  265. Convey("should set cookie", func() {
  266. So(sc.resp.Header().Get("Set-Cookie"), ShouldEqual, expectedCookie.String())
  267. })
  268. })
  269. middlewareScenario(t, "Invalid/expired auth token in cookie", func(sc *scenarioContext) {
  270. sc.withTokenSessionCookie("token")
  271. sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*models.UserToken, error) {
  272. return nil, models.ErrUserTokenNotFound
  273. }
  274. sc.fakeReq("GET", "/").exec()
  275. Convey("should not init context with user info", func() {
  276. So(sc.context.IsSignedIn, ShouldBeFalse)
  277. So(sc.context.UserId, ShouldEqual, 0)
  278. So(sc.context.UserToken, ShouldBeNil)
  279. })
  280. })
  281. middlewareScenario(t, "When anonymous access is enabled", func(sc *scenarioContext) {
  282. setting.AnonymousEnabled = true
  283. setting.AnonymousOrgName = "test"
  284. setting.AnonymousOrgRole = string(models.ROLE_EDITOR)
  285. bus.AddHandler("test", func(query *models.GetOrgByNameQuery) error {
  286. So(query.Name, ShouldEqual, "test")
  287. query.Result = &models.Org{Id: 2, Name: "test"}
  288. return nil
  289. })
  290. sc.fakeReq("GET", "/").exec()
  291. Convey("should init context with org info", func() {
  292. So(sc.context.UserId, ShouldEqual, 0)
  293. So(sc.context.OrgId, ShouldEqual, 2)
  294. So(sc.context.OrgRole, ShouldEqual, models.ROLE_EDITOR)
  295. })
  296. Convey("context signed in should be false", func() {
  297. So(sc.context.IsSignedIn, ShouldBeFalse)
  298. })
  299. })
  300. Convey("auth_proxy", func() {
  301. setting.AuthProxyEnabled = true
  302. setting.AuthProxyWhitelist = ""
  303. setting.AuthProxyAutoSignUp = true
  304. setting.LDAPEnabled = true
  305. setting.AuthProxyHeaderName = "X-WEBAUTH-USER"
  306. setting.AuthProxyHeaderProperty = "username"
  307. setting.AuthProxyHeaders = map[string]string{"Groups": "X-WEBAUTH-GROUPS"}
  308. name := "markelog"
  309. group := "grafana-core-team"
  310. middlewareScenario(t, "should not sync the user if it's in the cache", func(sc *scenarioContext) {
  311. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  312. query.Result = &models.SignedInUser{OrgId: 4, UserId: query.UserId}
  313. return nil
  314. })
  315. key := fmt.Sprintf(cachePrefix, base32.StdEncoding.EncodeToString([]byte(name+"-"+group)))
  316. sc.remoteCacheService.Set(key, int64(33), 0)
  317. sc.fakeReq("GET", "/")
  318. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  319. sc.req.Header.Add("X-WEBAUTH-GROUPS", group)
  320. sc.exec()
  321. Convey("Should init user via cache", func() {
  322. So(sc.context.IsSignedIn, ShouldBeTrue)
  323. So(sc.context.UserId, ShouldEqual, 33)
  324. So(sc.context.OrgId, ShouldEqual, 4)
  325. })
  326. })
  327. middlewareScenario(t, "should respect auto signup option", func(sc *scenarioContext) {
  328. setting.LDAPEnabled = false
  329. setting.AuthProxyAutoSignUp = false
  330. var actualAuthProxyAutoSignUp *bool = nil
  331. bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error {
  332. actualAuthProxyAutoSignUp = &cmd.SignupAllowed
  333. return login.ErrInvalidCredentials
  334. })
  335. sc.fakeReq("GET", "/")
  336. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  337. sc.exec()
  338. assert.False(t, *actualAuthProxyAutoSignUp)
  339. assert.Equal(t, sc.resp.Code, 500)
  340. assert.Nil(t, sc.context)
  341. })
  342. middlewareScenario(t, "should create an user from a header", func(sc *scenarioContext) {
  343. setting.LDAPEnabled = false
  344. setting.AuthProxyAutoSignUp = true
  345. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  346. if query.UserId > 0 {
  347. query.Result = &models.SignedInUser{OrgId: 4, UserId: 33}
  348. return nil
  349. }
  350. return models.ErrUserNotFound
  351. })
  352. bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error {
  353. cmd.Result = &models.User{Id: 33}
  354. return nil
  355. })
  356. sc.fakeReq("GET", "/")
  357. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  358. sc.exec()
  359. Convey("Should create user from header info", func() {
  360. So(sc.context.IsSignedIn, ShouldBeTrue)
  361. So(sc.context.UserId, ShouldEqual, 33)
  362. So(sc.context.OrgId, ShouldEqual, 4)
  363. })
  364. })
  365. middlewareScenario(t, "should get an existing user from header", func(sc *scenarioContext) {
  366. setting.LDAPEnabled = false
  367. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  368. query.Result = &models.SignedInUser{OrgId: 2, UserId: 12}
  369. return nil
  370. })
  371. bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error {
  372. cmd.Result = &models.User{Id: 12}
  373. return nil
  374. })
  375. sc.fakeReq("GET", "/")
  376. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  377. sc.exec()
  378. Convey("should init context with user info", func() {
  379. So(sc.context.IsSignedIn, ShouldBeTrue)
  380. So(sc.context.UserId, ShouldEqual, 12)
  381. So(sc.context.OrgId, ShouldEqual, 2)
  382. })
  383. })
  384. middlewareScenario(t, "should allow the request from whitelist IP", func(sc *scenarioContext) {
  385. setting.AuthProxyWhitelist = "192.168.1.0/24, 2001::0/120"
  386. setting.LDAPEnabled = false
  387. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  388. query.Result = &models.SignedInUser{OrgId: 4, UserId: 33}
  389. return nil
  390. })
  391. bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error {
  392. cmd.Result = &models.User{Id: 33}
  393. return nil
  394. })
  395. sc.fakeReq("GET", "/")
  396. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  397. sc.req.RemoteAddr = "[2001::23]:12345"
  398. sc.exec()
  399. Convey("Should init context with user info", func() {
  400. So(sc.context.IsSignedIn, ShouldBeTrue)
  401. So(sc.context.UserId, ShouldEqual, 33)
  402. So(sc.context.OrgId, ShouldEqual, 4)
  403. })
  404. })
  405. middlewareScenario(t, "should not allow the request from whitelist IP", func(sc *scenarioContext) {
  406. setting.AuthProxyWhitelist = "8.8.8.8"
  407. setting.LDAPEnabled = false
  408. bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
  409. query.Result = &models.SignedInUser{OrgId: 4, UserId: 33}
  410. return nil
  411. })
  412. bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error {
  413. cmd.Result = &models.User{Id: 33}
  414. return nil
  415. })
  416. sc.fakeReq("GET", "/")
  417. sc.req.Header.Add(setting.AuthProxyHeaderName, name)
  418. sc.req.RemoteAddr = "[2001::23]:12345"
  419. sc.exec()
  420. Convey("should return 407 status code", func() {
  421. So(sc.resp.Code, ShouldEqual, 407)
  422. So(sc.context, ShouldBeNil)
  423. })
  424. })
  425. })
  426. })
  427. }
  428. func middlewareScenario(t *testing.T, desc string, fn scenarioFunc) {
  429. Convey(desc, func() {
  430. defer bus.ClearBusHandlers()
  431. setting.LoginCookieName = "grafana_session"
  432. setting.LoginMaxLifetimeDays = 30
  433. sc := &scenarioContext{}
  434. viewsPath, _ := filepath.Abs("../../public/views")
  435. sc.m = macaron.New()
  436. sc.m.Use(AddDefaultResponseHeaders())
  437. sc.m.Use(macaron.Renderer(macaron.RenderOptions{
  438. Directory: viewsPath,
  439. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  440. }))
  441. sc.userAuthTokenService = auth.NewFakeUserAuthTokenService()
  442. sc.remoteCacheService = remotecache.NewFakeStore(t)
  443. sc.m.Use(GetContextHandler(sc.userAuthTokenService, sc.remoteCacheService))
  444. sc.m.Use(OrgRedirect())
  445. sc.defaultHandler = func(c *models.ReqContext) {
  446. sc.context = c
  447. if sc.handlerFunc != nil {
  448. sc.handlerFunc(sc.context)
  449. }
  450. }
  451. sc.m.Get("/", sc.defaultHandler)
  452. fn(sc)
  453. })
  454. }
  455. type scenarioContext struct {
  456. m *macaron.Macaron
  457. context *models.ReqContext
  458. resp *httptest.ResponseRecorder
  459. apiKey string
  460. authHeader string
  461. tokenSessionCookie string
  462. respJson map[string]interface{}
  463. handlerFunc handlerFunc
  464. defaultHandler macaron.Handler
  465. url string
  466. userAuthTokenService *auth.FakeUserAuthTokenService
  467. remoteCacheService *remotecache.RemoteCache
  468. req *http.Request
  469. }
  470. func (sc *scenarioContext) withValidApiKey() *scenarioContext {
  471. sc.apiKey = "eyJrIjoidjVuQXdwTWFmRlA2em5hUzR1cmhkV0RMUzU1MTFNNDIiLCJuIjoiYXNkIiwiaWQiOjF9"
  472. return sc
  473. }
  474. func (sc *scenarioContext) withTokenSessionCookie(unhashedToken string) *scenarioContext {
  475. sc.tokenSessionCookie = unhashedToken
  476. return sc
  477. }
  478. func (sc *scenarioContext) withAuthorizationHeader(authHeader string) *scenarioContext {
  479. sc.authHeader = authHeader
  480. return sc
  481. }
  482. func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
  483. sc.resp = httptest.NewRecorder()
  484. req, err := http.NewRequest(method, url, nil)
  485. So(err, ShouldBeNil)
  486. sc.req = req
  487. return sc
  488. }
  489. func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map[string]string) *scenarioContext {
  490. sc.resp = httptest.NewRecorder()
  491. req, err := http.NewRequest(method, url, nil)
  492. q := req.URL.Query()
  493. for k, v := range queryParams {
  494. q.Add(k, v)
  495. }
  496. req.URL.RawQuery = q.Encode()
  497. So(err, ShouldBeNil)
  498. sc.req = req
  499. return sc
  500. }
  501. func (sc *scenarioContext) handler(fn handlerFunc) *scenarioContext {
  502. sc.handlerFunc = fn
  503. return sc
  504. }
  505. func (sc *scenarioContext) exec() {
  506. if sc.apiKey != "" {
  507. sc.req.Header.Add("Authorization", "Bearer "+sc.apiKey)
  508. }
  509. if sc.authHeader != "" {
  510. sc.req.Header.Add("Authorization", sc.authHeader)
  511. }
  512. if sc.tokenSessionCookie != "" {
  513. sc.req.AddCookie(&http.Cookie{
  514. Name: setting.LoginCookieName,
  515. Value: sc.tokenSessionCookie,
  516. })
  517. }
  518. sc.m.ServeHTTP(sc.resp, sc.req)
  519. if sc.resp.Header().Get("Content-Type") == "application/json; charset=UTF-8" {
  520. err := json.NewDecoder(sc.resp.Body).Decode(&sc.respJson)
  521. So(err, ShouldBeNil)
  522. }
  523. }
  524. type scenarioFunc func(c *scenarioContext)
  525. type handlerFunc func(c *models.ReqContext)