middleware_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log/slog"
  8. "net/http"
  9. "net/http/httptest"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/mk6i/open-oscar-server/state"
  16. "github.com/mk6i/open-oscar-server/wire"
  17. )
  18. // stubValidator records how many times a key was looked up so the tests can
  19. // assert that CORSMiddleware and the auth layer share a single lookup.
  20. type stubValidator struct {
  21. key *state.WebAPIKey
  22. lookup int
  23. }
  24. func (s *stubValidator) GetAPIKeyByDevKey(_ context.Context, devKey string) (*state.WebAPIKey, error) {
  25. s.lookup++
  26. if s.key == nil || s.key.DevKey != devKey {
  27. return nil, nil
  28. }
  29. return s.key, nil
  30. }
  31. func newTestMiddleware(v APIKeyValidator) *AuthMiddleware {
  32. return NewAuthMiddleware(v, slog.New(slog.NewTextHandler(io.Discard, nil)))
  33. }
  34. // The Web AIM client permanently downgrades to JSONP when a cross-origin
  35. // response arrives without Access-Control-Allow-Origin, so every response the
  36. // auth layer rejects must still carry CORS headers. That only holds while
  37. // CORSMiddleware wraps the auth middleware.
  38. func TestCORSMiddleware_HeadersOnAuthRejection(t *testing.T) {
  39. // The auth layer reports failures in the response envelope rather than the
  40. // HTTP status, so the envelope's statusCode is what identifies a rejection.
  41. tests := []struct {
  42. name string
  43. query string
  44. validator *stubValidator
  45. wantEnvelope string
  46. }{
  47. {
  48. name: "missing credentials",
  49. query: "?f=json",
  50. validator: &stubValidator{},
  51. wantEnvelope: `"statusCode":400`,
  52. },
  53. {
  54. name: "unknown api key",
  55. query: "?k=nosuchkey",
  56. validator: &stubValidator{},
  57. wantEnvelope: `"statusCode":403`,
  58. },
  59. }
  60. for _, tt := range tests {
  61. t.Run(tt.name, func(t *testing.T) {
  62. m := newTestMiddleware(tt.validator)
  63. var reachedHandler bool
  64. h := m.CORSMiddleware(m.AuthenticateFlexible(
  65. http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  66. reachedHandler = true
  67. w.WriteHeader(http.StatusOK)
  68. })))
  69. r := httptest.NewRequest(http.MethodGet, "/im/sendIM"+tt.query, nil)
  70. r.Header.Set("Origin", "http://localhost:8000")
  71. w := httptest.NewRecorder()
  72. h.ServeHTTP(w, r)
  73. assert.False(t, reachedHandler, "auth layer should have rejected the request")
  74. assert.Contains(t, w.Body.String(), tt.wantEnvelope)
  75. assert.Equal(t, "http://localhost:8000", w.Header().Get("Access-Control-Allow-Origin"))
  76. assert.Equal(t, "Origin", w.Header().Get("Vary"))
  77. })
  78. }
  79. }
  80. // A 404 for an endpoint this server does not implement (/service/getAttributes,
  81. // /metrics/sendIM) must reach the client as a 404 rather than as a blocked
  82. // response.
  83. func TestCORSMiddleware_HeadersOn404(t *testing.T) {
  84. m := newTestMiddleware(&stubValidator{})
  85. h := m.CORSMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  86. w.WriteHeader(http.StatusNotFound)
  87. }))
  88. r := httptest.NewRequest(http.MethodGet, "/service/getAttributes?f=json&aimsid=abc", nil)
  89. r.Header.Set("Origin", "http://localhost:8000")
  90. w := httptest.NewRecorder()
  91. h.ServeHTTP(w, r)
  92. assert.Equal(t, http.StatusNotFound, w.Code)
  93. assert.Equal(t, "http://localhost:8000", w.Header().Get("Access-Control-Allow-Origin"))
  94. }
  95. func TestCORSMiddleware_PreflightShortCircuits(t *testing.T) {
  96. m := newTestMiddleware(&stubValidator{})
  97. var reachedNext bool
  98. h := m.CORSMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
  99. reachedNext = true
  100. }))
  101. r := httptest.NewRequest(http.MethodOptions, "/im/sendIM", nil)
  102. r.Header.Set("Origin", "http://localhost:8000")
  103. w := httptest.NewRecorder()
  104. h.ServeHTTP(w, r)
  105. assert.Equal(t, http.StatusNoContent, w.Code)
  106. assert.False(t, reachedNext, "preflight must not reach the wrapped handler")
  107. assert.Equal(t, "http://localhost:8000", w.Header().Get("Access-Control-Allow-Origin"))
  108. assert.Contains(t, w.Header().Get("Access-Control-Allow-Methods"), "POST")
  109. }
  110. // CORSMiddleware runs ahead of authentication and so resolves the API key
  111. // itself; the auth layer behind it must reuse that lookup rather than repeat it.
  112. func TestCORSMiddleware_SharesKeyLookupWithAuth(t *testing.T) {
  113. v := &stubValidator{key: &state.WebAPIKey{
  114. DevID: "dev1",
  115. DevKey: "goodkey",
  116. IsActive: true,
  117. RateLimit: 100,
  118. }}
  119. m := newTestMiddleware(v)
  120. var served bool
  121. h := m.CORSMiddleware(m.Authenticate(
  122. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. served = true
  124. key, ok := r.Context().Value(ContextKeyAPIKey).(*state.WebAPIKey)
  125. require.True(t, ok, "handler should see the validated key")
  126. assert.Equal(t, "dev1", key.DevID)
  127. w.WriteHeader(http.StatusOK)
  128. })))
  129. r := httptest.NewRequest(http.MethodGet, "/aim/startOSCARSession?k=goodkey", nil)
  130. r.Header.Set("Origin", "http://localhost:8000")
  131. w := httptest.NewRecorder()
  132. h.ServeHTTP(w, r)
  133. assert.True(t, served)
  134. assert.Equal(t, http.StatusOK, w.Code)
  135. assert.Equal(t, 1, v.lookup, "key should be resolved once per request, not once per middleware")
  136. }
  137. // Per-key origin allowlists must keep working now that the origin decision is
  138. // made before authentication.
  139. func TestCORSMiddleware_PerKeyOriginAllowlist(t *testing.T) {
  140. v := &stubValidator{key: &state.WebAPIKey{
  141. DevID: "dev1",
  142. DevKey: "goodkey",
  143. IsActive: true,
  144. RateLimit: 100,
  145. AllowedOrigins: []string{"http://allowed.example"},
  146. }}
  147. m := newTestMiddleware(v)
  148. h := m.CORSMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  149. w.WriteHeader(http.StatusOK)
  150. }))
  151. t.Run("allowed origin", func(t *testing.T) {
  152. r := httptest.NewRequest(http.MethodGet, "/im/sendIM?k=goodkey", nil)
  153. r.Header.Set("Origin", "http://allowed.example")
  154. w := httptest.NewRecorder()
  155. h.ServeHTTP(w, r)
  156. assert.Equal(t, "http://allowed.example", w.Header().Get("Access-Control-Allow-Origin"))
  157. })
  158. t.Run("disallowed origin", func(t *testing.T) {
  159. r := httptest.NewRequest(http.MethodGet, "/im/sendIM?k=goodkey", nil)
  160. r.Header.Set("Origin", "http://evil.example")
  161. w := httptest.NewRecorder()
  162. h.ServeHTTP(w, r)
  163. assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
  164. })
  165. }
  166. // A POST body must survive the middleware chain: CORSMiddleware reads the API
  167. // key from the query string only, so it never parses the form.
  168. func TestCORSMiddleware_DoesNotConsumePOSTBody(t *testing.T) {
  169. m := newTestMiddleware(&stubValidator{})
  170. h := m.CORSMiddleware(m.AuthenticateFlexible(
  171. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  172. body, err := io.ReadAll(r.Body)
  173. require.NoError(t, err)
  174. assert.Equal(t, "message=hello", string(body))
  175. w.WriteHeader(http.StatusOK)
  176. })))
  177. r := httptest.NewRequest(http.MethodPost, "/im/sendIM?aimsid=abc", strings.NewReader("message=hello"))
  178. r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  179. r.Header.Set("Origin", "http://localhost:8000")
  180. w := httptest.NewRecorder()
  181. h.ServeHTTP(w, r)
  182. assert.Equal(t, http.StatusOK, w.Code)
  183. }
  184. // The auth layer's own rejections must be JSONP-wrapped too, otherwise a client
  185. // already in JSONP mode gets a script-tag syntax error instead of the reason.
  186. func TestAuthErrorsHonorJSONP(t *testing.T) {
  187. m := newTestMiddleware(&stubValidator{})
  188. t.Run("session error", func(t *testing.T) {
  189. h := m.RequireSession(&stubSessionResolver{}, func(http.ResponseWriter, *http.Request, *Session) {
  190. t.Fatal("handler should not run")
  191. })
  192. r := httptest.NewRequest(http.MethodGet, "/im/sendIM?c=_callbacks_._x&r=7", nil)
  193. w := httptest.NewRecorder()
  194. h.ServeHTTP(w, r)
  195. body := w.Body.String()
  196. assert.True(t, strings.HasPrefix(body, "_callbacks_._x("), "got %s", body)
  197. assert.True(t, strings.HasSuffix(body, ");"), "got %s", body)
  198. assert.Contains(t, body, `"statusCode":400`)
  199. assert.Contains(t, body, `"requestId":"7"`)
  200. // A 4xx would stop the browser executing the script tag.
  201. assert.Equal(t, http.StatusOK, w.Code)
  202. })
  203. t.Run("missing credentials", func(t *testing.T) {
  204. h := m.AuthenticateFlexible(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
  205. t.Fatal("handler should not run")
  206. }))
  207. r := httptest.NewRequest(http.MethodGet, "/im/sendIM?c=cb&r=9", nil)
  208. w := httptest.NewRecorder()
  209. h.ServeHTTP(w, r)
  210. body := w.Body.String()
  211. assert.True(t, strings.HasPrefix(body, "cb("), "got %s", body)
  212. assert.Contains(t, body, `"statusCode":400`)
  213. assert.Contains(t, body, `"requestId":"9"`)
  214. assert.Equal(t, http.StatusOK, w.Code)
  215. })
  216. t.Run("without a callback the session error keeps its HTTP status", func(t *testing.T) {
  217. h := m.RequireSession(&stubSessionResolver{}, func(http.ResponseWriter, *http.Request, *Session) {
  218. t.Fatal("handler should not run")
  219. })
  220. r := httptest.NewRequest(http.MethodGet, "/im/sendIM", nil)
  221. w := httptest.NewRecorder()
  222. h.ServeHTTP(w, r)
  223. assert.Equal(t, http.StatusBadRequest, w.Code)
  224. assert.Contains(t, w.Header().Get("Content-Type"), "json")
  225. })
  226. }
  227. // An XML client cannot parse a JSON error, so it reports an unreadable response
  228. // instead of the reason the auth layer rejected it.
  229. func TestAuthErrorsHonorXML(t *testing.T) {
  230. m := newTestMiddleware(&stubValidator{})
  231. h := m.Authenticate(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
  232. t.Fatal("handler should not run")
  233. }))
  234. t.Run("format in the query string", func(t *testing.T) {
  235. r := httptest.NewRequest(http.MethodGet, "/aim/startOSCARSession?f=xml", nil)
  236. w := httptest.NewRecorder()
  237. h.ServeHTTP(w, r)
  238. assert.Contains(t, w.Header().Get("Content-Type"), "xml")
  239. assert.Contains(t, w.Body.String(), "<statusCode>400</statusCode>")
  240. })
  241. // A POST states the format in its body, the only place clientLogin sends it.
  242. t.Run("format in the POST body", func(t *testing.T) {
  243. r := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader("s=testuser&f=xml"))
  244. r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  245. w := httptest.NewRecorder()
  246. h.ServeHTTP(w, r)
  247. assert.Contains(t, w.Header().Get("Content-Type"), "xml")
  248. assert.Contains(t, w.Body.String(), "<statusCode>400</statusCode>")
  249. })
  250. // A client on the <script> transport needs executable JS back whatever "f"
  251. // says; XML there is a script load failure with no reason attached.
  252. t.Run("a callback outranks the format", func(t *testing.T) {
  253. r := httptest.NewRequest(http.MethodGet, "/aim/startOSCARSession?f=xml&c=cb&r=3", nil)
  254. w := httptest.NewRecorder()
  255. h.ServeHTTP(w, r)
  256. body := w.Body.String()
  257. assert.True(t, strings.HasPrefix(body, "cb("), "got %s", body)
  258. assert.Contains(t, body, `"statusCode":400`)
  259. assert.Contains(t, body, `"requestId":"3"`)
  260. })
  261. }
  262. // stubSessionResolver never resolves a session, so RequireSession always rejects.
  263. type stubSessionResolver struct{}
  264. func (stubSessionResolver) GetSession(context.Context, string) (*Session, error) {
  265. return nil, assert.AnError
  266. }
  267. func (stubSessionResolver) TouchSession(context.Context, string) error { return nil }
  268. func newTestRateLimitMiddleware() *RateLimitMiddleware {
  269. return NewRateLimitMiddleware(wire.DefaultSNACRateLimits(), slog.New(slog.DiscardHandler))
  270. }
  271. // assertRateLimited checks that a response is the Web API's rate limit
  272. // rejection: HTTP 200 at the transport level so the client parses the body,
  273. // with envelope code 430 carrying the rejection inside. wantRetryAfter is the
  274. // expected Retry-After header, "" for a rejection that carries none.
  275. func assertRateLimited(t *testing.T, rec *httptest.ResponseRecorder, wantRetryAfter string) {
  276. t.Helper()
  277. assert.Equal(t, http.StatusOK, rec.Code)
  278. assert.Equal(t, wantRetryAfter, rec.Header().Get("Retry-After"))
  279. var envelope struct {
  280. Response struct {
  281. StatusCode int `json:"statusCode"`
  282. StatusText string `json:"statusText"`
  283. } `json:"response"`
  284. }
  285. assert.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope))
  286. assert.Equal(t, statusRateLimited, envelope.Response.StatusCode)
  287. assert.Equal(t, "rate limit exceeded", envelope.Response.StatusText)
  288. }
  289. func TestRateLimitMiddleware_OSCAR(t *testing.T) {
  290. tests := []struct {
  291. name string
  292. // foodGroup/subGroup passed to the middleware
  293. foodGroup uint16
  294. subGroup uint16
  295. // requests is how many times the wrapped handler is invoked
  296. requests int
  297. // wantCalls is how many of those requests reach the handler
  298. wantCalls int
  299. // wantRetryAfter is the Retry-After header on the final rejection, "" for
  300. // a rejection that carries none
  301. wantRetryAfter string
  302. }{
  303. {
  304. name: "first request is allowed",
  305. foodGroup: wire.ICBM,
  306. subGroup: wire.ICBMChannelMsgToHost,
  307. requests: 1,
  308. wantCalls: 1,
  309. },
  310. {
  311. name: "a burst trips the limit",
  312. foodGroup: wire.ICBM,
  313. subGroup: wire.ICBMChannelMsgToHost,
  314. requests: 5,
  315. wantCalls: 1,
  316. // retryAfterFor rounds the sub-second wait these tight classes need
  317. // up to the minRetryAfter floor.
  318. wantRetryAfter: "1",
  319. },
  320. {
  321. name: "sustained abuse escalates to disconnect",
  322. foodGroup: wire.ICBM,
  323. subGroup: wire.ICBMChannelMsgToHost,
  324. // the 7th request drives the average below DisconnectLevel
  325. requests: 7,
  326. wantCalls: 1,
  327. // a disconnected session has no aimsid left to retry with
  328. wantRetryAfter: "",
  329. },
  330. {
  331. // A non-IM class is enforced the same way. The middleware only ever
  332. // rejects; notifying the client is the per-account monitor's job, and
  333. // it surfaces only the IM class to the alert.
  334. name: "a non-IM class is still enforced",
  335. foodGroup: wire.Feedbag,
  336. subGroup: wire.FeedbagInsertItem,
  337. requests: 5,
  338. wantCalls: 1,
  339. wantRetryAfter: "1",
  340. },
  341. {
  342. name: "unmapped SNAC fails open",
  343. // 0xFFFF is not a food group, so no rate class maps to it
  344. foodGroup: 0xFFFF,
  345. subGroup: 0xFFFF,
  346. requests: 5,
  347. wantCalls: 5,
  348. },
  349. }
  350. for _, tt := range tests {
  351. t.Run(tt.name, func(t *testing.T) {
  352. session := newTestWebAPISession(t, tightRateLimitClasses())
  353. middleware := newTestRateLimitMiddleware()
  354. calls := 0
  355. handler := middleware.OSCAR(tt.foodGroup, tt.subGroup)(
  356. func(w http.ResponseWriter, r *http.Request, s *Session) {
  357. calls++
  358. w.WriteHeader(http.StatusOK)
  359. })
  360. var last *httptest.ResponseRecorder
  361. for range tt.requests {
  362. last = httptest.NewRecorder()
  363. handler(last, httptest.NewRequest(http.MethodGet, "/im/sendIM", nil), session)
  364. }
  365. assert.Equal(t, tt.wantCalls, calls)
  366. // The middleware enforces the limit but never pushes rate limit
  367. // events; that is the per-account monitor's responsibility.
  368. assert.Empty(t, rateLimitEventStatuses(t, session))
  369. if tt.wantCalls < tt.requests {
  370. assertRateLimited(t, last, tt.wantRetryAfter)
  371. } else {
  372. assert.Equal(t, http.StatusOK, last.Code)
  373. }
  374. })
  375. }
  376. }
  377. // Retry-After must name a wait that actually clears the limit. A rejected
  378. // request is still charged, so a client retrying on the advertised interval
  379. // drives the moving average toward that interval: a hint below the class's
  380. // ClearLevel holds the average under the bar and the client stays limited
  381. // forever.
  382. func TestRetryAfterFor_clearsTheLimit(t *testing.T) {
  383. classes := wire.DefaultRateLimitClasses()
  384. for _, class := range classes.All() {
  385. t.Run(fmt.Sprintf("class %d", class.ID), func(t *testing.T) {
  386. sess := state.NewSession()
  387. sess.AddInstance()
  388. now := time.Now()
  389. sess.SetRateClasses(now, classes)
  390. // Burst until the class trips.
  391. var status wire.RateLimitStatus
  392. for status != wire.RateLimitStatusLimited {
  393. now = now.Add(100 * time.Millisecond)
  394. status = sess.EvaluateRateLimit(now, class.ID)
  395. require.NotEqual(t, wire.RateLimitStatusDisconnect, status, "burst escalated past limited")
  396. }
  397. // Wait exactly as long as the rejection advertised, then retry.
  398. retryAfter := retryAfterFor(sess.RateLimitStates()[class.ID-1])
  399. now = now.Add(retryAfter)
  400. assert.Equal(t, wire.RateLimitStatusClear, sess.EvaluateRateLimit(now, class.ID),
  401. "honoring a Retry-After of %s did not clear the limit", retryAfter)
  402. })
  403. }
  404. }
  405. // The rejection advertises the wait computed for the class it charged, not a
  406. // flat one.
  407. func TestRateLimitMiddleware_OSCAR_retryAfterMatchesClass(t *testing.T) {
  408. session := newTestWebAPISession(t, wire.DefaultRateLimitClasses())
  409. middleware := newTestRateLimitMiddleware()
  410. handler := middleware.OSCAR(wire.ICBM, wire.ICBMChannelMsgToHost)(
  411. func(w http.ResponseWriter, r *http.Request, s *Session) {})
  412. classID, ok := wire.DefaultSNACRateLimits().RateClassLookup(wire.ICBM, wire.ICBMChannelMsgToHost)
  413. require.True(t, ok)
  414. // Back-to-back requests trip the limit; keep going until one is rejected.
  415. var rec *httptest.ResponseRecorder
  416. for range 20 {
  417. rec = httptest.NewRecorder()
  418. handler(rec, httptest.NewRequest(http.MethodGet, "/im/sendIM", nil), session)
  419. if rec.Header().Get("Retry-After") != "" {
  420. break
  421. }
  422. }
  423. want := retryAfterFor(session.OSCARSession.Session().RateLimitStates()[classID-1])
  424. assert.Equal(t, fmt.Sprintf("%d", int(want.Seconds())), rec.Header().Get("Retry-After"))
  425. // The production IM class clears at 5100ms, so the wait is necessarily
  426. // longer than the flat 5s hint this replaced.
  427. assert.Greater(t, want, 5*time.Second)
  428. }
  429. // The rejection is encoded in whatever format the request negotiates, via the
  430. // same SendResponse path a normal handler uses.
  431. func TestRateLimitMiddleware_sendRateLimited(t *testing.T) {
  432. tests := []struct {
  433. name string
  434. // query is appended to the request URL
  435. query string
  436. // wantCode is the transport status
  437. wantCode int
  438. // wantBody is the exact response body
  439. wantBody string
  440. // wantContentType is a substring of the Content-Type header
  441. wantContentType string
  442. }{
  443. {
  444. name: "plain JSON",
  445. query: "",
  446. wantCode: http.StatusOK,
  447. wantBody: `{"response":{"statusCode":430,"statusText":"rate limit exceeded","data":{}}}`,
  448. wantContentType: "application/json",
  449. },
  450. {
  451. name: "JSONP callback",
  452. query: "?c=myCallback",
  453. wantCode: http.StatusOK,
  454. wantBody: `myCallback({"response":{"statusCode":430,"statusText":"rate limit exceeded","data":{}}});`,
  455. wantContentType: "application/javascript",
  456. },
  457. {
  458. // The client correlates a JSONP reply solely by response.requestId,
  459. // so the request's "r" param must be echoed back or the request hangs.
  460. name: "JSONP callback echoes requestId",
  461. query: "?c=myCallback&r=42",
  462. wantCode: http.StatusOK,
  463. wantBody: `myCallback({"response":{"statusCode":430,"statusText":"rate limit exceeded","requestId":"42","data":{}}});`,
  464. wantContentType: "application/javascript",
  465. },
  466. {
  467. // Parens would let the callback name inject script; SendResponse
  468. // rejects the malformed callback rather than reflecting it.
  469. name: "invalid JSONP callback is rejected",
  470. query: "?c=alert(1)",
  471. wantCode: http.StatusBadRequest,
  472. // sendJSONError encodes with json.Encoder, which appends a newline.
  473. wantBody: "{\"response\":{\"statusCode\":400,\"statusText\":\"invalid callback parameter\",\"data\":{}}}\n",
  474. wantContentType: "application/json",
  475. },
  476. }
  477. for _, tt := range tests {
  478. t.Run(tt.name, func(t *testing.T) {
  479. rec := httptest.NewRecorder()
  480. newTestRateLimitMiddleware().sendRateLimited(rec, httptest.NewRequest(http.MethodGet, "/im/sendIM"+tt.query, nil), 5*time.Second)
  481. body, err := io.ReadAll(rec.Body)
  482. assert.NoError(t, err)
  483. assert.Equal(t, tt.wantCode, rec.Code)
  484. assert.Contains(t, rec.Header().Get("Content-Type"), tt.wantContentType)
  485. assert.Equal(t, tt.wantBody, string(body))
  486. })
  487. }
  488. }
  489. // A client asking for XML or AMF (via f= or the Accept header) still gets a
  490. // parseable rejection envelope rather than JSON, since the rejection rides the
  491. // same SendResponse path as a normal handler.
  492. func TestRateLimitMiddleware_sendRateLimited_nonJSONFormats(t *testing.T) {
  493. t.Run("f=xml", func(t *testing.T) {
  494. rec := httptest.NewRecorder()
  495. newTestRateLimitMiddleware().sendRateLimited(rec, httptest.NewRequest(http.MethodGet, "/im/sendIM?f=xml", nil), 5*time.Second)
  496. assert.Equal(t, http.StatusOK, rec.Code)
  497. assert.Equal(t, "5", rec.Header().Get("Retry-After"))
  498. assert.Contains(t, rec.Header().Get("Content-Type"), "xml")
  499. body := rec.Body.String()
  500. assert.Contains(t, body, "<statusCode>430</statusCode>")
  501. assert.Contains(t, body, "rate limit exceeded")
  502. })
  503. t.Run("f=amf", func(t *testing.T) {
  504. rec := httptest.NewRecorder()
  505. newTestRateLimitMiddleware().sendRateLimited(rec, httptest.NewRequest(http.MethodGet, "/im/sendIM?f=amf", nil), 5*time.Second)
  506. assert.Equal(t, http.StatusOK, rec.Code)
  507. assert.Equal(t, "5", rec.Header().Get("Retry-After"))
  508. assert.Contains(t, rec.Header().Get("Content-Type"), "amf")
  509. assert.NotEmpty(t, rec.Body.Bytes())
  510. })
  511. t.Run("Accept amf", func(t *testing.T) {
  512. rec := httptest.NewRecorder()
  513. req := httptest.NewRequest(http.MethodGet, "/im/sendIM", nil)
  514. req.Header.Set("Accept", "application/x-amf")
  515. newTestRateLimitMiddleware().sendRateLimited(rec, req, 5*time.Second)
  516. assert.Equal(t, http.StatusOK, rec.Code)
  517. assert.Contains(t, rec.Header().Get("Content-Type"), "amf")
  518. assert.NotEmpty(t, rec.Body.Bytes())
  519. })
  520. }
  521. func TestRateLimitStatusName(t *testing.T) {
  522. tests := []struct {
  523. name string
  524. status wire.RateLimitStatus
  525. want string
  526. }{
  527. {name: "clear", status: wire.RateLimitStatusClear, want: "clear"},
  528. {name: "alert maps to the client's warn", status: wire.RateLimitStatusAlert, want: "warn"},
  529. {name: "limited", status: wire.RateLimitStatusLimited, want: "limit"},
  530. {name: "disconnect", status: wire.RateLimitStatusDisconnect, want: "disconnect"},
  531. {name: "unknown status has no client equivalent", status: wire.RateLimitStatus(0), want: ""},
  532. }
  533. for _, tt := range tests {
  534. t.Run(tt.name, func(t *testing.T) {
  535. assert.Equal(t, tt.want, rateLimitStatusName(tt.status))
  536. })
  537. }
  538. }