Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

services/horizon/internal/httpx: Exempt SSE requests from rate limiting middleware #4163

Merged
merged 3 commits into from
Jan 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion services/horizon/internal/httpx/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/stellar/go/services/horizon/internal/db2/history"
"github.com/stellar/go/services/horizon/internal/ledger"
"github.com/stellar/go/services/horizon/internal/paths"
"github.com/stellar/go/services/horizon/internal/render"
"github.com/stellar/go/services/horizon/internal/render/sse"
"github.com/stellar/go/services/horizon/internal/txsub"
"github.com/stellar/go/support/db"
Expand Down Expand Up @@ -97,7 +98,18 @@ func (r *Router) addMiddleware(config *RouterConfig,
r.Use(c.Handler)

if rateLimitter != nil {
r.Use(rateLimitter.RateLimit)
r.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Exempt streaming requests from rate limits via the HTTP middleware
// because rate limiting for streaming requests are already implemented in
// StreamHandler.ServeStream().
if render.Negotiate(r) == render.MimeEventStream {
handler.ServeHTTP(w, r)
return
}
rateLimitter.RateLimit(handler).ServeHTTP(w, r)
})
})
}

if config.PrimaryDBSession != nil {
Expand Down
7 changes: 7 additions & 0 deletions services/horizon/internal/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ func (suite *RateLimitMiddlewareTestSuite) TestRateLimit_LimitHeaders() {

// Sets X-RateLimit-Remaining headers correctly.
func (suite *RateLimitMiddlewareTestSuite) TestRateLimit_RemainingHeaders() {
// test that SSE requests are ignored
for i := 0; i < 10; i++ {
w := suite.rh.Get("/", test.RequestHelperStreaming)
assert.Equal(suite.T(), "", w.Header().Get("X-RateLimit-Remaining"))
tamirms marked this conversation as resolved.
Show resolved Hide resolved
}

for i := 0; i < 10; i++ {
w := suite.rh.Get("/")
expected := 10 - (i + 1)
Expand All @@ -92,6 +98,7 @@ func (suite *RateLimitMiddlewareTestSuite) TestRateLimit_RemainingHeaders() {
for i := 0; i < 10; i++ {
w := suite.rh.Get("/")
assert.Equal(suite.T(), "0", w.Header().Get("X-RateLimit-Remaining"))
assert.Equal(suite.T(), http.StatusTooManyRequests, w.Code)
}
}

Expand Down