Skip to content

Commit 7b9b608

Browse files
author
Nitish Agarwal
committed
feat: implement user-based daily publish rate limiting (modelcontextprotocol#21)
- Rate limit by authenticated user (authMethodSubject) instead of namespace - Admin bypass via hasGlobalPermissions parameter from auth handler - Atomic database operations with separate publish_attempts table - Integrated rate limiting directly into registry service - Support for rate limit exemptions with wildcard patterns - Comprehensive test coverage including concurrent request handling Configuration: - MCP_REGISTRY_RATE_LIMIT_ENABLED: Enable/disable rate limiting (default: true) - MCP_REGISTRY_RATE_LIMIT_PER_DAY: Daily publish limit per user (default: 10) - MCP_REGISTRY_RATE_LIMIT_EXEMPTIONS: Comma-separated exempt users/patterns Database changes: - New table: publish_attempts tracking auth_method_subject instead of namespace - Atomic check-and-increment operation prevents race conditions Testing: - All existing tests updated for new method signatures - New tests for concurrent requests, exemptions, and user-specific limits
1 parent 9d63afb commit 7b9b608

16 files changed

Lines changed: 1054 additions & 28 deletions

‎.env.example‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,15 @@ MCP_REGISTRY_OIDC_EXTRA_CLAIMS=[{"hd":"modelcontextprotocol.io"}]
3939
# Grant admin permissions to OIDC-authenticated users
4040
MCP_REGISTRY_OIDC_EDIT_PERMISSIONS=*
4141
MCP_REGISTRY_OIDC_PUBLISH_PERMISSIONS=*
42+
43+
# Rate Limiting Configuration
44+
# Enable/disable rate limiting for publish operations
45+
MCP_REGISTRY_RATE_LIMIT_ENABLED=true
46+
47+
# Maximum number of servers a user can publish per day
48+
MCP_REGISTRY_RATE_LIMIT_PER_DAY=10
49+
50+
# Comma-separated list of authenticated users (auth subjects) exempt from rate limiting
51+
# Supports wildcards: anthropic/* to exempt all users under anthropic domain
52+
# Examples: modelcontextprotocol, anthropic/*, specific-username
53+
MCP_REGISTRY_RATE_LIMIT_EXEMPTIONS=

‎internal/api/handlers/v0/edit_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func TestEditServerEndpoint(t *testing.T) {
3636
},
3737
Version: "1.0.0",
3838
}
39-
published, err := registryService.Publish(testServer)
39+
published, err := registryService.Publish(testServer, "testuser", false)
4040
assert.NoError(t, err)
4141
assert.NotNil(t, published)
4242
assert.NotNil(t, published.Meta)
@@ -56,7 +56,7 @@ func TestEditServerEndpoint(t *testing.T) {
5656
},
5757
Version: "1.0.0",
5858
}
59-
otherPublished, err := registryService.Publish(otherServer)
59+
otherPublished, err := registryService.Publish(otherServer, "testuser", false)
6060
assert.NoError(t, err)
6161
assert.NotNil(t, otherPublished)
6262
assert.NotNil(t, otherPublished.Meta)
@@ -76,7 +76,7 @@ func TestEditServerEndpoint(t *testing.T) {
7676
},
7777
Version: "1.0.0",
7878
}
79-
deletedPublished, err := registryService.Publish(deletedServer)
79+
deletedPublished, err := registryService.Publish(deletedServer, "testuser", false)
8080
assert.NoError(t, err)
8181
assert.NotNil(t, deletedPublished)
8282
assert.NotNil(t, deletedPublished.Meta)

‎internal/api/handlers/v0/publish.go‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,17 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
5353
return nil, huma.Error403Forbidden(buildPermissionErrorMessage(input.Body.Name, claims.Permissions))
5454
}
5555

56+
// Check if user has global permissions (admin)
57+
hasGlobalPermissions := false
58+
for _, perm := range claims.Permissions {
59+
if perm.ResourcePattern == "*" {
60+
hasGlobalPermissions = true
61+
break
62+
}
63+
}
64+
5665
// Publish the server with extensions
57-
publishedServer, err := registry.Publish(input.Body)
66+
publishedServer, err := registry.Publish(input.Body, claims.AuthMethodSubject, hasGlobalPermissions)
5867
if err != nil {
5968
return nil, huma.Error400BadRequest("Failed to publish server", err)
6069
}

‎internal/api/handlers/v0/publish_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ func TestPublishEndpoint(t *testing.T) {
192192
ID: "example/test-server-existing",
193193
},
194194
}
195-
_, _ = registry.Publish(existingServer)
195+
_, _ = registry.Publish(existingServer, "testuser", false)
196196
},
197197
expectedStatus: http.StatusBadRequest,
198198
expectedError: "invalid version: cannot publish duplicate version",

