Optimize API key auth: O(1) lookup via UUID-embedded key format

New format: gns3_<api_key_id>_<random_secret>
- Auth extracts api_key_id from token → single DB query by UUID → one bcrypt
- No more scanning all keys (was O(n) with bcrypt per key)
- bcrypt.checkpw offloaded to thread pool to prevent event loop blocking
- Legacy gns3_<random> format removed (compatibility break)
This commit is contained in:
YueGuobin 2026-06-15 23:56:36 +08:00
parent 796a2e6ca8
commit f522c947bc
No known key found for this signature in database
2 changed files with 33 additions and 29 deletions

View File

@ -39,12 +39,15 @@ API_KEY_PREFIX = "gns3_"
API_KEY_BYTES = 32 API_KEY_BYTES = 32
def _generate_api_key() -> tuple[str, str, str]: def _generate_api_key(api_key_id: UUID = None) -> tuple[str, str, str, UUID]:
if api_key_id is None:
api_key_id = uuid4()
random_bytes = secrets.token_hex(API_KEY_BYTES) random_bytes = secrets.token_hex(API_KEY_BYTES)
raw_key = API_KEY_PREFIX + random_bytes raw_key = f"gns3_{api_key_id}_{random_bytes}"
key_hash = bcrypt.hashpw(raw_key.encode(), bcrypt.gensalt()).decode() # Only hash the random secret part, so auth can extract api_key_id and do O(1) lookup
key_hash = bcrypt.hashpw(random_bytes.encode(), bcrypt.gensalt()).decode()
key_prefix = raw_key[: len(API_KEY_PREFIX) + 8] key_prefix = raw_key[: len(API_KEY_PREFIX) + 8]
return raw_key, key_hash, key_prefix return raw_key, key_hash, key_prefix, api_key_id
@router.post("", status_code=status.HTTP_201_CREATED) @router.post("", status_code=status.HTTP_201_CREATED)
@ -55,9 +58,9 @@ async def create_api_key(
) -> dict: ) -> dict:
"""Create a new API key. The full key is returned only once.""" """Create a new API key. The full key is returned only once."""
raw_key, key_hash, key_prefix = _generate_api_key() raw_key, key_hash, key_prefix, new_key_id = _generate_api_key()
db_key = await api_keys_repo.create_api_key( db_key = await api_keys_repo.create_api_key(
api_key_id=uuid4(), api_key_id=new_key_id,
user_id=current_user.user_id, user_id=current_user.user_id,
name=api_key_data.name, name=api_key_data.name,
key_hash=key_hash, key_hash=key_hash,

View File

@ -57,31 +57,32 @@ async def get_user_from_token(
headers={"WWW-Authenticate": "Bearer"}, headers={"WWW-Authenticate": "Bearer"},
) )
# API Key authentication # API Key authentication — format: gns3_<api_key_id>_<random_secret>
# Direct lookup by UUID avoids O(n) scan of all keys.
if token.startswith("gns3_"): if token.startswith("gns3_"):
log.info(f"[CTRL-TIMING] get_user_from_token API_KEY auth elapsed={time.time()-_t0:.3f}s") log.info(f"[CTRL-TIMING] get_user_from_token API_KEY auth elapsed={time.time()-_t0:.3f}s")
query = select(models.ApiKey).where(models.ApiKey.revoked == False) parts = token.split("_", 2)
result = await api_keys_repo._db_session.execute(query) if len(parts) != 3:
api_keys_list = result.scalars().all() raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key format")
log.info(f"[CTRL-TIMING] get_user_from_token api_keys_count={len(api_keys_list)} elapsed={time.time()-_t0:.3f}s") try:
for db_key in api_keys_list: key_id = UUID(parts[1])
# bcrypt.checkpw is CPU-bound and blocks the event loop; run in thread except ValueError:
if await asyncio.to_thread(bcrypt.checkpw, token.encode(), db_key.key_hash.encode()): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key format")
await api_keys_repo.update_last_used(db_key.api_key_id) secret = parts[2]
user = await user_repo.get_user(db_key.user_id) db_key = await api_keys_repo.get_api_key(key_id)
if user: if not db_key or db_key.revoked:
if not user.is_active: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
raise HTTPException( if not await asyncio.to_thread(bcrypt.checkpw, secret.encode(), db_key.key_hash.encode()):
status_code=status.HTTP_401_UNAUTHORIZED, raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
detail="Not an active user", await api_keys_repo.update_last_used(db_key.api_key_id)
headers={"WWW-Authenticate": "Bearer"}, user = await user_repo.get_user(db_key.user_id)
) if not user or not user.is_active:
return user raise HTTPException(
raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED,
status_code=status.HTTP_401_UNAUTHORIZED, detail="Not an active user",
detail="Invalid API key", headers={"WWW-Authenticate": "Bearer"},
headers={"WWW-Authenticate": "Bearer"}, )
) return user
# JWT authentication # JWT authentication
token_data = auth_service.get_token_data(token) token_data = auth_service.get_token_data(token)