middleware_test.go 20 KB

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