Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions internal/handlers/invite.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handlers
import (
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"rauth/internal/core"
"time"
Expand Down Expand Up @@ -60,6 +61,11 @@ func (h *InviteHandler) RedeemPage(c echo.Context) error {
}

func (h *InviteHandler) Redeem(c echo.Context) error {
clientIP := c.RealIP()
if !core.CheckRateLimit("reg_ip:"+clientIP, h.Cfg.RateLimitRegistrationMax, h.Cfg.RateLimitRegistrationDecay) {
return echo.NewHTTPError(http.StatusTooManyRequests, fmt.Sprintf("Too many registration attempts from this IP (%s)", clientIP))
}

token := c.FormValue("token")
username := c.FormValue("username")
password := c.FormValue("password")
Expand Down
33 changes: 33 additions & 0 deletions internal/handlers/invite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ func TestInviteHandler_Redeem(t *testing.T) {
cfg := &core.Config{
MinPasswordLength: 8,
ServerSecret: "32byte-secret-key-for-testing-!!",
RateLimitRegistrationMax: 100,
RateLimitRegistrationDecay: 60,
}
h := &InviteHandler{Cfg: cfg}
e := echo.New()
Expand Down Expand Up @@ -179,4 +181,35 @@ func TestInviteHandler_Redeem(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusConflict, rec.Code)
})

t.Run("Rate limit exceeded", func(t *testing.T) {
token := "rate-limit-token"
email := "test4@example.com"
core.InviteDB.Set(core.Ctx, "invite:"+token, email, 0)

f := make(url.Values)
f.Set("token", token)
f.Set("username", "newuser4")
f.Set("password", "strongpassword123")

c, _ := createTestContext(e, http.MethodPost, "/rauthredeem", f)

// Exceed the limit
for i := 0; i < cfg.RateLimitRegistrationMax+1; i++ {
err := h.Redeem(c)
if i < cfg.RateLimitRegistrationMax {
// We don't care about the result of the first N requests,
// some might fail due to "Username already taken" but we only care about the rate limit
// For the first request, it succeeds and deletes the token, making subsequent requests fail with 404
// So we need to re-insert the token
core.InviteDB.Set(core.Ctx, "invite:"+token, email, 0)
} else {
// The N+1 request should fail with 429
assert.Error(t, err)
he, ok := err.(*echo.HTTPError)
assert.True(t, ok)
assert.Equal(t, http.StatusTooManyRequests, he.Code)
}
}
})
}
Loading