‎internal/api/handlers/v0/servers_test.go‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ func TestServersListEndpoint(t *testing.T) {
5252
},
5353
Version: "2.0.0",
5454
}
55-
_, _ = registry.Publish(server1)
56-
_, _ = registry.Publish(server2)
55+
_, _ = registry.Publish(server1, "testuser", false)
56+
_, _ = registry.Publish(server2, "testuser", false)
5757
},
5858
expectedStatus: http.StatusOK,
5959
},
@@ -71,7 +71,7 @@ func TestServersListEndpoint(t *testing.T) {
7171
},
7272
Version: "1.5.0",
7373
}
74-
_, _ = registry.Publish(server)
74+
_, _ = registry.Publish(server, "testuser", false)
7575
},
7676
expectedStatus: http.StatusOK,
7777
},
@@ -141,8 +141,8 @@ func TestServersListEndpoint(t *testing.T) {
141141
},
142142
Version: "1.0.0",
143143
}
144-
_, _ = registry.Publish(server1)
145-
_, _ = registry.Publish(server2)
144+
_, _ = registry.Publish(server1, "testuser", false)
145+
_, _ = registry.Publish(server2, "testuser", false)
146146
},
147147
expectedStatus: http.StatusOK,
148148
},
@@ -160,7 +160,7 @@ func TestServersListEndpoint(t *testing.T) {
160160
},
161161
Version: "1.0.0",
162162
}
163-
_, _ = registry.Publish(server)
163+
_, _ = registry.Publish(server, "testuser", false)
164164
},
165165
expectedStatus: http.StatusOK,
166166
},
@@ -188,8 +188,8 @@ func TestServersListEndpoint(t *testing.T) {
188188
},
189189
Version: "2.0.0",
190190
}
191-
_, _ = registry.Publish(server1)
192-
_, _ = registry.Publish(server2) // This will be marked as latest
191+
_, _ = registry.Publish(server1, "testuser", false)
192+
_, _ = registry.Publish(server2, "testuser", false) // This will be marked as latest
193193
},
194194
expectedStatus: http.StatusOK,
195195
},
@@ -217,8 +217,8 @@ func TestServersListEndpoint(t *testing.T) {
217217
},
218218
Version: "1.0.0",
219219
}
220-
_, _ = registry.Publish(server1)
221-
_, _ = registry.Publish(server2)
220+
_, _ = registry.Publish(server1, "testuser", false)
221+
_, _ = registry.Publish(server2, "testuser", false)
222222
},
223223
expectedStatus: http.StatusOK,
224224
},
@@ -274,10 +274,10 @@ func TestServersListEndpoint(t *testing.T) {
274274
},
275275
Version: "3.0.0",
276276
}
277-
_, _ = registry.Publish(server1v1)
278-
_, _ = registry.Publish(server1v2)
279-
_, _ = registry.Publish(server2)
280-
_, _ = registry.Publish(server3)
277+
_, _ = registry.Publish(server1v1, "testuser", false)
278+
_, _ = registry.Publish(server1v2, "testuser", false)
279+
_, _ = registry.Publish(server2, "testuser", false)
280+
_, _ = registry.Publish(server3, "testuser", false)
281281
},
282282
expectedStatus: http.StatusOK,
283283
},
@@ -384,7 +384,7 @@ func TestServersDetailEndpoint(t *testing.T) {
384384
Name: "com.example/test-server",
385385
Description: "A test server",
386386
Version: "1.0.0",
387-
})
387+
}, "testuser", false)
388388
assert.NoError(t, err)
389389

390390
testCases := []struct {
@@ -472,7 +472,7 @@ func TestServersEndpointsIntegration(t *testing.T) {
472472
Version: "1.0.0",
473473
}
474474

475-
published, err := registryService.Publish(testServer)
475+
published, err := registryService.Publish(testServer, "testuser", false)
476476
assert.NoError(t, err)
477477
assert.NotNil(t, published)
478478

‎internal/api/handlers/v0/telemetry_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func TestPrometheusHandler(t *testing.T) {
3131
ID: "example/test-server",
3232
},
3333
Version: "2.0.0",
34-
})
34+
}, "testuser", false)
3535
assert.NoError(t, err)
3636

3737
cfg := config.NewConfig()

‎internal/config/config.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ type Config struct {
3333
OIDCExtraClaims string `env:"OIDC_EXTRA_CLAIMS" envDefault:""`
3434
OIDCEditPerms string `env:"OIDC_EDIT_PERMISSIONS" envDefault:""`
3535
OIDCPublishPerms string `env:"OIDC_PUBLISH_PERMISSIONS" envDefault:""`
36+
37+
// Rate Limiting Configuration
38+
RateLimitEnabled bool `env:"RATE_LIMIT_ENABLED" envDefault:"true"`
39+
RateLimitPerDay int `env:"RATE_LIMIT_PER_DAY" envDefault:"10"`
40+
RateLimitExemptions string `env:"RATE_LIMIT_EXEMPTIONS" envDefault:""` // comma-separated
3641
}
3742

3843
// NewConfig creates a new configuration with default values

