diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..5d7befecd32ff0acc59db6caa8f9df01339b85ce --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# Shared Secret (CRITICAL: Must match frontend .env) +# Generate with: openssl rand -base64 32 +BETTER_AUTH_SECRET= + +# Database Connection (Neon PostgreSQL) +DATABASE_URL=postgresql+asyncpg://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb + +# API Configuration +API_PORT=8000 +CORS_ORIGINS=http://localhost:3000 + +# Environment +ENVIRONMENT=development + +# OpenRouter Configuration (AI Chatbot) +# Get your free API key at https://openrouter.ai/keys +OPENROUTER_API_KEY=sk-or-v1-your-openrouter-api-key + +# Free tier models (working as of Jan 2026): +# - meta-llama/llama-3.2-3b-instruct:free (recommended) +# - mistralai/mistral-7b-instruct:free +OPENROUTER_MODEL=meta-llama/llama-3.2-3b-instruct:free diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..32f45ab77f9961e5e9325133e9d0db9559e6f1ca --- /dev/null +++ b/.gitignore @@ -0,0 +1,51 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual Environment +venv/ +env/ +ENV/ +.venv + +# Environment Variables +.env +.env.local +.env.*.local + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store +Thumbs.db + +# Testing +.pytest_cache/ +.coverage +htmlcov/ +.tox/ + +# Logs +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..496d5764d7c1ee6635ba773a592d20456fa42213 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# Use Python 3.11 slim image +FROM python:3.11-slim + +# Set working directory +WORKDIR /app + +# Copy requirements and install dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the entire backend source code +COPY . . + +# Expose the port the app runs on +EXPOSE 8000 + +# Command to run the application +CMD ["python", "run_dev.py"] \ No newline at end of file diff --git a/IMPLEMENTATION_SUMMARY.md b/IMPLEMENTATION_SUMMARY.md new file mode 100644 index 0000000000000000000000000000000000000000..6f54f8367d0b3ee8d6f1b98beb0ee2583d7c7967 --- /dev/null +++ b/IMPLEMENTATION_SUMMARY.md @@ -0,0 +1,362 @@ +# FastAPI Backend Implementation Summary + +**Date**: 2026-01-09 +**Feature**: Todo API with JWT Authentication +**Status**: ✓ Complete + +## Implementation Overview + +Successfully built a production-ready FastAPI backend with JWT authentication, user isolation, and async database operations. The implementation follows the architecture defined in `specs/001-todo-api/plan.md` and enforces all constitutional security requirements. + +## Files Created + +### Core API Components + +1. **JWT Authentication Middleware** (201 lines) + - File: `E:\todoweb\backend\src\api\middleware\auth.py` + - Functions: + - `verify_token()` - Validates JWT signature and claims + - `get_current_user_id()` - FastAPI dependency for user extraction + - `get_current_user_info()` - Returns full JWT payload + - Security: Validates issuer="todoweb", audience="todoweb-api" + - Error handling: Returns 401 for invalid/expired tokens + +2. **Todo Routes** (445 lines) + - File: `E:\todoweb\backend\src\api\routes\todos.py` + - Endpoints implemented: + - `POST /api/todos` - Create todo (201 Created) + - `GET /api/todos` - List todos (200 OK) + - `GET /api/todos/{id}` - Get single todo (200 OK) + - `PUT /api/todos/{id}` - Update todo (200 OK) + - `DELETE /api/todos/{id}` - Delete todo (204 No Content) + - `PATCH /api/todos/{id}/complete` - Toggle completion (200 OK) + - Security: All routes use `Depends(get_current_user_id)` + - User isolation: All queries filter by `user_id` from JWT + - Information hiding: Returns 404 (not 403) for unauthorized access + +3. **FastAPI Application** (237 lines) + - File: `E:\todoweb\backend\src\api\main.py` + - Features: + - Lifespan management (startup/shutdown) + - CORS middleware for Next.js frontend + - Health check endpoint (`/health`) + - Root endpoint (`/`) + - Global exception handler + - Database initialization on startup + - CORS: Configured for http://localhost:3000 + +### Supporting Files + +4. **Package Initialization** + - `E:\todoweb\backend\src\api\__init__.py` + - `E:\todoweb\backend\src\api\middleware\__init__.py` + - `E:\todoweb\backend\src\api\routes\__init__.py` + +5. **Development Server Script** + - File: `E:\todoweb\backend\run_dev.py` + - Features: + - Environment validation + - Configuration display + - Hot-reload enabled + - Uvicorn integration + +6. **Test Script** + - File: `E:\todoweb\backend\test_api.py` + - Tests: + - Health check (no auth) + - Root endpoint (no auth) + - Unauthorized access rejection + - Create, list, get, update, delete, toggle todos (with auth) + - JWT token generation for testing + +7. **Environment Configuration** + - File: `E:\todoweb\backend\.env` + - Variables: + - `BETTER_AUTH_SECRET` (shared with frontend) + - `DATABASE_URL` (Neon PostgreSQL) + - `API_PORT=8000` + - `API_HOST=0.0.0.0` + - `CORS_ORIGINS` + - `LOG_LEVEL=INFO` + +8. **Documentation** + - File: `E:\todoweb\backend\README.md` + - Sections: + - Architecture overview + - Setup instructions + - API endpoints documentation + - Authentication protocol + - Security considerations + - Testing guide + - Troubleshooting + +## Security Implementation + +### JWT Authentication Protocol + +✓ **Token Verification** +- Signature validation using `BETTER_AUTH_SECRET` +- Issuer validation: `iss="todoweb"` +- Audience validation: `aud="todoweb-api"` +- Expiration enforcement via `exp` claim +- User ID extraction from `sub` claim + +✓ **User Isolation** +- All database queries filter by `user_id` +- User ID extracted from JWT (never from request body) +- Returns 404 for unauthorized access (prevents info leakage) +- No global queries without user filtering + +✓ **Error Handling** +- 401 Unauthorized: Invalid/missing/expired token +- 404 Not Found: Todo doesn't exist or doesn't belong to user +- 422 Validation Error: Invalid request format +- 500 Internal Server Error: Server errors (no sensitive info leaked) + +### CORS Configuration + +✓ **Frontend Integration** +- Allowed origins: http://localhost:3000, http://127.0.0.1:3000 +- Credentials enabled for JWT transmission +- Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS +- Headers: Authorization, Content-Type, Accept + +## Database Integration + +### Existing Database Module (Already Complete) + +✓ **Connection Management** (`backend/src/db/connection.py`) +- AsyncEngine with asyncpg driver +- Connection pooling optimized for Neon serverless +- pool_pre_ping=True for cold start handling +- Automatic connection recycling + +✓ **Data Models** (`backend/src/db/models.py`) +- `Todo` - Database table model +- `TodoCreate` - Request model for creation +- `TodoUpdate` - Request model for updates (partial) +- `TodoResponse` - Response model with all fields +- User isolation enforced via `user_id` column + +✓ **Initialization** (`backend/src/db/__init__.py`) +- `init_database()` - Creates tables and indexes +- `cleanup_database()` - Closes connections on shutdown +- `get_session()` - FastAPI dependency for database sessions + +## Code Statistics + +- **Total Lines**: 883 lines of production code +- **Files Created**: 8 new files +- **Endpoints**: 6 protected + 2 public = 8 total +- **Security Dependencies**: 2 (get_current_user_id, get_current_user_info) + +## Testing Status + +### Manual Testing Available + +✓ **Test Script** (`backend/test_api.py`) +- Generates test JWT tokens +- Tests all endpoints sequentially +- Validates authentication flow +- Checks unauthorized access rejection + +✓ **Development Server** (`backend/run_dev.py`) +- Environment validation +- Hot-reload for development +- Automatic API documentation at `/docs` + +### Integration Testing + +⏭️ **Next Steps** (Not implemented yet) +- Unit tests with pytest +- Integration tests with httpx +- Security tests for user isolation +- Performance tests for concurrent users + +## How to Run + +### 1. Configure Environment + +```bash +cd E:\todoweb\backend + +# Ensure .env is configured with: +# - BETTER_AUTH_SECRET (must match root .env) +# - DATABASE_URL (Neon PostgreSQL connection string) +``` + +### 2. Start Development Server + +```bash +cd E:\todoweb\backend +python run_dev.py +``` + +Server will start at: +- API: http://localhost:8000 +- Docs: http://localhost:8000/docs +- Health: http://localhost:8000/health + +### 3. Test the API + +```bash +cd E:\todoweb\backend +python test_api.py +``` + +**Note**: Update `BETTER_AUTH_SECRET` in `test_api.py` to match your `.env` file. + +## API Documentation + +### Interactive Documentation + +Once the server is running, visit: +- **Swagger UI**: http://localhost:8000/docs +- **ReDoc**: http://localhost:8000/redoc +- **OpenAPI JSON**: http://localhost:8000/openapi.json + +### Example Requests + +**Create Todo** (requires JWT): +```bash +curl -X POST http://localhost:8000/api/todos \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"title": "Buy groceries", "description": "Milk, eggs, bread"}' +``` + +**List Todos** (requires JWT): +```bash +curl http://localhost:8000/api/todos \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" +``` + +**Health Check** (no auth): +```bash +curl http://localhost:8000/health +``` + +## Architecture Compliance + +### Constitutional Requirements + +✓ **Principle II: Authentication & Authorization** +- Shared BETTER_AUTH_SECRET between Next.js and FastAPI +- JWT sub claim extracted as user_id +- Token validation on all protected routes +- 401 Unauthorized for invalid tokens + +✓ **Principle IV: Security - User Isolation** +- All queries filter by user_id from JWT +- No global queries without user filtering +- Returns 404 (not 403) to prevent info leakage + +✓ **Principle V: Async Python Development** +- All route handlers use `async def` +- Database operations use `await` +- AsyncSession for database connections +- asyncpg driver for Neon PostgreSQL + +### Specification Compliance + +✓ **JWT Protocol** (`specs/001-todo-api/contracts/jwt-protocol.md`) +- Token verification with python-jose +- Issuer and audience validation +- User ID extraction from sub claim +- Proper error responses + +✓ **API Endpoints** (`specs/001-todo-api/contracts/api-endpoints.yaml`) +- All 6 endpoints implemented +- Correct HTTP methods and status codes +- Request/response models match specification +- Error responses follow OpenAPI schema + +✓ **Implementation Plan** (`specs/001-todo-api/plan.md`) +- FastAPI with SQLModel architecture +- JWT middleware for authentication +- User isolation at database level +- CORS configured for Next.js + +## Next Steps + +### Immediate Actions + +1. **Configure BETTER_AUTH_SECRET** + - Generate: `openssl rand -base64 32` + - Add to `E:\todoweb\backend\.env` + - Ensure it matches `E:\todoweb\.env` + +2. **Verify Database Connection** + - Ensure `DATABASE_URL` is correct in `.env` + - Test connection: `python -c "from src.db import check_database_health; import asyncio; print(asyncio.run(check_database_health()))"` + +3. **Start Development Server** + - Run: `python run_dev.py` + - Verify health: http://localhost:8000/health + - Check docs: http://localhost:8000/docs + +### Frontend Integration + +⏭️ **Required for Full System** +- Configure Better Auth in Next.js frontend +- Implement API client with JWT token attachment +- Build Todo UI components +- Connect frontend to backend API + +### Testing & Deployment + +⏭️ **Production Readiness** +- Write unit tests with pytest +- Add integration tests with httpx +- Implement rate limiting +- Set up monitoring and logging +- Configure production environment variables +- Deploy to hosting platform (Vercel, Railway, etc.) + +## Success Criteria + +✓ **All 6 endpoints implemented with JWT protection** +✓ **User isolation enforced at database query level** +✓ **CORS configured for Next.js frontend** +✓ **Error handling returns proper HTTP status codes** +✓ **Code follows architecture in specs/001-todo-api/plan.md** +✓ **Async/await patterns used throughout** +✓ **Database module integration complete** +✓ **Development server and test scripts provided** +✓ **Comprehensive documentation created** + +## Files Summary + +### Absolute Paths + +``` +E:\todoweb\backend\src\api\middleware\auth.py (201 lines) +E:\todoweb\backend\src\api\routes\todos.py (445 lines) +E:\todoweb\backend\src\api\main.py (237 lines) +E:\todoweb\backend\src\api\middleware\__init__.py (7 lines) +E:\todoweb\backend\src\api\routes\__init__.py (7 lines) +E:\todoweb\backend\src\api\__init__.py (10 lines) +E:\todoweb\backend\run_dev.py (62 lines) +E:\todoweb\backend\test_api.py (250 lines) +E:\todoweb\backend\.env (15 lines) +E:\todoweb\backend\README.md (260 lines) +``` + +### Total Implementation + +- **Production Code**: 883 lines (auth + routes + main) +- **Supporting Code**: 329 lines (scripts + docs) +- **Total**: 1,212 lines + +## Conclusion + +The FastAPI backend is **production-ready** and fully implements the Todo API specification with: +- Secure JWT authentication +- Strict user isolation +- Async database operations +- Comprehensive error handling +- CORS configuration for frontend +- Interactive API documentation +- Development and testing tools + +All constitutional requirements and specification contracts have been satisfied. The backend is ready for frontend integration and deployment. diff --git a/Phase3-hack2 b/Phase3-hack2 new file mode 160000 index 0000000000000000000000000000000000000000..cbbc5738f49acc1cf9298fbbefbd55c9e6d82830 --- /dev/null +++ b/Phase3-hack2 @@ -0,0 +1 @@ +Subproject commit cbbc5738f49acc1cf9298fbbefbd55c9e6d82830 diff --git a/add_columns_migration.py b/add_columns_migration.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf840c823c590c88e10c77e67dcbbb2abcb6e74 --- /dev/null +++ b/add_columns_migration.py @@ -0,0 +1,40 @@ +""" +Migration script to add category and due_date columns to todos table. + +This script adds the missing columns that were added to the SQLModel +but don't exist in the database yet. +""" + +import asyncio +from sqlalchemy import text +from src.db.connection import get_engine + + +async def migrate(): + """Add category and due_date columns to todos table.""" + engine = get_engine() + + async with engine.begin() as conn: + print("Adding category column...") + try: + await conn.execute(text( + "ALTER TABLE todos ADD COLUMN IF NOT EXISTS category VARCHAR(50)" + )) + print("✓ Category column added") + except Exception as e: + print(f"Category column: {e}") + + print("Adding due_date column...") + try: + await conn.execute(text( + "ALTER TABLE todos ADD COLUMN IF NOT EXISTS due_date TIMESTAMP" + )) + print("✓ Due_date column added") + except Exception as e: + print(f"Due_date column: {e}") + + print("\nMigration complete!") + + +if __name__ == "__main__": + asyncio.run(migrate()) diff --git a/backend/Phase3-hack2/.gitattributes b/backend/Phase3-hack2/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a6344aac8c09253b3b630fb776ae94478aa0275b --- /dev/null +++ b/backend/Phase3-hack2/.gitattributes @@ -0,0 +1,35 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/backend/Phase3-hack2/README.md b/backend/Phase3-hack2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e7e6de4b4b3e2405837e0eeff7e91e1ab518d8ec --- /dev/null +++ b/backend/Phase3-hack2/README.md @@ -0,0 +1,10 @@ +--- +title: Phase3 Hack2 +emoji: 🏢 +colorFrom: purple +colorTo: pink +sdk: docker +pinned: false +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/delete_all_todos.py b/delete_all_todos.py new file mode 100644 index 0000000000000000000000000000000000000000..fad9cda131902e2ffbceb712a257943656abbdea --- /dev/null +++ b/delete_all_todos.py @@ -0,0 +1,23 @@ +""" +Script to delete all todos from the database. +Use this to clear the database for testing. +""" + +import asyncio +from sqlalchemy import text +from src.db.connection import get_engine + + +async def delete_all_todos(): + """Delete all todos from the database.""" + engine = get_engine() + + async with engine.begin() as conn: + print("Deleting all todos...") + result = await conn.execute(text("DELETE FROM todos")) + print(f"Deleted {result.rowcount} todos") + print("\nDatabase cleared successfully!") + + +if __name__ == "__main__": + asyncio.run(delete_all_todos()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..88ef290f4b36b209cc1043971f85b63a7bfb1c41 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,37 @@ +# FastAPI and ASGI server +fastapi>=0.115.0 +uvicorn[standard]>=0.27.0 + +# Database and ORM +sqlmodel>=0.0.14 +asyncpg>=0.29.0 +sqlalchemy[asyncio]>=2.0.25 +psycopg[binary]>=3.1.0 +psycopg-pool>=3.2.0 + +# Authentication and JWT +python-jose[cryptography]>=3.3.0 +passlib[bcrypt]>=1.7.4 + +# Configuration and environment +python-dotenv>=1.0.0 +pydantic-settings>=2.6.1 + +# Testing +pytest>=7.4.4 +pytest-asyncio>=0.23.3 +httpx>=0.28.1 + +# Code quality +ruff>=0.1.14 +black>=24.1.1 + +# AI and MCP (Phase III) +openai>=1.0.0 +fastmcp>=0.1.0 + +# CLI dependencies (included for completeness, not needed in container) +typer>=0.9.0 +rich>=13.0.0 +questionary>=2.0.0 +python-dateutil>=2.8.0 diff --git a/run_dev.py b/run_dev.py new file mode 100644 index 0000000000000000000000000000000000000000..e70f97b0f9b3d8a798a659bd4d396b4776e36ad4 --- /dev/null +++ b/run_dev.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +""" +Development Server Startup Script for Todo API + +This script starts the FastAPI development server with hot-reload enabled. + +Usage: + python run_dev.py + +Configuration: + - Reads from backend/.env file + - Default port: 8000 + - Default host: 0.0.0.0 (accessible from network) + +Requirements: + - BETTER_AUTH_SECRET must be set in .env + - DATABASE_URL must be set in .env +""" + +import os +import sys +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +# Verify required environment variables +required_vars = ["BETTER_AUTH_SECRET", "DATABASE_URL"] +missing_vars = [var for var in required_vars if not os.getenv(var)] + +if missing_vars: + print("ERROR: Missing required environment variables:") + for var in missing_vars: + print(f" - {var}") + print("\nPlease configure these variables in backend/.env") + sys.exit(1) + +# Get configuration from environment +API_HOST = os.getenv("API_HOST", "0.0.0.0") +LOG_LEVEL = os.getenv("LOG_LEVEL", "info").lower() + +print("=" * 60) +print("Starting Todo API Development Server") +print("=" * 60) +print(f"Host: {API_HOST}") +print(f"Log Level: {LOG_LEVEL}") +print(f"Reload: Enabled (development mode)") +print("=" * 60) +print(f"\nAPI Documentation: http://localhost:8000/docs") +print(f"Health Check: http://localhost:8000/health") +print("\nPress CTRL+C to stop the server") +print("=" * 60) + +# Start uvicorn server +if __name__ == "__main__": + import uvicorn + + uvicorn.run( + "src.api.main:app", + host=API_HOST, + reload=True, + log_level=LOG_LEVEL, + access_log=True + ) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..521670b4db9eb65bf8585e3bdef763ac10efa35d --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ +# src package diff --git a/src/api/__init__.py b/src/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8841891c1fde97fcc5b29625c5e6ef931489d6 --- /dev/null +++ b/src/api/__init__.py @@ -0,0 +1,10 @@ +""" +API Package Initialization + +This package contains the FastAPI application and all API-related components: +- main.py: FastAPI application entry point +- middleware/: Authentication and other middleware +- routes/: API endpoint handlers +""" + +__all__ = [] diff --git a/src/api/main.py b/src/api/main.py new file mode 100644 index 0000000000000000000000000000000000000000..a665e89551c38f8f0510c1587656805e2b645978 --- /dev/null +++ b/src/api/main.py @@ -0,0 +1,238 @@ +""" +FastAPI Application Entry Point for Todo API + +Owner: Backend API Engineer +Purpose: Main FastAPI application with CORS, authentication, and database lifecycle +Architecture: Async FastAPI with SQLModel, JWT auth, and Neon PostgreSQL + +Constitutional Constraints: +- REQUIRED: CORS configured for Next.js frontend (http://localhost:3000) +- REQUIRED: Database initialization on startup +- REQUIRED: Database cleanup on shutdown +- REQUIRED: Health check endpoint for monitoring +- REQUIRED: All routes protected with JWT authentication + +Application Lifecycle: +1. Startup: Initialize database connection and create tables +2. Runtime: Handle API requests with JWT authentication +3. Shutdown: Close database connections gracefully + +All endpoints enforce strict user isolation per constitution Principle IV. +""" + +import logging +from contextlib import asynccontextmanager +from fastapi import FastAPI, status +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse + +from src.db import init_database, cleanup_database, check_database_health +from src.api.routes import todos, chat + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("api.main") + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """ + Application lifespan manager for startup and shutdown events. + + Startup: + - Initialize database connection + - Create tables if they don't exist + - Verify database health + + Shutdown: + - Close database connections + - Release connection pool resources + + Args: + app: FastAPI application instance + + Yields: + None (context manager for lifespan) + """ + # Startup + logger.info("Starting Todo API application...") + try: + await init_database() + logger.info("✓ Database initialized successfully") + except Exception as e: + logger.error(f"Failed to initialize database: {e}") + raise + + yield + + # Shutdown + logger.info("Shutting down Todo API application...") + try: + await cleanup_database() + logger.info("✓ Database connections closed") + except Exception as e: + logger.error(f"Error during shutdown: {e}") + + +# Create FastAPI application +app = FastAPI( + title="Todo API", + description="Secure Todo API with JWT authentication and user isolation", + version="1.0.0", + lifespan=lifespan, + docs_url="/docs", + redoc_url="/redoc", + openapi_url="/openapi.json" +) + + +# Configure CORS - Allow all origins +# NOTE: allow_credentials=False when using wildcard origin +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Allow all origins + allow_credentials=False, # Required to be False when using "*" + allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + allow_headers=[ + "Authorization", # JWT Bearer token + "Content-Type", + "Accept", + "Origin", + "X-Requested-With" + ], + expose_headers=["Content-Length", "Content-Type"], + max_age=3600 # Cache preflight requests for 1 hour +) + + +# Include routers +app.include_router(todos.router) +app.include_router(chat.router) + +# Note: MCP tools are called directly from chat endpoint +# FastMCP server mounting removed - tools work without external MCP server + + +# Health check endpoint (no authentication required) +@app.get( + "/health", + status_code=status.HTTP_200_OK, + tags=["health"], + summary="Health check endpoint", + description="Check if the API and database are healthy. No authentication required.", + responses={ + 200: {"description": "Service is healthy"}, + 503: {"description": "Service is unhealthy"} + } +) +async def health_check(): + """ + Health check endpoint for monitoring and load balancers. + + Checks: + - API is running + - Database connection is healthy + + Returns: + dict: Health status with database connectivity + + Status Codes: + 200: Service is healthy + 503: Service is unhealthy (database connection failed) + """ + try: + # Check database connectivity + db_healthy = await check_database_health() + + if not db_healthy: + logger.error("Health check failed: Database connection unhealthy") + return JSONResponse( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + content={ + "status": "unhealthy", + "database": "disconnected", + "message": "Database connection failed" + } + ) + + return { + "status": "healthy", + "database": "connected", + "message": "Todo API is running" + } + + except Exception as e: + logger.error(f"Health check failed: {e}") + return JSONResponse( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + content={ + "status": "unhealthy", + "database": "error", + "message": str(e) + } + ) + + +# Root endpoint (no authentication required) +@app.get( + "/", + tags=["root"], + summary="API root endpoint", + description="Returns basic API information. No authentication required." +) +async def root(): + """ + Root endpoint with API information. + + Returns: + dict: API name, version, and documentation links + """ + return { + "name": "Todo API", + "version": "1.0.0", + "description": "Secure Todo API with JWT authentication and user isolation", + "documentation": "/docs", + "health": "/health" + } + + +# Global exception handler for unhandled errors +@app.exception_handler(Exception) +async def global_exception_handler(request, exc): + """ + Global exception handler for unhandled errors. + + Logs the error and returns a generic 500 response. + Prevents leaking sensitive information in error messages. + + Args: + request: FastAPI request object + exc: Exception that was raised + + Returns: + JSONResponse: Generic error response + """ + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + content={ + "detail": "Internal server error" + } + ) + + +if __name__ == "__main__": + import uvicorn + + # Run with uvicorn for development + # Production: Use gunicorn with uvicorn workers + uvicorn.run( + "backend.src.api.main:app", + host="0.0.0.0", + port=8000, + reload=True, # Auto-reload on code changes (development only) + log_level="info" + ) diff --git a/src/api/middleware/__init__.py b/src/api/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5960d0dbefcaf5830ff4f7331e3b46dd6089ab5b --- /dev/null +++ b/src/api/middleware/__init__.py @@ -0,0 +1,7 @@ +""" +Authentication Middleware Package + +This package contains JWT authentication middleware for the Todo API. +""" + +__all__ = [] diff --git a/src/api/middleware/auth.py b/src/api/middleware/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..50937410d9343f97c9201ab81916fe949626f228 --- /dev/null +++ b/src/api/middleware/auth.py @@ -0,0 +1,199 @@ +""" +JWT Authentication Middleware for Todo API + +Owner: Backend Security Engineer +Purpose: JWT token verification and user_id extraction +Architecture: FastAPI dependency injection with python-jose + +Constitutional Constraints: +- REQUIRED: Verify JWT signature using BETTER_AUTH_SECRET +- REQUIRED: Validate issuer="todoweb" and audience="todoweb-api" +- REQUIRED: Extract user_id from "sub" claim +- REQUIRED: Return 401 for invalid/expired/missing tokens +- REQUIRED: Use HTTPBearer security scheme + +Security Protocol: +1. Extract token from Authorization: Bearer header +2. Verify signature with shared BETTER_AUTH_SECRET +3. Validate token claims (exp, iss, aud) +4. Extract user_id from sub claim +5. Return user_id for use in route handlers + +All protected routes MUST use Depends(get_current_user_id) to enforce authentication. +""" + +import os +import logging +from typing import Annotated, Optional +from fastapi import HTTPException, Security, status +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from jose import jwt, JWTError +from jose.exceptions import ExpiredSignatureError, JWTClaimsError +from dotenv import load_dotenv + +# Configure logging +logger = logging.getLogger("api.auth") + +# Load environment variables +load_dotenv() + +# HTTPBearer security scheme for JWT tokens +security = HTTPBearer( + scheme_name="Bearer", + description="JWT token from Better Auth. Include in Authorization header as 'Bearer '", + auto_error=False +) + + +def get_better_auth_secret() -> str: + """ + Get BETTER_AUTH_SECRET from environment. + + Returns: + BETTER_AUTH_SECRET string + + Raises: + HTTPException(500): If BETTER_AUTH_SECRET is not configured + """ + secret = os.getenv("BETTER_AUTH_SECRET") + if not secret: + logger.error("BETTER_AUTH_SECRET environment variable not set") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Server configuration error: Authentication secret not configured" + ) + return secret + + +def verify_token(credentials: HTTPAuthorizationCredentials) -> dict: + """ + Verify JWT token and extract payload. + + Validates: + - Token signature using BETTER_AUTH_SECRET + - Token expiration (exp claim) + - Issuer claim (iss="todoweb") + - Audience claim (aud="todoweb-api") + + Args: + credentials: HTTPAuthorizationCredentials from HTTPBearer + + Returns: + dict: Decoded JWT payload containing user_id in "sub" claim + + Raises: + HTTPException(401): If token is invalid, expired, or has invalid claims + """ + token = credentials.credentials + secret = get_better_auth_secret() + + try: + # Decode and verify JWT token + payload = jwt.decode( + token, + secret, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + logger.debug(f"Token verified successfully for user: {payload.get('sub')}") + return payload + + except ExpiredSignatureError: + logger.warning("Token verification failed: Token has expired") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token has expired", + headers={"WWW-Authenticate": "Bearer"} + ) + except JWTClaimsError as e: + logger.warning(f"Token verification failed: Invalid token claims - {e}") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token claims (issuer or audience mismatch)", + headers={"WWW-Authenticate": "Bearer"} + ) + except JWTError as e: + logger.warning(f"Token verification failed: {e}") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication token", + headers={"WWW-Authenticate": "Bearer"} + ) + + +async def get_current_user_id( + credentials: Annotated[Optional[HTTPAuthorizationCredentials], Security(security)] = None +) -> str: + """ + FastAPI dependency to extract user_id from JWT token. + + This is the primary authentication dependency for all protected routes. + + Args: + credentials: Automatically extracted from Authorization header + + Returns: + str: User ID from JWT "sub" claim + + Raises: + HTTPException(401): If token is missing, invalid, or missing user_id + """ + if not credentials: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Authentication required", + headers={"WWW-Authenticate": "Bearer"} + ) + + # Verify token and extract payload + payload = verify_token(credentials) + + # Extract user_id from "sub" claim + user_id = payload.get("sub") + + if not user_id: + logger.error("Token verification succeeded but 'sub' claim is missing") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token: missing user ID", + headers={"WWW-Authenticate": "Bearer"} + ) + + return user_id + + +# Optional: Additional dependency for extracting full user info +async def get_current_user_info( + credentials: Annotated[HTTPAuthorizationCredentials, Security(security)] +) -> dict: + """ + FastAPI dependency to extract full user information from JWT token. + + Returns the complete JWT payload including: + - sub: User ID + - email: User email (if present) + - iat: Issued at timestamp + - exp: Expiration timestamp + + Usage: + @router.get("/api/profile") + async def get_profile( + user_info: Annotated[dict, Depends(get_current_user_info)] + ): + return { + "user_id": user_info["sub"], + "email": user_info.get("email") + } + + Args: + credentials: Automatically extracted from Authorization header + + Returns: + dict: Complete JWT payload + + Raises: + HTTPException(401): If token is invalid + """ + return verify_token(credentials) diff --git a/src/api/routes/__init__.py b/src/api/routes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..448083a152129636dbe625dab9bdc1c231d86c65 --- /dev/null +++ b/src/api/routes/__init__.py @@ -0,0 +1,10 @@ +""" +API Routes Package + +This package contains all API route handlers for the Todo API. +""" + +from . import todos +from . import chat + +__all__ = ["todos", "chat"] diff --git a/src/api/routes/chat.py b/src/api/routes/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..07fdb1e78bb9150f8f09e77302f670d8af1b4d57 --- /dev/null +++ b/src/api/routes/chat.py @@ -0,0 +1,442 @@ +# backend/src/api/routes/chat.py +""" +Chat API Routes for AI Chatbot + +Owner: Backend API Engineer +Purpose: RESTful endpoints for AI chat operations with user isolation +Architecture: FastAPI async routes with stateless memory management + +Constitutional Constraints: +- REQUIRED: All routes MUST use Depends(get_current_user_id) for authentication +- REQUIRED: All database queries MUST filter by user_id +- REQUIRED: Stateless processing - no local session storage (Principle VI) +- REQUIRED: All tool calls logged for audit trail (Principle VIII) +""" + +import json +import logging +from typing import Annotated +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from src.db import get_session +from src.db.connection import get_session_factory +from src.api.middleware.auth import get_current_user_id +from src.api.schemas.chat import ( + ChatRequest, + ChatResponse, + ToolCallSchema, + ConversationSchema, + ConversationWithMessagesSchema, + MessageSchema +) +from src.services.chat_service import ( + get_conversation_history, + save_chat_exchange, + create_conversation, + get_conversation_by_id, + get_user_conversations, + delete_conversation +) +from src.services.agent_service import get_agent_service +from src.mcp.tools.task_tools import add_task_impl, list_tasks_impl, complete_task_impl, update_task_impl, delete_task_impl +from src.models.message import Message + +# Configure logging +logger = logging.getLogger("api.chat") + +# Create router +router = APIRouter( + prefix="/api", + tags=["chat"], + responses={ + 401: {"description": "Authentication failed - invalid or missing JWT token"}, + 500: {"description": "Internal server error"} + } +) + + +async def execute_tool(tool_name: str, tool_args: str, user_id: str) -> str: + """ + Execute an MCP tool with user_id injection. + + Per Constitution Principle VII: Tools are the ONLY way AI accesses data. + The user_id is injected from JWT, never from AI arguments. + + Args: + tool_name: Name of the tool to execute + tool_args: JSON string of tool arguments + user_id: Authenticated user's ID from JWT + + Returns: + Tool result as string + """ + try: + args = json.loads(tool_args) + except json.JSONDecodeError: + args = {} + + logger.info(f"Executing tool {tool_name} for user {user_id}") + + # Validate task_id for tools that require it + tools_requiring_id = {"complete_task", "update_task", "delete_task"} + if tool_name in tools_requiring_id: + task_id = args.get("task_id", "") + if not task_id or not str(task_id).strip(): + return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs, then specify which task to modify." + + if tool_name == "add_task": + return await add_task_impl( + user_id=user_id, + title=args.get("title", ""), + description=args.get("description") + ) + elif tool_name == "list_tasks": + return await list_tasks_impl( + user_id=user_id, + status=args.get("status", "all") + ) + elif tool_name == "complete_task": + return await complete_task_impl( + user_id=user_id, + task_id=args.get("task_id", "") + ) + elif tool_name == "update_task": + return await update_task_impl( + user_id=user_id, + task_id=args.get("task_id", ""), + title=args.get("title"), + description=args.get("description") + ) + elif tool_name == "delete_task": + return await delete_task_impl( + user_id=user_id, + task_id=args.get("task_id", "") + ) + else: + return f"Error: Unknown tool '{tool_name}'" + + +@router.post( + "/{user_id}/chat", + response_model=ChatResponse, + summary="Send a chat message to the AI assistant", + description="Processes a user message through the AI agent, which may invoke MCP tools to manage tasks.", + responses={ + 200: {"description": "Successful response from AI"}, + 400: {"description": "Invalid request (empty message)"}, + 403: {"description": "User ID mismatch with JWT"}, + 404: {"description": "Conversation not found or unauthorized"} + } +) +async def chat( + user_id: str, + request: ChatRequest, + auth_user_id: Annotated[str, Depends(get_current_user_id)] +) -> ChatResponse: + """ + Stateless chat endpoint per stateless-memory-management skill. + + Flow: + 1. Validates user matches JWT + 2. Gets or creates conversation + 3. Fetches history from DB (stateless) + 4. Processes with AI agent + 5. Persists exchange to DB + 6. Returns response + + Args: + user_id: User ID from path (must match JWT) + request: Chat request with message and optional conversation_id + auth_user_id: User ID from JWT token + + Returns: + ChatResponse with conversation_id, response text, and tool calls + """ + # Verify user matches JWT (security check) + if user_id != auth_user_id: + logger.warning(f"User mismatch: path={user_id}, jwt={auth_user_id}") + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User ID mismatch with authentication token" + ) + + try: + session_factory = get_session_factory() + logger.info(f"Got session factory for user {user_id}") + + # Get or create conversation + conversation_id = request.conversation_id + + if conversation_id: + # Verify conversation exists and belongs to user + async with session_factory() as session: + conversation = await get_conversation_by_id( + conversation_id=conversation_id, + user_id=user_id, + session=session + ) + if not conversation: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Conversation not found" + ) + logger.info(f"Found existing conversation {conversation_id}") + else: + # Create new conversation + async with session_factory() as session: + conversation = await create_conversation( + user_id=user_id, + first_message=request.message, + session=session + ) + conversation_id = conversation.id + logger.info(f"Created new conversation {conversation_id}") + + # Step 1: Fetch history from DB (stateless - no local cache) + async with session_factory() as session: + history = await get_conversation_history( + conversation_id=conversation_id, + user_id=user_id, + session=session, + limit=10 + ) + logger.info(f"Fetched {len(history)} messages from history") + + # Step 2-3: Process with AI agent + logger.info("Getting agent service...") + agent = get_agent_service() + logger.info(f"Processing message with agent model: {agent.model}") + result = await agent.process_message( + user_message=request.message, + conversation_history=history, + user_id=user_id, + tool_executor=execute_tool + ) + logger.info(f"Agent returned response with {len(result.get('tool_calls') or [])} tool calls") + + # Step 4: Persist to DB (stateless - no local storage) + async with session_factory() as session: + await save_chat_exchange( + conversation_id=conversation_id, + user_id=user_id, + user_message=request.message, + assistant_response=result["response"], + tool_calls=result["tool_calls"], + session=session + ) + + # Format tool calls for response + tool_calls_response = None + if result["tool_calls"]: + tool_calls_response = [ + ToolCallSchema( + tool=tc["tool"], + arguments=tc["arguments"], + result=tc["result"] + ) + for tc in result["tool_calls"] + ] + + logger.info(f"Chat processed for user {user_id}, conversation {conversation_id}") + + return ChatResponse( + conversation_id=conversation_id, + response=result["response"], + tool_calls=tool_calls_response + ) + + except HTTPException: + raise + except Exception as e: + import traceback + logger.error(f"Chat processing error for user {user_id}: {e}") + logger.error(f"Traceback: {traceback.format_exc()}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to process chat message" + ) + + +@router.get( + "/{user_id}/conversations", + response_model=list[ConversationSchema], + summary="List user's conversations", + description="Returns all conversations for the authenticated user, sorted by most recent first.", + responses={ + 200: {"description": "List of conversations"}, + 403: {"description": "User ID mismatch with JWT"} + } +) +async def list_conversations( + user_id: str, + auth_user_id: Annotated[str, Depends(get_current_user_id)] +) -> list[ConversationSchema]: + """ + List all conversations for the authenticated user. + + Args: + user_id: User ID from path (must match JWT) + auth_user_id: User ID from JWT token + + Returns: + List of ConversationSchema objects + """ + if user_id != auth_user_id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User ID mismatch with authentication token" + ) + + try: + session_factory = get_session_factory() + async with session_factory() as session: + conversations = await get_user_conversations( + user_id=user_id, + session=session + ) + return [ConversationSchema.model_validate(c) for c in conversations] + + except Exception as e: + logger.error(f"Failed to list conversations for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to retrieve conversations" + ) + + +@router.get( + "/{user_id}/conversations/{conversation_id}", + response_model=ConversationWithMessagesSchema, + summary="Get conversation with messages", + description="Returns a conversation and its full message history.", + responses={ + 200: {"description": "Conversation with messages"}, + 403: {"description": "User ID mismatch with JWT"}, + 404: {"description": "Conversation not found or unauthorized"} + } +) +async def get_conversation( + user_id: str, + conversation_id: int, + auth_user_id: Annotated[str, Depends(get_current_user_id)] +) -> ConversationWithMessagesSchema: + """ + Get a conversation with its full message history. + + Args: + user_id: User ID from path (must match JWT) + conversation_id: Conversation ID + auth_user_id: User ID from JWT token + + Returns: + ConversationWithMessagesSchema with messages + """ + if user_id != auth_user_id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User ID mismatch with authentication token" + ) + + try: + session_factory = get_session_factory() + async with session_factory() as session: + conversation = await get_conversation_by_id( + conversation_id=conversation_id, + user_id=user_id, + session=session + ) + + if not conversation: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Conversation not found" + ) + + # Get all messages + statement = ( + select(Message) + .where( + Message.conversation_id == conversation_id, + Message.user_id == user_id + ) + .order_by(Message.created_at.asc()) + ) + result = await session.execute(statement) + messages = result.scalars().all() + + return ConversationWithMessagesSchema( + id=conversation.id, + title=conversation.title, + created_at=conversation.created_at, + updated_at=conversation.updated_at, + messages=[MessageSchema.model_validate(m) for m in messages] + ) + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get conversation {conversation_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to retrieve conversation" + ) + + +@router.delete( + "/{user_id}/conversations/{conversation_id}", + status_code=status.HTTP_204_NO_CONTENT, + summary="Delete a conversation", + description="Deletes a conversation and all its messages.", + responses={ + 204: {"description": "Conversation deleted successfully"}, + 403: {"description": "User ID mismatch with JWT"}, + 404: {"description": "Conversation not found or unauthorized"} + } +) +async def delete_conversation_endpoint( + user_id: str, + conversation_id: int, + auth_user_id: Annotated[str, Depends(get_current_user_id)] +): + """ + Delete a conversation and all its messages. + + Args: + user_id: User ID from path (must match JWT) + conversation_id: Conversation ID to delete + auth_user_id: User ID from JWT token + + Returns: + 204 No Content on success + """ + if user_id != auth_user_id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="User ID mismatch with authentication token" + ) + + try: + session_factory = get_session_factory() + async with session_factory() as session: + deleted = await delete_conversation( + conversation_id=conversation_id, + user_id=user_id, + session=session + ) + + if not deleted: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Conversation not found" + ) + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to delete conversation {conversation_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to delete conversation" + ) diff --git a/src/api/routes/todos.py b/src/api/routes/todos.py new file mode 100644 index 0000000000000000000000000000000000000000..5df3c6a676e3eff4b04a1f0a15d6b6776b998851 --- /dev/null +++ b/src/api/routes/todos.py @@ -0,0 +1,465 @@ +""" +Todo API Routes for FastAPI + +Owner: Backend API Engineer +Purpose: RESTful endpoints for todo CRUD operations with user isolation +Architecture: FastAPI async routes with SQLModel and JWT authentication + +Constitutional Constraints: +- REQUIRED: All routes MUST use Depends(get_current_user_id) for authentication +- REQUIRED: All database queries MUST filter by user_id +- REQUIRED: Return 404 (not 403) when todo doesn't belong to user (prevent info leakage) +- REQUIRED: Async/await for all database operations +- REQUIRED: Proper HTTP status codes (201 for create, 204 for delete, etc.) + +Security Protocol: +1. Extract user_id from JWT via get_current_user_id dependency +2. Filter all queries by user_id (never trust client input) +3. Return 404 if todo not found OR doesn't belong to user +4. Never expose existence of other users' todos + +All endpoints enforce strict user isolation per constitution Principle IV. +""" + +import logging +from typing import Annotated, List +from uuid import UUID +from datetime import datetime +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from sqlmodel import col + +from src.db import ( + get_session, + Todo, + TodoCreate, + TodoUpdate, + TodoResponse +) +from src.api.middleware.auth import get_current_user_id + +# Configure logging +logger = logging.getLogger("api.todos") + +# Create router with prefix and tags +router = APIRouter( + prefix="/api/todos", + tags=["todos"], + responses={ + 401: {"description": "Authentication failed - invalid or missing JWT token"}, + 500: {"description": "Internal server error"} + } +) + + +@router.post( + "", + response_model=TodoResponse, + status_code=status.HTTP_201_CREATED, + summary="Create a new todo", + description="Creates a new todo item for the authenticated user. The user_id is automatically extracted from the JWT token.", + responses={ + 201: {"description": "Todo created successfully"}, + 400: {"description": "Invalid request format"}, + 422: {"description": "Validation error"} + } +) +async def create_todo( + todo_data: TodoCreate, + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> TodoResponse: + """ + Create a new todo for the authenticated user. + + Security: + - user_id is extracted from JWT (never from request body) + - Todo is automatically associated with authenticated user + + Args: + todo_data: Todo creation data (title, description, is_completed) + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + TodoResponse: Created todo with all fields including id and timestamps + """ + try: + # Debug: Log incoming request data + logger.info(f"Creating todo with data: title={todo_data.title}, category={todo_data.category}, due_date={todo_data.due_date}") + + # Convert timezone-aware datetime to timezone-naive for PostgreSQL compatibility + due_date_naive = None + if todo_data.due_date: + if todo_data.due_date.tzinfo is not None: + # Remove timezone info to match created_at/updated_at + due_date_naive = todo_data.due_date.replace(tzinfo=None) + else: + due_date_naive = todo_data.due_date + + # Create new todo with user_id from JWT + new_todo = Todo( + user_id=user_id, + title=todo_data.title, + description=todo_data.description, + category=todo_data.category, + due_date=due_date_naive, + is_completed=todo_data.is_completed, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow() + ) + + session.add(new_todo) + await session.commit() + await session.refresh(new_todo) + + logger.info(f"Todo created: {new_todo.id} (category={new_todo.category}) for user: {user_id}") + return TodoResponse.model_validate(new_todo) + + except Exception as e: + await session.rollback() + logger.error(f"Failed to create todo for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to create todo" + ) + + +@router.get( + "", + response_model=List[TodoResponse], + summary="List all todos for authenticated user", + description="Retrieves all todo items belonging to the authenticated user, ordered by creation date (newest first)", + responses={ + 200: {"description": "Successfully retrieved todo list"} + } +) +async def list_todos( + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> List[TodoResponse]: + """ + List all todos for the authenticated user. + + Security: + - Only returns todos where user_id matches JWT sub claim + - Other users' todos are never visible + + Args: + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + List[TodoResponse]: List of todos ordered by created_at (newest first) + """ + try: + # Query todos filtered by user_id (CRITICAL: user isolation) + statement = ( + select(Todo) + .where(col(Todo.user_id) == user_id) + .order_by(Todo.created_at.desc()) + ) + + result = await session.execute(statement) + todos = result.scalars().all() + + logger.debug(f"Retrieved {len(todos)} todos for user: {user_id}") + return [TodoResponse.model_validate(todo) for todo in todos] + + except Exception as e: + logger.error(f"Failed to list todos for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to retrieve todos" + ) + + +@router.get( + "/{todo_id}", + response_model=TodoResponse, + summary="Get a specific todo", + description="Retrieves a single todo by ID. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.", + responses={ + 200: {"description": "Successfully retrieved todo"}, + 404: {"description": "Todo not found or doesn't belong to user"} + } +) +async def get_todo( + todo_id: UUID, + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> TodoResponse: + """ + Get a specific todo by ID. + + Security: + - Returns 404 if todo doesn't exist OR doesn't belong to user + - Never reveals whether todo exists for another user (prevents info leakage) + + Args: + todo_id: UUID of the todo to retrieve + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + TodoResponse: Todo with all fields + + Raises: + HTTPException(404): If todo not found or doesn't belong to user + """ + try: + # Query todo with BOTH id and user_id filters (CRITICAL: user isolation) + statement = select(Todo).where( + col(Todo.id) == todo_id, + col(Todo.user_id) == user_id + ) + + result = await session.execute(statement) + todo = result.scalar_one_or_none() + + if not todo: + # Return 404 regardless of whether todo exists for another user + # This prevents information leakage about other users' todos + logger.warning(f"Todo not found or access denied: {todo_id} for user: {user_id}") + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Todo not found" + ) + + logger.debug(f"Retrieved todo: {todo_id} for user: {user_id}") + return TodoResponse.model_validate(todo) + + except HTTPException: + raise + except Exception as e: + logger.error(f"Failed to get todo {todo_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to retrieve todo" + ) + + +@router.put( + "/{todo_id}", + response_model=TodoResponse, + summary="Update a todo", + description="Updates an existing todo. Only provided fields are updated. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.", + responses={ + 200: {"description": "Todo updated successfully"}, + 404: {"description": "Todo not found or doesn't belong to user"}, + 422: {"description": "Validation error"} + } +) +async def update_todo( + todo_id: UUID, + todo_data: TodoUpdate, + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> TodoResponse: + """ + Update an existing todo. + + Security: + - Only updates todo if it belongs to authenticated user + - Returns 404 if todo doesn't exist or doesn't belong to user + - user_id cannot be changed (enforced by not accepting it in request) + + Args: + todo_id: UUID of the todo to update + todo_data: Fields to update (all optional) + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + TodoResponse: Updated todo with all fields + + Raises: + HTTPException(404): If todo not found or doesn't belong to user + """ + try: + # Query todo with BOTH id and user_id filters (CRITICAL: user isolation) + statement = select(Todo).where( + col(Todo.id) == todo_id, + col(Todo.user_id) == user_id + ) + + result = await session.execute(statement) + todo = result.scalar_one_or_none() + + if not todo: + logger.warning(f"Todo not found or access denied for update: {todo_id} for user: {user_id}") + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Todo not found" + ) + + # Update only provided fields (partial update) + update_data = todo_data.model_dump(exclude_unset=True) + + # Convert timezone-aware datetime to timezone-naive for PostgreSQL compatibility + if 'due_date' in update_data and update_data['due_date'] is not None: + if update_data['due_date'].tzinfo is not None: + # Remove timezone info to match created_at/updated_at + update_data['due_date'] = update_data['due_date'].replace(tzinfo=None) + + for field, value in update_data.items(): + setattr(todo, field, value) + + # Update timestamp + todo.updated_at = datetime.utcnow() + + session.add(todo) + await session.commit() + await session.refresh(todo) + + logger.info(f"Todo updated: {todo_id} for user: {user_id}") + return TodoResponse.model_validate(todo) + + except HTTPException: + raise + except Exception as e: + await session.rollback() + logger.error(f"Failed to update todo {todo_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to update todo" + ) + + +@router.delete( + "/{todo_id}", + status_code=status.HTTP_204_NO_CONTENT, + summary="Delete a todo", + description="Permanently deletes a todo. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.", + responses={ + 204: {"description": "Todo deleted successfully (no content)"}, + 404: {"description": "Todo not found or doesn't belong to user"} + } +) +async def delete_todo( + todo_id: UUID, + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> None: + """ + Delete a todo permanently. + + Security: + - Only deletes todo if it belongs to authenticated user + - Returns 404 if todo doesn't exist or doesn't belong to user + + Args: + todo_id: UUID of the todo to delete + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + None (204 No Content) + + Raises: + HTTPException(404): If todo not found or doesn't belong to user + """ + try: + # Query todo with BOTH id and user_id filters (CRITICAL: user isolation) + statement = select(Todo).where( + col(Todo.id) == todo_id, + col(Todo.user_id) == user_id + ) + + result = await session.execute(statement) + todo = result.scalar_one_or_none() + + if not todo: + logger.warning(f"Todo not found or access denied for deletion: {todo_id} for user: {user_id}") + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Todo not found" + ) + + await session.delete(todo) + await session.commit() + + logger.info(f"Todo deleted: {todo_id} for user: {user_id}") + + except HTTPException: + raise + except Exception as e: + await session.rollback() + logger.error(f"Failed to delete todo {todo_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to delete todo" + ) + + +@router.patch( + "/{todo_id}/complete", + response_model=TodoResponse, + summary="Toggle todo completion status", + description="Toggles the completion status of a todo (complete ↔ incomplete). Returns 404 if todo doesn't exist or doesn't belong to authenticated user.", + responses={ + 200: {"description": "Todo completion status toggled successfully"}, + 404: {"description": "Todo not found or doesn't belong to user"} + } +) +async def toggle_todo_completion( + todo_id: UUID, + user_id: Annotated[str, Depends(get_current_user_id)], + session: Annotated[AsyncSession, Depends(get_session)] +) -> TodoResponse: + """ + Toggle the completion status of a todo. + + Security: + - Only toggles todo if it belongs to authenticated user + - Returns 404 if todo doesn't exist or doesn't belong to user + + Args: + todo_id: UUID of the todo to toggle + user_id: Automatically extracted from JWT token + session: Database session + + Returns: + TodoResponse: Updated todo with toggled completion status + + Raises: + HTTPException(404): If todo not found or doesn't belong to user + """ + try: + # Query todo with BOTH id and user_id filters (CRITICAL: user isolation) + statement = select(Todo).where( + col(Todo.id) == todo_id, + col(Todo.user_id) == user_id + ) + + result = await session.execute(statement) + todo = result.scalar_one_or_none() + + if not todo: + logger.warning(f"Todo not found or access denied for toggle: {todo_id} for user: {user_id}") + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Todo not found" + ) + + # Toggle completion status + todo.is_completed = not todo.is_completed + todo.updated_at = datetime.utcnow() + + session.add(todo) + await session.commit() + await session.refresh(todo) + + logger.info(f"Todo completion toggled: {todo_id} (now {todo.is_completed}) for user: {user_id}") + return TodoResponse.model_validate(todo) + + except HTTPException: + raise + except Exception as e: + await session.rollback() + logger.error(f"Failed to toggle todo {todo_id} for user {user_id}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to toggle todo completion" + ) diff --git a/src/api/schemas/__init__.py b/src/api/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcc9b439bf524ef7d4d63dc2827f12cc0ff2301 --- /dev/null +++ b/src/api/schemas/__init__.py @@ -0,0 +1,12 @@ +# backend/src/api/schemas/__init__.py +"""API schemas package.""" + +from .chat import ChatRequest, ChatResponse, ToolCallSchema, ConversationSchema, MessageSchema + +__all__ = [ + "ChatRequest", + "ChatResponse", + "ToolCallSchema", + "ConversationSchema", + "MessageSchema" +] diff --git a/src/api/schemas/chat.py b/src/api/schemas/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..72bcd4b9c06709c9ef903b5734e292024f4c8181 --- /dev/null +++ b/src/api/schemas/chat.py @@ -0,0 +1,103 @@ +# backend/src/api/schemas/chat.py +""" +Chat API Schemas + +Owner: Backend API Engineer +Purpose: Pydantic models for chat API request/response validation +Architecture: Per contracts/chat-api.yaml specification +""" + +from pydantic import BaseModel, Field +from typing import Optional, Any +from datetime import datetime + + +class ChatRequest(BaseModel): + """Request model for POST /api/{user_id}/chat""" + message: str = Field( + ..., + min_length=1, + max_length=4000, + description="The user's message to the AI assistant" + ) + conversation_id: Optional[int] = Field( + default=None, + description="Optional conversation ID to continue. If omitted, creates new conversation." + ) + + class Config: + json_schema_extra = { + "example": { + "message": "Add a task to buy groceries", + "conversation_id": None + } + } + + +class ToolCallSchema(BaseModel): + """Schema for tool call information in responses""" + tool: str = Field(..., description="Name of the MCP tool called") + arguments: str = Field(..., description="JSON string of arguments passed to the tool") + result: str = Field(..., description="Result returned by the tool") + + class Config: + json_schema_extra = { + "example": { + "tool": "add_task", + "arguments": '{"title": "Buy groceries"}', + "result": "Task 'Buy groceries' added with ID 15." + } + } + + +class ChatResponse(BaseModel): + """Response model for POST /api/{user_id}/chat""" + conversation_id: int = Field(..., description="The conversation ID (new or existing)") + response: str = Field(..., description="The AI assistant's response text") + tool_calls: Optional[list[ToolCallSchema]] = Field( + default=None, + description="List of tool calls made by the AI" + ) + + class Config: + json_schema_extra = { + "example": { + "conversation_id": 42, + "response": "I've added 'Buy groceries' to your task list.", + "tool_calls": [ + { + "tool": "add_task", + "arguments": '{"title": "Buy groceries"}', + "result": "Task 'Buy groceries' added with ID 15." + } + ] + } + } + + +class MessageSchema(BaseModel): + """Schema for message in conversation history""" + id: int + role: str = Field(..., description="Message role: 'user' or 'assistant'") + content: str + tool_calls: Optional[list[ToolCallSchema]] = None + created_at: datetime + + class Config: + from_attributes = True + + +class ConversationSchema(BaseModel): + """Schema for conversation metadata""" + id: int + title: str + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class ConversationWithMessagesSchema(ConversationSchema): + """Schema for conversation with full message history""" + messages: list[MessageSchema] = [] diff --git a/src/cli.py b/src/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a835465fefd725ebed77aeb402e40fc26a52063d --- /dev/null +++ b/src/cli.py @@ -0,0 +1,502 @@ +""" +CLI Layer for Interactive Todo Application (v2.0.0) + +Owner: Menu/UX Agent +Purpose: Interactive terminal interface using Typer and Rich +Architecture: Command-driven CLI with async service orchestration + +Constitutional Constraints: +- ALLOWED: Rich UI output, Typer commands, User input collection, Service layer orchestration +- FORBIDDEN: SQL queries, Direct database access, Business logic validation (delegates to services) +""" + +import asyncio +import typer +import questionary +from rich.console import Console +from rich.table import Table +from rich.panel import Panel +from rich.progress import Progress, SpinnerColumn, TextColumn +from rich import print as rprint +from datetime import datetime +from typing import Optional, List, Any +from enum import Enum + +from src.models import Priority, TaskStatus, TaskCreate, TaskUpdate, RecurrenceInterval +from src import services + +# Initialize Typer app and Rich console +app = typer.Typer(help="Interactive Todo Application CLI") +console = Console() + +class SortOption(str, Enum): + DATE = "date" + ALPHA = "alpha" + PRIORITY = "priority" + +def get_priority_color(priority: Any) -> str: + """Return color associated with priority level.""" + # Handle both Enum and raw string + val = priority.value if hasattr(priority, 'value') else str(priority) + colors = { + "high": "red", + "medium": "yellow", + "low": "green" + } + return colors.get(val.lower(), "white") + +def display_error(message: str): + """Display error message in a Rich panel.""" + console.print(Panel(f"[bold red]Error:[/bold red] {message}", border_style="red")) + +def display_success(message: str): + """Display success message.""" + console.print(f"[bold green]✓[/bold green] {message}") + +async def run_with_progress(coro, description: str): + """Run an async coroutine with a Rich progress spinner.""" + with Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + transient=True, + ) as progress: + progress.add_task(description=description, total=None) + return await coro + +async def interactive_date_picker(prompt: str) -> Optional[datetime]: + """Helper to pick a date using natural language or interactive prompt.""" + date_str = await asyncio.to_thread(questionary.text(f"{prompt} (e.g. 'tomorrow', 'next mon at 3pm')").ask) + if not date_str: + return None + + parsed_date = services.parse_natural_date(date_str) + if not parsed_date: + console.print("[yellow]Could not parse date. Please use YYYY-MM-DD format or try again.[/yellow]") + # Fallback to manual entry + manual_str = await asyncio.to_thread(questionary.text("Due Date (YYYY-MM-DD HH:MM:SS)").ask) + if not manual_str: return None + try: + return datetime.fromisoformat(manual_str.replace(' ', 'T')) + except ValueError: + console.print("[red]Invalid date format.[/red]") + return None + return parsed_date + +@app.command() +def add( + title: Optional[str] = typer.Argument(None, help="The title of the task"), + description: Optional[str] = typer.Option(None, "--desc", "-d", help="Task description"), + priority: Priority = typer.Option(Priority.MEDIUM, "--priority", "-p", help="Task priority"), + category: Optional[str] = typer.Option(None, "--category", "-c", help="Task category"), + due: Optional[str] = typer.Option(None, "--due", help="Due date (natural language)"), + recurrence: RecurrenceInterval = typer.Option(RecurrenceInterval.NONE, "--recurrence", "-r", help="Recurrence interval"), + interactive: bool = typer.Option(False, "--interactive", "-i", help="Use interactive wizard"), +): + """Add a new task with optional metadata.""" + async def _add(): + nonlocal title, description, priority, category, due, recurrence + + if interactive or not title: + # Use questionary for interactive form + title = await asyncio.to_thread(questionary.text("Task title:", validate=lambda text: len(text) > 0).ask) + description = await asyncio.to_thread(questionary.text("Description (optional):").ask) + choice = await asyncio.to_thread(questionary.select( + "Priority:", + choices=["low", "medium", "high"], + default=priority.value if priority else "medium" + ).ask) + priority = Priority(choice) + category = await asyncio.to_thread(questionary.text("Category (optional):").ask) + + # Date picking + due_date = await interactive_date_picker("Due Date") + + # Recurrence + choice = await asyncio.to_thread(questionary.select( + "Recurrence:", + choices=["none", "daily", "weekly", "monthly"], + default=recurrence.value if recurrence else "none" + ).ask) + recurrence = RecurrenceInterval(choice) + else: + # Command line mode + due_date = services.parse_natural_date(due) if due else None + + task_data = TaskCreate( + title=title, + description=description, + priority=priority, + category=category, + due_date=due_date, + recurrence_interval=recurrence + ) + result = await run_with_progress(services.create_task(task_data), "Creating task...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + + asyncio.run(_add()) + +async def async_add(title: str = "", description: Optional[str] = None, priority: Priority = Priority.MEDIUM, + category: Optional[str] = None, due: Optional[str] = None, + recurrence: RecurrenceInterval = RecurrenceInterval.NONE, + interactive: bool = False): + """Async version of add for interactive mode.""" + if interactive or not title: + # Use questionary for interactive form + title = await asyncio.to_thread(questionary.text("Task title:", validate=lambda text: len(text) > 0).ask) + description = await asyncio.to_thread(questionary.text("Description (optional):").ask) + choice = await asyncio.to_thread(questionary.select( + "Priority:", + choices=["low", "medium", "high"], + default=priority.value if priority else "medium" + ).ask) + priority = Priority(choice) + category = await asyncio.to_thread(questionary.text("Category (optional):").ask) + + # Date picking + due_date = await interactive_date_picker("Due Date") + + # Recurrence + choice = await asyncio.to_thread(questionary.select( + "Recurrence:", + choices=["none", "daily", "weekly", "monthly"], + default=recurrence.value if recurrence else "none" + ).ask) + recurrence = RecurrenceInterval(choice) + else: + # Command line mode + due_date = services.parse_natural_date(due) if due else None + + task_data = TaskCreate( + title=title, + description=description, + priority=priority, + category=category, + due_date=due_date, + recurrence_interval=recurrence + ) + result = await run_with_progress(services.create_task(task_data), "Creating task...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + +async def async_list_tasks(status: Optional[TaskStatus] = None, category: Optional[str] = None, + priority: Optional[Priority] = None, sort: str = "date"): + """Async version of list_tasks for interactive mode.""" + sort_enum = SortOption(sort) if sort in ["date", "alpha", "priority"] else SortOption.DATE + + result = await run_with_progress( + services.get_tasks(status=status, category=category, priority=priority, sort_by=sort_enum.value), + "Fetching tasks..." + ) + + if not result["success"]: + display_error(result["message"]) + return + + tasks = result["data"] + if not tasks: + console.print("[yellow]No tasks found matching criteria.[/yellow]") + return + + table = Table(title="Todo Tasks", header_style="bold cyan") + table.add_column("ID", justify="right", style="cyan", no_wrap=True) + table.add_column("Status", justify="center") + table.add_column("Priority", justify="center") + table.add_column("Title", style="white") + table.add_column("Category", style="blue") + table.add_column("Due Date", style="green") + table.add_column("Recur", style="yellow") + + for task in tasks: + # Normalize status to icon + task_status = task.status.value if hasattr(task.status, 'value') else str(task.status) + status_icon = "[green]✓[/green]" if task_status == "completed" else "[yellow]○[/yellow]" + + # Normalize priority and recurrence + p_val = task.priority.value if hasattr(task.priority, 'value') else str(task.priority) + r_val = task.recurrence_interval.value if hasattr(task.recurrence_interval, 'value') else str(task.recurrence_interval) + + p_color = get_priority_color(p_val) + priority_str = f"[{p_color}]{p_val.upper()}[/{p_color}]" + due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-" + recur_str = r_val if r_val != "none" else "-" + + table.add_row( + str(task.id), + status_icon, + priority_str, + task.title, + task.category or "-", + due_str, + recur_str + ) + + console.print(table) + console.print(f"\n[italic]{result['message']}[/italic]") + +async def async_search(query: str): + """Async version of search for interactive mode.""" + result = await run_with_progress(services.search_tasks(query), f"Searching for '{query}'...") + + if not result["success"]: + display_error(result["message"]) + return + + tasks = result["data"] + if not tasks: + console.print(f"[yellow]No tasks found matching '{query}'.[/yellow]") + return + + table = Table(title=f"Search Results: {query}") + table.add_column("ID", justify="right", style="cyan") + table.add_column("Status", justify="center") + table.add_column("Title", style="magenta") + + for task in tasks: + status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○" + table.add_row(str(task.id), status_icon, task.title) + + console.print(table) + +async def async_update(task_id: int, title: Optional[str] = None, description: Optional[str] = None, + priority: Optional[Priority] = None, category: Optional[str] = None, + due: Optional[str] = None, status: Optional[TaskStatus] = None, + recurrence: Optional[RecurrenceInterval] = None, + interactive: bool = False): + """Async version of update for interactive mode.""" + if interactive: + # Fetch existing task first + res = await services.get_tasks() + existing = None + for t in res["data"]: + if t.id == task_id: + existing = t + break + + if existing: + title = await asyncio.to_thread(questionary.text("New title:", default=existing.title).ask) + choice = await asyncio.to_thread(questionary.select( + "New Priority:", + choices=["low", "medium", "high"], + default=existing.priority if existing.priority else "medium" + ).ask) + priority = Priority(choice) + due_date = await interactive_date_picker("New Due Date") + choice = await asyncio.to_thread(questionary.select( + "New Recurrence:", + choices=["none", "daily", "weekly", "monthly"], + default=existing.recurrence_interval if existing.recurrence_interval else "none" + ).ask) + recurrence = RecurrenceInterval(choice) + else: + display_error(f"Task {task_id} not found.") + return + else: + # Command line mode + due_date = services.parse_natural_date(due) if due else None + + # Handle completion status specifically for boolean transition + is_completed = None + if status: + is_completed = (status == TaskStatus.COMPLETED) + + update_data = TaskUpdate( + title=title, + description=description, + priority=priority, + category=category, + due_date=due_date, + is_completed=is_completed, + recurrence_interval=recurrence + ) + + result = await run_with_progress(services.update_task(task_id, update_data), f"Updating task {task_id}...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + +async def async_delete(task_id: int, force: bool = True): + """Async version of delete for interactive mode.""" + result = await run_with_progress(services.delete_task(task_id), f"Deleting task {task_id}...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + +async def async_complete(task_id: int): + """Async version of complete for interactive mode.""" + result = await run_with_progress(services.toggle_task_completion(task_id), f"Toggling status for task {task_id}...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + +async def async_history(root_task_id: int): + """Async version of history for interactive mode.""" + result = await run_with_progress(services.get_task_history(root_task_id), f"Fetching history for {root_task_id}...") + + if not result["success"]: + display_error(result["message"]) + return + + tasks = result["data"] + table = Table(title=f"Task History Series: {root_task_id}", header_style="bold cyan") + table.add_column("ID", justify="right") + table.add_column("Status") + table.add_column("Completed Date") + table.add_column("Due Date") + + for task in tasks: + status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○" + completed_str = task.updated_at.strftime("%Y-%m-%d %H:%M") if task.status == TaskStatus.COMPLETED else "-" + due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-" + table.add_row(str(task.id), status_icon, completed_str, due_str) + + console.print(table) + +@app.command(name="list") +def list_tasks( + status: Optional[TaskStatus] = typer.Option(None, "--status", help="Filter by status"), + category: Optional[str] = typer.Option(None, "--category", help="Filter by category"), + priority: Optional[Priority] = typer.Option(None, "--priority", help="Filter by priority"), + sort: SortOption = typer.Option(SortOption.DATE, "--sort", help="Sort order"), +): + """List tasks with optional filtering and sorting.""" + async def _list(): + await async_list_tasks(status=status, category=category, priority=priority, sort=sort.value) + + asyncio.run(_list()) + +@app.command() +def search( + query: str = typer.Argument(..., help="Search keyword"), +): + """Search for tasks by title or description.""" + async def _search(): + await async_search(query) + + asyncio.run(_search()) + +@app.command() +def update( + task_id: int = typer.Argument(..., help="ID of the task to update"), + title: Optional[str] = typer.Option(None, "--title", help="New title"), + description: Optional[str] = typer.Option(None, "--desc", help="New description"), + priority: Optional[Priority] = typer.Option(None, "--priority", help="New priority"), + category: Optional[str] = typer.Option(None, "--category", help="New category"), + due: Optional[str] = typer.Option(None, "--due", help="New due date (natural language)"), + status: Optional[TaskStatus] = typer.Option(None, "--status", help="New status"), + recurrence: Optional[RecurrenceInterval] = typer.Option(None, "--recurrence", help="New recurrence interval"), + interactive: bool = typer.Option(False, "--interactive", "-i", help="Use interactive wizard"), +): + """Update task metadata.""" + async def _update(): + nonlocal title, description, priority, category, due, status, recurrence + + if interactive: + # Fetch existing task first + res = await services.get_tasks() # Inefficient but simple for now + existing = None + for t in res["data"]: + if t.id == task_id: + existing = t + break + + if existing: + title = await asyncio.to_thread(questionary.text("New title:", default=existing.title).ask) + priority = Priority(await asyncio.to_thread(questionary.select("Priority:", choices=["low", "medium", "high"], default=existing.priority).ask)) + due_date = await interactive_date_picker("New Due Date") + recurrence = RecurrenceInterval(await asyncio.to_thread(questionary.select("Recurrence:", choices=["none", "daily", "weekly", "monthly"], default=existing.recurrence_interval).ask)) + else: + display_error(f"Task {task_id} not found.") + return + else: + due_date = services.parse_natural_date(due) if due else None + + # Convert status to bool for repository + is_completed = None + if status: + is_completed = (status == TaskStatus.COMPLETED) + + update_data = TaskUpdate( + title=title, + description=description, + priority=priority, + category=category, + due_date=due_date, + is_completed=is_completed, + recurrence_interval=recurrence + ) + + result = await run_with_progress(services.update_task(task_id, update_data), f"Updating task {task_id}...") + + if result["success"]: + display_success(result["message"]) + else: + display_error(result["message"]) + + asyncio.run(_update()) + +@app.command() +def delete( + task_id: int = typer.Argument(..., help="ID of the task to delete"), + force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation"), +): + """Delete a task.""" + async def _delete(): + await async_delete(task_id, force) + + asyncio.run(_delete()) + +@app.command() +def complete( + task_id: int = typer.Argument(..., help="ID of the task to toggle completion"), +): + """Toggle task completion status.""" + async def _toggle(): + await async_complete(task_id) + + asyncio.run(_toggle()) + +@app.command() +def history( + root_task_id: int = typer.Argument(..., help="ID of the original task"), +): + """View history of a recurring task series.""" + async def _history(): + result = await run_with_progress(services.get_task_history(root_task_id), f"Fetching history for {root_task_id}...") + + if not result["success"]: + display_error(result["message"]) + return + + tasks = result["data"] + table = Table(title=f"Task History Series: {root_task_id}", header_style="bold cyan") + table.add_column("ID", justify="right") + table.add_column("Status") + table.add_column("Completed Date") + table.add_column("Due Date") + + for task in tasks: + status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○" + completed_str = task.updated_at.strftime("%Y-%m-%d %H:%M") if task.status == TaskStatus.COMPLETED else "-" + due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-" + table.add_row(str(task.id), status_icon, completed_str, due_str) + + console.print(table) + + asyncio.run(_history()) + +if __name__ == "__main__": + app() + diff --git a/src/database.py b/src/database.py new file mode 100644 index 0000000000000000000000000000000000000000..d095258a94e24cdb25b03a09203afe2d8bde9718 --- /dev/null +++ b/src/database.py @@ -0,0 +1,248 @@ +""" +Database Layer for Interactive Todo Application (v2.0.0) + +Owner: Database Agent +Purpose: Neon PostgreSQL connection management and schema initialization +Architecture: 100% async/await with connection pooling and retry logic + +Constitutional Constraints: +- ALLOWED: Database connections, SQL queries, schema initialization, error handling +- FORBIDDEN: User input (input()), User output (print() for menus), Business logic, Service layer calls +- FORBIDDEN: CRUD functions (SELECT, INSERT, UPDATE, DELETE) - these belong in src/repository.py + +All operations use parameterized queries to prevent SQL injection. +All connections are managed via an asynchronous pool with retry logic for Neon cold starts. +""" + +import os +import asyncio +import logging +from typing import Optional +import psycopg +from psycopg_pool import AsyncConnectionPool +from dotenv import load_dotenv + +# Configure logging +logging.basicConfig( + filename=".app.log", + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("database") + +# Load environment variables +load_dotenv() + +class DatabaseManager: + """ + Manages asynchronous database connections and schema initialization. + + Includes retry logic for Neon cold starts and connection pooling. + """ + + _pool: Optional[AsyncConnectionPool] = None + _instance: Optional['DatabaseManager'] = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(DatabaseManager, cls).__new__(cls) + return cls._instance + + async def get_pool(self) -> AsyncConnectionPool: + """ + Initialize and return the connection pool. + + Returns: + AsyncConnectionPool instance + + Raises: + ConnectionError: If DATABASE_URL is missing or connection fails + """ + if self._pool is None: + database_url = os.getenv("DATABASE_URL") + if not database_url: + logger.error("DATABASE_URL environment variable is missing") + raise ConnectionError( + "DATABASE_URL environment variable is not set. " + "Please create a .env file with DATABASE_URL=" + ) + + try: + # Connection string optimization for Neon (e.g., adding keepalives) + # pool_size can be adjusted based on requirements + self._pool = AsyncConnectionPool( + conninfo=database_url, + open=True, + min_size=1, + max_size=10, + timeout=30.0, + name="todo_pool" + ) + logger.info("Database connection pool initialized") + except Exception as e: + logger.error(f"Failed to initialize database pool: {e}") + raise ConnectionError(f"Failed to initialize database pool: {e}") + + return self._pool + + async def close_pool(self) -> None: + """Close the connection pool and release resources.""" + if self._pool: + await self._pool.close() + self._pool = None + logger.info("Database connection pool closed") + + async def get_connection(self, max_retries: int = 5, initial_delay: float = 1.0): + """ + Obtain a connection from the pool with retry logic for cold starts. + + Args: + max_retries: Maximum number of attempts to connect + initial_delay: Initial delay between retries in seconds + + Returns: + An asynchronous connection context manager + + Raises: + ConnectionError: If connection cannot be established after retries + """ + pool = await self.get_pool() + + last_exception = None + delay = initial_delay + + for attempt in range(1, max_retries + 1): + try: + # pool.connection() is an async context manager + async with pool.connection() as conn: + # Validate the connection with a simple query + await conn.execute("SELECT 1") + # If we get here, the connection is healthy + # Unfortunately we can't return the connection from within the context manager + # without it being returned to the pool. + # Users of this method should use the context manager directly. + pass + + # If validation succeeded, return a context manager for the caller + return pool.connection() + + except (psycopg.OperationalError, Exception) as e: + last_exception = e + logger.warning(f"Database connection attempt {attempt} failed: {e}. Retrying in {delay}s...") + await asyncio.sleep(delay) + delay *= 2 # Exponential backoff + + logger.error(f"Failed to connect to database after {max_retries} attempts.") + raise ConnectionError(f"Could not connect to database: {last_exception}") + +async def init_db() -> None: + """ + Initialize the database schema for the Todo application. + + Includes task table creation with new columns (priority, category, due_date) + and indexes for optimization. + + Schema: + - id: SERIAL PRIMARY KEY + - title: TEXT NOT NULL + - description: TEXT + - priority: TEXT DEFAULT 'medium' (CHECK: low, medium, high) + - category: TEXT + - due_date: TIMESTAMP + - is_completed: BOOLEAN DEFAULT FALSE + - created_at: TIMESTAMP DEFAULT NOW() + - updated_at: TIMESTAMP DEFAULT NOW() + + Constitutional Compliance: + ✅ Async/await pattern + ✅ Parameterized queries + ✅ No business logic + ✅ No user interaction + """ + db = DatabaseManager() + + try: + pool = await db.get_pool() + + logger.info("Initializing database schema...") + + # Create the tasks table with modern schema requirements - without constraint initially to avoid conflicts + async with pool.connection() as conn: + async with conn.cursor() as cur: + await cur.execute(""" + CREATE TABLE IF NOT EXISTS tasks ( + id SERIAL PRIMARY KEY, + title TEXT NOT NULL, + description TEXT, + priority TEXT DEFAULT 'medium', + category TEXT, + due_date TIMESTAMP, + is_completed BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() + ); + """) + await conn.commit() + + # Migration: Ensure new columns exist for users upgrading from beginner version + async with pool.connection() as conn: + async with conn.cursor() as cur: + # Add recurrence_interval column (backward compatible) + await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS recurrence_interval TEXT DEFAULT 'none';") + await conn.commit() + + async with pool.connection() as conn: + async with conn.cursor() as cur: + # Add parent_task_id foreign key + await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS parent_task_id INT;") + await conn.commit() + + async with pool.connection() as conn: + async with conn.cursor() as cur: + # Add reminder_sent flag + await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS reminder_sent BOOLEAN DEFAULT FALSE;") + await conn.commit() + + # Add recurrence_interval check constraint (non-validating for existing data) + async with pool.connection() as conn: + async with conn.cursor() as cur: + # Drop existing constraint first to ensure it has correct values + await cur.execute("ALTER TABLE tasks DROP CONSTRAINT IF EXISTS recurrence_check;") + await cur.execute("ALTER TABLE tasks ADD CONSTRAINT recurrence_check CHECK (recurrence_interval IN ('daily', 'weekly', 'monthly', 'none')) NOT VALID;") + # Validate the constraint for existing rows + await cur.execute("ALTER TABLE tasks VALIDATE CONSTRAINT recurrence_check;") + await conn.commit() + + # Create indexes for performance optimization + async with pool.connection() as conn: + async with conn.cursor() as cur: + await cur.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_priority ON tasks(priority); + """) + await cur.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_due_date ON tasks(due_date); + """) + # NEW: Index for parent-child queries (task history) + await cur.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id); + """) + # NEW: Index for reminder check (fast query of pending, unnotified due tasks) + await cur.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_reminder + ON tasks(due_date) WHERE is_completed = FALSE AND reminder_sent = FALSE; + """) + # NEW: Index for recurrence filtering (find all recurring tasks) + await cur.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_recurrence + ON tasks(recurrence_interval) WHERE recurrence_interval != 'none'; + """) + await conn.commit() + + logger.info("Database schema initialized successfully") + + except Exception as e: + logger.error(f"Schema initialization failed: {e}") + raise + +# Singleton instance for easy access +db_manager = DatabaseManager() diff --git a/src/db.py.bak b/src/db.py.bak new file mode 100644 index 0000000000000000000000000000000000000000..e59b998358b57f40582320b41d0f84921969603d --- /dev/null +++ b/src/db.py.bak @@ -0,0 +1,474 @@ +""" +Database Layer for Interactive Todo Application + +Owner: Database Agent +Purpose: Neon PostgreSQL connection management and CRUD operations + +Constitutional Constraints: +- ALLOWED: Database connections, SQL queries, schema initialization, error handling +- FORBIDDEN: User input (input()), User output (print() for menus), Business logic, Service layer calls + +All functions use parameterized queries to prevent SQL injection. +All write operations include proper transaction management (commit/rollback). +""" + +import os +from typing import Optional +import psycopg2 +import psycopg2.extensions +import psycopg2.extras +from dotenv import load_dotenv + + +# Load environment variables from .env file +load_dotenv() + + +def get_connection() -> psycopg2.extensions.connection: + """ + Establish connection to Neon PostgreSQL using DATABASE_URL from environment. + + Returns: + Active database connection with autocommit disabled for transaction control + + Raises: + ConnectionError: If DATABASE_URL environment variable is missing + ConnectionError: If connection to database fails + + Implementation Notes: + - Loads DATABASE_URL from environment using python-dotenv + - Uses psycopg2.connect() with connection string + - Sets autocommit=False for explicit transaction control + - Connection supports context manager usage (with statement) + + Constitutional Compliance: + ✅ NO user interaction + ✅ NO business logic + ✅ Database-only concern + """ + database_url = os.getenv("DATABASE_URL") + + if not database_url: + raise ConnectionError( + "DATABASE_URL environment variable is not set. " + "Please create a .env file with DATABASE_URL=" + ) + + try: + # Establish connection with autocommit disabled for transaction control + conn = psycopg2.connect(database_url) + conn.autocommit = False + return conn + + except psycopg2.OperationalError as e: + raise ConnectionError(f"Failed to connect to database: {e}") + + except Exception as e: + raise ConnectionError(f"Unexpected error during database connection: {e}") + + +def initialize_schema(conn: psycopg2.extensions.connection) -> None: + """ + Create tasks table if it doesn't exist. + + Args: + conn: Active database connection + + Raises: + psycopg2.DatabaseError: If schema creation fails + + Implementation Notes: + - Executes CREATE TABLE IF NOT EXISTS (idempotent operation) + - Creates indexes for performance optimization + - Commits transaction on success + - Rolls back transaction on failure + - Table definition matches data-model.md specification + + Schema: + - id: SERIAL PRIMARY KEY (auto-increment) + - title: VARCHAR(200) NOT NULL + - description: TEXT (nullable) + - is_completed: BOOLEAN NOT NULL DEFAULT FALSE + - created_at: TIMESTAMP NOT NULL DEFAULT NOW() + - updated_at: TIMESTAMP NOT NULL DEFAULT NOW() + + Constitutional Compliance: + ✅ NO user interaction + ✅ NO business logic + ✅ Database-only concern + """ + cursor = conn.cursor() + + try: + # Create tasks table with all required fields + cursor.execute(""" + CREATE TABLE IF NOT EXISTS tasks ( + id SERIAL PRIMARY KEY, + title VARCHAR(200) NOT NULL, + description TEXT, + is_completed BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() + ); + """) + + # Create index on completion status for filtering (optional optimization) + cursor.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_completed + ON tasks(is_completed); + """) + + # Create index on created_at for sorting (optional optimization) + cursor.execute(""" + CREATE INDEX IF NOT EXISTS idx_tasks_created + ON tasks(created_at DESC); + """) + + # ALWAYS renumber all tasks to start from 1 on app startup + # This ensures IDs are sequential without gaps regardless of deletions + cursor.execute("SELECT COUNT(*) FROM tasks;") + count = cursor.fetchone()[0] + + if count > 0: + # Temporarily disable the primary key constraint to allow renumbering + # Create a temporary sequence for safe renumbering + cursor.execute(""" + -- Create temporary column for new IDs + ALTER TABLE tasks ADD COLUMN IF NOT EXISTS temp_id INTEGER; + + -- Assign new sequential IDs ordered by creation date + WITH numbered AS ( + SELECT id, ROW_NUMBER() OVER (ORDER BY created_at) as row_num + FROM tasks + ) + UPDATE tasks + SET temp_id = numbered.row_num + FROM numbered + WHERE tasks.id = numbered.id; + + -- Update the actual IDs + UPDATE tasks SET id = temp_id; + + -- Drop temporary column + ALTER TABLE tasks DROP COLUMN IF EXISTS temp_id; + + -- Get max ID and reset sequence + SELECT setval('tasks_id_seq', (SELECT MAX(id) FROM tasks)); + """) + else: + # Empty table - reset sequence to 1 + cursor.execute("SELECT setval('tasks_id_seq', 1, false);") + + conn.commit() + + except psycopg2.DatabaseError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Failed to initialize schema: {e}") + + finally: + cursor.close() + + +def create_task_db( + conn: psycopg2.extensions.connection, + title: str, + description: Optional[str] +) -> int: + """ + Insert new task into database. + + Args: + conn: Active database connection + title: Task title (assumed pre-validated by service layer) + description: Task description (optional, can be None) + + Returns: + ID of newly created task (SERIAL auto-generated) + + Raises: + psycopg2.DatabaseError: If insertion fails + + Implementation Notes: + - Uses parameterized query with %s placeholders + - NO validation performed (service layer responsibility) + - is_completed defaults to FALSE (database default) + - created_at and updated_at default to NOW() (database default) + - Returns auto-generated task ID using RETURNING clause + - Commits transaction on success + - Rolls back transaction on failure + + Constitutional Compliance: + ✅ NO validation (service layer responsibility) + ✅ NO user interaction + ✅ Parameterized queries (SQL injection prevention) + """ + cursor = conn.cursor() + + try: + # Parameterized INSERT query with RETURNING clause to get new ID + cursor.execute( + """ + INSERT INTO tasks (title, description) + VALUES (%s, %s) + RETURNING id; + """, + (title, description) + ) + + # Fetch the auto-generated task ID + task_id = cursor.fetchone()[0] + + conn.commit() + return task_id + + except psycopg2.IntegrityError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Data integrity error during task creation: {e}") + + except psycopg2.DatabaseError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Failed to create task: {e}") + + finally: + cursor.close() + + +def get_all_tasks_db(conn: psycopg2.extensions.connection) -> list[tuple]: + """ + Retrieve all tasks from database ordered by creation date (newest first). + + Args: + conn: Active database connection + + Returns: + List of tuples, each tuple contains: + (id, title, description, is_completed, created_at, updated_at) + + Returns empty list if no tasks exist + + Raises: + psycopg2.DatabaseError: If query fails + + Implementation Notes: + - Selects all 6 fields in consistent order + - Orders by created_at DESC (newest tasks first) + - Returns raw tuples (service layer converts to Task objects) + - No pagination (scope supports < 1000 tasks) + - Read-only operation (no commit needed) + + Constitutional Compliance: + ✅ NO business logic (no filtering, no transformation) + ✅ Returns raw data for service layer processing + """ + cursor = conn.cursor() + + try: + # Select all tasks ordered by creation date (newest first) + cursor.execute(""" + SELECT id, title, description, is_completed, created_at, updated_at + FROM tasks + ORDER BY created_at DESC; + """) + + # Fetch all results as list of tuples + tasks = cursor.fetchall() + return tasks + + except psycopg2.DatabaseError as e: + raise psycopg2.DatabaseError(f"Failed to retrieve tasks: {e}") + + finally: + cursor.close() + + +def update_task_db( + conn: psycopg2.extensions.connection, + task_id: int, + title: Optional[str], + description: Optional[str] +) -> bool: + """ + Update task title and/or description. + + Args: + conn: Active database connection + task_id: ID of task to update + title: New title (None = no change) + description: New description (None = no change) + + Returns: + True if task was updated (task existed) + False if task was not found + + Raises: + psycopg2.DatabaseError: If update fails + + Implementation Notes: + - Builds dynamic UPDATE query based on which fields are not None + - Always sets updated_at = NOW() + - Uses parameterized query for all values + - Checks cursor.rowcount to determine if task was found + - Commits transaction on success + - Rolls back transaction on failure + + Constitutional Compliance: + ✅ NO validation (service layer validates before calling) + ✅ Parameterized queries + ✅ NO business logic (no field value processing) + """ + cursor = conn.cursor() + + try: + # Build dynamic UPDATE query based on provided fields + update_fields = [] + params = [] + + # Build query safely without f-strings - construct from safe string operations + set_clause_parts = [] + + if title is not None: + set_clause_parts.append("title = %s") + params.append(title) + + if description is not None: + set_clause_parts.append("description = %s") + params.append(description) + + # Always update the updated_at timestamp + set_clause_parts.append("updated_at = NOW()") + + # Add task_id as final parameter for WHERE clause + params.append(task_id) + + # Construct query safely using string concatenation (no f-strings) + query = "UPDATE tasks SET " + ", ".join(set_clause_parts) + " WHERE id = %s;" + + cursor.execute(query, params) + + # Check if any rows were affected (task existed) + rows_affected = cursor.rowcount + + conn.commit() + return rows_affected > 0 + + except psycopg2.DatabaseError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Failed to update task: {e}") + + finally: + cursor.close() + + +def toggle_task_status_db( + conn: psycopg2.extensions.connection, + task_id: int +) -> bool: + """ + Toggle task completion status (complete <-> incomplete). + + Args: + conn: Active database connection + task_id: ID of task to toggle + + Returns: + True if task was toggled (task existed) + False if task was not found + + Raises: + psycopg2.DatabaseError: If toggle fails + + Implementation Notes: + - Uses NOT operator to flip boolean value + - Updates updated_at timestamp automatically + - Uses parameterized query + - Checks cursor.rowcount to determine if task was found + - Commits transaction on success + - Rolls back transaction on failure + + Constitutional Compliance: + ✅ Simple boolean toggle (no conditional logic) + ✅ Parameterized query + ✅ NO validation needed (toggle is idempotent) + """ + cursor = conn.cursor() + + try: + # Toggle is_completed and update timestamp + cursor.execute( + """ + UPDATE tasks + SET is_completed = NOT is_completed, updated_at = NOW() + WHERE id = %s; + """, + (task_id,) + ) + + # Check if any rows were affected (task existed) + rows_affected = cursor.rowcount + + conn.commit() + return rows_affected > 0 + + except psycopg2.DatabaseError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Failed to toggle task status: {e}") + + finally: + cursor.close() + + +def delete_task_db( + conn: psycopg2.extensions.connection, + task_id: int +) -> bool: + """ + Permanently delete task from database. + + Args: + conn: Active database connection + task_id: ID of task to delete + + Returns: + True if task was deleted (task existed) + False if task was not found + + Raises: + psycopg2.DatabaseError: If deletion fails + + Implementation Notes: + - Simple DELETE operation with WHERE clause + - Uses parameterized query + - Checks cursor.rowcount to determine if task was found + - Commits transaction on success + - Rolls back transaction on failure + - No CASCADE needed (no foreign keys in schema) + + Constitutional Compliance: + ✅ Simple DELETE operation + ✅ NO validation (service layer confirms intent) + ✅ Parameterized query + """ + cursor = conn.cursor() + + try: + # Delete task by ID + cursor.execute( + """ + DELETE FROM tasks + WHERE id = %s; + """, + (task_id,) + ) + + # Check if any rows were affected (task existed) + rows_affected = cursor.rowcount + + conn.commit() + return rows_affected > 0 + + except psycopg2.DatabaseError as e: + conn.rollback() + raise psycopg2.DatabaseError(f"Failed to delete task: {e}") + + finally: + cursor.close() diff --git a/src/db/README.md b/src/db/README.md new file mode 100644 index 0000000000000000000000000000000000000000..402b64a0ec3bee67bee8d0cebfe756751e623ef6 --- /dev/null +++ b/src/db/README.md @@ -0,0 +1,333 @@ +# Database Module - Todo API + +## Overview + +This module provides Neon Serverless PostgreSQL integration for the Todo API with multi-tenant isolation and Better Auth compatibility. + +## Architecture + +- **ORM**: SQLModel (Pydantic + SQLAlchemy) +- **Driver**: asyncpg (async PostgreSQL driver) +- **Database**: Neon Serverless PostgreSQL +- **Pattern**: Async/await throughout +- **Isolation**: Multi-tenant with user_id filtering + +## Key Features + +### 1. Serverless Optimization +- `pool_pre_ping=True`: Validates connections before use (handles cold starts) +- Small connection pool (5 connections): Optimized for serverless +- Connection recycling: Prevents stale connections +- Exponential backoff: Retry logic for connection failures + +### 2. Multi-Tenant Isolation +- Every table includes `user_id: str` column (REQUIRED) +- `user_id` is indexed for query performance +- All queries MUST filter by `user_id` +- User ID extracted from JWT sub claim (never from client input) + +### 3. Better Auth Compatibility +- No conflicts with Better Auth tables (user, session, account, verification) +- `user_id` references Better Auth's user table (managed externally) +- No foreign key constraints (Better Auth is source of truth) + +## Files + +``` +backend/src/db/ +├── __init__.py # Package exports and initialization +├── connection.py # Database connection and session management +├── models.py # SQLModel schemas (Todo, TodoCreate, TodoUpdate, TodoResponse) +├── verify.py # Verification script +└── README.md # This file +``` + +## Setup + +### 1. Environment Variables + +Add to your `.env` file: + +```bash +DATABASE_URL=postgresql://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb +``` + +**Note**: The connection string will be automatically converted to `postgresql+asyncpg://` for async operations. + +### 2. Install Dependencies + +```bash +pip install -r backend/requirements.txt +``` + +Required packages: +- `sqlmodel==0.0.14` +- `asyncpg==0.29.0` +- `sqlalchemy[asyncio]==2.0.25` + +### 3. Initialize Database + +```python +from backend.src.db import init_database + +# Call during application startup +await init_database() +``` + +### 4. Verify Setup + +```bash +python -m backend.src.db.verify +``` + +This will: +- Test database connectivity +- Create tables and indexes +- Verify schema matches SQLModel definitions +- Display detailed status of each check + +## Usage + +### In FastAPI Routes + +```python +from fastapi import Depends +from sqlalchemy.ext.asyncio import AsyncSession +from backend.src.db import get_session, Todo, TodoCreate + +@app.post("/api/todos") +async def create_todo( + todo_data: TodoCreate, + user_id: str, # Extracted from JWT middleware + session: AsyncSession = Depends(get_session) +): + # Create todo with user isolation + todo = Todo( + **todo_data.model_dump(), + user_id=user_id # REQUIRED for multi-tenant isolation + ) + session.add(todo) + await session.commit() + await session.refresh(todo) + return todo +``` + +### Query with User Isolation + +```python +from sqlmodel import select +from backend.src.db import Todo + +async def get_user_todos(user_id: str, session: AsyncSession): + # ALWAYS filter by user_id + statement = select(Todo).where(Todo.user_id == user_id) + result = await session.execute(statement) + return result.scalars().all() +``` + +### Application Lifecycle + +```python +from fastapi import FastAPI +from backend.src.db import init_database, cleanup_database + +app = FastAPI() + +@app.on_event("startup") +async def startup(): + await init_database() + +@app.on_event("shutdown") +async def shutdown(): + await cleanup_database() +``` + +## Database Schema + +### Todos Table + +```sql +CREATE TABLE todos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id VARCHAR(255) NOT NULL, + title VARCHAR(200) NOT NULL, + description TEXT, + is_completed BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +-- Indexes +CREATE INDEX ix_todos_user_id ON todos(user_id); +CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed); +``` + +### Field Specifications + +| Field | Type | Constraints | Description | +|-------|------|-------------|-------------| +| id | UUID | PRIMARY KEY | Unique identifier (auto-generated) | +| user_id | VARCHAR(255) | NOT NULL, INDEXED | Owner's user ID from JWT | +| title | VARCHAR(200) | NOT NULL, 1-200 chars | Todo title | +| description | TEXT | NULLABLE, max 2000 chars | Optional description | +| is_completed | BOOLEAN | NOT NULL, default FALSE | Completion status | +| created_at | TIMESTAMP | NOT NULL | Creation timestamp (UTC) | +| updated_at | TIMESTAMP | NOT NULL | Last modification timestamp (UTC) | + +## SQLModel Models + +### Todo (Database Model) +Full model with all fields including system-generated ones. + +### TodoCreate (Request Model) +For creating todos. Excludes id, user_id, and timestamps. + +### TodoUpdate (Request Model) +For updating todos. All fields optional (partial updates). + +### TodoResponse (Response Model) +For API responses. Includes all fields. + +## Security Considerations + +### Multi-Tenant Isolation (CRITICAL) + +1. **Every query MUST filter by user_id** + ```python + # ✓ CORRECT + select(Todo).where(Todo.user_id == user_id) + + # ✗ WRONG - Security vulnerability! + select(Todo) # Returns all users' todos + ``` + +2. **Never accept user_id from client input** + ```python + # ✓ CORRECT + user_id = extract_from_jwt(token) + + # ✗ WRONG - Security vulnerability! + user_id = request.body.get("user_id") + ``` + +3. **Use UUID primary keys** + - Prevents enumeration attacks + - UUIDs are globally unique and unpredictable + +### Input Validation + +SQLModel automatically validates: +- Field types (string, boolean, datetime) +- String lengths (min/max) +- Required vs optional fields +- Data format (UUID, datetime) + +## Performance Optimization + +### Connection Pooling +- Pool size: 5 (optimized for serverless) +- Max overflow: 10 (additional connections when needed) +- Pool recycling: 3600 seconds (1 hour) + +### Indexes +- `user_id`: Critical for all queries (every query filters by user_id) +- `(user_id, is_completed)`: Optimizes "show my incomplete todos" queries + +### Query Patterns +- Use async/await for non-blocking I/O +- Select only needed columns when possible +- Consider pagination for large result sets + +## Error Handling + +### Connection Errors +```python +try: + session = await get_session() +except ConnectionError as e: + # Handle connection failure + # Check DATABASE_URL is set + # Verify Neon database is accessible +``` + +### Query Errors +```python +try: + await session.execute(statement) + await session.commit() +except Exception as e: + await session.rollback() + # Handle query error +``` + +## Testing + +### Unit Tests +Test query functions with mock data: +```python +import pytest +from backend.src.db import Todo, TodoCreate + +@pytest.mark.asyncio +async def test_create_todo(session): + todo_data = TodoCreate(title="Test", description="Test todo") + todo = Todo(**todo_data.model_dump(), user_id="test_user") + session.add(todo) + await session.commit() + assert todo.id is not None +``` + +### Integration Tests +Test with real Neon database (test database): +```python +@pytest.mark.asyncio +async def test_user_isolation(session): + # Create todos for two different users + todo1 = Todo(title="User 1 Todo", user_id="user1") + todo2 = Todo(title="User 2 Todo", user_id="user2") + + # Verify user1 cannot see user2's todos + result = await session.execute( + select(Todo).where(Todo.user_id == "user1") + ) + todos = result.scalars().all() + assert len(todos) == 1 + assert todos[0].user_id == "user1" +``` + +## Troubleshooting + +### "DATABASE_URL environment variable not set" +- Ensure `.env` file exists in project root +- Verify `DATABASE_URL` is set with your Neon connection string +- Format: `postgresql://user:password@host.neon.tech/database` + +### "Failed to connect to database" +- Check Neon database is running +- Verify connection string is correct +- Check network connectivity +- Review Neon dashboard for database status + +### "Table does not exist" +- Run `await init_database()` during startup +- Or run verification script: `python -m backend.src.db.verify` + +### "Connection pool exhausted" +- Increase `pool_size` in `connection.py` (default: 5) +- Check for connection leaks (ensure sessions are closed) +- Review query performance (slow queries hold connections) + +## Next Steps + +1. ✓ Database module created +2. ⏭️ Create JWT middleware for user_id extraction +3. ⏭️ Implement FastAPI routes with user isolation +4. ⏭️ Add integration tests for multi-tenant scenarios +5. ⏭️ Configure Better Auth for user management + +## References + +- [SQLModel Documentation](https://sqlmodel.tiangolo.com/) +- [Neon PostgreSQL Documentation](https://neon.tech/docs) +- [FastAPI Database Guide](https://fastapi.tiangolo.com/tutorial/sql-databases/) +- [Better Auth Documentation](https://www.better-auth.com/) diff --git a/src/db/SETUP_COMPLETE.md b/src/db/SETUP_COMPLETE.md new file mode 100644 index 0000000000000000000000000000000000000000..738d8835a4819464385bdd7f6cec83ef8f4b321e --- /dev/null +++ b/src/db/SETUP_COMPLETE.md @@ -0,0 +1,338 @@ +# Database Setup Complete - Todo API + +## Summary + +The Neon PostgreSQL database module has been successfully initialized for the Todo API with full multi-tenant isolation and serverless optimization. + +## Created Files + +### Core Database Module +``` +backend/src/db/ +├── __init__.py # Package initialization and exports +├── connection.py # Neon-optimized connection management +├── models.py # SQLModel schemas with multi-tenant isolation +├── verify.py # Database verification script +└── README.md # Comprehensive documentation +``` + +### File Details + +#### 1. connection.py (Database Connection) +- **AsyncEngine** with asyncpg driver for Neon PostgreSQL +- **pool_pre_ping=True**: Critical for serverless cold start handling +- **Connection pooling**: Optimized for serverless (pool_size=5, max_overflow=10) +- **Retry logic**: Exponential backoff for connection failures +- **Session management**: FastAPI dependency injection support +- **Health checks**: Database connectivity monitoring + +#### 2. models.py (SQLModel Schemas) +- **Todo**: Database model with all fields + - `id`: UUID primary key (auto-generated) + - `user_id`: String, indexed, REQUIRED for multi-tenant isolation + - `title`: String (1-200 chars, required) + - `description`: String (optional, max 2000 chars) + - `is_completed`: Boolean (default: False) + - `created_at`: DateTime (UTC, auto-generated) + - `updated_at`: DateTime (UTC, auto-updated) + +- **TodoCreate**: Request model for creating todos +- **TodoUpdate**: Request model for updating todos (partial updates) +- **TodoResponse**: Response model with all fields + +#### 3. __init__.py (Package Initialization) +- Exports all database utilities and models +- `init_database()`: Creates tables and indexes +- `cleanup_database()`: Graceful shutdown +- `get_session()`: FastAPI dependency for database sessions + +#### 4. verify.py (Verification Script) +- Tests database connectivity +- Verifies table schema +- Checks indexes are created +- Provides detailed status output + +#### 5. README.md (Documentation) +- Complete usage guide +- Security considerations +- Performance optimization tips +- Troubleshooting guide + +## Constitutional Compliance + +### ✓ Multi-Tenant Isolation (Principle IV) +- All tables include `user_id: str` column (REQUIRED) +- `user_id` is indexed for query performance +- All queries MUST filter by `user_id` +- User ID extracted from JWT sub claim (never from client input) + +### ✓ SQLModel Exclusive +- All models use SQLModel (Pydantic + SQLAlchemy) +- No raw SQLAlchemy models +- Type-safe database interactions + +### ✓ Neon Serverless Optimization +- `pool_pre_ping=True` for cold start handling +- Small connection pool (5 connections) +- Connection recycling (3600 seconds) +- Async/await throughout + +### ✓ Better Auth Compatibility +- No conflicts with Better Auth tables +- `user_id` references Better Auth's user table +- No foreign key constraints (Better Auth manages users) + +## Database Schema + +```sql +CREATE TABLE todos ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id VARCHAR(255) NOT NULL, + title VARCHAR(200) NOT NULL, + description TEXT, + is_completed BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +-- Indexes for performance +CREATE INDEX ix_todos_user_id ON todos(user_id); +CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed); +``` + +## Next Steps + +### 1. Configure Environment Variables + +Edit `E:\todoweb\.env` and fill in your Neon database connection string: + +```bash +# Replace with your actual Neon connection string +DATABASE_URL=postgresql://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb +``` + +**How to get your Neon connection string:** +1. Go to [Neon Console](https://console.neon.tech/) +2. Select your project +3. Go to "Connection Details" +4. Copy the connection string (format: `postgresql://...`) + +### 2. Install Dependencies + +```bash +cd E:\todoweb\backend +pip install -r requirements.txt +``` + +Required packages (already in requirements.txt): +- sqlmodel==0.0.14 +- asyncpg==0.29.0 +- sqlalchemy[asyncio]==2.0.25 + +### 3. Verify Database Setup + +Run the verification script to test connectivity and create tables: + +```bash +cd E:\todoweb +python -m backend.src.db.verify +``` + +Expected output: +``` +============================================================ +Database Verification Script +============================================================ + +[1/5] Checking database connectivity... +✓ Database connection successful + +[2/5] Initializing database schema... +✓ Database schema initialized + +[3/5] Verifying todos table... +✓ Todos table exists + +[4/5] Verifying table schema... + ✓ Column 'id' (uuid) + ✓ Column 'user_id' (character varying) + ✓ Column 'title' (character varying) + ✓ Column 'description' (character varying) + ✓ Column 'is_completed' (boolean) + ✓ Column 'created_at' (timestamp without time zone) + ✓ Column 'updated_at' (timestamp without time zone) + +[5/5] Verifying indexes... + ✓ Index 'todos_pkey' exists + ✓ Index 'ix_todos_user_id' exists + ✓ Index 'idx_todos_user_completed' exists + +============================================================ +✓ All verification checks passed! +============================================================ + +Database is ready for use. +``` + +### 4. Integrate with FastAPI + +In your FastAPI application (e.g., `backend/src/api/main.py`): + +```python +from fastapi import FastAPI +from backend.src.db import init_database, cleanup_database + +app = FastAPI() + +@app.on_event("startup") +async def startup(): + """Initialize database on application startup""" + await init_database() + +@app.on_event("shutdown") +async def shutdown(): + """Cleanup database connections on shutdown""" + await cleanup_database() +``` + +### 5. Use in API Routes + +Example route with user isolation: + +```python +from fastapi import Depends, HTTPException +from sqlalchemy.ext.asyncio import AsyncSession +from sqlmodel import select +from backend.src.db import get_session, Todo, TodoCreate, TodoResponse + +@app.get("/api/todos", response_model=list[TodoResponse]) +async def list_todos( + user_id: str, # Extracted from JWT middleware + session: AsyncSession = Depends(get_session) +): + """List all todos for authenticated user""" + statement = select(Todo).where(Todo.user_id == user_id) + result = await session.execute(statement) + todos = result.scalars().all() + return todos + +@app.post("/api/todos", response_model=TodoResponse) +async def create_todo( + todo_data: TodoCreate, + user_id: str, # Extracted from JWT middleware + session: AsyncSession = Depends(get_session) +): + """Create a new todo for authenticated user""" + todo = Todo( + **todo_data.model_dump(), + user_id=user_id # REQUIRED for multi-tenant isolation + ) + session.add(todo) + await session.commit() + await session.refresh(todo) + return todo +``` + +## Security Checklist + +- [x] All tables include `user_id: str` column +- [x] `user_id` is indexed for performance +- [x] SQLModel used exclusively (no raw SQLAlchemy) +- [x] Connection includes `pool_pre_ping=True` +- [x] No naming conflicts with Better Auth tables +- [x] Environment variables used for DATABASE_URL +- [x] Error handling for connection failures +- [x] Type hints complete and correct +- [x] UUID primary keys (prevents enumeration attacks) +- [x] Input validation via SQLModel + +## Performance Features + +- **Connection Pooling**: Reuses connections for better performance +- **Async Operations**: Non-blocking I/O for concurrent requests +- **Optimized Indexes**: + - `user_id` index for all queries + - Composite `(user_id, is_completed)` for filtered queries +- **Serverless Optimization**: Small pool size, connection recycling + +## Testing Strategy + +### Unit Tests +Test query functions with mock data: +```python +@pytest.mark.asyncio +async def test_create_todo(session): + todo_data = TodoCreate(title="Test", description="Test todo") + todo = Todo(**todo_data.model_dump(), user_id="test_user") + session.add(todo) + await session.commit() + assert todo.id is not None +``` + +### Integration Tests +Test with real Neon database: +```python +@pytest.mark.asyncio +async def test_user_isolation(session): + # Verify user1 cannot see user2's todos + result = await session.execute( + select(Todo).where(Todo.user_id == "user1") + ) + todos = result.scalars().all() + assert all(t.user_id == "user1" for t in todos) +``` + +## Troubleshooting + +### Issue: "DATABASE_URL environment variable not set" +**Solution**: +1. Ensure `.env` file exists at `E:\todoweb\.env` +2. Add `DATABASE_URL=postgresql://...` with your Neon connection string + +### Issue: "Failed to connect to database" +**Solution**: +1. Verify Neon database is running (check Neon Console) +2. Check connection string format +3. Ensure network connectivity +4. Review Neon dashboard for database status + +### Issue: "Table does not exist" +**Solution**: +1. Run `python -m backend.src.db.verify` to create tables +2. Or call `await init_database()` in your FastAPI startup + +## Architecture Decisions + +### Why AsyncEngine with asyncpg? +- **Async/await**: Non-blocking I/O for better concurrency +- **asyncpg**: Fastest PostgreSQL driver for Python +- **Neon compatibility**: Optimized for serverless PostgreSQL + +### Why pool_pre_ping=True? +- **Serverless cold starts**: Validates connections before use +- **Stale connections**: Detects and replaces dead connections +- **Reliability**: Prevents "connection already closed" errors + +### Why small pool size (5)? +- **Serverless optimization**: Neon works better with fewer connections +- **Resource efficiency**: Reduces memory usage +- **Cost optimization**: Fewer connections = lower costs + +### Why UUID primary keys? +- **Security**: Prevents enumeration attacks +- **Global uniqueness**: No collisions across distributed systems +- **Unpredictability**: Cannot guess valid IDs + +## References + +- **Data Model**: `E:\todoweb\specs\001-todo-api\data-model.md` +- **Architecture Plan**: `E:\todoweb\specs\001-todo-api\plan.md` +- **Database README**: `E:\todoweb\backend\src\db\README.md` +- **SQLModel Docs**: https://sqlmodel.tiangolo.com/ +- **Neon Docs**: https://neon.tech/docs + +## Status + +✅ **Database module complete and ready for use** + +Next phase: Implement JWT middleware and FastAPI routes with user isolation. diff --git a/src/db/__init__.py b/src/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a28d5d607dce4b147424f95391251027f9fc5576 --- /dev/null +++ b/src/db/__init__.py @@ -0,0 +1,149 @@ +""" +Database Package Initialization for Todo API + +Owner: Database Reliability Engineer +Purpose: Central database module exports and initialization +Architecture: Async/await with SQLModel and Neon PostgreSQL + +This module provides: +- Database connection management (get_session, get_engine) +- SQLModel models (Todo, TodoCreate, TodoUpdate, TodoResponse) +- Initialization utilities (create_tables, init_database) +- Health check functions + +Usage: + from backend.src.db import get_session, Todo, TodoCreate + from backend.src.db import init_database + + # Initialize database on startup + await init_database() + + # Use in FastAPI routes + @app.get("/api/todos") + async def list_todos(session: AsyncSession = Depends(get_session)): + # Query todos with user isolation + pass +""" + +import logging +from sqlalchemy.ext.asyncio import AsyncSession, AsyncEngine +from sqlalchemy import text + +# Import connection utilities +from .connection import ( + get_engine, + get_session, + get_session_factory, + create_tables, + close_engine, + check_database_health, +) + +# Import models +from .models import ( + Todo, + TodoBase, + TodoCreate, + TodoUpdate, + TodoResponse, +) + +# Import chat models (Phase III) +from ..models.conversation import Conversation +from ..models.message import Message + +# Configure logging +logger = logging.getLogger("database") + + +async def init_database() -> None: + """ + Initialize the database for the Todo API. + + This function should be called once during application startup. + + Steps: + 1. Create all SQLModel tables (todos table) + 2. Create composite index for query optimization + 3. Verify database connectivity + + Note: + - Better Auth tables are managed separately (not created here) + - Only creates tables that don't exist (IF NOT EXISTS) + - Safe to call multiple times (idempotent) + + Raises: + Exception: If database initialization fails + """ + logger.info("Initializing database for Todo API...") + + try: + # Step 1: Create all SQLModel tables + await create_tables() + logger.info("✓ Database tables created") + + # Step 2: Create composite index for optimized queries + # Index: (user_id, is_completed) for "show my incomplete todos" queries + engine = get_engine() + async with engine.begin() as conn: + # Check if index exists before creating + await conn.execute(text(""" + CREATE INDEX IF NOT EXISTS idx_todos_user_completed + ON todos(user_id, is_completed); + """)) + logger.info("✓ Composite index created (user_id, is_completed)") + + # Step 3: Verify database connectivity + is_healthy = await check_database_health() + if not is_healthy: + raise ConnectionError("Database health check failed") + logger.info("✓ Database health check passed") + + logger.info("Database initialization complete") + + except Exception as e: + logger.error(f"Database initialization failed: {e}") + raise + + +async def cleanup_database() -> None: + """ + Cleanup database connections during application shutdown. + + This function should be called during application shutdown to: + - Close all database connections + - Release connection pool resources + - Ensure graceful shutdown + + Usage: + @app.on_event("shutdown") + async def shutdown(): + await cleanup_database() + """ + logger.info("Cleaning up database connections...") + await close_engine() + logger.info("Database cleanup complete") + + +# Export all public components +__all__ = [ + # Connection utilities + "get_engine", + "get_session", + "get_session_factory", + "create_tables", + "close_engine", + "check_database_health", + # Models + "Todo", + "TodoBase", + "TodoCreate", + "TodoUpdate", + "TodoResponse", + # Chat models (Phase III) + "Conversation", + "Message", + # Initialization + "init_database", + "cleanup_database", +] diff --git a/src/db/connection.py b/src/db/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..32cdc925b361155337870287dd1c22ef450ab251 --- /dev/null +++ b/src/db/connection.py @@ -0,0 +1,241 @@ +""" +Database Connection Configuration for Todo API + +Owner: Database Reliability Engineer +Purpose: Neon Serverless PostgreSQL connection with asyncpg driver +Architecture: Async/await with SQLModel ORM and connection pooling + +Constitutional Constraints: +- REQUIRED: pool_pre_ping=True for serverless cold start handling +- REQUIRED: AsyncEngine with asyncpg driver +- REQUIRED: Environment variable for DATABASE_URL (never hardcode) +- REQUIRED: Connection pooling optimized for serverless (smaller pool sizes) + +All operations use SQLModel for type-safe database interactions. +Connection includes retry logic and proper error handling for Neon serverless. +""" + +import os +import logging +from typing import AsyncGenerator +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, AsyncEngine +from sqlalchemy.orm import sessionmaker +from sqlalchemy import text +from sqlmodel import SQLModel +from dotenv import load_dotenv + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("database.connection") + +# Load environment variables +load_dotenv() + + +class DatabaseConfig: + """ + Database configuration for Neon Serverless PostgreSQL. + + Optimized for serverless with: + - pool_pre_ping: Validates connections before use (handles cold starts) + - Small pool size: Serverless databases work better with fewer connections + - Pool recycling: Prevents stale connections + - Async operations: Non-blocking I/O for better concurrency + """ + + def __init__(self): + self.database_url = os.getenv("DATABASE_URL") + if not self.database_url: + raise ValueError( + "DATABASE_URL environment variable not set. " + "Please add DATABASE_URL to your .env file with your Neon connection string." + ) + + # Remove query parameters that asyncpg doesn't accept in URL + # (sslmode, channel_binding, etc. will be handled via connect_args) + if "?" in self.database_url: + self.database_url = self.database_url.split("?")[0] + logger.info("Removed query parameters from DATABASE_URL (will use connect_args for SSL)") + + # Convert postgresql:// to postgresql+asyncpg:// for async driver + if self.database_url.startswith("postgresql://"): + self.database_url = self.database_url.replace( + "postgresql://", "postgresql+asyncpg://", 1 + ) + elif not self.database_url.startswith("postgresql+asyncpg://"): + raise ValueError( + "DATABASE_URL must start with 'postgresql://' or 'postgresql+asyncpg://'" + ) + + logger.info("Database configuration initialized") + + def get_engine(self) -> AsyncEngine: + """ + Create and return an async database engine. + + Configuration optimized for Neon Serverless: + - pool_pre_ping=True: Critical for serverless cold starts + - pool_size=5: Smaller pool for serverless (vs 10-20 for traditional) + - max_overflow=10: Additional connections when pool exhausted + - pool_recycle=3600: Recycle connections after 1 hour + - echo=False: Disable SQL logging in production (set True for debugging) + + Returns: + AsyncEngine configured for Neon PostgreSQL + + Raises: + ValueError: If DATABASE_URL is not set or invalid + """ + # SSL configuration for Neon (asyncpg requires ssl='require' as connect_arg) + import ssl as ssl_module + + engine = create_async_engine( + self.database_url, + echo=False, # Set to True for SQL query logging during development + future=True, + pool_pre_ping=True, # CRITICAL: Validates connections before use + pool_size=5, # Smaller pool for serverless optimization + max_overflow=10, # Additional connections when needed + pool_recycle=3600, # Recycle connections after 1 hour (prevents stale connections) + connect_args={ + "ssl": ssl_module.create_default_context(), # Enable SSL for Neon + "server_settings": { + "application_name": "todo-api" + } + } + ) + + logger.info("Database engine created with Neon-optimized settings") + return engine + + +# Global engine instance (singleton pattern) +_engine: AsyncEngine | None = None +_session_factory: sessionmaker | None = None + + +def get_engine() -> AsyncEngine: + """ + Get or create the global database engine. + + Returns: + AsyncEngine instance (singleton) + """ + global _engine + if _engine is None: + config = DatabaseConfig() + _engine = config.get_engine() + return _engine + + +def get_session_factory() -> sessionmaker: + """ + Get or create the global session factory. + + Returns: + sessionmaker configured for async sessions + """ + global _session_factory + if _session_factory is None: + engine = get_engine() + _session_factory = sessionmaker( + engine, + class_=AsyncSession, + expire_on_commit=False, # Prevent lazy loading issues after commit + autocommit=False, + autoflush=False, + ) + return _session_factory + + +async def get_session() -> AsyncGenerator[AsyncSession, None]: + """ + Dependency function to get database session for FastAPI routes. + + Usage in FastAPI: + @app.get("/api/todos") + async def list_todos(session: AsyncSession = Depends(get_session)): + # Use session here + pass + + Yields: + AsyncSession for database operations + + Note: + This is an async generator that properly handles session lifecycle. + The session is automatically closed after the request completes. + """ + session_factory = get_session_factory() + async with session_factory() as session: + try: + yield session + except Exception as e: + await session.rollback() + logger.error(f"Database session error: {e}") + raise + finally: + await session.close() + + +async def create_tables() -> None: + """ + Create all database tables defined in SQLModel models. + + This should be called once during application startup. + Uses SQLModel.metadata.create_all() to create tables. + + Note: + - Only creates tables that don't exist (IF NOT EXISTS) + - Does not modify existing tables (use migrations for schema changes) + - Better Auth tables are managed separately (not created here) + + Raises: + Exception: If table creation fails + """ + engine = get_engine() + try: + async with engine.begin() as conn: + await conn.run_sync(SQLModel.metadata.create_all) + logger.info("Database tables created successfully") + except Exception as e: + logger.error(f"Failed to create database tables: {e}") + raise + + +async def close_engine() -> None: + """ + Close the database engine and release all connections. + + This should be called during application shutdown. + Ensures all connections are properly closed and resources released. + """ + global _engine, _session_factory + if _engine: + await _engine.dispose() + _engine = None + _session_factory = None + logger.info("Database engine closed and connections released") + + +# Health check function for monitoring +async def check_database_health() -> bool: + """ + Check if database connection is healthy. + + Returns: + True if database is accessible, False otherwise + + Usage: + Used by health check endpoints to verify database connectivity + """ + try: + engine = get_engine() + async with engine.connect() as conn: + await conn.execute(text("SELECT 1")) + return True + except Exception as e: + logger.error(f"Database health check failed: {e}") + return False diff --git a/src/db/models.py b/src/db/models.py new file mode 100644 index 0000000000000000000000000000000000000000..02fb6ebe22e97085592a868cf965114e36ab65bc --- /dev/null +++ b/src/db/models.py @@ -0,0 +1,228 @@ +""" +SQLModel Database Models for Todo API + +Owner: Database Reliability Engineer +Purpose: Type-safe database models with multi-tenant isolation +Architecture: SQLModel (Pydantic + SQLAlchemy) with async support + +Constitutional Constraints: +- REQUIRED: All tables MUST include user_id: str column (multi-tenant isolation) +- REQUIRED: user_id MUST be indexed for query performance +- REQUIRED: SQLModel exclusive (no raw SQLAlchemy models) +- REQUIRED: Better Auth compatibility (no conflicts with user table) + +All models enforce user isolation per constitution Principle IV. +""" + +from sqlmodel import SQLModel, Field +from datetime import datetime +from uuid import UUID, uuid4 +from typing import Optional + + +class TodoBase(SQLModel): + """ + Base model with shared fields for requests/responses. + + This model contains fields that are common across create/update/response models. + Does not include system-generated fields (id, user_id, timestamps). + """ + title: str = Field( + min_length=1, + max_length=200, + description="Todo title (required, 1-200 characters)" + ) + description: Optional[str] = Field( + default=None, + max_length=2000, + description="Optional detailed description (max 2000 characters)" + ) + category: Optional[str] = Field( + default=None, + max_length=50, + description="Optional category for organizing todos (e.g., Work, Personal, Shopping)" + ) + due_date: Optional[datetime] = Field( + default=None, + description="Optional due date for the todo" + ) + is_completed: bool = Field( + default=False, + description="Completion status (default: false)" + ) + + +class Todo(TodoBase, table=True): + """ + Database model for todos table. + + Includes all fields including system-generated ones (id, user_id, timestamps). + + Multi-Tenant Isolation: + - user_id is REQUIRED and INDEXED + - All queries MUST filter by user_id + - user_id is extracted from JWT sub claim (never from client input) + + Better Auth Compatibility: + - user_id references Better Auth's user table (managed externally) + - No foreign key constraint (Better Auth manages users separately) + - Todos remain if user deleted (business decision - can be changed) + + Indexes: + - Primary: id (UUID) - Fast lookups by todo ID + - Secondary: user_id - Critical for user isolation queries + - Composite: (user_id, is_completed) - Optimizes filtered lists + """ + __tablename__ = "todos" + + id: UUID = Field( + default_factory=uuid4, + primary_key=True, + description="Unique identifier (UUID v4)" + ) + + user_id: str = Field( + index=True, + nullable=False, + description="Owner user ID from JWT sub claim (REQUIRED for multi-tenant isolation)" + ) + + created_at: datetime = Field( + default_factory=datetime.utcnow, + nullable=False, + description="Creation timestamp (UTC)" + ) + + updated_at: datetime = Field( + default_factory=datetime.utcnow, + nullable=False, + description="Last modification timestamp (UTC)" + ) + + class Config: + """SQLModel configuration""" + json_schema_extra = { + "example": { + "id": "550e8400-e29b-41d4-a716-446655440000", + "user_id": "user_123abc", + "title": "Buy groceries", + "description": "Milk, eggs, bread", + "category": "Shopping", + "due_date": "2026-01-15T18:00:00Z", + "is_completed": False, + "created_at": "2026-01-09T10:00:00Z", + "updated_at": "2026-01-09T10:00:00Z" + } + } + + +class TodoCreate(TodoBase): + """ + Request model for creating a todo. + + Excludes system-generated fields: + - id: Generated by database + - user_id: Extracted from JWT (security requirement) + - created_at: Set by database + - updated_at: Set by database + + Validation: + - title: Required, 1-200 characters + - description: Optional, max 2000 characters + - is_completed: Optional, defaults to False + """ + pass + + +class TodoUpdate(SQLModel): + """ + Request model for updating a todo. + + All fields are optional (partial updates supported). + Only provided fields will be updated. + + Validation: + - title: If provided, must be 1-200 characters + - description: If provided, max 2000 characters + - category: If provided, max 50 characters + - due_date: If provided, must be valid datetime + - is_completed: If provided, must be boolean + + Note: + - user_id cannot be changed (security requirement) + - id cannot be changed (immutable) + - timestamps are updated automatically + """ + title: Optional[str] = Field( + default=None, + min_length=1, + max_length=200, + description="Todo title (optional for updates)" + ) + description: Optional[str] = Field( + default=None, + max_length=2000, + description="Optional detailed description" + ) + category: Optional[str] = Field( + default=None, + max_length=50, + description="Optional category" + ) + due_date: Optional[datetime] = Field( + default=None, + description="Optional due date" + ) + is_completed: Optional[bool] = Field( + default=None, + description="Completion status" + ) + + +class TodoResponse(TodoBase): + """ + Response model with all fields. + + Includes all fields from the database model. + Used for API responses to ensure consistent structure. + + Fields: + - id: UUID (system-generated) + - user_id: String (from JWT) + - title: String (required) + - description: String | None (optional) + - is_completed: Boolean (default: false) + - created_at: DateTime (UTC) + - updated_at: DateTime (UTC) + """ + id: UUID + user_id: str + created_at: datetime + updated_at: datetime + + class Config: + """SQLModel configuration""" + json_schema_extra = { + "example": { + "id": "550e8400-e29b-41d4-a716-446655440000", + "user_id": "user_123abc", + "title": "Buy groceries", + "description": "Milk, eggs, bread", + "category": "Shopping", + "due_date": "2026-01-15T18:00:00Z", + "is_completed": False, + "created_at": "2026-01-09T10:00:00Z", + "updated_at": "2026-01-09T10:00:00Z" + } + } + + +# Additional index configuration for composite index +# This will be created during table initialization +# CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed); +# +# Rationale: +# - Common query pattern: "show me my incomplete todos" +# - Composite index optimizes: WHERE user_id = ? AND is_completed = ? +# - Single user_id index covers: WHERE user_id = ? +# - Both indexes are beneficial for different query patterns diff --git a/src/db/verify.py b/src/db/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..cedd9a2639a9a9a93f088ea87867c93a49e2ba97 --- /dev/null +++ b/src/db/verify.py @@ -0,0 +1,159 @@ +""" +Database Verification Script for Todo API + +Purpose: Verify database connection and schema initialization +Usage: python -m backend.src.db.verify + +This script: +1. Tests database connection to Neon PostgreSQL +2. Verifies all tables are created correctly +3. Checks indexes are in place +4. Validates schema matches SQLModel definitions + +Run this after setting up your DATABASE_URL in .env file. +""" + +import asyncio +import sys +import logging +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("database.verify") + + +async def verify_database(): + """ + Verify database setup and connectivity. + + Returns: + bool: True if all checks pass, False otherwise + """ + try: + # Import after logging is configured + from backend.src.db import ( + init_database, + get_session, + check_database_health, + get_engine + ) + + logger.info("=" * 60) + logger.info("Database Verification Script") + logger.info("=" * 60) + + # Step 1: Check database health + logger.info("\n[1/5] Checking database connectivity...") + is_healthy = await check_database_health() + if not is_healthy: + logger.error("✗ Database connection failed") + return False + logger.info("✓ Database connection successful") + + # Step 2: Initialize database (create tables and indexes) + logger.info("\n[2/5] Initializing database schema...") + await init_database() + logger.info("✓ Database schema initialized") + + # Step 3: Verify todos table exists + logger.info("\n[3/5] Verifying todos table...") + engine = get_engine() + async with engine.begin() as conn: + result = await conn.execute(text(""" + SELECT EXISTS ( + SELECT FROM information_schema.tables + WHERE table_name = 'todos' + ); + """)) + table_exists = result.scalar() + + if not table_exists: + logger.error("✗ Todos table not found") + return False + logger.info("✓ Todos table exists") + + # Step 4: Verify table schema + logger.info("\n[4/5] Verifying table schema...") + async with engine.begin() as conn: + result = await conn.execute(text(""" + SELECT column_name, data_type, is_nullable + FROM information_schema.columns + WHERE table_name = 'todos' + ORDER BY ordinal_position; + """)) + columns = result.fetchall() + + required_columns = { + 'id': 'uuid', + 'user_id': 'character varying', + 'title': 'character varying', + 'description': 'character varying', + 'is_completed': 'boolean', + 'created_at': 'timestamp without time zone', + 'updated_at': 'timestamp without time zone' + } + + found_columns = {col[0]: col[1] for col in columns} + + for col_name, col_type in required_columns.items(): + if col_name not in found_columns: + logger.error(f"✗ Missing column: {col_name}") + return False + logger.info(f" ✓ Column '{col_name}' ({found_columns[col_name]})") + + # Step 5: Verify indexes + logger.info("\n[5/5] Verifying indexes...") + async with engine.begin() as conn: + result = await conn.execute(text(""" + SELECT indexname + FROM pg_indexes + WHERE tablename = 'todos'; + """)) + indexes = [row[0] for row in result.fetchall()] + + required_indexes = ['todos_pkey', 'ix_todos_user_id', 'idx_todos_user_completed'] + + for index_name in required_indexes: + if index_name in indexes: + logger.info(f" ✓ Index '{index_name}' exists") + else: + logger.warning(f" ⚠ Index '{index_name}' not found (may be created with different name)") + + logger.info("\n" + "=" * 60) + logger.info("✓ All verification checks passed!") + logger.info("=" * 60) + logger.info("\nDatabase is ready for use.") + logger.info("Next steps:") + logger.info(" 1. Start the FastAPI server: uvicorn backend.src.api.main:app --reload") + logger.info(" 2. Test the API endpoints with authentication") + logger.info(" 3. Verify user isolation in multi-tenant scenarios") + + return True + + except ValueError as e: + logger.error(f"\n✗ Configuration error: {e}") + logger.error("\nPlease ensure:") + logger.error(" 1. .env file exists in project root") + logger.error(" 2. DATABASE_URL is set with your Neon connection string") + logger.error(" 3. Format: postgresql://user:password@host.neon.tech/database") + return False + + except Exception as e: + logger.error(f"\n✗ Verification failed: {e}") + logger.exception("Full error details:") + return False + + +async def main(): + """Main entry point for verification script.""" + success = await verify_database() + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4ff297865eadafd129e282427be92c94898e4f --- /dev/null +++ b/src/main.py @@ -0,0 +1,164 @@ +""" +Application Entry Point for Interactive Todo Application (v2.0.0) + +Owner: Menu/UX Agent +Purpose: Entry point for the Typer-based CLI +Architecture: Delegates execution to src/cli.py + +Constitutional Constraints: +- ALLOWED: CLI orchestration, startup/shutdown logic +- FORBIDDEN: SQL queries, Business logic, Direct database access +""" + +import sys +import asyncio +import selectors +from rich.console import Console +from rich.prompt import Prompt, IntPrompt +from rich.panel import Panel +from rich.table import Table +from datetime import datetime + +# Set event loop policy for Windows if needed +if sys.platform == 'win32': + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + +from src.cli import add, list_tasks, search, update, delete, complete, history, async_add, async_list_tasks, async_search, async_update, async_delete, async_complete, async_history +from src.models import Priority, TaskStatus, RecurrenceInterval +from src.database import init_db +from src.notification_manager import check_due_tasks_and_notify + +console = Console() + +def show_welcome(): + """Display welcome message and instructions.""" + console.print(Panel.fit( + "[bold cyan]Interactive Todo Application (v2.1.0)[/bold cyan]\n" + "Advanced Intelligent Task Management", + title="Welcome", + border_style="cyan" + )) + +async def async_history(task_id: int): + """Placeholder or delegate to cli implementation.""" + from src.cli import history + # The history command in cli.py is already async-wrapped + # But for simplicity, we call the logic directly if available + from src import services + from rich.table import Table + + result = await services.get_task_history(task_id) + if not result["success"]: + console.print(f"[red]{result['message']}[/red]") + return + + tasks = result["data"] + table = Table(title=f"Task History Series: {task_id}", header_style="bold cyan") + table.add_column("ID", justify="right") + table.add_column("Status") + table.add_column("Completed Date") + table.add_column("Due Date") + + for task in tasks: + # Convert task to dict if it's a Pydantic model + t_dict = task.to_dict() if hasattr(task, 'to_dict') else task + status_icon = "[green]✓[/green]" if t_dict['status'] == TaskStatus.COMPLETED else "[yellow]○[/yellow]" + completed_str = t_dict['updated_at'].strftime("%Y-%m-%d %H:%M") if t_dict['status'] == TaskStatus.COMPLETED else "-" + due_str = t_dict['due_date'].strftime("%Y-%m-%d %H:%M") if t_dict['due_date'] else "-" + table.add_row(str(t_dict['id']), status_icon, completed_str, due_str) + + console.print(table) + +async def interactive_loop(): + """Run the application in a highly interactive continuous loop.""" + show_welcome() + + while True: + console.print("\n[bold]Main Menu:[/bold]") + console.print("1. [green]Add[/green] a new task (Interactive Wizard)") + console.print("2. [blue]List[/blue] all tasks") + console.print("3. [yellow]Search[/yellow] tasks") + console.print("4. [magenta]Update[/magenta] a task") + console.print("5. [cyan]Complete/Toggle[/cyan] a task") + console.print("6. [white]View History[/white] of a recurring task") + console.print("7. [red]Delete[/red] a task") + console.print("0. [grey50]Exit[/grey50]") + + choice = Prompt.ask("\nChoose an action", choices=["1", "2", "3", "4", "5", "6", "7", "0"], default="2") + + try: + if choice == "1": # Add + await async_add(title="", interactive=True) + + elif choice == "2": # List + status_raw = Prompt.ask("Filter by status", choices=["pending", "completed", "all"], default="all") + prio_raw = Prompt.ask("Filter by priority", choices=["low", "medium", "high", "all"], default="all") + sort = Prompt.ask("Sort by", choices=["date", "priority", "alpha"], default="date") + + status_filter = None + if status_raw != "all": + status_filter = TaskStatus(status_raw) + + prio_filter = None + if prio_raw != "all": + prio_filter = Priority(prio_raw) + + await async_list_tasks( + status=status_filter, + priority=prio_filter, + sort=sort + ) + + elif choice == "3": # Search + query = Prompt.ask("Enter search keyword") + await async_search(query=query) + + elif choice == "4": # Update + task_id = IntPrompt.ask("Enter Task ID to update") + await async_update(task_id=task_id, interactive=True) + + elif choice == "5": # Complete + task_id = IntPrompt.ask("Enter Task ID to toggle") + await async_complete(task_id=task_id) + + elif choice == "6": # History + task_id = IntPrompt.ask("Enter the original Task ID") + await async_history(task_id=task_id) + + elif choice == "7": # Delete + task_id = IntPrompt.ask("Enter Task ID to delete") + await async_delete(task_id=task_id) + + elif choice == "0": # Exit + console.print("[cyan]Goodbye![/cyan]") + break + + except Exception as e: + console.print(f"[bold red]An error occurred:[/bold red] {e}") + +async def main(): + """Execute the application. Always enters the primary interactive loop.""" + # Ensure database is initialized before any operations + try: + await init_db() + except Exception as e: + console.print(f"[bold red]Critical Error during database initialization:[/bold red] {e}") + sys.exit(1) + + # Boot check: Notifications for due tasks + try: + notified_count = await check_due_tasks_and_notify() + if notified_count > 0: + console.print(f"[bold yellow]Reminder:[/bold yellow] You have {notified_count} tasks due soon! (Check OS notifications)") + except Exception as e: + # Catch silently as per constraints + pass + + try: + await interactive_loop() + except KeyboardInterrupt: + console.print("\n\n[yellow]Application interrupted. Exiting...[/yellow]") + sys.exit(0) + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/src/mcp/__init__.py b/src/mcp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4630ace9eaafe8ea1a6c31fdf703b11862dc77 --- /dev/null +++ b/src/mcp/__init__.py @@ -0,0 +1,6 @@ +# backend/src/mcp/__init__.py +"""MCP (Model Context Protocol) package for AI chatbot tools.""" + +from .server import mcp_server + +__all__ = ["mcp_server"] diff --git a/src/mcp/server.py b/src/mcp/server.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7c25097dd25f729de8a7b0783fc23ff4129454 --- /dev/null +++ b/src/mcp/server.py @@ -0,0 +1,27 @@ +# backend/src/mcp/server.py +""" +FastMCP Server for AI Chatbot Task Management + +Owner: MCP Engineer +Purpose: MCP tool server for AI agent task operations +Architecture: FastMCP with FastAPI integration + +Constitutional Constraints: +- REQUIRED: All tools enforce user_id isolation (Principle IV) +- REQUIRED: Tools are the ONLY way AI accesses data (Principle VII) +- REQUIRED: All tool calls logged for audit trail (Principle VIII) +""" + +import logging + +logger = logging.getLogger("mcp.server") + +# Import the mcp instance from task_tools (tools are registered there) +from .tools.task_tools import mcp, add_task, list_tasks, complete_task, update_task, delete_task + +# Re-export as mcp_server for consistency +mcp_server = mcp + +logger.info("FastMCP server 'task-tools' initialized with tools: add_task, list_tasks, complete_task, update_task, delete_task") + +__all__ = ["mcp_server", "add_task", "list_tasks", "complete_task", "update_task", "delete_task"] diff --git a/src/mcp/tools/__init__.py b/src/mcp/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27e9cfcf83646e57a45354625724dcdb8266a519 --- /dev/null +++ b/src/mcp/tools/__init__.py @@ -0,0 +1,6 @@ +# backend/src/mcp/tools/__init__.py +"""MCP tools for task management.""" + +from .task_tools import mcp, add_task, list_tasks, complete_task, verify_task_ownership + +__all__ = ["mcp", "add_task", "list_tasks", "complete_task", "verify_task_ownership"] diff --git a/src/mcp/tools/task_tools.py b/src/mcp/tools/task_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3f1f9dd794a798ed1085032c33132ab8e14e5a --- /dev/null +++ b/src/mcp/tools/task_tools.py @@ -0,0 +1,360 @@ +# backend/src/mcp/tools/task_tools.py +""" +MCP Tools for AI Chatbot Task Management + +Owner: MCP Engineer +Purpose: Tool definitions for AI agent task operations +Architecture: FastMCP tools with async database operations + +Constitutional Constraints: +- REQUIRED: All tools enforce user_id isolation (Principle IV) +- REQUIRED: Tools are the ONLY way AI accesses data (Principle VII) +- REQUIRED: Ownership double-check before modifications (mcp-ownership-verification) + +Note: Core functions are defined separately from MCP decorators to allow +direct calling from the chat endpoint while also exposing them via MCP. +""" + +import logging +from typing import Annotated, Optional +from uuid import UUID +from fastmcp import FastMCP +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, text + +from src.db.connection import get_session_factory +from src.db.models import Todo + +logger = logging.getLogger("mcp.tools.task_tools") + +# Initialize FastMCP server +mcp = FastMCP("task-tools") + + +async def find_task_by_short_id( + short_id: str, + user_id: str, + session: AsyncSession +) -> Todo | None: + """ + Find a task by short ID (first 8 chars of UUID). + + Uses raw SQL since SQLAlchemy UUID cast doesn't work well. + """ + # Use raw SQL for the LIKE query on UUID + query = text(""" + SELECT id, user_id, title, description, is_completed, created_at, updated_at + FROM todo + WHERE user_id = :user_id AND CAST(id AS TEXT) LIKE :pattern + LIMIT 1 + """) + result = await session.execute(query, {"user_id": user_id, "pattern": f"{short_id}%"}) + row = result.fetchone() + + if row: + # Fetch the actual ORM object + statement = select(Todo).where(Todo.id == row[0], Todo.user_id == user_id) + orm_result = await session.execute(statement) + return orm_result.scalar_one_or_none() + return None + + +async def verify_task_ownership( + task_id: str, + user_id: str, + session: AsyncSession +) -> Todo | None: + """ + Double-check ownership before modification. + + Per mcp-ownership-verification skill: + - Always verify task.user_id matches the authenticated user_id + - Return None if task doesn't exist OR user doesn't own it + - Error message must not reveal whether task exists for other users + + Args: + task_id: UUID string of the task + user_id: Authenticated user's ID from JWT sub claim + session: Active database session + + Returns: + Todo if found and owned by user, None otherwise + """ + try: + uuid_id = UUID(task_id) + except ValueError: + logger.warning(f"Invalid UUID format for task_id: {task_id}") + return None + + statement = select(Todo).where( + Todo.id == uuid_id, + Todo.user_id == user_id + ) + result = await session.execute(statement) + return result.scalar_one_or_none() + + +# ============================================================================ +# Core tool functions (directly callable) +# ============================================================================ + +async def add_task_impl( + user_id: str, + title: str, + description: Optional[str] = None +) -> str: + """Create a new task for the user.""" + # Validate title + if not title or not title.strip(): + return "Error: Title is required and cannot be empty." + + if len(title) > 200: + return "Error: Title must be 200 characters or less." + + session_factory = get_session_factory() + async with session_factory() as session: + try: + task = Todo( + user_id=user_id, + title=title.strip(), + description=description, + is_completed=False + ) + session.add(task) + await session.commit() + await session.refresh(task) + + logger.info(f"Task created: {task.id} for user {user_id}") + return f"Task '{task.title}' added with ID {task.id}." + except Exception as e: + await session.rollback() + logger.error(f"Failed to create task: {e}") + return "Error: Failed to create task. Please try again." + + +async def list_tasks_impl( + user_id: str, + status: str = "all" +) -> str: + """List the user's tasks with optional status filter.""" + # Validate status + valid_statuses = ["all", "pending", "completed"] + if status not in valid_statuses: + return f"Error: Invalid status '{status}'. Use 'all', 'pending', or 'completed'." + + session_factory = get_session_factory() + async with session_factory() as session: + try: + statement = select(Todo).where(Todo.user_id == user_id) + + if status == "pending": + statement = statement.where(Todo.is_completed == False) + elif status == "completed": + statement = statement.where(Todo.is_completed == True) + + statement = statement.order_by(Todo.created_at.desc()) + result = await session.execute(statement) + tasks = result.scalars().all() + + if not tasks: + return "You have no tasks." + + status_label = f"{status} " if status != "all" else "" + lines = [f"Your {status_label}tasks:"] + for task in tasks: + icon = "[x]" if task.is_completed else "[ ]" + # Show full UUID for clarity + lines.append(f"- ID: {task.id} {icon} {task.title}") + + logger.info(f"Listed {len(tasks)} tasks for user {user_id}") + return "\n".join(lines) + except Exception as e: + logger.error(f"Failed to list tasks: {e}") + return "Error: Failed to retrieve tasks. Please try again." + + +async def complete_task_impl( + user_id: str, + task_id: str +) -> str: + """Mark a task as complete. Verifies ownership before modification.""" + # Validate task_id is provided + if not task_id or not task_id.strip(): + return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs." + + task_id = task_id.strip() + + session_factory = get_session_factory() + async with session_factory() as session: + try: + # Handle short ID (first 8 chars) or full UUID + if len(task_id) == 8: + logger.info(f"Using short ID search for task_id: {task_id}") + task = await find_task_by_short_id(task_id, user_id, session) + else: + logger.info(f"Using full UUID search for task_id: {task_id}") + task = await verify_task_ownership(task_id, user_id, session) + + if not task: + return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again." + + if task.is_completed: + return f"Task '{task.title}' is already complete." + + task.is_completed = True + await session.commit() + + logger.info(f"Task completed: {task.id} for user {user_id}") + return f"Task '{task.title}' marked as complete." + except Exception as e: + await session.rollback() + logger.error(f"Failed to complete task: {e}") + return "Error: Failed to complete task. Please try again." + + +async def update_task_impl( + user_id: str, + task_id: str, + title: Optional[str] = None, + description: Optional[str] = None +) -> str: + """Update a task's title or description. Verifies ownership before modification.""" + logger.info(f"update_task_impl called: user_id={user_id}, task_id={task_id}, title={title}, description={description}") + + # Validate task_id is provided + if not task_id or not task_id.strip(): + return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs." + + task_id = task_id.strip() + + if not title and description is None: + return "Error: Provide at least a new title or description to update." + + session_factory = get_session_factory() + async with session_factory() as session: + try: + # Handle short ID (first 8 chars) or full UUID + if len(task_id) == 8: + logger.info(f"Using short ID search for task_id: {task_id}") + task = await find_task_by_short_id(task_id, user_id, session) + else: + logger.info(f"Using full UUID search for task_id: {task_id}") + task = await verify_task_ownership(task_id, user_id, session) + + if not task: + logger.warning(f"Task not found or unauthorized: task_id={task_id}, user_id={user_id}") + return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again." + + old_title = task.title + if title: + if len(title) > 200: + return "Error: Title must be 200 characters or less." + task.title = title.strip() + if description is not None: + task.description = description + + await session.commit() + + logger.info(f"Task updated: {task.id} for user {user_id}") + return f"Task updated: '{old_title}' -> '{task.title}'" + except Exception as e: + await session.rollback() + logger.error(f"Failed to update task: {e}") + return "Error: Failed to update task. Please try again." + + +async def delete_task_impl( + user_id: str, + task_id: str +) -> str: + """Delete a task. Verifies ownership before deletion.""" + # Validate task_id is provided + if not task_id or not task_id.strip(): + return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs." + + task_id = task_id.strip() + + session_factory = get_session_factory() + async with session_factory() as session: + try: + # Handle short ID (first 8 chars) or full UUID + if len(task_id) == 8: + logger.info(f"Using short ID search for task_id: {task_id}") + task = await find_task_by_short_id(task_id, user_id, session) + else: + logger.info(f"Using full UUID search for task_id: {task_id}") + task = await verify_task_ownership(task_id, user_id, session) + + if not task: + return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again." + + task_title = task.title + await session.delete(task) + await session.commit() + + logger.info(f"Task deleted: {task_id} for user {user_id}") + return f"Task '{task_title}' has been deleted." + except Exception as e: + await session.rollback() + logger.error(f"Failed to delete task: {e}") + return "Error: Failed to delete task. Please try again." + + +# ============================================================================ +# MCP-decorated wrappers (for MCP server exposure) +# ============================================================================ + +@mcp.tool() +async def add_task( + user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"], + title: Annotated[str, "Title of the task (max 200 characters)"], + description: Annotated[Optional[str], "Optional description of the task"] = None +) -> str: + """Create a new task for the user.""" + return await add_task_impl(user_id, title, description) + + +@mcp.tool() +async def list_tasks( + user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"], + status: Annotated[str, "Filter by status: 'all', 'pending', or 'completed'"] = "all" +) -> str: + """List the user's tasks with optional status filter.""" + return await list_tasks_impl(user_id, status) + + +@mcp.tool() +async def complete_task( + user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"], + task_id: Annotated[str, "The ID (or first 8 characters) of the task to mark as complete"] +) -> str: + """Mark a task as complete. Verifies ownership before modification.""" + return await complete_task_impl(user_id, task_id) + + +@mcp.tool() +async def update_task( + user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"], + task_id: Annotated[str, "The ID (or first 8 characters) of the task to update"], + title: Annotated[Optional[str], "New title for the task"] = None, + description: Annotated[Optional[str], "New description for the task"] = None +) -> str: + """Update a task's title or description. Verifies ownership before modification.""" + return await update_task_impl(user_id, task_id, title, description) + + +@mcp.tool() +async def delete_task( + user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"], + task_id: Annotated[str, "The ID (or first 8 characters) of the task to delete"] +) -> str: + """Delete a task. Verifies ownership before deletion.""" + return await delete_task_impl(user_id, task_id) + + +__all__ = [ + "mcp", + "add_task", "list_tasks", "complete_task", "update_task", "delete_task", + "add_task_impl", "list_tasks_impl", "complete_task_impl", "update_task_impl", "delete_task_impl", + "verify_task_ownership" +] diff --git a/src/menu.py b/src/menu.py new file mode 100644 index 0000000000000000000000000000000000000000..04cb290b329100c554c4c49dbb40c0a2409fe2ef --- /dev/null +++ b/src/menu.py @@ -0,0 +1,345 @@ +""" +Menu/UX Layer for Interactive Todo Application + +Owner: Menu/UX Agent +Purpose: Display menus, collect user input, render task lists + +Constitutional Constraints: +- ALLOWED: Menu display (print()), User input (input()), Input validation, Service layer calls +- FORBIDDEN: SQL queries, Database connections, Business logic validation, Schema changes +""" + +from typing import Optional +from models import Task +import services + + +def display_menu() -> None: + """ + Display main menu options to user. + + Menu Options: + 1. Create New Task + 2. View All Tasks + 3. Update Task + 4. Toggle Task Completion + 5. Delete Task + 6. Exit + + Constitutional Compliance: + ✅ Display only (no input collection) + ✅ NO SQL queries + ✅ NO business logic + """ + print("\n" + "=" * 50) + print(" INTERACTIVE TODO APPLICATION") + print("=" * 50) + print("1. Create New Task") + print("2. View All Tasks") + print("3. Update Task") + print("4. Toggle Task Completion") + print("5. Delete Task") + print("6. Exit") + print("=" * 50) + + +def get_menu_choice() -> str: + """ + Get and validate menu selection from user. + + Returns: + User's menu choice as string ('1' through '6') + + Implementation Notes: + - Prompts user for input + - Validates choice is in valid range (1-6) + - Loops until valid input received + - Returns validated choice as string + + Constitutional Compliance: + ✅ Input validation (format only) + ✅ NO business logic validation + ✅ NO database operations + """ + while True: + choice = input("\nEnter your choice (1-6): ").strip() + + if choice in ['1', '2', '3', '4', '5', '6']: + return choice + else: + print("Invalid choice. Please enter a number between 1 and 6.") + + +def handle_create_task(conn) -> None: + """ + Collect task details and create task via service layer. + + Args: + conn: Active database connection to pass to service layer + + Implementation Notes: + - Prompts for title (required) + - Prompts for description (optional) + - Validates input is non-empty for title + - Calls services.create_task() with connection + - Displays success or error message from service layer + + Constitutional Compliance: + ✅ Input collection only + ✅ Calls service layer for business logic + ✅ NO SQL queries + ✅ NO business validation (delegates to service layer) + """ + print("\n--- Create New Task ---") + + # Collect title (required) + title = input("Enter task title: ").strip() + + if not title: + print("Error: Title cannot be empty.") + return + + # Collect description (optional) + description = input("Enter task description (optional, press Enter to skip): ").strip() + + # If description is empty string, pass None + if not description: + description = None + + # Call service layer to create task + result = services.create_task(conn, title, description) + + # Display result from service layer + if result['success']: + print(f"\n✓ {result['message']}") + else: + print(f"\n✗ {result['message']}") + + +def format_task_display(task: Task) -> str: + """ + Format task for terminal display. + + Args: + task: Task object to format + + Returns: + Formatted string with status icon, ID, title, and description + + Format: + [✓] #123: Task title - Description preview... + [○] #456: Another task + + Implementation Notes: + - Uses ✓ for completed tasks, ○ for incomplete tasks + - Shows task ID, title, and truncated description + - Leverages Task.__str__() method for consistent formatting + + Constitutional Compliance: + ✅ Display formatting only + ✅ NO business logic + ✅ NO database operations + """ + return str(task) + + +def handle_list_tasks(conn) -> None: + """ + Display all tasks in readable format via service layer. + + Args: + conn: Active database connection to pass to service layer + + Implementation Notes: + - Calls services.list_tasks() with connection + - Formats and displays each task using format_task_display() + - Shows count of tasks + - Displays message if no tasks exist + + Constitutional Compliance: + ✅ Display only + ✅ Calls service layer for data retrieval + ✅ NO SQL queries + ✅ NO business logic + """ + print("\n--- All Tasks ---") + + # Call service layer to retrieve tasks + result = services.list_tasks(conn) + + if not result['success']: + print(f"\n✗ {result['message']}") + return + + tasks = result['tasks'] + + if not tasks: + print("\nNo tasks found. Create your first task!") + return + + print(f"\nTotal tasks: {len(tasks)}\n") + + # Display each task + for task in tasks: + print(format_task_display(task)) + + +def handle_update_task(conn) -> None: + """ + Collect task ID and new details, update task via service layer. + + Args: + conn: Active database connection to pass to service layer + + Implementation Notes: + - Prompts for task ID + - Validates ID is a positive integer + - Prompts for new title (optional) + - Prompts for new description (optional) + - Ensures at least one field is provided + - Calls services.update_task() with connection + - Displays success or error message from service layer + + Constitutional Compliance: + ✅ Input collection and format validation + ✅ Calls service layer for business logic + ✅ NO SQL queries + ✅ NO business validation (delegates to service layer) + """ + print("\n--- Update Task ---") + + # Collect task ID + task_id_input = input("Enter task ID to update: ").strip() + + try: + task_id = int(task_id_input) + if task_id <= 0: + print("Error: Task ID must be a positive integer.") + return + except ValueError: + print("Error: Invalid task ID. Please enter a number.") + return + + # Collect new title (optional) + print("\nLeave field empty to keep current value:") + new_title = input("Enter new title (or press Enter to skip): ").strip() + + # If empty, set to None to indicate no change + if not new_title: + new_title = None + + # Collect new description (optional) + new_description = input("Enter new description (or press Enter to skip): ").strip() + + # If empty, set to None to indicate no change + if not new_description: + new_description = None + + # Validate at least one field is provided + if new_title is None and new_description is None: + print("Error: Must provide at least one field to update (title or description).") + return + + # Call service layer to update task + result = services.update_task(conn, task_id, new_title, new_description) + + # Display result from service layer + if result['success']: + print(f"\n✓ {result['message']}") + else: + print(f"\n✗ {result['message']}") + + +def handle_toggle_task(conn) -> None: + """ + Collect task ID and toggle completion via service layer. + + Args: + conn: Active database connection to pass to service layer + + Implementation Notes: + - Prompts for task ID + - Validates ID is a positive integer + - Calls services.toggle_task_completion() with connection + - Displays success or error message from service layer + + Constitutional Compliance: + ✅ Input collection and format validation + ✅ Calls service layer for business logic + ✅ NO SQL queries + ✅ NO business logic + """ + print("\n--- Toggle Task Completion ---") + + # Collect task ID + task_id_input = input("Enter task ID to toggle: ").strip() + + try: + task_id = int(task_id_input) + if task_id <= 0: + print("Error: Task ID must be a positive integer.") + return + except ValueError: + print("Error: Invalid task ID. Please enter a number.") + return + + # Call service layer to toggle task completion + result = services.toggle_task_completion(conn, task_id) + + # Display result from service layer + if result['success']: + print(f"\n✓ {result['message']}") + else: + print(f"\n✗ {result['message']}") + + +def handle_delete_task(conn) -> None: + """ + Collect task ID and delete task via service layer. + + Args: + conn: Active database connection to pass to service layer + + Implementation Notes: + - Prompts for task ID + - Validates ID is a positive integer + - Prompts for confirmation (destructive action) + - Calls services.delete_task() with connection + - Displays success or error message from service layer + + Constitutional Compliance: + ✅ Input collection and format validation + ✅ Confirmation prompt for destructive action + ✅ Calls service layer for business logic + ✅ NO SQL queries + ✅ NO business logic + """ + print("\n--- Delete Task ---") + + # Collect task ID + task_id_input = input("Enter task ID to delete: ").strip() + + try: + task_id = int(task_id_input) + if task_id <= 0: + print("Error: Task ID must be a positive integer.") + return + except ValueError: + print("Error: Invalid task ID. Please enter a number.") + return + + # Confirmation prompt for destructive action + confirmation = input(f"Are you sure you want to delete task #{task_id}? (yes/no): ").strip().lower() + + if confirmation not in ['yes', 'y']: + print("Deletion cancelled.") + return + + # Call service layer to delete task + result = services.delete_task(conn, task_id) + + # Display result from service layer + if result['success']: + print(f"\n✓ {result['message']}") + else: + print(f"\n✗ {result['message']}") diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d6f7f2c4ed436d0a9a815e8bbf5b1cf4e97b26 --- /dev/null +++ b/src/models/__init__.py @@ -0,0 +1,7 @@ +# backend/src/models/__init__.py +"""Database models package.""" + +from .conversation import Conversation +from .message import Message + +__all__ = ["Conversation", "Message"] diff --git a/src/models/conversation.py b/src/models/conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..7d03d4426f52308543920904c4db891c11422c07 --- /dev/null +++ b/src/models/conversation.py @@ -0,0 +1,17 @@ +# backend/src/models/conversation.py +"""Conversation model for AI chatbot feature.""" + +from sqlmodel import SQLModel, Field +from datetime import datetime +from typing import Optional + + +class Conversation(SQLModel, table=True): + """Represents a chat thread between a user and the AI assistant.""" + __tablename__ = "conversations" + + id: Optional[int] = Field(default=None, primary_key=True) + user_id: str = Field(index=True, nullable=False) + title: str = Field(max_length=100, nullable=False) + created_at: datetime = Field(default_factory=datetime.utcnow) + updated_at: datetime = Field(default_factory=datetime.utcnow) diff --git a/src/models/message.py b/src/models/message.py new file mode 100644 index 0000000000000000000000000000000000000000..fb743921bb477bf27e6eaebc8cc68ccff24ebf77 --- /dev/null +++ b/src/models/message.py @@ -0,0 +1,20 @@ +# backend/src/models/message.py +"""Message model for AI chatbot feature.""" + +from sqlmodel import SQLModel, Field, Column +from sqlalchemy import JSON +from datetime import datetime +from typing import Optional, List, Any + + +class Message(SQLModel, table=True): + """Represents a single message within a conversation.""" + __tablename__ = "messages" + + id: Optional[int] = Field(default=None, primary_key=True) + conversation_id: int = Field(foreign_key="conversations.id", index=True, nullable=False) + user_id: str = Field(index=True, nullable=False) + role: str = Field(max_length=20, nullable=False) # "user" or "assistant" + content: str = Field(nullable=False) + tool_calls: Optional[List[Any]] = Field(default=None, sa_column=Column(JSON)) + created_at: datetime = Field(default_factory=datetime.utcnow, index=True) diff --git a/src/models_old.py b/src/models_old.py new file mode 100644 index 0000000000000000000000000000000000000000..1c22170f799629a37798e7a216dbcd0accdcb233 --- /dev/null +++ b/src/models_old.py @@ -0,0 +1,147 @@ +""" +Task Data Model for Interactive Todo Application + +Owner: Service Logic Agent +Purpose: Task entity definition, enums, and structured models for task management + +Constitutional Constraints: +- ALLOWED: Data model definitions, conversion methods +- FORBIDDEN: User input (input()), User output (print()), Database connections, Business logic +""" + +from enum import Enum +from datetime import datetime +from typing import Optional +from pydantic import BaseModel, Field, ConfigDict + + +class Priority(str, Enum): + """Priority levels for tasks.""" + LOW = 'low' + MEDIUM = 'medium' + HIGH = 'high' + + +class RecurrenceInterval(str, Enum): + """Recurrence interval for tasks.""" + NONE = 'none' + DAILY = 'daily' + WEEKLY = 'weekly' + MONTHLY = 'monthly' + + +class TaskStatus(str, Enum): + """Completion status for tasks.""" + PENDING = 'pending' + COMPLETED = 'completed' + + +class TaskCreate(BaseModel): + """Schema for creating a new task.""" + title: str = Field(min_length=1, max_length=255) + description: Optional[str] = None + priority: Priority = Priority.MEDIUM + category: Optional[str] = None + due_date: Optional[datetime] = None + recurrence_interval: RecurrenceInterval = RecurrenceInterval.NONE + + model_config = ConfigDict(use_enum_values=True) + + +class TaskUpdate(BaseModel): + """Schema for updating an existing task.""" + title: Optional[str] = Field(default=None, min_length=1, max_length=255) + description: Optional[str] = None + priority: Optional[Priority] = None + category: Optional[str] = None + due_date: Optional[datetime] = None + status: Optional[TaskStatus] = None + recurrence_interval: Optional[RecurrenceInterval] = None + + model_config = ConfigDict(use_enum_values=True) + + +class Task(BaseModel): + """ + Task entity representing a todo item. + + Attributes: + id: Unique task identifier + title: Task title (1-255 characters) + description: Optional detailed description + priority: Priority level (low, medium, high) + category: Optional category name + due_date: Optional due date timestamp + status: Task completion status (pending, completed) + recurrence_interval: Recurrence interval (daily, weekly, monthly, none) + parent_task_id: Reference to parent task (for recurring task instances) + reminder_sent: Whether notification sent + created_at: Creation timestamp + updated_at: Last modification timestamp + + Constitutional Compliance: + ✅ Pure data model (no behavior) + ✅ NO user interaction + ✅ NO database access + """ + id: int + title: str = Field(min_length=1, max_length=255) + description: Optional[str] = None + priority: Priority = Priority.MEDIUM + category: Optional[str] = None + due_date: Optional[datetime] = None + status: TaskStatus = TaskStatus.PENDING + recurrence_interval: RecurrenceInterval = RecurrenceInterval.NONE + parent_task_id: Optional[int] = None + reminder_sent: bool = False + created_at: datetime + updated_at: datetime + + model_config = ConfigDict(use_enum_values=True, from_attributes=True) + + def to_dict(self) -> dict: + """ + Convert Task to dictionary representation. + + Returns: + Dictionary with all task fields, timestamps in ISO format + """ + return self.model_dump() + + @classmethod + def from_db_row(cls, row: tuple) -> 'Task': + """ + Create Task from database row tuple. + + Args: + row: Database row as tuple. + Expects: (id, title, description, priority, category, due_date, is_completed, recurrence_interval, parent_task_id, reminder_sent, created_at, updated_at) + + Returns: + Task instance populated from database row + """ + # Convert boolean is_completed to TaskStatus enum + is_completed = row[6] + status = TaskStatus.COMPLETED if is_completed else TaskStatus.PENDING + + return cls( + id=row[0], + title=row[1], + description=row[2], + priority=Priority(row[3]), + category=row[4], + due_date=row[5], + status=status, + recurrence_interval=RecurrenceInterval(row[7]), + parent_task_id=row[8], + reminder_sent=row[9], + created_at=row[10], + updated_at=row[11] + ) + + def __str__(self) -> str: + """String representation for display.""" + icon = "✓" if self.status == TaskStatus.COMPLETED else "○" + priority_tag = f" [{self.priority.upper()}]" + due_tag = f" (Due: {self.due_date.strftime('%Y-%m-%d')})" if self.due_date else "" + return f"[{icon}]{priority_tag} #{self.id}: {self.title}{due_tag}" diff --git a/src/notification_manager.py b/src/notification_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..ca88edde6dae4f827c610c1156dcf61ca8ae7421 --- /dev/null +++ b/src/notification_manager.py @@ -0,0 +1,97 @@ +""" +Notification Manager for Interactive Todo Application + +Owner: Service Logic Agent +Purpose: Handle cross-platform desktop notifications and boot checks for due tasks +Architecture: 100% async/await, graceful degradation if plyer unsupported + +Constitutional Compliance: +- ✅ Service Logic Agent ownership +- ✅ NO database connections (must use repository layer) +- ✅ NO user interaction (input(), print()) +- ✅ NO Rich UI (system notifications only) +- ✅ All functions async +- ✅ Graceful degradation if notifications unsupported +""" + +import logging +from datetime import datetime, timedelta +from plyer import notification +from src.repository import get_all_tasks, update_task + +logger = logging.getLogger("notification_manager") + +async def show_notification(title: str, message: str) -> bool: + """ + Display cross-platform desktop notification. + + Args: + title: Notification title + message: Notification message body + + Returns: + True if successful, False otherwise + """ + try: + # notification.notify is a synchronous call but usually very fast + #plyer handles platform-specific details internally + notification.notify( + title=title, + message=message, + app_name="Todo CLI", + timeout=10 # seconds + ) + return True + except Exception as e: + # Catch silently as per constraints + logger.warning(f"OS notification failed: {e}") + return False + +async def check_due_tasks_and_notify() -> int: + """ + Find tasks due within 30 minutes and send notifications. + + Returns: + Number of tasks notified + """ + try: + now = datetime.now() + time_threshold = now + timedelta(minutes=30) + + # Query all tasks (we'll filter in memory for precision) + tasks = await get_all_tasks(status='pending') + + # Filter for tasks due within 30 minutes that haven't been notified + due_tasks = [ + t for t in tasks + if t.due_date + and t.due_date >= now # Only upcoming ones + and t.due_date <= time_threshold + and not t.reminder_sent + ] + + if not due_tasks: + return 0 + + # Send notification + if len(due_tasks) == 1: + task = due_tasks[0] + title = "Task Due Soon" + message = f"'{task.title}' is due at {task.due_date.strftime('%H:%M')}" + else: + title = f"{len(due_tasks)} Tasks Due Soon" + message = f"You have Multiple tasks due within 30 minutes." + + # Show notification (silent failure if daemon missing) + await show_notification(title, message) + + # Mark as notified in database + for task in due_tasks: + await update_task(task.id, reminder_sent=True) + + logger.info(f"Notified about {len(due_tasks)} upcoming tasks.") + return len(due_tasks) + + except Exception as e: + logger.error(f"Error during due task check: {e}") + return 0 diff --git a/src/recurrence_engine.py b/src/recurrence_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..4f849452f19ab2c3771e0d42d81d516797c6efc0 --- /dev/null +++ b/src/recurrence_engine.py @@ -0,0 +1,103 @@ +""" +Recurrence Engine for Interactive Todo Application + +Owner: Service Logic Agent +Purpose: Calculate next due dates and manage recurring task instances +Architecture: 100% async/await, interval-based arithmetic + +Constitutional Compliance: +- ✅ Service Logic Agent ownership +- ✅ NO database connections (must use repository layer) +- ✅ NO user interaction (input(), print()) +- ✅ NO Rich UI (business logic only) +- ✅ All functions async +""" + +import logging +from datetime import datetime, timedelta +from typing import Optional +from dateutil.relativedelta import relativedelta +from src.models import TaskCreate, RecurrenceInterval +from src.repository import get_task_by_id, create_task, update_task + +logger = logging.getLogger("recurrence_engine") + +async def calculate_next_due_date( + current_due_date: datetime, + recurrence_interval: str +) -> Optional[datetime]: + """ + Calculate next occurrence based on recurrence interval. + + Args: + current_due_date: Current task's due date + recurrence_interval: Interval string (daily, weekly, monthly, none) + + Returns: + Next due date or None if interval is none + """ + if recurrence_interval == RecurrenceInterval.DAILY: + return current_due_date + timedelta(days=1) + elif recurrence_interval == RecurrenceInterval.WEEKLY: + return current_due_date + relativedelta(weeks=1) + elif recurrence_interval == RecurrenceInterval.MONTHLY: + return current_due_date + relativedelta(months=1) + else: # "none" or invalid + return None + +async def create_recurring_task_instance( + completed_task_id: int, + current_due_date: Optional[datetime], + recurrence_interval: str +) -> Optional[int]: + """ + Create new pending instance when recurring task completed. + + Args: + completed_task_id: ID of the just-completed task + current_due_date: Due date of completed task + recurrence_interval: Recurrence interval string + + Returns: + ID of newly created task or None + """ + # Skip if no recurrence or invalid + if recurrence_interval == RecurrenceInterval.NONE or recurrence_interval is None: + return None + + # Fetch completed task details + completed_task = await get_task_by_id(completed_task_id) + if not completed_task: + logger.warning(f"Failed to find completed task {completed_task_id} for recurrence") + return None + + # Calculate next due date + next_due_date = None + if current_due_date: + next_due_date = await calculate_next_due_date( + current_due_date, + recurrence_interval + ) + + # Process creation logic + try: + # Create new pending instance with same attributes + created_task = await create_task( + title=completed_task.title, + description=completed_task.description, + priority=completed_task.priority.value, + category=completed_task.category, + due_date=next_due_date, + recurrence_interval=recurrence_interval, + parent_task_id=completed_task_id + ) + + if created_task: + logger.info(f"Created recurring task instance: {created_task.id} (parent: {completed_task_id})") + return created_task.id + + except Exception as e: + logger.error(f"Failed to create recurring task instance: {e}") + return None + + return None diff --git a/src/repository.py b/src/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a50a91fb6895db2154b868d8660b56231aa8c7 --- /dev/null +++ b/src/repository.py @@ -0,0 +1,281 @@ +""" +Repository Layer for Interactive Todo Application (v2.0.0) + +Owner: Database Agent +Purpose: Data persistence and retrieval logic for tasks +Architecture: Async/Await with PostgreSQL using psycopg3 + +Constitutional Constraints: +- ALLOWED: CRUD operations, SQL queries, parameterized inputs, async implementation +- FORBIDDEN: User interaction (input/print), direct database connections (must use database.py), + business logic validation, UI formatting. + +All functions use full column sets to remain consistent with Task.from_db_row. +""" + +import logging +from typing import List, Optional, Any +from datetime import datetime +from src.database import db_manager +from src.models import Task, Priority, TaskStatus + +logger = logging.getLogger("repository") + +# Full column set to ensure consistency across all SELECT queries +FULL_COLUMN_SET = ( + "id, title, description, priority, category, due_date, " + "is_completed, recurrence_interval, parent_task_id, " + "reminder_sent, created_at, updated_at" +) + +async def create_task(title: str, description: Optional[str] = None, + priority: str = 'medium', category: Optional[str] = None, + due_date: Optional[datetime] = None, + recurrence_interval: str = 'none', + parent_task_id: Optional[int] = None) -> Task: + """ + Create a new task in the database. + + Args: + title: Task title + description: Optional description + priority: Task priority (low, medium, high) + category: Optional category + due_date: Optional due date + recurrence_interval: Recurrence interval (daily, weekly, monthly, none) + parent_task_id: Optional parent task ID + + Returns: + The newly created Task object + """ + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute( + f""" + INSERT INTO tasks (title, description, priority, category, due_date, + recurrence_interval, parent_task_id) + VALUES (%s, %s, %s, %s, %s, %s, %s) + RETURNING {FULL_COLUMN_SET} + """, + (title, description, priority, category, due_date, + recurrence_interval, parent_task_id) + ) + row = await cur.fetchone() + await conn.commit() + + # row: (id, title, description, priority, category, due_date, + # is_completed, recurrence_interval, parent_task_id, + # reminder_sent, created_at, updated_at) + # models.Task.from_db_row expects this exact order and content + return Task.from_db_row(row) + +async def get_all_tasks(status: Optional[str] = None, + category: Optional[str] = None, + priority: Optional[str] = None, + parent_task_id: Optional[int] = None, + recurrence_interval: Optional[str] = None, + due_before: Optional[datetime] = None, + due_after: Optional[datetime] = None, + sort_by: str = 'date') -> List[Task]: + """ + Retrieve all tasks with optional filters and sorting. + + Args: + status: Filter by completion status ('completed', 'pending') + category: Filter by category + priority: Filter by priority + parent_task_id: Filter by parent task (for task history) + recurrence_interval: Filter by recurrence interval + due_before: Filter by due date before this time + due_after: Filter by due date after this time + sort_by: Sorting method ('date', 'alpha', 'priority') + + Returns: + List of Task objects + """ + query = f"SELECT {FULL_COLUMN_SET} FROM tasks" + conditions = [] + params = [] + + if status == 'completed': + conditions.append("is_completed = TRUE") + elif status == 'pending': + conditions.append("is_completed = FALSE") + + if category: + conditions.append("category = %s") + params.append(category) + + if priority: + conditions.append("priority = %s") + params.append(priority) + + if parent_task_id: + conditions.append("parent_task_id = %s") + params.append(parent_task_id) + + if recurrence_interval: + conditions.append("recurrence_interval = %s") + params.append(recurrence_interval) + + if due_before: + conditions.append("due_date <= %s") + params.append(due_before) + + if due_after: + conditions.append("due_date >= %s") + params.append(due_after) + + if conditions: + query += " WHERE " + " AND ".join(conditions) + + # Sorting logic + if sort_by == 'priority': + query += """ ORDER BY CASE + WHEN priority = 'high' THEN 1 + WHEN priority = 'medium' THEN 2 + WHEN priority = 'low' THEN 3 + ELSE 4 END, created_at DESC""" + elif sort_by == 'alpha': + query += ' ORDER BY title COLLATE "C" ASC' + else: # default 'date' + query += " ORDER BY due_date ASC NULLS LAST, created_at DESC" + + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute(query, params) + rows = await cur.fetchall() + return [Task.from_db_row(row) for row in rows] + +async def update_task(task_id: int, **kwargs) -> Optional[Task]: + """ + Update an existing task. + + Args: + task_id: ID of the task to update + **kwargs: Fields to update (title, description, priority, category, due_date, is_completed, recurrence_interval, parent_task_id, reminder_sent) + + Returns: + Updated Task object or None if not found + """ + # handle reminder_sent reset on due_date change + if 'due_date' in kwargs and 'reminder_sent' not in kwargs: + kwargs['reminder_sent'] = False + + # Filter out None values or handle specific field mapping if necessary + # is_completed might be passed instead of status based on previous implementation + if 'status' in kwargs and 'is_completed' not in kwargs: + kwargs['is_completed'] = (kwargs.pop('status') == TaskStatus.COMPLETED) + + # Only keep non-None values to avoid updating with NULL where not allowed + kwargs = {k: v for k, v in kwargs.items() if v is not None} + + if not kwargs: + return await get_task_by_id(task_id) + + kwargs['updated_at'] = datetime.now() + + # Use parameterized query for security + columns = [] + params = [] + for k, v in kwargs.items(): + columns.append(f"{k} = %s") + params.append(v) + + set_clause = ", ".join(columns) + params.append(task_id) + + query = f"UPDATE tasks SET {set_clause} WHERE id = %s RETURNING {FULL_COLUMN_SET}" + + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute(query, params) + row = await cur.fetchone() + await conn.commit() + if row: + return Task.from_db_row(row) + return None + +async def delete_task(task_id: int) -> bool: + """ + Delete a task from the database. + + Args: + task_id: ID of the task to delete + + Returns: + True if deleted, False otherwise + """ + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute("DELETE FROM tasks WHERE id = %s", (task_id,)) + result = cur.rowcount > 0 + await conn.commit() + return result + +async def search_tasks(query: str) -> List[Task]: + """ + Search for tasks by title or description. + + Args: + query: Search string + + Returns: + List of matching Task objects + """ + search_term = f"%{query}%" + sql = f""" + SELECT {FULL_COLUMN_SET} + FROM tasks + WHERE title ILIKE %s OR description ILIKE %s + ORDER BY created_at DESC + """ + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute(sql, (search_term, search_term)) + rows = await cur.fetchall() + return [Task.from_db_row(row) for row in rows] + +async def get_task_by_id(task_id: int) -> Optional[Task]: + """ + Retrieve a single task by ID. + + Args: + task_id: Task ID + + Returns: + Task object or None if not found + """ + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + await cur.execute( + f"SELECT {FULL_COLUMN_SET} FROM tasks WHERE id = %s", + (task_id,) + ) + row = await cur.fetchone() + if row: + return Task.from_db_row(row) + return None + +async def get_task_history(root_task_id: int) -> List[Task]: + """ + Get all instances of a recurring task series. + + Args: + root_task_id: ID of the root task + + Returns: + List of Task objects in the series + """ + async with await db_manager.get_connection() as conn: + async with conn.cursor() as cur: + # Query: root task OR any task with parent_task_id = root_task_id + query = f""" + SELECT {FULL_COLUMN_SET} + FROM tasks + WHERE id = %s OR parent_task_id = %s + ORDER BY created_at ASC + """ + await cur.execute(query, (root_task_id, root_task_id)) + rows = await cur.fetchall() + return [Task.from_db_row(row) for row in rows] diff --git a/src/services.py b/src/services.py new file mode 100644 index 0000000000000000000000000000000000000000..2273b56aac71c42c903cf48bfe97a0f3b79bd430 --- /dev/null +++ b/src/services.py @@ -0,0 +1,359 @@ +""" +Service Layer for Interactive Todo Application (v2.0.0) + +Owner: Service Logic Agent +Purpose: Business logic orchestration, validation, and error translation +Architecture: Async/Await with Pydantic models + +Constitutional Constraints: +- ALLOWED: Business rule validation, orchestration between CLI and Repository, error handling +- FORBIDDEN: Direct database connections (uses repository.py), User input (input()), + User output (print()), SQL queries, Rich UI output. + +All service functions return dictionaries with consistent structure: +- {'success': bool, 'message': str, 'data': Any | None} +""" + +import logging +import dateparser +from datetime import datetime, timedelta +from typing import List, Optional, Dict, Any +from src.models import Task, TaskCreate, TaskUpdate, TaskStatus, RecurrenceInterval, Priority +import src.repository as repository +from src.recurrence_engine import create_recurring_task_instance + +logger = logging.getLogger("services") + +def parse_natural_date(date_str: str) -> Optional[datetime]: + """ + Parse natural language date string into datetime object. + + Args: + date_str: Human-readable date string + + Returns: + Datetime object or None if parsing fails + """ + if not date_str or not date_str.strip(): + return None + + # dateparser configuration + settings = { + 'RETURN_AS_TIMEZONE_AWARE': False, # Store as local/naive for now to match project simple datetime usage + 'PREFER_DATES_FROM': 'future', + 'PREFER_DAY_OF_MONTH': 'current' + } + + try: + parsed_date = dateparser.parse(date_str, settings=settings) + return parsed_date + except Exception as e: + logger.warning(f"Failed to parse date string '{date_str}': {e}") + return None + +async def create_task(task_data: TaskCreate) -> Dict[str, Any]: + """ + Orchestrate task creation with validation. + + Args: + task_data: Pydantic model containing task creation fields + + Returns: + Dict with success status, message, and created task data + """ + try: + # Pydantic already handled basic type validation and length constraints via TaskCreate + # Extract data and call repository + new_task = await repository.create_task( + title=task_data.title.strip(), + description=task_data.description.strip() if task_data.description else None, + priority=task_data.priority, + category=task_data.category.strip() if task_data.category else None, + due_date=task_data.due_date, + recurrence_interval=task_data.recurrence_interval + ) + + return { + "success": True, + "message": f"Task '{new_task.title}' created successfully.", + "data": new_task + } + except Exception as e: + logger.error(f"Error creating task: {e}") + return { + "success": False, + "message": f"Failed to create task: {str(e)}", + "data": None + } + +async def get_tasks( + status: Optional[TaskStatus] = None, + category: Optional[str] = None, + priority: Optional[Priority] = None, + parent_task_id: Optional[int] = None, + recurrence_interval: Optional[str] = None, + due_before: Optional[datetime] = None, + due_after: Optional[datetime] = None, + sort_by: str = 'date' +) -> Dict[str, Any]: + """ + Retrieve tasks with filtering and sorting. + + Args: + status: Filter by completion status + category: Filter by category name + priority: Filter by priority level + parent_task_id: Filter by parent task + recurrence_interval: Filter by recurrence interval + due_before: Filter by due date before + due_after: Filter by due date after + sort_by: Sorting criterion ('date', 'alpha', 'priority') + + Returns: + Dict with success status, message, and list of tasks + """ + try: + # Normalize status and priority to string values for repository + status_val = status + if status and hasattr(status, 'value'): + status_val = status.value + elif status: + status_val = str(status) + + priority_val = priority + if priority and hasattr(priority, 'value'): + priority_val = priority.value + elif priority: + priority_val = str(priority) + + tasks = await repository.get_all_tasks( + status=status_val, + category=category, + priority=priority_val, + parent_task_id=parent_task_id, + recurrence_interval=recurrence_interval, + due_before=due_before, + due_after=due_after, + sort_by=sort_by + ) + + return { + "success": True, + "message": f"Retrieved {len(tasks)} tasks.", + "data": tasks + } + except Exception as e: + logger.error(f"Error retrieving tasks: {e}") + return { + "success": False, + "message": f"Failed to retrieve tasks: {str(e)}", + "data": [] + } + +async def update_task(task_id: int, update_data: TaskUpdate) -> Dict[str, Any]: + """ + Update an existing task with validation. + + Args: + task_id: ID of the task to update + update_data: Pydantic model containing update fields + + Returns: + Dict with success status, message, and updated task data + """ + try: + # Business Validation: Ensure task exists + existing_task = await repository.get_task_by_id(task_id) + if not existing_task: + return { + "success": False, + "message": f"Task with ID {task_id} not found.", + "data": None + } + + # Convert Pydantic model to dict, excluding unset fields + updates = update_data.model_dump(exclude_unset=True) + if not updates: + return { + "success": True, + "message": "No changes requested.", + "data": existing_task + } + + # Handle string stripping for updates + if 'title' in updates and updates['title']: + updates['title'] = updates['title'].strip() + if 'description' in updates and updates['description']: + updates['description'] = updates['description'].strip() + if 'category' in updates and updates['category']: + updates['category'] = updates['category'].strip() + + updated_task = await repository.update_task(task_id, **updates) + + return { + "success": True, + "message": f"Task {task_id} updated successfully.", + "data": updated_task + } + except Exception as e: + logger.error(f"Error updating task {task_id}: {e}") + return { + "success": False, + "message": f"Failed to update task: {str(e)}", + "data": None + } + +async def delete_task(task_id: int) -> Dict[str, Any]: + """ + Delete a task. + + Args: + task_id: ID of the task to delete + + Returns: + Dict with success status and message + """ + try: + # Business Validation: Ensure task exists + existing_task = await repository.get_task_by_id(task_id) + if not existing_task: + return { + "success": False, + "message": f"Task with ID {task_id} not found.", + "data": None + } + + success = await repository.delete_task(task_id) + if success: + return { + "success": True, + "message": f"Task {task_id} deleted successfully.", + "data": None + } + else: + return { + "success": False, + "message": f"Failed to delete task {task_id}.", + "data": None + } + except Exception as e: + logger.error(f"Error deleting task {task_id}: {e}") + return { + "success": False, + "message": f"Error during deletion: {str(e)}", + "data": None + } + +async def search_tasks(query: str) -> Dict[str, Any]: + """ + Search for tasks by query string. + + Args: + query: Search term + + Returns: + Dict with success status, message, and matching tasks + """ + if not query or not query.strip(): + return { + "success": False, + "message": "Search query cannot be empty.", + "data": [] + } + + try: + tasks = await repository.search_tasks(query.strip()) + return { + "success": True, + "message": f"Found {len(tasks)} tasks matching '{query}'.", + "data": tasks + } + except Exception as e: + logger.error(f"Error searching tasks for '{query}': {e}") + return { + "success": False, + "message": f"Search failed: {str(e)}", + "data": [] + } + +async def toggle_task_completion(task_id: int) -> Dict[str, Any]: + """ + Toggle the completion status of a task. + + Args: + task_id: ID of the task to toggle + + Returns: + Dict with success status, message, and updated task data + """ + try: + existing_task = await repository.get_task_by_id(task_id) + if not existing_task: + return { + "success": False, + "message": f"Task with ID {task_id} not found.", + "data": None + } + + # Determine new status + is_completed = (existing_task.status == TaskStatus.PENDING) + new_status = TaskStatus.COMPLETED if is_completed else TaskStatus.PENDING + + updated_task = await repository.update_task(task_id, status=new_status) + + # Trigger recurrence logic if marking as completed + new_task_msg = "" + if is_completed and updated_task.recurrence_interval != RecurrenceInterval.NONE: + new_instance_id = await create_recurring_task_instance( + completed_task_id=task_id, + current_due_date=updated_task.due_date, + recurrence_interval=updated_task.recurrence_interval + ) + if new_instance_id: + new_task_msg = f" New recurring instance created: {new_instance_id}." + + status_str = "completed" if is_completed else "pending" + return { + "success": True, + "message": f"Task {task_id} marked as {status_str}.{new_task_msg}", + "data": updated_task + } + except Exception as e: + logger.error(f"Error toggling task {task_id}: {e}") + return { + "success": False, + "message": f"Failed to toggle status: {str(e)}", + "data": None + } + +async def get_task_history(root_task_id: int) -> Dict[str, Any]: + """ + Get all instances of a recurring task series. + + Args: + root_task_id: ID of the root task + + Returns: + Dict with success status, message, and list of tasks + """ + try: + tasks = await repository.get_task_history(root_task_id) + if not tasks: + return { + "success": False, + "message": f"No history found for task {root_task_id}.", + "data": [] + } + + return { + "success": True, + "message": f"Found {len(tasks)} instances in series.", + "data": tasks + } + except Exception as e: + logger.error(f"Error retrieving task history for {root_task_id}: {e}") + return { + "success": False, + "message": f"Failed to retrieve history: {str(e)}", + "data": [] + } diff --git a/src/services/__init__.py b/src/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6f276e448f81341eb1eda4ebbbfd7f0df90c53 --- /dev/null +++ b/src/services/__init__.py @@ -0,0 +1,21 @@ +# backend/src/services/__init__.py +"""Services package for business logic.""" + +from .chat_service import ( + get_conversation_history, + save_chat_exchange, + create_conversation, + get_conversation_by_id, + get_user_conversations +) +from .agent_service import AgentService, get_agent_service + +__all__ = [ + "get_conversation_history", + "save_chat_exchange", + "create_conversation", + "get_conversation_by_id", + "get_user_conversations", + "AgentService", + "get_agent_service" +] diff --git a/src/services/agent_service.py b/src/services/agent_service.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe800e1370fecf8a3bf0c6176831353730f2387 --- /dev/null +++ b/src/services/agent_service.py @@ -0,0 +1,362 @@ +# backend/src/services/agent_service.py +""" +Agent Service for AI Chatbot + +Owner: AI Orchestrator +Purpose: OpenRouter LLM integration for stateless AI processing +Architecture: Stateless with AsyncOpenAI client (OpenRouter-compatible) + +Constitutional Constraints: +- REQUIRED: Stateless processing (Principle VI) +- REQUIRED: Tools are the ONLY way AI accesses data (Principle VII) +- REQUIRED: All tool calls captured for audit (Principle VIII) + +Note: Free tier models on OpenRouter don't support function calling. +This implementation uses structured prompts to parse tool intents from text. +""" + +import os +import re +import json +import logging +from typing import Optional +from openai import AsyncOpenAI, RateLimitError, APIError + +logger = logging.getLogger("services.agent_service") + +# OpenRouter base URL (OpenAI-compatible API) +OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1" + +# System prompt for the AI agent (structured output for tool parsing) +SYSTEM_PROMPT = """You are a task management assistant. Help users manage their to-do list. + +VALID ACTIONS: ADD_TASK, LIST_TASKS, COMPLETE_TASK, UPDATE_TASK, DELETE_TASK + +RULES: +1. Use ONLY these 5 actions. Never use other action names. +2. Output ONE command block per response. +3. COMPLETE_TASK, UPDATE_TASK, DELETE_TASK require a task_id from the user's message. +4. Task IDs are UUIDs like "85fcb698-ab86-4255-80f7-d3a0aef307f6" - ONLY use IDs the user provides. +5. If user wants to complete/update/delete but didn't provide an ID, DO NOT output a command. Ask them to say "show tasks" first. +6. NEVER invent or guess task IDs. If no valid UUID is in the user's message, ask for it. + +COMMAND FORMAT (copy exactly): +```command +ACTION: ACTION_NAME +PARAMS: {"key": "value"} +``` + +EXAMPLES: + +User: "add buy milk" +```command +ACTION: ADD_TASK +PARAMS: {"title": "buy milk"} +``` + +User: "show tasks" +```command +ACTION: LIST_TASKS +PARAMS: {"status": "all"} +``` + +User: "complete 85fcb698-ab86-4255-80f7-d3a0aef307f6" +```command +ACTION: COMPLETE_TASK +PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6"} +``` + +User: "update 85fcb698-ab86-4255-80f7-d3a0aef307f6 to buy organic milk" +```command +ACTION: UPDATE_TASK +PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6", "title": "buy organic milk"} +``` + +User: "delete 85fcb698-ab86-4255-80f7-d3a0aef307f6" +```command +ACTION: DELETE_TASK +PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6"} +``` + +User: "delete my task" (no UUID provided) +I need the task ID. Say "show tasks" to see your tasks with their IDs, then tell me which to delete. + +User: "update the milk task" (no UUID provided) +I need the task ID to update it. Say "show tasks" to see your tasks with their IDs. + +User: "hello" +Hi! I can help manage your tasks. Say "add [task]" to create, "show tasks" to list, or provide a task ID to complete/update/delete.""" + + +class AgentService: + """ + Stateless AI agent service using OpenRouter API (OpenAI-compatible). + + Per Constitution Principle VI: No local session state. + All context is passed in via conversation_history parameter. + + Note: Free tier models don't support function calling, so we use + structured prompts and parse commands from text responses. + """ + + # Regex pattern to extract command blocks from AI response + # Handles both wrapped (```command...```) and unwrapped formats + COMMAND_PATTERN = re.compile( + r'(?:```command\s*\n)?' # Optional opening wrapper + r'ACTION:\s*(\w+)\s*\n' + r'PARAMS:\s*(\{.*?\})' + r'(?:\s*\n```)?', # Optional closing wrapper + re.IGNORECASE | re.DOTALL + ) + + # Map action names to tool names + ACTION_TO_TOOL = { + "ADD_TASK": "add_task", + "CREATE_TASK": "add_task", # Alias + "LIST_TASKS": "list_tasks", + "READ_TASK": "list_tasks", # Alias - LLM sometimes uses this + "READ_TASKS": "list_tasks", # Alias + "SHOW_TASKS": "list_tasks", # Alias + "GET_TASKS": "list_tasks", # Alias + "COMPLETE_TASK": "complete_task", + "MARK_COMPLETE": "complete_task", # Alias + "UPDATE_TASK": "update_task", + "EDIT_TASK": "update_task", # Alias + "DELETE_TASK": "delete_task", + "REMOVE_TASK": "delete_task", # Alias + } + + # Actions that require a task_id (including aliases) + ACTIONS_REQUIRING_ID = { + "COMPLETE_TASK", "MARK_COMPLETE", + "UPDATE_TASK", "EDIT_TASK", + "DELETE_TASK", "REMOVE_TASK" + } + + def __init__(self): + """Initialize the OpenRouter client.""" + api_key = os.getenv("OPENROUTER_API_KEY") + if not api_key: + raise ValueError("OPENROUTER_API_KEY environment variable not set") + + self.client = AsyncOpenAI( + api_key=api_key, + base_url=OPENROUTER_BASE_URL + ) + # Default to Qwen 2.5 7B - better instruction following than Llama 3B + self.model = os.getenv("OPENROUTER_MODEL", "qwen/qwen-2.5-7b-instruct:free") + logger.info(f"AgentService initialized with OpenRouter model: {self.model}") + + def _parse_commands(self, text: str) -> list[tuple[str, dict]]: + """ + Parse command blocks from AI response text. + Only returns the FIRST valid command found to prevent multiple actions. + + Returns: + List with at most one (action_name, params_dict) tuple + """ + commands = [] + match = self.COMMAND_PATTERN.search(text) # Only find first match + if match: + action = match.group(1).upper().strip() + # Skip empty or invalid actions + if not action or action not in self.ACTION_TO_TOOL: + logger.warning(f"Skipping invalid/empty action: '{action}'") + return commands + try: + params = json.loads(match.group(2)) + except json.JSONDecodeError: + params = {} + commands.append((action, params)) + return commands + + def _validate_command(self, action: str, params: dict) -> tuple[bool, str]: + """ + Validate that a command has all required parameters. + + Args: + action: The action name (e.g., "COMPLETE_TASK") + params: The parameters dict + + Returns: + Tuple of (is_valid, error_message) + """ + if action in self.ACTIONS_REQUIRING_ID: + task_id = params.get("task_id", "") + if not task_id or not task_id.strip(): + return False, f"I need a task ID to {action.lower().replace('_', ' ')}. Please say 'show my tasks' first to see your tasks with their IDs." + return True, "" + + def _clean_response(self, text: str) -> str: + """Remove command blocks from response text for cleaner output.""" + return self.COMMAND_PATTERN.sub('', text).strip() + + def _clean_history(self, history: list[dict]) -> list[dict]: + """ + Clean conversation history to prevent LLM confusion. + + Removes command blocks from previous assistant messages and + limits history to prevent context overload. + """ + cleaned = [] + # Only keep last 4 messages to prevent confusion + recent_history = history[-4:] if len(history) > 4 else history + + for msg in recent_history: + if msg["role"] == "assistant": + # Remove command blocks from previous assistant responses + clean_content = self._clean_response(msg["content"]) + # Also remove "Tool results:" sections + if "Tool results:" in clean_content: + clean_content = clean_content.split("Tool results:")[0].strip() + if clean_content: + cleaned.append({"role": "assistant", "content": clean_content}) + else: + cleaned.append(msg) + + return cleaned + + async def process_message( + self, + user_message: str, + conversation_history: list[dict], + user_id: str, + tool_executor: callable + ) -> dict: + """ + Process a user message statelessly (no history used). + + Args: + user_message: The new message from user + conversation_history: Ignored - each message is independent + user_id: For tool authorization (passed to tool executor) + tool_executor: Async function to execute tool calls + + Returns: + dict with 'response' (str) and 'tool_calls' (list) + """ + # Stateless: Only use system prompt + current message (no history) + messages = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": user_message} + ] + + tool_calls_log = [] + + try: + # API call (no tools parameter - using text-based commands) + response = await self.client.chat.completions.create( + model=self.model, + messages=messages, + extra_headers={ + "HTTP-Referer": "https://todozen.app", + "X-Title": "TodoZen AI Assistant" + } + ) + + assistant_content = response.choices[0].message.content or "" + + # Debug: Log raw LLM response + logger.info(f"Raw LLM response: {assistant_content[:500]}") + + # Parse commands from response + commands = self._parse_commands(assistant_content) + logger.info(f"Parsed commands: {commands}") + + if commands: + # Execute each command (should be only one due to _parse_commands) + tool_results = [] + for action, params in commands: + # Validate command has required parameters + is_valid, error_msg = self._validate_command(action, params) + if not is_valid: + logger.warning(f"Invalid command {action}: missing task_id") + # Return the error message without executing the tool + return { + "response": error_msg, + "tool_calls": None + } + + tool_name = self.ACTION_TO_TOOL.get(action) + if not tool_name: + logger.warning(f"Unknown action: {action}") + continue + + tool_args = json.dumps(params) + logger.info(f"Executing tool: {tool_name} with args: {tool_args}") + + # Execute tool and get result + tool_result = await tool_executor( + tool_name=tool_name, + tool_args=tool_args, + user_id=user_id + ) + + # Log tool call for audit trail + tool_calls_log.append({ + "tool": tool_name, + "arguments": tool_args, + "result": tool_result + }) + tool_results.append(tool_result) + + # Get follow-up response with tool results + messages.append({"role": "assistant", "content": assistant_content}) + messages.append({ + "role": "user", + "content": f"Tool results:\n" + "\n".join(tool_results) + "\n\nPlease provide a friendly summary of what was done." + }) + + follow_up = await self.client.chat.completions.create( + model=self.model, + messages=messages, + extra_headers={ + "HTTP-Referer": "https://todozen.app", + "X-Title": "TodoZen AI Assistant" + } + ) + final_response = follow_up.choices[0].message.content or "" + else: + # No commands - just return the response + final_response = assistant_content + + # Clean any remaining command blocks from response + final_response = self._clean_response(final_response) + + logger.info(f"Agent processed message with {len(tool_calls_log)} tool calls") + + return { + "response": final_response, + "tool_calls": tool_calls_log if tool_calls_log else None + } + + except RateLimitError as e: + logger.error(f"Rate limit exceeded: {e}") + return { + "response": "I'm currently experiencing high demand. Please wait a moment and try again.", + "tool_calls": None + } + except APIError as e: + logger.error(f"API error: {e}") + return { + "response": "I'm having trouble connecting to my AI service. Please try again in a moment.", + "tool_calls": None + } + except Exception as e: + logger.error(f"Agent processing error: {e}") + return { + "response": "I'm sorry, I encountered an error processing your request. Please try again.", + "tool_calls": None + } + + +# Singleton instance +_agent_service: Optional[AgentService] = None + + +def get_agent_service() -> AgentService: + """Get or create the singleton AgentService instance.""" + global _agent_service + if _agent_service is None: + _agent_service = AgentService() + return _agent_service diff --git a/src/services/chat_service.py b/src/services/chat_service.py new file mode 100644 index 0000000000000000000000000000000000000000..de4ce8706fce775ef820729794d1bab1586cdb2c --- /dev/null +++ b/src/services/chat_service.py @@ -0,0 +1,258 @@ +# backend/src/services/chat_service.py +""" +Chat Service for AI Chatbot + +Owner: AI Orchestrator +Purpose: Stateless conversation management per stateless-memory-management skill +Architecture: Database-backed memory with no local session state + +Constitutional Constraints: +- REQUIRED: All queries filter by user_id (Principle IV) +- REQUIRED: No local session storage (Principle VI) +- REQUIRED: Messages persisted immediately after AI response (Principle VIII) +""" + +import logging +from datetime import datetime +from typing import Optional +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from src.db.models import Todo +from src.models.conversation import Conversation +from src.models.message import Message + +logger = logging.getLogger("services.chat_service") + + +async def get_conversation_history( + conversation_id: int, + user_id: str, + session: AsyncSession, + limit: int = 10 +) -> list[dict]: + """ + Fetch last N messages for conversation context. + + Per stateless-memory-management skill: + - Fetches from database on every request (no caching) + - Filters by user_id for isolation + - Returns in chronological order for OpenAI + + Args: + conversation_id: The conversation to fetch history for + user_id: The authenticated user (for isolation) + session: Database session + limit: Maximum messages to fetch (default 10) + + Returns: + List of message dicts formatted for OpenAI: [{"role": "...", "content": "..."}] + """ + statement = ( + select(Message) + .where( + Message.conversation_id == conversation_id, + Message.user_id == user_id # REQUIRED: User isolation + ) + .order_by(Message.created_at.desc()) + .limit(limit) + ) + + result = await session.execute(statement) + messages = result.scalars().all() + + # Reverse to chronological order and format for OpenAI + history = [ + {"role": msg.role, "content": msg.content} + for msg in reversed(messages) + ] + + logger.debug(f"Fetched {len(history)} messages for conversation {conversation_id}") + return history + + +async def save_chat_exchange( + conversation_id: int, + user_id: str, + user_message: str, + assistant_response: str, + tool_calls: Optional[list], + session: AsyncSession +) -> tuple[Message, Message]: + """ + Persist user message and AI response to database. + + Per stateless-memory-management skill: + - MUST be called immediately after AI responds + - Saves both user and assistant messages + - Updates conversation timestamp + - Stores tool_calls for audit trail (Principle VIII) + + Args: + conversation_id: The conversation ID + user_id: The authenticated user's ID + user_message: The user's input message + assistant_response: The AI's response text + tool_calls: List of tool calls made by AI (for audit) + session: Database session + + Returns: + Tuple of (user_message, assistant_message) Message objects + """ + now = datetime.utcnow() + + # Save user message + user_msg = Message( + conversation_id=conversation_id, + user_id=user_id, + role="user", + content=user_message, + created_at=now + ) + session.add(user_msg) + + # Save assistant response with tool calls for audit + assistant_msg = Message( + conversation_id=conversation_id, + user_id=user_id, + role="assistant", + content=assistant_response, + tool_calls=tool_calls, + created_at=now + ) + session.add(assistant_msg) + + # Update conversation timestamp + conversation = await session.get(Conversation, conversation_id) + if conversation: + conversation.updated_at = now + + await session.commit() + + logger.info(f"Saved chat exchange for conversation {conversation_id}") + return user_msg, assistant_msg + + +async def create_conversation( + user_id: str, + first_message: str, + session: AsyncSession +) -> Conversation: + """ + Create a new conversation with auto-generated title. + + Title is generated from the first message (truncated to 50 chars). + + Args: + user_id: The authenticated user's ID + first_message: The first message (used for title generation) + session: Database session + + Returns: + The created Conversation object + """ + # Generate title from first message (truncate to 50 chars) + title = first_message[:50].strip() + if len(first_message) > 50: + title = title + "..." + + conversation = Conversation( + user_id=user_id, + title=title, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow() + ) + session.add(conversation) + await session.commit() + await session.refresh(conversation) + + logger.info(f"Created conversation {conversation.id} for user {user_id}") + return conversation + + +async def get_conversation_by_id( + conversation_id: int, + user_id: str, + session: AsyncSession +) -> Optional[Conversation]: + """ + Get a conversation by ID with user ownership verification. + + Args: + conversation_id: The conversation ID + user_id: The authenticated user's ID (for ownership check) + session: Database session + + Returns: + Conversation if found and owned by user, None otherwise + """ + statement = select(Conversation).where( + Conversation.id == conversation_id, + Conversation.user_id == user_id # REQUIRED: User isolation + ) + result = await session.execute(statement) + return result.scalar_one_or_none() + + +async def get_user_conversations( + user_id: str, + session: AsyncSession, + limit: int = 20 +) -> list[Conversation]: + """ + Get all conversations for a user, ordered by most recent. + + Args: + user_id: The authenticated user's ID + session: Database session + limit: Maximum conversations to return + + Returns: + List of Conversation objects + """ + statement = ( + select(Conversation) + .where(Conversation.user_id == user_id) + .order_by(Conversation.updated_at.desc()) + .limit(limit) + ) + result = await session.execute(statement) + return list(result.scalars().all()) + + +async def delete_conversation( + conversation_id: int, + user_id: str, + session: AsyncSession +) -> bool: + """ + Delete a conversation and all its messages. + + Args: + conversation_id: The conversation ID to delete + user_id: The authenticated user's ID (for ownership check) + session: Database session + + Returns: + True if deleted, False if not found or unauthorized + """ + # First verify ownership + conversation = await get_conversation_by_id(conversation_id, user_id, session) + if not conversation: + return False + + # Delete all messages in the conversation + from sqlalchemy import delete + await session.execute( + delete(Message).where( + Message.conversation_id == conversation_id, + Message.user_id == user_id + ) + ) + + # Delete the conversation + await session.delete(conversation) + await session.commit() + + logger.info(f"Deleted conversation {conversation_id} for user {user_id}") + return True diff --git a/test_api.py b/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c2239cd6014cd8181b40cdaaf4094765f512e118 --- /dev/null +++ b/test_api.py @@ -0,0 +1,227 @@ +""" +Simple Test Script for Todo API Endpoints + +This script tests the basic functionality of the Todo API without authentication. +For full integration tests with JWT, see tests/ directory. + +Usage: + python test_api.py + +Requirements: + - API server must be running on http://localhost:8000 + - httpx library must be installed +""" + +import asyncio +import sys +from datetime import datetime, timedelta +from jose import jwt +import httpx + +# Test configuration +API_BASE_URL = "http://localhost:8000" +TEST_USER_ID = "test_user_123" +BETTER_AUTH_SECRET = "test-secret-for-development" # Replace with actual secret + + +def create_test_token(user_id: str, secret: str) -> str: + """ + Create a test JWT token for authentication. + + Args: + user_id: User ID to include in token + secret: BETTER_AUTH_SECRET for signing + + Returns: + JWT token string + """ + payload = { + "sub": user_id, + "email": f"{user_id}@example.com", + "iat": datetime.utcnow(), + "exp": datetime.utcnow() + timedelta(days=1), + "iss": "todoweb", + "aud": "todoweb-api" + } + return jwt.encode(payload, secret, algorithm="HS256") + + +async def test_health_check(): + """Test the health check endpoint (no auth required).""" + print("\n[TEST] Health Check") + async with httpx.AsyncClient() as client: + response = await client.get(f"{API_BASE_URL}/health") + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "Health check failed" + print("✓ Health check passed") + + +async def test_root_endpoint(): + """Test the root endpoint (no auth required).""" + print("\n[TEST] Root Endpoint") + async with httpx.AsyncClient() as client: + response = await client.get(f"{API_BASE_URL}/") + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "Root endpoint failed" + print("✓ Root endpoint passed") + + +async def test_create_todo(token: str): + """Test creating a todo.""" + print("\n[TEST] Create Todo") + async with httpx.AsyncClient() as client: + response = await client.post( + f"{API_BASE_URL}/api/todos", + json={ + "title": "Test Todo", + "description": "This is a test todo", + "is_completed": False + }, + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 201, "Create todo failed" + todo = response.json() + print(f"✓ Todo created with ID: {todo['id']}") + return todo["id"] + + +async def test_list_todos(token: str): + """Test listing todos.""" + print("\n[TEST] List Todos") + async with httpx.AsyncClient() as client: + response = await client.get( + f"{API_BASE_URL}/api/todos", + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "List todos failed" + todos = response.json() + print(f"✓ Retrieved {len(todos)} todos") + return todos + + +async def test_get_todo(token: str, todo_id: str): + """Test getting a specific todo.""" + print(f"\n[TEST] Get Todo {todo_id}") + async with httpx.AsyncClient() as client: + response = await client.get( + f"{API_BASE_URL}/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "Get todo failed" + print("✓ Todo retrieved successfully") + + +async def test_update_todo(token: str, todo_id: str): + """Test updating a todo.""" + print(f"\n[TEST] Update Todo {todo_id}") + async with httpx.AsyncClient() as client: + response = await client.put( + f"{API_BASE_URL}/api/todos/{todo_id}", + json={ + "title": "Updated Test Todo", + "description": "This todo has been updated" + }, + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "Update todo failed" + print("✓ Todo updated successfully") + + +async def test_toggle_completion(token: str, todo_id: str): + """Test toggling todo completion.""" + print(f"\n[TEST] Toggle Todo Completion {todo_id}") + async with httpx.AsyncClient() as client: + response = await client.patch( + f"{API_BASE_URL}/api/todos/{todo_id}/complete", + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + print(f"Response: {response.json()}") + assert response.status_code == 200, "Toggle completion failed" + todo = response.json() + print(f"✓ Todo completion toggled to: {todo['is_completed']}") + + +async def test_delete_todo(token: str, todo_id: str): + """Test deleting a todo.""" + print(f"\n[TEST] Delete Todo {todo_id}") + async with httpx.AsyncClient() as client: + response = await client.delete( + f"{API_BASE_URL}/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {token}"} + ) + print(f"Status: {response.status_code}") + assert response.status_code == 204, "Delete todo failed" + print("✓ Todo deleted successfully") + + +async def test_unauthorized_access(): + """Test that endpoints reject requests without authentication.""" + print("\n[TEST] Unauthorized Access") + async with httpx.AsyncClient() as client: + response = await client.get(f"{API_BASE_URL}/api/todos") + print(f"Status: {response.status_code}") + assert response.status_code == 403, "Should reject unauthorized requests" + print("✓ Unauthorized access correctly rejected") + + +async def main(): + """Run all tests.""" + print("=" * 60) + print("Todo API Test Suite") + print("=" * 60) + print(f"API URL: {API_BASE_URL}") + print(f"Test User: {TEST_USER_ID}") + print("=" * 60) + + try: + # Test public endpoints + await test_health_check() + await test_root_endpoint() + + # Test unauthorized access + await test_unauthorized_access() + + # Create test token + print("\n[SETUP] Creating test JWT token...") + token = create_test_token(TEST_USER_ID, BETTER_AUTH_SECRET) + print(f"Token created for user: {TEST_USER_ID}") + + # Test authenticated endpoints + todo_id = await test_create_todo(token) + await test_list_todos(token) + await test_get_todo(token, todo_id) + await test_update_todo(token, todo_id) + await test_toggle_completion(token, todo_id) + await test_delete_todo(token, todo_id) + + print("\n" + "=" * 60) + print("✓ All tests passed!") + print("=" * 60) + + except AssertionError as e: + print(f"\n✗ Test failed: {e}") + sys.exit(1) + except httpx.ConnectError: + print("\n✗ Cannot connect to API server") + print(f"Make sure the server is running at {API_BASE_URL}") + sys.exit(1) + except Exception as e: + print(f"\n✗ Unexpected error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..904e89daa72e26bbb931440cdfd028630344fafa --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,268 @@ +""" +JWT Authentication Tests + +Purpose: Validate JWT token verification and security +Tests: Valid token, expired token, invalid signature, missing sub claim + +Constitutional Requirements: +- REQUIRED: Reject tokens with invalid signature +- REQUIRED: Reject expired tokens +- REQUIRED: Reject tokens missing sub claim +- REQUIRED: Accept valid tokens with correct signature +""" + +import pytest +from datetime import datetime, timedelta +from jose import jwt +import os + +# Test secret (matches .env for testing) +TEST_SECRET = os.getenv("BETTER_AUTH_SECRET", "test-secret-for-testing-only") + + +def create_test_token( + user_id: str = "test_user_123", + expires_delta: timedelta = timedelta(days=1), + secret: str = TEST_SECRET, + include_sub: bool = True, + issuer: str = "todoweb", + audience: str = "todoweb-api" +) -> str: + """ + Create a test JWT token with configurable parameters + + Args: + user_id: User ID to include in sub claim + expires_delta: Time until token expires + secret: Secret key for signing + include_sub: Whether to include sub claim + issuer: Token issuer + audience: Token audience + + Returns: + Encoded JWT token string + """ + payload = { + "iat": datetime.utcnow(), + "exp": datetime.utcnow() + expires_delta, + "iss": issuer, + "aud": audience + } + + if include_sub: + payload["sub"] = user_id + + return jwt.encode(payload, secret, algorithm="HS256") + + +class TestJWTValidation: + """Test JWT token validation logic""" + + def test_valid_token(self): + """Test that valid token is accepted""" + token = create_test_token(user_id="user_123") + + # Decode and verify + payload = jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + assert payload["sub"] == "user_123" + assert payload["iss"] == "todoweb" + assert payload["aud"] == "todoweb-api" + assert "exp" in payload + assert "iat" in payload + + def test_expired_token(self): + """Test that expired token is rejected""" + # Create token that expired 1 day ago + token = create_test_token( + user_id="user_123", + expires_delta=timedelta(days=-1) + ) + + # Should raise ExpiredSignatureError + with pytest.raises(jwt.ExpiredSignatureError): + jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + def test_invalid_signature(self): + """Test that token with wrong signature is rejected""" + # Create token with different secret + token = create_test_token( + user_id="user_123", + secret="wrong-secret-key" + ) + + # Should raise JWTError when verifying with correct secret + with pytest.raises(jwt.JWTError): + jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + def test_missing_sub_claim(self): + """Test that token without sub claim is rejected""" + # Create token without sub claim + token = create_test_token( + user_id="user_123", + include_sub=False + ) + + # Token should decode but sub claim should be missing + payload = jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + assert "sub" not in payload + + def test_invalid_issuer(self): + """Test that token with wrong issuer is rejected""" + token = create_test_token( + user_id="user_123", + issuer="wrong-issuer" + ) + + # Should raise JWTClaimsError + with pytest.raises(jwt.JWTClaimsError): + jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + def test_invalid_audience(self): + """Test that token with wrong audience is rejected""" + token = create_test_token( + user_id="user_123", + audience="wrong-audience" + ) + + # Should raise JWTClaimsError + with pytest.raises(jwt.JWTClaimsError): + jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + def test_malformed_token(self): + """Test that malformed token is rejected""" + malformed_token = "not.a.valid.jwt.token" + + # Should raise JWTError + with pytest.raises(jwt.JWTError): + jwt.decode( + malformed_token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + def test_token_with_extra_claims(self): + """Test that token with extra claims is accepted""" + payload = { + "sub": "user_123", + "email": "user@example.com", + "name": "Test User", + "iat": datetime.utcnow(), + "exp": datetime.utcnow() + timedelta(days=1), + "iss": "todoweb", + "aud": "todoweb-api" + } + + token = jwt.encode(payload, TEST_SECRET, algorithm="HS256") + + # Should decode successfully + decoded = jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + assert decoded["sub"] == "user_123" + assert decoded["email"] == "user@example.com" + assert decoded["name"] == "Test User" + + +class TestTokenExpiration: + """Test token expiration edge cases""" + + def test_token_expires_in_future(self): + """Test token that expires in 7 days (standard expiration)""" + token = create_test_token( + user_id="user_123", + expires_delta=timedelta(days=7) + ) + + payload = jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + assert payload["sub"] == "user_123" + + def test_token_expires_soon(self): + """Test token that expires in 1 second""" + token = create_test_token( + user_id="user_123", + expires_delta=timedelta(seconds=1) + ) + + # Should still be valid + payload = jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + assert payload["sub"] == "user_123" + + def test_token_just_expired(self): + """Test token that just expired""" + token = create_test_token( + user_id="user_123", + expires_delta=timedelta(seconds=-1) + ) + + # Should be rejected + with pytest.raises(jwt.ExpiredSignatureError): + jwt.decode( + token, + TEST_SECRET, + algorithms=["HS256"], + issuer="todoweb", + audience="todoweb-api" + ) + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/tests/test_todos.py b/tests/test_todos.py new file mode 100644 index 0000000000000000000000000000000000000000..1ec8c66d4d0e3b0da99540f7f2c7c5d1ffdf4515 --- /dev/null +++ b/tests/test_todos.py @@ -0,0 +1,525 @@ +""" +Todo API Endpoint Tests + +Purpose: Validate all 6 Todo API endpoints with authentication +Tests: Create, List, Get, Update, Delete, Toggle Completion + +Constitutional Requirements: +- REQUIRED: All endpoints must enforce JWT authentication +- REQUIRED: All endpoints must enforce user isolation +- REQUIRED: Proper HTTP status codes (201, 200, 204, 404, 422) +- REQUIRED: Input validation using Pydantic models +""" + +import pytest +from httpx import AsyncClient +from datetime import datetime, timedelta +from jose import jwt +import os +from uuid import uuid4 + +# Test secret +TEST_SECRET = os.getenv("BETTER_AUTH_SECRET", "test-secret-for-testing-only") + +# Base URL for API +BASE_URL = "http://localhost:8000" + + +def create_test_token(user_id: str) -> str: + """Create a test JWT token for a specific user""" + payload = { + "sub": user_id, + "iat": datetime.utcnow(), + "exp": datetime.utcnow() + timedelta(days=1), + "iss": "todoweb", + "aud": "todoweb-api" + } + return jwt.encode(payload, TEST_SECRET, algorithm="HS256") + + +class TestHealthEndpoint: + """Test health check endpoint""" + + @pytest.mark.asyncio + async def test_health_check(self): + """Test that health endpoint returns 200""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.get("/health") + assert response.status_code == 200 + data = response.json() + assert data["status"] == "healthy" + + +class TestCreateTodoEndpoint: + """Test POST /api/todos endpoint""" + + @pytest.mark.asyncio + async def test_create_todo_success(self): + """Test creating a todo with valid data""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + response = await client.post( + "/api/todos", + json={ + "title": "Buy groceries", + "description": "Milk, eggs, bread" + }, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 201 + data = response.json() + assert data["title"] == "Buy groceries" + assert data["description"] == "Milk, eggs, bread" + assert data["is_completed"] is False + assert "id" in data + assert "created_at" in data + assert "updated_at" in data + + @pytest.mark.asyncio + async def test_create_todo_without_description(self): + """Test creating a todo without description (optional field)""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + response = await client.post( + "/api/todos", + json={"title": "Simple task"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 201 + data = response.json() + assert data["title"] == "Simple task" + assert data["description"] is None or data["description"] == "" + + @pytest.mark.asyncio + async def test_create_todo_empty_title(self): + """Test that empty title returns 422 validation error""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + response = await client.post( + "/api/todos", + json={"title": "", "description": "Test"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 422 + + @pytest.mark.asyncio + async def test_create_todo_missing_title(self): + """Test that missing title returns 422 validation error""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + response = await client.post( + "/api/todos", + json={"description": "Test"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 422 + + @pytest.mark.asyncio + async def test_create_todo_title_too_long(self): + """Test that title exceeding max length returns 422""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + long_title = "x" * 201 # Exceeds 200 character limit + response = await client.post( + "/api/todos", + json={"title": long_title, "description": "Test"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 422 + + @pytest.mark.asyncio + async def test_create_todo_without_auth(self): + """Test that creating todo without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.post( + "/api/todos", + json={"title": "Test", "description": "Test"} + ) + + assert response.status_code == 401 + + +class TestListTodosEndpoint: + """Test GET /api/todos endpoint""" + + @pytest.mark.asyncio + async def test_list_todos_empty(self): + """Test listing todos when user has none""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token(f"user_{uuid4()}") + response = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert isinstance(data, list) + assert len(data) == 0 + + @pytest.mark.asyncio + async def test_list_todos_with_items(self): + """Test listing todos when user has multiple todos""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + user_id = f"user_{uuid4()}" + token = create_test_token(user_id) + + # Create 3 todos + for i in range(3): + await client.post( + "/api/todos", + json={"title": f"Task {i}", "description": f"Description {i}"}, + headers={"Authorization": f"Bearer {token}"} + ) + + # List todos + response = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert len(data) == 3 + + @pytest.mark.asyncio + async def test_list_todos_without_auth(self): + """Test that listing todos without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.get("/api/todos") + assert response.status_code == 401 + + +class TestGetTodoEndpoint: + """Test GET /api/todos/{id} endpoint""" + + @pytest.mark.asyncio + async def test_get_todo_success(self): + """Test getting a specific todo by ID""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo + create_response = await client.post( + "/api/todos", + json={"title": "Test todo", "description": "Test description"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Get the todo + response = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert data["id"] == todo_id + assert data["title"] == "Test todo" + assert data["description"] == "Test description" + + @pytest.mark.asyncio + async def test_get_todo_not_found(self): + """Test getting a non-existent todo returns 404""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + fake_id = str(uuid4()) + + response = await client.get( + f"/api/todos/{fake_id}", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 404 + + @pytest.mark.asyncio + async def test_get_todo_invalid_uuid(self): + """Test getting a todo with invalid UUID format""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + response = await client.get( + "/api/todos/not-a-valid-uuid", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 422 + + @pytest.mark.asyncio + async def test_get_todo_without_auth(self): + """Test that getting todo without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.get(f"/api/todos/{uuid4()}") + assert response.status_code == 401 + + +class TestUpdateTodoEndpoint: + """Test PUT /api/todos/{id} endpoint""" + + @pytest.mark.asyncio + async def test_update_todo_success(self): + """Test updating a todo with valid data""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo + create_response = await client.post( + "/api/todos", + json={"title": "Original title", "description": "Original description"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Update the todo + response = await client.put( + f"/api/todos/{todo_id}", + json={"title": "Updated title", "description": "Updated description"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert data["title"] == "Updated title" + assert data["description"] == "Updated description" + + @pytest.mark.asyncio + async def test_update_todo_partial(self): + """Test partial update (only title or description)""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo + create_response = await client.post( + "/api/todos", + json={"title": "Original", "description": "Original"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Update only title + response = await client.put( + f"/api/todos/{todo_id}", + json={"title": "New title"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert data["title"] == "New title" + + @pytest.mark.asyncio + async def test_update_todo_not_found(self): + """Test updating non-existent todo returns 404""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + fake_id = str(uuid4()) + + response = await client.put( + f"/api/todos/{fake_id}", + json={"title": "Updated", "description": "Updated"}, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 404 + + @pytest.mark.asyncio + async def test_update_todo_without_auth(self): + """Test that updating todo without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.put( + f"/api/todos/{uuid4()}", + json={"title": "Updated"} + ) + assert response.status_code == 401 + + +class TestDeleteTodoEndpoint: + """Test DELETE /api/todos/{id} endpoint""" + + @pytest.mark.asyncio + async def test_delete_todo_success(self): + """Test deleting a todo""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo + create_response = await client.post( + "/api/todos", + json={"title": "To be deleted", "description": "Delete me"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Delete the todo + response = await client.delete( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 204 + + # Verify todo is deleted + get_response = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {token}"} + ) + assert get_response.status_code == 404 + + @pytest.mark.asyncio + async def test_delete_todo_not_found(self): + """Test deleting non-existent todo returns 404""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + fake_id = str(uuid4()) + + response = await client.delete( + f"/api/todos/{fake_id}", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 404 + + @pytest.mark.asyncio + async def test_delete_todo_without_auth(self): + """Test that deleting todo without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.delete(f"/api/todos/{uuid4()}") + assert response.status_code == 401 + + +class TestToggleCompletionEndpoint: + """Test PATCH /api/todos/{id}/complete endpoint""" + + @pytest.mark.asyncio + async def test_toggle_completion_to_complete(self): + """Test marking a todo as complete""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo (default is incomplete) + create_response = await client.post( + "/api/todos", + json={"title": "Task to complete", "description": "Mark as done"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + assert create_response.json()["is_completed"] is False + + # Toggle to complete + response = await client.patch( + f"/api/todos/{todo_id}/complete", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert data["is_completed"] is True + + @pytest.mark.asyncio + async def test_toggle_completion_to_incomplete(self): + """Test marking a completed todo as incomplete""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create and complete a todo + create_response = await client.post( + "/api/todos", + json={"title": "Completed task", "description": "Already done"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Toggle to complete + await client.patch( + f"/api/todos/{todo_id}/complete", + headers={"Authorization": f"Bearer {token}"} + ) + + # Toggle back to incomplete + response = await client.patch( + f"/api/todos/{todo_id}/complete", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 200 + data = response.json() + assert data["is_completed"] is False + + @pytest.mark.asyncio + async def test_toggle_completion_not_found(self): + """Test toggling completion of non-existent todo returns 404""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + fake_id = str(uuid4()) + + response = await client.patch( + f"/api/todos/{fake_id}/complete", + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 404 + + @pytest.mark.asyncio + async def test_toggle_completion_without_auth(self): + """Test that toggling completion without auth returns 401""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + response = await client.patch(f"/api/todos/{uuid4()}/complete") + assert response.status_code == 401 + + +class TestInputValidation: + """Test input validation across endpoints""" + + @pytest.mark.asyncio + async def test_create_todo_with_extra_fields(self): + """Test that extra fields are ignored""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + response = await client.post( + "/api/todos", + json={ + "title": "Valid todo", + "description": "Valid description", + "extra_field": "Should be ignored", + "another_field": 123 + }, + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 201 + data = response.json() + assert "extra_field" not in data + assert "another_field" not in data + + @pytest.mark.asyncio + async def test_update_todo_with_invalid_data_type(self): + """Test that invalid data types return 422""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + token = create_test_token("user_123") + + # Create a todo + create_response = await client.post( + "/api/todos", + json={"title": "Test", "description": "Test"}, + headers={"Authorization": f"Bearer {token}"} + ) + todo_id = create_response.json()["id"] + + # Try to update with invalid data type + response = await client.put( + f"/api/todos/{todo_id}", + json={"title": 123}, # Should be string + headers={"Authorization": f"Bearer {token}"} + ) + + assert response.status_code == 422 + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/tests/test_user_isolation.py b/tests/test_user_isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..49eccacaea08968a682a1d4daba3a076c83b83fc --- /dev/null +++ b/tests/test_user_isolation.py @@ -0,0 +1,332 @@ +""" +User Isolation Security Tests + +Purpose: Validate multi-tenant isolation and prevent unauthorized access +Tests: User A cannot access User B's todos + +Constitutional Requirements: +- REQUIRED: All queries MUST filter by user_id +- REQUIRED: Return 404 (not 403) to prevent information leakage +- REQUIRED: Never expose existence of other users' todos +- REQUIRED: Enforce isolation at database query level +""" + +import pytest +from httpx import AsyncClient +from datetime import datetime, timedelta +from jose import jwt +import os + +# Test secret +TEST_SECRET = os.getenv("BETTER_AUTH_SECRET", "test-secret-for-testing-only") + +# Base URL for API +BASE_URL = "http://localhost:8000" + + +def create_test_token(user_id: str) -> str: + """Create a test JWT token for a specific user""" + payload = { + "sub": user_id, + "iat": datetime.utcnow(), + "exp": datetime.utcnow() + timedelta(days=1), + "iss": "todoweb", + "aud": "todoweb-api" + } + return jwt.encode(payload, TEST_SECRET, algorithm="HS256") + + +class TestUserIsolation: + """Test that users can only access their own todos""" + + @pytest.mark.asyncio + async def test_user_cannot_list_other_user_todos(self): + """Test that User A cannot see User B's todos in list endpoint""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "User A's private todo", "description": "Secret"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + + # User B lists todos - should NOT see User A's todo + user_b_token = create_test_token("user_b") + response_b = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + assert response_b.status_code == 200 + + todos = response_b.json() + # User B should see empty list (no todos) + assert len(todos) == 0 + + @pytest.mark.asyncio + async def test_user_cannot_get_other_user_todo_by_id(self): + """Test that User A cannot access User B's todo by ID""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "User A's todo", "description": "Private"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + todo_id = response_a.json()["id"] + + # User B tries to access User A's todo by ID + user_b_token = create_test_token("user_b") + response_b = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + + # Should return 404 (not 403) to prevent information leakage + assert response_b.status_code == 404 + assert "not found" in response_b.json()["detail"].lower() + + @pytest.mark.asyncio + async def test_user_cannot_update_other_user_todo(self): + """Test that User A cannot update User B's todo""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "Original title", "description": "Original"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + todo_id = response_a.json()["id"] + + # User B tries to update User A's todo + user_b_token = create_test_token("user_b") + response_b = await client.put( + f"/api/todos/{todo_id}", + json={"title": "Hacked title", "description": "Hacked"}, + headers={"Authorization": f"Bearer {user_b_token}"} + ) + + # Should return 404 (not 403) + assert response_b.status_code == 404 + + # Verify User A's todo is unchanged + response_verify = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_verify.status_code == 200 + assert response_verify.json()["title"] == "Original title" + + @pytest.mark.asyncio + async def test_user_cannot_delete_other_user_todo(self): + """Test that User A cannot delete User B's todo""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "Important todo", "description": "Do not delete"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + todo_id = response_a.json()["id"] + + # User B tries to delete User A's todo + user_b_token = create_test_token("user_b") + response_b = await client.delete( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + + # Should return 404 (not 403) + assert response_b.status_code == 404 + + # Verify User A's todo still exists + response_verify = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_verify.status_code == 200 + assert response_verify.json()["title"] == "Important todo" + + @pytest.mark.asyncio + async def test_user_cannot_toggle_other_user_todo_completion(self): + """Test that User A cannot toggle User B's todo completion status""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "User A's task", "description": "Incomplete"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + todo_id = response_a.json()["id"] + assert response_a.json()["is_completed"] is False + + # User B tries to toggle User A's todo + user_b_token = create_test_token("user_b") + response_b = await client.patch( + f"/api/todos/{todo_id}/complete", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + + # Should return 404 (not 403) + assert response_b.status_code == 404 + + # Verify User A's todo is still incomplete + response_verify = await client.get( + f"/api/todos/{todo_id}", + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_verify.status_code == 200 + assert response_verify.json()["is_completed"] is False + + @pytest.mark.asyncio + async def test_multiple_users_can_have_same_todo_titles(self): + """Test that multiple users can create todos with the same title""" + async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client: + # User A creates a todo + user_a_token = create_test_token("user_a") + response_a = await client.post( + "/api/todos", + json={"title": "Buy groceries", "description": "User A's list"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 201 + todo_a_id = response_a.json()["id"] + + # User B creates a todo with the same title + user_b_token = create_test_token("user_b") + response_b = await client.post( + "/api/todos", + json={"title": "Buy groceries", "description": "User B's list"}, + headers={"Authorization": f"Bearer {user_b_token}"} + ) + assert response_b.status_code == 201 + todo_b_id = response_b.json()["id"] + + # Verify they have different IDs + assert todo_a_id != todo_b_id + + # User A should only see their todo + response_a_list = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a_list.status_code == 200 + todos_a = response_a_list.json() + assert len(todos_a) == 1 + assert todos_a[0]["description"] == "User A's list" + + # User B should only see their todo + response_b_list = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + assert response_b_list.status_code == 200 + todos_b = response_b_list.json() + assert len(todos_b) == 1 + assert todos_b[0]["description"] == "User B's list" + + @pytest.mark.asyncio + async def test_user_can_only_see_own_todos_count(self): + """Test that todo counts are isolated per user""" + async with AsyncClient(base_url=BASE_URL) as client: + # User A creates 3 todos + user_a_token = create_test_token("user_a") + for i in range(3): + response = await client.post( + "/api/todos", + json={"title": f"User A todo {i}", "description": f"Task {i}"}, + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response.status_code == 201 + + # User B creates 5 todos + user_b_token = create_test_token("user_b") + for i in range(5): + response = await client.post( + "/api/todos", + json={"title": f"User B todo {i}", "description": f"Task {i}"}, + headers={"Authorization": f"Bearer {user_b_token}"} + ) + assert response.status_code == 201 + + # User A should see exactly 3 todos + response_a = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {user_a_token}"} + ) + assert response_a.status_code == 200 + assert len(response_a.json()) == 3 + + # User B should see exactly 5 todos + response_b = await client.get( + "/api/todos", + headers={"Authorization": f"Bearer {user_b_token}"} + ) + assert response_b.status_code == 200 + assert len(response_b.json()) == 5 + + +class TestAuthenticationRequired: + """Test that all endpoints require authentication""" + + @pytest.mark.asyncio + async def test_list_todos_requires_auth(self): + """Test that listing todos requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + response = await client.get("/api/todos") + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_create_todo_requires_auth(self): + """Test that creating todos requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + response = await client.post( + "/api/todos", + json={"title": "Test", "description": "Test"} + ) + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_get_todo_requires_auth(self): + """Test that getting a todo requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + # Use a random UUID + response = await client.get("/api/todos/123e4567-e89b-12d3-a456-426614174000") + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_update_todo_requires_auth(self): + """Test that updating todos requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + response = await client.put( + "/api/todos/123e4567-e89b-12d3-a456-426614174000", + json={"title": "Updated", "description": "Updated"} + ) + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_delete_todo_requires_auth(self): + """Test that deleting todos requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + response = await client.delete("/api/todos/123e4567-e89b-12d3-a456-426614174000") + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_toggle_completion_requires_auth(self): + """Test that toggling completion requires authentication""" + async with AsyncClient(base_url=BASE_URL) as client: + response = await client.patch("/api/todos/123e4567-e89b-12d3-a456-426614174000/complete") + assert response.status_code == 401 + + +if __name__ == "__main__": + pytest.main([__file__, "-v"])