feat(auth): implement Keycloak authentication with RBAC and pagination
Some checks failed
ci/woodpecker/pr/lint Pipeline failed
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/type Pipeline was successful

Major changes:
- Add Keycloak integration via token introspection endpoint
- Implement RBAC system with roles: admin, user, guest
- Add role-based permissions for post operations
- Add pagination support (default limit: 10) to list endpoints
- Add published_only filter with admin-only override for unpublished posts

Security improvements:
- Remove hardcoded default secrets (SECRET_KEY, KEYCLOAK_CLIENT_SECRET)
- Update .env.example with proper security placeholders
- Add comprehensive RBAC unit tests

Infrastructure:
- Add httpx dependency for HTTP client
- Add KeycloakAuthClient with token caching (TTL: 60s)
- Add role-based dependencies (RequireAdmin, RequireUser, etc.)
- Update DI container with Keycloak provider

Endpoints updated:
- GET /posts: filter by published status (admin can see all)
- Add pagination params (limit, offset) to list endpoints
- Enforce RBAC on post operations

Tests:
- Add 16 auth infrastructure tests
- Add 13 RBAC role tests
- Update existing tests for new required settings

Breaking changes:
- SECRET_KEY and KEYCLOAK_CLIENT_SECRET now required (no defaults)
This commit is contained in:
2026-05-02 00:43:10 +03:00
parent ddab62a883
commit 184b95969c
20 changed files with 1461 additions and 99 deletions

33
.env.example Normal file
View File

@@ -0,0 +1,33 @@
# Environment mode: dev or prod
ENVIRONMENT=dev
# App settings
APP_NAME=Blog API
APP_DEBUG=false
APP_HOST=0.0.0.0
APP_PORT=8000
# Database settings
# For dev (SQLite): DB_URL=sqlite+aiosqlite:///./blog.db
# For prod (PostgreSQL): DB_URL=postgresql+asyncpg://user:pass@host:port/db
# Or use individual DB_* vars for prod (see below)
DB_URL=
DB_ECHO=false
# PostgreSQL-specific settings (used in prod when DB_URL is not set)
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=blog
# Security settings (REQUIRED)
SECURITY_SECRET_KEY=your-secret-key-here-change-in-production
SECURITY_ACCESS_TOKEN_EXPIRE_MINUTES=30
# Keycloak settings (REQUIRED for authentication)
KC_SERVER_URL=http://localhost:8080
KC_REALM=blog
KC_CLIENT_ID=blog-api
KC_CLIENT_SECRET=your-keycloak-client-secret-here
KC_TOKEN_CACHE_TTL=60