Imported from furevaljj/Authentication-and-authorization-service (
AGENTS.md). Install upstream withnpx skills add furevaljj/Authentication-and-authorization-service. Copyright stays with the author.
1. Core Stack & Libraries
- Language: Python 3.11+
- Framework: FastAPI
- Data Store (Primary): PostgreSQL via SQLAlchemy 2.0 (Async) + asyncpg
- Database Migrations: Alembic
- Cache & Session Engine: Redis via redis-py (Async)
- Hashing & Crypto: argon2-cffi (Password hashing), PyJWT / python-jose (JWT handling)
- Task Queue / Mailer: Celery o FastStream (para envío asíncrono de emails de verificación)
2. Python & FastAPI Code Standards
- All route handlers and DB methods MUST be asynchronous (
async def). - Strict typing using Python type hints and Pydantic v2 schemas.
- Dependency Injection: Use FastAPI
Depends()for DB sessions, Redis clients, and security context (e.g.,get_current_user,require_permission). - Error Handling: Use standard
HTTPExceptionwith structured error details (RFC 7807 compatible).
3. Domain & Data Specifications
Authentication & Sessions
- Tokens: Short-lived Access Token (JWT, TTL: 15m), Long-lived Refresh Token (Opaque Hash, TTL: 7d).
- Storage: Refresh tokens stored hashed (Argon2id or bcrypt) in Redis/DB with family rotation detection.
- Revocation: Support single session revocation and global user logout (all active devices).
Security Rules & Standards
- Passwords: Hash with Argon2id (or bcrypt with cost factor 12+).
- Rate Limiting: Sliding window pattern via Redis.
- Auth endpoints (
/login,/register,/forgot-password): 5 requests/minute per IP. - Refresh endpoint: 10 requests/minute per IP/User.
- Standard API: 100 requests/minute per User.
- Auth endpoints (
- Email Verification & Password Reset: Generate cryptographically secure random tokens with strict expiry (15 min) and single-use enforcement.
- OAuth 2.0: Use PKCE flow for open identity verification (Google/GitHub).
Authorization (RBAC / ABAC)
- Design flexible Role-Based Access Control:
Users<->UserRoles<->Roles<->RolePermissions<->Permissions. - All routes must require explicitly defined middleware permissions (e.g.,
@RequirePermission('users:read')).
4. Definition of Done (DoD) for Each Spec
For every feature module (e.g., OAuth, Magic Link, RBAC), ensure:
- Spec file created/updated in
/specs/. - Database migration written and rolled back successfully in dev.
- Happy path and edge-case integration tests passing (100% coverage on auth critical paths).
- Error responses strictly conform to standard RFC 7807 (Problem Details).
- Postman / OpenAPI specification updated.
5. Extras
Implementar la detección de reuso de refresh tokens: Si un Refresh Token usado previamente intenta ser canjeado de nuevo, el sistema debe revocar inmediatamente toda la familia de tokens de ese usuario, asumiendo una brecha de seguridad.