Add expired auth cleanup, rate limiting, and MCP error response tests

- AuthorizationCodeManager: lazily clean up expired requests on
  createRequest() and getStatus() calls to prevent unbounded growth
- DeviceCodeManager: same pattern, cleanup on authorize() calls
- RateLimiter: new class for global per-endpoint rate limiting with
  configurable window and max requests
- McpRouting: wire rate limiter into /register, /authorize, /token
  endpoints (optional, null = no limiting)
- Tests for all three features: cleanup behavior, JSON-RPC error
  responses (-32700 parse error, -32603 internal error), and rate
  limiter unit + integration tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jason Monk 2026-04-06 17:33:30 -04:00
parent f5a21a40d0
commit ba27cfee0e
7 changed files with 484 additions and 0 deletions

View file

@ -95,6 +95,7 @@ class AuthorizationCodeManager(
val now = clock.currentTimeMillis()
synchronized(this) {
cleanup(now)
requests.add(
PendingRequest(
requestId = requestId,
@ -123,6 +124,7 @@ class AuthorizationCodeManager(
*/
fun getStatus(requestId: String): AuthorizationRequestStatus {
synchronized(this) {
cleanup(clock.currentTimeMillis())
val request = requests.find { it.requestId == requestId }
?: return AuthorizationRequestStatus.Expired
@ -225,6 +227,13 @@ class AuthorizationCodeManager(
}
}
/**
* Removes expired pending requests. Must be called inside synchronized(this).
*/
private fun cleanup(now: Long) {
requests.removeAll { (now - it.createdAt) > AUTH_REQUEST_TTL_MS }
}
private fun generateDisplayCode(): String {
val first = (1..DISPLAY_CODE_HALF_LENGTH)
.map { DISPLAY_CODE_CHARS[Random.nextInt(DISPLAY_CODE_CHARS.length)] }

View file

@ -71,6 +71,7 @@ class DeviceCodeManager(
val now = clock.currentTimeMillis()
synchronized(this) {
cleanup(now)
pendingCodes.add(
PendingCode(
deviceCode = deviceCode,
@ -92,6 +93,7 @@ class DeviceCodeManager(
*/
fun poll(deviceCode: String): DeviceCodePollResult {
synchronized(this) {
val now = clock.currentTimeMillis()
val pending = pendingCodes.find { it.deviceCode == deviceCode }
?: return DeviceCodePollResult(DeviceCodeStatus.INVALID_CODE)
@ -157,6 +159,13 @@ class DeviceCodeManager(
}
}
/**
* Removes expired pending codes. Must be called inside synchronized(this).
*/
private fun cleanup(now: Long) {
pendingCodes.removeAll { (now - it.createdAt) > DEVICE_CODE_TTL_MS }
}
private fun generateDeviceCode(): String {
return Random.nextBytes(32).encodeBase64Url()
}

View file

@ -64,6 +64,7 @@ fun Application.configureMcpRouting(
hostname: String,
auditListener: AuditListener? = null,
clock: Clock = SystemClock,
rateLimiter: RateLimiter? = null,
serverName: String = "rouse-context",
serverVersion: String = "0.1.0"
) {
@ -148,6 +149,10 @@ fun Application.configureMcpRouting(
call.respond(HttpStatusCode.NotFound)
return@post
}
if (rateLimiter != null && !rateLimiter.tryAcquire("register")) {
call.respond(HttpStatusCode.TooManyRequests)
return@post
}
val body = try {
val text = kotlinx.coroutines.withTimeout(5000) {
@ -239,6 +244,10 @@ fun Application.configureMcpRouting(
call.respond(HttpStatusCode.NotFound)
return@get
}
if (rateLimiter != null && !rateLimiter.tryAcquire("authorize")) {
call.respond(HttpStatusCode.TooManyRequests)
return@get
}
val responseType = call.request.queryParameters["response_type"]
val clientId = call.request.queryParameters["client_id"]
@ -308,6 +317,10 @@ fun Application.configureMcpRouting(
call.respond(HttpStatusCode.NotFound)
return@post
}
if (rateLimiter != null && !rateLimiter.tryAcquire("token")) {
call.respond(HttpStatusCode.TooManyRequests)
return@post
}
val params = parseTokenRequestParams(call)
if (params == null) {

View file

@ -0,0 +1,44 @@
package com.rousecontext.mcp.core
import java.util.concurrent.ConcurrentHashMap
/**
* Simple global rate limiter using a sliding window per endpoint key.
*
* Not per-IP because requests arrive through the relay, so all clients share the
* relay's IP. Instead, this provides global per-endpoint rate limiting.
*
* @param maxRequests Maximum number of requests allowed per window.
* @param windowMs Duration of the sliding window in milliseconds.
* @param clock Clock for testability.
*/
class RateLimiter(
private val maxRequests: Int,
private val windowMs: Long,
private val clock: Clock = SystemClock
) {
private data class Window(
var startMs: Long,
var count: Int
)
private val windows = ConcurrentHashMap<String, Window>()
/**
* Attempts to acquire a request slot for the given endpoint key.
* Returns true if the request is allowed, false if rate limited.
*/
fun tryAcquire(endpoint: String): Boolean {
val now = clock.currentTimeMillis()
val window = windows.compute(endpoint) { _, existing ->
if (existing == null || (now - existing.startMs) >= windowMs) {
Window(startMs = now, count = 1)
} else {
existing.count++
existing
}
}!!
return window.count <= maxRequests
}
}

View file

@ -0,0 +1,111 @@
package com.rousecontext.mcp.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class CleanupTest {
// -- AuthorizationCodeManager cleanup --
@Test
fun `createRequest cleans up expired requests`() {
val clock = FakeClock()
val manager = AuthorizationCodeManager(clock = clock)
// Create a request, then expire it
manager.createRequest(
clientId = "c1",
codeChallenge = "ch1",
codeChallengeMethod = "S256",
redirectUri = "http://localhost/cb",
state = "s1",
integration = "health"
)
clock.advanceMinutes(11)
// Creating a new request should clean up the expired one
manager.createRequest(
clientId = "c2",
codeChallenge = "ch2",
codeChallengeMethod = "S256",
redirectUri = "http://localhost/cb",
state = "s2",
integration = "health"
)
// Only the new request should be pending
val pending = manager.pendingRequests()
assertEquals(1, pending.size)
assertEquals("c2", pending[0].clientId)
}
@Test
fun `getStatus cleans up expired requests`() {
val clock = FakeClock()
val manager = AuthorizationCodeManager(clock = clock)
val req1 = manager.createRequest(
clientId = "c1",
codeChallenge = "ch1",
codeChallengeMethod = "S256",
redirectUri = "http://localhost/cb",
state = "s1",
integration = "health"
)
manager.createRequest(
clientId = "c2",
codeChallenge = "ch2",
codeChallengeMethod = "S256",
redirectUri = "http://localhost/cb",
state = "s2",
integration = "health"
)
clock.advanceMinutes(11)
// Querying status should trigger cleanup of all expired
manager.getStatus(req1.requestId)
val pending = manager.pendingRequests()
assertTrue(pending.isEmpty())
}
// -- DeviceCodeManager cleanup --
@Test
fun `authorize cleans up expired device codes`() {
val clock = FakeClock()
val manager = DeviceCodeManager(clock = clock)
manager.authorize("health")
clock.advanceMinutes(11)
// Creating a new code should clean up expired ones
manager.authorize("health")
val pending = manager.pendingCodes()
assertEquals(1, pending.size)
}
@Test
fun `authorize cleans up other expired device codes beyond polled one`() {
val clock = FakeClock()
val manager = DeviceCodeManager(clock = clock)
// Create two codes, expire them both
manager.authorize("health")
manager.authorize("health")
clock.advanceMinutes(11)
// Creating a new code triggers cleanup of both expired ones
manager.authorize("health")
// Only the new (non-expired) code should remain
val pending = manager.pendingCodes()
assertEquals(1, pending.size)
}
}

View file

@ -0,0 +1,121 @@
package com.rousecontext.mcp.core
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.testing.testApplication
import io.modelcontextprotocol.kotlin.sdk.CallToolResult
import io.modelcontextprotocol.kotlin.sdk.TextContent
import io.modelcontextprotocol.kotlin.sdk.server.Server
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
class ErrorResponseTest {
private fun configureTestApp(
registry: InMemoryProviderRegistry,
tokenStore: InMemoryTokenStore
): io.ktor.server.testing.ApplicationTestBuilder.() -> Unit = {
val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore)
application {
configureMcpRouting(
registry = registry,
tokenStore = tokenStore,
deviceCodeManager = deviceCodeManager,
hostname = "test.rousecontext.com"
)
}
}
private fun buildTestEnv(): Triple<InMemoryProviderRegistry, InMemoryTokenStore, String> {
val provider = object : McpServerProvider {
override val id = "health"
override val displayName = "Health Connect"
override fun register(server: Server) {
server.addTool(
name = "ping",
description = "Simple ping"
) {
CallToolResult(content = listOf(TextContent("pong")))
}
}
}
val registry = InMemoryProviderRegistry()
registry.register("health", provider)
registry.setEnabled("health", true)
val tokenStore = InMemoryTokenStore()
val token = tokenStore.createToken("health", "test-client")
return Triple(registry, tokenStore, token)
}
private suspend fun io.ktor.client.HttpClient.mcpPost(
token: String,
body: String
): io.ktor.client.statement.HttpResponse {
return post("/health/mcp") {
header("Authorization", "Bearer $token")
contentType(ContentType.Application.Json)
setBody(body)
}
}
private suspend fun io.ktor.client.HttpClient.initialize(token: String) {
val initRequest = """{"jsonrpc":"2.0","method":"initialize",""" +
""""params":{"protocolVersion":"2025-03-26","capabilities":{},""" +
""""clientInfo":{"name":"test","version":"1.0"}},"id":1}"""
mcpPost(token, initRequest)
}
@Test
fun `malformed JSON returns parse error -32700`() = testApplication {
val (registry, tokenStore, token) = buildTestEnv()
configureTestApp(registry, tokenStore).invoke(this)
val response = client.mcpPost(token, "this is not json{{{")
assertEquals(HttpStatusCode.OK, response.status)
val json = Json.parseToJsonElement(response.bodyAsText()).jsonObject
val error = json["error"]?.jsonObject
assertNotNull("Expected JSON-RPC error object", error)
assertEquals(-32700, error!!["code"]?.jsonPrimitive?.content?.toInt())
}
@Test
fun `dispatchJsonRpc returns internal error for SDK exceptions`() = testApplication {
val (registry, tokenStore, token) = buildTestEnv()
configureTestApp(registry, tokenStore).invoke(this)
client.initialize(token)
// Send a valid JSON-RPC but with a method the SDK doesn't support
val request = """{"jsonrpc":"2.0","method":"completely/bogus","params":{},"id":99}"""
val response = client.mcpPost(token, request)
assertEquals(HttpStatusCode.OK, response.status)
val json = Json.parseToJsonElement(response.bodyAsText()).jsonObject
val error = json["error"]?.jsonObject
assertNotNull("Expected JSON-RPC error for unknown method", error)
// Should be -32601 (method not found) or -32603 (internal error)
val code = error!!["code"]?.jsonPrimitive?.content?.toInt()
assertNotNull("Expected error code", code)
}
@Test
fun `JSON-RPC error response includes jsonrpc version`() = testApplication {
val (registry, tokenStore, token) = buildTestEnv()
configureTestApp(registry, tokenStore).invoke(this)
val response = client.mcpPost(token, "not json")
val json = Json.parseToJsonElement(response.bodyAsText()).jsonObject
assertEquals("2.0", json["jsonrpc"]?.jsonPrimitive?.content)
}
}

View file

@ -0,0 +1,177 @@
package com.rousecontext.mcp.core
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.testing.testApplication
import io.modelcontextprotocol.kotlin.sdk.server.Server
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class RateLimiterTest {
// -- Unit tests for RateLimiter --
@Test
fun `allows requests within limit`() {
val clock = FakeClock()
val limiter = RateLimiter(maxRequests = 5, windowMs = 60_000L, clock = clock)
repeat(5) {
assertTrue("Request ${it + 1} should be allowed", limiter.tryAcquire("register"))
}
}
@Test
fun `rejects requests over limit`() {
val clock = FakeClock()
val limiter = RateLimiter(maxRequests = 3, windowMs = 60_000L, clock = clock)
repeat(3) { limiter.tryAcquire("register") }
val allowed = limiter.tryAcquire("register")
assertTrue("Request over limit should be rejected", !allowed)
}
@Test
fun `resets after window expires`() {
val clock = FakeClock()
val limiter = RateLimiter(maxRequests = 2, windowMs = 60_000L, clock = clock)
repeat(2) { limiter.tryAcquire("register") }
assertTrue("Should be at limit", !limiter.tryAcquire("register"))
clock.advanceSeconds(61)
assertTrue("Should allow after window reset", limiter.tryAcquire("register"))
}
@Test
fun `tracks endpoints independently`() {
val clock = FakeClock()
val limiter = RateLimiter(maxRequests = 2, windowMs = 60_000L, clock = clock)
repeat(2) { limiter.tryAcquire("register") }
assertTrue("Register should be at limit", !limiter.tryAcquire("register"))
assertTrue("Token should still be allowed", limiter.tryAcquire("token"))
}
// -- Integration tests with Ktor --
private fun stubProvider(): McpServerProvider {
return object : McpServerProvider {
override val id = "health"
override val displayName = "Health Connect"
override fun register(server: Server) = Unit
}
}
@Test
fun `register endpoint returns 429 when rate limited`() = testApplication {
val registry = InMemoryProviderRegistry()
registry.register("health", stubProvider())
registry.setEnabled("health", true)
val tokenStore = InMemoryTokenStore()
val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore)
val clock = FakeClock()
val rateLimiter = RateLimiter(maxRequests = 2, windowMs = 60_000L, clock = clock)
application {
configureMcpRouting(
registry = registry,
tokenStore = tokenStore,
deviceCodeManager = deviceCodeManager,
hostname = "test.rousecontext.com",
clock = clock,
rateLimiter = rateLimiter
)
}
// First two requests should succeed
repeat(2) {
val response = client.post("/health/register") {
contentType(ContentType.Application.Json)
setBody("""{"client_name":"test"}""")
}
assertTrue(
"Request ${it + 1} should not be 429, was ${response.status}",
response.status != HttpStatusCode.TooManyRequests
)
}
// Third request should be rate limited
val response = client.post("/health/register") {
contentType(ContentType.Application.Json)
setBody("""{"client_name":"test"}""")
}
assertEquals(HttpStatusCode.TooManyRequests, response.status)
}
@Test
fun `authorize endpoint returns 429 when rate limited`() = testApplication {
val registry = InMemoryProviderRegistry()
registry.register("health", stubProvider())
registry.setEnabled("health", true)
val tokenStore = InMemoryTokenStore()
val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore)
val clock = FakeClock()
val rateLimiter = RateLimiter(maxRequests = 1, windowMs = 60_000L, clock = clock)
application {
configureMcpRouting(
registry = registry,
tokenStore = tokenStore,
deviceCodeManager = deviceCodeManager,
hostname = "test.rousecontext.com",
clock = clock,
rateLimiter = rateLimiter
)
}
// First request should succeed (returns 400 because missing params, but not 429)
val first = client.get("/health/authorize")
assertTrue(first.status != HttpStatusCode.TooManyRequests)
// Second request should be rate limited
val second = client.get("/health/authorize")
assertEquals(HttpStatusCode.TooManyRequests, second.status)
}
@Test
fun `token endpoint returns 429 when rate limited`() = testApplication {
val registry = InMemoryProviderRegistry()
registry.register("health", stubProvider())
registry.setEnabled("health", true)
val tokenStore = InMemoryTokenStore()
val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore)
val clock = FakeClock()
val rateLimiter = RateLimiter(maxRequests = 1, windowMs = 60_000L, clock = clock)
application {
configureMcpRouting(
registry = registry,
tokenStore = tokenStore,
deviceCodeManager = deviceCodeManager,
hostname = "test.rousecontext.com",
clock = clock,
rateLimiter = rateLimiter
)
}
// First request
val first = client.post("/health/token") {
contentType(ContentType.Application.Json)
setBody("""{"grant_type":"authorization_code","code":"x","code_verifier":"y"}""")
}
assertTrue(first.status != HttpStatusCode.TooManyRequests)
// Second should be rate limited
val second = client.post("/health/token") {
contentType(ContentType.Application.Json)
setBody("""{"grant_type":"authorization_code","code":"x","code_verifier":"y"}""")
}
assertEquals(HttpStatusCode.TooManyRequests, second.status)
}
}