Skip to content
Closed
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
7 changes: 6 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,12 @@ func NewAPIWithVersion(ctx context.Context, globalConfig *conf.GlobalConfigurati

r.Get("/authorize", api.ExternalProviderRedirect)

r.With(api.requireAdminCredentials).Post("/invite", api.Invite)
r.With(api.requireAdminCredentials).With(api.limitHandler(
// Allow requests at a rate of 10 per minute.
tollbooth.NewLimiter(10.0/60, &limiter.ExpirableOptions{
DefaultExpirationTTL: time.Hour,
}).SetBurst(10),
)).Post("/invite", api.Invite)

r.With(api.requireEmailProvider).Post("/signup", api.Signup)
r.With(api.requireEmailProvider).Post("/recover", api.Recover)
Expand Down
34 changes: 34 additions & 0 deletions api/invite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"

Expand All @@ -29,6 +30,7 @@ type InviteTestSuite struct {
}

func TestInvite(t *testing.T) {
os.Setenv("GOTRUE_RATE_LIMIT_HEADER", "My-Custom-Header")
api, config, instanceID, err := setupAPIForTestForInstance()
require.NoError(t, err)

Expand Down Expand Up @@ -149,6 +151,38 @@ func (ts *InviteTestSuite) TestVerifyInvite() {
assert.Equal(ts.T(), http.StatusOK, w.Code, w.Body.String())
}

func (ts *InviteTestSuite) TestInviteRateLimit() {
for i := 0; i < 10; i++ {
var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"email": fmt.Sprintf("test%d@example.com", i),
}))

req := httptest.NewRequest(http.MethodPost, "http://localhost/invite", &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ts.token))
req.Header.Set("My-Custom-Header", "1.2.3.4") // add this

w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusOK, w.Code)
}

var buffer bytes.Buffer
require.NoError(ts.T(), json.NewEncoder(&buffer).Encode(map[string]interface{}{
"email": "ratelimited@example.com",
}))

req := httptest.NewRequest(http.MethodPost, "http://localhost/invite", &buffer)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ts.token))
req.Header.Set("My-Custom-Header", "1.2.3.4") // add this

w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), http.StatusTooManyRequests, w.Code)
}

func (ts *InviteTestSuite) TestVerifyInvite_NoPassword() {
user, err := models.NewUser(ts.instanceID, "test@example.com", "", ts.Config.JWT.Aud, nil)
now := time.Now()
Expand Down