‎internal/database/database.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ type Database interface {
4040
UpdateServer(ctx context.Context, id string, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error)
4141
// Close closes the database connection
4242
Close() error
43+
44+
// Rate limiting methods
45+
IncrementPublishCount(ctx context.Context, authMethodSubject string) error
46+
GetPublishCount(ctx context.Context, authMethodSubject string, date time.Time) (int, error)
47+
// CheckAndIncrementPublishCount atomically checks if the count is under the limit and increments if so
48+
// Returns the current count and whether the increment was successful
49+
CheckAndIncrementPublishCount(ctx context.Context, authMethodSubject string, limit int) (currentCount int, incrementSuccessful bool, err error)
4350
}
4451

4552
// ConnectionType represents the type of database connection

‎internal/database/memory.go‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,24 @@ import (
66
"sort"
77
"strings"
88
"sync"
9+
"time"
910

1011
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
1112
)
1213

1314
// MemoryDB is an in-memory implementation of the Database interface
1415
type MemoryDB struct {
15-
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
16-
mu sync.RWMutex
16+
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
17+
publishAttempts map[string]map[string]int // authMethodSubject -> date -> count
18+
mu sync.RWMutex
1719
}
1820

1921
func NewMemoryDB() *MemoryDB {
2022
// Convert input ServerJSON entries to have proper metadata
2123
serverRecords := make(map[string]*apiv0.ServerJSON)
2224
return &MemoryDB{
23-
entries: serverRecords,
25+
entries: serverRecords,
26+
publishAttempts: make(map[string]map[string]int),
2427
}
2528
}
2629

@@ -139,6 +142,58 @@ func (db *MemoryDB) UpdateServer(ctx context.Context, id string, server *apiv0.S
139142
return server, nil
140143
}
141144

145+
// IncrementPublishCount increments the publish count for an authenticated user today
146+
func (db *MemoryDB) IncrementPublishCount(_ context.Context, authMethodSubject string) error {
147+
db.mu.Lock()
148+
defer db.mu.Unlock()
149+
150+
today := time.Now().Format("2006-01-02")
151+
if db.publishAttempts[authMethodSubject] == nil {
152+
db.publishAttempts[authMethodSubject] = make(map[string]int)
153+
}
154+
db.publishAttempts[authMethodSubject][today]++
155+
return nil
156+
}
157+
158+
// GetPublishCount returns the number of publishes for an authenticated user on a specific date
159+
func (db *MemoryDB) GetPublishCount(_ context.Context, authMethodSubject string, date time.Time) (int, error) {
160+
db.mu.RLock()
161+
defer db.mu.RUnlock()
162+
163+
dateStr := date.Format("2006-01-02")
164+
if db.publishAttempts[authMethodSubject] == nil {
165+
return 0, nil
166+
}
167+
return db.publishAttempts[authMethodSubject][dateStr], nil
168+
}
169+
170+
// CheckAndIncrementPublishCount atomically checks if the count is under the limit and increments if so
171+
func (db *MemoryDB) CheckAndIncrementPublishCount(_ context.Context, authMethodSubject string, limit int) (currentCount int, incrementSuccessful bool, err error) {
172+
db.mu.Lock()
173+
defer db.mu.Unlock()
174+
175+
today := time.Now().Format("2006-01-02")
176+
177+
// Initialize authMethodSubject map if needed
178+
if db.publishAttempts[authMethodSubject] == nil {
179+
db.publishAttempts[authMethodSubject] = make(map[string]int)
180+
}
181+
182+
// Get current count
183+
currentCount = db.publishAttempts[authMethodSubject][today]
184+
185+
// Check if under limit and increment if so
186+
if currentCount < limit {
187+
db.publishAttempts[authMethodSubject][today]++
188+
currentCount++ // Return the new count after increment
189+
incrementSuccessful = true
190+
} else {
191+
incrementSuccessful = false
192+
}
193+
194+
return currentCount, incrementSuccessful, nil
195+
}
196+
142197
// For an in-memory database, this is a no-op
143198
func (db *MemoryDB) Close() error {
144199
return nil
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
-- Add rate limiting table to track publish attempts by authenticated user and date
2+
CREATE TABLE publish_attempts (
3+
auth_method_subject VARCHAR(255) NOT NULL,
4+
attempt_date DATE NOT NULL DEFAULT CURRENT_DATE,
5+
attempt_count INTEGER NOT NULL DEFAULT 0,
6+
first_attempt_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
7+
last_attempt_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
8+
PRIMARY KEY (auth_method_subject, attempt_date)
9+
);
10+
11+
-- Index for efficient lookups by auth_method_subject
12+
CREATE INDEX idx_publish_attempts_auth_subject ON publish_attempts(auth_method_subject);
13+
14+
-- Index for cleanup queries by date
15+
CREATE INDEX idx_publish_attempts_date ON publish_attempts(attempt_date);
16+
17+
-- Comment for documentation
18+
COMMENT ON TABLE publish_attempts IS 'Tracks daily publish attempts per authenticated user for rate limiting';
19+
COMMENT ON COLUMN publish_attempts.auth_method_subject IS 'The authenticated user identifier (e.g., GitHub username)';
20+
COMMENT ON COLUMN publish_attempts.attempt_date IS 'The date of the attempts (resets daily)';
21+
COMMENT ON COLUMN publish_attempts.attempt_count IS 'Number of successful publishes on this date';

0 commit comments

Comments
 (0)