MCPcopy Index your code
hub / github.com/coder/coder / TestRateLimit

Function TestRateLimit

coderd/httpmw/ratelimit_test.go:32–149  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

30}
31
32func TestRateLimit(t *testing.T) {
33 t.Parallel()
34 t.Run("NoUserSucceeds", func(t *testing.T) {
35 t.Parallel()
36 rtr := chi.NewRouter()
37 rtr.Use(httpmw.RateLimit(1, time.Second))
38 rtr.Get("/", func(rw http.ResponseWriter, r *http.Request) {
39 rw.WriteHeader(http.StatusOK)
40 })
41
42 for i := 0; i < 5; i++ {
43 req := httptest.NewRequest("GET", "/", nil)
44 rec := httptest.NewRecorder()
45 rtr.ServeHTTP(rec, req)
46 resp := rec.Result()
47 _ = resp.Body.Close()
48 require.Equal(t, i != 0, resp.StatusCode == http.StatusTooManyRequests)
49 }
50 })
51
52 t.Run("RandomIPs", func(t *testing.T) {
53 t.Parallel()
54 rtr := chi.NewRouter()
55 // Because these are random IPs, the limit should never be hit!
56 rtr.Use(httpmw.RateLimit(1, time.Second))
57 rtr.Get("/", func(rw http.ResponseWriter, r *http.Request) {
58 rw.WriteHeader(http.StatusOK)
59 })
60
61 for i := 0; i < 5; i++ {
62 req := httptest.NewRequest("GET", "/", nil)
63 rec := httptest.NewRecorder()
64 req.RemoteAddr = randRemoteAddr()
65 rtr.ServeHTTP(rec, req)
66 resp := rec.Result()
67 _ = resp.Body.Close()
68 require.False(t, resp.StatusCode == http.StatusTooManyRequests)
69 }
70 })
71
72 t.Run("RegularUser", func(t *testing.T) {
73 t.Parallel()
74
75 db, _ := dbtestutil.NewDB(t)
76 u := dbgen.User(t, db, database.User{})
77 _, key := dbgen.APIKey(t, db, database.APIKey{UserID: u.ID})
78
79 rtr := chi.NewRouter()
80 rtr.Use(httpmw.ExtractAPIKeyMW(httpmw.ExtractAPIKeyConfig{
81 DB: db,
82 Optional: false,
83 }))
84
85 rtr.Use(httpmw.RateLimit(1, time.Second))
86 rtr.Get("/", func(rw http.ResponseWriter, r *http.Request) {
87 rw.WriteHeader(http.StatusOK)
88 })
89

Callers

nothing calls this directly

Calls 14

RateLimitFunction · 0.92
NewDBFunction · 0.92
UserFunction · 0.92
APIKeyFunction · 0.92
ExtractAPIKeyMWFunction · 0.92
randRemoteAddrFunction · 0.85
RunMethod · 0.65
GetMethod · 0.65
CloseMethod · 0.65
SetMethod · 0.65
WriteHeaderMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected