API Security – How to Prevent Multiple Requests to a Public API

api-designSecurity

I have an api where visitor can send an email through subscription:

/api/subscribe

To prevent massive load due to public exposure, how can I secure this endpoint? Do I have to use database or can I do it without that with some kind of caching, inmemory etc which releases ever 10 minutes etc?

Best Answer

You can use Proof of Work to enforce rate limiting without needing to remember IP addresses.

With Proof of Work, you require that the client do a computationally expensive function to generate a proof that you can verify cheaply. One of the most common PoW is partial hash inversion, in which that you require that every API submission is attached with a hash of proof+request, for which the hash must have a predefined prefix (usually zeros) of a certain length. For the client, calculating the proof requires testing hundreds or thousands of potential proofs, until they stumbled upon one that have the required number of zeros; the goal should be to require typical clients to expend several seconds or minutes of computational power for each messages sent. But for the server, verifying the proof involves only one hash calculation. This asymmetry means it's much more expensive for the client to generate valid request, than for the server to reject invalid ones.

To prevent replay attack, you can require that requests must contain a timestamp or a counter. Your server can check to reject requests containing timestamps that are too old or which contains a counter value that had already been used.

Related Topic