Protect API from being tampered?

What if the attacker decides to tamper the "from:id" such that it could send arbitrary messages to anyone from any user?

Create a session, and use the session identifier as identifier, not the user ID directly. E.g. let user send credentials, and upon successful validation, return a (short lived) session handle, that can be used in future messages.

Validate that the session exists and is active, and map it back to user server-side.

What if the attacker builds a script that spams millions of messages by taking advantage of the "to:id" field?

Rate limit users server side. For instance, disallow sending messages to more than ten different users a minute. This will probably not bother legitimate users, but will hamper spammers efforts. Tuning of the limit may obviously be needed - and it may be an idea to raise it for trusted users, based on behavior, and lower it upon receiving reports about spam from users.


Basically, you have to treat every input from the user as potentially malicious.

Vidarlo has already mentioned two security issues and how they can be prevented in his answer.

I'd also add that the content itself ("text:") could contain malicious code (e.g. javascript snippets). Make sure that this code is not executed on the receiving end.

And I'd also check if the time seems correct. Depending on your application, having verified timestamps could be useful or even necessary.


What if the attacker decides to tamper the "from:id" such that it could send arbitrary messages to anyone from any user?

Do not use from:id in your API. You already know it from user authenticated session instead and have zero reason for user to transmit it to you in the first place. And if there's nothing to transmit, there's nothing to tamper.

On that note, throw away date and time too. You already know when you've received message and don't need user to tell you that. You only'd need those if your application+API have some concept of offline/scheduled/backlog messages.

What if the attacker builds a script that spams millions of messages by taking advantage of the "to:id" field?

That's pretty old, even classic problem that have different, just as old solutions. One of the simplest is to introduce a timeout: backend remembers when the use sent a message and he can't send anything until some period passed. Some more complex solution still boil down to limiting user to some amount of messages per some period of time, but use progressively larger delays that fall off with time as more messages are sent in. Search for "throttling" or "rate limit" for some examples and ideas.