Limit max body size to 64kb
This commit is contained in:
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.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<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 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))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user