potpie
potpie copied to clipboard
Improve error handling for API key validation (fixes #357)
Summary
This PR enhances error handling for API key validation in api_key_service.py, ensuring clear, specific, and secure error responses across validation scenarios. It also simplifies router logic and adds comprehensive test coverage.
Changes Made
1. Enhanced Error Handling (app/modules/auth/api_key_service.py:104–166)
-
Invalid format → Returns HTTP 401 when API key doesn’t start with
sk- - Not found → Returns HTTP 401 if API key hash isn’t found in DB
- Internal errors → Returns HTTP 500 with detailed logs for DB/internal issues
- Logging added → All failure scenarios logged for easier debugging
- Docstring updated → Improved documentation of return values and exceptions
2. Simplified Router Logic (app/api/router.py:69–74)
- Removed redundant error handling since
validate_api_key()now raises HTTPException directly - Centralized and cleaner error flow
3. Comprehensive Test Coverage (app/modules/auth/tests/api_key_service_test.py)
Added 25 unit tests covering:
- API key generation: format, uniqueness, length
- Hashing: consistency, hex format
- Validation scenarios:
- ✅ Successful validation
- ❌ Invalid/missing prefix
- ❌ Empty strings
- ❌ API key not found in DB
- ❌ Wrong prefix
- ❌ Database errors
- ❌ Special characters, unicode, whitespace
- ❌ SQL injection attempts
- ❌ Null bytes
- ❌ Very long keys
- API key creation: new vs existing users
- API key revocation: success and edge cases
All tests pass successfully (25/25).
Test Results## Security Improvements
- Proper handling of SQL injection attempts
- Safe processing of malformed input (unicode, null bytes, special chars)
- Consistent error messages without leaking sensitive info
- Appropriate HTTP codes (401 for auth failures, 500 for server errors)
Fixes
Closes #357
Summary by CodeRabbit
-
Bug Fixes
- Enhanced API key validation with improved error handling and clearer error messages for invalid, missing, or malformed keys.
-
Tests
- Added comprehensive test coverage for API key management, including generation, validation, creation, and revocation scenarios.