feat: Add JWT and API key authentication infrastructure#35
Merged
Conversation
Implement comprehensive authentication and authorization framework with JWT tokens and API keys, permission-based access control, and FastAPI integration.
Changes:
- Create shared/auth package with authentication utilities
- Add JWT token encoding, decoding, and validation with PyJWT
- Add API key generation, hashing, and validation
- Create Permission enum for fine-grained access control
- Add UserIdentity model for authenticated user context
- Create FastAPI dependencies for authentication and authorization
- Add require_permissions() and require_any_permission() decorators
Authentication Methods:
- JWT Bearer tokens (Authorization: Bearer <token>)
- API keys (X-API-Key: ck_xxxxx...)
- Service-to-service authentication support
Permission System:
- Session permissions (CREATE, READ, UPDATE, DELETE, LIST)
- Memory permissions (CREATE, READ, UPDATE, DELETE, SEARCH, LIST)
- Admin permissions (READ, WRITE)
Key Features:
- Dual authentication support (JWT + API keys)
- Permission-based authorization with has_permission(), has_any_permission(), has_all_permissions()
- FastAPI dependency injection for auth
- Token expiration and validation
- API key expiration and rate limiting
- Configurable auth settings via environment variables
- Comprehensive error handling (401 Unauthorized, 403 Forbidden)
Usage Example:
```python
from shared.auth.dependencies import get_current_user, require_permissions
from shared.auth.models import Permission
@app.post("/sessions")
async def create_session(
user: Annotated[UserIdentity, Depends(require_permissions(Permission.SESSION_CREATE))],
):
return {"user_id": user.user_id}
```
Configuration:
- AUTH_JWT_SECRET_KEY: JWT signing key
- AUTH_JWT_ALGORITHM: JWT algorithm (default: HS256)
- AUTH_JWT_ACCESS_TOKEN_EXPIRE_MINUTES: Token TTL (default: 60)
- AUTH_API_KEY_ENABLED: Enable API keys (default: true)
- AUTH_REQUIRE_AUTH: Require auth globally (default: true)
Documentation: See shared/auth/README.md for detailed usage guide
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implementation Details
Authentication Package (shared/auth/)
Core modules:
models.py- UserIdentity, Permission enum, TokenPayload, APIKeyInfojwt.py- JWT token creation, validation, and refreshapi_key.py- API key generation, hashing, and verificationdependencies.py- FastAPI dependencies for auth and authorizationconfig.py- Authentication settings (environment-based)JWT Authentication (jwt.py:17-147)
Features:
Example:
API Key Authentication (api_key.py:14-92)
Features:
ck_xxxxx...)Example:
Permission System (models.py:18-44)
Permission types:
Permission checking methods:
has_permission(perm)- Check single permissionhas_any_permission([perms])- Check if user has anyhas_all_permissions([perms])- Check if user has allFastAPI Integration (dependencies.py:71-202)
Dependencies:
get_current_user- Require authentication (JWT or API key)get_current_user_optional- Optional authenticationrequire_permissions(*perms)- Require specific permissionsrequire_any_permission(*perms)- Require any of the permissionsExample:
User Identity Model (models.py:47-87)
Contains:
user_id- Unique user identifierorg_id- Organization identifier (optional)email,name- User metadatapermissions- List of granted permissionsprovider- Auth method used (JWT, API_KEY, SERVICE)metadata- Additional contextConfiguration (config.py:11-33)
Environment variables:
AUTH_JWT_SECRET_KEY- Required JWT signing secretAUTH_JWT_ALGORITHM- JWT algorithm (default: HS256)AUTH_JWT_ACCESS_TOKEN_EXPIRE_MINUTES- Token TTL (default: 60)AUTH_API_KEY_ENABLED- Enable API keys (default: true)AUTH_REQUIRE_AUTH- Global auth requirement (default: true)AUTH_REQUIRE_AUTH_EXCEPTIONS- Endpoints exempt from authClient Authentication
JWT Bearer Token
curl -H "Authorization: Bearer eyJ0eXAi..." \ http://localhost:8000/api/v1/sessionsAPI Key
curl -H "X-API-Key: ck_xxxxx..." \ http://localhost:8000/api/v1/sessionsIntegration Guide
1. Configure Handlers
2. Override Dependencies
3. Protect Endpoints
Security Features
Error Responses
401 Unauthorized- Missing or invalid credentials403 Forbidden- Valid auth but insufficient permissionsDocumentation
Comprehensive usage guide in shared/auth/README.md with:
Future Enhancements
This PR provides the foundation. Future work can add:
Test Plan
🤖 Generated with Claude Code