« All posts

Why Trusting the Database for API Auth Is a Security Risk

A technical look at how HMAC-SHA512 signing, cryptographic peppers, and layered tenancy checks prevent SQL injection attacks from turning into full tenant takeovers.

This piece explains why treating the database as the ultimate source of truth for API authentication is a hidden but serious vulnerability. In the naive approach, API keys are hashed and stored in a database table; but if an attacker finds any SQL injection flaw elsewhere, they can simply overwrite a victim's stored hash with the hash of their own legitimate key. Using their own valid key, the attacker then impersonates the victim and breaks the entire tenant boundary.

The fix described is cryptographic binding: instead of a plain hash, an HMAC-SHA512 signature is computed using a server-side secret pepper, covering not just the secret but also the key-id, rotation version, and org-id. Because org-id is pulled from the URL path and folded into the signature, swapping hashes in the database no longer works — the wrong org-id breaks the signature. Since the pepper never touches the database, even an attacker with full read/write DB access cannot forge valid keys.

The design also uses database triggers to enforce a one-way ratchet on rotation version, preventing revoked 'zombie' keys from being resurrected via rollback. Tenancy is checked redundantly across four layers — routing, authentication, application logic, and database schema — embodying a defense-in-depth philosophy. Finally, a prev-hash column and grace-period timestamp enable zero-downtime key rotation, though the piece notes this flexibility can reintroduce rollback risks if not carefully bounded.

» SourceHashnode #3