From 11feb7f60610dde0d753da0b0fcf85c374011518 Mon Sep 17 00:00:00 2001 From: RTAkland Date: Thu, 27 Aug 2026 20:22:15 +0800 Subject: [PATCH] Limit max body size to 64kb --- .../snippets/routing/SnippetsRouting.kt | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/snippets-backend/src/commonMain/kotlin/snippets/routing/SnippetsRouting.kt b/snippets-backend/src/commonMain/kotlin/snippets/routing/SnippetsRouting.kt index 52c72c8..1041a56 100644 --- a/snippets-backend/src/commonMain/kotlin/snippets/routing/SnippetsRouting.kt +++ b/snippets-backend/src/commonMain/kotlin/snippets/routing/SnippetsRouting.kt @@ -15,8 +15,8 @@ import io.ktor.server.plugins.cors.routing.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* +import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* -import kotlinx.io.Buffer import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem @@ -28,6 +28,8 @@ import snippets.util.encodeJson import snippets.util.fromJson import kotlin.time.Clock +private const val MAX_CONTENT_SIZE_BYTES = 64 * 1024 + fun Application.registerSnippetsRouting() { install(ContentNegotiation) { json() @@ -49,14 +51,25 @@ fun Application.registerSnippetsRouting() { routing { post("/api/v1/snippets") { + val contentLength = call.request.contentLength() + if (contentLength != null && contentLength > MAX_CONTENT_SIZE_BYTES) { + call.respond(HttpStatusCode.PayloadTooLarge) + return@post + } val payload = call.receive() + val contentBytes = payload.content.toByteArray(Charsets.UTF_8) + if (contentBytes.size > MAX_CONTENT_SIZE_BYTES) { + call.respond(HttpStatusCode.PayloadTooLarge) + return@post + } + val snippetId = generateShortId() val meta = SnippetMeta(Clock.System.now(), payload.filename, payload.content) .encodeJson().toByteArray() val snippetPath = Path(dataDir, snippetId).apply { SystemFileSystem.createDirectories(this) } - SystemFileSystem.sink(Path(snippetPath, "meta.json")).use { - val buffer = Buffer().apply { write(meta) } - it.write(buffer, meta.size.toLong()) + + SystemFileSystem.sink(Path(snippetPath, "meta.json")).buffered().use { sink -> + sink.write(meta) } call.respond(status = HttpStatusCode.Created, message = mapOf("snippet_id" to snippetId)) }