In Ktor, is there a way to limit size of data that can be attempted to be deserialized from JSON? Context is defending against denial-of-service attacks where a malicious client might try and send a huge payload to cause out-of-memory issues
I've used a similar capability in Play before (https://www.playframework.com/documentation/2.8.x/ScalaBodyParsers#Max-content-length). You can set the maximum globally, and also specifically override on individual routes.
Unfortunately, there is no built-in functionality in Ktor to limit the size of a body for deserialization. Still, you can write an interceptor for the
ApplicationReceivePipelinepipeline to replace theByteReadChannel(body bytes are read from this object) with another channel. The latter's implementation will count a total number of bytes read and throw an exception if that count exceeds some limit. Here is an example: