Limit max body size to 64kb

This commit is contained in:
2026-08-27 20:22:15 +08:00
parent e2c06f7efe
commit 11feb7f606
1 file changed
+17 -4
@@ -15,8 +15,8 @@ import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.request.* import io.ktor.server.request.*
import io.ktor.server.response.* import io.ktor.server.response.*
import io.ktor.server.routing.* import io.ktor.server.routing.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.* import io.ktor.utils.io.core.*
import kotlinx.io.Buffer
import kotlinx.io.buffered import kotlinx.io.buffered
import kotlinx.io.files.Path import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem import kotlinx.io.files.SystemFileSystem
@@ -28,6 +28,8 @@ import snippets.util.encodeJson
import snippets.util.fromJson import snippets.util.fromJson
import kotlin.time.Clock import kotlin.time.Clock
private const val MAX_CONTENT_SIZE_BYTES = 64 * 1024
fun Application.registerSnippetsRouting() { fun Application.registerSnippetsRouting() {
install(ContentNegotiation) { install(ContentNegotiation) {
json() json()
@@ -49,14 +51,25 @@ fun Application.registerSnippetsRouting() {
routing { routing {
post("/api/v1/snippets") { 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<SnippetContent>() val payload = call.receive<SnippetContent>()
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 snippetId = generateShortId()
val meta = SnippetMeta(Clock.System.now(), payload.filename, payload.content) val meta = SnippetMeta(Clock.System.now(), payload.filename, payload.content)
.encodeJson().toByteArray() .encodeJson().toByteArray()
val snippetPath = Path(dataDir, snippetId).apply { SystemFileSystem.createDirectories(this) } val snippetPath = Path(dataDir, snippetId).apply { SystemFileSystem.createDirectories(this) }
SystemFileSystem.sink(Path(snippetPath, "meta.json")).use {
val buffer = Buffer().apply { write(meta) } SystemFileSystem.sink(Path(snippetPath, "meta.json")).buffered().use { sink ->
it.write(buffer, meta.size.toLong()) sink.write(meta)
} }
call.respond(status = HttpStatusCode.Created, message = mapOf("snippet_id" to snippetId)) call.respond(status = HttpStatusCode.Created, message = mapOf("snippet_id" to snippetId))
} }