Sync legacy api_keys row when the single legacy key is regenerated

regenerate_api_key() only updated users.api_key_hash/prefix, leaving the
backfilled 'Default (legacy)' row in api_keys stale after rotation — not a
security issue (the old hash was still correctly rejected) but the Tokens
page would show a wrong/orphaned prefix for a key that no longer works.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
MOHAN 2026-07-02 00:31:14 +05:30
parent 05babc6d99
commit 0439811613

View File

@ -97,12 +97,20 @@ def get_user_by_api_key(api_key: str) -> Optional[User]:
def regenerate_api_key(user_id: int) -> str: def regenerate_api_key(user_id: int) -> str:
"""Generate a new API key for the user. Returns the full key (shown once).""" """Generate a new API key for the user. Returns the full key (shown once).
Also syncs the backfilled 'Default (legacy)' row in api_keys (see
list_api_keys) if one exists, so the Tokens page doesn't show a stale
prefix/hash for a key that no longer works after rotation."""
full_key, key_hash, key_prefix = generate_api_key() full_key, key_hash, key_prefix = generate_api_key()
db_execute( db_execute(
"UPDATE users SET api_key_hash = ?, api_key_prefix = ? WHERE id = ?", "UPDATE users SET api_key_hash = ?, api_key_prefix = ? WHERE id = ?",
(key_hash, key_prefix, user_id), (key_hash, key_prefix, user_id),
) )
db_execute(
"UPDATE api_keys SET key_hash = ?, key_prefix = ? WHERE user_id = ? AND name = 'Default (legacy)'",
(key_hash, key_prefix, user_id),
)
db_commit() db_commit()
return full_key return full_key