📚 Encyclopedia

Security & Cryptography · updated 2026-10-13

Rotating API keys without locking yourself out

api-keysrotationfile-permissionsapachephp

Key rotation endpoints usually invalidate the old key the moment they return the new one. If the caller then fails to store the new key, both keys are gone and the service is locked out. Treat "where will I write the new key" as a precondition, not an afterthought.

The incident

The search project's PHP API called claude-service's rotate endpoint to replace its API key. claude-service returned a new key and retired the old one, but PHP could not write api_key.php: Apache/php-fpm runs as user apache and the file was owned by justin with no group write. The new key existed only in that failed response; the old one no longer worked.

Safe rotation order

  1. Check writability first, as the process that will do the write (is_writable($path) in PHP, or actually write and remove a temp file in the same directory).
  2. Only then call the rotate endpoint.
  3. Write the new key immediately, atomically (write to a temp file, then rename), and log a non-secret fingerprint (last 4 characters or a hash) so the two sides can be compared later.
  4. Prefer services that support overlapping keys (old key valid for a grace period, or an explicit confirm step), so a failed write is recoverable.

Deploy hygiene

A deploy that rewrites ownership or SELinux contexts can silently make the key file read-only to the web server again. Make the deploy script set the owner/group and mode of any file the app writes at runtime (here: group apache, writable), and check it after each deploy.

See also

Sources: search project memory