Skip to content

Improve Error Handling for API Key Validation (api_key_service.py) #357

@nndn

Description

@nndn

Issue Title: Improve Error Handling for API Key Validation in api_key_service.py

Description:

The validate_api_key function in api_key_service.py currently does not provide clear error messages when API key validation fails. To enhance user experience and debugging, we need to implement more informative error handling that specifies the nature of the validation failure.

Proposed Changes:

  1. Enhance Error Messaging:

    • Update the validate_api_key function to return specific error messages for different failure scenarios, such as:
      • When the API key format is incorrect (e.g., if it does not start with the expected prefix).
      • When the hashed API key does not match any records in the database.
  2. Code Implementation:

    • Modify the return statements in the function to provide structured error messages instead of simply returning None.
  3. Testing:

    • Add unit tests to ensure that various invalid inputs trigger the appropriate error messages.

Current Code Snippet:

@staticmethod async def validate_api_key(api_key: str, db: Session) -> Optional[dict]: 
"""Validate an API key and return user info if valid."""

if not api_key.startswith(APIKeyService.SECRET_PREFIX): return None # <-- Update this line to provide an error message

hashed_key = APIKeyService.hash_api_key(api_key)

result = (
    db.query(UserPreferences, User.email)
    .join(User, UserPreferences.user_id == User.uid)
    .filter(text("preferences->>'api_key_hash' = :hashed_key"))
    .params(hashed_key=hashed_key)
    .first()
)

if not result:
    return None  # <-- Update this line to provide an error message

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions