2

We have a REST API that returns user generated content from a database. Before inserting the data into the database the data is sanitized. But when returning the data we do not escape / decode the data, so in theory it would be possible to insert some user content that will execute an attack, once it is consumed from the client.

Right now the only client is an internal one, that displays the data in some HTML frontend.

Now my question is, should the API return json escaped JSON? Or should the client make sure to html escape the received content?

I am split here in my personal opinion, in general I would return data as is from any API and let take the client care of escaping (as there could be several different clients and the API should be agnostic to its content). On the other hand its an internal one and we know how we use it, so it could return escaped data.

Any inputs?

7

It belongs to the API to correctly serialize JSON: the user is not expected to be able to break JSON schema by introducing characters considered special in JSON, such as the quote character.

It doesn't belong to the API to HTML-encode the input: this is the responsibility of the consumer. If you HTML-encode data at the level of the API, it makes it extremely painful to use in any other context, such as a mobile application. Actually, using it even in web applications would become unnecessarily painful: React or Angular apps would require specific code to handle such strings in order to avoid double-escaping, and even outside those frameworks, the developer would have to think twice to avoid encoding strings which were already encoded.

Finally, the API should be agnostic; it is not expected to know if it is used by a PHP site, or through AJAX requests, or by a Java application, or an Android app.

1

You should only escape things and sanitise them at the last minute as a rule of thumb. You should always ask yourself this: Is this text going immediately be rendered as HTML? If not, don't escape. For example, if it's going to the database, then it's going to the database, not to a HTML render. If it's going to javascript then it's going to javascript, not a HTML renderer.

The reason for that is that it's only then that you know that you need to escape it and what you need to escape it for. If you escape things prematurely then you can end up having to unescape them, double escaping them or even losing data (especially if you sanitise).

Extreme care should be taken with sanitisation due to it's destructive nature. Sometimes validation is better.

Since you always know when to escape data then it's a lot easier if you know it's always unescaped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.