mirror of
https://github.com/Monkopedia/rouse-context.git
synced 2026-12-03 03:44:54 +00:00
Fix high-severity security findings from audit (5-12)
- Validate redirect_uris at /register: reject non-http/https schemes and
registrations with no valid URIs (Finding 5)
- Use per-integration rate limiter keys (e.g. "health/register") instead of
global keys to prevent cross-integration interference (Finding 6)
- Validate integration path parameter against ^[a-zA-Z0-9_-]{1,64}$ regex
at all route handlers to prevent path traversal (Finding 7)
- Finding 8 (SQLCipher for token DB) deferred: no SQLCipher dependency yet,
tokens already hashed
- Add security headers (X-Frame-Options, CSP, nosniff, HSTS) to the
/authorize HTML response (Finding 9)
- Add per-integration rate limiting to /mcp endpoint via separate
mcpRateLimiter parameter (Finding 10)
- Increase display/user code entropy from ~41 bits (4+4 chars) to ~61 bits
(6+6 chars) and switch from kotlin.random.Random to java.security.SecureRandom
in both AuthorizationCodeManager and DeviceCodeManager (Finding 11)
- Finding 12 (origin validation in device code approval) confirmed mitigated
by phone-side approval UI requiring physical user interaction
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
cf2f0edbf2
commit
cd40f32dff
6 changed files with 99 additions and 19 deletions
|
|
@ -1,9 +1,9 @@
|
|||
package com.rousecontext.mcp.core
|
||||
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* Status of an authorization request, returned by [AuthorizationCodeManager.getStatus].
|
||||
|
|
@ -42,7 +42,7 @@ private const val AUTH_REQUEST_TTL_MS = 10L * 60 * 1000 // 10 minutes
|
|||
* Characters allowed in display codes. Excludes 0, O, 1, I, L to avoid ambiguity.
|
||||
*/
|
||||
private const val DISPLAY_CODE_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
private const val DISPLAY_CODE_HALF_LENGTH = 4
|
||||
private const val DISPLAY_CODE_HALF_LENGTH = 6
|
||||
|
||||
/**
|
||||
* Manages OAuth 2.1 authorization code flow with PKCE for per-integration auth.
|
||||
|
|
@ -262,19 +262,22 @@ class AuthorizationCodeManager(
|
|||
}
|
||||
|
||||
private fun generateDisplayCode(): String {
|
||||
val random = SecureRandom()
|
||||
val first = (1..DISPLAY_CODE_HALF_LENGTH)
|
||||
.map { DISPLAY_CODE_CHARS[Random.nextInt(DISPLAY_CODE_CHARS.length)] }
|
||||
.map { DISPLAY_CODE_CHARS[random.nextInt(DISPLAY_CODE_CHARS.length)] }
|
||||
.toCharArray()
|
||||
.concatToString()
|
||||
val second = (1..DISPLAY_CODE_HALF_LENGTH)
|
||||
.map { DISPLAY_CODE_CHARS[Random.nextInt(DISPLAY_CODE_CHARS.length)] }
|
||||
.map { DISPLAY_CODE_CHARS[random.nextInt(DISPLAY_CODE_CHARS.length)] }
|
||||
.toCharArray()
|
||||
.concatToString()
|
||||
return "$first-$second"
|
||||
}
|
||||
|
||||
private fun generateAuthorizationCode(): String {
|
||||
return Random.nextBytes(32).encodeBase64Url()
|
||||
val bytes = ByteArray(32)
|
||||
SecureRandom().nextBytes(bytes)
|
||||
return bytes.encodeBase64Url()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package com.rousecontext.mcp.core
|
||||
|
||||
import kotlin.random.Random
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Status of a device code poll request.
|
||||
|
|
@ -37,7 +37,7 @@ private const val DEVICE_CODE_TTL_MS = 10L * 60 * 1000 // 10 minutes
|
|||
* Characters allowed in user codes. Excludes 0, O, 1, I, L to avoid ambiguity.
|
||||
*/
|
||||
private const val USER_CODE_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
private const val USER_CODE_HALF_LENGTH = 4
|
||||
private const val USER_CODE_HALF_LENGTH = 6
|
||||
|
||||
/**
|
||||
* Manages OAuth 2.1 device authorization grant (RFC 8628) for per-integration auth.
|
||||
|
|
@ -167,16 +167,19 @@ class DeviceCodeManager(
|
|||
}
|
||||
|
||||
private fun generateDeviceCode(): String {
|
||||
return Random.nextBytes(32).encodeBase64Url()
|
||||
val bytes = ByteArray(32)
|
||||
SecureRandom().nextBytes(bytes)
|
||||
return bytes.encodeBase64Url()
|
||||
}
|
||||
|
||||
private fun generateUserCode(): String {
|
||||
val random = SecureRandom()
|
||||
val first = (1..USER_CODE_HALF_LENGTH)
|
||||
.map { USER_CODE_CHARS[Random.nextInt(USER_CODE_CHARS.length)] }
|
||||
.map { USER_CODE_CHARS[random.nextInt(USER_CODE_CHARS.length)] }
|
||||
.toCharArray()
|
||||
.concatToString()
|
||||
val second = (1..USER_CODE_HALF_LENGTH)
|
||||
.map { USER_CODE_CHARS[Random.nextInt(USER_CODE_CHARS.length)] }
|
||||
.map { USER_CODE_CHARS[random.nextInt(USER_CODE_CHARS.length)] }
|
||||
.toCharArray()
|
||||
.concatToString()
|
||||
return "$first-$second"
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ fun Application.configureMcpRouting(
|
|||
auditListener: AuditListener? = null,
|
||||
clock: Clock = SystemClock,
|
||||
rateLimiter: RateLimiter? = null,
|
||||
mcpRateLimiter: RateLimiter? = null,
|
||||
serverName: String = "rouse-context",
|
||||
serverVersion: String = "0.1.0"
|
||||
) {
|
||||
|
|
@ -131,6 +132,10 @@ fun Application.configureMcpRouting(
|
|||
// OAuth metadata -- no auth required
|
||||
get("/.well-known/oauth-authorization-server") {
|
||||
val integration = call.parameters["integration"] ?: return@get
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@get
|
||||
}
|
||||
if (registry.providerForPath(integration) == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@get
|
||||
|
|
@ -145,11 +150,15 @@ fun Application.configureMcpRouting(
|
|||
// device code flow, so this is a simple pass-through.
|
||||
post("/register") {
|
||||
val integration = call.parameters["integration"] ?: return@post
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@post
|
||||
}
|
||||
if (registry.providerForPath(integration) == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@post
|
||||
}
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("register")) {
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("$integration/register")) {
|
||||
call.respond(HttpStatusCode.TooManyRequests)
|
||||
return@post
|
||||
}
|
||||
|
|
@ -173,6 +182,33 @@ fun Application.configureMcpRouting(
|
|||
}
|
||||
|
||||
val clientName = body["client_name"]?.jsonPrimitive?.content ?: "unknown"
|
||||
|
||||
// Validate redirect_uris: only http/https schemes allowed
|
||||
val rawUris = (body["redirect_uris"] as? kotlinx.serialization.json.JsonArray)
|
||||
?.mapNotNull { it.jsonPrimitive.content }
|
||||
?: emptyList()
|
||||
val validUris = rawUris.filter { uri ->
|
||||
try {
|
||||
val scheme = java.net.URI(uri).scheme?.lowercase()
|
||||
scheme == "http" || scheme == "https"
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
if (validUris.isEmpty()) {
|
||||
call.respond(
|
||||
HttpStatusCode.BadRequest,
|
||||
buildJsonObject {
|
||||
put("error", "invalid_redirect_uri")
|
||||
put(
|
||||
"error_description",
|
||||
"At least one http or https redirect_uri is required"
|
||||
)
|
||||
}
|
||||
)
|
||||
return@post
|
||||
}
|
||||
|
||||
val clientId = java.util.UUID.randomUUID().toString()
|
||||
authorizationCodeManager.registerClient(clientId, clientName)
|
||||
val response = buildJsonObject {
|
||||
|
|
@ -181,8 +217,7 @@ fun Application.configureMcpRouting(
|
|||
put(
|
||||
"redirect_uris",
|
||||
kotlinx.serialization.json.JsonArray(
|
||||
(body["redirect_uris"] as? kotlinx.serialization.json.JsonArray)
|
||||
?.toList() ?: emptyList()
|
||||
validUris.map { kotlinx.serialization.json.JsonPrimitive(it) }
|
||||
)
|
||||
)
|
||||
put(
|
||||
|
|
@ -218,6 +253,10 @@ fun Application.configureMcpRouting(
|
|||
// Device code authorize -- no auth required
|
||||
post("/device/authorize") {
|
||||
val integration = call.parameters["integration"] ?: return@post
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@post
|
||||
}
|
||||
if (registry.providerForPath(integration) == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@post
|
||||
|
|
@ -241,11 +280,15 @@ fun Application.configureMcpRouting(
|
|||
// Authorization code flow -- returns HTML page with display code
|
||||
get("/authorize") {
|
||||
val integration = call.parameters["integration"] ?: return@get
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@get
|
||||
}
|
||||
if (registry.providerForPath(integration) == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@get
|
||||
}
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("authorize")) {
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("$integration/authorize")) {
|
||||
call.respond(HttpStatusCode.TooManyRequests)
|
||||
return@get
|
||||
}
|
||||
|
|
@ -282,6 +325,16 @@ fun Application.configureMcpRouting(
|
|||
hostname = hostname,
|
||||
integration = integration
|
||||
)
|
||||
call.response.headers.append("X-Frame-Options", "DENY")
|
||||
call.response.headers.append(
|
||||
"Content-Security-Policy",
|
||||
"frame-ancestors 'none'; default-src 'self'; script-src 'unsafe-inline'"
|
||||
)
|
||||
call.response.headers.append("X-Content-Type-Options", "nosniff")
|
||||
call.response.headers.append(
|
||||
"Strict-Transport-Security",
|
||||
"max-age=31536000"
|
||||
)
|
||||
call.respondText(html, ContentType.Text.Html)
|
||||
}
|
||||
|
||||
|
|
@ -314,11 +367,15 @@ fun Application.configureMcpRouting(
|
|||
// Token exchange -- handles both authorization_code and device_code
|
||||
post("/token") {
|
||||
val integration = call.parameters["integration"] ?: return@post
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@post
|
||||
}
|
||||
if (registry.providerForPath(integration) == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@post
|
||||
}
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("token")) {
|
||||
if (rateLimiter != null && !rateLimiter.tryAcquire("$integration/token")) {
|
||||
call.respond(HttpStatusCode.TooManyRequests)
|
||||
return@post
|
||||
}
|
||||
|
|
@ -374,11 +431,21 @@ fun Application.configureMcpRouting(
|
|||
// MCP Streamable HTTP -- Bearer auth required
|
||||
post("/mcp") {
|
||||
val integration = call.parameters["integration"] ?: return@post
|
||||
if (!INTEGRATION_NAME_REGEX.matches(integration)) {
|
||||
call.respond(HttpStatusCode.BadRequest)
|
||||
return@post
|
||||
}
|
||||
val provider = registry.providerForPath(integration)
|
||||
if (provider == null) {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@post
|
||||
}
|
||||
if (mcpRateLimiter != null &&
|
||||
!mcpRateLimiter.tryAcquire("$integration/mcp")
|
||||
) {
|
||||
call.respond(HttpStatusCode.TooManyRequests)
|
||||
return@post
|
||||
}
|
||||
|
||||
// Auth check
|
||||
val authHeader = call.request.headers["Authorization"]
|
||||
|
|
@ -772,6 +839,9 @@ private fun emitAuditEvent(
|
|||
/** Timeout for reading the MCP request body and dispatching it (30 seconds). */
|
||||
private const val MCP_REQUEST_TIMEOUT_MS = 30_000L
|
||||
|
||||
/** Valid integration name pattern: alphanumeric, hyphens, underscores, 1-64 chars. */
|
||||
private val INTEGRATION_NAME_REGEX = Regex("^[a-zA-Z0-9_-]{1,64}$")
|
||||
|
||||
private fun jsonRpcError(
|
||||
id: kotlinx.serialization.json.JsonElement,
|
||||
code: Int,
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ class McpSession(
|
|||
AuthorizationCodeManager(tokenStore = tokenStore),
|
||||
private val auditListener: AuditListener? = null,
|
||||
private val hostname: String = "localhost",
|
||||
private val rateLimiter: RateLimiter? = null,
|
||||
private val mcpRateLimiter: RateLimiter? = null,
|
||||
private val serverName: String = "rouse-context",
|
||||
private val serverVersion: String = "0.1.0"
|
||||
) {
|
||||
|
|
@ -64,6 +66,8 @@ class McpSession(
|
|||
authorizationCodeManager = authorizationCodeManager,
|
||||
hostname = hostname,
|
||||
auditListener = auditListener,
|
||||
rateLimiter = rateLimiter,
|
||||
mcpRateLimiter = mcpRateLimiter,
|
||||
serverName = serverName,
|
||||
serverVersion = serverVersion
|
||||
)
|
||||
|
|
|
|||
|
|
@ -31,8 +31,8 @@ class AuthorizationCodeFlowTest {
|
|||
assertNotNull(request.requestId)
|
||||
assertTrue(request.requestId.isNotEmpty())
|
||||
assertNotNull(request.displayCode)
|
||||
// Display code format: XXXX-XXXX
|
||||
assertTrue(request.displayCode.matches(Regex("[A-Z2-9]{4}-[A-Z2-9]{4}")))
|
||||
// Display code format: XXXXXX-XXXXXX (12 chars total for ~61 bits entropy)
|
||||
assertTrue(request.displayCode.matches(Regex("[A-Z2-9]{6}-[A-Z2-9]{6}")))
|
||||
assertEquals("health", request.integration)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,8 +16,8 @@ class DeviceCodeFlowTest {
|
|||
assertNotNull(response.deviceCode)
|
||||
assertNotNull(response.userCode)
|
||||
assertTrue(response.deviceCode.isNotEmpty())
|
||||
// User code format: XXXX-XXXX (8 alphanumeric + dash)
|
||||
assertTrue(response.userCode.matches(Regex("[A-Z2-9]{4}-[A-Z2-9]{4}")))
|
||||
// User code format: XXXXXX-XXXXXX (12 alphanumeric + dash, ~61 bits entropy)
|
||||
assertTrue(response.userCode.matches(Regex("[A-Z2-9]{6}-[A-Z2-9]{6}")))
|
||||
assertEquals(5, response.interval)
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue